Download audit report
This document presents the security review performed by Nethermind on the Briq Protocol project written in the Cairo Language. The project is composed of 32 contracts (note that not all of these are in-scope for this audit). The Briq Protocol is based on the ERC-1155 standard with the ability to combine these tokens together into "sets" which are based on the ERC-721 standard. Most of the interactions with the protocol occur using materials (sometimes combined with unique ids), instead of typical token id’s.
During the initial audit, we concluded that the project can benefit from better technical documentation detailing a) use cases, b) functional requirements, c) non-functional requirements, d) diagrams showing how interactions take place, and e) a more extensive test suite. The audit was carried out using manual inspection of the code base and the generation of test cases. Most of the reported issues are related to missing validations, overflow risks, and non-defensive code. The initial audit reports 33 findings.
During the re-audit phase, the client has fixed 20 issues, acknowledged 6 issues, and not fixed 7 issues. The clarification for not fixing these issues is presented along this report. Some of these issues require more time to seek a better solution, while others are planned to be fixed during a final code cleanup.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | May 27, 2022 |
| Response from Client | Jun 3, 2022 |
| Final Report | Jun 7, 2022 |
| Methods | Manual Review, Creation of Test Cases |
| Repository | https://github.com/briqNFT/briq-protocol |
| Commit Hash (Initial Audit) | fa896be142 |
| Commit Hash (Final Audit) | 5368018c94 |
| Documentation | https://github.com/briqNFT/briq-protocol/tree/next/docs/briq |
| Cairo Files Reviewed (Initial Review) | |
Findings by severity
| File |
contracts/briq_erc1155_like/* |
contracts/library_erc721/* |
contracts/set_erc721/* |
contracts/upgrades/* |
contracts/utilities/* |
contracts/briq_impl.cairo |
contracts/set_impl.cairo |
contracts/types.cairo |
No system overview is included in this report.
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.
with_attr| File | Fix commit | Type | Status |
contracts/* | — | Info | Unresolved |
Failing asserts should use with_attr to have an error message on failure to make end users understand what may be happening when transactions fail.
Recommendation
Use with_attr to add error messages to asserts that can be expected to fail during normal use of the protocol.
Resolution
Aware, intend to fix some incrementally.
| File | Fix commit | Type | Status |
contracts/utilities/UInt256_felt_conv.cairo | c8b533d | Info | Fixed |
The name of the file UInt256_felt_conv.cairo is incorrect, it should be named Uint256_felt_conv.cairo. This filename issue causes the test tests/set_impl_test.py to fail.
Recommendation
Rename the file UInt256_felt_conv.cairo to Uint256_felt_conv.cairo.
Resolution
Mac Os is case insensitive which is why I missed this.
| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/transferability.cairo | — | Info | Acknowledged |
The privileged address _set_backend_address is able to control all funds on behalf of any user. Although the current protocol design relies on this feature, there are no safety features in place in the event that _set_backend_address is set to an incorrect or malicious address, which can lead to asset losses.
Recommendation
Clearly state in the user facing documentation the privileges, roles, and functions that can be performed by each entity of the application. In the interest of both the users and protocol owners it is recommended to have safety features in place to prevent an incorrect or dangerous address from being set.
Resolution
Documentation will need to be updated. Not sure on possible mitigation.
contracts/briq_erc1155_like/balance_enumerability.cairobalance_enumerability.cairo| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/balance_enumerability.cairo | — | Low | Acknowledged |
The contract is not emitting events for important state transitions. The events are important for post-deployment monitoring. A list of functions not emitting events is presented below.
func _setTokenByOwner(...)
func _unsetTokenByOwner(...)
func _setMaterialByOwner(...)
func _maybeUnsetMaterialByOwner(...)Recommendation
Emit events for post-deployment monitoring.
Resolution
Likely a WONTFIX for now - these can be reconstructed from other events, such as Transfer.
ownerOf_(...)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/balance_enumerability.cairo | 963350a | Info | Fixed |
The function balance_enumerability.ownerOf_(...) has the following inline comment.
# OZ: don't fail on res == 0, since 0 is impossible.It is unclear why res==0 is impossible. Since this is a view function, it can be called by anyone with any input parameter passed as token_id, including non-existent tokens. The code is reproduced below.
@view
func ownerOf_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (token_id: felt) -> (owner: felt):
let (res) = _owner.read(token_id)
# OZ : don't fail on res == 0, since 0 is impossible.
return (res)
endRecommendation
Please, clarify this use case and explain why res cannot be zero.
Resolution
This is an unclear comment. My note means that unlike the OZ / ERC1155 standard, I don’t assert 0, I just return 0. Value ’0’ is impossible for a briq token to legitimately take, and I don’t care to assert 0. Changed the comment.
contracts/briq_erc1155_like/minting.cairotoken_id zero can be minted| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/minting.cairo | 7ebfab2 | High | Fixed |
The function mintOneNFT_(...) does not have input validation to ensure that material is within the valid range of 1 to 2ˆ64 - 1. The token_id to be minted is calculated with the formula token_id = id * 2**64 + material which means that it is possible to set material and uid to values that satisfy material == (uid * 2**64) * -1 which will result in a token_id of zero, as shown in the code below:
@external
func minting.mintOneNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, material: felt, uid: felt):
_onlyAdminAndMintContract()
assert_not_zero(owner)
assert_not_zero(material)
assert_not_zero(uid)
assert_lt_felt(uid, 2**188)
# Update total supply.
let (res) = _total_supply.read(material)
_total_supply.write(material, res + 1)
# NFT conversion
let briq_token_id = uid * 2**64 + material
let (curr_owner) = _owner.read(briq_token_id)
assert curr_owner = 0
_owner.write(briq_token_id, owner)
_setMaterialByOwner(owner, material, 0)
_setTokenByOwner(owner, material, briq_token_id, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, 0, owner, briq_token_id, 1)
return ()
endThe following test(s) can be added to tests/briq_impl_test.py to verify this behavior:
@pytest.mark.asyncio
async def test_mint_token_id_zero(briq_contract):
# The specific values that `material` and `uid` must be to create a token id of zero
maliciousMaterial = -abs(2**64)
maliciousUid = 1
maliciousTokenId = maliciousUid * 2**64 + maliciousMaterial
# Mint an NFT token
await invoke_briq(briq_contract.mintOneNFT(owner=OTHER_ADDRESS, material=maliciousMaterial, uid=maliciousUid))
# Get the owner of token id `0`
zeroTokenOwner = (await briq_contract.ownerOf(0).call()).result.owner
# Assert that the owner of the zero token is now assigned to an address
assert zeroTokenOwner == OTHER_ADDRESSIt is only possible to create one of these tokens as any future mints check the owner of the "zerotoken" which will return a non-zero value. This "zerotoken" cannot be transferred or enumerated in balances as logic for checking balances relies on the token_id of zero to end recursion. However it permanently affects the user’s _materials_by_owner data as the material associated with the "zerotoken" cannot be removed.
Recommendation
The function must validate that material in within the range of 1 to 2ˆ64 - 1. Check for overflows on briq_token_id.
Resolution
Fixed in MintOneNFT_. A similar problem existed in MintFT_ that led to a weird state. Both fixed.
| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/minting.cairo | 757870a | High | Fixed |
The function mintFT_(...) does not check for overflows on the variable balance before writing to storage. Depending on the existing balance of owner different behavior will be observed. It is possible to use mintFT(...) to reduce a users balance and it is also possible to overflow a users balance to wrap around from zero to the Starknet P prime value. The code is reproduced below:
@external
func minting.mintFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, material: felt, qty: felt):
_onlyAdminAndMintContract()
assert_not_zero(owner)
assert_not_zero(material)
assert_not_zero(qty)
# Update total supply.
let (res) = _total_supply.read(material)
_total_supply.write(material, res + qty)
# FT conversion
let briq_token_id = material
let (balance) = _balance.read(owner, briq_token_id)
_balance.write(owner, briq_token_id, balance + qty)
_setMaterialByOwner(owner, material, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, 0, owner, briq_token_id, qty)
return ()
endThe following test(s) can be added to tests/briq_impl_test.py to verify this behavior:
@pytest.mark.asyncio
async def test_mint_fungible_overflow_reduce_balance(briq_contract):
# Mint 100 fungible tokens to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=100))
# Record the balance before
balanceBefore = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=1).call()).result.balance
# Mint -10 fungible tokens to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=-10))
# Record the balance after
balanceAfter = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=1).call()).result.balance
# Calling mint with an extremely large value causes an overflow which reduces the balance
assert balanceAfter < balanceBefore
@pytest.mark.asyncio
async def test_mint_fungible_overflow_from_empty_balance(briq_contract):
# Mint -10 fungible tokens to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=-10))
# Record the balance
balance = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=1).call()).result.balance
# Balance is extremely large
# The value of balance will specifically be the `P` prime value of Starknet minus 10
assert balance > 1000000000000000000000000000000000000000000000000000000000000Recommendation
Assert that the argument qty in the function mintFT_(...) is a positive number.
Resolution
The balance reduction issue is fixed. A similar issue existed for total supply for both FT and NFT, and has been fixed. The problem of minting negative numbers is left in but explicited, since this is just an interface issue (equivalent to minting a huge amount of FT).
minting.cairo| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/minting.cairo | — | Low | Acknowledged |
The contract does not emit events for important state transitions. Events are important for post-deployment monitoring. A list of functions with missing events is presented below:
func setMintContract_(...)
func mintFT_(...)
func mintOneNFT_(...)Recommendation
Emit events for these functions.
Resolution
SetMintContract should, the rest is reconstructed from Transfer().
_mint_contract can be set to address(0x0)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/minting.cairo | — | Info | Acknowledged |
The function setMintContract_(...) allows _mint_contract to be set to address(0x0). The code is reproduced below:
@external
func minting.setMintContract_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (address: felt):
_onlyAdmin()
_mint_contract.write(address)
return ()
endRecommendation
If this is intended functionality designed to disable minting from the _mint_contract address, it is recommended to create a separate function specifically for halting minting from _mint_contract. Otherwise, it is recommended to check that the argument address is not address(0x0).
Resolution
The contract will be removed in the genesis sale, so the code will be removed. As things stand, it is indeed just disabled and just looks odd.
contracts/briq_erc1155_like/convert_mutate.cairomutateFT_(...)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | 5368018 | High | Fixed |
In the function mutateFT_(...) the storage variables _balance and _total_supply are written without any checks to ensure that no overflows can occur. The function is reproduced below:
@external
@external
func mutateFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, source_material: felt, target_material: felt, qty: felt):
_onlyAdmin()
assert_not_zero(qty * (source_material - target_material))
let (balance) = _balance.read(owner, source_material)
assert_le_felt(qty, balance)
_balance.write(owner, source_material, balance - qty)
let (balance) = _balance.read(owner, target_material)
_balance.write(owner, target_material, balance + qty)
let (res) = _total_supply.read(source_material)
_total_supply.write(source_material, res - qty)
let (res) = _total_supply.read(target_material)
_total_supply.write(target_material, res + qty)
_setMaterialByOwner(owner, target_material, 0)
_maybeUnsetMaterialByOwner(owner, source_material)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, source_material, qty)
TransferSingle.emit(__addr, 0, owner, target_material, qty)
return ()
endRecommendation
Check for overflows before writing to storage. In case of overflow, revert.
material of zero| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | 5368018 | High | Fixed |
The function mutateFT_(...) does not assert that the argument target_material is not zero and allows for fungible Briq tokens to be mutated to have a material of zero. The function is reproduced below:
@external
func mutateFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, source_material: felt, target_material: felt, qty: felt):
_onlyAdmin()
assert_not_zero(qty * (source_material - target_material))
let (balance) = _balance.read(owner, source_material)
assert_le_felt(qty, balance)
_balance.write(owner, source_material, balance - qty)
let (balance) = _balance.read(owner, target_material)
_balance.write(owner, target_material, balance + qty)
let (res) = _total_supply.read(source_material)
_total_supply.write(source_material, res - qty)
let (res) = _total_supply.read(target_material)
_total_supply.write(target_material, res + qty)
_setMaterialByOwner(owner, target_material, 0)
_maybeUnsetMaterialByOwner(owner, source_material)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, source_material, qty)
TransferSingle.emit(__addr, 0, owner, target_material, qty)
return ()
endThe following test(s) can be added to tests/briq_impl_test.py to verify this behavior:
@pytest.mark.asyncio
async def test_mutate_ft_material_zero(briq_contract):
# Mint 100 fungible tokens of material `1` to `ADDRESS`
await invoke_briq(briq_contract.mintFT(owner=ADDRESS, material=1, qty=100))
# Mutate 10 of the tokens to a new material with id zero
await invoke_briq(briq_contract.mutateFT(owner=ADDRESS, source_material=1, target_material=0, qty=10))
# Get the balance of `ADDRESS` for material with id zero
balanceMaterialZero = (await briq_contract.balanceOfMaterial(owner=ADDRESS, material=0).call()).result.balance
assert balanceMaterialZero == 10Recommendation
Assert that the argument target_material in the function mutateFT_(...) cannot be zero.
token_id of zero| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | 5368018 | High | Fixed |
In the function mutateOneNFT_(...) after briq_token_id has been calculated for the second time there is no check to ensure that the value is zero. The variable briq_token_id is calculated with the formula briq_token_id = uid * 2**64 + target_material which means that it is possible to set target_material and uid to values that satisfy target_material == (uid * 2**64) * -1 which will result in a briq_token_id of zero. The code is reproduced below:
@external
func mutateOneNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, source_material: felt, target_material: felt, uid: felt, new_uid: felt):
_onlyAdmin()
assert_lt_felt(uid, 2**188)
assert_lt_felt(new_uid, 2**188)
assert_not_zero(source_material - target_material)
# NFT conversion
let (res) = _total_supply.read(source_material)
_total_supply.write(source_material, res - 1)
let briq_token_id = uid * 2**64 + source_material
let (curr_owner) = _owner.read(briq_token_id)
assert curr_owner = owner
_owner.write(briq_token_id, 0)
_unsetTokenByOwner(owner, source_material, briq_token_id)
_maybeUnsetMaterialByOwner(owner, source_material) # Keep after unset token or it won't unset
let (res) = _total_supply.read(target_material)
_total_supply.write(target_material, res + 1)
# briq_token_id is not the new ID
let briq_token_id = new_uid * 2**64 + target_material
let (curr_owner) = _owner.read(briq_token_id)
assert curr_owner = 0
_owner.write(briq_token_id, owner)
_setMaterialByOwner(owner, target_material, 0)
_setTokenByOwner(owner, target_material, briq_token_id, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, uid * 2**64 + source_material, 1)
TransferSingle.emit(__addr, 0, owner, new_uid * 2**64 + target_material, 1)
Mutate.emit(owner, uid * 2**64 + source_material, new_uid * 2**64 + target_material, source_material,,! target_material)
return ()
endThe following test(s) can be added to briq_impl_test.py to verify this behavior:
@pytest.mark.asyncio
async def test_mutate_one_nft_token_id_zero(briq_contract):
# Values for the NFT before the mutation
beforeUid = 1
beforeMaterial = 1
beforeTokenId = beforeUid * 2**64 + beforeMaterial
# Mint an NFT token
await invoke_briq(briq_contract.mintOneNFT(owner=ADDRESS, material=beforeMaterial, uid=beforeUid))
# The specific values needed to have a token id of zero after mutate
afterUid = 2
afterMaterial = -abs(2 * (2**64))
afterTokenId = afterUid * 2**64 + afterMaterial
# Mutate the NFT token
await invoke_briq(briq_contract.mutateOneNFT(owner=ADDRESS, source_material=beforeMaterial,,! target_material=afterMaterial, uid=beforeUid, new_uid=afterUid))
# Get the owner of token id `0`
zeroTokenOwner = (await briq_contract.ownerOf(0).call()).result.owner
# Assert that the owner of the zero token is now assigned to an address
assert zeroTokenOwner == ADDRESSRecommendation
The function must validate that both source_material and ‘target_material are within the range of 1 to 2ˆ64 - 1. Add a check to briq_token_id before writing to storage to ensure that the value is not zero.
| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | 5368018 | High | Fixed |
The function convertOneToNFT_(...) does not ensure that the fungible token balance of owner is sufficient. This allows a non-fungible Briq token to be created even if owner has no fungible tokens of the given material. The process of reducing the fungible token balance for the owner whose balance is zero will also cause an overflow upon writing to _balance which will change their fungible token balance to STARKNET_PRIME - 1. The code is shown below:
@external
func convertOneToNFT_{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr
} (owner: felt, material: felt, uid: felt):
_onlyAdmin()
assert_not_zero(owner)
assert_not_zero(material)
assert_lt_felt(uid, 2**188)
# NFT conversion
let token_id = uid * 2**64 + material
let (curr_owner) = _owner.read(token_id)
assert curr_owner = 0
_owner.write(token_id, owner)
# No need to change material
_setTokenByOwner(owner, material, token_id, 0)
let (balance) = _balance.read(owner, material)
_balance.write(owner, material, balance - 1)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, material, 1)
TransferSingle.emit(__addr, 0, owner, token_id, 1)
ConvertToNFT.emit(owner, material, token_id)
return ()
endThe following test(s) can be added to briq_impl_test.py to verify this behavior:
@pytest.mark.asyncio
async def test_convert_ft_to_nft_no_balance(briq_contract):
# Convert immediately without minting any tokens
await invoke_briq(briq_contract.convertOneToNFT(owner=ADDRESS, material=1, uid=1))
# Account `ADDRESS` now has a balance issue so to confirm the NFT was created transfer it to observe the balance on,! another account
await invoke_briq(briq_contract.transferOneNFT(sender=ADDRESS, recipient=OTHER_ADDRESS, material=1 ,,! briq_token_id=1 * 2**64 + 1), ADDRESS)
# Get the balance of the address that received the newly created NFT
materialBalance = (await briq_contract.balanceOfMaterial(owner=OTHER_ADDRESS, material=1).call()).result.balance
# Get the balance of fungible tokens owned by `ADDRESS`
fungibleBalance = (await briq_contract.balanceDetailsOfMaterial_(owner=ADDRESS,,! material=1).call()).result.ft_balance
# Balance of `ADDRESS` is now a very large value
assert fungibleBalance == 3618502788666131213697322783095070105623107215331596699973092056135872020480
# The NFT has successfully been transferred to another address
assert materialBalance == 1Recommendation
Ensure that the fungible token balance for owner is enough to convert a fungible token into a non-fungible token.
convertOneToNFT_(...)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | 5368018 | High | Fixed |
The parameters material and uid are not checked for range and validity. There are also no checks for overflow. The code is presented below.
@external
func convertOneToNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (owner: felt, material: felt, uid: felt):
_onlyAdmin()
assert_not_zero(owner)
assert_not_zero(material)
assert_lt_felt(uid, 2**188)
# NFT conversion
let token_id = uid * 2**64 + material
let (curr_owner) = _owner.read(token_id)
assert curr_owner = 0
_owner.write(token_id, owner)
# No need to change material
_setTokenByOwner(owner, material, token_id, 0)
let (balance) = _balance.read(owner, material)
_balance.write(owner, material, balance - 1)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, owner, 0, material, 1)
TransferSingle.emit(__addr, 0, owner, token_id, 1)
ConvertToNFT.emit(owner, material, token_id)
return ()
endRecommendation
Check material and uid for range and validity. Check for overflow. In case of error, revert.
uid can be same as existing uid when mutating non-fungible Briq tokens| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | 5368018 | Info | Fixed |
On L78 there is a comment that states that new_uid should be different to uid however this is not enforced in the function mutateOneNFT_(...) and it is possible to mutate a non-fungible Briq token to have a different material and the same uid. This has been set to an undetermined severity because the reason for changing the uid is that the UI can potentially conflict, however we do not know the full impact of conflicting uids on the front-end for the project. The following test(s) can be added to briq_impl_test.py to verify this behavior:
@pytest.mark.asyncio
async def test_mutate_one_nft_same_uid(briq_contract):
# Values for the NFT before the mutation
beforeUid = 1
beforeMaterial = 1
beforeTokenId = beforeUid * 2**64 + beforeMaterial
# Mint an NFT token
await invoke_briq(briq_contract.mintOneNFT(owner=ADDRESS, material=beforeMaterial, uid=beforeUid))
# The specific values needed to have a token id of zero after mutate
afterUid = beforeUid
afterMaterial = 2
afterTokenId = afterUid * 2**64 + afterMaterial
# Mutate the NFT token
await invoke_briq(briq_contract.mutateOneNFT(owner=ADDRESS, source_material=beforeMaterial,,! target_material=afterMaterial, uid=beforeUid, new_uid=afterUid))
# No asserts needed, if this test passes then the NFT token has successfully been mutated while having the same uidRecommendation
Add a check to ensure that uid and new_uid are not the same.
Resolution
I think this is a broken comment, actually. The general behavior is that new_uid == uid, and that is expected to work. However, since there can be a token_id with target_material and new_uid already, there is an option to pass a new_uid different to uid. The comment is rather unclear, but this is all working. I’ve rephrased.
convert_mutate.cairo| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | — | Info | Unresolved |
The following imports are not used in the file convert_mutate.cairo:
SignatureBuiltinget_caller_addressassert_nn_leassert_ltassert_leget_fp_and_pcallocRecommendation
Remove the unused imports.
Resolution
Will clean up at a later stage.
mutateFT_(...)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/convert_mutate.cairo | — | Info | Acknowledged |
The function mutateFT_(...) does not emit a Mutate event like other mutate function mutateOneNFT_(...).
Recommendation
Add an event emission for calls to mutateFT_(...).
Resolution
This was on purpose, the tokens being fungible, mutation is equivalent to burning and minting a corresponding amount (whereas we want to track NFTs, potentially). Having a dedicated event could still be useful, I’ll consider it.
contracts/briq_erc1155_like/transferability.cairotransferOneNFT_(...)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/transferability.cairo | d3938b4 | High | Fixed |
The function transferOneNFT_(...) does not validate the input parameters recipient, material, and briq_token_id. The input parameters material and briq_token_id are not checked to be within a valid range. The recipient is not checked for address(0x0). The code is reproduced below.
@external
func transferOneNFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, material: felt, briq_token_id: felt):
_onlySetAnd(sender)
assert_not_zero(sender)
assert_not_zero(material)
assert_not_zero(briq_token_id)
let (curr_owner) = _owner.read(briq_token_id)
assert sender = curr_owner
_owner.write(briq_token_id, recipient)
# Unset before setting, so that self-transfers work.
_unsetTokenByOwner(sender, material, briq_token_id)
_setTokenByOwner(recipient, material, briq_token_id, 0)
_maybeUnsetMaterialByOwner(sender, material) # Keep after unset token or it won't unset
_setTokenByOwner(recipient, material, briq_token_id, 0)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, sender, recipient, briq_token_id, 1)
return ()
endRecommendation
The function must check recipient for address(0x0). It must also assure that material and briq_token_id are valid identifiers.
Resolution
Asserted recipient and material / briq_token_id accordingly.
transferability.cairo| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/transferability.cairo | — | Low | Acknowledged |
The contract is not emitting events for important state transitions. The events are important for post-deployment monitoring. A list of functions that should emit events is presented below.
func setSetAddress_(...)
func transferFT_(...)Recommendation
Consider emitting events for the functions listed above.
Resolution
SetSetAddress should, the rest are reconstructed from Transfer().
setSetAddress_(...)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/transferability.cairo | — | Low | Unresolved |
The function setSetAddress_(...) does not validate the input parameter address. Although the function can only be called by the admin, the function can be more robust. Users also need protection from admin actions. Moreover, the function also does not emit an event. The code is reproduced below:
@external
func setSetAddress_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (address: felt):
_onlyAdmin()
_set_backend_address.write(address)
return ()
endRecommendation
The function must assert that the input parameter address is different from address(0x0). The function should also emit an event.
Resolution
Similar class of problem to other privileged functions. Not entirely sure how to proceed at the moment.
transferFT_(...)| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/transferability.cairo | 4052be9 | Info | Fixed |
The function transferFT_(...) does not explicitly check for overflows when updating the senders and receivers balance. The code is reproduced below:
@external
func transferFT_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, material: felt, qty: felt):
_onlySetAnd(sender)
assert_not_zero(sender)
assert_not_zero(material)
assert_not_zero(qty)
# FT conversion
let briq_token_id = material
let (balance_sender) = _balance.read(sender, briq_token_id)
assert_le_felt(qty, balance_sender)
_balance.write(sender, briq_token_id, balance_sender - qty)
let (balance) = _balance.read(recipient, briq_token_id)
_balance.write(recipient, briq_token_id, balance + qty)
_setMaterialByOwner(recipient, material, 0)
_maybeUnsetMaterialByOwner(sender, material)
let (__addr) = get_contract_address()
TransferSingle.emit(__addr, sender, recipient, briq_token_id, qty)
return ()
endRecommendation
Check for overflows before writing to _balance for both the sender and receiver.
Resolution
Added check. Interestingly, balanceOf_’s result can overflow from too many FT and NFT at once. I suppose I can’t really fix that too easily here.
| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/transferability.cairo | 1c54991 | Info | Fixed |
The functions transferFT_(...) and transferOneNFT_(...) allow the sender and receiver address to be the same. Currently this doesn’t introduce any bugs, however given that this protocol is still under development any changes may create bugs in the future.
Recommendation
During the discussion between the Nethermind and Briq teams it was mentioned that self transfers are not necessary for the protocol and do not benefit the user in any way. Since self transfers are not necessary for the protocol it is recommended to remove this feature as any changes to the protocol may introduce bugs related to self transfers in the future.
Resolution
Asserted against.
transferability.cairo| File | Fix commit | Type | Status |
contracts/briq_erc1155_like/transferability.cairo | — | Info | Unresolved |
The following imports are not used in the file transferability.cairo:
assert_nn_leassert_ltassert_lt_feltget_fp_and_pcallocRecommendation
Remove the unused imports.
Resolution
Planning to do a cleanup pass.
contracts/library_erc721/transferability_enum.cairotransferFrom_(...)| File | Fix commit | Type | Status |
contracts/library_erc721/transferability_enum.cairo | ab7111e | High | Fixed |
The function transferFrom_(...) does not check if the token_id is within a valid range, the sender and the recipient for address(0x0). It also does not check if sender is different from recipient. The function is reproduced below.
@external
func transferFrom_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, token_id: felt):
ERC721_approvals._onlyApproved(sender, token_id)
ERC721_lib_transfer._transfer(sender, recipient, token_id)
# Unset before setting, so that self-transfers work.
ERC721_enumerability._unsetTokenByOwner(sender, token_id)
ERC721_enumerability._setTokenByOwner(recipient, token_id, 0)
return ()
endRecommendation
Validate the token_id, sender, and recipient.
Resolution
Added checks in the called _transfer function.
| File | Fix commit | Type | Status |
contracts/library_erc721/transferability_enum.cairo | d1f75e5 | Info | Fixed |
The namespace title ERC271_transferability appears to be a spelled incorrectly, it should be ERC721_transferability. This issue extends into contracts/set_impl.cairo on L27 and L55 where the import also uses the same spelling error.
Recommendation
Rename the namespace to ERC721_transferability and reflect these changes in contracts/set_impl.cairo
contracts/set_impl.cairoview visibility making changes to state| File | Fix commit | Type | Status |
contracts/set_impl.cairo | 89fdd2d | Info | Fixed |
The functions assemble(...), disassemble(...) and transferOneNFT(...) use the @view decorator. However, these functions make state changes.
Recommendation
Change the decorators for assemble(...), disassemble(...) and transferOneNFT(...) to use the @external decorator.
Resolution
Changed to external.
contracts/briq_impl.cairo| File | Fix commit | Type | Status |
contracts/briq_impl.cairo | — | Info | Unresolved |
The functions balanceOf_(...), balanceDetailsOf_(...), multiBalanceOf_(...), totalSupply_(...) use the implicit argument bitwise_ptr which is unused by all functions. The relevant functions are shown below: disa
Recommendation
Remove the implicit argument bitwise_ptr from the relevant functions.
Resolution
I think I’ve added them to some of these because called functions use it and it avoids having to set local pointers. I also think that cairo-lang itself might evolve to make these redundant. Will consider in the future a cleanup here.
contracts/upgrades/proxy.cairoproxy.constructor(...)| File | Fix commit | Type | Status |
contracts/upgrades/proxy.cairo | 4f03d9c | Info | Fixed |
The proxy.constructor(...) does not emit any event. However, it performs important state changes: a) define the admin of the application; b) set the implementation address. The admin and the implementation_address are not checked for address(0x0). The code is shown below.
func constructor{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
}(admin: felt, implementation_address: felt):
Proxy_initializer(admin)
Proxy_set_implementation(implementation_address)
return ()
endRecommendation
Emit an event in the proxy.constructor(...) containing admin and the implementation_address. This event will be important to check that addresses have been set accordingly. Check admin and implementation_address for address(0x0).
Resolution
Done on my end of the contracts. Ideally, Open Zeppelin will change their code on that side.
contracts/upgrades/upgradable_mixin.cairoRootAdmin| File | Fix commit | Type | Status |
contracts/upgrades/upgradable_mixin.cairo | 4f03d9c | Low | Fixed |
The function upgradable_mixin.setRootAdmin_(...) does not emit any event. It calls the function library.Proxy_set_admin(...), which also does emit any event. Both functions do not check the new_admin for address(0x0). The code of both functions are presented below.
func upgradable_mixin.setRootAdmin_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (new_admin: felt):
_onlyAdmin()
Proxy_set_admin(new_admin)
return ()
end
func library.Proxy_set_admin{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
}(new_admin: felt):
Proxy_admin.write(new_admin)
return ()
endRecommendation
Emit an event in library.Proxy_set_admin(...) containing the new_admin. Check the new_admin of both functions for address(0x0). If the check is true, revert.
Resolution
Done on my end of the contracts. Ideally, Open Zeppelin will change their code on that side.
contracts/library_erc721/approvals.cairoapprovals.cairo| File | Fix commit | Type | Status |
contracts/library_erc721/approvals.cairo | — | Low | Unresolved |
The contract is not emitting events for important state transitions. The events are important for post-deployment monitoring. A list of functions not emitting events is presented below.
func approve_(...)
func setApprovalForAll_(...)Recommendation
Emit events for the functions listed above.
Resolution
Need to be added, as those are defined in ERC721 too.
contracts/library_erc721/transferability_library.cairo_transfer(...)| File | Fix commit | Type | Status |
contracts/library_erc721/transferability_library.cairo | 4477d5d | High | Fixed |
The function _transfer(...) does not check if balance has overflowed before writing to storage variable _balance for both the sender and recipient. The code is reproduced below:
func _transfer{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
range_check_ptr
} (sender: felt, recipient: felt, token_id: felt):
# Reset approval (0 cost if was 0 before on starknet I believe)
ERC721_approvals.approve_nocheck_(0, token_id)
let (curr_owner) = _owner.read(token_id)
assert sender = curr_owner
_owner.write(token_id, recipient)
let (balance) = _balance.read(sender)
_balance.write(sender, balance - 1)
let (balance) = _balance.read(recipient)
_balance.write(recipient, balance + 1)
_onTransfer(sender, recipient, token_id)
return ()
endRecommendation
Check for overflows on balance before writing to storage variable _balance.
Resolution
Overflow check added.
contracts/set_erc721/token_uri.cairo| File | Fix commit | Type | Status |
contracts/set_erc721/token_uri.cairo | — | Low | Unresolved |
The function setTokenURI_(...) has a comment stating that the function should be used for testing only. It is generally recommended to separate smart contract code used exclusively in testing from core protocol smart contract code. The function is reproduced below:
## Testing only
@external
func setTokenURI_{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
bitwise_ptr: BitwiseBuiltin*,
range_check_ptr
} (token_id: felt, uri_len: felt, uri: felt*):
alloc_locals
_onlyAdmin()
# TODO: is this useless?
let (owner) = _owner.read(token_id)
assert_not_zero(owner)
_setTokenURI(0, token_id, uri_len, uri)
URI.emit(uri_len, uri, token_id)
return()
endRecommendation
Move setTokenURI_ to a separate contract which imports set_impl.cairo to create a separation of concerns between testing code and protocol code.
Resolution
Planned but not fixed yet. Only admins can use it also mitigates the problem.
0 or 1| File | Fix commit | Type | Status |
contracts/set_erc721/token_uri.cairo | 402976a | Info | Fixed |
The function _setTokenURI is an internal function and is only called with may_use_special_token_mode set to 0 or 1. However this is not asserted inside _setTokenURI. If may_use_special_token_mode is at some point in the future determined non-deterministically this would allow uri_len * may_use_special_token_mode == 2 condition to pass with an invalid uri array. The function is reproduced below:
func _setTokenURI{
syscall_ptr: felt*,
pedersen_ptr: HashBuiltin*,
bitwise_ptr: BitwiseBuiltin*,
range_check_ptr
} (may_use_special_token_mode: felt, token_id: felt, uri_len: felt, uri: felt*):
assert_not_zero(uri_len)
assert_lt_felt(uri[0], 2**249)
# This is 0 or 1
if uri_len * may_use_special_token_mode == 2:
let (rem) = bitwise_and(uri[1], 2**59 - 1)
if uri[1] == rem:
# The rest has already been written in the token-id
# Flag it with both special bits for continuation and 'part of token_id'.
_token_uri.write(token_id, uri[0] * 4 + 3)
return ()
end
# Write the first URI with the special continuation LSB
_token_uri.write(token_id, uri[0] * 4 + 1)
_setExtraTokenURI(token_id, uri_len - 2, 0, uri + 1)
# event_uri.emit(token_id, uri_len, uri)
else:
if uri_len == 1:
# Just write the URI normally.
_token_uri.write(token_id, uri[0] * 4)
return ()
end
# Write the first URI with the special continuation LSB
_token_uri.write(token_id, uri[0] * 4 + 1)
_setExtraTokenURI(token_id, uri_len - 2, 0, uri + 1)
# event_uri.emit(token_id, uri_len, uri)
end
return()
endRecommendation
To improve maintainability, there should be a check to assert that may_use_special_token_mode is a boolean value (either 0 or 1). Using the Cairo bool library is also recommended to improve readability.
Resolution
Fixed as recommended.
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.
We recommend the following improvements be made to the documentation of this project:
The test suite is reduced and validates the behavior of the application if users behave as expected. Several edge cases are not handled. Unit Testing is the testing phase where each unit in the system is individually tested. The goal is to isolate each part of the system to ensure they are working as specified. The developer must consider the requirements of each function and make sure that the input/output parameters are in range. In this sense, the system’s technical specification plays an important role in creating good test cases, delimiting the scenarios for using a function, and which situations should be avoided by each function. It is critical that the test suite be created very carefully to reduce the risk of exploits, handling edge cases, and making sure that inputs and outputs of functions are in valid ranges and that overflow has not happened.
On the other hand, systemic tests validate the integration between the various modules of the system in an production-like environment. The system must be robust enough to deal with users interacting with it in unplanned ways, such as calling functions in a different order than expected, passing wrong input values, and even trying to hack the system.
Our analysis of the code indicates that many parameters are not properly validated. It is essential to assure that each input parameter has a valid range, the user calling the function has the proper privilege, inside the function check for overflows, and making sure that the output is also in valid range. In view of this, our recommendation is to considerably expand the test suite, as well as improve the technical documentation
During the re-audit phase Cairo 0.9.0 had been released, which introduced breaking changes to smart contracts written in Cairo 0.8.0. Because there is no upper limit for the cairo-lang version in requirements.txt the new version of cairo-lang is used to compile the contracts which causes them to fail compilation and testing. In order to run the tests correctly, line 3 was changed to cairo-lang>=0.8.1,<0.9 and requirements had to be reinstalled.
,! 'asyncio_mode' default value will change to 'strict' in future, please explicitly use 'asyncio_mode=strict' or,! 'asyncio_mode=auto' in pytest configuration file.
,! the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will,! stop working
,! default value will change to 'strict' in future, please explicitly use 'asyncio_mode=strict' or,! 'asyncio_mode=auto' in pytest configuration file.
,! ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop,! working
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