Basics Flashcards

1
Q

What are XSS attacks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you mitigate XSS attacks?

A
  1. 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
  2. CSP - Enforce a whitelist of trusted sources. CSP helps mitigate XSS attacks by blocking the execution of scripts from unauthorized sources
  3. XSS Protection Headers
  4. Secure Development Practices - avoid using eval() and unsafe functions. Utilize frameworks and libraries that have built-in security controls.
  5. Session Cookie security - Mark cookies as “secure”. Helps with session theft.
  6. 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are some consequences of XSS attacks?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are CSRF attacks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you mitigate CSRF attacks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you bypass CSRF mitigations?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are open redirects?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are insecure deserialization attacks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you prevent insecure deserialization attacks?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the 3 different types of XSS attacks?

A
  1. 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.
  2. 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.
  3. 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Explain step-by-step how XSS works.

A
  1. Vulnerable Web Application: a web application fails to properly sanitize/validate user input before displaying it on a web page.
  2. Malicious Payload Injection: An attacker takes advantage of this and injects malicious input into the application.
  3. 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.
  4. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is SQL injection?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you prevent SQL injection attacks?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is SSRF?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you prevent SSRF attacks?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Are there languages with built-in XSS protections?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What IDOR?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are the different types of SQL injection attacks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you prevent SQL injection attacks?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Explain container escaping

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How does buffer overflow work?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How can you prevent buffer overflows?

A

ASLR - Address Space Layout Randomization
Stack Canary
Bounds checking
Use a memory safe language
Use safe functions
Non-executable stacks (DEP - data execution prevention)
Source code audit

23
Q

How does HTTP handle state?

A

It doesn’t, of course. Not natively. Good answers are things like “cookies”, but the best answer is that cookies are a hack to make up for the fact that HTTP doesn’t do it itself.

24
Q

What is a path traversal vulnerability? How do you prevent it?

A

A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the web root folder. By manipulating variables that reference files with “dot-dot-slash (../)”

Don’t store sensitive files in the web root
Ensure user cannot supply all parts of the path
Validate user input
Restrict where files can be obtained/saved

25
Q

What is a side-channel attack (Spectre and Meltdown)?

A

Is an attack based on extra information that can be gathered because of the fundamental way a computer protocol or algorithm is implemented, rather than flaws in the design of the protocol or algorithm itself.
For example, timing information, power consumption, sound, etc.
A cache side-channel attack works by monitoring security critical operations such as AES T-table entry or modular exponentiation or multiplication or memory accesses. The attacker can then recover the secret key depending on the accesses made or not made by the victon, which allows them to deduce the encryption key. It does not create a fault in the ongoing cryptographic operation and is invisible to the victim.
Meltdown and Spectre were two CPU vulnerabilities in 2017. They used cache based side channel to allow an attacker to leak memory contents of other processes and the operating system itself.

26
Q

What is certificate pinning?

A

Certificate pinning is the process of associating a host with their expected X.509 certificate or public key. Once a certificate or public key is known for a host, it is associated or “pinned” to the host.
The certificate can be added to an application at development time or added upon first encountering the certificate or public key. Adding at development time is preferred. It means the attacker won’t be able to taint the pin.
If you connect to google.com and the certificate presented is not the pinned one, then the connection will be blocked.
You lose the ability to respond to needing to make certificate changes, since the previous version of the certificate is pinned.
A bogus certificate could get pinned and remain until the pin expires.

27
Q

What is WAF? Name one WAF solution.

A

WAF stands for web application firewall. It helps protect applications by filtering and monitoring HTTP traffic between the web application and the Internet. Typically protects from CSRF, XSS, file inclusion, SQL injection, etc. It is a protocol level 7 defense. A WAF is a type of reverse-proxy, protecting the server from exposure by having clients pass through the WAF before reaching the server.
WAF operates through a set of rules called policies. Policies can be quickly implemented to respond to an attack. Can operate on a blocklist or an allowlist.
A WAF can be implemented 3 different ways:
Network based WAF: generally hardware based. They are installed locally and minimize latency. Usually require maintenance of physical equipment and are the most expensive.
Host based WAF: may be fully integrated into an application’s software. Less expensive and more customizable. Consumes local server resources, implementation complexity, and maintenance costs. Typically requires engineering time. Host based like using ufw?
Cloud based WAF: usually a monthly cost. Usually consistently updated without any work required from the user. Have to hand over some responsibility to a third party (blackbox as to the implementation)

