devHọc Dev
EN
Bài học

Tuần 1 - Ngày 5: MFA, Passkeys, RBAC và ABAC

Tuần 1 – Ngày 5

Bài này gộp 2 chủ đề: MFA & Passkeys, RBAC, ABAC & Authorization Patterns.

Mục tiêu học tập

  • Hiểu vì sao password đơn lẻ không còn đủ trong threat landscape 2024
  • Cách hoạt động của TOTP (RFC 6238) — Google Authenticator, Authy
  • Vì sao SMS OTP yếu và khi nào còn chấp nhận được
  • WebAuthn / Passkeys — public-key crypto thay thế password, chống phishing hoàn toàn
  • Recovery codes và backup methods cho khi user mất device
  • Phân biệt Authentication (bạn là ai) và Authorization (bạn được phép gì)
  • Hiểu RBAC — roles và permissions, role hierarchy, ví dụ thực tế
  • Hiểu ABAC — attributes (user, resource, environment) và policy engines
  • Giới thiệu ReBAC — relationship-based (Google Zanzibar, SpiceDB)
  • Nhận diện và tránh OWASP A01: Broken Access Control

Phần 1: MFA & Passkeys

1. Vì sao password không đủ

Threat landscape 2024

ThreatCách hoạt độngPassword defense
PhishingSite giả g00gle.com lừa user nhập passwordYếu — user dễ bị lừa
Credential stuffingDùng password leak từ site khácYếu — 60-80% user reuse
Brute forceThử password phổ biếnMạnh nếu password phức tạp
Database breachHash password leak → crack offlinePhụ thuộc hashing algo
Keylogger / malwareGhi keystrokeYếu hoàn toàn
Shoulder surfingNhìn lén khi gõYếu
Social engineeringLừa user/support reset passwordPhụ thuộc process

Số liệu (Microsoft, Verizon DBIR 2024):

  • ~99.9% account compromise có thể chặn được nếu enable MFA
  • Credential stuffing chiếm 40%+ breach pattern
  • Phishing là vector #1 cho initial access

Các "factor" của authentication

┌─────────────────┐┌─────────────────┐┌──────────────────┐│Somethingyou││Somethingyou││Somethingyou││KNOW││HAVE││ARE││││││││-password││-phone(SMS)││-fingerprint││-PIN││-TOTPapp││-face││-securityQ││-hardwarekey││-voice│└─────────────────┘└─────────────────┘└──────────────────┘

Multi-Factor Authentication (MFA) = ≥ 2 factor khác loại. Password + PIN = 1 factor (cùng "know"). Password + phone OTP = 2 factor.

2. TOTP — Time-based One-Time Password

Chuẩn

RFC 6238 — TOTP, dựa trên RFC 4226 — HOTP (counter-based).

TOTP(secret, time) = HOTP(secret, floor(time / 30))

HOTP(K, C) = Truncate(HMAC-SHA1(K, C))
  • secret: random 160-bit (20 bytes), share giữa server và user device khi enroll
  • time: Unix timestamp tính bằng giây
  • Time step: 30 giây (standard)
  • Output: 6 chữ số

Flow enrollment

┌──────┐┌──────────┐┌────────────┐│User││Server││TOTPApp│└──┬───┘└────┬─────┘└─────┬──────┘││││EnableMFA││├──────────────────────────►│││││││Generate20-byterandom│││secret="JBSWY3DPEHPK3PXP"│││││QRcode:otpauth://totp/│││App:user@email.com?│││secret=JBSWY3DPEHPK3PXP&││issuer=App│││◄──────────────────────────│││││ScanQR(manualentryalternative)│├─────────────────────────────────────────────────────────►││││Storesecret││inkeychain││││Entercurrent6-digitcodetoconfirm││◄─────────────────────────────────────────────────────────┤││││POST/verify-mfa{code}││├──────────────────────────►││││TOTP(secret,now)==code?│││LưusecretvàoDBcủauser││Success│││◄──────────────────────────││

