Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Security › Web attacks and defenses

Three web attacks

What happens when you trust input as it is

Why it exists — If user input is joined as it is onto an SQL string or HTML, the input is interpreted as a command or script rather than a value, and if login is checked by the cookie alone, a request triggered from another site is processed as if it were the user's own. Parameter binding and output escaping make input be treated only as a value and as text, a CSRF token demands a value that the browser does not attach automatically and so checks whether a request came from that site's own page. The SameSite attribute of a cookie makes the browser leave the cookie off requests that start from another site. It does not replace the CSRF token but is a secondary defense used together with it.

Where it's used today — PreparedStatement, MyBatis's #{} binding, escaping output such as Thymeleaf's th:text, and Spring Security's CSRF protection (on by default, it requires a CSRF token on requests such as POST) take care of this defense, and SameSite=Lax on the session cookie is a setting layered on top of it. A hole opens where user input goes into MyBatis's ${} or th:utext. For an API that sends a token in the Authorization header instead of a cookie, the browser does not attach the token automatically, so CSRF protection is sometimes turned off.

SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF) work on different principles. In one, the input becomes part of the SQL. In another, the input runs as a script in another user's browser. In the third, a logged-in user's browser is made to send a request on the attacker's behalf. CSRF is stopped by the CSRF token check that Spring Security does by default, and the SameSite attribute of the cookie is compared as a secondary defense used together with it.

Partly checked against real execution · Part of each of the three attacks was checked with SQLite, a browser, and a Spring Security server

Concepts in this lab

SQL injection
An attack in which user input is interpreted as part of a SQL statement, so a query that the attacker intended is executed. It happens when SQL is built by concatenating input values as strings. Parameterized queries with bind variables (PreparedStatement) separate the SQL structure from the values, so input is always treated only as a value, which prevents the attack.
Cross-site scripting (XSS)
An attack in which an attacker injects a malicious script into a web page so that it runs in another user's browser. It happens when a script placed in a post or a comment is output as is. The script can steal the user's cookies or send requests with the user's privileges. The basic defense is to convert special characters (escaping) when you output user input to the page.
Cross-site request forgery (CSRF)
An attack that takes advantage of the fact that a user is logged in: a page made by the attacker causes the user's browser to send an unintended request to the target site. The browser attaches cookies automatically, so the server treats it as a normal request. The primary defense is to require requests to include an unpredictable token issued by the server (a CSRF token, which Spring Security checks by default), and the SameSite attribute of cookies is a secondary defense used together with it.
Spring Security CSRF protection (CsrfFilter)
Why it exists — On a site that keeps the login with a cookie, the browser attaches the cookie even to requests triggered from other sites, so the cookie alone could not show whether the user sent the request from our own page. The SameSite attribute of a cookie works only when the browser supports it and the setting is right, and the cookie is still attached to a GET that follows a link and to requests from subdomains treated as the same site. That is why a token that the server can check itself is the primary defense, and SameSite is a secondary defense used together with it.
Where it's used today — With Spring Security it is on even if you configure nothing. View technologies connected to RequestDataValueProcessor, such as Thymeleaf, add the hidden _csrf input to POST forms automatically, and pages that send requests with JavaScript put the token in a header. An API server that is called only by clients other than browsers and authenticates with the Authorization header sometimes turns it off with http.csrf(csrf -> csrf.disable()).
The CSRF defense that Spring Security turns on by default. The server makes an unpredictable value per session (the CSRF token) and puts it in the forms of its pages as a hidden _csrf input, and for requests that change state, such as POST, PUT, and DELETE, it requires that value to be sent along as the request parameter _csrf or the X-CSRF-TOKEN header. CsrfFilter in the security filter chain compares it with the expected value, and if it is missing or wrong, rejects the request with 403 without passing it to the controller. The browser attaches cookies automatically, but the page itself has to put this value in, so a request triggered by a page of another site cannot contain it. By default the expected value is kept in the HttpSession (HttpSessionCsrfTokenRepository).
HttpOnly, Secure, and SameSite
Why it exists — A cookie could originally be read by scripts on the page, and it was sent along even over unencrypted HTTP connections and with requests that started from other sites. The server attaches these attributes to each cookie in the Set-Cookie header to choose and block these paths.
Where it's used today — It is usual to attach all three to a login session cookie. In Spring Boot, they are attached to the session cookie with the http-only, secure, and same-site settings under server.servlet.session.cookie.
Attributes that protect cookies. HttpOnly stops JavaScript from reading the cookie, which prevents the cookie from being stolen by a script injection attack. Secure makes the browser send the cookie only over HTTPS connections. SameSite restricts sending the cookie with requests that start from another site, which reduces CSRF attacks, but it is a secondary defense used together with a CSRF token, not a replacement for it.
Cookie
A small piece of data that a server sends in a response. The browser stores it and automatically sends it back with every request to the same site. HTTP does not remember state between requests, so this data is used to keep information that must carry over, such as a login state. Because it is stored in the user's browser, you must use it on the assumption that the user can read or change its contents.

Try these

Running with the default settings

  1. The attacker types ' OR '1'='1 in the password field. The intent is to close the string early with the single quote and attach a SQL condition after it.
  2. The server concatenated the input into the SQL string as is. The single quote in the input closed the string in the SQL, and the OR '1'='1' after it became part of the SQL syntax.
  3. '1'='1' is always true, so the whole WHERE condition becomes true. A member row is returned, and the server decides that the login succeeded.

Result of this run

Code

// The input is concatenated into a string (only the lines inside a method are shown; class, method declaration, imports, and the declarations of email, password, and statement omitted)
String sql = "SELECT * FROM member WHERE email = '" + email
           + "' AND password = '" + password + "'";
ResultSet rs = statement.executeQuery(sql);

Assumptions of this model

All three attacks are textbook examples to show the principle, and they follow the explanations of OWASP and the defenses in the Spring Security documentation. The login code that compares the password directly in SQL is there to explain SQL injection. In practice, passwords are stored as hashes and verified in the application. The comparison covers states with only one defense turned on, but in practice several defenses are layered. For all three attacks, part of the behavior was checked by actually running it. For SQL injection, on a real SQL engine (SQLite), string concatenation returned 1 row and the query with bind variables returned 0 rows. For XSS, in a real browser (Chromium-based), the script in the comment that was printed as is ran and read the cookie, it did not run when the output was escaped, and an HttpOnly cookie was not visible even when the script ran. For CSRF, on a POST submitted automatically from another site, a SameSite=None cookie was attached and a SameSite=Lax cookie was not. A cookie with no SameSite specified was attached right after it was issued, but was not attached after about 2 minutes. The server side of CSRF was checked by running a Spring Boot 4.1.1 and Spring Security 7.1.1 server. A server with CSRF protection left on rejected with 403 a POST that carried the session cookie but had no _csrf value or a wrong one, so the transfer method did not run, and it handled with 200 a POST that also sent the _csrf value the page had received. A server with it turned off by csrf.disable() made the transfer for a POST that carried only the session cookie, and the same-site=lax setting only added SameSite=Lax to Set-Cookie while the server handled requests the same way. A POST without the cookie was sent back to the login page (302). That Thymeleaf adds a hidden _csrf input to a POST form that uses th:action follows the Spring Security documentation (Thymeleaf is not in the environment used for checking). Treating the CSRF token as the primary defense and SameSite as a secondary defense used together with it follows the OWASP CSRF Prevention Cheat Sheet and the Spring Security documentation (Cross Site Request Forgery).

Previous lab: Method security · Next lab: CORS

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these