Table of Contents

    Common Security Mistakes

    Programming Mastery

    Common Security Mistakes

    Learn the most common security mistakes beginners make in software development and how to avoid them using secure programming practices.

    Introduction

    Common security mistakes are repeated coding, design, configuration, and testing errors that can make software unsafe.

    Many security problems do not happen because developers intentionally write unsafe code. They often happen because developers forget to validate input, expose sensitive data, trust the frontend too much, use weak password handling, skip authorization checks, or ignore secure configuration.

    Security mistakes are usually easier to prevent during development than to fix after a breach or production issue.

    In this lesson, students will learn the most common beginner-friendly security mistakes and the safer habits that professional developers should follow.

    Easy Real-Life Example

    Security Mistakes as Leaving Doors Open

    Imagine building a beautiful house but forgetting to lock the doors, hiding the main key under the mat, leaving windows open, and showing the locker password on a wall. The house may look complete, but it is not secure.

    House Mistakes:
    - Leaving doors unlocked
    - Keeping keys in visible places
    - Not checking visitors
    - Showing private information publicly
    
    Software Mistakes:
    - Not validating input
    - Hardcoding passwords
    - Missing authorization checks
    - Showing internal errors to users

    Secure programming means checking these weak points before attackers or users accidentally misuse them.

    What are Common Security Mistakes?

    Common security mistakes are repeated unsafe practices that make applications easier to attack, misuse, or break.

    These mistakes can appear in input handling, output display, authentication, authorization, password storage, logging, file uploads, dependencies, configuration, APIs, databases, and code repositories.

    Key Idea: Secure programming is not only about writing features. It is also about preventing unsafe behavior.

    Why Students Should Learn These Mistakes

    Beginners often learn how to make code work, but professional software also needs to be safe, reliable, and maintainable.

    Learning Common Mistakes Helps Students To

    • Write safer programs from the beginning.
    • Understand why secure coding practices matter.
    • Recognize risky code during code review.
    • Avoid exposing sensitive data.
    • Build better authentication and authorization logic.
    • Protect applications from common web security risks.
    • Think like a defensive developer.
    • Improve software quality and user trust.

    Mistake 1: Trusting User Input

    One of the biggest security mistakes is trusting input directly.

    User input can come from forms, URLs, cookies, headers, files, APIs, or external systems. A secure program should treat all external input as untrusted until it is validated.

    Bad Practice

    INPUT marks
    
    IF marks >= 40 THEN
        DISPLAY "Pass"
    ELSE
        DISPLAY "Fail"
    END IF

    This code does not check whether marks is a number or whether it is within a valid range.

    Better Practice

    INPUT marks
    
    IF marks is not a number THEN
        DISPLAY "Invalid marks"
        STOP
    END IF
    
    IF marks < 0 OR marks > 100 THEN
        DISPLAY "Marks must be between 0 and 100"
        STOP
    END IF
    
    IF marks >= 40 THEN
        DISPLAY "Pass"
    ELSE
        DISPLAY "Fail"
    END IF
    Secure Habit: Validate type, length, range, format, and allowed values before processing input.

    Mistake 2: Validating Only on the Client Side

    Client-side validation is useful for user experience, but it is not enough for security.

    A user can bypass browser validation and send requests directly to the backend.

    Unsafe Thinking

    • The form already validates the input.
    • The browser will stop invalid values.
    • The user cannot modify the request.

    Secure Thinking

    • Validate on the frontend for convenience.
    • Validate on the backend for security.
    • Reject invalid input before processing.

    Mistake 3: Missing Output Encoding

    Another common mistake is displaying user input directly on a page without encoding it.

    If special characters are not encoded, the browser may interpret user input as markup or script instead of plain text.

    Bad Practice

    INPUT comment
    
    DISPLAY comment inside web page

    Better Practice

    INPUT comment
    
    safeComment = HTML_ENCODE(comment)
    
    DISPLAY safeComment inside web page
    Secure Habit: Validate input before accepting it and encode output before displaying it.

    Mistake 4: Storing Passwords as Plain Text

    Passwords should never be stored in readable form.

    If a database is exposed and passwords are stored as plain text, user accounts become highly vulnerable.

    Bad Practice

    SAVE email
    SAVE password

    Better Practice

    passwordHash = SECURE_PASSWORD_HASH(password)
    
    SAVE email
    SAVE passwordHash

    Secure applications store password hashes, not original passwords.

    Mistake 5: Hardcoding Secrets in Source Code

    Hardcoding secrets means placing passwords, API keys, tokens, database credentials, or private keys directly inside source code.

    This is unsafe because source code may be shared, copied, logged, committed, reviewed, or leaked.

    Bad Practice

    databasePassword = "AdminPassword123"
    apiKey = "my-secret-api-key"

    Better Practice

    databasePassword = GET_SECRET("DATABASE_PASSWORD")
    apiKey = GET_SECRET("PAYMENT_API_KEY")
    Secure Habit: Store secrets in secure configuration or secrets management systems, not in source code.

    Mistake 6: Weak Authentication

    Authentication verifies user identity. Weak authentication can allow unauthorized users to access accounts.

    Weak Authentication Examples

    • Using hardcoded usernames and passwords.
    • Allowing unlimited login attempts.
    • Using weak password handling.
    • Showing whether the username or password was wrong.
    • Not using MFA for sensitive accounts.
    • Not expiring sessions.

    Unsafe Error Message

    "User exists, but password is wrong."

    Safer Error Message

    "Invalid username or password."

    Mistake 7: Missing Authorization Checks

    Authentication proves identity, but authorization checks permission.

    A common mistake is assuming that a logged-in user can access everything.

    Bad Practice

    FUNCTION deleteStudent(studentId)
        DELETE student record
        RETURN "Student deleted"
    END FUNCTION

    Better Practice

    FUNCTION deleteStudent(currentUser, studentId)
        IF currentUser.role is not "Admin" THEN
            RETURN "Access denied"
        END IF
    
        DELETE student record
        RETURN "Student deleted"
    END FUNCTION
    Secure Habit: Check authorization before every protected action.

    Mistake 8: Giving Too Much Access

    Giving users or services more permissions than required increases risk.

    This violates the principle of least privilege.

    Unsafe Access Least Privilege Access
    Every user has admin access. Only admins have admin access.
    Application database user can delete everything. Application database user has only required permissions.
    All staff can view all records. Users view only records needed for their role.

    Mistake 9: Showing Detailed System Errors to Users

    Detailed technical error messages can reveal internal paths, database names, stack traces, server details, or logic clues.

    Bad Practice

    Database error at /internal/server/config/db_connection_line_42

    Better Practice

    Something went wrong while processing your request.
    Please try again later.

    Detailed errors should be logged securely for developers, while users should receive safe and friendly messages.

    Mistake 10: Logging Sensitive Data

    Logs are useful for debugging and monitoring, but logs should not contain sensitive data.

    Do Not Log

    • Passwords.
    • Full tokens.
    • Secret keys.
    • Payment details.
    • Private personal information.
    • Session identifiers in unsafe formats.

    Safer Logging

    • Log event type.
    • Log safe user identifier where appropriate.
    • Log access denied events.
    • Log repeated failed login attempts.
    • Log internal error reference ID.
    • Mask sensitive values.

    Mistake 11: Using Outdated Dependencies

    Many applications depend on libraries, packages, frameworks, plugins, and third-party components.

    Using outdated components with known vulnerabilities can make an application unsafe.

    Safer dependency habits:
    - Use trusted packages.
    - Keep dependencies updated.
    - Remove unused libraries.
    - Review dependency vulnerabilities.
    - Use dependency scanning tools when available.

    Mistake 12: Unsafe File Uploads

    File upload features are risky if the application accepts any file without validation.

    Safer File Upload Checks

    • Allow only required file types.
    • Check file size limits.
    • Validate file names safely.
    • Do not trust the original file name.
    • Store files in controlled locations.
    • Scan files where required.
    • Do not execute uploaded files as code.

    Mistake 13: Security Misconfiguration

    Security misconfiguration happens when systems, servers, frameworks, databases, APIs, cloud services, or applications are configured unsafely.

    Configuration Mistakes

    • Leaving default accounts enabled.
    • Using default passwords.
    • Leaving debug mode enabled in production.
    • Exposing unnecessary services.
    • Missing security headers.
    • Using overly broad permissions.
    • Leaving repositories or storage publicly accessible.

    Mistake 14: Weak Cryptographic Practices

    Cryptography is difficult to implement correctly. Beginners should avoid creating custom encryption or password hashing methods.

    Bad Practice

    Create a custom password scrambling method.

    Better Practice

    Use trusted security libraries and approved algorithms.

    Developers should rely on tested libraries and organization-approved security standards for cryptographic operations.

    Mistake 15: Skipping Code Review and Security Testing

    Security issues are easier to catch when developers review code, write tests, and use security scanning tools.

    Risky Behavior

    • Merge code without review.
    • Skip unit tests.
    • Skip security-focused questions.
    • Ignore dependency warnings.
    • Assume code is safe because it works.

    Better Behavior

    • Use peer review.
    • Run tests before merging.
    • Ask security-focused review questions.
    • Use automated checks where available.
    • Fix high-risk issues early.

    Mistake 16: Blindly Trusting AI-Generated Code

    AI tools can help generate code quickly, but generated code must still be reviewed and tested.

    A developer is responsible for checking whether generated code is correct, secure, maintainable, and aligned with project standards.

    Safer AI Code Usage

    • Review generated code carefully.
    • Check input validation.
    • Check authentication and authorization logic.
    • Check for hardcoded secrets.
    • Run tests and security scans.
    • Do not copy code blindly into production.

    Common Security Mistakes Summary Table

    Mistake Risk Safer Habit
    Trusting user input Invalid data, injection risks, crashes. Validate all untrusted input.
    Missing output encoding XSS and unsafe display behavior. Use context-specific output encoding.
    Plain-text passwords Password exposure if storage is compromised. Use secure password hashing.
    Hardcoded secrets Credential leakage. Use secure secrets management.
    Weak authorization Unauthorized actions and data access. Check permissions on the backend.
    Detailed public errors Internal information exposure. Show safe user messages and log details internally.
    Sensitive logging Secrets exposed through logs. Mask or avoid sensitive values.
    Outdated dependencies Known vulnerabilities remain exploitable. Update and scan dependencies.

    Real-World Example: E-Commerce Security Mistakes

    Consider an e-commerce checkout system.

    Mistake Example Fix
    No input validation User enters negative quantity. Reject quantity less than or equal to zero.
    No authorization User views another customer’s order. Check order ownership before displaying.
    Sensitive logging Payment token appears in logs. Never log payment tokens.
    Unsafe error message Database details shown to customer. Show generic error and log internal details securely.
    Hardcoded secret Payment API key inside source code. Use secure configuration or secret manager.

    Student-Friendly Example: School Portal Security Mistakes

    Common mistakes in a school portal:
    
    1. Student marks are accepted without checking 0 to 100.
    2. Student can view another student's report by changing studentId.
    3. Teacher password is stored directly in database.
    4. Admin password is written inside source code.
    5. Error page shows database connection details.
    6. Uploaded student documents are accepted without file checks.
    7. Logs contain passwords during debugging.

    Safer Version

    Safer school portal habits:
    
    1. Validate marks before saving.
    2. Check ownership and role before showing reports.
    3. Store password hashes, not passwords.
    4. Keep secrets outside source code.
    5. Show safe error messages to users.
    6. Validate uploaded file type and size.
    7. Never log passwords or secret values.

    Security Mistake Prevention Checklist

    Before Finalizing Code, Ask:

    • Did I validate all untrusted input?
    • Did I encode output before displaying user data?
    • Did I avoid storing passwords as plain text?
    • Did I keep secrets out of source code?
    • Did I check authentication where required?
    • Did I check authorization before protected actions?
    • Did I apply least privilege?
    • Did I avoid logging sensitive data?
    • Did I use safe error messages?
    • Did I validate uploaded files?
    • Did I update dependencies?
    • Did I review security-related code?
    • Did I test invalid, boundary, and denied-access cases?

    Best Practices to Avoid Common Security Mistakes

    Recommended Practices

    • Treat all external input as untrusted.
    • Validate input on trusted backend logic.
    • Use allowlist validation where possible.
    • Use context-specific output encoding.
    • Use secure password hashing and unique salts.
    • Never hardcode passwords, API keys, or tokens.
    • Use secure authentication and session handling.
    • Enforce authorization on the server side.
    • Apply least privilege to users and services.
    • Use safe and generic user-facing error messages.
    • Do not log sensitive data.
    • Keep dependencies and frameworks updated.
    • Use code reviews and security testing.
    • Use trusted libraries for cryptography.
    • Document security decisions clearly.

    Prerequisites Before Learning Common Security Mistakes

    Students should understand the following topics before learning this concept deeply:

    Required Knowledge

    • Basic programming syntax.
    • Variables and data types.
    • Conditional statements.
    • Functions or methods.
    • Input validation.
    • Output encoding.
    • Authentication basics.
    • Authorization basics.
    • Password handling basics.
    • Testing and code review basics.

    Trace Table Example: Secure Access Check

    FUNCTION updateMarks(currentUser, marks)
        IF currentUser is not authenticated THEN
            RETURN "Please login"
        END IF
    
        IF currentUser.role is not "Teacher" AND currentUser.role is not "Admin" THEN
            RETURN "Access denied"
        END IF
    
        IF marks is not a number OR marks < 0 OR marks > 100 THEN
            RETURN "Invalid marks"
        END IF
    
        SAVE marks
    
        RETURN "Marks updated"
    END FUNCTION
    Test Case Scenario Expected Result Security Concept
    TC_001 Unauthenticated user Please login Authentication check
    TC_002 Student tries to update marks Access denied Authorization check
    TC_003 Teacher enters marks 105 Invalid marks Input validation
    TC_004 Teacher enters marks 85 Marks updated Valid secure flow

    Practice Activity: Identify Security Mistakes

    Review the following pseudocode and identify security mistakes.

    databasePassword = "Admin123"
    
    FUNCTION login(email, password)
        LOG "Login password is " + password
    
        IF email == "admin@example.com" AND password == "admin123" THEN
            RETURN "Login successful"
        ELSE
            RETURN "Wrong password"
        END IF
    END FUNCTION
    
    FUNCTION deleteUser(userId)
        DELETE user by userId
        RETURN "Deleted"
    END FUNCTION

    Expected Issues

    Security mistakes:
    1. Database password is hardcoded.
    2. Password is logged.
    3. Admin credentials are hardcoded.
    4. Login error message is unsafe.
    5. Password handling is weak.
    6. deleteUser has no authorization check.
    7. No input validation is shown.

    Improved Concept

    databasePassword = GET_SECRET("DATABASE_PASSWORD")
    
    FUNCTION login(email, password)
        IF email is empty OR password is empty THEN
            RETURN "Invalid username or password"
        END IF
    
        userAccount = FIND account by email
    
        IF userAccount does not exist THEN
            RETURN "Invalid username or password"
        END IF
    
        IF VERIFY_PASSWORD(password, userAccount.passwordHash) is false THEN
            RETURN "Invalid username or password"
        END IF
    
        CREATE secure session
    
        RETURN "Login successful"
    END FUNCTION
    
    FUNCTION deleteUser(currentUser, userId)
        IF currentUser.role is not "Admin" THEN
            RETURN "Access denied"
        END IF
    
        DELETE user by userId
    
        RETURN "Deleted"
    END FUNCTION

    Practice Test Cases

    Test Case Scenario Expected Output
    TC_001 Empty email during login Invalid username or password
    TC_002 Wrong password Invalid username or password
    TC_003 Valid login Login successful
    TC_004 Normal user tries to delete another user Access denied
    TC_005 Admin deletes user Deleted

    Mini Quiz

    1

    What is a common security mistake?

    A common security mistake is an unsafe coding or configuration habit that can expose an application to security risks.

    2

    Why should user input not be trusted directly?

    User input may be incorrect, malformed, unexpected, or intentionally harmful, so it should be validated before use.

    3

    Why are hardcoded secrets dangerous?

    Hardcoded secrets may be exposed through source code, repositories, builds, logs, or accidental sharing.

    4

    What is the mistake in assuming login means full access?

    Login only proves identity. Authorization is still needed to check what the user is allowed to do.

    5

    Why should detailed errors not be shown to users?

    Detailed errors may reveal internal system information that can help attackers understand the application.

    Interview Questions on Common Security Mistakes

    1

    Name five common security mistakes in programming.

    Common mistakes include missing input validation, missing output encoding, plain-text password storage, hardcoded secrets, and missing authorization checks.

    2

    Why is client-side validation not enough?

    Client-side validation can be bypassed, so validation must also happen on trusted backend logic.

    3

    What is least privilege?

    Least privilege means giving users and services only the minimum permissions required to perform their tasks.

    4

    How can developers avoid exposing secrets?

    Developers can avoid exposing secrets by keeping credentials out of source code and using secure configuration or secret management.

    5

    Why should security be reviewed during code review?

    Security-focused code review helps catch issues such as missing validation, weak authorization, hardcoded secrets, unsafe logging, and poor error handling before release.

    Quick Summary

    Concept Meaning
    Common Security Mistakes Repeated unsafe coding, configuration, or design habits.
    Input Validation Mistake Accepting untrusted data without checking it.
    Output Encoding Mistake Displaying untrusted data without encoding it.
    Password Mistake Storing or logging passwords unsafely.
    Hardcoded Secret A password, token, or key written directly in source code.
    Authorization Mistake Allowing actions without checking permissions.
    Logging Mistake Writing sensitive information into logs.
    Configuration Mistake Using unsafe default or production settings.

    Final Takeaway

    Common security mistakes are avoidable when developers follow secure programming habits. Students should remember to validate input, encode output, protect passwords, avoid hardcoded secrets, enforce authorization, apply least privilege, use safe error messages, avoid sensitive logging, update dependencies, validate file uploads, and review code carefully. Secure programming is not a separate activity at the end of development; it is a continuous habit throughout design, coding, testing, review, and deployment.