public bool CheckUser(string UserName, string OldPassword) { bool result = true; string User = UserName; string Pass = OldPassword; // Creating an LdapConnection instance Novell.Directory.Ldap.LdapConnection ldapConn = new Novell.Directory.Ldap.LdapConnection(); string dn = "uid = " + UserName + ",ou=users,dc=example,dc=com"; try { //Connect function will create a socket connection to the server ldapConn.Connect(ldapHost, ldapPort); //Bind function will Bind the user object Credentials to the Server ldapConn.Bind(dn, OldPassword); } catch (Novell.Directory.Ldap.LdapException e) { TempData["msg"] = "<script>alert('Could not authenticate user!');</script>"; result = false; return(result); } finally { // Disconnect from LDAP ldapConn.Disconnect(); } return(result); }
static void Main(string[] args) { if ( args.Length != 4) { Console.WriteLine("Usage: mono SecureBind <host name> <ldap port> <login dn>" + " <password> \n"); Console.WriteLine("Example: mono SecureBind Acme.com 636" + " \"cn=admin,o=Acme\"" + " secret \n"); Console.WriteLine("Import the server Trusted Root Certificate in Mono trust store using certmgr.exe utility e.g.\n"); Console.WriteLine("certmgr -add -c Trust /home/exports/TrustedRootCert.cer\n"); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; LdapConnection conn=null; try { conn= new LdapConnection(); conn.SecureSocketLayer=true; Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); Console.WriteLine(" SSL Bind Successfull"); } catch(Exception e) { Console.WriteLine("Error:" + e.Message); } conn.Disconnect(); }
public static void Main(System.String[] args) { if (args.Length != 5) { System.Console.Error.WriteLine("Usage: mono ListReplicas <host Name> " + "<port number> <login dn> <password>" + "\n <server ND>"); System.Console.Error.WriteLine("Example: mono ListReplicas Acme.com 389 " + "\"cn=Admin,o=Acme\" secret" + "\n \"cn=myServer,o=Acme\""); System.Environment.Exit(1); } int ldapVersion = LdapConnection.Ldap_V3; System.String ldapHost = args[0]; int ldapPort = System.Int32.Parse(args[1]); System.String loginDN = args[2]; System.String password = args[3]; System.String serverDN = args[4]; LdapConnection ld = new LdapConnection(); try { // connect to the server ld.Connect(ldapHost, ldapPort); // bind to the server ld.Bind(ldapVersion, loginDN, password); System.Console.Out.WriteLine("\nLogin succeeded"); LdapExtendedOperation request = new ListReplicasRequest(serverDN); LdapExtendedResponse response = ld.ExtendedOperation(request); if ((response.ResultCode == LdapException.SUCCESS) && (response is ListReplicasResponse)) { System.Console.Out.WriteLine("Replica List: "); System.String[] rList = ((ListReplicasResponse)response).ReplicaList; int len = rList.Length; for (int i = 0; i < len; i++) { System.Console.Out.WriteLine(rList[i]); } System.Console.Out.WriteLine("\nList replica request succeeded\n"); } else { System.Console.Out.WriteLine("List Replicas request failed." + response.ResultCode); // throw new LdapException(response.ErrorMessage, response.ResultCode, (System.String) null); } /* Done, so disconnect */ if (ld.Connected) { ld.Disconnect(); } } catch (LdapException e) { System.Console.Out.WriteLine("\nError: " + e.ToString()); } }
public static void Main(System.String[] args) { if (args.Length != 5) { System.Console.Out.WriteLine("Usage: mono VerifyPassword <host name>" + " <login dn> <password> <object dn>\n" + " <test password>"); System.Console.Out.WriteLine("Example: mono VerifyPassword Acme.com " + "\"cn=Admin,o=Acme\" secret\n" + " \"cn=JSmith,ou=Sales,o=Acme\" testPassword"); System.Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int ldapVersion = LdapConnection.Ldap_V3; System.String ldapHost = args[0]; System.String loginDN = args[1]; System.String password = args[2]; System.String objectDN = args[3]; System.String testPassword = args[4]; LdapConnection conn = new LdapConnection(); try { // connect to the server conn.Connect(ldapHost, ldapPort); // authenticate to the server conn.Bind(ldapVersion, loginDN, password); LdapAttribute attr = new LdapAttribute("userPassword", testPassword); bool correct = conn.Compare(objectDN, attr); System.Console.Out.WriteLine(correct?"The password is correct.":"The password is incorrect.\n"); // disconnect with the server conn.Disconnect(); } catch (LdapException e) { if (e.ResultCode == LdapException.NO_SUCH_OBJECT) { System.Console.Error.WriteLine("Error: No such entry"); } else if (e.ResultCode == LdapException.NO_SUCH_ATTRIBUTE) { System.Console.Error.WriteLine("Error: No such attribute"); } else { System.Console.Error.WriteLine("Error: " + e.ToString()); } } catch (System.IO.IOException e) { System.Console.Out.WriteLine("Error: " + e.ToString()); } System.Environment.Exit(0); }
public static void Main(System.String[] args) { if (args.Length != 4) { System.Console.Error.WriteLine("Usage: mono GetBindDN " + "<host Name> <port number> <login dn>" + "\n <password>"); System.Console.Error.WriteLine("Example: mono GetBindDN Acme.com " + "389 \"cn=Admin,o=Acme\" secret"); System.Environment.Exit(1); } int LdapVersion = LdapConnection.Ldap_V3; System.String LdapHost = args[0]; int LdapPort = System.Int32.Parse(args[1]); System.String loginDN = args[2]; System.String password = args[3]; LdapConnection ld = new LdapConnection(); try { // connect to the server ld.Connect(LdapHost, LdapPort); // bind to the server ld.Bind(LdapVersion, loginDN, password); System.Console.Out.WriteLine("\nLogin succeeded"); LdapExtendedOperation request = new GetBindDNRequest(); LdapExtendedResponse response = ld.ExtendedOperation(request); if (((response.ResultCode) == LdapException.SUCCESS) && (response is GetBindDNResponse)) { System.Console.Out.WriteLine("You were logged in as: " + ((GetBindDNResponse)response).Identity); System.Console.Out.WriteLine("\nGetBindDN succeeded.\n"); } else { System.Console.Out.WriteLine("GetBindDN failed.\n"); throw new LdapException(response.ErrorMessage, response.ResultCode, (System.String)null); } /* Done, so disconnect */ if (ld.Connected) { ld.Disconnect(); } } catch (LdapException e) { System.Console.Out.WriteLine("\nError: " + e.LdapErrorMessage); } }
static void Main(string[] args) { if ( args.Length != 5) { Console.WriteLine("Usage: mono AddEntry <host name> <ldap port> <login dn>" + " <password> <container>"); Console.WriteLine("Example: mono AddEntry Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String containerName = args[4]; try { LdapAttributeSet attributeSet = new LdapAttributeSet(); attributeSet.Add( new LdapAttribute( "objectclass", "inetOrgPerson")); attributeSet.Add( new LdapAttribute("cn", new string[]{"James Smith", "Jim Smith", "Jimmy Smith"})); attributeSet.Add( new LdapAttribute("givenname", "James")); attributeSet.Add( new LdapAttribute("sn", "Smith")); attributeSet.Add( new LdapAttribute("telephonenumber","1 801 555 1212")); attributeSet.Add( new LdapAttribute("mail", "*****@*****.**")); attributeSet.Add( new LdapAttribute("userpassword","newpassword")); string dn = "cn=KSmith," + containerName; LdapEntry newEntry = new LdapEntry( dn, attributeSet ); LdapConnection conn= new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); conn.Add( newEntry ); Console.WriteLine("Entry:" + dn + " Added Successfully"); conn.Disconnect(); } catch(LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch(Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
static void Main(string[] args) { if ( args.Length != 5) { Console.WriteLine("Usage: mono ModifyEntry <host name> <ldap port> <login dn>" + " <password> <Modify dn>"); Console.WriteLine("Example: mono ModifyEntry Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"cn=ksmith,o=Acme\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String dn = args[4]; try { Console.WriteLine("Connecting to:" + ldapHost); LdapConnection conn= new LdapConnection(); ArrayList modList = new ArrayList(); String desc = "This object belongs to test user"; // Add a new value to the description attribute LdapAttribute attribute = new LdapAttribute( "description", desc); modList.Add( new LdapModification(LdapModification.ADD, attribute)); String email = "*****@*****.**"; attribute = new LdapAttribute( "mail", email); modList.Add( new LdapModification(LdapModification.REPLACE, attribute)); LdapModification[] mods = new LdapModification[modList.Count]; mods = (LdapModification[])modList.ToArray(typeof(LdapModification)); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); conn.Modify(dn,mods); Console.WriteLine(" Entry: " + dn + "Modified Successfully"); conn.Disconnect(); } catch(LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch(Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { try { LdapConnection conn = new LdapConnection(); //Console.WriteLine("Connecting to:" + ldapHost); conn.Connect("192.168.36.10", 389); conn.Bind(Login1.UserName, Login1.Password); conn.Disconnect(); } catch (Exception ex) { throw ex; } }
static void Main(string[] args) { if ( args.Length != 7) { Console.WriteLine("Usage: mono AddReplica <host name> <ldap port> <login dn>" + " <password> <replica dn> <replica type> <server dn> "); Console.WriteLine("Example: mono AddReplica Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=Sales,o=Acme\" 1 \"cn=myServer,o=Acme\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String replicaDN = args[4]; int replicaType = System.Convert.ToInt32(args[5]); String serverDN = args[6]; try { LdapConnection conn= new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); LdapExtendedOperation request = new AddReplicaRequest( replicaDN, serverDN, replicaType, ReplicationConstants.Ldap_ENSURE_SERVERS_UP); LdapExtendedResponse response = conn.ExtendedOperation(request); if ( response.ResultCode == LdapException.SUCCESS ) { Console.WriteLine("Add Replica Request succeeded\n"); } conn.Disconnect(); } catch(LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch(Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
public bool AuthenticateUser(string host, string username, string password, string port, out string Errmsg) { try { LdapConnection conn = new LdapConnection(); conn.Connect(host, Convert.ToInt32(port)); conn.Bind(username, password); conn.Disconnect(); Errmsg = ""; return true; } catch (Exception ex) { Errmsg = ex.Message; return false; } }
static void Main(string[] args) { if ( args.Length != 5) { Console.WriteLine("Usage: mono ModifyPass <host name> <ldap port> <login dn>" + " <old password> <new password>"); Console.WriteLine("Example: mono ModifyPass Acme.com 389" + " \"cn=tjhon,o=Acme\"" + " secret \"newpass\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String opassword = args[3]; String npassword = args[4]; try { LdapConnection conn= new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,opassword); LdapModification[] modifications = new LdapModification[2]; LdapAttribute deletePassword = new LdapAttribute("userPassword", opassword); modifications[0] = new LdapModification(LdapModification.DELETE, deletePassword); LdapAttribute addPassword = new LdapAttribute("userPassword", npassword); modifications[1] = new LdapModification(LdapModification.ADD, addPassword); conn.Modify(loginDN, modifications); System.Console.Out.WriteLine("Your password has been modified."); conn.Disconnect(); } catch(LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch(Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
static void Main(string[] args) { if ( args.Length != 4) { Console.WriteLine("Usage: mono RefreshLdapServer <host name> <ldap port> <login dn>" + " <password> "); Console.WriteLine("Example: mono RefreshLdapServer Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret "); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; try { LdapConnection conn= new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); LdapExtendedOperation request = new RefreshLdapServerRequest(); LdapExtendedResponse response = conn.ExtendedOperation(request); if ( response.ResultCode == LdapException.SUCCESS ) { Console.WriteLine("Refresh Ldap Server Request succeeded\n"); } conn.Disconnect(); } catch(LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch(Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
static void Main(string[] args) { if ( args.Length != 7) { Console.WriteLine("Usage: mono RenameEntry <host name> <ldap port> <login dn>" + " <password> <old dn> <new rdn> <parentDN>"); Console.WriteLine("Example: mono RenameEntry Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"cn=ksmith,o=Acme\" cn=JamesSmith \"o=Products,o=Acme\""); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; String oldDN = args[4]; String newRDN = args[5]; String parentDN = args[6]; try { Console.WriteLine("Connecting to:" + ldapHost); LdapConnection conn= new LdapConnection(); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); conn.Rename(oldDN, newRDN, parentDN, true); Console.WriteLine( "Entry " + oldDN + " has been renamed as " + newRDN + "," + parentDN ); 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 != 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); }
public LdapConnectionResult Test(string username, string password) { // Creating an LdapConnection instance var ldapConn = new LdapConnection(); var tempDomainName = new StringBuilder(100); if (!string.IsNullOrEmpty(_settings.DomainName)) { tempDomainName.Append(_settings.DomainName); tempDomainName.Append('\\'); } tempDomainName.Append(username); try { //Connect function will create a socket connection to the server ldapConn.Connect(_settings.Address, _settings.PortNumber); //Bind function will Bind the user object Credentials to the Server ldapConn.Bind(tempDomainName.ToString(), password); } catch (Exception e) { return(new LdapConnectionResult(false, e.Message, "Login")); } // Searches in the Marketing container and return all child entries just below this //container i.e. Single level search var claims = new List <ClaimViewModel>(); try { var cons = ldapConn.SearchConstraints; cons.ReferralFollowing = true; ldapConn.Constraints = cons; var attributes = _settings.Attributes?.Trim() == "" ? null : _settings.Attributes?.Split(",").Select(s => s.Trim()); var lsc = ldapConn.Search(_settings.DistinguishedName, (int)Enum.Parse <SearchScope>(_settings.SearchScope), $"(sAMAccountName={username})", attributes?.ToArray(), false, (LdapSearchConstraints)null); while (lsc.HasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.Next(); } catch (LdapException e) { ldapConn.Disconnect(); return(new LdapConnectionResult(false, e.Message, "Search Error")); } var attributeSet = nextEntry.GetAttributeSet(); System.Collections.IEnumerator ienum = attributeSet.GetEnumerator(); while (ienum.MoveNext()) { var attribute = (LdapAttribute)ienum.Current; var attributeName = attribute.Name; var attributeVal = attribute.StringValue; claims.Add(new ClaimViewModel(attributeName, attributeVal)); } } } catch (Exception e) { ldapConn.Disconnect(); return(new LdapConnectionResult(false, e.Message, "Search Error")); } ldapConn.Disconnect(); return(new LdapConnectionResult(true, claims.OrderBy(b => b.Type).ToList())); }
public static void Main(System.String[] args) { if (args.Length != 6) { System.Console.Error.WriteLine("Usage: mono GetReplicaInfo <host Name> " + "<port number> <login dn> <password>\n " + " <partition DN> <server ND>"); System.Console.Error.WriteLine("Example: mono GetReplicaInfo Acme.com 389 " + "\"cn=Admin,o=Acme\" secret\n " + "\"ou=Sales,o=Acme\" \"cn=myServer,o=Acme\""); System.Environment.Exit(1); } int ldapVersion = LdapConnection.Ldap_V3; System.String ldapHost = args[0]; int ldapPort = System.Int32.Parse(args[1]); System.String loginDN = args[2]; System.String password = args[3]; System.String partitionDN = args[4]; System.String serverDN = args[5]; int intInfo; System.String strInfo; LdapConnection ld = new LdapConnection(); try { // connect to the server ld.Connect(ldapHost, ldapPort); // bind to the server ld.Bind(ldapVersion, loginDN, password); System.Console.Out.WriteLine("\nLogin succeeded"); LdapExtendedOperation request = new GetReplicaInfoRequest(serverDN, partitionDN); LdapExtendedResponse response = ld.ExtendedOperation(request); if ((response.ResultCode == LdapException.SUCCESS) && (response is GetReplicaInfoResponse)) { System.Console.Out.WriteLine("Repica Info:"); strInfo = ((GetReplicaInfoResponse)response).getpartitionDN(); System.Console.Out.WriteLine(" Partition DN: " + strInfo); intInfo = ((GetReplicaInfoResponse)response).getpartitionID(); System.Console.Out.WriteLine(" Partition ID: " + intInfo); intInfo = ((GetReplicaInfoResponse)response).getreplicaState(); System.Console.Out.WriteLine(" Replica state: " + intInfo); intInfo = ((GetReplicaInfoResponse)response).getmodificationTime(); System.Console.Out.WriteLine(" Modification Time: " + intInfo); intInfo = ((GetReplicaInfoResponse)response).getpurgeTime(); System.Console.Out.WriteLine(" Purge Time: " + intInfo); intInfo = ((GetReplicaInfoResponse)response).getlocalPartitionID(); System.Console.Out.WriteLine(" Local partition ID: " + intInfo); intInfo = ((GetReplicaInfoResponse)response).getreplicaType(); System.Console.Out.WriteLine(" Replica Type: " + intInfo); intInfo = ((GetReplicaInfoResponse)response).getflags(); System.Console.Out.WriteLine(" Flags: " + intInfo); System.Console.Out.WriteLine("\nget replica information succeeded\n"); } else { System.Console.Out.WriteLine("Could not get replica information.\n"); throw new LdapException(response.ErrorMessage, response.ResultCode, (System.String)null); } /* Done, so disconnect */ if (ld.Connected) { ld.Disconnect(); } } catch (LdapException e) { System.Console.Out.WriteLine("Error: " + e.ToString()); } }
private void UnBind(LdapConnection conn) { if (conn != null && conn.Connected) { try { conn.Disconnect(); } catch { } } }
public static void Main(System.String[] args) { if (args.Length != 6) { System.Console.Error.WriteLine("Usage: mono GetEffectivePrivileges " + "<host Name> <port number> <login dn> " + "\n <password> <object dn> <trustee dn>"); System.Console.Error.WriteLine("Example: mono GetEffectivePrivileges Acme.com 389 " + "\"cn=Admin,o=Acme\" secret\n " + "\"cn=james,o=Acme\" " + "\"cn=admin,o=Acme\""); System.Environment.Exit(1); } int LdapVersion = LdapConnection.Ldap_V3; System.String LdapHost = args[0]; int LdapPort = System.Int32.Parse(args[1]); System.String loginDN = args[2]; System.String password = args[3]; System.String objectDN = args[4]; System.String trusteeDN = args[5]; int iRight = 0; System.String sRight = null; LdapConnection ld = new LdapConnection(); try { // connect to the server ld.Connect(LdapHost, LdapPort); // bind to the server ld.Bind(LdapVersion, loginDN, password); System.Console.Out.WriteLine("\nLogin succeeded"); // user can choose from: // 1. object rights(represented as [Entry Rights]); // 2. attribute rights(represented as [All Attributes Rights]; // 3. a single attribute name like 'acl' //String rightName = "[Entry Rights]" //String rightName = "[All Attributes Rights]"; System.String rightName = "acl"; LdapExtendedOperation request = new GetEffectivePrivilegesRequest(objectDN, trusteeDN, rightName); LdapExtendedResponse response = ld.ExtendedOperation(request); if (response.ResultCode == LdapException.SUCCESS && (response is GetEffectivePrivilegesResponse)) { iRight = ((GetEffectivePrivilegesResponse) response).Privileges; if (rightName.ToUpper().Equals("[Entry Rights]".ToUpper())) sRight = "object rights"; else if (rightName.ToUpper().Equals("[All Attributes Rights]".ToUpper())) sRight = "attribute rights"; else sRight = rightName; System.Console.Out.WriteLine("\"" + trusteeDN + "\" has the following" + " rights on \"" + objectDN + "\"s '" + sRight + "':"); PrintRights(rightName, iRight); System.Console.Out.WriteLine("\nGet Effective Privileges succeeded"); } else { System.Console.Out.WriteLine("Get Effective Privileges Failed"); throw new LdapException(response.ErrorMessage, response.ResultCode, (System.String) null); } /* Done, so disconnect */ if (ld.Connected) ld.Disconnect(); } catch (LdapException e) { System.Console.Out.WriteLine("Error: " + e.LdapErrorMessage); } }
static void Main( string[] args ) { if (args.Length != 6) { System.Console.Error.WriteLine("Usage: mono GetEffectivePrivilegesList " + "<host Name> <port number> <login dn> " + "\n <password> <object dn> <trustee dn>"); System.Console.Error.WriteLine("Example: mono GetEffectivePrivilegesList Acme.com 389 " + "\"cn=Admin,o=Acme\" secret\n " + "\"cn=james,o=Acme\" " + "\"cn=admin,o=Acme\""); System.Environment.Exit(1); } int ldapVersion = LdapConnection.Ldap_V3; System.String ldapHost = args[0]; int ldapPort = System.Int32.Parse(args[1]); System.String loginDN = args[2]; System.String password = args[3]; System.String objectDN = args[4]; System.String trusteeDN = args[5]; int[] iRight = {0}; System.String[] sRight = null; LdapConnection ld = new LdapConnection(); try { // connect to the server ld.Connect(ldapHost, ldapPort); // bind to the server ld.Bind(ldapVersion, loginDN, password); System.Console.Out.WriteLine("\nLogin succeeded"); // user can choose from: // 1. object rights(represented as [Entry Rights]); // 2. attribute rights(represented as [All Attributes Rights]; // 3. a single attribute name like 'acl' //String rightName = "{[Entry Rights],null}" //String rightName = "{[All Attributes Rights],null}"; //String rightName = "{attr1,attr2,attr3,.... ,null}" System.String[] rightName = {"acl","cn","dn",null}; LdapExtendedOperation request = new GetEffectivePrivilegesListRequest(objectDN,trusteeDN,rightName); LdapExtendedResponse response = ld.ExtendedOperation(request); if ( response.ResultCode == LdapException.SUCCESS && ( response is GetEffectivePrivilegesListResponse )) { iRight = ((GetEffectivePrivilegesListResponse)response).getPrivileges(); if(iRight.Length == (rightName.Length-1)) { sRight = new System.String[iRight.Length]; for ( int i =0 ; rightName[i] != null ; i++) { if ( rightName[i].ToUpper().Equals("[Entry Rights]".ToUpper()) ) sRight[i] = "object rights"; else if ( rightName[i].ToUpper().Equals("[All Attributes Rights]".ToUpper())) sRight[i] = "attribute rights"; else sRight[i] = rightName[i]; } System.Console.WriteLine("\"" + trusteeDN + "\" has the following rights on \""+ objectDN+"\'s "); for(int i=0;rightName[i]!=null;i++) { System.Console.WriteLine("'" + sRight[i] + "':"); PrintRights( rightName[i], iRight[i] ); System.Console.WriteLine("\nGet Effective Privileges succeeded"); } } else { System.Console.WriteLine("You have provided the wrong input in terms of attribute list"); } } else { System.Console.WriteLine("Get Effective Privileges List Failed"); throw new LdapException( response.ErrorMessage, response.ResultCode, (System.String) null); } /* Done, so disconnect */ if ( ld.Connected ) ld.Disconnect(); } catch( LdapException e ) { System.Console.Out.WriteLine("Error: " + e.LdapErrorMessage); } }
public static void Main(System.String[] args) { if (args.Length != 5) { System.Console.Error.WriteLine("Usage: mono PartitionEntryCount <host Name> " + "<port number> <login dn> <password>" + "\n <partition dn>"); System.Console.Error.WriteLine("Example: mono PartitionEntryCount Acme.com 389 " + "\"cn=Admin,o=Acme\" secret" + "\n \"ou=Sales,o=Acme\""); System.Environment.Exit(1); } int LdapVersion = LdapConnection.Ldap_V3; System.String LdapHost = args[0]; int LdapPort = System.Int32.Parse(args[1]); System.String loginDN = args[2]; System.String password = args[3]; System.String partitionDN = args[4]; int count = 0; LdapConnection ld = new LdapConnection(); try { // connect to the server ld.Connect(LdapHost, LdapPort); // bind to the server ld.Bind(LdapVersion, loginDN, password); System.Console.Out.WriteLine("\nLogin succeeded"); LdapExtendedOperation request = new PartitionEntryCountRequest(partitionDN); LdapExtendedResponse response = ld.ExtendedOperation(request); if ((response.ResultCode == LdapException.SUCCESS) && (response is PartitionEntryCountResponse)) { count = ((PartitionEntryCountResponse)response).Count; System.Console.Out.WriteLine("\n Entry count of partition " + partitionDN + " is: " + count); System.Console.Out.WriteLine("\nPartitionEntryCount succeeded\n"); } else { System.Console.Out.WriteLine("\nPartitionEntryCount Failed"); throw new LdapException(response.ErrorMessage, response.ResultCode, (System.String)null); } /* Done, so disconnect */ if (ld.Connected) { ld.Disconnect(); } } catch (LdapException e) { System.Console.Out.WriteLine("Error: " + e.LdapErrorMessage); } catch (Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
public static void Main(System.String[] args) { if (args.Length != 5) { System.Console.Error.WriteLine("Usage: mono ListReplicas <host Name> " + "<port number> <login dn> <password>" + "\n <server ND>"); System.Console.Error.WriteLine("Example: mono ListReplicas Acme.com 389 " + "\"cn=Admin,o=Acme\" secret" + "\n \"cn=myServer,o=Acme\""); System.Environment.Exit(1); } int ldapVersion = LdapConnection.Ldap_V3; System.String ldapHost = args[0]; int ldapPort = System.Int32.Parse(args[1]); System.String loginDN = args[2]; System.String password = args[3]; System.String serverDN = args[4]; LdapConnection ld = new LdapConnection(); try { // connect to the server ld.Connect(ldapHost, ldapPort); // bind to the server ld.Bind(ldapVersion, loginDN, password); System.Console.Out.WriteLine("\nLogin succeeded"); LdapExtendedOperation request = new ListReplicasRequest(serverDN); LdapExtendedResponse response = ld.ExtendedOperation(request); if ((response.ResultCode == LdapException.SUCCESS) && (response is ListReplicasResponse)) { System.Console.Out.WriteLine("Replica List: "); System.String[] rList = ((ListReplicasResponse) response).ReplicaList; int len = rList.Length; for (int i = 0; i < len; i++) System.Console.Out.WriteLine(rList[i]); System.Console.Out.WriteLine("\nList replica request succeeded\n"); } else { System.Console.Out.WriteLine("List Replicas request failed." + response.ResultCode); // throw new LdapException(response.ErrorMessage, response.ResultCode, (System.String) null); } /* Done, so disconnect */ if (ld.Connected) ld.Disconnect(); } catch (LdapException e) { System.Console.Out.WriteLine("\nError: " + e.ToString()); } }
/// <summary> Synchronously reads the entry specified by the Ldap URL, using the /// specified constraints. /// /// When this method is called, a new connection is created /// automatically, using the host and port specified in the URL. After /// finding the entry, the method closes the connection (in other words, /// it disconnects from the Ldap server). /// /// If the URL specifies a filter and scope, they are not used. Of the /// information specified in the URL, this method only uses the Ldap host /// name and port number, the base distinguished name (DN), and the list /// of attributes to return. /// /// </summary> /// <returns> The entry specified by the base DN. /// /// </returns> /// <param name="toGet"> Ldap URL specifying the entry to read. /// /// </param> /// <param name="cons"> Constraints specific to the operation. /// /// </param> /// <exception> LdapException if the object was not found /// </exception> public static LdapEntry Read(LdapUrl toGet, LdapSearchConstraints cons) { LdapConnection lconn = new LdapConnection(); lconn.Connect(toGet.Host, toGet.Port); LdapEntry toReturn = lconn.Read(toGet.getDN(), toGet.AttributeArray, cons); lconn.Disconnect(); return toReturn; }
protected void Execute(string ldapHost, string ldapPort, string loginDN, string password, string searchBase) { // Connect to the LDAP Server LdapConnection connection = new LdapConnection(); try { connection.Connect(ldapHost, int.Parse(ldapPort)); connection.Bind(loginDN, password); } catch(Exception e) { Console.WriteLine("Exception occurred: {0}", e.Message); try { connection.Disconnect(); } catch(Exception e2) { } Environment.Exit(1); } Console.WriteLine(STARTING_PROMPT); string[] noAttrs = { LdapConnection.NO_ATTRS }; // Make an object of PSearchEventSource PSearchEventSource objEventSource = new PSearchEventSource(connection, searchBase, LdapConnection.SCOPE_SUB, // scope "(objectClass=*)", // filter noAttrs, // attrs true, // typesOnly null, // constraints LdapEventType.LDAP_PSEARCH_ANY, // eventChangeType true// changeonly ); // register MySearchResultEventHandler as the handler for the Search // result events... objEventSource.SearchResultEvent += new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler); // Another listener could be added easily... objEventSource.SearchResultEvent += new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler02); // Add a listener for Referral Event objEventSource.SearchReferralEvent += new PSearchEventSource.SearchReferralEventHandler(MySearchReferralEventHandler); // Add a listener for generic directory event objEventSource.DirectoryEvent += new PSearchEventSource.DirectoryEventHandler(MyDirectoryEventHandler); // Add a listener for exception event objEventSource.DirectoryExceptionEvent += new PSearchEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler); string input; bool bContinue; do { Console.WriteLine(QUIT_PROMPT); input = Console.ReadLine(); bContinue = (input != null) && !(input.StartsWith("q")) && !(input.StartsWith("Q")); } while(bContinue); // time to unregister objEventSource.SearchResultEvent -= new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler); objEventSource.SearchResultEvent -= new PSearchEventSource.SearchResultEventHandler(MySearchResultEventHandler02); objEventSource.SearchReferralEvent -= new PSearchEventSource.SearchReferralEventHandler(MySearchReferralEventHandler); objEventSource.DirectoryEvent -= new LdapEventSource.DirectoryEventHandler(MyDirectoryEventHandler); objEventSource.DirectoryExceptionEvent -= new PSearchEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler); // Disconnect try { connection.Disconnect(); } catch(Exception e) { } }
public static void Main(String[] args) { if (args.Length != 3) { Console.WriteLine( "Usage: mono EdirEventSample <host name> <login dn>" + " <password> "); Console.WriteLine( "Example: mono EdirEventSample Acme.com \"cn=admin,o=Acme\"" + " secret "); Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int ldapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; LdapResponseQueue queue = null; LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect(ldapHost, ldapPort); // authenticate to the server lc.Bind(ldapVersion, loginDN, password); //Create an Array of EdirEventSpecifier EdirEventSpecifier[] specifier = new EdirEventSpecifier[1]; //Register for all Add Value events. specifier[0] = new EdirEventSpecifier(EdirEventType.EVT_CREATE_ENTRY, //Generate an Value Event of Type Add Value EdirEventResultType.EVT_STATUS_ALL //Generate Event for all status ); //Create an MonitorEventRequest using the specifiers. MonitorEventRequest requestoperation = new MonitorEventRequest(specifier); //Send the request to server and get the response queue. queue = lc.ExtendedOperation(requestoperation, null, null); } catch (LdapException e) { Console.WriteLine("Error: " + e.ToString()); try { lc.Disconnect(); } catch (LdapException e2) { Console.WriteLine("Error: " + e2.ToString()); } Environment.Exit(1); } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); } Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES ); Console.WriteLine(); //Set the timeout value timeOut= DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES); try { //Monitor till the timeout happens while (DateTime.Now.CompareTo(timeOut) < 0) { if (!checkForAChange(queue)) break; System.Threading.Thread.Sleep(10); } } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } catch (System.Threading.ThreadInterruptedException e) { Console.WriteLine(e.Message); } //disconnect from the server before exiting try { lc.Abandon(queue); //abandon the search lc.Disconnect(); } catch (LdapException e) { Console.WriteLine(); Console.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
public static void Main( String[] args ) { if (args.Length != 5) { Console.WriteLine("Usage: mono ClientSideSort <host name> "+ "<login dn> <password> <search base>\n" + " <search filter>"); Console.WriteLine("Example: mono ClientSideSort Acme.com" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\"\n" + " \"(objectclass=*)\""); Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int searchScope = LdapConnection.SCOPE_ONE; int ldapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String searchBase = args[3]; String searchFilter = args[4]; LdapConnection conn = new LdapConnection(); try { // connect to the server conn.Connect( ldapHost, ldapPort ); // bind to the server conn.Bind( ldapVersion, loginDN, password); LdapSearchResults searchResults = conn.Search( searchBase, searchScope, searchFilter, new String[] {"cn", "uid", "sn"}, //attributes false); // return attrs and values /* sortedResults will sort the entries according to the natural * ordering of LDAPEntry (by distiguished name). */ ArrayList sortedResults = new ArrayList(); while ( searchResults.hasMore()) { try { sortedResults.Add( searchResults.next() ); } catch(LdapException e) { Console.WriteLine("Error: " + e.ToString()); // Exception is thrown, go for next entry continue; } } // print the sorted results Console.WriteLine( "\n"+ "****************************\n"+ "Search results sorted by DN:\n"+ "****************************"); sortedResults.Sort(); IEnumerator i = sortedResults.GetEnumerator(0,sortedResults.Count-1); while (i.MoveNext()) { PrintEntry( (LdapEntry)(i.Current) ); } /* resort the results an an array using a specific comparator */ String[] namesToSortBy = { "sn", "uid", "cn" }; bool[] sortAscending = { true, false, true }; LdapCompareAttrNames myComparator = new LdapCompareAttrNames( namesToSortBy, sortAscending ); Object[] sortedSpecial = sortedResults.ToArray(); Array.Sort(sortedSpecial, myComparator); // print the re-sorted results Console.WriteLine( "\n" + "*****************************************************\n" + "Search results sorted by sn, uid(Descending), and cn:\n" + "*****************************************************"); for(int j=0; j< sortedSpecial.Length; j++) { PrintEntry( (LdapEntry) sortedSpecial[j] ); } // disconnect with the server conn.Disconnect(); } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); } catch( Exception e ) { Console.WriteLine( "Error: " + e.ToString() ); } Environment.Exit(0); }
static void Main(string[] args) { if ( args.Length != 5) { Console.WriteLine("Usage: mono SearchPersist <host name> <ldap port> <login dn>" + " <password> <search base>" ); Console.WriteLine("Example: mono SearchPersist Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\""); return; } int ldapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; int ldapPort = Convert.ToInt32(args[1]);; String loginDN = args[2]; String password = args[3]; String searchBase = args[4]; LdapSearchQueue queue = null; LdapSearchConstraints constraints; LdapPersistSearchControl psCtrl; LdapConnection lc = new LdapConnection(); constraints = new LdapSearchConstraints(); try { // connect to the server lc.Connect( ldapHost, ldapPort ); // authenticate to the server lc.Bind(ldapVersion, loginDN, password); //Create the persistent search control psCtrl = new LdapPersistSearchControl( LdapPersistSearchControl.ANY, // any change true, //only get changes true, //return entry change controls true); //control is critcal // add the persistent search control to the search constraints constraints.setControls( psCtrl ); // perform the search with no attributes returned String[] noAttrs = {LdapConnection.NO_ATTRS}; queue = lc.Search( searchBase, // container to search LdapConnection.SCOPE_SUB, // search container's subtree "(objectClass=*)", // search filter, all objects noAttrs, // don't return attributes false, // return attrs and values, ignored null, // use default search queue constraints); // use default search constraints } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); try { lc.Disconnect(); } catch(LdapException e2) { } Environment.Exit(1); } catch(Exception e) { Console.WriteLine( "Error: " + e.Message ); return; } Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES ); Console.WriteLine(); //Set the timeout value timeOut= DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES); try { //Monitor till the timeout happens while (DateTime.Now.CompareTo(timeOut) < 0) { if (!checkForAChange(queue)) break; System.Threading.Thread.Sleep(10); } } catch (System.IO.IOException e) { System.Console.Out.WriteLine(e.Message); } catch (System.Threading.ThreadInterruptedException e) { } //Disconnect from the server before exiting try { lc.Abandon(queue); //abandon the search lc.Disconnect(); } catch (LdapException e) { Console.Out.WriteLine(); Console.Out.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
public static void Main(System.String[] args) { if (args.Length != 5) { usage(); System.Environment.Exit(1); } int ldapPort = LdapConnection.DEFAULT_PORT; int ldapVersion = LdapConnection.Ldap_V3; bool status = false; LdapConnection conn = new LdapConnection(); System.String ldapHost = args[0]; System.String loginDN = args[1]; System.String password = args[2]; System.String userDN = args[3]; System.String groupDN = args[4]; try { // connect to the server conn.Connect(ldapHost, ldapPort); // bind to the server conn.Bind(ldapVersion, loginDN, password); // call _AddUseToGroup() to add the user to the group status = _AddUserToGroup(conn, userDN, groupDN); if (status) System.Console.Out.WriteLine("User: "******" was enrolled in group: " + groupDN); else System.Console.Out.WriteLine("User: "******" could not be enrolled in group: " + groupDN); // disconnect with the server conn.Disconnect(); } catch (LdapException e) { System.Console.Out.WriteLine("Error: " + e.LdapErrorMessage); } catch(Exception e) { Console.WriteLine("Error:" + e.Message); return; } System.Environment.Exit(0); }
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); }
static void Main( string[] args ) { if ( args.Length != 4 ) { Console.WriteLine("Usage: mono InteractiveSSL <host name> <ldap port> <login dn> <password>\n"); Console.WriteLine("Example: mono InteractiveSSL Acme.com 636" + " \"cn=admin,o=Acme\"" + " secret\n"); return; } LdapConnection conn=null; string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; bHowToProceed = true; String continueBind; try { do { bindCount++; conn= new LdapConnection(); conn.SecureSocketLayer=true; Console.WriteLine( "Connecting to:" + ldapHost ); conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(MySSLHandler); if(bHowToProceed == false) conn.Disconnect(); if(bHowToProceed == true) { conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); Console.WriteLine( " SSL Bind Successfull " ); conn.Disconnect(); } Console.WriteLine ( "\nDo you wish to Bind again to the server (y/n)?" ); continueBind = Console.ReadLine(); if(continueBind == "y" || continueBind == "Y") quit = false; if(continueBind == "n" || continueBind == "N") quit = true; }while(quit == false); } catch(LdapException ee) { Console.WriteLine(ee.LdapErrorMessage); } catch(Exception e) { Console.WriteLine(e.StackTrace); } conn.Disconnect(); }
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 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; } }
protected void Execute(string ldapHost, string ldapPort, string loginDN, string password) { // Connect to the LDAP Server LdapConnection connection = new LdapConnection(); try { connection.Connect(ldapHost, int.Parse(ldapPort)); connection.Bind(loginDN, password); } catch(Exception e) { Console.WriteLine("Exception occurred: {0}", e.Message); try { connection.Disconnect(); } catch(Exception e2) { } Environment.Exit(1); } Console.WriteLine(STARTING_PROMPT); EdirEventSpecifier[] specifier = new EdirEventSpecifier[1]; specifier[0] = new EdirEventSpecifier( EdirEventType.EVT_CREATE_ENTRY, EdirEventResultType.EVT_STATUS_ALL //, we could have optionally specified a filter here like "(attributeName=city)" ); // Make an object of EdirEventSource EdirEventSource objEventSource = new EdirEventSource(specifier, connection); // register for events objEventSource.EdirEvent += new EdirEventSource.EdirEventHandler(MyEdirEventHandler); // Another listener can be easily added objEventSource.EdirEvent += new EdirEventSource.EdirEventHandler(MyEdirEventHandler02); // Add a listener for generic directory event objEventSource.DirectoryEvent += new EdirEventSource.DirectoryEventHandler(MyDirectoryEventHandler); // Add a listener for exception event objEventSource.DirectoryExceptionEvent += new EdirEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler); string input; bool bContinue; do { Console.WriteLine(QUIT_PROMPT); input = Console.ReadLine(); bContinue = (input != null) && !(input.StartsWith("q")) && !( input.StartsWith("Q")); } while(bContinue); // time to unregister objEventSource.EdirEvent -= new EdirEventSource.EdirEventHandler(MyEdirEventHandler); objEventSource.EdirEvent -= new EdirEventSource.EdirEventHandler(MyEdirEventHandler02); objEventSource.DirectoryEvent -= new EdirEventSource.DirectoryEventHandler(MyDirectoryEventHandler); objEventSource.DirectoryExceptionEvent -= new EdirEventSource.DirectoryExceptionEventHandler(MyDirectoryExceptionEventHandler); // Disconnect try { connection.Disconnect(); } catch(Exception e) { } }
public ActionResult ChangeUserPass(string UserName, string PassWord, string RPassWord, string OldPassword) { string userName = UserName.ToString(); string newPassword = PassWord.ToString(); string OldPass = OldPassword.ToString(); string RPass = RPassWord.ToString(); TempData["msg"] = ""; if (newPassword == RPass) { // Creating an LdapConnection instance Novell.Directory.Ldap.LdapConnection ldapConn = new Novell.Directory.Ldap.LdapConnection(); string dn = "uid=" + userName + ",ou=users,dc=example,dc=com"; // Check if User Exists in LDAP if (CheckUser(userName, OldPass) == true) { try { //Connect function will create a socket connection to the server ldapConn.Connect(ldapHost, ldapPort); //Bind function will Bind the user object Credentials to the Server ldapConn.Bind(adminUname, adminPword); ArrayList modList = new ArrayList(); //Replace the existing email with the new email value LdapAttribute attributes = new LdapAttribute("userPassword", newPassword); modList.Add(new LdapModification(LdapModification.REPLACE, attributes)); LdapModification[] mods = new LdapModification[modList.Count]; Type mtype = Type.GetType("Novell.Directory.LdapModification"); mods = (LdapModification[])modList.ToArray(typeof(LdapModification)); //Modify the entry in the directory ldapConn.Modify(dn, mods); } catch (Novell.Directory.Ldap.LdapException e) { string error = "Error: " + e; TempData["msg"] = "<script>alert('" + error + "');</script>"; Thread.Sleep(2000); return(View("Index")); } finally { // Disconnect from LDAP ldapConn.Disconnect(); } TempData["msg"] = "<script>alert('Password Changed Successfully!');</script>"; Thread.Sleep(2000); return(View("Index")); } else { TempData["msg"] = "<script>alert('Could not authenticate user!');</script>"; Thread.Sleep(2000); return(View("Index")); } } else { TempData["msg"] = "<script>alert('New passwords do not match!');</script>"; Thread.Sleep(2000); return(View("Index")); } }
/// <summary> get an LdapConnection object so that we can follow a referral. /// This function is never called if cons.getReferralFollowing() returns /// false. /// /// </summary> /// <param name="referrals">the array of referral strings /// /// /// </param> /// <returns> The referralInfo object /// /// </returns> /// <exception> LdapReferralException A general exception which includes /// an error message and an Ldap error code. /// </exception> private ReferralInfo getReferralConnection(System.String[] referrals) { ReferralInfo refInfo = null; System.Exception ex = null; LdapConnection rconn = null; LdapReferralHandler rh = defSearchCons.getReferralHandler(); int i = 0; // Check if we use LdapRebind to get authentication credentials if ((rh == null) || (rh is LdapAuthHandler)) { for (i = 0; i < referrals.Length; i++) { // dn, pw are null in the default case (anonymous bind) System.String dn = null; sbyte[] pw = null; try { rconn = new LdapConnection(); rconn.Constraints = defSearchCons; LdapUrl url = new LdapUrl(referrals[i]); rconn.Connect(url.Host, url.Port); if (rh != null) { if (rh is LdapAuthHandler) { // Get application supplied dn and pw LdapAuthProvider ap = ((LdapAuthHandler) rh).getAuthProvider(url.Host, url.Port); dn = ap.DN; pw = ap.Password; } } rconn.Bind(Ldap_V3, dn, pw); ex = null; refInfo = new ReferralInfo(rconn, referrals, url); // Indicate this connection created to follow referral rconn.Connection.ActiveReferral = refInfo; break; } catch (System.Exception lex) { if (rconn != null) { try { rconn.Disconnect(); rconn = null; ex = lex; } catch (LdapException e) { ; // ignore } } } } } // Check if application gets connection and does bind else { // rh instanceof LdapBind try { rconn = ((LdapBindHandler) rh).Bind(referrals, this); if (rconn == null) { LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERRAL_ERROR); rex.setReferrals(referrals); throw rex; } // Figure out which Url belongs to the connection for (int idx = 0; idx < referrals.Length; idx++) { try { LdapUrl url = new LdapUrl(referrals[idx]); if (url.Host.ToUpper().Equals(rconn.Host.ToUpper()) && (url.Port == rconn.Port)) { refInfo = new ReferralInfo(rconn, referrals, url); break; } } catch (System.Exception e) { ; // ignore } } if (refInfo == null) { // Could not match LdapBind.bind() connecction with URL list ex = new LdapLocalException(ExceptionMessages.REFERRAL_BIND_MATCH, LdapException.CONNECT_ERROR); } } catch (System.Exception lex) { rconn = null; ex = lex; } } if (ex != null) { // Could not connect to any server, throw an exception LdapException ldapex; if (ex is LdapReferralException) { throw (LdapReferralException) ex; } else if (ex is LdapException) { ldapex = (LdapException) ex; } else { ldapex = new LdapLocalException(ExceptionMessages.SERVER_CONNECT_ERROR, new System.Object[]{conn.Host}, LdapException.CONNECT_ERROR, ex); } // Error attempting to follow a referral LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERRAL_ERROR, ldapex); rex.setReferrals(referrals); // Use last URL string for the failed referral rex.FailedReferral = referrals[referrals.Length - 1]; throw rex; } // We now have an authenticated connection // to be used to follow the referral. return refInfo; }
public static void Main( String[] args ) { // Verify correct number of parameters if (args.Length != 4) { Console.WriteLine("Usage: mono AsynchronousSortControl <host name> " + "<login dn> <password> <container>"); Console.WriteLine("Example: mono AsynchronousSortControl Acme.com" + " \"cn=admin,o=Acme\" secret \"ou=Sales,o=Acme\""); Environment.Exit(0); } // Read command line arguments String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String searchBase = args[3]; int MY_PORT = 389; int ldapVersion = LdapConnection.Ldap_V3; try { // Create a LdapConnection object LdapConnection lc = new LdapConnection(); // Connect to server lc.Connect( ldapHost, MY_PORT); lc.Bind(ldapVersion, loginDN, password ); Console.WriteLine( "Login succeeded"); // We will be searching for all objects String MY_FILTER = "(objectClass=*)"; // Results of the search should include givenname and cn String[] attrs = new String[2]; attrs[0] = "givenname"; attrs[1] = "cn"; // The results should be sorted using the cn attribute LdapSortKey[] keys = new LdapSortKey[1]; keys[0] = new LdapSortKey( "cn" ); // 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 = lc.SearchConstraints; cons.setControls( sort ); lc.Constraints = cons; // Perform the search - ASYNCHRONOUS SEARCH USED HERE Console.WriteLine( "Calling search request"); LdapSearchQueue queue = lc.Search( searchBase, LdapConnection.SCOPE_SUB, MY_FILTER, attrs, false, (LdapSearchQueue)null, (LdapSearchConstraints) null ); LdapMessage message; while (( message = queue.getResponse()) != null ) { // OPTION 1: the message is a search result reference if ( message is LdapSearchResultReference ) { // Not following referrals to keep things simple String[] urls = ((LdapSearchResultReference)message).Referrals; Console.WriteLine("Search result references:"); for ( int i = 0; i < urls.Length; i++ ) Console.WriteLine(urls[i]); } // OPTION 2:the message is a search result else if ( message is LdapSearchResult ) { // Get the object name LdapEntry entry = ((LdapSearchResult)message).Entry; Console.WriteLine("\n" + entry.DN); Console.WriteLine("\tAttributes: "); // Get the attributes and print them out LdapAttributeSet attributeSet = entry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); while(allAttributes.MoveNext()) { LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; Console.WriteLine("\t\t" + attributeName); // Print all values of the attribute IEnumerator allValues = attribute.StringValues; if( allValues != null) { while(allValues.MoveNext()) { String Value = (String) allValues.Current; Console.WriteLine("\t\t\t" + Value); } } } } // OPTION 3: The message is a search response else { LdapResponse response = (LdapResponse)message; int status = response.ResultCode; // the return code is Ldap success if ( status == LdapException.SUCCESS ) { Console.WriteLine("Asynchronous search succeeded."); } // the return code is referral exception else if ( status == LdapException.REFERRAL ) { String[] urls=((LdapResponse)message).Referrals; Console.WriteLine("Referrals:"); for ( int i = 0; i < urls.Length; i++ ) Console.WriteLine(urls[i]); } else { Console.WriteLine("Asynchronous search failed."); Console.WriteLine( response.ErrorMessage); } // Server should send back a control irrespective of the // status of the search request LdapControl[] controls = response.Controls; if ( controls != null ) { // Theoritically we could have multiple controls returned for( int i = 0; i < controls.Length; i++ ) { // We are looking for the LdapSortResponse Control class - the control // sent back in response to LdapSortControl if ( controls[i] is LdapSortResponse ) { Console.WriteLine("Received Ldap Sort Control fromserver"); // We must have an error code and maybe a string identifying // erring attribute in the response control. Get these. String bad = ((LdapSortResponse)controls[i]).FailedAttribute; int result = ((LdapSortResponse)controls[i]).ResultCode; // Print out error ccode (0 if no error) and any returned // attribute Console.WriteLine( "Error code: " + result ); if ( bad != null ) Console.WriteLine( "Offending " + "attribute: " + bad ); else Console.WriteLine( "No offending " + "attribute " + "returned" ); } } } } } // All done - disconnect if ( lc.Connected == true ) lc.Disconnect(); } catch( LdapException e ) { Console.WriteLine( e.ToString() ); } catch( Exception e ) { Console.WriteLine( "Error: " + e.ToString() ); } }
static void Main(string[] args) { if ( args.Length != 4) { Console.WriteLine("Usage: mono Bind <host name> <ldap port> <login dn>" + " <password> "); Console.WriteLine("Example: mono Bind Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret "); return; } string ldapHost = args[0]; int ldapPort = System.Convert.ToInt32(args[1]); String loginDN = args[2]; String password = args[3]; try { LdapConnection conn= new LdapConnection(); Console.WriteLine("Connecting to:" + ldapHost); conn.Connect(ldapHost,ldapPort); conn.Bind(loginDN,password); Console.WriteLine(" Bind Successfull"); conn.Disconnect(); } catch(LdapException e) { Console.WriteLine("Error:" + e.LdapErrorMessage); return; } catch(Exception e) { Console.WriteLine("Error:" + e.Message); return; } }
/* * Ldap URL search */ /// <summary> Synchronously perfoms the search specified by the Ldap URL, using /// the specified search constraints (such as the maximum number of /// entries to find or the maximum time to wait for search results). /// /// When this method is called, a new connection is created /// automatically, using the host and port specified in the URL. After /// all search results have been received from the server, the method /// closes the connection (in other words, it disconnects from the Ldap /// server). /// /// As part of the search constraints, a choice can be made as to whether /// to have the results delivered all at once or in smaller batches. If /// the results are to be delivered in smaller batches, each iteration /// blocks only until the next batch of results is returned. /// /// /// </summary> /// <param name="toGet"> Ldap URL specifying the entry to read. /// /// </param> /// <param name="cons"> The constraints specific to the search. /// /// </param> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> public static LdapSearchResults Search(LdapUrl toGet, LdapSearchConstraints cons) { LdapConnection lconn = new LdapConnection(); lconn.Connect(toGet.Host, toGet.Port); if (cons == null) { // This is a clone, so we already have our own copy cons = lconn.SearchConstraints; } else { // get our own copy of user's constraints because we modify it cons = (LdapSearchConstraints) cons.Clone(); } cons.BatchSize = 0; // Must wait until all results arrive LdapSearchResults toReturn = lconn.Search(toGet.getDN(), toGet.Scope, toGet.Filter, toGet.AttributeArray, false, cons); lconn.Disconnect(); return toReturn; }