@@ -35,59 +35,59 @@ |
||
35 | 35 | |
36 | 36 | class TestConfig extends Command { |
37 | 37 | |
38 | - protected function configure() { |
|
39 | - $this |
|
40 | - ->setName('ldap:test-config') |
|
41 | - ->setDescription('tests an LDAP configuration') |
|
42 | - ->addArgument( |
|
43 | - 'configID', |
|
44 | - InputArgument::REQUIRED, |
|
45 | - 'the configuration ID' |
|
46 | - ) |
|
47 | - ; |
|
48 | - } |
|
38 | + protected function configure() { |
|
39 | + $this |
|
40 | + ->setName('ldap:test-config') |
|
41 | + ->setDescription('tests an LDAP configuration') |
|
42 | + ->addArgument( |
|
43 | + 'configID', |
|
44 | + InputArgument::REQUIRED, |
|
45 | + 'the configuration ID' |
|
46 | + ) |
|
47 | + ; |
|
48 | + } |
|
49 | 49 | |
50 | - protected function execute(InputInterface $input, OutputInterface $output) { |
|
51 | - $helper = new Helper(\OC::$server->getConfig()); |
|
52 | - $availableConfigs = $helper->getServerConfigurationPrefixes(); |
|
53 | - $configID = $input->getArgument('configID'); |
|
54 | - if(!in_array($configID, $availableConfigs)) { |
|
55 | - $output->writeln("Invalid configID"); |
|
56 | - return; |
|
57 | - } |
|
50 | + protected function execute(InputInterface $input, OutputInterface $output) { |
|
51 | + $helper = new Helper(\OC::$server->getConfig()); |
|
52 | + $availableConfigs = $helper->getServerConfigurationPrefixes(); |
|
53 | + $configID = $input->getArgument('configID'); |
|
54 | + if(!in_array($configID, $availableConfigs)) { |
|
55 | + $output->writeln("Invalid configID"); |
|
56 | + return; |
|
57 | + } |
|
58 | 58 | |
59 | - $result = $this->testConfig($configID); |
|
60 | - if($result === 0) { |
|
61 | - $output->writeln('The configuration is valid and the connection could be established!'); |
|
62 | - } else if($result === 1) { |
|
63 | - $output->writeln('The configuration is invalid. Please have a look at the logs for further details.'); |
|
64 | - } else if($result === 2) { |
|
65 | - $output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.'); |
|
66 | - } else { |
|
67 | - $output->writeln('Your LDAP server was kidnapped by aliens.'); |
|
68 | - } |
|
69 | - } |
|
59 | + $result = $this->testConfig($configID); |
|
60 | + if($result === 0) { |
|
61 | + $output->writeln('The configuration is valid and the connection could be established!'); |
|
62 | + } else if($result === 1) { |
|
63 | + $output->writeln('The configuration is invalid. Please have a look at the logs for further details.'); |
|
64 | + } else if($result === 2) { |
|
65 | + $output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.'); |
|
66 | + } else { |
|
67 | + $output->writeln('Your LDAP server was kidnapped by aliens.'); |
|
68 | + } |
|
69 | + } |
|
70 | 70 | |
71 | - /** |
|
72 | - * tests the specified connection |
|
73 | - * @param string $configID |
|
74 | - * @return int |
|
75 | - */ |
|
76 | - protected function testConfig($configID) { |
|
77 | - $lw = new \OCA\User_LDAP\LDAP(); |
|
78 | - $connection = new Connection($lw, $configID); |
|
71 | + /** |
|
72 | + * tests the specified connection |
|
73 | + * @param string $configID |
|
74 | + * @return int |
|
75 | + */ |
|
76 | + protected function testConfig($configID) { |
|
77 | + $lw = new \OCA\User_LDAP\LDAP(); |
|
78 | + $connection = new Connection($lw, $configID); |
|
79 | 79 | |
80 | - //ensure validation is run before we attempt the bind |
|
81 | - $connection->getConfiguration(); |
|
80 | + //ensure validation is run before we attempt the bind |
|
81 | + $connection->getConfiguration(); |
|
82 | 82 | |
83 | - if(!$connection->setConfiguration([ |
|
84 | - 'ldap_configuration_active' => 1, |
|
85 | - ])) { |
|
86 | - return 1; |
|
87 | - } |
|
88 | - if($connection->bind()) { |
|
89 | - return 0; |
|
90 | - } |
|
91 | - return 2; |
|
92 | - } |
|
83 | + if(!$connection->setConfiguration([ |
|
84 | + 'ldap_configuration_active' => 1, |
|
85 | + ])) { |
|
86 | + return 1; |
|
87 | + } |
|
88 | + if($connection->bind()) { |
|
89 | + return 0; |
|
90 | + } |
|
91 | + return 2; |
|
92 | + } |
|
93 | 93 | } |
@@ -29,219 +29,219 @@ |
||
29 | 29 | use OCP\IDBConnection; |
30 | 30 | |
31 | 31 | class OfflineUser { |
32 | - /** |
|
33 | - * @var string $ocName |
|
34 | - */ |
|
35 | - protected $ocName; |
|
36 | - /** |
|
37 | - * @var string $dn |
|
38 | - */ |
|
39 | - protected $dn; |
|
40 | - /** |
|
41 | - * @var string $uid the UID as provided by LDAP |
|
42 | - */ |
|
43 | - protected $uid; |
|
44 | - /** |
|
45 | - * @var string $displayName |
|
46 | - */ |
|
47 | - protected $displayName; |
|
48 | - /** |
|
49 | - * @var string $homePath |
|
50 | - */ |
|
51 | - protected $homePath; |
|
52 | - /** |
|
53 | - * @var string $lastLogin the timestamp of the last login |
|
54 | - */ |
|
55 | - protected $lastLogin; |
|
56 | - /** |
|
57 | - * @var string $foundDeleted the timestamp when the user was detected as unavailable |
|
58 | - */ |
|
59 | - protected $foundDeleted; |
|
60 | - /** |
|
61 | - * @var string $email |
|
62 | - */ |
|
63 | - protected $email; |
|
64 | - /** |
|
65 | - * @var bool $hasActiveShares |
|
66 | - */ |
|
67 | - protected $hasActiveShares; |
|
68 | - /** |
|
69 | - * @var IConfig $config |
|
70 | - */ |
|
71 | - protected $config; |
|
72 | - /** |
|
73 | - * @var IDBConnection $db |
|
74 | - */ |
|
75 | - protected $db; |
|
76 | - /** |
|
77 | - * @var \OCA\User_LDAP\Mapping\UserMapping |
|
78 | - */ |
|
79 | - protected $mapping; |
|
80 | - |
|
81 | - /** |
|
82 | - * @param string $ocName |
|
83 | - * @param IConfig $config |
|
84 | - * @param IDBConnection $db |
|
85 | - * @param \OCA\User_LDAP\Mapping\UserMapping $mapping |
|
86 | - */ |
|
87 | - public function __construct($ocName, IConfig $config, IDBConnection $db, UserMapping $mapping) { |
|
88 | - $this->ocName = $ocName; |
|
89 | - $this->config = $config; |
|
90 | - $this->db = $db; |
|
91 | - $this->mapping = $mapping; |
|
92 | - $this->fetchDetails(); |
|
93 | - } |
|
94 | - |
|
95 | - /** |
|
96 | - * remove the Delete-flag from the user. |
|
97 | - */ |
|
98 | - public function unmark() { |
|
99 | - $this->config->deleteUserValue($this->ocName, 'user_ldap', 'isDeleted'); |
|
100 | - $this->config->deleteUserValue($this->ocName, 'user_ldap', 'foundDeleted'); |
|
101 | - } |
|
102 | - |
|
103 | - /** |
|
104 | - * exports the user details in an assoc array |
|
105 | - * @return array |
|
106 | - */ |
|
107 | - public function export() { |
|
108 | - $data = []; |
|
109 | - $data['ocName'] = $this->getOCName(); |
|
110 | - $data['dn'] = $this->getDN(); |
|
111 | - $data['uid'] = $this->getUID(); |
|
112 | - $data['displayName'] = $this->getDisplayName(); |
|
113 | - $data['homePath'] = $this->getHomePath(); |
|
114 | - $data['lastLogin'] = $this->getLastLogin(); |
|
115 | - $data['email'] = $this->getEmail(); |
|
116 | - $data['hasActiveShares'] = $this->getHasActiveShares(); |
|
117 | - |
|
118 | - return $data; |
|
119 | - } |
|
120 | - |
|
121 | - /** |
|
122 | - * getter for Nextcloud internal name |
|
123 | - * @return string |
|
124 | - */ |
|
125 | - public function getOCName() { |
|
126 | - return $this->ocName; |
|
127 | - } |
|
128 | - |
|
129 | - /** |
|
130 | - * getter for LDAP uid |
|
131 | - * @return string |
|
132 | - */ |
|
133 | - public function getUID() { |
|
134 | - return $this->uid; |
|
135 | - } |
|
136 | - |
|
137 | - /** |
|
138 | - * getter for LDAP DN |
|
139 | - * @return string |
|
140 | - */ |
|
141 | - public function getDN() { |
|
142 | - return $this->dn; |
|
143 | - } |
|
144 | - |
|
145 | - /** |
|
146 | - * getter for display name |
|
147 | - * @return string |
|
148 | - */ |
|
149 | - public function getDisplayName() { |
|
150 | - return $this->displayName; |
|
151 | - } |
|
152 | - |
|
153 | - /** |
|
154 | - * getter for email |
|
155 | - * @return string |
|
156 | - */ |
|
157 | - public function getEmail() { |
|
158 | - return $this->email; |
|
159 | - } |
|
160 | - |
|
161 | - /** |
|
162 | - * getter for home directory path |
|
163 | - * @return string |
|
164 | - */ |
|
165 | - public function getHomePath() { |
|
166 | - return $this->homePath; |
|
167 | - } |
|
168 | - |
|
169 | - /** |
|
170 | - * getter for the last login timestamp |
|
171 | - * @return int |
|
172 | - */ |
|
173 | - public function getLastLogin() { |
|
174 | - return (int)$this->lastLogin; |
|
175 | - } |
|
176 | - |
|
177 | - /** |
|
178 | - * getter for the detection timestamp |
|
179 | - * @return int |
|
180 | - */ |
|
181 | - public function getDetectedOn() { |
|
182 | - return (int)$this->foundDeleted; |
|
183 | - } |
|
184 | - |
|
185 | - /** |
|
186 | - * getter for having active shares |
|
187 | - * @return bool |
|
188 | - */ |
|
189 | - public function getHasActiveShares() { |
|
190 | - return $this->hasActiveShares; |
|
191 | - } |
|
192 | - |
|
193 | - /** |
|
194 | - * reads the user details |
|
195 | - */ |
|
196 | - protected function fetchDetails() { |
|
197 | - $properties = [ |
|
198 | - 'displayName' => 'user_ldap', |
|
199 | - 'uid' => 'user_ldap', |
|
200 | - 'homePath' => 'user_ldap', |
|
201 | - 'foundDeleted' => 'user_ldap', |
|
202 | - 'email' => 'settings', |
|
203 | - 'lastLogin' => 'login', |
|
204 | - ]; |
|
205 | - foreach($properties as $property => $app) { |
|
206 | - $this->$property = $this->config->getUserValue($this->ocName, $app, $property, ''); |
|
207 | - } |
|
208 | - |
|
209 | - $dn = $this->mapping->getDNByName($this->ocName); |
|
210 | - $this->dn = ($dn !== false) ? $dn : ''; |
|
211 | - |
|
212 | - $this->determineShares(); |
|
213 | - } |
|
214 | - |
|
215 | - |
|
216 | - /** |
|
217 | - * finds out whether the user has active shares. The result is stored in |
|
218 | - * $this->hasActiveShares |
|
219 | - */ |
|
220 | - protected function determineShares() { |
|
221 | - $query = $this->db->prepare(' |
|
32 | + /** |
|
33 | + * @var string $ocName |
|
34 | + */ |
|
35 | + protected $ocName; |
|
36 | + /** |
|
37 | + * @var string $dn |
|
38 | + */ |
|
39 | + protected $dn; |
|
40 | + /** |
|
41 | + * @var string $uid the UID as provided by LDAP |
|
42 | + */ |
|
43 | + protected $uid; |
|
44 | + /** |
|
45 | + * @var string $displayName |
|
46 | + */ |
|
47 | + protected $displayName; |
|
48 | + /** |
|
49 | + * @var string $homePath |
|
50 | + */ |
|
51 | + protected $homePath; |
|
52 | + /** |
|
53 | + * @var string $lastLogin the timestamp of the last login |
|
54 | + */ |
|
55 | + protected $lastLogin; |
|
56 | + /** |
|
57 | + * @var string $foundDeleted the timestamp when the user was detected as unavailable |
|
58 | + */ |
|
59 | + protected $foundDeleted; |
|
60 | + /** |
|
61 | + * @var string $email |
|
62 | + */ |
|
63 | + protected $email; |
|
64 | + /** |
|
65 | + * @var bool $hasActiveShares |
|
66 | + */ |
|
67 | + protected $hasActiveShares; |
|
68 | + /** |
|
69 | + * @var IConfig $config |
|
70 | + */ |
|
71 | + protected $config; |
|
72 | + /** |
|
73 | + * @var IDBConnection $db |
|
74 | + */ |
|
75 | + protected $db; |
|
76 | + /** |
|
77 | + * @var \OCA\User_LDAP\Mapping\UserMapping |
|
78 | + */ |
|
79 | + protected $mapping; |
|
80 | + |
|
81 | + /** |
|
82 | + * @param string $ocName |
|
83 | + * @param IConfig $config |
|
84 | + * @param IDBConnection $db |
|
85 | + * @param \OCA\User_LDAP\Mapping\UserMapping $mapping |
|
86 | + */ |
|
87 | + public function __construct($ocName, IConfig $config, IDBConnection $db, UserMapping $mapping) { |
|
88 | + $this->ocName = $ocName; |
|
89 | + $this->config = $config; |
|
90 | + $this->db = $db; |
|
91 | + $this->mapping = $mapping; |
|
92 | + $this->fetchDetails(); |
|
93 | + } |
|
94 | + |
|
95 | + /** |
|
96 | + * remove the Delete-flag from the user. |
|
97 | + */ |
|
98 | + public function unmark() { |
|
99 | + $this->config->deleteUserValue($this->ocName, 'user_ldap', 'isDeleted'); |
|
100 | + $this->config->deleteUserValue($this->ocName, 'user_ldap', 'foundDeleted'); |
|
101 | + } |
|
102 | + |
|
103 | + /** |
|
104 | + * exports the user details in an assoc array |
|
105 | + * @return array |
|
106 | + */ |
|
107 | + public function export() { |
|
108 | + $data = []; |
|
109 | + $data['ocName'] = $this->getOCName(); |
|
110 | + $data['dn'] = $this->getDN(); |
|
111 | + $data['uid'] = $this->getUID(); |
|
112 | + $data['displayName'] = $this->getDisplayName(); |
|
113 | + $data['homePath'] = $this->getHomePath(); |
|
114 | + $data['lastLogin'] = $this->getLastLogin(); |
|
115 | + $data['email'] = $this->getEmail(); |
|
116 | + $data['hasActiveShares'] = $this->getHasActiveShares(); |
|
117 | + |
|
118 | + return $data; |
|
119 | + } |
|
120 | + |
|
121 | + /** |
|
122 | + * getter for Nextcloud internal name |
|
123 | + * @return string |
|
124 | + */ |
|
125 | + public function getOCName() { |
|
126 | + return $this->ocName; |
|
127 | + } |
|
128 | + |
|
129 | + /** |
|
130 | + * getter for LDAP uid |
|
131 | + * @return string |
|
132 | + */ |
|
133 | + public function getUID() { |
|
134 | + return $this->uid; |
|
135 | + } |
|
136 | + |
|
137 | + /** |
|
138 | + * getter for LDAP DN |
|
139 | + * @return string |
|
140 | + */ |
|
141 | + public function getDN() { |
|
142 | + return $this->dn; |
|
143 | + } |
|
144 | + |
|
145 | + /** |
|
146 | + * getter for display name |
|
147 | + * @return string |
|
148 | + */ |
|
149 | + public function getDisplayName() { |
|
150 | + return $this->displayName; |
|
151 | + } |
|
152 | + |
|
153 | + /** |
|
154 | + * getter for email |
|
155 | + * @return string |
|
156 | + */ |
|
157 | + public function getEmail() { |
|
158 | + return $this->email; |
|
159 | + } |
|
160 | + |
|
161 | + /** |
|
162 | + * getter for home directory path |
|
163 | + * @return string |
|
164 | + */ |
|
165 | + public function getHomePath() { |
|
166 | + return $this->homePath; |
|
167 | + } |
|
168 | + |
|
169 | + /** |
|
170 | + * getter for the last login timestamp |
|
171 | + * @return int |
|
172 | + */ |
|
173 | + public function getLastLogin() { |
|
174 | + return (int)$this->lastLogin; |
|
175 | + } |
|
176 | + |
|
177 | + /** |
|
178 | + * getter for the detection timestamp |
|
179 | + * @return int |
|
180 | + */ |
|
181 | + public function getDetectedOn() { |
|
182 | + return (int)$this->foundDeleted; |
|
183 | + } |
|
184 | + |
|
185 | + /** |
|
186 | + * getter for having active shares |
|
187 | + * @return bool |
|
188 | + */ |
|
189 | + public function getHasActiveShares() { |
|
190 | + return $this->hasActiveShares; |
|
191 | + } |
|
192 | + |
|
193 | + /** |
|
194 | + * reads the user details |
|
195 | + */ |
|
196 | + protected function fetchDetails() { |
|
197 | + $properties = [ |
|
198 | + 'displayName' => 'user_ldap', |
|
199 | + 'uid' => 'user_ldap', |
|
200 | + 'homePath' => 'user_ldap', |
|
201 | + 'foundDeleted' => 'user_ldap', |
|
202 | + 'email' => 'settings', |
|
203 | + 'lastLogin' => 'login', |
|
204 | + ]; |
|
205 | + foreach($properties as $property => $app) { |
|
206 | + $this->$property = $this->config->getUserValue($this->ocName, $app, $property, ''); |
|
207 | + } |
|
208 | + |
|
209 | + $dn = $this->mapping->getDNByName($this->ocName); |
|
210 | + $this->dn = ($dn !== false) ? $dn : ''; |
|
211 | + |
|
212 | + $this->determineShares(); |
|
213 | + } |
|
214 | + |
|
215 | + |
|
216 | + /** |
|
217 | + * finds out whether the user has active shares. The result is stored in |
|
218 | + * $this->hasActiveShares |
|
219 | + */ |
|
220 | + protected function determineShares() { |
|
221 | + $query = $this->db->prepare(' |
|
222 | 222 | SELECT COUNT(`uid_owner`) |
223 | 223 | FROM `*PREFIX*share` |
224 | 224 | WHERE `uid_owner` = ? |
225 | 225 | ', 1); |
226 | - $query->execute([$this->ocName]); |
|
227 | - $sResult = $query->fetchColumn(0); |
|
228 | - if((int)$sResult === 1) { |
|
229 | - $this->hasActiveShares = true; |
|
230 | - return; |
|
231 | - } |
|
232 | - |
|
233 | - $query = $this->db->prepare(' |
|
226 | + $query->execute([$this->ocName]); |
|
227 | + $sResult = $query->fetchColumn(0); |
|
228 | + if((int)$sResult === 1) { |
|
229 | + $this->hasActiveShares = true; |
|
230 | + return; |
|
231 | + } |
|
232 | + |
|
233 | + $query = $this->db->prepare(' |
|
234 | 234 | SELECT COUNT(`owner`) |
235 | 235 | FROM `*PREFIX*share_external` |
236 | 236 | WHERE `owner` = ? |
237 | 237 | ', 1); |
238 | - $query->execute([$this->ocName]); |
|
239 | - $sResult = $query->fetchColumn(0); |
|
240 | - if((int)$sResult === 1) { |
|
241 | - $this->hasActiveShares = true; |
|
242 | - return; |
|
243 | - } |
|
244 | - |
|
245 | - $this->hasActiveShares = false; |
|
246 | - } |
|
238 | + $query->execute([$this->ocName]); |
|
239 | + $sResult = $query->fetchColumn(0); |
|
240 | + if((int)$sResult === 1) { |
|
241 | + $this->hasActiveShares = true; |
|
242 | + return; |
|
243 | + } |
|
244 | + |
|
245 | + $this->hasActiveShares = false; |
|
246 | + } |
|
247 | 247 | } |
@@ -49,745 +49,745 @@ |
||
49 | 49 | * represents an LDAP user, gets and holds user-specific information from LDAP |
50 | 50 | */ |
51 | 51 | class User { |
52 | - /** |
|
53 | - * @var Access |
|
54 | - */ |
|
55 | - protected $access; |
|
56 | - /** |
|
57 | - * @var Connection |
|
58 | - */ |
|
59 | - protected $connection; |
|
60 | - /** |
|
61 | - * @var IConfig |
|
62 | - */ |
|
63 | - protected $config; |
|
64 | - /** |
|
65 | - * @var FilesystemHelper |
|
66 | - */ |
|
67 | - protected $fs; |
|
68 | - /** |
|
69 | - * @var Image |
|
70 | - */ |
|
71 | - protected $image; |
|
72 | - /** |
|
73 | - * @var LogWrapper |
|
74 | - */ |
|
75 | - protected $log; |
|
76 | - /** |
|
77 | - * @var IAvatarManager |
|
78 | - */ |
|
79 | - protected $avatarManager; |
|
80 | - /** |
|
81 | - * @var IUserManager |
|
82 | - */ |
|
83 | - protected $userManager; |
|
84 | - /** |
|
85 | - * @var INotificationManager |
|
86 | - */ |
|
87 | - protected $notificationManager; |
|
88 | - /** |
|
89 | - * @var string |
|
90 | - */ |
|
91 | - protected $dn; |
|
92 | - /** |
|
93 | - * @var string |
|
94 | - */ |
|
95 | - protected $uid; |
|
96 | - /** |
|
97 | - * @var string[] |
|
98 | - */ |
|
99 | - protected $refreshedFeatures = []; |
|
100 | - /** |
|
101 | - * @var string |
|
102 | - */ |
|
103 | - protected $avatarImage; |
|
104 | - |
|
105 | - /** |
|
106 | - * DB config keys for user preferences |
|
107 | - */ |
|
108 | - const USER_PREFKEY_FIRSTLOGIN = 'firstLoginAccomplished'; |
|
109 | - const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh'; |
|
110 | - |
|
111 | - /** |
|
112 | - * @brief constructor, make sure the subclasses call this one! |
|
113 | - * @param string $username the internal username |
|
114 | - * @param string $dn the LDAP DN |
|
115 | - * @param Access $access |
|
116 | - * @param IConfig $config |
|
117 | - * @param FilesystemHelper $fs |
|
118 | - * @param Image $image any empty instance |
|
119 | - * @param LogWrapper $log |
|
120 | - * @param IAvatarManager $avatarManager |
|
121 | - * @param IUserManager $userManager |
|
122 | - * @param INotificationManager $notificationManager |
|
123 | - */ |
|
124 | - public function __construct($username, $dn, Access $access, |
|
125 | - IConfig $config, FilesystemHelper $fs, Image $image, |
|
126 | - LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager, |
|
127 | - INotificationManager $notificationManager) { |
|
128 | - |
|
129 | - if ($username === null) { |
|
130 | - $log->log("uid for '$dn' must not be null!", ILogger::ERROR); |
|
131 | - throw new \InvalidArgumentException('uid must not be null!'); |
|
132 | - } else if ($username === '') { |
|
133 | - $log->log("uid for '$dn' must not be an empty string", ILogger::ERROR); |
|
134 | - throw new \InvalidArgumentException('uid must not be an empty string!'); |
|
135 | - } |
|
136 | - |
|
137 | - $this->access = $access; |
|
138 | - $this->connection = $access->getConnection(); |
|
139 | - $this->config = $config; |
|
140 | - $this->fs = $fs; |
|
141 | - $this->dn = $dn; |
|
142 | - $this->uid = $username; |
|
143 | - $this->image = $image; |
|
144 | - $this->log = $log; |
|
145 | - $this->avatarManager = $avatarManager; |
|
146 | - $this->userManager = $userManager; |
|
147 | - $this->notificationManager = $notificationManager; |
|
148 | - |
|
149 | - \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry'); |
|
150 | - } |
|
151 | - |
|
152 | - /** |
|
153 | - * @brief updates properties like email, quota or avatar provided by LDAP |
|
154 | - * @return null |
|
155 | - */ |
|
156 | - public function update() { |
|
157 | - if(is_null($this->dn)) { |
|
158 | - return null; |
|
159 | - } |
|
160 | - |
|
161 | - $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap', |
|
162 | - self::USER_PREFKEY_FIRSTLOGIN, 0); |
|
163 | - |
|
164 | - if($this->needsRefresh()) { |
|
165 | - $this->updateEmail(); |
|
166 | - $this->updateQuota(); |
|
167 | - if($hasLoggedIn !== 0) { |
|
168 | - //we do not need to try it, when the user has not been logged in |
|
169 | - //before, because the file system will not be ready. |
|
170 | - $this->updateAvatar(); |
|
171 | - //in order to get an avatar as soon as possible, mark the user |
|
172 | - //as refreshed only when updating the avatar did happen |
|
173 | - $this->markRefreshTime(); |
|
174 | - } |
|
175 | - } |
|
176 | - } |
|
177 | - |
|
178 | - /** |
|
179 | - * marks a user as deleted |
|
180 | - * |
|
181 | - * @throws \OCP\PreConditionNotMetException |
|
182 | - */ |
|
183 | - public function markUser() { |
|
184 | - $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0'); |
|
185 | - if($curValue === '1') { |
|
186 | - // the user is already marked, do not write to DB again |
|
187 | - return; |
|
188 | - } |
|
189 | - $this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1'); |
|
190 | - $this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time()); |
|
191 | - } |
|
192 | - |
|
193 | - /** |
|
194 | - * processes results from LDAP for attributes as returned by getAttributesToRead() |
|
195 | - * @param array $ldapEntry the user entry as retrieved from LDAP |
|
196 | - */ |
|
197 | - public function processAttributes($ldapEntry) { |
|
198 | - $this->markRefreshTime(); |
|
199 | - //Quota |
|
200 | - $attr = strtolower($this->connection->ldapQuotaAttribute); |
|
201 | - if(isset($ldapEntry[$attr])) { |
|
202 | - $this->updateQuota($ldapEntry[$attr][0]); |
|
203 | - } else { |
|
204 | - if ($this->connection->ldapQuotaDefault !== '') { |
|
205 | - $this->updateQuota(); |
|
206 | - } |
|
207 | - } |
|
208 | - unset($attr); |
|
209 | - |
|
210 | - //displayName |
|
211 | - $displayName = $displayName2 = ''; |
|
212 | - $attr = strtolower($this->connection->ldapUserDisplayName); |
|
213 | - if(isset($ldapEntry[$attr])) { |
|
214 | - $displayName = (string)$ldapEntry[$attr][0]; |
|
215 | - } |
|
216 | - $attr = strtolower($this->connection->ldapUserDisplayName2); |
|
217 | - if(isset($ldapEntry[$attr])) { |
|
218 | - $displayName2 = (string)$ldapEntry[$attr][0]; |
|
219 | - } |
|
220 | - if ($displayName !== '') { |
|
221 | - $this->composeAndStoreDisplayName($displayName, $displayName2); |
|
222 | - $this->access->cacheUserDisplayName( |
|
223 | - $this->getUsername(), |
|
224 | - $displayName, |
|
225 | - $displayName2 |
|
226 | - ); |
|
227 | - } |
|
228 | - unset($attr); |
|
229 | - |
|
230 | ||
231 | - //email must be stored after displayname, because it would cause a user |
|
232 | - //change event that will trigger fetching the display name again |
|
233 | - $attr = strtolower($this->connection->ldapEmailAttribute); |
|
234 | - if(isset($ldapEntry[$attr])) { |
|
235 | - $this->updateEmail($ldapEntry[$attr][0]); |
|
236 | - } |
|
237 | - unset($attr); |
|
238 | - |
|
239 | - // LDAP Username, needed for s2s sharing |
|
240 | - if(isset($ldapEntry['uid'])) { |
|
241 | - $this->storeLDAPUserName($ldapEntry['uid'][0]); |
|
242 | - } else if(isset($ldapEntry['samaccountname'])) { |
|
243 | - $this->storeLDAPUserName($ldapEntry['samaccountname'][0]); |
|
244 | - } |
|
245 | - |
|
246 | - //homePath |
|
247 | - if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) { |
|
248 | - $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:'))); |
|
249 | - if(isset($ldapEntry[$attr])) { |
|
250 | - $this->access->cacheUserHome( |
|
251 | - $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0])); |
|
252 | - } |
|
253 | - } |
|
254 | - |
|
255 | - //memberOf groups |
|
256 | - $cacheKey = 'getMemberOf'.$this->getUsername(); |
|
257 | - $groups = false; |
|
258 | - if(isset($ldapEntry['memberof'])) { |
|
259 | - $groups = $ldapEntry['memberof']; |
|
260 | - } |
|
261 | - $this->connection->writeToCache($cacheKey, $groups); |
|
262 | - |
|
263 | - //external storage var |
|
264 | - $attr = strtolower($this->connection->ldapExtStorageHomeAttribute); |
|
265 | - if(isset($ldapEntry[$attr])) { |
|
266 | - $this->updateExtStorageHome($ldapEntry[$attr][0]); |
|
267 | - } |
|
268 | - unset($attr); |
|
269 | - |
|
270 | - //Avatar |
|
271 | - /** @var Connection $connection */ |
|
272 | - $connection = $this->access->getConnection(); |
|
273 | - $attributes = $connection->resolveRule('avatar'); |
|
274 | - foreach ($attributes as $attribute) { |
|
275 | - if(isset($ldapEntry[$attribute])) { |
|
276 | - $this->avatarImage = $ldapEntry[$attribute][0]; |
|
277 | - // the call to the method that saves the avatar in the file |
|
278 | - // system must be postponed after the login. It is to ensure |
|
279 | - // external mounts are mounted properly (e.g. with login |
|
280 | - // credentials from the session). |
|
281 | - \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin'); |
|
282 | - break; |
|
283 | - } |
|
284 | - } |
|
285 | - } |
|
286 | - |
|
287 | - /** |
|
288 | - * @brief returns the LDAP DN of the user |
|
289 | - * @return string |
|
290 | - */ |
|
291 | - public function getDN() { |
|
292 | - return $this->dn; |
|
293 | - } |
|
294 | - |
|
295 | - /** |
|
296 | - * @brief returns the Nextcloud internal username of the user |
|
297 | - * @return string |
|
298 | - */ |
|
299 | - public function getUsername() { |
|
300 | - return $this->uid; |
|
301 | - } |
|
302 | - |
|
303 | - /** |
|
304 | - * returns the home directory of the user if specified by LDAP settings |
|
305 | - * @param string $valueFromLDAP |
|
306 | - * @return bool|string |
|
307 | - * @throws \Exception |
|
308 | - */ |
|
309 | - public function getHomePath($valueFromLDAP = null) { |
|
310 | - $path = (string)$valueFromLDAP; |
|
311 | - $attr = null; |
|
312 | - |
|
313 | - if (is_null($valueFromLDAP) |
|
314 | - && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0 |
|
315 | - && $this->access->connection->homeFolderNamingRule !== 'attr:') |
|
316 | - { |
|
317 | - $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:')); |
|
318 | - $homedir = $this->access->readAttribute( |
|
319 | - $this->access->username2dn($this->getUsername()), $attr); |
|
320 | - if ($homedir && isset($homedir[0])) { |
|
321 | - $path = $homedir[0]; |
|
322 | - } |
|
323 | - } |
|
324 | - |
|
325 | - if ($path !== '') { |
|
326 | - //if attribute's value is an absolute path take this, otherwise append it to data dir |
|
327 | - //check for / at the beginning or pattern c:\ resp. c:/ |
|
328 | - if( '/' !== $path[0] |
|
329 | - && !(3 < strlen($path) && ctype_alpha($path[0]) |
|
330 | - && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2])) |
|
331 | - ) { |
|
332 | - $path = $this->config->getSystemValue('datadirectory', |
|
333 | - \OC::$SERVERROOT.'/data' ) . '/' . $path; |
|
334 | - } |
|
335 | - //we need it to store it in the DB as well in case a user gets |
|
336 | - //deleted so we can clean up afterwards |
|
337 | - $this->config->setUserValue( |
|
338 | - $this->getUsername(), 'user_ldap', 'homePath', $path |
|
339 | - ); |
|
340 | - return $path; |
|
341 | - } |
|
342 | - |
|
343 | - if( !is_null($attr) |
|
344 | - && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true) |
|
345 | - ) { |
|
346 | - // a naming rule attribute is defined, but it doesn't exist for that LDAP user |
|
347 | - throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername()); |
|
348 | - } |
|
349 | - |
|
350 | - //false will apply default behaviour as defined and done by OC_User |
|
351 | - $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', ''); |
|
352 | - return false; |
|
353 | - } |
|
354 | - |
|
355 | - public function getMemberOfGroups() { |
|
356 | - $cacheKey = 'getMemberOf'.$this->getUsername(); |
|
357 | - $memberOfGroups = $this->connection->getFromCache($cacheKey); |
|
358 | - if(!is_null($memberOfGroups)) { |
|
359 | - return $memberOfGroups; |
|
360 | - } |
|
361 | - $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf'); |
|
362 | - $this->connection->writeToCache($cacheKey, $groupDNs); |
|
363 | - return $groupDNs; |
|
364 | - } |
|
365 | - |
|
366 | - /** |
|
367 | - * @brief reads the image from LDAP that shall be used as Avatar |
|
368 | - * @return string data (provided by LDAP) | false |
|
369 | - */ |
|
370 | - public function getAvatarImage() { |
|
371 | - if(!is_null($this->avatarImage)) { |
|
372 | - return $this->avatarImage; |
|
373 | - } |
|
374 | - |
|
375 | - $this->avatarImage = false; |
|
376 | - /** @var Connection $connection */ |
|
377 | - $connection = $this->access->getConnection(); |
|
378 | - $attributes = $connection->resolveRule('avatar'); |
|
379 | - foreach($attributes as $attribute) { |
|
380 | - $result = $this->access->readAttribute($this->dn, $attribute); |
|
381 | - if($result !== false && is_array($result) && isset($result[0])) { |
|
382 | - $this->avatarImage = $result[0]; |
|
383 | - break; |
|
384 | - } |
|
385 | - } |
|
386 | - |
|
387 | - return $this->avatarImage; |
|
388 | - } |
|
389 | - |
|
390 | - /** |
|
391 | - * @brief marks the user as having logged in at least once |
|
392 | - * @return null |
|
393 | - */ |
|
394 | - public function markLogin() { |
|
395 | - $this->config->setUserValue( |
|
396 | - $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1); |
|
397 | - } |
|
398 | - |
|
399 | - /** |
|
400 | - * @brief marks the time when user features like email have been updated |
|
401 | - * @return null |
|
402 | - */ |
|
403 | - public function markRefreshTime() { |
|
404 | - $this->config->setUserValue( |
|
405 | - $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time()); |
|
406 | - } |
|
407 | - |
|
408 | - /** |
|
409 | - * @brief checks whether user features needs to be updated again by |
|
410 | - * comparing the difference of time of the last refresh to now with the |
|
411 | - * desired interval |
|
412 | - * @return bool |
|
413 | - */ |
|
414 | - private function needsRefresh() { |
|
415 | - $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap', |
|
416 | - self::USER_PREFKEY_LASTREFRESH, 0); |
|
417 | - |
|
418 | - if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) { |
|
419 | - return false; |
|
420 | - } |
|
421 | - return true; |
|
422 | - } |
|
423 | - |
|
424 | - /** |
|
425 | - * Stores a key-value pair in relation to this user |
|
426 | - * |
|
427 | - * @param string $key |
|
428 | - * @param string $value |
|
429 | - */ |
|
430 | - private function store($key, $value) { |
|
431 | - $this->config->setUserValue($this->uid, 'user_ldap', $key, $value); |
|
432 | - } |
|
433 | - |
|
434 | - /** |
|
435 | - * Composes the display name and stores it in the database. The final |
|
436 | - * display name is returned. |
|
437 | - * |
|
438 | - * @param string $displayName |
|
439 | - * @param string $displayName2 |
|
440 | - * @return string the effective display name |
|
441 | - */ |
|
442 | - public function composeAndStoreDisplayName($displayName, $displayName2 = '') { |
|
443 | - $displayName2 = (string)$displayName2; |
|
444 | - if($displayName2 !== '') { |
|
445 | - $displayName .= ' (' . $displayName2 . ')'; |
|
446 | - } |
|
447 | - $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null); |
|
448 | - if ($oldName !== $displayName) { |
|
449 | - $this->store('displayName', $displayName); |
|
450 | - $user = $this->userManager->get($this->getUsername()); |
|
451 | - if (!empty($oldName) && $user instanceof \OC\User\User) { |
|
452 | - // if it was empty, it would be a new record, not a change emitting the trigger could |
|
453 | - // potentially cause a UniqueConstraintViolationException, depending on some factors. |
|
454 | - $user->triggerChange('displayName', $displayName, $oldName); |
|
455 | - } |
|
456 | - } |
|
457 | - return $displayName; |
|
458 | - } |
|
459 | - |
|
460 | - /** |
|
461 | - * Stores the LDAP Username in the Database |
|
462 | - * @param string $userName |
|
463 | - */ |
|
464 | - public function storeLDAPUserName($userName) { |
|
465 | - $this->store('uid', $userName); |
|
466 | - } |
|
467 | - |
|
468 | - /** |
|
469 | - * @brief checks whether an update method specified by feature was run |
|
470 | - * already. If not, it will marked like this, because it is expected that |
|
471 | - * the method will be run, when false is returned. |
|
472 | - * @param string $feature email | quota | avatar (can be extended) |
|
473 | - * @return bool |
|
474 | - */ |
|
475 | - private function wasRefreshed($feature) { |
|
476 | - if(isset($this->refreshedFeatures[$feature])) { |
|
477 | - return true; |
|
478 | - } |
|
479 | - $this->refreshedFeatures[$feature] = 1; |
|
480 | - return false; |
|
481 | - } |
|
482 | - |
|
483 | - /** |
|
484 | - * fetches the email from LDAP and stores it as Nextcloud user value |
|
485 | - * @param string $valueFromLDAP if known, to save an LDAP read request |
|
486 | - * @return null |
|
487 | - */ |
|
488 | - public function updateEmail($valueFromLDAP = null) { |
|
489 | - if($this->wasRefreshed('email')) { |
|
490 | - return; |
|
491 | - } |
|
492 | - $email = (string)$valueFromLDAP; |
|
493 | - if(is_null($valueFromLDAP)) { |
|
494 | - $emailAttribute = $this->connection->ldapEmailAttribute; |
|
495 | - if ($emailAttribute !== '') { |
|
496 | - $aEmail = $this->access->readAttribute($this->dn, $emailAttribute); |
|
497 | - if(is_array($aEmail) && (count($aEmail) > 0)) { |
|
498 | - $email = (string)$aEmail[0]; |
|
499 | - } |
|
500 | - } |
|
501 | - } |
|
502 | - if ($email !== '') { |
|
503 | - $user = $this->userManager->get($this->uid); |
|
504 | - if (!is_null($user)) { |
|
505 | - $currentEmail = (string)$user->getEMailAddress(); |
|
506 | - if ($currentEmail !== $email) { |
|
507 | - $user->setEMailAddress($email); |
|
508 | - } |
|
509 | - } |
|
510 | - } |
|
511 | - } |
|
512 | - |
|
513 | - /** |
|
514 | - * Overall process goes as follow: |
|
515 | - * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function |
|
516 | - * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota |
|
517 | - * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default') |
|
518 | - * 4. check if the target user exists and set the quota for the user. |
|
519 | - * |
|
520 | - * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP |
|
521 | - * parameter can be passed with the value of the attribute. This value will be considered as the |
|
522 | - * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to |
|
523 | - * fetch all the user's attributes in one call and use the fetched values in this function. |
|
524 | - * The expected value for that parameter is a string describing the quota for the user. Valid |
|
525 | - * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in |
|
526 | - * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info) |
|
527 | - * |
|
528 | - * fetches the quota from LDAP and stores it as Nextcloud user value |
|
529 | - * @param string $valueFromLDAP the quota attribute's value can be passed, |
|
530 | - * to save the readAttribute request |
|
531 | - * @return null |
|
532 | - */ |
|
533 | - public function updateQuota($valueFromLDAP = null) { |
|
534 | - if($this->wasRefreshed('quota')) { |
|
535 | - return; |
|
536 | - } |
|
537 | - |
|
538 | - $quotaAttribute = $this->connection->ldapQuotaAttribute; |
|
539 | - $defaultQuota = $this->connection->ldapQuotaDefault; |
|
540 | - if($quotaAttribute === '' && $defaultQuota === '') { |
|
541 | - return; |
|
542 | - } |
|
543 | - |
|
544 | - $quota = false; |
|
545 | - if(is_null($valueFromLDAP) && $quotaAttribute !== '') { |
|
546 | - $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute); |
|
547 | - if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) { |
|
548 | - $quota = $aQuota[0]; |
|
549 | - } else if(is_array($aQuota) && isset($aQuota[0])) { |
|
550 | - $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG); |
|
551 | - } |
|
552 | - } else if ($this->verifyQuotaValue($valueFromLDAP)) { |
|
553 | - $quota = $valueFromLDAP; |
|
554 | - } else { |
|
555 | - $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG); |
|
556 | - } |
|
557 | - |
|
558 | - if ($quota === false && $this->verifyQuotaValue($defaultQuota)) { |
|
559 | - // quota not found using the LDAP attribute (or not parseable). Try the default quota |
|
560 | - $quota = $defaultQuota; |
|
561 | - } else if($quota === false) { |
|
562 | - $this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG); |
|
563 | - return; |
|
564 | - } |
|
565 | - |
|
566 | - $targetUser = $this->userManager->get($this->uid); |
|
567 | - if ($targetUser instanceof IUser) { |
|
568 | - $targetUser->setQuota($quota); |
|
569 | - } else { |
|
570 | - $this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO); |
|
571 | - } |
|
572 | - } |
|
573 | - |
|
574 | - private function verifyQuotaValue($quotaValue) { |
|
575 | - return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false; |
|
576 | - } |
|
577 | - |
|
578 | - /** |
|
579 | - * called by a post_login hook to save the avatar picture |
|
580 | - * |
|
581 | - * @param array $params |
|
582 | - */ |
|
583 | - public function updateAvatarPostLogin($params) { |
|
584 | - if(isset($params['uid']) && $params['uid'] === $this->getUsername()) { |
|
585 | - $this->updateAvatar(); |
|
586 | - } |
|
587 | - } |
|
588 | - |
|
589 | - /** |
|
590 | - * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar |
|
591 | - * @return bool |
|
592 | - */ |
|
593 | - public function updateAvatar($force = false) { |
|
594 | - if(!$force && $this->wasRefreshed('avatar')) { |
|
595 | - return false; |
|
596 | - } |
|
597 | - $avatarImage = $this->getAvatarImage(); |
|
598 | - if($avatarImage === false) { |
|
599 | - //not set, nothing left to do; |
|
600 | - return false; |
|
601 | - } |
|
602 | - |
|
603 | - if(!$this->image->loadFromBase64(base64_encode($avatarImage))) { |
|
604 | - return false; |
|
605 | - } |
|
606 | - |
|
607 | - // use the checksum before modifications |
|
608 | - $checksum = md5($this->image->data()); |
|
609 | - |
|
610 | - if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) { |
|
611 | - return true; |
|
612 | - } |
|
613 | - |
|
614 | - $isSet = $this->setOwnCloudAvatar(); |
|
615 | - |
|
616 | - if($isSet) { |
|
617 | - // save checksum only after successful setting |
|
618 | - $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum); |
|
619 | - } |
|
620 | - |
|
621 | - return $isSet; |
|
622 | - } |
|
623 | - |
|
624 | - /** |
|
625 | - * @brief sets an image as Nextcloud avatar |
|
626 | - * @return bool |
|
627 | - */ |
|
628 | - private function setOwnCloudAvatar() { |
|
629 | - if(!$this->image->valid()) { |
|
630 | - $this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR); |
|
631 | - return false; |
|
632 | - } |
|
633 | - |
|
634 | - |
|
635 | - //make sure it is a square and not bigger than 128x128 |
|
636 | - $size = min([$this->image->width(), $this->image->height(), 128]); |
|
637 | - if(!$this->image->centerCrop($size)) { |
|
638 | - $this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR); |
|
639 | - return false; |
|
640 | - } |
|
641 | - |
|
642 | - if(!$this->fs->isLoaded()) { |
|
643 | - $this->fs->setup($this->uid); |
|
644 | - } |
|
645 | - |
|
646 | - try { |
|
647 | - $avatar = $this->avatarManager->getAvatar($this->uid); |
|
648 | - $avatar->set($this->image); |
|
649 | - return true; |
|
650 | - } catch (\Exception $e) { |
|
651 | - \OC::$server->getLogger()->logException($e, [ |
|
652 | - 'message' => 'Could not set avatar for ' . $this->dn, |
|
653 | - 'level' => ILogger::INFO, |
|
654 | - 'app' => 'user_ldap', |
|
655 | - ]); |
|
656 | - } |
|
657 | - return false; |
|
658 | - } |
|
659 | - |
|
660 | - /** |
|
661 | - * @throws AttributeNotSet |
|
662 | - * @throws \OC\ServerNotAvailableException |
|
663 | - * @throws \OCP\PreConditionNotMetException |
|
664 | - */ |
|
665 | - public function getExtStorageHome():string { |
|
666 | - $value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', ''); |
|
667 | - if ($value !== '') { |
|
668 | - return $value; |
|
669 | - } |
|
670 | - |
|
671 | - $value = $this->updateExtStorageHome(); |
|
672 | - if ($value !== '') { |
|
673 | - return $value; |
|
674 | - } |
|
675 | - |
|
676 | - throw new AttributeNotSet(sprintf( |
|
677 | - 'external home storage attribute yield no value for %s', $this->getUsername() |
|
678 | - )); |
|
679 | - } |
|
680 | - |
|
681 | - /** |
|
682 | - * @throws \OCP\PreConditionNotMetException |
|
683 | - * @throws \OC\ServerNotAvailableException |
|
684 | - */ |
|
685 | - public function updateExtStorageHome(string $valueFromLDAP = null):string { |
|
686 | - if ($valueFromLDAP === null) { |
|
687 | - $extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute); |
|
688 | - } else { |
|
689 | - $extHomeValues = [$valueFromLDAP]; |
|
690 | - } |
|
691 | - if ($extHomeValues && isset($extHomeValues[0])) { |
|
692 | - $extHome = $extHomeValues[0]; |
|
693 | - $this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome); |
|
694 | - return $extHome; |
|
695 | - } else { |
|
696 | - $this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome'); |
|
697 | - return ''; |
|
698 | - } |
|
699 | - } |
|
700 | - |
|
701 | - /** |
|
702 | - * called by a post_login hook to handle password expiry |
|
703 | - * |
|
704 | - * @param array $params |
|
705 | - */ |
|
706 | - public function handlePasswordExpiry($params) { |
|
707 | - $ppolicyDN = $this->connection->ldapDefaultPPolicyDN; |
|
708 | - if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) { |
|
709 | - return;//password expiry handling disabled |
|
710 | - } |
|
711 | - $uid = $params['uid']; |
|
712 | - if (isset($uid) && $uid === $this->getUsername()) { |
|
713 | - //retrieve relevant user attributes |
|
714 | - $result = $this->access->search('objectclass=*', [$this->dn], ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']); |
|
715 | - |
|
716 | - if (array_key_exists('pwdpolicysubentry', $result[0])) { |
|
717 | - $pwdPolicySubentry = $result[0]['pwdpolicysubentry']; |
|
718 | - if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){ |
|
719 | - $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN |
|
720 | - } |
|
721 | - } |
|
722 | - |
|
723 | - $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : []; |
|
724 | - $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : []; |
|
725 | - $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : []; |
|
726 | - |
|
727 | - //retrieve relevant password policy attributes |
|
728 | - $cacheKey = 'ppolicyAttributes' . $ppolicyDN; |
|
729 | - $result = $this->connection->getFromCache($cacheKey); |
|
730 | - if(is_null($result)) { |
|
731 | - $result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']); |
|
732 | - $this->connection->writeToCache($cacheKey, $result); |
|
733 | - } |
|
734 | - |
|
735 | - $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : []; |
|
736 | - $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : []; |
|
737 | - $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : []; |
|
738 | - |
|
739 | - //handle grace login |
|
740 | - if (!empty($pwdGraceUseTime)) { //was this a grace login? |
|
741 | - if (!empty($pwdGraceAuthNLimit) |
|
742 | - && count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available? |
|
743 | - $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true'); |
|
744 | - header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute( |
|
745 | - 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid])); |
|
746 | - } else { //no more grace login available |
|
747 | - header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute( |
|
748 | - 'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid])); |
|
749 | - } |
|
750 | - exit(); |
|
751 | - } |
|
752 | - //handle pwdReset attribute |
|
753 | - if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password |
|
754 | - $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true'); |
|
755 | - header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute( |
|
756 | - 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid])); |
|
757 | - exit(); |
|
758 | - } |
|
759 | - //handle password expiry warning |
|
760 | - if (!empty($pwdChangedTime)) { |
|
761 | - if (!empty($pwdMaxAge) |
|
762 | - && !empty($pwdExpireWarning)) { |
|
763 | - $pwdMaxAgeInt = (int)$pwdMaxAge[0]; |
|
764 | - $pwdExpireWarningInt = (int)$pwdExpireWarning[0]; |
|
765 | - if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){ |
|
766 | - $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]); |
|
767 | - $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S')); |
|
768 | - $currentDateTime = new \DateTime(); |
|
769 | - $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp(); |
|
770 | - if ($secondsToExpiry <= $pwdExpireWarningInt) { |
|
771 | - //remove last password expiry warning if any |
|
772 | - $notification = $this->notificationManager->createNotification(); |
|
773 | - $notification->setApp('user_ldap') |
|
774 | - ->setUser($uid) |
|
775 | - ->setObject('pwd_exp_warn', $uid) |
|
776 | - ; |
|
777 | - $this->notificationManager->markProcessed($notification); |
|
778 | - //create new password expiry warning |
|
779 | - $notification = $this->notificationManager->createNotification(); |
|
780 | - $notification->setApp('user_ldap') |
|
781 | - ->setUser($uid) |
|
782 | - ->setDateTime($currentDateTime) |
|
783 | - ->setObject('pwd_exp_warn', $uid) |
|
784 | - ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)]) |
|
785 | - ; |
|
786 | - $this->notificationManager->notify($notification); |
|
787 | - } |
|
788 | - } |
|
789 | - } |
|
790 | - } |
|
791 | - } |
|
792 | - } |
|
52 | + /** |
|
53 | + * @var Access |
|
54 | + */ |
|
55 | + protected $access; |
|
56 | + /** |
|
57 | + * @var Connection |
|
58 | + */ |
|
59 | + protected $connection; |
|
60 | + /** |
|
61 | + * @var IConfig |
|
62 | + */ |
|
63 | + protected $config; |
|
64 | + /** |
|
65 | + * @var FilesystemHelper |
|
66 | + */ |
|
67 | + protected $fs; |
|
68 | + /** |
|
69 | + * @var Image |
|
70 | + */ |
|
71 | + protected $image; |
|
72 | + /** |
|
73 | + * @var LogWrapper |
|
74 | + */ |
|
75 | + protected $log; |
|
76 | + /** |
|
77 | + * @var IAvatarManager |
|
78 | + */ |
|
79 | + protected $avatarManager; |
|
80 | + /** |
|
81 | + * @var IUserManager |
|
82 | + */ |
|
83 | + protected $userManager; |
|
84 | + /** |
|
85 | + * @var INotificationManager |
|
86 | + */ |
|
87 | + protected $notificationManager; |
|
88 | + /** |
|
89 | + * @var string |
|
90 | + */ |
|
91 | + protected $dn; |
|
92 | + /** |
|
93 | + * @var string |
|
94 | + */ |
|
95 | + protected $uid; |
|
96 | + /** |
|
97 | + * @var string[] |
|
98 | + */ |
|
99 | + protected $refreshedFeatures = []; |
|
100 | + /** |
|
101 | + * @var string |
|
102 | + */ |
|
103 | + protected $avatarImage; |
|
104 | + |
|
105 | + /** |
|
106 | + * DB config keys for user preferences |
|
107 | + */ |
|
108 | + const USER_PREFKEY_FIRSTLOGIN = 'firstLoginAccomplished'; |
|
109 | + const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh'; |
|
110 | + |
|
111 | + /** |
|
112 | + * @brief constructor, make sure the subclasses call this one! |
|
113 | + * @param string $username the internal username |
|
114 | + * @param string $dn the LDAP DN |
|
115 | + * @param Access $access |
|
116 | + * @param IConfig $config |
|
117 | + * @param FilesystemHelper $fs |
|
118 | + * @param Image $image any empty instance |
|
119 | + * @param LogWrapper $log |
|
120 | + * @param IAvatarManager $avatarManager |
|
121 | + * @param IUserManager $userManager |
|
122 | + * @param INotificationManager $notificationManager |
|
123 | + */ |
|
124 | + public function __construct($username, $dn, Access $access, |
|
125 | + IConfig $config, FilesystemHelper $fs, Image $image, |
|
126 | + LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager, |
|
127 | + INotificationManager $notificationManager) { |
|
128 | + |
|
129 | + if ($username === null) { |
|
130 | + $log->log("uid for '$dn' must not be null!", ILogger::ERROR); |
|
131 | + throw new \InvalidArgumentException('uid must not be null!'); |
|
132 | + } else if ($username === '') { |
|
133 | + $log->log("uid for '$dn' must not be an empty string", ILogger::ERROR); |
|
134 | + throw new \InvalidArgumentException('uid must not be an empty string!'); |
|
135 | + } |
|
136 | + |
|
137 | + $this->access = $access; |
|
138 | + $this->connection = $access->getConnection(); |
|
139 | + $this->config = $config; |
|
140 | + $this->fs = $fs; |
|
141 | + $this->dn = $dn; |
|
142 | + $this->uid = $username; |
|
143 | + $this->image = $image; |
|
144 | + $this->log = $log; |
|
145 | + $this->avatarManager = $avatarManager; |
|
146 | + $this->userManager = $userManager; |
|
147 | + $this->notificationManager = $notificationManager; |
|
148 | + |
|
149 | + \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry'); |
|
150 | + } |
|
151 | + |
|
152 | + /** |
|
153 | + * @brief updates properties like email, quota or avatar provided by LDAP |
|
154 | + * @return null |
|
155 | + */ |
|
156 | + public function update() { |
|
157 | + if(is_null($this->dn)) { |
|
158 | + return null; |
|
159 | + } |
|
160 | + |
|
161 | + $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap', |
|
162 | + self::USER_PREFKEY_FIRSTLOGIN, 0); |
|
163 | + |
|
164 | + if($this->needsRefresh()) { |
|
165 | + $this->updateEmail(); |
|
166 | + $this->updateQuota(); |
|
167 | + if($hasLoggedIn !== 0) { |
|
168 | + //we do not need to try it, when the user has not been logged in |
|
169 | + //before, because the file system will not be ready. |
|
170 | + $this->updateAvatar(); |
|
171 | + //in order to get an avatar as soon as possible, mark the user |
|
172 | + //as refreshed only when updating the avatar did happen |
|
173 | + $this->markRefreshTime(); |
|
174 | + } |
|
175 | + } |
|
176 | + } |
|
177 | + |
|
178 | + /** |
|
179 | + * marks a user as deleted |
|
180 | + * |
|
181 | + * @throws \OCP\PreConditionNotMetException |
|
182 | + */ |
|
183 | + public function markUser() { |
|
184 | + $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0'); |
|
185 | + if($curValue === '1') { |
|
186 | + // the user is already marked, do not write to DB again |
|
187 | + return; |
|
188 | + } |
|
189 | + $this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1'); |
|
190 | + $this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time()); |
|
191 | + } |
|
192 | + |
|
193 | + /** |
|
194 | + * processes results from LDAP for attributes as returned by getAttributesToRead() |
|
195 | + * @param array $ldapEntry the user entry as retrieved from LDAP |
|
196 | + */ |
|
197 | + public function processAttributes($ldapEntry) { |
|
198 | + $this->markRefreshTime(); |
|
199 | + //Quota |
|
200 | + $attr = strtolower($this->connection->ldapQuotaAttribute); |
|
201 | + if(isset($ldapEntry[$attr])) { |
|
202 | + $this->updateQuota($ldapEntry[$attr][0]); |
|
203 | + } else { |
|
204 | + if ($this->connection->ldapQuotaDefault !== '') { |
|
205 | + $this->updateQuota(); |
|
206 | + } |
|
207 | + } |
|
208 | + unset($attr); |
|
209 | + |
|
210 | + //displayName |
|
211 | + $displayName = $displayName2 = ''; |
|
212 | + $attr = strtolower($this->connection->ldapUserDisplayName); |
|
213 | + if(isset($ldapEntry[$attr])) { |
|
214 | + $displayName = (string)$ldapEntry[$attr][0]; |
|
215 | + } |
|
216 | + $attr = strtolower($this->connection->ldapUserDisplayName2); |
|
217 | + if(isset($ldapEntry[$attr])) { |
|
218 | + $displayName2 = (string)$ldapEntry[$attr][0]; |
|
219 | + } |
|
220 | + if ($displayName !== '') { |
|
221 | + $this->composeAndStoreDisplayName($displayName, $displayName2); |
|
222 | + $this->access->cacheUserDisplayName( |
|
223 | + $this->getUsername(), |
|
224 | + $displayName, |
|
225 | + $displayName2 |
|
226 | + ); |
|
227 | + } |
|
228 | + unset($attr); |
|
229 | + |
|
230 | ||
231 | + //email must be stored after displayname, because it would cause a user |
|
232 | + //change event that will trigger fetching the display name again |
|
233 | + $attr = strtolower($this->connection->ldapEmailAttribute); |
|
234 | + if(isset($ldapEntry[$attr])) { |
|
235 | + $this->updateEmail($ldapEntry[$attr][0]); |
|
236 | + } |
|
237 | + unset($attr); |
|
238 | + |
|
239 | + // LDAP Username, needed for s2s sharing |
|
240 | + if(isset($ldapEntry['uid'])) { |
|
241 | + $this->storeLDAPUserName($ldapEntry['uid'][0]); |
|
242 | + } else if(isset($ldapEntry['samaccountname'])) { |
|
243 | + $this->storeLDAPUserName($ldapEntry['samaccountname'][0]); |
|
244 | + } |
|
245 | + |
|
246 | + //homePath |
|
247 | + if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) { |
|
248 | + $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:'))); |
|
249 | + if(isset($ldapEntry[$attr])) { |
|
250 | + $this->access->cacheUserHome( |
|
251 | + $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0])); |
|
252 | + } |
|
253 | + } |
|
254 | + |
|
255 | + //memberOf groups |
|
256 | + $cacheKey = 'getMemberOf'.$this->getUsername(); |
|
257 | + $groups = false; |
|
258 | + if(isset($ldapEntry['memberof'])) { |
|
259 | + $groups = $ldapEntry['memberof']; |
|
260 | + } |
|
261 | + $this->connection->writeToCache($cacheKey, $groups); |
|
262 | + |
|
263 | + //external storage var |
|
264 | + $attr = strtolower($this->connection->ldapExtStorageHomeAttribute); |
|
265 | + if(isset($ldapEntry[$attr])) { |
|
266 | + $this->updateExtStorageHome($ldapEntry[$attr][0]); |
|
267 | + } |
|
268 | + unset($attr); |
|
269 | + |
|
270 | + //Avatar |
|
271 | + /** @var Connection $connection */ |
|
272 | + $connection = $this->access->getConnection(); |
|
273 | + $attributes = $connection->resolveRule('avatar'); |
|
274 | + foreach ($attributes as $attribute) { |
|
275 | + if(isset($ldapEntry[$attribute])) { |
|
276 | + $this->avatarImage = $ldapEntry[$attribute][0]; |
|
277 | + // the call to the method that saves the avatar in the file |
|
278 | + // system must be postponed after the login. It is to ensure |
|
279 | + // external mounts are mounted properly (e.g. with login |
|
280 | + // credentials from the session). |
|
281 | + \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin'); |
|
282 | + break; |
|
283 | + } |
|
284 | + } |
|
285 | + } |
|
286 | + |
|
287 | + /** |
|
288 | + * @brief returns the LDAP DN of the user |
|
289 | + * @return string |
|
290 | + */ |
|
291 | + public function getDN() { |
|
292 | + return $this->dn; |
|
293 | + } |
|
294 | + |
|
295 | + /** |
|
296 | + * @brief returns the Nextcloud internal username of the user |
|
297 | + * @return string |
|
298 | + */ |
|
299 | + public function getUsername() { |
|
300 | + return $this->uid; |
|
301 | + } |
|
302 | + |
|
303 | + /** |
|
304 | + * returns the home directory of the user if specified by LDAP settings |
|
305 | + * @param string $valueFromLDAP |
|
306 | + * @return bool|string |
|
307 | + * @throws \Exception |
|
308 | + */ |
|
309 | + public function getHomePath($valueFromLDAP = null) { |
|
310 | + $path = (string)$valueFromLDAP; |
|
311 | + $attr = null; |
|
312 | + |
|
313 | + if (is_null($valueFromLDAP) |
|
314 | + && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0 |
|
315 | + && $this->access->connection->homeFolderNamingRule !== 'attr:') |
|
316 | + { |
|
317 | + $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:')); |
|
318 | + $homedir = $this->access->readAttribute( |
|
319 | + $this->access->username2dn($this->getUsername()), $attr); |
|
320 | + if ($homedir && isset($homedir[0])) { |
|
321 | + $path = $homedir[0]; |
|
322 | + } |
|
323 | + } |
|
324 | + |
|
325 | + if ($path !== '') { |
|
326 | + //if attribute's value is an absolute path take this, otherwise append it to data dir |
|
327 | + //check for / at the beginning or pattern c:\ resp. c:/ |
|
328 | + if( '/' !== $path[0] |
|
329 | + && !(3 < strlen($path) && ctype_alpha($path[0]) |
|
330 | + && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2])) |
|
331 | + ) { |
|
332 | + $path = $this->config->getSystemValue('datadirectory', |
|
333 | + \OC::$SERVERROOT.'/data' ) . '/' . $path; |
|
334 | + } |
|
335 | + //we need it to store it in the DB as well in case a user gets |
|
336 | + //deleted so we can clean up afterwards |
|
337 | + $this->config->setUserValue( |
|
338 | + $this->getUsername(), 'user_ldap', 'homePath', $path |
|
339 | + ); |
|
340 | + return $path; |
|
341 | + } |
|
342 | + |
|
343 | + if( !is_null($attr) |
|
344 | + && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true) |
|
345 | + ) { |
|
346 | + // a naming rule attribute is defined, but it doesn't exist for that LDAP user |
|
347 | + throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername()); |
|
348 | + } |
|
349 | + |
|
350 | + //false will apply default behaviour as defined and done by OC_User |
|
351 | + $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', ''); |
|
352 | + return false; |
|
353 | + } |
|
354 | + |
|
355 | + public function getMemberOfGroups() { |
|
356 | + $cacheKey = 'getMemberOf'.$this->getUsername(); |
|
357 | + $memberOfGroups = $this->connection->getFromCache($cacheKey); |
|
358 | + if(!is_null($memberOfGroups)) { |
|
359 | + return $memberOfGroups; |
|
360 | + } |
|
361 | + $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf'); |
|
362 | + $this->connection->writeToCache($cacheKey, $groupDNs); |
|
363 | + return $groupDNs; |
|
364 | + } |
|
365 | + |
|
366 | + /** |
|
367 | + * @brief reads the image from LDAP that shall be used as Avatar |
|
368 | + * @return string data (provided by LDAP) | false |
|
369 | + */ |
|
370 | + public function getAvatarImage() { |
|
371 | + if(!is_null($this->avatarImage)) { |
|
372 | + return $this->avatarImage; |
|
373 | + } |
|
374 | + |
|
375 | + $this->avatarImage = false; |
|
376 | + /** @var Connection $connection */ |
|
377 | + $connection = $this->access->getConnection(); |
|
378 | + $attributes = $connection->resolveRule('avatar'); |
|
379 | + foreach($attributes as $attribute) { |
|
380 | + $result = $this->access->readAttribute($this->dn, $attribute); |
|
381 | + if($result !== false && is_array($result) && isset($result[0])) { |
|
382 | + $this->avatarImage = $result[0]; |
|
383 | + break; |
|
384 | + } |
|
385 | + } |
|
386 | + |
|
387 | + return $this->avatarImage; |
|
388 | + } |
|
389 | + |
|
390 | + /** |
|
391 | + * @brief marks the user as having logged in at least once |
|
392 | + * @return null |
|
393 | + */ |
|
394 | + public function markLogin() { |
|
395 | + $this->config->setUserValue( |
|
396 | + $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1); |
|
397 | + } |
|
398 | + |
|
399 | + /** |
|
400 | + * @brief marks the time when user features like email have been updated |
|
401 | + * @return null |
|
402 | + */ |
|
403 | + public function markRefreshTime() { |
|
404 | + $this->config->setUserValue( |
|
405 | + $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time()); |
|
406 | + } |
|
407 | + |
|
408 | + /** |
|
409 | + * @brief checks whether user features needs to be updated again by |
|
410 | + * comparing the difference of time of the last refresh to now with the |
|
411 | + * desired interval |
|
412 | + * @return bool |
|
413 | + */ |
|
414 | + private function needsRefresh() { |
|
415 | + $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap', |
|
416 | + self::USER_PREFKEY_LASTREFRESH, 0); |
|
417 | + |
|
418 | + if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) { |
|
419 | + return false; |
|
420 | + } |
|
421 | + return true; |
|
422 | + } |
|
423 | + |
|
424 | + /** |
|
425 | + * Stores a key-value pair in relation to this user |
|
426 | + * |
|
427 | + * @param string $key |
|
428 | + * @param string $value |
|
429 | + */ |
|
430 | + private function store($key, $value) { |
|
431 | + $this->config->setUserValue($this->uid, 'user_ldap', $key, $value); |
|
432 | + } |
|
433 | + |
|
434 | + /** |
|
435 | + * Composes the display name and stores it in the database. The final |
|
436 | + * display name is returned. |
|
437 | + * |
|
438 | + * @param string $displayName |
|
439 | + * @param string $displayName2 |
|
440 | + * @return string the effective display name |
|
441 | + */ |
|
442 | + public function composeAndStoreDisplayName($displayName, $displayName2 = '') { |
|
443 | + $displayName2 = (string)$displayName2; |
|
444 | + if($displayName2 !== '') { |
|
445 | + $displayName .= ' (' . $displayName2 . ')'; |
|
446 | + } |
|
447 | + $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null); |
|
448 | + if ($oldName !== $displayName) { |
|
449 | + $this->store('displayName', $displayName); |
|
450 | + $user = $this->userManager->get($this->getUsername()); |
|
451 | + if (!empty($oldName) && $user instanceof \OC\User\User) { |
|
452 | + // if it was empty, it would be a new record, not a change emitting the trigger could |
|
453 | + // potentially cause a UniqueConstraintViolationException, depending on some factors. |
|
454 | + $user->triggerChange('displayName', $displayName, $oldName); |
|
455 | + } |
|
456 | + } |
|
457 | + return $displayName; |
|
458 | + } |
|
459 | + |
|
460 | + /** |
|
461 | + * Stores the LDAP Username in the Database |
|
462 | + * @param string $userName |
|
463 | + */ |
|
464 | + public function storeLDAPUserName($userName) { |
|
465 | + $this->store('uid', $userName); |
|
466 | + } |
|
467 | + |
|
468 | + /** |
|
469 | + * @brief checks whether an update method specified by feature was run |
|
470 | + * already. If not, it will marked like this, because it is expected that |
|
471 | + * the method will be run, when false is returned. |
|
472 | + * @param string $feature email | quota | avatar (can be extended) |
|
473 | + * @return bool |
|
474 | + */ |
|
475 | + private function wasRefreshed($feature) { |
|
476 | + if(isset($this->refreshedFeatures[$feature])) { |
|
477 | + return true; |
|
478 | + } |
|
479 | + $this->refreshedFeatures[$feature] = 1; |
|
480 | + return false; |
|
481 | + } |
|
482 | + |
|
483 | + /** |
|
484 | + * fetches the email from LDAP and stores it as Nextcloud user value |
|
485 | + * @param string $valueFromLDAP if known, to save an LDAP read request |
|
486 | + * @return null |
|
487 | + */ |
|
488 | + public function updateEmail($valueFromLDAP = null) { |
|
489 | + if($this->wasRefreshed('email')) { |
|
490 | + return; |
|
491 | + } |
|
492 | + $email = (string)$valueFromLDAP; |
|
493 | + if(is_null($valueFromLDAP)) { |
|
494 | + $emailAttribute = $this->connection->ldapEmailAttribute; |
|
495 | + if ($emailAttribute !== '') { |
|
496 | + $aEmail = $this->access->readAttribute($this->dn, $emailAttribute); |
|
497 | + if(is_array($aEmail) && (count($aEmail) > 0)) { |
|
498 | + $email = (string)$aEmail[0]; |
|
499 | + } |
|
500 | + } |
|
501 | + } |
|
502 | + if ($email !== '') { |
|
503 | + $user = $this->userManager->get($this->uid); |
|
504 | + if (!is_null($user)) { |
|
505 | + $currentEmail = (string)$user->getEMailAddress(); |
|
506 | + if ($currentEmail !== $email) { |
|
507 | + $user->setEMailAddress($email); |
|
508 | + } |
|
509 | + } |
|
510 | + } |
|
511 | + } |
|
512 | + |
|
513 | + /** |
|
514 | + * Overall process goes as follow: |
|
515 | + * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function |
|
516 | + * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota |
|
517 | + * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default') |
|
518 | + * 4. check if the target user exists and set the quota for the user. |
|
519 | + * |
|
520 | + * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP |
|
521 | + * parameter can be passed with the value of the attribute. This value will be considered as the |
|
522 | + * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to |
|
523 | + * fetch all the user's attributes in one call and use the fetched values in this function. |
|
524 | + * The expected value for that parameter is a string describing the quota for the user. Valid |
|
525 | + * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in |
|
526 | + * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info) |
|
527 | + * |
|
528 | + * fetches the quota from LDAP and stores it as Nextcloud user value |
|
529 | + * @param string $valueFromLDAP the quota attribute's value can be passed, |
|
530 | + * to save the readAttribute request |
|
531 | + * @return null |
|
532 | + */ |
|
533 | + public function updateQuota($valueFromLDAP = null) { |
|
534 | + if($this->wasRefreshed('quota')) { |
|
535 | + return; |
|
536 | + } |
|
537 | + |
|
538 | + $quotaAttribute = $this->connection->ldapQuotaAttribute; |
|
539 | + $defaultQuota = $this->connection->ldapQuotaDefault; |
|
540 | + if($quotaAttribute === '' && $defaultQuota === '') { |
|
541 | + return; |
|
542 | + } |
|
543 | + |
|
544 | + $quota = false; |
|
545 | + if(is_null($valueFromLDAP) && $quotaAttribute !== '') { |
|
546 | + $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute); |
|
547 | + if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) { |
|
548 | + $quota = $aQuota[0]; |
|
549 | + } else if(is_array($aQuota) && isset($aQuota[0])) { |
|
550 | + $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG); |
|
551 | + } |
|
552 | + } else if ($this->verifyQuotaValue($valueFromLDAP)) { |
|
553 | + $quota = $valueFromLDAP; |
|
554 | + } else { |
|
555 | + $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG); |
|
556 | + } |
|
557 | + |
|
558 | + if ($quota === false && $this->verifyQuotaValue($defaultQuota)) { |
|
559 | + // quota not found using the LDAP attribute (or not parseable). Try the default quota |
|
560 | + $quota = $defaultQuota; |
|
561 | + } else if($quota === false) { |
|
562 | + $this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG); |
|
563 | + return; |
|
564 | + } |
|
565 | + |
|
566 | + $targetUser = $this->userManager->get($this->uid); |
|
567 | + if ($targetUser instanceof IUser) { |
|
568 | + $targetUser->setQuota($quota); |
|
569 | + } else { |
|
570 | + $this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO); |
|
571 | + } |
|
572 | + } |
|
573 | + |
|
574 | + private function verifyQuotaValue($quotaValue) { |
|
575 | + return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false; |
|
576 | + } |
|
577 | + |
|
578 | + /** |
|
579 | + * called by a post_login hook to save the avatar picture |
|
580 | + * |
|
581 | + * @param array $params |
|
582 | + */ |
|
583 | + public function updateAvatarPostLogin($params) { |
|
584 | + if(isset($params['uid']) && $params['uid'] === $this->getUsername()) { |
|
585 | + $this->updateAvatar(); |
|
586 | + } |
|
587 | + } |
|
588 | + |
|
589 | + /** |
|
590 | + * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar |
|
591 | + * @return bool |
|
592 | + */ |
|
593 | + public function updateAvatar($force = false) { |
|
594 | + if(!$force && $this->wasRefreshed('avatar')) { |
|
595 | + return false; |
|
596 | + } |
|
597 | + $avatarImage = $this->getAvatarImage(); |
|
598 | + if($avatarImage === false) { |
|
599 | + //not set, nothing left to do; |
|
600 | + return false; |
|
601 | + } |
|
602 | + |
|
603 | + if(!$this->image->loadFromBase64(base64_encode($avatarImage))) { |
|
604 | + return false; |
|
605 | + } |
|
606 | + |
|
607 | + // use the checksum before modifications |
|
608 | + $checksum = md5($this->image->data()); |
|
609 | + |
|
610 | + if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) { |
|
611 | + return true; |
|
612 | + } |
|
613 | + |
|
614 | + $isSet = $this->setOwnCloudAvatar(); |
|
615 | + |
|
616 | + if($isSet) { |
|
617 | + // save checksum only after successful setting |
|
618 | + $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum); |
|
619 | + } |
|
620 | + |
|
621 | + return $isSet; |
|
622 | + } |
|
623 | + |
|
624 | + /** |
|
625 | + * @brief sets an image as Nextcloud avatar |
|
626 | + * @return bool |
|
627 | + */ |
|
628 | + private function setOwnCloudAvatar() { |
|
629 | + if(!$this->image->valid()) { |
|
630 | + $this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR); |
|
631 | + return false; |
|
632 | + } |
|
633 | + |
|
634 | + |
|
635 | + //make sure it is a square and not bigger than 128x128 |
|
636 | + $size = min([$this->image->width(), $this->image->height(), 128]); |
|
637 | + if(!$this->image->centerCrop($size)) { |
|
638 | + $this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR); |
|
639 | + return false; |
|
640 | + } |
|
641 | + |
|
642 | + if(!$this->fs->isLoaded()) { |
|
643 | + $this->fs->setup($this->uid); |
|
644 | + } |
|
645 | + |
|
646 | + try { |
|
647 | + $avatar = $this->avatarManager->getAvatar($this->uid); |
|
648 | + $avatar->set($this->image); |
|
649 | + return true; |
|
650 | + } catch (\Exception $e) { |
|
651 | + \OC::$server->getLogger()->logException($e, [ |
|
652 | + 'message' => 'Could not set avatar for ' . $this->dn, |
|
653 | + 'level' => ILogger::INFO, |
|
654 | + 'app' => 'user_ldap', |
|
655 | + ]); |
|
656 | + } |
|
657 | + return false; |
|
658 | + } |
|
659 | + |
|
660 | + /** |
|
661 | + * @throws AttributeNotSet |
|
662 | + * @throws \OC\ServerNotAvailableException |
|
663 | + * @throws \OCP\PreConditionNotMetException |
|
664 | + */ |
|
665 | + public function getExtStorageHome():string { |
|
666 | + $value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', ''); |
|
667 | + if ($value !== '') { |
|
668 | + return $value; |
|
669 | + } |
|
670 | + |
|
671 | + $value = $this->updateExtStorageHome(); |
|
672 | + if ($value !== '') { |
|
673 | + return $value; |
|
674 | + } |
|
675 | + |
|
676 | + throw new AttributeNotSet(sprintf( |
|
677 | + 'external home storage attribute yield no value for %s', $this->getUsername() |
|
678 | + )); |
|
679 | + } |
|
680 | + |
|
681 | + /** |
|
682 | + * @throws \OCP\PreConditionNotMetException |
|
683 | + * @throws \OC\ServerNotAvailableException |
|
684 | + */ |
|
685 | + public function updateExtStorageHome(string $valueFromLDAP = null):string { |
|
686 | + if ($valueFromLDAP === null) { |
|
687 | + $extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute); |
|
688 | + } else { |
|
689 | + $extHomeValues = [$valueFromLDAP]; |
|
690 | + } |
|
691 | + if ($extHomeValues && isset($extHomeValues[0])) { |
|
692 | + $extHome = $extHomeValues[0]; |
|
693 | + $this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome); |
|
694 | + return $extHome; |
|
695 | + } else { |
|
696 | + $this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome'); |
|
697 | + return ''; |
|
698 | + } |
|
699 | + } |
|
700 | + |
|
701 | + /** |
|
702 | + * called by a post_login hook to handle password expiry |
|
703 | + * |
|
704 | + * @param array $params |
|
705 | + */ |
|
706 | + public function handlePasswordExpiry($params) { |
|
707 | + $ppolicyDN = $this->connection->ldapDefaultPPolicyDN; |
|
708 | + if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) { |
|
709 | + return;//password expiry handling disabled |
|
710 | + } |
|
711 | + $uid = $params['uid']; |
|
712 | + if (isset($uid) && $uid === $this->getUsername()) { |
|
713 | + //retrieve relevant user attributes |
|
714 | + $result = $this->access->search('objectclass=*', [$this->dn], ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']); |
|
715 | + |
|
716 | + if (array_key_exists('pwdpolicysubentry', $result[0])) { |
|
717 | + $pwdPolicySubentry = $result[0]['pwdpolicysubentry']; |
|
718 | + if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){ |
|
719 | + $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN |
|
720 | + } |
|
721 | + } |
|
722 | + |
|
723 | + $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : []; |
|
724 | + $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : []; |
|
725 | + $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : []; |
|
726 | + |
|
727 | + //retrieve relevant password policy attributes |
|
728 | + $cacheKey = 'ppolicyAttributes' . $ppolicyDN; |
|
729 | + $result = $this->connection->getFromCache($cacheKey); |
|
730 | + if(is_null($result)) { |
|
731 | + $result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']); |
|
732 | + $this->connection->writeToCache($cacheKey, $result); |
|
733 | + } |
|
734 | + |
|
735 | + $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : []; |
|
736 | + $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : []; |
|
737 | + $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : []; |
|
738 | + |
|
739 | + //handle grace login |
|
740 | + if (!empty($pwdGraceUseTime)) { //was this a grace login? |
|
741 | + if (!empty($pwdGraceAuthNLimit) |
|
742 | + && count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available? |
|
743 | + $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true'); |
|
744 | + header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute( |
|
745 | + 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid])); |
|
746 | + } else { //no more grace login available |
|
747 | + header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute( |
|
748 | + 'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid])); |
|
749 | + } |
|
750 | + exit(); |
|
751 | + } |
|
752 | + //handle pwdReset attribute |
|
753 | + if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password |
|
754 | + $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true'); |
|
755 | + header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute( |
|
756 | + 'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid])); |
|
757 | + exit(); |
|
758 | + } |
|
759 | + //handle password expiry warning |
|
760 | + if (!empty($pwdChangedTime)) { |
|
761 | + if (!empty($pwdMaxAge) |
|
762 | + && !empty($pwdExpireWarning)) { |
|
763 | + $pwdMaxAgeInt = (int)$pwdMaxAge[0]; |
|
764 | + $pwdExpireWarningInt = (int)$pwdExpireWarning[0]; |
|
765 | + if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){ |
|
766 | + $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]); |
|
767 | + $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S')); |
|
768 | + $currentDateTime = new \DateTime(); |
|
769 | + $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp(); |
|
770 | + if ($secondsToExpiry <= $pwdExpireWarningInt) { |
|
771 | + //remove last password expiry warning if any |
|
772 | + $notification = $this->notificationManager->createNotification(); |
|
773 | + $notification->setApp('user_ldap') |
|
774 | + ->setUser($uid) |
|
775 | + ->setObject('pwd_exp_warn', $uid) |
|
776 | + ; |
|
777 | + $this->notificationManager->markProcessed($notification); |
|
778 | + //create new password expiry warning |
|
779 | + $notification = $this->notificationManager->createNotification(); |
|
780 | + $notification->setApp('user_ldap') |
|
781 | + ->setUser($uid) |
|
782 | + ->setDateTime($currentDateTime) |
|
783 | + ->setObject('pwd_exp_warn', $uid) |
|
784 | + ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)]) |
|
785 | + ; |
|
786 | + $this->notificationManager->notify($notification); |
|
787 | + } |
|
788 | + } |
|
789 | + } |
|
790 | + } |
|
791 | + } |
|
792 | + } |
|
793 | 793 | } |
@@ -48,1235 +48,1235 @@ |
||
48 | 48 | use OCP\ILogger; |
49 | 49 | |
50 | 50 | class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend { |
51 | - protected $enabled = false; |
|
52 | - |
|
53 | - /** |
|
54 | - * @var string[] $cachedGroupMembers array of users with gid as key |
|
55 | - */ |
|
56 | - protected $cachedGroupMembers; |
|
57 | - |
|
58 | - /** |
|
59 | - * @var string[] $cachedGroupsByMember array of groups with uid as key |
|
60 | - */ |
|
61 | - protected $cachedGroupsByMember; |
|
62 | - |
|
63 | - /** |
|
64 | - * @var string[] $cachedNestedGroups array of groups with gid (DN) as key |
|
65 | - */ |
|
66 | - protected $cachedNestedGroups; |
|
67 | - |
|
68 | - /** @var GroupPluginManager */ |
|
69 | - protected $groupPluginManager; |
|
70 | - |
|
71 | - public function __construct(Access $access, GroupPluginManager $groupPluginManager) { |
|
72 | - parent::__construct($access); |
|
73 | - $filter = $this->access->connection->ldapGroupFilter; |
|
74 | - $gassoc = $this->access->connection->ldapGroupMemberAssocAttr; |
|
75 | - if(!empty($filter) && !empty($gassoc)) { |
|
76 | - $this->enabled = true; |
|
77 | - } |
|
78 | - |
|
79 | - $this->cachedGroupMembers = new CappedMemoryCache(); |
|
80 | - $this->cachedGroupsByMember = new CappedMemoryCache(); |
|
81 | - $this->cachedNestedGroups = new CappedMemoryCache(); |
|
82 | - $this->groupPluginManager = $groupPluginManager; |
|
83 | - } |
|
84 | - |
|
85 | - /** |
|
86 | - * is user in group? |
|
87 | - * @param string $uid uid of the user |
|
88 | - * @param string $gid gid of the group |
|
89 | - * @return bool |
|
90 | - * |
|
91 | - * Checks whether the user is member of a group or not. |
|
92 | - */ |
|
93 | - public function inGroup($uid, $gid) { |
|
94 | - if(!$this->enabled) { |
|
95 | - return false; |
|
96 | - } |
|
97 | - $cacheKey = 'inGroup'.$uid.':'.$gid; |
|
98 | - $inGroup = $this->access->connection->getFromCache($cacheKey); |
|
99 | - if(!is_null($inGroup)) { |
|
100 | - return (bool)$inGroup; |
|
101 | - } |
|
102 | - |
|
103 | - $userDN = $this->access->username2dn($uid); |
|
104 | - |
|
105 | - if(isset($this->cachedGroupMembers[$gid])) { |
|
106 | - $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]); |
|
107 | - return $isInGroup; |
|
108 | - } |
|
109 | - |
|
110 | - $cacheKeyMembers = 'inGroup-members:'.$gid; |
|
111 | - $members = $this->access->connection->getFromCache($cacheKeyMembers); |
|
112 | - if(!is_null($members)) { |
|
113 | - $this->cachedGroupMembers[$gid] = $members; |
|
114 | - $isInGroup = in_array($userDN, $members, true); |
|
115 | - $this->access->connection->writeToCache($cacheKey, $isInGroup); |
|
116 | - return $isInGroup; |
|
117 | - } |
|
118 | - |
|
119 | - $groupDN = $this->access->groupname2dn($gid); |
|
120 | - // just in case |
|
121 | - if(!$groupDN || !$userDN) { |
|
122 | - $this->access->connection->writeToCache($cacheKey, false); |
|
123 | - return false; |
|
124 | - } |
|
125 | - |
|
126 | - //check primary group first |
|
127 | - if($gid === $this->getUserPrimaryGroup($userDN)) { |
|
128 | - $this->access->connection->writeToCache($cacheKey, true); |
|
129 | - return true; |
|
130 | - } |
|
131 | - |
|
132 | - //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course. |
|
133 | - $members = $this->_groupMembers($groupDN); |
|
134 | - if(!is_array($members) || count($members) === 0) { |
|
135 | - $this->access->connection->writeToCache($cacheKey, false); |
|
136 | - return false; |
|
137 | - } |
|
138 | - |
|
139 | - //extra work if we don't get back user DNs |
|
140 | - if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { |
|
141 | - $dns = []; |
|
142 | - $filterParts = []; |
|
143 | - $bytes = 0; |
|
144 | - foreach($members as $mid) { |
|
145 | - $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter); |
|
146 | - $filterParts[] = $filter; |
|
147 | - $bytes += strlen($filter); |
|
148 | - if($bytes >= 9000000) { |
|
149 | - // AD has a default input buffer of 10 MB, we do not want |
|
150 | - // to take even the chance to exceed it |
|
151 | - $filter = $this->access->combineFilterWithOr($filterParts); |
|
152 | - $bytes = 0; |
|
153 | - $filterParts = []; |
|
154 | - $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); |
|
155 | - $dns = array_merge($dns, $users); |
|
156 | - } |
|
157 | - } |
|
158 | - if(count($filterParts) > 0) { |
|
159 | - $filter = $this->access->combineFilterWithOr($filterParts); |
|
160 | - $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); |
|
161 | - $dns = array_merge($dns, $users); |
|
162 | - } |
|
163 | - $members = $dns; |
|
164 | - } |
|
165 | - |
|
166 | - $isInGroup = in_array($userDN, $members); |
|
167 | - $this->access->connection->writeToCache($cacheKey, $isInGroup); |
|
168 | - $this->access->connection->writeToCache($cacheKeyMembers, $members); |
|
169 | - $this->cachedGroupMembers[$gid] = $members; |
|
170 | - |
|
171 | - return $isInGroup; |
|
172 | - } |
|
173 | - |
|
174 | - /** |
|
175 | - * @param string $dnGroup |
|
176 | - * @return array |
|
177 | - * |
|
178 | - * For a group that has user membership defined by an LDAP search url attribute returns the users |
|
179 | - * that match the search url otherwise returns an empty array. |
|
180 | - */ |
|
181 | - public function getDynamicGroupMembers($dnGroup) { |
|
182 | - $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); |
|
183 | - |
|
184 | - if (empty($dynamicGroupMemberURL)) { |
|
185 | - return []; |
|
186 | - } |
|
187 | - |
|
188 | - $dynamicMembers = []; |
|
189 | - $memberURLs = $this->access->readAttribute( |
|
190 | - $dnGroup, |
|
191 | - $dynamicGroupMemberURL, |
|
192 | - $this->access->connection->ldapGroupFilter |
|
193 | - ); |
|
194 | - if ($memberURLs !== false) { |
|
195 | - // this group has the 'memberURL' attribute so this is a dynamic group |
|
196 | - // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice) |
|
197 | - // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500)) |
|
198 | - $pos = strpos($memberURLs[0], '('); |
|
199 | - if ($pos !== false) { |
|
200 | - $memberUrlFilter = substr($memberURLs[0], $pos); |
|
201 | - $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn'); |
|
202 | - $dynamicMembers = []; |
|
203 | - foreach($foundMembers as $value) { |
|
204 | - $dynamicMembers[$value['dn'][0]] = 1; |
|
205 | - } |
|
206 | - } else { |
|
207 | - \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. |
|
208 | - 'of group ' . $dnGroup, ILogger::DEBUG); |
|
209 | - } |
|
210 | - } |
|
211 | - return $dynamicMembers; |
|
212 | - } |
|
213 | - |
|
214 | - /** |
|
215 | - * @param string $dnGroup |
|
216 | - * @param array|null &$seen |
|
217 | - * @return array|mixed|null |
|
218 | - * @throws \OC\ServerNotAvailableException |
|
219 | - */ |
|
220 | - private function _groupMembers($dnGroup, &$seen = null) { |
|
221 | - if ($seen === null) { |
|
222 | - $seen = []; |
|
223 | - } |
|
224 | - $allMembers = []; |
|
225 | - if (array_key_exists($dnGroup, $seen)) { |
|
226 | - // avoid loops |
|
227 | - return []; |
|
228 | - } |
|
229 | - // used extensively in cron job, caching makes sense for nested groups |
|
230 | - $cacheKey = '_groupMembers'.$dnGroup; |
|
231 | - $groupMembers = $this->access->connection->getFromCache($cacheKey); |
|
232 | - if($groupMembers !== null) { |
|
233 | - return $groupMembers; |
|
234 | - } |
|
235 | - $seen[$dnGroup] = 1; |
|
236 | - $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr); |
|
237 | - if (is_array($members)) { |
|
238 | - $fetcher = function($memberDN, &$seen) { |
|
239 | - return $this->_groupMembers($memberDN, $seen); |
|
240 | - }; |
|
241 | - $allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members); |
|
242 | - } |
|
243 | - |
|
244 | - $allMembers += $this->getDynamicGroupMembers($dnGroup); |
|
245 | - |
|
246 | - $this->access->connection->writeToCache($cacheKey, $allMembers); |
|
247 | - return $allMembers; |
|
248 | - } |
|
249 | - |
|
250 | - /** |
|
251 | - * @param string $DN |
|
252 | - * @param array|null &$seen |
|
253 | - * @return array |
|
254 | - * @throws \OC\ServerNotAvailableException |
|
255 | - */ |
|
256 | - private function _getGroupDNsFromMemberOf($DN) { |
|
257 | - $groups = $this->access->readAttribute($DN, 'memberOf'); |
|
258 | - if (!is_array($groups)) { |
|
259 | - return []; |
|
260 | - } |
|
261 | - |
|
262 | - $fetcher = function($groupDN) { |
|
263 | - if (isset($this->cachedNestedGroups[$groupDN])) { |
|
264 | - $nestedGroups = $this->cachedNestedGroups[$groupDN]; |
|
265 | - } else { |
|
266 | - $nestedGroups = $this->access->readAttribute($groupDN, 'memberOf'); |
|
267 | - if (!is_array($nestedGroups)) { |
|
268 | - $nestedGroups = []; |
|
269 | - } |
|
270 | - $this->cachedNestedGroups[$groupDN] = $nestedGroups; |
|
271 | - } |
|
272 | - return $nestedGroups; |
|
273 | - }; |
|
274 | - |
|
275 | - $groups = $this->walkNestedGroups($DN, $fetcher, $groups); |
|
276 | - return $this->access->groupsMatchFilter($groups); |
|
277 | - } |
|
278 | - |
|
279 | - /** |
|
280 | - * @param string $dn |
|
281 | - * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns |
|
282 | - * @param array $list |
|
283 | - * @return array |
|
284 | - */ |
|
285 | - private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array { |
|
286 | - $nesting = (int) $this->access->connection->ldapNestedGroups; |
|
287 | - // depending on the input, we either have a list of DNs or a list of LDAP records |
|
288 | - // also, the output expects either DNs or records. Testing the first element should suffice. |
|
289 | - $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]); |
|
290 | - |
|
291 | - if ($nesting !== 1) { |
|
292 | - if($recordMode) { |
|
293 | - // the keys are numeric, but should hold the DN |
|
294 | - return array_reduce($list, function ($transformed, $record) use ($dn) { |
|
295 | - if($record['dn'][0] != $dn) { |
|
296 | - $transformed[$record['dn'][0]] = $record; |
|
297 | - } |
|
298 | - return $transformed; |
|
299 | - }, []); |
|
300 | - } |
|
301 | - return $list; |
|
302 | - } |
|
303 | - |
|
304 | - $seen = []; |
|
305 | - while ($record = array_pop($list)) { |
|
306 | - $recordDN = $recordMode ? $record['dn'][0] : $record; |
|
307 | - if ($recordDN === $dn || array_key_exists($recordDN, $seen)) { |
|
308 | - // Prevent loops |
|
309 | - continue; |
|
310 | - } |
|
311 | - $fetched = $fetcher($record, $seen); |
|
312 | - $list = array_merge($list, $fetched); |
|
313 | - $seen[$recordDN] = $record; |
|
314 | - } |
|
315 | - |
|
316 | - return $recordMode ? $seen : array_keys($seen); |
|
317 | - } |
|
318 | - |
|
319 | - /** |
|
320 | - * translates a gidNumber into an ownCloud internal name |
|
321 | - * @param string $gid as given by gidNumber on POSIX LDAP |
|
322 | - * @param string $dn a DN that belongs to the same domain as the group |
|
323 | - * @return string|bool |
|
324 | - */ |
|
325 | - public function gidNumber2Name($gid, $dn) { |
|
326 | - $cacheKey = 'gidNumberToName' . $gid; |
|
327 | - $groupName = $this->access->connection->getFromCache($cacheKey); |
|
328 | - if(!is_null($groupName) && isset($groupName)) { |
|
329 | - return $groupName; |
|
330 | - } |
|
331 | - |
|
332 | - //we need to get the DN from LDAP |
|
333 | - $filter = $this->access->combineFilterWithAnd([ |
|
334 | - $this->access->connection->ldapGroupFilter, |
|
335 | - 'objectClass=posixGroup', |
|
336 | - $this->access->connection->ldapGidNumber . '=' . $gid |
|
337 | - ]); |
|
338 | - $result = $this->access->searchGroups($filter, ['dn'], 1); |
|
339 | - if(empty($result)) { |
|
340 | - return false; |
|
341 | - } |
|
342 | - $dn = $result[0]['dn'][0]; |
|
343 | - |
|
344 | - //and now the group name |
|
345 | - //NOTE once we have separate ownCloud group IDs and group names we can |
|
346 | - //directly read the display name attribute instead of the DN |
|
347 | - $name = $this->access->dn2groupname($dn); |
|
348 | - |
|
349 | - $this->access->connection->writeToCache($cacheKey, $name); |
|
350 | - |
|
351 | - return $name; |
|
352 | - } |
|
353 | - |
|
354 | - /** |
|
355 | - * returns the entry's gidNumber |
|
356 | - * @param string $dn |
|
357 | - * @param string $attribute |
|
358 | - * @return string|bool |
|
359 | - */ |
|
360 | - private function getEntryGidNumber($dn, $attribute) { |
|
361 | - $value = $this->access->readAttribute($dn, $attribute); |
|
362 | - if(is_array($value) && !empty($value)) { |
|
363 | - return $value[0]; |
|
364 | - } |
|
365 | - return false; |
|
366 | - } |
|
367 | - |
|
368 | - /** |
|
369 | - * returns the group's primary ID |
|
370 | - * @param string $dn |
|
371 | - * @return string|bool |
|
372 | - */ |
|
373 | - public function getGroupGidNumber($dn) { |
|
374 | - return $this->getEntryGidNumber($dn, 'gidNumber'); |
|
375 | - } |
|
376 | - |
|
377 | - /** |
|
378 | - * returns the user's gidNumber |
|
379 | - * @param string $dn |
|
380 | - * @return string|bool |
|
381 | - */ |
|
382 | - public function getUserGidNumber($dn) { |
|
383 | - $gidNumber = false; |
|
384 | - if($this->access->connection->hasGidNumber) { |
|
385 | - $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber); |
|
386 | - if($gidNumber === false) { |
|
387 | - $this->access->connection->hasGidNumber = false; |
|
388 | - } |
|
389 | - } |
|
390 | - return $gidNumber; |
|
391 | - } |
|
392 | - |
|
393 | - /** |
|
394 | - * returns a filter for a "users has specific gid" search or count operation |
|
395 | - * |
|
396 | - * @param string $groupDN |
|
397 | - * @param string $search |
|
398 | - * @return string |
|
399 | - * @throws \Exception |
|
400 | - */ |
|
401 | - private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') { |
|
402 | - $groupID = $this->getGroupGidNumber($groupDN); |
|
403 | - if($groupID === false) { |
|
404 | - throw new \Exception('Not a valid group'); |
|
405 | - } |
|
406 | - |
|
407 | - $filterParts = []; |
|
408 | - $filterParts[] = $this->access->getFilterForUserCount(); |
|
409 | - if ($search !== '') { |
|
410 | - $filterParts[] = $this->access->getFilterPartForUserSearch($search); |
|
411 | - } |
|
412 | - $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID; |
|
413 | - |
|
414 | - return $this->access->combineFilterWithAnd($filterParts); |
|
415 | - } |
|
416 | - |
|
417 | - /** |
|
418 | - * returns a list of users that have the given group as gid number |
|
419 | - * |
|
420 | - * @param string $groupDN |
|
421 | - * @param string $search |
|
422 | - * @param int $limit |
|
423 | - * @param int $offset |
|
424 | - * @return string[] |
|
425 | - */ |
|
426 | - public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
427 | - try { |
|
428 | - $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); |
|
429 | - $users = $this->access->fetchListOfUsers( |
|
430 | - $filter, |
|
431 | - [$this->access->connection->ldapUserDisplayName, 'dn'], |
|
432 | - $limit, |
|
433 | - $offset |
|
434 | - ); |
|
435 | - return $this->access->nextcloudUserNames($users); |
|
436 | - } catch (\Exception $e) { |
|
437 | - return []; |
|
438 | - } |
|
439 | - } |
|
440 | - |
|
441 | - /** |
|
442 | - * returns the number of users that have the given group as gid number |
|
443 | - * |
|
444 | - * @param string $groupDN |
|
445 | - * @param string $search |
|
446 | - * @param int $limit |
|
447 | - * @param int $offset |
|
448 | - * @return int |
|
449 | - */ |
|
450 | - public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
451 | - try { |
|
452 | - $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); |
|
453 | - $users = $this->access->countUsers($filter, ['dn'], $limit, $offset); |
|
454 | - return (int)$users; |
|
455 | - } catch (\Exception $e) { |
|
456 | - return 0; |
|
457 | - } |
|
458 | - } |
|
459 | - |
|
460 | - /** |
|
461 | - * gets the gidNumber of a user |
|
462 | - * @param string $dn |
|
463 | - * @return string |
|
464 | - */ |
|
465 | - public function getUserGroupByGid($dn) { |
|
466 | - $groupID = $this->getUserGidNumber($dn); |
|
467 | - if($groupID !== false) { |
|
468 | - $groupName = $this->gidNumber2Name($groupID, $dn); |
|
469 | - if($groupName !== false) { |
|
470 | - return $groupName; |
|
471 | - } |
|
472 | - } |
|
473 | - |
|
474 | - return false; |
|
475 | - } |
|
476 | - |
|
477 | - /** |
|
478 | - * translates a primary group ID into an Nextcloud internal name |
|
479 | - * @param string $gid as given by primaryGroupID on AD |
|
480 | - * @param string $dn a DN that belongs to the same domain as the group |
|
481 | - * @return string|bool |
|
482 | - */ |
|
483 | - public function primaryGroupID2Name($gid, $dn) { |
|
484 | - $cacheKey = 'primaryGroupIDtoName'; |
|
485 | - $groupNames = $this->access->connection->getFromCache($cacheKey); |
|
486 | - if(!is_null($groupNames) && isset($groupNames[$gid])) { |
|
487 | - return $groupNames[$gid]; |
|
488 | - } |
|
489 | - |
|
490 | - $domainObjectSid = $this->access->getSID($dn); |
|
491 | - if($domainObjectSid === false) { |
|
492 | - return false; |
|
493 | - } |
|
494 | - |
|
495 | - //we need to get the DN from LDAP |
|
496 | - $filter = $this->access->combineFilterWithAnd([ |
|
497 | - $this->access->connection->ldapGroupFilter, |
|
498 | - 'objectsid=' . $domainObjectSid . '-' . $gid |
|
499 | - ]); |
|
500 | - $result = $this->access->searchGroups($filter, ['dn'], 1); |
|
501 | - if(empty($result)) { |
|
502 | - return false; |
|
503 | - } |
|
504 | - $dn = $result[0]['dn'][0]; |
|
505 | - |
|
506 | - //and now the group name |
|
507 | - //NOTE once we have separate Nextcloud group IDs and group names we can |
|
508 | - //directly read the display name attribute instead of the DN |
|
509 | - $name = $this->access->dn2groupname($dn); |
|
510 | - |
|
511 | - $this->access->connection->writeToCache($cacheKey, $name); |
|
512 | - |
|
513 | - return $name; |
|
514 | - } |
|
515 | - |
|
516 | - /** |
|
517 | - * returns the entry's primary group ID |
|
518 | - * @param string $dn |
|
519 | - * @param string $attribute |
|
520 | - * @return string|bool |
|
521 | - */ |
|
522 | - private function getEntryGroupID($dn, $attribute) { |
|
523 | - $value = $this->access->readAttribute($dn, $attribute); |
|
524 | - if(is_array($value) && !empty($value)) { |
|
525 | - return $value[0]; |
|
526 | - } |
|
527 | - return false; |
|
528 | - } |
|
529 | - |
|
530 | - /** |
|
531 | - * returns the group's primary ID |
|
532 | - * @param string $dn |
|
533 | - * @return string|bool |
|
534 | - */ |
|
535 | - public function getGroupPrimaryGroupID($dn) { |
|
536 | - return $this->getEntryGroupID($dn, 'primaryGroupToken'); |
|
537 | - } |
|
538 | - |
|
539 | - /** |
|
540 | - * returns the user's primary group ID |
|
541 | - * @param string $dn |
|
542 | - * @return string|bool |
|
543 | - */ |
|
544 | - public function getUserPrimaryGroupIDs($dn) { |
|
545 | - $primaryGroupID = false; |
|
546 | - if($this->access->connection->hasPrimaryGroups) { |
|
547 | - $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID'); |
|
548 | - if($primaryGroupID === false) { |
|
549 | - $this->access->connection->hasPrimaryGroups = false; |
|
550 | - } |
|
551 | - } |
|
552 | - return $primaryGroupID; |
|
553 | - } |
|
554 | - |
|
555 | - /** |
|
556 | - * returns a filter for a "users in primary group" search or count operation |
|
557 | - * |
|
558 | - * @param string $groupDN |
|
559 | - * @param string $search |
|
560 | - * @return string |
|
561 | - * @throws \Exception |
|
562 | - */ |
|
563 | - private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') { |
|
564 | - $groupID = $this->getGroupPrimaryGroupID($groupDN); |
|
565 | - if($groupID === false) { |
|
566 | - throw new \Exception('Not a valid group'); |
|
567 | - } |
|
568 | - |
|
569 | - $filterParts = []; |
|
570 | - $filterParts[] = $this->access->getFilterForUserCount(); |
|
571 | - if ($search !== '') { |
|
572 | - $filterParts[] = $this->access->getFilterPartForUserSearch($search); |
|
573 | - } |
|
574 | - $filterParts[] = 'primaryGroupID=' . $groupID; |
|
575 | - |
|
576 | - return $this->access->combineFilterWithAnd($filterParts); |
|
577 | - } |
|
578 | - |
|
579 | - /** |
|
580 | - * returns a list of users that have the given group as primary group |
|
581 | - * |
|
582 | - * @param string $groupDN |
|
583 | - * @param string $search |
|
584 | - * @param int $limit |
|
585 | - * @param int $offset |
|
586 | - * @return string[] |
|
587 | - */ |
|
588 | - public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
589 | - try { |
|
590 | - $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); |
|
591 | - $users = $this->access->fetchListOfUsers( |
|
592 | - $filter, |
|
593 | - [$this->access->connection->ldapUserDisplayName, 'dn'], |
|
594 | - $limit, |
|
595 | - $offset |
|
596 | - ); |
|
597 | - return $this->access->nextcloudUserNames($users); |
|
598 | - } catch (\Exception $e) { |
|
599 | - return []; |
|
600 | - } |
|
601 | - } |
|
602 | - |
|
603 | - /** |
|
604 | - * returns the number of users that have the given group as primary group |
|
605 | - * |
|
606 | - * @param string $groupDN |
|
607 | - * @param string $search |
|
608 | - * @param int $limit |
|
609 | - * @param int $offset |
|
610 | - * @return int |
|
611 | - */ |
|
612 | - public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
613 | - try { |
|
614 | - $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); |
|
615 | - $users = $this->access->countUsers($filter, ['dn'], $limit, $offset); |
|
616 | - return (int)$users; |
|
617 | - } catch (\Exception $e) { |
|
618 | - return 0; |
|
619 | - } |
|
620 | - } |
|
621 | - |
|
622 | - /** |
|
623 | - * gets the primary group of a user |
|
624 | - * @param string $dn |
|
625 | - * @return string |
|
626 | - */ |
|
627 | - public function getUserPrimaryGroup($dn) { |
|
628 | - $groupID = $this->getUserPrimaryGroupIDs($dn); |
|
629 | - if($groupID !== false) { |
|
630 | - $groupName = $this->primaryGroupID2Name($groupID, $dn); |
|
631 | - if($groupName !== false) { |
|
632 | - return $groupName; |
|
633 | - } |
|
634 | - } |
|
635 | - |
|
636 | - return false; |
|
637 | - } |
|
638 | - |
|
639 | - /** |
|
640 | - * Get all groups a user belongs to |
|
641 | - * @param string $uid Name of the user |
|
642 | - * @return array with group names |
|
643 | - * |
|
644 | - * This function fetches all groups a user belongs to. It does not check |
|
645 | - * if the user exists at all. |
|
646 | - * |
|
647 | - * This function includes groups based on dynamic group membership. |
|
648 | - */ |
|
649 | - public function getUserGroups($uid) { |
|
650 | - if(!$this->enabled) { |
|
651 | - return []; |
|
652 | - } |
|
653 | - $cacheKey = 'getUserGroups'.$uid; |
|
654 | - $userGroups = $this->access->connection->getFromCache($cacheKey); |
|
655 | - if(!is_null($userGroups)) { |
|
656 | - return $userGroups; |
|
657 | - } |
|
658 | - $userDN = $this->access->username2dn($uid); |
|
659 | - if(!$userDN) { |
|
660 | - $this->access->connection->writeToCache($cacheKey, []); |
|
661 | - return []; |
|
662 | - } |
|
663 | - |
|
664 | - $groups = []; |
|
665 | - $primaryGroup = $this->getUserPrimaryGroup($userDN); |
|
666 | - $gidGroupName = $this->getUserGroupByGid($userDN); |
|
667 | - |
|
668 | - $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); |
|
669 | - |
|
670 | - if (!empty($dynamicGroupMemberURL)) { |
|
671 | - // look through dynamic groups to add them to the result array if needed |
|
672 | - $groupsToMatch = $this->access->fetchListOfGroups( |
|
673 | - $this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]); |
|
674 | - foreach($groupsToMatch as $dynamicGroup) { |
|
675 | - if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) { |
|
676 | - continue; |
|
677 | - } |
|
678 | - $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '('); |
|
679 | - if ($pos !== false) { |
|
680 | - $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos); |
|
681 | - // apply filter via ldap search to see if this user is in this |
|
682 | - // dynamic group |
|
683 | - $userMatch = $this->access->readAttribute( |
|
684 | - $userDN, |
|
685 | - $this->access->connection->ldapUserDisplayName, |
|
686 | - $memberUrlFilter |
|
687 | - ); |
|
688 | - if ($userMatch !== false) { |
|
689 | - // match found so this user is in this group |
|
690 | - $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]); |
|
691 | - if(is_string($groupName)) { |
|
692 | - // be sure to never return false if the dn could not be |
|
693 | - // resolved to a name, for whatever reason. |
|
694 | - $groups[] = $groupName; |
|
695 | - } |
|
696 | - } |
|
697 | - } else { |
|
698 | - \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. |
|
699 | - 'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG); |
|
700 | - } |
|
701 | - } |
|
702 | - } |
|
703 | - |
|
704 | - // if possible, read out membership via memberOf. It's far faster than |
|
705 | - // performing a search, which still is a fallback later. |
|
706 | - // memberof doesn't support memberuid, so skip it here. |
|
707 | - if((int)$this->access->connection->hasMemberOfFilterSupport === 1 |
|
708 | - && (int)$this->access->connection->useMemberOfToDetectMembership === 1 |
|
709 | - && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid' |
|
710 | - ) { |
|
711 | - $groupDNs = $this->_getGroupDNsFromMemberOf($userDN); |
|
712 | - if (is_array($groupDNs)) { |
|
713 | - foreach ($groupDNs as $dn) { |
|
714 | - $groupName = $this->access->dn2groupname($dn); |
|
715 | - if(is_string($groupName)) { |
|
716 | - // be sure to never return false if the dn could not be |
|
717 | - // resolved to a name, for whatever reason. |
|
718 | - $groups[] = $groupName; |
|
719 | - } |
|
720 | - } |
|
721 | - } |
|
722 | - |
|
723 | - if($primaryGroup !== false) { |
|
724 | - $groups[] = $primaryGroup; |
|
725 | - } |
|
726 | - if($gidGroupName !== false) { |
|
727 | - $groups[] = $gidGroupName; |
|
728 | - } |
|
729 | - $this->access->connection->writeToCache($cacheKey, $groups); |
|
730 | - return $groups; |
|
731 | - } |
|
732 | - |
|
733 | - //uniqueMember takes DN, memberuid the uid, so we need to distinguish |
|
734 | - if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') |
|
735 | - || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member') |
|
736 | - ) { |
|
737 | - $uid = $userDN; |
|
738 | - } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { |
|
739 | - $result = $this->access->readAttribute($userDN, 'uid'); |
|
740 | - if ($result === false) { |
|
741 | - \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '. |
|
742 | - $this->access->connection->ldapHost, ILogger::DEBUG); |
|
743 | - $uid = false; |
|
744 | - } else { |
|
745 | - $uid = $result[0]; |
|
746 | - } |
|
747 | - } else { |
|
748 | - // just in case |
|
749 | - $uid = $userDN; |
|
750 | - } |
|
751 | - |
|
752 | - if($uid !== false) { |
|
753 | - if (isset($this->cachedGroupsByMember[$uid])) { |
|
754 | - $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]); |
|
755 | - } else { |
|
756 | - $groupsByMember = array_values($this->getGroupsByMember($uid)); |
|
757 | - $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember); |
|
758 | - $this->cachedGroupsByMember[$uid] = $groupsByMember; |
|
759 | - $groups = array_merge($groups, $groupsByMember); |
|
760 | - } |
|
761 | - } |
|
762 | - |
|
763 | - if($primaryGroup !== false) { |
|
764 | - $groups[] = $primaryGroup; |
|
765 | - } |
|
766 | - if($gidGroupName !== false) { |
|
767 | - $groups[] = $gidGroupName; |
|
768 | - } |
|
769 | - |
|
770 | - $groups = array_unique($groups, SORT_LOCALE_STRING); |
|
771 | - $this->access->connection->writeToCache($cacheKey, $groups); |
|
772 | - |
|
773 | - return $groups; |
|
774 | - } |
|
775 | - |
|
776 | - /** |
|
777 | - * @param string $dn |
|
778 | - * @param array|null &$seen |
|
779 | - * @return array |
|
780 | - */ |
|
781 | - private function getGroupsByMember($dn, &$seen = null) { |
|
782 | - if ($seen === null) { |
|
783 | - $seen = []; |
|
784 | - } |
|
785 | - if (array_key_exists($dn, $seen)) { |
|
786 | - // avoid loops |
|
787 | - return []; |
|
788 | - } |
|
789 | - $allGroups = []; |
|
790 | - $seen[$dn] = true; |
|
791 | - $filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn; |
|
792 | - $groups = $this->access->fetchListOfGroups($filter, |
|
793 | - [$this->access->connection->ldapGroupDisplayName, 'dn']); |
|
794 | - if (is_array($groups)) { |
|
795 | - $fetcher = function ($dn, &$seen) { |
|
796 | - if(is_array($dn) && isset($dn['dn'][0])) { |
|
797 | - $dn = $dn['dn'][0]; |
|
798 | - } |
|
799 | - return $this->getGroupsByMember($dn, $seen); |
|
800 | - }; |
|
801 | - $allGroups = $this->walkNestedGroups($dn, $fetcher, $groups); |
|
802 | - } |
|
803 | - $visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups)); |
|
804 | - return array_intersect_key($allGroups, array_flip($visibleGroups)); |
|
805 | - } |
|
806 | - |
|
807 | - /** |
|
808 | - * get a list of all users in a group |
|
809 | - * |
|
810 | - * @param string $gid |
|
811 | - * @param string $search |
|
812 | - * @param int $limit |
|
813 | - * @param int $offset |
|
814 | - * @return array with user ids |
|
815 | - * @throws \Exception |
|
816 | - */ |
|
817 | - public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { |
|
818 | - if(!$this->enabled) { |
|
819 | - return []; |
|
820 | - } |
|
821 | - if(!$this->groupExists($gid)) { |
|
822 | - return []; |
|
823 | - } |
|
824 | - $search = $this->access->escapeFilterPart($search, true); |
|
825 | - $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset; |
|
826 | - // check for cache of the exact query |
|
827 | - $groupUsers = $this->access->connection->getFromCache($cacheKey); |
|
828 | - if(!is_null($groupUsers)) { |
|
829 | - return $groupUsers; |
|
830 | - } |
|
831 | - |
|
832 | - // check for cache of the query without limit and offset |
|
833 | - $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search); |
|
834 | - if(!is_null($groupUsers)) { |
|
835 | - $groupUsers = array_slice($groupUsers, $offset, $limit); |
|
836 | - $this->access->connection->writeToCache($cacheKey, $groupUsers); |
|
837 | - return $groupUsers; |
|
838 | - } |
|
839 | - |
|
840 | - if($limit === -1) { |
|
841 | - $limit = null; |
|
842 | - } |
|
843 | - $groupDN = $this->access->groupname2dn($gid); |
|
844 | - if(!$groupDN) { |
|
845 | - // group couldn't be found, return empty resultset |
|
846 | - $this->access->connection->writeToCache($cacheKey, []); |
|
847 | - return []; |
|
848 | - } |
|
849 | - |
|
850 | - $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset); |
|
851 | - $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset); |
|
852 | - $members = $this->_groupMembers($groupDN); |
|
853 | - if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) { |
|
854 | - //in case users could not be retrieved, return empty result set |
|
855 | - $this->access->connection->writeToCache($cacheKey, []); |
|
856 | - return []; |
|
857 | - } |
|
858 | - |
|
859 | - $groupUsers = []; |
|
860 | - $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid'); |
|
861 | - $attrs = $this->access->userManager->getAttributes(true); |
|
862 | - foreach($members as $member) { |
|
863 | - if($isMemberUid) { |
|
864 | - //we got uids, need to get their DNs to 'translate' them to user names |
|
865 | - $filter = $this->access->combineFilterWithAnd([ |
|
866 | - str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter), |
|
867 | - $this->access->combineFilterWithAnd([ |
|
868 | - $this->access->getFilterPartForUserSearch($search), |
|
869 | - $this->access->connection->ldapUserFilter |
|
870 | - ]) |
|
871 | - ]); |
|
872 | - $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1); |
|
873 | - if(count($ldap_users) < 1) { |
|
874 | - continue; |
|
875 | - } |
|
876 | - $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]); |
|
877 | - } else { |
|
878 | - //we got DNs, check if we need to filter by search or we can give back all of them |
|
879 | - $uid = $this->access->dn2username($member); |
|
880 | - if(!$uid) { |
|
881 | - continue; |
|
882 | - } |
|
883 | - |
|
884 | - $cacheKey = 'userExistsOnLDAP' . $uid; |
|
885 | - $userExists = $this->access->connection->getFromCache($cacheKey); |
|
886 | - if($userExists === false) { |
|
887 | - continue; |
|
888 | - } |
|
889 | - if($userExists === null || $search !== '') { |
|
890 | - if (!$this->access->readAttribute($member, |
|
891 | - $this->access->connection->ldapUserDisplayName, |
|
892 | - $this->access->combineFilterWithAnd([ |
|
893 | - $this->access->getFilterPartForUserSearch($search), |
|
894 | - $this->access->connection->ldapUserFilter |
|
895 | - ]))) |
|
896 | - { |
|
897 | - if($search === '') { |
|
898 | - $this->access->connection->writeToCache($cacheKey, false); |
|
899 | - } |
|
900 | - continue; |
|
901 | - } |
|
902 | - $this->access->connection->writeToCache($cacheKey, true); |
|
903 | - } |
|
904 | - $groupUsers[] = $uid; |
|
905 | - } |
|
906 | - } |
|
907 | - |
|
908 | - $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers)); |
|
909 | - natsort($groupUsers); |
|
910 | - $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers); |
|
911 | - $groupUsers = array_slice($groupUsers, $offset, $limit); |
|
912 | - |
|
913 | - $this->access->connection->writeToCache($cacheKey, $groupUsers); |
|
914 | - |
|
915 | - return $groupUsers; |
|
916 | - } |
|
917 | - |
|
918 | - /** |
|
919 | - * returns the number of users in a group, who match the search term |
|
920 | - * @param string $gid the internal group name |
|
921 | - * @param string $search optional, a search string |
|
922 | - * @return int|bool |
|
923 | - */ |
|
924 | - public function countUsersInGroup($gid, $search = '') { |
|
925 | - if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) { |
|
926 | - return $this->groupPluginManager->countUsersInGroup($gid, $search); |
|
927 | - } |
|
928 | - |
|
929 | - $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search; |
|
930 | - if(!$this->enabled || !$this->groupExists($gid)) { |
|
931 | - return false; |
|
932 | - } |
|
933 | - $groupUsers = $this->access->connection->getFromCache($cacheKey); |
|
934 | - if(!is_null($groupUsers)) { |
|
935 | - return $groupUsers; |
|
936 | - } |
|
937 | - |
|
938 | - $groupDN = $this->access->groupname2dn($gid); |
|
939 | - if(!$groupDN) { |
|
940 | - // group couldn't be found, return empty result set |
|
941 | - $this->access->connection->writeToCache($cacheKey, false); |
|
942 | - return false; |
|
943 | - } |
|
944 | - |
|
945 | - $members = $this->_groupMembers($groupDN); |
|
946 | - $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, ''); |
|
947 | - if(!$members && $primaryUserCount === 0) { |
|
948 | - //in case users could not be retrieved, return empty result set |
|
949 | - $this->access->connection->writeToCache($cacheKey, false); |
|
950 | - return false; |
|
951 | - } |
|
952 | - |
|
953 | - if ($search === '') { |
|
954 | - $groupUsers = count($members) + $primaryUserCount; |
|
955 | - $this->access->connection->writeToCache($cacheKey, $groupUsers); |
|
956 | - return $groupUsers; |
|
957 | - } |
|
958 | - $search = $this->access->escapeFilterPart($search, true); |
|
959 | - $isMemberUid = |
|
960 | - (strtolower($this->access->connection->ldapGroupMemberAssocAttr) |
|
961 | - === 'memberuid'); |
|
962 | - |
|
963 | - //we need to apply the search filter |
|
964 | - //alternatives that need to be checked: |
|
965 | - //a) get all users by search filter and array_intersect them |
|
966 | - //b) a, but only when less than 1k 10k ?k users like it is |
|
967 | - //c) put all DNs|uids in a LDAP filter, combine with the search string |
|
968 | - // and let it count. |
|
969 | - //For now this is not important, because the only use of this method |
|
970 | - //does not supply a search string |
|
971 | - $groupUsers = []; |
|
972 | - foreach($members as $member) { |
|
973 | - if($isMemberUid) { |
|
974 | - //we got uids, need to get their DNs to 'translate' them to user names |
|
975 | - $filter = $this->access->combineFilterWithAnd([ |
|
976 | - str_replace('%uid', $member, $this->access->connection->ldapLoginFilter), |
|
977 | - $this->access->getFilterPartForUserSearch($search) |
|
978 | - ]); |
|
979 | - $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1); |
|
980 | - if(count($ldap_users) < 1) { |
|
981 | - continue; |
|
982 | - } |
|
983 | - $groupUsers[] = $this->access->dn2username($ldap_users[0]); |
|
984 | - } else { |
|
985 | - //we need to apply the search filter now |
|
986 | - if(!$this->access->readAttribute($member, |
|
987 | - $this->access->connection->ldapUserDisplayName, |
|
988 | - $this->access->getFilterPartForUserSearch($search))) { |
|
989 | - continue; |
|
990 | - } |
|
991 | - // dn2username will also check if the users belong to the allowed base |
|
992 | - if($ocname = $this->access->dn2username($member)) { |
|
993 | - $groupUsers[] = $ocname; |
|
994 | - } |
|
995 | - } |
|
996 | - } |
|
997 | - |
|
998 | - //and get users that have the group as primary |
|
999 | - $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search); |
|
1000 | - |
|
1001 | - return count($groupUsers) + $primaryUsers; |
|
1002 | - } |
|
1003 | - |
|
1004 | - /** |
|
1005 | - * get a list of all groups |
|
1006 | - * |
|
1007 | - * @param string $search |
|
1008 | - * @param $limit |
|
1009 | - * @param int $offset |
|
1010 | - * @return array with group names |
|
1011 | - * |
|
1012 | - * Returns a list with all groups (used by getGroups) |
|
1013 | - */ |
|
1014 | - protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) { |
|
1015 | - if(!$this->enabled) { |
|
1016 | - return []; |
|
1017 | - } |
|
1018 | - $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset; |
|
1019 | - |
|
1020 | - //Check cache before driving unnecessary searches |
|
1021 | - \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG); |
|
1022 | - $ldap_groups = $this->access->connection->getFromCache($cacheKey); |
|
1023 | - if(!is_null($ldap_groups)) { |
|
1024 | - return $ldap_groups; |
|
1025 | - } |
|
1026 | - |
|
1027 | - // if we'd pass -1 to LDAP search, we'd end up in a Protocol |
|
1028 | - // error. With a limit of 0, we get 0 results. So we pass null. |
|
1029 | - if($limit <= 0) { |
|
1030 | - $limit = null; |
|
1031 | - } |
|
1032 | - $filter = $this->access->combineFilterWithAnd([ |
|
1033 | - $this->access->connection->ldapGroupFilter, |
|
1034 | - $this->access->getFilterPartForGroupSearch($search) |
|
1035 | - ]); |
|
1036 | - \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG); |
|
1037 | - $ldap_groups = $this->access->fetchListOfGroups($filter, |
|
1038 | - [$this->access->connection->ldapGroupDisplayName, 'dn'], |
|
1039 | - $limit, |
|
1040 | - $offset); |
|
1041 | - $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups); |
|
1042 | - |
|
1043 | - $this->access->connection->writeToCache($cacheKey, $ldap_groups); |
|
1044 | - return $ldap_groups; |
|
1045 | - } |
|
1046 | - |
|
1047 | - /** |
|
1048 | - * get a list of all groups using a paged search |
|
1049 | - * |
|
1050 | - * @param string $search |
|
1051 | - * @param int $limit |
|
1052 | - * @param int $offset |
|
1053 | - * @return array with group names |
|
1054 | - * |
|
1055 | - * Returns a list with all groups |
|
1056 | - * Uses a paged search if available to override a |
|
1057 | - * server side search limit. |
|
1058 | - * (active directory has a limit of 1000 by default) |
|
1059 | - */ |
|
1060 | - public function getGroups($search = '', $limit = -1, $offset = 0) { |
|
1061 | - if(!$this->enabled) { |
|
1062 | - return []; |
|
1063 | - } |
|
1064 | - $search = $this->access->escapeFilterPart($search, true); |
|
1065 | - $pagingSize = (int)$this->access->connection->ldapPagingSize; |
|
1066 | - if ($pagingSize <= 0) { |
|
1067 | - return $this->getGroupsChunk($search, $limit, $offset); |
|
1068 | - } |
|
1069 | - $maxGroups = 100000; // limit max results (just for safety reasons) |
|
1070 | - if ($limit > -1) { |
|
1071 | - $overallLimit = min($limit + $offset, $maxGroups); |
|
1072 | - } else { |
|
1073 | - $overallLimit = $maxGroups; |
|
1074 | - } |
|
1075 | - $chunkOffset = $offset; |
|
1076 | - $allGroups = []; |
|
1077 | - while ($chunkOffset < $overallLimit) { |
|
1078 | - $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset); |
|
1079 | - $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset); |
|
1080 | - $nread = count($ldapGroups); |
|
1081 | - \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG); |
|
1082 | - if ($nread) { |
|
1083 | - $allGroups = array_merge($allGroups, $ldapGroups); |
|
1084 | - $chunkOffset += $nread; |
|
1085 | - } |
|
1086 | - if ($nread < $chunkLimit) { |
|
1087 | - break; |
|
1088 | - } |
|
1089 | - } |
|
1090 | - return $allGroups; |
|
1091 | - } |
|
1092 | - |
|
1093 | - /** |
|
1094 | - * @param string $group |
|
1095 | - * @return bool |
|
1096 | - */ |
|
1097 | - public function groupMatchesFilter($group) { |
|
1098 | - return (strripos($group, $this->groupSearch) !== false); |
|
1099 | - } |
|
1100 | - |
|
1101 | - /** |
|
1102 | - * check if a group exists |
|
1103 | - * @param string $gid |
|
1104 | - * @return bool |
|
1105 | - */ |
|
1106 | - public function groupExists($gid) { |
|
1107 | - $groupExists = $this->access->connection->getFromCache('groupExists'.$gid); |
|
1108 | - if(!is_null($groupExists)) { |
|
1109 | - return (bool)$groupExists; |
|
1110 | - } |
|
1111 | - |
|
1112 | - //getting dn, if false the group does not exist. If dn, it may be mapped |
|
1113 | - //only, requires more checking. |
|
1114 | - $dn = $this->access->groupname2dn($gid); |
|
1115 | - if(!$dn) { |
|
1116 | - $this->access->connection->writeToCache('groupExists'.$gid, false); |
|
1117 | - return false; |
|
1118 | - } |
|
1119 | - |
|
1120 | - //if group really still exists, we will be able to read its objectclass |
|
1121 | - if(!is_array($this->access->readAttribute($dn, ''))) { |
|
1122 | - $this->access->connection->writeToCache('groupExists'.$gid, false); |
|
1123 | - return false; |
|
1124 | - } |
|
1125 | - |
|
1126 | - $this->access->connection->writeToCache('groupExists'.$gid, true); |
|
1127 | - return true; |
|
1128 | - } |
|
1129 | - |
|
1130 | - /** |
|
1131 | - * Check if backend implements actions |
|
1132 | - * @param int $actions bitwise-or'ed actions |
|
1133 | - * @return boolean |
|
1134 | - * |
|
1135 | - * Returns the supported actions as int to be |
|
1136 | - * compared with GroupInterface::CREATE_GROUP etc. |
|
1137 | - */ |
|
1138 | - public function implementsActions($actions) { |
|
1139 | - return (bool)((GroupInterface::COUNT_USERS | |
|
1140 | - $this->groupPluginManager->getImplementedActions()) & $actions); |
|
1141 | - } |
|
1142 | - |
|
1143 | - /** |
|
1144 | - * Return access for LDAP interaction. |
|
1145 | - * @return Access instance of Access for LDAP interaction |
|
1146 | - */ |
|
1147 | - public function getLDAPAccess($gid) { |
|
1148 | - return $this->access; |
|
1149 | - } |
|
1150 | - |
|
1151 | - /** |
|
1152 | - * create a group |
|
1153 | - * @param string $gid |
|
1154 | - * @return bool |
|
1155 | - * @throws \Exception |
|
1156 | - */ |
|
1157 | - public function createGroup($gid) { |
|
1158 | - if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) { |
|
1159 | - if ($dn = $this->groupPluginManager->createGroup($gid)) { |
|
1160 | - //updates group mapping |
|
1161 | - $uuid = $this->access->getUUID($dn, false); |
|
1162 | - if(is_string($uuid)) { |
|
1163 | - $this->access->mapAndAnnounceIfApplicable( |
|
1164 | - $this->access->getGroupMapper(), |
|
1165 | - $dn, |
|
1166 | - $gid, |
|
1167 | - $uuid, |
|
1168 | - false |
|
1169 | - ); |
|
1170 | - $this->access->cacheGroupExists($gid); |
|
1171 | - } |
|
1172 | - } |
|
1173 | - return $dn != null; |
|
1174 | - } |
|
1175 | - throw new \Exception('Could not create group in LDAP backend.'); |
|
1176 | - } |
|
1177 | - |
|
1178 | - /** |
|
1179 | - * delete a group |
|
1180 | - * @param string $gid gid of the group to delete |
|
1181 | - * @return bool |
|
1182 | - * @throws \Exception |
|
1183 | - */ |
|
1184 | - public function deleteGroup($gid) { |
|
1185 | - if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) { |
|
1186 | - if ($ret = $this->groupPluginManager->deleteGroup($gid)) { |
|
1187 | - #delete group in nextcloud internal db |
|
1188 | - $this->access->getGroupMapper()->unmap($gid); |
|
1189 | - $this->access->connection->writeToCache("groupExists".$gid, false); |
|
1190 | - } |
|
1191 | - return $ret; |
|
1192 | - } |
|
1193 | - throw new \Exception('Could not delete group in LDAP backend.'); |
|
1194 | - } |
|
1195 | - |
|
1196 | - /** |
|
1197 | - * Add a user to a group |
|
1198 | - * @param string $uid Name of the user to add to group |
|
1199 | - * @param string $gid Name of the group in which add the user |
|
1200 | - * @return bool |
|
1201 | - * @throws \Exception |
|
1202 | - */ |
|
1203 | - public function addToGroup($uid, $gid) { |
|
1204 | - if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) { |
|
1205 | - if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) { |
|
1206 | - $this->access->connection->clearCache(); |
|
1207 | - unset($this->cachedGroupMembers[$gid]); |
|
1208 | - } |
|
1209 | - return $ret; |
|
1210 | - } |
|
1211 | - throw new \Exception('Could not add user to group in LDAP backend.'); |
|
1212 | - } |
|
1213 | - |
|
1214 | - /** |
|
1215 | - * Removes a user from a group |
|
1216 | - * @param string $uid Name of the user to remove from group |
|
1217 | - * @param string $gid Name of the group from which remove the user |
|
1218 | - * @return bool |
|
1219 | - * @throws \Exception |
|
1220 | - */ |
|
1221 | - public function removeFromGroup($uid, $gid) { |
|
1222 | - if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) { |
|
1223 | - if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) { |
|
1224 | - $this->access->connection->clearCache(); |
|
1225 | - unset($this->cachedGroupMembers[$gid]); |
|
1226 | - } |
|
1227 | - return $ret; |
|
1228 | - } |
|
1229 | - throw new \Exception('Could not remove user from group in LDAP backend.'); |
|
1230 | - } |
|
1231 | - |
|
1232 | - /** |
|
1233 | - * Gets group details |
|
1234 | - * @param string $gid Name of the group |
|
1235 | - * @return array | false |
|
1236 | - * @throws \Exception |
|
1237 | - */ |
|
1238 | - public function getGroupDetails($gid) { |
|
1239 | - if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) { |
|
1240 | - return $this->groupPluginManager->getGroupDetails($gid); |
|
1241 | - } |
|
1242 | - throw new \Exception('Could not get group details in LDAP backend.'); |
|
1243 | - } |
|
1244 | - |
|
1245 | - /** |
|
1246 | - * Return LDAP connection resource from a cloned connection. |
|
1247 | - * The cloned connection needs to be closed manually. |
|
1248 | - * of the current access. |
|
1249 | - * @param string $gid |
|
1250 | - * @return resource of the LDAP connection |
|
1251 | - */ |
|
1252 | - public function getNewLDAPConnection($gid) { |
|
1253 | - $connection = clone $this->access->getConnection(); |
|
1254 | - return $connection->getConnectionResource(); |
|
1255 | - } |
|
1256 | - |
|
1257 | - /** |
|
1258 | - * @throws \OC\ServerNotAvailableException |
|
1259 | - */ |
|
1260 | - public function getDisplayName(string $gid): string { |
|
1261 | - if ($this->groupPluginManager instanceof IGetDisplayNameBackend) { |
|
1262 | - return $this->groupPluginManager->getDisplayName($gid); |
|
1263 | - } |
|
1264 | - |
|
1265 | - $cacheKey = 'group_getDisplayName' . $gid; |
|
1266 | - if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { |
|
1267 | - return $displayName; |
|
1268 | - } |
|
1269 | - |
|
1270 | - $displayName = $this->access->readAttribute( |
|
1271 | - $this->access->groupname2dn($gid), |
|
1272 | - $this->access->connection->ldapGroupDisplayName); |
|
1273 | - |
|
1274 | - if ($displayName && (count($displayName) > 0)) { |
|
1275 | - $displayName = $displayName[0]; |
|
1276 | - $this->access->connection->writeToCache($cacheKey, $displayName); |
|
1277 | - return $displayName; |
|
1278 | - } |
|
1279 | - |
|
1280 | - return ''; |
|
1281 | - } |
|
51 | + protected $enabled = false; |
|
52 | + |
|
53 | + /** |
|
54 | + * @var string[] $cachedGroupMembers array of users with gid as key |
|
55 | + */ |
|
56 | + protected $cachedGroupMembers; |
|
57 | + |
|
58 | + /** |
|
59 | + * @var string[] $cachedGroupsByMember array of groups with uid as key |
|
60 | + */ |
|
61 | + protected $cachedGroupsByMember; |
|
62 | + |
|
63 | + /** |
|
64 | + * @var string[] $cachedNestedGroups array of groups with gid (DN) as key |
|
65 | + */ |
|
66 | + protected $cachedNestedGroups; |
|
67 | + |
|
68 | + /** @var GroupPluginManager */ |
|
69 | + protected $groupPluginManager; |
|
70 | + |
|
71 | + public function __construct(Access $access, GroupPluginManager $groupPluginManager) { |
|
72 | + parent::__construct($access); |
|
73 | + $filter = $this->access->connection->ldapGroupFilter; |
|
74 | + $gassoc = $this->access->connection->ldapGroupMemberAssocAttr; |
|
75 | + if(!empty($filter) && !empty($gassoc)) { |
|
76 | + $this->enabled = true; |
|
77 | + } |
|
78 | + |
|
79 | + $this->cachedGroupMembers = new CappedMemoryCache(); |
|
80 | + $this->cachedGroupsByMember = new CappedMemoryCache(); |
|
81 | + $this->cachedNestedGroups = new CappedMemoryCache(); |
|
82 | + $this->groupPluginManager = $groupPluginManager; |
|
83 | + } |
|
84 | + |
|
85 | + /** |
|
86 | + * is user in group? |
|
87 | + * @param string $uid uid of the user |
|
88 | + * @param string $gid gid of the group |
|
89 | + * @return bool |
|
90 | + * |
|
91 | + * Checks whether the user is member of a group or not. |
|
92 | + */ |
|
93 | + public function inGroup($uid, $gid) { |
|
94 | + if(!$this->enabled) { |
|
95 | + return false; |
|
96 | + } |
|
97 | + $cacheKey = 'inGroup'.$uid.':'.$gid; |
|
98 | + $inGroup = $this->access->connection->getFromCache($cacheKey); |
|
99 | + if(!is_null($inGroup)) { |
|
100 | + return (bool)$inGroup; |
|
101 | + } |
|
102 | + |
|
103 | + $userDN = $this->access->username2dn($uid); |
|
104 | + |
|
105 | + if(isset($this->cachedGroupMembers[$gid])) { |
|
106 | + $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]); |
|
107 | + return $isInGroup; |
|
108 | + } |
|
109 | + |
|
110 | + $cacheKeyMembers = 'inGroup-members:'.$gid; |
|
111 | + $members = $this->access->connection->getFromCache($cacheKeyMembers); |
|
112 | + if(!is_null($members)) { |
|
113 | + $this->cachedGroupMembers[$gid] = $members; |
|
114 | + $isInGroup = in_array($userDN, $members, true); |
|
115 | + $this->access->connection->writeToCache($cacheKey, $isInGroup); |
|
116 | + return $isInGroup; |
|
117 | + } |
|
118 | + |
|
119 | + $groupDN = $this->access->groupname2dn($gid); |
|
120 | + // just in case |
|
121 | + if(!$groupDN || !$userDN) { |
|
122 | + $this->access->connection->writeToCache($cacheKey, false); |
|
123 | + return false; |
|
124 | + } |
|
125 | + |
|
126 | + //check primary group first |
|
127 | + if($gid === $this->getUserPrimaryGroup($userDN)) { |
|
128 | + $this->access->connection->writeToCache($cacheKey, true); |
|
129 | + return true; |
|
130 | + } |
|
131 | + |
|
132 | + //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course. |
|
133 | + $members = $this->_groupMembers($groupDN); |
|
134 | + if(!is_array($members) || count($members) === 0) { |
|
135 | + $this->access->connection->writeToCache($cacheKey, false); |
|
136 | + return false; |
|
137 | + } |
|
138 | + |
|
139 | + //extra work if we don't get back user DNs |
|
140 | + if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { |
|
141 | + $dns = []; |
|
142 | + $filterParts = []; |
|
143 | + $bytes = 0; |
|
144 | + foreach($members as $mid) { |
|
145 | + $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter); |
|
146 | + $filterParts[] = $filter; |
|
147 | + $bytes += strlen($filter); |
|
148 | + if($bytes >= 9000000) { |
|
149 | + // AD has a default input buffer of 10 MB, we do not want |
|
150 | + // to take even the chance to exceed it |
|
151 | + $filter = $this->access->combineFilterWithOr($filterParts); |
|
152 | + $bytes = 0; |
|
153 | + $filterParts = []; |
|
154 | + $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); |
|
155 | + $dns = array_merge($dns, $users); |
|
156 | + } |
|
157 | + } |
|
158 | + if(count($filterParts) > 0) { |
|
159 | + $filter = $this->access->combineFilterWithOr($filterParts); |
|
160 | + $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); |
|
161 | + $dns = array_merge($dns, $users); |
|
162 | + } |
|
163 | + $members = $dns; |
|
164 | + } |
|
165 | + |
|
166 | + $isInGroup = in_array($userDN, $members); |
|
167 | + $this->access->connection->writeToCache($cacheKey, $isInGroup); |
|
168 | + $this->access->connection->writeToCache($cacheKeyMembers, $members); |
|
169 | + $this->cachedGroupMembers[$gid] = $members; |
|
170 | + |
|
171 | + return $isInGroup; |
|
172 | + } |
|
173 | + |
|
174 | + /** |
|
175 | + * @param string $dnGroup |
|
176 | + * @return array |
|
177 | + * |
|
178 | + * For a group that has user membership defined by an LDAP search url attribute returns the users |
|
179 | + * that match the search url otherwise returns an empty array. |
|
180 | + */ |
|
181 | + public function getDynamicGroupMembers($dnGroup) { |
|
182 | + $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); |
|
183 | + |
|
184 | + if (empty($dynamicGroupMemberURL)) { |
|
185 | + return []; |
|
186 | + } |
|
187 | + |
|
188 | + $dynamicMembers = []; |
|
189 | + $memberURLs = $this->access->readAttribute( |
|
190 | + $dnGroup, |
|
191 | + $dynamicGroupMemberURL, |
|
192 | + $this->access->connection->ldapGroupFilter |
|
193 | + ); |
|
194 | + if ($memberURLs !== false) { |
|
195 | + // this group has the 'memberURL' attribute so this is a dynamic group |
|
196 | + // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice) |
|
197 | + // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500)) |
|
198 | + $pos = strpos($memberURLs[0], '('); |
|
199 | + if ($pos !== false) { |
|
200 | + $memberUrlFilter = substr($memberURLs[0], $pos); |
|
201 | + $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn'); |
|
202 | + $dynamicMembers = []; |
|
203 | + foreach($foundMembers as $value) { |
|
204 | + $dynamicMembers[$value['dn'][0]] = 1; |
|
205 | + } |
|
206 | + } else { |
|
207 | + \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. |
|
208 | + 'of group ' . $dnGroup, ILogger::DEBUG); |
|
209 | + } |
|
210 | + } |
|
211 | + return $dynamicMembers; |
|
212 | + } |
|
213 | + |
|
214 | + /** |
|
215 | + * @param string $dnGroup |
|
216 | + * @param array|null &$seen |
|
217 | + * @return array|mixed|null |
|
218 | + * @throws \OC\ServerNotAvailableException |
|
219 | + */ |
|
220 | + private function _groupMembers($dnGroup, &$seen = null) { |
|
221 | + if ($seen === null) { |
|
222 | + $seen = []; |
|
223 | + } |
|
224 | + $allMembers = []; |
|
225 | + if (array_key_exists($dnGroup, $seen)) { |
|
226 | + // avoid loops |
|
227 | + return []; |
|
228 | + } |
|
229 | + // used extensively in cron job, caching makes sense for nested groups |
|
230 | + $cacheKey = '_groupMembers'.$dnGroup; |
|
231 | + $groupMembers = $this->access->connection->getFromCache($cacheKey); |
|
232 | + if($groupMembers !== null) { |
|
233 | + return $groupMembers; |
|
234 | + } |
|
235 | + $seen[$dnGroup] = 1; |
|
236 | + $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr); |
|
237 | + if (is_array($members)) { |
|
238 | + $fetcher = function($memberDN, &$seen) { |
|
239 | + return $this->_groupMembers($memberDN, $seen); |
|
240 | + }; |
|
241 | + $allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members); |
|
242 | + } |
|
243 | + |
|
244 | + $allMembers += $this->getDynamicGroupMembers($dnGroup); |
|
245 | + |
|
246 | + $this->access->connection->writeToCache($cacheKey, $allMembers); |
|
247 | + return $allMembers; |
|
248 | + } |
|
249 | + |
|
250 | + /** |
|
251 | + * @param string $DN |
|
252 | + * @param array|null &$seen |
|
253 | + * @return array |
|
254 | + * @throws \OC\ServerNotAvailableException |
|
255 | + */ |
|
256 | + private function _getGroupDNsFromMemberOf($DN) { |
|
257 | + $groups = $this->access->readAttribute($DN, 'memberOf'); |
|
258 | + if (!is_array($groups)) { |
|
259 | + return []; |
|
260 | + } |
|
261 | + |
|
262 | + $fetcher = function($groupDN) { |
|
263 | + if (isset($this->cachedNestedGroups[$groupDN])) { |
|
264 | + $nestedGroups = $this->cachedNestedGroups[$groupDN]; |
|
265 | + } else { |
|
266 | + $nestedGroups = $this->access->readAttribute($groupDN, 'memberOf'); |
|
267 | + if (!is_array($nestedGroups)) { |
|
268 | + $nestedGroups = []; |
|
269 | + } |
|
270 | + $this->cachedNestedGroups[$groupDN] = $nestedGroups; |
|
271 | + } |
|
272 | + return $nestedGroups; |
|
273 | + }; |
|
274 | + |
|
275 | + $groups = $this->walkNestedGroups($DN, $fetcher, $groups); |
|
276 | + return $this->access->groupsMatchFilter($groups); |
|
277 | + } |
|
278 | + |
|
279 | + /** |
|
280 | + * @param string $dn |
|
281 | + * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns |
|
282 | + * @param array $list |
|
283 | + * @return array |
|
284 | + */ |
|
285 | + private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array { |
|
286 | + $nesting = (int) $this->access->connection->ldapNestedGroups; |
|
287 | + // depending on the input, we either have a list of DNs or a list of LDAP records |
|
288 | + // also, the output expects either DNs or records. Testing the first element should suffice. |
|
289 | + $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]); |
|
290 | + |
|
291 | + if ($nesting !== 1) { |
|
292 | + if($recordMode) { |
|
293 | + // the keys are numeric, but should hold the DN |
|
294 | + return array_reduce($list, function ($transformed, $record) use ($dn) { |
|
295 | + if($record['dn'][0] != $dn) { |
|
296 | + $transformed[$record['dn'][0]] = $record; |
|
297 | + } |
|
298 | + return $transformed; |
|
299 | + }, []); |
|
300 | + } |
|
301 | + return $list; |
|
302 | + } |
|
303 | + |
|
304 | + $seen = []; |
|
305 | + while ($record = array_pop($list)) { |
|
306 | + $recordDN = $recordMode ? $record['dn'][0] : $record; |
|
307 | + if ($recordDN === $dn || array_key_exists($recordDN, $seen)) { |
|
308 | + // Prevent loops |
|
309 | + continue; |
|
310 | + } |
|
311 | + $fetched = $fetcher($record, $seen); |
|
312 | + $list = array_merge($list, $fetched); |
|
313 | + $seen[$recordDN] = $record; |
|
314 | + } |
|
315 | + |
|
316 | + return $recordMode ? $seen : array_keys($seen); |
|
317 | + } |
|
318 | + |
|
319 | + /** |
|
320 | + * translates a gidNumber into an ownCloud internal name |
|
321 | + * @param string $gid as given by gidNumber on POSIX LDAP |
|
322 | + * @param string $dn a DN that belongs to the same domain as the group |
|
323 | + * @return string|bool |
|
324 | + */ |
|
325 | + public function gidNumber2Name($gid, $dn) { |
|
326 | + $cacheKey = 'gidNumberToName' . $gid; |
|
327 | + $groupName = $this->access->connection->getFromCache($cacheKey); |
|
328 | + if(!is_null($groupName) && isset($groupName)) { |
|
329 | + return $groupName; |
|
330 | + } |
|
331 | + |
|
332 | + //we need to get the DN from LDAP |
|
333 | + $filter = $this->access->combineFilterWithAnd([ |
|
334 | + $this->access->connection->ldapGroupFilter, |
|
335 | + 'objectClass=posixGroup', |
|
336 | + $this->access->connection->ldapGidNumber . '=' . $gid |
|
337 | + ]); |
|
338 | + $result = $this->access->searchGroups($filter, ['dn'], 1); |
|
339 | + if(empty($result)) { |
|
340 | + return false; |
|
341 | + } |
|
342 | + $dn = $result[0]['dn'][0]; |
|
343 | + |
|
344 | + //and now the group name |
|
345 | + //NOTE once we have separate ownCloud group IDs and group names we can |
|
346 | + //directly read the display name attribute instead of the DN |
|
347 | + $name = $this->access->dn2groupname($dn); |
|
348 | + |
|
349 | + $this->access->connection->writeToCache($cacheKey, $name); |
|
350 | + |
|
351 | + return $name; |
|
352 | + } |
|
353 | + |
|
354 | + /** |
|
355 | + * returns the entry's gidNumber |
|
356 | + * @param string $dn |
|
357 | + * @param string $attribute |
|
358 | + * @return string|bool |
|
359 | + */ |
|
360 | + private function getEntryGidNumber($dn, $attribute) { |
|
361 | + $value = $this->access->readAttribute($dn, $attribute); |
|
362 | + if(is_array($value) && !empty($value)) { |
|
363 | + return $value[0]; |
|
364 | + } |
|
365 | + return false; |
|
366 | + } |
|
367 | + |
|
368 | + /** |
|
369 | + * returns the group's primary ID |
|
370 | + * @param string $dn |
|
371 | + * @return string|bool |
|
372 | + */ |
|
373 | + public function getGroupGidNumber($dn) { |
|
374 | + return $this->getEntryGidNumber($dn, 'gidNumber'); |
|
375 | + } |
|
376 | + |
|
377 | + /** |
|
378 | + * returns the user's gidNumber |
|
379 | + * @param string $dn |
|
380 | + * @return string|bool |
|
381 | + */ |
|
382 | + public function getUserGidNumber($dn) { |
|
383 | + $gidNumber = false; |
|
384 | + if($this->access->connection->hasGidNumber) { |
|
385 | + $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber); |
|
386 | + if($gidNumber === false) { |
|
387 | + $this->access->connection->hasGidNumber = false; |
|
388 | + } |
|
389 | + } |
|
390 | + return $gidNumber; |
|
391 | + } |
|
392 | + |
|
393 | + /** |
|
394 | + * returns a filter for a "users has specific gid" search or count operation |
|
395 | + * |
|
396 | + * @param string $groupDN |
|
397 | + * @param string $search |
|
398 | + * @return string |
|
399 | + * @throws \Exception |
|
400 | + */ |
|
401 | + private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') { |
|
402 | + $groupID = $this->getGroupGidNumber($groupDN); |
|
403 | + if($groupID === false) { |
|
404 | + throw new \Exception('Not a valid group'); |
|
405 | + } |
|
406 | + |
|
407 | + $filterParts = []; |
|
408 | + $filterParts[] = $this->access->getFilterForUserCount(); |
|
409 | + if ($search !== '') { |
|
410 | + $filterParts[] = $this->access->getFilterPartForUserSearch($search); |
|
411 | + } |
|
412 | + $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID; |
|
413 | + |
|
414 | + return $this->access->combineFilterWithAnd($filterParts); |
|
415 | + } |
|
416 | + |
|
417 | + /** |
|
418 | + * returns a list of users that have the given group as gid number |
|
419 | + * |
|
420 | + * @param string $groupDN |
|
421 | + * @param string $search |
|
422 | + * @param int $limit |
|
423 | + * @param int $offset |
|
424 | + * @return string[] |
|
425 | + */ |
|
426 | + public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
427 | + try { |
|
428 | + $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); |
|
429 | + $users = $this->access->fetchListOfUsers( |
|
430 | + $filter, |
|
431 | + [$this->access->connection->ldapUserDisplayName, 'dn'], |
|
432 | + $limit, |
|
433 | + $offset |
|
434 | + ); |
|
435 | + return $this->access->nextcloudUserNames($users); |
|
436 | + } catch (\Exception $e) { |
|
437 | + return []; |
|
438 | + } |
|
439 | + } |
|
440 | + |
|
441 | + /** |
|
442 | + * returns the number of users that have the given group as gid number |
|
443 | + * |
|
444 | + * @param string $groupDN |
|
445 | + * @param string $search |
|
446 | + * @param int $limit |
|
447 | + * @param int $offset |
|
448 | + * @return int |
|
449 | + */ |
|
450 | + public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
451 | + try { |
|
452 | + $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); |
|
453 | + $users = $this->access->countUsers($filter, ['dn'], $limit, $offset); |
|
454 | + return (int)$users; |
|
455 | + } catch (\Exception $e) { |
|
456 | + return 0; |
|
457 | + } |
|
458 | + } |
|
459 | + |
|
460 | + /** |
|
461 | + * gets the gidNumber of a user |
|
462 | + * @param string $dn |
|
463 | + * @return string |
|
464 | + */ |
|
465 | + public function getUserGroupByGid($dn) { |
|
466 | + $groupID = $this->getUserGidNumber($dn); |
|
467 | + if($groupID !== false) { |
|
468 | + $groupName = $this->gidNumber2Name($groupID, $dn); |
|
469 | + if($groupName !== false) { |
|
470 | + return $groupName; |
|
471 | + } |
|
472 | + } |
|
473 | + |
|
474 | + return false; |
|
475 | + } |
|
476 | + |
|
477 | + /** |
|
478 | + * translates a primary group ID into an Nextcloud internal name |
|
479 | + * @param string $gid as given by primaryGroupID on AD |
|
480 | + * @param string $dn a DN that belongs to the same domain as the group |
|
481 | + * @return string|bool |
|
482 | + */ |
|
483 | + public function primaryGroupID2Name($gid, $dn) { |
|
484 | + $cacheKey = 'primaryGroupIDtoName'; |
|
485 | + $groupNames = $this->access->connection->getFromCache($cacheKey); |
|
486 | + if(!is_null($groupNames) && isset($groupNames[$gid])) { |
|
487 | + return $groupNames[$gid]; |
|
488 | + } |
|
489 | + |
|
490 | + $domainObjectSid = $this->access->getSID($dn); |
|
491 | + if($domainObjectSid === false) { |
|
492 | + return false; |
|
493 | + } |
|
494 | + |
|
495 | + //we need to get the DN from LDAP |
|
496 | + $filter = $this->access->combineFilterWithAnd([ |
|
497 | + $this->access->connection->ldapGroupFilter, |
|
498 | + 'objectsid=' . $domainObjectSid . '-' . $gid |
|
499 | + ]); |
|
500 | + $result = $this->access->searchGroups($filter, ['dn'], 1); |
|
501 | + if(empty($result)) { |
|
502 | + return false; |
|
503 | + } |
|
504 | + $dn = $result[0]['dn'][0]; |
|
505 | + |
|
506 | + //and now the group name |
|
507 | + //NOTE once we have separate Nextcloud group IDs and group names we can |
|
508 | + //directly read the display name attribute instead of the DN |
|
509 | + $name = $this->access->dn2groupname($dn); |
|
510 | + |
|
511 | + $this->access->connection->writeToCache($cacheKey, $name); |
|
512 | + |
|
513 | + return $name; |
|
514 | + } |
|
515 | + |
|
516 | + /** |
|
517 | + * returns the entry's primary group ID |
|
518 | + * @param string $dn |
|
519 | + * @param string $attribute |
|
520 | + * @return string|bool |
|
521 | + */ |
|
522 | + private function getEntryGroupID($dn, $attribute) { |
|
523 | + $value = $this->access->readAttribute($dn, $attribute); |
|
524 | + if(is_array($value) && !empty($value)) { |
|
525 | + return $value[0]; |
|
526 | + } |
|
527 | + return false; |
|
528 | + } |
|
529 | + |
|
530 | + /** |
|
531 | + * returns the group's primary ID |
|
532 | + * @param string $dn |
|
533 | + * @return string|bool |
|
534 | + */ |
|
535 | + public function getGroupPrimaryGroupID($dn) { |
|
536 | + return $this->getEntryGroupID($dn, 'primaryGroupToken'); |
|
537 | + } |
|
538 | + |
|
539 | + /** |
|
540 | + * returns the user's primary group ID |
|
541 | + * @param string $dn |
|
542 | + * @return string|bool |
|
543 | + */ |
|
544 | + public function getUserPrimaryGroupIDs($dn) { |
|
545 | + $primaryGroupID = false; |
|
546 | + if($this->access->connection->hasPrimaryGroups) { |
|
547 | + $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID'); |
|
548 | + if($primaryGroupID === false) { |
|
549 | + $this->access->connection->hasPrimaryGroups = false; |
|
550 | + } |
|
551 | + } |
|
552 | + return $primaryGroupID; |
|
553 | + } |
|
554 | + |
|
555 | + /** |
|
556 | + * returns a filter for a "users in primary group" search or count operation |
|
557 | + * |
|
558 | + * @param string $groupDN |
|
559 | + * @param string $search |
|
560 | + * @return string |
|
561 | + * @throws \Exception |
|
562 | + */ |
|
563 | + private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') { |
|
564 | + $groupID = $this->getGroupPrimaryGroupID($groupDN); |
|
565 | + if($groupID === false) { |
|
566 | + throw new \Exception('Not a valid group'); |
|
567 | + } |
|
568 | + |
|
569 | + $filterParts = []; |
|
570 | + $filterParts[] = $this->access->getFilterForUserCount(); |
|
571 | + if ($search !== '') { |
|
572 | + $filterParts[] = $this->access->getFilterPartForUserSearch($search); |
|
573 | + } |
|
574 | + $filterParts[] = 'primaryGroupID=' . $groupID; |
|
575 | + |
|
576 | + return $this->access->combineFilterWithAnd($filterParts); |
|
577 | + } |
|
578 | + |
|
579 | + /** |
|
580 | + * returns a list of users that have the given group as primary group |
|
581 | + * |
|
582 | + * @param string $groupDN |
|
583 | + * @param string $search |
|
584 | + * @param int $limit |
|
585 | + * @param int $offset |
|
586 | + * @return string[] |
|
587 | + */ |
|
588 | + public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
589 | + try { |
|
590 | + $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); |
|
591 | + $users = $this->access->fetchListOfUsers( |
|
592 | + $filter, |
|
593 | + [$this->access->connection->ldapUserDisplayName, 'dn'], |
|
594 | + $limit, |
|
595 | + $offset |
|
596 | + ); |
|
597 | + return $this->access->nextcloudUserNames($users); |
|
598 | + } catch (\Exception $e) { |
|
599 | + return []; |
|
600 | + } |
|
601 | + } |
|
602 | + |
|
603 | + /** |
|
604 | + * returns the number of users that have the given group as primary group |
|
605 | + * |
|
606 | + * @param string $groupDN |
|
607 | + * @param string $search |
|
608 | + * @param int $limit |
|
609 | + * @param int $offset |
|
610 | + * @return int |
|
611 | + */ |
|
612 | + public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { |
|
613 | + try { |
|
614 | + $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); |
|
615 | + $users = $this->access->countUsers($filter, ['dn'], $limit, $offset); |
|
616 | + return (int)$users; |
|
617 | + } catch (\Exception $e) { |
|
618 | + return 0; |
|
619 | + } |
|
620 | + } |
|
621 | + |
|
622 | + /** |
|
623 | + * gets the primary group of a user |
|
624 | + * @param string $dn |
|
625 | + * @return string |
|
626 | + */ |
|
627 | + public function getUserPrimaryGroup($dn) { |
|
628 | + $groupID = $this->getUserPrimaryGroupIDs($dn); |
|
629 | + if($groupID !== false) { |
|
630 | + $groupName = $this->primaryGroupID2Name($groupID, $dn); |
|
631 | + if($groupName !== false) { |
|
632 | + return $groupName; |
|
633 | + } |
|
634 | + } |
|
635 | + |
|
636 | + return false; |
|
637 | + } |
|
638 | + |
|
639 | + /** |
|
640 | + * Get all groups a user belongs to |
|
641 | + * @param string $uid Name of the user |
|
642 | + * @return array with group names |
|
643 | + * |
|
644 | + * This function fetches all groups a user belongs to. It does not check |
|
645 | + * if the user exists at all. |
|
646 | + * |
|
647 | + * This function includes groups based on dynamic group membership. |
|
648 | + */ |
|
649 | + public function getUserGroups($uid) { |
|
650 | + if(!$this->enabled) { |
|
651 | + return []; |
|
652 | + } |
|
653 | + $cacheKey = 'getUserGroups'.$uid; |
|
654 | + $userGroups = $this->access->connection->getFromCache($cacheKey); |
|
655 | + if(!is_null($userGroups)) { |
|
656 | + return $userGroups; |
|
657 | + } |
|
658 | + $userDN = $this->access->username2dn($uid); |
|
659 | + if(!$userDN) { |
|
660 | + $this->access->connection->writeToCache($cacheKey, []); |
|
661 | + return []; |
|
662 | + } |
|
663 | + |
|
664 | + $groups = []; |
|
665 | + $primaryGroup = $this->getUserPrimaryGroup($userDN); |
|
666 | + $gidGroupName = $this->getUserGroupByGid($userDN); |
|
667 | + |
|
668 | + $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); |
|
669 | + |
|
670 | + if (!empty($dynamicGroupMemberURL)) { |
|
671 | + // look through dynamic groups to add them to the result array if needed |
|
672 | + $groupsToMatch = $this->access->fetchListOfGroups( |
|
673 | + $this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]); |
|
674 | + foreach($groupsToMatch as $dynamicGroup) { |
|
675 | + if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) { |
|
676 | + continue; |
|
677 | + } |
|
678 | + $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '('); |
|
679 | + if ($pos !== false) { |
|
680 | + $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos); |
|
681 | + // apply filter via ldap search to see if this user is in this |
|
682 | + // dynamic group |
|
683 | + $userMatch = $this->access->readAttribute( |
|
684 | + $userDN, |
|
685 | + $this->access->connection->ldapUserDisplayName, |
|
686 | + $memberUrlFilter |
|
687 | + ); |
|
688 | + if ($userMatch !== false) { |
|
689 | + // match found so this user is in this group |
|
690 | + $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]); |
|
691 | + if(is_string($groupName)) { |
|
692 | + // be sure to never return false if the dn could not be |
|
693 | + // resolved to a name, for whatever reason. |
|
694 | + $groups[] = $groupName; |
|
695 | + } |
|
696 | + } |
|
697 | + } else { |
|
698 | + \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. |
|
699 | + 'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG); |
|
700 | + } |
|
701 | + } |
|
702 | + } |
|
703 | + |
|
704 | + // if possible, read out membership via memberOf. It's far faster than |
|
705 | + // performing a search, which still is a fallback later. |
|
706 | + // memberof doesn't support memberuid, so skip it here. |
|
707 | + if((int)$this->access->connection->hasMemberOfFilterSupport === 1 |
|
708 | + && (int)$this->access->connection->useMemberOfToDetectMembership === 1 |
|
709 | + && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid' |
|
710 | + ) { |
|
711 | + $groupDNs = $this->_getGroupDNsFromMemberOf($userDN); |
|
712 | + if (is_array($groupDNs)) { |
|
713 | + foreach ($groupDNs as $dn) { |
|
714 | + $groupName = $this->access->dn2groupname($dn); |
|
715 | + if(is_string($groupName)) { |
|
716 | + // be sure to never return false if the dn could not be |
|
717 | + // resolved to a name, for whatever reason. |
|
718 | + $groups[] = $groupName; |
|
719 | + } |
|
720 | + } |
|
721 | + } |
|
722 | + |
|
723 | + if($primaryGroup !== false) { |
|
724 | + $groups[] = $primaryGroup; |
|
725 | + } |
|
726 | + if($gidGroupName !== false) { |
|
727 | + $groups[] = $gidGroupName; |
|
728 | + } |
|
729 | + $this->access->connection->writeToCache($cacheKey, $groups); |
|
730 | + return $groups; |
|
731 | + } |
|
732 | + |
|
733 | + //uniqueMember takes DN, memberuid the uid, so we need to distinguish |
|
734 | + if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') |
|
735 | + || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member') |
|
736 | + ) { |
|
737 | + $uid = $userDN; |
|
738 | + } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { |
|
739 | + $result = $this->access->readAttribute($userDN, 'uid'); |
|
740 | + if ($result === false) { |
|
741 | + \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '. |
|
742 | + $this->access->connection->ldapHost, ILogger::DEBUG); |
|
743 | + $uid = false; |
|
744 | + } else { |
|
745 | + $uid = $result[0]; |
|
746 | + } |
|
747 | + } else { |
|
748 | + // just in case |
|
749 | + $uid = $userDN; |
|
750 | + } |
|
751 | + |
|
752 | + if($uid !== false) { |
|
753 | + if (isset($this->cachedGroupsByMember[$uid])) { |
|
754 | + $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]); |
|
755 | + } else { |
|
756 | + $groupsByMember = array_values($this->getGroupsByMember($uid)); |
|
757 | + $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember); |
|
758 | + $this->cachedGroupsByMember[$uid] = $groupsByMember; |
|
759 | + $groups = array_merge($groups, $groupsByMember); |
|
760 | + } |
|
761 | + } |
|
762 | + |
|
763 | + if($primaryGroup !== false) { |
|
764 | + $groups[] = $primaryGroup; |
|
765 | + } |
|
766 | + if($gidGroupName !== false) { |
|
767 | + $groups[] = $gidGroupName; |
|
768 | + } |
|
769 | + |
|
770 | + $groups = array_unique($groups, SORT_LOCALE_STRING); |
|
771 | + $this->access->connection->writeToCache($cacheKey, $groups); |
|
772 | + |
|
773 | + return $groups; |
|
774 | + } |
|
775 | + |
|
776 | + /** |
|
777 | + * @param string $dn |
|
778 | + * @param array|null &$seen |
|
779 | + * @return array |
|
780 | + */ |
|
781 | + private function getGroupsByMember($dn, &$seen = null) { |
|
782 | + if ($seen === null) { |
|
783 | + $seen = []; |
|
784 | + } |
|
785 | + if (array_key_exists($dn, $seen)) { |
|
786 | + // avoid loops |
|
787 | + return []; |
|
788 | + } |
|
789 | + $allGroups = []; |
|
790 | + $seen[$dn] = true; |
|
791 | + $filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn; |
|
792 | + $groups = $this->access->fetchListOfGroups($filter, |
|
793 | + [$this->access->connection->ldapGroupDisplayName, 'dn']); |
|
794 | + if (is_array($groups)) { |
|
795 | + $fetcher = function ($dn, &$seen) { |
|
796 | + if(is_array($dn) && isset($dn['dn'][0])) { |
|
797 | + $dn = $dn['dn'][0]; |
|
798 | + } |
|
799 | + return $this->getGroupsByMember($dn, $seen); |
|
800 | + }; |
|
801 | + $allGroups = $this->walkNestedGroups($dn, $fetcher, $groups); |
|
802 | + } |
|
803 | + $visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups)); |
|
804 | + return array_intersect_key($allGroups, array_flip($visibleGroups)); |
|
805 | + } |
|
806 | + |
|
807 | + /** |
|
808 | + * get a list of all users in a group |
|
809 | + * |
|
810 | + * @param string $gid |
|
811 | + * @param string $search |
|
812 | + * @param int $limit |
|
813 | + * @param int $offset |
|
814 | + * @return array with user ids |
|
815 | + * @throws \Exception |
|
816 | + */ |
|
817 | + public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { |
|
818 | + if(!$this->enabled) { |
|
819 | + return []; |
|
820 | + } |
|
821 | + if(!$this->groupExists($gid)) { |
|
822 | + return []; |
|
823 | + } |
|
824 | + $search = $this->access->escapeFilterPart($search, true); |
|
825 | + $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset; |
|
826 | + // check for cache of the exact query |
|
827 | + $groupUsers = $this->access->connection->getFromCache($cacheKey); |
|
828 | + if(!is_null($groupUsers)) { |
|
829 | + return $groupUsers; |
|
830 | + } |
|
831 | + |
|
832 | + // check for cache of the query without limit and offset |
|
833 | + $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search); |
|
834 | + if(!is_null($groupUsers)) { |
|
835 | + $groupUsers = array_slice($groupUsers, $offset, $limit); |
|
836 | + $this->access->connection->writeToCache($cacheKey, $groupUsers); |
|
837 | + return $groupUsers; |
|
838 | + } |
|
839 | + |
|
840 | + if($limit === -1) { |
|
841 | + $limit = null; |
|
842 | + } |
|
843 | + $groupDN = $this->access->groupname2dn($gid); |
|
844 | + if(!$groupDN) { |
|
845 | + // group couldn't be found, return empty resultset |
|
846 | + $this->access->connection->writeToCache($cacheKey, []); |
|
847 | + return []; |
|
848 | + } |
|
849 | + |
|
850 | + $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset); |
|
851 | + $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset); |
|
852 | + $members = $this->_groupMembers($groupDN); |
|
853 | + if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) { |
|
854 | + //in case users could not be retrieved, return empty result set |
|
855 | + $this->access->connection->writeToCache($cacheKey, []); |
|
856 | + return []; |
|
857 | + } |
|
858 | + |
|
859 | + $groupUsers = []; |
|
860 | + $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid'); |
|
861 | + $attrs = $this->access->userManager->getAttributes(true); |
|
862 | + foreach($members as $member) { |
|
863 | + if($isMemberUid) { |
|
864 | + //we got uids, need to get their DNs to 'translate' them to user names |
|
865 | + $filter = $this->access->combineFilterWithAnd([ |
|
866 | + str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter), |
|
867 | + $this->access->combineFilterWithAnd([ |
|
868 | + $this->access->getFilterPartForUserSearch($search), |
|
869 | + $this->access->connection->ldapUserFilter |
|
870 | + ]) |
|
871 | + ]); |
|
872 | + $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1); |
|
873 | + if(count($ldap_users) < 1) { |
|
874 | + continue; |
|
875 | + } |
|
876 | + $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]); |
|
877 | + } else { |
|
878 | + //we got DNs, check if we need to filter by search or we can give back all of them |
|
879 | + $uid = $this->access->dn2username($member); |
|
880 | + if(!$uid) { |
|
881 | + continue; |
|
882 | + } |
|
883 | + |
|
884 | + $cacheKey = 'userExistsOnLDAP' . $uid; |
|
885 | + $userExists = $this->access->connection->getFromCache($cacheKey); |
|
886 | + if($userExists === false) { |
|
887 | + continue; |
|
888 | + } |
|
889 | + if($userExists === null || $search !== '') { |
|
890 | + if (!$this->access->readAttribute($member, |
|
891 | + $this->access->connection->ldapUserDisplayName, |
|
892 | + $this->access->combineFilterWithAnd([ |
|
893 | + $this->access->getFilterPartForUserSearch($search), |
|
894 | + $this->access->connection->ldapUserFilter |
|
895 | + ]))) |
|
896 | + { |
|
897 | + if($search === '') { |
|
898 | + $this->access->connection->writeToCache($cacheKey, false); |
|
899 | + } |
|
900 | + continue; |
|
901 | + } |
|
902 | + $this->access->connection->writeToCache($cacheKey, true); |
|
903 | + } |
|
904 | + $groupUsers[] = $uid; |
|
905 | + } |
|
906 | + } |
|
907 | + |
|
908 | + $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers)); |
|
909 | + natsort($groupUsers); |
|
910 | + $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers); |
|
911 | + $groupUsers = array_slice($groupUsers, $offset, $limit); |
|
912 | + |
|
913 | + $this->access->connection->writeToCache($cacheKey, $groupUsers); |
|
914 | + |
|
915 | + return $groupUsers; |
|
916 | + } |
|
917 | + |
|
918 | + /** |
|
919 | + * returns the number of users in a group, who match the search term |
|
920 | + * @param string $gid the internal group name |
|
921 | + * @param string $search optional, a search string |
|
922 | + * @return int|bool |
|
923 | + */ |
|
924 | + public function countUsersInGroup($gid, $search = '') { |
|
925 | + if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) { |
|
926 | + return $this->groupPluginManager->countUsersInGroup($gid, $search); |
|
927 | + } |
|
928 | + |
|
929 | + $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search; |
|
930 | + if(!$this->enabled || !$this->groupExists($gid)) { |
|
931 | + return false; |
|
932 | + } |
|
933 | + $groupUsers = $this->access->connection->getFromCache($cacheKey); |
|
934 | + if(!is_null($groupUsers)) { |
|
935 | + return $groupUsers; |
|
936 | + } |
|
937 | + |
|
938 | + $groupDN = $this->access->groupname2dn($gid); |
|
939 | + if(!$groupDN) { |
|
940 | + // group couldn't be found, return empty result set |
|
941 | + $this->access->connection->writeToCache($cacheKey, false); |
|
942 | + return false; |
|
943 | + } |
|
944 | + |
|
945 | + $members = $this->_groupMembers($groupDN); |
|
946 | + $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, ''); |
|
947 | + if(!$members && $primaryUserCount === 0) { |
|
948 | + //in case users could not be retrieved, return empty result set |
|
949 | + $this->access->connection->writeToCache($cacheKey, false); |
|
950 | + return false; |
|
951 | + } |
|
952 | + |
|
953 | + if ($search === '') { |
|
954 | + $groupUsers = count($members) + $primaryUserCount; |
|
955 | + $this->access->connection->writeToCache($cacheKey, $groupUsers); |
|
956 | + return $groupUsers; |
|
957 | + } |
|
958 | + $search = $this->access->escapeFilterPart($search, true); |
|
959 | + $isMemberUid = |
|
960 | + (strtolower($this->access->connection->ldapGroupMemberAssocAttr) |
|
961 | + === 'memberuid'); |
|
962 | + |
|
963 | + //we need to apply the search filter |
|
964 | + //alternatives that need to be checked: |
|
965 | + //a) get all users by search filter and array_intersect them |
|
966 | + //b) a, but only when less than 1k 10k ?k users like it is |
|
967 | + //c) put all DNs|uids in a LDAP filter, combine with the search string |
|
968 | + // and let it count. |
|
969 | + //For now this is not important, because the only use of this method |
|
970 | + //does not supply a search string |
|
971 | + $groupUsers = []; |
|
972 | + foreach($members as $member) { |
|
973 | + if($isMemberUid) { |
|
974 | + //we got uids, need to get their DNs to 'translate' them to user names |
|
975 | + $filter = $this->access->combineFilterWithAnd([ |
|
976 | + str_replace('%uid', $member, $this->access->connection->ldapLoginFilter), |
|
977 | + $this->access->getFilterPartForUserSearch($search) |
|
978 | + ]); |
|
979 | + $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1); |
|
980 | + if(count($ldap_users) < 1) { |
|
981 | + continue; |
|
982 | + } |
|
983 | + $groupUsers[] = $this->access->dn2username($ldap_users[0]); |
|
984 | + } else { |
|
985 | + //we need to apply the search filter now |
|
986 | + if(!$this->access->readAttribute($member, |
|
987 | + $this->access->connection->ldapUserDisplayName, |
|
988 | + $this->access->getFilterPartForUserSearch($search))) { |
|
989 | + continue; |
|
990 | + } |
|
991 | + // dn2username will also check if the users belong to the allowed base |
|
992 | + if($ocname = $this->access->dn2username($member)) { |
|
993 | + $groupUsers[] = $ocname; |
|
994 | + } |
|
995 | + } |
|
996 | + } |
|
997 | + |
|
998 | + //and get users that have the group as primary |
|
999 | + $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search); |
|
1000 | + |
|
1001 | + return count($groupUsers) + $primaryUsers; |
|
1002 | + } |
|
1003 | + |
|
1004 | + /** |
|
1005 | + * get a list of all groups |
|
1006 | + * |
|
1007 | + * @param string $search |
|
1008 | + * @param $limit |
|
1009 | + * @param int $offset |
|
1010 | + * @return array with group names |
|
1011 | + * |
|
1012 | + * Returns a list with all groups (used by getGroups) |
|
1013 | + */ |
|
1014 | + protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) { |
|
1015 | + if(!$this->enabled) { |
|
1016 | + return []; |
|
1017 | + } |
|
1018 | + $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset; |
|
1019 | + |
|
1020 | + //Check cache before driving unnecessary searches |
|
1021 | + \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG); |
|
1022 | + $ldap_groups = $this->access->connection->getFromCache($cacheKey); |
|
1023 | + if(!is_null($ldap_groups)) { |
|
1024 | + return $ldap_groups; |
|
1025 | + } |
|
1026 | + |
|
1027 | + // if we'd pass -1 to LDAP search, we'd end up in a Protocol |
|
1028 | + // error. With a limit of 0, we get 0 results. So we pass null. |
|
1029 | + if($limit <= 0) { |
|
1030 | + $limit = null; |
|
1031 | + } |
|
1032 | + $filter = $this->access->combineFilterWithAnd([ |
|
1033 | + $this->access->connection->ldapGroupFilter, |
|
1034 | + $this->access->getFilterPartForGroupSearch($search) |
|
1035 | + ]); |
|
1036 | + \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG); |
|
1037 | + $ldap_groups = $this->access->fetchListOfGroups($filter, |
|
1038 | + [$this->access->connection->ldapGroupDisplayName, 'dn'], |
|
1039 | + $limit, |
|
1040 | + $offset); |
|
1041 | + $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups); |
|
1042 | + |
|
1043 | + $this->access->connection->writeToCache($cacheKey, $ldap_groups); |
|
1044 | + return $ldap_groups; |
|
1045 | + } |
|
1046 | + |
|
1047 | + /** |
|
1048 | + * get a list of all groups using a paged search |
|
1049 | + * |
|
1050 | + * @param string $search |
|
1051 | + * @param int $limit |
|
1052 | + * @param int $offset |
|
1053 | + * @return array with group names |
|
1054 | + * |
|
1055 | + * Returns a list with all groups |
|
1056 | + * Uses a paged search if available to override a |
|
1057 | + * server side search limit. |
|
1058 | + * (active directory has a limit of 1000 by default) |
|
1059 | + */ |
|
1060 | + public function getGroups($search = '', $limit = -1, $offset = 0) { |
|
1061 | + if(!$this->enabled) { |
|
1062 | + return []; |
|
1063 | + } |
|
1064 | + $search = $this->access->escapeFilterPart($search, true); |
|
1065 | + $pagingSize = (int)$this->access->connection->ldapPagingSize; |
|
1066 | + if ($pagingSize <= 0) { |
|
1067 | + return $this->getGroupsChunk($search, $limit, $offset); |
|
1068 | + } |
|
1069 | + $maxGroups = 100000; // limit max results (just for safety reasons) |
|
1070 | + if ($limit > -1) { |
|
1071 | + $overallLimit = min($limit + $offset, $maxGroups); |
|
1072 | + } else { |
|
1073 | + $overallLimit = $maxGroups; |
|
1074 | + } |
|
1075 | + $chunkOffset = $offset; |
|
1076 | + $allGroups = []; |
|
1077 | + while ($chunkOffset < $overallLimit) { |
|
1078 | + $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset); |
|
1079 | + $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset); |
|
1080 | + $nread = count($ldapGroups); |
|
1081 | + \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG); |
|
1082 | + if ($nread) { |
|
1083 | + $allGroups = array_merge($allGroups, $ldapGroups); |
|
1084 | + $chunkOffset += $nread; |
|
1085 | + } |
|
1086 | + if ($nread < $chunkLimit) { |
|
1087 | + break; |
|
1088 | + } |
|
1089 | + } |
|
1090 | + return $allGroups; |
|
1091 | + } |
|
1092 | + |
|
1093 | + /** |
|
1094 | + * @param string $group |
|
1095 | + * @return bool |
|
1096 | + */ |
|
1097 | + public function groupMatchesFilter($group) { |
|
1098 | + return (strripos($group, $this->groupSearch) !== false); |
|
1099 | + } |
|
1100 | + |
|
1101 | + /** |
|
1102 | + * check if a group exists |
|
1103 | + * @param string $gid |
|
1104 | + * @return bool |
|
1105 | + */ |
|
1106 | + public function groupExists($gid) { |
|
1107 | + $groupExists = $this->access->connection->getFromCache('groupExists'.$gid); |
|
1108 | + if(!is_null($groupExists)) { |
|
1109 | + return (bool)$groupExists; |
|
1110 | + } |
|
1111 | + |
|
1112 | + //getting dn, if false the group does not exist. If dn, it may be mapped |
|
1113 | + //only, requires more checking. |
|
1114 | + $dn = $this->access->groupname2dn($gid); |
|
1115 | + if(!$dn) { |
|
1116 | + $this->access->connection->writeToCache('groupExists'.$gid, false); |
|
1117 | + return false; |
|
1118 | + } |
|
1119 | + |
|
1120 | + //if group really still exists, we will be able to read its objectclass |
|
1121 | + if(!is_array($this->access->readAttribute($dn, ''))) { |
|
1122 | + $this->access->connection->writeToCache('groupExists'.$gid, false); |
|
1123 | + return false; |
|
1124 | + } |
|
1125 | + |
|
1126 | + $this->access->connection->writeToCache('groupExists'.$gid, true); |
|
1127 | + return true; |
|
1128 | + } |
|
1129 | + |
|
1130 | + /** |
|
1131 | + * Check if backend implements actions |
|
1132 | + * @param int $actions bitwise-or'ed actions |
|
1133 | + * @return boolean |
|
1134 | + * |
|
1135 | + * Returns the supported actions as int to be |
|
1136 | + * compared with GroupInterface::CREATE_GROUP etc. |
|
1137 | + */ |
|
1138 | + public function implementsActions($actions) { |
|
1139 | + return (bool)((GroupInterface::COUNT_USERS | |
|
1140 | + $this->groupPluginManager->getImplementedActions()) & $actions); |
|
1141 | + } |
|
1142 | + |
|
1143 | + /** |
|
1144 | + * Return access for LDAP interaction. |
|
1145 | + * @return Access instance of Access for LDAP interaction |
|
1146 | + */ |
|
1147 | + public function getLDAPAccess($gid) { |
|
1148 | + return $this->access; |
|
1149 | + } |
|
1150 | + |
|
1151 | + /** |
|
1152 | + * create a group |
|
1153 | + * @param string $gid |
|
1154 | + * @return bool |
|
1155 | + * @throws \Exception |
|
1156 | + */ |
|
1157 | + public function createGroup($gid) { |
|
1158 | + if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) { |
|
1159 | + if ($dn = $this->groupPluginManager->createGroup($gid)) { |
|
1160 | + //updates group mapping |
|
1161 | + $uuid = $this->access->getUUID($dn, false); |
|
1162 | + if(is_string($uuid)) { |
|
1163 | + $this->access->mapAndAnnounceIfApplicable( |
|
1164 | + $this->access->getGroupMapper(), |
|
1165 | + $dn, |
|
1166 | + $gid, |
|
1167 | + $uuid, |
|
1168 | + false |
|
1169 | + ); |
|
1170 | + $this->access->cacheGroupExists($gid); |
|
1171 | + } |
|
1172 | + } |
|
1173 | + return $dn != null; |
|
1174 | + } |
|
1175 | + throw new \Exception('Could not create group in LDAP backend.'); |
|
1176 | + } |
|
1177 | + |
|
1178 | + /** |
|
1179 | + * delete a group |
|
1180 | + * @param string $gid gid of the group to delete |
|
1181 | + * @return bool |
|
1182 | + * @throws \Exception |
|
1183 | + */ |
|
1184 | + public function deleteGroup($gid) { |
|
1185 | + if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) { |
|
1186 | + if ($ret = $this->groupPluginManager->deleteGroup($gid)) { |
|
1187 | + #delete group in nextcloud internal db |
|
1188 | + $this->access->getGroupMapper()->unmap($gid); |
|
1189 | + $this->access->connection->writeToCache("groupExists".$gid, false); |
|
1190 | + } |
|
1191 | + return $ret; |
|
1192 | + } |
|
1193 | + throw new \Exception('Could not delete group in LDAP backend.'); |
|
1194 | + } |
|
1195 | + |
|
1196 | + /** |
|
1197 | + * Add a user to a group |
|
1198 | + * @param string $uid Name of the user to add to group |
|
1199 | + * @param string $gid Name of the group in which add the user |
|
1200 | + * @return bool |
|
1201 | + * @throws \Exception |
|
1202 | + */ |
|
1203 | + public function addToGroup($uid, $gid) { |
|
1204 | + if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) { |
|
1205 | + if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) { |
|
1206 | + $this->access->connection->clearCache(); |
|
1207 | + unset($this->cachedGroupMembers[$gid]); |
|
1208 | + } |
|
1209 | + return $ret; |
|
1210 | + } |
|
1211 | + throw new \Exception('Could not add user to group in LDAP backend.'); |
|
1212 | + } |
|
1213 | + |
|
1214 | + /** |
|
1215 | + * Removes a user from a group |
|
1216 | + * @param string $uid Name of the user to remove from group |
|
1217 | + * @param string $gid Name of the group from which remove the user |
|
1218 | + * @return bool |
|
1219 | + * @throws \Exception |
|
1220 | + */ |
|
1221 | + public function removeFromGroup($uid, $gid) { |
|
1222 | + if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) { |
|
1223 | + if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) { |
|
1224 | + $this->access->connection->clearCache(); |
|
1225 | + unset($this->cachedGroupMembers[$gid]); |
|
1226 | + } |
|
1227 | + return $ret; |
|
1228 | + } |
|
1229 | + throw new \Exception('Could not remove user from group in LDAP backend.'); |
|
1230 | + } |
|
1231 | + |
|
1232 | + /** |
|
1233 | + * Gets group details |
|
1234 | + * @param string $gid Name of the group |
|
1235 | + * @return array | false |
|
1236 | + * @throws \Exception |
|
1237 | + */ |
|
1238 | + public function getGroupDetails($gid) { |
|
1239 | + if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) { |
|
1240 | + return $this->groupPluginManager->getGroupDetails($gid); |
|
1241 | + } |
|
1242 | + throw new \Exception('Could not get group details in LDAP backend.'); |
|
1243 | + } |
|
1244 | + |
|
1245 | + /** |
|
1246 | + * Return LDAP connection resource from a cloned connection. |
|
1247 | + * The cloned connection needs to be closed manually. |
|
1248 | + * of the current access. |
|
1249 | + * @param string $gid |
|
1250 | + * @return resource of the LDAP connection |
|
1251 | + */ |
|
1252 | + public function getNewLDAPConnection($gid) { |
|
1253 | + $connection = clone $this->access->getConnection(); |
|
1254 | + return $connection->getConnectionResource(); |
|
1255 | + } |
|
1256 | + |
|
1257 | + /** |
|
1258 | + * @throws \OC\ServerNotAvailableException |
|
1259 | + */ |
|
1260 | + public function getDisplayName(string $gid): string { |
|
1261 | + if ($this->groupPluginManager instanceof IGetDisplayNameBackend) { |
|
1262 | + return $this->groupPluginManager->getDisplayName($gid); |
|
1263 | + } |
|
1264 | + |
|
1265 | + $cacheKey = 'group_getDisplayName' . $gid; |
|
1266 | + if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { |
|
1267 | + return $displayName; |
|
1268 | + } |
|
1269 | + |
|
1270 | + $displayName = $this->access->readAttribute( |
|
1271 | + $this->access->groupname2dn($gid), |
|
1272 | + $this->access->connection->ldapGroupDisplayName); |
|
1273 | + |
|
1274 | + if ($displayName && (count($displayName) > 0)) { |
|
1275 | + $displayName = $displayName[0]; |
|
1276 | + $this->access->connection->writeToCache($cacheKey, $displayName); |
|
1277 | + return $displayName; |
|
1278 | + } |
|
1279 | + |
|
1280 | + return ''; |
|
1281 | + } |
|
1282 | 1282 | } |
@@ -37,126 +37,126 @@ discard block |
||
37 | 37 | |
38 | 38 | class Helper { |
39 | 39 | |
40 | - /** @var IConfig */ |
|
41 | - private $config; |
|
42 | - |
|
43 | - /** |
|
44 | - * Helper constructor. |
|
45 | - * |
|
46 | - * @param IConfig $config |
|
47 | - */ |
|
48 | - public function __construct(IConfig $config) { |
|
49 | - $this->config = $config; |
|
50 | - } |
|
51 | - |
|
52 | - /** |
|
53 | - * returns prefixes for each saved LDAP/AD server configuration. |
|
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) { |
|
73 | - $referenceConfigkey = 'ldap_configuration_active'; |
|
74 | - |
|
75 | - $keys = $this->getServersConfig($referenceConfigkey); |
|
76 | - |
|
77 | - $prefixes = []; |
|
78 | - foreach ($keys as $key) { |
|
79 | - if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') { |
|
80 | - continue; |
|
81 | - } |
|
82 | - |
|
83 | - $len = strlen($key) - strlen($referenceConfigkey); |
|
84 | - $prefixes[] = substr($key, 0, $len); |
|
85 | - } |
|
86 | - asort($prefixes); |
|
87 | - |
|
88 | - return $prefixes; |
|
89 | - } |
|
90 | - |
|
91 | - /** |
|
92 | - * |
|
93 | - * determines the host for every configured connection |
|
94 | - * @return array an array with configprefix as keys |
|
95 | - * |
|
96 | - */ |
|
97 | - public function getServerConfigurationHosts() { |
|
98 | - $referenceConfigkey = 'ldap_host'; |
|
99 | - |
|
100 | - $keys = $this->getServersConfig($referenceConfigkey); |
|
101 | - |
|
102 | - $result = []; |
|
103 | - foreach($keys as $key) { |
|
104 | - $len = strlen($key) - strlen($referenceConfigkey); |
|
105 | - $prefix = substr($key, 0, $len); |
|
106 | - $result[$prefix] = $this->config->getAppValue('user_ldap', $key); |
|
107 | - } |
|
108 | - |
|
109 | - return $result; |
|
110 | - } |
|
111 | - |
|
112 | - /** |
|
113 | - * return the next available configuration prefix |
|
114 | - * |
|
115 | - * @return string |
|
116 | - */ |
|
117 | - public function getNextServerConfigurationPrefix() { |
|
118 | - $serverConnections = $this->getServerConfigurationPrefixes(); |
|
119 | - |
|
120 | - if(count($serverConnections) === 0) { |
|
121 | - return 's01'; |
|
122 | - } |
|
123 | - |
|
124 | - sort($serverConnections); |
|
125 | - $lastKey = array_pop($serverConnections); |
|
126 | - $lastNumber = (int)str_replace('s', '', $lastKey); |
|
127 | - return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT); |
|
128 | - } |
|
129 | - |
|
130 | - private function getServersConfig($value) { |
|
131 | - $regex = '/' . $value . '$/S'; |
|
132 | - |
|
133 | - $keys = $this->config->getAppKeys('user_ldap'); |
|
134 | - $result = []; |
|
135 | - foreach ($keys as $key) { |
|
136 | - if (preg_match($regex, $key) === 1) { |
|
137 | - $result[] = $key; |
|
138 | - } |
|
139 | - } |
|
140 | - |
|
141 | - return $result; |
|
142 | - } |
|
143 | - |
|
144 | - /** |
|
145 | - * deletes a given saved LDAP/AD server configuration. |
|
146 | - * @param string $prefix the configuration prefix of the config to delete |
|
147 | - * @return bool true on success, false otherwise |
|
148 | - */ |
|
149 | - public function deleteServerConfiguration($prefix) { |
|
150 | - if(!in_array($prefix, self::getServerConfigurationPrefixes())) { |
|
151 | - return false; |
|
152 | - } |
|
153 | - |
|
154 | - $saveOtherConfigurations = ''; |
|
155 | - if(empty($prefix)) { |
|
156 | - $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; |
|
157 | - } |
|
158 | - |
|
159 | - $query = \OC_DB::prepare(' |
|
40 | + /** @var IConfig */ |
|
41 | + private $config; |
|
42 | + |
|
43 | + /** |
|
44 | + * Helper constructor. |
|
45 | + * |
|
46 | + * @param IConfig $config |
|
47 | + */ |
|
48 | + public function __construct(IConfig $config) { |
|
49 | + $this->config = $config; |
|
50 | + } |
|
51 | + |
|
52 | + /** |
|
53 | + * returns prefixes for each saved LDAP/AD server configuration. |
|
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) { |
|
73 | + $referenceConfigkey = 'ldap_configuration_active'; |
|
74 | + |
|
75 | + $keys = $this->getServersConfig($referenceConfigkey); |
|
76 | + |
|
77 | + $prefixes = []; |
|
78 | + foreach ($keys as $key) { |
|
79 | + if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') { |
|
80 | + continue; |
|
81 | + } |
|
82 | + |
|
83 | + $len = strlen($key) - strlen($referenceConfigkey); |
|
84 | + $prefixes[] = substr($key, 0, $len); |
|
85 | + } |
|
86 | + asort($prefixes); |
|
87 | + |
|
88 | + return $prefixes; |
|
89 | + } |
|
90 | + |
|
91 | + /** |
|
92 | + * |
|
93 | + * determines the host for every configured connection |
|
94 | + * @return array an array with configprefix as keys |
|
95 | + * |
|
96 | + */ |
|
97 | + public function getServerConfigurationHosts() { |
|
98 | + $referenceConfigkey = 'ldap_host'; |
|
99 | + |
|
100 | + $keys = $this->getServersConfig($referenceConfigkey); |
|
101 | + |
|
102 | + $result = []; |
|
103 | + foreach($keys as $key) { |
|
104 | + $len = strlen($key) - strlen($referenceConfigkey); |
|
105 | + $prefix = substr($key, 0, $len); |
|
106 | + $result[$prefix] = $this->config->getAppValue('user_ldap', $key); |
|
107 | + } |
|
108 | + |
|
109 | + return $result; |
|
110 | + } |
|
111 | + |
|
112 | + /** |
|
113 | + * return the next available configuration prefix |
|
114 | + * |
|
115 | + * @return string |
|
116 | + */ |
|
117 | + public function getNextServerConfigurationPrefix() { |
|
118 | + $serverConnections = $this->getServerConfigurationPrefixes(); |
|
119 | + |
|
120 | + if(count($serverConnections) === 0) { |
|
121 | + return 's01'; |
|
122 | + } |
|
123 | + |
|
124 | + sort($serverConnections); |
|
125 | + $lastKey = array_pop($serverConnections); |
|
126 | + $lastNumber = (int)str_replace('s', '', $lastKey); |
|
127 | + return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT); |
|
128 | + } |
|
129 | + |
|
130 | + private function getServersConfig($value) { |
|
131 | + $regex = '/' . $value . '$/S'; |
|
132 | + |
|
133 | + $keys = $this->config->getAppKeys('user_ldap'); |
|
134 | + $result = []; |
|
135 | + foreach ($keys as $key) { |
|
136 | + if (preg_match($regex, $key) === 1) { |
|
137 | + $result[] = $key; |
|
138 | + } |
|
139 | + } |
|
140 | + |
|
141 | + return $result; |
|
142 | + } |
|
143 | + |
|
144 | + /** |
|
145 | + * deletes a given saved LDAP/AD server configuration. |
|
146 | + * @param string $prefix the configuration prefix of the config to delete |
|
147 | + * @return bool true on success, false otherwise |
|
148 | + */ |
|
149 | + public function deleteServerConfiguration($prefix) { |
|
150 | + if(!in_array($prefix, self::getServerConfigurationPrefixes())) { |
|
151 | + return false; |
|
152 | + } |
|
153 | + |
|
154 | + $saveOtherConfigurations = ''; |
|
155 | + if(empty($prefix)) { |
|
156 | + $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; |
|
157 | + } |
|
158 | + |
|
159 | + $query = \OC_DB::prepare(' |
|
160 | 160 | DELETE |
161 | 161 | FROM `*PREFIX*appconfig` |
162 | 162 | WHERE `configkey` LIKE ? |
@@ -164,149 +164,149 @@ discard block |
||
164 | 164 | AND `appid` = \'user_ldap\' |
165 | 165 | AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\') |
166 | 166 | '); |
167 | - $delRows = $query->execute([$prefix.'%']); |
|
168 | - |
|
169 | - if($delRows === null) { |
|
170 | - return false; |
|
171 | - } |
|
172 | - |
|
173 | - if($delRows === 0) { |
|
174 | - return false; |
|
175 | - } |
|
176 | - |
|
177 | - return true; |
|
178 | - } |
|
179 | - |
|
180 | - /** |
|
181 | - * checks whether there is one or more disabled LDAP configurations |
|
182 | - * @throws \Exception |
|
183 | - * @return bool |
|
184 | - */ |
|
185 | - public function haveDisabledConfigurations() { |
|
186 | - $all = $this->getServerConfigurationPrefixes(false); |
|
187 | - $active = $this->getServerConfigurationPrefixes(true); |
|
188 | - |
|
189 | - if(!is_array($all) || !is_array($active)) { |
|
190 | - throw new \Exception('Unexpected Return Value'); |
|
191 | - } |
|
192 | - |
|
193 | - return count($all) !== count($active) || count($all) === 0; |
|
194 | - } |
|
195 | - |
|
196 | - /** |
|
197 | - * extracts the domain from a given URL |
|
198 | - * @param string $url the URL |
|
199 | - * @return string|false domain as string on success, false otherwise |
|
200 | - */ |
|
201 | - public function getDomainFromURL($url) { |
|
202 | - $uinfo = parse_url($url); |
|
203 | - if(!is_array($uinfo)) { |
|
204 | - return false; |
|
205 | - } |
|
206 | - |
|
207 | - $domain = false; |
|
208 | - if(isset($uinfo['host'])) { |
|
209 | - $domain = $uinfo['host']; |
|
210 | - } else if(isset($uinfo['path'])) { |
|
211 | - $domain = $uinfo['path']; |
|
212 | - } |
|
213 | - |
|
214 | - return $domain; |
|
215 | - } |
|
216 | - |
|
217 | - /** |
|
218 | - * |
|
219 | - * Set the LDAPProvider in the config |
|
220 | - * |
|
221 | - */ |
|
222 | - public function setLDAPProvider() { |
|
223 | - $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null); |
|
224 | - if(is_null($current)) { |
|
225 | - \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class); |
|
226 | - } |
|
227 | - } |
|
228 | - |
|
229 | - /** |
|
230 | - * sanitizes a DN received from the LDAP server |
|
231 | - * @param array $dn the DN in question |
|
232 | - * @return array|string the sanitized DN |
|
233 | - */ |
|
234 | - public function sanitizeDN($dn) { |
|
235 | - //treating multiple base DNs |
|
236 | - if(is_array($dn)) { |
|
237 | - $result = []; |
|
238 | - foreach($dn as $singleDN) { |
|
239 | - $result[] = $this->sanitizeDN($singleDN); |
|
240 | - } |
|
241 | - return $result; |
|
242 | - } |
|
243 | - |
|
244 | - //OID sometimes gives back DNs with whitespace after the comma |
|
245 | - // a la "uid=foo, cn=bar, dn=..." We need to tackle this! |
|
246 | - $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn); |
|
247 | - |
|
248 | - //make comparisons and everything work |
|
249 | - $dn = mb_strtolower($dn, 'UTF-8'); |
|
250 | - |
|
251 | - //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn |
|
252 | - //to use the DN in search filters, \ needs to be escaped to \5c additionally |
|
253 | - //to use them in bases, we convert them back to simple backslashes in readAttribute() |
|
254 | - $replacements = [ |
|
255 | - '\,' => '\5c2C', |
|
256 | - '\=' => '\5c3D', |
|
257 | - '\+' => '\5c2B', |
|
258 | - '\<' => '\5c3C', |
|
259 | - '\>' => '\5c3E', |
|
260 | - '\;' => '\5c3B', |
|
261 | - '\"' => '\5c22', |
|
262 | - '\#' => '\5c23', |
|
263 | - '(' => '\28', |
|
264 | - ')' => '\29', |
|
265 | - '*' => '\2A', |
|
266 | - ]; |
|
267 | - $dn = str_replace(array_keys($replacements), array_values($replacements), $dn); |
|
268 | - |
|
269 | - return $dn; |
|
270 | - } |
|
271 | - |
|
272 | - /** |
|
273 | - * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters |
|
274 | - * @param string $dn the DN |
|
275 | - * @return string |
|
276 | - */ |
|
277 | - public function DNasBaseParameter($dn) { |
|
278 | - return str_ireplace('\\5c', '\\', $dn); |
|
279 | - } |
|
280 | - |
|
281 | - /** |
|
282 | - * listens to a hook thrown by server2server sharing and replaces the given |
|
283 | - * login name by a username, if it matches an LDAP user. |
|
284 | - * |
|
285 | - * @param array $param |
|
286 | - * @throws \Exception |
|
287 | - */ |
|
288 | - public static function loginName2UserName($param) { |
|
289 | - if(!isset($param['uid'])) { |
|
290 | - throw new \Exception('key uid is expected to be set in $param'); |
|
291 | - } |
|
292 | - |
|
293 | - //ain't it ironic? |
|
294 | - $helper = new Helper(\OC::$server->getConfig()); |
|
295 | - |
|
296 | - $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
297 | - $ldapWrapper = new LDAP(); |
|
298 | - $ocConfig = \OC::$server->getConfig(); |
|
299 | - $notificationManager = \OC::$server->getNotificationManager(); |
|
300 | - |
|
301 | - $userSession = \OC::$server->getUserSession(); |
|
302 | - $userPluginManager = \OC::$server->query('LDAPUserPluginManager'); |
|
303 | - |
|
304 | - $userBackend = new User_Proxy( |
|
305 | - $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager |
|
306 | - ); |
|
307 | - $uid = $userBackend->loginName2UserName($param['uid'] ); |
|
308 | - if($uid !== false) { |
|
309 | - $param['uid'] = $uid; |
|
310 | - } |
|
311 | - } |
|
167 | + $delRows = $query->execute([$prefix.'%']); |
|
168 | + |
|
169 | + if($delRows === null) { |
|
170 | + return false; |
|
171 | + } |
|
172 | + |
|
173 | + if($delRows === 0) { |
|
174 | + return false; |
|
175 | + } |
|
176 | + |
|
177 | + return true; |
|
178 | + } |
|
179 | + |
|
180 | + /** |
|
181 | + * checks whether there is one or more disabled LDAP configurations |
|
182 | + * @throws \Exception |
|
183 | + * @return bool |
|
184 | + */ |
|
185 | + public function haveDisabledConfigurations() { |
|
186 | + $all = $this->getServerConfigurationPrefixes(false); |
|
187 | + $active = $this->getServerConfigurationPrefixes(true); |
|
188 | + |
|
189 | + if(!is_array($all) || !is_array($active)) { |
|
190 | + throw new \Exception('Unexpected Return Value'); |
|
191 | + } |
|
192 | + |
|
193 | + return count($all) !== count($active) || count($all) === 0; |
|
194 | + } |
|
195 | + |
|
196 | + /** |
|
197 | + * extracts the domain from a given URL |
|
198 | + * @param string $url the URL |
|
199 | + * @return string|false domain as string on success, false otherwise |
|
200 | + */ |
|
201 | + public function getDomainFromURL($url) { |
|
202 | + $uinfo = parse_url($url); |
|
203 | + if(!is_array($uinfo)) { |
|
204 | + return false; |
|
205 | + } |
|
206 | + |
|
207 | + $domain = false; |
|
208 | + if(isset($uinfo['host'])) { |
|
209 | + $domain = $uinfo['host']; |
|
210 | + } else if(isset($uinfo['path'])) { |
|
211 | + $domain = $uinfo['path']; |
|
212 | + } |
|
213 | + |
|
214 | + return $domain; |
|
215 | + } |
|
216 | + |
|
217 | + /** |
|
218 | + * |
|
219 | + * Set the LDAPProvider in the config |
|
220 | + * |
|
221 | + */ |
|
222 | + public function setLDAPProvider() { |
|
223 | + $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null); |
|
224 | + if(is_null($current)) { |
|
225 | + \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class); |
|
226 | + } |
|
227 | + } |
|
228 | + |
|
229 | + /** |
|
230 | + * sanitizes a DN received from the LDAP server |
|
231 | + * @param array $dn the DN in question |
|
232 | + * @return array|string the sanitized DN |
|
233 | + */ |
|
234 | + public function sanitizeDN($dn) { |
|
235 | + //treating multiple base DNs |
|
236 | + if(is_array($dn)) { |
|
237 | + $result = []; |
|
238 | + foreach($dn as $singleDN) { |
|
239 | + $result[] = $this->sanitizeDN($singleDN); |
|
240 | + } |
|
241 | + return $result; |
|
242 | + } |
|
243 | + |
|
244 | + //OID sometimes gives back DNs with whitespace after the comma |
|
245 | + // a la "uid=foo, cn=bar, dn=..." We need to tackle this! |
|
246 | + $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn); |
|
247 | + |
|
248 | + //make comparisons and everything work |
|
249 | + $dn = mb_strtolower($dn, 'UTF-8'); |
|
250 | + |
|
251 | + //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn |
|
252 | + //to use the DN in search filters, \ needs to be escaped to \5c additionally |
|
253 | + //to use them in bases, we convert them back to simple backslashes in readAttribute() |
|
254 | + $replacements = [ |
|
255 | + '\,' => '\5c2C', |
|
256 | + '\=' => '\5c3D', |
|
257 | + '\+' => '\5c2B', |
|
258 | + '\<' => '\5c3C', |
|
259 | + '\>' => '\5c3E', |
|
260 | + '\;' => '\5c3B', |
|
261 | + '\"' => '\5c22', |
|
262 | + '\#' => '\5c23', |
|
263 | + '(' => '\28', |
|
264 | + ')' => '\29', |
|
265 | + '*' => '\2A', |
|
266 | + ]; |
|
267 | + $dn = str_replace(array_keys($replacements), array_values($replacements), $dn); |
|
268 | + |
|
269 | + return $dn; |
|
270 | + } |
|
271 | + |
|
272 | + /** |
|
273 | + * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters |
|
274 | + * @param string $dn the DN |
|
275 | + * @return string |
|
276 | + */ |
|
277 | + public function DNasBaseParameter($dn) { |
|
278 | + return str_ireplace('\\5c', '\\', $dn); |
|
279 | + } |
|
280 | + |
|
281 | + /** |
|
282 | + * listens to a hook thrown by server2server sharing and replaces the given |
|
283 | + * login name by a username, if it matches an LDAP user. |
|
284 | + * |
|
285 | + * @param array $param |
|
286 | + * @throws \Exception |
|
287 | + */ |
|
288 | + public static function loginName2UserName($param) { |
|
289 | + if(!isset($param['uid'])) { |
|
290 | + throw new \Exception('key uid is expected to be set in $param'); |
|
291 | + } |
|
292 | + |
|
293 | + //ain't it ironic? |
|
294 | + $helper = new Helper(\OC::$server->getConfig()); |
|
295 | + |
|
296 | + $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
297 | + $ldapWrapper = new LDAP(); |
|
298 | + $ocConfig = \OC::$server->getConfig(); |
|
299 | + $notificationManager = \OC::$server->getNotificationManager(); |
|
300 | + |
|
301 | + $userSession = \OC::$server->getUserSession(); |
|
302 | + $userPluginManager = \OC::$server->query('LDAPUserPluginManager'); |
|
303 | + |
|
304 | + $userBackend = new User_Proxy( |
|
305 | + $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager |
|
306 | + ); |
|
307 | + $uid = $userBackend->loginName2UserName($param['uid'] ); |
|
308 | + if($uid !== false) { |
|
309 | + $param['uid'] = $uid; |
|
310 | + } |
|
311 | + } |
|
312 | 312 | } |
@@ -30,293 +30,293 @@ |
||
30 | 30 | * @package OCA\User_LDAP\Mapping |
31 | 31 | */ |
32 | 32 | abstract class AbstractMapping { |
33 | - /** |
|
34 | - * @var \OCP\IDBConnection $dbc |
|
35 | - */ |
|
36 | - protected $dbc; |
|
33 | + /** |
|
34 | + * @var \OCP\IDBConnection $dbc |
|
35 | + */ |
|
36 | + protected $dbc; |
|
37 | 37 | |
38 | - /** |
|
39 | - * returns the DB table name which holds the mappings |
|
40 | - * @return string |
|
41 | - */ |
|
42 | - abstract protected function getTableName(); |
|
38 | + /** |
|
39 | + * returns the DB table name which holds the mappings |
|
40 | + * @return string |
|
41 | + */ |
|
42 | + abstract protected function getTableName(); |
|
43 | 43 | |
44 | - /** |
|
45 | - * @param \OCP\IDBConnection $dbc |
|
46 | - */ |
|
47 | - public function __construct(\OCP\IDBConnection $dbc) { |
|
48 | - $this->dbc = $dbc; |
|
49 | - } |
|
44 | + /** |
|
45 | + * @param \OCP\IDBConnection $dbc |
|
46 | + */ |
|
47 | + public function __construct(\OCP\IDBConnection $dbc) { |
|
48 | + $this->dbc = $dbc; |
|
49 | + } |
|
50 | 50 | |
51 | - /** |
|
52 | - * checks whether a provided string represents an existing table col |
|
53 | - * @param string $col |
|
54 | - * @return bool |
|
55 | - */ |
|
56 | - public function isColNameValid($col) { |
|
57 | - switch($col) { |
|
58 | - case 'ldap_dn': |
|
59 | - case 'owncloud_name': |
|
60 | - case 'directory_uuid': |
|
61 | - return true; |
|
62 | - default: |
|
63 | - return false; |
|
64 | - } |
|
65 | - } |
|
51 | + /** |
|
52 | + * checks whether a provided string represents an existing table col |
|
53 | + * @param string $col |
|
54 | + * @return bool |
|
55 | + */ |
|
56 | + public function isColNameValid($col) { |
|
57 | + switch($col) { |
|
58 | + case 'ldap_dn': |
|
59 | + case 'owncloud_name': |
|
60 | + case 'directory_uuid': |
|
61 | + return true; |
|
62 | + default: |
|
63 | + return false; |
|
64 | + } |
|
65 | + } |
|
66 | 66 | |
67 | - /** |
|
68 | - * Gets the value of one column based on a provided value of another column |
|
69 | - * @param string $fetchCol |
|
70 | - * @param string $compareCol |
|
71 | - * @param string $search |
|
72 | - * @throws \Exception |
|
73 | - * @return string|false |
|
74 | - */ |
|
75 | - protected function getXbyY($fetchCol, $compareCol, $search) { |
|
76 | - if(!$this->isColNameValid($fetchCol)) { |
|
77 | - //this is used internally only, but we don't want to risk |
|
78 | - //having SQL injection at all. |
|
79 | - throw new \Exception('Invalid Column Name'); |
|
80 | - } |
|
81 | - $query = $this->dbc->prepare(' |
|
67 | + /** |
|
68 | + * Gets the value of one column based on a provided value of another column |
|
69 | + * @param string $fetchCol |
|
70 | + * @param string $compareCol |
|
71 | + * @param string $search |
|
72 | + * @throws \Exception |
|
73 | + * @return string|false |
|
74 | + */ |
|
75 | + protected function getXbyY($fetchCol, $compareCol, $search) { |
|
76 | + if(!$this->isColNameValid($fetchCol)) { |
|
77 | + //this is used internally only, but we don't want to risk |
|
78 | + //having SQL injection at all. |
|
79 | + throw new \Exception('Invalid Column Name'); |
|
80 | + } |
|
81 | + $query = $this->dbc->prepare(' |
|
82 | 82 | SELECT `' . $fetchCol . '` |
83 | 83 | FROM `'. $this->getTableName() .'` |
84 | 84 | WHERE `' . $compareCol . '` = ? |
85 | 85 | '); |
86 | 86 | |
87 | - $res = $query->execute([$search]); |
|
88 | - if($res !== false) { |
|
89 | - return $query->fetchColumn(); |
|
90 | - } |
|
87 | + $res = $query->execute([$search]); |
|
88 | + if($res !== false) { |
|
89 | + return $query->fetchColumn(); |
|
90 | + } |
|
91 | 91 | |
92 | - return false; |
|
93 | - } |
|
92 | + return false; |
|
93 | + } |
|
94 | 94 | |
95 | - /** |
|
96 | - * Performs a DELETE or UPDATE query to the database. |
|
97 | - * @param \Doctrine\DBAL\Driver\Statement $query |
|
98 | - * @param array $parameters |
|
99 | - * @return bool true if at least one row was modified, false otherwise |
|
100 | - */ |
|
101 | - protected function modify($query, $parameters) { |
|
102 | - $result = $query->execute($parameters); |
|
103 | - return ($result === true && $query->rowCount() > 0); |
|
104 | - } |
|
95 | + /** |
|
96 | + * Performs a DELETE or UPDATE query to the database. |
|
97 | + * @param \Doctrine\DBAL\Driver\Statement $query |
|
98 | + * @param array $parameters |
|
99 | + * @return bool true if at least one row was modified, false otherwise |
|
100 | + */ |
|
101 | + protected function modify($query, $parameters) { |
|
102 | + $result = $query->execute($parameters); |
|
103 | + return ($result === true && $query->rowCount() > 0); |
|
104 | + } |
|
105 | 105 | |
106 | - /** |
|
107 | - * Gets the LDAP DN based on the provided name. |
|
108 | - * Replaces Access::ocname2dn |
|
109 | - * @param string $name |
|
110 | - * @return string|false |
|
111 | - */ |
|
112 | - public function getDNByName($name) { |
|
113 | - return $this->getXbyY('ldap_dn', 'owncloud_name', $name); |
|
114 | - } |
|
106 | + /** |
|
107 | + * Gets the LDAP DN based on the provided name. |
|
108 | + * Replaces Access::ocname2dn |
|
109 | + * @param string $name |
|
110 | + * @return string|false |
|
111 | + */ |
|
112 | + public function getDNByName($name) { |
|
113 | + return $this->getXbyY('ldap_dn', 'owncloud_name', $name); |
|
114 | + } |
|
115 | 115 | |
116 | - /** |
|
117 | - * Updates the DN based on the given UUID |
|
118 | - * @param string $fdn |
|
119 | - * @param string $uuid |
|
120 | - * @return bool |
|
121 | - */ |
|
122 | - public function setDNbyUUID($fdn, $uuid) { |
|
123 | - $query = $this->dbc->prepare(' |
|
116 | + /** |
|
117 | + * Updates the DN based on the given UUID |
|
118 | + * @param string $fdn |
|
119 | + * @param string $uuid |
|
120 | + * @return bool |
|
121 | + */ |
|
122 | + public function setDNbyUUID($fdn, $uuid) { |
|
123 | + $query = $this->dbc->prepare(' |
|
124 | 124 | UPDATE `' . $this->getTableName() . '` |
125 | 125 | SET `ldap_dn` = ? |
126 | 126 | WHERE `directory_uuid` = ? |
127 | 127 | '); |
128 | 128 | |
129 | - return $this->modify($query, [$fdn, $uuid]); |
|
130 | - } |
|
129 | + return $this->modify($query, [$fdn, $uuid]); |
|
130 | + } |
|
131 | 131 | |
132 | - /** |
|
133 | - * Updates the UUID based on the given DN |
|
134 | - * |
|
135 | - * required by Migration/UUIDFix |
|
136 | - * |
|
137 | - * @param $uuid |
|
138 | - * @param $fdn |
|
139 | - * @return bool |
|
140 | - */ |
|
141 | - public function setUUIDbyDN($uuid, $fdn) { |
|
142 | - $query = $this->dbc->prepare(' |
|
132 | + /** |
|
133 | + * Updates the UUID based on the given DN |
|
134 | + * |
|
135 | + * required by Migration/UUIDFix |
|
136 | + * |
|
137 | + * @param $uuid |
|
138 | + * @param $fdn |
|
139 | + * @return bool |
|
140 | + */ |
|
141 | + public function setUUIDbyDN($uuid, $fdn) { |
|
142 | + $query = $this->dbc->prepare(' |
|
143 | 143 | UPDATE `' . $this->getTableName() . '` |
144 | 144 | SET `directory_uuid` = ? |
145 | 145 | WHERE `ldap_dn` = ? |
146 | 146 | '); |
147 | 147 | |
148 | - return $this->modify($query, [$uuid, $fdn]); |
|
149 | - } |
|
148 | + return $this->modify($query, [$uuid, $fdn]); |
|
149 | + } |
|
150 | 150 | |
151 | - /** |
|
152 | - * Gets the name based on the provided LDAP DN. |
|
153 | - * @param string $fdn |
|
154 | - * @return string|false |
|
155 | - */ |
|
156 | - public function getNameByDN($fdn) { |
|
157 | - return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn); |
|
158 | - } |
|
151 | + /** |
|
152 | + * Gets the name based on the provided LDAP DN. |
|
153 | + * @param string $fdn |
|
154 | + * @return string|false |
|
155 | + */ |
|
156 | + public function getNameByDN($fdn) { |
|
157 | + return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn); |
|
158 | + } |
|
159 | 159 | |
160 | - /** |
|
161 | - * Searches mapped names by the giving string in the name column |
|
162 | - * @param string $search |
|
163 | - * @param string $prefixMatch |
|
164 | - * @param string $postfixMatch |
|
165 | - * @return string[] |
|
166 | - */ |
|
167 | - public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") { |
|
168 | - $query = $this->dbc->prepare(' |
|
160 | + /** |
|
161 | + * Searches mapped names by the giving string in the name column |
|
162 | + * @param string $search |
|
163 | + * @param string $prefixMatch |
|
164 | + * @param string $postfixMatch |
|
165 | + * @return string[] |
|
166 | + */ |
|
167 | + public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") { |
|
168 | + $query = $this->dbc->prepare(' |
|
169 | 169 | SELECT `owncloud_name` |
170 | 170 | FROM `'. $this->getTableName() .'` |
171 | 171 | WHERE `owncloud_name` LIKE ? |
172 | 172 | '); |
173 | 173 | |
174 | - $res = $query->execute([$prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch]); |
|
175 | - $names = []; |
|
176 | - if($res !== false) { |
|
177 | - while($row = $query->fetch()) { |
|
178 | - $names[] = $row['owncloud_name']; |
|
179 | - } |
|
180 | - } |
|
181 | - return $names; |
|
182 | - } |
|
174 | + $res = $query->execute([$prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch]); |
|
175 | + $names = []; |
|
176 | + if($res !== false) { |
|
177 | + while($row = $query->fetch()) { |
|
178 | + $names[] = $row['owncloud_name']; |
|
179 | + } |
|
180 | + } |
|
181 | + return $names; |
|
182 | + } |
|
183 | 183 | |
184 | - /** |
|
185 | - * Gets the name based on the provided LDAP UUID. |
|
186 | - * @param string $uuid |
|
187 | - * @return string|false |
|
188 | - */ |
|
189 | - public function getNameByUUID($uuid) { |
|
190 | - return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid); |
|
191 | - } |
|
184 | + /** |
|
185 | + * Gets the name based on the provided LDAP UUID. |
|
186 | + * @param string $uuid |
|
187 | + * @return string|false |
|
188 | + */ |
|
189 | + public function getNameByUUID($uuid) { |
|
190 | + return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid); |
|
191 | + } |
|
192 | 192 | |
193 | - /** |
|
194 | - * Gets the UUID based on the provided LDAP DN |
|
195 | - * @param string $dn |
|
196 | - * @return false|string |
|
197 | - * @throws \Exception |
|
198 | - */ |
|
199 | - public function getUUIDByDN($dn) { |
|
200 | - return $this->getXbyY('directory_uuid', 'ldap_dn', $dn); |
|
201 | - } |
|
193 | + /** |
|
194 | + * Gets the UUID based on the provided LDAP DN |
|
195 | + * @param string $dn |
|
196 | + * @return false|string |
|
197 | + * @throws \Exception |
|
198 | + */ |
|
199 | + public function getUUIDByDN($dn) { |
|
200 | + return $this->getXbyY('directory_uuid', 'ldap_dn', $dn); |
|
201 | + } |
|
202 | 202 | |
203 | - /** |
|
204 | - * gets a piece of the mapping list |
|
205 | - * @param int $offset |
|
206 | - * @param int $limit |
|
207 | - * @return array |
|
208 | - */ |
|
209 | - public function getList($offset = null, $limit = null) { |
|
210 | - $query = $this->dbc->prepare(' |
|
203 | + /** |
|
204 | + * gets a piece of the mapping list |
|
205 | + * @param int $offset |
|
206 | + * @param int $limit |
|
207 | + * @return array |
|
208 | + */ |
|
209 | + public function getList($offset = null, $limit = null) { |
|
210 | + $query = $this->dbc->prepare(' |
|
211 | 211 | SELECT |
212 | 212 | `ldap_dn` AS `dn`, |
213 | 213 | `owncloud_name` AS `name`, |
214 | 214 | `directory_uuid` AS `uuid` |
215 | 215 | FROM `' . $this->getTableName() . '`', |
216 | - $limit, |
|
217 | - $offset |
|
218 | - ); |
|
216 | + $limit, |
|
217 | + $offset |
|
218 | + ); |
|
219 | 219 | |
220 | - $query->execute(); |
|
221 | - return $query->fetchAll(); |
|
222 | - } |
|
220 | + $query->execute(); |
|
221 | + return $query->fetchAll(); |
|
222 | + } |
|
223 | 223 | |
224 | - /** |
|
225 | - * attempts to map the given entry |
|
226 | - * @param string $fdn fully distinguished name (from LDAP) |
|
227 | - * @param string $name |
|
228 | - * @param string $uuid a unique identifier as used in LDAP |
|
229 | - * @return bool |
|
230 | - */ |
|
231 | - public function map($fdn, $name, $uuid) { |
|
232 | - if(mb_strlen($fdn) > 255) { |
|
233 | - \OC::$server->getLogger()->error( |
|
234 | - 'Cannot map, because the DN exceeds 255 characters: {dn}', |
|
235 | - [ |
|
236 | - 'app' => 'user_ldap', |
|
237 | - 'dn' => $fdn, |
|
238 | - ] |
|
239 | - ); |
|
240 | - return false; |
|
241 | - } |
|
224 | + /** |
|
225 | + * attempts to map the given entry |
|
226 | + * @param string $fdn fully distinguished name (from LDAP) |
|
227 | + * @param string $name |
|
228 | + * @param string $uuid a unique identifier as used in LDAP |
|
229 | + * @return bool |
|
230 | + */ |
|
231 | + public function map($fdn, $name, $uuid) { |
|
232 | + if(mb_strlen($fdn) > 255) { |
|
233 | + \OC::$server->getLogger()->error( |
|
234 | + 'Cannot map, because the DN exceeds 255 characters: {dn}', |
|
235 | + [ |
|
236 | + 'app' => 'user_ldap', |
|
237 | + 'dn' => $fdn, |
|
238 | + ] |
|
239 | + ); |
|
240 | + return false; |
|
241 | + } |
|
242 | 242 | |
243 | - $row = [ |
|
244 | - 'ldap_dn' => $fdn, |
|
245 | - 'owncloud_name' => $name, |
|
246 | - 'directory_uuid' => $uuid |
|
247 | - ]; |
|
243 | + $row = [ |
|
244 | + 'ldap_dn' => $fdn, |
|
245 | + 'owncloud_name' => $name, |
|
246 | + 'directory_uuid' => $uuid |
|
247 | + ]; |
|
248 | 248 | |
249 | - try { |
|
250 | - $result = $this->dbc->insertIfNotExist($this->getTableName(), $row); |
|
251 | - // insertIfNotExist returns values as int |
|
252 | - return (bool)$result; |
|
253 | - } catch (\Exception $e) { |
|
254 | - return false; |
|
255 | - } |
|
256 | - } |
|
249 | + try { |
|
250 | + $result = $this->dbc->insertIfNotExist($this->getTableName(), $row); |
|
251 | + // insertIfNotExist returns values as int |
|
252 | + return (bool)$result; |
|
253 | + } catch (\Exception $e) { |
|
254 | + return false; |
|
255 | + } |
|
256 | + } |
|
257 | 257 | |
258 | - /** |
|
259 | - * removes a mapping based on the owncloud_name of the entry |
|
260 | - * @param string $name |
|
261 | - * @return bool |
|
262 | - */ |
|
263 | - public function unmap($name) { |
|
264 | - $query = $this->dbc->prepare(' |
|
258 | + /** |
|
259 | + * removes a mapping based on the owncloud_name of the entry |
|
260 | + * @param string $name |
|
261 | + * @return bool |
|
262 | + */ |
|
263 | + public function unmap($name) { |
|
264 | + $query = $this->dbc->prepare(' |
|
265 | 265 | DELETE FROM `'. $this->getTableName() .'` |
266 | 266 | WHERE `owncloud_name` = ?'); |
267 | 267 | |
268 | - return $this->modify($query, [$name]); |
|
269 | - } |
|
268 | + return $this->modify($query, [$name]); |
|
269 | + } |
|
270 | 270 | |
271 | - /** |
|
272 | - * Truncate's the mapping table |
|
273 | - * @return bool |
|
274 | - */ |
|
275 | - public function clear() { |
|
276 | - $sql = $this->dbc |
|
277 | - ->getDatabasePlatform() |
|
278 | - ->getTruncateTableSQL('`' . $this->getTableName() . '`'); |
|
279 | - return $this->dbc->prepare($sql)->execute(); |
|
280 | - } |
|
271 | + /** |
|
272 | + * Truncate's the mapping table |
|
273 | + * @return bool |
|
274 | + */ |
|
275 | + public function clear() { |
|
276 | + $sql = $this->dbc |
|
277 | + ->getDatabasePlatform() |
|
278 | + ->getTruncateTableSQL('`' . $this->getTableName() . '`'); |
|
279 | + return $this->dbc->prepare($sql)->execute(); |
|
280 | + } |
|
281 | 281 | |
282 | - /** |
|
283 | - * clears the mapping table one by one and executing a callback with |
|
284 | - * each row's id (=owncloud_name col) |
|
285 | - * |
|
286 | - * @param callable $preCallback |
|
287 | - * @param callable $postCallback |
|
288 | - * @return bool true on success, false when at least one row was not |
|
289 | - * deleted |
|
290 | - */ |
|
291 | - public function clearCb(Callable $preCallback, Callable $postCallback): bool { |
|
292 | - $picker = $this->dbc->getQueryBuilder(); |
|
293 | - $picker->select('owncloud_name') |
|
294 | - ->from($this->getTableName()); |
|
295 | - $cursor = $picker->execute(); |
|
296 | - $result = true; |
|
297 | - while($id = $cursor->fetchColumn(0)) { |
|
298 | - $preCallback($id); |
|
299 | - if($isUnmapped = $this->unmap($id)) { |
|
300 | - $postCallback($id); |
|
301 | - } |
|
302 | - $result &= $isUnmapped; |
|
303 | - } |
|
304 | - $cursor->closeCursor(); |
|
305 | - return $result; |
|
306 | - } |
|
282 | + /** |
|
283 | + * clears the mapping table one by one and executing a callback with |
|
284 | + * each row's id (=owncloud_name col) |
|
285 | + * |
|
286 | + * @param callable $preCallback |
|
287 | + * @param callable $postCallback |
|
288 | + * @return bool true on success, false when at least one row was not |
|
289 | + * deleted |
|
290 | + */ |
|
291 | + public function clearCb(Callable $preCallback, Callable $postCallback): bool { |
|
292 | + $picker = $this->dbc->getQueryBuilder(); |
|
293 | + $picker->select('owncloud_name') |
|
294 | + ->from($this->getTableName()); |
|
295 | + $cursor = $picker->execute(); |
|
296 | + $result = true; |
|
297 | + while($id = $cursor->fetchColumn(0)) { |
|
298 | + $preCallback($id); |
|
299 | + if($isUnmapped = $this->unmap($id)) { |
|
300 | + $postCallback($id); |
|
301 | + } |
|
302 | + $result &= $isUnmapped; |
|
303 | + } |
|
304 | + $cursor->closeCursor(); |
|
305 | + return $result; |
|
306 | + } |
|
307 | 307 | |
308 | - /** |
|
309 | - * returns the number of entries in the mappings table |
|
310 | - * |
|
311 | - * @return int |
|
312 | - */ |
|
313 | - public function count() { |
|
314 | - $qb = $this->dbc->getQueryBuilder(); |
|
315 | - $query = $qb->select($qb->func()->count('ldap_dn')) |
|
316 | - ->from($this->getTableName()); |
|
317 | - $res = $query->execute(); |
|
318 | - $count = $res->fetchColumn(); |
|
319 | - $res->closeCursor(); |
|
320 | - return (int)$count; |
|
321 | - } |
|
308 | + /** |
|
309 | + * returns the number of entries in the mappings table |
|
310 | + * |
|
311 | + * @return int |
|
312 | + */ |
|
313 | + public function count() { |
|
314 | + $qb = $this->dbc->getQueryBuilder(); |
|
315 | + $query = $qb->select($qb->func()->count('ldap_dn')) |
|
316 | + ->from($this->getTableName()); |
|
317 | + $res = $query->execute(); |
|
318 | + $count = $res->fetchColumn(); |
|
319 | + $res->closeCursor(); |
|
320 | + return (int)$count; |
|
321 | + } |
|
322 | 322 | } |
@@ -34,361 +34,361 @@ |
||
34 | 34 | use OCA\User_LDAP\Exceptions\ConstraintViolationException; |
35 | 35 | |
36 | 36 | class LDAP implements ILDAPWrapper { |
37 | - protected $curFunc = ''; |
|
38 | - protected $curArgs = []; |
|
39 | - |
|
40 | - /** |
|
41 | - * @param resource $link |
|
42 | - * @param string $dn |
|
43 | - * @param string $password |
|
44 | - * @return bool|mixed |
|
45 | - */ |
|
46 | - public function bind($link, $dn, $password) { |
|
47 | - return $this->invokeLDAPMethod('bind', $link, $dn, $password); |
|
48 | - } |
|
49 | - |
|
50 | - /** |
|
51 | - * @param string $host |
|
52 | - * @param string $port |
|
53 | - * @return mixed |
|
54 | - */ |
|
55 | - public function connect($host, $port) { |
|
56 | - if(strpos($host, '://') === false) { |
|
57 | - $host = 'ldap://' . $host; |
|
58 | - } |
|
59 | - if(strpos($host, ':', strpos($host, '://') + 1) === false) { |
|
60 | - //ldap_connect ignores port parameter when URLs are passed |
|
61 | - $host .= ':' . $port; |
|
62 | - } |
|
63 | - return $this->invokeLDAPMethod('connect', $host); |
|
64 | - } |
|
65 | - |
|
66 | - /** |
|
67 | - * @param resource $link |
|
68 | - * @param resource $result |
|
69 | - * @param string $cookie |
|
70 | - * @return bool|LDAP |
|
71 | - */ |
|
72 | - public function controlPagedResultResponse($link, $result, &$cookie) { |
|
73 | - $this->preFunctionCall('ldap_control_paged_result_response', |
|
74 | - [$link, $result, $cookie]); |
|
75 | - $result = ldap_control_paged_result_response($link, $result, $cookie); |
|
76 | - $this->postFunctionCall(); |
|
77 | - |
|
78 | - return $result; |
|
79 | - } |
|
80 | - |
|
81 | - /** |
|
82 | - * @param LDAP $link |
|
83 | - * @param int $pageSize |
|
84 | - * @param bool $isCritical |
|
85 | - * @param string $cookie |
|
86 | - * @return mixed|true |
|
87 | - */ |
|
88 | - public function controlPagedResult($link, $pageSize, $isCritical, $cookie) { |
|
89 | - return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize, |
|
90 | - $isCritical, $cookie); |
|
91 | - } |
|
92 | - |
|
93 | - /** |
|
94 | - * @param LDAP $link |
|
95 | - * @param LDAP $result |
|
96 | - * @return mixed |
|
97 | - */ |
|
98 | - public function countEntries($link, $result) { |
|
99 | - return $this->invokeLDAPMethod('count_entries', $link, $result); |
|
100 | - } |
|
101 | - |
|
102 | - /** |
|
103 | - * @param LDAP $link |
|
104 | - * @return integer |
|
105 | - */ |
|
106 | - public function errno($link) { |
|
107 | - return $this->invokeLDAPMethod('errno', $link); |
|
108 | - } |
|
109 | - |
|
110 | - /** |
|
111 | - * @param LDAP $link |
|
112 | - * @return string |
|
113 | - */ |
|
114 | - public function error($link) { |
|
115 | - return $this->invokeLDAPMethod('error', $link); |
|
116 | - } |
|
117 | - |
|
118 | - /** |
|
119 | - * Splits DN into its component parts |
|
120 | - * @param string $dn |
|
121 | - * @param int @withAttrib |
|
122 | - * @return array|false |
|
123 | - * @link http://www.php.net/manual/en/function.ldap-explode-dn.php |
|
124 | - */ |
|
125 | - public function explodeDN($dn, $withAttrib) { |
|
126 | - return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib); |
|
127 | - } |
|
128 | - |
|
129 | - /** |
|
130 | - * @param LDAP $link |
|
131 | - * @param LDAP $result |
|
132 | - * @return mixed |
|
133 | - */ |
|
134 | - public function firstEntry($link, $result) { |
|
135 | - return $this->invokeLDAPMethod('first_entry', $link, $result); |
|
136 | - } |
|
137 | - |
|
138 | - /** |
|
139 | - * @param LDAP $link |
|
140 | - * @param LDAP $result |
|
141 | - * @return array|mixed |
|
142 | - */ |
|
143 | - public function getAttributes($link, $result) { |
|
144 | - return $this->invokeLDAPMethod('get_attributes', $link, $result); |
|
145 | - } |
|
146 | - |
|
147 | - /** |
|
148 | - * @param LDAP $link |
|
149 | - * @param LDAP $result |
|
150 | - * @return mixed|string |
|
151 | - */ |
|
152 | - public function getDN($link, $result) { |
|
153 | - return $this->invokeLDAPMethod('get_dn', $link, $result); |
|
154 | - } |
|
155 | - |
|
156 | - /** |
|
157 | - * @param LDAP $link |
|
158 | - * @param LDAP $result |
|
159 | - * @return array|mixed |
|
160 | - */ |
|
161 | - public function getEntries($link, $result) { |
|
162 | - return $this->invokeLDAPMethod('get_entries', $link, $result); |
|
163 | - } |
|
164 | - |
|
165 | - /** |
|
166 | - * @param LDAP $link |
|
167 | - * @param resource $result |
|
168 | - * @return mixed |
|
169 | - */ |
|
170 | - public function nextEntry($link, $result) { |
|
171 | - return $this->invokeLDAPMethod('next_entry', $link, $result); |
|
172 | - } |
|
173 | - |
|
174 | - /** |
|
175 | - * @param LDAP $link |
|
176 | - * @param string $baseDN |
|
177 | - * @param string $filter |
|
178 | - * @param array $attr |
|
179 | - * @return mixed |
|
180 | - */ |
|
181 | - public function read($link, $baseDN, $filter, $attr) { |
|
182 | - return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr); |
|
183 | - } |
|
184 | - |
|
185 | - /** |
|
186 | - * @param LDAP $link |
|
187 | - * @param string $baseDN |
|
188 | - * @param string $filter |
|
189 | - * @param array $attr |
|
190 | - * @param int $attrsOnly |
|
191 | - * @param int $limit |
|
192 | - * @return mixed |
|
193 | - * @throws \Exception |
|
194 | - */ |
|
195 | - public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) { |
|
196 | - $oldHandler = set_error_handler(function($no, $message, $file, $line) use (&$oldHandler) { |
|
197 | - if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) { |
|
198 | - return true; |
|
199 | - } |
|
200 | - $oldHandler($no, $message, $file, $line); |
|
201 | - return true; |
|
202 | - }); |
|
203 | - try { |
|
204 | - $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit); |
|
205 | - restore_error_handler(); |
|
206 | - return $result; |
|
207 | - } catch (\Exception $e) { |
|
208 | - restore_error_handler(); |
|
209 | - throw $e; |
|
210 | - } |
|
211 | - } |
|
212 | - |
|
213 | - /** |
|
214 | - * @param LDAP $link |
|
215 | - * @param string $userDN |
|
216 | - * @param string $password |
|
217 | - * @return bool |
|
218 | - */ |
|
219 | - public function modReplace($link, $userDN, $password) { |
|
220 | - return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]); |
|
221 | - } |
|
222 | - |
|
223 | - /** |
|
224 | - * @param LDAP $link |
|
225 | - * @param string $userDN |
|
226 | - * @param string $oldPassword |
|
227 | - * @param string $password |
|
228 | - * @return bool |
|
229 | - */ |
|
230 | - public function exopPasswd($link, $userDN, $oldPassword, $password) { |
|
231 | - return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password); |
|
232 | - } |
|
233 | - |
|
234 | - /** |
|
235 | - * @param LDAP $link |
|
236 | - * @param string $option |
|
237 | - * @param int $value |
|
238 | - * @return bool|mixed |
|
239 | - */ |
|
240 | - public function setOption($link, $option, $value) { |
|
241 | - return $this->invokeLDAPMethod('set_option', $link, $option, $value); |
|
242 | - } |
|
243 | - |
|
244 | - /** |
|
245 | - * @param LDAP $link |
|
246 | - * @return mixed|true |
|
247 | - */ |
|
248 | - public function startTls($link) { |
|
249 | - return $this->invokeLDAPMethod('start_tls', $link); |
|
250 | - } |
|
251 | - |
|
252 | - /** |
|
253 | - * @param resource $link |
|
254 | - * @return bool|mixed |
|
255 | - */ |
|
256 | - public function unbind($link) { |
|
257 | - return $this->invokeLDAPMethod('unbind', $link); |
|
258 | - } |
|
259 | - |
|
260 | - /** |
|
261 | - * Checks whether the server supports LDAP |
|
262 | - * @return boolean if it the case, false otherwise |
|
263 | - * */ |
|
264 | - public function areLDAPFunctionsAvailable() { |
|
265 | - return function_exists('ldap_connect'); |
|
266 | - } |
|
267 | - |
|
268 | - /** |
|
269 | - * Checks whether the submitted parameter is a resource |
|
270 | - * @param Resource $resource the resource variable to check |
|
271 | - * @return bool true if it is a resource, false otherwise |
|
272 | - */ |
|
273 | - public function isResource($resource) { |
|
274 | - return is_resource($resource); |
|
275 | - } |
|
276 | - |
|
277 | - /** |
|
278 | - * Checks whether the return value from LDAP is wrong or not. |
|
279 | - * |
|
280 | - * When using ldap_search we provide an array, in case multiple bases are |
|
281 | - * configured. Thus, we need to check the array elements. |
|
282 | - * |
|
283 | - * @param $result |
|
284 | - * @return bool |
|
285 | - */ |
|
286 | - protected function isResultFalse($result) { |
|
287 | - if($result === false) { |
|
288 | - return true; |
|
289 | - } |
|
290 | - |
|
291 | - if($this->curFunc === 'ldap_search' && is_array($result)) { |
|
292 | - foreach ($result as $singleResult) { |
|
293 | - if($singleResult === false) { |
|
294 | - return true; |
|
295 | - } |
|
296 | - } |
|
297 | - } |
|
298 | - |
|
299 | - return false; |
|
300 | - } |
|
301 | - |
|
302 | - /** |
|
303 | - * @return mixed |
|
304 | - */ |
|
305 | - protected function invokeLDAPMethod() { |
|
306 | - $arguments = func_get_args(); |
|
307 | - $func = 'ldap_' . array_shift($arguments); |
|
308 | - if(function_exists($func)) { |
|
309 | - $this->preFunctionCall($func, $arguments); |
|
310 | - $result = call_user_func_array($func, $arguments); |
|
311 | - if ($this->isResultFalse($result)) { |
|
312 | - $this->postFunctionCall(); |
|
313 | - } |
|
314 | - return $result; |
|
315 | - } |
|
316 | - return null; |
|
317 | - } |
|
318 | - |
|
319 | - /** |
|
320 | - * @param string $functionName |
|
321 | - * @param array $args |
|
322 | - */ |
|
323 | - private function preFunctionCall($functionName, $args) { |
|
324 | - $this->curFunc = $functionName; |
|
325 | - $this->curArgs = $args; |
|
326 | - } |
|
327 | - |
|
328 | - /** |
|
329 | - * Analyzes the returned LDAP error and acts accordingly if not 0 |
|
330 | - * |
|
331 | - * @param resource $resource the LDAP Connection resource |
|
332 | - * @throws ConstraintViolationException |
|
333 | - * @throws ServerNotAvailableException |
|
334 | - * @throws \Exception |
|
335 | - */ |
|
336 | - private function processLDAPError($resource) { |
|
337 | - $errorCode = ldap_errno($resource); |
|
338 | - if($errorCode === 0) { |
|
339 | - return; |
|
340 | - } |
|
341 | - $errorMsg = ldap_error($resource); |
|
342 | - |
|
343 | - if($this->curFunc === 'ldap_get_entries' |
|
344 | - && $errorCode === -4) { |
|
345 | - } else if ($errorCode === 32) { |
|
346 | - //for now |
|
347 | - } else if ($errorCode === 10) { |
|
348 | - //referrals, we switch them off, but then there is AD :) |
|
349 | - } else if ($errorCode === -1) { |
|
350 | - throw new ServerNotAvailableException('Lost connection to LDAP server.'); |
|
351 | - } else if ($errorCode === 52) { |
|
352 | - throw new ServerNotAvailableException('LDAP server is shutting down.'); |
|
353 | - } else if ($errorCode === 48) { |
|
354 | - throw new \Exception('LDAP authentication method rejected', $errorCode); |
|
355 | - } else if ($errorCode === 1) { |
|
356 | - throw new \Exception('LDAP Operations error', $errorCode); |
|
357 | - } else if ($errorCode === 19) { |
|
358 | - ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error); |
|
359 | - throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode); |
|
360 | - } else { |
|
361 | - \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [ |
|
362 | - 'app' => 'user_ldap', |
|
363 | - 'message' => $errorMsg, |
|
364 | - 'code' => $errorCode, |
|
365 | - 'func' => $this->curFunc, |
|
366 | - ]); |
|
367 | - } |
|
368 | - } |
|
369 | - |
|
370 | - /** |
|
371 | - * Called after an ldap method is run to act on LDAP error if necessary |
|
372 | - * @throw \Exception |
|
373 | - */ |
|
374 | - private function postFunctionCall() { |
|
375 | - if($this->isResource($this->curArgs[0])) { |
|
376 | - $resource = $this->curArgs[0]; |
|
377 | - } else if( |
|
378 | - $this->curFunc === 'ldap_search' |
|
379 | - && is_array($this->curArgs[0]) |
|
380 | - && $this->isResource($this->curArgs[0][0]) |
|
381 | - ) { |
|
382 | - // we use always the same LDAP connection resource, is enough to |
|
383 | - // take the first one. |
|
384 | - $resource = $this->curArgs[0][0]; |
|
385 | - } else { |
|
386 | - return; |
|
387 | - } |
|
388 | - |
|
389 | - $this->processLDAPError($resource); |
|
390 | - |
|
391 | - $this->curFunc = ''; |
|
392 | - $this->curArgs = []; |
|
393 | - } |
|
37 | + protected $curFunc = ''; |
|
38 | + protected $curArgs = []; |
|
39 | + |
|
40 | + /** |
|
41 | + * @param resource $link |
|
42 | + * @param string $dn |
|
43 | + * @param string $password |
|
44 | + * @return bool|mixed |
|
45 | + */ |
|
46 | + public function bind($link, $dn, $password) { |
|
47 | + return $this->invokeLDAPMethod('bind', $link, $dn, $password); |
|
48 | + } |
|
49 | + |
|
50 | + /** |
|
51 | + * @param string $host |
|
52 | + * @param string $port |
|
53 | + * @return mixed |
|
54 | + */ |
|
55 | + public function connect($host, $port) { |
|
56 | + if(strpos($host, '://') === false) { |
|
57 | + $host = 'ldap://' . $host; |
|
58 | + } |
|
59 | + if(strpos($host, ':', strpos($host, '://') + 1) === false) { |
|
60 | + //ldap_connect ignores port parameter when URLs are passed |
|
61 | + $host .= ':' . $port; |
|
62 | + } |
|
63 | + return $this->invokeLDAPMethod('connect', $host); |
|
64 | + } |
|
65 | + |
|
66 | + /** |
|
67 | + * @param resource $link |
|
68 | + * @param resource $result |
|
69 | + * @param string $cookie |
|
70 | + * @return bool|LDAP |
|
71 | + */ |
|
72 | + public function controlPagedResultResponse($link, $result, &$cookie) { |
|
73 | + $this->preFunctionCall('ldap_control_paged_result_response', |
|
74 | + [$link, $result, $cookie]); |
|
75 | + $result = ldap_control_paged_result_response($link, $result, $cookie); |
|
76 | + $this->postFunctionCall(); |
|
77 | + |
|
78 | + return $result; |
|
79 | + } |
|
80 | + |
|
81 | + /** |
|
82 | + * @param LDAP $link |
|
83 | + * @param int $pageSize |
|
84 | + * @param bool $isCritical |
|
85 | + * @param string $cookie |
|
86 | + * @return mixed|true |
|
87 | + */ |
|
88 | + public function controlPagedResult($link, $pageSize, $isCritical, $cookie) { |
|
89 | + return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize, |
|
90 | + $isCritical, $cookie); |
|
91 | + } |
|
92 | + |
|
93 | + /** |
|
94 | + * @param LDAP $link |
|
95 | + * @param LDAP $result |
|
96 | + * @return mixed |
|
97 | + */ |
|
98 | + public function countEntries($link, $result) { |
|
99 | + return $this->invokeLDAPMethod('count_entries', $link, $result); |
|
100 | + } |
|
101 | + |
|
102 | + /** |
|
103 | + * @param LDAP $link |
|
104 | + * @return integer |
|
105 | + */ |
|
106 | + public function errno($link) { |
|
107 | + return $this->invokeLDAPMethod('errno', $link); |
|
108 | + } |
|
109 | + |
|
110 | + /** |
|
111 | + * @param LDAP $link |
|
112 | + * @return string |
|
113 | + */ |
|
114 | + public function error($link) { |
|
115 | + return $this->invokeLDAPMethod('error', $link); |
|
116 | + } |
|
117 | + |
|
118 | + /** |
|
119 | + * Splits DN into its component parts |
|
120 | + * @param string $dn |
|
121 | + * @param int @withAttrib |
|
122 | + * @return array|false |
|
123 | + * @link http://www.php.net/manual/en/function.ldap-explode-dn.php |
|
124 | + */ |
|
125 | + public function explodeDN($dn, $withAttrib) { |
|
126 | + return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib); |
|
127 | + } |
|
128 | + |
|
129 | + /** |
|
130 | + * @param LDAP $link |
|
131 | + * @param LDAP $result |
|
132 | + * @return mixed |
|
133 | + */ |
|
134 | + public function firstEntry($link, $result) { |
|
135 | + return $this->invokeLDAPMethod('first_entry', $link, $result); |
|
136 | + } |
|
137 | + |
|
138 | + /** |
|
139 | + * @param LDAP $link |
|
140 | + * @param LDAP $result |
|
141 | + * @return array|mixed |
|
142 | + */ |
|
143 | + public function getAttributes($link, $result) { |
|
144 | + return $this->invokeLDAPMethod('get_attributes', $link, $result); |
|
145 | + } |
|
146 | + |
|
147 | + /** |
|
148 | + * @param LDAP $link |
|
149 | + * @param LDAP $result |
|
150 | + * @return mixed|string |
|
151 | + */ |
|
152 | + public function getDN($link, $result) { |
|
153 | + return $this->invokeLDAPMethod('get_dn', $link, $result); |
|
154 | + } |
|
155 | + |
|
156 | + /** |
|
157 | + * @param LDAP $link |
|
158 | + * @param LDAP $result |
|
159 | + * @return array|mixed |
|
160 | + */ |
|
161 | + public function getEntries($link, $result) { |
|
162 | + return $this->invokeLDAPMethod('get_entries', $link, $result); |
|
163 | + } |
|
164 | + |
|
165 | + /** |
|
166 | + * @param LDAP $link |
|
167 | + * @param resource $result |
|
168 | + * @return mixed |
|
169 | + */ |
|
170 | + public function nextEntry($link, $result) { |
|
171 | + return $this->invokeLDAPMethod('next_entry', $link, $result); |
|
172 | + } |
|
173 | + |
|
174 | + /** |
|
175 | + * @param LDAP $link |
|
176 | + * @param string $baseDN |
|
177 | + * @param string $filter |
|
178 | + * @param array $attr |
|
179 | + * @return mixed |
|
180 | + */ |
|
181 | + public function read($link, $baseDN, $filter, $attr) { |
|
182 | + return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr); |
|
183 | + } |
|
184 | + |
|
185 | + /** |
|
186 | + * @param LDAP $link |
|
187 | + * @param string $baseDN |
|
188 | + * @param string $filter |
|
189 | + * @param array $attr |
|
190 | + * @param int $attrsOnly |
|
191 | + * @param int $limit |
|
192 | + * @return mixed |
|
193 | + * @throws \Exception |
|
194 | + */ |
|
195 | + public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) { |
|
196 | + $oldHandler = set_error_handler(function($no, $message, $file, $line) use (&$oldHandler) { |
|
197 | + if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) { |
|
198 | + return true; |
|
199 | + } |
|
200 | + $oldHandler($no, $message, $file, $line); |
|
201 | + return true; |
|
202 | + }); |
|
203 | + try { |
|
204 | + $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit); |
|
205 | + restore_error_handler(); |
|
206 | + return $result; |
|
207 | + } catch (\Exception $e) { |
|
208 | + restore_error_handler(); |
|
209 | + throw $e; |
|
210 | + } |
|
211 | + } |
|
212 | + |
|
213 | + /** |
|
214 | + * @param LDAP $link |
|
215 | + * @param string $userDN |
|
216 | + * @param string $password |
|
217 | + * @return bool |
|
218 | + */ |
|
219 | + public function modReplace($link, $userDN, $password) { |
|
220 | + return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]); |
|
221 | + } |
|
222 | + |
|
223 | + /** |
|
224 | + * @param LDAP $link |
|
225 | + * @param string $userDN |
|
226 | + * @param string $oldPassword |
|
227 | + * @param string $password |
|
228 | + * @return bool |
|
229 | + */ |
|
230 | + public function exopPasswd($link, $userDN, $oldPassword, $password) { |
|
231 | + return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password); |
|
232 | + } |
|
233 | + |
|
234 | + /** |
|
235 | + * @param LDAP $link |
|
236 | + * @param string $option |
|
237 | + * @param int $value |
|
238 | + * @return bool|mixed |
|
239 | + */ |
|
240 | + public function setOption($link, $option, $value) { |
|
241 | + return $this->invokeLDAPMethod('set_option', $link, $option, $value); |
|
242 | + } |
|
243 | + |
|
244 | + /** |
|
245 | + * @param LDAP $link |
|
246 | + * @return mixed|true |
|
247 | + */ |
|
248 | + public function startTls($link) { |
|
249 | + return $this->invokeLDAPMethod('start_tls', $link); |
|
250 | + } |
|
251 | + |
|
252 | + /** |
|
253 | + * @param resource $link |
|
254 | + * @return bool|mixed |
|
255 | + */ |
|
256 | + public function unbind($link) { |
|
257 | + return $this->invokeLDAPMethod('unbind', $link); |
|
258 | + } |
|
259 | + |
|
260 | + /** |
|
261 | + * Checks whether the server supports LDAP |
|
262 | + * @return boolean if it the case, false otherwise |
|
263 | + * */ |
|
264 | + public function areLDAPFunctionsAvailable() { |
|
265 | + return function_exists('ldap_connect'); |
|
266 | + } |
|
267 | + |
|
268 | + /** |
|
269 | + * Checks whether the submitted parameter is a resource |
|
270 | + * @param Resource $resource the resource variable to check |
|
271 | + * @return bool true if it is a resource, false otherwise |
|
272 | + */ |
|
273 | + public function isResource($resource) { |
|
274 | + return is_resource($resource); |
|
275 | + } |
|
276 | + |
|
277 | + /** |
|
278 | + * Checks whether the return value from LDAP is wrong or not. |
|
279 | + * |
|
280 | + * When using ldap_search we provide an array, in case multiple bases are |
|
281 | + * configured. Thus, we need to check the array elements. |
|
282 | + * |
|
283 | + * @param $result |
|
284 | + * @return bool |
|
285 | + */ |
|
286 | + protected function isResultFalse($result) { |
|
287 | + if($result === false) { |
|
288 | + return true; |
|
289 | + } |
|
290 | + |
|
291 | + if($this->curFunc === 'ldap_search' && is_array($result)) { |
|
292 | + foreach ($result as $singleResult) { |
|
293 | + if($singleResult === false) { |
|
294 | + return true; |
|
295 | + } |
|
296 | + } |
|
297 | + } |
|
298 | + |
|
299 | + return false; |
|
300 | + } |
|
301 | + |
|
302 | + /** |
|
303 | + * @return mixed |
|
304 | + */ |
|
305 | + protected function invokeLDAPMethod() { |
|
306 | + $arguments = func_get_args(); |
|
307 | + $func = 'ldap_' . array_shift($arguments); |
|
308 | + if(function_exists($func)) { |
|
309 | + $this->preFunctionCall($func, $arguments); |
|
310 | + $result = call_user_func_array($func, $arguments); |
|
311 | + if ($this->isResultFalse($result)) { |
|
312 | + $this->postFunctionCall(); |
|
313 | + } |
|
314 | + return $result; |
|
315 | + } |
|
316 | + return null; |
|
317 | + } |
|
318 | + |
|
319 | + /** |
|
320 | + * @param string $functionName |
|
321 | + * @param array $args |
|
322 | + */ |
|
323 | + private function preFunctionCall($functionName, $args) { |
|
324 | + $this->curFunc = $functionName; |
|
325 | + $this->curArgs = $args; |
|
326 | + } |
|
327 | + |
|
328 | + /** |
|
329 | + * Analyzes the returned LDAP error and acts accordingly if not 0 |
|
330 | + * |
|
331 | + * @param resource $resource the LDAP Connection resource |
|
332 | + * @throws ConstraintViolationException |
|
333 | + * @throws ServerNotAvailableException |
|
334 | + * @throws \Exception |
|
335 | + */ |
|
336 | + private function processLDAPError($resource) { |
|
337 | + $errorCode = ldap_errno($resource); |
|
338 | + if($errorCode === 0) { |
|
339 | + return; |
|
340 | + } |
|
341 | + $errorMsg = ldap_error($resource); |
|
342 | + |
|
343 | + if($this->curFunc === 'ldap_get_entries' |
|
344 | + && $errorCode === -4) { |
|
345 | + } else if ($errorCode === 32) { |
|
346 | + //for now |
|
347 | + } else if ($errorCode === 10) { |
|
348 | + //referrals, we switch them off, but then there is AD :) |
|
349 | + } else if ($errorCode === -1) { |
|
350 | + throw new ServerNotAvailableException('Lost connection to LDAP server.'); |
|
351 | + } else if ($errorCode === 52) { |
|
352 | + throw new ServerNotAvailableException('LDAP server is shutting down.'); |
|
353 | + } else if ($errorCode === 48) { |
|
354 | + throw new \Exception('LDAP authentication method rejected', $errorCode); |
|
355 | + } else if ($errorCode === 1) { |
|
356 | + throw new \Exception('LDAP Operations error', $errorCode); |
|
357 | + } else if ($errorCode === 19) { |
|
358 | + ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error); |
|
359 | + throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode); |
|
360 | + } else { |
|
361 | + \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [ |
|
362 | + 'app' => 'user_ldap', |
|
363 | + 'message' => $errorMsg, |
|
364 | + 'code' => $errorCode, |
|
365 | + 'func' => $this->curFunc, |
|
366 | + ]); |
|
367 | + } |
|
368 | + } |
|
369 | + |
|
370 | + /** |
|
371 | + * Called after an ldap method is run to act on LDAP error if necessary |
|
372 | + * @throw \Exception |
|
373 | + */ |
|
374 | + private function postFunctionCall() { |
|
375 | + if($this->isResource($this->curArgs[0])) { |
|
376 | + $resource = $this->curArgs[0]; |
|
377 | + } else if( |
|
378 | + $this->curFunc === 'ldap_search' |
|
379 | + && is_array($this->curArgs[0]) |
|
380 | + && $this->isResource($this->curArgs[0][0]) |
|
381 | + ) { |
|
382 | + // we use always the same LDAP connection resource, is enough to |
|
383 | + // take the first one. |
|
384 | + $resource = $this->curArgs[0][0]; |
|
385 | + } else { |
|
386 | + return; |
|
387 | + } |
|
388 | + |
|
389 | + $this->processLDAPError($resource); |
|
390 | + |
|
391 | + $this->curFunc = ''; |
|
392 | + $this->curArgs = []; |
|
393 | + } |
|
394 | 394 | } |
@@ -68,621 +68,621 @@ |
||
68 | 68 | * @property string ldapGroupDisplayName |
69 | 69 | */ |
70 | 70 | class Connection extends LDAPUtility { |
71 | - private $ldapConnectionRes = null; |
|
72 | - private $configPrefix; |
|
73 | - private $configID; |
|
74 | - private $configured = false; |
|
75 | - //whether connection should be kept on __destruct |
|
76 | - private $dontDestruct = false; |
|
77 | - |
|
78 | - /** |
|
79 | - * @var bool runtime flag that indicates whether supported primary groups are available |
|
80 | - */ |
|
81 | - public $hasPrimaryGroups = true; |
|
82 | - |
|
83 | - /** |
|
84 | - * @var bool runtime flag that indicates whether supported POSIX gidNumber are available |
|
85 | - */ |
|
86 | - public $hasGidNumber = true; |
|
87 | - |
|
88 | - //cache handler |
|
89 | - protected $cache; |
|
90 | - |
|
91 | - /** @var Configuration settings handler **/ |
|
92 | - protected $configuration; |
|
93 | - |
|
94 | - protected $doNotValidate = false; |
|
95 | - |
|
96 | - protected $ignoreValidation = false; |
|
97 | - |
|
98 | - protected $bindResult = []; |
|
99 | - |
|
100 | - /** |
|
101 | - * Constructor |
|
102 | - * @param ILDAPWrapper $ldap |
|
103 | - * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) |
|
104 | - * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections |
|
105 | - */ |
|
106 | - public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { |
|
107 | - parent::__construct($ldap); |
|
108 | - $this->configPrefix = $configPrefix; |
|
109 | - $this->configID = $configID; |
|
110 | - $this->configuration = new Configuration($configPrefix, |
|
111 | - !is_null($configID)); |
|
112 | - $memcache = \OC::$server->getMemCacheFactory(); |
|
113 | - if($memcache->isAvailable()) { |
|
114 | - $this->cache = $memcache->createDistributed(); |
|
115 | - } |
|
116 | - $helper = new Helper(\OC::$server->getConfig()); |
|
117 | - $this->doNotValidate = !in_array($this->configPrefix, |
|
118 | - $helper->getServerConfigurationPrefixes()); |
|
119 | - } |
|
120 | - |
|
121 | - public function __destruct() { |
|
122 | - if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { |
|
123 | - @$this->ldap->unbind($this->ldapConnectionRes); |
|
124 | - $this->bindResult = []; |
|
125 | - } |
|
126 | - } |
|
127 | - |
|
128 | - /** |
|
129 | - * defines behaviour when the instance is cloned |
|
130 | - */ |
|
131 | - public function __clone() { |
|
132 | - $this->configuration = new Configuration($this->configPrefix, |
|
133 | - !is_null($this->configID)); |
|
134 | - if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { |
|
135 | - $this->bindResult = []; |
|
136 | - } |
|
137 | - $this->ldapConnectionRes = null; |
|
138 | - $this->dontDestruct = true; |
|
139 | - } |
|
140 | - |
|
141 | - /** |
|
142 | - * @param string $name |
|
143 | - * @return bool|mixed |
|
144 | - */ |
|
145 | - public function __get($name) { |
|
146 | - if(!$this->configured) { |
|
147 | - $this->readConfiguration(); |
|
148 | - } |
|
149 | - |
|
150 | - return $this->configuration->$name; |
|
151 | - } |
|
152 | - |
|
153 | - /** |
|
154 | - * @param string $name |
|
155 | - * @param mixed $value |
|
156 | - */ |
|
157 | - public function __set($name, $value) { |
|
158 | - $this->doNotValidate = false; |
|
159 | - $before = $this->configuration->$name; |
|
160 | - $this->configuration->$name = $value; |
|
161 | - $after = $this->configuration->$name; |
|
162 | - if($before !== $after) { |
|
163 | - if ($this->configID !== '' && $this->configID !== null) { |
|
164 | - $this->configuration->saveConfiguration(); |
|
165 | - } |
|
166 | - $this->validateConfiguration(); |
|
167 | - } |
|
168 | - } |
|
169 | - |
|
170 | - /** |
|
171 | - * @param string $rule |
|
172 | - * @return array |
|
173 | - * @throws \RuntimeException |
|
174 | - */ |
|
175 | - public function resolveRule($rule) { |
|
176 | - return $this->configuration->resolveRule($rule); |
|
177 | - } |
|
178 | - |
|
179 | - /** |
|
180 | - * sets whether the result of the configuration validation shall |
|
181 | - * be ignored when establishing the connection. Used by the Wizard |
|
182 | - * in early configuration state. |
|
183 | - * @param bool $state |
|
184 | - */ |
|
185 | - public function setIgnoreValidation($state) { |
|
186 | - $this->ignoreValidation = (bool)$state; |
|
187 | - } |
|
188 | - |
|
189 | - /** |
|
190 | - * initializes the LDAP backend |
|
191 | - * @param bool $force read the config settings no matter what |
|
192 | - */ |
|
193 | - public function init($force = false) { |
|
194 | - $this->readConfiguration($force); |
|
195 | - $this->establishConnection(); |
|
196 | - } |
|
197 | - |
|
198 | - /** |
|
199 | - * Returns the LDAP handler |
|
200 | - */ |
|
201 | - public function getConnectionResource() { |
|
202 | - if(!$this->ldapConnectionRes) { |
|
203 | - $this->init(); |
|
204 | - } else if(!$this->ldap->isResource($this->ldapConnectionRes)) { |
|
205 | - $this->ldapConnectionRes = null; |
|
206 | - $this->establishConnection(); |
|
207 | - } |
|
208 | - if(is_null($this->ldapConnectionRes)) { |
|
209 | - \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); |
|
210 | - throw new ServerNotAvailableException('Connection to LDAP server could not be established'); |
|
211 | - } |
|
212 | - return $this->ldapConnectionRes; |
|
213 | - } |
|
214 | - |
|
215 | - /** |
|
216 | - * resets the connection resource |
|
217 | - */ |
|
218 | - public function resetConnectionResource() { |
|
219 | - if(!is_null($this->ldapConnectionRes)) { |
|
220 | - @$this->ldap->unbind($this->ldapConnectionRes); |
|
221 | - $this->ldapConnectionRes = null; |
|
222 | - $this->bindResult = []; |
|
223 | - } |
|
224 | - } |
|
225 | - |
|
226 | - /** |
|
227 | - * @param string|null $key |
|
228 | - * @return string |
|
229 | - */ |
|
230 | - private function getCacheKey($key) { |
|
231 | - $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; |
|
232 | - if(is_null($key)) { |
|
233 | - return $prefix; |
|
234 | - } |
|
235 | - return $prefix.hash('sha256', $key); |
|
236 | - } |
|
237 | - |
|
238 | - /** |
|
239 | - * @param string $key |
|
240 | - * @return mixed|null |
|
241 | - */ |
|
242 | - public function getFromCache($key) { |
|
243 | - if(!$this->configured) { |
|
244 | - $this->readConfiguration(); |
|
245 | - } |
|
246 | - if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { |
|
247 | - return null; |
|
248 | - } |
|
249 | - $key = $this->getCacheKey($key); |
|
250 | - |
|
251 | - return json_decode(base64_decode($this->cache->get($key)), true); |
|
252 | - } |
|
253 | - |
|
254 | - /** |
|
255 | - * @param string $key |
|
256 | - * @param mixed $value |
|
257 | - * |
|
258 | - * @return string |
|
259 | - */ |
|
260 | - public function writeToCache($key, $value) { |
|
261 | - if(!$this->configured) { |
|
262 | - $this->readConfiguration(); |
|
263 | - } |
|
264 | - if(is_null($this->cache) |
|
265 | - || !$this->configuration->ldapCacheTTL |
|
266 | - || !$this->configuration->ldapConfigurationActive) { |
|
267 | - return null; |
|
268 | - } |
|
269 | - $key = $this->getCacheKey($key); |
|
270 | - $value = base64_encode(json_encode($value)); |
|
271 | - $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); |
|
272 | - } |
|
273 | - |
|
274 | - public function clearCache() { |
|
275 | - if(!is_null($this->cache)) { |
|
276 | - $this->cache->clear($this->getCacheKey(null)); |
|
277 | - } |
|
278 | - } |
|
279 | - |
|
280 | - /** |
|
281 | - * Caches the general LDAP configuration. |
|
282 | - * @param bool $force optional. true, if the re-read should be forced. defaults |
|
283 | - * to false. |
|
284 | - * @return null |
|
285 | - */ |
|
286 | - private function readConfiguration($force = false) { |
|
287 | - if((!$this->configured || $force) && !is_null($this->configID)) { |
|
288 | - $this->configuration->readConfiguration(); |
|
289 | - $this->configured = $this->validateConfiguration(); |
|
290 | - } |
|
291 | - } |
|
292 | - |
|
293 | - /** |
|
294 | - * set LDAP configuration with values delivered by an array, not read from configuration |
|
295 | - * @param array $config array that holds the config parameters in an associated array |
|
296 | - * @param array &$setParameters optional; array where the set fields will be given to |
|
297 | - * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters |
|
298 | - */ |
|
299 | - public function setConfiguration($config, &$setParameters = null) { |
|
300 | - if(is_null($setParameters)) { |
|
301 | - $setParameters = []; |
|
302 | - } |
|
303 | - $this->doNotValidate = false; |
|
304 | - $this->configuration->setConfiguration($config, $setParameters); |
|
305 | - if(count($setParameters) > 0) { |
|
306 | - $this->configured = $this->validateConfiguration(); |
|
307 | - } |
|
308 | - |
|
309 | - |
|
310 | - return $this->configured; |
|
311 | - } |
|
312 | - |
|
313 | - /** |
|
314 | - * saves the current Configuration in the database and empties the |
|
315 | - * cache |
|
316 | - * @return null |
|
317 | - */ |
|
318 | - public function saveConfiguration() { |
|
319 | - $this->configuration->saveConfiguration(); |
|
320 | - $this->clearCache(); |
|
321 | - } |
|
322 | - |
|
323 | - /** |
|
324 | - * get the current LDAP configuration |
|
325 | - * @return array |
|
326 | - */ |
|
327 | - public function getConfiguration() { |
|
328 | - $this->readConfiguration(); |
|
329 | - $config = $this->configuration->getConfiguration(); |
|
330 | - $cta = $this->configuration->getConfigTranslationArray(); |
|
331 | - $result = []; |
|
332 | - foreach($cta as $dbkey => $configkey) { |
|
333 | - switch($configkey) { |
|
334 | - case 'homeFolderNamingRule': |
|
335 | - if(strpos($config[$configkey], 'attr:') === 0) { |
|
336 | - $result[$dbkey] = substr($config[$configkey], 5); |
|
337 | - } else { |
|
338 | - $result[$dbkey] = ''; |
|
339 | - } |
|
340 | - break; |
|
341 | - case 'ldapBase': |
|
342 | - case 'ldapBaseUsers': |
|
343 | - case 'ldapBaseGroups': |
|
344 | - case 'ldapAttributesForUserSearch': |
|
345 | - case 'ldapAttributesForGroupSearch': |
|
346 | - if(is_array($config[$configkey])) { |
|
347 | - $result[$dbkey] = implode("\n", $config[$configkey]); |
|
348 | - break; |
|
349 | - } //else follows default |
|
350 | - default: |
|
351 | - $result[$dbkey] = $config[$configkey]; |
|
352 | - } |
|
353 | - } |
|
354 | - return $result; |
|
355 | - } |
|
356 | - |
|
357 | - private function doSoftValidation() { |
|
358 | - //if User or Group Base are not set, take over Base DN setting |
|
359 | - foreach(['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { |
|
360 | - $val = $this->configuration->$keyBase; |
|
361 | - if(empty($val)) { |
|
362 | - $this->configuration->$keyBase = $this->configuration->ldapBase; |
|
363 | - } |
|
364 | - } |
|
365 | - |
|
366 | - foreach(['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', |
|
367 | - 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] |
|
368 | - as $expertSetting => $effectiveSetting) { |
|
369 | - $uuidOverride = $this->configuration->$expertSetting; |
|
370 | - if(!empty($uuidOverride)) { |
|
371 | - $this->configuration->$effectiveSetting = $uuidOverride; |
|
372 | - } else { |
|
373 | - $uuidAttributes = Access::UUID_ATTRIBUTES; |
|
374 | - array_unshift($uuidAttributes, 'auto'); |
|
375 | - if(!in_array($this->configuration->$effectiveSetting, |
|
376 | - $uuidAttributes) |
|
377 | - && (!is_null($this->configID))) { |
|
378 | - $this->configuration->$effectiveSetting = 'auto'; |
|
379 | - $this->configuration->saveConfiguration(); |
|
380 | - \OCP\Util::writeLog('user_ldap', |
|
381 | - 'Illegal value for the '. |
|
382 | - $effectiveSetting.', '.'reset to '. |
|
383 | - 'autodetect.', ILogger::INFO); |
|
384 | - } |
|
385 | - |
|
386 | - } |
|
387 | - } |
|
388 | - |
|
389 | - $backupPort = (int)$this->configuration->ldapBackupPort; |
|
390 | - if ($backupPort <= 0) { |
|
391 | - $this->configuration->backupPort = $this->configuration->ldapPort; |
|
392 | - } |
|
393 | - |
|
394 | - //make sure empty search attributes are saved as simple, empty array |
|
395 | - $saKeys = ['ldapAttributesForUserSearch', |
|
396 | - 'ldapAttributesForGroupSearch']; |
|
397 | - foreach($saKeys as $key) { |
|
398 | - $val = $this->configuration->$key; |
|
399 | - if(is_array($val) && count($val) === 1 && empty($val[0])) { |
|
400 | - $this->configuration->$key = []; |
|
401 | - } |
|
402 | - } |
|
403 | - |
|
404 | - if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) |
|
405 | - && $this->configuration->ldapTLS) { |
|
406 | - $this->configuration->ldapTLS = false; |
|
407 | - \OCP\Util::writeLog( |
|
408 | - 'user_ldap', |
|
409 | - 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.', |
|
410 | - ILogger::INFO |
|
411 | - ); |
|
412 | - } |
|
413 | - } |
|
414 | - |
|
415 | - /** |
|
416 | - * @return bool |
|
417 | - */ |
|
418 | - private function doCriticalValidation() { |
|
419 | - $configurationOK = true; |
|
420 | - $errorStr = 'Configuration Error (prefix '. |
|
421 | - (string)$this->configPrefix .'): '; |
|
422 | - |
|
423 | - //options that shall not be empty |
|
424 | - $options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName', |
|
425 | - 'ldapGroupDisplayName', 'ldapLoginFilter']; |
|
426 | - foreach($options as $key) { |
|
427 | - $val = $this->configuration->$key; |
|
428 | - if(empty($val)) { |
|
429 | - switch($key) { |
|
430 | - case 'ldapHost': |
|
431 | - $subj = 'LDAP Host'; |
|
432 | - break; |
|
433 | - case 'ldapPort': |
|
434 | - $subj = 'LDAP Port'; |
|
435 | - break; |
|
436 | - case 'ldapUserDisplayName': |
|
437 | - $subj = 'LDAP User Display Name'; |
|
438 | - break; |
|
439 | - case 'ldapGroupDisplayName': |
|
440 | - $subj = 'LDAP Group Display Name'; |
|
441 | - break; |
|
442 | - case 'ldapLoginFilter': |
|
443 | - $subj = 'LDAP Login Filter'; |
|
444 | - break; |
|
445 | - default: |
|
446 | - $subj = $key; |
|
447 | - break; |
|
448 | - } |
|
449 | - $configurationOK = false; |
|
450 | - \OCP\Util::writeLog( |
|
451 | - 'user_ldap', |
|
452 | - $errorStr.'No '.$subj.' given!', |
|
453 | - ILogger::WARN |
|
454 | - ); |
|
455 | - } |
|
456 | - } |
|
457 | - |
|
458 | - //combinations |
|
459 | - $agent = $this->configuration->ldapAgentName; |
|
460 | - $pwd = $this->configuration->ldapAgentPassword; |
|
461 | - if ( |
|
462 | - ($agent === '' && $pwd !== '') |
|
463 | - || ($agent !== '' && $pwd === '') |
|
464 | - ) { |
|
465 | - \OCP\Util::writeLog( |
|
466 | - 'user_ldap', |
|
467 | - $errorStr.'either no password is given for the user ' . |
|
468 | - 'agent or a password is given, but not an LDAP agent.', |
|
469 | - ILogger::WARN); |
|
470 | - $configurationOK = false; |
|
471 | - } |
|
472 | - |
|
473 | - $base = $this->configuration->ldapBase; |
|
474 | - $baseUsers = $this->configuration->ldapBaseUsers; |
|
475 | - $baseGroups = $this->configuration->ldapBaseGroups; |
|
476 | - |
|
477 | - if(empty($base) && empty($baseUsers) && empty($baseGroups)) { |
|
478 | - \OCP\Util::writeLog( |
|
479 | - 'user_ldap', |
|
480 | - $errorStr.'Not a single Base DN given.', |
|
481 | - ILogger::WARN |
|
482 | - ); |
|
483 | - $configurationOK = false; |
|
484 | - } |
|
485 | - |
|
486 | - if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
487 | - === false) { |
|
488 | - \OCP\Util::writeLog( |
|
489 | - 'user_ldap', |
|
490 | - $errorStr.'login filter does not contain %uid place holder.', |
|
491 | - ILogger::WARN |
|
492 | - ); |
|
493 | - $configurationOK = false; |
|
494 | - } |
|
495 | - |
|
496 | - return $configurationOK; |
|
497 | - } |
|
498 | - |
|
499 | - /** |
|
500 | - * Validates the user specified configuration |
|
501 | - * @return bool true if configuration seems OK, false otherwise |
|
502 | - */ |
|
503 | - private function validateConfiguration() { |
|
504 | - |
|
505 | - if($this->doNotValidate) { |
|
506 | - //don't do a validation if it is a new configuration with pure |
|
507 | - //default values. Will be allowed on changes via __set or |
|
508 | - //setConfiguration |
|
509 | - return false; |
|
510 | - } |
|
511 | - |
|
512 | - // first step: "soft" checks: settings that are not really |
|
513 | - // necessary, but advisable. If left empty, give an info message |
|
514 | - $this->doSoftValidation(); |
|
515 | - |
|
516 | - //second step: critical checks. If left empty or filled wrong, mark as |
|
517 | - //not configured and give a warning. |
|
518 | - return $this->doCriticalValidation(); |
|
519 | - } |
|
520 | - |
|
521 | - |
|
522 | - /** |
|
523 | - * Connects and Binds to LDAP |
|
524 | - * |
|
525 | - * @throws ServerNotAvailableException |
|
526 | - */ |
|
527 | - private function establishConnection() { |
|
528 | - if(!$this->configuration->ldapConfigurationActive) { |
|
529 | - return null; |
|
530 | - } |
|
531 | - static $phpLDAPinstalled = true; |
|
532 | - if(!$phpLDAPinstalled) { |
|
533 | - return false; |
|
534 | - } |
|
535 | - if(!$this->ignoreValidation && !$this->configured) { |
|
536 | - \OCP\Util::writeLog( |
|
537 | - 'user_ldap', |
|
538 | - 'Configuration is invalid, cannot connect', |
|
539 | - ILogger::WARN |
|
540 | - ); |
|
541 | - return false; |
|
542 | - } |
|
543 | - if(!$this->ldapConnectionRes) { |
|
544 | - if(!$this->ldap->areLDAPFunctionsAvailable()) { |
|
545 | - $phpLDAPinstalled = false; |
|
546 | - \OCP\Util::writeLog( |
|
547 | - 'user_ldap', |
|
548 | - 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.', |
|
549 | - ILogger::ERROR |
|
550 | - ); |
|
551 | - |
|
552 | - return false; |
|
553 | - } |
|
554 | - if($this->configuration->turnOffCertCheck) { |
|
555 | - if(putenv('LDAPTLS_REQCERT=never')) { |
|
556 | - \OCP\Util::writeLog('user_ldap', |
|
557 | - 'Turned off SSL certificate validation successfully.', |
|
558 | - ILogger::DEBUG); |
|
559 | - } else { |
|
560 | - \OCP\Util::writeLog( |
|
561 | - 'user_ldap', |
|
562 | - 'Could not turn off SSL certificate validation.', |
|
563 | - ILogger::WARN |
|
564 | - ); |
|
565 | - } |
|
566 | - } |
|
567 | - |
|
568 | - $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer |
|
569 | - || $this->getFromCache('overrideMainServer')); |
|
570 | - $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); |
|
571 | - $bindStatus = false; |
|
572 | - try { |
|
573 | - if (!$isOverrideMainServer) { |
|
574 | - $this->doConnect($this->configuration->ldapHost, |
|
575 | - $this->configuration->ldapPort); |
|
576 | - return $this->bind(); |
|
577 | - } |
|
578 | - } catch (ServerNotAvailableException $e) { |
|
579 | - if(!$isBackupHost) { |
|
580 | - throw $e; |
|
581 | - } |
|
582 | - } |
|
583 | - |
|
584 | - //if LDAP server is not reachable, try the Backup (Replica!) Server |
|
585 | - if($isBackupHost || $isOverrideMainServer) { |
|
586 | - $this->doConnect($this->configuration->ldapBackupHost, |
|
587 | - $this->configuration->ldapBackupPort); |
|
588 | - $this->bindResult = []; |
|
589 | - $bindStatus = $this->bind(); |
|
590 | - $error = $this->ldap->isResource($this->ldapConnectionRes) ? |
|
591 | - $this->ldap->errno($this->ldapConnectionRes) : -1; |
|
592 | - if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { |
|
593 | - //when bind to backup server succeeded and failed to main server, |
|
594 | - //skip contacting him until next cache refresh |
|
595 | - $this->writeToCache('overrideMainServer', true); |
|
596 | - } |
|
597 | - } |
|
598 | - |
|
599 | - return $bindStatus; |
|
600 | - } |
|
601 | - return null; |
|
602 | - } |
|
603 | - |
|
604 | - /** |
|
605 | - * @param string $host |
|
606 | - * @param string $port |
|
607 | - * @return bool |
|
608 | - * @throws \OC\ServerNotAvailableException |
|
609 | - */ |
|
610 | - private function doConnect($host, $port) { |
|
611 | - if ($host === '') { |
|
612 | - return false; |
|
613 | - } |
|
614 | - |
|
615 | - $this->ldapConnectionRes = $this->ldap->connect($host, $port); |
|
616 | - |
|
617 | - if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { |
|
618 | - throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); |
|
619 | - } |
|
620 | - |
|
621 | - if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { |
|
622 | - throw new ServerNotAvailableException('Could not disable LDAP referrals.'); |
|
623 | - } |
|
624 | - |
|
625 | - if($this->configuration->ldapTLS) { |
|
626 | - if(!$this->ldap->startTls($this->ldapConnectionRes)) { |
|
627 | - throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); |
|
628 | - } |
|
629 | - } |
|
630 | - |
|
631 | - return true; |
|
632 | - } |
|
633 | - |
|
634 | - /** |
|
635 | - * Binds to LDAP |
|
636 | - */ |
|
637 | - public function bind() { |
|
638 | - if(!$this->configuration->ldapConfigurationActive) { |
|
639 | - return false; |
|
640 | - } |
|
641 | - $cr = $this->ldapConnectionRes; |
|
642 | - if(!$this->ldap->isResource($cr)) { |
|
643 | - $cr = $this->getConnectionResource(); |
|
644 | - } |
|
645 | - |
|
646 | - if( |
|
647 | - count($this->bindResult) !== 0 |
|
648 | - && $this->bindResult['dn'] === $this->configuration->ldapAgentName |
|
649 | - && \OC::$server->getHasher()->verify( |
|
650 | - $this->configPrefix . $this->configuration->ldapAgentPassword, |
|
651 | - $this->bindResult['hash'] |
|
652 | - ) |
|
653 | - ) { |
|
654 | - // don't attempt to bind again with the same data as before |
|
655 | - // bind might have been invoked via getConnectionResource(), |
|
656 | - // but we need results specifically for e.g. user login |
|
657 | - return $this->bindResult['result']; |
|
658 | - } |
|
659 | - |
|
660 | - $ldapLogin = @$this->ldap->bind($cr, |
|
661 | - $this->configuration->ldapAgentName, |
|
662 | - $this->configuration->ldapAgentPassword); |
|
663 | - |
|
664 | - $this->bindResult = [ |
|
665 | - 'dn' => $this->configuration->ldapAgentName, |
|
666 | - 'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword), |
|
667 | - 'result' => $ldapLogin, |
|
668 | - ]; |
|
669 | - |
|
670 | - if(!$ldapLogin) { |
|
671 | - $errno = $this->ldap->errno($cr); |
|
672 | - |
|
673 | - \OCP\Util::writeLog('user_ldap', |
|
674 | - 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), |
|
675 | - ILogger::WARN); |
|
676 | - |
|
677 | - // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS |
|
678 | - // or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS |
|
679 | - if($errno !== 0 && $errno !== 49 && $errno !== 50) { |
|
680 | - $this->ldapConnectionRes = null; |
|
681 | - } |
|
682 | - |
|
683 | - return false; |
|
684 | - } |
|
685 | - return true; |
|
686 | - } |
|
71 | + private $ldapConnectionRes = null; |
|
72 | + private $configPrefix; |
|
73 | + private $configID; |
|
74 | + private $configured = false; |
|
75 | + //whether connection should be kept on __destruct |
|
76 | + private $dontDestruct = false; |
|
77 | + |
|
78 | + /** |
|
79 | + * @var bool runtime flag that indicates whether supported primary groups are available |
|
80 | + */ |
|
81 | + public $hasPrimaryGroups = true; |
|
82 | + |
|
83 | + /** |
|
84 | + * @var bool runtime flag that indicates whether supported POSIX gidNumber are available |
|
85 | + */ |
|
86 | + public $hasGidNumber = true; |
|
87 | + |
|
88 | + //cache handler |
|
89 | + protected $cache; |
|
90 | + |
|
91 | + /** @var Configuration settings handler **/ |
|
92 | + protected $configuration; |
|
93 | + |
|
94 | + protected $doNotValidate = false; |
|
95 | + |
|
96 | + protected $ignoreValidation = false; |
|
97 | + |
|
98 | + protected $bindResult = []; |
|
99 | + |
|
100 | + /** |
|
101 | + * Constructor |
|
102 | + * @param ILDAPWrapper $ldap |
|
103 | + * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) |
|
104 | + * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections |
|
105 | + */ |
|
106 | + public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { |
|
107 | + parent::__construct($ldap); |
|
108 | + $this->configPrefix = $configPrefix; |
|
109 | + $this->configID = $configID; |
|
110 | + $this->configuration = new Configuration($configPrefix, |
|
111 | + !is_null($configID)); |
|
112 | + $memcache = \OC::$server->getMemCacheFactory(); |
|
113 | + if($memcache->isAvailable()) { |
|
114 | + $this->cache = $memcache->createDistributed(); |
|
115 | + } |
|
116 | + $helper = new Helper(\OC::$server->getConfig()); |
|
117 | + $this->doNotValidate = !in_array($this->configPrefix, |
|
118 | + $helper->getServerConfigurationPrefixes()); |
|
119 | + } |
|
120 | + |
|
121 | + public function __destruct() { |
|
122 | + if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { |
|
123 | + @$this->ldap->unbind($this->ldapConnectionRes); |
|
124 | + $this->bindResult = []; |
|
125 | + } |
|
126 | + } |
|
127 | + |
|
128 | + /** |
|
129 | + * defines behaviour when the instance is cloned |
|
130 | + */ |
|
131 | + public function __clone() { |
|
132 | + $this->configuration = new Configuration($this->configPrefix, |
|
133 | + !is_null($this->configID)); |
|
134 | + if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { |
|
135 | + $this->bindResult = []; |
|
136 | + } |
|
137 | + $this->ldapConnectionRes = null; |
|
138 | + $this->dontDestruct = true; |
|
139 | + } |
|
140 | + |
|
141 | + /** |
|
142 | + * @param string $name |
|
143 | + * @return bool|mixed |
|
144 | + */ |
|
145 | + public function __get($name) { |
|
146 | + if(!$this->configured) { |
|
147 | + $this->readConfiguration(); |
|
148 | + } |
|
149 | + |
|
150 | + return $this->configuration->$name; |
|
151 | + } |
|
152 | + |
|
153 | + /** |
|
154 | + * @param string $name |
|
155 | + * @param mixed $value |
|
156 | + */ |
|
157 | + public function __set($name, $value) { |
|
158 | + $this->doNotValidate = false; |
|
159 | + $before = $this->configuration->$name; |
|
160 | + $this->configuration->$name = $value; |
|
161 | + $after = $this->configuration->$name; |
|
162 | + if($before !== $after) { |
|
163 | + if ($this->configID !== '' && $this->configID !== null) { |
|
164 | + $this->configuration->saveConfiguration(); |
|
165 | + } |
|
166 | + $this->validateConfiguration(); |
|
167 | + } |
|
168 | + } |
|
169 | + |
|
170 | + /** |
|
171 | + * @param string $rule |
|
172 | + * @return array |
|
173 | + * @throws \RuntimeException |
|
174 | + */ |
|
175 | + public function resolveRule($rule) { |
|
176 | + return $this->configuration->resolveRule($rule); |
|
177 | + } |
|
178 | + |
|
179 | + /** |
|
180 | + * sets whether the result of the configuration validation shall |
|
181 | + * be ignored when establishing the connection. Used by the Wizard |
|
182 | + * in early configuration state. |
|
183 | + * @param bool $state |
|
184 | + */ |
|
185 | + public function setIgnoreValidation($state) { |
|
186 | + $this->ignoreValidation = (bool)$state; |
|
187 | + } |
|
188 | + |
|
189 | + /** |
|
190 | + * initializes the LDAP backend |
|
191 | + * @param bool $force read the config settings no matter what |
|
192 | + */ |
|
193 | + public function init($force = false) { |
|
194 | + $this->readConfiguration($force); |
|
195 | + $this->establishConnection(); |
|
196 | + } |
|
197 | + |
|
198 | + /** |
|
199 | + * Returns the LDAP handler |
|
200 | + */ |
|
201 | + public function getConnectionResource() { |
|
202 | + if(!$this->ldapConnectionRes) { |
|
203 | + $this->init(); |
|
204 | + } else if(!$this->ldap->isResource($this->ldapConnectionRes)) { |
|
205 | + $this->ldapConnectionRes = null; |
|
206 | + $this->establishConnection(); |
|
207 | + } |
|
208 | + if(is_null($this->ldapConnectionRes)) { |
|
209 | + \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); |
|
210 | + throw new ServerNotAvailableException('Connection to LDAP server could not be established'); |
|
211 | + } |
|
212 | + return $this->ldapConnectionRes; |
|
213 | + } |
|
214 | + |
|
215 | + /** |
|
216 | + * resets the connection resource |
|
217 | + */ |
|
218 | + public function resetConnectionResource() { |
|
219 | + if(!is_null($this->ldapConnectionRes)) { |
|
220 | + @$this->ldap->unbind($this->ldapConnectionRes); |
|
221 | + $this->ldapConnectionRes = null; |
|
222 | + $this->bindResult = []; |
|
223 | + } |
|
224 | + } |
|
225 | + |
|
226 | + /** |
|
227 | + * @param string|null $key |
|
228 | + * @return string |
|
229 | + */ |
|
230 | + private function getCacheKey($key) { |
|
231 | + $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; |
|
232 | + if(is_null($key)) { |
|
233 | + return $prefix; |
|
234 | + } |
|
235 | + return $prefix.hash('sha256', $key); |
|
236 | + } |
|
237 | + |
|
238 | + /** |
|
239 | + * @param string $key |
|
240 | + * @return mixed|null |
|
241 | + */ |
|
242 | + public function getFromCache($key) { |
|
243 | + if(!$this->configured) { |
|
244 | + $this->readConfiguration(); |
|
245 | + } |
|
246 | + if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { |
|
247 | + return null; |
|
248 | + } |
|
249 | + $key = $this->getCacheKey($key); |
|
250 | + |
|
251 | + return json_decode(base64_decode($this->cache->get($key)), true); |
|
252 | + } |
|
253 | + |
|
254 | + /** |
|
255 | + * @param string $key |
|
256 | + * @param mixed $value |
|
257 | + * |
|
258 | + * @return string |
|
259 | + */ |
|
260 | + public function writeToCache($key, $value) { |
|
261 | + if(!$this->configured) { |
|
262 | + $this->readConfiguration(); |
|
263 | + } |
|
264 | + if(is_null($this->cache) |
|
265 | + || !$this->configuration->ldapCacheTTL |
|
266 | + || !$this->configuration->ldapConfigurationActive) { |
|
267 | + return null; |
|
268 | + } |
|
269 | + $key = $this->getCacheKey($key); |
|
270 | + $value = base64_encode(json_encode($value)); |
|
271 | + $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); |
|
272 | + } |
|
273 | + |
|
274 | + public function clearCache() { |
|
275 | + if(!is_null($this->cache)) { |
|
276 | + $this->cache->clear($this->getCacheKey(null)); |
|
277 | + } |
|
278 | + } |
|
279 | + |
|
280 | + /** |
|
281 | + * Caches the general LDAP configuration. |
|
282 | + * @param bool $force optional. true, if the re-read should be forced. defaults |
|
283 | + * to false. |
|
284 | + * @return null |
|
285 | + */ |
|
286 | + private function readConfiguration($force = false) { |
|
287 | + if((!$this->configured || $force) && !is_null($this->configID)) { |
|
288 | + $this->configuration->readConfiguration(); |
|
289 | + $this->configured = $this->validateConfiguration(); |
|
290 | + } |
|
291 | + } |
|
292 | + |
|
293 | + /** |
|
294 | + * set LDAP configuration with values delivered by an array, not read from configuration |
|
295 | + * @param array $config array that holds the config parameters in an associated array |
|
296 | + * @param array &$setParameters optional; array where the set fields will be given to |
|
297 | + * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters |
|
298 | + */ |
|
299 | + public function setConfiguration($config, &$setParameters = null) { |
|
300 | + if(is_null($setParameters)) { |
|
301 | + $setParameters = []; |
|
302 | + } |
|
303 | + $this->doNotValidate = false; |
|
304 | + $this->configuration->setConfiguration($config, $setParameters); |
|
305 | + if(count($setParameters) > 0) { |
|
306 | + $this->configured = $this->validateConfiguration(); |
|
307 | + } |
|
308 | + |
|
309 | + |
|
310 | + return $this->configured; |
|
311 | + } |
|
312 | + |
|
313 | + /** |
|
314 | + * saves the current Configuration in the database and empties the |
|
315 | + * cache |
|
316 | + * @return null |
|
317 | + */ |
|
318 | + public function saveConfiguration() { |
|
319 | + $this->configuration->saveConfiguration(); |
|
320 | + $this->clearCache(); |
|
321 | + } |
|
322 | + |
|
323 | + /** |
|
324 | + * get the current LDAP configuration |
|
325 | + * @return array |
|
326 | + */ |
|
327 | + public function getConfiguration() { |
|
328 | + $this->readConfiguration(); |
|
329 | + $config = $this->configuration->getConfiguration(); |
|
330 | + $cta = $this->configuration->getConfigTranslationArray(); |
|
331 | + $result = []; |
|
332 | + foreach($cta as $dbkey => $configkey) { |
|
333 | + switch($configkey) { |
|
334 | + case 'homeFolderNamingRule': |
|
335 | + if(strpos($config[$configkey], 'attr:') === 0) { |
|
336 | + $result[$dbkey] = substr($config[$configkey], 5); |
|
337 | + } else { |
|
338 | + $result[$dbkey] = ''; |
|
339 | + } |
|
340 | + break; |
|
341 | + case 'ldapBase': |
|
342 | + case 'ldapBaseUsers': |
|
343 | + case 'ldapBaseGroups': |
|
344 | + case 'ldapAttributesForUserSearch': |
|
345 | + case 'ldapAttributesForGroupSearch': |
|
346 | + if(is_array($config[$configkey])) { |
|
347 | + $result[$dbkey] = implode("\n", $config[$configkey]); |
|
348 | + break; |
|
349 | + } //else follows default |
|
350 | + default: |
|
351 | + $result[$dbkey] = $config[$configkey]; |
|
352 | + } |
|
353 | + } |
|
354 | + return $result; |
|
355 | + } |
|
356 | + |
|
357 | + private function doSoftValidation() { |
|
358 | + //if User or Group Base are not set, take over Base DN setting |
|
359 | + foreach(['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) { |
|
360 | + $val = $this->configuration->$keyBase; |
|
361 | + if(empty($val)) { |
|
362 | + $this->configuration->$keyBase = $this->configuration->ldapBase; |
|
363 | + } |
|
364 | + } |
|
365 | + |
|
366 | + foreach(['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute', |
|
367 | + 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] |
|
368 | + as $expertSetting => $effectiveSetting) { |
|
369 | + $uuidOverride = $this->configuration->$expertSetting; |
|
370 | + if(!empty($uuidOverride)) { |
|
371 | + $this->configuration->$effectiveSetting = $uuidOverride; |
|
372 | + } else { |
|
373 | + $uuidAttributes = Access::UUID_ATTRIBUTES; |
|
374 | + array_unshift($uuidAttributes, 'auto'); |
|
375 | + if(!in_array($this->configuration->$effectiveSetting, |
|
376 | + $uuidAttributes) |
|
377 | + && (!is_null($this->configID))) { |
|
378 | + $this->configuration->$effectiveSetting = 'auto'; |
|
379 | + $this->configuration->saveConfiguration(); |
|
380 | + \OCP\Util::writeLog('user_ldap', |
|
381 | + 'Illegal value for the '. |
|
382 | + $effectiveSetting.', '.'reset to '. |
|
383 | + 'autodetect.', ILogger::INFO); |
|
384 | + } |
|
385 | + |
|
386 | + } |
|
387 | + } |
|
388 | + |
|
389 | + $backupPort = (int)$this->configuration->ldapBackupPort; |
|
390 | + if ($backupPort <= 0) { |
|
391 | + $this->configuration->backupPort = $this->configuration->ldapPort; |
|
392 | + } |
|
393 | + |
|
394 | + //make sure empty search attributes are saved as simple, empty array |
|
395 | + $saKeys = ['ldapAttributesForUserSearch', |
|
396 | + 'ldapAttributesForGroupSearch']; |
|
397 | + foreach($saKeys as $key) { |
|
398 | + $val = $this->configuration->$key; |
|
399 | + if(is_array($val) && count($val) === 1 && empty($val[0])) { |
|
400 | + $this->configuration->$key = []; |
|
401 | + } |
|
402 | + } |
|
403 | + |
|
404 | + if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) |
|
405 | + && $this->configuration->ldapTLS) { |
|
406 | + $this->configuration->ldapTLS = false; |
|
407 | + \OCP\Util::writeLog( |
|
408 | + 'user_ldap', |
|
409 | + 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.', |
|
410 | + ILogger::INFO |
|
411 | + ); |
|
412 | + } |
|
413 | + } |
|
414 | + |
|
415 | + /** |
|
416 | + * @return bool |
|
417 | + */ |
|
418 | + private function doCriticalValidation() { |
|
419 | + $configurationOK = true; |
|
420 | + $errorStr = 'Configuration Error (prefix '. |
|
421 | + (string)$this->configPrefix .'): '; |
|
422 | + |
|
423 | + //options that shall not be empty |
|
424 | + $options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName', |
|
425 | + 'ldapGroupDisplayName', 'ldapLoginFilter']; |
|
426 | + foreach($options as $key) { |
|
427 | + $val = $this->configuration->$key; |
|
428 | + if(empty($val)) { |
|
429 | + switch($key) { |
|
430 | + case 'ldapHost': |
|
431 | + $subj = 'LDAP Host'; |
|
432 | + break; |
|
433 | + case 'ldapPort': |
|
434 | + $subj = 'LDAP Port'; |
|
435 | + break; |
|
436 | + case 'ldapUserDisplayName': |
|
437 | + $subj = 'LDAP User Display Name'; |
|
438 | + break; |
|
439 | + case 'ldapGroupDisplayName': |
|
440 | + $subj = 'LDAP Group Display Name'; |
|
441 | + break; |
|
442 | + case 'ldapLoginFilter': |
|
443 | + $subj = 'LDAP Login Filter'; |
|
444 | + break; |
|
445 | + default: |
|
446 | + $subj = $key; |
|
447 | + break; |
|
448 | + } |
|
449 | + $configurationOK = false; |
|
450 | + \OCP\Util::writeLog( |
|
451 | + 'user_ldap', |
|
452 | + $errorStr.'No '.$subj.' given!', |
|
453 | + ILogger::WARN |
|
454 | + ); |
|
455 | + } |
|
456 | + } |
|
457 | + |
|
458 | + //combinations |
|
459 | + $agent = $this->configuration->ldapAgentName; |
|
460 | + $pwd = $this->configuration->ldapAgentPassword; |
|
461 | + if ( |
|
462 | + ($agent === '' && $pwd !== '') |
|
463 | + || ($agent !== '' && $pwd === '') |
|
464 | + ) { |
|
465 | + \OCP\Util::writeLog( |
|
466 | + 'user_ldap', |
|
467 | + $errorStr.'either no password is given for the user ' . |
|
468 | + 'agent or a password is given, but not an LDAP agent.', |
|
469 | + ILogger::WARN); |
|
470 | + $configurationOK = false; |
|
471 | + } |
|
472 | + |
|
473 | + $base = $this->configuration->ldapBase; |
|
474 | + $baseUsers = $this->configuration->ldapBaseUsers; |
|
475 | + $baseGroups = $this->configuration->ldapBaseGroups; |
|
476 | + |
|
477 | + if(empty($base) && empty($baseUsers) && empty($baseGroups)) { |
|
478 | + \OCP\Util::writeLog( |
|
479 | + 'user_ldap', |
|
480 | + $errorStr.'Not a single Base DN given.', |
|
481 | + ILogger::WARN |
|
482 | + ); |
|
483 | + $configurationOK = false; |
|
484 | + } |
|
485 | + |
|
486 | + if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
487 | + === false) { |
|
488 | + \OCP\Util::writeLog( |
|
489 | + 'user_ldap', |
|
490 | + $errorStr.'login filter does not contain %uid place holder.', |
|
491 | + ILogger::WARN |
|
492 | + ); |
|
493 | + $configurationOK = false; |
|
494 | + } |
|
495 | + |
|
496 | + return $configurationOK; |
|
497 | + } |
|
498 | + |
|
499 | + /** |
|
500 | + * Validates the user specified configuration |
|
501 | + * @return bool true if configuration seems OK, false otherwise |
|
502 | + */ |
|
503 | + private function validateConfiguration() { |
|
504 | + |
|
505 | + if($this->doNotValidate) { |
|
506 | + //don't do a validation if it is a new configuration with pure |
|
507 | + //default values. Will be allowed on changes via __set or |
|
508 | + //setConfiguration |
|
509 | + return false; |
|
510 | + } |
|
511 | + |
|
512 | + // first step: "soft" checks: settings that are not really |
|
513 | + // necessary, but advisable. If left empty, give an info message |
|
514 | + $this->doSoftValidation(); |
|
515 | + |
|
516 | + //second step: critical checks. If left empty or filled wrong, mark as |
|
517 | + //not configured and give a warning. |
|
518 | + return $this->doCriticalValidation(); |
|
519 | + } |
|
520 | + |
|
521 | + |
|
522 | + /** |
|
523 | + * Connects and Binds to LDAP |
|
524 | + * |
|
525 | + * @throws ServerNotAvailableException |
|
526 | + */ |
|
527 | + private function establishConnection() { |
|
528 | + if(!$this->configuration->ldapConfigurationActive) { |
|
529 | + return null; |
|
530 | + } |
|
531 | + static $phpLDAPinstalled = true; |
|
532 | + if(!$phpLDAPinstalled) { |
|
533 | + return false; |
|
534 | + } |
|
535 | + if(!$this->ignoreValidation && !$this->configured) { |
|
536 | + \OCP\Util::writeLog( |
|
537 | + 'user_ldap', |
|
538 | + 'Configuration is invalid, cannot connect', |
|
539 | + ILogger::WARN |
|
540 | + ); |
|
541 | + return false; |
|
542 | + } |
|
543 | + if(!$this->ldapConnectionRes) { |
|
544 | + if(!$this->ldap->areLDAPFunctionsAvailable()) { |
|
545 | + $phpLDAPinstalled = false; |
|
546 | + \OCP\Util::writeLog( |
|
547 | + 'user_ldap', |
|
548 | + 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.', |
|
549 | + ILogger::ERROR |
|
550 | + ); |
|
551 | + |
|
552 | + return false; |
|
553 | + } |
|
554 | + if($this->configuration->turnOffCertCheck) { |
|
555 | + if(putenv('LDAPTLS_REQCERT=never')) { |
|
556 | + \OCP\Util::writeLog('user_ldap', |
|
557 | + 'Turned off SSL certificate validation successfully.', |
|
558 | + ILogger::DEBUG); |
|
559 | + } else { |
|
560 | + \OCP\Util::writeLog( |
|
561 | + 'user_ldap', |
|
562 | + 'Could not turn off SSL certificate validation.', |
|
563 | + ILogger::WARN |
|
564 | + ); |
|
565 | + } |
|
566 | + } |
|
567 | + |
|
568 | + $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer |
|
569 | + || $this->getFromCache('overrideMainServer')); |
|
570 | + $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); |
|
571 | + $bindStatus = false; |
|
572 | + try { |
|
573 | + if (!$isOverrideMainServer) { |
|
574 | + $this->doConnect($this->configuration->ldapHost, |
|
575 | + $this->configuration->ldapPort); |
|
576 | + return $this->bind(); |
|
577 | + } |
|
578 | + } catch (ServerNotAvailableException $e) { |
|
579 | + if(!$isBackupHost) { |
|
580 | + throw $e; |
|
581 | + } |
|
582 | + } |
|
583 | + |
|
584 | + //if LDAP server is not reachable, try the Backup (Replica!) Server |
|
585 | + if($isBackupHost || $isOverrideMainServer) { |
|
586 | + $this->doConnect($this->configuration->ldapBackupHost, |
|
587 | + $this->configuration->ldapBackupPort); |
|
588 | + $this->bindResult = []; |
|
589 | + $bindStatus = $this->bind(); |
|
590 | + $error = $this->ldap->isResource($this->ldapConnectionRes) ? |
|
591 | + $this->ldap->errno($this->ldapConnectionRes) : -1; |
|
592 | + if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { |
|
593 | + //when bind to backup server succeeded and failed to main server, |
|
594 | + //skip contacting him until next cache refresh |
|
595 | + $this->writeToCache('overrideMainServer', true); |
|
596 | + } |
|
597 | + } |
|
598 | + |
|
599 | + return $bindStatus; |
|
600 | + } |
|
601 | + return null; |
|
602 | + } |
|
603 | + |
|
604 | + /** |
|
605 | + * @param string $host |
|
606 | + * @param string $port |
|
607 | + * @return bool |
|
608 | + * @throws \OC\ServerNotAvailableException |
|
609 | + */ |
|
610 | + private function doConnect($host, $port) { |
|
611 | + if ($host === '') { |
|
612 | + return false; |
|
613 | + } |
|
614 | + |
|
615 | + $this->ldapConnectionRes = $this->ldap->connect($host, $port); |
|
616 | + |
|
617 | + if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { |
|
618 | + throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); |
|
619 | + } |
|
620 | + |
|
621 | + if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { |
|
622 | + throw new ServerNotAvailableException('Could not disable LDAP referrals.'); |
|
623 | + } |
|
624 | + |
|
625 | + if($this->configuration->ldapTLS) { |
|
626 | + if(!$this->ldap->startTls($this->ldapConnectionRes)) { |
|
627 | + throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); |
|
628 | + } |
|
629 | + } |
|
630 | + |
|
631 | + return true; |
|
632 | + } |
|
633 | + |
|
634 | + /** |
|
635 | + * Binds to LDAP |
|
636 | + */ |
|
637 | + public function bind() { |
|
638 | + if(!$this->configuration->ldapConfigurationActive) { |
|
639 | + return false; |
|
640 | + } |
|
641 | + $cr = $this->ldapConnectionRes; |
|
642 | + if(!$this->ldap->isResource($cr)) { |
|
643 | + $cr = $this->getConnectionResource(); |
|
644 | + } |
|
645 | + |
|
646 | + if( |
|
647 | + count($this->bindResult) !== 0 |
|
648 | + && $this->bindResult['dn'] === $this->configuration->ldapAgentName |
|
649 | + && \OC::$server->getHasher()->verify( |
|
650 | + $this->configPrefix . $this->configuration->ldapAgentPassword, |
|
651 | + $this->bindResult['hash'] |
|
652 | + ) |
|
653 | + ) { |
|
654 | + // don't attempt to bind again with the same data as before |
|
655 | + // bind might have been invoked via getConnectionResource(), |
|
656 | + // but we need results specifically for e.g. user login |
|
657 | + return $this->bindResult['result']; |
|
658 | + } |
|
659 | + |
|
660 | + $ldapLogin = @$this->ldap->bind($cr, |
|
661 | + $this->configuration->ldapAgentName, |
|
662 | + $this->configuration->ldapAgentPassword); |
|
663 | + |
|
664 | + $this->bindResult = [ |
|
665 | + 'dn' => $this->configuration->ldapAgentName, |
|
666 | + 'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword), |
|
667 | + 'result' => $ldapLogin, |
|
668 | + ]; |
|
669 | + |
|
670 | + if(!$ldapLogin) { |
|
671 | + $errno = $this->ldap->errno($cr); |
|
672 | + |
|
673 | + \OCP\Util::writeLog('user_ldap', |
|
674 | + 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), |
|
675 | + ILogger::WARN); |
|
676 | + |
|
677 | + // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS |
|
678 | + // or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS |
|
679 | + if($errno !== 0 && $errno !== 49 && $errno !== 50) { |
|
680 | + $this->ldapConnectionRes = null; |
|
681 | + } |
|
682 | + |
|
683 | + return false; |
|
684 | + } |
|
685 | + return true; |
|
686 | + } |
|
687 | 687 | |
688 | 688 | } |
@@ -42,1320 +42,1320 @@ |
||
42 | 42 | use OCP\ILogger; |
43 | 43 | |
44 | 44 | class Wizard extends LDAPUtility { |
45 | - /** @var \OCP\IL10N */ |
|
46 | - static protected $l; |
|
47 | - protected $access; |
|
48 | - protected $cr; |
|
49 | - protected $configuration; |
|
50 | - protected $result; |
|
51 | - protected $resultCache = []; |
|
52 | - |
|
53 | - const LRESULT_PROCESSED_OK = 2; |
|
54 | - const LRESULT_PROCESSED_INVALID = 3; |
|
55 | - const LRESULT_PROCESSED_SKIP = 4; |
|
56 | - |
|
57 | - const LFILTER_LOGIN = 2; |
|
58 | - const LFILTER_USER_LIST = 3; |
|
59 | - const LFILTER_GROUP_LIST = 4; |
|
60 | - |
|
61 | - const LFILTER_MODE_ASSISTED = 2; |
|
62 | - const LFILTER_MODE_RAW = 1; |
|
63 | - |
|
64 | - const LDAP_NW_TIMEOUT = 4; |
|
65 | - |
|
66 | - /** |
|
67 | - * Constructor |
|
68 | - * @param Configuration $configuration an instance of Configuration |
|
69 | - * @param ILDAPWrapper $ldap an instance of ILDAPWrapper |
|
70 | - * @param Access $access |
|
71 | - */ |
|
72 | - public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) { |
|
73 | - parent::__construct($ldap); |
|
74 | - $this->configuration = $configuration; |
|
75 | - if(is_null(Wizard::$l)) { |
|
76 | - Wizard::$l = \OC::$server->getL10N('user_ldap'); |
|
77 | - } |
|
78 | - $this->access = $access; |
|
79 | - $this->result = new WizardResult(); |
|
80 | - } |
|
81 | - |
|
82 | - public function __destruct() { |
|
83 | - if($this->result->hasChanges()) { |
|
84 | - $this->configuration->saveConfiguration(); |
|
85 | - } |
|
86 | - } |
|
87 | - |
|
88 | - /** |
|
89 | - * counts entries in the LDAP directory |
|
90 | - * |
|
91 | - * @param string $filter the LDAP search filter |
|
92 | - * @param string $type a string being either 'users' or 'groups'; |
|
93 | - * @return int |
|
94 | - * @throws \Exception |
|
95 | - */ |
|
96 | - public function countEntries(string $filter, string $type): int { |
|
97 | - $reqs = ['ldapHost', 'ldapPort', 'ldapBase']; |
|
98 | - if($type === 'users') { |
|
99 | - $reqs[] = 'ldapUserFilter'; |
|
100 | - } |
|
101 | - if(!$this->checkRequirements($reqs)) { |
|
102 | - throw new \Exception('Requirements not met', 400); |
|
103 | - } |
|
104 | - |
|
105 | - $attr = ['dn']; // default |
|
106 | - $limit = 1001; |
|
107 | - if($type === 'groups') { |
|
108 | - $result = $this->access->countGroups($filter, $attr, $limit); |
|
109 | - } else if($type === 'users') { |
|
110 | - $result = $this->access->countUsers($filter, $attr, $limit); |
|
111 | - } else if ($type === 'objects') { |
|
112 | - $result = $this->access->countObjects($limit); |
|
113 | - } else { |
|
114 | - throw new \Exception('Internal error: Invalid object type', 500); |
|
115 | - } |
|
116 | - |
|
117 | - return (int)$result; |
|
118 | - } |
|
119 | - |
|
120 | - /** |
|
121 | - * formats the return value of a count operation to the string to be |
|
122 | - * inserted. |
|
123 | - * |
|
124 | - * @param int $count |
|
125 | - * @return string |
|
126 | - */ |
|
127 | - private function formatCountResult(int $count): string { |
|
128 | - if($count > 1000) { |
|
129 | - return '> 1000'; |
|
130 | - } |
|
131 | - return (string)$count; |
|
132 | - } |
|
133 | - |
|
134 | - public function countGroups() { |
|
135 | - $filter = $this->configuration->ldapGroupFilter; |
|
136 | - |
|
137 | - if(empty($filter)) { |
|
138 | - $output = self::$l->n('%s group found', '%s groups found', 0, [0]); |
|
139 | - $this->result->addChange('ldap_group_count', $output); |
|
140 | - return $this->result; |
|
141 | - } |
|
142 | - |
|
143 | - try { |
|
144 | - $groupsTotal = $this->countEntries($filter, 'groups'); |
|
145 | - } catch (\Exception $e) { |
|
146 | - //400 can be ignored, 500 is forwarded |
|
147 | - if($e->getCode() === 500) { |
|
148 | - throw $e; |
|
149 | - } |
|
150 | - return false; |
|
151 | - } |
|
152 | - $output = self::$l->n( |
|
153 | - '%s group found', |
|
154 | - '%s groups found', |
|
155 | - $groupsTotal, |
|
156 | - [$this->formatCountResult($groupsTotal)] |
|
157 | - ); |
|
158 | - $this->result->addChange('ldap_group_count', $output); |
|
159 | - return $this->result; |
|
160 | - } |
|
161 | - |
|
162 | - /** |
|
163 | - * @return WizardResult |
|
164 | - * @throws \Exception |
|
165 | - */ |
|
166 | - public function countUsers() { |
|
167 | - $filter = $this->access->getFilterForUserCount(); |
|
168 | - |
|
169 | - $usersTotal = $this->countEntries($filter, 'users'); |
|
170 | - $output = self::$l->n( |
|
171 | - '%s user found', |
|
172 | - '%s users found', |
|
173 | - $usersTotal, |
|
174 | - [$this->formatCountResult($usersTotal)] |
|
175 | - ); |
|
176 | - $this->result->addChange('ldap_user_count', $output); |
|
177 | - return $this->result; |
|
178 | - } |
|
179 | - |
|
180 | - /** |
|
181 | - * counts any objects in the currently set base dn |
|
182 | - * |
|
183 | - * @return WizardResult |
|
184 | - * @throws \Exception |
|
185 | - */ |
|
186 | - public function countInBaseDN() { |
|
187 | - // we don't need to provide a filter in this case |
|
188 | - $total = $this->countEntries('', 'objects'); |
|
189 | - if($total === false) { |
|
190 | - throw new \Exception('invalid results received'); |
|
191 | - } |
|
192 | - $this->result->addChange('ldap_test_base', $total); |
|
193 | - return $this->result; |
|
194 | - } |
|
195 | - |
|
196 | - /** |
|
197 | - * counts users with a specified attribute |
|
198 | - * @param string $attr |
|
199 | - * @param bool $existsCheck |
|
200 | - * @return int|bool |
|
201 | - */ |
|
202 | - public function countUsersWithAttribute($attr, $existsCheck = false) { |
|
203 | - if(!$this->checkRequirements(['ldapHost', |
|
204 | - 'ldapPort', |
|
205 | - 'ldapBase', |
|
206 | - 'ldapUserFilter', |
|
207 | - ])) { |
|
208 | - return false; |
|
209 | - } |
|
210 | - |
|
211 | - $filter = $this->access->combineFilterWithAnd([ |
|
212 | - $this->configuration->ldapUserFilter, |
|
213 | - $attr . '=*' |
|
214 | - ]); |
|
215 | - |
|
216 | - $limit = ($existsCheck === false) ? null : 1; |
|
217 | - |
|
218 | - return $this->access->countUsers($filter, ['dn'], $limit); |
|
219 | - } |
|
220 | - |
|
221 | - /** |
|
222 | - * detects the display name attribute. If a setting is already present that |
|
223 | - * returns at least one hit, the detection will be canceled. |
|
224 | - * @return WizardResult|bool |
|
225 | - * @throws \Exception |
|
226 | - */ |
|
227 | - public function detectUserDisplayNameAttribute() { |
|
228 | - if(!$this->checkRequirements(['ldapHost', |
|
229 | - 'ldapPort', |
|
230 | - 'ldapBase', |
|
231 | - 'ldapUserFilter', |
|
232 | - ])) { |
|
233 | - return false; |
|
234 | - } |
|
235 | - |
|
236 | - $attr = $this->configuration->ldapUserDisplayName; |
|
237 | - if ($attr !== '' && $attr !== 'displayName') { |
|
238 | - // most likely not the default value with upper case N, |
|
239 | - // verify it still produces a result |
|
240 | - $count = (int)$this->countUsersWithAttribute($attr, true); |
|
241 | - if($count > 0) { |
|
242 | - //no change, but we sent it back to make sure the user interface |
|
243 | - //is still correct, even if the ajax call was cancelled meanwhile |
|
244 | - $this->result->addChange('ldap_display_name', $attr); |
|
245 | - return $this->result; |
|
246 | - } |
|
247 | - } |
|
248 | - |
|
249 | - // first attribute that has at least one result wins |
|
250 | - $displayNameAttrs = ['displayname', 'cn']; |
|
251 | - foreach ($displayNameAttrs as $attr) { |
|
252 | - $count = (int)$this->countUsersWithAttribute($attr, true); |
|
253 | - |
|
254 | - if($count > 0) { |
|
255 | - $this->applyFind('ldap_display_name', $attr); |
|
256 | - return $this->result; |
|
257 | - } |
|
258 | - } |
|
259 | - |
|
260 | - throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.')); |
|
261 | - } |
|
262 | - |
|
263 | - /** |
|
264 | - * detects the most often used email attribute for users applying to the |
|
265 | - * user list filter. If a setting is already present that returns at least |
|
266 | - * one hit, the detection will be canceled. |
|
267 | - * @return WizardResult|bool |
|
268 | - */ |
|
269 | - public function detectEmailAttribute() { |
|
270 | - if(!$this->checkRequirements(['ldapHost', |
|
271 | - 'ldapPort', |
|
272 | - 'ldapBase', |
|
273 | - 'ldapUserFilter', |
|
274 | - ])) { |
|
275 | - return false; |
|
276 | - } |
|
277 | - |
|
278 | - $attr = $this->configuration->ldapEmailAttribute; |
|
279 | - if ($attr !== '') { |
|
280 | - $count = (int)$this->countUsersWithAttribute($attr, true); |
|
281 | - if($count > 0) { |
|
282 | - return false; |
|
283 | - } |
|
284 | - $writeLog = true; |
|
285 | - } else { |
|
286 | - $writeLog = false; |
|
287 | - } |
|
288 | - |
|
289 | - $emailAttributes = ['mail', 'mailPrimaryAddress']; |
|
290 | - $winner = ''; |
|
291 | - $maxUsers = 0; |
|
292 | - foreach($emailAttributes as $attr) { |
|
293 | - $count = $this->countUsersWithAttribute($attr); |
|
294 | - if($count > $maxUsers) { |
|
295 | - $maxUsers = $count; |
|
296 | - $winner = $attr; |
|
297 | - } |
|
298 | - } |
|
299 | - |
|
300 | - if($winner !== '') { |
|
301 | - $this->applyFind('ldap_email_attr', $winner); |
|
302 | - if($writeLog) { |
|
303 | - \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' . |
|
304 | - 'automatically been reset, because the original value ' . |
|
305 | - 'did not return any results.', ILogger::INFO); |
|
306 | - } |
|
307 | - } |
|
308 | - |
|
309 | - return $this->result; |
|
310 | - } |
|
311 | - |
|
312 | - /** |
|
313 | - * @return WizardResult |
|
314 | - * @throws \Exception |
|
315 | - */ |
|
316 | - public function determineAttributes() { |
|
317 | - if(!$this->checkRequirements(['ldapHost', |
|
318 | - 'ldapPort', |
|
319 | - 'ldapBase', |
|
320 | - 'ldapUserFilter', |
|
321 | - ])) { |
|
322 | - return false; |
|
323 | - } |
|
324 | - |
|
325 | - $attributes = $this->getUserAttributes(); |
|
326 | - |
|
327 | - natcasesort($attributes); |
|
328 | - $attributes = array_values($attributes); |
|
329 | - |
|
330 | - $this->result->addOptions('ldap_loginfilter_attributes', $attributes); |
|
331 | - |
|
332 | - $selected = $this->configuration->ldapLoginFilterAttributes; |
|
333 | - if(is_array($selected) && !empty($selected)) { |
|
334 | - $this->result->addChange('ldap_loginfilter_attributes', $selected); |
|
335 | - } |
|
336 | - |
|
337 | - return $this->result; |
|
338 | - } |
|
339 | - |
|
340 | - /** |
|
341 | - * detects the available LDAP attributes |
|
342 | - * @return array|false The instance's WizardResult instance |
|
343 | - * @throws \Exception |
|
344 | - */ |
|
345 | - private function getUserAttributes() { |
|
346 | - if(!$this->checkRequirements(['ldapHost', |
|
347 | - 'ldapPort', |
|
348 | - 'ldapBase', |
|
349 | - 'ldapUserFilter', |
|
350 | - ])) { |
|
351 | - return false; |
|
352 | - } |
|
353 | - $cr = $this->getConnection(); |
|
354 | - if(!$cr) { |
|
355 | - throw new \Exception('Could not connect to LDAP'); |
|
356 | - } |
|
357 | - |
|
358 | - $base = $this->configuration->ldapBase[0]; |
|
359 | - $filter = $this->configuration->ldapUserFilter; |
|
360 | - $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1); |
|
361 | - if(!$this->ldap->isResource($rr)) { |
|
362 | - return false; |
|
363 | - } |
|
364 | - $er = $this->ldap->firstEntry($cr, $rr); |
|
365 | - $attributes = $this->ldap->getAttributes($cr, $er); |
|
366 | - $pureAttributes = []; |
|
367 | - for($i = 0; $i < $attributes['count']; $i++) { |
|
368 | - $pureAttributes[] = $attributes[$i]; |
|
369 | - } |
|
370 | - |
|
371 | - return $pureAttributes; |
|
372 | - } |
|
373 | - |
|
374 | - /** |
|
375 | - * detects the available LDAP groups |
|
376 | - * @return WizardResult|false the instance's WizardResult instance |
|
377 | - */ |
|
378 | - public function determineGroupsForGroups() { |
|
379 | - return $this->determineGroups('ldap_groupfilter_groups', |
|
380 | - 'ldapGroupFilterGroups', |
|
381 | - false); |
|
382 | - } |
|
383 | - |
|
384 | - /** |
|
385 | - * detects the available LDAP groups |
|
386 | - * @return WizardResult|false the instance's WizardResult instance |
|
387 | - */ |
|
388 | - public function determineGroupsForUsers() { |
|
389 | - return $this->determineGroups('ldap_userfilter_groups', |
|
390 | - 'ldapUserFilterGroups'); |
|
391 | - } |
|
392 | - |
|
393 | - /** |
|
394 | - * detects the available LDAP groups |
|
395 | - * @param string $dbKey |
|
396 | - * @param string $confKey |
|
397 | - * @param bool $testMemberOf |
|
398 | - * @return WizardResult|false the instance's WizardResult instance |
|
399 | - * @throws \Exception |
|
400 | - */ |
|
401 | - private function determineGroups($dbKey, $confKey, $testMemberOf = true) { |
|
402 | - if(!$this->checkRequirements(['ldapHost', |
|
403 | - 'ldapPort', |
|
404 | - 'ldapBase', |
|
405 | - ])) { |
|
406 | - return false; |
|
407 | - } |
|
408 | - $cr = $this->getConnection(); |
|
409 | - if(!$cr) { |
|
410 | - throw new \Exception('Could not connect to LDAP'); |
|
411 | - } |
|
412 | - |
|
413 | - $this->fetchGroups($dbKey, $confKey); |
|
414 | - |
|
415 | - if($testMemberOf) { |
|
416 | - $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf(); |
|
417 | - $this->result->markChange(); |
|
418 | - if(!$this->configuration->hasMemberOfFilterSupport) { |
|
419 | - throw new \Exception('memberOf is not supported by the server'); |
|
420 | - } |
|
421 | - } |
|
422 | - |
|
423 | - return $this->result; |
|
424 | - } |
|
425 | - |
|
426 | - /** |
|
427 | - * fetches all groups from LDAP and adds them to the result object |
|
428 | - * |
|
429 | - * @param string $dbKey |
|
430 | - * @param string $confKey |
|
431 | - * @return array $groupEntries |
|
432 | - * @throws \Exception |
|
433 | - */ |
|
434 | - public function fetchGroups($dbKey, $confKey) { |
|
435 | - $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames']; |
|
436 | - |
|
437 | - $filterParts = []; |
|
438 | - foreach($obclasses as $obclass) { |
|
439 | - $filterParts[] = 'objectclass='.$obclass; |
|
440 | - } |
|
441 | - //we filter for everything |
|
442 | - //- that looks like a group and |
|
443 | - //- has the group display name set |
|
444 | - $filter = $this->access->combineFilterWithOr($filterParts); |
|
445 | - $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']); |
|
446 | - |
|
447 | - $groupNames = []; |
|
448 | - $groupEntries = []; |
|
449 | - $limit = 400; |
|
450 | - $offset = 0; |
|
451 | - do { |
|
452 | - // we need to request dn additionally here, otherwise memberOf |
|
453 | - // detection will fail later |
|
454 | - $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset); |
|
455 | - foreach($result as $item) { |
|
456 | - if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { |
|
457 | - // just in case - no issue known |
|
458 | - continue; |
|
459 | - } |
|
460 | - $groupNames[] = $item['cn'][0]; |
|
461 | - $groupEntries[] = $item; |
|
462 | - } |
|
463 | - $offset += $limit; |
|
464 | - } while ($this->access->hasMoreResults()); |
|
465 | - |
|
466 | - if(count($groupNames) > 0) { |
|
467 | - natsort($groupNames); |
|
468 | - $this->result->addOptions($dbKey, array_values($groupNames)); |
|
469 | - } else { |
|
470 | - throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
471 | - } |
|
472 | - |
|
473 | - $setFeatures = $this->configuration->$confKey; |
|
474 | - if(is_array($setFeatures) && !empty($setFeatures)) { |
|
475 | - //something is already configured? pre-select it. |
|
476 | - $this->result->addChange($dbKey, $setFeatures); |
|
477 | - } |
|
478 | - return $groupEntries; |
|
479 | - } |
|
480 | - |
|
481 | - public function determineGroupMemberAssoc() { |
|
482 | - if(!$this->checkRequirements(['ldapHost', |
|
483 | - 'ldapPort', |
|
484 | - 'ldapGroupFilter', |
|
485 | - ])) { |
|
486 | - return false; |
|
487 | - } |
|
488 | - $attribute = $this->detectGroupMemberAssoc(); |
|
489 | - if($attribute === false) { |
|
490 | - return false; |
|
491 | - } |
|
492 | - $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]); |
|
493 | - $this->result->addChange('ldap_group_member_assoc_attribute', $attribute); |
|
494 | - |
|
495 | - return $this->result; |
|
496 | - } |
|
497 | - |
|
498 | - /** |
|
499 | - * Detects the available object classes |
|
500 | - * @return WizardResult|false the instance's WizardResult instance |
|
501 | - * @throws \Exception |
|
502 | - */ |
|
503 | - public function determineGroupObjectClasses() { |
|
504 | - if(!$this->checkRequirements(['ldapHost', |
|
505 | - 'ldapPort', |
|
506 | - 'ldapBase', |
|
507 | - ])) { |
|
508 | - return false; |
|
509 | - } |
|
510 | - $cr = $this->getConnection(); |
|
511 | - if(!$cr) { |
|
512 | - throw new \Exception('Could not connect to LDAP'); |
|
513 | - } |
|
514 | - |
|
515 | - $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*']; |
|
516 | - $this->determineFeature($obclasses, |
|
517 | - 'objectclass', |
|
518 | - 'ldap_groupfilter_objectclass', |
|
519 | - 'ldapGroupFilterObjectclass', |
|
520 | - false); |
|
521 | - |
|
522 | - return $this->result; |
|
523 | - } |
|
524 | - |
|
525 | - /** |
|
526 | - * detects the available object classes |
|
527 | - * @return WizardResult |
|
528 | - * @throws \Exception |
|
529 | - */ |
|
530 | - public function determineUserObjectClasses() { |
|
531 | - if(!$this->checkRequirements(['ldapHost', |
|
532 | - 'ldapPort', |
|
533 | - 'ldapBase', |
|
534 | - ])) { |
|
535 | - return false; |
|
536 | - } |
|
537 | - $cr = $this->getConnection(); |
|
538 | - if(!$cr) { |
|
539 | - throw new \Exception('Could not connect to LDAP'); |
|
540 | - } |
|
541 | - |
|
542 | - $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson', |
|
543 | - 'user', 'posixAccount', '*']; |
|
544 | - $filter = $this->configuration->ldapUserFilter; |
|
545 | - //if filter is empty, it is probably the first time the wizard is called |
|
546 | - //then, apply suggestions. |
|
547 | - $this->determineFeature($obclasses, |
|
548 | - 'objectclass', |
|
549 | - 'ldap_userfilter_objectclass', |
|
550 | - 'ldapUserFilterObjectclass', |
|
551 | - empty($filter)); |
|
552 | - |
|
553 | - return $this->result; |
|
554 | - } |
|
555 | - |
|
556 | - /** |
|
557 | - * @return WizardResult|false |
|
558 | - * @throws \Exception |
|
559 | - */ |
|
560 | - public function getGroupFilter() { |
|
561 | - if(!$this->checkRequirements(['ldapHost', |
|
562 | - 'ldapPort', |
|
563 | - 'ldapBase', |
|
564 | - ])) { |
|
565 | - return false; |
|
566 | - } |
|
567 | - //make sure the use display name is set |
|
568 | - $displayName = $this->configuration->ldapGroupDisplayName; |
|
569 | - if ($displayName === '') { |
|
570 | - $d = $this->configuration->getDefaults(); |
|
571 | - $this->applyFind('ldap_group_display_name', |
|
572 | - $d['ldap_group_display_name']); |
|
573 | - } |
|
574 | - $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST); |
|
575 | - |
|
576 | - $this->applyFind('ldap_group_filter', $filter); |
|
577 | - return $this->result; |
|
578 | - } |
|
579 | - |
|
580 | - /** |
|
581 | - * @return WizardResult|false |
|
582 | - * @throws \Exception |
|
583 | - */ |
|
584 | - public function getUserListFilter() { |
|
585 | - if(!$this->checkRequirements(['ldapHost', |
|
586 | - 'ldapPort', |
|
587 | - 'ldapBase', |
|
588 | - ])) { |
|
589 | - return false; |
|
590 | - } |
|
591 | - //make sure the use display name is set |
|
592 | - $displayName = $this->configuration->ldapUserDisplayName; |
|
593 | - if ($displayName === '') { |
|
594 | - $d = $this->configuration->getDefaults(); |
|
595 | - $this->applyFind('ldap_display_name', $d['ldap_display_name']); |
|
596 | - } |
|
597 | - $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST); |
|
598 | - if(!$filter) { |
|
599 | - throw new \Exception('Cannot create filter'); |
|
600 | - } |
|
601 | - |
|
602 | - $this->applyFind('ldap_userlist_filter', $filter); |
|
603 | - return $this->result; |
|
604 | - } |
|
605 | - |
|
606 | - /** |
|
607 | - * @return bool|WizardResult |
|
608 | - * @throws \Exception |
|
609 | - */ |
|
610 | - public function getUserLoginFilter() { |
|
611 | - if(!$this->checkRequirements(['ldapHost', |
|
612 | - 'ldapPort', |
|
613 | - 'ldapBase', |
|
614 | - 'ldapUserFilter', |
|
615 | - ])) { |
|
616 | - return false; |
|
617 | - } |
|
618 | - |
|
619 | - $filter = $this->composeLdapFilter(self::LFILTER_LOGIN); |
|
620 | - if(!$filter) { |
|
621 | - throw new \Exception('Cannot create filter'); |
|
622 | - } |
|
623 | - |
|
624 | - $this->applyFind('ldap_login_filter', $filter); |
|
625 | - return $this->result; |
|
626 | - } |
|
627 | - |
|
628 | - /** |
|
629 | - * @return bool|WizardResult |
|
630 | - * @param string $loginName |
|
631 | - * @throws \Exception |
|
632 | - */ |
|
633 | - public function testLoginName($loginName) { |
|
634 | - if(!$this->checkRequirements(['ldapHost', |
|
635 | - 'ldapPort', |
|
636 | - 'ldapBase', |
|
637 | - 'ldapLoginFilter', |
|
638 | - ])) { |
|
639 | - return false; |
|
640 | - } |
|
641 | - |
|
642 | - $cr = $this->access->connection->getConnectionResource(); |
|
643 | - if(!$this->ldap->isResource($cr)) { |
|
644 | - throw new \Exception('connection error'); |
|
645 | - } |
|
646 | - |
|
647 | - if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
648 | - === false) { |
|
649 | - throw new \Exception('missing placeholder'); |
|
650 | - } |
|
651 | - |
|
652 | - $users = $this->access->countUsersByLoginName($loginName); |
|
653 | - if($this->ldap->errno($cr) !== 0) { |
|
654 | - throw new \Exception($this->ldap->error($cr)); |
|
655 | - } |
|
656 | - $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter); |
|
657 | - $this->result->addChange('ldap_test_loginname', $users); |
|
658 | - $this->result->addChange('ldap_test_effective_filter', $filter); |
|
659 | - return $this->result; |
|
660 | - } |
|
661 | - |
|
662 | - /** |
|
663 | - * Tries to determine the port, requires given Host, User DN and Password |
|
664 | - * @return WizardResult|false WizardResult on success, false otherwise |
|
665 | - * @throws \Exception |
|
666 | - */ |
|
667 | - public function guessPortAndTLS() { |
|
668 | - if(!$this->checkRequirements(['ldapHost', |
|
669 | - ])) { |
|
670 | - return false; |
|
671 | - } |
|
672 | - $this->checkHost(); |
|
673 | - $portSettings = $this->getPortSettingsToTry(); |
|
674 | - |
|
675 | - if(!is_array($portSettings)) { |
|
676 | - throw new \Exception(print_r($portSettings, true)); |
|
677 | - } |
|
678 | - |
|
679 | - //proceed from the best configuration and return on first success |
|
680 | - foreach($portSettings as $setting) { |
|
681 | - $p = $setting['port']; |
|
682 | - $t = $setting['tls']; |
|
683 | - \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG); |
|
684 | - //connectAndBind may throw Exception, it needs to be catched by the |
|
685 | - //callee of this method |
|
686 | - |
|
687 | - try { |
|
688 | - $settingsFound = $this->connectAndBind($p, $t); |
|
689 | - } catch (\Exception $e) { |
|
690 | - // any reply other than -1 (= cannot connect) is already okay, |
|
691 | - // because then we found the server |
|
692 | - // unavailable startTLS returns -11 |
|
693 | - if($e->getCode() > 0) { |
|
694 | - $settingsFound = true; |
|
695 | - } else { |
|
696 | - throw $e; |
|
697 | - } |
|
698 | - } |
|
699 | - |
|
700 | - if ($settingsFound === true) { |
|
701 | - $config = [ |
|
702 | - 'ldapPort' => $p, |
|
703 | - 'ldapTLS' => (int)$t |
|
704 | - ]; |
|
705 | - $this->configuration->setConfiguration($config); |
|
706 | - \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG); |
|
707 | - $this->result->addChange('ldap_port', $p); |
|
708 | - return $this->result; |
|
709 | - } |
|
710 | - } |
|
711 | - |
|
712 | - //custom port, undetected (we do not brute force) |
|
713 | - return false; |
|
714 | - } |
|
715 | - |
|
716 | - /** |
|
717 | - * tries to determine a base dn from User DN or LDAP Host |
|
718 | - * @return WizardResult|false WizardResult on success, false otherwise |
|
719 | - */ |
|
720 | - public function guessBaseDN() { |
|
721 | - if(!$this->checkRequirements(['ldapHost', |
|
722 | - 'ldapPort', |
|
723 | - ])) { |
|
724 | - return false; |
|
725 | - } |
|
726 | - |
|
727 | - //check whether a DN is given in the agent name (99.9% of all cases) |
|
728 | - $base = null; |
|
729 | - $i = stripos($this->configuration->ldapAgentName, 'dc='); |
|
730 | - if($i !== false) { |
|
731 | - $base = substr($this->configuration->ldapAgentName, $i); |
|
732 | - if($this->testBaseDN($base)) { |
|
733 | - $this->applyFind('ldap_base', $base); |
|
734 | - return $this->result; |
|
735 | - } |
|
736 | - } |
|
737 | - |
|
738 | - //this did not help :( |
|
739 | - //Let's see whether we can parse the Host URL and convert the domain to |
|
740 | - //a base DN |
|
741 | - $helper = new Helper(\OC::$server->getConfig()); |
|
742 | - $domain = $helper->getDomainFromURL($this->configuration->ldapHost); |
|
743 | - if(!$domain) { |
|
744 | - return false; |
|
745 | - } |
|
746 | - |
|
747 | - $dparts = explode('.', $domain); |
|
748 | - while(count($dparts) > 0) { |
|
749 | - $base2 = 'dc=' . implode(',dc=', $dparts); |
|
750 | - if ($base !== $base2 && $this->testBaseDN($base2)) { |
|
751 | - $this->applyFind('ldap_base', $base2); |
|
752 | - return $this->result; |
|
753 | - } |
|
754 | - array_shift($dparts); |
|
755 | - } |
|
756 | - |
|
757 | - return false; |
|
758 | - } |
|
759 | - |
|
760 | - /** |
|
761 | - * sets the found value for the configuration key in the WizardResult |
|
762 | - * as well as in the Configuration instance |
|
763 | - * @param string $key the configuration key |
|
764 | - * @param string $value the (detected) value |
|
765 | - * |
|
766 | - */ |
|
767 | - private function applyFind($key, $value) { |
|
768 | - $this->result->addChange($key, $value); |
|
769 | - $this->configuration->setConfiguration([$key => $value]); |
|
770 | - } |
|
771 | - |
|
772 | - /** |
|
773 | - * Checks, whether a port was entered in the Host configuration |
|
774 | - * field. In this case the port will be stripped off, but also stored as |
|
775 | - * setting. |
|
776 | - */ |
|
777 | - private function checkHost() { |
|
778 | - $host = $this->configuration->ldapHost; |
|
779 | - $hostInfo = parse_url($host); |
|
780 | - |
|
781 | - //removes Port from Host |
|
782 | - if(is_array($hostInfo) && isset($hostInfo['port'])) { |
|
783 | - $port = $hostInfo['port']; |
|
784 | - $host = str_replace(':'.$port, '', $host); |
|
785 | - $this->applyFind('ldap_host', $host); |
|
786 | - $this->applyFind('ldap_port', $port); |
|
787 | - } |
|
788 | - } |
|
789 | - |
|
790 | - /** |
|
791 | - * tries to detect the group member association attribute which is |
|
792 | - * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber' |
|
793 | - * @return string|false, string with the attribute name, false on error |
|
794 | - * @throws \Exception |
|
795 | - */ |
|
796 | - private function detectGroupMemberAssoc() { |
|
797 | - $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber']; |
|
798 | - $filter = $this->configuration->ldapGroupFilter; |
|
799 | - if(empty($filter)) { |
|
800 | - return false; |
|
801 | - } |
|
802 | - $cr = $this->getConnection(); |
|
803 | - if(!$cr) { |
|
804 | - throw new \Exception('Could not connect to LDAP'); |
|
805 | - } |
|
806 | - $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0]; |
|
807 | - $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000); |
|
808 | - if(!$this->ldap->isResource($rr)) { |
|
809 | - return false; |
|
810 | - } |
|
811 | - $er = $this->ldap->firstEntry($cr, $rr); |
|
812 | - while(is_resource($er)) { |
|
813 | - $this->ldap->getDN($cr, $er); |
|
814 | - $attrs = $this->ldap->getAttributes($cr, $er); |
|
815 | - $result = []; |
|
816 | - $possibleAttrsCount = count($possibleAttrs); |
|
817 | - for($i = 0; $i < $possibleAttrsCount; $i++) { |
|
818 | - if(isset($attrs[$possibleAttrs[$i]])) { |
|
819 | - $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count']; |
|
820 | - } |
|
821 | - } |
|
822 | - if(!empty($result)) { |
|
823 | - natsort($result); |
|
824 | - return key($result); |
|
825 | - } |
|
826 | - |
|
827 | - $er = $this->ldap->nextEntry($cr, $er); |
|
828 | - } |
|
829 | - |
|
830 | - return false; |
|
831 | - } |
|
832 | - |
|
833 | - /** |
|
834 | - * Checks whether for a given BaseDN results will be returned |
|
835 | - * @param string $base the BaseDN to test |
|
836 | - * @return bool true on success, false otherwise |
|
837 | - * @throws \Exception |
|
838 | - */ |
|
839 | - private function testBaseDN($base) { |
|
840 | - $cr = $this->getConnection(); |
|
841 | - if(!$cr) { |
|
842 | - throw new \Exception('Could not connect to LDAP'); |
|
843 | - } |
|
844 | - |
|
845 | - //base is there, let's validate it. If we search for anything, we should |
|
846 | - //get a result set > 0 on a proper base |
|
847 | - $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1); |
|
848 | - if(!$this->ldap->isResource($rr)) { |
|
849 | - $errorNo = $this->ldap->errno($cr); |
|
850 | - $errorMsg = $this->ldap->error($cr); |
|
851 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base. |
|
852 | - ' Error '.$errorNo.': '.$errorMsg, ILogger::INFO); |
|
853 | - return false; |
|
854 | - } |
|
855 | - $entries = $this->ldap->countEntries($cr, $rr); |
|
856 | - return ($entries !== false) && ($entries > 0); |
|
857 | - } |
|
858 | - |
|
859 | - /** |
|
860 | - * Checks whether the server supports memberOf in LDAP Filter. |
|
861 | - * Note: at least in OpenLDAP, availability of memberOf is dependent on |
|
862 | - * a configured objectClass. I.e. not necessarily for all available groups |
|
863 | - * memberOf does work. |
|
864 | - * |
|
865 | - * @return bool true if it does, false otherwise |
|
866 | - * @throws \Exception |
|
867 | - */ |
|
868 | - private function testMemberOf() { |
|
869 | - $cr = $this->getConnection(); |
|
870 | - if(!$cr) { |
|
871 | - throw new \Exception('Could not connect to LDAP'); |
|
872 | - } |
|
873 | - $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1); |
|
874 | - if(is_int($result) && $result > 0) { |
|
875 | - return true; |
|
876 | - } |
|
877 | - return false; |
|
878 | - } |
|
879 | - |
|
880 | - /** |
|
881 | - * creates an LDAP Filter from given configuration |
|
882 | - * @param integer $filterType int, for which use case the filter shall be created |
|
883 | - * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or |
|
884 | - * self::LFILTER_GROUP_LIST |
|
885 | - * @return string|false string with the filter on success, false otherwise |
|
886 | - * @throws \Exception |
|
887 | - */ |
|
888 | - private function composeLdapFilter($filterType) { |
|
889 | - $filter = ''; |
|
890 | - $parts = 0; |
|
891 | - switch ($filterType) { |
|
892 | - case self::LFILTER_USER_LIST: |
|
893 | - $objcs = $this->configuration->ldapUserFilterObjectclass; |
|
894 | - //glue objectclasses |
|
895 | - if(is_array($objcs) && count($objcs) > 0) { |
|
896 | - $filter .= '(|'; |
|
897 | - foreach($objcs as $objc) { |
|
898 | - $filter .= '(objectclass=' . $objc . ')'; |
|
899 | - } |
|
900 | - $filter .= ')'; |
|
901 | - $parts++; |
|
902 | - } |
|
903 | - //glue group memberships |
|
904 | - if($this->configuration->hasMemberOfFilterSupport) { |
|
905 | - $cns = $this->configuration->ldapUserFilterGroups; |
|
906 | - if(is_array($cns) && count($cns) > 0) { |
|
907 | - $filter .= '(|'; |
|
908 | - $cr = $this->getConnection(); |
|
909 | - if(!$cr) { |
|
910 | - throw new \Exception('Could not connect to LDAP'); |
|
911 | - } |
|
912 | - $base = $this->configuration->ldapBase[0]; |
|
913 | - foreach($cns as $cn) { |
|
914 | - $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']); |
|
915 | - if(!$this->ldap->isResource($rr)) { |
|
916 | - continue; |
|
917 | - } |
|
918 | - $er = $this->ldap->firstEntry($cr, $rr); |
|
919 | - $attrs = $this->ldap->getAttributes($cr, $er); |
|
920 | - $dn = $this->ldap->getDN($cr, $er); |
|
921 | - if ($dn === false || $dn === '') { |
|
922 | - continue; |
|
923 | - } |
|
924 | - $filterPart = '(memberof=' . $dn . ')'; |
|
925 | - if(isset($attrs['primaryGroupToken'])) { |
|
926 | - $pgt = $attrs['primaryGroupToken'][0]; |
|
927 | - $primaryFilterPart = '(primaryGroupID=' . $pgt .')'; |
|
928 | - $filterPart = '(|' . $filterPart . $primaryFilterPart . ')'; |
|
929 | - } |
|
930 | - $filter .= $filterPart; |
|
931 | - } |
|
932 | - $filter .= ')'; |
|
933 | - } |
|
934 | - $parts++; |
|
935 | - } |
|
936 | - //wrap parts in AND condition |
|
937 | - if($parts > 1) { |
|
938 | - $filter = '(&' . $filter . ')'; |
|
939 | - } |
|
940 | - if ($filter === '') { |
|
941 | - $filter = '(objectclass=*)'; |
|
942 | - } |
|
943 | - break; |
|
944 | - |
|
945 | - case self::LFILTER_GROUP_LIST: |
|
946 | - $objcs = $this->configuration->ldapGroupFilterObjectclass; |
|
947 | - //glue objectclasses |
|
948 | - if(is_array($objcs) && count($objcs) > 0) { |
|
949 | - $filter .= '(|'; |
|
950 | - foreach($objcs as $objc) { |
|
951 | - $filter .= '(objectclass=' . $objc . ')'; |
|
952 | - } |
|
953 | - $filter .= ')'; |
|
954 | - $parts++; |
|
955 | - } |
|
956 | - //glue group memberships |
|
957 | - $cns = $this->configuration->ldapGroupFilterGroups; |
|
958 | - if(is_array($cns) && count($cns) > 0) { |
|
959 | - $filter .= '(|'; |
|
960 | - foreach($cns as $cn) { |
|
961 | - $filter .= '(cn=' . $cn . ')'; |
|
962 | - } |
|
963 | - $filter .= ')'; |
|
964 | - } |
|
965 | - $parts++; |
|
966 | - //wrap parts in AND condition |
|
967 | - if($parts > 1) { |
|
968 | - $filter = '(&' . $filter . ')'; |
|
969 | - } |
|
970 | - break; |
|
971 | - |
|
972 | - case self::LFILTER_LOGIN: |
|
973 | - $ulf = $this->configuration->ldapUserFilter; |
|
974 | - $loginpart = '=%uid'; |
|
975 | - $filterUsername = ''; |
|
976 | - $userAttributes = $this->getUserAttributes(); |
|
977 | - $userAttributes = array_change_key_case(array_flip($userAttributes)); |
|
978 | - $parts = 0; |
|
979 | - |
|
980 | - if($this->configuration->ldapLoginFilterUsername === '1') { |
|
981 | - $attr = ''; |
|
982 | - if(isset($userAttributes['uid'])) { |
|
983 | - $attr = 'uid'; |
|
984 | - } else if(isset($userAttributes['samaccountname'])) { |
|
985 | - $attr = 'samaccountname'; |
|
986 | - } else if(isset($userAttributes['cn'])) { |
|
987 | - //fallback |
|
988 | - $attr = 'cn'; |
|
989 | - } |
|
990 | - if ($attr !== '') { |
|
991 | - $filterUsername = '(' . $attr . $loginpart . ')'; |
|
992 | - $parts++; |
|
993 | - } |
|
994 | - } |
|
995 | - |
|
996 | - $filterEmail = ''; |
|
997 | - if($this->configuration->ldapLoginFilterEmail === '1') { |
|
998 | - $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))'; |
|
999 | - $parts++; |
|
1000 | - } |
|
1001 | - |
|
1002 | - $filterAttributes = ''; |
|
1003 | - $attrsToFilter = $this->configuration->ldapLoginFilterAttributes; |
|
1004 | - if(is_array($attrsToFilter) && count($attrsToFilter) > 0) { |
|
1005 | - $filterAttributes = '(|'; |
|
1006 | - foreach($attrsToFilter as $attribute) { |
|
1007 | - $filterAttributes .= '(' . $attribute . $loginpart . ')'; |
|
1008 | - } |
|
1009 | - $filterAttributes .= ')'; |
|
1010 | - $parts++; |
|
1011 | - } |
|
1012 | - |
|
1013 | - $filterLogin = ''; |
|
1014 | - if($parts > 1) { |
|
1015 | - $filterLogin = '(|'; |
|
1016 | - } |
|
1017 | - $filterLogin .= $filterUsername; |
|
1018 | - $filterLogin .= $filterEmail; |
|
1019 | - $filterLogin .= $filterAttributes; |
|
1020 | - if($parts > 1) { |
|
1021 | - $filterLogin .= ')'; |
|
1022 | - } |
|
1023 | - |
|
1024 | - $filter = '(&'.$ulf.$filterLogin.')'; |
|
1025 | - break; |
|
1026 | - } |
|
1027 | - |
|
1028 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG); |
|
1029 | - |
|
1030 | - return $filter; |
|
1031 | - } |
|
1032 | - |
|
1033 | - /** |
|
1034 | - * Connects and Binds to an LDAP Server |
|
1035 | - * |
|
1036 | - * @param int $port the port to connect with |
|
1037 | - * @param bool $tls whether startTLS is to be used |
|
1038 | - * @return bool |
|
1039 | - * @throws \Exception |
|
1040 | - */ |
|
1041 | - private function connectAndBind($port, $tls) { |
|
1042 | - //connect, does not really trigger any server communication |
|
1043 | - $host = $this->configuration->ldapHost; |
|
1044 | - $hostInfo = parse_url($host); |
|
1045 | - if(!$hostInfo) { |
|
1046 | - throw new \Exception(self::$l->t('Invalid Host')); |
|
1047 | - } |
|
1048 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG); |
|
1049 | - $cr = $this->ldap->connect($host, $port); |
|
1050 | - if(!is_resource($cr)) { |
|
1051 | - throw new \Exception(self::$l->t('Invalid Host')); |
|
1052 | - } |
|
1053 | - |
|
1054 | - //set LDAP options |
|
1055 | - $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1056 | - $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1057 | - $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1058 | - |
|
1059 | - try { |
|
1060 | - if($tls) { |
|
1061 | - $isTlsWorking = @$this->ldap->startTls($cr); |
|
1062 | - if(!$isTlsWorking) { |
|
1063 | - return false; |
|
1064 | - } |
|
1065 | - } |
|
1066 | - |
|
1067 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG); |
|
1068 | - //interesting part: do the bind! |
|
1069 | - $login = $this->ldap->bind($cr, |
|
1070 | - $this->configuration->ldapAgentName, |
|
1071 | - $this->configuration->ldapAgentPassword |
|
1072 | - ); |
|
1073 | - $errNo = $this->ldap->errno($cr); |
|
1074 | - $error = ldap_error($cr); |
|
1075 | - $this->ldap->unbind($cr); |
|
1076 | - } catch(ServerNotAvailableException $e) { |
|
1077 | - return false; |
|
1078 | - } |
|
1079 | - |
|
1080 | - if($login === true) { |
|
1081 | - $this->ldap->unbind($cr); |
|
1082 | - \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG); |
|
1083 | - return true; |
|
1084 | - } |
|
1085 | - |
|
1086 | - if($errNo === -1) { |
|
1087 | - //host, port or TLS wrong |
|
1088 | - return false; |
|
1089 | - } |
|
1090 | - throw new \Exception($error, $errNo); |
|
1091 | - } |
|
1092 | - |
|
1093 | - /** |
|
1094 | - * checks whether a valid combination of agent and password has been |
|
1095 | - * provided (either two values or nothing for anonymous connect) |
|
1096 | - * @return bool, true if everything is fine, false otherwise |
|
1097 | - */ |
|
1098 | - private function checkAgentRequirements() { |
|
1099 | - $agent = $this->configuration->ldapAgentName; |
|
1100 | - $pwd = $this->configuration->ldapAgentPassword; |
|
1101 | - |
|
1102 | - return |
|
1103 | - ($agent !== '' && $pwd !== '') |
|
1104 | - || ($agent === '' && $pwd === '') |
|
1105 | - ; |
|
1106 | - } |
|
1107 | - |
|
1108 | - /** |
|
1109 | - * @param array $reqs |
|
1110 | - * @return bool |
|
1111 | - */ |
|
1112 | - private function checkRequirements($reqs) { |
|
1113 | - $this->checkAgentRequirements(); |
|
1114 | - foreach($reqs as $option) { |
|
1115 | - $value = $this->configuration->$option; |
|
1116 | - if(empty($value)) { |
|
1117 | - return false; |
|
1118 | - } |
|
1119 | - } |
|
1120 | - return true; |
|
1121 | - } |
|
1122 | - |
|
1123 | - /** |
|
1124 | - * does a cumulativeSearch on LDAP to get different values of a |
|
1125 | - * specified attribute |
|
1126 | - * @param string[] $filters array, the filters that shall be used in the search |
|
1127 | - * @param string $attr the attribute of which a list of values shall be returned |
|
1128 | - * @param int $dnReadLimit the amount of how many DNs should be analyzed. |
|
1129 | - * The lower, the faster |
|
1130 | - * @param string $maxF string. if not null, this variable will have the filter that |
|
1131 | - * yields most result entries |
|
1132 | - * @return array|false an array with the values on success, false otherwise |
|
1133 | - */ |
|
1134 | - public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) { |
|
1135 | - $dnRead = []; |
|
1136 | - $foundItems = []; |
|
1137 | - $maxEntries = 0; |
|
1138 | - if(!is_array($this->configuration->ldapBase) |
|
1139 | - || !isset($this->configuration->ldapBase[0])) { |
|
1140 | - return false; |
|
1141 | - } |
|
1142 | - $base = $this->configuration->ldapBase[0]; |
|
1143 | - $cr = $this->getConnection(); |
|
1144 | - if(!$this->ldap->isResource($cr)) { |
|
1145 | - return false; |
|
1146 | - } |
|
1147 | - $lastFilter = null; |
|
1148 | - if(isset($filters[count($filters)-1])) { |
|
1149 | - $lastFilter = $filters[count($filters)-1]; |
|
1150 | - } |
|
1151 | - foreach($filters as $filter) { |
|
1152 | - if($lastFilter === $filter && count($foundItems) > 0) { |
|
1153 | - //skip when the filter is a wildcard and results were found |
|
1154 | - continue; |
|
1155 | - } |
|
1156 | - // 20k limit for performance and reason |
|
1157 | - $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000); |
|
1158 | - if(!$this->ldap->isResource($rr)) { |
|
1159 | - continue; |
|
1160 | - } |
|
1161 | - $entries = $this->ldap->countEntries($cr, $rr); |
|
1162 | - $getEntryFunc = 'firstEntry'; |
|
1163 | - if(($entries !== false) && ($entries > 0)) { |
|
1164 | - if(!is_null($maxF) && $entries > $maxEntries) { |
|
1165 | - $maxEntries = $entries; |
|
1166 | - $maxF = $filter; |
|
1167 | - } |
|
1168 | - $dnReadCount = 0; |
|
1169 | - do { |
|
1170 | - $entry = $this->ldap->$getEntryFunc($cr, $rr); |
|
1171 | - $getEntryFunc = 'nextEntry'; |
|
1172 | - if(!$this->ldap->isResource($entry)) { |
|
1173 | - continue 2; |
|
1174 | - } |
|
1175 | - $rr = $entry; //will be expected by nextEntry next round |
|
1176 | - $attributes = $this->ldap->getAttributes($cr, $entry); |
|
1177 | - $dn = $this->ldap->getDN($cr, $entry); |
|
1178 | - if($dn === false || in_array($dn, $dnRead)) { |
|
1179 | - continue; |
|
1180 | - } |
|
1181 | - $newItems = []; |
|
1182 | - $state = $this->getAttributeValuesFromEntry($attributes, |
|
1183 | - $attr, |
|
1184 | - $newItems); |
|
1185 | - $dnReadCount++; |
|
1186 | - $foundItems = array_merge($foundItems, $newItems); |
|
1187 | - $this->resultCache[$dn][$attr] = $newItems; |
|
1188 | - $dnRead[] = $dn; |
|
1189 | - } while(($state === self::LRESULT_PROCESSED_SKIP |
|
1190 | - || $this->ldap->isResource($entry)) |
|
1191 | - && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit)); |
|
1192 | - } |
|
1193 | - } |
|
1194 | - |
|
1195 | - return array_unique($foundItems); |
|
1196 | - } |
|
1197 | - |
|
1198 | - /** |
|
1199 | - * determines if and which $attr are available on the LDAP server |
|
1200 | - * @param string[] $objectclasses the objectclasses to use as search filter |
|
1201 | - * @param string $attr the attribute to look for |
|
1202 | - * @param string $dbkey the dbkey of the setting the feature is connected to |
|
1203 | - * @param string $confkey the confkey counterpart for the $dbkey as used in the |
|
1204 | - * Configuration class |
|
1205 | - * @param bool $po whether the objectClass with most result entries |
|
1206 | - * shall be pre-selected via the result |
|
1207 | - * @return array|false list of found items. |
|
1208 | - * @throws \Exception |
|
1209 | - */ |
|
1210 | - private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) { |
|
1211 | - $cr = $this->getConnection(); |
|
1212 | - if(!$cr) { |
|
1213 | - throw new \Exception('Could not connect to LDAP'); |
|
1214 | - } |
|
1215 | - $p = 'objectclass='; |
|
1216 | - foreach($objectclasses as $key => $value) { |
|
1217 | - $objectclasses[$key] = $p.$value; |
|
1218 | - } |
|
1219 | - $maxEntryObjC = ''; |
|
1220 | - |
|
1221 | - //how deep to dig? |
|
1222 | - //When looking for objectclasses, testing few entries is sufficient, |
|
1223 | - $dig = 3; |
|
1224 | - |
|
1225 | - $availableFeatures = |
|
1226 | - $this->cumulativeSearchOnAttribute($objectclasses, $attr, |
|
1227 | - $dig, $maxEntryObjC); |
|
1228 | - if(is_array($availableFeatures) |
|
1229 | - && count($availableFeatures) > 0) { |
|
1230 | - natcasesort($availableFeatures); |
|
1231 | - //natcasesort keeps indices, but we must get rid of them for proper |
|
1232 | - //sorting in the web UI. Therefore: array_values |
|
1233 | - $this->result->addOptions($dbkey, array_values($availableFeatures)); |
|
1234 | - } else { |
|
1235 | - throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
1236 | - } |
|
1237 | - |
|
1238 | - $setFeatures = $this->configuration->$confkey; |
|
1239 | - if(is_array($setFeatures) && !empty($setFeatures)) { |
|
1240 | - //something is already configured? pre-select it. |
|
1241 | - $this->result->addChange($dbkey, $setFeatures); |
|
1242 | - } else if ($po && $maxEntryObjC !== '') { |
|
1243 | - //pre-select objectclass with most result entries |
|
1244 | - $maxEntryObjC = str_replace($p, '', $maxEntryObjC); |
|
1245 | - $this->applyFind($dbkey, $maxEntryObjC); |
|
1246 | - $this->result->addChange($dbkey, $maxEntryObjC); |
|
1247 | - } |
|
1248 | - |
|
1249 | - return $availableFeatures; |
|
1250 | - } |
|
1251 | - |
|
1252 | - /** |
|
1253 | - * appends a list of values fr |
|
1254 | - * @param resource $result the return value from ldap_get_attributes |
|
1255 | - * @param string $attribute the attribute values to look for |
|
1256 | - * @param array &$known new values will be appended here |
|
1257 | - * @return int, state on of the class constants LRESULT_PROCESSED_OK, |
|
1258 | - * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP |
|
1259 | - */ |
|
1260 | - private function getAttributeValuesFromEntry($result, $attribute, &$known) { |
|
1261 | - if(!is_array($result) |
|
1262 | - || !isset($result['count']) |
|
1263 | - || !$result['count'] > 0) { |
|
1264 | - return self::LRESULT_PROCESSED_INVALID; |
|
1265 | - } |
|
1266 | - |
|
1267 | - // strtolower on all keys for proper comparison |
|
1268 | - $result = \OCP\Util::mb_array_change_key_case($result); |
|
1269 | - $attribute = strtolower($attribute); |
|
1270 | - if(isset($result[$attribute])) { |
|
1271 | - foreach($result[$attribute] as $key => $val) { |
|
1272 | - if($key === 'count') { |
|
1273 | - continue; |
|
1274 | - } |
|
1275 | - if(!in_array($val, $known)) { |
|
1276 | - $known[] = $val; |
|
1277 | - } |
|
1278 | - } |
|
1279 | - return self::LRESULT_PROCESSED_OK; |
|
1280 | - } else { |
|
1281 | - return self::LRESULT_PROCESSED_SKIP; |
|
1282 | - } |
|
1283 | - } |
|
1284 | - |
|
1285 | - /** |
|
1286 | - * @return bool|mixed |
|
1287 | - */ |
|
1288 | - private function getConnection() { |
|
1289 | - if(!is_null($this->cr)) { |
|
1290 | - return $this->cr; |
|
1291 | - } |
|
1292 | - |
|
1293 | - $cr = $this->ldap->connect( |
|
1294 | - $this->configuration->ldapHost, |
|
1295 | - $this->configuration->ldapPort |
|
1296 | - ); |
|
1297 | - |
|
1298 | - $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1299 | - $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1300 | - $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1301 | - if($this->configuration->ldapTLS === 1) { |
|
1302 | - $this->ldap->startTls($cr); |
|
1303 | - } |
|
1304 | - |
|
1305 | - $lo = @$this->ldap->bind($cr, |
|
1306 | - $this->configuration->ldapAgentName, |
|
1307 | - $this->configuration->ldapAgentPassword); |
|
1308 | - if($lo === true) { |
|
1309 | - $this->$cr = $cr; |
|
1310 | - return $cr; |
|
1311 | - } |
|
1312 | - |
|
1313 | - return false; |
|
1314 | - } |
|
1315 | - |
|
1316 | - /** |
|
1317 | - * @return array |
|
1318 | - */ |
|
1319 | - private function getDefaultLdapPortSettings() { |
|
1320 | - static $settings = [ |
|
1321 | - ['port' => 7636, 'tls' => false], |
|
1322 | - ['port' => 636, 'tls' => false], |
|
1323 | - ['port' => 7389, 'tls' => true], |
|
1324 | - ['port' => 389, 'tls' => true], |
|
1325 | - ['port' => 7389, 'tls' => false], |
|
1326 | - ['port' => 389, 'tls' => false], |
|
1327 | - ]; |
|
1328 | - return $settings; |
|
1329 | - } |
|
1330 | - |
|
1331 | - /** |
|
1332 | - * @return array |
|
1333 | - */ |
|
1334 | - private function getPortSettingsToTry() { |
|
1335 | - //389 ← LDAP / Unencrypted or StartTLS |
|
1336 | - //636 ← LDAPS / SSL |
|
1337 | - //7xxx ← UCS. need to be checked first, because both ports may be open |
|
1338 | - $host = $this->configuration->ldapHost; |
|
1339 | - $port = (int)$this->configuration->ldapPort; |
|
1340 | - $portSettings = []; |
|
1341 | - |
|
1342 | - //In case the port is already provided, we will check this first |
|
1343 | - if($port > 0) { |
|
1344 | - $hostInfo = parse_url($host); |
|
1345 | - if(!(is_array($hostInfo) |
|
1346 | - && isset($hostInfo['scheme']) |
|
1347 | - && stripos($hostInfo['scheme'], 'ldaps') !== false)) { |
|
1348 | - $portSettings[] = ['port' => $port, 'tls' => true]; |
|
1349 | - } |
|
1350 | - $portSettings[] =['port' => $port, 'tls' => false]; |
|
1351 | - } |
|
1352 | - |
|
1353 | - //default ports |
|
1354 | - $portSettings = array_merge($portSettings, |
|
1355 | - $this->getDefaultLdapPortSettings()); |
|
1356 | - |
|
1357 | - return $portSettings; |
|
1358 | - } |
|
45 | + /** @var \OCP\IL10N */ |
|
46 | + static protected $l; |
|
47 | + protected $access; |
|
48 | + protected $cr; |
|
49 | + protected $configuration; |
|
50 | + protected $result; |
|
51 | + protected $resultCache = []; |
|
52 | + |
|
53 | + const LRESULT_PROCESSED_OK = 2; |
|
54 | + const LRESULT_PROCESSED_INVALID = 3; |
|
55 | + const LRESULT_PROCESSED_SKIP = 4; |
|
56 | + |
|
57 | + const LFILTER_LOGIN = 2; |
|
58 | + const LFILTER_USER_LIST = 3; |
|
59 | + const LFILTER_GROUP_LIST = 4; |
|
60 | + |
|
61 | + const LFILTER_MODE_ASSISTED = 2; |
|
62 | + const LFILTER_MODE_RAW = 1; |
|
63 | + |
|
64 | + const LDAP_NW_TIMEOUT = 4; |
|
65 | + |
|
66 | + /** |
|
67 | + * Constructor |
|
68 | + * @param Configuration $configuration an instance of Configuration |
|
69 | + * @param ILDAPWrapper $ldap an instance of ILDAPWrapper |
|
70 | + * @param Access $access |
|
71 | + */ |
|
72 | + public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) { |
|
73 | + parent::__construct($ldap); |
|
74 | + $this->configuration = $configuration; |
|
75 | + if(is_null(Wizard::$l)) { |
|
76 | + Wizard::$l = \OC::$server->getL10N('user_ldap'); |
|
77 | + } |
|
78 | + $this->access = $access; |
|
79 | + $this->result = new WizardResult(); |
|
80 | + } |
|
81 | + |
|
82 | + public function __destruct() { |
|
83 | + if($this->result->hasChanges()) { |
|
84 | + $this->configuration->saveConfiguration(); |
|
85 | + } |
|
86 | + } |
|
87 | + |
|
88 | + /** |
|
89 | + * counts entries in the LDAP directory |
|
90 | + * |
|
91 | + * @param string $filter the LDAP search filter |
|
92 | + * @param string $type a string being either 'users' or 'groups'; |
|
93 | + * @return int |
|
94 | + * @throws \Exception |
|
95 | + */ |
|
96 | + public function countEntries(string $filter, string $type): int { |
|
97 | + $reqs = ['ldapHost', 'ldapPort', 'ldapBase']; |
|
98 | + if($type === 'users') { |
|
99 | + $reqs[] = 'ldapUserFilter'; |
|
100 | + } |
|
101 | + if(!$this->checkRequirements($reqs)) { |
|
102 | + throw new \Exception('Requirements not met', 400); |
|
103 | + } |
|
104 | + |
|
105 | + $attr = ['dn']; // default |
|
106 | + $limit = 1001; |
|
107 | + if($type === 'groups') { |
|
108 | + $result = $this->access->countGroups($filter, $attr, $limit); |
|
109 | + } else if($type === 'users') { |
|
110 | + $result = $this->access->countUsers($filter, $attr, $limit); |
|
111 | + } else if ($type === 'objects') { |
|
112 | + $result = $this->access->countObjects($limit); |
|
113 | + } else { |
|
114 | + throw new \Exception('Internal error: Invalid object type', 500); |
|
115 | + } |
|
116 | + |
|
117 | + return (int)$result; |
|
118 | + } |
|
119 | + |
|
120 | + /** |
|
121 | + * formats the return value of a count operation to the string to be |
|
122 | + * inserted. |
|
123 | + * |
|
124 | + * @param int $count |
|
125 | + * @return string |
|
126 | + */ |
|
127 | + private function formatCountResult(int $count): string { |
|
128 | + if($count > 1000) { |
|
129 | + return '> 1000'; |
|
130 | + } |
|
131 | + return (string)$count; |
|
132 | + } |
|
133 | + |
|
134 | + public function countGroups() { |
|
135 | + $filter = $this->configuration->ldapGroupFilter; |
|
136 | + |
|
137 | + if(empty($filter)) { |
|
138 | + $output = self::$l->n('%s group found', '%s groups found', 0, [0]); |
|
139 | + $this->result->addChange('ldap_group_count', $output); |
|
140 | + return $this->result; |
|
141 | + } |
|
142 | + |
|
143 | + try { |
|
144 | + $groupsTotal = $this->countEntries($filter, 'groups'); |
|
145 | + } catch (\Exception $e) { |
|
146 | + //400 can be ignored, 500 is forwarded |
|
147 | + if($e->getCode() === 500) { |
|
148 | + throw $e; |
|
149 | + } |
|
150 | + return false; |
|
151 | + } |
|
152 | + $output = self::$l->n( |
|
153 | + '%s group found', |
|
154 | + '%s groups found', |
|
155 | + $groupsTotal, |
|
156 | + [$this->formatCountResult($groupsTotal)] |
|
157 | + ); |
|
158 | + $this->result->addChange('ldap_group_count', $output); |
|
159 | + return $this->result; |
|
160 | + } |
|
161 | + |
|
162 | + /** |
|
163 | + * @return WizardResult |
|
164 | + * @throws \Exception |
|
165 | + */ |
|
166 | + public function countUsers() { |
|
167 | + $filter = $this->access->getFilterForUserCount(); |
|
168 | + |
|
169 | + $usersTotal = $this->countEntries($filter, 'users'); |
|
170 | + $output = self::$l->n( |
|
171 | + '%s user found', |
|
172 | + '%s users found', |
|
173 | + $usersTotal, |
|
174 | + [$this->formatCountResult($usersTotal)] |
|
175 | + ); |
|
176 | + $this->result->addChange('ldap_user_count', $output); |
|
177 | + return $this->result; |
|
178 | + } |
|
179 | + |
|
180 | + /** |
|
181 | + * counts any objects in the currently set base dn |
|
182 | + * |
|
183 | + * @return WizardResult |
|
184 | + * @throws \Exception |
|
185 | + */ |
|
186 | + public function countInBaseDN() { |
|
187 | + // we don't need to provide a filter in this case |
|
188 | + $total = $this->countEntries('', 'objects'); |
|
189 | + if($total === false) { |
|
190 | + throw new \Exception('invalid results received'); |
|
191 | + } |
|
192 | + $this->result->addChange('ldap_test_base', $total); |
|
193 | + return $this->result; |
|
194 | + } |
|
195 | + |
|
196 | + /** |
|
197 | + * counts users with a specified attribute |
|
198 | + * @param string $attr |
|
199 | + * @param bool $existsCheck |
|
200 | + * @return int|bool |
|
201 | + */ |
|
202 | + public function countUsersWithAttribute($attr, $existsCheck = false) { |
|
203 | + if(!$this->checkRequirements(['ldapHost', |
|
204 | + 'ldapPort', |
|
205 | + 'ldapBase', |
|
206 | + 'ldapUserFilter', |
|
207 | + ])) { |
|
208 | + return false; |
|
209 | + } |
|
210 | + |
|
211 | + $filter = $this->access->combineFilterWithAnd([ |
|
212 | + $this->configuration->ldapUserFilter, |
|
213 | + $attr . '=*' |
|
214 | + ]); |
|
215 | + |
|
216 | + $limit = ($existsCheck === false) ? null : 1; |
|
217 | + |
|
218 | + return $this->access->countUsers($filter, ['dn'], $limit); |
|
219 | + } |
|
220 | + |
|
221 | + /** |
|
222 | + * detects the display name attribute. If a setting is already present that |
|
223 | + * returns at least one hit, the detection will be canceled. |
|
224 | + * @return WizardResult|bool |
|
225 | + * @throws \Exception |
|
226 | + */ |
|
227 | + public function detectUserDisplayNameAttribute() { |
|
228 | + if(!$this->checkRequirements(['ldapHost', |
|
229 | + 'ldapPort', |
|
230 | + 'ldapBase', |
|
231 | + 'ldapUserFilter', |
|
232 | + ])) { |
|
233 | + return false; |
|
234 | + } |
|
235 | + |
|
236 | + $attr = $this->configuration->ldapUserDisplayName; |
|
237 | + if ($attr !== '' && $attr !== 'displayName') { |
|
238 | + // most likely not the default value with upper case N, |
|
239 | + // verify it still produces a result |
|
240 | + $count = (int)$this->countUsersWithAttribute($attr, true); |
|
241 | + if($count > 0) { |
|
242 | + //no change, but we sent it back to make sure the user interface |
|
243 | + //is still correct, even if the ajax call was cancelled meanwhile |
|
244 | + $this->result->addChange('ldap_display_name', $attr); |
|
245 | + return $this->result; |
|
246 | + } |
|
247 | + } |
|
248 | + |
|
249 | + // first attribute that has at least one result wins |
|
250 | + $displayNameAttrs = ['displayname', 'cn']; |
|
251 | + foreach ($displayNameAttrs as $attr) { |
|
252 | + $count = (int)$this->countUsersWithAttribute($attr, true); |
|
253 | + |
|
254 | + if($count > 0) { |
|
255 | + $this->applyFind('ldap_display_name', $attr); |
|
256 | + return $this->result; |
|
257 | + } |
|
258 | + } |
|
259 | + |
|
260 | + throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.')); |
|
261 | + } |
|
262 | + |
|
263 | + /** |
|
264 | + * detects the most often used email attribute for users applying to the |
|
265 | + * user list filter. If a setting is already present that returns at least |
|
266 | + * one hit, the detection will be canceled. |
|
267 | + * @return WizardResult|bool |
|
268 | + */ |
|
269 | + public function detectEmailAttribute() { |
|
270 | + if(!$this->checkRequirements(['ldapHost', |
|
271 | + 'ldapPort', |
|
272 | + 'ldapBase', |
|
273 | + 'ldapUserFilter', |
|
274 | + ])) { |
|
275 | + return false; |
|
276 | + } |
|
277 | + |
|
278 | + $attr = $this->configuration->ldapEmailAttribute; |
|
279 | + if ($attr !== '') { |
|
280 | + $count = (int)$this->countUsersWithAttribute($attr, true); |
|
281 | + if($count > 0) { |
|
282 | + return false; |
|
283 | + } |
|
284 | + $writeLog = true; |
|
285 | + } else { |
|
286 | + $writeLog = false; |
|
287 | + } |
|
288 | + |
|
289 | + $emailAttributes = ['mail', 'mailPrimaryAddress']; |
|
290 | + $winner = ''; |
|
291 | + $maxUsers = 0; |
|
292 | + foreach($emailAttributes as $attr) { |
|
293 | + $count = $this->countUsersWithAttribute($attr); |
|
294 | + if($count > $maxUsers) { |
|
295 | + $maxUsers = $count; |
|
296 | + $winner = $attr; |
|
297 | + } |
|
298 | + } |
|
299 | + |
|
300 | + if($winner !== '') { |
|
301 | + $this->applyFind('ldap_email_attr', $winner); |
|
302 | + if($writeLog) { |
|
303 | + \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' . |
|
304 | + 'automatically been reset, because the original value ' . |
|
305 | + 'did not return any results.', ILogger::INFO); |
|
306 | + } |
|
307 | + } |
|
308 | + |
|
309 | + return $this->result; |
|
310 | + } |
|
311 | + |
|
312 | + /** |
|
313 | + * @return WizardResult |
|
314 | + * @throws \Exception |
|
315 | + */ |
|
316 | + public function determineAttributes() { |
|
317 | + if(!$this->checkRequirements(['ldapHost', |
|
318 | + 'ldapPort', |
|
319 | + 'ldapBase', |
|
320 | + 'ldapUserFilter', |
|
321 | + ])) { |
|
322 | + return false; |
|
323 | + } |
|
324 | + |
|
325 | + $attributes = $this->getUserAttributes(); |
|
326 | + |
|
327 | + natcasesort($attributes); |
|
328 | + $attributes = array_values($attributes); |
|
329 | + |
|
330 | + $this->result->addOptions('ldap_loginfilter_attributes', $attributes); |
|
331 | + |
|
332 | + $selected = $this->configuration->ldapLoginFilterAttributes; |
|
333 | + if(is_array($selected) && !empty($selected)) { |
|
334 | + $this->result->addChange('ldap_loginfilter_attributes', $selected); |
|
335 | + } |
|
336 | + |
|
337 | + return $this->result; |
|
338 | + } |
|
339 | + |
|
340 | + /** |
|
341 | + * detects the available LDAP attributes |
|
342 | + * @return array|false The instance's WizardResult instance |
|
343 | + * @throws \Exception |
|
344 | + */ |
|
345 | + private function getUserAttributes() { |
|
346 | + if(!$this->checkRequirements(['ldapHost', |
|
347 | + 'ldapPort', |
|
348 | + 'ldapBase', |
|
349 | + 'ldapUserFilter', |
|
350 | + ])) { |
|
351 | + return false; |
|
352 | + } |
|
353 | + $cr = $this->getConnection(); |
|
354 | + if(!$cr) { |
|
355 | + throw new \Exception('Could not connect to LDAP'); |
|
356 | + } |
|
357 | + |
|
358 | + $base = $this->configuration->ldapBase[0]; |
|
359 | + $filter = $this->configuration->ldapUserFilter; |
|
360 | + $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1); |
|
361 | + if(!$this->ldap->isResource($rr)) { |
|
362 | + return false; |
|
363 | + } |
|
364 | + $er = $this->ldap->firstEntry($cr, $rr); |
|
365 | + $attributes = $this->ldap->getAttributes($cr, $er); |
|
366 | + $pureAttributes = []; |
|
367 | + for($i = 0; $i < $attributes['count']; $i++) { |
|
368 | + $pureAttributes[] = $attributes[$i]; |
|
369 | + } |
|
370 | + |
|
371 | + return $pureAttributes; |
|
372 | + } |
|
373 | + |
|
374 | + /** |
|
375 | + * detects the available LDAP groups |
|
376 | + * @return WizardResult|false the instance's WizardResult instance |
|
377 | + */ |
|
378 | + public function determineGroupsForGroups() { |
|
379 | + return $this->determineGroups('ldap_groupfilter_groups', |
|
380 | + 'ldapGroupFilterGroups', |
|
381 | + false); |
|
382 | + } |
|
383 | + |
|
384 | + /** |
|
385 | + * detects the available LDAP groups |
|
386 | + * @return WizardResult|false the instance's WizardResult instance |
|
387 | + */ |
|
388 | + public function determineGroupsForUsers() { |
|
389 | + return $this->determineGroups('ldap_userfilter_groups', |
|
390 | + 'ldapUserFilterGroups'); |
|
391 | + } |
|
392 | + |
|
393 | + /** |
|
394 | + * detects the available LDAP groups |
|
395 | + * @param string $dbKey |
|
396 | + * @param string $confKey |
|
397 | + * @param bool $testMemberOf |
|
398 | + * @return WizardResult|false the instance's WizardResult instance |
|
399 | + * @throws \Exception |
|
400 | + */ |
|
401 | + private function determineGroups($dbKey, $confKey, $testMemberOf = true) { |
|
402 | + if(!$this->checkRequirements(['ldapHost', |
|
403 | + 'ldapPort', |
|
404 | + 'ldapBase', |
|
405 | + ])) { |
|
406 | + return false; |
|
407 | + } |
|
408 | + $cr = $this->getConnection(); |
|
409 | + if(!$cr) { |
|
410 | + throw new \Exception('Could not connect to LDAP'); |
|
411 | + } |
|
412 | + |
|
413 | + $this->fetchGroups($dbKey, $confKey); |
|
414 | + |
|
415 | + if($testMemberOf) { |
|
416 | + $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf(); |
|
417 | + $this->result->markChange(); |
|
418 | + if(!$this->configuration->hasMemberOfFilterSupport) { |
|
419 | + throw new \Exception('memberOf is not supported by the server'); |
|
420 | + } |
|
421 | + } |
|
422 | + |
|
423 | + return $this->result; |
|
424 | + } |
|
425 | + |
|
426 | + /** |
|
427 | + * fetches all groups from LDAP and adds them to the result object |
|
428 | + * |
|
429 | + * @param string $dbKey |
|
430 | + * @param string $confKey |
|
431 | + * @return array $groupEntries |
|
432 | + * @throws \Exception |
|
433 | + */ |
|
434 | + public function fetchGroups($dbKey, $confKey) { |
|
435 | + $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames']; |
|
436 | + |
|
437 | + $filterParts = []; |
|
438 | + foreach($obclasses as $obclass) { |
|
439 | + $filterParts[] = 'objectclass='.$obclass; |
|
440 | + } |
|
441 | + //we filter for everything |
|
442 | + //- that looks like a group and |
|
443 | + //- has the group display name set |
|
444 | + $filter = $this->access->combineFilterWithOr($filterParts); |
|
445 | + $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']); |
|
446 | + |
|
447 | + $groupNames = []; |
|
448 | + $groupEntries = []; |
|
449 | + $limit = 400; |
|
450 | + $offset = 0; |
|
451 | + do { |
|
452 | + // we need to request dn additionally here, otherwise memberOf |
|
453 | + // detection will fail later |
|
454 | + $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset); |
|
455 | + foreach($result as $item) { |
|
456 | + if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) { |
|
457 | + // just in case - no issue known |
|
458 | + continue; |
|
459 | + } |
|
460 | + $groupNames[] = $item['cn'][0]; |
|
461 | + $groupEntries[] = $item; |
|
462 | + } |
|
463 | + $offset += $limit; |
|
464 | + } while ($this->access->hasMoreResults()); |
|
465 | + |
|
466 | + if(count($groupNames) > 0) { |
|
467 | + natsort($groupNames); |
|
468 | + $this->result->addOptions($dbKey, array_values($groupNames)); |
|
469 | + } else { |
|
470 | + throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
471 | + } |
|
472 | + |
|
473 | + $setFeatures = $this->configuration->$confKey; |
|
474 | + if(is_array($setFeatures) && !empty($setFeatures)) { |
|
475 | + //something is already configured? pre-select it. |
|
476 | + $this->result->addChange($dbKey, $setFeatures); |
|
477 | + } |
|
478 | + return $groupEntries; |
|
479 | + } |
|
480 | + |
|
481 | + public function determineGroupMemberAssoc() { |
|
482 | + if(!$this->checkRequirements(['ldapHost', |
|
483 | + 'ldapPort', |
|
484 | + 'ldapGroupFilter', |
|
485 | + ])) { |
|
486 | + return false; |
|
487 | + } |
|
488 | + $attribute = $this->detectGroupMemberAssoc(); |
|
489 | + if($attribute === false) { |
|
490 | + return false; |
|
491 | + } |
|
492 | + $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]); |
|
493 | + $this->result->addChange('ldap_group_member_assoc_attribute', $attribute); |
|
494 | + |
|
495 | + return $this->result; |
|
496 | + } |
|
497 | + |
|
498 | + /** |
|
499 | + * Detects the available object classes |
|
500 | + * @return WizardResult|false the instance's WizardResult instance |
|
501 | + * @throws \Exception |
|
502 | + */ |
|
503 | + public function determineGroupObjectClasses() { |
|
504 | + if(!$this->checkRequirements(['ldapHost', |
|
505 | + 'ldapPort', |
|
506 | + 'ldapBase', |
|
507 | + ])) { |
|
508 | + return false; |
|
509 | + } |
|
510 | + $cr = $this->getConnection(); |
|
511 | + if(!$cr) { |
|
512 | + throw new \Exception('Could not connect to LDAP'); |
|
513 | + } |
|
514 | + |
|
515 | + $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*']; |
|
516 | + $this->determineFeature($obclasses, |
|
517 | + 'objectclass', |
|
518 | + 'ldap_groupfilter_objectclass', |
|
519 | + 'ldapGroupFilterObjectclass', |
|
520 | + false); |
|
521 | + |
|
522 | + return $this->result; |
|
523 | + } |
|
524 | + |
|
525 | + /** |
|
526 | + * detects the available object classes |
|
527 | + * @return WizardResult |
|
528 | + * @throws \Exception |
|
529 | + */ |
|
530 | + public function determineUserObjectClasses() { |
|
531 | + if(!$this->checkRequirements(['ldapHost', |
|
532 | + 'ldapPort', |
|
533 | + 'ldapBase', |
|
534 | + ])) { |
|
535 | + return false; |
|
536 | + } |
|
537 | + $cr = $this->getConnection(); |
|
538 | + if(!$cr) { |
|
539 | + throw new \Exception('Could not connect to LDAP'); |
|
540 | + } |
|
541 | + |
|
542 | + $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson', |
|
543 | + 'user', 'posixAccount', '*']; |
|
544 | + $filter = $this->configuration->ldapUserFilter; |
|
545 | + //if filter is empty, it is probably the first time the wizard is called |
|
546 | + //then, apply suggestions. |
|
547 | + $this->determineFeature($obclasses, |
|
548 | + 'objectclass', |
|
549 | + 'ldap_userfilter_objectclass', |
|
550 | + 'ldapUserFilterObjectclass', |
|
551 | + empty($filter)); |
|
552 | + |
|
553 | + return $this->result; |
|
554 | + } |
|
555 | + |
|
556 | + /** |
|
557 | + * @return WizardResult|false |
|
558 | + * @throws \Exception |
|
559 | + */ |
|
560 | + public function getGroupFilter() { |
|
561 | + if(!$this->checkRequirements(['ldapHost', |
|
562 | + 'ldapPort', |
|
563 | + 'ldapBase', |
|
564 | + ])) { |
|
565 | + return false; |
|
566 | + } |
|
567 | + //make sure the use display name is set |
|
568 | + $displayName = $this->configuration->ldapGroupDisplayName; |
|
569 | + if ($displayName === '') { |
|
570 | + $d = $this->configuration->getDefaults(); |
|
571 | + $this->applyFind('ldap_group_display_name', |
|
572 | + $d['ldap_group_display_name']); |
|
573 | + } |
|
574 | + $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST); |
|
575 | + |
|
576 | + $this->applyFind('ldap_group_filter', $filter); |
|
577 | + return $this->result; |
|
578 | + } |
|
579 | + |
|
580 | + /** |
|
581 | + * @return WizardResult|false |
|
582 | + * @throws \Exception |
|
583 | + */ |
|
584 | + public function getUserListFilter() { |
|
585 | + if(!$this->checkRequirements(['ldapHost', |
|
586 | + 'ldapPort', |
|
587 | + 'ldapBase', |
|
588 | + ])) { |
|
589 | + return false; |
|
590 | + } |
|
591 | + //make sure the use display name is set |
|
592 | + $displayName = $this->configuration->ldapUserDisplayName; |
|
593 | + if ($displayName === '') { |
|
594 | + $d = $this->configuration->getDefaults(); |
|
595 | + $this->applyFind('ldap_display_name', $d['ldap_display_name']); |
|
596 | + } |
|
597 | + $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST); |
|
598 | + if(!$filter) { |
|
599 | + throw new \Exception('Cannot create filter'); |
|
600 | + } |
|
601 | + |
|
602 | + $this->applyFind('ldap_userlist_filter', $filter); |
|
603 | + return $this->result; |
|
604 | + } |
|
605 | + |
|
606 | + /** |
|
607 | + * @return bool|WizardResult |
|
608 | + * @throws \Exception |
|
609 | + */ |
|
610 | + public function getUserLoginFilter() { |
|
611 | + if(!$this->checkRequirements(['ldapHost', |
|
612 | + 'ldapPort', |
|
613 | + 'ldapBase', |
|
614 | + 'ldapUserFilter', |
|
615 | + ])) { |
|
616 | + return false; |
|
617 | + } |
|
618 | + |
|
619 | + $filter = $this->composeLdapFilter(self::LFILTER_LOGIN); |
|
620 | + if(!$filter) { |
|
621 | + throw new \Exception('Cannot create filter'); |
|
622 | + } |
|
623 | + |
|
624 | + $this->applyFind('ldap_login_filter', $filter); |
|
625 | + return $this->result; |
|
626 | + } |
|
627 | + |
|
628 | + /** |
|
629 | + * @return bool|WizardResult |
|
630 | + * @param string $loginName |
|
631 | + * @throws \Exception |
|
632 | + */ |
|
633 | + public function testLoginName($loginName) { |
|
634 | + if(!$this->checkRequirements(['ldapHost', |
|
635 | + 'ldapPort', |
|
636 | + 'ldapBase', |
|
637 | + 'ldapLoginFilter', |
|
638 | + ])) { |
|
639 | + return false; |
|
640 | + } |
|
641 | + |
|
642 | + $cr = $this->access->connection->getConnectionResource(); |
|
643 | + if(!$this->ldap->isResource($cr)) { |
|
644 | + throw new \Exception('connection error'); |
|
645 | + } |
|
646 | + |
|
647 | + if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8') |
|
648 | + === false) { |
|
649 | + throw new \Exception('missing placeholder'); |
|
650 | + } |
|
651 | + |
|
652 | + $users = $this->access->countUsersByLoginName($loginName); |
|
653 | + if($this->ldap->errno($cr) !== 0) { |
|
654 | + throw new \Exception($this->ldap->error($cr)); |
|
655 | + } |
|
656 | + $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter); |
|
657 | + $this->result->addChange('ldap_test_loginname', $users); |
|
658 | + $this->result->addChange('ldap_test_effective_filter', $filter); |
|
659 | + return $this->result; |
|
660 | + } |
|
661 | + |
|
662 | + /** |
|
663 | + * Tries to determine the port, requires given Host, User DN and Password |
|
664 | + * @return WizardResult|false WizardResult on success, false otherwise |
|
665 | + * @throws \Exception |
|
666 | + */ |
|
667 | + public function guessPortAndTLS() { |
|
668 | + if(!$this->checkRequirements(['ldapHost', |
|
669 | + ])) { |
|
670 | + return false; |
|
671 | + } |
|
672 | + $this->checkHost(); |
|
673 | + $portSettings = $this->getPortSettingsToTry(); |
|
674 | + |
|
675 | + if(!is_array($portSettings)) { |
|
676 | + throw new \Exception(print_r($portSettings, true)); |
|
677 | + } |
|
678 | + |
|
679 | + //proceed from the best configuration and return on first success |
|
680 | + foreach($portSettings as $setting) { |
|
681 | + $p = $setting['port']; |
|
682 | + $t = $setting['tls']; |
|
683 | + \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG); |
|
684 | + //connectAndBind may throw Exception, it needs to be catched by the |
|
685 | + //callee of this method |
|
686 | + |
|
687 | + try { |
|
688 | + $settingsFound = $this->connectAndBind($p, $t); |
|
689 | + } catch (\Exception $e) { |
|
690 | + // any reply other than -1 (= cannot connect) is already okay, |
|
691 | + // because then we found the server |
|
692 | + // unavailable startTLS returns -11 |
|
693 | + if($e->getCode() > 0) { |
|
694 | + $settingsFound = true; |
|
695 | + } else { |
|
696 | + throw $e; |
|
697 | + } |
|
698 | + } |
|
699 | + |
|
700 | + if ($settingsFound === true) { |
|
701 | + $config = [ |
|
702 | + 'ldapPort' => $p, |
|
703 | + 'ldapTLS' => (int)$t |
|
704 | + ]; |
|
705 | + $this->configuration->setConfiguration($config); |
|
706 | + \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG); |
|
707 | + $this->result->addChange('ldap_port', $p); |
|
708 | + return $this->result; |
|
709 | + } |
|
710 | + } |
|
711 | + |
|
712 | + //custom port, undetected (we do not brute force) |
|
713 | + return false; |
|
714 | + } |
|
715 | + |
|
716 | + /** |
|
717 | + * tries to determine a base dn from User DN or LDAP Host |
|
718 | + * @return WizardResult|false WizardResult on success, false otherwise |
|
719 | + */ |
|
720 | + public function guessBaseDN() { |
|
721 | + if(!$this->checkRequirements(['ldapHost', |
|
722 | + 'ldapPort', |
|
723 | + ])) { |
|
724 | + return false; |
|
725 | + } |
|
726 | + |
|
727 | + //check whether a DN is given in the agent name (99.9% of all cases) |
|
728 | + $base = null; |
|
729 | + $i = stripos($this->configuration->ldapAgentName, 'dc='); |
|
730 | + if($i !== false) { |
|
731 | + $base = substr($this->configuration->ldapAgentName, $i); |
|
732 | + if($this->testBaseDN($base)) { |
|
733 | + $this->applyFind('ldap_base', $base); |
|
734 | + return $this->result; |
|
735 | + } |
|
736 | + } |
|
737 | + |
|
738 | + //this did not help :( |
|
739 | + //Let's see whether we can parse the Host URL and convert the domain to |
|
740 | + //a base DN |
|
741 | + $helper = new Helper(\OC::$server->getConfig()); |
|
742 | + $domain = $helper->getDomainFromURL($this->configuration->ldapHost); |
|
743 | + if(!$domain) { |
|
744 | + return false; |
|
745 | + } |
|
746 | + |
|
747 | + $dparts = explode('.', $domain); |
|
748 | + while(count($dparts) > 0) { |
|
749 | + $base2 = 'dc=' . implode(',dc=', $dparts); |
|
750 | + if ($base !== $base2 && $this->testBaseDN($base2)) { |
|
751 | + $this->applyFind('ldap_base', $base2); |
|
752 | + return $this->result; |
|
753 | + } |
|
754 | + array_shift($dparts); |
|
755 | + } |
|
756 | + |
|
757 | + return false; |
|
758 | + } |
|
759 | + |
|
760 | + /** |
|
761 | + * sets the found value for the configuration key in the WizardResult |
|
762 | + * as well as in the Configuration instance |
|
763 | + * @param string $key the configuration key |
|
764 | + * @param string $value the (detected) value |
|
765 | + * |
|
766 | + */ |
|
767 | + private function applyFind($key, $value) { |
|
768 | + $this->result->addChange($key, $value); |
|
769 | + $this->configuration->setConfiguration([$key => $value]); |
|
770 | + } |
|
771 | + |
|
772 | + /** |
|
773 | + * Checks, whether a port was entered in the Host configuration |
|
774 | + * field. In this case the port will be stripped off, but also stored as |
|
775 | + * setting. |
|
776 | + */ |
|
777 | + private function checkHost() { |
|
778 | + $host = $this->configuration->ldapHost; |
|
779 | + $hostInfo = parse_url($host); |
|
780 | + |
|
781 | + //removes Port from Host |
|
782 | + if(is_array($hostInfo) && isset($hostInfo['port'])) { |
|
783 | + $port = $hostInfo['port']; |
|
784 | + $host = str_replace(':'.$port, '', $host); |
|
785 | + $this->applyFind('ldap_host', $host); |
|
786 | + $this->applyFind('ldap_port', $port); |
|
787 | + } |
|
788 | + } |
|
789 | + |
|
790 | + /** |
|
791 | + * tries to detect the group member association attribute which is |
|
792 | + * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber' |
|
793 | + * @return string|false, string with the attribute name, false on error |
|
794 | + * @throws \Exception |
|
795 | + */ |
|
796 | + private function detectGroupMemberAssoc() { |
|
797 | + $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber']; |
|
798 | + $filter = $this->configuration->ldapGroupFilter; |
|
799 | + if(empty($filter)) { |
|
800 | + return false; |
|
801 | + } |
|
802 | + $cr = $this->getConnection(); |
|
803 | + if(!$cr) { |
|
804 | + throw new \Exception('Could not connect to LDAP'); |
|
805 | + } |
|
806 | + $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0]; |
|
807 | + $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000); |
|
808 | + if(!$this->ldap->isResource($rr)) { |
|
809 | + return false; |
|
810 | + } |
|
811 | + $er = $this->ldap->firstEntry($cr, $rr); |
|
812 | + while(is_resource($er)) { |
|
813 | + $this->ldap->getDN($cr, $er); |
|
814 | + $attrs = $this->ldap->getAttributes($cr, $er); |
|
815 | + $result = []; |
|
816 | + $possibleAttrsCount = count($possibleAttrs); |
|
817 | + for($i = 0; $i < $possibleAttrsCount; $i++) { |
|
818 | + if(isset($attrs[$possibleAttrs[$i]])) { |
|
819 | + $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count']; |
|
820 | + } |
|
821 | + } |
|
822 | + if(!empty($result)) { |
|
823 | + natsort($result); |
|
824 | + return key($result); |
|
825 | + } |
|
826 | + |
|
827 | + $er = $this->ldap->nextEntry($cr, $er); |
|
828 | + } |
|
829 | + |
|
830 | + return false; |
|
831 | + } |
|
832 | + |
|
833 | + /** |
|
834 | + * Checks whether for a given BaseDN results will be returned |
|
835 | + * @param string $base the BaseDN to test |
|
836 | + * @return bool true on success, false otherwise |
|
837 | + * @throws \Exception |
|
838 | + */ |
|
839 | + private function testBaseDN($base) { |
|
840 | + $cr = $this->getConnection(); |
|
841 | + if(!$cr) { |
|
842 | + throw new \Exception('Could not connect to LDAP'); |
|
843 | + } |
|
844 | + |
|
845 | + //base is there, let's validate it. If we search for anything, we should |
|
846 | + //get a result set > 0 on a proper base |
|
847 | + $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1); |
|
848 | + if(!$this->ldap->isResource($rr)) { |
|
849 | + $errorNo = $this->ldap->errno($cr); |
|
850 | + $errorMsg = $this->ldap->error($cr); |
|
851 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base. |
|
852 | + ' Error '.$errorNo.': '.$errorMsg, ILogger::INFO); |
|
853 | + return false; |
|
854 | + } |
|
855 | + $entries = $this->ldap->countEntries($cr, $rr); |
|
856 | + return ($entries !== false) && ($entries > 0); |
|
857 | + } |
|
858 | + |
|
859 | + /** |
|
860 | + * Checks whether the server supports memberOf in LDAP Filter. |
|
861 | + * Note: at least in OpenLDAP, availability of memberOf is dependent on |
|
862 | + * a configured objectClass. I.e. not necessarily for all available groups |
|
863 | + * memberOf does work. |
|
864 | + * |
|
865 | + * @return bool true if it does, false otherwise |
|
866 | + * @throws \Exception |
|
867 | + */ |
|
868 | + private function testMemberOf() { |
|
869 | + $cr = $this->getConnection(); |
|
870 | + if(!$cr) { |
|
871 | + throw new \Exception('Could not connect to LDAP'); |
|
872 | + } |
|
873 | + $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1); |
|
874 | + if(is_int($result) && $result > 0) { |
|
875 | + return true; |
|
876 | + } |
|
877 | + return false; |
|
878 | + } |
|
879 | + |
|
880 | + /** |
|
881 | + * creates an LDAP Filter from given configuration |
|
882 | + * @param integer $filterType int, for which use case the filter shall be created |
|
883 | + * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or |
|
884 | + * self::LFILTER_GROUP_LIST |
|
885 | + * @return string|false string with the filter on success, false otherwise |
|
886 | + * @throws \Exception |
|
887 | + */ |
|
888 | + private function composeLdapFilter($filterType) { |
|
889 | + $filter = ''; |
|
890 | + $parts = 0; |
|
891 | + switch ($filterType) { |
|
892 | + case self::LFILTER_USER_LIST: |
|
893 | + $objcs = $this->configuration->ldapUserFilterObjectclass; |
|
894 | + //glue objectclasses |
|
895 | + if(is_array($objcs) && count($objcs) > 0) { |
|
896 | + $filter .= '(|'; |
|
897 | + foreach($objcs as $objc) { |
|
898 | + $filter .= '(objectclass=' . $objc . ')'; |
|
899 | + } |
|
900 | + $filter .= ')'; |
|
901 | + $parts++; |
|
902 | + } |
|
903 | + //glue group memberships |
|
904 | + if($this->configuration->hasMemberOfFilterSupport) { |
|
905 | + $cns = $this->configuration->ldapUserFilterGroups; |
|
906 | + if(is_array($cns) && count($cns) > 0) { |
|
907 | + $filter .= '(|'; |
|
908 | + $cr = $this->getConnection(); |
|
909 | + if(!$cr) { |
|
910 | + throw new \Exception('Could not connect to LDAP'); |
|
911 | + } |
|
912 | + $base = $this->configuration->ldapBase[0]; |
|
913 | + foreach($cns as $cn) { |
|
914 | + $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']); |
|
915 | + if(!$this->ldap->isResource($rr)) { |
|
916 | + continue; |
|
917 | + } |
|
918 | + $er = $this->ldap->firstEntry($cr, $rr); |
|
919 | + $attrs = $this->ldap->getAttributes($cr, $er); |
|
920 | + $dn = $this->ldap->getDN($cr, $er); |
|
921 | + if ($dn === false || $dn === '') { |
|
922 | + continue; |
|
923 | + } |
|
924 | + $filterPart = '(memberof=' . $dn . ')'; |
|
925 | + if(isset($attrs['primaryGroupToken'])) { |
|
926 | + $pgt = $attrs['primaryGroupToken'][0]; |
|
927 | + $primaryFilterPart = '(primaryGroupID=' . $pgt .')'; |
|
928 | + $filterPart = '(|' . $filterPart . $primaryFilterPart . ')'; |
|
929 | + } |
|
930 | + $filter .= $filterPart; |
|
931 | + } |
|
932 | + $filter .= ')'; |
|
933 | + } |
|
934 | + $parts++; |
|
935 | + } |
|
936 | + //wrap parts in AND condition |
|
937 | + if($parts > 1) { |
|
938 | + $filter = '(&' . $filter . ')'; |
|
939 | + } |
|
940 | + if ($filter === '') { |
|
941 | + $filter = '(objectclass=*)'; |
|
942 | + } |
|
943 | + break; |
|
944 | + |
|
945 | + case self::LFILTER_GROUP_LIST: |
|
946 | + $objcs = $this->configuration->ldapGroupFilterObjectclass; |
|
947 | + //glue objectclasses |
|
948 | + if(is_array($objcs) && count($objcs) > 0) { |
|
949 | + $filter .= '(|'; |
|
950 | + foreach($objcs as $objc) { |
|
951 | + $filter .= '(objectclass=' . $objc . ')'; |
|
952 | + } |
|
953 | + $filter .= ')'; |
|
954 | + $parts++; |
|
955 | + } |
|
956 | + //glue group memberships |
|
957 | + $cns = $this->configuration->ldapGroupFilterGroups; |
|
958 | + if(is_array($cns) && count($cns) > 0) { |
|
959 | + $filter .= '(|'; |
|
960 | + foreach($cns as $cn) { |
|
961 | + $filter .= '(cn=' . $cn . ')'; |
|
962 | + } |
|
963 | + $filter .= ')'; |
|
964 | + } |
|
965 | + $parts++; |
|
966 | + //wrap parts in AND condition |
|
967 | + if($parts > 1) { |
|
968 | + $filter = '(&' . $filter . ')'; |
|
969 | + } |
|
970 | + break; |
|
971 | + |
|
972 | + case self::LFILTER_LOGIN: |
|
973 | + $ulf = $this->configuration->ldapUserFilter; |
|
974 | + $loginpart = '=%uid'; |
|
975 | + $filterUsername = ''; |
|
976 | + $userAttributes = $this->getUserAttributes(); |
|
977 | + $userAttributes = array_change_key_case(array_flip($userAttributes)); |
|
978 | + $parts = 0; |
|
979 | + |
|
980 | + if($this->configuration->ldapLoginFilterUsername === '1') { |
|
981 | + $attr = ''; |
|
982 | + if(isset($userAttributes['uid'])) { |
|
983 | + $attr = 'uid'; |
|
984 | + } else if(isset($userAttributes['samaccountname'])) { |
|
985 | + $attr = 'samaccountname'; |
|
986 | + } else if(isset($userAttributes['cn'])) { |
|
987 | + //fallback |
|
988 | + $attr = 'cn'; |
|
989 | + } |
|
990 | + if ($attr !== '') { |
|
991 | + $filterUsername = '(' . $attr . $loginpart . ')'; |
|
992 | + $parts++; |
|
993 | + } |
|
994 | + } |
|
995 | + |
|
996 | + $filterEmail = ''; |
|
997 | + if($this->configuration->ldapLoginFilterEmail === '1') { |
|
998 | + $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))'; |
|
999 | + $parts++; |
|
1000 | + } |
|
1001 | + |
|
1002 | + $filterAttributes = ''; |
|
1003 | + $attrsToFilter = $this->configuration->ldapLoginFilterAttributes; |
|
1004 | + if(is_array($attrsToFilter) && count($attrsToFilter) > 0) { |
|
1005 | + $filterAttributes = '(|'; |
|
1006 | + foreach($attrsToFilter as $attribute) { |
|
1007 | + $filterAttributes .= '(' . $attribute . $loginpart . ')'; |
|
1008 | + } |
|
1009 | + $filterAttributes .= ')'; |
|
1010 | + $parts++; |
|
1011 | + } |
|
1012 | + |
|
1013 | + $filterLogin = ''; |
|
1014 | + if($parts > 1) { |
|
1015 | + $filterLogin = '(|'; |
|
1016 | + } |
|
1017 | + $filterLogin .= $filterUsername; |
|
1018 | + $filterLogin .= $filterEmail; |
|
1019 | + $filterLogin .= $filterAttributes; |
|
1020 | + if($parts > 1) { |
|
1021 | + $filterLogin .= ')'; |
|
1022 | + } |
|
1023 | + |
|
1024 | + $filter = '(&'.$ulf.$filterLogin.')'; |
|
1025 | + break; |
|
1026 | + } |
|
1027 | + |
|
1028 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG); |
|
1029 | + |
|
1030 | + return $filter; |
|
1031 | + } |
|
1032 | + |
|
1033 | + /** |
|
1034 | + * Connects and Binds to an LDAP Server |
|
1035 | + * |
|
1036 | + * @param int $port the port to connect with |
|
1037 | + * @param bool $tls whether startTLS is to be used |
|
1038 | + * @return bool |
|
1039 | + * @throws \Exception |
|
1040 | + */ |
|
1041 | + private function connectAndBind($port, $tls) { |
|
1042 | + //connect, does not really trigger any server communication |
|
1043 | + $host = $this->configuration->ldapHost; |
|
1044 | + $hostInfo = parse_url($host); |
|
1045 | + if(!$hostInfo) { |
|
1046 | + throw new \Exception(self::$l->t('Invalid Host')); |
|
1047 | + } |
|
1048 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG); |
|
1049 | + $cr = $this->ldap->connect($host, $port); |
|
1050 | + if(!is_resource($cr)) { |
|
1051 | + throw new \Exception(self::$l->t('Invalid Host')); |
|
1052 | + } |
|
1053 | + |
|
1054 | + //set LDAP options |
|
1055 | + $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1056 | + $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1057 | + $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1058 | + |
|
1059 | + try { |
|
1060 | + if($tls) { |
|
1061 | + $isTlsWorking = @$this->ldap->startTls($cr); |
|
1062 | + if(!$isTlsWorking) { |
|
1063 | + return false; |
|
1064 | + } |
|
1065 | + } |
|
1066 | + |
|
1067 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG); |
|
1068 | + //interesting part: do the bind! |
|
1069 | + $login = $this->ldap->bind($cr, |
|
1070 | + $this->configuration->ldapAgentName, |
|
1071 | + $this->configuration->ldapAgentPassword |
|
1072 | + ); |
|
1073 | + $errNo = $this->ldap->errno($cr); |
|
1074 | + $error = ldap_error($cr); |
|
1075 | + $this->ldap->unbind($cr); |
|
1076 | + } catch(ServerNotAvailableException $e) { |
|
1077 | + return false; |
|
1078 | + } |
|
1079 | + |
|
1080 | + if($login === true) { |
|
1081 | + $this->ldap->unbind($cr); |
|
1082 | + \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG); |
|
1083 | + return true; |
|
1084 | + } |
|
1085 | + |
|
1086 | + if($errNo === -1) { |
|
1087 | + //host, port or TLS wrong |
|
1088 | + return false; |
|
1089 | + } |
|
1090 | + throw new \Exception($error, $errNo); |
|
1091 | + } |
|
1092 | + |
|
1093 | + /** |
|
1094 | + * checks whether a valid combination of agent and password has been |
|
1095 | + * provided (either two values or nothing for anonymous connect) |
|
1096 | + * @return bool, true if everything is fine, false otherwise |
|
1097 | + */ |
|
1098 | + private function checkAgentRequirements() { |
|
1099 | + $agent = $this->configuration->ldapAgentName; |
|
1100 | + $pwd = $this->configuration->ldapAgentPassword; |
|
1101 | + |
|
1102 | + return |
|
1103 | + ($agent !== '' && $pwd !== '') |
|
1104 | + || ($agent === '' && $pwd === '') |
|
1105 | + ; |
|
1106 | + } |
|
1107 | + |
|
1108 | + /** |
|
1109 | + * @param array $reqs |
|
1110 | + * @return bool |
|
1111 | + */ |
|
1112 | + private function checkRequirements($reqs) { |
|
1113 | + $this->checkAgentRequirements(); |
|
1114 | + foreach($reqs as $option) { |
|
1115 | + $value = $this->configuration->$option; |
|
1116 | + if(empty($value)) { |
|
1117 | + return false; |
|
1118 | + } |
|
1119 | + } |
|
1120 | + return true; |
|
1121 | + } |
|
1122 | + |
|
1123 | + /** |
|
1124 | + * does a cumulativeSearch on LDAP to get different values of a |
|
1125 | + * specified attribute |
|
1126 | + * @param string[] $filters array, the filters that shall be used in the search |
|
1127 | + * @param string $attr the attribute of which a list of values shall be returned |
|
1128 | + * @param int $dnReadLimit the amount of how many DNs should be analyzed. |
|
1129 | + * The lower, the faster |
|
1130 | + * @param string $maxF string. if not null, this variable will have the filter that |
|
1131 | + * yields most result entries |
|
1132 | + * @return array|false an array with the values on success, false otherwise |
|
1133 | + */ |
|
1134 | + public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) { |
|
1135 | + $dnRead = []; |
|
1136 | + $foundItems = []; |
|
1137 | + $maxEntries = 0; |
|
1138 | + if(!is_array($this->configuration->ldapBase) |
|
1139 | + || !isset($this->configuration->ldapBase[0])) { |
|
1140 | + return false; |
|
1141 | + } |
|
1142 | + $base = $this->configuration->ldapBase[0]; |
|
1143 | + $cr = $this->getConnection(); |
|
1144 | + if(!$this->ldap->isResource($cr)) { |
|
1145 | + return false; |
|
1146 | + } |
|
1147 | + $lastFilter = null; |
|
1148 | + if(isset($filters[count($filters)-1])) { |
|
1149 | + $lastFilter = $filters[count($filters)-1]; |
|
1150 | + } |
|
1151 | + foreach($filters as $filter) { |
|
1152 | + if($lastFilter === $filter && count($foundItems) > 0) { |
|
1153 | + //skip when the filter is a wildcard and results were found |
|
1154 | + continue; |
|
1155 | + } |
|
1156 | + // 20k limit for performance and reason |
|
1157 | + $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000); |
|
1158 | + if(!$this->ldap->isResource($rr)) { |
|
1159 | + continue; |
|
1160 | + } |
|
1161 | + $entries = $this->ldap->countEntries($cr, $rr); |
|
1162 | + $getEntryFunc = 'firstEntry'; |
|
1163 | + if(($entries !== false) && ($entries > 0)) { |
|
1164 | + if(!is_null($maxF) && $entries > $maxEntries) { |
|
1165 | + $maxEntries = $entries; |
|
1166 | + $maxF = $filter; |
|
1167 | + } |
|
1168 | + $dnReadCount = 0; |
|
1169 | + do { |
|
1170 | + $entry = $this->ldap->$getEntryFunc($cr, $rr); |
|
1171 | + $getEntryFunc = 'nextEntry'; |
|
1172 | + if(!$this->ldap->isResource($entry)) { |
|
1173 | + continue 2; |
|
1174 | + } |
|
1175 | + $rr = $entry; //will be expected by nextEntry next round |
|
1176 | + $attributes = $this->ldap->getAttributes($cr, $entry); |
|
1177 | + $dn = $this->ldap->getDN($cr, $entry); |
|
1178 | + if($dn === false || in_array($dn, $dnRead)) { |
|
1179 | + continue; |
|
1180 | + } |
|
1181 | + $newItems = []; |
|
1182 | + $state = $this->getAttributeValuesFromEntry($attributes, |
|
1183 | + $attr, |
|
1184 | + $newItems); |
|
1185 | + $dnReadCount++; |
|
1186 | + $foundItems = array_merge($foundItems, $newItems); |
|
1187 | + $this->resultCache[$dn][$attr] = $newItems; |
|
1188 | + $dnRead[] = $dn; |
|
1189 | + } while(($state === self::LRESULT_PROCESSED_SKIP |
|
1190 | + || $this->ldap->isResource($entry)) |
|
1191 | + && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit)); |
|
1192 | + } |
|
1193 | + } |
|
1194 | + |
|
1195 | + return array_unique($foundItems); |
|
1196 | + } |
|
1197 | + |
|
1198 | + /** |
|
1199 | + * determines if and which $attr are available on the LDAP server |
|
1200 | + * @param string[] $objectclasses the objectclasses to use as search filter |
|
1201 | + * @param string $attr the attribute to look for |
|
1202 | + * @param string $dbkey the dbkey of the setting the feature is connected to |
|
1203 | + * @param string $confkey the confkey counterpart for the $dbkey as used in the |
|
1204 | + * Configuration class |
|
1205 | + * @param bool $po whether the objectClass with most result entries |
|
1206 | + * shall be pre-selected via the result |
|
1207 | + * @return array|false list of found items. |
|
1208 | + * @throws \Exception |
|
1209 | + */ |
|
1210 | + private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) { |
|
1211 | + $cr = $this->getConnection(); |
|
1212 | + if(!$cr) { |
|
1213 | + throw new \Exception('Could not connect to LDAP'); |
|
1214 | + } |
|
1215 | + $p = 'objectclass='; |
|
1216 | + foreach($objectclasses as $key => $value) { |
|
1217 | + $objectclasses[$key] = $p.$value; |
|
1218 | + } |
|
1219 | + $maxEntryObjC = ''; |
|
1220 | + |
|
1221 | + //how deep to dig? |
|
1222 | + //When looking for objectclasses, testing few entries is sufficient, |
|
1223 | + $dig = 3; |
|
1224 | + |
|
1225 | + $availableFeatures = |
|
1226 | + $this->cumulativeSearchOnAttribute($objectclasses, $attr, |
|
1227 | + $dig, $maxEntryObjC); |
|
1228 | + if(is_array($availableFeatures) |
|
1229 | + && count($availableFeatures) > 0) { |
|
1230 | + natcasesort($availableFeatures); |
|
1231 | + //natcasesort keeps indices, but we must get rid of them for proper |
|
1232 | + //sorting in the web UI. Therefore: array_values |
|
1233 | + $this->result->addOptions($dbkey, array_values($availableFeatures)); |
|
1234 | + } else { |
|
1235 | + throw new \Exception(self::$l->t('Could not find the desired feature')); |
|
1236 | + } |
|
1237 | + |
|
1238 | + $setFeatures = $this->configuration->$confkey; |
|
1239 | + if(is_array($setFeatures) && !empty($setFeatures)) { |
|
1240 | + //something is already configured? pre-select it. |
|
1241 | + $this->result->addChange($dbkey, $setFeatures); |
|
1242 | + } else if ($po && $maxEntryObjC !== '') { |
|
1243 | + //pre-select objectclass with most result entries |
|
1244 | + $maxEntryObjC = str_replace($p, '', $maxEntryObjC); |
|
1245 | + $this->applyFind($dbkey, $maxEntryObjC); |
|
1246 | + $this->result->addChange($dbkey, $maxEntryObjC); |
|
1247 | + } |
|
1248 | + |
|
1249 | + return $availableFeatures; |
|
1250 | + } |
|
1251 | + |
|
1252 | + /** |
|
1253 | + * appends a list of values fr |
|
1254 | + * @param resource $result the return value from ldap_get_attributes |
|
1255 | + * @param string $attribute the attribute values to look for |
|
1256 | + * @param array &$known new values will be appended here |
|
1257 | + * @return int, state on of the class constants LRESULT_PROCESSED_OK, |
|
1258 | + * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP |
|
1259 | + */ |
|
1260 | + private function getAttributeValuesFromEntry($result, $attribute, &$known) { |
|
1261 | + if(!is_array($result) |
|
1262 | + || !isset($result['count']) |
|
1263 | + || !$result['count'] > 0) { |
|
1264 | + return self::LRESULT_PROCESSED_INVALID; |
|
1265 | + } |
|
1266 | + |
|
1267 | + // strtolower on all keys for proper comparison |
|
1268 | + $result = \OCP\Util::mb_array_change_key_case($result); |
|
1269 | + $attribute = strtolower($attribute); |
|
1270 | + if(isset($result[$attribute])) { |
|
1271 | + foreach($result[$attribute] as $key => $val) { |
|
1272 | + if($key === 'count') { |
|
1273 | + continue; |
|
1274 | + } |
|
1275 | + if(!in_array($val, $known)) { |
|
1276 | + $known[] = $val; |
|
1277 | + } |
|
1278 | + } |
|
1279 | + return self::LRESULT_PROCESSED_OK; |
|
1280 | + } else { |
|
1281 | + return self::LRESULT_PROCESSED_SKIP; |
|
1282 | + } |
|
1283 | + } |
|
1284 | + |
|
1285 | + /** |
|
1286 | + * @return bool|mixed |
|
1287 | + */ |
|
1288 | + private function getConnection() { |
|
1289 | + if(!is_null($this->cr)) { |
|
1290 | + return $this->cr; |
|
1291 | + } |
|
1292 | + |
|
1293 | + $cr = $this->ldap->connect( |
|
1294 | + $this->configuration->ldapHost, |
|
1295 | + $this->configuration->ldapPort |
|
1296 | + ); |
|
1297 | + |
|
1298 | + $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3); |
|
1299 | + $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0); |
|
1300 | + $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT); |
|
1301 | + if($this->configuration->ldapTLS === 1) { |
|
1302 | + $this->ldap->startTls($cr); |
|
1303 | + } |
|
1304 | + |
|
1305 | + $lo = @$this->ldap->bind($cr, |
|
1306 | + $this->configuration->ldapAgentName, |
|
1307 | + $this->configuration->ldapAgentPassword); |
|
1308 | + if($lo === true) { |
|
1309 | + $this->$cr = $cr; |
|
1310 | + return $cr; |
|
1311 | + } |
|
1312 | + |
|
1313 | + return false; |
|
1314 | + } |
|
1315 | + |
|
1316 | + /** |
|
1317 | + * @return array |
|
1318 | + */ |
|
1319 | + private function getDefaultLdapPortSettings() { |
|
1320 | + static $settings = [ |
|
1321 | + ['port' => 7636, 'tls' => false], |
|
1322 | + ['port' => 636, 'tls' => false], |
|
1323 | + ['port' => 7389, 'tls' => true], |
|
1324 | + ['port' => 389, 'tls' => true], |
|
1325 | + ['port' => 7389, 'tls' => false], |
|
1326 | + ['port' => 389, 'tls' => false], |
|
1327 | + ]; |
|
1328 | + return $settings; |
|
1329 | + } |
|
1330 | + |
|
1331 | + /** |
|
1332 | + * @return array |
|
1333 | + */ |
|
1334 | + private function getPortSettingsToTry() { |
|
1335 | + //389 ← LDAP / Unencrypted or StartTLS |
|
1336 | + //636 ← LDAPS / SSL |
|
1337 | + //7xxx ← UCS. need to be checked first, because both ports may be open |
|
1338 | + $host = $this->configuration->ldapHost; |
|
1339 | + $port = (int)$this->configuration->ldapPort; |
|
1340 | + $portSettings = []; |
|
1341 | + |
|
1342 | + //In case the port is already provided, we will check this first |
|
1343 | + if($port > 0) { |
|
1344 | + $hostInfo = parse_url($host); |
|
1345 | + if(!(is_array($hostInfo) |
|
1346 | + && isset($hostInfo['scheme']) |
|
1347 | + && stripos($hostInfo['scheme'], 'ldaps') !== false)) { |
|
1348 | + $portSettings[] = ['port' => $port, 'tls' => true]; |
|
1349 | + } |
|
1350 | + $portSettings[] =['port' => $port, 'tls' => false]; |
|
1351 | + } |
|
1352 | + |
|
1353 | + //default ports |
|
1354 | + $portSettings = array_merge($portSettings, |
|
1355 | + $this->getDefaultLdapPortSettings()); |
|
1356 | + |
|
1357 | + return $portSettings; |
|
1358 | + } |
|
1359 | 1359 | |
1360 | 1360 | |
1361 | 1361 | } |