ldap.js 18 KB

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