Express helmet

1 minute read

웹 서버에서 response header를 통해 보안을 간단하게 설정해주는 helmet을 적용해보았습니다.

개요

node + express 환경에서 Content-Security-Policy 같은 보안 설정을 helmet을 통해 쉽게 제어가 가능합니다.

예제 코드

const express = require('express')
const port = 3000
const helmet = require("helmet");
const app = express();
const https = require('https');
const fs = require('fs');

app.use(helmet()); //express.static 이전에 위치해야합니다.
app.use(express.static('public'));

const key = fs.readFileSync(__dirname + '/cert/key.pem');
const cert = fs.readFileSync(__dirname + '/cert/cert.pem');
const options = {
  key: key,
  cert: cert
};

const server = https.createServer(options, app);

server.listen(port, () => {
  console.log("server starting on port : " + port)
});

결과

설정 전 response header

Accept-Ranges: bytes
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Length: 255
Content-Type: text/html; charset=UTF-8
Date: Sun, 21 Mar 2021 03:53:51 GMT
ETag: W/"ff-1785279751a"
Keep-Alive: timeout=5
Last-Modified: Sun, 21 Mar 2021 01:49:54 GMT
X-Powered-By: Express

설정 후 response header

Accept-Ranges: bytes
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Length: 255
Content-Security-Policy: default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
Content-Type: text/html; charset=UTF-8
Date: Sun, 21 Mar 2021 03:51:24 GMT
ETag: W/"ff-1785279751a"
Expect-CT: max-age=0
Keep-Alive: timeout=5
Last-Modified: Sun, 21 Mar 2021 01:49:54 GMT
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-Permitted-Cross-Domain-Policies: none
X-XSS-Protection: 0

한눈에 봐도 response header에 여러 보안 설정이 적용된것을 확인할 수 있습니다.

helmet적용후 다른 origin에 대한 fetch 요청

Refused to connect to 'https://i.imgur.com/yX67htE.jpeg' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

브라우저 수준에서 요청 자체를 막는것을 확인 할 수 있습니다.

Leave a comment