Owner Checks

Lesson Objectives

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

  • Explain the security risks associated with not performing appropriate owner checks
  • Implement owner checks using long-form Rust
  • Use Anchor’s Account<'info, T> wrapper and an account type to automate owner checks
  • Use Anchor’s #[account(owner = <expr>)] constraint to explicitly define an external program that should own an account

TL;DR

  • Use Owner Checks to verify that accounts are owned by the expected program. Without appropriate owner checks, accounts owned by unexpected programs could be used in an instruction.
  • To implement an owner check in Rust, simply check that an account’s owner matches an expected program ID
1if ctx.accounts.account.owner != ctx.program_id {
2    return Err(ProgramError::IncorrectProgramId.into());
3}
  • Anchor program account types implement the Owner trait which allows the Account<'info, T> wrapper to automatically verify program ownership
  • Anchor gives you the option to explicitly define the owner of an account if it should be anything other than the currently executing program

Overview

Owner checks are used to verify that an account passed into an instruction is owned by an expected program. This prevents accounts owned by an unexpected program from being used in an instruction.

As a refresher, the AccountInfo struct contains the following fields. An owner check refers to checking that the owner field in the AccountInfo matches an expected program ID.

1/// Account information
2#[derive(Clone)]
3pub struct AccountInfo<'a> {
4    /// Public key of the account
5    pub key: &'a Pubkey,
6    /// Was the transaction signed by this account's public key?
7    pub is_signer: bool,
8    /// Is the account writable?
9    pub is_writable: bool,
10    /// The lamports in the account.  Modifiable by programs.
11    pub lamports: Rc<RefCell<&'a mut u64>>,
12    /// The data held in this account.  Modifiable by programs.
13    pub data: Rc<RefCell<&'a mut [u8]>>,
14    /// Program that owns this account
15    pub owner: &'a Pubkey,
16    /// This account's data contains a loaded program (and is now read-only)
17    pub executable: bool,
18    /// The epoch at which this account will next owe rent
19    pub rent_epoch: Epoch,
20}

Missing owner check

The example below shows an admin_instruction intended to be accessible only by an admin account stored on an admin_config account.

Although the instruction checks the admin account signed the transaction and matches the admin field stored on the admin_config account, there is no owner check to verify the admin_config account passed into the instruction is owned by the executing program.

Since the admin_config is unchecked as indicated by the AccountInfo type, a fake admin_config account owned by a different program could be used in the admin_instruction. This means that an attacker could create a program with an admin_config whose data structure matches the admin_config of your program, set their public key as the admin and pass their admin_config account into your program. This would let them effectively spoof your program into thinking that they are the authorized admin for your program.

This simplified example only prints the admin to the program logs. However, you can imagine how a missing owner check could allow fake accounts to exploit an instruction.

1use anchor_lang::prelude::*;
2
3declare_id!("Cft4eTTrt4sJU4Ar35rUQHx6PSXfJju3dixmvApzhWws");
4
5#[program]
6pub mod owner_check {
7    use super::*;
8	...
9
10    pub fn admin_instruction(ctx: Context<Unchecked>) -> Result<()> {
11        let account_data = ctx.accounts.admin_config.try_borrow_data()?;
12        let mut account_data_slice: &[u8] = &account_data;
13        let account_state = AdminConfig::try_deserialize(&mut account_data_slice)?;
14
15        if account_state.admin != ctx.accounts.admin.key() {
16            return Err(ProgramError::InvalidArgument.into());
17        }
18        msg!("Admin: {}", account_state.admin.to_string());
19        Ok(())
20    }
21}
22
23#[derive(Accounts)]
24pub struct Unchecked<'info> {
25    admin_config: AccountInfo<'info>,
26    admin: Signer<'info>,
27}
28
29#[account]
30pub struct AdminConfig {
31    admin: Pubkey,
32}

Add owner check

In vanilla Rust, you could solve this problem by comparing the owner field on the account to the program ID. If they do not match, you would return an IncorrectProgramId error.

1if ctx.accounts.admin_config.owner != ctx.program_id {
2    return Err(ProgramError::IncorrectProgramId.into());
3}

