node-activedirectory icon indicating copy to clipboard operation
node-activedirectory copied to clipboard

DC connection remains active on InvalidCredentialsError

Open yuredd opened this issue 10 years ago • 9 comments

Hi, I'm triyng to catch all the possible errors for my AD LDAP query. If I put an invalid or inaccessible url or basedn the library correctly calls my callback with a non-null err parameter. When I issue a bad username or password for binding, the library retries the bind another time than hangs because the connection with the DC remains active.

This is the code I'm using for my query:

var ActiveDirectory = require('activedirectory');
var ad = new ActiveDirectory({
        url: '...',
        baseDN: '...',
        username: '...',
        password: 'wrongpassword',
});
ad.find('(mobile=...)', function(err, user) {
       if(err) {
                console.log(JSON.stringify(err));

                return;
        }

        if(!user) {
                console.log('user not found');
                return;
        }

        console.log("User of ... found: " + user.users[0].displayName);

});

And this is the results (after this output node doesn't exit like it does on the other Ldap errors):

{"dn":"","code":49,"name":"InvalidCredentialsError","message":"80090308: LdapErr: DSID-0C0903CF, comment: AcceptSecurityContext error, data 52e, v2580\u0000"}
{"dn":"","code":49,"name":"InvalidCredentialsError","message":"80090308: LdapErr: DSID-0C0903CF, comment: AcceptSecurityContext error, data 52e, v2580\u0000"}

I've used wtfnode to show the hanging connection:

[WTF Node?] open handles:
- Sockets:
  - undefined:undefined -> undefined:undefined
    - Listeners:
  - undefined:undefined -> undefined:undefined
    - Listeners:
  - (MY IP):57795 -> (DC IP):389

Many thanks for your work.

yuredd avatar Feb 05 '16 18:02 yuredd

I've read the similar issue #108 that suggests to indicate a timeout in the config, I've tried but won't work. The version I'm using is 0.7.2.

yuredd avatar Feb 05 '16 18:02 yuredd

See if the following diff/patch fixes the problem:

--- a/lib/activedirectory.js
+++ b/lib/activedirectory.js
@@ -1811,6 +1811,7 @@ ActiveDirectory.prototype.authenticate = function authenticate(username, passwor

   var errorHandled = false;
   function handleError(err) {
+    client.unbind();
     if (! errorHandled) {
       errorHandled = true;
       if (hasEvents.call(self, 'error')) self.emit('error', err);

Also are you running this on Windows or a *NIX operating system?

gheeres avatar Feb 08 '16 14:02 gheeres

Thanks for the answer, I've tried your patch but the outcome doesn't change. I'm using node on raspbian. Here the details of my system:

Linux raspberrypi 4.1.13+ #826 PREEMPT Fri Nov 13 20:13:22 GMT 2015 armv6l GNU/Linux
Raspbian GNU/Linux 8
node v5.4.1

I'll update you if I found a workaround.

yuredd avatar Feb 09 '16 14:02 yuredd

Reading through the ldapjs source. Trying changing the .unbind call to .destroy.

--- a/lib/activedirectory.js
+++ b/lib/activedirectory.js
@@ -1811,6 +1811,7 @@ ActiveDirectory.prototype.authenticate = function authenticate(username, passwor

   var errorHandled = false;
   function handleError(err) {
+    client.destroy();
     if (! errorHandled) {
       errorHandled = true;
       if (hasEvents.call(self, 'error')) self.emit('error', err);

If that doesn't work, try putting client.unbind() before the client.destroy() to ensure that the ldapjs socket handling code is called.

--- a/lib/activedirectory.js
+++ b/lib/activedirectory.js
@@ -1811,6 +1811,7 @@ ActiveDirectory.prototype.authenticate = function authenticate(username, passwor

   var errorHandled = false;
   function handleError(err) {
+    client.unbind();
+    client.destroy();
     if (! errorHandled) {
       errorHandled = true;
       if (hasEvents.call(self, 'error')) self.emit('error', err);

It's also possible that we'll need wrap the existing code into the unbind callback due to asynchronous execution. The comments indicate it's not necessary though...

Here is the relevant ldapjs functions for destroy() and unbind():

/**
 * Disconnect from the LDAP server and do not allow reconnection.
 *
 * If the client is instantiated with proper reconnection options, it's
 * possible to initiate new requests after a call to unbind since the client
 * will attempt to reconnect in order to fulfill the request.
 *
 * Calling destroy will prevent any further reconnection from occurring.
 *
 * @param {Object} err (Optional) error that was cause of client destruction
 */
Client.prototype.destroy = function destroy(err) {
  this.destroyed = true;
  this.queue.freeze();
  // Purge any queued requests which are now meaningless
  this.queue.flush(function (msg, expect, emitter, cb) {
    if (typeof (cb) === 'function') {
      cb(new Error('client destroyed'));
      }
  });
  if (this.connected) {
    this.unbind();
  } else if (this._socket) {
    this._socket.destroy();
  }
  this.emit('destroy', err);
};

/**
 * Unbinds this client from the LDAP server.
 *
 * Note that unbind does not have a response, so this callback is actually
 * optional; either way, the client is disconnected.
 *
 * @param {Function} callback of the form f(err).
 * @throws {TypeError} if you pass in callback as not a function.
 */
Client.prototype.unbind = function unbind(callback) {
  if (!callback)
    callback = function () {};

  if (typeof (callback) !== 'function')
    throw new TypeError('callback must be a function');

  // When the socket closes, it is useful to know whether it was due to a
  // user-initiated unbind or something else.
  this.unbound = true;

  if (!this._socket)
    return callback();

  var req = new UnbindRequest();
  return this._send(req, 'unbind', null, callback);
};

gheeres avatar Feb 09 '16 14:02 gheeres

I've tried with the destroy or unbind method but with no results. Currently I'm trying to do an authenticate before requesting queries at the DC and it has the same problem but it correctly displays a single ldap error before the hang.

ad.authenticate(user, wrongpassword, function(err, auth) {
        if(err) {
                console.log('AD node error: ' + err);
                return;
        }
        if(!auth) {
                console.log('authentication failed.');
                return;
        }
});

output:

AD node error: InvalidCredentialsError: 80090308: LdapErr: DSID-0C0903CF, comment: AcceptSecurityContext error, data 52e, v2580

The connection remains, with or without destroy or unbind in the errorHandler function. I'm reading ldapjs for searching where it raises the error.

yuredd avatar Feb 09 '16 16:02 yuredd

It's not just when a failure to authenticate happens. Even on a successful authentication node doesn't exit. If I create the ActiveDirectory object and don't call authenticate the app will run and close, but when I call authenticate, the authentication comes back, and then the app hangs. pass or fail, it still doesn't exit. This indicates to me that something is being left open somewhere in ActiveDirectory Object

var ActiveDirectory = require('activedirectory');

var config = { url: 'ldaps://example.net',
               baseDN: 'dc=example,dc=com',
               tlsOptions:  {
                 'rejectUnauthorized': false
               }
};
var ad = new ActiveDirectory(config);

// try to authenticate:
ad.authenticate("[email protected]", "clearTextPassword", (err, auth) => {
    if (err) { console.log("ERROR: "+JSON.stringify(err)); }
    if (auth)   { console.log("Authenticated!"); } else { console.log("Authentication Failed.") }
});

AllenKll avatar May 05 '16 15:05 AllenKll

I was experiencing the same problem (socket not released on bad credentials) using findUser instead of authenticate. I was able to get it to release the socket by adding client.destroy to the onClientError method:

function onClientError(err, res) {
  if ((err || {}).name === 'SizeLimitExceededError') {
    onSearchEnd(res);
    return;
  }
  if ((err || {}).lde_message) {
    client.destroy(err);
  } else {
    client.unbind();
  }
  log.error(err, '[%s] An error occurred performing the requested LDAP search on %s (%j)',
          (err || {}).errno || 'UNKNOWN', baseDN, opts);
  if (callback) callback(err);
}

Also, I found that this article explains that the lde_message starting with '80090308: LdapErr: DSID-0C' error has a variety of details: https://www-01.ibm.com/support/docview.wss?uid=swg21290631

pbatey avatar Nov 22 '16 16:11 pbatey

I've filed a pull-request against ldapjs to address this issue: https://github.com/mcavage/node-ldapjs/pull/405

pbatey avatar Nov 22 '16 18:11 pbatey

Guys, I have the same issue, so merge it please asap.

denis-peshkov avatar Feb 27 '18 07:02 denis-peshkov