🔒 Security

Hacking

Hacking

The act of gaining unauthorized access to a system. Divided into white hat (ethical), black hat (malicious), and gray hat.

📖 Detailed Explanation

Hacking was originally a computer culture term with the positive meaning of "solving problems in ingenious ways," but today it encompasses the act of detecting and exploiting (or testing) security vulnerabilities in computer systems, networks, and applications. Depending on the hacker's intent and ethics, hackers are classified as White Hat, Black Hat, and Gray Hat.

White hat hackers (ethical hackers) are security professionals who, with an organization's permission, test system security and discover and report vulnerabilities. They work through penetration testing (pentesting), red team exercises, bug bounty programs, and more. In contrast, black hat hackers attempt unauthorized intrusion for malicious purposes such as financial gain, information theft, and system destruction. Gray hats are in a middle zone: they discover vulnerabilities without permission but then publicly disclose them or exploit them in a limited way.

Penetration testing follows a systematic methodology. In the Reconnaissance phase, publicly available information about the target system is collected, and in the Scanning phase, open ports and services are detected. After a Vulnerability Assessment, an actual attack (Exploitation) is attempted, and additional systems are taken over through Privilege Escalation and Lateral Movement. Finally, the findings are documented and reported. Standard methodologies include OWASP, PTES, and OSSTMM.

A bug bounty program is a scheme in which a company provides rewards to external security researchers for discovering vulnerabilities. Bug bounty programs are run by organizations ranging from large companies such as Google, Microsoft, and Apple to startups, and are managed through platforms such as HackerOne and Bugcrowd. For critical vulnerabilities, rewards ranging from tens of thousands to hundreds of thousands of dollars are sometimes paid. This allows organizations to detect, through crowdsourcing, vulnerabilities that are difficult to find with an internal security team alone.

💻 Code Example

Caution: The examples below are provided for security education and defensive purposes. Applying them to others' systems without permission is illegal. Practice only in your own test environment or on systems for which you have explicit permission.

Vulnerability Types and Defensive Code Examples

# ===========================================
# 1. SQL Injection 취약점과 방어
# ===========================================

# 취약한 코드 (절대 사용 금지)
def get_user_vulnerable(username):
    # 사용자 입력을 직접 쿼리에 삽입 - SQL Injection 취약!
    query = f"SELECT * FROM users WHERE username = '{username}'"
    # 공격 예: username = "' OR '1'='1" 입력 시 모든 사용자 조회

# 안전한 코드 (Parameterized Query 사용)
import sqlite3

def get_user_safe(username: str) -> dict:
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()

    # 파라미터 바인딩으로 SQL Injection 방지
    cursor.execute(
        "SELECT id, username, email FROM users WHERE username = ?",
        (username,)  # 튜플로 파라미터 전달
    )

    row = cursor.fetchone()
    conn.close()

    if row:
        return {"id": row[0], "username": row[1], "email": row[2]}
    return None

# ORM 사용 (SQLAlchemy) - 가장 안전한 방법
from sqlalchemy.orm import Session
from models import User

def get_user_with_orm(db: Session, username: str) -> User:
    # ORM이 자동으로 파라미터 이스케이프 처리
    return db.query(User).filter(User.username == username).first()


# ===========================================
# 2. XSS (Cross-Site Scripting) 방어
# ===========================================

from markupsafe import escape
from flask import Flask, request, render_template_string

app = Flask(__name__)

# 취약한 코드
@app.route('/vulnerable')
def vulnerable():
    name = request.args.get('name', '')
    # 사용자 입력을 그대로 출력 - XSS 취약!
    return f"<h1>Hello, {name}</h1>"
    # 공격: ?name=<script>alert('XSS')</script>

# 안전한 코드 - HTML 이스케이프
@app.route('/safe')
def safe():
    name = request.args.get('name', '')
    # markupsafe.escape()로 특수문자 이스케이프
    safe_name = escape(name)
    return f"<h1>Hello, {safe_name}</h1>"
    # <script> -> &lt;script&gt; 로 변환

# 템플릿 엔진 사용 (Jinja2 - 자동 이스케이프)
@app.route('/template')
def with_template():
    name = request.args.get('name', '')
    # Jinja2는 기본적으로 자동 이스케이프
    return render_template_string("<h1>Hello, {{ name }}</h1>", name=name)


# ===========================================
# 3. 비밀번호 안전 저장
# ===========================================

import bcrypt
import secrets

class PasswordManager:
    @staticmethod
    def hash_password(password: str) -> str:
        """비밀번호를 bcrypt로 해시 (솔트 자동 생성)"""
        salt = bcrypt.gensalt(rounds=12)  # cost factor 12
        hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
        return hashed.decode('utf-8')

    @staticmethod
    def verify_password(password: str, hashed: str) -> bool:
        """비밀번호 검증"""
        return bcrypt.checkpw(
            password.encode('utf-8'),
            hashed.encode('utf-8')
        )

    @staticmethod
    def generate_secure_token(length: int = 32) -> str:
        """암호학적으로 안전한 랜덤 토큰 생성"""
        return secrets.token_urlsafe(length)

# 사용 예
password = "my_secure_password"
hashed = PasswordManager.hash_password(password)
print(f"Hashed: {hashed}")

is_valid = PasswordManager.verify_password(password, hashed)
print(f"Valid: {is_valid}")  # True


# ===========================================
# 4. CSRF (Cross-Site Request Forgery) 방어
# ===========================================

