1<?php
2/**
3 * Password policy checking for a user
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23/**
24 * Check if a user's password complies with any password policies that apply to that
25 * user, based on the user's group membership.
26 * @since 1.26
27 */
28class UserPasswordPolicy {
29
30	/**
31	 * @var array
32	 */
33	private $policies;
34
35	/**
36	 * Mapping of statements to the function that will test the password for compliance. The
37	 * checking functions take the policy value, the user, and password, and return a Status
38	 * object indicating compliance.
39	 * @var array
40	 */
41	private $policyCheckFunctions;
42
43	/**
44	 * @param array $policies
45	 * @param array $checks mapping statement to its checking function. Checking functions are
46	 *   called with the policy value for this user, the user object, and the password to check.
47	 */
48	public function __construct( array $policies, array $checks ) {
49		if ( !isset( $policies['default'] ) ) {
50			throw new InvalidArgumentException(
51				'Must include a \'default\' password policy'
52			);
53		}
54		$this->policies = $policies;
55
56		foreach ( $checks as $statement => $check ) {
57			if ( !is_callable( $check ) ) {
58				throw new InvalidArgumentException(
59					"Policy check functions must be callable. '$statement' isn't callable."
60				);
61			}
62			$this->policyCheckFunctions[$statement] = $check;
63		}
64	}
65
66	/**
67	 * Check if a password meets the effective password policy for a User.
68	 * @param User $user whose policy we are checking
69	 * @param string $password the password to check
70	 * @return Status error to indicate the password didn't meet the policy, or fatal to
71	 *   indicate the user shouldn't be allowed to login. The status value will be an array,
72	 *   potentially with the following keys:
73	 *   - forceChange: do not allow the user to login without changing the password if invalid.
74	 *   - suggestChangeOnLogin: prompt for a password change on login if the password is invalid.
75	 */
76	public function checkUserPassword( User $user, $password ) {
77		$effectivePolicy = $this->getPoliciesForUser( $user );
78		return $this->checkPolicies(
79			$user,
80			$password,
81			$effectivePolicy,
82			$this->policyCheckFunctions
83		);
84	}
85
86	/**
87	 * Check if a password meets the effective password policy for a User, using a set
88	 * of groups they may or may not belong to. This function does not use the DB, so can
89	 * be used in the installer.
90	 * @param User $user whose policy we are checking
91	 * @param string $password the password to check
92	 * @param array $groups list of groups to which we assume the user belongs
93	 * @return Status error to indicate the password didn't meet the policy, or fatal to
94	 *   indicate the user shouldn't be allowed to login. The status value will be an array,
95	 *   potentially with the following keys:
96	 *   - forceChange: do not allow the user to login without changing the password if invalid.
97	 *   - suggestChangeOnLogin: prompt for a password change on login if the password is invalid.
98	 */
99	public function checkUserPasswordForGroups( User $user, $password, array $groups ) {
100		$effectivePolicy = self::getPoliciesForGroups(
101			$this->policies,
102			$groups,
103			$this->policies['default']
104		);
105		return $this->checkPolicies(
106			$user,
107			$password,
108			$effectivePolicy,
109			$this->policyCheckFunctions
110		);
111	}
112
113	/**
114	 * @param User $user
115	 * @param string $password
116	 * @param array $policies
117	 * @param array $policyCheckFunctions
118	 * @return Status
119	 */
120	private function checkPolicies( User $user, $password, $policies, $policyCheckFunctions ) {
121		$status = Status::newGood( [] );
122		$forceChange = false;
123		$suggestChangeOnLogin = false;
124		foreach ( $policies as $policy => $settings ) {
125			if ( !isset( $policyCheckFunctions[$policy] ) ) {
126				throw new DomainException( "Invalid password policy config. No check defined for '$policy'." );
127			}
128			if ( !is_array( $settings ) ) {
129				// legacy format
130				$settings = [ 'value' => $settings ];
131			}
132			if ( !array_key_exists( 'value', $settings ) ) {
133				throw new DomainException( "Invalid password policy config. No value defined for '$policy'." );
134			}
135			$value = $settings['value'];
136			/** @var StatusValue $policyStatus */
137			$policyStatus = call_user_func(
138				$policyCheckFunctions[$policy],
139				$value,
140				$user,
141				$password
142			);
143
144			if ( !$policyStatus->isGood() ) {
145				if ( !empty( $settings['forceChange'] ) ) {
146					$forceChange = true;
147				}
148
149				if ( !empty( $settings['suggestChangeOnLogin'] ) ) {
150					$suggestChangeOnLogin = true;
151				}
152			}
153			$status->merge( $policyStatus );
154		}
155
156		if ( $status->isOK() ) {
157			if ( $forceChange ) {
158				$status->value['forceChange'] = true;
159			} elseif ( $suggestChangeOnLogin ) {
160				$status->value['suggestChangeOnLogin'] = true;
161			}
162		}
163
164		return $status;
165	}
166
167	/**
168	 * Get the policy for a user, based on their group membership. Public so
169	 * UI elements can access and inform the user.
170	 * @param User $user
171	 * @return array the effective policy for $user
172	 */
173	public function getPoliciesForUser( User $user ) {
174		$effectivePolicy = self::getPoliciesForGroups(
175			$this->policies,
176			$user->getEffectiveGroups(),
177			$this->policies['default']
178		);
179
180		Hooks::runner()->onPasswordPoliciesForUser( $user, $effectivePolicy );
181
182		return $effectivePolicy;
183	}
184
185	/**
186	 * Utility function to get the effective policy from a list of policies, based
187	 * on a list of groups.
188	 * @param array $policies list of policies to consider
189	 * @param array $userGroups the groups from which we calculate the effective policy
190	 * @param array $defaultPolicy the default policy to start from
191	 * @return array effective policy
192	 */
193	public static function getPoliciesForGroups( array $policies, array $userGroups,
194		array $defaultPolicy
195	) {
196		$effectivePolicy = $defaultPolicy;
197		foreach ( $policies as $group => $policy ) {
198			if ( in_array( $group, $userGroups ) ) {
199				$effectivePolicy = self::maxOfPolicies(
200					$effectivePolicy,
201					$policy
202				);
203			}
204		}
205
206		return $effectivePolicy;
207	}
208
209	/**
210	 * Utility function to get a policy that is the most restrictive of $p1 and $p2. For
211	 * simplicity, we setup the policy values so the maximum value is always more restrictive.
212	 * It is also used recursively to merge settings within the same policy.
213	 * @param array $p1
214	 * @param array $p2
215	 * @return array containing the more restrictive values of $p1 and $p2
216	 */
217	public static function maxOfPolicies( array $p1, array $p2 ) {
218		$ret = [];
219		$keys = array_merge( array_keys( $p1 ), array_keys( $p2 ) );
220		foreach ( $keys as $key ) {
221			if ( !isset( $p1[$key] ) ) {
222				$ret[$key] = $p2[$key];
223			} elseif ( !isset( $p2[$key] ) ) {
224				$ret[$key] = $p1[$key];
225			} elseif ( !is_array( $p1[$key] ) && !is_array( $p2[$key] ) ) {
226				$ret[$key] = max( $p1[$key], $p2[$key] );
227			} else {
228				if ( !is_array( $p1[$key] ) ) {
229					$p1[$key] = [ 'value' => $p1[$key] ];
230				} elseif ( !is_array( $p2[$key] ) ) {
231					$p2[$key] = [ 'value' => $p2[$key] ];
232				}
233				$ret[$key] = self::maxOfPolicies( $p1[$key], $p2[$key] );
234			}
235		}
236		return $ret;
237	}
238
239}
240