ldap.js 18 KB

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