Do not block the Node.js event loop
Node.js uses a single-thread event-driven architecture. Blocking operations prevent the event loop from processing other requests. Perform all blocking operations asynchronously using callbacks within promises or async/await. When operations depend on each other, place them in the same callback to prevent race conditions. For example, do not call `fs.unlinkSync()` after an async `fs.readFile()` without placing the unlink inside the callback.
Enable strict mode with "use strict" directive
Use `"use strict";` at the top of code to enable ES5 strict mode, which removes unsafe legacy features. Strict mode converts silent errors into thrown errors (e.g., `ReferenceError` for undefined variables) and allows JavaScript engine optimizations.
Use Object.defineProperty for secure property attributes
Object properties have three hidden attributes: `writable` (if false, property value cannot be changed), `enumerable` (if false, property cannot be used in for loops), and `configurable` (if false, property cannot be deleted). When assigning properties directly, all three default to true. Define properties securely using `Object.defineProperty()`. Use `Object.preventExtensions()` to prevent new properties from being added to objects.
REST web services definition and characteristics
RESTful web services are lightweight variants of web services based on the RESTful design pattern that utilize HTTP requests for machine-to-machine communication. They use HTTP methods (GET, POST, PUT, DELETE) as primary verbs for requested operations. Parameters can be specified non-standardly in URLs, headers, or as structured JSON/XML in request/response bodies. REST services typically employ custom authentication and session management using custom security tokens rather than traditional login sequences.
CORS disabled by default
Disable CORS headers if cross-domain calls are not supported or expected. Be as specific as possible and as general as necessary when setting the origins of cross-domain calls.
Management endpoint exposure restrictions
Avoid exposing management endpoints via Internet. If management endpoints must be accessible via the Internet, ensure users must use a strong authentication mechanism (e.g. multi-factor). Expose management endpoints via different HTTP ports or hosts, preferably on a different NIC and restricted subnet. Restrict access to these endpoints by firewall rules or access control lists.
IaaS responsibility and security considerations
Infrastructure as a Service (IaaS) requires developer maintenance of: authentication and authorization, data storage/access/management, certain networking tasks (ports, NACLs), and application software. Pros: Control over most components, high level of flexibility, easy transition from on-premises. Cons: Highest cost, more required maintenance, high level of complexity. Responsibility is held almost exclusively by the developer and must be secured as such. Everything from network access control, operating system vulnerabilities, application vulnerabilities, data access, and authentication/authorization must be considered when developing an IaaS security strategy.
DDoS protection options from cloud providers
Cloud service providers offer DDoS protection products ranging from simple to advanced. Simple DDoS protection can be implemented using WAFs with rate limits and route blocking rules. Advanced protection requires specific managed tools: AWS Shield (https://aws.amazon.com/shield/), GCP Cloud Armor Managed Protection (https://cloud.google.com/armor/docs/managed-protection-overview), Azure DDoS Protection (https://learn.microsoft.com/en-us/azure/ddos-protection/ddos-protection-overview). Decision to enable advanced DDoS protections should be based on risk and business criticality, considering mitigating factors and cost.
Developer security responsibilities in managed services
Even with managed services that update and secure underlying hardware, development teams remain responsible for: authentication and authorization, logging and monitoring, code security (OWASP Top 10), and third-party library patching. Refer to cloud service provider documentation to understand which aspects of security are the responsibility of each party based on the selected service.
SaaS responsibility and security considerations
Software as a Service (SaaS) model is an nearly complete product where end user controls: configuration/administration/code within product boundaries, some user access (designating administrators), and high-level connections to other products through permissions or integrations. Pros: Low maintenance, inexpensive, customer support/troubleshooting available. Cons: Restricted by provider constraints, minimal control, minimal insight/oversight. Developer only manages small set of security functions like some access controls, data trust/sharing relationships with integrations, and security implications of customizations. All other security layers are controlled by provider. Security fixes are out of developer's hands and could be handled in an untimely manner. When looking for SaaS solutions, consider asking for company's attestation records and proof of compliance to standards like ISO 27001.
High trust trust boundary configuration
High trust model trusts everything, with dangerous user input essentially handed directly to high criticality business components. Auth/identity and ephemeral IAM servers are not used. Pros: Efficient, simple. Cons: Insecure, potentially wasteful, high risk of compromise. Do not use this configuration unless there is no sensitive content to protect or efficiency is the only metric for success.
Some trust trust boundary configuration
Most applications use a 'some trust' configuration where security reasonably assigns trust to low risk components or processes and verifies only when necessary. API gateway checks auth/identity of user then passes request to compute instance without re-verification. Compute instance still assumes ephemeral identity to access storage as it works with untrusted user inputs. Pros: Secured based on risk, cost/efficiency derived from criticality. Cons: Known gaps in security.
VPC and subnet architecture for security separation
Virtual Private Clouds (VPC) and public/private subnets segment applications into distinct chunks for security. Public subnets house internet-facing components like front-end web applications, load balancers, routers, and bastions. Private subnets contain databases, data stores, backend servers, and anything too sensitive for direct internet access. A typical flow: external access through internet gateway/API gateway → load balancer or web server in public subnet → backend counterparts (database or backend server) in private subnet.
Serverless function security responsibilities by provider
Security responsibilities for serverless functions are defined by provider: AWS Lambda (https://docs.aws.amazon.com/lambda/latest/dg/lambda-security.html), GCP Cloud Functions (https://cloud.google.com/functions/docs/securing), Azure Functions (https://learn.microsoft.com/en-us/azure/architecture/serverless-quest/functions-app-security). Developers should refer to provider documentation to understand which aspects of security are their responsibility.
PaaS responsibility and security considerations
Platform as a Service (PaaS) requires developer control of: application authentication and authorization, application software, and external data storage. Pros: Easier to onboard and maintain, better scalability. Cons: Potential compatibility issues, offering-specific limitations. Manual security is less extensive compared to IaaS. Application-specific authentication and authorization must still be handled by developer along with any access to external data systems. Cloud service provider is responsible for securing containerized instances, operating systems, ephemeral file systems, and certain networking controls.
No trust trust boundary configuration
A no trust model means no component trusts any other component, regardless of criticality or threat level. Both API gateway and compute components call out to auth/identity server. Compute instance assumes ephemeral identity to access storage even after user is authenticated. Pros: High assurance of data integrity, defense in depth. Cons: Slow and inefficient, complicated, likely more expensive. Necessary for financial, military or critical infrastructure systems.
Trust boundaries definition and occurrence points
Trust boundaries are connections between components where a trust decision must be made, occurring where two components with potentially different trust levels meet. Trust boundaries typically occur in connections between cloud components and between applications and third-party elements like end users and other vendors.
Serverless security don'ts: no hardcoded secrets, assume clean runtime, no wildcard permissions, no sensitive data in /tmp or globals, no blind trust of event sources
Anti-patterns to avoid in serverless security: do not hardcode secrets in code or configurations; do not assume a clean runtime between invocations; do not grant wildcard IAM permissions; do not leave sensitive data in /tmp or global variables; do not trust event sources blindly.
AWS Lambda VPC Config for restrictive network access
Restrict Lambda network access using VpcConfig with SubnetIds (for example, subnet-123456) and SecurityGroupIds (for example, sg-restrict-outbound) to enforce controlled egress.
Serverless security do's: least privilege, input validation, vault secrets, network restriction, monitoring
Best practices for serverless security: enforce least privilege permissions per function; validate all event inputs; fetch secrets from vaults, not platform configuration; restrict network egress; and monitor invocations and logs.
Environment isolation for serverless: disable default network access, private subnets, function isolation, environment separation
Disable default network access unless required (for example, outbound internet access). Place functions in private subnets with controlled egress. Isolate sensitive functions (such as payment or authentication functions) from general-purpose ones. Separate production versus staging environments with strict boundaries.
Serverless key risks: over-permissions, unvalidated inputs, cold start leakage, function chaining, shared environments, hardcoded secrets, excessive network access
Serverless computing (FaaS) platforms introduce unique security risks compared to traditional architectures: over-permissioned functions with broad IAM roles or wildcard policies; unvalidated event inputs from API Gateway, S3, Pub/Sub, and IoT; cold start data leakage through persistent state or side-channel timing; function chaining abuse where a compromised function invokes others; shared environment risks including multi-tenant leakage and /tmp file reuse; hardcoded secrets in code or platform configuration; and excessive network access.
Build environment hardening techniques
Hardening techniques for build environments include: (1) Ensure build tools are located in appropriately segregated networks; (2) Use DLP and other tools and techniques to detect and prevent exfiltration; (3) Disable/remove unused services; (4) Use version control systems to manage and store pipeline configurations.
Secure development platform requirements
IDEs, development plugins, and similar development tools can become attack vectors through vulnerabilities. The development system should have endpoint security software installed and threat assessments performed against it. Only trusted, well-vetted software should be used, including core tools like IDEs and any plugins or extensions. These tools should be included in the organization's system inventory.
Build tool inventory requirements
An inventory of all build tools, including versions and any plugins, should be automatically collected and maintained. Vulnerability databases, vendor security advisories, and other sources must be monitored for any vulnerabilities related to identified build tools.
Four categories of Software Supply Chain threats
SSC threats are grouped into four categories: (1) Source code threats that violate integrity of source code through VCS exploits, malicious code introduction, or building from unauthorized branches; (2) Build environment threats that modify software artifacts without altering source code, including build cache poisoning or compromised build tool accounts; (3) Dependency related threats from consumption of direct and transitive dependencies, commonly vulnerable or compromised dependencies; (4) Deployment and runtime threats that exploit the deployment process or runtime environment, including compromised CI/CD accounts, misconfigurations, and compromised binaries.
Common SSC components requiring security
Components that require security in the Software Supply Chain include: IDEs and code editors, internally developed source code, third-party software libraries, version control systems (VCS), build tools (Maven, Rake, make, Grunt, etc.), CI/CD software (Jenkins, CircleCI, TeamCity, etc.), configuration management tools (Ansible, Puppet, Chef, etc.), and package management software and ecosystems (pip, npm, Composer, etc.).
SSC compromise propagation through consumer-supplier relationships
Many SSC threats can propagate across multiple entities due to the consumer-supplier relationships integral to an SSC. If a large-scale software supplier (proprietary or open-source) is compromised, many downstream consuming entities could also be impacted. Real-world examples include the 2020 SolarWinds incident and the 2021 Codecov incident.
VCS security configuration best practices
Compromise or abuse of source control systems is a significant SSC risk. Security features specific to VCS systems should be leveraged, such as protected branches and merge policies in git. General security best practices of strong access control and logging/monitoring apply. Tools like Legitify (open-source tool by Legit security) can detect misconfigurations in GitHub and GitLab and assist with best practice implementation. Secrets should never be committed to VCS.
Code signing enforcement for SSC
From the perspective of software consumers, only accepting digitally signed components and validating the signature before use is an important step in ensuring authenticity and that the component has not been tampered with. For those performing code signing, the code signing infrastructure must be thoroughly hardened to mitigate risk of compromise.
Version control for build scripts and CI/CD configuration
Configuration and scripts related to CI/CD pipelines should be stored in version control systems. This allows incorporation of reviews, merge rules, and similar controls into the config update process. Using VCS increases visibility into any changes, whether malicious or benign.
Private artifact repository benefits and requirements
Using a private artifact repository increases control over artifacts used within the SSC. Artifacts should be reviewed before being allowed in the private repository, and usage of these repositories must not be bypassable. Although private repositories can introduce extra maintenance or reduce agility, they are an important component of SSCS, especially for sensitive or critical applications.
Minimize user-controllable build parameters
Passing user-controllable parameters to a build process increases flexibility but also increases risk. If parameters can be modified by users to alter how a build is performed, attackers with sufficient permission can also modify parameters and potentially compromise the build process. Effort should be made to minimize or eliminate user-controllable build parameters.
Software Supply Chain definition per NIST
According to NIST, an entity's Software Supply Chain (SSC) is defined as a collection of steps that create, transform, and assess the quality and policy conformance of software artifacts.
Ephemeral and isolated build environments
Builds should be performed in isolated, temporary ('ephemeral') environments to prevent cache poisoning or easier injection of malicious code through reuse and sharing of build environments. This can be achieved using technologies such as VMs or containers for builds, with the environment immediately destroyed afterward.
Software provenance generation and verification
Provenance, defined in SLSA 1.0 as verifiable information about software artifacts describing where, when, and how something was produced, is important for SSCS. Provenance should be generated by the build platform (not local development systems), be very difficult for attackers to forge, and contain all details necessary to link the result back to the builder. SLSA 1.0 compliant provenance can be generated using builders such as FRSCA or Github Actions and verified using SLSA Verifier.
Regular backups and recovery plan
Implement regular backups of production database and critical files. Have a recovery plan in place to quickly restore the application in case of any issues.
Enforce HTTPS with SSL certificate
Ensure the SSL certificate is properly configured in the web server and configured to enforce HTTPS by redirecting HTTP traffic to HTTPS.
Disable debug mode in production
Ensure the application is not in debug mode in production. Set the APP_ENV environment variable to 'prod': APP_ENV=prod
File and directory permissions security
Ensure file and directory permissions are set correctly to minimize security risks.
Transport Layer Protection Cheat Sheet deprecated
The Transport Layer Protection Cheat Sheet has been deprecated. Readers should consult the Transport Layer Security Cheat Sheet instead for current guidance.
Four foundational questions of threat modeling
According to the Threat Modeling Manifesto, the threat modeling process should answer the following four questions: (1) What are we working on? (2) What can go wrong? (3) What are we going to do about it? (4) Did we do a good enough job? These four questions act as the foundation for the four major phases of threat modeling.
Threat modeling methodologies
Threat modeling methodologies include LINDDUN, PASTA, STRIDE, OCTAVE, and VAST. While STRIDE is popular and well-integrated into tools, different approaches may be used alongside or instead of STRIDE depending on organizational needs.
Mitigation strategies must be actionable
Mitigation strategies must be actionable, not hypothetical; they must be something that can actually be built into the system being developed. Although mitigation strategies must be tailored to the particular application, resources such as OWASP's ASVS and MITRE's CWE list can prove valuable when formulating these responses.
Cloud threat modeling considerations
Cloud-native systems introduce unique considerations for threat modeling: Cloud architecture components include virtual networks, IAM roles, managed services, and storage buckets; Shared responsibility requires understanding which security controls are managed by the provider vs. the customer; Dynamic environments include container orchestration, serverless functions, and ephemeral infrastructure; Compliance and data residency must ensure that workloads meet jurisdictional and privacy requirements. Cloud threat modeling frameworks such as AWS's Well-Architected Framework – Security Pillar can serve as references.
Threat ranking based on likelihood and impact
Threats should ideally be ranked based on the mathematical product of an identified threat's likelihood and its impact. A threat that is likely to occur and result in serious damage would be prioritized much higher than one that is unlikely to occur and would only have a moderate impact. However, likelihood and impact can be challenging to calculate, and some advocate for including the work to fix a problem in a single prioritization score.
Review and validation checklist for threat models
Areas to focus on when reviewing a threat model include: Does the DFD (or comparable) accurately reflect the system? Have all threats been identified? For each identified threat, has a response strategy been agreed upon? For identified threats for which mitigation is the desired response, have mitigation strategies been developed which reduce risk to an acceptable level? Has the threat model been formally documented? Are artifacts from the threat model process stored in such a way that it can be accessed by those with 'need to know'? Can the agreed upon mitigations be tested? Can success or failure of the requirements and recommendations from the threat model be measured?
DFD creation tools
Data flow diagrams can be created using dedicated threat modeling tools such as OWASP's Threat Dragon or Microsoft's Threat Modeling Tool, general purpose diagramming solutions such as draw.io, or as-code approaches like OWASP's pytm. Technical tools are not strictly necessary; whiteboarding may be sufficient in some instances, though it is preferable to have the DFDs in a form that can be easily stored, referenced, and updated as needed.
Data Flow Diagrams (DFDs) components
A Data Flow Diagram should provide a clear view of trust boundaries, data flows, data stores, processes, and the external entities which may interact with the system. These elements often represent possible attack points and provide crucial input for subsequent threat modeling steps.
Threat response strategies
Threat responses include the following options: Mitigate - take action to reduce the likelihood that the threat will materialize; Eliminate - simply remove the feature or component that is causing the threat; Transfer - shift responsibility to another entity such as the customer; Accept - do not mitigate, eliminate, or transfer the risk because none of the above options are acceptable given business requirements or constraints.
STRIDE threat categories and attributes
STRIDE is a mature threat modeling technique that groups threats into six categories: Spoofing (violates Authentication) - attacker impersonates a user by stealing an authentication token; Tampering (violates Integrity) - attacker performs unintended updates to a database; Repudiation (violates Accounting) - attacker manipulates logs to cover actions; Information Disclosure (violates Confidentiality) - attacker extracts data from a database containing user account info; Denial of Service (violates Availability) - attacker locks a legitimate user out of their account by performing many failed authentication attempts; Elevation of Privileges (violates Authorization) - attacker tampers with a JWT to change their role.
Four major phases of threat modeling
The threat modeling process comprises four major phases: (1) System Modeling (or application decomposition) to answer 'what are we building'; (2) Threat Identification and Ranking to answer 'what can go wrong'; (3) Response and Mitigations to answer 'what are we going to do about it'; (4) Review and Validation to answer 'did we do a good enough job'.
Threat modeling timing in SDLC
Threat modeling is ideally performed early in the SDLC, such as during the design phase. It is not performed once and abandoned, but should be maintained, updated, and refined alongside the system. Threat modeling should be integrated seamlessly into a team's normal SDLC process as a standard and necessary step, not an add-on.
Brainstorming for system modeling
Brainstorming is an effective technique for generating ideas and discovering the project's domain as an alternative to or complement to traditional Data Flow Diagrams. Benefits include increased team engagement, unification of knowledge and terminology, shared understanding of the domain, and quick identification of key processes and dependencies. Brainstorming is particularly useful when less technical individuals participate, as it eliminates barriers related to understanding DFD components. It fosters better communication, mutual understanding, allows every team member to contribute, increases responsibility and involvement, and enables the team to quickly identify key business processes and their interrelations.
Honesty and transparency regarding data protection limitations
If the web application cannot provide enough legal or political protections to the user, or if it cannot prevent misuse or disclosure of sensitive information such as logs, the truth must be told to users in a clear understandable form so users can make an educated choice about whether to use that service. If it does not violate the law, inform users if their information is being requested for removal or investigation by external entities. Honesty cultivates a culture of trust between a web application and its users, and allows users to weigh their options carefully.
Allow connections from anonymity networks for privacy protection
Web developers and network administrators must enable users to access services from behind anonymity networks such as Tor Project and I2P. Any policy made against anonymity networks must be carefully re-evaluated with respect to impact on people around the world. Developers should try to integrate or enable easy coupling of applications with anonymity networks, such as supporting SOCKS proxies or integration libraries like OnionKit for Android.
Web Services-Interoperability compliance requirement
Web services must be compliant with Web Services-Interoperability (WS-I) Basic Profile at minimum.
Zero Trust core principle: access to resources granted on per-session basis
Do not give permanent access to anything. Each time someone tries to access a resource, evaluate whether they should be allowed. Sessions should be short-lived and require re-authentication when they expire. Avoid set-it-and-forget-it access.
Zero Trust core principle: all communication is secured regardless of network location
Every connection must be encrypted and authenticated, whether between office and cloud, between internal systems, or from home to work. Network location does not determine trust level. Use strong encryption (TLS 1.3 or better) for everything.
Zero Trust core principle: all data sources and computing services are resources
Everything in your network is a resource that needs protection including servers, databases, cloud services, IoT devices, and user devices. Do not assume anything is safe just because it is internal to your network. Each resource needs its own security controls.