ldap.js 18 KB

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