This repository was archived by the owner on May 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathldap.js
More file actions
290 lines (251 loc) · 9.05 KB
/
Copy pathldap.js
File metadata and controls
290 lines (251 loc) · 9.05 KB
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
'use strict';
const Joi = require('joi');
const LDAP = require('ldapjs');
const Logger = require('../lib/logger.js');
const Utils = require('../lib/utils.js');
const Qs = require('qs');
const helpers = require("../lib/helpers.js")
/**
*
* @type {import('@hapi/hapi').PluginBase}
*/
exports.plugin = {
name: 'ldap',
register: async function (server) {
server.ext('onRequest', (request, h) => {
helpers.setQueryParameterTemplateValues(request.query);
let { tlsOptions, attributes } = request.query;
if (tlsOptions) {
tlsOptions = Qs.parse(tlsOptions, {
delimiter: /[;,]/,
});
request.query.tlsOptions = tlsOptions;
}
if (attributes && !Array.isArray(attributes)) {
attributes = [attributes];
request.query.attributes = attributes;
}
return h.continue;
});
server.route({
method: 'GET',
path: '/ldap/search',
options: {
description: 'Search LDAP server',
notes:
'Performs a search operation against the LDAP server. We are using ldapjs npm here. Check http://ldapjs.org for full docs.',
tags: ['api', 'ldap'],
validate: {
query: Joi.object({
url: Joi.string()
.required()
.description(
'A valid LDAP URL (proto/host/port), e.g. `ldap://ad.example.com`.'
),
username: Joi.string()
.required()
.description(
'An account name capbable of performing the operations desired, e.g. `test@domain.com`'
),
password: Joi.string()
.required()
.description('Password for the given username.'),
tlsOptions: Joi.object({
isServer: Joi.boolean()
.description(
'isServer: The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If true the TLS socket will be instantiated as a server. Default: false.'
)
.default(false),
requestCert: Joi.boolean()
.description(
'Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (isServer is true) may set requestCert to true to request a client certificate. Default: false.'
)
.default(false),
rejectUnauthorized: Joi.boolean()
.description(
'If not false the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if requestCert is true. Default: true.'
)
.default(true),
clientCertEngine: Joi.string().description(
'Name of an OpenSSL engine which can provide the client certificate.'
),
})
.optional()
.description(
'Additional options passed to TLS connection layer when connecting via ldaps://'
),
base: Joi.string()
.required()
.description(
'The root DN from which all searches will be performed, e.g. `dc=example,dc=com`.'
),
filter: Joi.string()
.required()
.description(
'LDAP filter, e.g. `(&(|(objectClass=user)(objectClass=person))(!(objectClass=computer))(!(objectClass=group)))`'
),
scope: Joi.string()
.valid('base', 'one', 'sub')
.default('base')
.required()
.description('One of `base`, `one`, or `sub`'),
attributes: Joi.array()
.items(Joi.string().required())
.optional()
.default(['dn', 'sn', 'cn'])
.description('Attributes to select and return'),
raw: Joi.boolean()
.default(false)
.description(
'Either return the raw object (true) or a simplified structure (false)'
),
paged: Joi.boolean()
.default(false)
.optional()
.description('Enable and/or configure automatic result paging'),
pageSize: Joi.number()
.integer()
.default(100)
.max(10000)
.optional()
.description(
'The pageSize parameter sets the size of result pages requested from the server.'
),
}),
},
},
handler: async function (request, h) {
Logger.debug(`Request ${request.method.toUpperCase()} ${request.path}`);
const { url, username, password, tlsOptions } = request.query;
async function setupClient() {
return new Promise((resolve, reject) => {
const client = LDAP.createClient({
url,
tlsOptions,
});
const clientErrorListener = (error) => {
if (client) {
client.unbind((error) => {
if (error) {
Logger.warn(error.message);
}
});
}
reject(error);
};
client.on('error', clientErrorListener);
client.on('connect', () => {
client.removeListener('error', clientErrorListener);
resolve(client);
});
});
}
const { filter, base, scope, attributes, raw, paged, pageSize } =
request.query;
const options = {
filter,
scope,
attributes,
paged: paged ? { pageSize, pagePause: true } : false,
};
try {
const client = await setupClient();
function simplify(rows) {
return rows.reduce((accumulator, row) => {
const { objectName, objectSid, objectGUID, attributes } = row;
let obj = {
objectName,
};
if (objectSid) {
obj.objectSid = objectSid;
}
if (objectGUID) {
obj.objectGUID = objectGUID;
}
for (const attribute of attributes) {
const { type, values } = attribute;
for (const value of values) {
obj[type] = value;
}
}
accumulator.push(obj);
return accumulator;
}, []);
}
async function login() {
return new Promise((resolve, reject) => {
client.bind(username, password, (error) => {
if (error) {
error.statusCode = 401;
reject(error);
}
resolve();
});
});
}
async function search() {
return new Promise((resolve, reject) => {
client.search(base, options, (error, result) => {
let rows = [];
function normalizeRows() {
try {
for (const row of rows) {
if (!raw) {
if (row.objectSid) {
row.objectSid = Utils.binarySidToStringSid(
Buffer.from(row.objectSid, 'binary')
);
}
if (row.objectGUID) {
row.objectGUID = Utils.binarySidToStringSid(
Buffer.from(row.objectGUID, 'binary')
);
}
}
}
return !raw ? simplify(rows) : rows;
} catch (error) {
reject(error);
}
}
result.on('searchEntry', (entry) => {
rows.push(entry.pojo);
});
result.on('error', (error) => {
reject(error);
});
result.on('end', () => {
client.unbind((error) => {
if (error) {
Logger.warn(error.message);
}
});
resolve(normalizeRows());
});
result.on('page', () => {
client.unbind((error) => {
if (error) {
Logger.warn(error.message);
}
});
resolve(normalizeRows());
});
if (error) {
reject(error);
}
});
});
}
await login();
let result = await search();
return h.response(result).code(200);
} catch (error) {
Logger.error(error.message);
return h
.response({ error: error.message })
.code(error.statusCode ?? 500);
}
},
});
},
};