Adding an owner check prevents accounts owned by an unexpected program to be passed in as the admin_config account. If a fake admin_config account was used in the admin_instruction, then the transaction would fail.

1use anchor_lang::prelude::*;
2
3declare_id!("Cft4eTTrt4sJU4Ar35rUQHx6PSXfJju3dixmvApzhWws");
4
5#[program]
6pub mod owner_check {
7    use super::*;
8    ...
9    pub fn admin_instruction(ctx: Context<Unchecked>) -> Result<()> {
10        if ctx.accounts.admin_config.owner != ctx.program_id {
11            return Err(ProgramError::IncorrectProgramId.into());
12        }
13
14        let account_data = ctx.accounts.admin_config.try_borrow_data()?;
15        let mut account_data_slice: &[u8] = &account_data;
16        let account_state = AdminConfig::try_deserialize(&mut account_data_slice)?;
17
18        if account_state.admin != ctx.accounts.admin.key() {
19            return Err(ProgramError::InvalidArgument.into());
20        }
21        msg!("Admin: {}", account_state.admin.to_string());
22        Ok(())
23    }
24}
25
26#[derive(Accounts)]
27pub struct Unchecked<'info> {
28    admin_config: AccountInfo<'info>,
29    admin: Signer<'info>,
30}
31
32#[account]
33pub struct AdminConfig {
34    admin: Pubkey,
35}

Use Anchor’s Account<'info, T>

Anchor can make this simpler with the Account type.

Account<'info, T> is a wrapper around AccountInfo that verifies program ownership and deserializes underlying data into the specified account type T. This in turn allows you to use Account<'info, T> to easily validate ownership.

For context, the #[account] attribute implements various traits for a data structure representing an account. One of these is the Owner trait which defines an address expected to own an account. The owner is set as the program ID specified in the declare_id! macro.

In the example below, Account<'info, AdminConfig> is used to validate the admin_config. This will automatically perform the owner check and deserialize the account data. Additionally, the has_one constraint is used to check that the admin account matches the admin field stored on the admin_config account.

This way, you don’t need to clutter your instruction logic with owner checks.

1use anchor_lang::prelude::*;
2
3declare_id!("Cft4eTTrt4sJU4Ar35rUQHx6PSXfJju3dixmvApzhWws");
4
5#[program]
6pub mod owner_check {
7    use super::*;
8	...
9    pub fn admin_instruction(ctx: Context<Checked>) -> Result<()> {
10        msg!("Admin: {}", ctx.accounts.admin_config.admin.to_string());
11        Ok(())
12    }
13}
14
15#[derive(Accounts)]
16pub struct Checked<'info> {
17    #[account(
18        has_one = admin,
19    )]
20    admin_config: Account<'info, AdminConfig>,
21    admin: Signer<'info>,
22}
23
24#[account]
25pub struct AdminConfig {
26    admin: Pubkey,
27}

Use Anchor’s #[account(owner = <expr>)] constraint

In addition to the Account type, you can use an owner constraint. The owner constraint allows you to define the program that should own an account if it’s different from the currently executing one. This comes in handy if, for example, you are writing an instruction that expects an account to be a PDA derived from a different program. You can use the seeds and bump constraints and define the owner to properly derive and verify the address of the account passed in.

To use the owner constraint, you’ll have to have access to the public key of the program you expect to own an account. You can either pass the program in as an additional account or hard-code the public key somewhere in your program.

1use anchor_lang::prelude::*;
2
3declare_id!("Cft4eTTrt4sJU4Ar35rUQHx6PSXfJju3dixmvApzhWws");
4
5#[program]
6pub mod owner_check {
7    use super::*;
8    ...
9    pub fn admin_instruction(ctx: Context<Checked>) -> Result<()> {
10        msg!("Admin: {}", ctx.accounts.admin_config.admin.to_string());
11        Ok(())
12    }
13}
14
15#[derive(Accounts)]
16pub struct Checked<'info> {
17    #[account(
18        has_one = admin,
19    )]
20    admin_config: Account<'info, AdminConfig>,
21    admin: Signer<'info>,
22    #[account(
23            seeds = b"test-seed",
24            bump,
25            owner = token_program.key()
26    )]
27    pda_derived_from_another_program: AccountInfo<'info>,
28    token_program: Program<'info, Token>
29}
30
31#[account]
32pub struct AdminConfig {
33    admin: Pubkey,
34}

