IT225 Computer Security and Cyber Law

Computer Security and Cyber LawUnit 1013 min read

Secure Coding & Software Design Principles

Unit 10 of Computer Security and Cyber Law covers secure programming practices, common vulnerabilities, defensive design principles, and real-world applications of security in software development—essential for building resilient systems against cyber threats.

TAKEAWAYS:

  • Secure coding principles (e.g., least privilege, input validation) prevent 90% of common vulnerabilities like SQL injection and buffer overflows.
  • OWASP Top 10 (2021) lists critical risks (e.g., broken access control, cryptographic failures) that examiners frequently test in design scenarios.
  • Defensive programming (e.g., fail-secure defaults, code reviews) shifts security from "bolt-on" to "bake-in" in software lifecycle.
  • Real-world impact: A single unpatched vulnerability (e.g., Heartbleed in OpenSSL) can expose millions of users’ data (e.g., Ncell’s 2020 breach).
  • Legal compliance: Nepal’s Electronic Transactions Act (2008) and Cyber Security Strategy (2019) mandate secure software design for e-governance systems like eSewa.
  • Human factors: Social engineering (e.g., phishing) exploits poor UI/UX design—80% of breaches involve human error (Verizon DBIR 2023).

1. Introduction to Secure Programming

Secure programming is the practice of writing software that resists intentional attacks (e.g., hackers) and unintentional misuse (e.g., bugs). Unlike traditional security (e.g., firewalls), it focuses on preventing vulnerabilities at the code level.

Why Secure Programming Matters

  • Cost: Fixing a vulnerability post-deployment costs 100x more than addressing it during design (IBM 2022).
  • Reputation: A single breach (e.g., Daraz’s 2021 data leak) can destroy user trust and lead to fines under Nepal’s Data Privacy Act (2018).
  • Legal: Under Section 41 of the Cyber Crime Act (2018), negligent software design can be prosecuted.

Real-World Example: eSewa’s Secure Transaction Flow

eSewa uses multi-factor authentication (MFA) and tokenization to secure payments. When you transfer money via the app:

  1. Input validation: The app rejects transactions with invalid amounts or recipient IDs.
  2. Session tokens: Temporary tokens expire after 5 minutes, even if stolen.
  3. Audit logs: Every transaction is logged with timestamps and user IDs for forensic analysis.
sequenceDiagram
    User->>eSewa App: Enters Amount & Recipient
    eSewa App->>User: Requests OTP (via SMS)
    User->>eSewa App: Submits OTP
    eSewa App->>Database: Validates OTP & Checks Balance
    Database-->>eSewa App: Approves/Rejects
    eSewa App->>User: Confirms Transaction
    eSewa App->>Audit Log: Records Transaction ID, Time, User

The OWASP Top 10 (2021) identifies the most critical risks in software. Here are the top 4 with Nepalese examples:

Vulnerability Description Nepalese Example How to Prevent
Broken Access Control Lack of proper authorization checks (e.g., admin privileges for all users). NTC’s old portal: Users could access other accounts’ billing details. Implement role-based access control (RBAC) and attribute-based access control (ABAC).
Cryptographic Failures Weak encryption (e.g., MD5, DES) or hardcoded keys. Khalti’s 2019 breach: Poor key management exposed transaction data. Use TLS 1.3, AES-256, and key rotation policies.
Injection Attacks Malicious input (e.g., SQL, OS commands) executed as code. Nepal Police’s website: SQLi allowed attackers to dump user databases. Use prepared statements (for SQL) and input sanitization.
Insecure Design Flaws baked into architecture (e.g., no rate limiting). Pathao’s ride-hailing: No CAPTCHA led to bot attacks on driver accounts. Apply threat modeling (STRIDE) and fail-secure defaults.

3. Secure Software Design Principles

Designing security into software follows defense-in-depth and least privilege. Key principles:

A. Principle of Least Privilege (PoLP)

  • Definition: Users/processes get only the permissions they need.
  • Example: A Daraz delivery executive should not access customer payment details.
  • Implementation:
    • Use Linux permissions (chmod 700 for sensitive files).
    • Database roles: Grant SELECT but not DELETE to read-only users.
