Code-1
Vulnerable to Xss. Code is taken from PentesterLabs Java code review 05.
Code
Whole code:
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:
Builds an
ApplicationContext(the Spring IoC container).Scans for components (
@Controller,@Service,@Component,@Repository,@Configuration, etc.).Instantiates those bean classes (calling their constructors) and performs dependency injection.
Calls lifecycle callbacks (e.g.,
@PostConstruct,InitializingBean.afterPropertiesSet()), and runs anyCommandLineRunnerbeans after the context is ready.
So the constructors for beans are invoked during context startup, not because main() called them directly.
Spring will instantiate
MainControllerat startup (constructor called then).showHomePage(...)will only be invoked when a client requestsGET /— e.g., the user openshttp://host/?name=alice.The controller’s constructor is not what invokes
showHomePage. So handlers don't run automatically.
Vulnerability
The controller reads user input directly from the request:
The Thymeleaf template uses
th:utext:
th:utextinserts unescaped HTML into the page. Ifnamecontains HTML or script, it will be interpreted by the browser.
A user can craft a URL such as:
Fix
Template Side fix:
th:text escapes HTML entities so "<script>" becomes <script>, 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