cs

SOP, CORS, 공격 기법(CSRF과 XSS)

ssoonn 2024. 12. 18. 16:56

SOP(Same Origin Policy)

동일 출처 정책으로, 웹 보안의 기본 원칙

  • 동일한 origin에서만 리소스를 공유할 수 있다.
  • e.g. https://blog.example.comhttps://api.example.com은 다른 origin이므로, 리소스를 공유할 수 없다.

cf. origin의 개념

URL
세부 구성
Site   https://blog.example.com:0000/1
Domain
(Hostname)
domain https://blog.example.com:0000/1
Host domain + port https://blog.example.com:0000/1
Origin scheme + domain + port https://blog.example.com:0000/1

 

SOP 예외 및 Cross-Origin

SOP 정책에 따라서, Cross-Origin들은 기본적으로 접근이 차단되지만, 일부는 허용된다.

Script js, css embedded
cross origin
허용
Image 허용
Video 허용
FORM POST, GET 요청은 허용
응답에 대한 접근은 차단
AJAX   XMLHttpRequest, fetch API를 통한 Cross-Origin 요청 차단

FORM(동기 호출)과 AJAX(비동기 호출)는 api 호출 방법이다.

 


CORS (Cross-Origin Resource Sharing)

SOP 제약을 완화하기 위해 도입된 브라우저 보안 매커니즘 (for AJAX)

  • 브라우저의 요청-서버의 응답 간 승인/폐기를 결정하는 정책
  결정자 (브라우저의 요청) CORS
(승인/폐기)
정책 설정 (서버 응답)
  브라우저가 보내주는 요청 비교하여 승인/폐기 결정 서버에서 정의하는 것
우리는 어떤 요청만 허용해
origin https://blog.example.com = example.com
blog.example.com
method POST != GET, DELETE
header Content-Type = application/json = Content-Type = application/json
credential “include” 포함시킬 것
cookie, authorization 등 인증, 보안 헤더
= T or F 반환
(표 예시의 경우, T)

 

표의 경우, method에서 불일치하므로 폐기

 

  • 서버가 응답할 때, 허용된 Origin을 명시적으로 지정한다면 다른 Origin에서도 데이터를 요청할 수 있다.
    • 서버의 헤더 설정
      • Access-Control-Allow-Origin: *  -> 모든 Origin에서 접근 허용
      • Access-Control-Allow-Origin: https://example.com -> 특정 Origin에만 허용

 

요청의 종류

CORS는 요청을 확인한다.

  • 원래 요청(POST, GET 등) : 이하 A
  • 검증(CORS) 요청 : 이하 B
    • 검증헤더: origin, method, header, credentia.
      • 옵션을 통해 검사하고, 그 후 원래요청 수행
  요청 어떻게 보냄? 왜 나눠서 보냄?
non-preflight 한번에 원래 요청/검증요청을 보냄
모든 응답을 받아 폐기 여부 검토

A+B -> A,B 응답 => 폐기 결정
별 헤더 없음,, 상태 변경 안함

헤더 없는 GET, HEAD, POST
preflight 검증 요청 먼저 -> ok 시 원래 요청 -> 원래 요청에 대한 응답

B -> B? A응답 : 폐기
상태 변경함 -> 위험한 호출이므로, 신중

헤더 있는 GET, HEAD, POST
DELETE

 


공격 기법

CSRF (Cross-Site Request Forgery)

사용자가 인증된 상태에서, 공격자가 "사용자가 의도하지 않은" 요청 실행을 유도하는 것

  1. 사용자가 특정 웹사이트에 로그인한 상태에서 공격자가 조작한 링크나 폼에 접근.
  2. 브라우저가 사용자의 인증된 세션 쿠키를 자동으로 포함하여 요청을 전송.
  3. 서버는 요청이 유효한 사용자로부터 온 것처럼 인식하고 실행.
  • e.g. 사용자가 로그인한 상태에서 악성 사이트가 POST 요청을 보내 계좌 이체를 수행

