blog

Content Security Policy and X-Frame-Options

  • Content Security Policy
  • X-Frame-Options
  • 프로젝트를 하다보면 마주칠 수 있는 문제중 하나가 CSP(Content Security Policy)이다.
    사실 보안적으로 중요하며, 반드시 신경써야되는 부분이다. 이와 같이 X-Frame-Options도 살펴보아야 한다.

    Content Security Policy

    Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. (MDN)

    CSP는 보안을 위해 추가된 계층이다. CSP를 동작하게 하려면 웹 서버에서 Content-Security-Policy HTTP header를 리턴해줘야 한다. 예를 들어 Node js에서는 helmet 라이브러리를 이용하면 다음과 같이 설정할 수 있다.

    app.use(
      helmet.contentSecurityPolicy({
        useDefaults: true,
        directives: {
          "script-src": ["'self'", "example.com"],
          "style-src": null,
        },
      })
    );
    
    

    nginx 등의 load balancer를 이용한다면 서버 앞단에서 설정해줄 수도 있다.

    meta tag를 통해서도 삽입할 수 있다.

    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">

    지시문과 제한 대상

    지시문제한대상
    base-uri도큐먼트의 base URI(상대 경로의 시작점)
    child-src작업자와 삽입된 프레임 콘텐스에 대한 URL을 나열. Web Worker, <frame>, <iframe>으로 이용할 수 있는 URL
    connect-srcXMLHttpRequest, WebSocket, EventSource와 같은 자바스크립트로 연결할 출처
    font-srcCSS의 @font-face에서 로드할 웹 글꼴
    form-action<form> 태그에서 제출을 위해 유요한 엔드포인트를 나열
    frame-ancestors현재 페이지를 삽입할 수 있는 소스를 지정. <frame>, <iframe>, <embed>, <applet>태그에 적용됨.
    frame-src지원중단.
    img-src이미지 로드할 수 있는 출처
    media-src<audio>, <video>를 제공하는 출처
    object-src플래시나 자바 애플릿 등 기타 플러그인에 대한 제어
    script-src자바스크립트를 로드할 출처
    style-src읽기 가능한 스타일시트를 로드할 출처
    upgrade-insecure-request사용자 에이전트에 URL구성표를 다시 작성하여 HTTP를 HTTPS로 변경하도록 지시.

    default-src 지시문을 지정하여 이 기본 동작을 재정의할 수 있다. 이 지시문은 지정하지 않은 채로 두는 대부분의 지시문에 대한 기본값을 정의한다. 일반적으로 -src로 끝나는 모든 지시문에 이 사항이 적용이 된다.

    키워드/데이터 속성 및 설명

    키워드/데이터 속성설명
    none로드를 금지
    self같은 출처로 지정
    unsafe-inline스크립트 및 인라인의 <script> 태그, 이벤트 핸들러의 자바스크립트: 표기, 인라인의 <style>을 허가한다. 이름 그대로 XSS의 위험이 있음
    unsafe-eval문자열을 자바스크립트로서 실행하는 eval(), new Function(), setTimeout() 등의 실행을 허가한다. 이것도 XSS 위험이 있음
    data:data URI 허용
    mediastreammediastream:URI 허용
    blob:blob:URI 허용
    filesystem:filesystem:URI 허용

    Example of Content Security Policy

    Content-Security-Policy: img-src 'self' data: blob: filesystem: ;
    media-src mediastream; script-src 'self' https://example.com
    

    이외에도 report-uri 지시문을 통해 브라우저에서 위반 사항을 탐지했을 때 지정된 URL로 JSON형식의 위반보고서를 POST함.

    {
      "csp-report": {
        "document-uri": "http://example.org/page.html",
        "referrer": "http://evil.example.com/",
        "blocked-uri": "http://evil.example.com/evil.js",
        "violated-directive": "script-src 'self' https://apis.google.com",
        "original-policy": "script-src 'self' https://apis.google.com; report-uri http://example.org/my_amazing_csp_report_parser"
      }
    }

    referrer 지시문: referrer 동작을 변경
    reflected-xss 지시문: allow, block, filter option을 통해 반사형 크로스 사이트 스크립팅으로 불리는 공격에 대한 필터를 활성화(X-XSS-Protection header와 동일한 효과)

    X-Frame-Options

    X-Frame-Options Header는 MDN에서 말하고 있는 것 그자체로 간단하다. deny, sameorigin, allow-from 옵션 3가지가 있다. 그 중 allow-from은 대부분의 브라우저에서 지원하고 있지 않으므로 사용하지 못한다고 봐도 무방하다.

    The X-Frame-Options HTTP 응답 헤더는 해당 페이지를 <frame> 또는<iframe>, <object>에서 렌더링할 수 있는지 여부를 나타내는데 사용됩니다. - MDN

    1. deny: 어떤 사이트에서도 frame상에서 보여질 수 없음
    2. sameorigin: 동일한 사이트의 frame에서만 보여짐
    3. allow-from uri: 지정된 특정 uri의 frame에서만 보여짐

    Content Security Policy vs X-Frame-Options

    그렇다면 CSP의 child-src, frame-ancestors 같은 지시문이 X-Frame-Options Header와 같이 쓰였을 때는 어떻게 동작할까? 다음과 같이 stackoverflow에서 답을 찾을 수 있었다. 간단히 말하면 frame-ancestors 지시문이 있을 때 X-Frame-Options는 무시된다.

    This directive is similar to the X-Frame-Options header that several user agents have implemented. The 'none' source expression is roughly equivalent to that header’s DENY, 'self' to SAMEORIGIN, and so on. The major difference is that many user agents implement SAMEORIGIN such that it only matches against the top-level document’s location. This directive checks each ancestor. If any ancestor doesn’t match, the load is cancelled. RFC7034

    The frame-ancestors directive obsoletes the X-Frame-Options header. If a resource has both policies, the frame-ancestors policy SHOULD be enforced and the X-Frame-Options policy SHOULD be ignored.

    관련자료

    살펴보면 좋을 자료
    참고

    alb에서는 CORS를 지원하지 않는다

    관련자료

    Top
    Copyright©2022 Klog(blackbell) all right reserved