불완전한 호스트네임 정규식 (. 이스케이프 누락)

Improper Input Validation (Incomplete hostname RegExp)

설명

정규식에서 이스케이프하지 않은 .은 점 외의 문자와도 일치합니다. 호스트명의 구분자를 이렇게 검사하면 허용 목록에 없는 호스트도 통과할 수 있습니다.

잠재적 영향

리다이렉트는 사용자를 잘못된 사이트로 보낼 수 있습니다. 같은 검사를 서버 요청이나 연동에 쓰면 승인되지 않은 호스트로 연결할 수 있습니다.

해결 방법

  • 표준 URL 파서로 포트를 제외한 hostname을 구한 뒤 허용 목록과 정확히 비교하세요. 모든 하위 도메인을 허용해야 한다면 기본 도메인과 일치하거나 점을 포함한 접미사 .example.com으로 끝나는지 확인하세요.
  • 정규식이 필요하면 ^와 $로 호스트명 전체를 검사하고 구분자는 \.로 쓰세요. 허용할 레이블의 문자와 길이를 정하고 광범위하거나 중첩된 반복은 피하세요.

예시

URL 리다이렉트

변경 전

javascript
const express = require("express");
const app = express();

// /jump?next=https://example.com
app.get("/jump", (req, res) => {
  const next = req.query.next;
  if (!next) return res.status(400).send("missing");

  let host;
  try {
    host = new URL(next).hostname; // 사용자가 준 URL의 호스트네임
  } catch {
    return res.status(400).send("bad url");
  }

  // 취약: '.'를 이스케이프하지 않아 의도보다 넓게 매칭됨
  // 예: staticXexampleYcom, static-exampleZcom 등도 통과 가능
  const allowed = /^((static|media).)?example.com$/i.test(host);
  if (allowed) return res.redirect(next);
  return res.status(400).send("blocked");
});

변경 후

javascript
const express = require("express");
const app = express();

// 엄격한 allow-list 기반 검증
const ALLOW_HOSTS = new Set([
  "example.com",
  "static.example.com",
  "media.example.com",
]);

app.get("/jump", (req, res) => {
  const next = req.query.next;
  if (typeof next !== "string") return res.status(400).send("missing");

  let parsed;
  try {
    parsed = new URL(next);
  } catch {
    return res.status(400).send("bad url");
  }

  const host = parsed.hostname.toLowerCase();
  const safeTransport =
    parsed.protocol === "https:" &&
    parsed.port === "" &&
    parsed.username === "" &&
    parsed.password === "";

  // 정확한 호스트와 HTTPS 기본 포트만 허용
  if (!safeTransport || !ALLOW_HOSTS.has(host)) {
    return res.status(400).send("blocked");
  }
  return res.redirect(parsed.toString());
});

// 참고: 정규식을 꼭 써야 한다면 다음처럼 점을 이스케이프하세요.
// const ok = /^((static|media)\.)?example\.com$/i.test(host);

리다이렉트 핸들러는 허용 목록의 세 호스트와 HTTPS 기본 포트만 허용하고 URL에 사용자 이름이나 비밀번호가 있으면 거부합니다.

브라우저 호스트네임

변경 전

javascript
function checkLocation(document) {
  return /^example.com$/.test(globalThis.location.hostname);
}

변경 후

javascript
function checkLocation(document) {
  return /^example\.com$/.test(globalThis.location.hostname);
}

브라우저 예시는 globalThis.location.hostname 전체를 검사합니다. 이스케이프한 점은 도메인 구분자와만 일치합니다.

참조