Demo

In this demo we’ll use two programs to demonstrate how a missing owner check could allow a fake account to drain the tokens from a simplified token “vault” account (note that this is very similar to the demo from the Signer Authorization lesson).

To help illustrate this, one program will be missing an account owner check on the vault account it withdraws tokens to.

The second program will be a direct clone of the first program created by a malicious user to create an account identical to the first program’s vault account.

Without the owner check, this malicious user will be able to pass in the vault account owned by their “faked” program and the original program will still execute.

1. Starter

To get started, download the starter code from the starter branch of this repository. The starter code includes two programs clone and owner_check and the boilerplate setup for the test file.

The owner_check program includes two instructions:

  • initialize_vault initializes a simplified vault account that stores the addresses of a token account and an authority account
  • insecure_withdraw withdraws tokens from the token account, but is missing an owner check for the vault account
1use anchor_lang::prelude::*;
2use anchor_spl::token::{self, Mint, Token, TokenAccount};
3
4declare_id!("HQYNznB3XTqxzuEqqKMAD9XkYE5BGrnv8xmkoDNcqHYB");
5
6#[program]
7pub mod owner_check {
8    use super::*;
9
10    pub fn initialize_vault(ctx: Context<InitializeVault>) -> Result<()> {
11        ctx.accounts.vault.token_account = ctx.accounts.token_account.key();
12        ctx.accounts.vault.authority = ctx.accounts.authority.key();
13        Ok(())
14    }
15
16    pub fn insecure_withdraw(ctx: Context<InsecureWithdraw>) -> Result<()> {
17        let account_data = ctx.accounts.vault.try_borrow_data()?;
18        let mut account_data_slice: &[u8] = &account_data;
19        let account_state = Vault::try_deserialize(&mut account_data_slice)?;
20
21        if account_state.authority != ctx.accounts.authority.key() {
22            return Err(ProgramError::InvalidArgument.into());
23        }
24
25        let amount = ctx.accounts.token_account.amount;
26
27        let seeds = &[
28            b"token".as_ref(),
29            &[*ctx.bumps.get("token_account").unwrap()],
30        ];
31        let signer = [&seeds[..]];
32
33        let cpi_ctx = CpiContext::new_with_signer(
34            ctx.accounts.token_program.to_account_info(),
35            token::Transfer {
36                from: ctx.accounts.token_account.to_account_info(),
37                authority: ctx.accounts.token_account.to_account_info(),
38                to: ctx.accounts.withdraw_destination.to_account_info(),
39            },
40            &signer,
41        );
42
43        token::transfer(cpi_ctx, amount)?;
44        Ok(())
45    }
46}
47
48#[derive(Accounts)]
49pub struct InitializeVault<'info> {
50    #[account(
51        init,
52        payer = authority,
53        space = 8 + 32 + 32,
54    )]
55    pub vault: Account<'info, Vault>,
56    #[account(
57        init,
58        payer = authority,
59        token::mint = mint,
60        token::authority = token_account,
61        seeds = [b"token"],
62        bump,
63    )]
64    pub token_account: Account<'info, TokenAccount>,
65    pub mint: Account<'info, Mint>,
66    #[account(mut)]
67    pub authority: Signer<'info>,
68    pub token_program: Program<'info, Token>,
69    pub system_program: Program<'info, System>,
70    pub rent: Sysvar<'info, Rent>,
71}
72
73#[derive(Accounts)]
74pub struct InsecureWithdraw<'info> {
75    /// CHECK:
76    pub vault: UncheckedAccount<'info>,
77    #[account(
78        mut,
79        seeds = [b"token"],
80        bump,
81    )]
82    pub token_account: Account<'info, TokenAccount>,
83    #[account(mut)]
84    pub withdraw_destination: Account<'info, TokenAccount>,
85    pub token_program: Program<'info, Token>,
86    pub authority: Signer<'info>,
87}
88
89#[account]
90pub struct Vault {
91    token_account: Pubkey,
92    authority: Pubkey,
93}

