Secure Coding Practices & Tools 2
Secure Coding Practices & Tools 2
WEB APPLICATIONS
Ronak Hingonia
IIT Gandhinagar
I. INTRODUCTION
This document is intended for students and professional developers as a quick reference checklist for security
practices. It covers 11 categorized security aspects that, when implemented, can help prevent the corresponding
attacks. A before-and-after code example is then presented to demonstrate what secure code looks like in Ex-
press.js for easier understanding. Finally, a table lists the top open-source security tools every developer should
know.
III. DEFINITIONS
4. Firewall: A network security system that monitors and controls incoming and outgoing traffic.
5. Web Application: A software application that runs on a web server and is accessed via a web browser.
6. Vulnerability: A weakness in a system that can be exploited to cause harm.
7. Attack: An information security threat that involves an attempt to obtain, alter, destroy, remove, implant, or
reveal unauthorized information.
IV. ABBREVIATIONS
1
S CATEGORY DESCRIPTION IMPLEMENTATION/ PRACTICES PREVENTS FROM
No.
1 Authentication Verifies the identity of • Enforce multi-factor authentication • Unauthorized
users or systems to (MFA) or two-factor (2FA) access
ensure that only • Use secure hashing algorithms for • Identity spoofing
legitimate actors gain storing passwords • Brute force attacks
access to the application. • Integrate biometric or OTP
solutions
3 Data Control Prevents Excessive Data • Create Data Transfer Objects • Property Level
Exposure—a (DTOs) issues
vulnerability where more • Least privilege • Unauthorized
information than • Select only the fields that are safe disclosure of
necessary is sent to the and necessary for the client. sensitive data
client, inadvertently • A mapper library can be used
exposing sensitive data. instead of manually created DTOs.
This type of problem is
often framed as Broken
Object Property Level
Authorization (BOPLA)
4 Input Ensures that • Never trust the request • SQL Injection
Validation user-provided data • Validate type, length, format, and • XSS (cross-site
conforms to expected range scripting)
formats and rules before • Enforce Limits • Command
processing, preventing • Validate Strings (use regexp) injection.
malicious input from • Prefer allowed lists (deny by • Exceptions - might
being processed by the deafault) expose the tech
application. • Validate Parameters stack being used in
• Should add the same validations on back end which
frontend as well can be then used
by a malicious
actor.
5 File Upload File uploads can be a • Scan the file first for viruses • Path traversal
significant security risk if • Never trust the request vulnerabilities
not handled correctly. • Use upload & download limits • Malware Injection
Attackers can upload • Do not trust the content type • Performance issues
malicious files that can headers because that can be altered • Remote code
compromise the security as well. execution
of the entire application • Validate the extension and type of
file
• Set file name length limit
• Always check for file MetaData
directly
2
S CATEGORY DESCRIPTION IMPLEMENTATION/ PRACTICES PREVENTS FROM
No.
6 Cross Origin Manages how web • Configure CORS policies to allow • Unauthorized
Resource applications can request only trusted domains cross-origin data
Sharing resources from a different • Use proper HTTP headers (e.g., access
domain, ensuring secure Access-Control-Allow-Origin) • Data leakage to
cross-origin • Restrict methods (e.g., GET, untrusted domains
communication. POST) and headers allowed in
cross-origin requests
• Avoid using wildcards (*) for
sensitive endpoints
• Implement preflight request
handling for complex requests
• Validate and sanitize incoming
cross-origin requests
7 Session Ensures secure handling • Use strong & random session IDs - • Session hijacking
Management of user sessions to prevent long and complex. • Session fixation
unauthorized access or • Implement session expiration and • Unauthorized
session hijacking. timeout policies Data access
• Regenerate session IDs after login or
performs any sensitive actions.
• Use HTTPS for session cookies
8 Rate Limiting Controls the frequency of • Use algorithms like token bucket, • Denial-of-service
client requests within a leaky bucket, fixed window, or (DoS) attacks
defined time frame to sliding window counters to control • Brute-force
protect application the flow of requests. attempts
resources from abuse and • Use Distributed Rate Limiting to • API abuse
overload ensure consistent enforcement across • Resource
multiple servers exhaustion
• Implement at multiple layers (API
gateway, load balancer, or web
server level)
9 Secure Com- Ensures data transmitted • Use HTTPS with strong TLS • Man-in-the-middle
munication between the client and configurations attacks
server is encrypted and • Enforce HSTS (HTTP Strict • Data interception
protected from Transport Security) • Eavesdropping
interception. • Disable weak ciphers and protocols
3
Secure Coding Practices (JS)
This document outlines secure coding practices in JavaScript and Express by demonstrating
common security vulnerabilities and their corresponding solutions. Each example is presented
in a "before-and-after" format to highlight the transition from insecure to secure code.
• The rst code represents an insecure version with vulnerabilities, while the last code is its
secure, nalized version.
• Intermediate steps, if any, are shown with di erent themes are to illustrate the progression
toward secure implementation.
• Please go through the comments in code for explanation.
This visual approach is intended to make it easier to understand the security issues and how to
address them e ectively.
fi
fi
ff
ff
1. Authorization
Improvements:
✅ Passwords are no longer exposed
✅ Admin status is hidden, preventing privilege enumeration attacks
✅ Only necessary elds (id, name, email) are returned
✅ Prevents accidental data leaks in future updates
fi
3. Input Validation
Issues:
❌ No Input Validation – Allows any data type, length, or format.
❌ No Role Restriction – Any string can be used as a role.
❌ Potential DoS Attack Risk – Large or malformed inputs can overload the system.
Improvements
✅ Enums for Role Validation: Prevents arbitrary values.
✅ DTO for Input Validation: Enforces strict validation rules.
✅ Model for Data Structuring: Ensures consistency.
3.1 Parameters Validation
Issues:
❌ No Input Validation
❌ Denial of Service (DoS) Risk
❌ Excessive Data Exposure
Improvements
✅ Validated and Sanitized inputs with parameterized queries.
✅ Type Safety
3.2 SQL Injection
Injection Type-1:
Injection Type-2:
Final Code
4. File Uploads
● Security Issues in the Above Code
1. Path Traversal: A user can upload a le with a name like ../../evil.sh, escaping the
upload directory.
2. No File Type Validation: Accepts any le type, including malicious ones.
3. No File Size Limit: Attackers can upload huge les to crash the server.
4. Trusting Content-Type Header: Easily spoofed by attackers.
5. No File Name Length Restriction: Very long lenames can cause issues.
Final Code
fi
fi
fi
fi
5. CORS (cross origin resource sharing)
✅ Restricted Origins
✅ Limited Methods/Headers
✅ Authentication Check and Minimal Exposure
5 Open Source Security Tools
Developers Should Know
3 KICS (IaC • Includes 2000+ queries • Provides 200+ • Queries written in Growing
Scanner) supporting 18 build-in OPA (Rego) popularity &
frameworks remediation • Ability to support community of
• Nightly Build recipes new frameworks contributors
• Curated rules with unit • Runs everywhere
tests (IDE plugin, local,
CI)
5 ZAP (Runtime • Numerous features, • Runs everywhere • Extensible through • GitHub top
Scanner) detects the OWASP (docker, desktop extensions (100+ 1000 project
Top 10 risks app) available today) • Very popular &
• 250+ curated rules • Includes a headless • Plugins to extend large
mode to integrate the CLI community
in CI/CD pipeline • ZAP
Marketplace