Basics Flashcards
What are XSS attacks?
Cross-Site Scripting is a type of security vulnerability that occurs when a web application does not properly sanitize or validate user input and allows malicious code to be injected into the application and run in the victim’s browser.
How can you mitigate XSS attacks?
- Input validation and output encoding
- output encoding ensures that user input is treated as text and not as executable code (use framework default output encoding or use a library)
- reject or sanitize input that does not conform to the expected type
- strict input invalidation and enforce content types - CSP - Enforce a whitelist of trusted sources. CSP helps mitigate XSS attacks by blocking the execution of scripts from unauthorized sources
- XSS Protection Headers
- Secure Development Practices - avoid using eval() and unsafe functions. Utilize frameworks and libraries that have built-in security controls.
- Session Cookie security - Mark cookies as “secure”. Helps with session theft.
- HTML sanitization
- maybe you need to let the user write html
- output encoding doesn’t work in this case bc it breaks the intended functionality
- use DOMPurify
Firewalls
Don’t use innerHTML. use innerText. Don’t ever use eval()
Encode data before you use it
What are some consequences of XSS attacks?
Cookie Theft: The injected code can steal the victim’s session cookies, allowing the attacker to impersonate the user and gain unauthorized access to their accounts.
Defacement: The attacker may modify the appearance or content of the web page, potentially spreading misinformation or damaging the website’s reputation.
Data Theft: Personal or confidential information entered by the victim on the compromised page can be captured and sent to the attacker.
Phishing Attacks: XSS can be utilized to create convincing phishing pages that trick users into entering their credentials or sensitive information.
Malware Distribution: The injected code can redirect users to malicious websites or initiate the download of malware onto the victim’s device.
What are CSRF attacks?
CSRF (Cross-Site Request Forgery) attacks, also known as session riding or one-click attacks, are a type of web security vulnerability that exploits the trust a website has in a user’s browser. In a CSRF attack, an attacker tricks a victim into unknowingly executing unwanted actions on a website on which the victim is authenticated.
A CSRF attack works because browser requests automatically include all cookies including session cookies. Therefore, if the user is authenticated to the site, the site cannot distinguish between legitimate authorized requests and forged authenticated requests.
Here’s how a typical CSRF attack works:
User authentication: The victim logs into a legitimate website (e.g., a social media platform or an online banking portal) using their credentials, which generates an authentication cookie.
Exploiting trust: The attacker prepares a malicious website or embeds malicious code on a legitimate website that the victim is likely to visit.
Malicious request: When the victim visits the malicious website or clicks on a manipulated link, a hidden request is sent from the victim’s browser to the targeted website. This request is typically an action that the victim did not intend to perform, such as changing account settings, making a purchase, or performing a transaction.
Trust-based execution: The targeted website receives the forged request and treats it as a legitimate action because it comes with the victim’s authentication cookie. The server assumes that the victim intentionally initiated the request.
Unauthorized action: The targeted website executes the request, causing the unintended action to take place, which could lead to various consequences, such as modifying account settings, transferring funds, or posting on social media.
The main challenge with CSRF attacks is that they exploit the inherent trust between a website and the user’s browser. Websites generally assume that requests originating from a user’s browser are legitimate. This trust can be abused by an attacker who leverages the victim’s active session on a website to perform unauthorized actions.
How can you mitigate CSRF attacks?
Cross-Site Request Forgery (CSRF) is a type of attack where an attacker tricks a victim into performing unintended actions on a web application in which the victim is authenticated. To mitigate CSRF attacks, several countermeasures can be implemented:
Use CSRF Tokens: Implementing CSRF tokens is one of the most effective defenses against CSRF attacks. A CSRF token is a unique value associated with a user’s session and is included in each request that modifies data or performs sensitive actions. The token is generated by the server and embedded in forms or added to AJAX requests. The server then validates the token with each incoming request to ensure it matches the expected value for that user’s session. This prevents attackers from forging requests since they won’t possess the correct token.
Same-Site Cookies: Set the “SameSite” attribute on cookies to restrict their use to the same site that originated them. This attribute prevents the browser from sending cookies in cross-site requests, effectively blocking many CSRF attacks. By setting “SameSite” to “Strict” or “Lax” (depending on your specific requirements), you can significantly reduce the risk of CSRF.
Check Origin and Referrer Headers: Verify the “Origin” and “Referer” headers on requests to ensure they match the expected values. The “Origin” header contains the site making the request, while the “Referer” header specifies the URL of the previous page. Although these headers can be spoofed, checking them adds an additional layer of protection against CSRF attacks.
Implement CAPTCHA or reCAPTCHA: Including CAPTCHA challenges or Google reCAPTCHA in sensitive operations or user actions can help verify that the request is coming from a legitimate user rather than an automated script. CAPTCHA prompts the user to complete a challenge, such as solving a visual puzzle or entering a code, before proceeding with the action, making it difficult for automated attacks to succeed.
Use Anti-CSRF Libraries or Frameworks: Many web frameworks and libraries provide built-in mechanisms for mitigating CSRF attacks. These frameworks often handle CSRF token generation and verification automatically, reducing the burden on developers to implement the protection themselves. It is recommended to leverage these security features provided by your chosen framework or library.
Limit or Avoid CSRF-Susceptible Actions via GET: Since GET requests can be triggered by simply visiting a malicious page, it is advisable to avoid performing sensitive or state-changing operations via GET requests. Instead, use POST or other non-idempotent methods for actions that modify data or have side effects. This reduces the likelihood of unintentional CSRF vulnerabilities.
It’s important to note that implementing multiple layers of defense is typically more effective than relying on a single measure. By combining these countermeasures, you can significantly reduce the risk of CSRF attacks and enhance the security of your web application.
How can you bypass CSRF mitigations?
Cross-Domain Exploitation: If the target website allows cross-domain requests or has permissive Cross-Origin Resource Sharing (CORS) settings, an attacker can leverage this to bypass CSRF mitigations. By making requests from a different domain or subdomain, the attacker can circumvent the same-origin policy enforced by browsers.
Exploiting Vulnerabilities in Subdomains: CSRF mitigations often operate on a per-domain basis, assuming that subdomains are trustworthy. However, if an attacker discovers a vulnerability in a subdomain that doesn’t implement the necessary CSRF protections, they can exploit it to carry out CSRF attacks.
JSONP and CORS Misconfigurations: JSONP (JSON with Padding) and CORS (Cross-Origin Resource Sharing) are techniques that allow cross-domain communication in specific scenarios. Misconfigurations in the implementation of JSONP or CORS can open avenues for CSRF attacks. Attackers may attempt to find weaknesses in these configurations to bypass CSRF mitigations.
Clickjacking: Clickjacking involves tricking a user into clicking on a maliciously crafted webpage element that initiates a CSRF attack without their knowledge. Attackers achieve this by overlaying or framing the targeted web application within their malicious page, making it appear as if the user is interacting with the legitimate site. Clickjacking attacks bypass CSRF mitigations by abusing the user’s trust rather than directly exploiting the mitigations themselves.
Cross-Site Scripting (XSS): If a web application has XSS vulnerabilities, an attacker can exploit them to inject malicious code into a trusted page. This injected code can then bypass CSRF mitigations since it executes within the context of the targeted web application. By leveraging XSS vulnerabilities, attackers can trick users into unintentionally executing malicious actions.
https://shahmeeramir.com/methods-to-bypass-csrf-protection-on-a-web-application-3198093f6599
https://portswigger.net/web-security/csrf/bypassing-token-validation
What are open redirects?
Makes it easier for attackers to direct users to malicious resources. An application allows attackers to pass information to the app that results in users being sent to another location. The location can be an attacker-controlled website or server used to distribute malware, trick a user into trusting a link, etc. Could be in a GET query parameter for example. Can harm your reputation.
An open redirect is a redirect that a user is able to manipulate the link to point somewhere potentially malicious.
Potential attacks:
If the link is a parameter in a GET request, then the link can be sent with the modified URL to send to victims as part of a phishing campaign in a link. If the URL parameter is in a POST request, this is harder to exploit, but it could still be used to create a malicious POST request for a user to make.
For OAuth, the redirect link with the token from the identity provider (like FB) could be changed to a maliciously controlled site. The attacker could then use this code to get information from FB about a user.
SSRF. Can bypass SSRF filters.
Referrer check bypass. One way to protect against CSRF is to check the referrer header to confirm that the request originated from the website itself. If the open redirect can redirect and then redirect again to the correct page, it will look like the CSRF originated from the open redirect page, and will be allowed to perform a request.
To prevent, a whitelist should be made for where the URL is allowed to point to.
To mitigate open redirect vulnerabilities, it’s important for web applications to validate and sanitize any user-supplied input used for redirection. The application should have a whitelist of trusted URLs or a strict validation mechanism to ensure that the redirect target is within the expected domain or a predefined set of safe destinations.
By implementing proper input validation and only allowing redirection to trusted URLs, the risk of open redirect vulnerabilities can be minimized, thus protecting users from being redirected to potentially harmful or malicious websites.
What are insecure deserialization attacks?
Deserialization is the reverse of that process, taking data structured in some format, and rebuilding it into an object. Today, the most popular data format for serializing data is JSON. Before that, it was XML.
Use safe deserialization functions.
Insecure deserialization refers to a security vulnerability that arises when an application deserializes untrusted or malicious data without implementing proper validation and security controls. Deserialization is the process of converting serialized data (such as JSON, XML, or binary formats) into objects or data structures that can be used by an application.
Here’s a step-by-step explanation of insecure deserialization:
Serialization and Deserialization: Serialization is the process of converting objects or data structures into a format suitable for storage or transmission, such as JSON or binary. Deserialization is the reverse process, converting the serialized data back into objects or data structures.
Insecure Deserialization Vulnerability: Insecure deserialization occurs when an application deserializes untrusted data without adequately validating or sanitizing it. This allows an attacker to provide manipulated or maliciously crafted serialized data with the intent of exploiting vulnerabilities in the deserialization process.
Exploitation: Once the application deserializes the manipulated data, various security risks can arise, including:
a. Remote Code Execution (RCE): Attackers can craft serialized data that, when deserialized, executes arbitrary code on the server. This can lead to full compromise of the application or underlying system.
b. Denial-of-Service (DoS): By providing malformed or large serialized data, an attacker can cause resource exhaustion, leading to a denial of service by consuming excessive system resources.
c. Object Injection: Attackers can manipulate serialized data to inject unauthorized or malicious objects into the application’s context. These objects can potentially lead to unauthorized access, privilege escalation, or other types of attacks.
d. Data Tampering: Insecure deserialization can allow attackers to modify serialized data to alter the application’s behavior, bypass security controls, or modify critical data.
Mitigation: To mitigate insecure deserialization vulnerabilities, several best practices can be followed:
a. Input Validation: Ensure that serialized data is validated for expected types, length, and structure before deserialization. Reject any data that does not conform to the expected format.
b. Secure Deserialization Libraries: Use well-maintained and secure deserialization libraries or frameworks that implement safeguards against common deserialization vulnerabilities. These libraries may include features such as whitelisting allowed classes, signature verification, or sandboxing the deserialization process.
c. Least Privilege: Ensure that the deserialized objects or data have the least privileges necessary for their intended use. Avoid granting unnecessary access or permissions.
d. Integrity Checks: Implement integrity checks, such as digital signatures or message authentication codes (MACs), to verify the integrity of serialized data before deserialization.
e. Secure Configuration: Follow secure configuration practices for the deserialization process, such as running deserialization code in isolated environments or sandboxes to limit potential damage.
How can you prevent insecure deserialization attacks?
Input validation and filtering: Implement strict input validation and filtering mechanisms to ensure that only trusted and expected data is deserialized. Validate the structure, integrity, and content of the serialized data to detect any anomalies or malicious payloads. Reject any unexpected or suspicious data.
Use whitelisting: Maintain a whitelist of allowed classes, types, or objects that can be deserialized. This helps restrict the deserialization process to only trusted classes and prevents the execution of arbitrary or malicious code. Avoid using blacklists, as they can be incomplete and easily bypassed.
Implement secure deserialization libraries: Use well-established and secure deserialization libraries or frameworks that have built-in safeguards against insecure deserialization vulnerabilities. These libraries often provide features like input validation, object integrity checks, and other security mechanisms.
Enforce strong access controls: Apply strong access controls and least privilege principles to limit the permissions and capabilities of deserialized objects. Only grant necessary permissions to the deserialized objects and restrict their ability to execute sensitive operations.
Disable or restrict dangerous classes and gadgets: In certain cases, it may be necessary to disable or restrict the use of certain classes or gadgets during deserialization. Some classes or gadgets can be abused to execute arbitrary code or perform unauthorized actions. Understand the deserialization libraries and platforms you’re using and be aware of any potentially dangerous classes or gadgets.
Monitor and log deserialization activities: Implement robust logging and monitoring mechanisms to track deserialization activities, including the data being deserialized, the sources of the data, and any errors or exceptions that occur during the process. This helps in detecting and investigating potential attacks.
Keep software and libraries up to date: Regularly update and patch the deserialization libraries, frameworks, and platforms used in your applications. Developers often release security updates that address known vulnerabilities, including insecure deserialization issues. Stay informed about security advisories and apply patches promptly.
Perform security testing: Conduct thorough security testing, including penetration testing and vulnerability assessments, to identify and address any insecure deserialization vulnerabilities. Use tools and techniques that specifically target deserialization vulnerabilities.
What are the 3 different types of XSS attacks?
- Stored (persistent) XSS: the malicious script is stored on the target server, usually in a db or another type of persistent storage. When the user requests a page that returns this malicious script, the code will get executed in the victim’s browser.
- Reflected (non-persistent) XSS: this occurs when the malicious script is embedded in a URL parameter or form input. The attacker usually tricks the user into clicking on the crafted link with the malicious script. The victim’s browser then executes the script, potentially leading to unauthorized actions or data theft. Unlike stored XSS, the payload is not permanently stored on the server.
- Dom XSS: DOM-based XSS attacks involve the manipulation of the Document Object Model (DOM) of a web page, which represents the structure and content of the page. In this type of attack, the injected script is directly inserted into the DOM by manipulating client-side scripting, such as JavaScript, without involving the server. The script is then executed within the victim’s browser, potentially leading to malicious actions or data compromise.
DOM is client-side injection vs server-side injection for the other two. It is injected into the application during runtime in the client directly.
Explain step-by-step how XSS works.
- Vulnerable Web Application: a web application fails to properly sanitize/validate user input before displaying it on a web page.
- Malicious Payload Injection: An attacker takes advantage of this and injects malicious input into the application.
- User Interaction: When a user visits the page or interacts with the afflicted function, the injected code is served as part of the web application’s response.
- Execution in User’s Browser: the browser executes the code as if it were legitimate, trusted code. Since the code runs within the context of the affected web page, it can access sensitive information, manipulate the page’s content, or perform actions on behalf of the user.
What is SQL injection?
SQL injection is a type of web security vulnerability that occurs when an attacker is able to manipulate the input parameters of a web application’s SQL query. This vulnerability arises when user-supplied data is not properly validated, sanitized, or parameterized before being used in constructing SQL queries. As a result, an attacker can inject malicious SQL code into the query, leading to unauthorized access, data disclosure, data manipulation, or even remote code execution.
Here’s how SQL injection attacks typically work:
Injection point identification: The attacker identifies a vulnerable input field or parameter in a web application that directly or indirectly interacts with the underlying SQL database. Common injection points include user login forms, search fields, or any input that is concatenated into SQL queries without proper validation.
Malicious payload injection: The attacker crafts a malicious payload by inserting SQL code snippets into the input field or parameter. The injected SQL code is designed to manipulate the original query’s logic or retrieve unauthorized data from the database.
Query execution and unintended consequences: When the vulnerable web application processes the user’s input without proper sanitization or validation, it constructs a SQL query that incorporates the injected code. This leads to the unintended execution of the injected SQL code, potentially altering the query’s behavior or exposing sensitive data.
Exploitation and potential outcomes: Depending on the attacker’s intent and the extent of the vulnerability, SQL injection attacks can result in various consequences. These may include unauthorized access to databases, disclosure of sensitive information, modification or deletion of data, and even the execution of arbitrary commands or code on the underlying server.
How do you prevent SQL injection attacks?
Use parameterized queries or prepared statements: Instead of constructing SQL queries by directly concatenating user input, use parameterized queries or prepared statements provided by your programming language or framework. These techniques ensure that user-supplied values are treated as data rather than executable SQL code.
Input validation and sanitization: Implement strict input validation and sanitization routines to filter and cleanse user input. Validate input against expected formats, data types, and ranges, and sanitize input to remove or escape potentially malicious characters or sequences.
Principle of least privilege: Employ the principle of least privilege when configuring database access permissions. Ensure that the application’s database user account has limited privileges, granting only the necessary permissions for the application’s intended functionality.
Least exposure principle: Limit the exposure of database error messages or detailed stack traces to prevent attackers from gaining information that can aid in exploiting SQL injection vulnerabilities.
Regularly update and patch software: Keep your web application’s software components, frameworks, and libraries up to date. Developers often release security patches that address known SQL injection vulnerabilities. Stay informed about security advisories and promptly apply relevant updates.
Perform security testing: Conduct regular security testing, including vulnerability assessments and penetration testing, to identify and remediate any SQL injection vulnerabilities. Automated vulnerability scanning tools and manual code reviews can help detect potential weaknesses.
What is SSRF?
Server-side request forgery.
SSRF vulnerabilities let attackers send crafted requests from a backend server of a vulnerable application. This is used to target internal systems that are behind firewalls and not accessible via the external network. Commonly occur when an attacker can control the URL to which the web application makes a request. They could try to access resources using localhost. Try internal IPs, AWS metadata. This is all because the request appears to originate from a trusted location.
An SSRF exploit that causes connections to external third-party systems might result in malicious onward attacks that appear to originate from the organization hosting the vulnerable application.
How do you prevent SSRF attacks?
Whitelist and DNS resolution
Response handling - ensure that the received response is as expected
Authentication on internal services
Input validation
Application should only be allowed to make requests to other applications it is allowed to.
Blacklists and whitelists don’t work that well bc the attacker could use an alternative ip representation or obfuscate the url, or use a # to indicate a url fragment.
You can also bypass SSRF if there is a open redirection vulnerability in the application.
stockApi=http://weliketoshop.net/product/nextProduct?currentProductId=6&path=http://192.168.0.68/admin
This SSRF exploit works because the application first validates that the supplied stockAPI URL is on an allowed domain, which it is. The application then requests the supplied URL, which triggers the open redirection. It follows the redirection, and makes a request to the internal URL of the attacker’s choosing.
Are there languages with built-in XSS protections?
Java: The Java Servlet Specification provides built-in protection against XSS attacks through the use of methods like HttpServletRequest#getParameter and Response#setContentType that automatically handle input validation and output encoding.
ASP.NET: ASP.NET provides protection against XSS attacks through features like Request Validation and AntiXSS Library. Request Validation automatically sanitizes user input, and the AntiXSS Library offers additional encoding and validation functions specifically designed to prevent XSS vulnerabilities.
Ruby on Rails: Ruby on Rails framework incorporates automatic output encoding by default, which helps mitigate XSS attacks. It encourages developers to use helper methods like h or html_safe to explicitly mark content as safe or escape unsafe content.
Django (Python): Django framework includes built-in XSS protection through its template system. By default, Django automatically escapes output when rendering templates, preventing the execution of injected scripts.
Express.js (Node.js): Express.js, a popular Node.js web application framework, provides security middleware like Helmet.js, which includes XSS protection features. Helmet.js sets appropriate headers, such as Content Security Policy (CSP) and X-XSS-Protection, to mitigate XSS attacks.
What IDOR?
Insecure Direct Object Reference occurs when a application exposes a reference to an internal implementation object. Allows for enumeration attacks.
To be exploited IDOR must be combined with an access control issue.
What are the different types of SQL injection attacks?
Blind SQL Injection - the application does not return the results of the SQL queries or the database errors that occur. Asks the database true or false questions.
- detect the difference in the application response based on the input (true or false - boolean based)
- trigger a time delay and inferring the truth of the condition based on the time it takes the application to respond (time-based)
- trigger an out of band network interaction
Second-Order SQLi - app takes user input and stores it. later when handling a different request, the app takes the stored input and incorporates it into a SQL query in an unsafe way.
UNION attacks - Union-based SQLi is an in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result which is then returned as part of the HTTP response.
Out-of-band SQLi - techniques would rely on the database server’s ability to make DNS or HTTP requests to deliver data to an attacker. Such is the case with Microsoft SQL Server’s xp_dirtree command, which can be used to make DNS requests to a server an attacker controls; as well as Oracle Database’s UTL_HTTP package, which can be used to send HTTP requests from SQL and PL/SQL to a server an attacker controls.
How do you prevent SQL injection attacks?
WAF rules for SQL injection
Parameterized queries (prepared statements) instead of string concatenation
- can be used for WHERE, INSERT, and UPDATE statements
- CANNOT be used to handle untrusted input in other parts of the query such as table name, column names, or ORDER BY clause (need to whitelist or use different logic)
- Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to distinguish between code and data, regardless of what user input is supplied. Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker
Validation / escaping
Least privilege
https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
Explain container escaping
Container escape is a security risk in which malicious players can leverage a containerized application’s vulnerabilities to breach its isolation boundary, gaining access to the host system’s resources.
Use safe images
Don’t run as root
Strong network policies
Patch and upgrade containers
How does buffer overflow work?
A buffer overflow condition exists when a program attempts to put more data in a buffer than it can hold or when a program attempts to put data in a memory area past a buffer.
Writing outside the bounds of a block of allocated memory can corrupt data, crash the program, or cause the execution of malicious code.
In a classic buffer overflow exploit, the attacker sends data to a program, which it stores in an undersized stack buffer. The result is that information on the call stack is overwritten, including the function’s return pointer. The data sets the value of the return pointer so that when the function returns, it transfers control to malicious code contained in the attacker’s data.
There’s also heap overflow, format string attack, etc.