Under the Hacker’s Hood: JSON Injection in NFT Metadata

A Guide to Understanding and Preventing Data Exploits

Stuart
Zokyo_io
9 min readMar 25, 2024

--

The intersection of Web2 vulnerabilities within the Web3 ecosystem is a growing concern, especially as we delve deeper into the nuances of NFT metadata. This article will unravel the complexities of JSON Injection, shed light on its impact on NFT metadata, and provide actionable strategies to shield against such vulnerabilities.

Contents

What is JSON Injection?
Types of JSON Injection
Server-Side JSON Injection Example
Client-Side JSON Injection Example
JSON Injection in NFTs
What an attacker can do
Vulnerability Example: SVG Injection in “ArtGallery”
How To Mitigate
Conclusion
Additional Reading

What is JSON Injection?

Before delving into the specifics of JSON Injection, it’s crucial to establish a foundational understanding of JSON.

JSON (JavaScript Object Notation) is a lightweight data format designed for data interchange between applications. It is derived from JavaScript, making it highly readable and easy to use within the web’s most popular programming language. JSON operates as a string for efficient data transmission across networks and requires conversion to a native JavaScript object for data manipulation. Its simplicity and efficiency have made JSON a widely adopted standard for web applications, especially in RESTful APIs and AJAX applications, for transmitting data, including sensitive information like authentication credentials.

An object is an unordered set of name/value pairs. An object begins with ‘{‘ (left brace) and ends with ‘}’ (right brace). Each name is followed by ‘:’ (colon), and the name/value pairs are separated by ‘,’ (comma).

JSON injection is a type of cyber-attack where an attacker injects malicious code into JSON data streams to alter the normal execution of web applications. This can result in data loss, data modification, or denial of service, making it a significant security risk.

Types of JSON Injection

  • Server-Side JSON Injection: This occurs when unsanitized data from an untrusted source is directly written to a JSON stream by the server. An attacker manipulates input fields such as username or password without sanitization, appending data to elevate privileges or altering the JSON data structure.
  • Client-Side JSON Injection: This happens when unsanitized data from an untrusted JSON source is parsed using the JavaScript eval function. An attacker injects malicious code that is executed when JSON data is parsed with eval(), potentially leading to Cross-Site Scripting (XSS) or other malicious outcomes.

To illustrate the concept of JSON injection, we will demonstrate both server-side and client-side JSON injection attacks.

Server-Side JSON Injection Example

Scenario:

A web application stores user data in a JSON string, which includes information such as username and password. The application constructs this JSON string from user input without proper validation or sanitization.

// PHP code simulating the server-side creation of a JSON string from user input
$userInput = $_GET['username']; // User input from a GET request
$passwordInput = $_GET['password']; // Password input from a GET request
$jsonString = '{"username":"' . $userInput . '", "password":"' . $passwordInput . '"}';

Attack Vector:

An attacker manipulates the username input by appending additional JSON fields or altering existing ones. For example, the attacker inputs the following as the username:

admin", "role": "administrator

Resulting JSON String:

{
"username": "admin", "role": "administrator", "password": "attacker's password"
}

By injecting additional JSON fields, the attacker can potentially elevate their privileges within the application or alter its behavior.

Client-Side JSON Injection Example

Scenario:

A web application fetches user profile data in JSON format from an API and displays it on the webpage. The application uses JavaScript’s eval() function to parse the JSON data.

Example Code:

// JavaScript code to fetch and display user profile data
fetch('https://example.com/api/user/profile')
.then(response => response.text())
.then(data => {
var userProfile = eval("(" + data + ")");
document.getElementById("username").innerText = userProfile.username;
document.getElementById("role").innerText = userProfile.role;
});

Attack Vector:

An attacker has managed to inject malicious content into the user’s profile data stored on the server. The malicious data includes a script execution as part of the role field:

{
"username": "victim",
"role": "user"); alert('XSS Attack!'); ("
}

Execution:

When the application fetches and processes this malicious JSON data, the eval() function executes the injected script, resulting in an XSS attack. This demonstrates how client-side JSON injection can be exploited to execute arbitrary JavaScript in the context of the user's session.

JSON Injection in NFTs

Non-Fungible Tokens (NFTs) have become a cornerstone of digital asset verification and ownership within the blockchain ecosystem. NFT metadata plays a critical role, as it describes the unique attributes and properties of the NFT, often stored in JSON format. However, this also opens up a potential vulnerability known as JSON Injection.

