shaozi / ldap-authentication

🔐🔐🔐 A simple Nodejs Async LDAP authentication library
BSD 2-Clause "Simplified" License
110 stars 28 forks source link

Bug when user cn has utf8 characters #61

Closed ansibleguy76 closed 5 months ago

ansibleguy76 commented 9 months ago

Add function :

function unescapeLdapResult(ldapResult) {
  // Regular expression to match the escaped sequences
  const regex = /\\([0-9a-fA-F]{2})\\([0-9a-fA-F]{2})/g;

  // Replace each escaped sequence with its Unicode character
  return ldapResult.replace(regex, (match, p1, p2) => {
      // Convert the hex codes to a Buffer
      const bytes = Buffer.from([parseInt(p1, 16), parseInt(p2, 16)]);
      // Convert the Buffer to a UTF-8 String
      return bytes.toString('utf8');
  });
}

and use it to unescape the result :

  ldapAdminClient.unbind()
  if (!user || !user.dn) {
    ldapOpts.log &&
      ldapOpts.log.trace(
        `admin did not find user! (${usernameAttribute}=${username})`
      )
    throw new LdapAuthenticationError(
      'user not found or usernameAttribute is wrong'
    )
  }
  var userDn = user.dn
  userDn = unescapeLdapResult(userDn)
  let ldapUserClient
  try {
    ldapUserClient = await _ldapBind(userDn, userPassword, starttls, ldapOpts)
  } catch (error) {
    throw error
  }
  ldapUserClient.unbind()
  if (groupsSearchBase && groupClass && groupMemberAttribute) {
    try {
      ldapAdminClient = await _ldapBind(
shaozi commented 5 months ago

I would like to understand more about this patch:

ansibleguy76 commented 5 months ago

i went into the code of ldap.js and noticed that they return encoded utf8 chars. which wasn't handled in your code. if you would patch your code, i can use npm again.

i will try to simulate a user later

shaozi commented 5 months ago

Can you be kindly to point me to where in the ldapjs code that it return encoded utf8?

shaozi commented 5 months ago

ok. I think I get what you mean. The return string from ldapjs will be backslash escaped hex if the result have utf encode runes. like this: 'cn=\\e7\\a0\\94\\e5\\8f\\91A\\e9\\83\\a8,ou=users,dc=example,dc=com' Your method may not be enough to decode it. We need a better way.

shaozi commented 5 months ago

fixed by merge #66

ansibleguy76 commented 5 months ago

Hi, I tested your 3.2.1 version from npm Did this fix make it ? Because I still have the same issue. If I fall back to my verions, it work.

ansibleguy76 commented 5 months ago

Seems not, I copied your code manually, and it works too.

shaozi commented 5 months ago

just published 3.2.2 which has the fix