🔒 Security

SSL/TLS

Secure Sockets Layer / Transport Layer Security

A security protocol that encrypts network communication. The foundation technology of HTTPS, it verifies server identity through certificates and encrypts data. TLS 1.3 is the current latest standard.

📖 Detailed Explanation

SSL (Secure Sockets Layer) is an encryption protocol developed by Netscape in 1995, and TLS (Transport Layer Security) is the successor protocol standardized by the IETF based on SSL 3.0. SSL has now been completely deprecated due to security vulnerabilities, and TLS 1.2 and TLS 1.3 are what is actually used. By convention it is called "SSL," but in practice it means TLS. TLS 1.3 was standardized in 2018 as RFC 8446 and provides faster and more secure connections.

The TLS handshake is the process by which a client and a server establish an encrypted connection. The client proposes the cipher suites it supports, and the server selects one, exchanges certificates, and negotiates session keys. In TLS 1.3, the handshake has been shortened to 1-RTT (Round Trip Time), significantly reducing connection latency. In addition, the 0-RTT resumption feature allows data to be sent immediately to a server that was previously connected to.

A certificate is a digital document that proves the identity of a server. It is issued by a CA (Certificate Authority), and comes in domain validation (DV), organization validation (OV), and extended validation (EV) levels. Thanks to free CAs such as Let's Encrypt, HTTPS adoption has risen sharply. mTLS (Mutual TLS) performs two-way authentication by having not only the server but also the client present a certificate, and it is widely used for communication between microservices.

In AI/ML systems, TLS is essential for encrypting API communication, model serving, and data pipelines. All ML infrastructure, including MLflow, TensorFlow Serving, and gRPC, supports TLS. In particular, TLS must be applied when transmitting sensitive training data or inference results, and mTLS is recommended even between internal services in line with the Zero Trust principle. Automatic certificate renewal (cert-manager, ACME) is key to operational stability.

💻 Code Example

