The vulnerability is Improper Input Validation
html
<!-- Insert the vulnerable code into a short web application -->
<!DOCTYPE html>
<html>
<head>
  <script src="vulnerable.js"></script>
</head>
<body>
  <button onclick="greetUser('<script>alert("Hacked!")</script>')">Say hello</button>
</body>
</html>
javascript
// Vulnerable code
function greetUser(username) {
  const welcomeMsg = "Welcome, " + username + "!";
  console.log(welcomeMsg);
}

greetUser('<script>alert("Hacked!")</script>');
javascript // Vulnerable code function greetUser(username) { const welcomeMsg = "Welcome, " + username + "!"; console.log(welcomeMsg); } greetUser(''); n greetUser(username) { const welcomeMsg = "Welcome, " + username + "!"; console.log(welcomeMsg); } greetUser(''); ``` ```html ``` ```javascript // Solution to fix the vulnerable code function greetUser(username) { const safeUsername = username.replace(//g, '>'); const welcomeMsg = "Welcome, " + safeUsername + "!"; console.log(welcomeMsg); } greetUser(''); ``` To fix the vulnerability, we need to sanitize the input by escaping any dangerous characters (like `<` and `>`) before creating the welcome message. This will prevent any potentially harmful code from being executed.
javascript
// Solution to fix the vulnerable code
function greetUser(username) {
  const safeUsername = username.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const welcomeMsg = "Welcome, " + safeUsername + "!";
  console.log(welcomeMsg);
}

greetUser('<script>alert("Hacked!")</script>');