Reinitialization Attacks

Lesson Objectives

By the end of this lesson, you will be able to:

  • Explain security risks associated with a reinitialization vulnerability
  • Use long-form Rust check if an account has already been initialized
  • Using Anchor’s init constraint to initialize accounts, which automatically sets an account discriminator that is checked to prevent the reinitialization of an account

TL;DR

  • Use an account discriminator or initialization flag to check whether an account has already been initialized to prevent an account from being reinitialized and overriding existing account data.
  • To prevent account reinitialization in plain Rust, initialize accounts with an is_initialized flag and check if it has already been set to true when initializing an account
    1if account.is_initialized {
    2    return Err(ProgramError::AccountAlreadyInitialized.into());
    3}
  • To simplify this, use Anchor’s init constraint to create an account via a CPI to the system program and sets its discriminator

Overview

Initialization refers to setting the data of a new account for the first time. When initializing a new account, you should implement a way to check if the account has already been initialized. Without an appropriate check, an existing account could be reinitialized and have existing data overwritten.

Note that initializing an account and creating an account are two separate instructions. Creating an account requires invoking the create_account instruction on the System Program which specifies the space required for the account, the rent in lamports allocated to the account, and the program owner of the account. Initialization is an instruction that sets the data of a newly created account. Creating and initializing an account can be combined into a single transaction.

Missing Initialization Check

In the example below, there are no checks on the user account. The initialize instruction deserializes the data of the user account as a User account type, sets the authority field, and serializes the updated account data to the user account.

Without checks on the user account, the same account could be passed into the initialize instruction a second time by another party to overwrite the existing authority stored on the account data.

1use anchor_lang::prelude::*;
2use borsh::{BorshDeserialize, BorshSerialize};
3
4declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
5
6#[program]
7pub mod initialization_insecure  {
8    use super::*;
9
10    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
11        let mut user = User::try_from_slice(&ctx.accounts.user.data.borrow()).unwrap();
12        user.authority = ctx.accounts.authority.key();
13        user.serialize(&mut *ctx.accounts.user.data.borrow_mut())?;
14        Ok(())
15    }
16}
17
18#[derive(Accounts)]
19pub struct Initialize<'info> {
20		#[account(mut)]
21    user: AccountInfo<'info>,
22    #[account(mut)]
23		authority: Signer<'info>,
24}
25
26#[derive(BorshSerialize, BorshDeserialize)]
27pub struct User {
28    authority: Pubkey,
29}

Add is_initialized check

One approach to fix this is to add an additional is_initialized field to the User account type and use it as a flag to check if an account has already been initialized.

1if user.is_initialized {
2    return Err(ProgramError::AccountAlreadyInitialized.into());
3}

By including a check within the initialize instruction, the user account would only be initialized if the is_initialized field has not yet been set to true. If the is_initialized field was already set, the transaction would fail, thereby avoiding the scenario where an attacker could replace the account authority with their own public key.

1use anchor_lang::prelude::*;
2use borsh::{BorshDeserialize, BorshSerialize};
3
4declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
5
6#[program]
7pub mod initialization_secure {
8    use super::*;
9
10    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
11        let mut user = User::try_from_slice(&ctx.accounts.user.data.borrow()).unwrap();
12        if user.is_initialized {
13            return Err(ProgramError::AccountAlreadyInitialized.into());
14        }
15
16        user.authority = ctx.accounts.authority.key();
17        user.is_initialized = true;
18
19        user.serialize(&mut *ctx.accounts.user.data.borrow_mut())?;
20        Ok(())
21    }
22}
23
24#[derive(Accounts)]
25pub struct Initialize<'info> {
26		#[account(mut)]
27    user: AccountInfo<'info>,
28    #[account(mut)]
29		authority: Signer<'info>,
30}
31
32#[derive(BorshSerialize, BorshDeserialize)]
33pub struct User {
34    is_initialized: bool,
35    authority: Pubkey,
36}

Use Anchor’s init constraint

Anchor provides an init constraint that can be used with the #[account(...)] attribute to initialize an account. The init constraint creates the account via a CPI to the system program and sets the account discriminator.

The init constraint must be used in combination with the payer and space constraints. The payer specifies the account paying for the initialization of the new account. The space specifies the amount of space the new account requires, which determines the amount of lamports that must be allocated to the account. The first 8 bytes of data is set as a discriminator that Anchor automatically adds to identify the account type.

Most importantly for this lesson, the init constraint ensures that this instruction can only be called once per account, so you can set the initial state of the account in the instruction logic and not have to worry about an attacker trying to reinitialize the account.

