C.W.K.
Stream
Lesson 03 of 06 · published

Bcrypt, Local IP Bypass, Session Cookie

~15 min · bcrypt, session-cookies, ip-binding

Level 0Greenhorn
0 XP0/53 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Middleware 가 기대는 세 primitive. 각각 작고; 합치면 AuthN 스토리 전부.

Bcrypt — 복원 못 하게 PIN 저장

Local IP bypass — audit trail 있는 편의

Bypass 는 의도적 trade — 이 IP 들의 누구든 "너" 라고 받아들이는 대신 dev 머신에서 reload 할 때마다 PIN 안 입력. 두 룰이 survivable 하게 만들어.

  1. 어떤 IP 인지 명시. 셋 하드코딩; 기본 "RFC1918 어떤 주소" 받지 마.
  2. trigger 시 로그. "PIN 작동했어?" 디버깅하는 미래 네가 "trusted list 에 있어서 bypass" 봐야 해.

Session 쿠키 — 브라우저 안의 토큰

Code

Bcrypt 헬퍼·python
import bcrypt

def hash_pin(pin: str) -> bytes:
    # cost 12 = 모던 하드웨어에서 hash 당 ~150ms
    # 튜닝: 네 안 짜증 날 만큼 낮고, 공격자 늦출 만큼 높게
    return bcrypt.hashpw(pin.encode(), bcrypt.gensalt(rounds=12))

def verify_pin(input_pin: str, stored_hash: bytes) -> bool:
    try:
        return bcrypt.checkpw(input_pin.encode(), stored_hash)
    except ValueError:
        return False  # 잘못된 hash
명시적 local IP bypass set·python
LOCAL_BYPASS = {
    "127.0.0.1",       # loopback IPv4
    "::1",             # loopback IPv6
    "192.168.1.42",    # 책상의 맥 — 명시적
    # "192.168.1.0/24" X — 너무 넓어
}
Session 발급과 검증·python
import secrets, time

SESSION_SECONDS = 30 * 24 * 3600   # 30일

def create_session(ip: str) -> str:
    token = secrets.token_urlsafe(32)        # 256비트 엔트로피
    now   = int(time.time())
    db.execute(
        "INSERT INTO security_sessions(token, ip, created_at, expires_at) "
        "VALUES (?, ?, ?, ?)",
        (token, ip, now, now + SESSION_SECONDS)
    )
    db.commit()
    return token

def session_valid(token: str, ip: str) -> bool:
    row = db.execute(
        "SELECT ip, expires_at FROM security_sessions WHERE token = ?",
        (token,)
    ).fetchone()
    if not row:
        return False
    stored_ip, expires_at = row
    if expires_at < int(time.time()):
        return False
    if stored_ip != ip:
        return False              # 토큰이 발급 IP 에 묶임
    return True
Session 쿠키 설정·python
response.set_cookie(
    key="session",
    value=token,
    max_age=SESSION_SECONDS,
    httponly=True,          # JS 가 못 읽음
    secure=True,            # HTTPS 만 (local dev 때만 OFF)
    samesite="strict",      # cross-site 전송 X
    path="/"
)

External links

Exercise

이전 레슨의 middleware 위에 세 헬퍼 (hash_pin, verify_pin, create_session, session_valid) 구현. security_config 에 pin_hash = hash_pin('4729') 로 row insert. Python REPL 에서 verify_pin('4729', stored) 가 True, verify_pin('4730', stored) 가 False 반환 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.