from flask_wtf import CSRFProtect
from flask import Flask, render_template, request

app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_hex(32)
csrf = CSRFProtect(app)

# HTML 폼에 CSRF 토큰 포함
"""
<form method="post" action="/transfer">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="text" name="amount">
    <button type="submit">Transfer</button>
</form>
"""

@app.route('/transfer', methods=['POST'])
def transfer():
    # Flask-WTF가 자동으로 CSRF 토큰 검증
    amount = request.form.get('amount')
    # ... 송금 처리
    return "Transfer complete"

# API에서 CSRF 토큰 검증 (SameSite 쿠키와 함께 사용)
@app.route('/api/transfer', methods=['POST'])
@csrf.exempt  # API는 다른 방식으로 보호
def api_transfer():
    # Authorization 헤더 검증
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return {"error": "Unauthorized"}, 401
    # ... JWT 토큰 검증 및 처리
    return {"status": "success"}

Security Scanning and Vulnerability Detection (Defensive Perspective)

# ===========================================
# 보안 감사 및 취약점 스캔 도구 (방어 목적)
# ===========================================

# 1. 의존성 취약점 스캔
# npm audit (Node.js)
npm audit
npm audit fix

# pip-audit (Python)
pip install pip-audit
pip-audit

# Snyk (다양한 언어 지원)
snyk test
snyk monitor

# 2. 정적 코드 분석 (보안 취약점 탐지)
# Bandit (Python 보안 분석)
pip install bandit
bandit -r ./src -f html -o security-report.html

# ESLint Security Plugin (JavaScript)
npm install eslint-plugin-security
# .eslintrc에 추가: "plugins": ["security"]

# Semgrep (다양한 언어 지원)
semgrep --config=auto ./src

# 3. 컨테이너 이미지 취약점 스캔
# Trivy
trivy image myapp:latest
trivy fs --security-checks vuln,secret ./

# Docker Scout
docker scout cves myapp:latest

# 4. 인프라 취약점 스캔
# Nmap (네트워크 스캔 - 자체 시스템만!)
nmap -sV -sC -p- localhost

# OWASP ZAP (웹 취약점 스캔)
zap-cli quick-scan --self-contained https://your-test-site.com

# 5. 시크릿 탐지 (Git 저장소)
# TruffleHog
trufflehog git https://github.com/your-org/your-repo

# GitLeaks
gitleaks detect --source . --verbose

Security Headers and Hardening Configuration

# Flask 보안 헤더 설정
from flask import Flask
from flask_talisman import Talisman

app = Flask(__name__)

# Content Security Policy 설정
csp = {
    'default-src': "'self'",
    'script-src': ["'self'", "'unsafe-inline'", "cdnjs.cloudflare.com"],
    'style-src': ["'self'", "'unsafe-inline'", "fonts.googleapis.com"],
    'font-src': ["'self'", "fonts.gstatic.com"],
    'img-src': ["'self'", "data:", "https:"],
    'connect-src': "'self'",
    'frame-ancestors': "'none'",
    'form-action': "'self'",
}

# Talisman으로 보안 헤더 자동 추가
Talisman(
    app,
    content_security_policy=csp,
    force_https=True,
    strict_transport_security=True,
    strict_transport_security_max_age=31536000,
    session_cookie_secure=True,
    session_cookie_http_only=True,
    session_cookie_samesite='Strict',
)

# Django 보안 설정 (settings.py)
"""
# HTTPS 강제
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# HSTS (HTTP Strict Transport Security)
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

# XSS 보호
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True

# Clickjacking 방지
X_FRAME_OPTIONS = 'DENY'

# 쿠키 보안
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Strict'
CSRF_COOKIE_SECURE = True

# Content Security Policy (django-csp 패키지)
CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'", "cdnjs.cloudflare.com")
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'")
"""

🗣️ How It's Said in Practice

  • "The quarterly penetration test results are in, and we found 2 critical vulnerabilities. We need to patch them this sprint."
  • "Since we started the bug bounty program, vulnerabilities that we couldn't find internally are being reported. It's cost-effective."
  • "We're planning to conduct a security audit based on the OWASP Top 10. Please check SQL Injection and XSS first."
  • "I think we should schedule a red team exercise to practice responding to real attack scenarios. We should also test the blue team's response capabilities."
  • "A white hat hacker performs security tests with an organization's permission, while a black hat attempts unauthorized intrusion for malicious purposes."
  • "Penetration testing proceeds through the stages of reconnaissance, scanning, vulnerability analysis, exploitation, privilege escalation, and reporting. It follows methodologies such as PTES and the OWASP Testing Guide."
  • "Bug bounty is a program that strengthens security through crowdsourcing by offering rewards to external security researchers for discovering vulnerabilities."
  • "For defense, you need to implement countermeasures against major web vulnerabilities such as SQL Injection, XSS, and CSRF, based on the OWASP Top 10."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

  • "If you put user input directly into a query, it's a SQL Injection vulnerability. Use a Parameterized Query or an ORM."
  • "The HTML output isn't processed with escape(). An XSS vulnerability could occur. Use the template engine's automatic escaping feature."
  • "You shouldn't hash passwords with MD5. Use bcrypt or Argon2, and make sure the salt is generated automatically too."
  • "There's no CSRF token verification logic. Please make sure to apply CSRF protection to state-changing APIs."

⚠️ Cautions

🔗 Related Terms

📚 Learn More