Flagging Spring project for Missing_HSTS_Header in Checkmarx - java

I am currently working on a Spring project.
However it is being flagged by Checkmarx with the following error
MEDIUM SEVERITY VULNERABILITIES:
Missing_HSTS_Header (OWASP Top 10 2021)
File: con-delivery-app/src/main/webapp/index.jsp
Location: Line 1, Column 19
I have added the following class to try to fix the issue but it still doesn't help
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.headers()
.httpStrictTransportSecurity()
.includeSubDomains(true)
.maxAgeInSeconds(157680000);
}
}
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Hello from Delivery Orchestration</h1>
</body>
</html>

Related

SpringMVC (Security) - 403 error

I'm developing a simple Java web application with SpringMVC. With security enabled, I cannot send a HTTP post request (from the index.jsp) to the server although I am already authenticated. POST request does work when the security isn't implemented. So I think it's a problem with my SecurityConfig.java code.Could you please help me with this? Thanks very much
Error Code :
HTTP Status 403 – Forbidden
Type Status Report
Message Forbidden
Description The server understood the request but refuses to authorize it.
This is my security configuration.
SecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("{noop}123456").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers(HttpMethod.POST, "/index").hasRole("USER");
}
}
index.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<form action='#{/index}' method="POST">
<div class="form-group">
<td><textarea class="form-control" name="textForm">${text1}</textarea>
<input type="submit" value="Submit">
<textarea name="textFin">${textFinal}</textarea></td>
</form>
</div>
</body>
</html>
Add
http.csrf().disable(); to configure method.
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers(HttpMethod.POST, "/index").hasRole("USER")
.and()
.csrf().disable();
}
You are confusing jsp with thymleaf. Edit the jsp file to:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<form:form action="/index" method="POST">
<div class="form-group">
<td><textarea class="form-control" name="textForm">${text1}</textarea>
<input type="submit" value="Submit">
<textarea name="textFin">${textFinal}</textarea></td>
</form:form>
</div>
</body>
</html>
The UserDetailService bean that you have provided didn't work for me. I had to change it like this:
#Bean
public UserDetailsService userDetailsService() {
// ensure the passwords are encoded properly
#SuppressWarnings("deprecation")
UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("me").password("me").roles("USER").build());
return manager;
}
When we enable web security, for every form submitted, we need to send the _crsf(cross-site request forgery) token which is generated randomly base on the user's session.
If we don't want to use this token, we can disable it by calling .csrf().disable()
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers(HttpMethod.POST, "/index").hasRole("USER")
.and()
.csrf().disable();
}
But, in the real world, the token is preferred for security purposes. There are 2 approaches to generate the token.
Approach 1: Generating token automatically by form tag <form:form>. Spring MVC will help us generated the token behind the scenes.
use taglib:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
and modify <form action='#{/index}' method="POST"> to:
<form:form action='#{/index}' method="POST">
// our html code
</form:form>
Approach 2: Generating token manually by adding the hidden field.
Before the close form tag </form>, add the following code.
<form action='#{/index}' method="POST">
// our html code
...
<input type="hidden" name="_csrf.parameterName" value="_csrf.token" />
</form>

Java Spring Tool Suite security

I have a simple java application where I would like all my pages to have access to the style sheet folder and files even if the user has not been authenticated. I have the following code in my WebSecurityConfig.java file:
package com.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
// Add WebSecurityConfig class to configure security
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String USER = "USER";
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/security").permitAll()
.antMatchers("/css/**.css").permitAll()
.antMatchers("/hands_on").hasAnyRole(USER)
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
I have this code in my hands_on.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>hands on Demo</title>
<link th:href="#{/css/style.css}" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>hands on Demo</h1>
</body>
</html>
And I have this code in my login.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Demo</title>
<link th:href="#{/css/style.css}" rel="stylesheet" type="text/css" />
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="#{/login}" method="post">
<div><label> Enter your User Name : <input type="text" name="username"/> </label></div>
<div><label> Enter your Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
If I start my java application and launch a browser and go to localhost:8080/hands_on I would expect the login page to get displayed and be presented with my style sheet. What happens is the login page gets displayed but without the styles being applied. When I look at my javascript console, I see this:
Refused to apply style from 'http://localhost:8080/css/style.css' because its MIME type ('application/json') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
My style.css file is in the folder security[boot]/src/main/resources/static/css.
I thought I would have access to the style.css file based on the .antMatchers("/css/**.css").permitAll() in my WebSecurityConfig.java file but I guess I am missing something. Ideas?

why Thymeleaf's th:text not working in my Spring project?

I have included Thymeleaf for my Spring project for the first time and want to create a simple project(display one word using th:text). But I get nothing in my html page. Why?
Greeting.java
package com.supermegaproject.Main;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class Greeting
{
#GetMapping("/")
public String getMessage(Model model)
{
model.addAttribute("name", "John");
return "mainPage";
}
}
mainPage.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<h1>Main Page</h1> // DOES APPEAR
<h1 th:text="${name}"></h1> // DOESN'T APPEAR AT ALL
</body>
</html>
At first I thought it may be because of build.gradle. But after checking it looks ok, thymeleaf included, so I don't know why then.
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
Thank you in advance.
I solved it. All you had to do - is to delete Mustache dependency.

I have a text field in html.Now i want to take the data from the html page and import it to my JSP page.How to do that?

I have created the input form in html.Now to accept the data in my jsp page should I assign a string variable to accept the data in jsp Or what variable should I use.I want to store the data in mysql,There also I have created a text column.
this is a simple example
1/ you create a jsp page where you put your form with inputs
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> My first JSP </title>
</head>
<body>
<form action="HelloServlet" method="GET">
Please enter a color <br>
<input type="text" name="color" >
<input type="submit" value="submit">
</form>
</body>
</html>
2/ create a servlet :
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class HelloWorld extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String color= request.getParameter("color");
// HERE CALL A METHOD TO STORE DATA IN DATABASE exp insertInDB(color);
request.setAttribute("mycolor", color);// if you want to see your data
request.getRequestDispatcher("test.jsp").forward(request, response);
}
}
3/ create another JSP page (test.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> My first JSP </title>
</head>
<body>
the color is : ${mycolor}
</body>
</html>
4/ in your web.xml file you should have (or put)
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>

Can't access resources outside WEB-INF folder

I put index.jsp inside WEB-INF. Then I have a servlet which dispatch request to that file.
#WebServlet(name="Home", urlPatterns={"/"})
public class Home extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
}
I have a css folder which is outside the WEB-INF folder. It contains the css.css file.
The This is the content of index.jsp file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" href="<c:url value="/css/css.css" />" rel="stylesheet">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
The content of css file:
body {
color: red;
}
Question: Why doesn't the sentence "Hello World" turn red? Why can't the index.jsp file access the css file?
It looks like you are mapping your servlet "Home" for all incoming requests. So when the browser makes a request for the css url, it is intercepted by the servlet and it is unable to find it.
You can change the servlet mapping for the home servlet so that it does not intercept all requests
#WebServlet(name="Home", urlPatterns={"/home"})
Add following in your jsp
<link rel="stylesheet" type="text/css" href="/project-context-root-name/css/myfile.css"/>
If it did not work further then do below step.
In your web.xml file add following
<servlet-mapping>
<servlet-name>servlet-name</servlet-name>
<url-pattern>/css/*</url-pattern>
</servlet-mapping>

Categories