PHP XSS(크로스 사이트 스크립팅) 방지

프리터코더·2025년 5월 25일

php 문제 해결

목록 보기
9/79

XSS란?

웹 애플리케이션에서 악의적인 스크립트를 삽입하여 실행하는 공격 기법입니다.

기본 방어 방법

1. HTML 특수문자 이스케이프

$safeOutput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

2. 입력값 필터링

$cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
$cleanUrl = filter_var($url, FILTER_SANITIZE_URL);

출력 보안

1. 템플릿 이스케이프 함수

function e($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}

2. HTML 퍼지 필터링

require_once 'HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$cleanHtml = $purifier->purify($dirtyHtml);

보안 헤더 설정

header("Content-Security-Policy: default-src 'self'");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");

폼 데이터 처리

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

JSON 데이터 처리

$jsonData = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

보안 클래스 구현

class Security {
    public static function sanitize($input) {
        if (is_array($input)) {
            return array_map([self::class, 'sanitize'], $input);
        }
        return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
    }
    
    public static function validateUrl($url) {
        return filter_var($url, FILTER_VALIDATE_URL);
    }
}

모범 사례

  • 모든 사용자 입력 검증
  • 컨텍스트에 맞는 이스케이프 처리
  • CSP(Content Security Policy) 구현
  • 정기적인 보안 감사
  • 최신 보안 패치 적용

실제 구현 예시

// 폼 데이터 처리
$userInput = $_POST['message'] ?? '';
$safeOutput = Security::sanitize($userInput);

// HTML 출력
echo '<div class="message">' . e($safeOutput) . '</div>';

// JSON 응답
header('Content-Type: application/json');
echo json_encode(['message' => $safeOutput], JSON_HEX_TAG);
profile
일용직 개발자. freetercoder@gmail.com

0개의 댓글