Skip to content

Commit 4252ce8

Browse files
committed
Sanitize invalid UTF-8 user agent in DatabaseSessionHandler
1 parent c728e56 commit 4252ce8

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/Illuminate/Session/DatabaseSessionHandler.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,13 @@ protected function ipAddress()
255255
*/
256256
protected function userAgent()
257257
{
258-
return substr((string) $this->container->make('request')->header('User-Agent'), 0, 500);
258+
$userAgent = (string) $this->container->make('request')->header('User-Agent');
259+
260+
if (! mb_check_encoding($userAgent, 'UTF-8')) {
261+
$userAgent = (string) mb_convert_encoding($userAgent, 'UTF-8', 'UTF-8');
262+
}
263+
264+
return substr($userAgent, 0, 500);
259265
}
260266

261267
/**

tests/Integration/Session/DatabaseSessionHandlerTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,4 +110,26 @@ public function test_it_can_work_without_container()
110110
$this->assertNull($session->ip_address);
111111
$this->assertNull($session->user_id);
112112
}
113+
114+
public function test_it_sanitizes_invalid_utf8_user_agent_on_write()
115+
{
116+
$connection = $this->app['db']->connection();
117+
$handler = new DatabaseSessionHandler($connection, 'sessions', 1);
118+
$handler->setContainer($this->app);
119+
120+
$invalidUa = 'Mozilla/5.0 (compatible; YodaoBot/1.0; http://www.yodao.com/help/webmaster/spider/'."\xA1".'; )';
121+
122+
$this->app['request']->headers->set('User-Agent', $invalidUa);
123+
$this->app['request']->server->set('REMOTE_ADDR', '134.122.184.11');
124+
125+
// Should not throw and should persist a valid UTF-8 string to the DB
126+
$this->assertTrue($handler->write('ua_invalid_utf8', json_encode(['k' => 'v'])));
127+
128+
$session = $connection->table('sessions')->where('id', 'ua_invalid_utf8')->first();
129+
130+
$this->assertNotNull($session);
131+
$this->assertNotNull($session->user_agent);
132+
$this->assertTrue(mb_check_encoding($session->user_agent, 'UTF-8'));
133+
$this->assertStringNotContainsString("\xA1", $session->user_agent);
134+
}
113135
}

0 commit comments

Comments
 (0)