Code-1

Vulnerable to Xss. Code is taken from PentesterLabs Java code review 05.

Code

Whole code:

79KB
Open

Structure

vulnerable/
├── mvnw.cmd
├── pom.xml
├── .gitignore
├── .mvn/
│   └── wrapper/
│       ├── maven-wrapper.properties
│       └── maven-wrapper.jar
├── mvnw
├── src/
│   ├── test/
│   │   └── java/
│   │       └── com/
│   │           └── pentesterlab/
│   │               └── vulnerable/
│   │                   └── VulnerableApplicationTests.java
│   ├── main/
│   │   ├── resources/
│   │   │   ├── static/
│   │   │   │   ├── css/
│   │   │   │   │   ├── bootstrap.css
│   │   │   │   │   └── pentesterlab.css
│   │   │   ├── templates/
│   │   │   │   ├── index.html
│   │   │   │   └── fragments.html
│   │   │   └── application.properties
│   │   └── java/
│   │       └── com/
│   │           └── pentesterlab/
│   │               └── vulnerable/
│   │                   └── controller/
│   │                       └── MainController.java
│   │                   └── VulnerableApplication.java

VulnerableApplication.java

MainController.java

Index.html

First we need to learn this:

SpringApplication.run(...) does:

  1. Builds an ApplicationContext (the Spring IoC container).

  2. Scans for components (@Controller, @Service, @Component, @Repository, @Configuration, etc.).

  3. Instantiates those bean classes (calling their constructors) and performs dependency injection.

  4. Calls lifecycle callbacks (e.g., @PostConstruct, InitializingBean.afterPropertiesSet()), and runs any CommandLineRunner beans after the context is ready.

So the constructors for beans are invoked during context startup, not because main() called them directly.

  • Spring will instantiate MainController at startup (constructor called then).

  • showHomePage(...) will only be invoked when a client requests GET / — e.g., the user opens http://host/?name=alice.

  • The controller’s constructor is not what invokes showHomePage. So handlers don't run automatically.

Vulnerability

  1. The controller reads user input directly from the request:

  1. The Thymeleaf template uses th:utext:

  • th:utext inserts unescaped HTML into the page. If name contains HTML or script, it will be interpreted by the browser.

  1. A user can craft a URL such as:

Fix

Template Side fix:

th:text escapes HTML entities so "<script>" becomes &lt;script&gt;, so it is shown as text, not executed.

2) Server-side defense (defense-in-depth)

If you want extra safety or are rendering data in other contexts, escape/sanitize on the server:

Escape HTML (Spring utility)

or sanitize to allow only safe HTML (if you specifically intend to allow limited HTML) using JSoup:

Last updated