Helper.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. * This is used and done to have a stable format of DNs that can be compared
  182. * and identified again. The input DN value is modified as following:
  183. *
  184. * 1) whitespaces after commas are removed
  185. * 2) the DN is turned to lower-case
  186. * 3) the DN is escaped according to RFC 2253
  187. *
  188. * When a future DN is supposed to be used as a base parameter, it has to be
  189. * run through DNasBaseParameter() first, to recode \5c into a backslash
  190. * again, otherwise the search or read operation will fail with LDAP error
  191. * 32, NO_SUCH_OBJECT. Regular usage in LDAP filters requires the backslash
  192. * being escaped, however.
  193. *
  194. * Internally, DNs are stored in their sanitized form.
  195. *
  196. * @param array|string $dn the DN in question
  197. * @return array|string the sanitized DN
  198. */
  199. public function sanitizeDN($dn) {
  200. //treating multiple base DNs
  201. if (is_array($dn)) {
  202. $result = [];
  203. foreach ($dn as $singleDN) {
  204. $result[] = $this->sanitizeDN($singleDN);
  205. }
  206. return $result;
  207. }
  208. if (!is_string($dn)) {
  209. throw new \LogicException('String expected ' . \gettype($dn) . ' given');
  210. }
  211. if (($sanitizedDn = $this->sanitizeDnCache->get($dn)) !== null) {
  212. return $sanitizedDn;
  213. }
  214. //OID sometimes gives back DNs with whitespace after the comma
  215. // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
  216. $sanitizedDn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
  217. //make comparisons and everything work
  218. $sanitizedDn = mb_strtolower($sanitizedDn, 'UTF-8');
  219. //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
  220. //to use the DN in search filters, \ needs to be escaped to \5c additionally
  221. //to use them in bases, we convert them back to simple backslashes in readAttribute()
  222. $replacements = [
  223. '\,' => '\5c2C',
  224. '\=' => '\5c3D',
  225. '\+' => '\5c2B',
  226. '\<' => '\5c3C',
  227. '\>' => '\5c3E',
  228. '\;' => '\5c3B',
  229. '\"' => '\5c22',
  230. '\#' => '\5c23',
  231. '(' => '\28',
  232. ')' => '\29',
  233. '*' => '\2A',
  234. ];
  235. $sanitizedDn = str_replace(array_keys($replacements), array_values($replacements), $sanitizedDn);
  236. $this->sanitizeDnCache->set($dn, $sanitizedDn);
  237. return $sanitizedDn;
  238. }
  239. /**
  240. * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
  241. *
  242. * @param string $dn the DN
  243. * @return string
  244. */
  245. public function DNasBaseParameter($dn) {
  246. return str_ireplace('\\5c', '\\', $dn);
  247. }
  248. /**
  249. * listens to a hook thrown by server2server sharing and replaces the given
  250. * login name by a username, if it matches an LDAP user.
  251. *
  252. * @param array $param contains a reference to a $uid var under 'uid' key
  253. * @throws \Exception
  254. */
  255. public static function loginName2UserName($param): void {
  256. if (!isset($param['uid'])) {
  257. throw new \Exception('key uid is expected to be set in $param');
  258. }
  259. $userBackend = \OC::$server->get(User_Proxy::class);
  260. $uid = $userBackend->loginName2UserName($param['uid']);
  261. if ($uid !== false) {
  262. $param['uid'] = $uid;
  263. }
  264. }
  265. }