Helper.php 8.2 KB

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