World
Identity Deletion

World added the ability to remove identities from World ID's tree. We reviewed the new identity manager that verifies deletion proofs and updates the root.
report id
0144
category
Identity & Cryptography
language
Solidity
final report
October 12, 2023
lines of code
449
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind on the WorldID Contracts Upgrade containing 449 lines of code. The Worldcoin team has implemented a new feature that allows the removal of identities from the tree structure. To implement this feature, a new contract called WorldIDIdentityManagerImplV2 has been created. This contract inherits from the v1 implementation and is responsible for receiving an array of identities to be deleted, verifying their proof, and updating the latest root accordingly.

In addition, there has been an update to the code where all elements now come out reduced from the circuit. As a result, all checks for inputs being reduced have been removed from the contract. Along the audit of this contract, we report 8 points of attention, where 1 is classified as Low, 1 is classified as Info and 6 are classified as Best Practices.

Audit assessment
Audit TypeSecurity Review
Initial ReportOct. 6, 2023
Response from ClientOct. 10, 2023
Final ReportOct. 12, 2023
MethodsManual Review, Automated Analysis
Repositoryworld-id-contracts
Commit Hash (Audit)42c26ecbd8
DocumentationREADME.md
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
8
Fixed
6
Acknowledged
2
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium0
  • Low1
  • Informational1
  • Best Practices6

2

Audited Files

4

System Overview

No system overview is included in this report.

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 Invalid batchSize can result in incorrect hash calculation

FileFix commitTypeStatus
WorldIDIdentityManagerImplV2.solPR #134
PR #134
LowFixed

The function deleteIdentities(...) takes a uint32 input batchSize, which specifies the number of identities to be deleted. The indices of these identities are packed in the packedDeletionIndices input, with each index occupying exactly 32 bits (4 bytes).

function deleteIdentities(
uint256[8] calldata deletionProof,
uint32 batchSize, // @audit `batchSize` should be the same as the number of deleted elements.
bytes calldata packedDeletionIndices,
uint256 preRoot,
uint256 postRoot
){
...
// @audit batchSize is used to compute `inputHash`
bytes32 inputHash = calculateIdentityDeletionInputHash(packedDeletionIndices, preRoot, postRoot, batchSize);
...
}

However, the code lacks a validation check to ensure that the provided batchSize aligns with the actual number of elements presented in packedDeletionIndices. A mismatch between these two inputs could lead to erroneous inputHash calculations within calculateIdentityDeletionInputHash function.

function calculateIdentityDeletionInputHash(
bytes calldata packedDeletionIndices,
uint256 preRoot,
uint256 postRoot,
uint32 batchSize
) public view virtual onlyProxy onlyInitialized returns (bytes32 hash) {
assembly {
let startOffset := mload(0x40)
let indicesByteSize := mul(batchSize, 4) // @audit the real size of deletion indices can be different
calldatacopy(startOffset, packedDeletionIndices.offset, indicesByteSize)
let rootsOffset := add(startOffset, indicesByteSize)
mstore(rootsOffset, preRoot)
mstore(add(rootsOffset, 32), postRoot)
hash := keccak256(startOffset, add(64, indicesByteSize))
}
}

Recommendation

Consider adding a check to ensure that batchSize corresponds precisely to the number of elements detailed in packedDeletionIndices, i.e., packedDeletionIndices should have exactly (batchSize * 4) bytes. Furthermore, batchSize can potentially be omitted from the inputs, as it can be computed internally using packedDeletionIndices.

Resolution

Implemented fix in commit 6821849a and commit 8937c4c3.

6.2 Possible duplicate roots block propagating root to L2 contracts

FileFix commitTypeStatus
WorldIDIdentityManagerImplV2.sol—InfoAcknowledged

When an identity is deleted in the identity manager, a new root will be created and then propagated to L2 contracts by state bridge. In the L2 contracts, if a root already exists, it cannot be received again as can be seen in this line. However, it is possible that an existing root is created again after deleting an identity, but since it existed and was progagated before, it will be prevented from propagating to L2 again.

Consider the following scenario:

1. The tree has 4 leaves. The latest root is propagated to L2, containing 4 identities; 2. Two new identities are added, and then two more are added. Now the tree has 8 leaves. The latest root is propagated to L2, containing 8 identities; 3. The last 4 identities are deleted from the tree. The tree now has 4 leaves;

Now, the state of the tree at steps 1 and 3 is the same, making the root after step 3 unable to be propagated. The latest root is still the root of step 2, which contains the deleted identities.

Recommendation

Consider reviewing the mechanism for propagating latest root to L2 or preventing duplicated roots in the manager contract to align with the logic in L2.

Resolution

In practice we run very big batches (100 or 1000 most of the time) and deletions are highly unlikely to be done from people who just registered. We don’t believe that in practice this would be an error that could impact root propagation, since we do hourly batches and a new root would be propagated if for a very odd chance you had the same root for an hour. The signup-sequencer service which handles insertions/deletions among other things also has checks against this happening.

