Error Handling and Logging
Best Practice | Description | CWE ID |
---|---|---|
Display Generic Error Messages | Error messages should not reveal details about the internal state of the application. For example, file system path and stack information should not be exposed to the user through error messages. | |
No Unhandled Exceptions | Given the languages and frameworks in use for web application development, never allow an unhandled exception to occur. Error handlers should be configured to handle unexpected errors and gracefully return controlled output to the user. | |
Suppress Framework Generated Errors | Your development framework or platform may generate default error messages. These should be suppressed or replaced with customized error messages as framework generated messages may reveal sensitive information to the user. | |
Log All Authentication Activities | Log all login attempts, token issuance (OAuth, JWT, etc.), refreshes, and failed authentications. Include relevant metadata such as client ID, IP address, and device info. | |
Log All Privilege Changes | Any activities or occasions where the user's privilege level changes should be logged. | |
Log Administrative Activities | Any administrative activities on the application or any of its components should be logged. | |
Log Access to Sensitive Data | Any access to sensitive data should be logged. This is particularly important for corporations that have to meet regulatory requirements like HIPAA, PCI, or SOX. | |
Do Not Log Inappropriate Data | While logging errors and auditing access is important, sensitive data should never be logged in an unencrypted form. For example, under HIPAA and PCI, it would be a violation to log sensitive data into the log itself unless the log is encrypted on the disk. Additionally, it can create a serious exposure point should the web application itself become compromised. | |
Active Security Monitoring | Consolidate system logs into a protected central repository (SIEM) for holistic visibility. Safeguard log authenticity through cryptographic validation including secure transmission and digital signatures. Deploy algorithm-driven surveillance systems that automatically analyze patterns across your infrastructure. Configure notification thresholds to alert security personnel about potential threats based on predefined risk signatures. Implement response protocols tied to detection systems for consistent handling of security incidents. | |
Store Logs Securely | Logs should be stored and maintained appropriately to avoid information loss or tampering by intruder. Log retention should also follow the retention policy set forth by the organization to meet regulatory requirements and provide enough information for forensic and incident response activities. |
Data Protection
Best Practice | Description | CWE ID |
---|---|---|
Use HTTPS Everywhere | Ideally, HTTPS should be used for your entire application. If you have to limit where it’s used, then HTTPS must be applied to any authentication pages as well as to all pages after the user is authenticated. If sensitive information (e.g., personal information) can be submitted before authentication, those features must also be sent over HTTPS. | |
Encrypt Sensitive Data at Rest | Sensitive data stored by the application should be encrypted using strong encryption algorithms to protect against unauthorized access. | |
Secure Data in Transit | All sensitive data transmitted over the network should be encrypted using protocols like TLS to prevent interception and tampering. | |
Implement Proper Key Management | Encryption keys should be managed securely, including regular rotation and storage in secure key management systems, to prevent unauthorized access. Apply least privilege principles to key access and consider key separation for different environments or data types. | |
Avoid Storing Sensitive Data Unless Necessary | Applications should minimize the storage of sensitive data. If storage is necessary, ensure that data is encrypted and access is restricted. | |
Field-Level Access Controls | Implement field-level access controls to filter API responses based on user permissions before data transmission. Define attribute-based policies (using role, group, data relationship) to control visibility and modification rights for specific fields. Ensure responses are automatically filtered server-side (e.g., via API gateway or middleware) to remove unauthorized fields, rather than relying on client-side hiding. For enhanced security, consider dynamically generating response schemas tailored to user entitlements. Rigorously test these controls against data leakage scenarios (like relationship traversal, bulk operations, aggregation) and maintain detailed audit logs for sensitive field access to meet compliance needs. |
Configuration and Operations
Best Practice | Description | CWE ID |
---|---|---|
Automate Secure Application Integration and Deployment | Automating the deployment of your application, using Continuous Integration and Continuous Deployment, helps to ensure that changes are made in a consistent, repeatable manner in all environments. Though the pipeline, integrate security validations such as SAST, SCA, DAST, secrets scanning, IaC and containers validations as integral steps of the development process. | |
Establish a Rigorous Change Management Process | A rigorous change management process must be maintained during change management operations. For example, new releases should only be deployed after process. | |
Define Security Requirements | Engage the business owner to define security requirements for the application. This includes items that range from the whitelist validation rules all the way to nonfunctional requirements like the performance of the login function. Defining these requirements up front ensures that security is baked into the system. | |
Conduct a Design Review and Threat Modeling | Integrating security into the design phase is crucial for saving time and cost. This requires conducting Threat Modeling—a systematic analysis performed with security professionals to understand the application's architecture, data flows, and trust boundaries. Threat modeling proactively identifies potential threats, attack vectors, and vulnerabilities based on the intended design. The insights gained from this process allow for the definition and integration of appropriate security controls and countermeasures directly into the application's architecture before development commences. | |
Perform Code Reviews | Security focused code reviews can be one of the most effective ways to find security bugs. Regularly review your code looking for common issues like SQL Injection and Cross-Site Scripting. | |
Perform Security Testing | Conduct security testing both during and after development to ensure the application meets security standards. Testing should also be conducted after major releases to ensure vulnerabilities did not get introduced during the update process. | |
Secure the CI/CD pipeline | Implement robust security controls throughout the entire CI/CD pipeline to prevent tampering and unauthorized code execution. Secure source code repositories, build processes, pipeline infrastructure, generated artifacts, and deployment stages. Enforce least privilege access controls for users and services interacting with the pipeline. Employ secure secrets management for credentials used during build and deployment. Ensure build and artifact integrity, protecting against malicious code injection or unauthorized modifications during automated software delivery. | |
Harden the Infrastructure | All components of infrastructure that support the application should be configured according to security best practices and hardening guidelines. In a typical web application this can include routers, firewalls, network switches, operating systems, web servers, application servers, databases, and application frameworks. Utilize API Gateways and WAF where appropriate to centralize enforcement of security controls like authentication, rate limiting, and logging for API endpoints. | |
Define an Incident Handling Plan | An incident handling plan should be drafted and tested on a regular basis. The contact list of people to involve in a security incident related to the application should be well defined and kept up to date. | |
Educate the Team on Security | Training helps define a common language that the team can use to improve the security of the application. Education should not be confined solely to software developers, testers, and architects. Anyone associated with the development process, such as business analysts and project managers, should all have periodic software security awareness training. | |
Applications and Middleware Should Run with Minimal Privileges | If an application becomes compromised it is important that the application itself and any middleware services be configured to run with minimal privileges. For instance, while the application layer or business layer needs the ability to read and write data to the underlying database, administrative credentials that grant access to other databases or tables should not be provided. | |
Rate limiting | Implement tiered rate limits varying by client type (anonymous, authenticated, premium) with stricter thresholds for write operations. Use progressive throttling as limits approach instead of immediate blocking. Return HTTP 429 responses with Retry-After headers and clear guidance on backoff strategies. Identify clients using multiple factors: API keys, IP addresses, and request signatures. Deploy token bucket or sliding window algorithms for sophisticated traffic management. In distributed systems, use centralized tracking to prevent limit bypass. Protect backend services with circuit breakers to prevent cascading failures. Configure automatic service degradation during high load to maintain core functionality while temporarily disabling non-essential operations. Implement rate limit bypass mechanisms for critical operations with proper approval workflows and audit logging. | |
Maintain API Inventory and Documentation | A comprehensive inventory of all internal and external APIs must be established and regularly updated. This inventory should include detailed documentation (using standards like OpenAPI/Swagger), clear ownership assignments, data classification levels, and security requirements for each API. Proper inventory management ensures complete security coverage, facilitates threat modeling, enables security testing, and prevents "shadow APIs" that may lack appropriate controls. Regular reviews of the inventory help maintain accurate security posture and ensure proper governance as the API landscape evolves. |
Authentication
Best Practice | Description | CWE ID |
---|---|---|
Don't Hardcode Credentials | Never allow credentials to be stored directly within the application code. While it can be convenient to test application code with hardcoded credentials during development this significantly increases risk and | |
Develop a Strong Password Reset System | Password reset systems are often the weakest link in an application. These systems are often based on the user answering personal questions to establish their identity and in turn reset the password. The system needs to be based on questions that are both hard to guess and brute force. Additionally, any password reset option must not reveal whether or not an account is valid, preventing username harvesting. | |
Implement a Strong Password Policy and Move Towards Passwordless Authentication | For password based authentication, password policy should be created and implemented so that passwords meet specific strength criteria. If the user base and application can support it, leverage the various forms of passwordless authentication such as FIDO2 based authentication or mobile application push based authenticators. | |
Support modern MFA authentications | Implement Multi-Factor Authentication (MFA) for user accounts, particularly those accessing sensitive data or administrative functions. Authentication should require verification using at least two independent factor types (e.g., knowledge, possession, inherence) to mitigate risks from single-factor credential compromise. Better security can be achieved by the support of modern, phishing-resistant authenticators, such as FIDO-based Passkeys, offering secure, passwordless authentication options leveraging device-bound credentials to protect against prevalent threats. | |
Implement Account Lockout against Brute Force and Credential Stuffing Attacks | Implement account lockout mechanisms to counter brute force attacks targeting specific user accounts during authentication and password resets. Lock accounts temporarily after several failed attempts, using generic messages like "Invalid credentials" to prevent username enumeration. Beyond simple lockouts, deploy advanced defenses against credential stuffing attacks, where attackers programmatically test breached username/password combinations across numerous accounts simultaneously. Monitor for suspicious patterns such as high volumes of failed authentication attempts from specific sources (IP addresses, subnets, user agents) across multiple accounts. Apply progressive security measures including strict rate limiting, CAPTCHAs, browser fingerprinting, and behavioral analysis to detect and block automated attack tools. Implement login attempt velocity checks to identify abnormal access patterns. Consider implementing IP reputation scoring and temporary IP blocks for suspicious sources. For critical systems, enforce Multi-Factor Authentication (MFA) as the most effective defense, as it neutralizes the threat of compromised passwords by requiring additional verification factors that attackers typically cannot obtain through credential breaches. | |
Don't Disclose Too Much Information in Error Messages | Messages for authentication errors must be clear and, at the same time, be written so that sensitive information about the system is not disclosed. For example, error messages which reveal that the userid is valid but that the corresponding password is incorrect confirms to an attacker that the account does exist on the system. | |
Store Database Credentials and API keys Securely | Modern web applications usually consist of multiple layers. The business logic tier (processing of information) often connects to the data tier (database). Connecting to the database, of course, requires authentication. The authentication credentials in the business logic tier must be stored in a centralized location that is locked down. The same applies to accessing APIs providing services to support your application. Scattering credentials throughout the source code is not acceptable. Some development frameworks provide a centralized secure location for storing credentials to the backend database. Secret management solutions that are cloud based or on-premise can be used to allow the application to acquire the credential at application launch or when needed, therefore securing the credentials and avoid storing them statically on disk within a server or a container image. |
Session Management
Best Practice | Description | CWE ID |
---|---|---|
Ensure That Session Identifiers Are Sufficiently Random | Session tokens must be generated by secure random functions and must be of a sufficient length so as to withstand analysis and prediction. | |
Regenerate Session Tokens | Session tokens should be regenerated when the user authenticates to the application and when the user privilege level changes. Additionally, should the encryption status change, the session token should always be regenerated. This helps to prevent attacks such as Session Fixation | |
Implement an Idle Session Timeout | When a user is not active, the application should automatically log the user out. Be aware that Ajax applications may make recurring calls to the application effectively resetting the timeout counter automatically. | |
Implement an Absolute Session Timeout | Users should be logged out after an extensive amount of time (e.g. 4-8 hours) has passed since they logged in. This helps mitigate the risk of an attacker using a hijacked session. | |
Destroy Sessions at Any Sign of Tampering | Unless the application requires multiple simultaneous sessions for a single user, implement features to detect session cloning attempts. Should any sign of session cloning be detected, the session should be destroyed, forcing the real user to re-authenticate. | |
Invalidate the Session after Logout | When the user logs out of the application the session and corresponding data on the server must be destroyed. This ensures that the session can not be accidentally revived. | |
Place a Logout Button on Every Page | The logout button or logout link should be easily accessible to the user on every page after they have authenticated. | |
Use Secure Cookie Attributes (HttpOnly, Secure and SameSite Flags) | The session cookie should be set with both the HttpOnly and the Secure flags. This ensures that the session id will not be accessible to client-side scripts and it will only be transmitted over HTTPS, respectively. In addition, the SameSite attribute should be set to with either lax or straight mode to reduce the risk of Cross Site Request Forgery. | |
Set the Cookie Domain and Path Correctly | The cookie domain and path scope should be set to the most restrictive settings for your application. Any wildcard domain scoped cookie must have a good justification for its existence. | |
Set the Cookie Expiration Time | The session cookie should have a reasonable expiration time. Non-expiring session cookies should be avoided. | |
API token handling - Token Generation | Implement industry standards like OAuth 2.0 or JWT for API authentication. Generate tokens using secure cryptographic algorithms (RS256/ES256) with a proper key management strategy. Structure your approach around short-lived access tokens (minutes/hours) paired with longer-lived refresh tokens. Include essential claims in tokens: subject, issuer, audience, expiration, and issuance time. Apply the principle of least privilege when defining token scopes. Assign appropriate lifetimes based on security requirements and user experience considerations. CWE-330 (Use of Insufficiently Random Values) | |
API token handling - Token Validation | Perform comprehensive server-side validation of all tokens. Verify cryptographic signatures using secure algorithms, never accepting 'none' as an algorithm. Validate all claims including expiration, issuer, audience, and permitted scopes. Implement refresh token rotation and reuse detection to prevent replay attacks. Maintain an effective token revocation mechanism through blocklists for JWTs or standard OAuth endpoints to immediately invalidate tokens upon logout or suspected compromise. | |
API token handling - Token storage and transmission | Transmit tokens exclusively via HTTP Authorization: Bearer headers rather than exposing them in URLs where they risk being intercepted or logged. For client-side storage in single-page applications and mobile applications, use secure options like HttpOnly cookies with appropriate flags (Secure, SameSite=Lax/Strict) or platform-specific secure storage solutions to mitigate XSS risks. | |
Cross-Origin Resource Sharing (CORS) Configuration | Securely configuring Cross-Origin Resource Sharing (CORS) is vital for controlling how APIs permit access from different web domains. Implement a strict policy using an explicit allowlist of trusted domains in the Access-Control-Allow-Origin header; avoid the wildcard (*), especially when handling sensitive data or credentials. Appropriately configure allowed HTTP methods via Access-Control-Allow-Methods and permitted request headers using Access-Control-Allow-Headers. If requests must include credentials (e.g., cookies), set Access-Control-Allow-Credentials to true and ensure Access-Control-Allow-Origin specifies an explicit domain, never a wildcard. Always validate the incoming Origin request header server-side before returning permissive CORS response headers. |
Input and Output Handling
Best Practie | Description | CWE ID |
---|---|---|
Conduct Contextual Output Encoding | All output functions must contextually encode data before sending it to the user. Depending on where the output will end up in the HTML page, the output must be encoded differently. For example, data placed in the URL context must be encoded differently than data placed in JavaScript context within the HTML page. | |
Prefer Allowlists over Blocklists | For each user input field, there should be serverside validation on the input content. Allowlisting input is the preferred approach. Only accept data that meets a certain criteria. For input that needs more flexibility, blocklisting can also be applied where known bad input patterns or characters are blocked. | |
Use Parameterized SQL Queries | SQL queries should be crafted with user content passed into a bind variable. Queries written this way are safe against SQL injection attacks. SQL queries should not be created dynamically using string concatenation. Similarly, the SQL query string used in a bound or parameterized query should never be dynamically built from user input. | |
Use Tokens and cookie parameter to Prevent Forged Requests | In order to prevent Cross-Site Request Forgery attacks, you must embed a random value that is not known to third parties into the HTML form. This CSRF protection token must be unique to each request. This prevents a forged CSRF request from being submitted because the attacker does not know the value of the token. In addition to the header, the same-site attribute of the cookie can also be configured to provide additional protection. | |
Set the Encoding for Your Application Content | For every page in your application set the encoding using HTTP headers or meta tags within HTML. This ensures that the encoding of the page is always defined and that browser will not have to determine the encoding on its own. Setting a consistent encoding, like UTF-8, for your application reduces the overall risk of issues like Cross-Site Scripting. | |
Validate Uploaded Files | When accepting file uploads from the user make sure to validate the size of the file, the file type, and the file contents as well as ensuring that it is not possible to override the destination path for the file. | |
Use the Nosniff Header for Uploaded Content | When hosting user uploaded content which can be viewed by other users, use the X-Content-Type-Options: nosniff header so that browsers do not try to guess the data type. Sometimes the browser can be tricked into displaying the data type incorrectly (e.g. showing a GIF file as HTML). Always let the server or application determine the data type. | |
Validate the Source of Input | The source of the input must be validated. For example, if input is expected from a POST request do not accept the input variable from a GET request. | |
Use Secure HTTP Response Headers | Use the X-Frame-Options header to prevent content from being loaded by a foreign site in a frame. This mitigates Clickjacking attacks. For older browsers that do not support this header add framebusting Javascript code to mitigate Clickjacking (although this method is not foolproof and can be circumvented). Example: Flash camera and mic hack | |
Deserialize Untrusted Data with Proper Controls | When handling serialized data from untrusted source (or passing through untrusted paths), proper controls have to be in place to prevent attacker from abusing the automatic data structure rebuilding capability within the programming language. Each programming platform has its own mitigation strategy which range from using alternative data interchange format such as JSON to restricting the types of objects that can be deserialized. Refer to OWASP Deserialization Cheat Sheet for some great defense information. | |
Mass Assignment Protection | Implement safeguards against overposting/mass assignment attacks where attackers can modify unexpected properties. | |
HTML Sanitization for Rich Content | Especially for front end data integration between origins, apply HTML sanitization libraries for user-generated content that needs to contain markup |
Access Control
Best Practice | Description | CWE ID |
---|---|---|
Apply Access Controls Checks Consistently | Always apply the principle of complete mediation, forcing all requests through a common security "gate keeper". This ensures that access control checks are triggered whether or not the user is authenticated. | |
Apply the Principle of Least Privilege | Make use of a Mandatory Access Control system. All access decisions will be based on the principle of least privilege. If not explicitly allowed then access should be denied. Additionally, after an account is created, rights must be specifically added to that account to grant access to resources. | |
Don't Use Direct Object References for Access Control Checks | Do not allow direct references to files or parameters that can be manipulated to grant excessive access. Access control decisions must be based on the authenticated user identity and trusted server side information. | |
Don't Use Unvalidated Forwards or Redirects | An unvalidated forward can allow an attacker to access private content without authentication. Unvalidated redirects allow an attacker to lure victims into visiting malicious sites. Prevent these from occurring by conducting the appropriate access controls checks before sending the user to the given location. | |
Use Secrets Management solutions to protect credentials and API keys | Secure generation, storage, rotation, and revocation of API keys used for client application authentication/authorization. Secrets Management solutions provide a secure, centralized vault to store, manage, and tightly control access to these credentials, often incorporating features like automatic rotation, fine-grained access policies, and detailed audit trails, thereby significantly reducing the attack surface and improving the overall security posture of the application infrastructure. | |
Apply Correct Authorization Checks | Verify that authenticated users have appropriate permissions for each resource and function they attempt to access. Checks must apply not only to resources/pages but also to specific actions/functionsand individual data records/fields, ensuring users only access their own data. Example: First American Financial Breach |
Nine Key Cloud Security Concentrations & SWAT Checklist
Download your free copy of this poster here.
SWAT Checklist Contributors
David Deatherage, Silicon Valley Bank