forked from milux/ctldap
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ctldap.js
666 lines (618 loc) · 21.2 KB
/
ctldap.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
// ChurchTools LDAP-Wrapper 2.1
// This tool requires a node.js-Server and ChurchTools >= 3.25.0
// (c) 2017 Michael Lux
// (c) 2019 André Schild
// License: GNU/GPL v3.0
var ldap = require('ldapjs');
var fs = require('fs');
var ini = require('ini');
var rp = require('request-promise');
var ldapEsc = require('ldap-escape');
var parseDN = require('ldapjs').parseDN;
var extend = require('extend');
var Promise = require("bluebird");
var path = require('path');
var bcrypt = require('bcrypt');
var userAgent = 'CTLDAP-MS';
var helpers = require('ldap-filter/lib/helpers');
var config = ini.parse(fs.readFileSync(path.resolve(__dirname, 'ctldap.config'), 'utf-8'));
var rateLimitStore = {};
function logDebug(site, msg) {
if (config.debug) {
console.log("[DEBUG] " + site.sitename+" - "+msg);
}
}
function logWarn(site, msg) {
console.log("[WARN] "+site.sitename+" - "+msg);
}
function logInfo(site, msg) {
console.log("[INFO] "+site.sitename+" - "+msg);
}
function logError(site, msg, error) {
console.log("[ERROR] "+site.sitename+" - "+msg);
if (error) {
console.log(error);
}
}
if (config.debug) {
console.log("Debug mode enabled, expect lots of output!");
}
if (config.ldap_base_dn) {
if (!config.sites) {
config.sites = {};
}
config.sites[config.ldap_base_dn] = {
sitename: config.ldap_base_dn,
ldap_password: config.ldap_password,
ct_uri: config.ct_uri,
api_user: config.api_user,
api_password: config.api_password
}
}
Object.keys(config.sites).map(function(sitename, index) {
var site = config.sites[sitename];
site.sitename = sitename;
site.fnUserDn = ldapEsc.dn("cn=${cn},ou=users,o=" + sitename);
site.fnGroupDn = ldapEsc.dn("cn=${cn},ou=groups,o=" + sitename);
site.cookieJar = rp.jar();
site.loginPromise = null;
site.adminDn = site.fnUserDn({cn: config.ldap_user});
site.CACHE = {};
site.loginErrorCount = 0;
site.loginBlockedDate = null;
if (site.dn_lower_case || ((site.dn_lower_case === undefined) && config.dn_lower_case)) {
site.compatTransform = function (s) {
return s.toLowerCase();
};
} else {
site.compatTransform = function (s) {
return s;
};
}
if (site.email_lower_case || ((site.email_lower_case === undefined) && config.email_lower_case)) {
site.compatTransformEmail = function (s) {
return s ? s.toLowerCase() : s;
};
} else {
site.compatTransformEmail = function (s) {
return s;
};
}
if (site.emails_unique || ((site.emails_unique === undefined) && config.emails_unique)) {
site.uniqueEmails = function (users) {
var mails = {};
var filteredUsers = users.filter(function (user) {
if (!user.attributes.email || (user.attributes.email == '')) {
return false;
}
var result = !(user.attributes.email in mails);
mails[user.attributes.email] = true;
return result;
});
return filteredUsers;
};
} else {
site.uniqueEmails = function (users) {
return users;
};
}
if (site.ldap_password_bcrypt || ((site.ldap_password_bcrypt === undefined) && config.ldap_password_bcrypt)) {
site.checkPassword = function (password, callback) {
if (site.loginBlockedDate) {
var now = new Date();
var checkDate = new Date(site.loginBlockedDate.getTime() + 1000*3600*24); // one day
if (now < checkDate) {
callback(false);
return;
} else {
site.loginBlockedDate = null;
site.loginErrorCount = 0;
}
}
var directCheckValid = (password === site.ldap_password);
if (directCheckValid) {
callback(true);
} else {
var hash = site.ldap_password.replace(/^\$2y(.+)$/i, '$2a$1');
bcrypt.compare(password, hash, function (err, valid) {
if (!valid) {
site.loginErrorCount += 1;
if (site.loginErrorCount > 5) {
site.loginBlockedDate = new Date();
}
}
callback(valid);
});
}
}
} else {
site.checkPassword = function (password, callback) {
if (site.loginBlockedDate) {
var now = new Date();
var checkDate = new Date(site.loginBlockedDate.getTime() + 1000*3600*24); // one day
if (now < checkDate) {
callback(false);
return;
} else {
site.loginBlockedDate = null;
site.loginErrorCount = 0;
}
}
var valid = (password === site.ldap_password);
if (!valid) {
site.loginErrorCount += 1;
if (site.loginErrorCount > 5) {
site.loginBlockedDate = new Date();
}
}
callback(valid);
}
}
if (site.ct_uri.slice(-1) !== "/") {
site.ct_uri += "/";
}
});
if (config.ldap_cert_filename && config.ldap_key_filename) {
var ldapCert = fs.readFileSync(config.ldap_cert_filename, {encoding: "utf8"}),
ldapKey = fs.readFileSync(config.ldap_key_filename, {encoding: "utf8"});
var server = ldap.createServer({ certificate: ldapCert, key: ldapKey });
} else {
var server = ldap.createServer();
}
if (typeof config.cache_lifetime !== 'number') {
config.cache_lifetime = 10000; // 10 seconds
}
function getCsrfToken(site) {
return rp({
"method": "GET",
"jar": site.cookieJar,
"uri": site.ct_uri + "/api/csrftoken",
"json": true,
headers: {
'User-Agent': userAgent
},
}).then(function (result) {
if (!result.data) {
throw new Error(JSON.stringify(result));
}
site.csrftoken = result.data;
logDebug(site, "Got CSRF-Token.");
return true;
}).catch(function (error) {
logError(site, "Could not get CSRF-Token: "+ JSON.stringify(error));
return true; // continue anyway, maybe this is an older CT selfhosting version
});
}
/**
* Returns a promise for the login on the ChurchTools API.
* If a pending login promise already exists, it is returned right away.
*/
function apiLogin(site) {
if (site.loginPromise === null) {
logInfo(site, "Performing CT API login...");
site.csrftoken = 'foobar';
site.loginPromise = rp({
"method": "POST",
"jar": site.cookieJar,
"uri": site.ct_uri + "?q=login/ajax",
"form": {
"func": "login",
"email": site.api_user,
"password": site.api_password
},
"json": true,
headers: {
'User-Agent': userAgent
},
}).then(function (result) {
if (result.status !== "success") {
logError(site, "CT API login failed: " + JSON.stringify(result));
// clear login promise
site.loginPromise = null;
throw new Error(JSON.stringify(result));
}
logInfo(site, "CT API login successful, fetching CSRF-Token...");
return getCsrfToken(site);
}).then(function () {
logDebug(site, "CT API login completed");
// clear login promise
site.loginPromise = null;
// end gracefully
return null;
}).catch(function (error) {
logError(site, "CT API login failed with exception.");
// clear login promise
site.loginPromise = null;
// rethrow error
throw error;
});
} else if (config.debug) {
logDebug(site, "Return pending login promise");
}
return site.loginPromise;
}
function checkRateLimit(site, windowInSeconds, maxRequests) {
sitename = site.sitename;
var now = new Date();
if (!rateLimitStore[windowInSeconds]) {
rateLimitStore[windowInSeconds] = {};
}
if (!rateLimitStore[windowInSeconds][sitename]) {
rateLimitStore[windowInSeconds][sitename] = {
windowStartTime: now,
requestCount: 0
};
}
var secondsBetweenStartOfWindowAndNow = (now.getTime() - rateLimitStore[windowInSeconds][sitename].windowStartTime.getTime()) / 1000;
if (secondsBetweenStartOfWindowAndNow > windowInSeconds) {
rateLimitStore[windowInSeconds][sitename] = {
windowStartTime: now,
requestCount: 0
};
}
if (rateLimitStore[windowInSeconds][sitename].requestCount > maxRequests) {
logWarn(site, 'Rate Limit reached');
throw new Error('Rate Limit reached for site ' + sitename + ' and limit ' + maxRequests + 'in ' + windowInSeconds + 'seconds window');
}
rateLimitStore[windowInSeconds][sitename].requestCount++;
}
/**
* Retrieves data from the PHP API via a POST call.
* @param {object} site - The current site
* @param {function} func - The function to call in the API class
* @param {object} [data] - The optional form data to pass along with the POST request
* @param {boolean} [triedLogin] - Is true if this is the second attempt after API login
*/
function apiPost(site, func, data, triedLogin, triedCSRFUpdate) {
logInfo(site, "Performing request to API function "+func);
checkRateLimit(site, 60 * 10, site.requests10Minutes? site.requests10Minutes: 150);
checkRateLimit(site, 60 * 60, site.requests60Minutes? site.requests60Minutes: 300);
return rp({
"method": "POST",
"jar": site.cookieJar,
"headers": {'CSRF-Token': site.csrftoken, 'User-Agent': userAgent},
"uri": site.ct_uri + "?q=churchdb/ajax",
"form": extend({ "func": func }, data || {}),
"json": true
}).then(function (result) {
if (result.status !== "success") {
// If this was the first attempt, login and try again
if (!triedLogin) {
logDebug(site, "CT session invalid, login and retry...");
return apiLogin(site).then(function () {
// Retry operation after login
logDebug(site, "Retry request to API function " + func + " after login");
// Set "triedLogin" parameter to prevent looping
return apiPost(site, func, data, true, triedCSRFUpdate);
});
} else {
var error = new Error(JSON.stringify(result));
logError(site, "CT API request still not working after login: ", error);
throw error;
}
}
return result.data;
}, function (error) {
if (error.error && (
(error.error.message === "CSRF-Token is invalid") ||
(error.error.errors && error.error.errors[0] && error.error.errors[0].message === "CSRF-Token is invalid")
) && !triedCSRFUpdate) {
logDebug(site, "CSRF token is invalid, get new one and retry...");
return getCsrfToken(site).then(function() {
// Retry operation
logDebug(site, "Retry request to API function " + func + " with fresh CSRF token");
// Set "triedCSRFUpdate" parameter to prevent looping
return apiPost(site, func, data, triedLogin, true);
});
}
throw error;
});
}
var USERS_KEY = "users", GROUPS_KEY = "groups";
/**
* Retrieves data from cache as a Promise or refreshes the data with the provided Promise factory.
* @param {string} key - The cache key
* @param {number} maxAge - The maximum age of the cache entry, if older the data will be refreshed
* @param {function} factory - A function returning a Promise that resolves with the new cache entry or rejects
*/
function getCached(site, key, maxAge, factory) {
return new Promise(function (resolve, reject) {
var time = new Date().getTime();
var co = site.CACHE[key] || { time: -1, entry: null };
if (time - maxAge < co.time) {
logDebug(site, "using cached data");
resolve(co.entry);
} else {
// Call the factory() function to retrieve the Promise for the fresh entry
// Either resolve with the new entry (plus cache update), or pass on the rejection
factory().then(function (result) {
co.entry = result;
co.time = new Date().getTime();
site.CACHE[key] = co;
resolve(result);
}, reject);
}
});
}
/**
* Retrieves the users for the processed request as a Promise.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function requestUsers (req, res, next) {
var site = req.site;
req.usersPromise = getCached(site, USERS_KEY, config.cache_lifetime, function () {
return apiPost(site, "getUsersData").then(function (results) {
var newCache = results.users.map(function (v) {
var cn = v.cmsuserid;
return {
dn: site.compatTransform(site.fnUserDn({ cn: cn })),
attributes: {
cn: cn,
displayname: v.vorname + " " + v.name,
id: String(v.id),
uid: cn,
nsuniqueid: "u" + v.id,
givenname: v.vorname,
street: v.strasse,
telephoneMobile: v.telefonhandy,
telephoneHome: v.telefonprivat,
postalCode: v.plz,
l: v.ort,
sn: v.name,
email: site.compatTransformEmail(v.email),
mail: site.compatTransformEmail(v.email),
objectclass: ['CTPerson'],
memberof: (results.userGroups[v.id] || []).map(function (cn) {
return site.compatTransform(site.fnGroupDn({ cn: cn }));
})
}
};
});
newCache = site.uniqueEmails(newCache);
// Virtual admin user
if (site.ldap_password !== undefined) {
var cn = config.ldap_user;
newCache.push({
dn: site.compatTransform(site.fnUserDn({ cn: cn })),
attributes: {
cn: cn,
displayname: "LDAP Administrator",
id: 0,
uid: cn,
nsuniqueid: "u0",
givenname: "LDAP Administrator",
objectclass: ['CTPerson'],
}
});
}
var size = newCache.length;
logDebug(site, "Updated users: " + size);
return newCache;
});
});
return next();
}
/**
* Retrieves the groups for the processed request as a Promise.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function requestGroups (req, res, next) {
var site = req.site;
req.groupsPromise = getCached(site, GROUPS_KEY, config.cache_lifetime, function () {
return apiPost(site, "getGroupsData").then(function (results) {
var newCache = results.groups.map(function (v) {
var cn = v.bezeichnung;
var groupType = v.gruppentyp;
return {
dn: site.compatTransform(site.fnGroupDn({ cn: cn })),
attributes: {
cn: cn,
displayname: v.bezeichnung,
id: v.id,
nsuniqueid: "g" + v.id,
objectclass: ["group", "CTGroup" + groupType.charAt(0).toUpperCase() + groupType.slice(1)],
uniquemember: (results.groupMembers[v.id] || []).map(function (cn) {
return site.compatTransform(site.fnUserDn({ cn: cn }));
}),
memberUID: results.groupMembers[v.id] || []
}
};
});
var size = newCache.length;
logDebug(site, "Updated groups: " + size);
return newCache;
});
});
return next();
}
/**
* Validates root user authentication by comparing the bind DN with the configured admin DN.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function authorize(req, res, next) {
if (!req.connection.ldap.bindDN.equals(req.site.adminDn)) {
logWarn(req.site, "Rejected search without proper binding!");
return next(new ldap.InsufficientAccessRightsError());
}
return next();
}
/**
* Performs debug logging if debug mode is enabled.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function searchLogging (req, res, next) {
logInfo(req.site, "SEARCH base object: " + req.dn.toString() + " scope: " + req.scope);
logInfo(req.site, "Filter: " + req.filter.toString());
return next();
}
/**
* Evaluates req.usersPromise and sends matching elements to the client.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function sendUsers (req, res, next) {
var strDn = req.dn.toString();
req.usersPromise.then(function (users) {
users.forEach(function (u) {
if ((req.checkAll || parseDN(strDn).equals(parseDN(u.dn))) && (req.filter.matches(u.attributes))) {
logDebug(req.site, "MatchUser: " + u.dn);
res.send(u);
}
});
return next();
}).catch(function (error) {
logError(req.site, "Error while retrieving users: ", error);
return next();
});
}
/**
* Evaluates req.groupsPromise and sends matching elements to the client.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function sendGroups (req, res, next) {
var strDn = req.dn.toString();
req.groupsPromise.then(function (groups) {
groups.forEach(function (g) {
if ((req.checkAll || parseDN(strDn).equals(parseDN(g.dn))) && (req.filter.matches(g.attributes))) {
logDebug(req.site, "MatchGroup: " + g.dn);
res.send(g);
}
});
return next();
}).catch(function (error) {
logError(req.site, "Error while retrieving groups: ", error);
return next();
});
}
/**
* Calls the res.end() function to finalize successful chain processing.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function endSuccess (req, res, next) {
res.end();
return next();
}
/**
* Checks the given credentials against the credentials in the config file or against a ChurchTools server.
* @param {object} req - Request object
* @param {object} res - Response object
* @param {function} next - Next handler function of filter chain
*/
function authenticate (req, res, next) {
var site = req.site;
if (req.dn.equals(site.adminDn)) {
logInfo(site, "Admin bind DN: " + req.dn.toString());
// If ldap_password is undefined, try a default ChurchTools authentication with this user
if (site.ldap_password !== undefined) {
site.checkPassword(req.credentials, function (result) {
if (result) {
logInfo(site, "Authentication success");
return next();
} else {
logError(site, "Invalid root password!");
return next(new ldap.InvalidCredentialsError());
}
});
return;
}
} else {
logInfo(site, "Bind user DN: " + req.dn);
}
apiPost(site, "authenticate", {
"user": req.dn.rdns[0].attrs.cn.value,
"password": req.credentials
}).then(function () {
logInfo(site, "Authentication successful for " + req.dn.toString());
return next();
}).catch(function (error) {
logError(site, "Authentication error: ", error);
return next(new ldap.InvalidCredentialsError());
});
}
Object.keys(config.sites).map(function(sitename, index) {
// Login bind for user
server.bind("ou=users,o=" + sitename, function (req, res, next) {
req.site = config.sites[sitename];
next();
}, authenticate, endSuccess);
// Search implementation for user search
server.search("ou=users,o=" + sitename, function (req, res, next) {
req.site = config.sites[sitename];
next();
}, searchLogging, authorize, function (req, res, next) {
req.checkAll = req.scope !== "base";
return next();
}, requestUsers, sendUsers, endSuccess);
// Search implementation for group search
server.search("ou=groups,o=" + sitename, function (req, res, next) {
req.site = config.sites[sitename];
next();
}, searchLogging, authorize, function (req, res, next) {
req.checkAll = req.scope !== "base";
return next();
}, requestGroups, sendGroups, endSuccess);
// Search implementation for user and group search
server.search("o=" + sitename, function (req, res, next) {
req.site = config.sites[sitename];
next();
}, searchLogging, authorize, function (req, res, next) {
logInfo({ sitename: sitename }, "Search for users and groups combined");
req.checkAll = req.scope === "sub";
return next();
}, requestUsers, requestGroups, sendUsers, sendGroups, endSuccess);
});
// Search implementation for basic search for Directory Information Tree and the LDAP Root DSE
server.search('', function (req, res, next) {
logInfo({ sitename: req.dn.o }, "empty request, return directory information");
var obj = {
"attributes": {
"objectClass": ["top", "OpenLDAProotDSE"],
"subschemaSubentry": ["cn=subschema"],
"namingContexts": "o=" + req.dn.o,
},
"dn": "",
};
if (req.filter.matches(obj.attributes))
res.send(obj);
res.end();
}, endSuccess);
function escapeRegExp(str) {
/* JSSTYLED */
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/** Case insensitive search on substring filters */
ldap.SubstringFilter.prototype.matches = function (target, strictAttrCase) {
var tv = helpers.getAttrValue(target, this.attribute, strictAttrCase);
if (tv !== undefined && tv !== null) {
var re = '';
if (this.initial)
re += '^' + escapeRegExp(this.initial) + '.*';
this.any.forEach(function (s) {
re += escapeRegExp(s) + '.*';
});
if (this.final)
re += escapeRegExp(this.final) + '$';
var matcher = new RegExp(re, 'i');
return helpers.testValues(function (v) {
return matcher.test(v);
}, tv);
}
return false;
};
// Start LDAP server
server.listen(parseInt(config.ldap_port), config.ldap_ip, function () {
console.log('ChurchTools-LDAP-Wrapper listening @ %s', server.url);
});