Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the vulnerability created by using entities at a requestMapping method?

I have a controller with a method like

@PostMapping(value="/{reader}")
public String addToReadingList(@PathVariable("reader") String reader, Book book) {
    book.setReader(reader);
    readingListRepository.save(book);
    return "redirect:/readingList/{reader}";
}

When I run a static code analysis with Sonarqube I get a vulnerability report stating that

Replace this persistent entity with a simple POJO or DTO object

But if I use a DTO (which has exactly the same fields as the entity class, then I get another error:

1 duplicated blocks of code must be removed

What should be the right solution?

Thanks in advance. Enric

like image 840
eprats Avatar asked Jan 17 '19 10:01

eprats


2 Answers

You should build a new separate class which represents your Entity ("Book" ) as Plain Old Java Object (POJO) or Data Transfer Object (DTO). If you use JSF or other stateful technology this rule is important. If your entity is stateful there might be open JPA sessions etc. which may modify your database (e.g. if you call a setter in JSF on a stateful bean).

For my projects I ignore this Sonar rule because of two reasons:

  • I alway you REST and REST will map my Java Class into JSON which can be seen as a DTO.
  • REST is stateless (no server session) so no database transaction will be open after the transformation to JSON
like image 133
Simon Avatar answered Nov 03 '22 18:11

Simon


Information obtained from sonarsource official documentation.

On one side, Spring MVC automatically bind request parameters to beans declared as arguments of methods annotated with @RequestMapping. Because of this automatic binding feature, it’s possible to feed some unexpected fields on the arguments of the @RequestMapping annotated methods.

On the other end, persistent objects (@Entity or @Document) are linked to the underlying database and updated automatically by a persistence framework, such as Hibernate, JPA or Spring Data MongoDB.

These two facts combined together can lead to malicious attack: if a persistent object is used as an argument of a method annotated with @RequestMapping, it’s possible from a specially crafted user input, to change the content of unexpected fields into the database.

For this reason, using @Entity or @Document objects as arguments of methods annotated with @RequestMapping should be avoided.

In addition to @RequestMapping, this rule also considers the annotations introduced in Spring Framework 4.3: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping.

See More Here

like image 27
Shoniisra Avatar answered Nov 03 '22 17:11

Shoniisra