Taking Notes on the OWASP Cheat Sheets
I read about Account Lockout in the OWASP cheat sheets while reading about common cybersecurity attacks. I saw good tips and things to consider in that cheat sheet, so I am going to read all the cheat sheets and take notes on them.
References
About
The OWASP Cheat Sheet Series was cretaed to provide a concise collection of high value information on specific application security topics. These cheat sheets were created by various application security professionals who have expertise in their specific topics.
- I will only be reading about the topics that I think affect me and what I see myself doing in the future.
- Some of the topics in the cheat sheet series, e.g. Java Security and Lavarel, go over topics that I do not use now and do not plan to use in the future, so I will not be going over them.
Ajax Security
- Use
innerText
instead ofinnerHTML
- Data should be properly encoded before inserting it into HTML
- Don't rely on client side logic for security
- Use CSRF protection
- Always return JSON with an object on the outside - you don't want to return an array of JSON objects
Exploitable:
[{"object": "inside an array"}]
Not Exploitable:
{"result": [{"object": "inside an array"}]}
Abuse Case
The objective of this cheat sheet is to provide an explanation of what an Abuse Case is, why abuse cases are important when considering the security of an application, and finally to provide a proposal for a pragmatic approach to building a list of abuse cases and tracking them for every feature planned for implementation as part of an application.
- Abuse Case - a way to use a feature that was not expected by the implementer, allowing an attack to influence the feature or outcome of use of the feature based on the attacker action (or input).
Attack Surface Analysis
- The focus here is on protecting an application from external attack - it does not take into account attacks on the users or operators of the system (e.g., malware or social engineering attacks), and there is less focus on insider threats, although the principles remain the same.
Attack surface analysis helps you to:
- identify what functions and what parts of the system you need to review/test for security vulnerabilities
- identify high risk area of code that require defense in depth protection - what parts of the system you need to defend
- identify when you have changed the attack surface and need to do some kind of threat assessment
The Atack surface of an application is:
- The sum of all paths for data/commands into and out of the application
- the code that protects these paths
- all valuable data in the application
- the code that protects these data
Authentication
- Authentication (AuthN) is the process of verifying that an individual, entity, or website is who or what it claims to be by determining the validity of one or more authenticators (like passwords or fingerprints) that are used to back up this claim
- Digital Identity is the unique representation of a subject engaged in an online transaction. A digital identity is always unique in the context of a digital service but does not necessarily need to be traceable back to a specific real-life subject
- Identity Proofing establishes that a subject is actually who they claim to be. This concept is related to KYC concepts and it aims to bind a digital identity with a real person
- Session Management is a process by which a server maintains the state of an entity interacting with it. This is required for a server to remember how to react to subsequent requests throughout a transaction. Sessions are maintained on the server by a session identifier which can be passed back and forth between the client and the server when transmitting and receiving requests. Sessions should be unique per user and computationally very difficult to predict.
- Usernames and User IDs:
- User IDs should be randomly generated - don't use sequential User IDs.
- Users should be permitted to use their email address as a username, provided the email is verified during signup. They should also have a username separate from their email address.
- Passwords:
- All characters should be allowed in passwords. Make sure that passwords are strong.
- Implement a secure password security mechanism
- Store passwords in a secure fashion.
- Compare password hashes using safe functions
- Transmit passwords only over TLS or some other strong transport
- Require reauthentication for sensitive features
- Respond with a generic error message whenever the user login doesn't work. Don't give the user too much information. The server should respond to incorrect login credentials in generally the same amount of time for different errors (The server should respond in the same amount of time when the user submits an invalid username and when the password hashing compare function returns
false
- this is in order to not give hackers too much information).
- Multi Factor Authentication (MFA) is by far the best dense against the majority of password related attacks, including brute force attacks - it would have stopped 99.9% of account compromises according to Microsoft.
- Login Throttling is a protocol used to prevent an attack from making too many attempts at guessing a password through normal interactive means. It includes:
- Maximum number of attempts
- The most common protection against these attacks is to implement an account lockout, which prevents any more login attempts for a period after a certain number of failed logins.
- The counter of failed logins should be associated with the account itself, rather than the source of the IP address, in order to prevent an attacker from making login attempts from a large number of different IP addresses.
Authorization
- Authorization may be defined as
the process of verifying that a requested action or service is approved for a specific entity
. Authorization if distinct from authentication which is the process of verifying an entity's identity. - A user that is authenticated is not authorized to access every resource and perform every action that is technically possible through a system.
- As a security concept, Least Privileges refers to the principle of assigning users only the minimum privileges necessary to complete their job.
- Relationship Based Access Control (ReBAC) is an access control model that grants access based on the relationship between resources. For instance, allowing only the user who created the post to edit it.
- Avoid exposing identifiers to the user when possible - try not including user ID in query parameters or URLs
- Ensure that static resources are properly secured
Authorization Testing Automation
- When you are implementing protection measures for an application, one of the most important parts of the process is defining and implementing the application's authorization.
CI CD Security
- CI/CD refers to a set of largely automated processes used to build and deliver software; it is often portrays as a pipeline consisting of a series of sequential, discrete steps. The pipeline generally begins when code under development is pushed to a repository and, if all steps complete successfully, ends with the software solution built, tested, and deployed to a production environment.
- CI, continuous integration, focuses on build and testing automation; CD, continuous delivery, focuses on promoting this built code to a staging or higher environment and generally performing additional automated testing.
- Identity and Access Management (IAM) is the process of managing digital identities and controlling their access to digital resources.
Clickjacking Defense
- There are three main mechanisms that can be used to defined against these attacks:
- Preventing the browser from loading the page in frame using
X-Frame-Options
or Content Security Policy (frame-ancestors) HTTP headers - Preventing session cookies from being included when the page is loaded in a frame using the
SameSite
cookie attribute - Implementing JavaScript code in the page to attempt to prevent it from being loaded in a page (known as a
frame buster
)
- Preventing the browser from loading the page in frame using
- The
frame-ancestors
directive can be used in a Content Security Policy HTTP response header to indicate whether or not a browser should be allowed to render a page in a<frame>
or<iframe>
. Sites can use this to avoid Clickjacking attacks by ensuring that their content is not embedded into other sites.X-Frame-Options
takes priority over this - Examples:
Content-Security-Policy: frame-ancestors 'none';
- This prevents any domain from framing the content. This setting is recommended unless a specific need has been identified for framing.
Content-Security-Policy: frame-ancestors 'self';
- This only allows the current site to frame the content.
Content-Security-Policy: frame-ancestors 'self' *.somesite.com;
- This allows the current site, as well as any page on
somesite.com
(using any protocol) and only the pagemyfriend.site.com
, using HTTPS only on the default port (443).
- This allows the current site, as well as any page on
- The
X-Frame-Options
HTTP header can be used to indicate whether or not a browser should be allowed to render a page in a<frame>
or<iframe>
, X-Frame-Options
Header Types:- DENY
- Prevents any domain from framing the content. The
DENY
setting is recommended unless a specific need has been identified for framing
- Prevents any domain from framing the content. The
- SAMEORIGIN
- Allows the current site to frame the content
- ALLOW-FROM uri
- permits the specified uri to frame this page
- The
SameSite
cookie attribute defined in RFC 6265bis is primarily intended to defend against cross site request forgery (CSRF); however it can also provide protection against clickjacking attacks. - Cookies with a
SameSite
attribute of eitherstrict
orlax
will not be included in requests made to a page within an<iframe>
. This means that if the session cookies are marked asSameSite
, any Clickjacking attack that requires the victim to be authenticated will not work, as the cookie will not be sent.
Content Security Policy
A strong CSP provides an effective second layer of protection against various types of vulnerabilities, especially XSS. Although CSP doesn't prevent web applications from containing vulnerabilities, it can make those vulnerabilities significantly more difficult for an attacker to exploit.
Even on a fully static website, which does not accept any user input, a CSP can be used to enforce the use of Sub resource Integrity (SRI). This can help prevent malicious code from being loaded on the website if one of the third-party sites hosting JavaScript files is compromised.
- You can set the
Content-Security-Policy
header or use a<meta http-equiv="Content-Security-Policy" content="..." >
to enforce the CSP. You can also set theContent-Security-Policy-Report-Only
header, but this does not get enforced.
Detailed CSP Directives
- Fetch Directives
- Fetch directives tell the browser the locations to trust and load resources from.
child-src
- allows the developer to control nested browsing contexts and worker execution contextsconnect-src
- provides control over fetch requests, XHR, event source, beacon and WebSockets connectionsfont-src
- specifies which URLs to load fonts fromimg-src
- specifies the URLs that images can be loaded frommanifest-src
- specifies the URLs that application manifests may be loaded fromprefetch-src
- specifies the URLs from which resources may be prefetches fromobject-src
- specifies the URLs from which plugins can be loaded fromscript-src
- specifies the locations from which a script can be executed from. It is a fallback directive for other script-like directivesstyle-src
- controls where styles get applied to a document. This includes<link>
elements,@import
rules, and requests originating from aLink
HTTP resource header fielddefault-src
- fallback directive for other fetch directives. Directives that are specified to have no inheritance, yet directives that are not specified will fall back to the value ofdefault-src
- Document Directives
- Instruct the browser about the properties of the document to which the policies will apply to.
base-uri
- specifies the possible URLs that the<base>
element can useplugin-types
- limits the types of resources that can be loaded into the document.sandbox
- restricts a page's actions such as submitting forms
- Navigation Directives
- Instruct the browser about the locations that the document can navigate to or be embedded from
form-action
- restricts the URLs which the forms can submit toframe-ancestors
- restricts the URLs that can embed the requested resource inside of<frame>
,<iframe>
, ...
- Reporting Directives
- Deliver violations of prevented behaviors to specified locations. These directives serve no purpose on their own and are dependent on other directives.
report-to
- which is a group name defined in the header in a JSON formatted header valuereport-uri
- directive is deprecated byreport-to
, which is a URI that the reports are sent to
Credential Stuffing Prevention
Use Multi Factor Authentication:
In order to balance security and usability, multi-factor authentication can be combined with other techniques to require the 2nd factor inly in specific circumstances where there is reason to suspect that the login attempt may not be legitimate, such as a login from:
- a new browser/device or IP address
- an unusual country or location
- Specific countries that are considered untrusted or typically do not contain users of a service
- An IP address that appears on known denylists or is associated with anonymization services, such as proxy or VPN services
- An IP address that has tried to login to multiple accounts
- A login attempt that appears to be scripted or from a bot rather than a human
Other Ways to Make Website More Secure:
- Secondary Passwords, PINs, and Security Questions
- Not the best
- CAPTCHA
- May slow down bots
- IP mitigation and intelligence
- Blocking IP addresses may be sufficient to stop less sophisticated attacks, but should not be used as the primary defense die to the ease of circumvention. It is more effective to have a graduated response to abuse that leverages multiple defensive measures depending on different factors of the attack.
- Device Fingerprinting
- Connection Fingerprinting
- Require Unpredictable Usernames
- Multistep Login Process
- Slow down hackers
- Require JavaScript and Block Headless Browsers
- Require the client to do some calculation on the client and require that they include the calculated value on all POST requests. This forces an attacker to either use a real browser with an automation framework like Selenium or Headless Chrome or to implement JavaScript parsing with another tool such as PhantomJS.
- This reduces accessibility somehow.
- Degradation
- A more aggressive defense against credential stuffing is to implement measures that increase the amount of time the attack takes to complete.
- Identify Leaked Passwords
- Don't use passwords that have been found in prior breaches. A good service for this is Pwned Passwords
- Notify users about unusual security events
Cross-Site Request Forgery
A Cross-Site Request Forgery attack occurs when a malicious web site, email, blog, instant message, or program tricks an authenticated user's web browser into performing an authenticated user's web browser into performing an unwanted action on a trusted site.
- The following principles should be used to defend against CSRF:
- Check if your framework has built-in CSRF protection and use it
- Add CSRF tokens to all state changing requests and validate them on the backend
- Stateful software should use the synchronizer token pattern
- CSRF tokens should be generated on the server-side and they should be generated only once per user session or each request. Because the time range for an attacker to exploit the stolen tokens is minimal for per-request tokens, they are more secure than per-session tokens. Per-request tokens may result in usability concerns.
- CSRF tokens should be:
- unique per session
- secret
- unpredicatable
- Stateless software should double submit cookies
- If an API driven site can't use
<form>
tags, consider using custom request headers - Adding headers in CloudFront or in the Application Load Balancer may be a good idea
- Implement at least one mitigation from Defense in Depth Mitigations section
- SameSite Cookie attribute can be used for session cookies but be careful to NOT set a cookie specifically for a domain
- Consider implementing user interaction based protection for highly sensitive operations
- Consider verifying the origin with standard headers
- Don not use GET requests for state changing operations
- If for any reason you do it, protect those resources against CSRF
Cross Site Scripting Prevention
- In order for an XSS attack to be successful, an attacker must be able to insert and execute malicious content in a webpage. Ensuring all variables go through validation and are then escaped or sanitized is known as perfect injection resistance. Any variable that does not go through this process is a potential weakness.
DOM Clobbering Prevention
- DOM Clobbering is a type of code-reuse, HTML-only injection attack where attackers confuse a web application by injecting HTML elements whose
id
orname
attribute matches the name of security-sensitive variables or browser APIs such as variables used for fetching remote content and overshadow their value. - Mitigation Techniques:
- HTML Sanitation
- Use
DOMPurify
to prevent or reduce the risk of DOM clobbering.
- Use
- Content Security Policy
- You can restrict the sources of JavaScript files
- Freeze Sensitive DOM Objects using the
Object.freeze()
method - Validate All Inputs to the DOM Tree
- Sanitize
id
andname
attributes
- Sanitize
- Use Explicit Variable Declarations
- Do Not Use Document and Window for Global Variables
- Avoid using
document
andwindow
for storing global variables, since they can be easily manipulated
- Avoid using
- Do Not Trust Document Built-In APIs Before Validation
- Document properties, including built-in ones, are always overshadowed by DOM Clobbering
- Enforce Type Checking
- Always check the type of document and window properties before using them in sensitive operations
- Use Strict Mode
- Use
strict
mode to prevent unintended global variable creating and to raise an error when read-only properties are attempted to be over-written
- Use
- Apply Browser Feature Detection
- Instead of relying on browser-specific features or properties, use feature detection to determine whether a feature is supported before using it
- Limit Variables to Local Scope
- Use Unique Variable Names in Production
- Use Object-oriented Programming Techniques like Encapsulation
DOM Based XSS Prevention
- DOM based XSS is a client (browser) side injection issue.
- Just make sure to escape things properly and sanitize user generated HTML
Database Security
- The application's backend database should be isolated from other servers and only connect with as few hosts as possible.
- Configure the database to only allow encrypted connections
- Databases should always require authentication
- When assigning permissions to database user accounts, developers should employ the principle of least privilege
- Most security-critical applications apply permissions at more granular levels, including:
- Table-level permissions
- Column-level permissions
- Row-level permissions
Denial of Service
- A successful DoS attack hinders the availability of instances or objects to a system and can eventually render the entire system inaccessible.
- To understand problems related to DOS, a solid understanding of your environment is essential to develop suitable defense mechanisms.
DoS Weaknesses:
- Application Attacks - focus on rendering applications unavailable by exhausting resources or by making it unusable in a functional way
- Session (or protocol) attacks - focus on consuming server resources, or resources of intermediary equipment like firewalls and load-balancers
- Network (or volumetric) attacks - focus on saturating the bandwidth of the network resource
Mitigation:
- Software
- Using validation that is cheap in resources first
- Employ graceful degradation
- Prevent single point of failure
- Avoid highly CPU consuming operations
- Handle exceptions
- Protect overflow and underflow
- Threading
- Session
- Limit server side session time based on inactivity and a final timeout
- Limit session bound information storage
- The less data is linked to a session, the less burden a user session has on the webserver's performance
- Input Validation
- Limit file upload size and extensions
- Total request size
- Prevent input based resource allocation
- Prevent input based function and threading interaction
- Input based puzzles
- Access Control
- Authentication as a means to expose functionality
- User lockout
Docker Security
- Docker is the most popular containerization technology. When used correctly, it can enhance security compared to running applications directly on the host system. Certain misconfigurations can reduce security levels or introduce new vulnerabilities.
I will come back to Docker when I need to create a server that needs to scale.
- Keep Host and Docker Up to date
- Do not expose the Docker daemon socket
- Set a user
- Limit capabilities (Grant only specific capabilities, needed by a container)
- Prevent in-container privilege escalation
- Be mindful of Inter-container connectivity
- Use Linux Security Module
- Limit resources (memory, CPU, file descriptors, processes, restarts)
- Set filesystem and volumes to read-only
- Integrate container scanning into your CI/CD pipeline
- Keep the Docker scanning tools into your CI/CD pipeline
- Keep the Docker daemon logging level at info
- Run Docker in rootless mode
- Utilize Docker Secrets for sensitive data
- Enhance supply chain security
Error Handling
Except in movies, an attack always begins with a Reconnaissance phase in which the attack will try to gather as much technical information (often name and version properties) as possible about the target, such as the application server, frameworks, libraries, etc.
- Unhandled errors can assist an attacker in this initial phase, which is very important for the rest of the attack.
- This is why you should remove certain headers that AWS (CloudFront, ALB) adds in the process of handling requests.
- Don't disclose you technology stack when handling errors.
- Error details should be logged on the server side for investigation, but you should not send the user too much information that gives the users too much information.
File Upload
- File upload is becoming more important. The application should be able to fend off bogus and malicious files in a way to keep the application and the users safe.
The following principle should be followed to reach a secure file upload implementation:
- List allowed extensions. Only allow sage and critical extensions for business functionality.
- Validate the file type, don't trust the
Content-Type
header, as it can be spoofed - Change the filename to something generated by the application
- Set the filename length limit. Restrict the allowed characters if possible.
- Set the file size limit
- Only allow authorized users to upload files
- Store the files on a different server
- Run the file through an antivirus or a sandbox if available to validate that it doesn't contain malicious data
- Ensure that any libraries used are securely configured and keep up to date
- Protect the file upload from CSRF attacks.
Forgot Password
- In order to implement a proper user management system, systems integrate a Forgot Password service that allows the user to request a password reset.
- The following short guidelines can be used as a quick reference to protect the forgot password service:
- Return a consistent message for both existent and non-existent accounts.
- Ensure that the time taken for the user response message is uniform.
- Use a side-channel to communicate the method to reset their password.
- Use the URL tokens for the simplest and fastest implementation.
- Generate a token to the user and attach it in the URL query string
- Send this token to the user via email.
- The user receives the email, and browses to the URL with the attached token.
- Perform any additional validation steps such as requiring the user to answer security questions.
- Let the user create a new password and confirm it. Ensure that the same password policy used elsewhere in the application is applied.
- Ensure that generated tokens or codes are:
- Randomly generated using a cryptographically safe algorithm
- Sufficiently long to protect against brute force attacks
- Stored securely
- Single use and expire after an appropriate period.
- Do not make a change to the account until a valid token is presented, such as locking out the account.
HTML5 Security
- Web messaging provides a means of messaging between documents from different origins in a way that is generally safer than the multiple hacks used in the past to accomplish this task. There are some security concerns that you should keep in mind.
- Use the
sandbox
attribute of aniframe
for untrusted content. - The
sandbox
attribute of aniframe
enables restrictions on content within aniframe
. The following restrictions are active when thesandbox
attribute is set: - All markup is treated as being from a unique origin
- All forms and scripts are disabled
- All links are prevented from targeting other browsing contexts.
- All features that trigger automatically are blocked
- All plugins are disabled.
- Credential and Personally Identifiable Information (PII) Input Hints:
- Text areas and input fields for PII (name, email, address, phone number) and login credentials (username, password) should be prevented from being stored in the browser. Use these HTML5 attributes to prevent the browser from storing PII from your form:
spellcheck="false"
autocomplete="off"
autocorrect="off"
autocapitablize="off"
HTTP Headers
HTTP Headers are a great booster for web security with easy implementation. Proper HTTP response headers can help prevent security vulnerabilities like Cross-Site Scripting, Clickjacking, Information disclosure and more.
Security Headers
X-Frame-Options
- Used to indicate whether or not a browser should be allows to render a page in a
<frame>
,<iframe>
,<embed>
, or<object>
. - Recommendation:
X-Frame-Option:DENY
- Used to indicate whether or not a browser should be allows to render a page in a
X-XSS-Protection
: do not use this header or explicitly turn it off:X-XSS-Protection: 0
X-Content-Type-Options
- Used by the server to indicate to the browsers that the MIME types advertised in the
Content-Type
headers should be followed and not guessed - Recommendation:
X-Content-Type-Options: nosniff
- Used by the server to indicate to the browsers that the MIME types advertised in the
Referrer-Policy
- How much referrer information (sent via the Referrer header) should be included with requests
- Recommendation:
Referrer-Policy: strict-origin-when-cross-origin
Content-Type
- Used to indicate the original media type of the resource (before any encoding is applied for sending).
- Recommendation:
Content-Type: text/html; charset=UTF-8
- Note: The
charset
attribute is necessary to prevent XSS in HTML pages - Note: the
text/html
can be any of the possible MIME types
Set-Cookie
- Used to send a cookie from the server to the user agent, so the user agent can send it back to the server later
Strict-Transport-Security
- Lets a website tell browsers that it should be accessed using HTTPS, instead of using HTTP
- Recommendation:
Strict-Transport-Security: max-age=63062000; includeSubDomains; preload
Content-Security-Policy
- I've been over this
Access-Control-Allow-Origin
- This is a CORS header. This header indicates whether the response it is relayed to can be shared with requesting code from the given origin.
- Recommendation:
Access-Control-Allow-Origin: https://yoursite.com
Cross-Origin-Opener-Policy
- Allows you to ensure a top-level document does not share a browsing context group with cross-origin documents.
- Recommendation:
HTTP Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy
- This response header prevents any document from loading any cross origin resources that don't explicitly grant the document permission
- Recommendation:
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Resource-Policy
- This header allows you to control the set of origins that are empowered to include a resource.
- Recommendation:
Cross-Origin-Resource-Policy: same-site
Permissions-Policy
- Allows you to control which origins can use which browser features, both in the top-level page and in embedded frames.
- Recommendation: Set it and disable all features that your site does not need or allow them only to the authorized domains
- FLoC
- This is something proposed by Google to provide interest-based advertisements to groups of users (
cohorts
) - Recommendation:
Permissions-Policy: interest-cohort=()
- This is something proposed by Google to provide interest-based advertisements to groups of users (
Server
- Describes the software used by the origin server that handled the request
- Recommendation:
Server: webserver
- remove this header or set non-informative values
X-Powered-By
- This header describes the technologies used by the webserver. This information exposes the server to attackers.
- Remove all
X-Powered-By
headers
X-DNS-Prefetch-Control
- The default behavior is to perform DNS caching, which is good for most websites. You probably don't need to change this.
Public-Key-Pins
- This header is deprecated and should not be used anymore.
HTTP Strict Transport Security
HTTP Strict Transport Security is an opt-in security enhancement that is specified by a web application through the use of a special response header. Once a supported browser receives this header that browser will prevent any communications from being sent over HTTP to the specified domain and will instead send all communications over HTTPS.
- HSTS automatically redirects HTTP requests to HTTPS for the target domain
- HSTS does not allow a user to override the invalid certificate message.
Input Validation
Input validation is performed to ensure only properly formed data is entering the workflow in an information system, preventing malformed data from persisting in the database and triggering malfunction of various downstream components. Input validation should happen as early as possible in the data flow, preferably as soon as the data is received from the external party.
- Syntactic validation should enforce correct syntax of structured fields (e.g. SSN, date, currency symbol)
- Semantic validation should enforce correctness of their values in the specific business context
Insecure Direct Object Reference Prevention
Insecure Direct Object Reference (IDOR) is a vulnerability that arises when attackers can access or modifiy objects by manipulating identifiers used in a web application's URLs or parameters. It occurs due to missing access control checks, which fail to verify whether a user should be allowed to access specific data.
- To mitigate IDOR, implement access control checks for each object that users try to access. Additionally, use complex identifiers as a defense-in-depth measure, but remember that access control is crucial even with these identifiers.
LDAP Injection Prevention
Lightweight Directory Access Protocol (LDAP) allows an application to remotely perform operations such as searching and modifying records in directories. LDAP injection results from inadequate input sanitation and validation and allows malicious users to glean restricted information using the directory service.
LDAP injection is an attack used to exploit web based applications that consturct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements through techniques similar to SQL injection.
Logging
- Application logging should always be included for security events. Application logs are invaluable data for:
- Identifying security incidents
- Monitoring policy violations
- Establishing baselines
- Assisting non-repudiation controls
- Providing information about problems and unusual conditions
- Contributing additional application-specific data for incident investigation which is lacking in other log sources
- Helping defend against vulnerability identification and exploitation through attack injection
- Application logging might also be used to record other types of events such as:
- Security events
- Business process monitoring
- Anti-automation monitoring
- Audit trails
- Performance monitoring
- Compliance monitoring
- Data for subsequent requests for information
- Legally sanctioned interception of data
- Other business specific requirements
- Events to Log:
- Input validation failures, e.g. protocol violations, unacceptable encodings, invalid parameter names and values
- Output validation failures
- Authentication successes and failures
- Authorization (access control) failures
- Session management failures
- Application errors and system events
- Application and related systems start-ups and shut-downs
- Suspicious business logic activities
- What Information Should Logs Include?
- When
- Time / Date
- Where
- Application identifier
- Application address
- Service
- Geolocation
- Window /form/page
- Code Location
- Who
- Source address (IP address)
- User Identity
- What
- Type of Event
- Severity
- Security relevant Event Flag
- Description
- Data To Exclude:
- Application source code
- Session identification values
- Access Tokens
- Sensitive personal data and some forms of personally identifiable information
- Authentication passwords
- database connection strings
- Bank account or payment card holder data
- Data of a higher security classification that the logging system is allowed to store
- Commercially sensitive information
- Information a user has opted out of collection or has not consented to
Logging Vocabulary
This document proposes a standard vocabulary for logging security events. The intent is to simplify monitoring and alerting such that, assuming developers trap errors and log them using this vocabulary, monitoring and alerting would be improved by simply keying on these terms.
Mass Assignment
- Software frameworks sometime allow developers to automatically bind HTTP request parameters into program code variables or objects to make using that framework easier on developers. This can sometimes cause harm. Attackers can sometimes use this methodology to create new parameters that the developer never intended which in turn creates new variables or objects in program code that was not intended.
- This is called a Mass Assignment vulnerability.
- I don't see myself doing this.
Microservices Security
- It is vital for applications security architects to understand and properly use existing architecture patterns to implement authentication and authorization in microservices-based systems.
- In simple scenarios, authorization can happen only at the edge level (API gateway). The API gateway can be leveraged to centralize enforcement of authorization for all downstream microservices, eliminating the need to provide authorization and access control for each of the individual services. This has the following limitations:
- Hard to manage in complex ecosystems
- Violates the defense in depth principle
- Different teams own different processes
- Service level authorization gives each microservice more control to enforce access control policies.
- Recommended: Centralized Pattern with Embedded Policy Decision Point
- In this pattern, access control rules are defined centrally but stored and evaluated at the microservice level. Access control rules are defined using PAP and delivered to an embedded PDP, along with the attributes required to evaluate those rules. When a subject invokes a microservice endpoint, the microservice code invokes the PDP, and the PDP generates an access control policy decision by evaluating the query input against access control rules and attributes. Based on the PDP decision, the microservice enforces authorization.
Multifactor Authentication
- When to require MFA
- Changing passwords or security questions
- Changing the email address associated with the account
- Disabling MFA
- Elevating a user session to an administrative session
- Risk Based Authentication
- Requiring MFA when the user logs in from a new device or location
- Requiring MFA when the user logs in from a location that is considered to be high risk
- Allowing corporate IP ranges (or using geolocation as an additional factor)
- When the user enters their password, but fails to authenticate using a second factor, this could mean:
- The user has lost their second factor or doesn't have it available
- The user's password has been compromised
- Authentication based on Biometrics may be a good idea:
- They are hard to spoof
- They are fast
- There are privacy concerns though
NPM Security
- 10 npm security best practices and productivity tips, useful for JavaScript and NodeJS developers:
- Avoid publishing secrets to the npm registry
- Enforce the lock file
- Minimize attack surfaces by ignoring run-scripts
- Access npm project health
- Audit for vulnerabilities in open source dependencies
- Use a local npm proxy
- Responsibly disclose security vulnerabilities
- Enable 2FA
- Use npm author tokens
- Understand module naming conventions and typosquatting attacks
NodeJS Security
- Set request size limits
- Do not block the event loop
- Use callbacks
- Perform input validation
- Perform output escaping
- Perform application activity logging
- Monitor the event loop
- Look into the
toobusy-js
npm module
- Look into the
- Take precautions against brute-forcing - look into rate limiting
- Use anti-CSRF token
- Remove unnecessary roots
- Prevent HTTP Parameter Pollution
- HTTP Parameter pollution is an attack in which attackers send multiple HTTP parameter with the same name and this causes your application to interpret them unpredictably. When multiple parameter values are sent, Express populates them in an array
- Use the
hpp
module to solve this issue - it gets the last parameter value submitted forreq.query
andreq.body
- Only return what is necessary
- Use object property descriptors
- Use access control limits
- Handle uncaughtException
process.on("uncaughtException", function(err) {
// clean up allocated resources
// log necessary error details to log files
process.exit(); // exit the process to avoid unknown state
});
- Listen to errors when using
EventEmitter
- Handle errors in asynchronous calls
- Set cookie flags appropriately
- Use appropriate security headers
- Keep your packages up to date
- Do not use dangerous functions
- Stay away from evil regexes
- Run security linters
- Use strict mode
- Adhere to general application security principles
OS Command Injection Defense
- Avoid calling OS commands directly
- OS Command Injection seems to involve using user supplied values to call an operating system command - I don't really see myself ever doing this
Password Storage
When passwords are stored, they must be protected from an attacker even if the application or database is compromised. Fortunately, a majority of modern languages and frameworks provide built-in functionality to help store passwords safely.
However, once an attacker has acquired stored password hashed, they are always able to brute force hashed offline. Defenders can slow down offline attacks by selecting hash algorithms that are as resource intensive as possible.
- Passwords should be hashed, not encrypted
- Strong passwords stored with modern hashing algorithms and using hashing best practices should be effectively impossible for an attacker to crack
- Methods for enhancing password storage:
- Salting
- Peppering
- Using work factors
Prototype Pollution Prevention
Prototype Pollution is a critical vulnerability that can allow attackers to manipulate an application's JavaScript objects and properties, leading to serious security issues such as unauthorized access to data, privilege escalation, and even remote code execution.
- Use
new Set()
ornew Map()
instead of using object literals
REST Security
- Secure REST services must only provide HTTPS endpoints. This protects authentication credentials in transit. It also allows clients to authenticate the service and guarantees integrity of the transmitted data.
- Non-public REST services must perform access control at each API endpoint. Web services in monolithic applications implement this by means of user authentication, authorization logic, and session management.
- Validate Content types
- RESTful web services should be careful to prevent leaking credentials. Passwords, security tokens, and API keys should not appear in the URL, as this can be captured in web server logs
- In
POST
/PUT
requests sensitive data should be transferred in the request body or request headers - In
GET
requests sensitive data should be transferred in an HTTP Header
- In
- Make sure to return the correct HTTP status code
SAML Security
- The Security Assertion Markup Language (SAML) is an open standard for exchanging authorization and authentication information.
SQL Injection Prevention
- Attackers can use SQL injection on an application if it has dynamic database queries that use string concatenation and user supplied input. To avoid SQL injection flaws, developers need to:
- Stop writing dynamic queries with string concatenation
- Prevent malicious SQL input from being included in executed queries.
Primary Defenses:
- Use of prepared statements (with parameterized queries)
- Use of properly constructed stored procedures
- Allow-list input validation
- STRONGLY DISCOURAGED: Escaping All User Supplied Input
Secure Cloud Architecture
Virtual Private Clouds (VPC) and public/private network subnets allow an application and its network to be segmented into distinct chunks, adding layers of security within a cloud system. Unlike other private vs public trade-offs, an application will likely incorporate most or all of these components in a mature architecture.
VPCs
VPCs are used to create network boundaries within an application, where-in components can talk to each other, much like physical network in a data center. The VPX will be made up of some number of subnets, both public and private. VPXs can be used to:
- Separate entire applications within the same cloud account
- Separate large components of application into distinct VPCs with isolated networks
- Create separations between duplicate applications used for different customers or data sets
Public Subnets
Public subnets house components which will have an internet facing presence. The subnet will contain network routing elements to allow components within the subnet to connect directly to the internet. Some cases include:
- Public facing resources, like front-end web applications
- Initial touch points for applications, like load balancers and routers
- Developer access points
Private Subnets
Private subnets house components which should not have direct internet access. The subnet will likely contain network routing to connect it to public subnets, to receive internet traffic in a structured and protected way. Private subnets are for:
- Databases and data stores
- Backend servers and associated file systems
- Anything deemed too sensitive to have internet access
Web Application Firewalls (WAF) are used to monitor or block common attack payloads or allow only specific request types or patterns. Applications should use them as a first line of defense, attaching them to entry points like load balancers or PAI gateways, to handle potentially malicious content before it reaches the application code.
Server Side Request Forgery Prevention
- Server Side Request Forgery (SSRF) is an attack vector that abuses an application to interact with the internal/external network on the machine itself.
Session Management
A web session is a sequence of network HTTP request and response transactions associated with the same user. Modern and complex web applications require the retaining of information or status about each user for the duration of multiple requests. Therefore, sessions provide the ability to establish variables - such as access rights and localization settings - which will apply to each and every interaction a user has with the web application for the duration of the session.
- The name used by the session ID should not be extremely descriptive nor offer unnecessary details about the purpose and meaning of the ID.
- The session ID must be unpredictable (random enough) to prevent guessing attacks, where an attacker is able to guess or predict the ID of a valid session through statistical analysis techniques. The session ID value must provide at least
64 bits
of entropy. - The session ID content (or value) must be meaningless to prevent information disclosure attacks, where an attacker is able to decode the contents of the ID and extract details of the user, the session, or the inner workings of the web application.
Cookies
- The
Secure
cookie attribute instructs web browsers to only send the cookie through an encrypted HTTPS (SSL/TLS) connection. The session protection mechanism is mandatory to prevent the disclosure of the session ID through MitM attacks. It ensures that an attacker cannot simply capture the session ID from web browser traffic. - The
HttpOnly
cookie attribute instructs web browsers not to allow scripts (JavaScript or VBscript) an ability to access the cookies via the DOMdocument.cookie
attribute. SameSite
defines a cookie attribute preventing browsers from sending aSameSite
flagged cookie with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provides some protection against cross-site request forgery attacks.Domain
cookie attribute instructs web browsers to only send the cookie to the specified domain and all subdomains.Path
instructs web browsers to only send the cookie to the specified directory or subdirectories within a web application- If a cookie presents the
Max-Age
orExpires
attributes, it will be considered a persistent cookie and will be stored on disk by the web browser based until the expiration time
XML Security
- You probably should use a framework to render
sitemap.xml
.
XS Leaks
- XS Leaks = Cross-Site Leaks
Since this vulnerability is based on the core mechanism of modern web browsers, it's also called a browser side-channel attack. XS-Leaks attacks seek to exploit the fact of seemingly insignificant information that is exchanged in cross-site communications between sites.
- Attack vector:
- The entire attack takes place on the victim's browser side - just like an XSS attack
- In some cases, the victim must remain on the attacker's site longer for the attack to succeed.
Same Origin Policy (SOP)
- Two URLs are considered as same-origin if their protocol, port, and host are the same.
- Any origin can send a request to another source, but due to the Same-origin policy, they will not be able to read the response directly
- Prevent sending code to
iframe
on the server:
app.get('/', (req, res) => {
if (req.get('Sec-Fetch-Dest') === 'iframe') {
return res.sendStatus(403);
}
res.send({
message: 'Hello!'
});
});
Comments
There are currently no comments to show for this article.