🔒 Security

MFA

Multi-Factor Authentication

An authentication method that strengthens account security by requiring additional authentication factors (possession, biometric) beyond the password (knowledge factor). There are various methods such as OTP, SMS, authenticator apps, hardware security keys, and biometrics, and FIDO2/Passkey is emerging as the standard for phishing-resistant MFA. With Passkey, login is 14 times faster (3 seconds vs. 69 seconds) than the traditional password + MFA combination.

📖 Detailed Explanation

MFA (Multi-Factor Authentication) is a security method that verifies identity by combining two or more of three authentication factors: "something you know (password)," "something you have (smartphone, security key)," and "something you are (fingerprint, face)." Because passwords alone are vulnerable to phishing, credential stuffing, and brute-force attacks, an additional authentication layer is introduced to strengthen security.

Traditional MFA methods include SMS OTP, email verification codes, and TOTP (Time-based One-Time Password) apps (Google Authenticator, Microsoft Authenticator). However, SMS is vulnerable to SIM swapping attacks, and with TOTP, a code entered on a phishing site can be stolen by the attacker. These limitations have given rise to the need for "Phishing-Resistant MFA."

The FIDO2 (WebAuthn + CTAP2) standard is at the core of phishing-resistant MFA. A public/private key pair is generated on the user's device, and the private key is stored in the device's secure hardware (TPM, Secure Enclave). During authentication, the server sends a challenge, and the device signs it with the private key only when it matches the registered domain (origin). Because a phishing site is not the legitimate domain, authentication is impossible. Hardware security keys such as YubiKey and platform authenticators such as Windows Hello and Apple Face ID support FIDO2.

Passkey is a user-friendly evolution of FIDO2, designed to replace passwords entirely. Synced Passkeys are synchronized across multiple devices through iCloud, Google Password Manager, and similar services, improving convenience. Device-bound Passkeys are stored on a single device only, providing higher security. PCI DSS v4.0.1 mandates MFA for all access to the cardholder data environment from March 31, 2025, and adopting phishing-resistant MFA is also becoming essential from a regulatory compliance perspective.

💻 Code Example

// TOTP (Time-based OTP) MFA 구현 - Node.js
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
const express = require('express');
const app = express();

// 1. MFA 등록 - 시크릿 생성 및 QR 코드 제공
app.post('/api/mfa/setup', async (req, res) => {
    const userId = req.user.id;

    // TOTP 시크릿 생성
    const secret = speakeasy.generateSecret({
        name: `MyApp:${req.user.email}`,
        issuer: 'MyApp',
        length: 32
    });

    // 시크릿을 DB에 임시 저장 (검증 전까지는 활성화하지 않음)
    await db.users.update(userId, {
        mfa_secret_temp: secret.base32,
        mfa_enabled: false
    });

    // QR 코드 생성 (사용자가 인증 앱으로 스캔)
    const qrCodeUrl = await QRCode.toDataURL(secret.otpauth_url);

    res.json({
        secret: secret.base32,  // 수동 입력용
        qrCode: qrCodeUrl,      // 앱 스캔용
        message: 'MFA 앱에서 QR 코드를 스캔한 후 코드를 입력하세요'
    });
});

// 2. MFA 등록 확인 - 첫 번째 코드 검증
app.post('/api/mfa/verify-setup', async (req, res) => {
    const { token } = req.body;
    const userId = req.user.id;

    const user = await db.users.findById(userId);

    // TOTP 검증 (30초 윈도우, 전후 1개 허용)
    const verified = speakeasy.totp.verify({
        secret: user.mfa_secret_temp,
        encoding: 'base32',
        token: token,
        window: 1  // 시간 드리프트 허용
    });

    if (!verified) {
        return res.status(400).json({ error: '잘못된 인증 코드입니다' });
    }

    // MFA 활성화 및 복구 코드 생성
    const recoveryCodes = generateRecoveryCodes(10);

    await db.users.update(userId, {
        mfa_secret: user.mfa_secret_temp,
        mfa_secret_temp: null,
        mfa_enabled: true,
        mfa_recovery_codes: hashRecoveryCodes(recoveryCodes)
    });

    res.json({
        success: true,
        recoveryCodes: recoveryCodes,
        message: '복구 코드를 안전한 곳에 저장하세요. 다시 표시되지 않습니다.'
    });
});