Popular WAF solution: Cloudflare.

28
Q

Explain DDOS attacks

A

A DDOS(Distributed Denial of Service) attack is a cyberattack that causes the servers to refuse to provide services to genuine clients. DDOS attack can be classified into two types:

Flooding attacks: In this type, the hacker sends a huge amount of traffic to the server which the server can not handle. And hence, the server stops functioning. This type of attack is usually executed by using automated programs that continuously send packets to the server.
Crash attacks: In this type, the hackers exploit a bug on the server resulting in the system to crash and hence the server is not able to provide service to the clients.
You can prevent DDOS attacks by using the following practices:

Use Anti-DDOS services
Configure Firewalls and Routers
Use Front-End Hardware
Use Load Balancing
Handle Spikes in Traffic

29
Q

What are some common types of DDoS attacks?

A

The most common DDoS attacks = UDP reflection and SYN floods, which are both infrastructure layer attacks. UDP is a network layer attack. SYN floods are a transport layer attack.

Layer 3 attacks do not have to open up a TCP connection first and do not target a specific port (layer 3 is connectionless). Layer 3 is where routing across the Internet takes place. The most important protocol for this process is IP.

UDP Reflection Attack - takes advantage of the fact that UDP is a stateless protocol. The attacker spoofs the target’s IP address as the UDP source IP. The attacker sends the spoofed packet to an intermediate server. The intermediate server is tricked into sending its UDP response to the target server. The intermediate server is used because it generates a response many times larger than the request packet. The amplification ratio varies depending on the protocol the attacker uses.

SYN Flood Attack - not about volume, but about taking up available server connections so that no resources are available for legitimate users. A malicious client sends a large number of SYN packets to a target, but never sends the final ACK packet to complete the handshake. The server is left waiting for a response to the half-open connections and eventually runs out of capacity to accept new connections.

In an HTTP flood attack, an attacker sends HTTP requests that appear to be from a real user of the web application. Some HTTP floods target a specific resource, while more complex HTTP floods attempt to emulate human interaction with the application.

Application layer attacks can also target domain name system (DNS) services. The most common of these attacks is a DNS query flood in which an attacker uses many well-formed DNS queries to exhaust the resources of a DNS server.

Ping flood - the attacker sends a huge number of ping requests at once to overwhelm the server

30
Q

How do you mitigate DDoS attacks?

A

AWS Shield
Detect traffic anomalies - determine a baseline first
AWS WAF - for application layer protection
Set ACLs based on rules
Block certain request signatures
Block the IP addresses of bad actors
Cloudfront - leveraging edge locations
Overprovisioning capacity
Use larger size instances
Autoscaling
Elastic Load Balancing
Reduce the attack surface*
Put instances behind an ELB
Security groups
Make instances not publicly accessible
Amazon API Gateway to protect API endpoints
Caching
Rate limiting

CDN - Cloudflare
DDoS protection systems (disperse traffic)
WAF
Captcha

31
Q

Go over some basics of JWT security.

A

Can exchange information “claims”
HMAC takes a header, payload, and a secret key to produce a unique signature
the server uses the same key to validate the HMAC of the JWT
Reject it if it does not match
You can also use asymmetric encryption. Sign with private key. Validate using public key. This allows services to not all have access to the private key. Only the issuer of the JWT has access to the private key. This prevents services from forging valid JWTs.
Asymmetric encryption version in OpenID Connect
Stateless session management, no session cookies
Once configured, backend doesn’t need to talk to authorization server
Header - with algorithm
Payload - with claims
And JWT signature
validate to verify there was no tampering
The token content is in plaintext - don’t put secrets or sensitive information in the claim
JWT token cannot be invalidated by itself
stateless backends need to be careful about token lifetimes
On logout can try to keep a Redis store of invalidated JWTs
Validate the header to only allow certain algorithms
Validate the payload
expiration time