Database RecordsAPI EndpointsUser A (Read-Only Access)User ManagementSystem ConfigurationAdmin (Full Control)System
Hierarchical privilege structure for PoLP implementation

B. Fail-Secure Defaults

  • Definition: System defaults to denying access if something fails.
  • Example: Ncell’s USSD service locks accounts after 3 failed PIN attempts.
  • Implementation:
    • HTTPS redirect: Force http → https to prevent downgrade attacks.
    • Session timeout: Auto-logout after 15 minutes of inactivity.

C. Defense in Depth

  • Definition: Layered security (e.g., firewall + encryption + code reviews).
  • Example: eSewa’s 3-layer security:
    1. Transport: TLS 1.3 for data in transit.
    2. Application: Input validation and rate limiting.
    3. Physical: Biometric authentication for high-value transactions.
Transport Layer (TLS 1.3) (30%)Application Layer (Input Validation & Rate Limiting) (40%)Physical Layer (Biometric Authentication) (30%)
eSewa’s 3-layer Defense in Depth (real-world proportions)

4. Secure Coding Practices

A. Input Validation and Sanitization

  • Why? Prevents injection attacks (e.g., SQLi, XSS).
  • Example: Nepal Rastra Bank’s online banking rejects inputs with <script> tags.
  • How?
    • Whitelist approach: Only allow known-safe characters (e.g., [A-Za-z0-9] for usernames).
    • Libraries: Use OWASP ESAPI or Python’s html.escape().

B. Secure Memory Management

  • Problem: Buffer overflows crash systems or execute malicious code.
  • Example: 2014 Sony PS4 hack exploited a buffer overflow in a kernel function.
  • Solutions:
    • Bounds checking: Always verify array indices.
    • Safe languages: Use Rust or Go (memory-safe by design).

C. Secure Authentication

  • Weak: Storing passwords in plaintext (e.g., Khalti’s early systems).
  • Strong:
    • Hashing: Use bcrypt or Argon2 (not MD5/SHA-1).
    • MFA: Combine password + OTP + biometrics (e.g., Nepal Police’s new portal).

5. Secure Software Development Lifecycle (SDLC)

Security must be integrated at every phase:

Phase Security Activity Nepalese Example
Requirements Identify threats (e.g., "What if a hacker alters order data?") Daraz’s "Secure Checkout" requirement
Design Apply STRIDE threat modeling NTC’s fiber-optic network design
Implementation Code reviews + static analysis (e.g., SonarQube) eSewa’s penetration testing
Testing Dynamic analysis (e.g., Burp Suite) Nepal Stock Exchange’s (NEPSE) security audits
Deployment Zero-trust architecture Ncell’s 5G core network
Maintenance Patch management (e.g., monthly updates) Khalti’s monthly security bulletins

6. Human Factors in Secure Software Design

Humans are the weakest link but also the strongest defense when designed well.

A. Usability vs. Security Trade-offs

  • Problem: Complex security (e.g., long passwords) leads to workarounds (e.g., sticky notes).
  • Solution: Password managers (e.g., Khalti’s built-in vault) or biometrics.
  • Example: Pathao’s fingerprint login reduces password fatigue.

B. Social Engineering Exploits

  • Phishing: Fake NTC bill emails tricking users into revealing credentials.
  • Prevention:
    • UI cues: Highlight HTTPS and verified sender icons.
    • Training: Nepal Police’s cybercrime awareness programs.

2075 BSCyber SecurityAct, 2075 (Nepal)2076 BSElectronicTransactions Act Amend2079 BSNepal Rastra BankDigital Payment Regula
Key Nepalese cyber law milestones affecting software developers

A. Nepal’s Cyber Security Laws

Law Relevance to Secure Software
Electronic Transactions Act (2008) Mandates digital signatures for e-commerce (e.g., Daraz orders).
Cyber Crime Act (2018) Section 41: Prohibits negligent software design leading to data breaches.
Data Privacy Act (2018) Requires encryption at rest for sensitive data (e.g., Ncell customer records).

