Prepared by:
HALBORN
Last Updated 04/26/2024
Date of Engagement by: March 28th, 2022 - April 4th, 2022
100% of all REPORTED Findings have been addressed
All findings
5
Critical
0
High
1
Medium
0
Low
1
Informational
3
Mars Protocol
engaged Halborn to conduct a security audit on their smart contracts beginning on March 28th, 2022 and ending on April 4th, 2022. The security assessment was scoped to the smart contracts provided to the Halborn team.
The team at Halborn was provided one week for the engagement and assigned a full-time security engineer to audit the security of the smart contract. The security engineer is a blockchain and smart-contract security expert with advanced penetration testing, smart-contract hacking, and deep knowledge of multiple blockchain protocols.
The purpose of this audit is to:
Ensure that smart contract functions operate as intended
Identify potential security issues with the smart contracts
In summary, Halborn identified some improvements to reduce the likelihood and impact of multiple risks, which were accepted by Mars team
. The main ones are the following:
Implement normalization of addresses in the functions that work with addresses and avoid locked funds or unnecessary gas spending by users.
Split owner address transfer functionality to allow transfer to be
completed by the recipient.
CosmWasm Smart Contracts (a) Repository: \url{https://github.com/mars-protocol/cw-plus/} (b) Commit ID: \href{https://github.com/mars-protocol/cw-plus/tree/8191a9ddfb5fdc5f135bd7827399bd3463f444ac}{8191a9ddfb5fdc5f135bd7827399bd3463f444ac} (c) Contracts in scope: i. cw20-base ii. cw1-whitelist
Out-of-scope:
External libraries and financial related attacks
Critical
0
High
1
Medium
0
Low
1
Informational
3
Impact x Likelihood
HAL-02
HAL-01
HAL-03
HAL-04
HAL-05
Security analysis | Risk level | Remediation Date |
---|---|---|
LACK OF ADDRESS CANONICALIZATION/NORMALIZATION | High | Risk Accepted |
PRIVILEGED ADDRESS CAN BE TRANSFERRED WITHOUT CONFIRMATION | Low | Risk Accepted |
MULTIPLE INSTANCES OF UNCHECKED MATH / ARITHMETIC OVERFLOW | Informational | Acknowledged |
OVERFLOW CHECKS NOT SET FOR PROFILE RELEASE | Informational | Acknowledged |
LACK OF VERIFICATION FOR MULTIPLE MARKETING INFOS | Informational | Acknowledged |
// High
The multiple functionality of the cw20-base contract fails to consider that Terra addresses are valid both in all uppercase and all lowercase. Although valid, a strict comparison between the same address in its all uppercase version (e.g.: TERRA1KG...XNL8) and its all lowercase version (e.g.: terra1kg...xnl8) will fail.
While in the cw1-whitelist contract, the map_validate
function considers valid admin addresses in lower and upper case, however, the info.sender
address is in lower case and when compared to the same address in upper case it will not match, in this case, which may cause admin access to not be granted.
Knowing this, there are some functions that take address as input and do not normalize to manipulate them, the consequences are listed below:
In CW20-base contract, the minter and the marketing address may not be able to perform their functions if the addresses provided in the instantiate
function are in upper case.
If a user wants to increase or decrease the allowance given to a given address and use the upper case address to perform the action, the allowance will not be modified.
If a user makes a transfer on the cw20-base contract to an upper case address, the funds will be locked.
The instantiate
function implementation takes the instantiator input of minter and marketing addresses without performing any normalization:
let mint = match msg.mint {
Some(m) => Some(MinterData {
minter: deps.api.addr_validate(&m.minter)?,
cap: m.cap,
}),
None => None,
};
let data = MarketingInfoResponse {
project: marketing.project,
description: marketing.description,
marketing: marketing
.marketing
.map(|addr| deps.api.addr_validate(&addr))
.transpose()?,
logo,
};
MARKETING_INFO.save(deps.storage, &data)?;
\color{black}\color{white}The create_accounts
function does not perform normalization on the address vector (accounts
) and stores it to handle user balances.
pub fn create_accounts(deps: &mut DepsMut, accounts: &[Cw20Coin]) -> StdResult<Uint128> {
let mut total_supply = Uint128::zero();
for row in accounts {
let address = deps.api.addr_validate(&row.address)?;
BALANCES.save(deps.storage, &address, &row.amount)?;
total_supply += row.amount;
}
Ok(total_supply)
\color{black}\color{white}In the function execute_transfer
, funds can be locked if transferred to an uppercase address.
pub fn execute_transfer(
deps: DepsMut,
_env: Env,
info: MessageInfo,
recipient: String,
amount: Uint128,
) -> Result<Response, ContractError> {
if amount == Uint128::zero() {
return Err(ContractError::InvalidZeroAmount {});
}
let rcpt_addr = deps.api.addr_validate(&recipient)?;
BALANCES.update(
deps.storage,
&info.sender,
|balance: Option<Uint128>| -> StdResult<_> {
Ok(balance.unwrap_or_default().checked_sub(amount)?)
},
)?;
BALANCES.update(
deps.storage,
&rcpt_addr,
|balance: Option<Uint128>| -> StdResult<_> { Ok(balance.unwrap_or_default() + amount) },
)?;
let res = Response::new()
.add_attribute("action", "transfer")
.add_attribute("from", info.sender)
.add_attribute("to", recipient)
.add_attribute("amount", amount);
Ok(res)
}
\color{black}\color{white}The execute_mint
and execute_send
functions does not normalize the address that receives the mint (rcpt_addr
).
pub fn execute_mint(
deps: DepsMut,
_env: Env,
info: MessageInfo,
recipient: String,
amount: Uint128,
) -> Result<Response, ContractError> {
if amount == Uint128::zero() {
return Err(ContractError::InvalidZeroAmount {});
}
let mut config = TOKEN_INFO.load(deps.storage)?;
if config.mint.is_none() || config.mint.as_ref().unwrap().minter != info.sender {
return Err(ContractError::Unauthorized {});
}
// update supply and enforce cap
config.total_supply += amount;
if let Some(limit) = config.get_cap() {
if config.total_supply > limit {
return Err(ContractError::CannotExceedCap {});
}
}
TOKEN_INFO.save(deps.storage, &config)?;
// add amount to recipient balance
let rcpt_addr = deps.api.addr_validate(&recipient)?;
BALANCES.update(
deps.storage,
&rcpt_addr,
|balance: Option<Uint128>| -> StdResult<_> { Ok(balance.unwrap_or_default() + amount) },
)?;
let res = Response::new()
.add_attribute("action", "mint")
.add_attribute("to", recipient)
.add_attribute("amount", amount);
pub fn execute_send(
deps: DepsMut,
_env: Env,
info: MessageInfo,
contract: String,
amount: Uint128,
msg: Binary,
) -> Result<Response, ContractError> {
if amount == Uint128::zero() {
return Err(ContractError::InvalidZeroAmount {});
}
let rcpt_addr = deps.api.addr_validate(&contract)?;
// move the tokens to the contract
BALANCES.update(
deps.storage,
&info.sender,
|balance: Option<Uint128>| -> StdResult<_> {
Ok(balance.unwrap_or_default().checked_sub(amount)?)
},
)?;
BALANCES.update(
deps.storage,
&rcpt_addr,
|balance: Option<Uint128>| -> StdResult<_> { Ok(balance.unwrap_or_default() + amount) },
)?;
let res = Response::new()
.add_attribute("action", "send")
.add_attribute("from", &info.sender)
.add_attribute("to", &contract)
.add_attribute("amount", amount)
.add_message(
Cw20ReceiveMsg {
sender: info.sender.into(),
amount,
msg,
}
.into_cosmos_msg(contract)?,
);
Ok(res)
\color{black}\color{white}The execute_increase_allowance
and execute_decrease_allowance
functions used to manipulate allowance limits does not normalize the spender
address.
pub fn execute_increase_allowance(
deps: DepsMut,
_env: Env,
info: MessageInfo,
spender: String,
amount: Uint128,
expires: Option<Expiration>,
) -> Result<Response, ContractError> {
let spender_addr = deps.api.addr_validate(&spender)?;
if spender_addr == info.sender {
return Err(ContractError::CannotSetOwnAccount {});
}
ALLOWANCES.update(
deps.storage,
(&info.sender, &spender_addr),
|allow| -> StdResult<_> {
let mut val = allow.unwrap_or_default();
if let Some(exp) = expires {
val.expires = exp;
}
val.allowance += amount;
Ok(val)
},
)?;
let res = Response::new().add_attributes(vec![
attr("action", "increase_allowance"),
attr("owner", info.sender),
attr("spender", spender),
attr("amount", amount),
]);
Ok(res)
pub fn execute_decrease_allowance(
deps: DepsMut,
_env: Env,
info: MessageInfo,
spender: String,
amount: Uint128,
expires: Option<Expiration>,
) -> Result<Response, ContractError> {
let spender_addr = deps.api.addr_validate(&spender)?;
if spender_addr == info.sender {
return Err(ContractError::CannotSetOwnAccount {});
}
let key = (&info.sender, &spender_addr);
// load value and delete if it hits 0, or update otherwise
let mut allowance = ALLOWANCES.load(deps.storage, key)?;
if amount < allowance.allowance {
// update the new amount
allowance.allowance = allowance
.allowance
.checked_sub(amount)
.map_err(StdError::overflow)?;
if let Some(exp) = expires {
allowance.expires = exp;
}
ALLOWANCES.save(deps.storage, key, &allowance)?;
} else {
ALLOWANCES.remove(deps.storage, key);
}
\color{black}\color{white}The execute_transfer_from
, execute_burn_from
and execute_send_from
functions use addresses without normalization and this can lead to unnecessary fees spent by users.
pub fn execute_transfer_from(
deps: DepsMut,
env: Env,
info: MessageInfo,
owner: String,
recipient: String,
amount: Uint128,
) -> Result<Response, ContractError> {
let rcpt_addr = deps.api.addr_validate(&recipient)?;
let owner_addr = deps.api.addr_validate(&owner)?;
// deduct allowance before doing anything else have enough allowance
deduct_allowance(deps.storage, &owner_addr, &info.sender, &env.block, amount)?;
BALANCES.update(
deps.storage,
&owner_addr,
|balance: Option<Uint128>| -> StdResult<_> {
Ok(balance.unwrap_or_default().checked_sub(amount)?)
},
)?;
BALANCES.update(
deps.storage,
&rcpt_addr,
|balance: Option<Uint128>| -> StdResult<_> { Ok(balance.unwrap_or_default() + amount) },
)?;
let res = Response::new().add_attributes(vec![
attr("action", "transfer_from"),
attr("from", owner),
attr("to", recipient),
attr("by", info.sender),
attr("amount", amount),
]);
Ok(res)
}
pub fn execute_burn_from(
deps: DepsMut,
env: Env,
info: MessageInfo,
owner: String,
amount: Uint128,
) -> Result<Response, ContractError> {
let owner_addr = deps.api.addr_validate(&owner)?;
// deduct allowance before doing anything else have enough allowance
deduct_allowance(deps.storage, &owner_addr, &info.sender, &env.block, amount)?;
// lower balance
BALANCES.update(
deps.storage,
&owner_addr,
|balance: Option<Uint128>| -> StdResult<_> {
Ok(balance.unwrap_or_default().checked_sub(amount)?)
},
)?;
// reduce total_supply
TOKEN_INFO.update(deps.storage, |mut meta| -> StdResult<_> {
meta.total_supply = meta.total_supply.checked_sub(amount)?;
Ok(meta)
})?;
let res = Response::new().add_attributes(vec![
attr("action", "burn_from"),
attr("from", owner),
attr("by", info.sender),
attr("amount", amount),
]);
Ok(res)
}
pub fn execute_send_from(
deps: DepsMut,
env: Env,
info: MessageInfo,
owner: String,
contract: String,
amount: Uint128,
msg: Binary,
) -> Result<Response, ContractError> {
let rcpt_addr = deps.api.addr_validate(&contract)?;
let owner_addr = deps.api.addr_validate(&owner)?;
// deduct allowance before doing anything else have enough allowance
deduct_allowance(deps.storage, &owner_addr, &info.sender, &env.block, amount)?;
// move the tokens to the contract
BALANCES.update(
deps.storage,
&owner_addr,
|balance: Option<Uint128>| -> StdResult<_> {
Ok(balance.unwrap_or_default().checked_sub(amount)?)
},
)?;
BALANCES.update(
deps.storage,
&rcpt_addr,
|balance: Option<Uint128>| -> StdResult<_> { Ok(balance.unwrap_or_default() + amount) },
)?;
let attrs = vec![
attr("action", "send_from"),
attr("from", &owner),
attr("to", &contract),
attr("by", &info.sender),
attr("amount", amount),
];
// create a send message
let msg = Cw20ReceiveMsg {
sender: info.sender.into(),
amount,
msg,
}
.into_cosmos_msg(contract)?;
let res = Response::new().add_message(msg).add_attributes(attrs);
Ok(res)
}
\color{black}\color{white}The map_validate
function creates the accounts without normalizing the addresses fed by the addr
variable.
pub fn map_validate(api: &dyn Api, admins: &[String]) -> StdResult<Vec<Addr>> {
admins.iter().map(|addr| api.addr_validate(&addr)).collect()
}
RISK ACCEPTED: The Mars team
accepted the risk of this finding.
// Low
An incorrect use of the execute_update_admins
function from the contracts/cw1-whitelist/src/contract.rs contract could set the ADMIN to an invalid address, unwillingly losing control of the contract which cannot be undone in any way if this is the only admin. Currently, the ADMINS of the contracts can change its address using the aforementioned function in a single transaction
and without confirmation
from the new address.
pub fn execute_update_admins(
deps: DepsMut,
_env: Env,
info: MessageInfo,
admins: Vec<String>,
) -> Result<Response, ContractError> {
let mut cfg = ADMIN_LIST.load(deps.storage)?;
if !cfg.can_modify(info.sender.as_ref()) {
Err(ContractError::Unauthorized {})
} else {
cfg.admins = map_validate(deps.api, &admins)?;
ADMIN_LIST.save(deps.storage, &cfg)?;
let res = Response::new().add_attribute("action", "update_admins");
Ok(res)
}
}
RISK ACCEPTED: The Mars team
accepted the risk of this finding.
// Informational
In computer programming, an overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.
The config.total_supply variable is incremented without checking if the operation will exceed the type limit.
pub fn execute_mint(
deps: DepsMut,
_env: Env,
info: MessageInfo,
recipient: String,
amount: Uint128,
) -> Result<Response, ContractError> {
if amount == Uint128::zero() {
return Err(ContractError::InvalidZeroAmount {});
}
let mut config = TOKEN_INFO.load(deps.storage)?;
if config.mint.is_none() || config.mint.as_ref().unwrap().minter != info.sender {
return Err(ContractError::Unauthorized {});
}
// update supply and enforce cap
config.total_supply += amount;
if let Some(limit) = config.get_cap() {
if config.total_supply > limit {
return Err(ContractError::CannotExceedCap {});
}
}
TOKEN_INFO.save(deps.storage, &config)?;
// add amount to recipient balance
let rcpt_addr = deps.api.addr_validate(&recipient)?;
BALANCES.update(
deps.storage,
&rcpt_addr,
|balance: Option<Uint128>| -> StdResult<_> { Ok(balance.unwrap_or_default() + amount) },
)?;
let res = Response::new()
.add_attribute("action", "mint")
.add_attribute("to", recipient)
.add_attribute("amount", amount);
Ok(res)
}
At each iteration of the for loop the variable total_supply is incremented without checking whether it will exceed the maximum limit.
pub fn create_accounts(deps: &mut DepsMut, accounts: &[Cw20Coin]) -> StdResult<Uint128> {
let mut total_supply = Uint128::zero();
for row in accounts {
let address = deps.api.addr_validate(&row.address)?;
BALANCES.save(deps.storage, &address, &row.amount)?;
total_supply += row.amount;
}
Ok(total_supply)
}
When the allowance is increased there is no validation to know if the sum will cause an integer overflow in the variable val.allowance.
pub fn execute_increase_allowance(
deps: DepsMut,
_env: Env,
info: MessageInfo,
spender: String,
amount: Uint128,
expires: Option<Expiration>,
) -> Result<Response, ContractError> {
let spender_addr = deps.api.addr_validate(&spender)?;
if spender_addr == info.sender {
return Err(ContractError::CannotSetOwnAccount {});
}
ALLOWANCES.update(
deps.storage,
(&info.sender, &spender_addr),
|allow| -> StdResult<_> {
let mut val = allow.unwrap_or_default();
if let Some(exp) = expires {
val.expires = exp;
}
val.allowance += amount;
Ok(val)
},
)?;
let res = Response::new().add_attributes(vec![
attr("action", "increase_allowance"),
attr("owner", info.sender),
attr("spender", spender),
attr("amount", amount),
]);
Ok(res)
}
ACKNOWLEDGED: The Mars team
acknowledged this finding.
// Informational
While the overflow-checks
parameter is set to true in profile.release
and implicitly applied to all contracts and packages from in workspace, it is not explicitly enabled in Cargo.toml file for each individual contract and package, which could lead to unexpected consequences if the project is refactored.
contracts/cw1-whitelist/Cargo.toml
contracts/cw20-base/Cargo.toml
ACKNOWLEDGED: The Mars team
acknowledged this finding.
// Informational
The multiple functionality of the contracts/cw20-base/src/contract.rs does not validate data entered in marketing variables (Logo::Url(_)
, project
and description
).
When the instantiate
function receives the marketing.project
and marketing.description
variables, no sanitization is performed to prevent problems in the front-end of the web application with malformed data, in this way, the contract stores the information in the respective variables for storage.
pub fn instantiate(
mut deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
// check valid token info
msg.validate()?;
// create initial accounts
let total_supply = create_accounts(&mut deps, &msg.initial_balances)?;
if let Some(limit) = msg.get_cap() {
if total_supply > limit {
return Err(StdError::generic_err("Initial supply greater than cap").into());
}
}
let mint = match msg.mint {
Some(m) => Some(MinterData {
minter: deps.api.addr_validate(&m.minter)?,
cap: m.cap,
}),
None => None,
};
// store token info
let data = TokenInfo {
name: msg.name,
symbol: msg.symbol,
decimals: msg.decimals,
total_supply,
mint,
};
TOKEN_INFO.save(deps.storage, &data)?;
if let Some(marketing) = msg.marketing {
let logo = if let Some(logo) = marketing.logo {
verify_logo(&logo)?;
LOGO.save(deps.storage, &logo)?;
match logo {
Logo::Url(url) => Some(LogoInfo::Url(url)),
Logo::Embedded(_) => Some(LogoInfo::Embedded),
}
} else {
None
};
let data = MarketingInfoResponse {
project: marketing.project,
description: marketing.description,
marketing: marketing
.marketing
.map(|addr| deps.api.addr_validate(&addr))
.transpose()?,
logo,
};
MARKETING_INFO.save(deps.storage, &data)?;
}
Ok(Response::default())
}
The
execute_update_marketing
has the same behavior as the instantiate
function.
pub fn execute_update_marketing(
deps: DepsMut,
_env: Env,
info: MessageInfo,
project: Option<String>,
description: Option<String>,
marketing: Option<String>,
) -> Result<Response, ContractError> {
let mut marketing_info = MARKETING_INFO
.may_load(deps.storage)?
.ok_or(ContractError::Unauthorized {})?;
if marketing_info
.marketing
.as_ref()
.ok_or(ContractError::Unauthorized {})?
!= &info.sender
{
return Err(ContractError::Unauthorized {});
}
match project {
Some(empty) if empty.trim().is_empty() => marketing_info.project = None,
Some(project) => marketing_info.project = Some(project),
None => (),
}
match description {
Some(empty) if empty.trim().is_empty() => marketing_info.description = None,
Some(description) => marketing_info.description = Some(description),
None => (),
}
match marketing {
Some(empty) if empty.trim().is_empty() => marketing_info.marketing = None,
Some(marketing) => marketing_info.marketing = Some(deps.api.addr_validate(&marketing)?),
None => (),
}
if marketing_info.project.is_none()
&& marketing_info.description.is_none()
&& marketing_info.marketing.is_none()
&& marketing_info.logo.is_none()
{
MARKETING_INFO.remove(deps.storage);
} else {
MARKETING_INFO.save(deps.storage, &marketing_info)?;
}
let res = Response::new().add_attribute("action", "update_marketing");
Ok(res)
}
When the
verify_logo
function receives the URL of the logo, no sanitization is done to prevent problems in the front-end of the web application with malformed links.
fn verify_logo(logo: &Logo) -> Result<(), ContractError> {
match logo {
Logo::Embedded(EmbeddedLogo::Svg(logo)) => verify_xml_logo(&logo),
Logo::Embedded(EmbeddedLogo::Png(logo)) => verify_png_logo(&logo),
Logo::Url(_) => Ok(()), // Any reasonable url validation would be regex based, probably not worth it
}
}
ACKNOWLEDGED: The Mars team
acknowledged this finding.
Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.
// Download the full report
* Use Google Chrome for best results
** Check "Background Graphics" in the print settings if needed