Zip Slip (압축 해제 경로 조작)

Zip Slip (Archive Extraction Path Traversal)

설명

ZIP 항목을 추출할 때는 entryName을 대상 디렉터리 안의 경로로 제한하세요. 링크 항목과 다른 사용자가 바꿀 수 있는 디렉터리도 쓰기 위치를 바꿀 수 있습니다.

잠재적 영향

서비스 계정이 쓸 수 있는 설정, 로그, 데이터가 손상될 수 있습니다. 덮어쓴 파일을 실행하거나 설정으로 읽으면 코드 실행이나 서비스 중단으로 이어질 수 있습니다.

해결 방법

  • 신뢰할 수 있는 부모 아래에 새 비공개 디렉터리를 만들고 필요한 확장자와 디렉터리만 허용하세요. 라이브러리가 항목 필터를 지원하면 사용하세요. ZIP 외부 속성에 UNIX 심볼릭 링크로 표시된 항목은 건너뛰세요.
  • 이름을 정규화한 뒤 절대 경로, Windows 드라이브 접두사와 남은 상위 경로 요소를 거부하세요. path.resolve 결과가 목적지 안에 있는지 path.relative로 확인하세요.
  • 디렉터리 쓰기 권한을 제한하고 파일은 wx로 새로 만드세요.

예시

변경 전

javascript
// 비준수: 엔트리 경로를 그대로 사용해 추출 (Zip Slip 취약)
const fs = require("fs");
const path = require("path");
const AdmZip = require("adm-zip");

function extractUnsafe(zipPath, destDir) {
  const zip = new AdmZip(zipPath);
  zip.getEntries().forEach((entry) => {
    const outPath = path.join(destDir, entry.entryName); // 검증 없음
    const data = entry.getData();
    // 공격자가 entry.entryName에 "../../../../var/www/html/shell.js"를 넣으면 외부로 탈출 가능
    fs.mkdirSync(path.dirname(outPath), { recursive: true });
    fs.writeFileSync(outPath, data); // 임의 위치 파일 생성/덮어쓰기
  });
}

변경 후

javascript
// 준수: 새 전용 디렉터리에서 엔트리 형식과 최종 경로를 검증한 뒤 쓰기
const fs = require("fs");
const path = require("path");
const AdmZip = require("adm-zip");

function isUnixSymlink(entry) {
  // ZIP 외부 속성의 상위 16비트에는 UNIX 파일 모드가 저장됩니다.
  const unixMode = entry.header.attr >>> 16;
  return (unixMode & 0o170000) === 0o120000;
}

function extractSafe(zipPath, destParent) {
  const zip = new AdmZip(zipPath);
  const parentReal = fs.realpathSync(destParent);
  const destReal = fs.mkdtempSync(path.join(parentReal, "extract-"));
  fs.chmodSync(destReal, 0o700);

  for (const entry of zip.getEntries()) {
    // 1) UNIX 심볼릭 링크 엔트리 거부
    if (isUnixSymlink(entry)) continue;

    // 2) 경로 정규화
    const normalized = path.normalize(entry.entryName);

    // 3) 빈 경로/절대 경로/드라이브 문자/상위 디렉터리 요소 차단
    if (normalized === "" || normalized === ".") continue;
    if (path.isAbsolute(normalized)) continue;
    if (normalized.split(path.sep).includes("..")) continue;
    if (/^[A-Za-z]:/.test(normalized)) continue;

    // 4) 최종 경로 계산 후 목적지 안쪽인지 확인
    const targetPath = path.resolve(destReal, normalized);
    if (
      path.relative(destReal, targetPath) !== ".." &&
      !path.relative(destReal, targetPath).startsWith(".." + path.sep) &&
      !path.isAbsolute(path.relative(destReal, targetPath))
    ) {
      if (entry.isDirectory) {
        fs.mkdirSync(targetPath, { recursive: true, mode: 0o700 });
        continue;
      }

      // 5) 새 전용 디렉터리 안에서만 생성하고 기존 파일은 덮어쓰지 않음
      fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 });
      const data = entry.getData();
      fs.writeFileSync(targetPath, data, { flag: "wx", mode: 0o600 });
    }
  }

  return destReal;
}

예시는 UNIX 링크 항목을 건너뛰고 허용된 경로만 씁니다. entry.getData()는 한 항목의 데이터를 메모리에 풀므로 실제 압축 해제 크기는 별도로 제한하세요.

참조