Cấp độ: intermediate35 phútminMiễn phíFreeProduct DeveloperProduct Developer

Bảo mật ứng dụng cơ bảnBasic application security

Security checklist cho ứng dụng webA security checklist for web apps

Bạn sẽ học gìWhat you will learn

  • Nhận biết SQL injection và XSSRecognize SQL injection and XSS
  • Sanitize input và outputSanitize input and output
  • Dùng environment variables đúng cáchUse environment variables correctly

Bạn sẽ tạo gìWhat you will build

Security checklist cho ứng dụng webA security checklist for web apps

Nội dung bài họcLesson content

SQL Injection: lỗ hổng nguy hiểmSQL Injection: a dangerous vulnerability

SQL Injection là khi kẻ tấn công chèn SQL độc vào input. Ví dụ: form đăng nhập nhập username = "admin' OR '1'='1" → SQL trở thành SELECT * FROM users WHERE username='admin' OR '1'='1' → luôn đúng → đăng nhập được mà không cần mật khẩu. Phòng: dùng parameterized queries.SQL Injection is when an attacker injects malicious SQL into input. Example: login form with username = "admin' OR '1'='1" → SQL becomes SELECT * FROM users WHERE username='admin' OR '1'='1' → always true → logs in without a password. Prevention: use parameterized queries.

javascript
                      
                        // ❌ SAI: nối chuỗi SQL — dễ bị injection
const sql = `SELECT * FROM users WHERE username='${username}'`;
db.query(sql);

// ✅ ĐÚNG: parameterized query
const sql = 'SELECT * FROM users WHERE username = ?';
db.query(sql, [username]);  // ? được thay an toàn
                      
                    

XSS: Cross-Site ScriptingXSS: Cross-Site Scripting

XSS là khi kẻ tấn công chèn JavaScript độc vào trang web. Ví dụ: comment chứa <script>document.cookie</script> → khi người khác xem comment, script chạy → đánh cắp cookie. Phòng: escape HTML trước khi hiển thị, không dùng innerHTML với input chưa kiểm tra, dùng textContent.XSS is when an attacker injects malicious JavaScript into a web page. Example: a comment containing <script>document.cookie</script> → when others view the comment, the script runs → steals cookies. Prevention: escape HTML before display, don't use innerHTML with unchecked input, use textContent.

javascript
                      
                        // ❌ SAI: innerHTML với input — dễ bị XSS
commentDiv.innerHTML = userComment;

// ✅ ĐÚNG: textContent — không chạy script
commentDiv.textContent = userComment;

// Hoặc escape HTML
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}
                      
                    

CSRF: Cross-Site Request ForgeryCSRF: Cross-Site Request Forgery

CSRF là khi kẻ tấn công lừa user đã đăng nhập thực hiện hành động không chủ đích. Ví dụ: user đã đăng nhập bank, vào trang độc → trang độc gửi POST request chuyển tiền. Phòng: dùng CSRF token, kiểm tra Origin/Referer header, SameSite cookie.CSRF is when an attacker tricks a logged-in user into performing unintended actions. Example: user is logged into a bank, visits a malicious page → the page sends a POST request to transfer money. Prevention: use CSRF tokens, check Origin/Referer headers, SameSite cookies.

Best practices bảo mậtSecurity best practices

(1) Mật khẩu: hash bằng bcrypt/argon2, KHÔNG bao giờ lưu plaintext. (2) Secrets: dùng environment variables, không commit lên Git. (3) HTTPS: bắt buộc, chuyển hướng HTTP sang HTTPS. (4) Rate limit: chống brute force. (5) Validate input: không tin input từ client. (6) Keep dependencies updated.(1) Passwords: hash with bcrypt/argon2, NEVER store plaintext. (2) Secrets: use environment variables, don't commit to Git. (3) HTTPS: mandatory, redirect HTTP to HTTPS. (4) Rate limiting: prevent brute force. (5) Validate input: don't trust client input. (6) Keep dependencies updated.

Bài tập thực hànhHands-on exercises

1Sửa code SQL sau để dùng parameterized query: db.query(`SELECT * FROM users WHERE email='${email}'`)Fix the following SQL code to use parameterized queries: db.query(`SELECT * FROM users WHERE email='${email}'`)

Gợi ýHint

Dùng ? thay ${email}, truyền email trong mảng tham số.Use ? instead of ${email}, pass email in the parameter array.

Lời giảiSolution
javascript
                      
                        const sql = 'SELECT * FROM users WHERE email = ?';
db.query(sql, [email]);
                      
                    

2Viết hàm escapeHtml(text) để escape ký tự HTML đặc biệt, chống XSS.Write a function escapeHtml(text) to escape special HTML characters, preventing XSS.

Gợi ýHint

Thay & < > " ' bằng HTML entities. Hoặc dùng div.textContent trick.Replace & < > " ' with HTML entities. Or use the div.textContent trick.

Lời giảiSolution
javascript
                      
                        function escapeHtml(text) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return text.replace(/[&<>"']/g, m => map[m]);
}

// Hoặc đơn giản hơn:
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}
                      
                    

Kiểm traQuiz

Chọn đáp án đúng cho mỗi câu. Nhấn để xem giải thích.Choose the correct answer for each question. Click to see explanation.

Câu 1: SQL Injection là gì?Q1: What is SQL Injection?

Câu 2: Cách nào phòng XSS khi hiển thị input user?Q2: Which way prevents XSS when displaying user input?

Câu 3: Mật khẩu nên lưu thế nào trong database?Q3: How should passwords be stored in a database?

Câu 4: API key và secret nên đặt ở đâu?Q4: Where should API keys and secrets be placed?