exploits.adoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. = Exploit Protection Migrations
  2. The following steps relate to changes around how to configure CSRF.
  3. == Defer Loading CsrfToken
  4. In Spring Security 5, the default behavior is that the `CsrfToken` will be loaded on every request.
  5. This means that in a typical setup, the `HttpSession` must be read for every request even if it is unnecessary.
  6. [NOTE]
  7. ====
  8. Some examples of where it should be unnecessary to read the session include endpoints marked `permitAll()` such as static assets, static HTML pages, single-page applications hosted under the same domain/server, etc.
  9. ====
  10. In Spring Security 6, the default is that the lookup of the `CsrfToken` will be deferred until it is needed.
  11. [NOTE]
  12. ====
  13. The `CsrfToken` is needed whenever a request is made with an HTTP verb that would change the state of the application.
  14. This is covered in detail in xref:features/exploits/csrf.adoc#csrf-protection-read-only[Safe Methods Must be Read-only].
  15. Additionally, it is needed by any request that renders the token to the response, such as a web page with a `<form>` tag that includes a hidden `<input>` for the CSRF token.
  16. ====
  17. To opt into the new Spring Security 6 default, the following configuration can be used.
  18. [[servlet-opt-in-defer-loading-csrf-token]]
  19. .Defer Loading `CsrfToken`
  20. [tabs]
  21. ======
  22. Java::
  23. +
  24. [source,java,role="primary"]
  25. ----
  26. @Bean
  27. public SecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
  28. CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
  29. // set the name of the attribute the CsrfToken will be populated on
  30. requestHandler.setCsrfRequestAttributeName("_csrf");
  31. http
  32. // ...
  33. .csrf((csrf) -> csrf
  34. .csrfTokenRequestHandler(requestHandler)
  35. );
  36. return http.build();
  37. }
  38. ----
  39. Kotlin::
  40. +
  41. [source,kotlin,role="secondary"]
  42. ----
  43. @Bean
  44. open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
  45. val requestHandler = CsrfTokenRequestAttributeHandler()
  46. // set the name of the attribute the CsrfToken will be populated on
  47. requestHandler.setCsrfRequestAttributeName("_csrf")
  48. http {
  49. csrf {
  50. csrfTokenRequestHandler = requestHandler
  51. }
  52. }
  53. return http.build()
  54. }
  55. ----
  56. XML::
  57. +
  58. [source,xml,role="secondary"]
  59. ----
  60. <http>
  61. <!-- ... -->
  62. <csrf request-handler-ref="requestHandler"/>
  63. </http>
  64. <b:bean id="requestHandler"
  65. class="org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler"
  66. p:csrfRequestAttributeName="_csrf"/>
  67. ----
  68. ======
  69. [NOTE]
  70. ====
  71. When the `CsrfToken` is deferred (the default in Spring Security 6), some applications may break due to the fact that they were designed with non-deferred CSRF tokens.
  72. See <<servlet-defer-loading-csrf-token-opt-out,Opt-out Steps>> below for more information.
  73. ====
  74. [[servlet-defer-loading-csrf-token-opt-out]]
  75. === Opt-out Steps
  76. If configuring the `CsrfToken` to be deferred gives you trouble, take a look at these scenarios for optimal opt out behavior:
  77. ==== I am using a Single-Page Application with `CookieCsrfTokenRepository`
  78. If you are using a single-page app (SPA) to connect to a backend protected by Spring Security along with `CookieCsrfTokenRepository.withHttpOnlyFalse()`, you may find that the CSRF token is no longer returned to your application as a cookie on the first request to the server.
  79. In this case, you have several options for restoring the behavior your client-side application expects.
  80. One option is to add a `Filter` that eagerly renders the `CsrfToken` to the response regardless of which request is made first, like so:
  81. .Add a `Filter` to return a cookie on the response
  82. [tabs]
  83. ======
  84. Java::
  85. +
  86. [source,java,role="primary"]
  87. ----
  88. @Bean
  89. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  90. CookieCsrfTokenRepository tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
  91. CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
  92. // set the name of the attribute the CsrfToken will be populated on
  93. requestHandler.setCsrfRequestAttributeName("_csrf");
  94. http
  95. // ...
  96. .csrf((csrf) -> csrf
  97. .csrfTokenRepository(tokenRepository)
  98. .csrfTokenRequestHandler(requestHandler)
  99. )
  100. .addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class);
  101. return http.build();
  102. }
  103. private static final class CsrfCookieFilter extends OncePerRequestFilter {
  104. @Override
  105. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
  106. throws ServletException, IOException {
  107. CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
  108. // Render the token value to a cookie by causing the deferred token to be loaded
  109. csrfToken.getToken();
  110. filterChain.doFilter(request, response);
  111. }
  112. }
  113. ----
  114. Kotlin::
  115. +
  116. [source,kotlin,role="secondary"]
  117. ----
  118. @Bean
  119. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  120. val tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse()
  121. val requestHandler = CsrfTokenRequestAttributeHandler()
  122. // set the name of the attribute the CsrfToken will be populated on
  123. requestHandler.setCsrfRequestAttributeName("_csrf")
  124. http {
  125. csrf {
  126. csrfTokenRepository = tokenRepository
  127. csrfTokenRequestHandler = requestHandler
  128. }
  129. addFilterAfter<BasicAuthenticationFilter>(CsrfCookieFilter())
  130. }
  131. return http.build()
  132. }
  133. class CsrfCookieFilter : OncePerRequestFilter() {
  134. override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) {
  135. val csrfToken = request.getAttribute(CsrfToken::class.java.name) as CsrfToken
  136. // Render the token value to a cookie by causing the deferred token to be loaded
  137. csrfToken.token
  138. filterChain.doFilter(request, response)
  139. }
  140. }
  141. ----
  142. ======
  143. The option above does not require changes to the single-page application, but does cause the `CsrfToken` to be loaded on every request.
  144. If you do not wish to add a `Filter` to eagerly load tokens on every request, additional options are listed below.
  145. ==== I am using a Single-Page Application with `HttpSessionCsrfTokenRepository`
  146. If you are using sessions, your application will benefit from deferred tokens.
  147. Instead of opting out, another option is to add a new `@RestController` with a `/csrf` endpoint, like so:
  148. .Add a `/csrf` endpoint
  149. [tabs]
  150. ======
  151. Java::
  152. +
  153. [source,java,role="primary"]
  154. ----
  155. @RestController
  156. public class CsrfController {
  157. @GetMapping("/csrf")
  158. public CsrfToken csrf(CsrfToken csrfToken) {
  159. return csrfToken;
  160. }
  161. }
  162. ----
  163. Kotlin::
  164. +
  165. [source,kotlin,role="secondary"]
  166. ----
  167. @RestController
  168. class CsrfController {
  169. @GetMapping("/csrf")
  170. fun csrf(csrfToken: CsrfToken): CsrfToken {
  171. return csrfToken
  172. }
  173. }
  174. ----
  175. ======
  176. [NOTE]
  177. ====
  178. You may consider adding `.requestMatchers("/csrf").permitAll()` if the endpoint above is required prior to authenticating with the server.
  179. ====
  180. The `/csrf` endpoint would need to be consumed by the client-side application in order to bootstrap the application for subsequent requests.
  181. [NOTE]
  182. ====
  183. Instructions for calling the `/csrf` endpoint on application launch are specific to your client-side framework and therefore outside the scope of this document.
  184. ====
  185. [NOTE]
  186. ====
  187. While this requires changes to your single-page application, the benefit is that the CSRF token is only loaded once and the token can continue to be deferred.
  188. This approach works particularly well with applications that use `HttpSessionCsrfTokenRepository` and do benefit from deferred tokens by allowing the `HttpSession` not to be read on every request.
  189. ====
  190. If you simply wish to opt out of deferred tokens altogether, that option is listed next.
  191. ==== I need to opt out of deferred tokens for another reason
  192. If deferred tokens break your application for another reason, then you can explicitly opt into the 5.8 defaults using the following configuration:
  193. .Explicit Configure `CsrfToken` with 5.8 Defaults
  194. [tabs]
  195. ======
  196. Java::
  197. +
  198. [source,java,role="primary"]
  199. ----
  200. @Bean
  201. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  202. CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
  203. // set the name of the attribute the CsrfToken will be populated on
  204. requestHandler.setCsrfRequestAttributeName(null);
  205. http
  206. // ...
  207. .csrf((csrf) -> csrf
  208. .csrfTokenRequestHandler(requestHandler)
  209. );
  210. return http.build();
  211. }
  212. ----
  213. Kotlin::
  214. +
  215. [source,kotlin,role="secondary"]
  216. ----
  217. @Bean
  218. open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  219. val requestHandler = CsrfTokenRequestAttributeHandler()
  220. // set the name of the attribute the CsrfToken will be populated on
  221. requestHandler.setCsrfRequestAttributeName(null)
  222. http {
  223. csrf {
  224. csrfTokenRequestHandler = requestHandler
  225. }
  226. }
  227. return http.build()
  228. }
  229. ----
  230. XML::
  231. +
  232. [source,xml,role="secondary"]
  233. ----
  234. <http>
  235. <!-- ... -->
  236. <csrf request-handler-ref="requestHandler"/>
  237. </http>
  238. <b:bean id="requestHandler"
  239. class="org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler">
  240. <b:property name="csrfRequestAttributeName">
  241. <b:null/>
  242. </b:property>
  243. </b:bean>
  244. ----
  245. ======
  246. [NOTE]
  247. ====
  248. By setting the `csrfRequestAttributeName` to `null`, the `CsrfToken` must first be loaded to determine what attribute name to use.
  249. This causes the `CsrfToken` to be loaded on every request.
  250. ====
  251. == Protect against CSRF BREACH
  252. If the steps for <<Defer Loading CsrfToken>> work for you, then you can also opt into Spring Security 6's default support for BREACH protection of the `CsrfToken` using the following configuration:
  253. .`CsrfToken` BREACH Protection
  254. [tabs]
  255. ======
  256. Java::
  257. +
  258. [source,java,role="primary"]
  259. ----
  260. @Bean
  261. DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
  262. XorCsrfTokenRequestAttributeHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();
  263. // set the name of the attribute the CsrfToken will be populated on
  264. requestHandler.setCsrfRequestAttributeName("_csrf");
  265. http
  266. // ...
  267. .csrf((csrf) -> csrf
  268. .csrfTokenRequestHandler(requestHandler)
  269. );
  270. return http.build();
  271. }
  272. ----
  273. Kotlin::
  274. +
  275. [source,kotlin,role="secondary"]
  276. ----
  277. @Bean
  278. open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
  279. val requestHandler = XorCsrfTokenRequestAttributeHandler()
  280. // set the name of the attribute the CsrfToken will be populated on
  281. requestHandler.setCsrfRequestAttributeName("_csrf")
  282. http {
  283. csrf {
  284. csrfTokenRequestHandler = requestHandler
  285. }
  286. }
  287. return http.build()
  288. }
  289. ----
  290. XML::
  291. +
  292. [source,xml,role="secondary"]
  293. ----
  294. <http>
  295. <!-- ... -->
  296. <csrf request-handler-ref="requestHandler"/>
  297. </http>
  298. <b:bean id="requestHandler"
  299. class="org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler"
  300. p:csrfRequestAttributeName="_csrf"/>
  301. ----
  302. ======
  303. [[servlet-csrf-breach-opt-out]]
  304. === Opt-out Steps
  305. If configuring CSRF BREACH protection gives you trouble, take a look at these scenarios for optimal opt out behavior:
  306. ==== I am using AngularJS or another Javascript framework
  307. If you are using AngularJS and the https://angular.io/api/common/http/HttpClientXsrfModule[HttpClientXsrfModule] (or a similar module in another framework) along with `CookieCsrfTokenRepository.withHttpOnlyFalse()`, you may find that automatic support no longer works.
  308. In this case, you can configure Spring Security to validate the raw `CsrfToken` from the cookie while keeping CSRF BREACH protection of the response using a custom `CsrfTokenRequestHandler` with delegation, like so:
  309. .Configure `CsrfToken` BREACH Protection to validate raw tokens
  310. [tabs]
  311. ======
  312. Java::
  313. +
  314. [source,java,role="primary"]
  315. ----
  316. @Bean
  317. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  318. CookieCsrfTokenRepository tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
  319. XorCsrfTokenRequestAttributeHandler delegate = new XorCsrfTokenRequestAttributeHandler();
  320. // set the name of the attribute the CsrfToken will be populated on
  321. delegate.setCsrfRequestAttributeName("_csrf");
  322. // Use only the handle() method of XorCsrfTokenRequestAttributeHandler and the
  323. // default implementation of resolveCsrfTokenValue() from CsrfTokenRequestHandler
  324. CsrfTokenRequestHandler requestHandler = delegate::handle;
  325. http
  326. // ...
  327. .csrf((csrf) -> csrf
  328. .csrfTokenRepository(tokenRepository)
  329. .csrfTokenRequestHandler(requestHandler)
  330. );
  331. return http.build();
  332. }
  333. ----
  334. Kotlin::
  335. +
  336. [source,kotlin,role="secondary"]
  337. ----
  338. @Bean
  339. open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
  340. val tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse()
  341. val delegate = XorCsrfTokenRequestAttributeHandler()
  342. // set the name of the attribute the CsrfToken will be populated on
  343. delegate.setCsrfRequestAttributeName("_csrf")
  344. // Use only the handle() method of XorCsrfTokenRequestAttributeHandler and the
  345. // default implementation of resolveCsrfTokenValue() from CsrfTokenRequestHandler
  346. val requestHandler = CsrfTokenRequestHandler(delegate::handle)
  347. http {
  348. csrf {
  349. csrfTokenRepository = tokenRepository
  350. csrfTokenRequestHandler = requestHandler
  351. }
  352. }
  353. return http.build()
  354. }
  355. ----
  356. XML::
  357. +
  358. [source,xml,role="secondary"]
  359. ----
  360. <http>
  361. <!-- ... -->
  362. <csrf token-repository-ref="tokenRepository"
  363. request-handler-ref="requestHandler"/>
  364. </http>
  365. <b:bean id="tokenRepository"
  366. class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"
  367. p:cookieHttpOnly="false"/>
  368. ----
  369. ======
  370. This is the RECOMMENDED way to configure Spring Security to work with a client-side application that uses cookie values, because it continues to allow the response to return a randomized value for the CSRF token in case the application returns HTML or other responses that could be vulnerable to BREACH without your knowledge.
  371. [NOTE]
  372. ====
  373. BREACH protection works to protect the token when it is included in a response body that can be GZIP compressed, which generally does not include headers and cookies.
  374. ====
  375. [TIP]
  376. ====
  377. Any token value returned by the server can be used successfully by the client-side application because the underlying (raw) CSRF token does not change.
  378. It is not required for an AngularJS (or similar) application to refresh the CSRF token before/after every request.
  379. ====
  380. If you simply wish to opt out of CSRF BREACH protection altogether, that option is listed next.
  381. ==== I need to opt out of CSRF BREACH protection for another reason
  382. If CSRF BREACH protection does not work for you for another reason, you can opt out using the configuration from the <<servlet-opt-in-defer-loading-csrf-token>> section.
  383. == CSRF BREACH with WebSocket support
  384. If the steps for <<Protect against CSRF BREACH>> work for normal HTTP requests and you are using xref:servlet/integrations/websocket.adoc[WebSocket Security] support, then you can also opt into Spring Security 6's default support for BREACH protection of the `CsrfToken` with xref:servlet/integrations/websocket.adoc#websocket-sameorigin-csrf[Stomp headers].
  385. .WebSocket Security BREACH Protection
  386. [tabs]
  387. ======
  388. Java::
  389. +
  390. [source,java,role="primary"]
  391. ----
  392. @Bean
  393. ChannelInterceptor csrfChannelInterceptor() {
  394. return new XorCsrfChannelInterceptor();
  395. }
  396. ----
  397. Kotlin::
  398. +
  399. [source,kotlin,role="secondary"]
  400. ----
  401. @Bean
  402. open fun csrfChannelInterceptor(): ChannelInterceptor {
  403. return XorCsrfChannelInterceptor()
  404. }
  405. ----
  406. XML::
  407. +
  408. [source,xml,role="secondary"]
  409. ----
  410. <b:bean id="csrfChannelInterceptor"
  411. class="org.springframework.security.messaging.web.csrf.XorCsrfChannelInterceptor"/>
  412. ----
  413. ======
  414. If configuring CSRF BREACH protection for WebSocket Security gives you trouble, you can configure the 5.8 default using the following configuration:
  415. .Configure WebSocket Security with 5.8 default
  416. [tabs]
  417. ======
  418. Java::
  419. +
  420. [source,java,role="primary"]
  421. ----
  422. @Bean
  423. ChannelInterceptor csrfChannelInterceptor() {
  424. return new CsrfChannelInterceptor();
  425. }
  426. ----
  427. Kotlin::
  428. +
  429. [source,kotlin,role="secondary"]
  430. ----
  431. @Bean
  432. open fun csrfChannelInterceptor(): ChannelInterceptor {
  433. return CsrfChannelInterceptor()
  434. }
  435. ----
  436. XML::
  437. +
  438. [source,xml,role="secondary"]
  439. ----
  440. <b:bean id="csrfChannelInterceptor"
  441. class="org.springframework.security.messaging.web.csrf.CsrfChannelInterceptor"/>
  442. ----
  443. ======