1use anchor_lang::prelude::*;
2
3declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
4
5#[program]
6pub mod initialization_recommended {
7    use super::*;
8
9    pub fn initialize(_ctx: Context<Initialize>) -> Result<()> {
10        msg!("GM");
11        Ok(())
12    }
13}
14
15#[derive(Accounts)]
16pub struct Initialize<'info> {
17    #[account(init, payer = authority, space = 8+32)]
18    user: Account<'info, User>,
19    #[account(mut)]
20    authority: Signer<'info>,
21    system_program: Program<'info, System>,
22}
23
24#[account]
25pub struct User {
26    authority: Pubkey,
27}

Anchor’s init_if_needed constraint

It’s worth noting that Anchor has an init_if_needed constraint. This constraint should be used very cautiously. In fact, it is blocked behind a feature flag so that you are forced to be intentional about using it.

The init_if_needed constraint does the same thing as the init constraint, only if the account has already been initialized the instruction will still run.

Given this, it’s extremely important that when you use this constraint you include checks to avoid resetting the account to its initial state.

For example, if the account stores an authority field that gets set in the instruction using the init_if_needed constraint, you need checks that ensure that no attacker could call the instruction after it has already been initialized and have the authority field set again.

In most cases, it’s safer to have a separate instruction for initializing account data.

Demo

For this demo we’ll create a simple program that does nothing but initialize accounts. We’ll include two instructions:

  • insecure_initialization - initializes an account that can be reinitialized
  • recommended_initialization - initialize an account using Anchor’s init constraint

1. Starter

To get started, download the starter code from the starter branch of this repository. The starter code includes a program with one instruction and the boilerplate setup for the test file.

The insecure_initialization instruction initializes a new user account that stores the public key of an authority. In this instruction, the account is expected to be allocated client-side, then passed into the program instruction. Once passed into the program, there are no checks to see if the user account's initial state has already been set. This means the same account can be passed in a second time to override the authority stored on an existing user account.

1use anchor_lang::prelude::*;
2use borsh::{BorshDeserialize, BorshSerialize};
3
4declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
5
6#[program]
7pub mod initialization {
8    use super::*;
9
10    pub fn insecure_initialization(ctx: Context<Unchecked>) -> Result<()> {
11        let mut user = User::try_from_slice(&ctx.accounts.user.data.borrow()).unwrap();
12        user.authority = ctx.accounts.authority.key();
13        user.serialize(&mut *ctx.accounts.user.data.borrow_mut())?;
14        Ok(())
15    }
16}
17
18#[derive(Accounts)]
19pub struct Unchecked<'info> {
20    #[account(mut)]
21    /// CHECK:
22    user: UncheckedAccount<'info>,
23    authority: Signer<'info>,
24}
25
26#[derive(BorshSerialize, BorshDeserialize)]
27pub struct User {
28    authority: Pubkey,
29}

2. Test insecure_initialization instruction

The test file includes the setup to create an account by invoking the system program and then invokes the insecure_initialization instruction twice using the same account.

Since there are no checks the verify that the account data has not already been initialized, the insecure_initialization instruction will complete successfully both times, despite the second invocation providing a different authority account.

1import * as anchor from "@project-serum/anchor"
2import { Program } from "@project-serum/anchor"
3import { expect } from "chai"
4import { Initialization } from "../target/types/initialization"
5
6describe("initialization", () => {
7  const provider = anchor.AnchorProvider.env()
8  anchor.setProvider(provider)
9
10  const program = anchor.workspace.Initialization as Program<Initialization>
11
12  const wallet = anchor.workspace.Initialization.provider.wallet
13  const walletTwo = anchor.web3.Keypair.generate()
14
15  const userInsecure = anchor.web3.Keypair.generate()
16  const userRecommended = anchor.web3.Keypair.generate()
17
18  before(async () => {
19    const tx = new anchor.web3.Transaction().add(
20      anchor.web3.SystemProgram.createAccount({
21        fromPubkey: wallet.publicKey,
22        newAccountPubkey: userInsecure.publicKey,
23        space: 32,
24        lamports: await provider.connection.getMinimumBalanceForRentExemption(
25          32
26        ),
27        programId: program.programId,
28      })
29    )
30
31    await anchor.web3.sendAndConfirmTransaction(provider.connection, tx, [
32      wallet.payer,
33      userInsecure,
34    ])
35
36    await provider.connection.confirmTransaction(
37      await provider.connection.requestAirdrop(
38        walletTwo.publicKey,
39        1 * anchor.web3.LAMPORTS_PER_SOL
40      ),
41      "confirmed"
42    )
43  })
44
45  it("Insecure init", async () => {
46    await program.methods
47      .insecureInitialization()
48      .accounts({
49        user: userInsecure.publicKey,
50      })
51      .rpc()
52  })
53
54  it("Re-invoke insecure init with different auth", async () => {
55    const tx = await program.methods
56      .insecureInitialization()
57      .accounts({
58        user: userInsecure.publicKey,
59        authority: walletTwo.publicKey,
60      })
61      .transaction()
62    await anchor.web3.sendAndConfirmTransaction(provider.connection, tx, [
63      walletTwo,
64    ])
65  })
66})

