Can I directly echo the PHP user agent?

394    Asked by AndrewJenkins in Cyber Security , Asked on Feb 2, 2022

 Is this script vulnerable to PHP or JS code injection? In my quick test I changed the useragent to a PHP script but it will not be executed just printed. If I change the user agent to a javascript code I receive a connection refused by the webserver. So am I safe with this type of script?

<?php 
$u=$_SERVER['HTTP_USER_AGENT']
?>
<html>
string

<?php echo $u; ?>
</html>
Answered by Andrew Jenkins

You are correct that you do not need to worry about PHP user agent code being injected. The echo command just echoes stuff - it does not execute it. The JS is more problematic, though. Your code may be vulnerable to XSS. The client controls the user agent, and the attacker controls the client. You are giving an attacker the ability to inject arbitrary HTML and JS code into your webpage. Just use a user agent like this:


There is one big problem for the attacker: While it's easy to change your own user agent, you can't really change someone else's. So it's not obvious how you would hack anyone but yourself with this - it's a quite advanced form of self-XSS. If you are storing and then displaying other users' user-agents (e.g. from logs) you have a much bigger danger. But that is not the case with your simple script. So why doesn't that work for you? It looks like your attack gets blocked by some kind of WAF or similar. That's great, but don't write bad code in the hope that your WAF will protect you! A WAF will not protect you against everything. And who knows where your code will run in the future and if there will even be a WAF there…



Your Answer

Interviews

Parent Categories