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); }
//--- Methods --- private LdapConnection GetLdapConnectionFromBindingDN(string server, string bindingdn, string password) { LdapConnection conn = null; try { conn = new LdapConnection(); conn.SecureSocketLayer = _config.SSL; int port = _config.SSL ? LDAPS_PORT : LDAP_PORT; conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidateCert); string[] temp = server.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); server = temp[0]; if(temp.Length > 1) { int.TryParse(temp[1], out port); } //if server has a port number specified, it's used instead. conn.Connect(server, port); if (!string.IsNullOrEmpty(bindingdn)) { conn.Bind(bindingdn, password); } } catch (Exception x) { UnBind(conn); _log.WarnExceptionMethodCall(x, "GetLdapConnection", string.Format("Failed to bind to LDAP server: '{0}' with bindingdn: '{1}'. Password provided? {2}. Exception: {3}", server, bindingdn, string.IsNullOrEmpty(password), x)); throw; } return conn; }
protected virtual void Dispose (bool disposing) { if (conn != null) { conn.Disconnect (); conn = null; } }
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> Construct the ReferralInfo class /// /// </summary> /// <param name="lc">The DirectoryEntry opened to process this referral /// /// </param> /// <param name="refUrl">The URL string associated with this connection /// </param> public ReferralInfo(LdapConnection lc, System.String[] refList, LdapUrl refUrl) { conn = lc; referralUrl = refUrl; referralList = refList; return ; }
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(); }
/// <summary> /// Initialises a new instance of the <see cref="LdapConnectorNovell"/> class. /// </summary> /// <param name="hostname"> /// The hostname. /// </param> /// <param name="networkCredential"> /// The network credential. /// </param> /// <param name="dnsRootDn"> /// The DNS root DN. /// </param> public LdapConnectorNovell(string hostname, int port, NetworkCredential networkCredential, string dnsRootDn) { this.ldapConnection = new LdapConnection(); this.ldapConnection.Connect(hostname, port); this.ldapConnection.Bind(networkCredential.UserName, networkCredential.Password); this.dnsRootDn = dnsRootDn; }
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; } }
private void InitBlock() { _conn = new LdapConnection(); LdapUrl lUrl=new LdapUrl(SearchRoot.Path); _Host=lUrl.Host; _Port=lUrl.Port; _conn.Connect(_Host,_Port); _conn.Bind(SearchRoot.Username,SearchRoot.Password); }
private void InitBlock() { _conn = new LdapConnection(); LdapUrl lUrl=new LdapUrl(SearchRoot.ADsPath); _Host=lUrl.Host; _Port=lUrl.Port; _conn.Connect(_Host,_Port); _conn.Bind(SearchRoot.Username,SearchRoot.Password,(Novell.Directory.Ldap.AuthenticationTypes)SearchRoot.AuthenticationType); }
public UserViewModel Login(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); //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); var uservm = new UserViewModel() { UserName = username, Name = username }; 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; nextEntry = lsc.Next(); 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; uservm.CustomClaims.Add(new Claim(attributeName, attributeVal)); } } return(uservm); }
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 != 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; } }
public void Initialize(NameValueCollection properties) { this.properties = properties; if(!Utility.KeyExists(properties, "server")) throw(new Exception("Server property not specified.")); if(!Utility.KeyExists(properties, "base")) throw(new Exception("Base property not specified.")); connection = new LdapConnection(); connection.Connect(properties["server"], Utility.KeyExists(properties, "port") ? int.Parse(properties["port"]) : LdapConnection.DEFAULT_PORT); }
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; } }
/// <summary> Initializes the Connection and other properties. /// /// </summary> private void InitBlock() { try { LdapUrl lUrl=new LdapUrl(_Bpath); _Conn = new LdapConnection(); _Conn.Connect(lUrl.Host,lUrl.Port); _Conn.Bind(_Buser,_Bpass); } catch(LdapException ex) { throw ex; } catch(Exception e) { throw e; } }
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); } }
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; } }
public UnixIdentity(string domain, string userName, LdapConnection connection = null) : base(GetUserIDAsToken(domain, userName), null, WindowsAccountType.Normal, true) { m_domain = domain; m_userName = userName; Connection = connection; if (UserInfo.IsLocalDomain(domain)) { // Cache shadow information for local user before possible reduction in privileges if (GetLocalUserPasswordInformation(userName, out m_userPasswordInformation, out m_accountStatus) == 0) m_loadedUserPasswordInformation = true; else m_accountStatus = AccountStatus.Disabled; } }
public Task LoginAsync (string username, string password, CancellationToken cancellationToken) { ValidateConfiguration (); return Task.Factory.StartNew (() => { // // Search // conn = new LdapConnection (); conn.Connect (Host, Port); if (!string.IsNullOrEmpty (username)) conn.Bind (username, password); }, cancellationToken); }
public User Login(string userName, string password) { User user = new User(); using (var cn = new Novell.Directory.Ldap.LdapConnection()) { cn.Connect(config.Path, config.Port); try { cn.Bind(config.UserDomainName + "\\" + userName, password); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Failed login attempt for user " + userName); user = null; return(user); } string filter = "sAMAccountname=" + userName; string baseStr = "OU=BLS,DC=blacklanternsecurity,DC=com"; LdapSearchResults result = (LdapSearchResults)cn.Search(baseStr, LdapConnection.ScopeSub, filter, null, false); LdapEntry entry = null; try { entry = result.First(); } catch (LdapException e) { Console.WriteLine("Error: " + e.LdapErrorMessage); } LdapAttributeSet attributeSet = entry.GetAttributeSet(); user.DisplayName = attributeSet.GetAttribute("displayName").StringValue; user.GivenName = attributeSet.GetAttribute("givenName").StringValue; user.UserName = userName; return(user); } }
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; } }
//--- Methods --- private LdapConnection GetLdapConnectionFromBindingDN(string server, string bindingdn, string password) { LdapConnection conn = null; try { conn = new LdapConnection(); conn.SecureSocketLayer = _config.SSL; int port = _config.SSL ? LDAPS_PORT : LDAP_PORT; conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidateCert); //if server has a port number specified, it's used instead. conn.Connect(server, port); if (!string.IsNullOrEmpty(bindingdn)) { conn.Bind(bindingdn, password); } } catch (Exception x) { UnBind(conn); LogUtils.LogWarning(_log, x, "GetLdapConnection", string.Format("Failed to bind to LDAP server: '{0}' with bindingdn: '{1}'. Password provided? {2}. Exception: {3}", server, bindingdn, string.IsNullOrEmpty(password).ToString(), x.ToString())); throw; } return conn; }
/// <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 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())); }
/// <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; }
/// <summary> /// Searches the directory store at the specified path to see whether /// an entry exists /// </summary> /// <param name="path"> /// The path at which to search the directory store. /// </param> /// <returns> /// true if an entry exists in the directory store at the specified /// path; otherwise, false. /// </returns> public static bool Exists(string path) { LdapConnection aconn=new LdapConnection(); LdapUrl lurl=new LdapUrl(path); aconn.Connect(lurl.Host,lurl.Port); aconn.Bind("",""); if(CheckEntry(aconn,path)) return true; else return false; }
/// <summary> /// Checks whether the entry exists in the Ldap directory or not /// </summary> /// <param name="lconn"> /// Connection used to communicate with directory /// </param> /// <param name="epath"> /// path of the entry /// </param> /// <returns> /// true of the entry exists in the Ldap directory /// false if entry doesn't exists /// </returns> private static bool CheckEntry(LdapConnection lconn, string epath) { LdapUrl lUrl=new LdapUrl(epath); string eDn=lUrl.getDN(); if(eDn==null) { eDn = String.Empty; } // rootDSE is a "virtual" entry that always exists else if (String.Compare (eDn,"rootDSE",true) == 0) return true; string[] attrs={"objectClass"}; try { LdapSearchResults lsc=lconn.Search( eDn, LdapConnection.SCOPE_BASE, "objectClass=*", attrs, false); while(lsc.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = lsc.next(); } catch(LdapException e) { // Exception is thrown, go for next entry throw e; } break; } } catch(LdapException le) { if(le.ResultCode == LdapException.NO_SUCH_OBJECT) { return false; } else { throw le; } } catch(Exception e) { throw e; } return true; }
// // Summary: // The System.DirectoryServices.Protocols.LdapConnection.#ctor(System.String) constructor // creates an instance of the System.DirectoryServices.Protocols.LdapConnection // class using the specified server. // // Parameters: // server: // A string specifying the server which can be a domain name, LDAP server name or // dotted strings representing the IP address of the LDAP server. Optionally, this // parameter may also include a port number, separated from the right end of the // string by a colon (:). // // Exceptions: // T:System.DirectoryServices.Protocols.LdapException: // Thrown if it fails to create a connection block or fails to open a connection // to server. public LdapConnection(string server) { //TODO: ALACHISOFT _ldapConnection = new Novell.Directory.Ldap.LdapConnection(); }
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 async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { try { if (String.IsNullOrEmpty(context.UserName) || String.IsNullOrEmpty(context.Password)) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "As credenciais do usuário são obrigatórias", null); return; } string cpfMok = null; switch (context.UserName) { case "sisgp_gestor": cpfMok = "08056275029"; break; case "sisgp_cg": cpfMok = "95387502500"; break; case "sisgp_coget": cpfMok = "43321040565"; break; case "sisgp_coordenador": cpfMok = "25715446597"; break; case "sisgp_diretor": cpfMok = "39178470510"; break; case "sisgp_servidor": cpfMok = "08152972541"; break; case "sisgp_servidor1": cpfMok = "59516301002"; break; case "sisgp_servidor2": cpfMok = "18761704091"; break; case "sisgp_servidor3": cpfMok = "07721701007"; break; case "sisgp_servidor4": cpfMok = "51884275087"; break; } Pessoa pessoa = null; if (!string.IsNullOrEmpty(cpfMok)) { //if (context.Password.ToUpper() == "S20211014") //{ pessoa = await this.PessoaRepository.ObterPorCriteriosAsync(null, cpfMok); //} } else { if (this.Options.Value.Configurations == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "As configurações do LDAP são inválidas", null); } else { pessoa = await Task.Run(() => { foreach (var configuration in this.Options.Value.Configurations) { using (var connection = new Novell.Directory.Ldap.LdapConnection()) { try { connection.Connect(configuration.Url, configuration.Port); connection.Bind(configuration.BindDN, configuration.BindPassword); } catch { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Não foi possível pesquisar no LDAP. A autenticação do usuário de serviço falhou", null); return(null); } List <string> attibutes = new List <string>(); if (!String.IsNullOrEmpty(configuration.SisrhIdAttributeFilter)) { attibutes.Add(configuration.SisrhIdAttributeFilter); } if (!String.IsNullOrEmpty(configuration.EmailAttributeFilter)) { attibutes.Add(configuration.EmailAttributeFilter); } if (!String.IsNullOrEmpty(configuration.CpfAttributeFilter)) { attibutes.Add(configuration.CpfAttributeFilter); } var searchFilter = String.Format(configuration.SearchFilter, context.UserName); var entities = connection.Search( configuration.SearchBaseDC, Novell.Directory.Ldap.LdapConnection.ScopeSub, searchFilter, attibutes.ToArray(), false); while (entities.HasMore()) { var entity = entities.Next(); var entityAttributes = entity.GetAttributeSet(); //Valida o password connection.Bind(entity.Dn, context.Password); var sisrhId = GetAttributeValue(entity, configuration.SisrhIdAttributeFilter); if (!String.IsNullOrEmpty(sisrhId)) { var _pessoa = this.PessoaRepository.ObterAsync(Int64.Parse(sisrhId)); if (_pessoa != null) { return(_pessoa); } } string email = GetAttributeValue(entity, configuration.EmailAttributeFilter); string cpf = GetAttributeValue(entity, configuration.CpfAttributeFilter); var dadosPessoa = this.PessoaRepository.ObterPorCriteriosAsync(email, cpf); if (dadosPessoa != null) { return(dadosPessoa); } } } } return(null); }); } } if (pessoa != null) { context.Result = new GrantValidationResult(pessoa.PessoaId.ToString(), "password", null, "local", null); } else { if (context.Result == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "Não foi encontrado usuário com esse login", null); } } } catch (Novell.Directory.Ldap.LdapException ex) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, ex.Message, null); context.Result.Error = ex.StackTrace.ToString(); } }
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 System.Collections.ArrayList referralConn = null; // Referral Connections /// <summary> Constructs a queue object for search results. /// /// </summary> /// <param name="conn">The LdapConnection which initiated the search /// /// </param> /// <param name="queue">The queue for the search results. /// /// </param> /// <param name="cons">The LdapSearchConstraints associated with this search /// </param> /* package */ internal LdapSearchResults(LdapConnection conn, LdapSearchQueue queue, LdapSearchConstraints cons) { // setup entry Vector this.conn = conn; this.cons = cons; int batchSize = cons.BatchSize; int vectorIncr = (batchSize == 0)?64:0; entries = new System.Collections.ArrayList((batchSize == 0)?64:batchSize); entryCount = 0; entryIndex = 0; // setup search reference Vector references = new System.Collections.ArrayList(5); referenceCount = 0; referenceIndex = 0; this.queue = queue; this.batchSize = (batchSize == 0)?System.Int32.MaxValue:batchSize; return ; }
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")); } }
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; }