[카테고리:] 미분류

  • 웹사이트 보안 강화: Git 디렉토리 노출 차단과 보안 헤더 설정 가이드

    웹사이트 운영 중 가장 중요하면서도 놓치기 쉬운 부분이 바로 보안 설정입니다. 특히 .git 디렉토리 노출보안 헤더 미설정은 흔하지만 치명적인 취약점입니다. 이번 포스팅에서는 이러한 문제들을 어떻게 진단하고 해결하는지 상세히 다루겠습니다.

    📌 Git 디렉토리 노출의 위험성

    문제의 심각성

    .git 디렉토리가 웹상에 노출되면 다음과 같은 심각한 보안 위협이 발생합니다:

    1. 전체 소스코드 유출: 웹사이트의 모든 코드를 다운로드 가능
    2. 민감 정보 노출: 데이터베이스 접속 정보, API 키, 비밀번호 등
    3. 코드 히스토리 열람: 모든 커밋 내역과 변경 이력
    4. 취약점 분석 가능: 공격자가 코드를 분석하여 보안 허점 발견

    노출 여부 확인 방법

    # 주요 Git 파일 접근 테스트
    curl -I https://yourdomain.com/.git/config
    curl -I https://yourdomain.com/.git/HEAD
    curl -I https://yourdomain.com/.git/index
    curl -I https://yourdomain.com/.git/logs/HEAD
    

    200 또는 403 응답이 나오면 파일이 노출된 상태이며, 404 응답이 나와야 안전합니다.

    🔧 Nginx에서 Git 디렉토리 차단하기

    기본 차단 설정

    server {
        listen 443 ssl http2;
        server_name yourdomain.com;
        
        # Git 디렉토리 차단 (최상위에 위치)
        location ~ /\.git {
            deny all;
            return 404;
        }
        
        # Git 관련 파일 모두 차단
        location ~ /\.(git|gitignore|gitmodules|gitattributes) {
            deny all;
            return 404;
        }
        
        # 명시적 차단 (추가 보안)
        location = /.git/config {
            return 404;
        }
        location = /.git/HEAD {
            return 404;
        }
        location = /.git/index {
            return 404;
        }
        
        # 기타 설정들...
    }
    

    Apache에서의 차단 설정

    .htaccess 파일 사용:

    # Git 디렉토리 차단
    RedirectMatch 404 /\.git
    RedirectMatch 404 /\.gitignore
    RedirectMatch 404 /\.gitmodules
    
    # 또는 RewriteRule 사용
    RewriteEngine On
    RewriteRule ^(.*/)?\.git/ - [F,L]
    

    🛡️ 보안 헤더 설정

    보안 헤더는 다양한 웹 공격으로부터 사이트를 보호하는 중요한 방어 수단입니다.

    필수 보안 헤더들

    1. X-Frame-Options

    클릭재킹 공격 방지:

    add_header X-Frame-Options "SAMEORIGIN" always;
    

    2. X-Content-Type-Options

    콘텐츠 타입 스니핑 방지:

    add_header X-Content-Type-Options "nosniff" always;
    

    3. Content-Security-Policy (CSP)

    XSS 공격 방지:

    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self';" always;
    

    4. Strict-Transport-Security (HSTS)

    HTTPS 강제:

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    

    5. 추가 권장 헤더들

    # Referrer 정보 제어
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # XSS 필터 활성화
    add_header X-XSS-Protection "1; mode=block" always;
    
    # 권한 정책
    add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
    

    전체 Nginx 보안 설정 예시

    server {
        listen 443 ssl http2;
        server_name yourdomain.com;
        
        # SSL 설정
        ssl_certificate /path/to/cert.pem;
        ssl_certificate_key /path/to/key.pem;
        
        # 서버 정보 숨기기
        server_tokens off;
        
        # Git 및 숨김 파일 차단
        location ~ /\.(git|gitignore|gitmodules|gitattributes|htaccess|htpasswd) {
            deny all;
            return 404;
        }
        
        # 백업 파일 차단
        location ~ /\.(bak|backup|save|old|~|swp)$ {
            deny all;
            return 404;
        }
        
        # 보안 헤더
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;
        add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;" always;
        add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
        
        # 메인 location
        location / {
            # 애플리케이션 설정
            proxy_pass http://localhost:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
    

    🔍 설정 검증 방법

    1. Nginx 설정 테스트

    # 문법 검사
    sudo nginx -t
    
    # 설정 적용
    sudo systemctl reload nginx
    

    2. 보안 헤더 확인

    # 헤더 확인
    curl -I https://yourdomain.com | grep -E "(X-Frame-Options|X-Content-Type-Options|Content-Security-Policy)"
    
    # 온라인 도구 활용
    # - https://securityheaders.com
    # - https://observatory.mozilla.org
    

    3. Git 차단 확인

    # 각 경로 테스트
    curl -sI https://yourdomain.com/.git/config | head -n 1
    curl -sI https://yourdomain.com/.git/HEAD | head -n 1
    

    🚀 근본적인 해결 방안

    1. Git 디렉토리 제거

    프로덕션 서버에서는 .git 디렉토리를 완전히 제거하는 것이 가장 안전합니다:

    # 백업 생성
    tar -czf git_backup_$(date +%Y%m%d).tar.gz .git
    
    # 디렉토리 제거
    rm -rf .git
    
    # 확인
    find . -name ".git" -type d
    

    2. 배포 프로세스 개선

    # rsync를 이용한 배포 시 .git 제외
    rsync -av --exclude='.git' --exclude='.env' source/ destination/
    
    # Git archive 명령 사용
    git archive --format=tar --output=deploy.tar HEAD
    

    3. CI/CD 파이프라인 설정

    # GitHub Actions 예시
    - name: Deploy
      run: |
        rsync -av --delete \
          --exclude='.git' \
          --exclude='.github' \
          --exclude='.env' \
          ./ ${{ secrets.DEPLOY_PATH }}
    

    📋 보안 체크리스트

    • [ ] .git 디렉토리 접근 차단 설정
    • [ ] 보안 헤더 모두 적용
    • [ ] 서버 정보 숨기기 (server_tokens off)
    • [ ] HTTPS 강제 적용 (HSTS)
    • [ ] CSP 정책 구성
    • [ ] 백업 및 임시 파일 차단
    • [ ] 정기적인 보안 스캔 실행
    • [ ] 로그 모니터링 설정

    🌟 추가 보안 권장사항

    1. 정기적인 보안 스캔

    • Sucuri SiteCheck
    • SSL Labs
    • Observatory by Mozilla

    2. 실시간 모니터링

    # 의심스러운 접근 로깅
    location ~ /\.(git|env|config) {
        access_log /var/log/nginx/suspicious.log;
        deny all;
        return 404;
    }
    

    3. Web Application Firewall (WAF)

    • ModSecurity
    • Cloudflare WAF
    • AWS WAF

    🎯 결론

    웹사이트 보안은 단순히 한 번 설정하고 끝나는 것이 아니라 지속적인 관리가 필요합니다. 특히 Git 디렉토리 노출과 보안 헤더 미설정은 가장 흔한 취약점이면서도 쉽게 해결할 수 있는 문제입니다.

    핵심 포인트:

    1. Git 디렉토리는 프로덕션 서버에서 완전히 제거
    2. 필수 보안 헤더는 반드시 설정
    3. 정기적인 보안 스캔과 모니터링
    4. 배포 프로세스에서 보안 고려

    작은 설정 하나가 큰 보안 사고를 막을 수 있습니다. 지금 바로 여러분의 웹사이트를 점검해보세요!


    보안은 끝이 없는 여정입니다. 이 가이드가 여러분의 웹사이트를 더 안전하게 만드는 데 도움이 되기를 바랍니다.