Node.js에서 sanitize-html 미들웨어로 XSS 공격 방지하기

Node.js에서 sanitize-html 미들웨어로 XSS 공격 방지하기

XSS(크로스 사이트 스크립팅) 공격은 웹 애플리케이션에서 매우 흔한 보안 취약점 중 하나입니다. 이러한 공격은 악의적인 스크립트가 사용자의 브라우저에서 실행되게 하여 사용자의 데이터를 탈취할 수 있습니다. Node.js 애플리케이션에서 이를 방지하기 위해 sanitize-html 미들웨어를 사용할 수 있습니다.

sanitize-html이란?

  • sanitize-html은 받은 HTML에서 XSS(크로스 사이트 스크립팅) 공격을 방지하기 위해 사용할 수 있는 태그, 속성, 스타일 등을 제거하거나 정리(clean)하는 데 사용되는 라이브러리입니다.
  • 웹 어플리케이션에서 사용자 입력을 HTML로 출력할 때, 악의적인 스크립트가 실행되는 것을 방지하기 위해 이 라이브러리를 사용해 입력 값을 정화합니다.
  • 예를 들어, sanitizeHtml('<script>alert("xss")</script><p>This is valid</p>')<p>This is valid</p>만을 반환하며, 스크립트 태그를 제거합니다.

sanitize-html 설치하기

먼저, sanitize-html 라이브러리를 프로젝트에 설치해야 합니다. 터미널에서 다음 명령어를 실행합니다.

npm install --save sanitize-html

sanitize-html 사용 예제

다음은 sanitize-html을 사용하여 사용자 입력을 정화하는 간단한 예제입니다.

const express = require('express');
const sanitizeHtml = require('sanitize-html');

const app = express();

app.use(express.json()); // JSON 형태의 요청 본문을 파싱합니다.

app.post('/comment', (req, res) => {
  const {comment} = req.body;
  const sanitizedComment = sanitizeHtml(comment, {
    allowedTags: ['b', 'i', 'em', 'strong', 'a'],
    allowedAttributes: {
      'a': ['href']
    }
  });

  // 정화된 코멘트를 저장하거나 응답으로 보냅니다.
  console.log(sanitizedComment);
  res.send(sanitizedComment);
});

const port = 3000;
app.listen(port, () => console.log(`App listening on port ${port}`));

이 코드는 사용자로부터 받은 코멘트를 sanitize-html을 사용하여 정화합니다. 이때, <b>, <i>, <em>, <strong>, <a> 태그만 허용하고, <a> 태그에 대해서는 href 속성만 허용합니다.

결론

Node.js에서 sanitize-html 미들웨어를 사용하면, 사용자의 입력을 안전하게 정화하여 XSS 공격을 방지할 수 있습니다. 이는 웹 애플리케이션의 보안을 강화하는 중요한 단계입니다.

자세한 정보는 sanitize-html npm 페이지를 참조하세요.

관련 이전 게시글

이 글이 도움이 되셨다면 공유 부탁 드립니다.

위로 스크롤