Added support for LDAP account images (#4283)

Ylian Saint-Hilaire committed Jul 20, 2022 at 12:57 UTC 61e486ba38afc630ee36185aa5fdbb89cb95ac3f
2 files changed +84 -76
meshcentral-config-schema.json
+7 -5
@@ -501,11 +501,13 @@
501 },
502 "twoFactorCookieDurationDays": { "type": "integer", "default": 30, "description": "Number of days that a user is allowed to remember this device for when completing 2FA. Set this to 0 to remove this option." },
503 "auth": { "type": "string", "default": null, "enum": [null, "sspi", "ldap"], "description": "Type of user authentication to use, this can be SSPI on Windows or LDAP. If not set, username/password is used." },
504 - "ldapUserKey": { "type": "string" },
505 - "ldapUserName": { "type": "string" },
506 - "ldapUserEmail": { "type": "string" },
507 - "ldapUserRealName": { "type": "string" },
508 - "ldapUserPhoneNumber": { "type": "string" },
504 + "ldapUserKey": { "type": "string", "default": null, "description": "The LDAP value to use as a user's unique account identifier. Use \"ldapUserKey\" or \"ldapUserBinaryKey\"." },
505 + "ldapUserBinaryKey": { "type": "string", "default": "objectSid", "description": "The LDAP value to use as a user's unique account identifier, when specified in this feild, the values will be HEX converted." },
506 + "ldapUserName": { "type": "string", "default": "displayName", "description": "The LDAP value to use for the user name, you can also compose the name by setting this value to, for example: \"{{{givenName}}} {{{sn}}}\"" },
507 + "ldapUserEmail": { "type": "string", "default": "mail", "description": "The LDAP value to use for the user's email address." },
508 + "ldapUserRealName": { "type": "string", "default": "name", "description": "The LDAP value to use for the user's real name, you can also compose the name by setting this value to, for example: \"{{{givenName}}} {{{sn}}}\"" },
509 + "ldapUserPhoneNumber": { "type": "string", "default": "telephoneNumber", "description": "The LDAP value to use for the user's phone number." },
510 + "ldapUserImage": { "type": "string", "default": "thumbnailPhoto", "description": "The LDAP value to use for the user's image." },
511 "ldapSaveUserToFile": { "type": "string", "default": null, "description": "When set to a filename, for example c:\\temp\\ldapusers.txt, MeshCentral will save the LDAP user object to this file each time a user logs in. This is used for debugging LDAP issues." },
512 "ldapOptions": { "type": "object", "description": "LDAP options passed to ldapauth-fork" },
513 "agentInviteCodes": { "type": "boolean", "default": false, "description": "Enabled a feature where you can set one or more invitation codes in a device group. You can then give a invitation link to users who can use it to download the agent." },
webserver.js
+77 -71
@@ -89,45 +89,45 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
89 var webRelayNextSessionId = 1;
90 var webRelaySessions = {} // UserId/SessionId/Host --> Web Relay Session
91 var webRelayCleanupTimer = null;
92 -
92 +
93 // Mesh Rights
94 - const MESHRIGHT_EDITMESH = 0x00000001;
95 - const MESHRIGHT_MANAGEUSERS = 0x00000002;
96 - const MESHRIGHT_MANAGECOMPUTERS = 0x00000004;
97 - const MESHRIGHT_REMOTECONTROL = 0x00000008;
98 - const MESHRIGHT_AGENTCONSOLE = 0x00000010;
99 - const MESHRIGHT_SERVERFILES = 0x00000020;
100 - const MESHRIGHT_WAKEDEVICE = 0x00000040;
101 - const MESHRIGHT_SETNOTES = 0x00000080;
102 - const MESHRIGHT_REMOTEVIEWONLY = 0x00000100;
103 - const MESHRIGHT_NOTERMINAL = 0x00000200;
104 - const MESHRIGHT_NOFILES = 0x00000400;
105 - const MESHRIGHT_NOAMT = 0x00000800;
106 - const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000;
107 - const MESHRIGHT_LIMITEVENTS = 0x00002000;
108 - const MESHRIGHT_CHATNOTIFY = 0x00004000;
109 - const MESHRIGHT_UNINSTALL = 0x00008000;
110 - const MESHRIGHT_NODESKTOP = 0x00010000;
111 - const MESHRIGHT_REMOTECOMMAND = 0x00020000;
112 - const MESHRIGHT_RESETOFF = 0x00040000;
113 - const MESHRIGHT_GUESTSHARING = 0x00080000;
114 - const MESHRIGHT_ADMIN = 0xFFFFFFFF;
94 + const MESHRIGHT_EDITMESH = 0x00000001;
95 + const MESHRIGHT_MANAGEUSERS = 0x00000002;
96 + const MESHRIGHT_MANAGECOMPUTERS = 0x00000004;
97 + const MESHRIGHT_REMOTECONTROL = 0x00000008;
98 + const MESHRIGHT_AGENTCONSOLE = 0x00000010;
99 + const MESHRIGHT_SERVERFILES = 0x00000020;
100 + const MESHRIGHT_WAKEDEVICE = 0x00000040;
101 + const MESHRIGHT_SETNOTES = 0x00000080;
102 + const MESHRIGHT_REMOTEVIEWONLY = 0x00000100;
103 + const MESHRIGHT_NOTERMINAL = 0x00000200;
104 + const MESHRIGHT_NOFILES = 0x00000400;
105 + const MESHRIGHT_NOAMT = 0x00000800;
106 + const MESHRIGHT_DESKLIMITEDINPUT = 0x00001000;
107 + const MESHRIGHT_LIMITEVENTS = 0x00002000;
108 + const MESHRIGHT_CHATNOTIFY = 0x00004000;
109 + const MESHRIGHT_UNINSTALL = 0x00008000;
110 + const MESHRIGHT_NODESKTOP = 0x00010000;
111 + const MESHRIGHT_REMOTECOMMAND = 0x00020000;
112 + const MESHRIGHT_RESETOFF = 0x00040000;
113 + const MESHRIGHT_GUESTSHARING = 0x00080000;
114 + const MESHRIGHT_ADMIN = 0xFFFFFFFF;
115
116 // Site rights
117 - const SITERIGHT_SERVERBACKUP = 0x00000001;
118 - const SITERIGHT_MANAGEUSERS = 0x00000002;
119 - const SITERIGHT_SERVERRESTORE = 0x00000004;
120 - const SITERIGHT_FILEACCESS = 0x00000008;
121 - const SITERIGHT_SERVERUPDATE = 0x00000010;
122 - const SITERIGHT_LOCKED = 0x00000020;
123 - const SITERIGHT_NONEWGROUPS = 0x00000040;
124 - const SITERIGHT_NOMESHCMD = 0x00000080;
125 - const SITERIGHT_USERGROUPS = 0x00000100;
126 - const SITERIGHT_RECORDINGS = 0x00000200;
127 - const SITERIGHT_LOCKSETTINGS = 0x00000400;
128 - const SITERIGHT_ALLEVENTS = 0x00000800;
129 - const SITERIGHT_NONEWDEVICES = 0x00001000;
130 - const SITERIGHT_ADMIN = 0xFFFFFFFF;
117 + const SITERIGHT_SERVERBACKUP = 0x00000001;
118 + const SITERIGHT_MANAGEUSERS = 0x00000002;
119 + const SITERIGHT_SERVERRESTORE = 0x00000004;
120 + const SITERIGHT_FILEACCESS = 0x00000008;
121 + const SITERIGHT_SERVERUPDATE = 0x00000010;
122 + const SITERIGHT_LOCKED = 0x00000020;
123 + const SITERIGHT_NONEWGROUPS = 0x00000040;
124 + const SITERIGHT_NOMESHCMD = 0x00000080;
125 + const SITERIGHT_USERGROUPS = 0x00000100;
126 + const SITERIGHT_RECORDINGS = 0x00000200;
127 + const SITERIGHT_LOCKSETTINGS = 0x00000400;
128 + const SITERIGHT_ALLEVENTS = 0x00000800;
129 + const SITERIGHT_NONEWDEVICES = 0x00001000;
130 + const SITERIGHT_ADMIN = 0xFFFFFFFF;
131
132 // Setup SSPI authentication if needed
133 if ((obj.parent.platform == 'win32') && (obj.args.nousers != true) && (obj.parent.config != null) && (obj.parent.config.domains != null)) {
@@ -442,8 +442,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
442 } else if (domain.auth == 'ldap') {
443 // This method will handle LDAP login
444 const ldapHandler = function ldapHandlerFunc(err, xxuser) {
445 - if (ldapHandlerFunc.ldapobj) { try { ldapHandlerFunc.ldapobj.close(); } catch (ex) { console.log(ex); } } // Close the LDAP object
446 - if (err) { fn(new Error('invalid password')); return; }
445 + if (err) { if (ldapHandlerFunc.ldapobj) { try { ldapHandlerFunc.ldapobj.close(); } catch (ex) { console.log(ex); } } fn(new Error('invalid password')); return; }
446
447 // Save this LDAP user to file if needed
448 if (typeof domain.ldapsaveusertofile == 'string') {
@@ -464,18 +463,18 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
463 if (xxuser[domain.ldapuserkey]) { shortname = xxuser[domain.ldapuserkey]; }
464 } else {
465 // Use the default key as the userid
467 - if (xxuser.objectSid) { shortname = Buffer.from(xxuser.objectSid, 'binary').toString('hex').toLowerCase(); }
468 - else if (xxuser.objectGUID) { shortname = Buffer.from(xxuser.objectGUID, 'binary').toString('hex').toLowerCase(); }
469 - else if (xxuser.name) { shortname = xxuser.name; }
470 - else if (xxuser.cn) { shortname = xxuser.cn; }
466 + if (xxuser['objectSid']) { shortname = Buffer.from(xxuser['objectSid'], 'binary').toString('hex').toLowerCase(); }
467 + else if (xxuser['objectGUID']) { shortname = Buffer.from(xxuser['objectGUID'], 'binary').toString('hex').toLowerCase(); }
468 + else if (xxuser['name']) { shortname = xxuser['name']; }
469 + else if (xxuser['cn']) { shortname = xxuser['cn']; }
470 }
472 - if (shortname == null) { fn(new Error('no user identifier')); return; }
471 + if (shortname == null) { fn(new Error('no user identifier')); if (ldapHandlerFunc.ldapobj) { try { ldapHandlerFunc.ldapobj.close(); } catch (ex) { console.log(ex); } } return; }
472 if (username == null) { username = shortname; }
473 var userid = 'user/' + domain.id + '/' + shortname;
474
475 // Get the email address for this LDAP user
476 var email = null;
478 - if (domain.ldapuseremail) { email = xxuser[domain.ldapuseremail]; } else if (xxuser.mail) { email = xxuser.mail; } // Use given feild name or default
477 + if (domain.ldapuseremail) { email = xxuser[domain.ldapuseremail]; } else if (xxuser['mail']) { email = xxuser['mail']; } // Use given feild name or default
478 if (Array.isArray(email)) { email = email[0]; } // Mail may be multivalued in LDAP in which case, answer is an array. Use the 1st value.
479 if (email) { email = email.toLowerCase(); } // it seems some code elsewhere also lowercase the emailaddress, so let's be consistant.
480
@@ -492,13 +491,15 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
491 else { if (typeof xxuser['telephoneNumber'] == 'string') { phonenumber = xxuser['telephoneNumber']; } }
492
493 // Work on getting the image of this LDAP user
495 - // TODO: We need to get the image from LDAP as a buffer: https://github.com/ldapjs/node-ldapjs/issues/137
494 var userimage = null, userImageBuffer = null;
497 - if (domain.ldapuserimage && xxuser[domain.ldapuserimage]) { try { userImageBuffer = Buffer.from(xxuser[domain.ldapuserimage], 'binary'); } catch (ex) { } }
498 - if (xxuser['thumbnailPhoto']) { try { userImageBuffer = Buffer.from(xxuser['thumbnailPhoto'], 'binary'); } catch (ex) { } }
499 - if (userImageBuffer != null) {
500 - if ((userImageBuffer[0] == 0xFF) && (userImageBuffer[1] == 0xD8) && (userImageBuffer[2] == 0xFF) && (userImageBuffer[3] == 0xE0)) { userimage = 'data:image/jpeg;base64,' + userImageBuffer.toString('base64'); }
501 - if ((userImageBuffer[0] == 0x89) && (userImageBuffer[1] == 0x50) && (userImageBuffer[2] == 0x4E) && (userImageBuffer[3] == 0x47)) { userimage = 'data:image/png;base64,' + userImageBuffer.toString('base64'); }
495 + if (xxuser._raw) { // Using _raw allows us to get data directly as buffer.
496 + if (domain.ldapuserimage && xxuser[domain.ldapuserimage]) { userImageBuffer = xxuser._raw[domain.ldapuserimage]; }
497 + else if (xxuser['thumbnailPhoto']) { userImageBuffer = xxuser._raw['thumbnailPhoto']; }
498 + else if (xxuser['jpegPhoto']) { userImageBuffer = xxuser._raw['jpegPhoto']; }
499 + if (userImageBuffer != null) {
500 + if ((userImageBuffer[0] == 0xFF) && (userImageBuffer[1] == 0xD8) && (userImageBuffer[2] == 0xFF) && (userImageBuffer[3] == 0xE0)) { userimage = 'data:image/jpeg;base64,' + userImageBuffer.toString('base64'); }
501 + if ((userImageBuffer[0] == 0x89) && (userImageBuffer[1] == 0x50) && (userImageBuffer[2] == 0x4E) && (userImageBuffer[3] == 0x47)) { userimage = 'data:image/png;base64,' + userImageBuffer.toString('base64'); }
502 + }
503 }
504
505 // Display user information extracted from LDAP data
@@ -520,6 +521,9 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
521 // Save the user image
522 if (userimage != null) { parent.db.Set({ _id: 'im' + userid, image: userimage }); } else { db.Remove('im' + userid); }
523
524 + // Close the LDAP object
525 + if (ldapHandlerFunc.ldapobj) { try { ldapHandlerFunc.ldapobj.close(); } catch (ex) { console.log(ex); } }
526 +
527 // Check if the user already exists
528 var user = obj.users[userid];
529 if (user == null) {
@@ -628,6 +632,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
632 } else {
633 // LDAP login
634 var LdapAuth = require('ldapauth-fork');
635 + if (domain.ldapoptions == null) { domain.ldapoptions = {}; }
636 + domain.ldapoptions.includeRaw = true; // This allows us to get data as buffers which is useful for images.
637 var ldap = new LdapAuth(domain.ldapoptions);
638 ldapHandler.ldapobj = ldap;
639 ldap.on('error', function (err) { try { ldap.close(); } catch (ex) { console.log(ex); } console.log('ldap error: ', err); }); // Close the LDAP object
@@ -2062,7 +2068,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
2068 render(req, res, getRenderPage(page, req, domain), getRenderArgs({ cookie: cookie, name: encodeURIComponent(node.name).replace(/'/g, '%27'), serverCredentials: serverCredentials, features: features }, req, domain));
2069 });
2070 }
2065 -
2071 +
2072 // Called to handle push-only requests
2073 function handleFirebasePushOnlyRelayRequest(req, res) {
2074 parent.debug('email', 'handleFirebasePushOnlyRelayRequest');
@@ -2919,7 +2925,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
2925 }
2926
2927 // Return a list of server supported features for a given domain and user
2922 - obj.getDomainUserFeatures = function(domain, user, req) {
2928 + obj.getDomainUserFeatures = function (domain, user, req) {
2929 var features = 0;
2930 var features2 = 0;
2931 if (obj.args.wanonly == true) { features += 0x00000001; } // WAN-only mode
@@ -3492,7 +3498,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
3498 if (domain.titlepicture) {
3499 if ((parent.configurationFiles != null) && (parent.configurationFiles[domain.titlepicture] != null)) {
3500 // Use the logo in the database
3495 - res.set({ 'Content-Type': domain.titlepicture.toLowerCase().endsWith('.png')?'image/png':'image/jpeg' });
3501 + res.set({ 'Content-Type': domain.titlepicture.toLowerCase().endsWith('.png') ? 'image/png' : 'image/jpeg' });
3502 res.send(parent.configurationFiles[domain.titlepicture]);
3503 return;
3504 } else {
@@ -3607,7 +3613,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
3613 if (domain.welcomepicture) {
3614 if ((parent.configurationFiles != null) && (parent.configurationFiles[domain.welcomepicture] != null)) {
3615 // Use the welcome image in the database
3610 - res.set({ 'Content-Type': domain.welcomepicture.toLowerCase().endsWith('.png')?'image/png':'image/jpeg' });
3616 + res.set({ 'Content-Type': domain.welcomepicture.toLowerCase().endsWith('.png') ? 'image/png' : 'image/jpeg' });
3617 res.send(parent.configurationFiles[domain.welcomepicture]);
3618 return;
3619 }
@@ -3692,7 +3698,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
3698 if ((user.siteadmin & 512) == 0) { try { ws.close(); } catch (ex) { } return; } // Check if we have right to get recordings
3699 const filefullpath = obj.path.join(recordingsPath, req.query.file);
3700
3695 - obj.fs.stat(filefullpath, function(err, stats) {
3701 + obj.fs.stat(filefullpath, function (err, stats) {
3702 if (err) {
3703 try { ws.close(); } catch (ex) { } // File does not exist
3704 } else {
@@ -4609,7 +4615,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
4615 }
4616
4617 });
4612 - }
4618 + }
4619
4620 // Setup agent to/from server file transfer handler
4621 function handleAgentFileTransfer(ws, req) {
@@ -5771,7 +5777,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
5777 require('dns').lookup(obj.args.trustedproxy[0], function (err, address, family) { if (err == null) { obj.app.set('trust proxy', address); obj.args.trustedproxy = [address]; } });
5778 }
5779 }
5774 - }
5780 + }
5781 else if (typeof obj.args.tlsoffload == 'object') {
5782 // Reverse proxy should add the "X-Forwarded-*" headers
5783 try {
@@ -5916,7 +5922,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
5922
5923 // Skip the rest if this is an agent connection
5924 if ((req.url.indexOf('/meshrelay.ashx/.websocket') >= 0) || (req.url.indexOf('/agent.ashx/.websocket') >= 0) || (req.url.indexOf('/localrelay.ashx/.websocket') >= 0)) { next(); return; }
5919 -
5925 +
5926 // Setup security headers
5927 const geourl = (domain.geolocation ? ' *.openstreetmap.org' : '');
5928 var selfurl = ' wss://' + req.headers.host;
@@ -6114,7 +6120,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6120 obj.app.ws(url + 'localrelay.ashx', function (ws, req) {
6121 PerformWSSessionAuth(ws, req, true, function (ws1, req1, domain, user, cookie, authData) {
6122 if ((user == null) || (cookie == null)) {
6117 - try { ws1.close(); } catch (ex) { }
6123 + try { ws1.close(); } catch (ex) { }
6124 } else {
6125 obj.meshRelayHandler.CreateLocalRelay(obj, ws1, req1, domain, user, cookie); // Local relay
6126 }
@@ -6373,23 +6379,23 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6379
6380 // Generic OpenID Connect
6381 if ((typeof domain.authstrategies.oidc == 'object') && (typeof domain.authstrategies.oidc.clientid == 'string') && (typeof domain.authstrategies.oidc.clientsecret == 'string') && (typeof domain.authstrategies.oidc.issuer == 'string')) {
6376 - var options = {
6377 - authorizationURL: domain.authstrategies.oidc.authorizationurl,
6382 + var options = {
6383 + authorizationURL: domain.authstrategies.oidc.authorizationurl,
6384 callbackURL: domain.authstrategies.oidc.callbackurl,
6379 - clientID: domain.authstrategies.oidc.clientid,
6385 + clientID: domain.authstrategies.oidc.clientid,
6386 clientSecret: domain.authstrategies.oidc.clientsecret,
6381 - issuer: domain.authstrategies.oidc.issuer,
6382 - tokenURL: domain.authstrategies.oidc.tokenurl,
6383 - userInfoURL: domain.authstrategies.oidc.userinfourl,
6384 - scope: [ 'openid profile email' ],
6385 - responseMode: 'form_post' ,
6387 + issuer: domain.authstrategies.oidc.issuer,
6388 + tokenURL: domain.authstrategies.oidc.tokenurl,
6389 + userInfoURL: domain.authstrategies.oidc.userinfourl,
6390 + scope: ['openid profile email'],
6391 + responseMode: 'form_post',
6392 state: true
6393 };
6394 const OIDCStrategy = require('@mstrhakr/passport-generic-oidc');
6395 if (typeof domain.authstrategies.oidc.callbackurl == 'string') { options.callbackURL = domain.authstrategies.oidc.callbackurl; } else { options.callbackURL = url + 'oidc-callback'; }
6396 parent.debug('web', 'Adding Generic OIDC SSO with options: ' + JSON.stringify(options));
6397 passport.use('openidconnect', new OIDCStrategy.Strategy(options,
6392 - function verify( iss, sub, profile, cb ) {
6398 + function verify(iss, sub, profile, cb) {
6399 var user = { sid: '~oidc:' + profile.id, name: profile.displayName, email: profile.email, strategy: 'oidc' };
6400 parent.debug('AUTH', 'OIDC: Configured user: ' + JSON.stringify(user));
6401 return cb(null, user);
@@ -6842,7 +6848,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6848 if ((obj.common.validateString(command.cnonce, 1, 256) == false) || (obj.common.validateString(command.tlshash, 1, 512) == false)) {
6849 try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'badargs' })); } catch (ex) { }
6850 try { ws.close(); } catch (ex) { }
6845 - break;
6851 + break;
6852 }
6853
6854 // Check that the TLS hash is an acceptable one.
@@ -7972,7 +7978,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
7978 }
7979 xargs.extitle = encodeURIComponent(xargs.title).split('\'').join('\\\'');
7980 xargs.domainurl = domain.url;
7975 - xargs.autocomplete = (domain.autocomplete === false)?'x':'autocomplete'; // This option allows autocomplete to be turned off on the login page.
7981 + xargs.autocomplete = (domain.autocomplete === false) ? 'x' : 'autocomplete'; // This option allows autocomplete to be turned off on the login page.
7982 if (typeof domain.hide == 'number') { xargs.hide = domain.hide; }
7983
7984 // To mitigate any possible BREACH attack, we generate a random 0 to 255 bytes length string here.
@@ -8265,7 +8271,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
8271 var event = { etype: 'node', action: 'changenode', nodeid: oldNode._id, domain: oldNode.domain, node: obj.CloneSafeNode(oldNode) }
8272 if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the mesh. Another event will come.
8273 parent.DispatchEvent(['*', oldNode.meshid, oldNode._id], obj, event);
8268 - }
8274 + }
8275 }
8276 });
8277 }