Helper.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 OCP\IConfig;
  36. class Helper {
  37. /** @var IConfig */
  38. private $config;
  39. /**
  40. * Helper constructor.
  41. *
  42. * @param IConfig $config
  43. */
  44. public function __construct(IConfig $config) {
  45. $this->config = $config;
  46. }
  47. /**
  48. * returns prefixes for each saved LDAP/AD server configuration.
  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) {
  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. * @return array an array with configprefix as keys
  85. *
  86. */
  87. public function getServerConfigurationHosts() {
  88. $referenceConfigkey = 'ldap_host';
  89. $keys = $this->getServersConfig($referenceConfigkey);
  90. $result = [];
  91. foreach($keys as $key) {
  92. $len = strlen($key) - strlen($referenceConfigkey);
  93. $prefix = substr($key, 0, $len);
  94. $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
  95. }
  96. return $result;
  97. }
  98. /**
  99. * return the next available configuration prefix
  100. *
  101. * @return string
  102. */
  103. public function getNextServerConfigurationPrefix() {
  104. $serverConnections = $this->getServerConfigurationPrefixes();
  105. if(count($serverConnections) === 0) {
  106. return 's01';
  107. }
  108. sort($serverConnections);
  109. $lastKey = array_pop($serverConnections);
  110. $lastNumber = (int)str_replace('s', '', $lastKey);
  111. return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
  112. }
  113. private function getServersConfig($value) {
  114. $regex = '/' . $value . '$/S';
  115. $keys = $this->config->getAppKeys('user_ldap');
  116. $result = [];
  117. foreach ($keys as $key) {
  118. if (preg_match($regex, $key) === 1) {
  119. $result[] = $key;
  120. }
  121. }
  122. return $result;
  123. }
  124. /**
  125. * deletes a given saved LDAP/AD server configuration.
  126. * @param string $prefix the configuration prefix of the config to delete
  127. * @return bool true on success, false otherwise
  128. */
  129. public function deleteServerConfiguration($prefix) {
  130. if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
  131. return false;
  132. }
  133. $saveOtherConfigurations = '';
  134. if(empty($prefix)) {
  135. $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
  136. }
  137. $query = \OC_DB::prepare('
  138. DELETE
  139. FROM `*PREFIX*appconfig`
  140. WHERE `configkey` LIKE ?
  141. '.$saveOtherConfigurations.'
  142. AND `appid` = \'user_ldap\'
  143. AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\')
  144. ');
  145. $delRows = $query->execute([$prefix.'%']);
  146. if($delRows === null) {
  147. return false;
  148. }
  149. if($delRows === 0) {
  150. return false;
  151. }
  152. return true;
  153. }
  154. /**
  155. * checks whether there is one or more disabled LDAP configurations
  156. * @throws \Exception
  157. * @return bool
  158. */
  159. public function haveDisabledConfigurations() {
  160. $all = $this->getServerConfigurationPrefixes(false);
  161. $active = $this->getServerConfigurationPrefixes(true);
  162. if(!is_array($all) || !is_array($active)) {
  163. throw new \Exception('Unexpected Return Value');
  164. }
  165. return count($all) !== count($active) || count($all) === 0;
  166. }
  167. /**
  168. * extracts the domain from a given URL
  169. * @param string $url the URL
  170. * @return string|false domain as string on success, false otherwise
  171. */
  172. public function getDomainFromURL($url) {
  173. $uinfo = parse_url($url);
  174. if(!is_array($uinfo)) {
  175. return false;
  176. }
  177. $domain = false;
  178. if(isset($uinfo['host'])) {
  179. $domain = $uinfo['host'];
  180. } else if(isset($uinfo['path'])) {
  181. $domain = $uinfo['path'];
  182. }
  183. return $domain;
  184. }
  185. /**
  186. *
  187. * Set the LDAPProvider in the config
  188. *
  189. */
  190. public function setLDAPProvider() {
  191. $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
  192. if(is_null($current)) {
  193. \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class);
  194. }
  195. }
  196. /**
  197. * sanitizes a DN received from the LDAP server
  198. * @param array $dn the DN in question
  199. * @return array|string the sanitized DN
  200. */
  201. public function sanitizeDN($dn) {
  202. //treating multiple base DNs
  203. if(is_array($dn)) {
  204. $result = [];
  205. foreach($dn as $singleDN) {
  206. $result[] = $this->sanitizeDN($singleDN);
  207. }
  208. return $result;
  209. }
  210. //OID sometimes gives back DNs with whitespace after the comma
  211. // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
  212. $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
  213. //make comparisons and everything work
  214. $dn = mb_strtolower($dn, 'UTF-8');
  215. //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
  216. //to use the DN in search filters, \ needs to be escaped to \5c additionally
  217. //to use them in bases, we convert them back to simple backslashes in readAttribute()
  218. $replacements = [
  219. '\,' => '\5c2C',
  220. '\=' => '\5c3D',
  221. '\+' => '\5c2B',
  222. '\<' => '\5c3C',
  223. '\>' => '\5c3E',
  224. '\;' => '\5c3B',
  225. '\"' => '\5c22',
  226. '\#' => '\5c23',
  227. '(' => '\28',
  228. ')' => '\29',
  229. '*' => '\2A',
  230. ];
  231. $dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
  232. return $dn;
  233. }
  234. /**
  235. * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
  236. * @param string $dn the DN
  237. * @return string
  238. */
  239. public function DNasBaseParameter($dn) {
  240. return str_ireplace('\\5c', '\\', $dn);
  241. }
  242. /**
  243. * listens to a hook thrown by server2server sharing and replaces the given
  244. * login name by a username, if it matches an LDAP user.
  245. *
  246. * @param array $param
  247. * @throws \Exception
  248. */
  249. public static function loginName2UserName($param) {
  250. if(!isset($param['uid'])) {
  251. throw new \Exception('key uid is expected to be set in $param');
  252. }
  253. //ain't it ironic?
  254. $helper = new Helper(\OC::$server->getConfig());
  255. $configPrefixes = $helper->getServerConfigurationPrefixes(true);
  256. $ldapWrapper = new LDAP();
  257. $ocConfig = \OC::$server->getConfig();
  258. $notificationManager = \OC::$server->getNotificationManager();
  259. $userSession = \OC::$server->getUserSession();
  260. $userPluginManager = \OC::$server->query('LDAPUserPluginManager');
  261. $userBackend = new User_Proxy(
  262. $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
  263. );
  264. $uid = $userBackend->loginName2UserName($param['uid'] );
  265. if($uid !== false) {
  266. $param['uid'] = $uid;
  267. }
  268. }
  269. }