79 lines
2.3 KiB
Python
79 lines
2.3 KiB
Python
import secrets
|
|
import hashlib
|
|
from typing import Dict, Optional
|
|
from datetime import datetime, timedelta
|
|
|
|
class TempSshPasswordManager:
|
|
"""임시 SSH 비밀번호 관리"""
|
|
|
|
def __init__(self):
|
|
# 메모리 기반 저장소 (프로덕션에서는 Redis 사용 권장)
|
|
self._passwords: Dict[str, dict] = {}
|
|
|
|
def generate_password(self, username: str, validity_hours: int = 1) -> str:
|
|
"""
|
|
임시 SSH 비밀번호 생성
|
|
|
|
Args:
|
|
username: 사용자명
|
|
validity_hours: 유효 시간 (기본 1시간)
|
|
|
|
Returns:
|
|
임시 비밀번호
|
|
"""
|
|
# 안전한 랜덤 비밀번호 생성 (32자)
|
|
temp_password = secrets.token_urlsafe(32)
|
|
|
|
# 해시 저장 (실제 비밀번호는 저장하지 않음)
|
|
password_hash = hashlib.sha256(temp_password.encode()).hexdigest()
|
|
|
|
# 만료 시간 계산
|
|
expires_at = datetime.utcnow() + timedelta(hours=validity_hours)
|
|
|
|
# 저장
|
|
self._passwords[username] = {
|
|
"password_hash": password_hash,
|
|
"expires_at": expires_at,
|
|
"created_at": datetime.utcnow()
|
|
}
|
|
|
|
return temp_password
|
|
|
|
def verify_password(self, username: str, password: str) -> bool:
|
|
"""
|
|
비밀번호 검증
|
|
|
|
Args:
|
|
username: 사용자명
|
|
password: 검증할 비밀번호
|
|
|
|
Returns:
|
|
유효 여부
|
|
"""
|
|
if username not in self._passwords:
|
|
return False
|
|
|
|
stored = self._passwords[username]
|
|
|
|
# 만료 확인
|
|
if datetime.utcnow() > stored["expires_at"]:
|
|
del self._passwords[username]
|
|
return False
|
|
|
|
# 비밀번호 확인
|
|
password_hash = hashlib.sha256(password.encode()).hexdigest()
|
|
return password_hash == stored["password_hash"]
|
|
|
|
def cleanup_expired(self):
|
|
"""만료된 비밀번호 정리"""
|
|
now = datetime.utcnow()
|
|
expired = [
|
|
username for username, data in self._passwords.items()
|
|
if now > data["expires_at"]
|
|
]
|
|
for username in expired:
|
|
del self._passwords[username]
|
|
|
|
# 싱글톤 인스턴스
|
|
temp_ssh_password_manager = TempSshPasswordManager()
|