Helper.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\User_LDAP;
  8. use OCP\Cache\CappedMemoryCache;
  9. use OCP\DB\QueryBuilder\IQueryBuilder;
  10. use OCP\IConfig;
  11. use OCP\IDBConnection;
  12. class Helper {
  13. private IConfig $config;
  14. private IDBConnection $connection;
  15. /** @var CappedMemoryCache<string> */
  16. protected CappedMemoryCache $sanitizeDnCache;
  17. public function __construct(IConfig $config,
  18. IDBConnection $connection) {
  19. $this->config = $config;
  20. $this->connection = $connection;
  21. $this->sanitizeDnCache = new CappedMemoryCache(10000);
  22. }
  23. /**
  24. * returns prefixes for each saved LDAP/AD server configuration.
  25. *
  26. * @param bool $activeConfigurations optional, whether only active configuration shall be
  27. * retrieved, defaults to false
  28. * @return array with a list of the available prefixes
  29. *
  30. * Configuration prefixes are used to set up configurations for n LDAP or
  31. * AD servers. Since configuration is stored in the database, table
  32. * appconfig under appid user_ldap, the common identifiers in column
  33. * 'configkey' have a prefix. The prefix for the very first server
  34. * configuration is empty.
  35. * Configkey Examples:
  36. * Server 1: ldap_login_filter
  37. * Server 2: s1_ldap_login_filter
  38. * Server 3: s2_ldap_login_filter
  39. *
  40. * The prefix needs to be passed to the constructor of Connection class,
  41. * except the default (first) server shall be connected to.
  42. *
  43. */
  44. public function getServerConfigurationPrefixes($activeConfigurations = false): array {
  45. $referenceConfigkey = 'ldap_configuration_active';
  46. $keys = $this->getServersConfig($referenceConfigkey);
  47. $prefixes = [];
  48. foreach ($keys as $key) {
  49. if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
  50. continue;
  51. }
  52. $len = strlen($key) - strlen($referenceConfigkey);
  53. $prefixes[] = substr($key, 0, $len);
  54. }
  55. asort($prefixes);
  56. return $prefixes;
  57. }
  58. /**
  59. *
  60. * determines the host for every configured connection
  61. *
  62. * @return array an array with configprefix as keys
  63. *
  64. */
  65. public function getServerConfigurationHosts() {
  66. $referenceConfigkey = 'ldap_host';
  67. $keys = $this->getServersConfig($referenceConfigkey);
  68. $result = [];
  69. foreach ($keys as $key) {
  70. $len = strlen($key) - strlen($referenceConfigkey);
  71. $prefix = substr($key, 0, $len);
  72. $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
  73. }
  74. return $result;
  75. }
  76. /**
  77. * return the next available configuration prefix
  78. *
  79. * @return string
  80. */
  81. public function getNextServerConfigurationPrefix() {
  82. $serverConnections = $this->getServerConfigurationPrefixes();
  83. if (count($serverConnections) === 0) {
  84. return 's01';
  85. }
  86. sort($serverConnections);
  87. $lastKey = array_pop($serverConnections);
  88. $lastNumber = (int)str_replace('s', '', $lastKey);
  89. return 's' . str_pad((string)($lastNumber + 1), 2, '0', STR_PAD_LEFT);
  90. }
  91. private function getServersConfig(string $value): array {
  92. $regex = '/' . $value . '$/S';
  93. $keys = $this->config->getAppKeys('user_ldap');
  94. $result = [];
  95. foreach ($keys as $key) {
  96. if (preg_match($regex, $key) === 1) {
  97. $result[] = $key;
  98. }
  99. }
  100. return $result;
  101. }
  102. /**
  103. * deletes a given saved LDAP/AD server configuration.
  104. *
  105. * @param string $prefix the configuration prefix of the config to delete
  106. * @return bool true on success, false otherwise
  107. */
  108. public function deleteServerConfiguration($prefix) {
  109. if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
  110. return false;
  111. }
  112. $query = $this->connection->getQueryBuilder();
  113. $query->delete('appconfig')
  114. ->where($query->expr()->eq('appid', $query->createNamedParameter('user_ldap')))
  115. ->andWhere($query->expr()->like('configkey', $query->createNamedParameter((string)$prefix . '%')))
  116. ->andWhere($query->expr()->notIn('configkey', $query->createNamedParameter([
  117. 'enabled',
  118. 'installed_version',
  119. 'types',
  120. 'bgjUpdateGroupsLastRun',
  121. ], IQueryBuilder::PARAM_STR_ARRAY)));
  122. if (empty($prefix)) {
  123. $query->andWhere($query->expr()->notLike('configkey', $query->createNamedParameter('s%')));
  124. }
  125. $deletedRows = $query->execute();
  126. return $deletedRows !== 0;
  127. }
  128. /**
  129. * checks whether there is one or more disabled LDAP configurations
  130. */
  131. public function haveDisabledConfigurations(): bool {
  132. $all = $this->getServerConfigurationPrefixes(false);
  133. $active = $this->getServerConfigurationPrefixes(true);
  134. return count($all) !== count($active) || count($all) === 0;
  135. }
  136. /**
  137. * extracts the domain from a given URL
  138. *
  139. * @param string $url the URL
  140. * @return string|false domain as string on success, false otherwise
  141. */
  142. public function getDomainFromURL($url) {
  143. $uinfo = parse_url($url);
  144. if (!is_array($uinfo)) {
  145. return false;
  146. }
  147. $domain = false;
  148. if (isset($uinfo['host'])) {
  149. $domain = $uinfo['host'];
  150. } elseif (isset($uinfo['path'])) {
  151. $domain = $uinfo['path'];
  152. }
  153. return $domain;
  154. }
  155. /**
  156. * sanitizes a DN received from the LDAP server
  157. *
  158. * This is used and done to have a stable format of DNs that can be compared
  159. * and identified again. The input DN value is modified as following:
  160. *
  161. * 1) whitespaces after commas are removed
  162. * 2) the DN is turned to lower-case
  163. * 3) the DN is escaped according to RFC 2253
  164. *
  165. * When a future DN is supposed to be used as a base parameter, it has to be
  166. * run through DNasBaseParameter() first, to recode \5c into a backslash
  167. * again, otherwise the search or read operation will fail with LDAP error
  168. * 32, NO_SUCH_OBJECT. Regular usage in LDAP filters requires the backslash
  169. * being escaped, however.
  170. *
  171. * Internally, DNs are stored in their sanitized form.
  172. *
  173. * @param array|string $dn the DN in question
  174. * @return array|string the sanitized DN
  175. */
  176. public function sanitizeDN($dn) {
  177. //treating multiple base DNs
  178. if (is_array($dn)) {
  179. $result = [];
  180. foreach ($dn as $singleDN) {
  181. $result[] = $this->sanitizeDN($singleDN);
  182. }
  183. return $result;
  184. }
  185. if (!is_string($dn)) {
  186. throw new \LogicException('String expected ' . \gettype($dn) . ' given');
  187. }
  188. if (($sanitizedDn = $this->sanitizeDnCache->get($dn)) !== null) {
  189. return $sanitizedDn;
  190. }
  191. //OID sometimes gives back DNs with whitespace after the comma
  192. // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
  193. $sanitizedDn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
  194. //make comparisons and everything work
  195. $sanitizedDn = mb_strtolower($sanitizedDn, 'UTF-8');
  196. //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
  197. //to use the DN in search filters, \ needs to be escaped to \5c additionally
  198. //to use them in bases, we convert them back to simple backslashes in readAttribute()
  199. $replacements = [
  200. '\,' => '\5c2C',
  201. '\=' => '\5c3D',
  202. '\+' => '\5c2B',
  203. '\<' => '\5c3C',
  204. '\>' => '\5c3E',
  205. '\;' => '\5c3B',
  206. '\"' => '\5c22',
  207. '\#' => '\5c23',
  208. '(' => '\28',
  209. ')' => '\29',
  210. '*' => '\2A',
  211. ];
  212. $sanitizedDn = str_replace(array_keys($replacements), array_values($replacements), $sanitizedDn);
  213. $this->sanitizeDnCache->set($dn, $sanitizedDn);
  214. return $sanitizedDn;
  215. }
  216. /**
  217. * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
  218. *
  219. * @param string $dn the DN
  220. * @return string
  221. */
  222. public function DNasBaseParameter($dn) {
  223. return str_ireplace('\\5c', '\\', $dn);
  224. }
  225. /**
  226. * listens to a hook thrown by server2server sharing and replaces the given
  227. * login name by a username, if it matches an LDAP user.
  228. *
  229. * @param array $param contains a reference to a $uid var under 'uid' key
  230. * @throws \Exception
  231. */
  232. public static function loginName2UserName($param): void {
  233. if (!isset($param['uid'])) {
  234. throw new \Exception('key uid is expected to be set in $param');
  235. }
  236. $userBackend = \OC::$server->get(User_Proxy::class);
  237. $uid = $userBackend->loginName2UserName($param['uid']);
  238. if ($uid !== false) {
  239. $param['uid'] = $uid;
  240. }
  241. }
  242. }