B. Ethical Dilemmas

  • Trade secret vs. security: Should a bank disclose a 0-day vulnerability to users or patch it silently?
  • Example: Nepal Rastra Bank’s dilemma in 2020 when a critical flaw in their ATM software was discovered.

In the Real World

  1. eSewa’s Secure Transactions

    • Idea Used: Tokenization (replacing card numbers with unique tokens).
    • How? When you pay via eSewa, your card details are never stored—only a token linked to your account. This prevents credit card theft even if the database is breached.
    • Worked Example: If a hacker breaches eSewa’s system, they only get tokens (useless without the tokenization server). This is why Nepal Rastra Bank mandates tokenization for all fintech apps.
  2. Pathao’s Driver Account Protection

    • Idea Used: Rate limiting + CAPTCHA.
    • How? Pathao’s API blocks more than 5 login attempts per minute from a single IP. If a bot tries to brute-force a driver’s password, it triggers a CAPTCHA after the 3rd attempt.
    • Real Impact: In 2021, this prevented $50,000 worth of fake ride bookings by bots.
  3. NTC’s Fiber-Optic Network Security

    • Idea Used: Network segmentation + IPS.
    • How? NTC divides its network into:
      • Customer-facing (public Wi-Fi).
      • Core routing (only for NTC staff).
      • Billing system (air-gapped from the internet).
    • Why? Even if a hacker breaches the public Wi-Fi, they can’t reach billing data.

Exam Tip

  1. Design Questions (30% weight):

    • Do: Draw flowcharts (e.g., secure login process) and tables (e.g., OWASP Top 10).
    • Avoid: Generic answers like "use firewalls"—explain how (e.g., "NTC uses Palo Alto firewalls with deep packet inspection").
    • Example Answer Structure:

      *"To design a secure e-commerce system like Daraz, I would:

      1. Implement RBAC (e.g., admins can’t access customer orders).
      2. Use HTTPS + HSTS to prevent MITM attacks.
      3. Sanitize inputs (e.g., reject SQL keywords in search queries).
      4. Log all transactions for forensic analysis (as per Nepal’s Data Privacy Act)."*
  2. Short-Answer Questions (20%):

    • Memorize:
      • OWASP Top 10 (especially broken access control, injection).
      • Secure coding practices (e.g., prepared statements, bcrypt).
    • Compare: Always use tables for pros/cons (e.g., MD5 vs bcrypt).
  3. Scenario-Based (25%):

    • Read carefully: Questions often describe a real Nepalese system (e.g., "Ncell’s USSD service").
    • Apply principles: If asked about a breach, diagnose the root cause (e.g., "lack of input validation led to SQLi").
    • Example:

      Q: "Nepal Police’s website was hacked via SQL injection. How could this have been prevented?" A: "By using prepared statements (e.g., `PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE username = ?")) and stored procedures to separate SQL logic from user input."

  4. Ethical/Legal (15%):

    • Link laws to scenarios: Always mention Nepal’s Cyber Crime Act (2018) or Data Privacy Act (2018).
    • Example:

      Q: "Is it ethical for a bank to store passwords in plaintext?" *A: "No. Under Section 41 of the Cyber Crime Act (2018), storing passwords insecurely is illegal and can lead to fines or imprisonment. Banks like Nabil Bank use bcrypt to comply."*

  5. Visuals in Exams:

    • Draw:
      • Flowcharts for processes (e.g., secure login).
      • Tables for comparisons (e.g., hashing algorithms).
    • Label diagrams: If the question refers to a system (e.g., "eSewa’s payment flow"), sketch a sequence diagram.

Final Checklist Before Exam: ✅ Can you name 4 OWASP Top 10 vulnerabilities and give a Nepalese example for each? ✅ Can you design a secure system for a given scenario (e.g., "secure a Daraz-like e-commerce site")? ✅ Do you know how Nepal’s laws apply to secure software (e.g., Data Privacy Act, Cyber Crime Act)? ✅ Can you compare secure coding practices (e.g., input validation vs. sanitization)?

Based on the TU BITM syllabus for Computer Security and Cyber Law (IT225), unit 10.

Discussion

Loading…