SV.CSRF.ORIGIN

This error identifies state changing requests handlers that do not validate requests are same origin.

Vulnerability and risk

Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated.

Standard HTTP headers (Origin, Referer) should be checked and compared to ensure the request complies with the same-origin policy. If the source origin, as identified by the Origin or Referer headers, doesn’t match the expected origin, we have a cross-origin request.

Code examples

Vulnerable code example 1

6    void doPost(HttpServletRequest req, HttpServletResponse resp) {
7        String action = req.getParameter("action");
8        String id = req.getParameter("id");
9    
10       if("update".equals(action)){
11           updateUser(id, req);
12       }
13       //...
14   }
15
16   void updateUser(String userid, HttpServletRequest req) {
17       //...
18   }

SV.CSRF.ORIGIN is reported on line 6: ‘req’ is never validated to be a same origin request. An attacker could cause a user’s browser to make a request on user’s behalf originating from a malicious site.

Fixed code example 1

6    void doPost(HttpServletRequest req, HttpServletResponse resp) { 
7        String origin = req.getHeader("Origin"); 
8        if(isSameOriginRequest(origin)) {
9            String action = req.getParameter("action");
10           String id = req.getParameter("id");
11
12           if ("update".equals(action)) {
13               updateUser(id, req);
14           }
15       }
16       //...
17   }
18
19   void updateUser(String userid, HttpServletRequest req) {
20       //...
21   }

This example checks standard headers for the source of the request (by inspecting the Origin header) and comparing to some expected value. If the values match, the request is same-origin.

Security training

Application security training materials provided by Secure Code Warrior.

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning Java analysis for more information.