Home SonarSource CodeAdvent Security Calendar 2021 Notes
Post
Cancel

SonarSource CodeAdvent Security Calendar 2021 Notes

Notes related to RipsTech/SonarSource CodeAdvent Security Calendar 2021.

Day 1

  • Line 13: The code registers a handler for message events and writes the event’s data directly into the DOM.

  • Vulnerability: This approach poses a security risk. Malicious websites can embed this page and send a message containing malicious code (XSS payload) that gets executed by the handler.

This challenge is based on Ghost CMS: https://www.sonarsource.com/blog/ghost-admin-takeover/

Day 2

  • Security Issue: The code uses os.path.join to combine user-provided data (img parameter) with a fixed path.

  • Vulnerability in os.path.join: According to the documentation, if any path segment in os.path.join starts with a forward slash (/), it’s treated as an absolute path, discarding everything before it.

  • Exploitation: A malicious user could send a request with img set to /etc/passwd. This absolute path would bypass the intended path construction and potentially allow access to the system’s password file!

This challenge is based on https://www.sonarsource.com/blog/10-unknown-security-pitfalls-for-python/

Day 3

  • Missing Security Check: The code lacks a check for the .phar extension, which is often interpreted as PHP by default Apache configurations.

  • Inherent Risk of Extension Blocklists: As discussed in our blog post about elFinder vulnerabilities, extension blocklists are often unreliable and can be bypassed.

This challenge is based on https://www.sonarsource.com/blog/elfinder-case-study-of-web-file-manager-vulnerabilities/

Day 4

  • Missing Content-Type Header: Files are stored without extensions, causing Apache to omit a Content-Type header in the response.

  • Browser Misinterpretation: Modern browsers often interpret files without a specified content type as HTML, leading to a potential Stored Cross-Site Scripting (XSS) vulnerability.

Day 5

Hint Given: PATH is ignored by execl, but several bug hunters already found that the command could be executed from the current working directory. Speaking of environment variables, can you think of another interesting one?

  • Insecure Environment Inheritance: The execl() function on line 16 inherits the environment variables from the parent process.
  • Potential for Privilege Escalation: Malicious actors could exploit this by setting environment variables like MODPROBE_OPTIONS to load arbitrary kernel modules, potentially leading to privilege escalation.
  • Mitigation: Always provide a clean environment to execl() to prevent unintended consequences.

Day 6

  • Vulnerable Bash Expansion: The code is susceptible to manipulation through bash expansion within the tar command. Example: An attacker could create a file named "-I touch shell" in the /opt/webapp directory. When executed by tar, the -I touch shell argument would be interpreted, potentially creating a file named “shell”.
  • Alternative Attack Methods: --checkpoint-action Argument: Replies suggest exploiting the --checkpoint-action argument for similar malicious purposes.
  • Filename Manipulation: Uploading filenames containing special characters like ; (semicolon) could also allow command injection.
  • Zip Slip Vulnerability: The vulnerability extends to potential Zip Slip attacks on the .tar archive format. Uploading a file with a specially crafted directory traversal path (e.g., ../../evil.sh) could lead to the extraction of malicious code outside the intended directory and its subsequent execution.

Day 7

  • DNS Rebinding Vulnerability: The code’s reliance on two separate DNS queries, first with Dns.GetHostEntry() and then with WebRequest, creates an opportunity for DNS rebinding attacks.
  • Attack Scenario: A malicious actor could exploit this by manipulating DNS responses to redirect the second WebRequest to a malicious server, even if the initial DNS query was validated against an allowlist.
  • Mitigation: To prevent this, always use the IP address obtained from the initial DNS query, rather than relying on a subsequent DNS lookup. This ensures that the request is sent to the intended server.

Day 8

  • Buffer Overflow Vulnerability: The server code on line 13 reads 16 bytes into a buffer without validating for null termination.
  • Data Exposure Risk: An attacker can exploit this vulnerability by sending a 16-byte input that doesn’t end with a null byte. This can cause the server to read and return additional data from adjacent memory locations, potentially including sensitive information.
  • Mitigation: The server code should strictly enforce input validation and bounds checking to prevent buffer overflows. This can be achieved by ensuring that the input data is properly null-terminated or by limiting the number of bytes read to a safe maximum.

Day 9

  • The regex at line 7 is correct in itself as it checks for the right characters.
  • The bug lies in the g flag:
    • It makes the regex object retain the last match index.
    • It will continue after that index when .test() is called again.
  • Attackers could still use quotes and perform SQL injection by sending their request two times in a row:
    • The second regex check will start after the quote.