# Nginx TLS 1.3 최적 설정
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name api.example.com;

    # 인증서 경로
    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;

    # TLS 버전 - 1.2, 1.3만 허용 (1.0, 1.1 비활성화)
    ssl_protocols TLSv1.2 TLSv1.3;

    # 강력한 암호화 스위트만 사용
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;  # TLS 1.3에서는 off 권장

    # OCSP Stapling - 인증서 유효성 검증 가속화
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/api.example.com/chain.pem;
    resolver 8.8.8.8 8.8.4.4 valid=300s;

    # 세션 캐시 - 핸드셰이크 최적화
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;  # Forward Secrecy 보장

    # HSTS - HTTPS 강제
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    # mTLS 설정 (클라이언트 인증서 요구)
    # ssl_client_certificate /etc/nginx/client-ca.crt;
    # ssl_verify_client on;

    location / {
        proxy_pass http://backend:8080;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# HTTP → HTTPS 리다이렉트
server {
    listen 80;
    listen [::]:80;
    server_name api.example.com;
    return 301 https://$server_name$request_uri;
}
# Python TLS/SSL 설정 예제
import ssl
import requests
from urllib3.util.ssl_ import create_urllib3_context

# === requests 라이브러리 TLS 설정 ===

# 기본 HTTPS 요청 (시스템 CA 인증서 사용)
response = requests.get("https://api.example.com/v1/models")
print(f"TLS Version: {response.raw.version}")  # 사용된 TLS 버전

# 커스텀 CA 인증서 지정 (사내 PKI 사용 시)
response = requests.get(
    "https://internal-api.company.com",
    verify="/path/to/company-ca-bundle.crt"
)

# mTLS - 클라이언트 인증서 사용
response = requests.get(
    "https://secure-api.example.com/v1/data",
    cert=("/path/to/client.crt", "/path/to/client.key"),
    verify="/path/to/server-ca.crt"
)

# === ssl 모듈 직접 사용 (저수준 제어) ===

# TLS 1.3 강제, 약한 암호화 비활성화
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.maximum_version = ssl.TLSVersion.TLSv1_3

# 인증서 검증 필수
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_verify_locations("/etc/ssl/certs/ca-certificates.crt")

# 연결 테스트
import socket
with socket.create_connection(("api.example.com", 443)) as sock:
    with context.wrap_socket(sock, server_hostname="api.example.com") as ssock:
        print(f"TLS Version: {ssock.version()}")
        print(f"Cipher: {ssock.cipher()}")
        cert = ssock.getpeercert()
        print(f"Server: {cert['subject']}")

# === FastAPI/Uvicorn TLS 서버 설정 ===
# uvicorn main:app --ssl-keyfile=./key.pem --ssl-certfile=./cert.pem

# === gRPC mTLS 설정 ===
import grpc

# 서버 측
server_credentials = grpc.ssl_server_credentials(
    [(open('server.key', 'rb').read(), open('server.crt', 'rb').read())],
    root_certificates=open('client-ca.crt', 'rb').read(),
    require_client_auth=True  # mTLS 활성화
)

# 클라이언트 측
channel_credentials = grpc.ssl_channel_credentials(
    root_certificates=open('server-ca.crt', 'rb').read(),
    private_key=open('client.key', 'rb').read(),
    certificate_chain=open('client.crt', 'rb').read()
)
channel = grpc.secure_channel('api.example.com:443', channel_credentials)
# OpenSSL CLI - TLS 디버깅 및 인증서 관리

# === TLS 연결 테스트 ===
# 서버 TLS 설정 확인
openssl s_client -connect api.example.com:443 -tls1_3

# 인증서 체인 전체 출력
openssl s_client -connect api.example.com:443 -showcerts

# SNI(Server Name Indication) 지정
openssl s_client -connect api.example.com:443 -servername api.example.com

# 지원 암호화 스위트 확인
openssl s_client -connect api.example.com:443 -cipher 'ECDHE+AESGCM'

# === 인증서 정보 확인 ===
# 원격 서버 인증서 만료일 확인
echo | openssl s_client -connect api.example.com:443 2>/dev/null | \
  openssl x509 -noout -dates

# 인증서 상세 정보
openssl x509 -in server.crt -text -noout

# 인증서와 개인키 일치 확인
openssl x509 -noout -modulus -in server.crt | openssl md5
openssl rsa -noout -modulus -in server.key | openssl md5
# 두 해시가 같아야 함

# === 자체 서명 인증서 생성 (개발용) ===
# 개인키 생성
openssl genrsa -out server.key 4096

# CSR(Certificate Signing Request) 생성
openssl req -new -key server.key -out server.csr \
  -subj "/CN=api.example.com/O=MyOrg/C=KR"

# 자체 서명 인증서 생성 (365일 유효)
openssl x509 -req -days 365 -in server.csr \
  -signkey server.key -out server.crt

# 한 줄로 키+인증서 생성
openssl req -x509 -newkey rsa:4096 -nodes -days 365 \
  -keyout server.key -out server.crt \
  -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"

# === Let's Encrypt 인증서 발급 (certbot) ===
# 설치
apt install certbot python3-certbot-nginx

# Nginx 자동 설정으로 발급
certbot --nginx -d api.example.com

# 인증서만 발급 (수동 설정)
certbot certonly --webroot -w /var/www/html -d api.example.com

# 갱신 테스트
certbot renew --dry-run

# 자동 갱신 (cron)
# 0 0 * * * certbot renew --quiet && systemctl reload nginx

🗣️ How It's Said in Practice

💬 In a Security Review Meeting
"TLS 1.0 and 1.1 are already deprecated, so please disable them in nginx. Leave only TLSv1.2 and TLSv1.3 in ssl_protocols, and let's check whether we get an A+ on Qualys SSL Labs."
💬 In a microservice architecture review
"Communication between internal services should also use mTLS. If we use Istio, the sidecar automatically performs the mTLS handshake, so just set PeerAuthentication to STRICT mode."
💬 During production incident response
"The API went down because the certificate expired. Let's set up cert-manager so that Let's Encrypt certificates renew automatically, and add monitoring so that a Slack alert is sent 30 days before expiration."

⚠️ Cautions & Best Practices

❌
Do Not Disable Certificate Verification

Options such as verify=False and CERT_NONE expose you to MITM attacks. Even in development environments, create and use a self-signed certificate, and never disable verification in production.

❌
Do Not Use Legacy TLS Versions

TLS 1.0 and 1.1 have known vulnerabilities such as POODLE and BEAST. They are also prohibited under compliance standards such as PCI-DSS. Use at least TLS 1.2, and preferably only 1.3.

❌
Certificate Expiration Monitoring Is Essential

Certificate expiration is the most common cause of outages. Set up automatic renewal with cert-manager and the ACME protocol, and configure alerts for when expiration is imminent.

✅
TLS Best Practices

Enforce HTTPS with the HSTS header, and speed up certificate verification with OCSP Stapling. Store private keys securely in an HSM or Vault, and use ECDHE cipher suites for Forward Secrecy.

🔗 Related Terms

📚 Learn More