iframe domain별 제한하기(Content Security Policy)
iframe의 domain별 제한을 위해 사용할 수 있는 header는 x-frame-options와 content-security-policy가 있다. x-frame-options는 IE를 사용하는 경우 문제가 없지만 다른 브라우저를 사용경우 무시될 수 있다.
- X-Frame-Options - HTTP | MDN
content-security-policy header를 사용하여 iframe domain별로 제한하는 방법에 대하여 알아보았다.
content-security-policy
content-security-policy header를 추가하는 방법은 아래와 같다.
Content-Security-Policy: <policy-directive>; <policy-directive>
content-security-policy의 policy-directive에는 여러 종류가 있다. font-src
, maniufest-src
, img-src
등 여러 resource를 제어할 수 있도록 구성되어 있다. 그 중에서 frame-src
, frame-ancestors
가 iframe에 관련된 directive이다.
child-src
도 CSP에서 iframe관련된 directive이지만,child-src
대신frame-src
를 사용할 것을 권장하고 있다.
frame-src
는 하위단의 iframe domain을 확인하는 것이고 frame-ancestors
는 상위의 domain을 확인하는 것이다. 예를 들어 https://example1.com/a.html page에 https://example2.com/b.html page를 iframe으로 넣을 경우 a.html에서 frame-src
를 사용하여 b.html을 제어하게 된다.
// a.html page header에 포함
Content-Security-Policy: frame-src https://example2.com
b.html에서는 frame-ancestors
를 사용하여 a.html을 제어하게 된다.
// b.html page header에 포함
Content-Security-Policy: frame-ancestors https://example1.com
html meta tag 사용
Html meta tag를 사용하여 CSP를 구성할 수 있다.
// meta tag
<meta http-equiv="Content-Security-Policy" frame-src https://example2.com">
helmet module 사용
Node 서버를 운영하는 경우 아래와 같이 helmet module을 사용하여 CSP를 구성할 수 있다.
const helmet = require('helmet')
const csp = require('helmet-csp')
// x-frame-options
app.use(helmet.frameguard({
action: 'allow-from',
domain: 'a.com',
}));
// content-security-policy
app.use(csp({
directives: {
frameSrc: ['a.com'],
frameAncestors: ['a.com']
}
}));