Download audit report
This document outlines the security review conducted by Nethermind for the Dojo Game Engine. Dojo is a provable game engine and toolchain for building on-chain games and autonomous worlds. It is built around the concept of Entity Component System architecture. This model revolves around systems acting on entities, which are collections of pure data components. Systems efficiently determine which entities to process based on persistent queries over these components. The world contract controls all these components (systems and models). This contract enables the registration, creation, and deletion of entities. All data of these entities is stored in an on-chain database that supports indexing. The world contract also includes access control logic to authorize which addresses and systems can create, delete, or update entities.
The audited code comprises 945 lines of code in Cairo. The Dojo team has provided comprehensive documentation that explains Dojo’s core architecture, and the detailed properties of each component, as well as how they interact with each other.
The audit was performed using: (a) manual analysis of the codebase and (b) simulation of the smart contracts.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Jan 25, 2024 |
| Final Report | Feb 7, 2024 |
| Methods | Manual Review |
| Repository | dojo-core |
| Commit Hash | 36e5853877 |
| Final Commit Hash | 1a1f348536 |
| Documentation | Dojo Book |
| Documentation Assessment | High |
| Test Suite Assessment | Medium |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | src/world.cairo | 368 | 222 | 60.3% | 82 | 672 |
| 2 | src/components.cairo | 1 | 0 | 0.0% | 0 | 1 |
| 3 | src/database.cairo | 78 | 15 | 19.2% | 10 | 103 |
| 4 | src/base.cairo | 24 | 8 | 33.3% | 8 | 40 |
| 5 | src/packing.cairo | 128 | 12 | 9.4% | 17 | 157 |
| 6 | src/executor.cairo | 26 | 15 | 57.7% | 6 | 47 |
| 7 | src/lib.cairo | 14 | 7 | 50.0% | 3 | 24 |
| 8 | src/model.cairo | 12 | 1 | 8.3% | 1 | 14 |
| 9 | src/database/utils.cairo | 94 | 48 | 51.1% | 24 | 166 |
| 10 | src/database/storage.cairo | 59 | 0 | 0.0% | 12 | 71 |
| 11 | src/database/index.cairo | 101 | 24 | 23.8% | 29 | 154 |
| 12 | src/components/upgradeable.cairo | 40 | 7 | 17.5% | 9 | 56 |
| Total | 945 | 359 | 38.0% | 201 | 1505 |
Dojo is a provable game engine for onchain games on Starknet and autonomous worlds. The game’s owner deploys a world contract, which behaves as a database. It stores world models and systems. The world contract is a core contract that allows users to register their models, deploy system contracts, or set metadata for models.
The resource owners deploy system contracts that hold the world’s logic, or it is possible to say game logic. The best way to understand this is an example: Imagine a system contract as a movement functionality for the world. It will hold functions that will update the player’s position in the world.
Another component of this protocol is the model. A model is a structure that is represented as a table. It holds keys and values, which are stored in the world contract. First, an owner of a model needs to declare a class of a specific model to be able to register it within the World contract.
The protocol contains two main contracts: World and Executor. Code is organized into separate files, which we call modules or libraries. The main libraries of World contract are:
Fig. 2 presents the interaction diagram of the contracts.
The Database module contains the logic of a relational database. Users can create tables with keys and values, with each table representing an entity in the world contract.
The Index module handles creating and deleting indexes for the pair table-key.
The Storage module works as the storage of world contract. It offers low-level functionality for storing and fetching data from the internal storage of the contract.
The Packing module enables packing and unpacking functionality for custom data structures, ensuring efficient data handling within the system.
The modules mentioned above are part of the World contract, which implements an additional access control layer and external functionality for associating classes of models with the World contract and deploying system contracts. Furthermore, it allows functionality to write into a database and obtain needed data.
Another contract of the protocol is the Executor. Executor provides library system calls to deployed classes. In the current implementation, the Executor is called from World contract to obtain the name of the module class.
Two types of actors will interact with the World contract are:
a) Resource owners: Users who register models or deploy system contracts associated with the World contract become resource owners. They have the authority to manage these resources by inserting data and metadata related to them. Additionally, resource owners can assign ownership or writing privileges to other account contracts for their resources. It’s important to note that the admin of the World contract is also part of this group.
b) Writers: Members of this group, likely system contracts, are responsible for setting data to the relational database or deleting data.
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:
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:
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 / Likelihood | Low | Medium | High |
| High | Medium | High | Critical |
| Medium | Low | Medium | High |
| Low | Info / Best Practices | Low | Medium |
| Undetermined | Undetermined | Undetermined | Undetermined |
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.
| File | Fix commit | Type | Status |
world.cairo | bfd952b202d0770e1ea821a1f348 | Critical | Fixed |
The registering model process has no access control checks if the model name does not exist. However, owners of models are stored in the same mapping. A malicious actor can register their own model to take ownership of existing contracts or anything like the following assumption.
If there is a contract deployed by calling the deploy_contract(...) method, the owner will be the caller. However, a malicious actor can register the model with the name as the contract address of this newly deployed contract to take ownership.
Deploying a contract does not write models storage its contract address. So following if statement will grant ownership to the malicious actor;
fn register_model(ref self: ContractState, class_hash: ClassHash) {
// ...
let current_class_hash = self.models.read(name);
if current_class_hash.is_non_zero() {
assert(self.is_owner(caller, name), 'only owner can update');
prev_class_hash = current_class_hash;
} else {
self.owners.write((name, caller), true);
};
// @audit-issue: Everyone can make themselves of owner of anything that doesn't exist in models.
self.models.write(name, class_hash);
EventEmitter::emit(ref self, ModelRegistered { name, class_hash, prev_class_hash });
}As we see there is no model storage writing on the deploy_contract(...) method.
fn deploy_contract(
ref self: ContractState, salt: felt252, class_hash: ClassHash
) -> ContractAddress {
let (contract_address, _) = deploy_syscall(
self.contract_base.read(), salt, array![].span(), false
)
.unwrap_syscall();
let upgradeable_dispatcher = IUpgradeableDispatcher { contract_address };
upgradeable_dispatcher.upgrade(class_hash);
self.owners.write((contract_address.into(), get_caller_address()), true);
EventEmitter::emit(
ref self, ContractDeployed { salt, class_hash, address: contract_address }
);
contract_address
}So initially, the model mapping will be zero for newly deployed contracts, and malicious actors can register the model to get ownership and then get access to access-controlled methods.
Recommendation
Consider changing the owner storage structure or registering the deployed contract address as a model.
Resolution
In the commit bfd952b5112f3790621b1a5f68d47b25d9daa7d2 a new storage variable was added to avoid such conflict.
Update from Nethermind Security
It is still feasible to get an ownership of WORLD.
Update from the client
Fixed in 202d077 and missing test added in 0e1ea82. Updated in 1a1f3485 to ensure the resource metadata are also protected and only controlled by the world’s creator.
| File | Fix commit | Type | Status |
world.cairo | f129edf | Critical | Fixed |
Resource metadata stored in one storage mapping like
#[storage]
struct Storage {
// ...
metadata_uri: LegacyMap::<felt252, felt252>,
// ...
}Where the felt value is the name of the resource, and the first mapped value is the length of the metadata array. Length is used to read metadata like the following.
fn metadata_uri(self: @ContractState, resource: felt252) -> Span<felt252> {
let mut uri = array![];
// We add one here since we start i at 1;
let len = self.metadata_uri.read(resource) + 1;
let mut i = resource + 1;
loop {
if len == i {
break;
}
uri.append(self.metadata_uri.read(i));
i += 1;
};
uri.span()
}However, writing can be done by only the owner of the resource;
fn set_metadata_uri(ref self: ContractState, resource: felt252, mut uri: Span<felt252>) {
assert(self.is_owner(get_caller_address(), resource), 'not owner');
// ...
}But everyone can register their own model and be their own model’s owner by calling register_model(...). If a malicious actor registers a model with the name felt of target_resource - 1, then the actor can use this ownership to overwrite target resources metadata.
Recommendation
Consider changing metadata storing structure. Use Resource -> Span mapping.
Resolution
That’s a good catch. The situation here originates from the metadata uri being handles as a resource, but on more than one felt. Resources are to be considered as a one felt long identifier. To address this, we’ve adjusted the way metadata are handled by the world, and now it follows the regular ACL flow by using the same logic as models do. commit: f129edfc.
| File | Fix commit | Type | Status |
world.cairo | 479197e04f7ef7 | High | Fixed |
Function register_model(...) can be used to upgrade existing executor contract implementation. In this function, there is an external call to the executor, where the executor library calls to target class hash. However, a malicious actor can pass any class hash. That class hash can contain replace_class_syscall to upgrade the executor contract to any other class hash.
fn register_model(ref self: ContractState, class_hash: ClassHash) {
// ...
let name = *class_call(@self, class_hash, NAME_ENTRYPOINT, calldata.span())[0];
// @audit-issue: Any class hash can be used to library call at executor.
// ...
}
impl Executor of IExecutor<ContractState> {
fn call(
self: @ContractState,
class_hash: ClassHash,
entrypoint: felt252,
calldata: Span<felt252>
) -> Span<felt252> {
starknet::syscalls::library_call_syscall(class_hash, entrypoint, calldata)
.unwrap_syscall() // @audit-issue: There are no checks, call forwarded directly.
}
}Recommendation
Consider deploying the contract, then call to get the name.
Resolution
To limit the API changes on current Dojo implementation, we propose in commits 479197e4f and 04f7ef756 to remove the executor. Indeed, the library_call syscall can’t prevent the execution of syscalls, and in the context of Dojo, we do need model registering to be permissionless. The proposed solution introduces communication with models via regular contract_call syscall instead of library call, which prevents the world (or auxiliary contract like executor) from being modified.
delete(...) does not update the new position for the last element| File | Fix commit | Type | Status |
index.cairo | e95153c | High | Fixed |
In the index.cairo contract, there are 3 mappings used to store elements.
1. The first mapping stores the position of an element (index, id) => position + 1; 2. The second mapping stores the number of elements in this index (index) => length; 3. The third mapping stores the id of the element in each position (index, position) => id;
When an element is removed from an index, the function delete(...) does the following:
However, since the last element is moved to a new position, the position of the last element is also changed. This means that we also need to update the first mapping for the last element. Currently, the function delete(...) does not handle this, which breaks the structure of the contract as the first mapping points to the wrong position.
fn delete(address_domain: u32, index: felt252, id: felt252) {
if !exists(address_domain, index, id) {
return ();
}
let index_len_key = build_index_len_key(index);
let replace_item_idx = storage::get(address_domain, index_len_key) - 1;
let index_item_key = build_index_item_key(index, id);
let delete_item_idx = storage::get(address_domain, index_item_key) - 1;
storage::set(address_domain, index_item_key, 0);
storage::set(address_domain, index_len_key, replace_item_idx);
// Replace the deleted element with the last element.
// NOTE: We leave the last element set as to not produce an unncessary state diff.
// @audit-issue Not update new position of replace item
let replace_item_value = storage::get(address_domain, build_index_key(index, replace_item_idx));
storage::set(address_domain, build_index_key(index, delete_item_idx), replace_item_value);
}Recommendation
Consider updating the new position for the last element.
storage::set(address_domain, build_index_item_key(index, replace_item_value), delete_item_idx + 1);Resolution
Related to index removed code in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.
get_many() function results in missing return data| File | Fix commit | Type | Status |
storage.cairo | f03cce84b5c0f8 | Medium | Fixed |
The get_many(...) function uses offset to specify the starting position for retrieval from storage. It should retrieve storage slots from offset to offset + length - 1. However, the current code retrieves from offset to length - 1 only. If offset > length, it causes an infinite loop. The issue is evident in the code snippet below, where the loop breaks when offset == length.
let mut offset = offset;
loop {
// @audit-issue Incorrect check, should be (length + original_offset == offset.into())
if length == offset.into() {
break ();
}Recommendation
Consider changing the break condition to length + original_offset == offset.into() where the original_offset is the initial value of offset before the loop starts.
Resolution
Yes that’s correct. Currently only the offset 0 is enforced by the dojo-lang macro. This is the reason why it wasn’t detected before.
We’ve adjusted the storage layer to always start at the offset 0, and offset is no longer exposed.
commit: f03cce87ade45848b5c5ab9b4a6cf72666343211.
And in a second commit, adjustement to be backward compatible without storing the length in the storage: 4b5c0f8023357a8d3c9c782ae89621b2978947ad.
We may update this to add the offset again to allow some further optimization on data retrieval. If added, it bounds checking will come along the offset.
metadata_uri() cause infinite loop| File | Fix commit | Type | Status |
world.cairo | — | Medium | Fixed |
In world.cairo, the metadata URI of a resource is stored as follows. First, at the resource position, it will store the length of the metadata URI. The following positions store the actual metadata URI.
fn metadata_uri(self: @ContractState, resource: felt252) -> Span<felt252> {
let mut uri = array![];
// We add one here since we start i at 1;
let len = self.metadata_uri.read(resource) + 1;
let mut i = resource + 1;
loop {
// @audit Incorrect check, it is assuming resource = 0
// @audit The check should be `if resource + len == i`
if len == i {
break;
}
uri.append(self.metadata_uri.read(i));
i += 1;
};
uri.span()
}Consider the following scenario:
1. Alice stores the metadata URI for resource = 256 with a length of 5. In set_metadata_uri(...), it will set metadata_uri[256] = 5, and the next 5 positions from 257 to 261 will store the metadata URI; 2. Now, when the function metadata_uri(...) is called to get the metadata URI for resource = 256, it will calculate:;
len = metadata_uri[256] + 1 = 6
i = resource + 1 = 257As you can see, since the starting value of i = 257 is already larger than len = 6, the break condition len == i will never be reached as the value of i will increase in each iteration.
Recommendation
Change the check to resource + metadata_uri[resource] == i.
Resolution
Concern addressed in the previous one as this code is not longer present.
query(...) function when the condition is specified| File | Fix commit | Type | Status |
index.cairo | 98ed168 | Medium | Fixed |
The query(...) function serves to return all elements from a table. This function allows the usage of the where parameter, which works similarly to the SQL where keyword, as it will return elements based on the condition. If this parameter is not specified, the function will return all values from the table.
However, only the elements that match the condition should be returned if the where parameter is used. This part of the code contains a loop that iterates through elements connected with a specific index. The index is created based on the key of the condition. The loop is where the issue arises, as the variable idx is not updated at the end of the iteration, which will cause an infinite loop, and the function will fail for an out of gas error.
Option::Some(clause) => {
let mut serialized = ArrayTrait::new();
table.serialize(ref serialized);
clause.key.serialize(ref serialized);
let index = poseidon_hash_span(serialized.span());
let index_len_key = build_index_len_key(index);
let index_len = storage::get(address_domain, index_len_key);
let mut idx = 0;
loop {
if idx == index_len {
break ();
}
let id = storage::get(address_domain, build_index_key(index, idx));
res.append(id);
// @audit-issue idx is not updated
}
},Recommendation
It is necessary to update the idx variable inside a loop at the end of the iteration.
Resolution
Linked to WhereClause.
Code related to index was removed for now as it will be reworked in the future:
| File | Fix commit | Type | Status |
packing.cairo | — | Medium | Acknowledged |
Packing method trusting layout parameter for bitsizes of variables inside unpacked span. However, the layout parameter is not coming from a trusted source. It can be inputted as any inside set_entity(...) method.
fn pack(ref packed: Array<felt252>, ref unpacked: Span<felt252>, ref layout: Span<u8>) {
assert(unpacked.len() == layout.len(), 'mismatched input lens');
let mut packing: felt252 = 0x0;
let mut offset: u8 = 0x0;
loop {
match unpacked.pop_front() {
Option::Some(item) => {
pack_inner(item, *layout.pop_front().unwrap(), ref packing, ref offset, ref packed);
},
Option::None(_) => {
break;
}
};
};
packed.append(packing);
}Recommendation
Consider store using native types. If the writer is trusted executable, consider packing off-chain.
Resolution
The explicit layout is currently something very controlled by the dojo-lang compiler, where expansion of macro auto-generate the layout to be sent. As mentioned, sending a transaction explicitely can result in corrupted data, but since ACLs are covering who can modify the data, the input is always considered as trusted.
Finally, this is also a flexible way to allow the user to send arbitrarily packed data.
| File | Fix commit | Type | Status |
world.cairo | 1d65123 | Medium | Fixed |
The protocol allows the contract deployment to be associated with the world contract by the function deploy_contract(...). When the contract is deployed, it updates a mapping owners so that the caller of this function becomes an owner of the deployed contract.
The contract associated with the world can also be upgraded by invoking upgrade_contract(...) function. The following function checks the permissions of a caller by the following line:
assert_can_write(@self, address.into(), get_caller_address());
...
fn assert_can_write(self: @ContractState, resource: felt252, caller: ContractAddress) {
assert(
IWorld::is_writer(self, resource, caller)
|| IWorld::is_owner(self, get_tx_info().unbox().account_contract_address, resource)
|| IWorld::is_owner(self, get_tx_info().unbox().account_contract_address, WORLD),
'not writer'
);
}The function assert_can_write(...) checks if the caller is the owner of WORLD or the owner of the resource(in this case, an owner of the contract) or has writing permissions.
However, that is where the issue arises as just an owner of the contract or of the WORLD should be able to upgrade a contract. The writer should not have a privilege for this action.
Recommendation
Consider checking access control for the upgrade_contract(...) function.
Resolution
Fixed in 1d65123556f8b070ebd730647d4407befb1c92d8 where only ownership is check for upgrade.
get_by_key(...) cannot be used because specific keys are not set anywhere| File | Fix commit | Type | Status |
index.cairo | e95153c | Info | Fixed |
In the index.cairo contract, the get_by_key(...) function is designed to return all entries containing a specific key. The function utilizes build_index_specific_key_len(...) and build_index_specific_key(...) to create the specific keys and build the storage address. However, these keys are not set anywhere in the contract. As a result, the function will fail to return any results, rendering it unusable.
fn get_by_key(address_domain: u32, index: felt252, key: felt252) -> Array<felt252> {
let mut res = ArrayTrait::new();
let specific_len_key = build_index_specific_key_len(index, key); // @audit-issue Not set anywhere
let index_len = storage::get(address_domain, specific_len_key);
let mut idx = 0;
loop {
if idx == index_len {
break ();
}
let specific_key = build_index_specific_key(index, key, idx); // @audit-issue Not set anywhere
let id = storage::get(address_domain, specific_key);
res.append(id);
idx += 1;
};
res
}Recommendation
Implement features to set specific keys for index.
Resolution
Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.
ids input params in the function find_matching(...)| File | Fix commit | Type | Status |
utils.cairo | e95153c | Info | Fixed |
The function find_matching(...) takes multiple entity lists as input parameters. It aims to find the set of entities present in all the provided lists. It does this by counting how many times each entity id occurs. If an id appears a number of times equal to the number of lists, it means the entity with this id exists in all lists. However, the function does not account for cases where a list contains duplicated entities. If any entity_ids list contains duplicate values, it would cause the count in ids_match to be incorrect, potentially returning an id that does not exist in all lists.
Recommendation
Consider checking for duplicate elements in each entity_ids list.
Resolution
Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.
| File | Fix commit | Type | Status |
packing.cairo | 29621f5 | Info | Fixed |
The pack_inner(...) function is packing a felt element. It takes several parameters. One of them is a size specifying the element’s size. This element is obtained from the layout array parameter of the pack(...) function.
The element must fit to felt252; however, due to the following line and comments, the maximum size allowed is 251.
// Cannot use all 252 bits because some bit arrangements (eg. 11111...11111) are not valid felt252 values.
// Thus only 251 bits are used. ^-252 times-^
// One could optimize by some conditional alligment mechanism, but it would be an at most 1/252 space-wise improvement.
let remaining_bits: u8 = (251 - packing_offset).into();If not, the line above will overflow, and the packing will revert. But If the last element of the layout (size) is larger than 251 and lower than 256 (to fit u8 space), the pack_inner(...) will not revert. There is no direct impact from this missing edge case. Still, to keep the consistency of the code, there should be an assertion that the size is not larger than 251.
Recommendation
Consider additional checks that the size is not larger than the 251 value.
Resolution
Was addressed in 29621f526957d5a330d2dc5c52af24fa68621c42 to ensure good behavior if layout is not correct.
| File | Fix commit | Type | Status |
packing.cairo | b1e1aa8 | Info | Fixed |
There is an open TODO in the function unpack(...). According to the comment, the function should raise an error, but currently, it only exits the loop.
Option::None(_) => {
// TODO: Raise error
break;
}Recommendation
Consider reviewing the intended behavior of this branch again.
Resolution
Changed for a comment in b1e1aa82fa542dc516fa94d0915e0a4ab825a25f.
register_model(...)| File | Fix commit | Type | Status |
world.cairo | — | Info | Acknowledged |
The world contract includes multiple models, each tracked by its name. This name is retrieved from the model class hash during the registration of the model.
fn register_model(ref self: ContractState, class_hash: ClassHash) {
let caller = get_caller_address();
let calldata = ArrayTrait::new();
// @audit-issue Can front-run to register model with the same name
let name = *class_call(@self, class_hash, NAME_ENTRYPOINT, calldata.span())[0];
let mut prev_class_hash = starknet::class_hash::ClassHashZeroable::zero();
// If model is already registered, validate permission to update.
let current_class_hash = self.models.read(name);
if current_class_hash.is_non_zero() {
assert(self.is_owner(caller, name), 'only owner can update');
prev_class_hash = current_class_hash;
} else {
self.owners.write((name, caller), true);
};
self.models.write(name, class_hash);
EventEmitter::emit(ref self, ModelRegistered { name, class_hash, prev_class_hash });
}However, since register_model(...) is a public function, an attacker could front-run and register a null or malicious model using the same name as the legitimate model registration transaction. Consequently, the legitimate model cannot be registered because its name already exists. The attacker could repeatedly do this to effectively block all model registrations.
Recommendation
Consider restricting the addresses that can register a new model or change the method of model tracking. For instance, use a combination of (name, caller_address) to mitigate the issue.
Resolution
This is inherent to how the permissionless registration of the models works in the world. Due to that, front-running is indeed possible, but per se not an issue as then the permissions are still controlled by the owner.
offset in the function get_many(...)| File | Fix commit | Type | Status |
storage.cairo | f03cce8 | Info | Fixed |
The get_many(...) function uses offset to specify the start position to get from storage. The function retrieves storage slots from offset to offset + length - 1. However, offset uses u8 while length uses usize. Therefore, if length > max(u8), offset may overflow.
fn get_many(address_domain: u32, keys: Span<felt252>, offset: u8, length: usize, mut layout: Span<u8>) -> Span<felt252> {
let base = starknet::storage_base_address_from_felt252(poseidon_hash_span(keys));
let mut packed = ArrayTrait::new();
let mut offset = offset;
loop {
// @audit-issue offset's datatype is smaller than `usize` and could overflow
if length == offset.into() {
break ();
}
packed
.append(
starknet::storage_read_syscall(
address_domain, starknet::storage_address_from_base_and_offset(base, offset)
)
.unwrap_syscall()
);
offset += 1;
};
...
}Recommendation
Consider using the same data type for offset and length.
Resolution
Solved in f03cce87ade45848b5c5ab9b4a6cf72666343211 where the offset is no longer exposed.
If we re-introduce the offset, bounds checks will be implemented as mentioned here.
| File | Fix commit | Type | Status |
packing.cairo | 0c0a4ec | Info | Fixed |
Method fpow(...) returns 1 if the second variable is zero. But there is no check for whether the first value is zero or not. In math, 0 power 0 should be undefined. In this case the method should return. But it returns 1 early because the second variable is zero.
fn fpow(x: u256, n: u8) -> u256 {
let y = x;
// @audit-issue: Should revert if x and n are zero.
if n == 0 {
return 1;
}
// ...
}Recommendation
Consider checking if both parameters are zero or not.
Resolution
Updated in 0c0a4ec462bff2ed5f8de3a8c712fc785621603d.
find_matching(...) will fail for empty arrays| File | Fix commit | Type | Status |
utils.cairo | e95153c | Info | Fixed |
The function find_matching(...) in utils.cairo serves to find entities that match the same IDs across all supplied entities.
As this function is not used anywhere in world.cairo, we guess that this function will be used for some off-chain interaction. Therefore, this function should handle all edge cases and probably not fail in different cases than assert statements checks.
However, the following function will fail if the supplied arrays are empty due to the following line.
// we want to keep the ordering from the first entity IDs
let mut ids1: Span<felt252> = *(ids.pop_front().unwrap()); //@audit-issue here it will fail for zero arraysRecommendation
Consider handling a case when the supplied params are empty arrays.
Resolution
Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.
set_entity(...)| File | Fix commit | Type | Status |
world.cairo | e95153c | Info | Fixed |
The world.cairo exposes two functions: set_entity(...) and delete_entity(...), for setting the model to the entity and deleting the model from the entity, respectively.
When the entity is set, the contract interacts with the storage to store data related to the model based on the keys.
All the values linked with keys are set to 0 during the entity’s deletion. Additionally, when the entity is deleted, its index is also removed from the storage. However, no index is created with the entity during the flow of set_entity(...) function.
Recommendation
Consider creating an index when setting an entity.
Resolution
Index related code was removed in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6.
| File | Fix commit | Type | Status |
components/upgradeable.cairo | 8ff011f | Info | Fixed |
The upgrade method has a couple of checks, but it is not checking that the new class hash has the method world(...). If upgraded to a hash that this function doesn’t exist, then all further upgrade trials will revert, and it can’t be reversed.
fn upgrade(ref self: ComponentState<TContractState>, new_class_hash: ClassHash) {
// @audit-issue: The assertion below will revert if there is no world entrypoint in the new class.
assert(
self.get_contract().world().contract_address.is_non_zero(),
Errors::INVALID_WORLD_ADDRESS
);
assert(
get_caller_address() == self.get_contract().world().contract_address,
Errors::INVALID_CALLER
);
// ...
}Recommendation
Consider checking methods used in assertions that also exist in the new implementation.
Resolution
Attempt to fix with a library_call_syscall, not sure about the point of doing that right now. I would say we can wait interfaces to be supported and standardized (SNIP). A first attempt to mitigate this risk was done in commit: 8ff011.
WhereCondition is never being used in the function query(...)| File | Fix commit | Type | Status |
database.cairoindex.cairo | 98ed168 | Info | Fixed |
The function query(...) accommodates both conditional and non-conditional queries by allowing an input where: Option<WhereCondition>. However, this function is currently only used in the function scan_ids(...), which always inputs Option::None as the where parameter. Consequently, WhereCondition is never used, and the logic written for it is redundant.
Consider the test case below for the function scan(...) that tests the case where it uses WhereCondition. This test fails and throws an Index out of bounds error.
#[test]
#[available_gas(10000000)]
fn test_database_scan2() {
let even = array![2, 4].span();
let odd = array![1, 3].span();
let layout = array![251, 251].span();
set_with_index('table', 'even', 0, even, layout);
set_with_index('table', 'odd', 0, odd, layout);
let condition : WhereCondition = WhereCondition {
key: 'odd', // Replace with an appropriate key
value: '1', // Replace with an appropriate value
};
let (keys, values) = scan('table', Option::Some((condition)), 2, layout);
let res = *keys.at(0);
res.print();
}Recommendation
Review the logic around WhereCondition in the function query(...). If it’s no longer being used, consider removing it.
Resolution
The WhereClause was deprecated in 98ed1689eabad628331789c82ac01fdb3ff7e173.
| File | Fix commit | Type | Status |
world.cairo | fdebe59 | Best Practices | Fixed |
The approach for setting a boolean value is differentiated across functions revoke_owner(...) and revoke_write(...). The first function applies the following line:
self.owners.write((resource, address), bool::False(()));While the second one uses simple false:
self.writers.write((model, system), false);In practice, there is no distinction. However, adhering to consistent coding practices is advisable.
Recommendation
Standardize the approach for setting boolean values.
Resolution
Updated in fdebe59d0997811b763d3059467fcb1d20b1a987.
| File | Fix commit | Type | Status |
world.cairo | ef92799 | Best Practices | Fixed |
Documentation for functions and contracts plays a crucial role in providing clarity on expected behaviour and the parameters required for utilizing specific functionality. Accurate comments (inline documentation) are essential for facilitating a clear understanding for developers, auditors, and users.
The inline documentation is wrongly written for the following functions:
set_entity(...);delete_entity(...);entity(...);entities(...);entity_ids(...);upgrade_contract(...);deploy_contract(...);set_metadata_uri(...);metadata_uri(...);Recommendation
Consider changing the documentation to describe the correct implementation of the functions.
Resolution
Documentation updated in ef9279995afd379cb13f7dabb2b8c6912b9b8690 with error refactoring.
| File | Fix commit | Type | Status |
world.cairo | c804b77 | Best Practices | Fixed |
The function set_executor(...) can change the executor’s address but this function can be called just by the owner of the WORLD contract. The address of the new executor can be set to any arbitrary value.
However, a potential issue may arise if the executor’s address is unintentionally set to zero or if a contract lacks the implementation of the call(...) function.
Recommendation
Consider checking if the new executor’s address is not zero and if the call(...) function is available.
Resolution
First update by verifying that the new address is not zero in c804b77e9b92a058829d4171c3a5c766832d0a50. TBD for the verification of call, should be done using interfaces instead of verification of entry point existency. But the executor may be removed anyway.
| File | Fix commit | Type | Status |
components/upgradeable.cairo | — | Best Practices | Acknowledged |
The upgrade method is already checking that the caller is a world address. However, there is no way that caller’s address can be zero. So first assertion
assert(
self.get_contract().world().contract_address.is_non_zero(),
Errors::INVALID_WORLD_ADDRESS
);is unnecessary in this case.
Recommendation
Consider removing this assertion.
Resolution
If the contract has the world dispatcher uninitialized in the storage, the contract address will be 0. Then, even if there is a low chance to have the get_caller_address() to be zero, this is technically possible, and the second assertion alone is not enough to prevent this situation.
| File | Fix commit | Type | Status |
world.cairoexecutor.cairo | 9a94a39e95153c73d7809c04ffa5572fdc8 | Best Practices | Fixed |
The codebase contains several variables that are declared but never used.
delete_entity(...) defines a model_class_hash variable that is not used;entities(...) has an index input parameter that is never used;EXECUTE_ENTRYPOINT in executor.cairo is not used anywhere;Recommendation
Consider deleting unused variables.
Resolution
This was solved by several commits: delete_entity in 9a94a397867928347955b61bd3df2bd4b3355fc3. entities() removed as never used for now in e95153c46cfcb2e83a21f31ded201b41a6b0c2d6. EXECUTE_ENTRYPOINT removed in 73d78093f4f1e0df95b4874c8b00af80b5034601.
Update from Nethermind Security
The changes in the code introduced unused storage variable metadata_uri in the world.cairo.
Update from the client
Fixed in c04ffa5c42c31b5cf90f6fca5bd1ea7b675e938b and 572fdc8a0d46d6a286dae8014d5824e6a34acd2d.
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:
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.
The Dojo team has provided documentation about their core game engine in the codebase comments and through their official documentation - Dojo Book. Moreover, the Dojo team was available to address any inquiries or concerns raised by the Nethermind auditors.
| 60Tests passed | 0Failed |
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.
The Leading Engineers of Blockchain Infrastructure