Prevent token sidejacking:
A way to prevent it is to add a “user context” in the token. A user context will be composed of the following information:
A random string that will be generated during the authentication phase. It will be sent to the client as an hardened cookie (flags: HttpOnly + Secure + SameSite + Max-Age + cookie prefixes). Avoid setting expires header so that the cookie is cleared when the browser is closed. Set Max-Age to a value smaller or equal to the value of JWT token expiry, but never more.
A SHA256 hash of the random string will be stored in the token (instead of the raw value) in order to prevent any XSS issues allowing the attacker to read the random string value and setting the expected cookie.

32
Q

What is a honeypot? What type of attack does it defend against?

A

It’s a trap for hackers essentially. It’s a server/network intended to attract cybersecurity threats. It uses the attackers intrusion attempts to learn about their operations or distract from other targets. They mimic a real computer system and application. They’re made attractive by adding in security vulnerabilities.
Email traps: email address found only by harvesters to attack phishing attempts.
Decoy database.
Spider honeyspot - designed to attract crawlers. Can help to detect any crawlers.
Risk - if misconfigured, the honeypot could allow the hacker into your system. Bad information can be fed to the honeypot or the honeypot could be used to distract from a real attack.

33
Q

What technologies and approaches are used to secure information and services deployed on cloud computing infrastructure?

A

Utilize the tools provided by the cloud computing provider. Like config analysis tools, logging tools, GuardDuty, monitoring. Encryption at rest and in transit. Monitoring and logging. Alerts. Threat intel reports. Audit access. Control access through an identity and access management platform. Use a DLP tool.

34
Q

How do parameterized queries and prepared statements work?

A
  1. Parameterized queries:

In a parameterized query, placeholders or parameters are used in the SQL code instead of directly inserting user input.
The SQL query is constructed with placeholders, typically using a special syntax provided by the programming language or database library. For example, instead of directly including a user’s name in the query, a placeholder like ? or :name is used.
The query is then prepared by the database engine, which parses and compiles the query without specific parameter values. The structure and logic of the query are determined at this stage.
When executing the query, the actual parameter values are provided separately, binding them to the corresponding placeholders in a secure manner.
The database engine handles the parameter values as data, eliminating the risk of SQL injection as the values are not interpreted as executable code.

  1. Prepared statements:

Prepared statements follow a similar concept but are typically implemented at the database level.
The SQL query is prepared and compiled by the database server with placeholders representing parameters.
The prepared statement is then sent to the database server, where it is stored in a compiled state.
When executing the prepared statement, the actual parameter values are provided and bound to the placeholders. The database server ensures that the bound values are treated as data, preventing SQL injection vulnerabilities.
Prepared statements can be reused multiple times with different parameter values, providing performance benefits as the query does not need to be recompiled each time.

35
Q

Docker Security

A
  • Keep host and Docker up-to-date
  • Do not expose the Docker daemon socket (even to the containers) - exposing un-encrypted and unauthenticated direct access to the Docker daemon, if the host is internet connected this means the docker daemon on your computer can be used by anyone from the public internet (Docker socket /var/run/docker.sock is the UNIX socket that Docker is listening to. This is the primary entry point for the Docker API. The owner of this socket is root)
  • set an unprivileged user to prevent privilege escalation attacks
  • limit capabilities
  • Always run your docker images with –security-opt=no-new-privileges in order to prevent escalate privileges using setuid or setgid binaries.
  • Disable inter-container communication (–icc=false)
  • use seccomp
  • limit resources to prevent DoS
  • set filesystem and volumes to read only
36
Q

SQL Injection Impact

A

An unintended data enters a program from an untrusted source.
The data is used to dynamically construct a SQL query

Get sensitive data, corrupt a database
DoS

37
Q

Preventing automated login attempts

A
  1. 2FA - codes, security key
  2. Login throttling
  3. CAPTCHA
38
Q

Authentication protocols that require no password

A
  1. OAuth
  2. OpenID
  3. SAML
  4. FIDO
39
Q

DOM XSS Prevention

