forked from auth0/ad-ldap-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws_validator.js
334 lines (294 loc) · 9.91 KB
/
ws_validator.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
var WebSocket = require('ws');
var exit = require('./lib/exit');
var jwt = require('jsonwebtoken');
var nconf = require('nconf');
var fs = require('fs');
var Users = require('./lib/users');
var users = new Users();
var async = require('async');
var cb = require('cb');
var ms = require('ms');
var cert = {
key: nconf.get('AUTH_CERT_KEY') || fs.readFileSync(__dirname + '/certs/cert.key'),
cert: nconf.get('AUTH_CERT') || fs.readFileSync(__dirname + '/certs/cert.pem')
};
var authenticate_when_password_expired = nconf.get('ALLOW_PASSWORD_EXPIRED');
var authenticate_when_password_change_required = nconf.get('ALLOW_PASSWORD_CHANGE_REQUIRED');
var socket_server_address = nconf.get('AD_HUB').replace(/^http/i, 'ws');
var ws = module.exports = new WebSocket(socket_server_address);
var AccountDisabled = require('./lib/errors/AccountDisabled');
var AccountExpired = require('./lib/errors/AccountExpired');
var AccountLocked = require('./lib/errors/AccountLocked');
var PasswordChangeRequired = require('./lib/errors/PasswordChangeRequired');
var PasswordExpired = require('./lib/errors/PasswordExpired');
var WrongPassword = require('./lib/errors/WrongPassword');
var WrongUsername = require('./lib/errors/WrongUsername');
var InsufficientAccessRightsError = require('./lib/errors/InsufficientAccessRightsError');
var PasswordComplexityError = require('./lib/errors/PasswordComplexityError');
ws.sendEvent = function (name, payload) {
this.send(JSON.stringify({
n: name,
p: payload
}));
};
ws.reply = function (pid, response) {
return this.sendEvent(pid + '_result', response);
};
function ping(client, count, callback) {
if (typeof count === 'undefined') {
count = 0;
callback = function () {};
}
var pong = cb(function (err) {
if (err instanceof cb.TimeoutError) {
client.removeListener('pong', pong);
if (count === 4) {
return callback(new Error('Auth0 server didn\'t respond to ' + (count + 1) + ' ping commands. Re-pinging.'));
}
return ping(client, ++count, callback);
}
callback(null, {
failed_pings: count
});
}).timeout(ms('4s'));
if (client.readyState !== WebSocket.OPEN) {
return callback(new Error('connection is closed'));
}
client.once('pong', pong).ping('');
}
var log_from_auth0 = console.log.bind(console, 'auth0'.blue + ':');
console.log('Connecting to ' + socket_server_address.green + '.');
ws.on('open', function () {
authenticate_connector();
}).on('message', function (msg) {
var m;
try {
m = JSON.parse(msg);
} catch (er) {
return;
}
if (!m || !m.n) return;
this.emit(m.n, m.p);
}).on('error', function (err) {
console.error('Socket error: ' + err);
exit(1);
}).on('authenticated', function () {
log_from_auth0('Agent accepted.');
var client = this;
async.whilst(
function () {
return true;
},
function (done) {
setTimeout(function () {
ping(client, 0, function (err, result) {
if (err) return done(err);
if (result.failed_pings > 0) {
console.log('Ping success after failed ' + result.failed_pings + ' pings.');
}
done();
});
}, ms('5s'));
},
function (err) {
console.log(err.message);
return exit(1);
}
);
}).on('authentication_failure', function () {
log_from_auth0('Agent ' + 'rejected'.red + '.');
exit(0);
}).on('close', function () {
if (process.exiting) {
log_from_auth0('Connection closed as requested.');
} else {
log_from_auth0('Connection closed.');
exit(1);
}
}).on('authenticate_user', function (msg) {
jwt.verify(msg.jwt, nconf.get('TENANT_SIGNING_KEY'), function (err, payload) {
if (err) {
console.error('Unauthorized attemp of authentication.');
return;
}
var log_prepend = 'user ' + payload.username + ':';
var log = console.log.bind(console, log_prepend.blue);
log('Starting authentication attempt.');
users.validate(payload.username, payload.password, function (err, user) {
if (err) {
if (err instanceof AccountDisabled) {
log("Authentication attempt failed. Reason: " + "account disabled".red);
return ws.reply(payload.pid, {
err: err,
profile: err.profile
});
}
if (err instanceof AccountExpired) {
log("Authentication attempt failed. Reason: " + "account expired".red);
return ws.reply(payload.pid, {
err: err,
profile: err.profile
});
}
if (err instanceof AccountLocked) {
log("Authentication attempt failed. Reason: " + "account locked".red);
return ws.reply(payload.pid, {
err: err,
profile: err.profile
});
}
if (err instanceof PasswordChangeRequired) {
if (authenticate_when_password_change_required) {
log("Authentication succeeded, but " + "password change is required".red);
return ws.sendEvent(payload.pid + '_result', {
profile: err.profile
});
} else {
log("Authentication attempt failed. Reason: " + "password change is required".red);
return ws.reply(payload.pid, {
err: err,
profile: err.profile
});
}
}
if (err instanceof PasswordExpired) {
if (authenticate_when_password_expired) {
log("Authentication succeeded but " + "password expired".red);
return ws.sendEvent(payload.pid + '_result', {
profile: err.profile
});
} else {
log("Authentication attempt failed. Reason: " + "password expired".red);
return ws.reply(payload.pid, {
err: err,
profile: err.profile
});
}
}
if (err instanceof WrongPassword) {
log("Authentication attempt failed. Reason: " + "wrong password".red);
return ws.reply(payload.pid, {
err: err,
profile: err.profile
});
}
if (err instanceof WrongUsername) {
log("Authentication attempt failed. Reason: " + "wrong username".red);
return ws.reply(payload.pid, {
err: err,
profile: {
username: payload.username
}
});
}
log("Authentication attempt failed. Reason: " + "unexpected error".red);
if (err.inner && err.inner.stack) {
console.error('Inner error:', err.inner.stack);
} else {
console.log(err);
}
ws.reply(payload.pid, {
err: err
});
return exit(1);
}
log('Authentication succeeded.');
ws.sendEvent(payload.pid + '_result', {
profile: user
});
});
});
}).on('search_users', function (msg) {
jwt.verify(msg.jwt, nconf.get('TENANT_SIGNING_KEY'), function (err, payload) {
if (err) {
console.error('Unauthorized attemp of search_users.');
return;
}
console.log('Searching users.');
var options = {
limit: payload.limit
};
users.list(payload.search, options, function (err, users) {
if (err) return ws.sendEvent(payload.pid + '_search_users_result', {
err: err
});
console.log('Search succeeded.');
ws.sendEvent(payload.pid + '_search_users_result', {
users: users
});
});
});
}).on('list_groups', function(msg) {
jwt.verify(msg.jwt, nconf.get('TENANT_SIGNING_KEY'), function(err, payload) {
if (err) {
console.error('Unauthorized attempt of list_groups');
return;
}
console.log('Listing groups.');
var options = {
limit: payload.limit
};
users.listGroups(options, function (err, groups) {
if (err) return ws.sendEvent(payload.pid + '_list_groups_result', {
err: err
});
console.log('Listing groups succeeded.');
ws.sendEvent(payload.pid + '_list_groups_result', {
groups: groups
});
});
})
});
// Listen only for change_password event when write back is enabled.
if (nconf.get('ENABLE_WRITE_BACK')) {
ws.on('change_password', function (command) {
jwt.verify(command.jwt, nconf.get('TENANT_SIGNING_KEY'), function (err, payload) {
if (err) {
console.error('Unauthorized change_password attempt');
return;
};
var log_prepend = 'user ' + payload.username + ':';
var log = console.log.bind(console, log_prepend.blue);
log('Attempting change_password.');
users.changePassword(payload.username, payload.password, function (err, profile) {
if (err) {
if (err instanceof InsufficientAccessRightsError || err instanceof PasswordComplexityError) {
log("Change Password attempt failed. Reason: " + err.message.red);
return ws.sendEvent(payload.pid + '_change_password_result', {
err: err,
profile: err.profile
});
}
log("Change Password attempt failed. Reason: " + "unexpected error".red);
if (err.inner && err.inner.stack) {
console.error('Inner error:', err.inner.stack);
} else {
console.log(err);
};
ws.sendEvent(payload.pid + '_change_password_result', {
err: err
});
return exit(1);
}
log('Password Change succeeded.');
ws.sendEvent(payload.pid + '_change_password_result', {
profile: profile
});
});
});
});
}
function authenticate_connector() {
var defaultCapabilities = ['search', 'login'];
if (nconf.get('ENABLE_WRITE_BACK')) defaultCapabilities.push('change_password');
var token = jwt.sign({}, cert.key, {
algorithm: 'RS256',
expiresInMinutes: 1,
issuer: nconf.get('CONNECTION'),
audience: nconf.get('REALM'),
"http://schemas.auth0.com/ad-ldap-connector/capabilites": defaultCapabilities
});
ws.sendEvent('authenticate', {
jwt: token
});
};