public static void Main(String[] args) { if (args.Length != 4) { Console.Error.WriteLine("Usage: mono CompareAttrs <host name> <login dn> " + "<password> <compare dn> "); Console.Error.WriteLine("Example: mono CompareAttrs Acme.com \"cn=Admin," + "o=Acme\" secret\n \"cn=JSmith,ou=Sales,o=Acme\""); Environment.Exit(1); } int ldapPort = LdapConnection.DEFAULT_PORT; int ldapVersion = LdapConnection.Ldap_V3; bool compareResults = false; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String dn = args[3]; LdapConnection lc = new LdapConnection(); LdapAttribute attr = null; try { // connect to the server lc.Connect(ldapHost, ldapPort); // authenticate to the server lc.Bind(ldapVersion, loginDN, password); attr = new LdapAttribute("objectclass", "inetOrgPerson"); System.Collections.IEnumerator allValues = attr.StringValues; allValues.MoveNext(); // Compare the value of the objectclass attribute. if (compareResults == lc.Compare(dn, attr)) { Console.WriteLine("\t" + (String)allValues.Current + " is contained in the " + attr.Name + " attribute."); } else { Console.WriteLine("\t" + (String)allValues.Current + " is not contained in the " + attr.Name + " attribute."); } attr = new LdapAttribute("sn", "Bunny"); allValues = attr.StringValues; allValues.MoveNext(); // Compare the value of the sn attribute. if (compareResults == lc.Compare(dn, attr)) { Console.WriteLine("\t" + (String)allValues.Current + " is contained in the " + attr.Name + " attribute."); } else { Console.WriteLine("\t" + (String)allValues.Current + " is not contained in the " + attr.Name + " attribute."); } // disconnect with the server lc.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
public void TestLdapAttributeGetBytesBoolean2() { var attribute = new LdapAttribute(UniversalDataType.Boolean, false); Assert.AreEqual("010100", Utils.ByteArrayToString(attribute.GetBytes())); }
public void TestAttributeClass() { var attribute = new LdapAttribute(LdapOperation.BindRequest); Assert.IsNull(attribute.DataType); }
/// <summary> /// Method to reset a user's password /// </summary> /// <param name="DistinguishedUserName" mandatory="true">DistinguishedUserName to set the password on.</param> /// <param name="OldPassword" mandatory="true">Old password.</param> /// <param name="NewPassword" mandatory="true">New password.</param> /// <returns>Zero - iF Successful, greater that zero for failures</returns> public int ResetPassword(string DistinguishedUserName, string OldPassword, string NewPassword) { log.Debug("Resetting password for: " + DistinguishedUserName); LdapConnection LDAPconn = null; LdapConnection proxyConnection = null; string UserID; try { LDAPconn = new LdapConnection(); LDAPconn.SecureSocketLayer = ldapSettings.SSL; LDAPconn.Connect(ldapSettings.Host, ldapSettings.Port); LDAPconn.Bind(DistinguishedUserName, OldPassword); if (LDAPconn.AuthenticationDN == null) { log.Info("LDAPconn.AuthenticationDN = null"); return((int)PasswordChangeStatus.IncorrectOldPassword); } int result = GetUserStatusInfo(LDAPconn, DistinguishedUserName, NewPassword.Length); if (result != (int)PasswordChangeStatus.FailedToResetPassword) { log.Info("result VALUE: {0}", result); return((int)result); } else { try { LdapModification[] modification = new LdapModification[2]; LdapAttribute deletePassword = new LdapAttribute("userPassword", OldPassword); modification[0] = new LdapModification(LdapModification.DELETE, deletePassword); LdapAttribute addPassword = new LdapAttribute("userPassword", NewPassword); modification[1] = new LdapModification(LdapModification.ADD, addPassword); LDAPconn.Modify(DistinguishedUserName, modification); } catch (Exception e) { log.Error("Unable to reset Password for DN:" + DistinguishedUserName); log.Error("Error:" + e.Message); return((int)PasswordChangeStatus.FailedToResetPassword); } return((int)PasswordChangeStatus.Success); } } catch (LdapException e) { log.Error("Password Reset failed for DN:" + DistinguishedUserName); log.Error("LdapError:" + e.LdapErrorMessage); log.Error("Error:" + e.Message); if (e.ResultCode == LdapException.INVALID_CREDENTIALS) { return((int)PasswordChangeStatus.IncorrectOldPassword); } proxyConnection = BindProxyUser(); if (proxyConnection != null) { return((int)GetUserStatusInfo(proxyConnection, DistinguishedUserName, NewPassword.Length)); } } catch (Exception e) { log.Error("Password Reset failed for DN:" + DistinguishedUserName); log.Error("Error:" + e.Message); proxyConnection = BindProxyUser(); if (proxyConnection != null) { return(GetUserStatusInfo(proxyConnection, DistinguishedUserName, NewPassword.Length)); } } finally { try{ if (LDAPconn != null) { LDAPconn.Disconnect(); } if (proxyConnection != null) { proxyConnection.Disconnect(); } }catch {} } return((int)PasswordChangeStatus.FailedToResetPassword); }
public void TestLdapAttributeGetBytes2() { var attribute = new LdapAttribute(UniversalDataType.Integer, (Byte)2); Assert.AreEqual("020102", Utils.ByteArrayToString(attribute.GetBytes())); }
/// <summary> /// Extends the Active directory AD iFolderschema /// </summary> /// <returns>True on successful schema Extension and false on Failure. </returns> public bool ExtendADiFolderschema() { LdapAttribute attr = null; LdapEntry entry = null; string retschemaNamingContext = String.Empty; string[] searchAttributes = { "schemaNamingContext" }; LdapSearchResults lsc = connection.Search("", LdapConnection.SCOPE_BASE, "objectClass=*", searchAttributes, false); while (lsc.hasMore()) { entry = null; try { entry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); continue; } LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { attr = (LdapAttribute)ienum.Current; string attributeName = attr.Name; Console.WriteLine(attributeName + ": value :" + attr.StringValue); if (String.Equals(attributeName, searchAttributes[0]) == true) { retschemaNamingContext = attr.StringValue; break; } } } try { LdapAttributeSet newattr_attributeSet = new LdapAttributeSet(); newattr_attributeSet.Add(new LdapAttribute("adminDisplayName", "iFolderHomeServer")); newattr_attributeSet.Add(new LdapAttribute("attributeID", "2.16.840.1.113719.1.288.1.42")); newattr_attributeSet.Add(new LdapAttribute("cn", "iFolderHomeServer")); newattr_attributeSet.Add(new LdapAttribute("attributeSyntax", "2.5.5.12")); newattr_attributeSet.Add(new LdapAttribute("adminDescription", "iFolder 3.x iFolderHomeServer Attribute, stores DNS Name or IP address of Users/Groups iFolder server.")); newattr_attributeSet.Add(new LdapAttribute("isMemberOfPartialAttributeSet", "FALSE")); newattr_attributeSet.Add(new LdapAttribute("isSingleValued", "TRUE")); newattr_attributeSet.Add(new LdapAttribute("showInAdvancedViewOnly", "FALSE")); newattr_attributeSet.Add(new LdapAttribute("lDAPDisplayName", "iFolderHomeServer")); newattr_attributeSet.Add(new LdapAttribute("distinguishedName", "CN=iFolderHomeServer," + retschemaNamingContext)); newattr_attributeSet.Add(new LdapAttribute("objectCategory", "CN=Attribute-Schema," + retschemaNamingContext)); newattr_attributeSet.Add(new LdapAttribute("objectClass", "attributeSchema")); newattr_attributeSet.Add(new LdapAttribute("oMSyntax", "64")); newattr_attributeSet.Add(new LdapAttribute("name", "iFolderHomeServer")); newattr_attributeSet.Add(new LdapAttribute("searchFlags", "0")); Console.WriteLine("\nExtending Active Directory Schema for {0}", "CN=iFolderHomeServer," + retschemaNamingContext); LdapEntry newattr_entry = new LdapEntry("CN=iFolderHomeServer," + retschemaNamingContext, newattr_attributeSet); connection.Add(newattr_entry); LdapAttribute newattr_modattribute = new LdapAttribute("schemaUpdateNow", "1"); LdapModification newattr_modification = new LdapModification(LdapModification.REPLACE, newattr_modattribute); connection.Modify("", newattr_modification); Console.WriteLine("\n Updating {0}", "CN=user," + retschemaNamingContext); LdapAttribute newclass_modattribute = new LdapAttribute("mayContain", "iFolderHomeServer"); LdapModification newclass_modification = new LdapModification(LdapModification.ADD, newclass_modattribute); connection.Modify("cn=user," + retschemaNamingContext, newclass_modification); newclass_modattribute = new LdapAttribute("schemaUpdateNow", "1"); newclass_modification = new LdapModification(LdapModification.REPLACE, newclass_modattribute); connection.Modify("", newclass_modification); Console.WriteLine("Completed.\n"); } catch (LdapException e) { if (e.ResultCode == LdapException.ENTRY_ALREADY_EXISTS) { Console.WriteLine("\n Active Directory iFolder Schema is already Extended."); return(true); } else { Console.WriteLine("\n Unable to extend Active Directory iFolder Schema. {0}::{1}", e.ResultCode.ToString(), e.Message); return(false); } } catch (Exception e) { Console.WriteLine("\n Unable to extend Active Directory iFolder Schema. Ex.Message {0}", e.Message); return(false); } Console.WriteLine("\nActive Directory iFolder Schema Extended."); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="LdapModification" /> class. /// Specifies a modification to be made to an attribute. /// </summary> /// <param name="op">The op.</param> /// <param name="attr">The attribute to modify.</param> public LdapModification(LdapModificationOp op, LdapAttribute attr) { Op = op; Attribute = attr; }
public static Task <bool> ModifyAsync(string oldUsername, string username, string password, string nombre, string apellido, string email) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken cancellationToken = cts.Token; LdapConnection conn = null; return(Task.Factory.StartNew(() => { conn = new LdapConnection(); conn.Connect(Host, Port); if (!string.IsNullOrEmpty(username)) { try { conn.Bind(dn, pa); } catch (Exception e) { conn.Disconnect(); return false; } string searchBase = filter; int searchScope = LdapConnection.ScopeSub; string searchFilter = "uid=" + username.Trim(); LdapSearchQueue queue = conn.Search(searchBase, searchScope, searchFilter, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.GetResponse()) != null) { try { string msg = message.ToString(); LdapEntry entry = ((LdapSearchResult)message).Entry; LdapAttributeSet attributeSet = entry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); LdapAttribute cn = attributeSet.GetAttribute("cn"); string idUser = cn.StringValue; try { conn.Delete("cn=" + idUser + "," + filter); LdapAttributeSet ldapAttributeSet = new LdapAttributeSet(); ldapAttributeSet.Add(new LdapAttribute("cn", nombre + " " + apellido)); ldapAttributeSet.Add(new LdapAttribute("sn", nombre)); ldapAttributeSet.Add(new LdapAttribute("homeDirectory", "/home/users/" + username)); ldapAttributeSet.Add(new LdapAttribute("objectClass", new string[] { "inetOrgPerson", "posixAccount", "top" })); ldapAttributeSet.Add(new LdapAttribute("uid", username)); ldapAttributeSet.Add(new LdapAttribute("givenName", nombre)); ldapAttributeSet.Add(new LdapAttribute("uidNumber", "1000")); ldapAttributeSet.Add(new LdapAttribute("gidNumber", "500")); ldapAttributeSet.Add(new LdapAttribute("mail", email)); ldapAttributeSet.Add(new LdapAttribute("userPassword", password)); LdapEntry ldapEntry = new LdapEntry("cn=" + nombre + " " + apellido + "," + filter, ldapAttributeSet); conn.Add(ldapEntry); } catch (Exception e) { conn.Disconnect(); return false; } conn.Disconnect(); return true; } catch (Exception e) { conn.Disconnect(); return false; } } } return false; }, cancellationToken)); }
public static Task <bool> LoginAsync(string username, string password) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken cancellationToken = cts.Token; LdapConnection conn = null; return(Task.Factory.StartNew(() => { conn = new LdapConnection(); conn.Connect(Host, Port); if (!string.IsNullOrEmpty(username)) { try { conn.Bind(dn, pa); } catch (Exception e) { conn.Disconnect(); return false; } string searchBase = filter; int searchScope = LdapConnection.ScopeSub; string searchFilter = "uid=" + username.Trim(); LdapSearchQueue queue = conn.Search(searchBase, searchScope, searchFilter, null, false, (LdapSearchQueue)null, (LdapSearchConstraints)null); LdapMessage message; while ((message = queue.GetResponse()) != null) { try { string msg = message.ToString(); LdapEntry entry = ((LdapSearchResult)message).Entry; LdapAttributeSet attributeSet = entry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); LdapAttribute cn = attributeSet.GetAttribute("cn"); string idUser = cn.StringValue; try { conn.Bind("cn=" + idUser + "," + filter, password); } catch (Exception e) { conn.Disconnect(); return false; } conn.Disconnect(); return true; } catch (Exception e) { conn.Disconnect(); return false; } } } return false; }, cancellationToken)); }
public async Task <IActionResult> Post([FromBody] ChangePasswordModel model) { // Validate the request if (model == null) { return(BadRequest(ApiResult.InvalidRequest())); } var result = new ApiResult(); // Validate the model if (ModelState.IsValid == false) { result.AddModelStateErrors(ModelState); return(BadRequest(result)); } // Validate the Captcha try { if (await ValidateRecaptcha(model.Recaptcha) == false) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCaptcha }); } } catch (Exception ex) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message }); } if (result.HasErrors) { return(BadRequest(result)); } // perform the password change try { #if SWAN var distinguishedName = await GetDN(model.Username); if (string.IsNullOrEmpty(distinguishedName)) { result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCredentials, Message = "Invalid Username or Password" }); return(BadRequest(result)); } var cn = new LdapConnection(); await cn.Connect(_options.PasswordChangeOptions.LdapHostname, _options.PasswordChangeOptions.LdapPort); await cn.Bind(_options.PasswordChangeOptions.LdapUsername, _options.PasswordChangeOptions.LdapPassword); var modList = new ArrayList(); var attribute = new LdapAttribute("userPassword", model.NewPassword); modList.Add(new LdapModification(LdapModificationOp.Replace, attribute)); var mods = (LdapModification[])modList.ToArray(typeof(LdapModification)); await cn.Modify(distinguishedName, mods); cn.Disconnect(); #else using (var principalContext = AcquirePrincipalContext()) { var userPrincipal = AcquireUserPricipal(principalContext, model.Username); // Check if the user principal exists if (userPrincipal == null) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.UserNotFound, Message = "Invalid Username or Password" }); return(BadRequest(result)); } // Check if password change is allowed if (userPrincipal.UserCannotChangePassword) { throw new Exception(_options.ClientSettings.Alerts.ErrorPasswordChangeNotAllowed); } // Validate user credentials if (principalContext.ValidateCredentials(model.Username, model.CurrentPassword) == false) { // Your new authenticate code snippet IntPtr token = IntPtr.Zero; try { var parts = userPrincipal.UserPrincipalName.Split(new [] { '@' }, StringSplitOptions.RemoveEmptyEntries); string domain = parts.Length > 1 ? parts[1] : null; if (domain == null) { throw new Exception(_options.ClientSettings.Alerts.ErrorInvalidCredentials); } if (!PasswordChangeFallBack.LogonUser(model.Username, domain, model.CurrentPassword, PasswordChangeFallBack.LogonTypes.Network, PasswordChangeFallBack.LogonProviders.Default, out token)) { int errorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); switch (errorCode) { case PasswordChangeFallBack.ERROR_PASSWORD_MUST_CHANGE: case PasswordChangeFallBack.ERROR_PASSWORD_EXPIRED: // Both of these means that the password CAN change and that we got the correct password break; default: throw new Exception(_options.ClientSettings.Alerts.ErrorInvalidCredentials); } } } finally { PasswordChangeFallBack.CloseHandle(token); } } // Verify user is not a member of an excluded group if (_options.ClientSettings.CheckRestrictedAdGroups) { foreach (Principal userPrincipalAuthGroup in userPrincipal.GetAuthorizationGroups()) { if (_options.ClientSettings.RestrictedADGroups.Contains(userPrincipalAuthGroup.Name)) { throw new Exception(_options.ClientSettings.Alerts.ErrorPasswordChangeNotAllowed); } } } // Change the password via 2 different methods. Try SetPassword if ChangePassword fails. try { // Try by regular ChangePassword method userPrincipal.ChangePassword(model.CurrentPassword, model.NewPassword); } catch (Exception ex2) { // If the previous attempt failed, use the SetPassword method. if (_options.PasswordChangeOptions.UseAutomaticContext == false) { userPrincipal.SetPassword(model.NewPassword); } else { throw ex2; } } userPrincipal.Save(); } #endif } catch (Exception ex) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message }); return(BadRequest(result)); } if (result.HasErrors) { Response.StatusCode = (int)HttpStatusCode.BadRequest; } return(Json(result)); }
public async Task <IActionResult> Post([FromBody] ChangePasswordModel model) { // Validate the request if (model == null) { return(BadRequest(ApiResult.InvalidRequest())); } var result = new ApiResult(); // Validate the model if (ModelState.IsValid == false) { result.AddModelStateErrors(ModelState); return(BadRequest(result)); } // Validate the Captcha try { if (await ValidateRecaptcha(model.Recaptcha) == false) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCaptcha }); } } catch (Exception ex) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message }); } if (result.HasErrors) { return(BadRequest(result)); } // perform the password change try { #if SWAN var distinguishedName = await GetDN(model.Username); if (string.IsNullOrEmpty(distinguishedName)) { result.Errors.Add(new ApiErrorItem() { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.InvalidCredentials, Message = "Invalid Username or Password" }); return(BadRequest(result)); } var cn = new LdapConnection(); await cn.Connect(_options.PasswordChangeOptions.LdapHostname, _options.PasswordChangeOptions.LdapPort); await cn.Bind(_options.PasswordChangeOptions.LdapUsername, _options.PasswordChangeOptions.LdapPassword); var modList = new ArrayList(); var attribute = new LdapAttribute("userPassword", model.NewPassword); modList.Add(new LdapModification(LdapModificationOp.Replace, attribute)); var mods = (LdapModification[])modList.ToArray(typeof(LdapModification)); await cn.Modify(distinguishedName, mods); cn.Disconnect(); #else using (var principalContext = AcquirePrincipalContext()) { var userPrincipal = AcquireUserPricipal(principalContext, model.Username); // Check if the user principal exists if (userPrincipal == null) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.UserNotFound, Message = "Invalid Username or Password" }); return(BadRequest(result)); } // Check if password change is allowed if (userPrincipal.UserCannotChangePassword) { throw new Exception(_options.ClientSettings.Alerts.ErrorPasswordChangeNotAllowed); } // Validate user credentials if (principalContext.ValidateCredentials(model.Username, model.CurrentPassword) == false) { throw new Exception(_options.ClientSettings.Alerts.ErrorInvalidCredentials); } // Change the password via 2 different methods. Try SetPassword if ChangePassword fails. try { // Try by regular ChangePassword method userPrincipal.ChangePassword(model.CurrentPassword, model.NewPassword); } catch (Exception ex2) { // If the previous attempt failed, use the SetPassword method. if (_options.PasswordChangeOptions.UseAutomaticContext == false) { userPrincipal.SetPassword(model.NewPassword); } else { throw ex2; } } userPrincipal.Save(); } #endif } catch (Exception ex) { result.Errors.Add(new ApiErrorItem { ErrorType = ApiErrorType.GeneralFailure, ErrorCode = ApiErrorCode.Generic, Message = ex.Message }); return(BadRequest(result)); } if (result.HasErrors) { Response.StatusCode = (int)HttpStatusCode.BadRequest; } return(Json(result)); }
/// <summary> /// add the ldap details into this user object /// </summary> /// <param name="entry">ldap entry</param> private void ProcessUserEntry(LdapEntry entry) { log.Debug("ProcessUserEntry(" + entry.DN + ")"); string commonName = String.Empty; string firstName = String.Empty; string lastName = String.Empty; string fullName = String.Empty; string distinguishedName = String.Empty; string ldapGuid = null; char[] dnDelimiters = { ',', '=' }; LdapAttribute timeStampAttr = null; bool attrError = false; string FullNameDisplay = ""; store = Store.GetStore(); Domain domain = store.GetDomain(store.DefaultDomain); if (domain != null) { FullNameDisplay = domain.UsersFullNameDisplay; } try { // get the last update time timeStampAttr = entry.getAttribute("modifytimestamp"); ldapGuid = GetLdapGuid(entry); distinguishedName = entry.DN; // retrieve from configuration the directory attribute configured // for naming in Simias. LdapAttribute cAttr = entry.getAttribute(ldapSettings.NamingAttribute); if (cAttr != null && cAttr.StringValue.Length != 0) { commonName = cAttr.StringValue; } else if (ldapSettings.NamingAttribute.ToLower() == LdapSettings.DefaultNamingAttribute.ToLower()) { // If the naming attribute is default (cn) then we want to continue // to work the way we previously did so we don't break any existing installs. // // If the distinguishing attribute did not exist, // then make the Simias username the first component // of the ldap DN. string[] components = entry.DN.Split(dnDelimiters); commonName = components[1]; } LdapAttribute givenAttr = entry.getAttribute("givenName"); if (givenAttr != null && givenAttr.StringValue.Length != 0) { firstName = givenAttr.StringValue as string; } LdapAttribute sirAttr = entry.getAttribute("sn"); if (sirAttr != null && sirAttr.StringValue.Length != 0) { lastName = sirAttr.StringValue as string; } if (firstName != null && lastName != null) { if (FullNameDisplay == "FirstNameLastName") { fullName = firstName + " " + lastName; } else { fullName = lastName + " " + firstName; } } else { fullName = commonName; } } catch (Exception gEx) { log.Error(gEx.Message); log.Error(gEx.StackTrace); state.ReportError(gEx.Message); attrError = true; } // No exception were generated gathering member info // so call the sync engine to process this member if (attrError == false) { if (timeStampAttr != null && timeStampAttr.StringValue.Length != 0) { Property ts = new Property("LdapTimeStamp", timeStampAttr.StringValue); ts.LocalProperty = true; Property[] propertyList = { ts }; state.ProcessMember( ldapGuid, commonName, firstName, lastName, fullName, distinguishedName, propertyList); } else { state.ProcessMember( ldapGuid, commonName, firstName, lastName, fullName, distinguishedName, null); } } }
/// <summary> /// The SimiasAdmin is processed differently than normal simias users because /// the account is aleady created in the Simias store before LdapSync runs /// so the GUID has already been created. The SimiasAdmin must always exist in the /// store and the DN entry in the store must be correct with the Distinguished /// Name in the directory. LdapSync counts on the AdminDN entry in Simias.config /// to be updated if the admin is moved in the directory. /// </summary> /// <param name="conn">ldap connection</param> private void ProcessSimiasAdmin(LdapConnection conn) { // Since the first version of the iFolder 3.0 only // exposes a username, firstname, lastname and full // name, we'll limit the scope of the search string[] searchAttributes = { "modifytimestamp", ldapSettings.NamingAttribute, "cn", "sn", "GUID", "givenName" }; char[] dnDelimiters = { ',', '=' }; LdapEntry entry = null; LdapAttribute timeStampAttr = null; Member cMember = null; Property dn = null; string ldapGuid = null; log.Debug("ProcessSimiasAdmin( " + ldapSettings.AdminDN + ")"); if (domain == null) { store = Store.GetStore(); domain = store.GetDomain(store.DefaultDomain); if (domain == null) { throw new SimiasException("Enterprise domain does not exist!"); } } // If the DN property has never been set on the SimiasAdmin, // set it now cMember = domain.Owner; dn = cMember.Properties.GetSingleProperty("DN"); if (dn == null || dn.Value.ToString() == "") { if (ldapSettings.AdminDN != null && ldapSettings.AdminDN != "") { dn = new Property("DN", ldapSettings.AdminDN); cMember.Properties.ModifyProperty(dn); } } // Check if the Simias Admin has changed in configuration if (ldapSettings.AdminDN != null && ldapSettings.AdminDN != "" && dn.Value.ToString() != ldapSettings.AdminDN) { ChangeSimiasAdmin(conn); cMember = domain.Owner; } // The Simias admin is tracked in the directory by the directory // guid. Make sure the guid is stored in the node Property lguidProp = cMember.Properties.GetSingleProperty("LdapGuid"); if (lguidProp == null) { // This must be the first time thru so let's get the directory // entry based on the configured DN try { entry = conn.Read(ldapSettings.AdminDN, searchAttributes); } catch (LdapException lEx) { log.Error("The Simias Administrator does not exist in the Ldap directory as configured in Simias.config!"); log.Error(lEx.Message); } catch (Exception e1) { log.Error("The Simias Administrator does not exist in the Ldap directory as configured in Simias.config!"); log.Error(e1.Message); } if (entry != null) { ldapGuid = GetLdapGuid(entry); lguidProp = new Property("LdapGuid", ldapGuid); lguidProp.LocalProperty = true; cMember.Properties.ModifyProperty(lguidProp); } } else { ldapGuid = lguidProp.Value.ToString(); } if (ldapGuid != null) { try { entry = null; // Now go find the SimiasAdmin in the Ldap directory string guidFilter = BuildGuidFilter(ldapGuid); LdapSearchResults results = conn.Search( "", LdapConnection.SCOPE_SUB, "(&(objectclass=inetOrgPerson)" + guidFilter + ")", searchAttributes, false); if (results.hasMore() == true) { entry = results.next(); } } catch (LdapException e) { log.Error(e.LdapErrorMessage); log.Error(e.StackTrace); } catch (Exception e) { log.Error(e.Message); log.Error(e.StackTrace); } if (entry != null) { // // check if the ldap object's time stamp has changed // try { timeStampAttr = entry.getAttribute("modifytimestamp"); Property pStamp = cMember.Properties.GetSingleProperty("LdapTimeStamp"); if ((pStamp == null) || (pStamp != null && (string)pStamp.Value != timeStampAttr.StringValue)) { // The time stamp changed let's look at first and // last name try { bool changed = false; // If we're tracking by ldap see if the naming attribute // has changed LdapAttribute namingAttr = entry.getAttribute(ldapSettings.NamingAttribute); if (namingAttr != null && namingAttr.StringValue.Length != 0) { if (namingAttr.StringValue != cMember.Name) { cMember.Name = namingAttr.StringValue; } } LdapAttribute givenAttr = entry.getAttribute("givenName"); if (givenAttr != null && givenAttr.StringValue.Length != 0) { if (givenAttr.StringValue != cMember.Given) { changed = true; cMember.Given = givenAttr.StringValue; } } LdapAttribute sirAttr = entry.getAttribute("sn"); if (sirAttr != null && sirAttr.StringValue.Length != 0) { if (sirAttr.StringValue != cMember.Family) { cMember.Family = sirAttr.StringValue; changed = true; } } // If the entry has changed and we have a valid // family and given if (changed == true && cMember.Given != null && cMember.Given != "" && cMember.Family != null && cMember.Family != "") { cMember.FN = cMember.Given + " " + cMember.Family; } // Did the distinguished name change? Property dnProp = cMember.Properties.GetSingleProperty("DN"); if (dnProp != null && (dnProp.ToString() != entry.DN)) { dnProp.Value = entry.DN; cMember.Properties.ModifyProperty("DN", dnProp); } } catch {} pStamp = new Property("LdapTimeStamp", timeStampAttr.StringValue); pStamp.LocalProperty = true; cMember.Properties.ModifyProperty(pStamp); } } catch {} } else { log.Error("The Simias administrator could not be verified in the directory!"); log.Error("Please update Simias.config with a valid Ldap user"); } } else { log.Error("The Simias administrator could not be verified in the directory!"); log.Error("Please update Simias.config with a valid Ldap user"); } // Now matter what always update the sync guid so // the SimiasAdmin won't be deleted from Simias cMember.Properties.ModifyProperty(state.SyncGuid); domain.Commit(cMember); }
public static void Main(String[] args) { if (args.Length != 6) { Console.Error.WriteLine( "Usage: mono ModifyACL <host name> <port number> <login dn>" + " <password> \n <entry dn> <trustee dn>"); Console.Error.WriteLine( "Example: mono ModifyACL Acme.com 389 \"cn=Admin,o=Acme\"" + " secret \n \"cn=test,ou=Sales,o=Acme\" " + "\"cn=trustee,o=Acme\""); Environment.Exit(1); } int privileges = 0; int ldapVersion = LdapConnection.Ldap_V3; int ldapPort = System.Convert.ToInt32(args[1]); String ldapHost = args[0]; String loginDN = args[2]; String password = args[3]; String entryDN = args[4]; String trusteeDN = args[5]; LdapConnection lc = new LdapConnection(); // encode ACL value privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_BROWSE); privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_ADD); privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_DELETE); String aclValue = System.Convert.ToString(privileges) + "#" + "entry" + "#" + trusteeDN + "#" + "[Entry Rights]"; try { // connect to the server lc.Connect(ldapHost, ldapPort); // bind to the server lc.Bind(ldapVersion, loginDN, password); // modify entryDN's ACL attribute Console.WriteLine(" Entry DN: " + entryDN); Console.WriteLine(" Trustee DN: " + trusteeDN); Console.WriteLine(" Modifying entryDN's ACL value..."); LdapAttribute acl = new LdapAttribute("acl", aclValue); lc.Modify(entryDN, new LdapModification(LdapModification.ADD, acl)); Console.WriteLine(" Modified ACL values to grant trusteeDN the" + "\n 'read', 'write', and 'delete' entry rights.\n"); // display entryDN's ACL values findACLValues(lc, entryDN); // remove the Modified entryDN's ACL value Console.WriteLine("\n Removing the modified ACL value..."); lc.Modify(entryDN, new LdapModification(LdapModification.DELETE, acl)); Console.WriteLine(" Removed modified ACL value."); lc.Disconnect(); } catch (LdapException e) { if (e.ResultCode == LdapException.NO_SUCH_OBJECT) { Console.Error.WriteLine("Error: ModifyACL.java, No such entry"); } else if (e.ResultCode == LdapException.INSUFFICIENT_ACCESS_RIGHTS) { Console.Error.WriteLine("Error: ModifyACL.java, Insufficient rights"); } else if (e.ResultCode == LdapException.ATTRIBUTE_OR_VALUE_EXISTS) { Console.Error.WriteLine("Error: ModifyACL.java, Attribute or value " + "exists"); } else { Console.WriteLine("Error: ModifyACL.java, " + e.ToString()); } Environment.Exit(1); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
private void DoSearch() { InitBlock(); String[] attrs = new String[PropertiesToLoad.Count]; PropertiesToLoad.CopyTo(attrs, 0); LdapSearchConstraints cons = _conn.SearchConstraints; if (SizeLimit > 0) { cons.MaxResults = SizeLimit; } if (ServerTimeLimit != DefaultTimeSpan) { cons.ServerTimeLimit = (int)ServerTimeLimit.TotalSeconds; } int connScope = LdapConnection.SCOPE_SUB; switch (_SearchScope) { case SearchScope.Base: connScope = LdapConnection.SCOPE_BASE; break; case SearchScope.OneLevel: connScope = LdapConnection.SCOPE_ONE; break; case SearchScope.Subtree: connScope = LdapConnection.SCOPE_SUB; break; default: connScope = LdapConnection.SCOPE_SUB; break; } LdapSearchResults lsc = _conn.Search(SearchRoot.Fdn, connScope, Filter, attrs, PropertyNamesOnly, cons); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { switch (e.ResultCode) { // in case of this return codes exception should not be thrown case LdapException.SIZE_LIMIT_EXCEEDED: case LdapException.TIME_LIMIT_EXCEEDED: case LdapException.REFERRAL: continue; default: throw e; } } DirectoryEntry de = new DirectoryEntry(_conn); PropertyCollection pcoll = new PropertyCollection(); // de.SetProperties(); de.Path = DirectoryEntry.GetLdapUrlString(_Host, _Port, nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); if (ienum != null) { while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; pcoll[attributeName].AddRange(attribute.StringValueArray); // de.Properties[attributeName].AddRange(attribute.StringValueArray); // de.Properties[attributeName].Mbit=false; } } if (!pcoll.Contains("ADsPath")) { pcoll["ADsPath"].Add(de.Path); } // _SrchColl.Add(new SearchResult(de,PropertiesToLoad)); _SrchColl.Add(new SearchResult(de, pcoll)); } return; }
/// <summary> /// Retrieve information about one or more users /// </summary> /// <param name="retrieveGroupMembership">retrieving list of groups for each user will take longer</param> /// <param name="username">Username to lookup</param> /// <returns></returns> public XDoc GetUserInfo(bool retrieveGroupMembership, string username) { XDoc resultXml = null; LdapConnection conn = null; try { LdapSearchResults results = LookupLdapUser(retrieveGroupMembership, username, out conn); if (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) { throw new ArgumentNullException("nextEntry"); } //Create xml from search entry resultXml = new XDoc("user"); string name = string.Empty; //If a usernameattribute is configured, use that. Otherwise try the common ones. if (!string.IsNullOrEmpty(_config.UserNameAttribute)) { name = GetAttributeSafe(nextEntry, _config.UserNameAttribute); } else { name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory if (string.IsNullOrEmpty(name)) { name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP } if (string.IsNullOrEmpty(name)) { name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP } if (string.IsNullOrEmpty(name)) { name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory } } string displayName = BuildDisplayNameFromPattern(_config.DisplayNamePattern, nextEntry); resultXml.Attr("name", name); if (!string.IsNullOrEmpty(displayName)) { resultXml.Attr("displayname", displayName); } resultXml.Start("ldap-dn").Value(nextEntry.DN).End(); resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End(); resultXml.Start("firstname").Value(GetAttributeSafe(nextEntry, "givenname")).End(); resultXml.Start("lastname").Value(GetAttributeSafe(nextEntry, "sn")).End(); resultXml.Start("phonenumber").Value(GetAttributeSafe(nextEntry, "telephonenumber")).End(); resultXml.Start("email").Value(GetAttributeSafe(nextEntry, "mail")).End(); resultXml.Start("description").Value(GetAttributeSafe(nextEntry, "description")).End(); //Retrieve group memberships if (string.IsNullOrEmpty(_config.GroupMembershipQuery)) { LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet(); LdapAttribute memberAttr = null; if (memberAttrSet != null) { memberAttr = memberAttrSet.getAttribute(_config.GroupMembersAttribute); } if (memberAttr != null) { resultXml.Start("groups"); foreach (string member in memberAttr.StringValueArray) { resultXml.Start("group"); resultXml.Attr("name", GetNameFromDn(member)); resultXml.Start("ldap-dn").Value(member).End(); resultXml.End(); } resultXml.End(); } } else { //Perform custom query to determine groups of a user PopulateGroupsForUserWithQuery(resultXml, username, conn); } } } finally { UnBind(conn); } return(resultXml); }
/// <summary> /// Queries to find the type of directory /// </summary> /// <returns>The LDAP directory type.</returns> public LdapDirectoryType QueryDirectoryType() { Console.WriteLine("get directory type"); LdapAttribute attr = null; LdapEntry entry = null; bool eDirectory = false; LdapSearchResults lsc = connection.Search("", LdapConnection.SCOPE_BASE, "objectClass=*", null, false); while (lsc.hasMore()) { entry = null; try { entry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + entry.DN); LdapAttributeSet attributeSet = entry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { attr = (LdapAttribute)ienum.Current; string attributeName = attr.Name; string attributeVal = attr.StringValue; Console.WriteLine(attributeName + ": value :" + attributeVal); //eDirectory specific attributes //If any of the following attribute is found, conclude this as eDirectory if ( /*String.Equals(attributeName, "vendorVersion")==true || */ String.Equals(attributeVal, "Novell, Inc.") == true || String.Equals(attributeVal, "NetIQ Corporation") == true /* || * String.Equals(attributeName, "dsaName")==true ||*/ /*String.Equals(attributeName, "directoryTreeName")==true*/) { eDirectory = true; Console.WriteLine("Type : Novell eDirectory"); break; } } } if (eDirectory == true) { ldapType = LdapDirectoryType.eDirectory; } else { // Decide is this a Active Directory or not. If not AD then the assumption is OpenLDAP entry = connection.Read(""); attr = entry.getAttribute("defaultNamingContext"); if (attr != null) { ldapType = LdapDirectoryType.ActiveDirectory; } else { ldapType = LdapDirectoryType.OpenLDAP; } } return(ldapType); }
/// <summary> /// Retrieves group information from ldap /// </summary> /// <param name="retrieveGroupMembers">true to return users in each group. This may hurt performance</param> /// <param name="optionalGroupName">Group to lookup by name. Null for all groups</param> /// <returns></returns> public XDoc GetGroupInfo(bool retrieveGroupMembers, string optionalGroupName) { LdapConnection conn = null; XDoc resultXml = null; try { //Confirm a query bind has been established conn = Bind(); string searchFilter; //Build the searchfilter based on if a group name is given. if (!string.IsNullOrEmpty(optionalGroupName)) { optionalGroupName = EscapeLdapString(optionalGroupName); //Looking up group by name searchFilter = string.Format(PhpUtil.ConvertToFormatString(_config.GroupQuery), optionalGroupName); } else { //Looking up all groups searchFilter = _config.GroupQueryAll; } //Build interesting attribute list List <string> attrs = new List <string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); if (retrieveGroupMembers) { attrs.Add("member"); } if (!string.IsNullOrEmpty(_config.GroupNameAttribute) && !attrs.Contains(_config.GroupNameAttribute)) { attrs.Add(_config.GroupNameAttribute); } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); //Create outer groups collection if multiple groups are being looked up or none provided if (string.IsNullOrEmpty(optionalGroupName)) { resultXml = new XDoc("groups"); } while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); continue; } //Create xml from search entry if (resultXml == null) { resultXml = new XDoc("group"); } else { resultXml.Start("group"); } string name = string.Empty; //If a groupnameattribute is configured, use that. Otherwise try the common ones. if (!string.IsNullOrEmpty(_config.GroupNameAttribute)) { name = GetAttributeSafe(nextEntry, _config.GroupNameAttribute); } else { name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory if (string.IsNullOrEmpty(name)) { name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP } if (string.IsNullOrEmpty(name)) { name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP } if (string.IsNullOrEmpty(name)) { name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory } } resultXml.Attr("name", name); resultXml.Start("ldap-dn").Value(nextEntry.DN).End(); resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End(); //Retrieve and write group membership to xml LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet(); LdapAttribute memberAttr = memberAttrSet.getAttribute("member"); // TODO MaxM: This currently does not differentiate between user and group // members. if (memberAttr != null) { foreach (string member in memberAttr.StringValueArray) { resultXml.Start("member"); resultXml.Attr("name", GetNameFromDn(member)); resultXml.Start("ldap-dn").Value(member).End(); resultXml.End(); } } if (string.IsNullOrEmpty(optionalGroupName)) { resultXml.End(); } } } finally { UnBind(conn); } return(resultXml); }
static void Main(string[] args) { if (args.Length != 6) { Console.WriteLine("Usage: mono Search <host name> <ldap port> <login dn>" + " <password> <search base>" + " <search filter>"); Console.WriteLine("Example: mono Search Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"" + " \"(objectclass=*)\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String searchBase = args[4]; String searchFilter = args[5]; try { LdapConnection conn = new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, password); LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, null, false); while (lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; if (!Base64.isLDIFSafe(attributeVal)) { byte[] tbyte = SupportClass.ToByteArray(attributeVal); attributeVal = Base64.encode(SupportClass.ToSByteArray(tbyte)); } Console.WriteLine(attributeName + "value:" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
public static void Main(String[] args) { if (args.Length != 4) { Console.WriteLine("Usage: mono ListGroups <host name> <login dn>" + " <password> <group dn>\n"); Console.WriteLine("Example: mono ListGroups Acme.com" + " \"cn=admin,o=Acme\" secret " + " cn=salesGroup,ou=sales,o=acme\n"); Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int searchScope = LdapConnection.SCOPE_BASE; int ldapVersion = LdapConnection.Ldap_V3; int i; IEnumerator objClass = null; IEnumerator queryURL = null; IEnumerator identity = null; IEnumerator excludedMember = null; IEnumerator member = null; bool isGroup = false, isDynamicGroup = false; String[] attrs = new String[] { "objectClass", "memberQueryURL", "dgIdentity", "excludedMember", "member" }; /* Since reading members of a dynamic group could potentially involve * a significant directory search, we use a timeout. Setting * time out to 10 seconds */ LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String groupDN = args[3]; LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect(ldapHost, ldapPort); // bind to the server lc.Bind(ldapVersion, loginDN, password); Console.WriteLine("\n\tReading object :" + groupDN); LdapSearchResults searchResults = lc.Search(groupDN, // object to read searchScope, // scope - read single object null, // search filter attrs, // return only required attributes false, // return attrs and values cons); // time out value // Examine the attributes that were returned and extract the data LdapEntry nextEntry = null; try { nextEntry = searchResults.Next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); Environment.Exit(1); } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); while (allAttributes.MoveNext()) { LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; // Save objectclass values if (attributeName.ToUpper().Equals("objectClass".ToUpper())) { objClass = attribute.StringValues; } // Save the memberQueryURL attribute if present else if (attributeName.ToUpper().Equals("memberQueryURL".ToUpper())) { queryURL = attribute.StringValues; } // Save the dgIdentity attribute if present else if (attributeName.ToUpper().Equals("dgIdentity".ToUpper())) { identity = attribute.StringValues; } // Save the excludedMember attribute if present else if (attributeName.ToUpper().Equals("excludedMember".ToUpper())) { excludedMember = attribute.StringValues; } /* Save the member attribute. This may also show up * as uniqueMember */ else if (attributeName.ToUpper().Equals("member".ToUpper()) || attributeName.ToUpper().Equals("uniqueMember".ToUpper())) { member = attribute.StringValues; } } /* Verify that this is a group object (i.e. objectClass contains * the value "group", "groupOfNames", or "groupOfUniqueNames"). * Also determine if this is a dynamic group object * (i.e. objectClass contains the value "dynamicGroup" or * "dynamicGroupAux"). */ while (objClass.MoveNext()) { String objectName = (String)objClass.Current; if (objectName.ToUpper().Equals("group".ToUpper()) || objectName.ToUpper().Equals("groupOfNames".ToUpper()) || objectName.ToUpper().Equals("groupOfUniqueNames".ToUpper())) { isGroup = true; } else if (objectName.ToUpper().Equals("dynamicGroup".ToUpper()) || objectName.ToUpper().Equals("dynamicGroupAux".ToUpper())) { isGroup = isDynamicGroup = true; } } if (!isGroup) { Console.WriteLine("\tThis object is NOT a group object." + "Exiting.\n"); Environment.Exit(0); } /* If this is a dynamic group, display its memberQueryURL, identity * and excluded member list. */ if (isDynamicGroup) { if ((queryURL != null) && (queryURL.MoveNext())) { Console.WriteLine("\tMember Query URL:"); while (queryURL.MoveNext()) { Console.WriteLine("\t\t" + queryURL.Current); } } if ((identity != null) && (identity.MoveNext())) { Console.WriteLine("\tIdentity for search:" + identity.Current); } if ((excludedMember != null) && (excludedMember.MoveNext())) { Console.WriteLine("\tExcluded member list:"); while (excludedMember.MoveNext()) { Console.WriteLine("\t\t" + excludedMember.Current); } } } // Print the goup's member list if (member != null && member.MoveNext()) { Console.WriteLine("\n\tMember list:"); while (member.MoveNext()) { Console.WriteLine("\t\t" + member.Current); } } // disconnect with the server lc.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); Environment.Exit(1); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
static void Main(string[] args) { if (args.Length != 6) { Console.WriteLine("Usage: mono SortSearch <host name> <ldap port> <login dn>" + " <password> <search base>" + " <search filter>"); Console.WriteLine("Example: mono SortSearch Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"" + " \"(objectclass=*)\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String searchBase = args[4]; String searchFilter = args[5]; String[] attrs = new String[1]; attrs[0] = "sn"; LdapSortKey[] keys = new LdapSortKey[1]; keys[0] = new LdapSortKey("sn"); try { LdapConnection conn = new LdapConnection(); conn.Connect(ldapHost, ldapPort); conn.Bind(loginDN, password); // Create a LDAPSortControl object - Fail if cannot sort LdapSortControl sort = new LdapSortControl(keys, true); // Set the Sort control to be sent as part of search request LdapSearchConstraints cons = conn.SearchConstraints; cons.setControls(sort); conn.Constraints = cons; Console.WriteLine("Connecting to:" + ldapHost); LdapSearchResults lsc = conn.Search(searchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs, false, (LdapSearchConstraints)null); while (lsc.HasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.Next(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); // Exception is thrown, go for next entry continue; } Console.WriteLine("\n" + nextEntry.DN); LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { LdapAttribute attribute = (LdapAttribute)ienum.Current; string attributeName = attribute.Name; string attributeVal = attribute.StringValue; Console.WriteLine(attributeName + "value:" + attributeVal); } } conn.Disconnect(); } catch (LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); Console.WriteLine("Error:" + e.ToString()); return; } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
/// <summary> Specifies a modification to be made to an attribute. /// /// </summary> /// <param name="op"> The type of modification to make, which can be /// one of the following: /// <ul> /// <li>LdapModification.ADD - The value should be added to /// the attribute</li> /// /// <li>LdapModification.DELETE - The value should be removed /// from the attribute </li> /// /// <li>LdapModification.REPLACE - The value should replace all /// existing values of the /// attribute </li> /// </ul> /// </param> /// <param name="attr"> The attribute to modify. /// /// </param> public LdapModification(int op, LdapAttribute attr) { this.op = op; this.attr = attr; }
private void CommitEntry() { PropertyCollection properties = GetProperties(false); if (!Nflag) { System.Collections.ArrayList modList = new System.Collections.ArrayList(); foreach (string attribute in properties.PropertyNames) { LdapAttribute attr = null; if (properties [attribute].Mbit) { switch (properties [attribute].Count) { case 0: attr = new LdapAttribute(attribute, new string [0]); modList.Add(new LdapModification(LdapModification.DELETE, attr)); break; case 1: string val = (string)properties [attribute].Value; attr = new LdapAttribute(attribute, val); modList.Add(new LdapModification(LdapModification.REPLACE, attr)); break; default: object [] vals = (object [])properties [attribute].Value; string [] aStrVals = new string [properties [attribute].Count]; Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count); attr = new LdapAttribute(attribute, aStrVals); modList.Add(new LdapModification(LdapModification.REPLACE, attr)); break; } properties [attribute].Mbit = false; } } if (modList.Count > 0) { LdapModification[] mods = new LdapModification[modList.Count]; Type mtype = typeof(LdapModification); mods = (LdapModification[])modList.ToArray(mtype); ModEntry(mods); } } else { LdapAttributeSet attributeSet = new LdapAttributeSet(); foreach (string attribute in properties.PropertyNames) { if (properties [attribute].Count == 1) { string val = (string)properties [attribute].Value; attributeSet.Add(new LdapAttribute(attribute, val)); } else { object[] vals = (object [])properties [attribute].Value; string[] aStrVals = new string [properties [attribute].Count]; Array.Copy(vals, 0, aStrVals, 0, properties [attribute].Count); attributeSet.Add(new LdapAttribute(attribute, aStrVals)); } } LdapEntry newEntry = new LdapEntry(Fdn, attributeSet); conn.Add(newEntry); Nflag = false; } }
public static bool ContainsAttr(this LdapEntry entry, string attrName) { LdapAttribute ldapAttribute = new LdapAttribute(attrName); return(entry.getAttributeSet().Contains(ldapAttribute)); }
public void TestLdapAttributeGetBytesMaxInt() { var attribute = new LdapAttribute(UniversalDataType.Integer, Int32.MaxValue); Assert.AreEqual(Int32.MaxValue, attribute.GetValue <Int32>()); }
// read and print search results public static bool searchDynamicGroupEntry(LdapConnection lc, String searchBase) { bool status = true; int searchScope = LdapConnection.SCOPE_BASE; String[] attrList = new String[] { "member" }; String searchFilter = "(objectclass=*)"; /* Since reading members of a dynamic group could potentially involve * a significant directory search, we use a timeout. Setting * time out to 10 seconds */ LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000; try { LdapSearchResults searchResults = lc.Search(searchBase, searchScope, searchFilter, attrList, // return only "member" attr false, // return attrs and values cons); // time out value LdapEntry nextEntry = null; // Read and print search results. We expect only one entry */ if ((nextEntry = searchResults.next()) != null) { LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); if (allAttributes.MoveNext()) { // found member(s) in this group LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; IEnumerator allValues = attribute.StringValues; if (allValues != null) { while (allValues.MoveNext()) { String Value = (String)allValues.Current; Console.WriteLine(" " + attributeName + " : " + Value); } } } else { // no member(s) found in this group Console.WriteLine(" No objects matched the " + " memberQueryURL filter.\n "); } } } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); status = false; } return(status); }
public void TestLdapAttributeGetBytesString() { var attribute = new LdapAttribute(UniversalDataType.OctetString, "dc=karakorum,dc=net"); Assert.AreEqual("041364633d6b6172616b6f72756d2c64633d6e6574", Utils.ByteArrayToString(attribute.GetBytes())); }
public static void Main(String[] args) { if (args.Length != 6) { Console.Error.WriteLine("Usage: mono SimplePassword <host Name> " + "<port number> <login dn> <password> <user dn>" + " <new user password>"); Console.Error.WriteLine("\n Example: mono SimplePassword Acme.com 389" + " \"cn=Admin,o=Acme\" secret\n" + " \"cn=JSmith,ou=sales,o=Acme\" userPWD"); Environment.Exit(1); } int ldapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; int ldapPort = int.Parse(args[1]); String loginDN = args[2]; String password = args[3]; String userDN = args[4]; String userPWD = args[5]; /* Simple Password control. There is no value associated with this control, * just an OID and criticality. Setting the criticality to TRUE means the * server will return an error if it does not recognize or is unable to * perform the control. */ LdapControl cont = new LdapControl(simplePassOID, true, null); LdapConstraints lcons = new LdapConstraints(); lcons.setControls(cont); LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect(ldapHost, ldapPort); // bind to the server lc.Bind(ldapVersion, loginDN, password); // Modify the 'userpassword' attribute, with the Simple // Password control. LdapModification[] modifications = new LdapModification[1]; LdapAttribute sPassword = new LdapAttribute("userPassword", userPWD); modifications[0] = new LdapModification(LdapModification.REPLACE, sPassword); lc.Modify(userDN, modifications, lcons); Console.WriteLine("Your Simple password has been modified."); lc.Disconnect(); } catch (LdapException e) { Console.Error.WriteLine("SimplePassword example failed"); Console.Error.WriteLine("Error: " + e.ToString()); Environment.Exit(1); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
public void TestAttributeClass2() { var attribute = new LdapAttribute(LdapOperation.BindRequest); Assert.AreEqual(LdapOperation.BindRequest, attribute.LdapOperation); }
public void Add(LdapAttribute anAttribute) { fData.Add(anAttribute); }