Total Complexity | 116 |
Total Lines | 886 |
Duplicated Lines | 0 % |
Changes | 8 | ||
Bugs | 1 | Features | 1 |
Complex classes like Ldap often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Ldap, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
34 | class Ldap |
||
35 | { |
||
36 | /** |
||
37 | * LDAP link identifier. |
||
38 | * |
||
39 | * @var resource |
||
40 | */ |
||
41 | protected $ldap; |
||
42 | |||
43 | /** |
||
44 | * LDAP user: authz_id if SASL is in use, binding dn otherwise |
||
45 | * |
||
46 | * @var string|null |
||
47 | */ |
||
48 | protected $authz_id = null; |
||
49 | |||
50 | /** |
||
51 | * Timeout value, in seconds. |
||
52 | * |
||
53 | * @var int |
||
54 | */ |
||
55 | protected $timeout = 0; |
||
56 | |||
57 | /** |
||
58 | * Private constructor restricts instantiation to getInstance(). |
||
59 | * |
||
60 | * @param string $hostname |
||
61 | * @param bool $enable_tls |
||
62 | * @param bool $debug |
||
63 | * @param int $timeout |
||
64 | * @param int $port |
||
65 | * @param bool $referrals |
||
66 | * @psalm-suppress NullArgument |
||
67 | */ |
||
68 | public function __construct( |
||
69 | $hostname, |
||
70 | $enable_tls = true, |
||
71 | $debug = false, |
||
72 | $timeout = 0, |
||
73 | $port = 389, |
||
74 | $referrals = true |
||
75 | ) { |
||
76 | // Debug |
||
77 | Logger::debug('Library - LDAP __construct(): Setup LDAP with '. |
||
78 | 'host=\''.$hostname. |
||
79 | '\', tls='.var_export($enable_tls, true). |
||
80 | ', debug='.var_export($debug, true). |
||
81 | ', timeout='.var_export($timeout, true). |
||
82 | ', referrals='.var_export($referrals, true)); |
||
83 | |||
84 | /* |
||
85 | * Set debug level before calling connect. Note that this passes |
||
86 | * NULL to ldap_set_option, which is an undocumented feature. |
||
87 | * |
||
88 | * OpenLDAP 2.x.x or Netscape Directory SDK x.x needed for this option. |
||
89 | */ |
||
90 | if ($debug && !ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7)) { |
||
91 | Logger::warning('Library - LDAP __construct(): Unable to set debug level (LDAP_OPT_DEBUG_LEVEL) to 7'); |
||
92 | } |
||
93 | |||
94 | /* |
||
95 | * Prepare a connection for to this LDAP server. Note that this function |
||
96 | * doesn't actually connect to the server. |
||
97 | */ |
||
98 | $resource = @ldap_connect($hostname, $port); |
||
99 | if ($resource === false) { |
||
100 | throw $this->makeException( |
||
101 | 'Library - LDAP __construct(): Unable to connect to \''.$hostname.'\'', |
||
102 | ERR_INTERNAL |
||
103 | ); |
||
104 | } |
||
105 | $this->ldap = $resource; |
||
106 | |||
107 | // Enable LDAP protocol version 3 |
||
108 | if (!@ldap_set_option($this->ldap, LDAP_OPT_PROTOCOL_VERSION, 3)) { |
||
109 | throw $this->makeException( |
||
110 | 'Library - LDAP __construct(): Failed to set LDAP Protocol version (LDAP_OPT_PROTOCOL_VERSION) to 3', |
||
111 | ERR_INTERNAL |
||
112 | ); |
||
113 | } |
||
114 | |||
115 | // Set referral option |
||
116 | if (!@ldap_set_option($this->ldap, LDAP_OPT_REFERRALS, $referrals)) { |
||
117 | throw $this->makeException( |
||
118 | 'Library - LDAP __construct(): Failed to set LDAP Referrals (LDAP_OPT_REFERRALS) to '.$referrals, |
||
119 | ERR_INTERNAL |
||
120 | ); |
||
121 | } |
||
122 | |||
123 | // Set timeouts, if supported |
||
124 | // (OpenLDAP 2.x.x or Netscape Directory SDK x.x needed) |
||
125 | $this->timeout = $timeout; |
||
126 | if ($timeout > 0) { |
||
127 | if (!@ldap_set_option($this->ldap, LDAP_OPT_NETWORK_TIMEOUT, $timeout)) { |
||
128 | Logger::warning( |
||
129 | 'Library - LDAP __construct(): Unable to set timeouts (LDAP_OPT_NETWORK_TIMEOUT) to '.$timeout |
||
130 | ); |
||
131 | } |
||
132 | if (!@ldap_set_option($this->ldap, LDAP_OPT_TIMELIMIT, $timeout)) { |
||
133 | Logger::warning( |
||
134 | 'Library - LDAP __construct(): Unable to set timeouts (LDAP_OPT_TIMELIMIT) to '.$timeout |
||
135 | ); |
||
136 | } |
||
137 | } |
||
138 | |||
139 | // Enable TLS, if needed |
||
140 | if (stripos($hostname, "ldaps:") === false && $enable_tls) { |
||
141 | if (!@ldap_start_tls($this->ldap)) { |
||
142 | throw $this->makeException('Library - LDAP __construct():'. |
||
143 | ' Unable to force TLS', ERR_INTERNAL); |
||
144 | } |
||
145 | } |
||
146 | } |
||
147 | |||
148 | |||
149 | /** |
||
150 | * Convenience method to create an LDAPException as well as log the |
||
151 | * description. |
||
152 | * |
||
153 | * @param string $description The exception's description |
||
154 | * @param int|null $type The exception's type |
||
155 | * @return \Exception |
||
156 | */ |
||
157 | private function makeException($description, $type = null) |
||
158 | { |
||
159 | $errNo = @ldap_errno($this->ldap); |
||
160 | |||
161 | // Decide exception type and return |
||
162 | if ($type !== null) { |
||
163 | if ($errNo !== 0) { |
||
164 | // Only log real LDAP errors; not success |
||
165 | Logger::error($description.'; cause: \''.ldap_error($this->ldap).'\' (0x'.dechex($errNo).')'); |
||
166 | } else { |
||
167 | Logger::error($description); |
||
168 | } |
||
169 | |||
170 | switch ($type) { |
||
171 | case ERR_INTERNAL:// 1 - ExInternal |
||
172 | return new Error\Exception($description, $errNo); |
||
173 | case ERR_NO_USER:// 2 - ExUserNotFound |
||
174 | return new Error\UserNotFound($description, $errNo); |
||
175 | case ERR_WRONG_PW:// 3 - ExInvalidCredential |
||
176 | return new Error\InvalidCredential($description, $errNo); |
||
177 | case ERR_AS_DATA_INCONSIST:// 4 - ExAsDataInconsist |
||
178 | return new Error\AuthSource('ldap', $description); |
||
179 | case ERR_AS_INTERNAL:// 5 - ExAsInternal |
||
180 | return new Error\AuthSource('ldap', $description); |
||
181 | } |
||
182 | } else { |
||
183 | if ($errNo !== 0) { |
||
184 | $description .= '; cause: \''.ldap_error($this->ldap).'\' (0x'.dechex($errNo).')'; |
||
185 | if (@ldap_get_option($this->ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extendedError) |
||
186 | && !empty($extendedError) |
||
187 | ) { |
||
188 | $description .= '; additional: \''.$extendedError.'\''; |
||
189 | } |
||
190 | } |
||
191 | switch ($errNo) { |
||
192 | case 0x20://LDAP_NO_SUCH_OBJECT |
||
193 | Logger::warning($description); |
||
194 | return new Error\UserNotFound($description, $errNo); |
||
195 | case 0x31://LDAP_INVALID_CREDENTIALS |
||
196 | Logger::info($description); |
||
197 | return new Error\InvalidCredential($description, $errNo); |
||
198 | case -1://NO_SERVER_CONNECTION |
||
199 | Logger::error($description); |
||
200 | return new Error\AuthSource('ldap', $description); |
||
201 | default: |
||
202 | Logger::error($description); |
||
203 | return new Error\AuthSource('ldap', $description); |
||
204 | } |
||
205 | } |
||
206 | return new \Exception('Unknown LDAP error.'); |
||
207 | } |
||
208 | |||
209 | |||
210 | /** |
||
211 | * Search for DN from a single base. |
||
212 | * |
||
213 | * @param string $base |
||
214 | * Indication of root of subtree to search |
||
215 | * @param string|array $attribute |
||
216 | * The attribute name(s) to search for. |
||
217 | * @param string $value |
||
218 | * The attribute value to search for. |
||
219 | * Additional search filter |
||
220 | * @param string|null $searchFilter |
||
221 | * The scope of the search |
||
222 | * @param string $scope |
||
223 | * @return string |
||
224 | * The DN of the resulting found element. |
||
225 | * @throws Error\Exception if: |
||
226 | * - Attribute parameter is wrong type |
||
227 | * @throws Error\AuthSource if: |
||
228 | * - Not able to connect to LDAP server |
||
229 | * - False search result |
||
230 | * - Count return false |
||
231 | * - Searche found more than one result |
||
232 | * - Failed to get first entry from result |
||
233 | * - Failed to get DN for entry |
||
234 | * @throws Error\UserNotFound if: |
||
235 | * - Zero entries were found |
||
236 | * @psalm-suppress TypeDoesNotContainType |
||
237 | */ |
||
238 | private function search($base, $attribute, $value, $searchFilter = null, $scope = "subtree") |
||
308 | } |
||
309 | |||
310 | |||
311 | /** |
||
312 | * Search for a DN. |
||
313 | * |
||
314 | * @param string|array $base |
||
315 | * The base, or bases, which to search from. |
||
316 | * @param string|array $attribute |
||
317 | * The attribute name(s) searched for. |
||
318 | * @param string $value |
||
319 | * The attribute value searched for. |
||
320 | * @param bool $allowZeroHits |
||
321 | * Determines if the method will throw an exception if no hits are found. |
||
322 | * Defaults to FALSE. |
||
323 | * @param string|null $searchFilter |
||
324 | * Additional searchFilter to be added to the (attribute=value) filter |
||
325 | * @param string $scope |
||
326 | * The scope of the search |
||
327 | * @return string|null |
||
328 | * The DN of the matching element, if found. If no element was found and |
||
329 | * $allowZeroHits is set to FALSE, an exception will be thrown; otherwise |
||
330 | * NULL will be returned. |
||
331 | * @throws Error\AuthSource if: |
||
332 | * - LDAP search encounter some problems when searching cataloge |
||
333 | * - Not able to connect to LDAP server |
||
334 | * @throws Error\UserNotFound if: |
||
335 | * - $allowZeroHits is FALSE and no result is found |
||
336 | * |
||
337 | */ |
||
338 | public function searchfordn( |
||
371 | } |
||
372 | } |
||
373 | |||
374 | |||
375 | /** |
||
376 | * This method was created specifically for the ldap:AttributeAddUsersGroups->searchActiveDirectory() |
||
377 | * method, but could be used for other LDAP search needs. It will search LDAP and return all the entries. |
||
378 | * |
||
379 | * @throws \Exception |
||
380 | * @param string|array $bases |
||
381 | * @param string|array $filters Array of 'attribute' => 'values' to be combined into the filter, |
||
382 | * or a raw filter string |
||
383 | * @param string|array $attributes Array of attributes requested from LDAP |
||
384 | * @param bool $and If multiple filters defined, then either bind them with & or | |
||
385 | * @param bool $escape Weather to escape the filter values or not |
||
386 | * @param string $scope The scope of the search |
||
387 | * @return array |
||
388 | */ |
||
389 | public function searchformultiple( |
||
494 | } |
||
495 | |||
496 | |||
497 | /** |
||
498 | * Bind to LDAP with a specific DN and password. Simple wrapper around |
||
499 | * ldap_bind() with some additional logging. |
||
500 | * |
||
501 | * @param string $dn |
||
502 | * The DN used. |
||
503 | * @param string $password |
||
504 | * The password used. |
||
505 | * @param array $sasl_args |
||
506 | * Array of SASL options for SASL bind |
||
507 | * @return bool |
||
508 | * Returns TRUE if successful, FALSE if |
||
509 | * LDAP_INVALID_CREDENTIALS, LDAP_X_PROXY_AUTHZ_FAILURE, |
||
510 | * LDAP_INAPPROPRIATE_AUTH, LDAP_INSUFFICIENT_ACCESS |
||
511 | * @throws Error\Exception on other errors |
||
512 | */ |
||
513 | public function bind($dn, $password, array $sasl_args = null) |
||
514 | { |
||
515 | if ($sasl_args != null) { |
||
516 | if (!function_exists('ldap_sasl_bind')) { |
||
517 | $ex_msg = 'Library - missing SASL support'; |
||
518 | throw $this->makeException($ex_msg); |
||
519 | } |
||
520 | |||
521 | // SASL Bind, with error handling |
||
522 | $authz_id = $sasl_args['authz_id']; |
||
523 | $error = @ldap_sasl_bind( |
||
524 | $this->ldap, |
||
525 | $dn, |
||
526 | $password, |
||
527 | $sasl_args['mech'], |
||
528 | $sasl_args['realm'], |
||
529 | $sasl_args['authc_id'], |
||
530 | $sasl_args['authz_id'], |
||
531 | $sasl_args['props'] |
||
532 | ); |
||
533 | } else { |
||
534 | // Simple Bind, with error handling |
||
535 | $authz_id = $dn; |
||
536 | $error = @ldap_bind($this->ldap, $dn, $password); |
||
537 | } |
||
538 | |||
539 | if ($error === true) { |
||
540 | // Good |
||
541 | $this->authz_id = $authz_id; |
||
542 | Logger::debug('Library - LDAP bind(): Bind successful with DN \''.$dn.'\''); |
||
543 | return true; |
||
544 | } |
||
545 | |||
546 | /* Handle errors |
||
547 | * LDAP_INVALID_CREDENTIALS |
||
548 | * LDAP_INSUFFICIENT_ACCESS */ |
||
549 | switch (ldap_errno($this->ldap)) { |
||
550 | case 32: // LDAP_NO_SUCH_OBJECT |
||
551 | // no break |
||
552 | case 47: // LDAP_X_PROXY_AUTHZ_FAILURE |
||
553 | // no break |
||
554 | case 48: // LDAP_INAPPROPRIATE_AUTH |
||
555 | // no break |
||
556 | case 49: // LDAP_INVALID_CREDENTIALS |
||
557 | // no break |
||
558 | case 50: // LDAP_INSUFFICIENT_ACCESS |
||
559 | return false; |
||
560 | default: |
||
561 | break; |
||
562 | } |
||
563 | |||
564 | // Bad |
||
565 | throw $this->makeException('Library - LDAP bind(): Bind failed with DN \''.$dn.'\''); |
||
566 | } |
||
567 | |||
568 | |||
569 | /** |
||
570 | * Applies an LDAP option to the current connection. |
||
571 | * |
||
572 | * @throws Exception |
||
573 | * @param mixed $option |
||
574 | * @param mixed $value |
||
575 | * @return void |
||
576 | */ |
||
577 | public function setOption($option, $value) |
||
578 | { |
||
579 | // Attempt to set the LDAP option |
||
580 | if (!@ldap_set_option($this->ldap, $option, $value)) { |
||
581 | throw $this->makeException( |
||
582 | 'ldap:LdapConnection->setOption : Failed to set LDAP option ['. |
||
583 | $option.'] with the value ['.$value.'] error: '.ldap_error($this->ldap), |
||
584 | ERR_INTERNAL |
||
585 | ); |
||
586 | } |
||
587 | |||
588 | // Log debug message |
||
589 | Logger::debug( |
||
590 | 'ldap:LdapConnection->setOption : Set the LDAP option ['. |
||
591 | $option.'] with the value ['.$value.']' |
||
592 | ); |
||
593 | } |
||
594 | |||
595 | |||
596 | /** |
||
597 | * Search a given DN for attributes, and return the resulting associative |
||
598 | * array. |
||
599 | * |
||
600 | * @param string $dn |
||
601 | * The DN of an element. |
||
602 | * @param string|array $attributes |
||
603 | * The names of the attribute(s) to retrieve. Defaults to NULL; that is, |
||
604 | * all available attributes. Note that this is not very effective. |
||
605 | * @param int $maxsize |
||
606 | * The maximum size of any attribute's value(s). If exceeded, the attribute |
||
607 | * will not be returned. |
||
608 | * @return array |
||
609 | * The array of attributes and their values. |
||
610 | * @see http://no.php.net/manual/en/function.ldap-read.php |
||
611 | */ |
||
612 | public function getAttributes($dn, $attributes = null, $maxsize = null) |
||
684 | } |
||
685 | |||
686 | |||
687 | /** |
||
688 | * Enter description here... |
||
689 | * |
||
690 | * @param array $config |
||
691 | * @param string $username |
||
692 | * @param string $password |
||
693 | * @return array|false |
||
694 | */ |
||
695 | public function validate($config, $username, $password = null) |
||
696 | { |
||
697 | /** |
||
698 | * Escape any characters with a special meaning in LDAP. The following |
||
699 | * characters have a special meaning (according to RFC 2253): |
||
700 | * ',', '+', '"', '\', '<', '>', ';', '*' |
||
701 | * These characters are escaped by prefixing them with '\'. |
||
702 | */ |
||
703 | $username = addcslashes($username, ',+"\\<>;*'); |
||
704 | |||
705 | if (isset($config['priv_user_dn'])) { |
||
706 | $this->bind($config['priv_user_dn'], $config['priv_user_pw']); |
||
707 | } |
||
708 | if (isset($config['dnpattern'])) { |
||
709 | $dn = str_replace('%username%', $username, $config['dnpattern']); |
||
710 | } else { |
||
711 | /** @var string $dn */ |
||
712 | $dn = $this->searchfordn($config['searchbase'], $config['searchattributes'], $username, false); |
||
713 | } |
||
714 | |||
715 | if ($password !== null) { |
||
716 | // checking users credentials ... assuming below that she may read her own attributes ... |
||
717 | // escape characters with a special meaning, also in the password |
||
718 | $password = addcslashes($password, ',+"\\<>;*'); |
||
719 | if (!$this->bind($dn, $password)) { |
||
720 | Logger::info( |
||
721 | 'Library - LDAP validate(): Failed to authenticate \''.$username.'\' using DN \''.$dn.'\'' |
||
722 | ); |
||
723 | return false; |
||
724 | } |
||
725 | } |
||
726 | |||
727 | /** |
||
728 | * Retrieve attributes from LDAP |
||
729 | */ |
||
730 | $attributes = $this->getAttributes($dn, $config['attributes']); |
||
731 | return $attributes; |
||
732 | } |
||
733 | |||
734 | |||
735 | /** |
||
736 | * Borrowed function from PEAR:LDAP. |
||
737 | * |
||
738 | * Escapes the given VALUES according to RFC 2254 so that they can be safely used in LDAP filters. |
||
739 | * |
||
740 | * Any control characters with an ACII code < 32 as well as the characters with special meaning in |
||
741 | * LDAP filters "*", "(", ")", and "\" (the backslash) are converted into the representation of a |
||
742 | * backslash followed by two hex digits representing the hexadecimal value of the character. |
||
743 | * |
||
744 | * @static |
||
745 | * @param string|array $values Array of values to escape |
||
746 | * @param bool $singleValue |
||
747 | * @return string|array Array $values, but escaped |
||
748 | */ |
||
749 | public static function escape_filter_value($values = [], $singleValue = true) |
||
774 | } |
||
775 | |||
776 | |||
777 | /** |
||
778 | * Borrowed function from PEAR:LDAP. |
||
779 | * |
||
780 | * Converts all ASCII chars < 32 to "\HEX" |
||
781 | * |
||
782 | * @param string $string String to convert |
||
783 | * |
||
784 | * @static |
||
785 | * @return string |
||
786 | */ |
||
787 | public static function asc2hex32($string) |
||
800 | } |
||
801 | |||
802 | |||
803 | /** |
||
804 | * Convert SASL authz_id into a DN |
||
805 | * |
||
806 | * @param string $searchBase |
||
807 | * @param array $searchAttributes |
||
808 | * @param string $authz_id |
||
809 | * @return string|null |
||
810 | */ |
||
811 | private function authzidToDn($searchBase, $searchAttributes, $authz_id) |
||
812 | { |
||
813 | if (preg_match("/^dn:/", $authz_id)) { |
||
814 | return preg_replace("/^dn:/", "", $authz_id); |
||
815 | } |
||
816 | |||
817 | if (preg_match("/^u:/", $authz_id)) { |
||
818 | return $this->searchfordn( |
||
819 | $searchBase, |
||
820 | $searchAttributes, |
||
821 | preg_replace("/^u:/", "", $authz_id) |
||
822 | ); |
||
823 | } |
||
824 | return $authz_id; |
||
825 | } |
||
826 | |||
827 | |||
828 | /** |
||
829 | * ldap_exop_whoami accessor, if available. Use requested authz_id |
||
830 | * otherwise. |
||
831 | * |
||
832 | * ldap_exop_whoami() has been provided as a third party patch that |
||
833 | * waited several years to get its way upstream: |
||
834 | * http://cvsweb.netbsd.org/bsdweb.cgi/pkgsrc/databases/php-ldap/files |
||
835 | * |
||
836 | * When it was integrated into PHP repository, the function prototype |
||
837 | * was changed, The new prototype was used in third party patch for |
||
838 | * PHP 7.0 and 7.1, hence the version test below. |
||
839 | * |
||
840 | * @param string $searchBase |
||
841 | * @param array $searchAttributes |
||
842 | * @throws \Exception |
||
843 | * @return string |
||
844 | */ |
||
845 | public function whoami($searchBase, $searchAttributes) |
||
846 | { |
||
847 | $authz_id = ''; |
||
848 | if (function_exists('ldap_exop_whoami')) { |
||
849 | if (version_compare(phpversion(), '7', '<')) { |
||
850 | /** @psalm-suppress TooManyArguments */ |
||
851 | if (ldap_exop_whoami($this->ldap, $authz_id) === false) { |
||
852 | throw $this->makeException('LDAP whoami exop failure'); |
||
853 | } |
||
854 | } else { |
||
855 | /** @var string|false $authz_id */ |
||
856 | $authz_id = ldap_exop_whoami($this->ldap); |
||
857 | if ($authz_id === false) { |
||
858 | throw $this->makeException('LDAP whoami exop failure'); |
||
859 | } |
||
860 | } |
||
861 | } else { |
||
862 | Assert::string($authz_id); |
||
863 | /** @var string $authz_id */ |
||
864 | $authz_id = $this->authz_id; |
||
865 | } |
||
866 | |||
867 | $dn = $this->authzidToDn($searchBase, $searchAttributes, $authz_id); |
||
868 | |||
869 | if (empty($dn)) { |
||
870 | throw $this->makeException('Cannot figure userID'); |
||
871 | } |
||
872 | |||
873 | return $dn; |
||
874 | } |
||
875 | |||
876 | |||
877 | /** |
||
878 | * Set for a given DN attributes |
||
879 | * |
||
880 | * @param string $dn |
||
881 | * The DN of an element. |
||
882 | * @param array $attributes |
||
883 | * The names and value of the attribute(s) to set using ldap_mod_replace structure; |
||
884 | * @return bool |
||
885 | * Result of operation |
||
886 | */ |
||
887 | public function setAttributes($dn, array $attributes) { |
||
897 | } |
||
898 | |||
899 | |||
900 | /** |
||
901 | * Adds for a given DN attributes |
||
902 | * |
||
903 | * @param string $dn |
||
904 | * The DN of an element. |
||
905 | * @param array $attributes |
||
906 | * The names and value of the attribute(s) to set using ldap_mod_add structure; |
||
907 | * @return bool |
||
908 | * Result of operation |
||
909 | */ |
||
910 | public function addAttributes($dn, array $attributes) { |
||
920 | } |
||
921 | } |
||
922 |