You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Helper.php 8.4KB

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