A
  1. HTML escape javascript before inserting untrusted data into the HTML subcontext within the execution context
  2. Javascript escape before inserting untrusted data into HTML attribute subcontext within the execution context
  3. Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts within an Execution Context
  4. JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext within the Execution Context
  5. URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext within the Execution Context
  6. Populate the DOM using safe JavaScript functions or properties
  7. The best way to fix DOM based cross-site scripting is to use the right output method (sink). For example if you want to use user input to write in a div tag element don’t use innerHtml, instead use innerText or textContent. This will solve the problem, and it is the right way to re-mediate DOM based XSS vulnerabilities.
40
Q

Database security

A

Transport layer protection
- only allow encrypted connections
- use trusted digital certificate on the server

Authentication
- one account per service
- account management process periodically

Storing database credentials
- Vault

Logs

Least privilege for permissions

41
Q

DoS prevention

A

setting limits
avoiding single points of failure
threading
WAF
CDN
Rate limiting
Validation -file size, etc.
Handle exceptions

42
Q

What is a JWT?

A

JSON Web Token is used to carry information related to the identity and characteristics (claims) of a client. This information is signed by the server (using the HMAC algorithm) in order for it to detect whether it was tampered with after sending it to the client. This will prevent an attacker from changing the identity or any characteristics.

This token is created during authentication (is provided in case of successful authentication) and is verified by the server before any processing. This is stateless.

Token Structure:
[Base64(HEADER)].[Base64(PAYLOAD)].[Base64(SIGNATURE)]

Store the token using the browser sessionStorage container, or use JavaScript closures with private variables
Add it as a Bearer HTTP Authentication header with JavaScript when calling services.
Add fingerprint information to the token.

43
Q

How to prevent OS Command injection?

A
  1. avoid calling OS commands directly
    - use built-in library functions
  2. escape values added to OS commands for specific OS
  3. Parameterization in conjunction with Input Validation
  4. run application using lowest required privileges
44
Q

What is pinning?

A

Pinning is the process of associating a host with their expected X509 certificate or public key. Once a certificate or public key is known or seen for a host, the certificate or public key is associated or ‘pinned’ to the host.

A host or service’s certificate or public key can be added to an application at development time, or it can be added upon first encountering the certificate or public key.

Pinning the root CA is generally not recommended since it highly increases the risk because it implies also trusting all its intermediate CAs.
Pinning a specific intermediate CA reduces the risk but the application will be also trusting any other certificates issues by that CA, not only the ones meant for your application.
Pinning a leaf certificate is recommended but must include backup (e.g. intermediate CA). It provides 100% certainty that the app exclusively trusts the remote hosts it was designed to connect to.

45
Q

What are some cookie security features?

A

Secure cookie attribute - only send cookies using encrypted HTTPS connection

HttpOnly attribute - cookie attribute instructs web browsers not to allow scripts (e.g. JavaScript or VBscript) an ability to access the cookies via the DOM document.cookie object. This session ID protection is mandatory to prevent session ID stealing through XSS attacks. However, if an XSS attack is combined with a CSRF attack, the requests sent to the web application will include the session cookie, as the browser always includes the cookies when sending requests.

Samesite cookie attribute - SameSite defines a cookie attribute preventing browsers from sending a SameSite 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 cookie attribute - instructs web browsers to only send the cookie to the specified directory or subdirectories (or paths or resources) within the web application.

It is recommended to use a narrow or restricted scope for these two attributes. In this way, the Domain attribute should not be set (restricting the cookie just to the origin server) and the Path attribute should be set as restrictive as possible to the web application path that makes use of the session ID.

Expire and Max-Age Attributes - it will be considered a persistent cookie and will be stored on disk by the web browser based until the expiration time.

46
Q

Third Party Javascript Managment

A

Tags, aka marketing tags, analytics tags etc. are small bits of JavaScript on a web page.

Third party vendor JavaScript tags (hereinafter, tags) can be divided into two types:
User interface tags.
Analytic tags.

The invocation of third-party JS code in a web application requires consideration for 3 risks in particular:
1. The loss of control over changes to the client application,
2. The execution of arbitrary code on client systems,
The disclosure or leakage of sensitive information to 3rd parties.