The clone program includes a single instruction:

  • initialize_vault initializes a “vault” account that mimics the vault account of the owner_check program. It stores the address of the real vault’s token account, but allows the malicious user to put their own authority account.
1use anchor_lang::prelude::*;
2use anchor_spl::token::TokenAccount;
3
4declare_id!("DUN7nniuatsMC7ReCh5eJRQExnutppN1tAfjfXFmGDq3");
5
6#[program]
7pub mod clone {
8    use super::*;
9
10    pub fn initialize_vault(ctx: Context<InitializeVault>) -> Result<()> {
11        ctx.accounts.vault.token_account = ctx.accounts.token_account.key();
12        ctx.accounts.vault.authority = ctx.accounts.authority.key();
13        Ok(())
14    }
15}
16
17#[derive(Accounts)]
18pub struct InitializeVault<'info> {
19    #[account(
20        init,
21        payer = authority,
22        space = 8 + 32 + 32,
23    )]
24    pub vault: Account<'info, Vault>,
25    pub token_account: Account<'info, TokenAccount>,
26    #[account(mut)]
27    pub authority: Signer<'info>,
28    pub system_program: Program<'info, System>,
29}
30
31#[account]
32pub struct Vault {
33    token_account: Pubkey,
34    authority: Pubkey,
35}

2. Test insecure_withdraw instruction

The test file includes a test to invoke the initialize_vault instruction on the owner_check program using the provider wallet as the authority and then mints 100 tokens to the token account.

The test file also includes a test to invoke the initialize_vault instruction on the clone program to initialize a fake vault account storing the same tokenPDA account, but a different authority. Note that no new tokens are minted here.

Let’s add a test to invoke the insecure_withdraw instruction. This test should pass in the cloned vault and the fake authority. Since there is no owner check to verify the vaultClone account is owned by the owner_check program, the instruction’s data validation check will pass and show walletFake as a valid authority. The tokens from the tokenPDA account will then be withdrawn to the withdrawDestinationFake account.

1describe("owner-check", () => {
2	...
3    it("Insecure withdraw", async () => {
4    const tx = await program.methods
5        .insecureWithdraw()
6        .accounts({
7            vault: vaultClone.publicKey,
8            tokenAccount: tokenPDA,
9            withdrawDestination: withdrawDestinationFake,
10            authority: walletFake.publicKey,
11        })
12        .transaction()
13
14        await anchor.web3.sendAndConfirmTransaction(connection, tx, [walletFake])
15
16        const balance = await connection.getTokenAccountBalance(tokenPDA)
17        expect(balance.value.uiAmount).to.eq(0)
18    })
19
20})

Run anchor test to see that the insecure_withdraw completes successfully.

1owner-check
2  ✔ Initialize Vault (808ms)
3  ✔ Initialize Fake Vault (404ms)
4  ✔ Insecure withdraw (409ms)

Note that vaultClone deserializes successfully even though Anchor automatically initializes new accounts with a unique 8 byte discriminator and checks the discriminator when deserializing an account. This is because the discriminator is a hash of the account type name.

1#[account]
2pub struct Vault {
3    token_account: Pubkey,
4    authority: Pubkey,
5}

Since both programs initialize identical accounts and both structs are named Vault, the accounts have the same discriminator even though they are owned by different programs.

3. Add secure_withdraw instruction

Let’s close up this security loophole.

In the lib.rs file of the owner_check program add a secure_withdraw instruction and a SecureWithdraw accounts struct.

In the SecureWithdraw struct, let’s use Account<'info, Vault> to ensure that an owner check is performed on the vault account. We’ll also use the has_one constraint to check that the token_account and authority passed into the instruction match the values stored on the vault account.