Day 10

  • Vulnerability at line 9: Email address converted to uppercase before SQL query.
    • Issue: Unicode characters can map to the same uppercase version, causing different emails to appear identical.
  • Potential Attack:
    • Send password reset to a different email with a similar-looking address.
    • Example:
      • Original email: foo@mix.com
      • Attacker email (using a similar-looking Unicode character): foo@mıhttp://x.com/ (appears as FOO@MIX.com after uppercase conversion)
    • Consequence: Account takeover if successful.

Day 11

  • Issue with isPrivileged() function:
    • Always returns true due to the way integer casting to enums works.
    • Casting an integer to an enum never throws an exception, even if the integer doesn’t correspond to a defined enum member.
  • Solution:
    • Use PrivRoles.IsDefined((PrivRoles) role) to correctly check if the role is a defined enum value.

Day 12

  • Issue: External entity loading can be accidentally re-enabled in PHP 8.
    • Even with default settings, using LIBXML_NOENT can lead to unintended consequences.
    • LIBXML_NOENT does not disable external entity loading.

This challenge is based from https://www.sonarsource.com/blog/wordpress-xxe-security-vulnerability/

Day 13

Hint from SonarSource: There is a small typo in the challenge, please read filename.endsWith(“.xml”) instead of !filename.endsWith(“xml”); good catch @c4mxPwn

  • Vulnerability: Filename truncation and ineffective input sanitization.
    • Filenames are limited to 60 characters, bypassing extension checks with long filenames.
    • The .replace() function is used but its result is not assigned, making it ineffective.
  • Potential Attack:
    • Upload a malicious file with a long filename and a dangerous extension (e.g., .php).
    • The filename will be truncated, but the server might still process the file based on its actual content.

This challenge is based from https://www.sonarsource.com/blog/mybb-stored-xss-to-rce/

Day 14

  • Vulnerability: ToCToU race condition in file access.
    • Checks for file existence can be bypassed by creating a symlink before the file is opened.
  • Potential Attack:
    • Attacker creates a symlink to a different file or directory. e.g. /tmp/logs.txt right before the call to fopen()
    • The application opens the symlink, leading to unintended file operations.
  • Mitigation Strategies:
    • Use restrictive file permissions to limit access to sensitive directories.
    • Employ file descriptors instead of paths for operations like fstat to reduce the window for race conditions.

Day 15

  • Vulnerability: Prototype Pollution in line 12 (ejs templating engine).
    • When type is set to "__proto__" and id and content are provided, it allows modification of Object.prototype.
    • This can affect all existing and newly created objects, leading to unintended behavior.
  • Example (Kibana vulnerability): https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/
  • Mitigation:
    • Use Object.create(null) to create new objects without inherited attributes.
  • Challenge: Discover a payload leading to code execution in recent ejs versions.
  • Potential Attack (Solution by @jorge_ctf):
    • Set type to "__proto__".
    • Set id to "client" (truthy value).
    • Set content to a JavaScript payload that will be executed during template rendering.

Day 16

  • Vulnerability: Unreliable assertion in user deletion logic.
    • assert statements are ignored in optimized Python code (PYTHONOPTIMIZE, -O).
  • Impact:
    • Any user can delete other users, bypassing authorization checks.
  • Mitigation:
    • Replace assert with a robust authorization check that is always executed, regardless of optimization flags.
    • Consider using a more secure language or framework that enforces strong security principles.

Day 17

  • Vulnerability: Unsanitized object deserialization in PHP.
    • PHP supports two serialization formats (O: and C:).
    • The C: format is not properly handled by the blocklist.
  • Potential Impact:
    • Arbitrary object deserialization could lead to various security issues, including remote code execution (RCE) under specific conditions.
  • Mitigation:
    • Implement strict input validation and filtering for serialized data.
    • Consider using a more secure serialization format or library that provides better protection against vulnerabilities.
    • Regularly update PHP and frameworks to address known vulnerabilities.

Day 18

  • Vulnerability: Command Injection via FastJSON Deserialization.
    • FastJSON invokes setters of deserialized objects during parsing.
    • Malicious JSON data can trigger command execution through vulnerable setters.
  • Attack Vector:
    • Crafting a specific JSON payload to exploit the CSRFToken class’s behavior.
    • Leveraging the chain of object instantiation and method calls to execute arbitrary commands.
  • Mitigation:
    • Avoid using vulnerable libraries like FastJSON.
    • Implement strict input validation and sanitization for all deserialized data.
    • Consider using safer deserialization libraries or frameworks that provide protection against such attacks.