// 3. 로그인 시 MFA 검증
app.post('/api/auth/verify-mfa', async (req, res) => {
    const { sessionToken, mfaToken } = req.body;

    // 1단계 인증(비밀번호) 완료된 세션 확인
    const pendingSession = await getPendingMfaSession(sessionToken);
    if (!pendingSession) {
        return res.status(401).json({ error: '세션이 만료되었습니다' });
    }

    const user = await db.users.findById(pendingSession.userId);

    // TOTP 검증
    const verified = speakeasy.totp.verify({
        secret: user.mfa_secret,
        encoding: 'base32',
        token: mfaToken,
        window: 1
    });

    if (!verified) {
        // 복구 코드인지 확인
        const isRecoveryCode = await verifyRecoveryCode(user, mfaToken);
        if (!isRecoveryCode) {
            await logFailedMfa(user.id, req.ip);
            return res.status(401).json({ error: '잘못된 인증 코드입니다' });
        }
    }

    // 인증 성공 - 전체 세션 발급
    const fullSession = await createFullSession(user);

    res.json({
        success: true,
        accessToken: fullSession.accessToken,
        refreshToken: fullSession.refreshToken
    });
});

// 복구 코드 생성 함수
function generateRecoveryCodes(count) {
    const codes = [];
    for (let i = 0; i < count; i++) {
        // 8자리 영숫자 코드 (예: ABCD-1234)
        const code = require('crypto').randomBytes(4)
            .toString('hex').toUpperCase();
        codes.push(`${code.slice(0, 4)}-${code.slice(4)}`);
    }
    return codes;
}

app.listen(3000);
// WebAuthn (FIDO2/Passkey) 구현 - 브라우저 + 서버
// 피싱 방지 MFA의 표준 구현

// ===== 프론트엔드 (브라우저) =====

// 1. Passkey 등록 (Registration)
async function registerPasskey() {
    // 서버에서 등록 옵션 가져오기
    const optionsRes = await fetch('/api/webauthn/register-options', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    });
    const options = await optionsRes.json();

    // Base64 -> ArrayBuffer 변환
    options.challenge = base64ToBuffer(options.challenge);
    options.user.id = base64ToBuffer(options.user.id);

    // 브라우저의 WebAuthn API 호출
    // 사용자에게 생체인식 또는 보안키 프롬프트 표시
    const credential = await navigator.credentials.create({
        publicKey: options
    });

    // 서버에 등록 완료 전송
    const response = await fetch('/api/webauthn/register-verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            id: credential.id,
            rawId: bufferToBase64(credential.rawId),
            response: {
                clientDataJSON: bufferToBase64(credential.response.clientDataJSON),
                attestationObject: bufferToBase64(credential.response.attestationObject)
            },
            type: credential.type
        })
    });

    return response.json();
}

// 2. Passkey 인증 (Authentication)
async function authenticateWithPasskey() {
    // 서버에서 인증 옵션 가져오기
    const optionsRes = await fetch('/api/webauthn/auth-options', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    });
    const options = await optionsRes.json();

    options.challenge = base64ToBuffer(options.challenge);
    options.allowCredentials = options.allowCredentials?.map(cred => ({
        ...cred,
        id: base64ToBuffer(cred.id)
    }));

    // 브라우저의 WebAuthn API 호출
    // Passkey 선택 프롬프트 또는 생체인식
    const assertion = await navigator.credentials.get({
        publicKey: options
    });

    // 서버에 인증 검증 요청
    const response = await fetch('/api/webauthn/auth-verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            id: assertion.id,
            rawId: bufferToBase64(assertion.rawId),
            response: {
                clientDataJSON: bufferToBase64(assertion.response.clientDataJSON),
                authenticatorData: bufferToBase64(assertion.response.authenticatorData),
                signature: bufferToBase64(assertion.response.signature),
                userHandle: assertion.response.userHandle
                    ? bufferToBase64(assertion.response.userHandle) : null
            },
            type: assertion.type
        })
    });

    return response.json();
}

