Auditoria de segurança da rede Nym mixnet e contratos de aquisição de direitos

Auditoria de segurança da rede mixnet e dos contratos de aquisição de direitos da Nym

8 mins Ler

Introdução

Em dezembro de 2022, a Nym passou por uma auditoria de segurança independente conduzida pela Oak Security, uma empresa de consultoria em segurança cibernética sediada na Alemanha, especializada em auditorias de blockchains de terceira geração e protocolos descentralizados. Com ampla experiência em ecossistemas como Cosmos, Terra, Polkadot e Flow, a Oak Security foi encarregada de avaliar dois componentes críticos do ecossistema Nym: (1) a rede mixnet Nym e os contratos de aquisição de direitos (ver relatório completo) e (2) a carteira Nym (ver relatório completo). A auditoria teve como objetivo avaliar a robustez desses componentes, identificar possíveis vulnerabilidades e garantir a adesão às melhores práticas no desenvolvimento de código. Para facilitar o acompanhamento, dividimos as conclusões para cada componente. Você pode conferir o resumo da auditoria da Nym Wallet aqui.

Resumo da auditoria da Nym Mixnet & Contratos Vesting pela Oak Security

Com duração de 2 semanas, a auditoria envolveu uma equipe de 4 especialistas. A equipe da Nym forneceu à Oak Security acesso total ao código-fonte do projeto, especificações detalhadas do projeto e documentação de apoio. O escopo da auditoria abrangeu os contratos/mixnet, contratos/repositórios de aquisição de direitos e importações relevantes por esses contratos para a mixnet Nym e contratos de aquisição de direitos.

A Oak Security revisou minuciosamente o código, combinando análise automatizada do código-fonte e das dependências com uma inspeção manual linha por linha para descobrir vulnerabilidades de segurança, avaliar a qualidade do código e avaliar a conformidade com os princípios de codificação segura. Essa abordagem abrangente incluiu uma análise aprofundada de áreas críticas, como vulnerabilidades de condições de corrida, problemas de subfluxo e estouro, práticas importantes de gerenciamento, robustez criptográfica, riscos de vazamento de dados, tratamento de senhas e controles de acesso e autorização.

O foco da auditoria foi garantir o funcionamento correto dos protocolos, identificar quaisquer vulnerabilidades exploráveis ou bugs nos contratos inteligentes e recomendar melhorias para a segurança e legibilidade do código.

Visão geral dos resultados

A rede mixnet e os contratos de aquisição de direitos da Nym caracterizavam-se por uma elevada legibilidade e clareza, com uma cobertura de testes robusta que comprovava a sua fiabilidade. Na sua avaliação, os auditores identificaram 19 conclusões, incluindo 9 vulnerabilidades de segurança – compreendendo questões críticas e de gravidade elevada – e 10 deficiências gerais classificadas como menores ou informativas.

A equipe Nym abordou rapidamente todas as questões críticas e de alta gravidade. A equipe da Oak Security verificou e aprovou nossas correções.

NYM-MIX-VEST-CONTRACT-1: Uma falha na execução de um evento de época ou intervalo bloqueia permanentemente o avanço da época (Crítico)

A auditoria identificou uma vulnerabilidade no tratamento das mensagens AdvanceCurrentEpoch em contracts/mixnet/src/interval/transactions.rs. Um loop sequencial processa todos os eventos pendentes diretamente dentro do contexto da transação, o que significa que um único evento com falha pode reverter toda a transação, interrompendo efetivamente o avanço da época e do intervalo e fazendo com que o protocolo fique travado.

To address this, the auditors recommended wrapping event execution in sub-messages with a reply policy. This approach would allow the system to handle failures gracefully without reverting the entire transaction. However, we deliberately chose not to follow this recommendation. A failure during event execution indicates a significant logic flaw that could compromise the reward mechanism, making it preferable to halt epoch advancement for manual inspection rather than risk operating in a corrupted state. Instead, we implemented enhanced monitoring in the Nym API to detect and alert us to failed epoch advancements. This approach ensures that such failures are promptly flagged, enabling timely intervention to resolve issues.

A vulnerability was identified in the JoinFamilyOnBehalf message, which could allow an attacker to add a mix node to a family without its consent. By creating a malicious family and using the victim mix node’s identity key signed with its private key as the signature, the attacker could trap the mix node in the family. This could potentially allow an attacker to group orphan mix nodes into a single family, disrupting the network by concentrating nodes in the same layer and increasing the attacker’s chances of influencing routing.

To address the vulnerability in the JoinFamilyOnBehalf message, the contract's signature mechanism was redesigned. Instead of simply signing the mix node's identity, signatures were updated to include a message with a clear intent and a unique nonce. This change ensures that signatures cannot be reused or replayed.