1#[program]
2pub mod owner_check {
3    use super::*;
4	...
5
6	pub fn secure_withdraw(ctx: Context<SecureWithdraw>) -> Result<()> {
7        let amount = ctx.accounts.token_account.amount;
8
9        let seeds = &[
10            b"token".as_ref(),
11            &[*ctx.bumps.get("token_account").unwrap()],
12        ];
13        let signer = [&seeds[..]];
14
15        let cpi_ctx = CpiContext::new_with_signer(
16            ctx.accounts.token_program.to_account_info(),
17            token::Transfer {
18                from: ctx.accounts.token_account.to_account_info(),
19                authority: ctx.accounts.token_account.to_account_info(),
20                to: ctx.accounts.withdraw_destination.to_account_info(),
21            },
22            &signer,
23        );
24
25        token::transfer(cpi_ctx, amount)?;
26        Ok(())
27    }
28}
29...
30
31#[derive(Accounts)]
32pub struct SecureWithdraw<'info> {
33    #[account(
34       has_one = token_account,
35       has_one = authority
36    )]
37    pub vault: Account<'info, Vault>,
38    #[account(
39        mut,
40        seeds = [b"token"],
41        bump,
42    )]
43    pub token_account: Account<'info, TokenAccount>,
44    #[account(mut)]
45    pub withdraw_destination: Account<'info, TokenAccount>,
46    pub token_program: Program<'info, Token>,
47    pub authority: Signer<'info>,
48}

4. Test secure_withdraw instruction

To test the secure_withdraw instruction, we’ll invoke the instruction twice. First, we’ll invoke the instruction using the vaultClone account, which we expect to fail. Then, we’ll invoke the instruction using the correct vault account to check that the instruction works as intended.

1describe("owner-check", () => {
2	...
3	it("Secure withdraw, expect error", async () => {
4        try {
5            const tx = await program.methods
6                .secureWithdraw()
7                .accounts({
8                    vault: vaultClone.publicKey,
9                    tokenAccount: tokenPDA,
10                    withdrawDestination: withdrawDestinationFake,
11                    authority: walletFake.publicKey,
12                })
13                .transaction()
14
15            await anchor.web3.sendAndConfirmTransaction(connection, tx, [walletFake])
16        } catch (err) {
17            expect(err)
18            console.log(err)
19        }
20    })
21
22    it("Secure withdraw", async () => {
23        await spl.mintTo(
24            connection,
25            wallet.payer,
26            mint,
27            tokenPDA,
28            wallet.payer,
29            100
30        )
31
32        await program.methods
33        .secureWithdraw()
34        .accounts({
35            vault: vault.publicKey,
36            tokenAccount: tokenPDA,
37            withdrawDestination: withdrawDestination,
38            authority: wallet.publicKey,
39        })
40        .rpc()
41
42        const balance = await connection.getTokenAccountBalance(tokenPDA)
43        expect(balance.value.uiAmount).to.eq(0)
44    })
45})

Run anchor test to see that the transaction using the vaultClone account will now return an Anchor Error while the transaction using the vault account completes successfully.

1'Program HQYNznB3XTqxzuEqqKMAD9XkYE5BGrnv8xmkoDNcqHYB invoke [1]',
2'Program log: Instruction: SecureWithdraw',
3'Program log: AnchorError caused by account: vault. Error Code: AccountOwnedByWrongProgram. Error Number: 3007. Error Message: The given account is owned by a different program than expected.',
4'Program log: Left:',
5'Program log: DUN7nniuatsMC7ReCh5eJRQExnutppN1tAfjfXFmGDq3',
6'Program log: Right:',
7'Program log: HQYNznB3XTqxzuEqqKMAD9XkYE5BGrnv8xmkoDNcqHYB',
8'Program HQYNznB3XTqxzuEqqKMAD9XkYE5BGrnv8xmkoDNcqHYB consumed 5554 of 200000 compute units',
9'Program HQYNznB3XTqxzuEqqKMAD9XkYE5BGrnv8xmkoDNcqHYB failed: custom program error: 0xbbf'

Here we see how using Anchor’s Account<'info, T> type can simplify the account validation process to automate the ownership check. Additionally, note that Anchor Errors can specify the account that causes the error (e.g. the third line of the logs above say AnchorError caused by account: vault). This can be very helpful when debugging.

1✔ Secure withdraw, expect error (78ms)
2✔ Secure withdraw (10063ms)

That’s all you need to ensure you check the owner on an account! Like some other exploits, it’s fairly simple to avoid but very important. Be sure to always think through which accounts should be owned by which programs and ensure that you add appropriate validation.

If you want to take a look at the final solution code you can find it on the solution branch of the 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 proper owner checks are performed on the accounts passed into each instruction.

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