PHP 세션 하이재킹 방지

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

php 문제 해결

목록 보기
8/79

세션 하이재킹이란?

공격자가 정상적인 사용자의 세션 ID를 탈취하여 해당 사용자로 위장하는 공격 기법입니다.

보안 설정 방법

1. php.ini 설정

session.use_only_cookies = 1
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = "Strict"
session.gc_maxlifetime = 3600

2. 세션 설정 코드

ini_set('session.cookie_httponly', 1);
session_start([
    'cookie_secure' => true,
    'cookie_httponly' => true,
    'cookie_samesite' => 'Strict'
]);

3. 세션 ID 재생성

session_start();
if(!isset($_SESSION['created'])) {
    session_regenerate_id(true);
    $_SESSION['created'] = time();
}

추가 보안 조치

1. IP 검증

function checkSessionIP() {
    if (!isset($_SESSION['ip'])) {
        $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
    }
    return $_SESSION['ip'] === $_SERVER['REMOTE_ADDR'];
}

2. 사용자 에이전트 검증

function checkUserAgent() {
    if (!isset($_SESSION['user_agent'])) {
        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
    }
    return $_SESSION['user_agent'] === $_SERVER['HTTP_USER_AGENT'];
}

3. 세션 만료 처리

function checkSessionExpiry() {
    $max_lifetime = 3600; // 1시간
    if (isset($_SESSION['last_activity']) && 
        (time() - $_SESSION['last_activity'] > $max_lifetime)) {
        session_unset();
        session_destroy();
        return false;
    }
    $_SESSION['last_activity'] = time();
    return true;
}

보안 헤더 설정

header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");

모범 사례

  • HTTPS 사용 강제
  • 세션 ID 정기적 갱신
  • 로그인 시 세션 재생성
  • 중요 작업 시 재인증
  • 세션 데이터 암호화

구현 예시

class SecureSession {
    public function __construct() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start([
                'cookie_secure' => true,
                'cookie_httponly' => true,
                'cookie_samesite' => 'Strict'
            ]);
        }
        $this->regenerateSession();
    }

    private function regenerateSession() {
        if (!isset($_SESSION['created'])) {
            session_regenerate_id(true);
            $_SESSION['created'] = time();
        }
    }
}
profile
일용직 개발자. freetercoder@gmail.com

0개의 댓글