NYM-MIX-VEST-CONTRACT-3: Unbounded iteration in TrackUndelegation message handling could make the user unable to undelegate, which also permanently inhibits epoch advancement (Critical)

The TrackUndelegation message's unbounded iteration could cause gas exhaustion when handling accounts with numerous delegations, preventing users from undelegating. This failure would also halt epoch advancement, leaving the protocol stuck in its current state.

To address the issue, we implemented a limit of 25 vesting delegations per account. This solution was based on the highest observed number of vesting delegations at the time.

Update: As of 2024, the option to make vesting delegations is completely disabled.

NYM-MIX-VEST-CONTRACT-4: An attacker can front-run BondMixnodeOnBehalf and CreateFamilyOnBehalf messages and modify their payload (Critical)

This vulnerability would allow an attacker to frontrun BondMixNodeOnBehalf and CreateFamilyOnBehalf messages, extract the signature, and modify the payload. In the case of BondMixNodeOnBehalf, the attacker could also set themselves as the proxy, gaining full control over the registered bond.

To address the vulnerability, we implemented a twofold solution. First, we applied the signature creation changes described in NYM-MIX-VEST-CONTRACT-2 which added a clear intent and a unique nonce. Second, we restricted the legal proxy address to the vesting account, ensuring that attackers cannot set themselves as the proxy and gain unauthorized control over registered bonds.

Update: As of 2024 all proxy operations are disabled making the attack unapplicable.

NYM-MIX-VEST-CONTRACT-5: Signatures can be replayed within “on behalf” transactions to impersonate users (Critical)

This vulnerability allows signatures to be replayed within “on behalf” transactions, enabling attackers to impersonate users. Since the signatures only include raw data without additional metadata like nonces or message identifiers, an attacker could reuse a signature from one message for another to forcibly remove family members. Additionally, attackers can reuse signatures for the same message type, allowing a member to rejoin a family multiple times using the same signature.

The solution to this issue mirrors the one implemented in NYM-MIX-VEST-CONTRACT-4.

NYM-MIX-VEST-CONTRACT-6: Key generation for (owner, proxy) pairs could lead to collisions (Critical)

This vulnerability would allow two different (owner, proxy) address pairs to generate the same XOR result in the generate_owner_storage_subkey function, which could lead to key collisions and data overwrites.

The solution of restricting the legal proxy to only the vesting contract address, which was applied in the NYM-MIX-VEST-CONTRACT-4, also solves this vulnerability. By ensuring that the XOR operation is always performed against a constant string, this change effectively eliminates the risk of collisions.

NYM-MIX-VEST-CONTRACT-7: track_delegation can overwrite existing delegation if more than one is processed within the same block (Critical)

This issue would allow key collisions to occur if multiple delegations are made within the same block, potentially causing the save_delegation function to overwrite an existing delegation, resulting in the loss of the previous delegation.

To address the issue, we changed the logic of the save_delegation function to first read the existing delegation amount before saving the new one. If a delegation already exists for the same key, we retrieve the current amount, add the new delegation, and then save the updated total, ensuring no existing delegation is overwritten.

NYM-MIX-VEST-CONTRACT-8: Bond owner is not able to perform operations if the bond is created “on behalf” by a proxy (Major)

This issue would prevent the bond owner from performing any operations on their bond if the bond was created "on behalf" and the current transaction is initiated by the owner instead of the proxy. Since the proxy could be compromised or lost, and there is no way for the owner to change it, this could result in the owner losing control over their bond.

We do not consider this to be an issue, as it is intentional behavior by design. When a mix node is bonded (or delegations are made) through the vesting contract, all subsequent interactions with the bond or delegation are expected to occur only via the vesting contract.

Update: As of 2024, the vesting contract is removed.

NYM-MIX-VEST-CONTRACT-9: LeaveFamily and LeaveFamilyOnBehalf messages execution could fail if a significant amount of mix nodes are members of a family (Major)

This issue would result in the failure of LeaveFamily and LeaveFamilyOnBehalf messages due to gas exhaustion when iterating over a large number of family members in the MEMBERS map. This would prevent mix nodes from leaving a family, effectively locking them in their current family.

Solution: The solution involved reworking the logic to directly access the MEMBERS map and verify the membership of a mix node. This change removed the need for iteration, which could result in out-of-gas errors, and ensured that members can leave a family successfully, even when there are many members in the family.

Update: As of 2024, node families are removed.

Last words

We would like to thank the Oak Security team for their expertise and dedication throughout this audit process. We also appreciate the collaboration and professionalism demonstrated during both the planning and execution stages of the audit. Our ongoing commitment to security remains a top priority, and we look forward to continued partnerships with security experts to uphold the highest standards for our ecosystem.

Compartilhar