ldap.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. import ldapjs from 'ldapjs';
  2. import { Log } from 'meteor/logging';
  3. // copied from https://github.com/ldapjs/node-ldapjs/blob/a113953e0d91211eb945d2a3952c84b7af6de41c/lib/filters/index.js#L167
  4. function escapedToHex (str) {
  5. if (str !== undefined) {
  6. return str.replace(/\\([0-9a-f][^0-9a-f]|[0-9a-f]$|[^0-9a-f]|$)/gi, function (match, p1) {
  7. if (!p1) {
  8. return '\\5c';
  9. }
  10. const hexCode = p1.charCodeAt(0).toString(16);
  11. const rest = p1.substring(1);
  12. return '\\' + hexCode + rest;
  13. });
  14. } else {
  15. return undefined;
  16. }
  17. }
  18. export default class LDAP {
  19. constructor() {
  20. this.ldapjs = ldapjs;
  21. this.connected = false;
  22. this.options = {
  23. host : this.constructor.settings_get('LDAP_HOST'),
  24. port : this.constructor.settings_get('LDAP_PORT'),
  25. Reconnect : this.constructor.settings_get('LDAP_RECONNECT'),
  26. timeout : this.constructor.settings_get('LDAP_TIMEOUT'),
  27. connect_timeout : this.constructor.settings_get('LDAP_CONNECT_TIMEOUT'),
  28. idle_timeout : this.constructor.settings_get('LDAP_IDLE_TIMEOUT'),
  29. encryption : this.constructor.settings_get('LDAP_ENCRYPTION'),
  30. ca_cert : this.constructor.settings_get('LDAP_CA_CERT'),
  31. reject_unauthorized : this.constructor.settings_get('LDAP_REJECT_UNAUTHORIZED') !== undefined ? this.constructor.settings_get('LDAP_REJECT_UNAUTHORIZED') : true,
  32. Authentication : this.constructor.settings_get('LDAP_AUTHENTIFICATION'),
  33. Authentication_UserDN : this.constructor.settings_get('LDAP_AUTHENTIFICATION_USERDN'),
  34. Authentication_Password : this.constructor.settings_get('LDAP_AUTHENTIFICATION_PASSWORD'),
  35. Authentication_Fallback : this.constructor.settings_get('LDAP_LOGIN_FALLBACK'),
  36. BaseDN : this.constructor.settings_get('LDAP_BASEDN'),
  37. Internal_Log_Level : this.constructor.settings_get('INTERNAL_LOG_LEVEL'), //this setting does not have any effect any more and should be deprecated
  38. User_Authentication : this.constructor.settings_get('LDAP_USER_AUTHENTICATION'),
  39. User_Authentication_Field : this.constructor.settings_get('LDAP_USER_AUTHENTICATION_FIELD'),
  40. User_Attributes : this.constructor.settings_get('LDAP_USER_ATTRIBUTES'),
  41. User_Search_Filter : escapedToHex(this.constructor.settings_get('LDAP_USER_SEARCH_FILTER')),
  42. User_Search_Scope : this.constructor.settings_get('LDAP_USER_SEARCH_SCOPE'),
  43. User_Search_Field : this.constructor.settings_get('LDAP_USER_SEARCH_FIELD'),
  44. Search_Page_Size : this.constructor.settings_get('LDAP_SEARCH_PAGE_SIZE'),
  45. Search_Size_Limit : this.constructor.settings_get('LDAP_SEARCH_SIZE_LIMIT'),
  46. group_filter_enabled : this.constructor.settings_get('LDAP_GROUP_FILTER_ENABLE'),
  47. group_filter_object_class : this.constructor.settings_get('LDAP_GROUP_FILTER_OBJECTCLASS'),
  48. group_filter_group_id_attribute : this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_ID_ATTRIBUTE'),
  49. group_filter_group_member_attribute: this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_MEMBER_ATTRIBUTE'),
  50. group_filter_group_member_format : this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_MEMBER_FORMAT'),
  51. group_filter_group_name : this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_NAME'),
  52. AD_Simple_Auth : this.constructor.settings_get('LDAP_AD_SIMPLE_AUTH'),
  53. Default_Domain : this.constructor.settings_get('LDAP_DEFAULT_DOMAIN'),
  54. };
  55. }
  56. static settings_get(name, ...args) {
  57. let value = process.env[name];
  58. if (value !== undefined) {
  59. if (value === 'true' || value === 'false') {
  60. value = JSON.parse(value);
  61. } else if (value !== '' && !isNaN(value)) {
  62. value = Number(value);
  63. }
  64. return value;
  65. } else {
  66. //Log.warn(`Lookup for unset variable: ${name}`);
  67. }
  68. }
  69. connectSync(...args) {
  70. if (!this._connectSync) {
  71. this._connectSync = Meteor.wrapAsync(this.connectAsync, this);
  72. }
  73. return this._connectSync(...args);
  74. }
  75. searchAllSync(...args) {
  76. if (!this._searchAllSync) {
  77. this._searchAllSync = Meteor.wrapAsync(this.searchAllAsync, this);
  78. }
  79. return this._searchAllSync(...args);
  80. }
  81. connectAsync(callback) {
  82. Log.info('Init setup');
  83. let replied = false;
  84. const connectionOptions = {
  85. url : `${this.options.host}:${this.options.port}`,
  86. timeout : this.options.timeout,
  87. connectTimeout: this.options.connect_timeout,
  88. idleTimeout : this.options.idle_timeout,
  89. reconnect : this.options.Reconnect,
  90. };
  91. const tlsOptions = {
  92. rejectUnauthorized: this.options.reject_unauthorized,
  93. };
  94. if (this.options.ca_cert && this.options.ca_cert !== '') {
  95. // Split CA cert into array of strings
  96. const chainLines = this.constructor.settings_get('LDAP_CA_CERT').replace(/\\n/g,'\n').split('\n');
  97. let cert = [];
  98. const ca = [];
  99. chainLines.forEach((line) => {
  100. cert.push(line);
  101. if (line.match(/-END CERTIFICATE-/)) {
  102. ca.push(cert.join('\n'));
  103. cert = [];
  104. }
  105. });
  106. tlsOptions.ca = ca;
  107. }
  108. if (this.options.encryption === 'ssl') {
  109. connectionOptions.url = `ldaps://${connectionOptions.url}`;
  110. connectionOptions.tlsOptions = tlsOptions;
  111. } else {
  112. connectionOptions.url = `ldap://${connectionOptions.url}`;
  113. }
  114. Log.info(`Connecting ${connectionOptions.url}`);
  115. Log.debug(`connectionOptions ${JSON.stringify(connectionOptions)}`);
  116. this.client = ldapjs.createClient(connectionOptions);
  117. this.bindSync = Meteor.wrapAsync(this.client.bind, this.client);
  118. this.client.on('error', (error) => {
  119. Log.error(`connection ${error}`);
  120. if (replied === false) {
  121. replied = true;
  122. callback(error, null);
  123. }
  124. });
  125. this.client.on('idle', () => {
  126. Log.info('Idle');
  127. this.disconnect();
  128. });
  129. this.client.on('close', () => {
  130. Log.info('Closed');
  131. });
  132. if (this.options.encryption === 'tls') {
  133. // Set host parameter for tls.connect which is used by ldapjs starttls. This shouldn't be needed in newer nodejs versions (e.g v5.6.0).
  134. // https://github.com/RocketChat/Rocket.Chat/issues/2035
  135. // https://github.com/mcavage/node-ldapjs/issues/349
  136. tlsOptions.host = this.options.host;
  137. Log.info('Starting TLS');
  138. Log.debug(`tlsOptions ${JSON.stringify(tlsOptions)}`);
  139. this.client.starttls(tlsOptions, null, (error, response) => {
  140. if (error) {
  141. Log.error(`TLS connection ${JSON.stringify(error)}`);
  142. if (replied === false) {
  143. replied = true;
  144. callback(error, null);
  145. }
  146. return;
  147. }
  148. Log.info('TLS connected');
  149. this.connected = true;
  150. if (replied === false) {
  151. replied = true;
  152. callback(null, response);
  153. }
  154. });
  155. } else {
  156. this.client.on('connect', (response) => {
  157. Log.info('LDAP connected');
  158. this.connected = true;
  159. if (replied === false) {
  160. replied = true;
  161. callback(null, response);
  162. }
  163. });
  164. }
  165. setTimeout(() => {
  166. if (replied === false) {
  167. Log.error(`connection time out ${connectionOptions.connectTimeout}`);
  168. replied = true;
  169. callback(new Error('Timeout'));
  170. }
  171. }, connectionOptions.connectTimeout);
  172. }
  173. getUserFilter(username) {
  174. const filter = [];
  175. if (this.options.User_Search_Filter !== '') {
  176. if (this.options.User_Search_Filter[0] === '(') {
  177. filter.push(`${this.options.User_Search_Filter}`);
  178. } else {
  179. filter.push(`(${this.options.User_Search_Filter})`);
  180. }
  181. }
  182. const usernameFilter = this.options.User_Search_Field.split(',').map((item) => `(${item}=${username})`);
  183. if (usernameFilter.length === 0) {
  184. Log.error('LDAP_LDAP_User_Search_Field not defined');
  185. } else if (usernameFilter.length === 1) {
  186. filter.push(`${usernameFilter[0]}`);
  187. } else {
  188. filter.push(`(|${usernameFilter.join('')})`);
  189. }
  190. return `(&${filter.join('')})`;
  191. }
  192. bindUserIfNecessary(username, password) {
  193. if (this.domainBinded === true) {
  194. return;
  195. }
  196. if (!this.options.User_Authentication) {
  197. return;
  198. }
  199. /* if SimpleAuth is configured, the BaseDN is not needed */
  200. if (!this.options.BaseDN && !this.options.AD_Simple_Auth) throw new Error('BaseDN is not provided');
  201. var userDn = "";
  202. if (this.options.AD_Simple_Auth === true || this.options.AD_Simple_Auth === 'true') {
  203. userDn = `${username}@${this.options.Default_Domain}`;
  204. } else {
  205. userDn = `${this.options.User_Authentication_Field}=${username},${this.options.BaseDN}`;
  206. }
  207. Log.info(`Binding with User ${userDn}`);
  208. this.bindSync(userDn, password);
  209. this.domainBinded = true;
  210. }
  211. bindIfNecessary() {
  212. if (this.domainBinded === true) {
  213. return;
  214. }
  215. if (this.options.Authentication !== true) {
  216. return;
  217. }
  218. Log.info(`Binding UserDN ${this.options.Authentication_UserDN}`);
  219. this.bindSync(this.options.Authentication_UserDN, this.options.Authentication_Password);
  220. this.domainBinded = true;
  221. }
  222. searchUsersSync(username, page) {
  223. this.bindIfNecessary();
  224. const searchOptions = {
  225. filter : this.getUserFilter(username),
  226. scope : this.options.User_Search_Scope || 'sub',
  227. sizeLimit: this.options.Search_Size_Limit,
  228. };
  229. if (!!this.options.User_Attributes) searchOptions.attributes = this.options.User_Attributes.split(',');
  230. if (this.options.Search_Page_Size > 0) {
  231. searchOptions.paged = {
  232. pageSize : this.options.Search_Page_Size,
  233. pagePause: !!page,
  234. };
  235. }
  236. Log.info(`Searching user ${username}`);
  237. Log.debug(`searchOptions ${searchOptions}`);
  238. Log.debug(`BaseDN ${this.options.BaseDN}`);
  239. if (page) {
  240. return this.searchAllPaged(this.options.BaseDN, searchOptions, page);
  241. }
  242. return this.searchAllSync(this.options.BaseDN, searchOptions);
  243. }
  244. getUserByIdSync(id, attribute) {
  245. this.bindIfNecessary();
  246. const Unique_Identifier_Field = this.constructor.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD').split(',');
  247. let filter;
  248. if (attribute) {
  249. filter = new this.ldapjs.filters.EqualityFilter({
  250. attribute,
  251. value: Buffer.from(id, 'hex'),
  252. });
  253. } else {
  254. const filters = [];
  255. Unique_Identifier_Field.forEach((item) => {
  256. filters.push(new this.ldapjs.filters.EqualityFilter({
  257. attribute: item,
  258. value : Buffer.from(id, 'hex'),
  259. }));
  260. });
  261. filter = new this.ldapjs.filters.OrFilter({ filters });
  262. }
  263. const searchOptions = {
  264. filter,
  265. scope: 'sub',
  266. };
  267. Log.info(`Searching by id ${id}`);
  268. Log.debug(`search filter ${searchOptions.filter.toString()}`);
  269. Log.debug(`BaseDN ${this.options.BaseDN}`);
  270. const result = this.searchAllSync(this.options.BaseDN, searchOptions);
  271. if (!Array.isArray(result) || result.length === 0) {
  272. return;
  273. }
  274. if (result.length > 1) {
  275. Log.error(`Search by id ${id} returned ${result.length} records`);
  276. }
  277. return result[0];
  278. }
  279. getUserByUsernameSync(username) {
  280. this.bindIfNecessary();
  281. const searchOptions = {
  282. filter: this.getUserFilter(username),
  283. scope : this.options.User_Search_Scope || 'sub',
  284. };
  285. Log.info(`Searching user ${username}`);
  286. Log.debug(`searchOptions ${searchOptions}`);
  287. Log.debug(`BaseDN ${this.options.BaseDN}`);
  288. const result = this.searchAllSync(this.options.BaseDN, searchOptions);
  289. if (!Array.isArray(result) || result.length === 0) {
  290. return;
  291. }
  292. if (result.length > 1) {
  293. Log.error(`Search by username ${username} returned ${result.length} records`);
  294. }
  295. return result[0];
  296. }
  297. getUserGroups(username, ldapUser) {
  298. if (!this.options.group_filter_enabled) {
  299. return true;
  300. }
  301. const filter = ['(&'];
  302. if (this.options.group_filter_object_class !== '') {
  303. filter.push(`(objectclass=${this.options.group_filter_object_class})`);
  304. }
  305. if (this.options.group_filter_group_member_attribute !== '') {
  306. const format_value = ldapUser[this.options.group_filter_group_member_format];
  307. if (format_value) {
  308. filter.push(`(${this.options.group_filter_group_member_attribute}=${format_value})`);
  309. }
  310. }
  311. filter.push(')');
  312. const searchOptions = {
  313. filter: filter.join('').replace(/#{username}/g, username).replace("\\", "\\\\"),
  314. scope : 'sub',
  315. };
  316. Log.debug(`Group list filter LDAP: ${searchOptions.filter}`);
  317. const result = this.searchAllSync(this.options.BaseDN, searchOptions);
  318. if (!Array.isArray(result) || result.length === 0) {
  319. return [];
  320. }
  321. const grp_identifier = this.options.group_filter_group_id_attribute || 'cn';
  322. const groups = [];
  323. result.map((item) => {
  324. groups.push(item[grp_identifier]);
  325. });
  326. Log.debug(`Groups: ${groups.join(', ')}`);
  327. return groups;
  328. }
  329. isUserInGroup(username, ldapUser) {
  330. if (!this.options.group_filter_enabled) {
  331. return true;
  332. }
  333. const grps = this.getUserGroups(username, ldapUser);
  334. const filter = ['(&'];
  335. if (this.options.group_filter_object_class !== '') {
  336. filter.push(`(objectclass=${this.options.group_filter_object_class})`);
  337. }
  338. if (this.options.group_filter_group_member_attribute !== '') {
  339. const format_value = ldapUser[this.options.group_filter_group_member_format];
  340. if (format_value) {
  341. filter.push(`(${this.options.group_filter_group_member_attribute}=${format_value})`);
  342. }
  343. }
  344. if (this.options.group_filter_group_id_attribute !== '') {
  345. filter.push(`(${this.options.group_filter_group_id_attribute}=${this.options.group_filter_group_name})`);
  346. }
  347. filter.push(')');
  348. const searchOptions = {
  349. filter: filter.join('').replace(/#{username}/g, username).replace("\\", "\\\\"),
  350. scope : 'sub',
  351. };
  352. Log.debug(`Group filter LDAP: ${searchOptions.filter}`);
  353. const result = this.searchAllSync(this.options.BaseDN, searchOptions);
  354. if (!Array.isArray(result) || result.length === 0) {
  355. return false;
  356. }
  357. return true;
  358. }
  359. extractLdapEntryData(entry) {
  360. const values = {
  361. _raw: entry.raw,
  362. };
  363. Object.keys(values._raw).forEach((key) => {
  364. const value = values._raw[key];
  365. if (!['thumbnailPhoto', 'jpegPhoto'].includes(key)) {
  366. if (value instanceof Buffer) {
  367. values[key] = value.toString();
  368. } else {
  369. values[key] = value;
  370. }
  371. }
  372. });
  373. return values;
  374. }
  375. searchAllPaged(BaseDN, options, page) {
  376. this.bindIfNecessary();
  377. const processPage = ({ entries, title, end, next }) => {
  378. Log.info(title);
  379. // Force LDAP idle to wait the record processing
  380. this.client._updateIdle(true);
  381. page(null, entries, {
  382. end, next: () => {
  383. // Reset idle timer
  384. this.client._updateIdle();
  385. next && next();
  386. }
  387. });
  388. };
  389. this.client.search(BaseDN, options, (error, res) => {
  390. if (error) {
  391. Log.error(error);
  392. page(error);
  393. return;
  394. }
  395. res.on('error', (error) => {
  396. Log.error(error);
  397. page(error);
  398. return;
  399. });
  400. let entries = [];
  401. const internalPageSize = options.paged && options.paged.pageSize > 0 ? options.paged.pageSize * 2 : 500;
  402. res.on('searchEntry', (entry) => {
  403. entries.push(this.extractLdapEntryData(entry));
  404. if (entries.length >= internalPageSize) {
  405. processPage({
  406. entries,
  407. title: 'Internal Page',
  408. end : false,
  409. });
  410. entries = [];
  411. }
  412. });
  413. res.on('page', (result, next) => {
  414. if (!next) {
  415. this.client._updateIdle(true);
  416. processPage({
  417. entries,
  418. title: 'Final Page',
  419. end : true,
  420. });
  421. } else if (entries.length) {
  422. Log.info('Page');
  423. processPage({
  424. entries,
  425. title: 'Page',
  426. end : false,
  427. next,
  428. });
  429. entries = [];
  430. }
  431. });
  432. res.on('end', () => {
  433. if (entries.length) {
  434. processPage({
  435. entries,
  436. title: 'Final Page',
  437. end : true,
  438. });
  439. entries = [];
  440. }
  441. });
  442. });
  443. }
  444. searchAllAsync(BaseDN, options, callback) {
  445. this.bindIfNecessary();
  446. this.client.search(BaseDN, options, (error, res) => {
  447. if (error) {
  448. Log.error(error);
  449. callback(error);
  450. return;
  451. }
  452. res.on('error', (error) => {
  453. Log.error(error);
  454. callback(error);
  455. return;
  456. });
  457. const entries = [];
  458. res.on('searchEntry', (entry) => {
  459. entries.push(this.extractLdapEntryData(entry));
  460. });
  461. res.on('end', () => {
  462. Log.info(`Search result count ${entries.length}`);
  463. callback(null, entries);
  464. });
  465. });
  466. }
  467. authSync(dn, password) {
  468. Log.info(`Authenticating ${dn}`);
  469. try {
  470. if (password === '') {
  471. throw new Error('Password is not provided');
  472. }
  473. this.bindSync(dn, password);
  474. Log.info(`Authenticated ${dn}`);
  475. return true;
  476. } catch (error) {
  477. Log.info(`Not authenticated ${dn}`);
  478. Log.debug('error', error);
  479. return false;
  480. }
  481. }
  482. disconnect() {
  483. this.connected = false;
  484. this.domainBinded = false;
  485. Log.info('Disconecting');
  486. this.client.unbind();
  487. }
  488. }