Helper.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author root <root@localhost.localdomain>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\User_LDAP;
  31. use OCP\Cache\CappedMemoryCache;
  32. use OCP\DB\QueryBuilder\IQueryBuilder;
  33. use OCP\IConfig;
  34. use OCP\IDBConnection;
  35. class Helper {
  36. private IConfig $config;
  37. private IDBConnection $connection;
  38. /** @var CappedMemoryCache<string> */
  39. protected CappedMemoryCache $sanitizeDnCache;
  40. public function __construct(IConfig $config,
  41. IDBConnection $connection) {
  42. $this->config = $config;
  43. $this->connection = $connection;
  44. $this->sanitizeDnCache = new CappedMemoryCache(10000);
  45. }
  46. /**
  47. * returns prefixes for each saved LDAP/AD server configuration.
  48. *
  49. * @param bool $activeConfigurations optional, whether only active configuration shall be
  50. * retrieved, defaults to false
  51. * @return array with a list of the available prefixes
  52. *
  53. * Configuration prefixes are used to set up configurations for n LDAP or
  54. * AD servers. Since configuration is stored in the database, table
  55. * appconfig under appid user_ldap, the common identifiers in column
  56. * 'configkey' have a prefix. The prefix for the very first server
  57. * configuration is empty.
  58. * Configkey Examples:
  59. * Server 1: ldap_login_filter
  60. * Server 2: s1_ldap_login_filter
  61. * Server 3: s2_ldap_login_filter
  62. *
  63. * The prefix needs to be passed to the constructor of Connection class,
  64. * except the default (first) server shall be connected to.
  65. *
  66. */
  67. public function getServerConfigurationPrefixes($activeConfigurations = false): array {
  68. $referenceConfigkey = 'ldap_configuration_active';
  69. $keys = $this->getServersConfig($referenceConfigkey);
  70. $prefixes = [];
  71. foreach ($keys as $key) {
  72. if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
  73. continue;
  74. }
  75. $len = strlen($key) - strlen($referenceConfigkey);
  76. $prefixes[] = substr($key, 0, $len);
  77. }
  78. asort($prefixes);
  79. return $prefixes;
  80. }
  81. /**
  82. *
  83. * determines the host for every configured connection
  84. *
  85. * @return array an array with configprefix as keys
  86. *
  87. */
  88. public function getServerConfigurationHosts() {
  89. $referenceConfigkey = 'ldap_host';
  90. $keys = $this->getServersConfig($referenceConfigkey);
  91. $result = [];
  92. foreach ($keys as $key) {
  93. $len = strlen($key) - strlen($referenceConfigkey);
  94. $prefix = substr($key, 0, $len);
  95. $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
  96. }
  97. return $result;
  98. }
  99. /**
  100. * return the next available configuration prefix
  101. *
  102. * @return string
  103. */
  104. public function getNextServerConfigurationPrefix() {
  105. $serverConnections = $this->getServerConfigurationPrefixes();
  106. if (count($serverConnections) === 0) {
  107. return 's01';
  108. }
  109. sort($serverConnections);
  110. $lastKey = array_pop($serverConnections);
  111. $lastNumber = (int)str_replace('s', '', $lastKey);
  112. return 's' . str_pad((string)($lastNumber + 1), 2, '0', STR_PAD_LEFT);
  113. }
  114. private function getServersConfig(string $value): array {
  115. $regex = '/' . $value . '$/S';
  116. $keys = $this->config->getAppKeys('user_ldap');
  117. $result = [];
  118. foreach ($keys as $key) {
  119. if (preg_match($regex, $key) === 1) {
  120. $result[] = $key;
  121. }
  122. }
  123. return $result;
  124. }
  125. /**
  126. * deletes a given saved LDAP/AD server configuration.
  127. *
  128. * @param string $prefix the configuration prefix of the config to delete
  129. * @return bool true on success, false otherwise
  130. */
  131. public function deleteServerConfiguration($prefix) {
  132. if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
  133. return false;
  134. }
  135. $query = $this->connection->getQueryBuilder();
  136. $query->delete('appconfig')
  137. ->where($query->expr()->eq('appid', $query->createNamedParameter('user_ldap')))
  138. ->andWhere($query->expr()->like('configkey', $query->createNamedParameter((string)$prefix . '%')))
  139. ->andWhere($query->expr()->notIn('configkey', $query->createNamedParameter([
  140. 'enabled',
  141. 'installed_version',
  142. 'types',
  143. 'bgjUpdateGroupsLastRun',
  144. ], IQueryBuilder::PARAM_STR_ARRAY)));
  145. if (empty($prefix)) {
  146. $query->andWhere($query->expr()->notLike('configkey', $query->createNamedParameter('s%')));
  147. }
  148. $deletedRows = $query->execute();
  149. return $deletedRows !== 0;
  150. }
  151. /**
  152. * checks whether there is one or more disabled LDAP configurations
  153. */
  154. public function haveDisabledConfigurations(): bool {
  155. $all = $this->getServerConfigurationPrefixes(false);
  156. $active = $this->getServerConfigurationPrefixes(true);
  157. return count($all) !== count($active) || count($all) === 0;
  158. }
  159. /**
  160. * extracts the domain from a given URL
  161. *
  162. * @param string $url the URL
  163. * @return string|false domain as string on success, false otherwise
  164. */
  165. public function getDomainFromURL($url) {
  166. $uinfo = parse_url($url);
  167. if (!is_array($uinfo)) {
  168. return false;
  169. }
  170. $domain = false;
  171. if (isset($uinfo['host'])) {
  172. $domain = $uinfo['host'];
  173. } elseif (isset($uinfo['path'])) {
  174. $domain = $uinfo['path'];
  175. }
  176. return $domain;
  177. }
  178. /**
  179. * sanitizes a DN received from the LDAP server
  180. *
  181. * @param array|string $dn the DN in question
  182. * @return array|string the sanitized DN
  183. */
  184. public function sanitizeDN($dn) {
  185. //treating multiple base DNs
  186. if (is_array($dn)) {
  187. $result = [];
  188. foreach ($dn as $singleDN) {
  189. $result[] = $this->sanitizeDN($singleDN);
  190. }
  191. return $result;
  192. }
  193. if (!is_string($dn)) {
  194. throw new \LogicException('String expected ' . \gettype($dn) . ' given');
  195. }
  196. if (($sanitizedDn = $this->sanitizeDnCache->get($dn)) !== null) {
  197. return $sanitizedDn;
  198. }
  199. //OID sometimes gives back DNs with whitespace after the comma
  200. // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
  201. $sanitizedDn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
  202. //make comparisons and everything work
  203. $sanitizedDn = mb_strtolower($sanitizedDn, 'UTF-8');
  204. //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
  205. //to use the DN in search filters, \ needs to be escaped to \5c additionally
  206. //to use them in bases, we convert them back to simple backslashes in readAttribute()
  207. $replacements = [
  208. '\,' => '\5c2C',
  209. '\=' => '\5c3D',
  210. '\+' => '\5c2B',
  211. '\<' => '\5c3C',
  212. '\>' => '\5c3E',
  213. '\;' => '\5c3B',
  214. '\"' => '\5c22',
  215. '\#' => '\5c23',
  216. '(' => '\28',
  217. ')' => '\29',
  218. '*' => '\2A',
  219. ];
  220. $sanitizedDn = str_replace(array_keys($replacements), array_values($replacements), $sanitizedDn);
  221. $this->sanitizeDnCache->set($dn, $sanitizedDn);
  222. return $sanitizedDn;
  223. }
  224. /**
  225. * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
  226. *
  227. * @param string $dn the DN
  228. * @return string
  229. */
  230. public function DNasBaseParameter($dn) {
  231. return str_ireplace('\\5c', '\\', $dn);
  232. }
  233. /**
  234. * listens to a hook thrown by server2server sharing and replaces the given
  235. * login name by a username, if it matches an LDAP user.
  236. *
  237. * @param array $param contains a reference to a $uid var under 'uid' key
  238. * @throws \Exception
  239. */
  240. public static function loginName2UserName($param): void {
  241. if (!isset($param['uid'])) {
  242. throw new \Exception('key uid is expected to be set in $param');
  243. }
  244. $userBackend = \OC::$server->get(User_Proxy::class);
  245. $uid = $userBackend->loginName2UserName($param['uid']);
  246. if ($uid !== false) {
  247. $param['uid'] = $uid;
  248. }
  249. }
  250. }