Day 19

  • Vulnerability: Missing Signature Verification in JWT Processing.
    • The code at line 10 processes the JWT token but fails to verify its digital signature.
  • Impact:
    • Attackers can forge valid-looking JWT tokens without the correct secret key.
    • This allows unauthorized users to impersonate legitimate users and gain access to protected resources.
  • Mitigation:
    • Implement robust JWT signature verification using the appropriate secret key.
    • Ensure that the verification process is performed before granting user access.
    • Consider additional security measures like token expiration, revocation, and rate limiting to further enhance protection.

Challenge based on https://rules.sonarsource.com/python/RSPEC-5659/

Day 20

  • Windows Execution Context:
    • When a command is executed by name (e.g., img-converter) on Windows, the OS searches for the executable in the following order:
      1. Current directory
      2. System PATH
  • Exploit Scenario:
    • An attacker can upload a malicious file named img-converter.exe to the target directory.
    • When the application attempts to execute the img-converter command within this directory, the malicious executable is executed instead of the legitimate one.
  • Potential Impact:
    • Remote Code Execution (RCE): The malicious code within the uploaded file can gain control over the system, allowing the attacker to execute arbitrary commands.

Day 21

  • Path Traversal Sanitization:
    • The application sanitizes file paths to prevent Path Traversal attacks.
    • The sanitization process removes two consecutive dots (..) from the filename.
    • However, backslashes () are removed from the filename after this step.
  • Exploit Scenario:
    • An attacker can craft a malicious filename like .\./.\.shell.jsp.
    • After sanitization, the filename becomes ../../shell.jsp.
    • This allows the attacker to access files outside the intended directory.
  • Potential Impact:
    • File Access and Manipulation: The attacker can read, write, or delete files on the server.
    • Remote Code Execution (RCE): If the server allows the execution of certain file types (e.g., JSP), the attacker could upload a malicious script and execute it remotely.

Day 22

  • SQL Injection:
    • The application uses the addslashes() function to sanitize user input.
    • However, the sanitized input is not enclosed in quotes when inserted into the SQL query.
    • This allows attackers to inject malicious SQL code.
  • Shell Injection:
    • The application executes external shell commands using the user-provided input.
    • The input is not properly escaped, making it vulnerable to shell injection attacks.
  • Exploit Scenario:
    • An attacker can craft a payload like 1--$(id>foo):
      • The addslashes() function will sanitize the input but won’t prevent SQL injection due to the lack of quotes.
      • The shell command will execute the malicious payload, leading to RCE.
  • Potential Impact:
    • Database Compromise: Attackers can access, modify, or delete sensitive data.
    • Remote Code Execution (RCE): Attackers can gain control over the server and execute arbitrary commands.

Day 23

  • Format String Vulnerability:
    • The syslog() function in C is designed to log messages with formatted strings.
    • However, the second argument in this case is not a format string but rather arbitrary user-controlled input.
    • This can lead to format string vulnerabilities, allowing attackers to exploit the function’s behavior to execute arbitrary code or read sensitive memory.
  • Compiler Warnings:
    • While some compilers (like GCC with the -Wformat-security flag) can detect potential format string vulnerabilities, this may not be the case for all compilers or libraries used in the project.
  • Potential Impact:
    • Remote Code Execution (RCE): Attackers can exploit the vulnerability to execute arbitrary code on the system.
    • Information Disclosure: Attackers can read sensitive memory contents, including passwords, encryption keys, or other confidential data.

Challenge based from https://www.youtube.com/watch?v=MBz5C9Wa6KM

Day 24

Vulnerability Description:

  • SSRF via Java URI.resolve() and OkHttp
    • Component: Java URI.resolve() method
    • Behavior: This method returns its parameter unchanged if it’s already an absolute URL.
    • Exploit:
      • An attacker can provide a crafted URL like http:/example.com#.
      • URI.resolve() will treat it as an absolute URL due to the leading protocol scheme (http:) and fragment (#).
    • Vulnerable Library: OkHttp library accepts the crafted URL when making the request.
  • Potential Impact:
    • Server-Side Request Forgery (SSRF): The attacker can trick the application into making unauthorized requests to internal servers or external resources.
    • Depending on the application’s configuration and permissions, this could allow attackers to:
      • Leak sensitive information from internal systems.
      • Perform Denial-of-Service (DoS) attacks on internal or external resources.
      • Execute arbitrary code on the server (if the server allows code execution from the requested resource).
This post is licensed under CC BY 4.0 by the author.