6.3 Absence of event emission during contract initialization

FileFix commitTypeStatus
WorldIDIdentityManagerImplV2.solPR #134Best PracticesFixed

The initializeV2(...) function, responsible for initializing the WorldIDIdentityManagerImplV2 contract, currently lacks an event emission.

// @audit Function does not emit an event for the contract initialization
function initializeV2(VerifierLookupTable _batchUpdateVerifiers) public reinitializer(2) {
batchDeletionVerifiers = _batchUpdateVerifiers;
}

Recommendation

It is recommended to emit an event upon contract initialization to provide a clear record of this operation and enable better monitoring.

Resolution

Implemented fix in commit 9188a5

6.4 Floating pragma

FileFix commitTypeStatus
WorldIDIdentityManagerImplV1.sol
WorldIDIdentityManagerImplV2.sol
—Best PracticesAcknowledged

The Solidity version has been upgraded from 0.8.19 to 0.8.21 in the V2 implementation. However, the contracts still use a floating pragma, which is not recommended and could result in unexpected behavior.

Recommendation

Consider locking the version of Solidity to ensure that the contract is deployed with the version it was carefully tested with.

Resolution

We have chosen to keep utilizing a floating pragma, since World ID contracts will live only on Ethereum. The solc version used is fixed using foundry.toml.

6.5 Function deleteIdentities(...) has different access control than stated in the documentation

FileFix commitTypeStatus
WorldIDIdentityManagerImplV2.solPR #134Best PracticesFixed

The documentation states that only the owner can call the function deleteIdentities(...). However, the function is implemented with the onlyIdentityOperator modifier instead of the onlyOwner modifier. This means that the function is limited to identity operators instead of the owner.

Recommendation

Consider updating the documentation to match the implemented access control or change the modifier to onlyOwner.

Resolution

Implemented fix in commit 9eee488.

6.6 Missing input validation in some functions

Certain variables lack validation during initialization and setting operations.

  • In the WorldIDIdentityManagerImplV1 contract, batchInsertionVerifiers and semaphoreVerifier are not verified to be non-zero addresses during initialize and the respective setter functions: setRegisterIdentitiesVerifierLookupTable and setSemaphoreVerifier;
  • In the WorldIDIdentityManagerImplV2 contract, batchDeletionVerifiers is not verified to be a non-zero address on initialize and setDeleteIdentitiesVerifierLookupTable functions;

Recommendation

Consider incorporating input validation checks for these inputs.

Resolution

Fixed in commits 51a6d82b4 and f200c3e

6.7 Outdated NatSpec documentation and comments in V2 implementation

FileFix commitTypeStatus
WorldIDIdentityManagerImplV2.solPR #134Best PracticesFixed

Some NatSpec documentation and comments in WorldIDIdentityManagerImplV2 contracts seem to be taken from the V1 contract and refer to the insertion logic instead of the deletion.

function deleteIdentities(...){
...
try deletionVerifier.verifyProof(deletionProof, [reducedElement]) {
// If it did verify, we need to update the contract's state. We set the currently valid
// root to the root after the insertions.
// @audit old comment referring to insertions.
_latestRoot = postRoot;
...
}
...
/// @param preRoot The root value of the tree before these insertions were made.
/// @param postRoot The root value of the tree after these insertions were made.
/// @param batchSize The number of identities that were deleted in this batch
// @audit NatSpec documentation referring to insertions
...
function calculateIdentityDeletionInputHash(...)

Recommendation

Consider updating the documentation and comments to reflect the deletion logic accurately.

Resolution

Implemented fix in commit 9eee488.

6.8 Used event marked as unused in the documentation

FileFix commitTypeStatus
WorldIDIdentityManagerImplV1.solPR #134Best PracticesFixed

The NatSpec documentation of TreeChange structure states that the enum is no longer used in the logic.

/// @notice Represents the kind of change that is made to the root of the tree.
/// @dev TreeChange.Update preserved for ABI backwards compatibility with V1, no longer used
// @audit Documentation states that the enum is no longer used.
enum TreeChange {
Insertion,
Deletion
}

However, the enum is used when emitting TreeChanged event in both registerIdentities and deleteIdentities functions, as shown below.

function registerIdentities(...){
...
// @audit `TreeChange` used to emit `TreeChanged` event for insertion
emit TreeChanged(preRoot, TreeChange.Insertion, postRoot);
...
}
function deleteIdentities(...){
...
// @audit `TreeChange` used to emit `TreeChanged` event for deletion
emit TreeChanged(preRoot, TreeChange.Deletion, postRoot);
...
}

Recommendation

Update the NatSpec documentation to avoid confusion.

Resolution

Implemented fix in commit a11dfad.

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

The documentation is presented in README.md. The documentation is sufficient for this audit.

7.3 Code Coverage

The relevant output is presented below.

Test suite
148Tests passed0Failed

The complete test output is in the full report.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.