Under the Hacker’s Hood: JSON Injection in NFT Metadata
25 mar 2024
9 minutes
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.
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 witheval()
, 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.
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:
Resulting JSON String:
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:
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:
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:
What an attacker can do
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.
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.
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.
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.
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.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.
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.
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.
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.
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):
Attack Vector:
An attacker, Eve, mints an NFT with a malicious SVG image containing JavaScript code. The SVG is crafted as follows:
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
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.
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’sescapeJSON:
https://github.com/Vectorized/solady/blob/9deb9ed36a27261a8745db5b7cd7f4cdc3b1cd4e/src/utils/LibString.sol#L1001C1-L1060C6Sanitize 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.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.
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.
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.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.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
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.
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
Content security policy | Web Security Academy (portswigger.net)
html — What could an “<img src=” XSS do? — Information Security Stack Exchange
Do you allow to load SVG files? You have XSS! — research.securitum.com
allanlw/svg-cheatsheet: A cheatsheet for exploiting server-side SVG processors. (github.com)
Escalating SSRF to RCE. Escalating SSRF to RCE in AWS Elastic… | by Youssef A. Mohamed | Medium
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.