NFT metadata serves as the descriptive layer of information for non-fungible tokens, detailing attributes such as name, description, and image links. It is crucial for identifying, authenticating, and providing additional context about the digital asset represented by an NFT. Stored either on-chain, directly within the blockchain, or off-chain, through external storage solutions like IPFS, metadata ensures the uniqueness and value preservation of NFTs. Furthermore, metadata facilitates a variety of applications, from transactional details to asset provenance, enhancing the utility and interoperability of NFTs across different platforms and use cases.

Consider a blockchain project called “ArtChain,” which allows artists to mint NFTs representing their artwork. Each NFT’s metadata includes the artwork’s name, description, and a link to an image stored on IPFS (InterPlanetary File System).

Vulnerability Example: An artist named Alice decides to mint an NFT for her latest painting, “Sunset Bliss.” The application allows Alice to input the metadata, which is then converted into a JSON string for storage. However, the application fails to sanitize the inputs properly.

Alice enters the following data:

  • Name: “Sunset Bliss”
  • Description: “An evocative landscape painting capturing the serene beauty of a sunset.”
  • Image URL: “ipfs://validImageLink”

However, an attacker, Bob, sees an opportunity to exploit the JSON Injection vulnerability. He crafts a malicious input for the image URL field:

  • Image URL: "ipfs://validImageLink", "additionalField": "maliciousContent"

When Bob mints his NFT, the unsanitized input results in the following JSON metadata:

{
"name": "Malicious Art",
"description": "This is just a sample.",
"image": "ipfs://validImageLink",
"additionalField": "maliciousContent"
}

What an attacker can do

  1. Mimic or Clone NFTs: An attacker could create counterfeit NFTs by injecting malicious JSON data to copy the name or other attributes of legitimate NFTs, misleading users and potentially damaging the credibility of the NFT marketplace.
  2. Alter NFT Metadata: Through JSON injection, attackers might change critical metadata of an NFT, such as the name, description, or associated digital assets (e.g., images, videos), thus altering the perceived value or authenticity of the NFT.
  3. Redirect to External URLs: By injecting malicious URLs into JSON data, attackers could redirect users to phishing sites or other malicious web pages, potentially leading to further exploitation.
  4. Execute Cross-Site Scripting (XSS) Attacks: If JSON data is improperly handled and includes executable JavaScript, attackers might trigger XSS attacks, compromising user sessions or stealing sensitive information.
  5. Steal Cryptocurrency or Assets: If the front-end application improperly processes JSON data, such as using eval() to parse token URIs, attackers could execute malicious code leading to the theft of cryptocurrency or digital assets from users' wallets.
  6. Replace Digital Assets: Attackers could exploit JSON injection vulnerabilities to replace digital assets associated with NFTs, such as images or animations, with arbitrary content after the voting or verification stage, thereby misrepresenting the NFT’s content.
  7. Gain Unauthorized Access or Privileges: By manipulating JSON data, attackers can potentially elevate their privileges within an application, gaining unauthorized access to sensitive information or functionalities.
  8. Manipulate Application Behavior: Injecting malicious JSON can alter the normal execution of an application, leading to unintended behaviors that could disrupt services or expose vulnerabilities for further exploitation.
  9. Trigger Denial of Service (DoS): In some cases, JSON injection could be used to overload systems or corrupt data, leading to denial of service and making the application unavailable to legitimate users.
  10. Compromise System Integrity: JSON injection vulnerabilities can be a stepping stone for attackers to compromise the overall integrity of a system, leading to a full system compromise in severe cases.

That’s not all. We have SVG Injection too!!

To demonstrate SVG injection in smart contracts with a new example, let’s consider a blockchain platform called “ArtGallery,” which allows artists to mint NFTs of their artworks. Each NFT contains metadata, including an SVG image that represents the artwork on various marketplaces and galleries.

Vulnerability Example: SVG Injection in “ArtGallery”

Scenario:

“ArtGallery” allows artists to define custom SVG images for their NFTs. The smart contract does not sanitize the SVG content, assuming that the input is benign.

Smart Contract Code Snippet (Vulnerable):

