Helper.php 8.1 KB

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