스프링

https://gs.saro.me/#!m=elec&jn=823




CSRF 시리즈
1. 공격법과 방어법 (XSS 설명 추가)
- https://gs.saro.me/#!m=elec&jn=822
2. 스프링 시큐리티를 이용한 적용 (확장 태그 미지원 템플릿을 위한)
- https://gs.saro.me/#!m=elec&jn=823


스프링 시큐리티 설치
- 스프링 시큐리티 시리즈
https://gs.saro.me/#!m=elec&p=1&jn=790
스프링 시큐리티 설치시 기본으로 csrf 가 작동합니다.


Mustache 예제
또 여러가지 지원을 해주지 않는 머스터치를 위해 인터셉터를 추가해보겠습니다.

 
  1. <html>
  2. <body>
  3. <form method="POST" enctype="multipart/form-data" action="/넘길페이지">
  4. <div>
  5. <input type="submit" value="Upload" />
  6. </div>
  7. </form>
  8. </body>
  9. </html>

보통 위와 같이 넘기게 될경우 403 (서비스 거부) 오류가 날 것입니다.
머스터치에선 바로 시큐리티를 빼올 수 없기 때문에 HandlerInterceptor 를 써보겠습니다.


 
  1. <html>
  2. <body>
  3. <form method="POST" enctype="multipart/form-data" action="/넘길페이지">
  4. <div>
  5. <input type="hidden" name="_csrf" value="{{#_csrf}}token{{/_csrf}}" />
  6. <input type="submit" value="Upload" />
  7. </div>
  8. </form>
  9. </body>
  10. </html>

_csrf.token 으로 값을 주었습니다.
HandlerInterceptorAdapter
- 참고 : https://gs.saro.me/#!m=elec&jn=810


 
  1. @Component
  2. public class CsrfInterceptor extends HandlerInterceptorAdapter
  3. {
  4. @Override
  5. public void postHandle
  6. (
  7. HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView
  8. ) throws Exception
  9. {
  10. if (modelAndView != null)
  11. {
  12. // _csrf 를 찾아.
  13. modelAndView.addObject("_csrf", new Mustache.Lambda()
  14. {
  15. public void execute(Template.Fragment frag, Writer out) throws IOException
  16. {
  17. // token 에 해당할 경우
  18. if ("token".equals(frag.execute()))
  19. {
  20. // 토큰으로 치환
  21. out.write( ((CsrfToken) req.getAttribute(CsrfToken.class.getName())).getToken() );
  22. }
  23. }
  24. });
  25. }
  26.  
  27. super.postHandle(req, res, handler, modelAndView);
  28. }
  29. }

인터셉터 추가


 
  1. @Configuration
  2. public class WebMvcConfig extends WebMvcConfigurerAdapter
  3. {
  4. @Autowired
  5. CsrfInterceptor csrfInterceptor;
  6.  
  7. @Override
  8. public void addInterceptors(InterceptorRegistry registry)
  9. {
  10. registry.addInterceptor(csrfInterceptor);
  11. }
  12. }



실행
소스보기를 누르면 아래와같이 추가되어있을겁니다.
물론 저 벨류는 랜덤한 값으로 보냅니다. (강의 1장 참고)


 
  1. <html>
  2. <body>
  3. <form method="POST" enctype="multipart/form-data" action="/넘길페이지">
  4. <div>
  5. <input type="hidden" name="_csrf" value="a60159ae-9b7f-45dc-9c97-3a5f14a39cbd" />
  6. <input type="submit" value="Upload" />
  7. </div>
  8. </form>
  9. </body>
  10. </html>

그리고 넘겼을 경우 403없이 정상 작동할 경우 성공!!

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

움 안에서 떡 받는다 , 구하지도 않은 좋은 물건을 뜻밖에 얻게 됨을 이르는 말.

댓글 ( 4)

댓글 남기기

작성

스프링 목록    more