Run anchor test to see that both transactions will complete successfully.

1initialization
2  ✔ Insecure init (478ms)
3  ✔ Re-invoke insecure init with different auth (464ms)

3. Add recommended_initialization instruction

Let's create a new instruction called recommended_initialization that fixes this problem. Unlike the previous insecure instruction, this instruction should handle both the creation and initialization of the user's account using Anchor's init constraint.

This constraint instructs the program to create the account via a CPI to the system program, so the account no longer needs to be created client-side. The constraint also sets the account discriminator. Your instruction logic can then set the account's initial state.

By doing this, you ensure that any subsequent invocation of the same instruction with the same user account will fail rather than reset the account's initial state.

1use anchor_lang::prelude::*;
2use borsh::{BorshDeserialize, BorshSerialize};
3
4declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
5
6#[program]
7pub mod initialization {
8    use super::*;
9		...
10    pub fn recommended_initialization(ctx: Context<Checked>) -> Result<()> {
11        ctx.accounts.user.authority = ctx.accounts.authority.key();
12        Ok(())
13    }
14}
15
16#[derive(Accounts)]
17pub struct Checked<'info> {
18    #[account(init, payer = authority, space = 8+32)]
19    user: Account<'info, User>,
20    #[account(mut)]
21    authority: Signer<'info>,
22    system_program: Program<'info, System>,
23}

4. Test recommended_initialization instruction

To test the recommended_initialization instruction, we’ll invoke the instruction twice just like before. This time, we expect the transaction to fail when we try to initialize the same account a second time.

1describe("initialization", () => {
2  ...
3  it("Recommended init", async () => {
4    await program.methods
5      .recommendedInitialization()
6      .accounts({
7        user: userRecommended.publicKey,
8      })
9      .signers([userRecommended])
10      .rpc()
11  })
12
13  it("Re-invoke recommended init with different auth, expect error", async () => {
14    try {
15      // Add your test here.
16      const tx = await program.methods
17        .recommendedInitialization()
18        .accounts({
19          user: userRecommended.publicKey,
20          authority: walletTwo.publicKey,
21        })
22        .transaction()
23      await anchor.web3.sendAndConfirmTransaction(provider.connection, tx, [
24        walletTwo,
25        userRecommended,
26      ])
27    } catch (err) {
28      expect(err)
29      console.log(err)
30    }
31  })
32})

Run anchor test and to see that the second transaction which tries to initialize the same account twice will now return an error stating the account address is already in use.

1'Program CpozUgSwe9FPLy9BLNhY2LTGqLUk1nirUkMMA5RmDw6t invoke [1]',
2'Program log: Instruction: RecommendedInitialization',
3'Program 11111111111111111111111111111111 invoke [2]',
4'Allocate: account Address { address: EMvbwzrs4VTR7G1sNUJuQtvRX1EuvLhqs4PFqrtDcCGV, base: None } already in use',
5'Program 11111111111111111111111111111111 failed: custom program error: 0x0',
6'Program CpozUgSwe9FPLy9BLNhY2LTGqLUk1nirUkMMA5RmDw6t consumed 4018 of 200000 compute units',
7'Program CpozUgSwe9FPLy9BLNhY2LTGqLUk1nirUkMMA5RmDw6t failed: custom program error: 0x0'

If you use Anchor's init constraint, that's usually all you need to protect against reinitialization attacks! Remember, just because the fix for these security exploits is simple doesn't mean it isn't important. Every time your initialize an account, make sure you're either using the init constraint or have some other check in place to avoid resetting an existing account's initial state.

If you want to take a look at the final solution code you can find it on the solution branch of this repository.

Challenge

Just as with other lessons in this module, your opportunity to practice avoiding this security exploit lies in auditing your own or other programs.

Take some time to review at least one program and ensure that instructions are properly protected against reinitialization attacks.

Remember, if you find a bug or exploit in somebody else's program, please alert them! If you find one in your own program, be sure to patch it right away.

Table of Contents