├── .dockerignore ├── .gitignore ├── ARACHNI.MD ├── Dockerfile ├── LICENSE ├── README.md ├── pom.xml └── src └── main ├── java └── com │ └── github │ └── rafaelrpinto │ └── vulnerablejavawebapp │ ├── config │ ├── AppLauncher.java │ └── SessionUserFilter.java │ ├── controller │ ├── AdvertisementController.java │ └── UserController.java │ ├── model │ ├── Advertisement.java │ └── User.java │ └── repository │ ├── AdvertisementRepository.java │ └── UserRepository.java ├── resources ├── application.properties ├── db │ ├── data.sql │ └── schema.sql └── keystore.jks └── webapp ├── WEB-INF └── jsp │ ├── home.jsp │ ├── include │ ├── footer.jsp │ └── header.jsp │ ├── login.jsp │ ├── newAdForm.jsp │ └── signUp.jsp └── resources ├── css ├── bootstrap-theme.min.css ├── bootstrap-theme.min.css.map ├── bootstrap.min.css └── bootstrap.min.css.map ├── fonts ├── glyphicons-halflings-regular.eot ├── glyphicons-halflings-regular.svg ├── glyphicons-halflings-regular.ttf ├── glyphicons-halflings-regular.woff └── glyphicons-halflings-regular.woff2 └── js ├── bootstrap.min.js └── jquery.min.js /.dockerignore: -------------------------------------------------------------------------------- 1 | .settings 2 | .classpath 3 | .directory 4 | .project 5 | target 6 | *.log 7 | *.MD 8 | LICENSE 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .settings 2 | .classpath 3 | .directory 4 | .project 5 | target 6 | -------------------------------------------------------------------------------- /ARACHNI.MD: -------------------------------------------------------------------------------- 1 | ## Scanning the application with Arachni Scanner 2 | 3 | The application is running on the **HTTPS port 9000**. 4 | 5 | The command line initiates the scan with the following configurations: 6 | 7 | 1. Logs in as 'User 1' 8 | 2. Ignores some checks to improve the scan performance 9 | 3. Replaces the arachni User-Agent with a recent Chrome one 10 | 4. Saves the result adding the scan date to the file name 11 | 12 | `./arachni --checks=*,-code_injection_php_input_wrapper,-ldap_injection,-no_sql*,-backup_files,-backup_directories,-captcha,-cvs_svn_users,-credit_card,-ssn,-localstart_asp,-webdav --plugin=autologin:url=https://$(hostname):9000/login,parameters='login=user1@user1.com&password=abcd1234',check='Hi User 1|Logout' --scope-exclude-pattern='logout' --scope-exclude-pattern='resources' --session-check-pattern='Hi User 1' --session-check-url=https://$(hostname):9000 --http-user-agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36' --report-save-path=../scan_report_$(date -d "today" +"%Y%m%d%H%M").afr https://$(hostname):9000` 13 | 14 | ## Processing the result report to a zip file containing HTML pages (replace _X for the generated timestamp) 15 | `./arachni_reporter ../scan_report_X.afr --reporter=html:outfile=../scan_report.html_X.zip` 16 | 17 | For more scanning options check https://github.com/Arachni/arachni. 18 | 19 | The article that I wrote explaining how to use Arachni to check this application [is available on linkedin](https://www.linkedin.com/pulse/identifying-security-flaws-legacy-web-applications-arachni-pinto). 20 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # JDK 8 + Maven 3.3.9 2 | FROM maven:3.3.9-jdk-8 3 | 4 | # Prepare the folder 5 | RUN mkdir -p /app 6 | COPY . /app 7 | WORKDIR /app 8 | 9 | # Generates the package 10 | RUN mvn install 11 | 12 | # Http port 13 | ENV PORT 9000 14 | EXPOSE $PORT 15 | 16 | # Executes spring boot's jar 17 | CMD ["java", "-jar", "target/vulnerablejavawebapp-0.0.1-SNAPSHOT.jar"] 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Rafael Pinto 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vulnerable Java Web Application 2 | 3 | This repository provides a simple and self-contained Java web application with security flaws common to mid-00's legacy projects that have not been updated. 4 | 5 | The application uses Spring Boot and an embedded H2 database that resets every time it starts. If you break it just restart and everything will be reset. 6 | 7 | The application will run on **HTTPS port 9000**. If this port is not available you will need to change the `application.properties` file on the source folder with the new one. (if you are using docker you just need to map the container's 9000 port to another port in the host). 8 | 9 | ## Running the application manually 10 | 11 | If you have a Java 8 + Maven 3.x development environment, just import the project on your IDE and run the class `com.github.rafaelrpinto.vulnerablejavawebapp.config.AppLauncher`. 12 | 13 | ## Running with docker 14 | 15 | If your workstation is not configured for Java 8 development the easiest way to run the application is with Docker. 16 | 17 | ```bash 18 | # gets the code 19 | git clone https://github.com/rafaelrpinto/VulnerableJavaWebApplication 20 | cd VulnerableJavaWebApplication 21 | 22 | # creates the docker image 23 | docker build -t vulnerable-java-application:0.1 . 24 | 25 | # creates/starts the container 26 | docker run --name vulnerable-java-application -p 9000:9000 -d vulnerable-java-application:0.1 27 | ``` 28 | ## Testing the application with Arachni and ModSecurity 29 | 30 | The [ARACHNI.MD](https://github.com/rafaelrpinto/VulnerableJavaWebApplication/blob/master/ARACHNI.MD) file has an example of default security scan with automatic login and other tweaks enabled. For more scanning options check https://github.com/Arachni/arachni. 31 | 32 | The ModSecurity scripts to protect this application are available [in my other repository](https://github.com/rafaelrpinto/ModSecurityScripts). 33 | 34 | The article that I wrote explaining how to use Arachni to check this application [is available on linkedin](https://www.linkedin.com/pulse/identifying-security-flaws-legacy-web-applications-arachni-pinto). 35 | 36 | If is there any problem running the application or you want to add more security flaws, feel free to open an issue or send a pull request. 37 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.github.rafaelrpinto 7 | vulnerablejavawebapp 8 | 0.0.1-SNAPSHOT 9 | 10 | 11 | org.springframework.boot 12 | spring-boot-starter-parent 13 | 1.4.2.RELEASE 14 | 15 | 16 | 17 | 1.8 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | org.apache.tomcat.embed 28 | tomcat-embed-jasper 29 | provided 30 | 31 | 32 | javax.servlet 33 | jstl 34 | 35 | 36 | org.springframework 37 | spring-jdbc 38 | 39 | 40 | com.h2database 41 | h2 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-maven-plugin 49 | ${parent.version} 50 | 51 | 52 | 53 | repackage 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/config/AppLauncher.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.config; 2 | 3 | import java.util.Collections; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.ServletContext; 7 | import javax.servlet.ServletException; 8 | import javax.servlet.SessionCookieConfig; 9 | import javax.servlet.SessionTrackingMode; 10 | import javax.sql.DataSource; 11 | 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.SpringApplication; 14 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 15 | import org.springframework.boot.context.embedded.ServletContextInitializer; 16 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 17 | import org.springframework.context.annotation.Bean; 18 | import org.springframework.context.annotation.ComponentScan; 19 | import org.springframework.jdbc.core.JdbcTemplate; 20 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; 21 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; 22 | import org.springframework.web.servlet.ViewResolver; 23 | import org.springframework.web.servlet.view.InternalResourceViewResolver; 24 | 25 | /** 26 | * Class that configures and launches the application. 27 | * 28 | * @author Rafael 29 | * 30 | */ 31 | @ComponentScan(basePackages = { "com.github.rafaelrpinto.vulnerablejavawebapp.controller", 32 | "com.github.rafaelrpinto.vulnerablejavawebapp.repository" }) 33 | @EnableAutoConfiguration 34 | public class AppLauncher { 35 | 36 | @Autowired 37 | private DataSource dataSource; 38 | 39 | @Bean 40 | public ViewResolver getViewResolver() { 41 | InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 42 | resolver.setPrefix("/WEB-INF/jsp/"); 43 | resolver.setSuffix(".jsp"); 44 | return resolver; 45 | } 46 | 47 | @Bean 48 | public DataSource dataSource() { 49 | EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); 50 | return builder.setType(EmbeddedDatabaseType.H2).addScript("db/schema.sql").addScript("db/data.sql").build(); 51 | } 52 | 53 | @Bean 54 | public JdbcTemplate getJdbcTemplate() { 55 | return new JdbcTemplate(dataSource); 56 | } 57 | 58 | @Bean 59 | public FilterRegistrationBean someFilterRegistration() { 60 | FilterRegistrationBean registration = new FilterRegistrationBean(); 61 | registration.setFilter(sessionUserFilter()); 62 | registration.addUrlPatterns("/secure/*"); 63 | registration.setName("sessionUserFilter"); 64 | registration.setOrder(1); 65 | return registration; 66 | } 67 | 68 | @Bean(name = "sessionUserFilter") 69 | public Filter sessionUserFilter() { 70 | return new SessionUserFilter(); 71 | } 72 | 73 | public static void main(String[] args) throws Exception { 74 | SpringApplication.run(AppLauncher.class, args); 75 | } 76 | 77 | // The following configurations are usally on the application servers and 78 | // not in the code 79 | // but since we are using spring boot to make things simple we configure via 80 | // code 81 | @SuppressWarnings("deprecation") 82 | @Bean 83 | public ServletContextInitializer servletContextInitializer() { 84 | return new ServletContextInitializer() { 85 | @Override 86 | public void onStartup(ServletContext servletContext) throws ServletException { 87 | servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE)); 88 | SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig(); 89 | sessionCookieConfig.setHttpOnly(true); 90 | } 91 | }; 92 | 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/config/SessionUserFilter.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.config; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import com.github.rafaelrpinto.vulnerablejavawebapp.model.User; 15 | 16 | /** 17 | * 18 | * Simple filter to manually check if the user is logged on secure context 19 | * requests. 20 | * 21 | * @author Rafael 22 | * 23 | */ 24 | public class SessionUserFilter implements Filter { 25 | 26 | @Override 27 | public void destroy() { 28 | } 29 | 30 | @Override 31 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) 32 | throws IOException, ServletException { 33 | HttpServletRequest request = (HttpServletRequest) servletRequest; 34 | HttpServletResponse response = (HttpServletResponse) servletResponse; 35 | 36 | User user = (User) request.getSession().getAttribute("sessionUser"); 37 | if (user == null) { 38 | response.sendRedirect("/login"); 39 | } else { 40 | chain.doFilter(request, response); 41 | } 42 | } 43 | 44 | @Override 45 | public void init(FilterConfig arg0) throws ServletException { 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/controller/AdvertisementController.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.controller; 2 | 3 | import java.util.Date; 4 | 5 | import javax.servlet.http.HttpSession; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.Model; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | 14 | import com.github.rafaelrpinto.vulnerablejavawebapp.model.Advertisement; 15 | import com.github.rafaelrpinto.vulnerablejavawebapp.model.User; 16 | import com.github.rafaelrpinto.vulnerablejavawebapp.repository.AdvertisementRepository; 17 | 18 | /** 19 | * 20 | * Controller responsible for requests related to Advertisements. 21 | * 22 | * @author Rafael 23 | * 24 | */ 25 | @Controller 26 | public class AdvertisementController { 27 | 28 | @Autowired 29 | private AdvertisementRepository advertisementRepository; 30 | 31 | @RequestMapping(value = "/") 32 | String home(Model model) { 33 | model.addAttribute("ads", this.advertisementRepository.findAll()); 34 | return "home"; 35 | } 36 | 37 | @RequestMapping(value = "/search") 38 | String search(@RequestParam("keyword") String keyword, Model model) { 39 | model.addAttribute("ads", this.advertisementRepository.findByKeyword(keyword)); 40 | model.addAttribute("keyword", keyword); 41 | return "home"; 42 | } 43 | 44 | @RequestMapping(value = "/secure/newAd", method=RequestMethod.GET) 45 | String showNewAdForm(Model model) { 46 | return "newAdForm"; 47 | } 48 | 49 | @RequestMapping(value = "/secure/newAd", method=RequestMethod.POST) 50 | String processNewAdForm(@RequestParam("title") String title, @RequestParam("text") String text, HttpSession session) { 51 | 52 | User user = (User) session.getAttribute("sessionUser"); 53 | 54 | Advertisement ad = new Advertisement(); 55 | ad.setTitle(title); 56 | ad.setText(text); 57 | ad.setCreateDate(new Date()); 58 | ad.setUser(user); 59 | 60 | this.advertisementRepository.insert(ad); 61 | 62 | return "redirect:/"; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.controller; 2 | 3 | import java.util.logging.Logger; 4 | 5 | import javax.servlet.http.HttpSession; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.ui.Model; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | 14 | import com.github.rafaelrpinto.vulnerablejavawebapp.model.User; 15 | import com.github.rafaelrpinto.vulnerablejavawebapp.repository.UserRepository; 16 | 17 | /** 18 | * 19 | * Controller for requests related to users. 20 | * 21 | * @author Rafael 22 | * 23 | */ 24 | @Controller 25 | public class UserController { 26 | 27 | private static final Logger LOGGER = Logger.getLogger( UserController.class.getName() ); 28 | 29 | @Autowired 30 | private UserRepository userRepository; 31 | 32 | @RequestMapping(value = "/logout", method = RequestMethod.GET) 33 | String showLogin(HttpSession session) { 34 | LOGGER.info("Logging out..."); 35 | session.invalidate(); 36 | return "redirect:/"; 37 | } 38 | 39 | @RequestMapping(value = "/login", method = RequestMethod.GET) 40 | String showLoginForm(Model model) { 41 | return "login"; 42 | } 43 | 44 | @RequestMapping(value = "/login", method = RequestMethod.POST) 45 | String processLoginForm(@RequestParam("login") String login, @RequestParam("password") String password, Model model, HttpSession session) { 46 | LOGGER.info("Processing login for " + login); 47 | User user = this.userRepository.authenticate(login, password); 48 | if (user != null) { 49 | LOGGER.info("Login successful!"); 50 | session.setAttribute("sessionUser", user); 51 | return "redirect:/"; 52 | } else { 53 | LOGGER.info("Invalid credentials!"); 54 | model.addAttribute("invalidCredentials", true); 55 | return showLoginForm(model); 56 | } 57 | } 58 | 59 | @RequestMapping(value = "/signUp", method = RequestMethod.GET) 60 | String showSignUpForm(Model model) { 61 | return "signUp"; 62 | } 63 | 64 | @RequestMapping(value = "/signUp", method = RequestMethod.POST) 65 | String processSignUpForm(@RequestParam("name") String name, @RequestParam("email") String email, @RequestParam("password") String password, 66 | Model model, HttpSession session) { 67 | LOGGER.info("Processing sign up form!"); 68 | User user = this.userRepository.find(email); 69 | if (user == null) { 70 | user = new User(); 71 | user.setName(name); 72 | user.setEmail(email); 73 | user.setPassword(password); 74 | 75 | this.userRepository.insert(user); 76 | session.setAttribute("sessionUser", user); 77 | 78 | LOGGER.info("Sugn up successful!"); 79 | 80 | return "forward:/"; 81 | } else { 82 | LOGGER.info("E-mail already exist: " + email); 83 | model.addAttribute("emailExists", true); 84 | return showSignUpForm(model); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/model/Advertisement.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.model; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | /** 7 | * 8 | * An advertisement made by an user. 9 | * 10 | * @author Rafael 11 | * 12 | */ 13 | public class Advertisement implements Serializable { 14 | 15 | private static final long serialVersionUID = 1743217303847332506L; 16 | 17 | private int id; 18 | private Date createDate; 19 | private String title; 20 | private String text; 21 | private User user; 22 | 23 | public Advertisement() { 24 | 25 | } 26 | 27 | public int getId() { 28 | return id; 29 | } 30 | 31 | public void setId(int id) { 32 | this.id = id; 33 | } 34 | 35 | public Date getCreateDate() { 36 | return createDate; 37 | } 38 | 39 | public void setCreateDate(Date createDate) { 40 | this.createDate = createDate; 41 | } 42 | 43 | public String getTitle() { 44 | return title; 45 | } 46 | 47 | public void setTitle(String title) { 48 | this.title = title; 49 | } 50 | 51 | public String getText() { 52 | return text; 53 | } 54 | 55 | public void setText(String text) { 56 | this.text = text; 57 | } 58 | 59 | public User getUser() { 60 | return user; 61 | } 62 | 63 | public void setUser(User user) { 64 | this.user = user; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/model/User.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.model; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * 7 | * Registered user of the application. 8 | * 9 | * @author Rafael 10 | * 11 | */ 12 | public class User implements Serializable { 13 | 14 | private static final long serialVersionUID = 5746803907489367890L; 15 | 16 | private int id; 17 | private String name; 18 | private String email; 19 | private String password; 20 | 21 | public User() { 22 | 23 | } 24 | 25 | public String getPassword() { 26 | return password; 27 | } 28 | 29 | public void setPassword(String password) { 30 | this.password = password; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | public int getId() { 42 | return id; 43 | } 44 | 45 | public void setId(int id) { 46 | this.id = id; 47 | } 48 | 49 | public String getEmail() { 50 | return email; 51 | } 52 | 53 | public void setEmail(String email) { 54 | this.email = email; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/repository/AdvertisementRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.repository; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.jdbc.core.JdbcTemplate; 8 | import org.springframework.jdbc.core.RowMapper; 9 | import org.springframework.jdbc.support.GeneratedKeyHolder; 10 | import org.springframework.jdbc.support.KeyHolder; 11 | import org.springframework.stereotype.Repository; 12 | 13 | import com.github.rafaelrpinto.vulnerablejavawebapp.model.Advertisement; 14 | import com.github.rafaelrpinto.vulnerablejavawebapp.model.User; 15 | 16 | /** 17 | * 18 | * Repository for advertisements. 19 | * 20 | * @author Rafael 21 | * 22 | */ 23 | @Repository 24 | public class AdvertisementRepository { 25 | 26 | @Autowired 27 | private JdbcTemplate jdbcTemplate; 28 | 29 | private static final RowMapper ROW_MAPPER = (rs, n) -> { 30 | Advertisement ad = new Advertisement(); 31 | ad.setId(rs.getInt("ID")); 32 | ad.setCreateDate(rs.getDate("CREATE_DATE")); 33 | ad.setTitle(rs.getString("TITLE")); 34 | ad.setText(rs.getString("TEXT")); 35 | 36 | User user = new User(); 37 | user.setId(rs.getInt("USER_ID")); 38 | user.setName(rs.getString("NAME")); 39 | user.setEmail(rs.getString("EMAIL")); 40 | ad.setUser(user); 41 | 42 | return ad; 43 | }; 44 | 45 | /** 46 | * Creates a new ad on the database. 47 | */ 48 | public void insert(Advertisement ad) { 49 | String sql = "INSERT INTO ADVERTISEMENT(CREATE_DATE, TITLE, TEXT, USER_ID) VALUES (?, ?, ?, ?)"; 50 | KeyHolder holder = new GeneratedKeyHolder(); 51 | 52 | this.jdbcTemplate.update((connection) -> { 53 | PreparedStatement pstmt = connection.prepareStatement(sql); 54 | pstmt.setDate(1, new java.sql.Date(ad.getCreateDate().getTime())); 55 | pstmt.setString(2, ad.getTitle()); 56 | pstmt.setString(3, ad.getText()); 57 | pstmt.setInt(4, ad.getUser().getId()); 58 | return pstmt; 59 | }, holder); 60 | 61 | ad.setId(holder.getKey().intValue()); 62 | } 63 | 64 | /** 65 | * @return All the ads ordered by date. 66 | */ 67 | public List findAll() { 68 | return this.jdbcTemplate.query(getBaseQuery() + " ORDER BY ad.CREATE_DATE DESC", ROW_MAPPER); 69 | } 70 | 71 | /** 72 | * @return All the ads with the matching keyword. 73 | */ 74 | public List findByKeyword(String keyword) { 75 | String sql = getBaseQuery() + " WHERE ad.TITLE LIKE ? OR ad.TEXT LIKE ? ORDER BY ad.CREATE_DATE DESC"; 76 | String wildcard = "%" + keyword + "%"; 77 | return this.jdbcTemplate.query(sql, new Object[] { wildcard, wildcard }, ROW_MAPPER); 78 | } 79 | 80 | private String getBaseQuery() { 81 | return "SELECT ad.ID, ad.CREATE_DATE, ad.TITLE, ad.TEXT, ad.USER_ID, u.NAME, u.EMAIL FROM " 82 | + "ADVERTISEMENT ad INNER JOIN USER u ON ad.USER_ID = u.ID"; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/github/rafaelrpinto/vulnerablejavawebapp/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.rafaelrpinto.vulnerablejavawebapp.repository; 2 | 3 | import java.sql.PreparedStatement; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.dao.EmptyResultDataAccessException; 7 | import org.springframework.jdbc.core.JdbcTemplate; 8 | import org.springframework.jdbc.core.RowMapper; 9 | import org.springframework.jdbc.support.GeneratedKeyHolder; 10 | import org.springframework.jdbc.support.KeyHolder; 11 | import org.springframework.stereotype.Repository; 12 | 13 | import com.github.rafaelrpinto.vulnerablejavawebapp.model.User; 14 | 15 | /** 16 | * 17 | * Repository for Users. 18 | * 19 | * @author Rafael 20 | * 21 | */ 22 | @Repository 23 | public class UserRepository { 24 | 25 | @Autowired 26 | private JdbcTemplate jdbcTemplate; 27 | 28 | private static final RowMapper ROW_MAPPER = (rs, n) -> { 29 | User user = new User(); 30 | user.setId(rs.getInt("ID")); 31 | user.setName(rs.getString("NAME")); 32 | user.setEmail(rs.getString("EMAIL")); 33 | return user; 34 | }; 35 | 36 | /** 37 | * Creates a new user on the database. 38 | */ 39 | public void insert(User user) { 40 | String sql = "INSERT INTO USER(NAME, EMAIL, PASSWORD) VALUES (?, ?, ?)"; 41 | KeyHolder holder = new GeneratedKeyHolder(); 42 | 43 | this.jdbcTemplate.update((connection) -> { 44 | PreparedStatement pstmt = connection.prepareStatement(sql); 45 | pstmt.setString(1, user.getName()); 46 | pstmt.setString(2, user.getEmail().toLowerCase().trim()); 47 | pstmt.setString(3, user.getPassword()); 48 | return pstmt; 49 | }, holder); 50 | 51 | user.setId(holder.getKey().intValue()); 52 | } 53 | 54 | /** 55 | * @return The user with the provided ID. 56 | */ 57 | public User find(int id) { 58 | String sql = getBaseQuery() + " WHERE ID = ?"; 59 | return this.jdbcTemplate.queryForObject(sql, new Object[] { id }, ROW_MAPPER); 60 | }; 61 | 62 | /** 63 | * @return The user with the provided e-mail. 64 | */ 65 | public User find(String email) { 66 | try { 67 | String sql = getBaseQuery() + " WHERE EMAIL = ?"; 68 | return this.jdbcTemplate.queryForObject(sql, new Object[] { email.toLowerCase().trim() }, ROW_MAPPER); 69 | } catch (EmptyResultDataAccessException e) { 70 | return null; 71 | } 72 | }; 73 | 74 | /** 75 | * @return the user if the provided credentials are correct. 76 | */ 77 | public User authenticate(String email, String password) { 78 | try { 79 | String sql = getBaseQuery() + " WHERE EMAIL = ? AND PASSWORD = ?"; 80 | return this.jdbcTemplate.queryForObject(sql, new Object[] { email.toLowerCase().trim(), password }, ROW_MAPPER); 81 | } catch (EmptyResultDataAccessException e) { 82 | return null; 83 | } 84 | }; 85 | 86 | private String getBaseQuery() { 87 | return "SELECT ID, NAME, EMAIL FROM USER"; 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=9000 2 | server.ssl.key-store = classpath:keystore.jks 3 | server.ssl.key-password = secret -------------------------------------------------------------------------------- /src/main/resources/db/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO USER(NAME, EMAIL, PASSWORD) VALUES 2 | ('User 1', 'user1@user1.com', 'abcd1234'), 3 | ('User 2', 'user2@user2.com', 'abcd1234'), 4 | ('User 3', 'user3@user3.com', 'abcd1234'); 5 | 6 | INSERT INTO ADVERTISEMENT(CREATE_DATE, TITLE, TEXT, USER_ID) VALUES 7 | ('2016-08-05', 'Advertisement 1', 'This is the advertisement one!', 1), 8 | ('2016-08-04', 'Advertisement 2', 'This is the advertisement two!', 2), 9 | ('2016-08-03', 'Advertisement 3', 'This is the advertisement three!', 3); 10 | -------------------------------------------------------------------------------- /src/main/resources/db/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE USER( 2 | ID INT PRIMARY KEY auto_increment, 3 | NAME VARCHAR(255) NOT NULL, 4 | EMAIL VARCHAR(255) NOT NULL UNIQUE, 5 | PASSWORD VARCHAR(255) NOT NULL 6 | ); 7 | 8 | CREATE TABLE ADVERTISEMENT( 9 | ID INT PRIMARY KEY auto_increment, 10 | CREATE_DATE DATE NOT NULL, 11 | TITLE VARCHAR(100) NOT NULL, 12 | TEXT CLOB NOT NULL, 13 | USER_ID INT NOT NULL, 14 | FOREIGN KEY(USER_ID) REFERENCES USER(ID) 15 | ); -------------------------------------------------------------------------------- /src/main/resources/keystore.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rafaelrpinto/VulnerableJavaWebApplication/b6f6aa8e545dff34b31dca1b84fe97e2e63206f2/src/main/resources/keystore.jks -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/home.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 4 | 5 | 6 | 7 | 8 | 9 | '">Create Advertisement 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | ${ad.title} (posted by ${ad.user.name} on ${ad.createDate}) 22 | ${ad.text} 23 | 24 | 25 | 26 | 27 | No advertisements found for "${keyword}" 28 | '">Go Back 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/include/footer.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | 4 |