The best way to make the generated code secure is to confine it to getting DOM data from a host defined data layer.
This is a secure technique because only your JavaScript executes on your users browser, and only the data you decide on is sent to the vendor. The data layer can perform any validation of the values, especially values from DOM objects exposed to the user like URL parameters and input fields, if these are required for the marketing analysis.

Sandboxing Content
Both of these tools be used by sites to sandbox/clean DOM data.
DOMPurify is a fast, tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks.
MentalJS is a JavaScript parser and sandbox. It allow-lists JavaScript code by adding a “$” suffix to variables and accessors.

Subresource Integrity will ensure that only the code that has been reviewed is executed. The developer generates integrity metadata for the vendor javascript, and adds it to the script element like this:

You can also put vendor JavaScript into an iframe from different domain (e.g. static data host). It will work as a “jail” and vendor JavaScript will not have direct access to the host page DOM and cookies.

The host main page and sandbox iframe can communicate between each other via the postMessage mechanism.

47
Q

List some preventions for XML external entity injection (XXE).

A
  1. Disable external entities completely
  2. Be careful of having certain options defined
  3. Use XML parsers carefully using secure configs
48
Q

List some XML parsing issues

A

XXE injection can be used for sensitive file retrieval, SSRF, and CPU overload

49
Q

How do you prevent clickjacking?

A

Clickjacking, also known as a “UI redress attack”, is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the top level page. Thus, the attacker is “hijacking” clicks meant for their page and routing them to another page, most likely owned by another application, domain, or both.

  1. Sending the proper Content Security Policy (CSP) frame-ancestors directive response headers that instruct the browser to not allow framing from other domains. The older X-Frame-Options HTTP headers is used for graceful degradation and older browser compatibility.
  2. Properly setting authentication cookies with SameSite=Strict (or Lax), unless they explicitly need None (which is rare).
  3. Employing defensive code in the UI to ensure that the current frame is the most top level window.
  4. Use the sandbox attribute of an iframe for untrusted content.
50
Q

List some LDAP injection prevention

A

LDAP Injection is an attack used to exploit web based applications that construct 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.

LDAP injection attacks could result in the granting of permissions to unauthorized queries, and content modification inside the LDAP tree.

  1. Escape all variables using the right LDAP encoding function
  2. Use Frameworks that Automatically Protect from LDAP Injection
51
Q

List some ways to ensure SAML security

A

The Security Assertion Markup Language (SAML) is an open standard for exchanging authorization and authentication information.

  1. Validate protocol usage. Require the following elements:
    - AuthnRequest(ID, SP): An AuthnRequest must contain and ID and SP. Where ID is a string uniquely identifying the request and an SP identifies the Service Provider that initiated the request. Furthermore, the request ID attribute must be returned in the response
    - Response(ID, SP, IdP, {AA} K -1/IdP): A Response must contain all these elements. Where ID is a string uniquely identifying the response. SP identifies the recipient of the response. IdP identifies the identity provider authorizing the response. {AA} K -1/IdP is the assertion digitally signed with the private key of the IdP.
    - AuthAssert(ID, C, IdP, SP): An authentication assertion must exist within the Response. It must contain an ID, a client (C), an identity provider (IdP), and a service provider (SP) identifier.

Validate signatures

52
Q

What is prototype pollution?

A

Prototype pollution is a JavaScript vulnerability that enables an attacker to add arbitrary properties to global object prototypes, which may then be inherited by user-defined objects.

If the application subsequently handles an attacker-controlled property in an unsafe way, this can potentially be chained with other vulnerabilities. In client-side JavaScript, this commonly leads to DOM XSS, while server-side prototype pollution can even result in remote code execution.

Prototype pollution vulnerabilities typically arise when a JavaScript function recursively merges an object containing user-controllable properties into an existing object, without first sanitizing the keys. This can allow an attacker to inject a property with a key like __proto__, along with arbitrary nested properties.
Due to the special meaning of __proto__ in a JavaScript context, the merge operation may assign the nested properties to the object’s prototype instead of the target object itself. As a result, the attacker can pollute the prototype with properties containing harmful values, which may subsequently be used by the application in a dangerous way.

53
Q

How does TOTP work?

A