대응 방안:

  • SameSite 쿠키 설정 → 다른 출처에서 쿠키를 전송하지 않도록 제한
    • SameSite=Strict → 동일 Origin에서만 쿠키 전송
    • SameSite=Lax → 일부 안전한 요청(GET)만 다른 Origin에 전송
  • Anti CSFR Token:
    • 부분 CSRF 방어책
    • 매번 서버가 의미없는 token 발생 -> AJAX, FORM은 요청 시 해당 토큰을 무조건 넣어 호출
      • e.g. OTP

XSS (Cross-Site Scripting) 

공격자가 악의적인 JavaScript를 삽입해 클라이언트에서 실행되도록 유도하는 것

  1. 공격자가 악성 JavaScript를 포함한 데이터를 입력 폼이나 URL에 삽입
  2. 서버가 이 데이터를 적절히 검증하지 않고 클라이언트로 반환 -> 악성 스크립트가 실행
  3. 사용자의 쿠키, 세션 토큰, 기타 민감한 정보를 탈취하거나, 사용자를 피싱 사이트로 리다이렉트

 

대응 방안:

  • 입력값 검증 및 필터링 (특수 문자 escape 처리) 등
  • CSP (Content Security Policy) 설정

JS Injection

XSS(크로스 사이트 스크립팅)의 주요 공격 방식 중 하나

  • 공격자가 JavaScript 코드를 삽입하여 브라우저에서 실행

대응 방안:

  • DOM purify
    • 불필요한 <tag> 삭제

 

 

cf. SQL Injection

데이터베이스를 대상으로 하는 공격

  • 웹 애플리케이션에서 사용자의 입력을 제대로 검증하지 않을 경우, 공격자가 SQL 쿼리를 변조하여 데이터베이스를 조작
    • SQL 구문에 악의적인 입력값을 추가하여 데이터를 유출하거나 삭제
SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';
# 쿼리가 항상 참으로, 인증 절차를 우회할 수 있다

 

대응 방안:

  • SQL sanitizing ""

 

ref.

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#cross-origin_network_access

 

Same-origin policy - Security on the web | MDN

The same-origin policy is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin.

developer.mozilla.org

 

https://medium.com/@zhaojunemail/sop-cors-csrf-and-xss-simply-explained-with-examples-af6119156726

 

SOP, CORS, CSRF and XSS simply explained with examples

If you read this article, you must have known these abbreviations and have some basic understanding of web security. This article is not…

medium.com

https://medium.com/datamindedbe/cors-and-the-sop-explained-f59de3a5078

 

CORS and the SOP explained

Introduction to Cross-Origin Resource Sharing (CORS) and the Same-Origin Policy (SOP). Structured as a dialogue, and focused on the why.

medium.com

https://gddaredevil.medium.com/what-is-all-the-fuss-with-sop-cors-and-csrf-4c8e441a5b98

 

WHAT IS ALL THE FUSS WITH SOP, CORS AND CSRF?

This is Part-1 of a three-part series on ‘What the all the Fuss with SOP, CORS and CSRF’. So, make sure to check the other ones out as…

gddaredevil.medium.com

https://www.ma-no.org/en/programming/javascript/cross-origin-resource-sharing-cors-and-examples-of-xss-and-csrf

 

Cross-Origin Resource Sharing (CORS) and examples of XSS and CSRF

Cross-Origin Resource Sharing (CORS) enables web clients to make HTTP requests to servers hosted on different origins. CORS is a… | Web design web development news, website design and online marketing. Web design, development, javascript, angular, react,

www.ma-no.org

https://lo-victoria.com/introduction-to-cross-origin-resource-sharing-cors

 

Introduction to Cross Origin Resource Sharing (CORS)

In web development practice, it is common for web apps to separate their front-end from back-end services. As such, accessing resources from the back-end requires the understanding of Cross-Origin Resource Sharing or CORS for short. It is an essentia...

lo-victoria.com