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
23use MediaWiki\MediaWikiServices;
24use MediaWiki\User\UserIdentity;
25
26/**
27 * Check if a user's password complies with any password policies that apply to that
28 * user, based on the user's group membership.
29 * @since 1.26
30 */
31class UserPasswordPolicy {
32
33	/**
34	 * @var array
35	 */
36	private $policies;
37
38	/**
39	 * Mapping of statements to the function that will test the password for compliance. The
40	 * checking functions take the policy value, the user, and password, and return a Status
41	 * object indicating compliance.
42	 * @var array
43	 */
44	private $policyCheckFunctions;
45
46	/**
47	 * @param array $policies
48	 * @param array $checks mapping statement to its checking function. Checking functions are
49	 *   called with the policy value for this user, the user object, and the password to check.
50	 */
51	public function __construct( array $policies, array $checks ) {
52		if ( !isset( $policies['default'] ) ) {
53			throw new InvalidArgumentException(
54				'Must include a \'default\' password policy'
55			);
56		}
57		$this->policies = $policies;
58
59		foreach ( $checks as $statement => $check ) {
60			if ( !is_callable( $check ) ) {
61				throw new InvalidArgumentException(
62					"Policy check functions must be callable. '$statement' isn't callable."
63				);
64			}
65			$this->policyCheckFunctions[$statement] = $check;
66		}
67	}
68
69	/**
70	 * Check if a password meets the effective password policy for a User.
71	 * @param UserIdentity $user whose policy we are checking
72	 * @param string $password the password to check
73	 * @return Status error to indicate the password didn't meet the policy, or fatal to
74	 *   indicate the user shouldn't be allowed to login. The status value will be an array,
75	 *   potentially with the following keys:
76	 *   - forceChange: do not allow the user to login without changing the password if invalid.
77	 *   - suggestChangeOnLogin: prompt for a password change on login if the password is invalid.
78	 */
79	public function checkUserPassword( UserIdentity $user, $password ) {
80		$effectivePolicy = $this->getPoliciesForUser( $user );
81		return $this->checkPolicies(
82			$user,
83			$password,
84			$effectivePolicy,
85			$this->policyCheckFunctions
86		);
87	}
88
89	/**
90	 * Check if a password meets the effective password policy for a User, using a set
91	 * of groups they may or may not belong to. This function does not use the DB, so can
92	 * be used in the installer.
93	 * @param UserIdentity $user whose policy we are checking
94	 * @param string $password the password to check
95	 * @param array $groups list of groups to which we assume the user belongs
96	 * @return Status error to indicate the password didn't meet the policy, or fatal to
97	 *   indicate the user shouldn't be allowed to login. The status value will be an array,
98	 *   potentially with the following keys:
99	 *   - forceChange: do not allow the user to login without changing the password if invalid.
100	 *   - suggestChangeOnLogin: prompt for a password change on login if the password is invalid.
101	 */
102	public function checkUserPasswordForGroups( UserIdentity $user, $password, array $groups ) {
103		$effectivePolicy = self::getPoliciesForGroups(
104			$this->policies,
105			$groups,
106			$this->policies['default']
107		);
108		return $this->checkPolicies(
109			$user,
110			$password,
111			$effectivePolicy,
112			$this->policyCheckFunctions
113		);
114	}
115
116	/**
117	 * @param UserIdentity $user
118	 * @param string $password
119	 * @param array $policies
120	 * @param array $policyCheckFunctions
121	 * @return Status
122	 */
123	private function checkPolicies( UserIdentity $user, $password, $policies, $policyCheckFunctions ) {
124		$status = Status::newGood( [] );
125		$forceChange = false;
126		$suggestChangeOnLogin = false;
127		$legacyUser = MediaWikiServices::getInstance()
128			->getUserFactory()
129			->newFromUserIdentity( $user );
130		foreach ( $policies as $policy => $settings ) {
131			if ( !isset( $policyCheckFunctions[$policy] ) ) {
132				throw new DomainException( "Invalid password policy config. No check defined for '$policy'." );
133			}
134			if ( !is_array( $settings ) ) {
135				// legacy format
136				$settings = [ 'value' => $settings ];
137			}
138			if ( !array_key_exists( 'value', $settings ) ) {
139				throw new DomainException( "Invalid password policy config. No value defined for '$policy'." );
140			}
141			$value = $settings['value'];
142			/** @var StatusValue $policyStatus */
143			$policyStatus = call_user_func(
144				$policyCheckFunctions[$policy],
145				$value,
146				$legacyUser,
147				$password
148			);
149
150			if ( !$policyStatus->isGood() ) {
151				if ( !empty( $settings['forceChange'] ) ) {
152					$forceChange = true;
153				}
154
155				if ( !empty( $settings['suggestChangeOnLogin'] ) ) {
156					$suggestChangeOnLogin = true;
157				}
158			}
159			$status->merge( $policyStatus );
160		}
161
162		if ( $status->isOK() ) {
163			if ( $forceChange ) {
164				$status->value['forceChange'] = true;
165			} elseif ( $suggestChangeOnLogin ) {
166				$status->value['suggestChangeOnLogin'] = true;
167			}
168		}
169
170		return $status;
171	}
172
173	/**
174	 * Get the policy for a user, based on their group membership. Public so
175	 * UI elements can access and inform the user.
176	 * @param UserIdentity $user
177	 * @return array the effective policy for $user
178	 */
179	public function getPoliciesForUser( UserIdentity $user ) {
180		$effectivePolicy = self::getPoliciesForGroups(
181			$this->policies,
182			MediaWikiServices::getInstance()
183				->getUserGroupManager()
184				->getUserEffectiveGroups( $user ),
185			$this->policies['default']
186		);
187
188		$legacyUser = MediaWikiServices::getInstance()
189			->getUserFactory()
190			->newFromUserIdentity( $user );
191		Hooks::runner()->onPasswordPoliciesForUser( $legacyUser, $effectivePolicy );
192
193		return $effectivePolicy;
194	}
195
196	/**
197	 * Utility function to get the effective policy from a list of policies, based
198	 * on a list of groups.
199	 * @param array $policies list of policies to consider
200	 * @param array $userGroups the groups from which we calculate the effective policy
201	 * @param array $defaultPolicy the default policy to start from
202	 * @return array effective policy
203	 */
204	public static function getPoliciesForGroups( array $policies, array $userGroups,
205		array $defaultPolicy
206	) {
207		$effectivePolicy = $defaultPolicy;
208		foreach ( $policies as $group => $policy ) {
209			if ( in_array( $group, $userGroups ) ) {
210				$effectivePolicy = self::maxOfPolicies(
211					$effectivePolicy,
212					$policy
213				);
214			}
215		}
216
217		return $effectivePolicy;
218	}
219
220	/**
221	 * Utility function to get a policy that is the most restrictive of $p1 and $p2. For
222	 * simplicity, we setup the policy values so the maximum value is always more restrictive.
223	 * It is also used recursively to merge settings within the same policy.
224	 * @param array $p1
225	 * @param array $p2
226	 * @return array containing the more restrictive values of $p1 and $p2
227	 */
228	public static function maxOfPolicies( array $p1, array $p2 ) {
229		$ret = [];
230		$keys = array_merge( array_keys( $p1 ), array_keys( $p2 ) );
231		foreach ( $keys as $key ) {
232			if ( !isset( $p1[$key] ) ) {
233				$ret[$key] = $p2[$key];
234			} elseif ( !isset( $p2[$key] ) ) {
235				$ret[$key] = $p1[$key];
236			} elseif ( !is_array( $p1[$key] ) && !is_array( $p2[$key] ) ) {
237				$ret[$key] = max( $p1[$key], $p2[$key] );
238			} else {
239				if ( !is_array( $p1[$key] ) ) {
240					$p1[$key] = [ 'value' => $p1[$key] ];
241				} elseif ( !is_array( $p2[$key] ) ) {
242					$p2[$key] = [ 'value' => $p2[$key] ];
243				}
244				$ret[$key] = self::maxOfPolicies( $p1[$key], $p2[$key] );
245			}
246		}
247		return $ret;
248	}
249
250}
251