Helper.php 8.5 KB

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