TOTP URI format (otpauth://)

otpauth://totp/MyApp:alice@example.com
   ?secret=JBSWY3DPEHPK3PXP
   &issuer=MyApp
   &algorithm=SHA1
   &digits=6
   &period=30

App scan QR → tự lưu, tự generate code mỗi 30s.

Code Node.js với otplib

// npm install otplib qrcode
import { authenticator } from "otplib";
import QRCode from "qrcode";

// 1. Enroll: generate secret cho user
function setupMFA(user) {
  const secret = authenticator.generateSecret();   // base32, 32 chars
  
  // Lưu encrypted vào DB
  const uri = authenticator.keyuri(
    user.email,           // account name
    "MyApp",              // issuer
    secret
  );
  
  return { secret, uri };   // user scan uri → QR code
}

// 2. Render QR
const qrDataUrl = await QRCode.toDataURL(uri);

// 3. Verify code
function verifyMFA(user, userCode) {
  const secret = decrypt(user.mfa_secret);
  
  // window=1 cho phép ±30s clock skew
  return authenticator.verify({ token: userCode, secret });
}

// 4. Generate code (chỉ dùng để test, app làm phía user)
const currentCode = authenticator.generate(secret);
console.log(currentCode);   // "523891"

Python với pyotp

# pip install pyotp qrcode
import pyotp
import qrcode

# Enroll
secret = pyotp.random_base32()   # "JBSWY3DPEHPK3PXP..."
uri = pyotp.totp.TOTP(secret).provisioning_uri(
    name="alice@example.com",
    issuer_name="MyApp"
)

# Generate QR
img = qrcode.make(uri)
img.save("qr.png")

# Verify
totp = pyotp.TOTP(secret)
print(totp.now())              # "523891"
print(totp.verify("523891"))   # True nếu trong window 30s

TOTP pitfalls

  • Clock skew: server và device không sync → verify thường accept ±1 window (±30s)
  • Replay: same code có thể dùng lại trong 30s window → lưu last-used code, từ chối nếu match
  • Secret lưu plaintext: phải encrypt at rest, dùng KMS
  • QR code leak: nếu user screenshot QR và lưu cloud, attacker chiếm cloud lấy được → enrollment không phải one-shot, có thể regenerate

3. SMS OTP — Tại sao yếu?

Cách hoạt động

Server → Twilio/AWS SNS → SMS gateway → carrier → user phone
                ↑                          ↑
        có nhiều mắt xích           có thể intercept

Threats cụ thể

1. SIM swap (SIM hijacking)

Attacker gọi telco của victim:
  "Hi, tôi mất phone, port số XXX sang SIM mới của tôi"
  → Social engineering support → port thành công
  → Mọi SMS đi vào SIM của attacker
  → Attacker nhận OTP, reset password

Đã xảy ra với nhiều người nổi tiếng (Jack Dorsey, crypto whales mất hàng triệu USD).

2. SS7 protocol attack

  • SS7 là protocol cũ kết nối các carrier toàn cầu
  • Attacker truy cập SS7 (mua trên dark web hoặc qua corrupt telco) → intercept SMS bất kỳ số nào toàn cầu
  • Đã được chứng minh thực tế nhiều lần

3. SMS phishing (smishing)

  • "Bank của bạn: gửi OTP 123456 cho support để verify"
  • User gửi OTP cho attacker

4. Telco insider

  • Nhân viên telco có thể nhìn nội dung SMS

Khi nào SMS OTP còn chấp nhận?

Use caseSMS OTP OK?Lý do
Low-value consumer appOKChi phí breach thấp, UX dễ
Bank, crypto exchangeKHÔNGHigh-value target, SIM swap nghiêm trọng
HealthcareKHÔNGHIPAA, dữ liệu nhạy cảm
Internal corporateKHÔNGPhishing/social engineering vector
Fallback khi user mất TOTP/passkeyOK với giới hạnBetter than nothing, nên thêm friction (waiting period)

NIST 800-63B (2017) xếp SMS OTP vào nhóm RESTRICTED — không cấm nhưng khuyến cáo hạn chế, nhất là với high-assurance. Nhiều app (Google, Microsoft) cho phép disable SMS hoàn toàn.

So sánh MFA methods

MethodPhishing-resistantSIM swapUX
SMS OTPKhôngVulnerableDễ
Email OTPKhôngOK (nếu email an toàn)Dễ
TOTP appKhông (vẫn enter code)An toànTrung bình (cần app)
Push notificationKhông (push fatigue)An toànDễ
Hardware key (FIDO2)CóAn toànCần đem theo
Passkey (WebAuthn)CóAn toànDễ (built-in OS)

4. WebAuthn / Passkeys

Vấn đề mọi MFA "code" gặp phải

User vào g00gle.com (phishing site):
  1. Nhập username + password → attacker capture
  2. Site giả forward username/password tới google.com thật
  3. Google gửi MFA challenge → user nhập TOTP code
  4. User type 6 chữ số vào g00gle.com → attacker capture
  5. Attacker dùng TOTP code trong 30s window → login thành công

TOTP, SMS, email OTP đều không chống phishing vì user "type code" vào bất kỳ site nào.

WebAuthn / FIDO2 nguyên lý

Public-key cryptography:
  - Khi đăng ký: device sinh keypair (private + public)
  - Server lưu PUBLIC key, gắn với origin (https://example.com)
  - Private key NEVER LEAVE device

Authentication:
  - Server gửi challenge (random bytes)
  - Device sign challenge với PRIVATE key
  - GẮN VỚI ORIGIN — browser chỉ cho dùng key với đúng domain
  - Server verify signature với PUBLIC key

Phishing impossible: nếu user đến g00gle.com, browser sẽ không cho dùng key của google.com → không có gì để type/leak.

Passkey vs Hardware Security Key

┌──────────────────────────┐┌──────────────────────────┐│Passkey││HardwareSecurityKey││││(YubiKey,Titan)││-Lưutrongdevice││-Vậtlýriêngbiệt││(iCloudKeychain,││-USB/NFC/Bluetooth││GooglePasswordMgr,││-Khôngsync││WindowsHello)││-Bền,chốngmalware││-Syncquacloud││-Cầnđemtheo││-UXrấttốt││-Caocấp(enterprise)││-TouchID/FaceID│││└──────────────────────────┘└──────────────────────────┘
PasskeyHardware Key
Phishing-resistantCóCó
Sync giữa devicesCó (qua iCloud/Google)Không (cần multiple keys)
Lost device recoveryPhục hồi từ cloudCần backup key
UXExcellentTốt nhưng cần plug-in
CostFree$25-70 mỗi key
Best forConsumerEnterprise, high-value account

Flow registration (WebAuthn)

// 1. Server tạo challenge
const challenge = crypto.randomBytes(32);
// Lưu challenge gắn với session

// 2. Client browser
const credential = await navigator.credentials.create({
  publicKey: {
    challenge: challenge,
    rp: { name: "MyApp", id: "example.com" },
    user: {
      id: Uint8Array.from(userId, c => c.charCodeAt(0)),
      name: "alice@example.com",
      displayName: "Alice",
    },
    pubKeyCredParams: [
      { alg: -7,  type: "public-key" },   // ES256
      { alg: -257, type: "public-key" },  // RS256
    ],
    authenticatorSelection: {
      authenticatorAttachment: "platform",   // built-in (TouchID, etc.)
      userVerification: "required",
      residentKey: "required",               // discoverable cho passkey
    },
    attestation: "none",
  },
});

// 3. Send credential.id, credential.publicKey, clientDataJSON to server
// 4. Server verify, lưu publicKey gắn với user

Flow authentication

// 1. Server tạo challenge
// 2. Client
const assertion = await navigator.credentials.get({
  publicKey: {
    challenge: challenge,
    rpId: "example.com",
    userVerification: "required",
  },
});

// 3. Send signature to server
// 4. Server verify signature với stored publicKey
//    Verify rpIdHash, challenge, origin, signature

Trong thực tế dùng thư viện như SimpleWebAuthn:

// npm install @simplewebauthn/server @simplewebauthn/browser
import { generateRegistrationOptions, verifyRegistrationResponse } from "@simplewebauthn/server";

// Server side
const options = await generateRegistrationOptions({
  rpName: "MyApp",
  rpID: "example.com",
  userID: Buffer.from(user.id),
  userName: user.email,
  attestationType: "none",
  authenticatorSelection: {
    residentKey: "required",
    userVerification: "required",
  },
});

// Browser side
import { startRegistration } from "@simplewebauthn/browser";
const attestation = await startRegistration(options);

// Server verify
const verification = await verifyRegistrationResponse({
  response: attestation,
  expectedChallenge: storedChallenge,
  expectedOrigin: "https://example.com",
  expectedRPID: "example.com",
});

if (verification.verified) {
  // Lưu verification.registrationInfo.credentialPublicKey, credentialID
}

5. Recovery Codes & Backup

User mất phone / hardware key → cần recovery, không thì lock account vĩnh viễn.

Pattern recovery codes

Khi enable MFA, server generate 10 codes one-time:
  4f7a-9b2c
  3d8e-1c5f
  9a2b-7e4d
  ... 7 codes nữa

User được yêu cầu:
  - Lưu offline (print, password manager)
  - Mỗi code dùng được 1 lần
  - Dùng để bypass MFA khi cần

Implementation:

function generateRecoveryCodes(count = 10) {
  return Array.from({ length: count }, () => {
    const bytes = crypto.randomBytes(4);
    return bytes.toString("hex").slice(0, 8);
  });
}

// Lưu HASH của recovery codes (như password)
const hashes = await Promise.all(
  codes.map(c => bcrypt.hash(c, 12))
);
// DB.user.recovery_code_hashes = hashes

// Verify
async function verifyRecoveryCode(user, code) {
  for (let i = 0; i < user.recovery_code_hashes.length; i++) {
    const hash = user.recovery_code_hashes[i];
    if (hash && await bcrypt.compare(code, hash)) {
      user.recovery_code_hashes[i] = null;   // invalidate
      await user.save();
      return true;
    }
  }
  return false;
}

Multiple methods

User profile:
  ✓ Password (always)
  ✓ Passkey 1: "iPhone 15"     (primary)
  ✓ Passkey 2: "Macbook Air"   (backup)
  ✓ TOTP: "Google Authenticator"  (backup)
  ✓ Recovery codes: 8/10 còn lại
  ✗ SMS (disabled by user)

Best practice: cho phép user enroll nhiều passkey trên nhiều device → mất 1 device vẫn login được.

Recovery flow đặt câu hỏi

Recovery methodAn toàn?
Email reset linkOK nếu email có MFA
SMS reset linkYếu (SIM swap)
Security questionsRất yếu (đoán/Google ra)
Backup codesTốt
Identity verification (passport upload)Tốt nhưng manual
Trusted contactOK cho consumer (Apple ID, Google)

Phần 2: RBAC, ABAC & Authorization Patterns

1. Authentication vs Authorization

┌─────────────────────────────┐┌─────────────────────────────┐│AUTHENTICATION(AuthN)││AUTHORIZATION(AuthZ)││"Whoareyou?"││"Whatcanyoudo?"││││││-Password││-Roles││-MFA││-Permissions││-OIDC││-Policies││-Session││-Resourceownership││││││Output:useridentity││Output:allow/deny│└─────────────────────────────┘└─────────────────────────────┘Bước1Bước2(đãhọcW2)(bàihômnay)

Tại sao phân biệt quan trọng?

Một số người nhầm: "Đã login thì truy cập được mọi thứ" → broken access control (OWASP A01 #1).

Ví dụ bug thực tế:

# User A xem order của mình
GET /api/orders/12345

# Server chỉ check "user authenticated?" → YES
# Không check "order 12345 có thuộc user A không?"
# → User A đổi ID, xem order của User B
GET /api/orders/99999   ← thuộc User B → vẫn trả về!

Đây là IDOR (Insecure Direct Object Reference) — vulnerability cực phổ biến.

2. RBAC — Role-Based Access Control

Khái niệm cơ bản

┌───────┐┌───────┐┌──────────────┐│User│──────►│Role│──────►│Permission│└───────┘has└───────┘grants└──────────────┘│▼┌──────────────────┐│Action+Resource││"read:orders"││"write:users"│└──────────────────┘

User được gán role → role có permissions → permission cho phép action trên resource type.

Ví dụ: blog platform

Roles:├──admin│└──permissions:[│posts:create,posts:read,posts:update,posts:delete,│users:read,users:update,users:delete,│site:configure│]├──editor│└──permissions:[posts:create,posts:read,posts:update]├──viewer│└──permissions:[posts:read]└──anonymous└──permissions:[posts:read]←chỉpublicposts

Role hierarchy

Roles có thể "thừa kế" permissions:

admin
  ↑ inherits
editor
  ↑ inherits
viewer

admin tự động có mọi permission của editor, editor có mọi permission của viewer. Đỡ duplicate.

Schema database

-- Roles
CREATE TABLE roles (
  id       SERIAL PRIMARY KEY,
  name     VARCHAR(50) UNIQUE,
  parent_id INT REFERENCES roles(id)   -- hierarchy
);

-- Permissions
CREATE TABLE permissions (
  id   SERIAL PRIMARY KEY,
  name VARCHAR(100) UNIQUE   -- "posts:create"
);

-- Many-to-many
CREATE TABLE role_permissions (
  role_id       INT REFERENCES roles(id),
  permission_id INT REFERENCES permissions(id),
  PRIMARY KEY (role_id, permission_id)
);

CREATE TABLE user_roles (
  user_id INT REFERENCES users(id),
  role_id INT REFERENCES roles(id),
  PRIMARY KEY (user_id, role_id)
);

Code Node.js — middleware

// Lấy permissions của user (cached)
async function getUserPermissions(userId) {
  const cached = await cache.get(`perms:${userId}`);
  if (cached) return cached;
  
  // Query roles + hierarchy + permissions
  const perms = await db.query(`
    WITH RECURSIVE role_tree AS (
      SELECT id FROM roles WHERE id IN (
        SELECT role_id FROM user_roles WHERE user_id = $1
      )
      UNION
      SELECT r.parent_id FROM roles r
      JOIN role_tree rt ON r.id = rt.id
      WHERE r.parent_id IS NOT NULL
    )
    SELECT DISTINCT p.name FROM permissions p
    JOIN role_permissions rp ON rp.permission_id = p.id
    WHERE rp.role_id IN (SELECT id FROM role_tree)
  `, [userId]);
  
  const list = perms.rows.map(r => r.name);
  await cache.set(`perms:${userId}`, list, 60);
  return list;
}

// Middleware
function requirePermission(perm) {
  return async (req, res, next) => {
    const perms = await getUserPermissions(req.user.id);
    if (!perms.includes(perm)) {
      return res.status(403).json({ error: "Forbidden" });
    }
    next();
  };
}

// Route
app.delete("/posts/:id",
  requireAuth,
  requirePermission("posts:delete"),
  deletePostHandler
);

RBAC ưu / nhược

ProsCons
Đơn giản, dễ hiểu, dễ implementKhông xử lý được "user A chỉ edit post của mình"
Tốt cho ít roles, rõ ràngRole explosion: mỗi combination → role mới
Audit dễ (xem role có quyền gì)Không context (thời gian, location, IP)
Hỗ trợ rộng (DB native, framework)Static — khó change real-time

Role explosion ví dụ: bạn có 5 phòng ban × 4 levels × 3 regions = 60 roles → quản lý nightmare.

3. ABAC — Attribute-Based Access Control

Khác RBAC ở chỗ nào?

RBAC: User → Role → Permission
ABAC: User attrs + Resource attrs + Environment → Policy → Allow/Deny

Quyết định dựa trên attributes (thuộc tính):

Loại attributeVí dụ
User (Subject)dept, level, clearance, location, age
Resource (Object)owner, classification, type, dept
Actionread, write, delete, share
Environmenttime, IP, device, MFA passed, request method

Ví dụ chính sách ABAC

Policy: "Bác sĩ chỉ xem được hồ sơ bệnh nhân của khoa mình
         trong giờ hành chính từ máy nội bộ"

ALLOW
  IF user.role == "doctor"
  AND resource.type == "patient_record"
  AND user.department == resource.department
  AND environment.time BETWEEN 08:00 AND 18:00
  AND environment.ip IN hospital_network

Cùng user bác sĩ, cùng action read, cùng resource type, nhưng kết quả khác nhau theo context — RBAC không làm được.

Policy languages

1. XACML (eXtensible Access Control Markup Language)

  • Chuẩn OASIS, XML
  • Phức tạp, học thuật → ít dùng trong startup

2. AWS IAM Policy (JSON-based ABAC + RBAC hybrid)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/${aws:username}/*",
    "Condition": {
      "IpAddress": { "aws:SourceIp": "10.0.0.0/8" },
      "DateGreaterThan": { "aws:CurrentTime": "2025-01-01T00:00:00Z" }
    }
  }]
}

3. OPA / Rego (Open Policy Agent)

package authz

default allow = false

allow {
    input.user.role == "doctor"
    input.resource.type == "patient_record"
    input.user.department == input.resource.department
    time.now_ns() <= time.parse_rfc3339_ns(input.resource.expires_at)
}

OPA chạy như sidecar/service, app gửi input (user, resource, action), nhận về allow/deny. Phổ biến trong Kubernetes admission control, microservices.

4. AWS Cedar (2023)

permit (
    principal in Group::"doctors",
    action == Action::"viewRecord",
    resource
) when {
    principal.department == resource.department &&
    context.time >= time("08:00:00") &&
    context.time <= time("18:00:00")
};

Cedar có verifier formal (proved correct), schema-aware, syntax dễ hơn Rego.

Architecture ABAC

┌──────────────────┐│Client│└────────┬─────────┘│Request:GET/record/42▼┌──────────────────┐┌──────────────────┐│PolicyEnforce-││PolicyAdmin││mentPoint(PEP)││Point(PAP)││app/proxy││(UIviếtpolicy)│└────────┬─────────┘└─────────┬────────┘│Query:allow?│define▼▼┌──────────────────────────────────────────┐│PolicyDecisionPoint(PDP)││(OPA,Cedar,AWSIAM)│└────────┬─────────────────────────────────┘│fetchattributes▼┌──────────────────┐│PolicyInfo││Point(PIP)││(DB,LDAP,...)│└──────────────────┘
ComponentVai trò
PEPIntercept request, gọi PDP để hỏi quyết định
PDPEvaluate policy, return allow/deny
PAPNơi admin viết policy
PIPProvide attributes (user, resource) cho PDP

RBAC vs ABAC

RBACABAC
Quyết định dựa trênRoleAttributes (user/resource/env)
Context-aware (time, IP)Không (cần extend)Có
"User edit chỉ post của mình"Khó (cần per-resource policy)Dễ (user.id == resource.owner_id)
Quản lýĐơn giản, UI dễPhức tạp, cần ngôn ngữ policy
AuditDễ (list role → permission)Khó (cần evaluate policy với data thật)
Khi nào dùngÍt role, rõ ràng (CMS, basic SaaS)Compliance phức tạp (healthcare, finance, multi-tenant SaaS)

4. ReBAC — Relationship-Based Access Control

Khái niệm

ReBAC mô hình hóa permission như graph relationships:

user:alice──member──►group:engineeringgroup:engineering──viewer──►doc:design-spec│└──alicecóquyềnviewertrêndocuser:bob──owner──►doc:design-spec│└──boblàowner→cóquyềncaohơn

Google Zanzibar (2019 paper)

Google publish paper mô tả hệ thống unified authorization phục vụ Drive, Docs, YouTube, Cloud — xử lý trillions of permission checks/day.

Mô hình tuple đơn giản:

<object>#<relation>@<subject>

doc:readme#viewer@user:alice
doc:readme#viewer@group:engineering#member
group:engineering#member@user:bob

Query:

Can user:alice view doc:readme?
  → Tìm path từ alice tới doc:readme với relation "viewer" hoặc cao hơn
  → Trả lời trong < 10ms với consistency guarantees

Implementation phổ biến

SpiceDBOpenFGAPermify
OriginAuthZedAuth0/OktaPermify Inc
Inspired byZanzibarZanzibarZanzibar
Open sourceYesYes (CNCF)Yes
Use caseProduction, enterpriseMainstreamProduction

Ví dụ schema (SpiceDB)

definition user {}

definition group {
  relation member: user
}

definition document {
  relation owner: user
  relation viewer: user | group#member
  relation editor: user | group#member
  
  permission view = viewer + editor + owner
  permission edit = editor + owner
  permission delete = owner
}
# Write relationships
zed relationship create document:readme viewer user:alice
zed relationship create group:eng member user:bob
zed relationship create document:readme viewer group:eng#member

# Check
zed permission check document:readme view user:alice    # true
zed permission check document:readme delete user:alice  # false
zed permission check document:readme view user:bob       # true (through group)

Khi nào ReBAC vượt trội?

Use cases hợp với ReBAC:
- File sharing (Google Drive, Dropbox, Notion)
- Collaborative docs (figma, Linear, GitHub repos)
- Multi-tenant SaaS (tenant → workspace → project → user)
- Social network (friend-of-friend, group access)
- Healthcare (patient → care team → records)

Đặc điểm chung: resource ownership và sharing là first-class concept, không thể nhồi vào "role" được.

5. Authorization Pitfalls — OWASP A01

Pitfall 1: Client-side authorization

<!-- ❌ SAI: Hide delete button cho non-admin -->
<button v-if="user.role === 'admin'" @click="deletePost">Delete</button>

<!-- API endpoint không check → attacker gọi trực tiếp: -->
<!-- curl -X DELETE /api/posts/123 -H "Authorization: ..." -->

UI chỉ là UX, không phải security. Mọi authorization check phải ở backend.

Pitfall 2: IDOR (Insecure Direct Object Reference)

// ❌ SAI
app.get("/orders/:id", requireAuth, async (req, res) => {
  const order = await db.orders.findById(req.params.id);
  return res.json(order);   // không check ownership!
});

// ✅ ĐÚNG
app.get("/orders/:id", requireAuth, async (req, res) => {
  const order = await db.orders.findById(req.params.id);
  if (!order) return res.status(404).end();
  if (order.user_id !== req.user.id && !req.user.isAdmin) {
    return res.status(403).end();   // hoặc 404 để không leak existence
  }
  return res.json(order);
});

Pitfall 3: Missing function-level authz

// ❌ SAI: chỉ require auth, không require role
app.delete("/admin/users/:id", requireAuth, deleteUser);

// ✅ ĐÚNG
app.delete("/admin/users/:id",
  requireAuth,
  requirePermission("users:delete"),
  deleteUser
);

Path bắt đầu bằng /admin/* không tự dưng "admin only" — phải explicit middleware.

Pitfall 4: Mass assignment

// ❌ SAI
app.put("/users/:id", requireAuth, async (req, res) => {
  await db.users.update(req.params.id, req.body);
  // Attacker POST: { name: "...", role: "admin" }
  // → role bị overwrite thành admin
});

// ✅ ĐÚNG: whitelist field cho phép update
app.put("/users/:id", requireAuth, async (req, res) => {
  const { name, email, phone } = req.body;   // explicit pick
  await db.users.update(req.params.id, { name, email, phone });
});

Pitfall 5: Default permissive

// ❌ SAI
function canAccess(user, resource) {
  if (user.role === "guest") return false;
  return true;   // default allow!
}

// ✅ ĐÚNG: default deny
function canAccess(user, resource) {
  if (user.role === "admin") return true;
  if (user.role === "user" && resource.owner_id === user.id) return true;
  return false;   // default deny
}

Pitfall 6: Bỏ qua trong query

// ❌ SAI: filter ở app level → race condition, DB leak qua join
const allOrders = await db.orders.find();
return allOrders.filter(o => o.user_id === req.user.id);

// ✅ ĐÚNG: filter ngay trong query
const myOrders = await db.orders.find({ user_id: req.user.id });

PostgreSQL có Row-Level Security (RLS) — enforce ownership ở DB layer, không tin app:

CREATE POLICY user_orders ON orders
  FOR SELECT USING (user_id = current_setting('app.user_id')::int);

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

6. Mô hình kết hợp trong thực tế

Apps lớn thường kết hợp nhiều model:

Layer 1: RBAC cho global roles
  - admin, support, billing, user

Layer 2: ABAC cho conditions
  - user_dept == resource_dept
  - request_time IN business_hours
  - mfa_passed == true (cho sensitive ops)

Layer 3: ReBAC cho resource ownership
  - User own document
  - User member of workspace
  - Workspace shares folder with team

Ví dụ Notion-like app:

  • Global roles (admin, member, guest) → RBAC
  • Workspace/page/block ownership và sharing → ReBAC
  • Time-based access (token expiry, business hours) → ABAC

Câu hỏi ôn tập

  1. Tại sao password + TOTP vẫn không chống được phishing 100%?

    Xem đáp án

    Phishing site có thể proxy real-time: user nhập password trên g00gle.com, site forward đến google.com thật → google.com prompts MFA → user nhập TOTP code trên g00gle.com → site forward code trong window 30s → đăng nhập thành công. TOTP code là "shared secret tạm thời" — bất kỳ ai có code đều dùng được. Chỉ WebAuthn/Passkey (gắn key với origin) mới chống được phishing tuyệt đối.

  2. SMS OTP có ít nhất 3 lỗ hổng chính, kể ra và giải thích?

    Xem đáp án

    (1) SIM swap: attacker social-engineer telco port số sang SIM mới → nhận mọi SMS của victim → bypass MFA. (2) SS7 attack: protocol giữa các carrier không có authentication mạnh → attacker với SS7 access có thể intercept SMS bất kỳ số toàn cầu. (3) Smishing: user bị lừa gửi OTP qua phone/SMS cho fake support. (4) Bonus: SMS không encrypted end-to-end, nhân viên telco và trên đường truyền có thể đọc. NIST 800-63B xếp SMS OTP vào nhóm RESTRICTED — khuyến cáo hạn chế, nhất là với high-assurance.

  3. WebAuthn dùng nguyên lý gì để chống phishing, và "origin binding" nghĩa là gì?

    Xem đáp án

    WebAuthn dùng public-key cryptography: device sinh keypair khi đăng ký, private key never leaves device. Khi authenticate, device sign challenge bằng private key. Origin binding: browser chỉ cho phép dùng key với đúng rpId (domain) đã đăng ký. Nếu user đến g00gle.com (phishing), browser thấy origin không match → không cho dùng key của google.com → user không có gì để "type" hay leak → phishing impossible. Khác với TOTP nơi user gõ code vào bất kỳ site nào.

  4. Khác nhau giữa Passkey và hardware security key (YubiKey)?

    Xem đáp án

    Passkey lưu trong device (iCloud Keychain, Google Password Manager, Windows Hello), sync qua cloud giữa các device của user → mất phone vẫn login được trên laptop. Authenticate qua Touch ID/Face ID. Hardware key là thiết bị vật lý riêng (USB/NFC), không sync, phải cắm/chạm để dùng. Hardware key bền hơn, chống malware tốt hơn, không phụ thuộc cloud provider — phù hợp enterprise high-security. Passkey UX tốt hơn cho consumer, free. Cả hai đều phishing-resistant (đều là FIDO2/WebAuthn).

  5. Tại sao recovery codes nên hash như password, không lưu plaintext?

    Xem đáp án

    Recovery codes có cùng giá trị như password thứ hai — biết code = bypass MFA. Nếu DB breach và codes lưu plaintext, attacker có thể bypass MFA của tất cả user. Hash bằng bcrypt/argon2 giống password chính. Lưu ý: recovery codes ngắn (8-12 ký tự hex, entropy ~32-48 bit) nên brute force nhanh hơn password → vẫn cần hashing với work factor. Một số implementation dùng denylist: lưu list null cho codes đã used thay vì xóa entry để đếm số codes còn lại.

  6. Authentication và Authorization khác nhau thế nào, và lỗi thường gặp khi chỉ làm Authentication?

    Xem đáp án

    Authentication = "bạn là ai" (kiểm tra danh tính qua password/MFA/OIDC). Authorization = "bạn được phép làm gì" (kiểm tra quyền với resource cụ thể). Lỗi thường gặp: chỉ check requireAuth middleware → mọi user authenticated truy cập được mọi resource → IDOR (User A xem được order của User B chỉ bằng cách đổi ID trong URL). OWASP A01 (Broken Access Control) là vulnerability #1 năm 2021-2024 chính vì lỗi này.

  7. RBAC có "role explosion problem" — vấn đề gì và ABAC giải quyết ra sao?

    Xem đáp án

    Khi tổ chức có nhiều phòng ban × levels × regions × project, số roles bùng nổ theo cấp số nhân (5×4×3×10 = 600 roles). Mỗi user có thể cần nhiều role, mỗi role chỉ khác nhau ở 1-2 attribute. Quản lý nightmare. ABAC giải quyết bằng cách dùng attributes thay vì hardcode role: thay vì 600 roles, có 1 policy user.dept == resource.dept AND user.level >= resource.required_level — dùng được cho mọi combination. Trade-off: ABAC khó audit và evaluate hơn.

  8. ABAC policy hữu ích trong tình huống nào mà RBAC không xử lý được?

    Xem đáp án

    Các tình huống cần context: (1) "User edit chỉ post mình tạo" — cần check resource.owner_id == user.id, RBAC không có concept ownership per-resource. (2) "Truy cập admin chỉ trong giờ hành chính từ IP công ty" — cần check time và IP. (3) "Tài liệu classified chỉ user có clearance level ≥ tương đương" — cần compare attributes. (4) Multi-tenant SaaS: user thuộc tenant A không thể đọc data tenant B — user.tenant_id == resource.tenant_id. RBAC chỉ làm được nếu tạo 1 role per ownership/tenant → role explosion.

  9. ReBAC khác ABAC ở điểm cốt lõi nào? Cho ví dụ.

    Xem đáp án

    ABAC xét attributes (giá trị field) của user/resource/env. ReBAC xét graph relationships giữa các entity và traverse path. Ví dụ Google Drive: "alice có view doc:X?" — ReBAC trace: alice → member of → team-eng → viewer on → folder:designs → contains → doc:X → trả lời yes. Khó biểu diễn bằng attribute đơn giản. ReBAC tự nhiên cho collaborative apps (Drive, Notion, GitHub), social network (friend-of-friend), multi-level org structure. Google Zanzibar và open source clone (SpiceDB, OpenFGA) implement pattern này.

  10. Vì sao filter authorization ở app level (sau khi query) là pattern nguy hiểm?

Xem đáp án

(1) Race condition: nếu permission thay đổi giữa query và filter, dữ liệu lộ. (2) Bug nguy hiểm: dev quên filter sẽ leak data. (3) Performance: query trả về quá nhiều record, filter sau → lãng phí. (4) Logs/error messages có thể leak qua exception. (5) Side channels: số lượng record trả về có thể leak existence. Pattern đúng: filter ngay trong query (WHERE user_id = ?) hoặc dùng Row-Level Security (Postgres RLS) để DB enforce — code app không bypass được.

Bài tập thực hành

Phần 1: MFA & Passkeys

# 1. TOTP với Node.js + otplib
mkdir mfa-lab && cd mfa-lab
npm init -y
npm install otplib qrcode

cat > totp.mjs << 'EOF'
import { authenticator } from "otplib";
import QRCode from "qrcode";

const secret = authenticator.generateSecret();
console.log("Secret:", secret);

const uri = authenticator.keyuri("alice@example.com", "MyApp", secret);
console.log("URI:", uri);

// Print QR ASCII
console.log(await QRCode.toString(uri, { type: "terminal" }));

// Generate current code
console.log("Current code:", authenticator.generate(secret));

// Verify (paste code từ Google Authenticator app)
import readline from "readline";
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question("Enter code from app: ", (token) => {
  console.log("Valid:", authenticator.verify({ token, secret }));
  rl.close();
});
EOF

node totp.mjs
# - Mở Google Authenticator/Authy
# - Scan QR code in terminal
# - Nhập 6-digit code, verify

# 2. Passkey demo với SimpleWebAuthn
# Clone https://github.com/MasterKale/SimpleWebAuthn/tree/master/example
# Chạy example, đăng ký passkey với TouchID/Face ID

# 3. Quan sát passkey trong:
# - macOS Keychain (Passwords app)
# - iCloud Keychain settings → Passwords
# - chrome://settings/passwords

# 4. Test phishing-resistance:
# - Đăng ký passkey trên localhost
# - Thử truy cập http://127.0.0.1 (khác origin) → passkey không hoạt động
# - Quan sát browser từ chối dùng key sai origin

Phần 2: RBAC, ABAC & Authorization Patterns

# 1. RBAC từ đầu với Node.js + Postgres
mkdir authz-lab && cd authz-lab
docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=pw postgres:16

# Tạo schema (xem section 2)
# Seed: admin, editor, viewer roles + permissions

# 2. Test IDOR
# - Implement /orders/:id KHÔNG check ownership
# - Curl với token user A, gọi GET /orders/<order_of_userB>
# - Quan sát leak
# - Sửa endpoint thêm check ownership, test lại

# 3. OPA (Rego) demo
brew install opa   # hoặc download binary
cat > policy.rego << 'EOF'
package authz
default allow = false

allow {
    input.user.role == "doctor"
    input.user.department == input.resource.department
}
EOF

cat > input.json << 'EOF'
{
  "user": { "role": "doctor", "department": "cardiology" },
  "resource": { "department": "cardiology" }
}
EOF

opa eval -d policy.rego -i input.json "data.authz.allow"
# → true

# Đổi resource.department = "neurology" → false

# 4. SpiceDB demo
docker run -p 50051:50051 authzed/spicedb serve --grpc-preshared-key "secret"
# Cài zed CLI, write schema và relationships (xem section 4)

# 5. Postgres Row-Level Security
psql -h localhost -U postgres -d test -c "
  CREATE TABLE notes (id SERIAL, user_id INT, content TEXT);
  ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
  CREATE POLICY user_notes ON notes USING (user_id = current_setting('app.user_id')::int);
"
# SET app.user_id = '1' → chỉ thấy notes của user 1

Tài liệu tham khảo


Bài tiếp theo →