ldap.js 17 KB

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