// ===== 백엔드 (Node.js + @simplewebauthn/server) =====

const {
    generateRegistrationOptions,
    verifyRegistrationResponse,
    generateAuthenticationOptions,
    verifyAuthenticationResponse
} = require('@simplewebauthn/server');

const rpName = 'MyApp';
const rpID = 'myapp.com';
const origin = 'https://myapp.com';

// 등록 옵션 생성
app.post('/api/webauthn/register-options', async (req, res) => {
    const user = req.user;
    const existingCredentials = await db.credentials.findByUserId(user.id);

    const options = await generateRegistrationOptions({
        rpName,
        rpID,
        userID: user.id,
        userName: user.email,
        userDisplayName: user.name,
        attestationType: 'none',
        excludeCredentials: existingCredentials.map(cred => ({
            id: cred.credentialID,
            type: 'public-key'
        })),
        authenticatorSelection: {
            residentKey: 'preferred',      // Passkey (Discoverable Credential)
            userVerification: 'preferred'  // 생체인식 선호
        }
    });

    // 챌린지를 세션에 저장 (검증 시 사용)
    req.session.webauthnChallenge = options.challenge;

    res.json(options);
});

// 인증 검증
app.post('/api/webauthn/auth-verify', async (req, res) => {
    const { body } = req;
    const expectedChallenge = req.session.webauthnChallenge;

    const credential = await db.credentials.findByCredentialId(body.id);
    if (!credential) {
        return res.status(400).json({ error: 'Unknown credential' });
    }

    const verification = await verifyAuthenticationResponse({
        response: body,
        expectedChallenge,
        expectedOrigin: origin,  // 피싱 방지의 핵심!
        expectedRPID: rpID,
        authenticator: {
            credentialID: credential.credentialID,
            credentialPublicKey: credential.publicKey,
            counter: credential.counter
        }
    });

    if (!verification.verified) {
        return res.status(401).json({ error: 'Verification failed' });
    }

    // 카운터 업데이트 (클로닝 공격 방지)
    await db.credentials.updateCounter(
        credential.id,
        verification.authenticationInfo.newCounter
    );

    // 세션 발급
    const session = await createSession(credential.userId);
    res.json({ success: true, ...session });
});
# TOTP MFA 구현 - Python/Flask
import pyotp
import qrcode
import io
import base64
import secrets
from flask import Flask, request, jsonify, session
from functools import wraps

app = Flask(__name__)
app.secret_key = secrets.token_hex(32)

# 1. MFA 등록 시작
@app.route('/api/mfa/setup', methods=['POST'])
def setup_mfa():
    user_id = session.get('user_id')
    user = db.get_user(user_id)

    # TOTP 시크릿 생성 (Base32 인코딩)
    secret = pyotp.random_base32()

    # OTP URI 생성 (인증 앱용)
    totp = pyotp.TOTP(secret)
    provisioning_uri = totp.provisioning_uri(
        name=user['email'],
        issuer_name='MyApp'
    )

    # QR 코드 생성
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(provisioning_uri)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    buffer = io.BytesIO()
    img.save(buffer, format='PNG')
    qr_base64 = base64.b64encode(buffer.getvalue()).decode()

    # 임시 저장 (검증 전)
    db.update_user(user_id, {
        'mfa_secret_temp': secret,
        'mfa_pending': True
    })

    return jsonify({
        'secret': secret,
        'qr_code': f'data:image/png;base64,{qr_base64}',
        'message': 'MFA 앱에서 QR 코드를 스캔하세요'
    })

# 2. MFA 등록 확인
@app.route('/api/mfa/verify-setup', methods=['POST'])
def verify_mfa_setup():
    user_id = session.get('user_id')
    token = request.json.get('token')

    user = db.get_user(user_id)
    secret = user.get('mfa_secret_temp')

    if not secret:
        return jsonify({'error': 'MFA 설정을 먼저 시작하세요'}), 400

    # TOTP 검증
    totp = pyotp.TOTP(secret)
    if not totp.verify(token, valid_window=1):
        return jsonify({'error': '잘못된 인증 코드입니다'}), 400

    # 복구 코드 생성
    recovery_codes = [
        f"{secrets.token_hex(2).upper()}-{secrets.token_hex(2).upper()}"
        for _ in range(10)
    ]

    # MFA 활성화
    db.update_user(user_id, {
        'mfa_secret': secret,
        'mfa_secret_temp': None,
        'mfa_enabled': True,
        'mfa_pending': False,
        'mfa_recovery_codes': hash_recovery_codes(recovery_codes)
    })

    return jsonify({
        'success': True,
        'recovery_codes': recovery_codes,
        'message': '복구 코드를 안전하게 저장하세요'
    })