pragma solidity ^0.8.0;
contract ArtGalleryNFT {
mapping(uint256 => string) public tokenSVGs;
function mintArtwork(uint256 tokenId, string memory svgImage) public {
// Directly storing the SVG image without sanitization
tokenSVGs[tokenId] = svgImage;
}
function getTokenSVG(uint256 tokenId) public view returns (string memory) {
return tokenSVGs[tokenId];
}
}

Attack Vector:

An attacker, Eve, mints an NFT with a malicious SVG image containing JavaScript code. The SVG is crafted as follows:

<svg xmlns="http://www.w3.org/2000/svg">
<script type="text/javascript">
alert('Your session is hijacked!');
</script>
</svg>

Eve calls mintArtwork with the malicious SVG, which is then stored associated with the NFT.

Impact:

When a user views this NFT on any platform that does not properly sanitize SVG content, the embedded JavaScript executes, leading to potential XSS attacks. This can result in session hijacking, phishing, or other malicious activities.

How To Mitigate

  1. Encode User Inputs: Ensure that user inputs are properly encoded to prevent alteration of the returned JSON data. This restricts attackers from injecting malicious content.
  2. Escape JSON Strings: Implement a function to escape strings for safe inclusion within double-quotes in JSON. This involves replacing or escaping characters like ", {, }, [, ], and control characters to prevent JSON structure manipulation. Use Solady’s escapeJSON: https://github.com/Vectorized/solady/blob/9deb9ed36a27261a8745db5b7cd7f4cdc3b1cd4e/src/utils/LibString.sol#L1001C1-L1060C6
  3. Sanitize SVG Content: Use sanitization functions to clean SVG inputs, ensuring that characters with special meanings in SVG, such as <, are escaped or removed. This prevents the injection of malicious SVG content.
  4. Validate Inputs Off-Chain: Before processing, carefully evaluate all inputs off-chain for invalid characters or patterns that could lead to injection attacks. Suspicious or malformed requests should be rejected or flagged for manual review.
  5. Limit Dynamic Data Usage: Minimize the direct use of user-supplied data in outputs, particularly in sensitive formats like JSON and SVG. Static data or server-side-generated content is less vulnerable to injection attacks.
  6. Implement Safe Token URI Handling: The tokenURI function should escape any user inputs or forbid special characters that can lead to injection vulnerabilities when minting NFTs.
  7. Check for Malicious Symbols: Implement checks in minting functions to prevent “javascript launching” symbols, such as < or the word "javascript", and to block common injection vectors.
  8. Utilize JSON Sanitization Libraries: Employ libraries like the OWASP JSON Sanitizer to ensure that JSON outputs are secure and free from injection vulnerabilities. https://github.com/OWASP/json-sanitizer
  9. Frontend Vigilance: While backend sanitization is crucial, frontends should also treat NFT metadata as untrusted data, applying their sanitization measures to prevent XSS and other client-side attacks.
  10. Protocol Level Protections: Protocols must protect users by ensuring that the art piece or metadata users vote on or interact with remains unchanged throughout the process, preventing bait-and-switch attacks.

Be mindful of the gas costs associated with on-chain data validation and sanitization. Balancing security measures with cost-efficiency is crucial for practical implementation.

Conclusion

In the intersecting realms of Web2 and Web3, JSON and SVG injections pose real threats, leveraging oversights in data sanitization to compromise NFT metadata integrity. Awareness and preventive measures are paramount. Solutions like Zokyo’s in-depth security assessments and Mamoru.ai’s vigilant monitoring provide a robust defense, ensuring that as we innovate in the digital art space, we also safeguard the uniqueness and authenticity of every NFT.

Stay safe out there 🔒

Additional Reading

About Zokyo

Zokyo (“augment” in Japanese) keeps pace with your in-house development team and provides blockchain security, design, and development talent to startups and enterprise organizations as needed. As a go-to web3 security, development, and investment partner working with some of the most progressive companies since 2019, we are highly experienced in tackling some of the most challenging problems with an entrepreneurial spirit.

With immediate access to in-demand skills ranging from security auditing, cryptography, white-hat hacking, mathematical specifications of network design, UI/UX design, QA, and full-stack engineering, we help legendary companies accelerate time to market and achieve their goals on time and on budget. Our clients demand and deserve best-in-class security and engineering support. As such, we at Zokyo are committed, passionate and proud to build a more secure Web3 future.

Website | LinkedIn | X (Twitter) | Get in Touch

--

--