A free open source IT asset/license management system
Auth: Fixed FD-56498 - check username case for non-local logins
snipe2304066d79fe
diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.phpindex 98ec93d7a4..9dcbff5c70 100644--- a/app/Http/Controllers/Auth/LoginController.php+++ b/app/Http/Controllers/Auth/LoginController.php@@ -173,6 +173,7 @@ class LoginController extends Controller// Check if the user already exists in the database and was imported via LDAP$user = User::where('username', '=', $request->input('username'))->whereNull('deleted_at')->where('ldap_import', '=', 1)->where('activated', '=', '1')->first(); // FIXME - if we get more than one we should fail. and we sure about this ldap_import thing?+ $user = User::verifyExactUsernameMatch($user, (string) $request->input('username'));Log::debug('Local auth lookup complete');// The user does not exist in the database. Try to get them from LDAP.@@ -243,7 +244,9 @@ class LoginController extends Controllertry {$user = User::where('username', '=', $remote_user)->whereNull('deleted_at')->where('activated', '=', '1')->first();+ $user = User::verifyExactUsernameMatch($user, (string) $remote_user);Log::debug('Remote user auth lookup complete');+if (! is_null($user)) {Auth::login($user, $request->input('remember'));}diff --git a/app/Http/Controllers/GoogleAuthController.php b/app/Http/Controllers/GoogleAuthController.phpindex a1e7118fa7..f6ab95d59c 100644--- a/app/Http/Controllers/GoogleAuthController.php+++ b/app/Http/Controllers/GoogleAuthController.php@@ -52,6 +52,8 @@ class GoogleAuthController extends Controller->whereNull('deleted_at')->first();+ $user = User::verifyExactUsernameMatch($user, (string) $socialUser->getEmail());+if ($user) {if (! $user->activated) {Log::debug('Google user '.$socialUser->getEmail().' is deactivated in Snipe-IT');diff --git a/app/Models/User.php b/app/Models/User.phpindex 02cd192f68..9bb152169b 100644--- a/app/Models/User.php+++ b/app/Models/User.php@@ -1299,6 +1299,28 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param string $query* @return string*/+ /**+ * Verify that a resolved local user's stored username byte-exactly matches+ * the externally-supplied identifier. The MySQL/MariaDB default collation+ * utf8mb4_unicode_ci folds accents and case, so `WHERE username = ?` on+ * that engine can silently route 'snípeitreport3' or 'Admin' to the row+ * for 'snipeitreport3' or 'admin'. Federated/SSO auth flows (SAML, LDAP,+ * REMOTE_USER, Google OAuth) must call this after their username lookup+ * so an attacker-controlled external identifier can't authenticate as a+ * different local account. hash_equals runs in constant time so this+ * check doesn't leak any timing signal.+ *+ * Returns the user when the strings match byte-for-byte, null otherwise.+ */+ public static function verifyExactUsernameMatch(?self $user, string $expected): ?self+ {+ if ($user === null) {+ return null;+ }++ return hash_equals((string) $user->username, $expected) ? $user : null;+ }+public static function generateEmailFromFullName($name){$username = self::generateFormattedNameFromFullName($name, Setting::getSettings()->email_format);diff --git a/app/Services/Saml.php b/app/Services/Saml.phpindex 222c2c2ea3..5ae16f5b05 100644--- a/app/Services/Saml.php+++ b/app/Services/Saml.php@@ -6,13 +6,13 @@ use App\Models\Setting;use App\Models\User;use Exception;use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Session;use OneLogin\Saml2\Auth as OneLogin_Saml2_Auth;use OneLogin\Saml2\IdPMetadataParser as OneLogin_Saml2_IdPMetadataParser;use OneLogin\Saml2\Settings as OneLogin_Saml2_Settings;use OneLogin\Saml2\Utils as OneLogin_Saml2_Utils;use Symfony\Component\HttpKernel\Exception\HttpException;-use Illuminate\Support\Facades\Log;/*** SAML Singleton that builds the settings and loads the onelogin/php-saml library.@@ -134,8 +134,8 @@ class Samltry {$this->_auth = new OneLogin_Saml2_Auth($this->_settings);} catch (Exception $e) {- if ( $this->isEnabled() ) { // $this->loadSettings() initializes this to true if SAML is enabled by settings.- Log::warning('Trying OneLogin_Saml2_Auth failed. Setting SAML enabled to false. OneLogin_Saml2_Auth error message is: '. $e->getMessage());+ if ($this->isEnabled()) { // $this->loadSettings() initializes this to true if SAML is enabled by settings.+ Log::warning('Trying OneLogin_Saml2_Auth failed. Setting SAML enabled to false. OneLogin_Saml2_Auth error message is: '.$e->getMessage());}$this->_enabled = false;}@@ -159,11 +159,11 @@ class Saml$this->_enabled = $setting->saml_enabled == '1';if ($this->isEnabled()) {- //Let onelogin/php-saml know to use 'X-Forwarded-*' headers if it is from a trusted proxy+ // Let onelogin/php-saml know to use 'X-Forwarded-*' headers if it is from a trusted proxyOneLogin_Saml2_Utils::setProxyVars(request()->isFromTrustedProxy());data_set($settings, 'sp.entityId', config('app.url'));- data_set($settings, 'baseurl', config('app.url') . '/saml');+ data_set($settings, 'baseurl', config('app.url').'/saml');data_set($settings, 'sp.assertionConsumerService.url', route('saml.acs'));data_set($settings, 'sp.singleLogoutService.url', route('saml.sls'));data_set($settings, 'sp.x509cert', $setting->saml_sp_x509cert);@@ -259,8 +259,7 @@ class Saml** @since 5.0.0*- * @param string $data- *+ * @param string $data* @return void*/private function saveDataToSession($data)@@ -304,16 +303,21 @@ class Saml** @since 5.0.0*- * @param string $data- *- * @return \App\Models\User+ * @param string $data+ * @return User*/public function samlLogin($data){$this->saveDataToSession($data);$this->loadDataFromSession();$username = $this->getUsername();- return User::where('username', '=', $username)->whereNull('deleted_at')->where('activated', '=', '1')->first();++ $user = User::where('username', '=', $username)+ ->whereNull('deleted_at')+ ->where('activated', '=', '1')+ ->first();++ return User::verifyExactUsernameMatch($user, (string) $username);}/**@@ -337,12 +341,11 @@ class Saml/*** Get a setting.*- * @param string|array|int $key- * @param mixed $default- *+ * @param string|array|int $key+ * @param mixed $default* @return mixed- * @author Johnson Yi <[email protected]>*+ * @author Johnson Yi <[email protected]>*/public function getSetting($key, $default = null){@@ -352,15 +355,14 @@ class Saml/*** Gets the SP metadata. The XML representation.*- * @param bool $alwaysPublishEncryptionCert When 'true', the returned- * metadata will always include an 'encryption' KeyDescriptor. Otherwise,- * the 'encryption' KeyDescriptor will only be included if- * $advancedSettings['security']['wantNameIdEncrypted'] or- * $advancedSettings['security']['wantAssertionsEncrypted'] are enabled.- * @param int|null $validUntil Metadata's valid time- * @param int|null $cacheDuration Duration of the cache in seconds- *- * @return string SP metadata (xml)+ * @param bool $alwaysPublishEncryptionCert When 'true', the returned+ * metadata will always include an 'encryption' KeyDescriptor. Otherwise,+ * the 'encryption' KeyDescriptor will only be included if+ * $advancedSettings['security']['wantNameIdEncrypted'] or+ * $advancedSettings['security']['wantAssertionsEncrypted'] are enabled.+ * @param int|null $validUntil Metadata's valid time+ * @param int|null $cacheDuration Duration of the cache in seconds+ * @return string SP metadata (xml)*/public function getSPMetadata($alwaysPublishEncryptionCert = false, $validUntil = null, $cacheDuration = null){@@ -404,7 +406,7 @@ class Saml/*** Checks if the user is authenticated or not.*- * @return bool True if the user is authenticated+ * @return bool True if the user is authenticated*/public function isAuthenticated(){@@ -414,7 +416,7 @@ class Saml/*** Returns the set of SAML attributes.*- * @return array Attributes of the user.+ * @return array Attributes of the user.*/public function getAttributes(){@@ -424,7 +426,7 @@ class Saml/*** Returns the set of SAML attributes indexed by FriendlyName*- * @return array Attributes of the user.+ * @return array Attributes of the user.*/public function getAttributesWithFriendlyName(){@@ -434,7 +436,7 @@ class Saml/*** Returns the nameID*- * @return string The nameID of the assertion+ * @return string The nameID of the assertion*/public function getNameId(){@@ -444,7 +446,7 @@ class Saml/*** Returns the nameID Format*- * @return string The nameID Format of the assertion+ * @return string The nameID Format of the assertion*/public function getNameIdFormat(){@@ -454,7 +456,7 @@ class Saml/*** Returns the nameID NameQualifier*- * @return string The nameID NameQualifier of the assertion+ * @return string The nameID NameQualifier of the assertion*/public function getNameIdNameQualifier(){@@ -464,7 +466,7 @@ class Saml/*** Returns the nameID SP NameQualifier*- * @return string The nameID SP NameQualifier of the assertion+ * @return string The nameID SP NameQualifier of the assertion*/public function getNameIdSPNameQualifier(){@@ -474,7 +476,7 @@ class Saml/*** Returns the SessionIndex*- * @return string|null The SessionIndex of the assertion+ * @return string|null The SessionIndex of the assertion*/public function getSessionIndex(){@@ -484,7 +486,7 @@ class Saml/*** Returns the SessionNotOnOrAfter*- * @return int|null The SessionNotOnOrAfter of the assertion+ * @return int|null The SessionNotOnOrAfter of the assertion*/public function getSessionExpiration(){diff --git a/tests/Unit/Models/User/VerifyExactUsernameMatchTest.php b/tests/Unit/Models/User/VerifyExactUsernameMatchTest.phpnew file mode 100644index 0000000000..518d2ac21b--- /dev/null+++ b/tests/Unit/Models/User/VerifyExactUsernameMatchTest.php@@ -0,0 +1,139 @@+<?php++namespace Tests\Unit\Models\User;++use App\Models\User;+use Tests\TestCase;++/**+ * Coverage for User::verifyExactUsernameMatch, the SSO/federated-auth ATO+ * guard against DB collation folding. The MySQL/MariaDB default collation+ * utf8mb4_unicode_ci treats snipeitreport3 and snípeitreport3 as equal, so+ * `WHERE username = ?` can return the wrong row for an attacker-controlled+ * external identifier. The helper is the byte-exact re-check every federated+ * auth callsite (SAML, LDAP, REMOTE_USER, Google OAuth) runs before trusting+ * the resolved local user. These tests instantiate the User model without+ * touching the DB because the helper is a pure function on the resolved row+ * plus the expected string.+ *+ * Original vulnerability report: whale120 (@whale120_tw), DEVCORE Internship+ * Program.+ */+class VerifyExactUsernameMatchTest extends TestCase+{+ public function test_null_user_returns_null()+ {+ $this->assertNull(User::verifyExactUsernameMatch(null, 'anything'));+ }++ public function test_null_user_returns_null_even_when_expected_is_empty()+ {+ $this->assertNull(User::verifyExactUsernameMatch(null, ''));+ }++ public function test_exact_byte_match_returns_the_user()+ {+ $user = new User(['username' => 'snipeitreport3']);++ $this->assertSame($user, User::verifyExactUsernameMatch($user, 'snipeitreport3'));+ }++ /**+ * The literal customer-report scenario: MySQL's utf8mb4_unicode_ci returns+ * the snipeitreport3 row when the query is snípeitreport3 (accented i).+ * The helper must reject that row so SAML/LDAP/etc. cannot log in as it.+ */+ public function test_accented_variant_is_rejected()+ {+ $user = new User(['username' => 'snipeitreport3']);++ $this->assertNull(User::verifyExactUsernameMatch($user, 'snípeitreport3'));+ }++ public function test_case_variant_is_rejected()+ {+ $user = new User(['username' => 'admin']);++ $this->assertNull(User::verifyExactUsernameMatch($user, 'Admin'));+ }++ public function test_uppercase_variant_is_rejected()+ {+ $user = new User(['username' => 'admin']);++ $this->assertNull(User::verifyExactUsernameMatch($user, 'ADMIN'));+ }++ /**+ * Trailing/leading whitespace is a known family of collation-adjacent+ * traps (PADSPACE semantics for CHAR columns, though users.username is+ * VARCHAR); pin the behavior here so a future refactor can't drop into+ * a trim()-based comparison and reintroduce a folding side channel.+ */+ public function test_trailing_whitespace_variant_is_rejected()+ {+ $user = new User(['username' => 'snipeitreport3']);++ $this->assertNull(User::verifyExactUsernameMatch($user, 'snipeitreport3 '));+ }++ public function test_leading_whitespace_variant_is_rejected()+ {+ $user = new User(['username' => 'snipeitreport3']);++ $this->assertNull(User::verifyExactUsernameMatch($user, ' snipeitreport3'));+ }++ public function test_different_length_variant_is_rejected()+ {+ $user = new User(['username' => 'admin']);++ $this->assertNull(User::verifyExactUsernameMatch($user, 'administrator'));+ }++ public function test_prefix_variant_is_rejected()+ {+ $user = new User(['username' => 'administrator']);++ $this->assertNull(User::verifyExactUsernameMatch($user, 'admin'));+ }++ public function test_empty_expected_string_against_stored_username_is_rejected()+ {+ $user = new User(['username' => 'admin']);++ $this->assertNull(User::verifyExactUsernameMatch($user, ''));+ }++ public function test_empty_stored_username_against_empty_expected_returns_the_user()+ {+ // Not a realistic identity but the helper must not throw on empty+ // strings; hash_equals accepts them as long as both sides match.+ $user = new User(['username' => '']);++ $this->assertSame($user, User::verifyExactUsernameMatch($user, ''));+ }++ public function test_null_stored_username_is_rejected()+ {+ // users.username is nullable in the schema. Cast to string inside the+ // helper coerces null to '' before comparing, so a stored null must+ // never match any non-empty external identifier.+ $user = new User(['username' => null]);++ $this->assertNull(User::verifyExactUsernameMatch($user, 'anything'));+ }++ /**+ * Cyrillic а (U+0430) is a common lookalike for Latin a (U+0061). Some+ * collation configurations fold Cyrillic to Latin for confusable-detection+ * purposes; the byte-exact guard must reject regardless.+ */+ public function test_cyrillic_lookalike_variant_is_rejected()+ {+ $user = new User(['username' => 'admin']);++ // First 'а' is Cyrillic U+0430, not Latin U+0061.+ $this->assertNull(User::verifyExactUsernameMatch($user, 'аdmin'));+ }+}