# 3. MFA 검증 데코레이터
def require_mfa(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        user_id = session.get('user_id')
        mfa_verified = session.get('mfa_verified')

        if not user_id:
            return jsonify({'error': 'Unauthorized'}), 401

        user = db.get_user(user_id)

        if user.get('mfa_enabled') and not mfa_verified:
            return jsonify({
                'error': 'MFA required',
                'mfa_required': True
            }), 403

        return f(*args, **kwargs)
    return decorated

# 4. 로그인 시 MFA 검증
@app.route('/api/auth/verify-mfa', methods=['POST'])
def verify_mfa():
    token = request.json.get('token')
    user_id = session.get('pending_user_id')  # 1단계 인증 완료 상태

    if not user_id:
        return jsonify({'error': '먼저 로그인하세요'}), 401

    user = db.get_user(user_id)
    totp = pyotp.TOTP(user['mfa_secret'])

    if totp.verify(token, valid_window=1):
        # MFA 성공
        session['user_id'] = user_id
        session['mfa_verified'] = True
        session.pop('pending_user_id', None)

        return jsonify({'success': True})

    # 복구 코드 확인
    if verify_recovery_code(user, token):
        session['user_id'] = user_id
        session['mfa_verified'] = True
        return jsonify({'success': True, 'used_recovery_code': True})

    return jsonify({'error': '잘못된 인증 코드입니다'}), 401

# 보호된 엔드포인트 예시
@app.route('/api/sensitive-data')
@require_mfa
def get_sensitive_data():
    return jsonify({'data': 'This is protected data'})

if __name__ == '__main__':
    app.run(debug=True)

🗣️ Say It Like This in Practice

💬 In a Security Policy Meeting
"SMS OTP is vulnerable to SIM swapping attacks, so let's phase it out. We propose a roadmap in which administrators and developers switch to FIDO2 security keys immediately, and general users migrate to an authenticator app (TOTP) or Passkey within 6 months. We also need to consider the PCI DSS 4.0 compliance deadline."
💬 In a User Experience Discussion
"Adopting Passkey reduces login time from 69 seconds to 3 seconds, and raises the success rate from 30% to 95%. We can resolve the user drop-off problem while also strengthening phishing defense. In the beginning, we can run passwords and Passkey in parallel and then transition gradually."
💬 In an Incident Review
"In this phishing attack, 3 accounts that were using TOTP were taken over. The attacker relayed the OTP in real time. By contrast, the accounts using FIDO2 security keys were safe. This is because, thanks to WebAuthn's origin binding, authentication itself was impossible on the phishing site."

⚠️ Cautions & Best Practices

❌
Reliance on SMS OTP

SMS is the weakest MFA method due to SIM swapping and SS7 vulnerabilities. NIST also classifies SMS OTP as a "restricted" authenticator. Avoid SMS OTP in new implementations, and migrate existing systems to TOTP or Passkey.

❌
Lack of Recovery Methods

You must prepare for situations where account access becomes impossible if an MFA device is lost. Issue recovery codes (10 or more) and encourage users to register a backup MFA method. The recovery process must also be sufficiently secure.

❌
MFA Fatigue Attacks (MFA Fatigue)

With push notification-based MFA, an attacker can repeatedly send authentication requests, causing the user to approve one by mistake. Switch to methods that require user interaction, such as Number Matching or FIDO2.

✅
MFA Best Practices

Deploy FIDO2 security keys first to high-risk users (administrators, developers, finance), and expand to general users with Passkey/TOTP. Monitor the MFA enrollment rate, and send periodic reminders to users who have not enrolled. When implementing WebAuthn, test that origin binding works properly.

🔗 Related Terms

📚 Learn More