-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.js
471 lines (456 loc) · 12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
const assert = require('assert')
const ldap = require('ldapjs')
// convert an escaped utf8 string returned from ldapjs
function _isHex(c) {
return (
(c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
)
}
function _parseEscapedHexToUtf8(s) {
// convert 'cn=\\e7\\a0\\94\\e5\\8f\\91A\\e9\\83\\a8,ou=users,dc=example,dc=com'
// to 'cn=研发A部,ou=users,dc=example,dc=com'
let ret = Buffer.alloc(0)
let len = s.length
for (let i = 0; i < len; i++) {
let c = s[i]
let item
if (c == '\\' && i < len - 2 && _isHex(s[i + 1]) && _isHex(s[i + 2])) {
item = Buffer.from(s.substring(i + 1, i + 3), 'hex')
i += 2
} else {
item = Buffer.from(c)
}
ret = Buffer.concat([ret, item])
}
return ret.toString()
}
function _recursiveParseHexString(obj) {
if (Array.isArray(obj)) {
return obj.map((ele) => _recursiveParseHexString(ele))
}
if (typeof obj == 'string') {
return _parseEscapedHexToUtf8(obj)
}
if (typeof obj == 'object') {
for (let key in obj) {
obj[key] = _recursiveParseHexString(obj[key])
}
return obj
}
return obj
}
// convert a SearchResultEntry object in ldapjs 3.0
// to a user object to maintain backward compatibility
function _searchResultToUser(pojo) {
assert(pojo.type == 'SearchResultEntry')
let user = { dn: pojo.objectName }
pojo.attributes.forEach((attribute) => {
user[attribute.type] =
attribute.values.length == 1 ? attribute.values[0] : attribute.values
})
return _recursiveParseHexString(user)
}
// bind and return the ldap client
function _ldapBind(dn, password, starttls, ldapOpts) {
return new Promise(function (resolve, reject) {
ldapOpts.connectTimeout = ldapOpts.connectTimeout || 5000
let client = ldap.createClient(ldapOpts)
client.on('connect', function () {
if (starttls) {
client.starttls(ldapOpts.tlsOptions, null, function (error) {
if (error) {
reject(error)
return
}
client.bind(dn, password, function (err) {
if (err) {
reject(err)
return
}
ldapOpts.log && ldapOpts.log.trace('bind success!')
resolve(client)
})
})
} else {
client.bind(dn, password, function (err) {
if (err) {
reject(err)
return
}
ldapOpts.log && ldapOpts.log.trace('bind success!')
resolve(client)
})
}
})
//Fix for issue https://github.com/shaozi/ldap-authentication/issues/13
client.on('timeout', (err) => {
reject(err)
})
client.on('connectTimeout', (err) => {
reject(err)
})
client.on('error', (err) => {
reject(err)
})
client.on('connectError', function (error) {
if (error) {
reject(error)
return
}
})
})
}
// search a user and return the object
async function _searchUser(
ldapClient,
searchBase,
usernameAttribute,
username,
attributes = null
) {
return new Promise(function (resolve, reject) {
let filter = new ldap.filters.EqualityFilter({
attribute: usernameAttribute,
value: username,
})
let searchOptions = {
filter: filter,
scope: 'sub',
attributes: attributes,
}
if (attributes) {
searchOptions.attributes = attributes
}
ldapClient.search(searchBase, searchOptions, function (err, res) {
let user = null
if (err) {
reject(err)
return
}
res.on('searchEntry', function (entry) {
user = _searchResultToUser(entry.pojo)
})
res.on('searchReference', function (referral) {
// TODO: we don't support reference yet
// If the server was able to locate the entry referred to by the baseObject
// but could not search one or more non-local entries,
// the server may return one or more SearchResultReference messages,
// each containing a reference to another set of servers for continuing the operation.
// referral.uris
})
res.on('error', function (err) {
reject(err)
})
res.on('end', function (result) {
if (result.status != 0) {
reject(new Error('ldap search status is not 0, search failed'))
} else {
resolve(user)
}
})
})
})
}
// search a groups which user is member
async function _searchUserGroups(
ldapClient,
searchBase,
user,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn'
) {
return new Promise(function (resolve, reject) {
ldapClient.search(
searchBase,
{
filter: `(&(objectclass=${groupClass})(${groupMemberAttribute}=${user[groupMemberUserAttribute]}))`,
scope: 'sub',
},
function (err, res) {
let groups = []
if (err) {
reject(err)
return
}
res.on('searchEntry', function (entry) {
groups.push(_recursiveParseHexString(entry.pojo))
})
res.on('searchReference', function (referral) {})
res.on('error', function (err) {
reject(err)
})
res.on('end', function (result) {
if (result.status != 0) {
reject(new Error('ldap search status is not 0, search failed'))
} else {
resolve(groups)
}
})
}
)
})
}
async function authenticateWithAdmin(
adminDn,
adminPassword,
userSearchBase,
usernameAttribute,
username,
userPassword,
starttls,
ldapOpts,
groupsSearchBase,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn',
attributes = null
) {
let ldapAdminClient
try {
ldapAdminClient = await _ldapBind(
adminDn,
adminPassword,
starttls,
ldapOpts
)
} catch (error) {
throw { admin: error }
}
let user = await _searchUser(
ldapAdminClient,
userSearchBase,
usernameAttribute,
username,
attributes
)
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'
)
}
let userDn = user.dn
let ldapUserClient
try {
ldapUserClient = await _ldapBind(userDn, userPassword, starttls, ldapOpts)
} catch (error) {
throw error
}
if (groupsSearchBase && groupClass && groupMemberAttribute) {
let groups = await _searchUserGroups(
ldapAdminClient,
groupsSearchBase,
user,
groupClass,
groupMemberAttribute,
groupMemberUserAttribute
)
user.groups = groups
}
return user
}
async function authenticateWithUser(
userDn,
userSearchBase,
usernameAttribute,
username,
userPassword,
starttls,
ldapOpts,
groupsSearchBase,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn',
attributes = null
) {
let ldapUserClient
try {
ldapUserClient = await _ldapBind(userDn, userPassword, starttls, ldapOpts)
} catch (error) {
throw error
}
if (!usernameAttribute || !userSearchBase) {
// if usernameAttribute is not provided, no user detail is needed.
return true
}
let user = await _searchUser(
ldapUserClient,
userSearchBase,
usernameAttribute,
username,
attributes
)
if (!user || !user.dn) {
ldapOpts.log &&
ldapOpts.log.trace(
`user logged in, but user details could not be found. (${usernameAttribute}=${username}). Probabaly wrong attribute or searchBase?`
)
throw new LdapAuthenticationError(
'user logged in, but user details could not be found. Probabaly usernameAttribute or userSearchBase is wrong?'
)
}
if (groupsSearchBase && groupClass && groupMemberAttribute) {
let groups = await _searchUserGroups(
ldapUserClient,
groupsSearchBase,
user,
groupClass,
groupMemberAttribute,
groupMemberUserAttribute
)
user.groups = groups
}
return user
}
async function verifyUserExists(
adminDn,
adminPassword,
userSearchBase,
usernameAttribute,
username,
starttls,
ldapOpts,
groupsSearchBase,
groupClass,
groupMemberAttribute = 'member',
groupMemberUserAttribute = 'dn',
attributes = null
) {
let ldapAdminClient
try {
ldapAdminClient = await _ldapBind(
adminDn,
adminPassword,
starttls,
ldapOpts
)
} catch (error) {
throw { admin: error }
}
let user = await _searchUser(
ldapAdminClient,
userSearchBase,
usernameAttribute,
username,
attributes
)
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'
)
}
if (groupsSearchBase && groupClass && groupMemberAttribute) {
let groups = await _searchUserGroups(
ldapAdminClient,
groupsSearchBase,
user,
groupClass,
groupMemberAttribute,
groupMemberUserAttribute
)
user.groups = groups
}
return user
}
async function authenticate(options) {
if (!options.userDn) {
assert(options.adminDn, 'Admin mode adminDn must be provided')
assert(options.adminPassword, 'Admin mode adminPassword must be provided')
assert(options.userSearchBase, 'Admin mode userSearchBase must be provided')
assert(
options.usernameAttribute,
'Admin mode usernameAttribute must be provided'
)
assert(options.username, 'Admin mode username must be provided')
} else {
assert(options.userDn, 'User mode userDn must be provided')
}
assert(
options.ldapOpts && options.ldapOpts.url,
'ldapOpts.url must be provided'
)
if (options.verifyUserExists) {
assert(options.adminDn, 'Admin mode adminDn must be provided')
assert(
options.adminPassword,
'adminDn and adminPassword must be both provided.'
)
return await verifyUserExists(
options.adminDn,
options.adminPassword,
options.userSearchBase,
options.usernameAttribute,
options.username,
options.starttls,
options.ldapOpts,
options.groupsSearchBase,
options.groupClass,
options.groupMemberAttribute,
options.groupMemberUserAttribute,
options.attributes
)
}
assert(options.userPassword, 'userPassword must be provided')
if (options.adminDn) {
assert(
options.adminPassword,
'adminDn and adminPassword must be both provided.'
)
return await authenticateWithAdmin(
options.adminDn,
options.adminPassword,
options.userSearchBase,
options.usernameAttribute,
options.username,
options.userPassword,
options.starttls,
options.ldapOpts,
options.groupsSearchBase,
options.groupClass,
options.groupMemberAttribute,
options.groupMemberUserAttribute,
options.attributes
)
}
assert(options.userDn, 'adminDn/adminPassword OR userDn must be provided')
return await authenticateWithUser(
options.userDn,
options.userSearchBase,
options.usernameAttribute,
options.username,
options.userPassword,
options.starttls,
options.ldapOpts,
options.groupsSearchBase,
options.groupClass,
options.groupMemberAttribute,
options.groupMemberUserAttribute,
options.attributes
)
}
class LdapAuthenticationError extends Error {
constructor(message) {
super(message)
// Ensure the name of this error is the same as the class name
this.name = this.constructor.name
// This clips the constructor invocation from the stack trace.
// It's not absolutely essential, but it does make the stack trace a little nicer.
// @see Node.js reference (bottom)
Error.captureStackTrace(this, this.constructor)
}
}
module.exports.authenticate = authenticate
module.exports.LdapAuthenticationError = LdapAuthenticationError
module.exports.exportForTesting = {
_isHex,
_parseEscapedHexToUtf8,
_recursiveParseHexString,
}