Type Cosplay

Lesson Objectives

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

  • Explain the security risks associated with not checking account types
  • Implement an account type discriminator using long-form Rust
  • Use Anchor's init constraint to initialize accounts
  • Use Anchor's Account type for account validation

TL;DR

  • Use discriminators to distinguish between different account types

  • To implement a discriminator in Rust, include a field in the account struct to represent the account type

    1#[derive(BorshSerialize, BorshDeserialize)]
    2pub struct User {
    3    discriminant: AccountDiscriminant,
    4    user: Pubkey,
    5}
    6
    7#[derive(BorshSerialize, BorshDeserialize, PartialEq)]
    8pub enum AccountDiscriminant {
    9    User,
    10    Admin,
    11}
  • To implement a discriminator check in Rust, verify that the discriminator of the deserialized account data matches the expected value

    1if user.discriminant != AccountDiscriminant::User {
    2    return Err(ProgramError::InvalidAccountData.into());
    3}
  • In Anchor, program account types automatically implement the Discriminator trait which creates an 8 byte unique identifier for a type

  • Use Anchor’s Account<'info, T> type to automatically check the discriminator of the account when deserializing the account data

Overview

“Type cosplay” refers to an unexpected account type being used in place of an expected account type. Under the hood, account data is simply stored as an array of bytes that a program deserializes into a custom account type. Without implementing a way to explicitly distinguish between account types, account data from an unexpected account could result in an instruction being used in unintended ways.

Unchecked account

In the example below, both the AdminConfig and UserConfig account types store a single public key. The admin_instruction instruction deserializes the admin_config account as an AdminConfig type and then performs a owner check and data validation check.

However, the AdminConfig and UserConfig account types have the same data structure. This means a UserConfig account type could be passed in as the admin_config account. As long as the public key stored on the account data matches the admin signing the transaction, the admin_instruction instruction would continue to process, even if the signer isn't actually an admin.

Note that the names of the fields stored on the account types (admin and user) make no difference when deserializing account data. The data is serialized and deserialized based on the order of fields rather than their names.

1use anchor_lang::prelude::*;
2use borsh::{BorshDeserialize, BorshSerialize};
3
4declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
5
6#[program]
7pub mod type_cosplay_insecure {
8    use super::*;
9
10    pub fn admin_instruction(ctx: Context<AdminInstruction>) -> Result<()> {
11        let account_data =
12            AdminConfig::try_from_slice(&ctx.accounts.admin_config.data.borrow()).unwrap();
13        if ctx.accounts.admin_config.owner != ctx.program_id {
14            return Err(ProgramError::IllegalOwner.into());
15        }
16        if account_data.admin != ctx.accounts.admin.key() {
17            return Err(ProgramError::InvalidAccountData.into());
18        }
19        msg!("Admin {}", account_data.admin);
20        Ok(())
21    }
22}
23
24#[derive(Accounts)]
25pub struct AdminInstruction<'info> {
26    admin_config: UncheckedAccount<'info>,
27    admin: Signer<'info>,
28}
29
30#[derive(BorshSerialize, BorshDeserialize)]
31pub struct AdminConfig {
32    admin: Pubkey,
33}
34
35#[derive(BorshSerialize, BorshDeserialize)]
36pub struct UserConfig {
37    user: Pubkey,
38}

Add account discriminator

To solve this, you can add a discriminant field for each account type and set the discriminant when initializing an account.

The example below updates the AdminConfig and UserConfig account types with a discriminant field. The admin_instruction instruction includes an additional data validation check for the discriminant field.

1if account_data.discriminant != AccountDiscriminant::Admin {
2    return Err(ProgramError::InvalidAccountData.into());
3}

If the discriminant field of the account passed into the instruction as the admin_config account does not match the expected AccountDiscriminant, then the transaction will fail. Simply make sure to set the appropriate value for discriminant when you initialize each account (not shown in the example), and then you can include these discriminant checks in every subsequent instruction.

1use anchor_lang::prelude::*;
2use borsh::{BorshDeserialize, BorshSerialize};
3
4declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
5
6#[program]
7pub mod type_cosplay_secure {
8    use super::*;
9
10    pub fn admin_instruction(ctx: Context<AdminInstruction>) -> Result<()> {
11        let account_data =
12            AdminConfig::try_from_slice(&ctx.accounts.admin_config.data.borrow()).unwrap();
13        if ctx.accounts.admin_config.owner != ctx.program_id {
14            return Err(ProgramError::IllegalOwner.into());
15        }
16        if account_data.admin != ctx.accounts.admin.key() {
17            return Err(ProgramError::InvalidAccountData.into());
18        }
19        if account_data.discriminant != AccountDiscriminant::Admin {
20            return Err(ProgramError::InvalidAccountData.into());
21        }
22        msg!("Admin {}", account_data.admin);
23        Ok(())
24    }
25}
26
27#[derive(Accounts)]
28pub struct AdminInstruction<'info> {
29    admin_config: UncheckedAccount<'info>,
30    admin: Signer<'info>,
31}
32
33#[derive(BorshSerialize, BorshDeserialize)]
34pub struct AdminConfig {
35    discriminant: AccountDiscriminant,
36    admin: Pubkey,
37}
38
39#[derive(BorshSerialize, BorshDeserialize)]
40pub struct UserConfig {
41    discriminant: AccountDiscriminant,
42    user: Pubkey,
43}
44
45#[derive(BorshSerialize, BorshDeserialize, PartialEq)]
46pub enum AccountDiscriminant {
47    Admin,
48    User,
49}

Use Anchor’s Account wrapper

Implementing these checks for every account needed for every instruction can be tedious. Fortunately, Anchor provides a #[account] attribute macro for automatically implementing traits that every account should have.

Structs marked with #[account] can then be used with Account to validate that the passed in account is indeed the type you expect it to be. When initializing an account whose struct representation has the #[account] attribute, the first 8 bytes are automatically reserved for a discriminator unique to the account type. When deserializing the account data, Anchor will automatically check if the discriminator on the account matches the expected account type and throw and error if it does not match.

In the example below, Account<'info, AdminConfig> specifies that the admin_config account should be of type AdminConfig. Anchor then automatically checks that the first 8 bytes of account data match the discriminator of the AdminConfig type.

The data validation check for the admin field is also moved from the instruction logic to the account validation struct using the has_one constraint. #[account(has_one = admin)] specifies that the admin_config account’s admin field must match the admin account passed into the instruction. Note that for the has_one constraint to work, the naming of the account in the struct must match the naming of field on the account you are validating.

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

It’s important to note that this is a vulnerability you don’t really have to worry about when using Anchor - that’s the whole point of it in the first place! After going through how this can be exploited if not handled properly in a native rust program, hopefully you have a much better understanding of what the purpose of the account discriminator is in an Anchor account. The fact that Anchor sets and checks this discriminator automatically means that developers can spend more time focusing on their product, but it’s still very important to understand what Anchor is doing behind the scenes to develop robust Solana programs.

Demo

For this demo we’ll create two programs to demonstrate a type cosplay vulnerability.

  • The first program will initialize program accounts without a discriminator
  • The second program will initialize program accounts using Anchor’s init constraint which automatically sets an account discriminator

1. Starter

To get started, download the starter code from the starter branch of this repository. The starter code includes a program with three instructions and some tests.

The three instructions are:

  1. initialize_admin - initializes an admin account and sets the admin authority of the program
  2. initialize_user - intializes a standard user account
  3. update_admin - allows the existing admin to update the admin authority of the program

Take a look at these three instructions in the lib.rs file. The last instruction should only be callable by the account matching the admin field on the admin account initialized using the initialize_admin instruction.

2. Test insecure update_admin instruction

However, both accounts have the same fields and field types:

1#[derive(BorshSerialize, BorshDeserialize)]
2pub struct AdminConfig {
3    admin: Pubkey,
4}
5
6#[derive(BorshSerialize, BorshDeserialize)]
7pub struct User {
8    user: Pubkey,
9}

Because of this, it's possible to pass in a User account in place of the admin account in the update_admin instruction, thereby bypassing the requirement that one be an admin to call this instruction.

Take a look at the solana-type-cosplay.ts file in the tests directory. It contains some basic setup and two tests. One test initializes a user account, and the other invokes update_admin and passes in the user account in place of an admin account.

Run anchor test to see that invoking update_admin will complete successfully.

1type-cosplay
2    ✔ Initialize User Account (233ms)
3    ✔ Invoke update admin instruction with user account (487ms)

3. Create type-checked program

Now we'll create a new program called type-checked by running anchor new type-checked from the root of the existing anchor program.

Now in your programs folder you will have two programs. Run anchor keys list and you should see the program ID for the new program. Add it to the lib.rs file of the type-checked program and to the type_checked program in the Anchor.toml file.

Next, update the test file's setup to include the new program and two new keypairs for the accounts we'll be initializing for the new program.

1import * as anchor from "@project-serum/anchor"
2import { Program } from "@project-serum/anchor"
3import { TypeCosplay } from "../target/types/type_cosplay"
4import { TypeChecked } from "../target/types/type_checked"
5import { expect } from "chai"
6
7describe("type-cosplay", () => {
8  const provider = anchor.AnchorProvider.env()
9  anchor.setProvider(provider)
10
11  const program = anchor.workspace.TypeCosplay as Program<TypeCosplay>
12  const programChecked = anchor.workspace.TypeChecked as Program<TypeChecked>
13
14  const userAccount = anchor.web3.Keypair.generate()
15  const newAdmin = anchor.web3.Keypair.generate()
16
17  const userAccountChecked = anchor.web3.Keypair.generate()
18  const adminAccountChecked = anchor.web3.Keypair.generate()
19})

4. Implement the type-checked program

In the type_checked program, add two instructions using the init constraint to initialize an AdminConfig account and a User account. When using the init constraint to initialize new program accounts, Anchor will automatically set the first 8 bytes of account data as a unique discriminator for the account type.

We’ll also add an update_admin instruction that validates the admin_config account as a AdminConfig account type using Anchor’s Account wrapper. For any account passed in as the admin_config account, Anchor will automatically check that the account discriminator matches the expected account type.

1use anchor_lang::prelude::*;
2
3declare_id!("FZLRa6vX64QL6Vj2JkqY1Uzyzjgi2PYjCABcDabMo8U7");
4
5#[program]
6pub mod type_checked {
7    use super::*;
8
9    pub fn initialize_admin(ctx: Context<InitializeAdmin>) -> Result<()> {
10        ctx.accounts.admin_config.admin = ctx.accounts.admin.key();
11        Ok(())
12    }
13
14    pub fn initialize_user(ctx: Context<InitializeUser>) -> Result<()> {
15        ctx.accounts.user_account.user = ctx.accounts.user.key();
16        Ok(())
17    }
18
19    pub fn update_admin(ctx: Context<UpdateAdmin>) -> Result<()> {
20        ctx.accounts.admin_config.admin = ctx.accounts.admin.key();
21        Ok(())
22    }
23}
24
25#[derive(Accounts)]
26pub struct InitializeAdmin<'info> {
27    #[account(
28        init,
29        payer = admin,
30        space = 8 + 32
31    )]
32    pub admin_config: Account<'info, AdminConfig>,
33    #[account(mut)]
34    pub admin: Signer<'info>,
35    pub system_program: Program<'info, System>,
36}
37
38#[derive(Accounts)]
39pub struct InitializeUser<'info> {
40    #[account(
41        init,
42        payer = user,
43        space = 8 + 32
44    )]
45    pub user_account: Account<'info, User>,
46    #[account(mut)]
47    pub user: Signer<'info>,
48    pub system_program: Program<'info, System>,
49}
50
51#[derive(Accounts)]
52pub struct UpdateAdmin<'info> {
53    #[account(
54        mut,
55        has_one = admin
56    )]
57    pub admin_config: Account<'info, AdminConfig>,
58    pub new_admin: SystemAccount<'info>,
59    #[account(mut)]
60    pub admin: Signer<'info>,
61}
62
63#[account]
64pub struct AdminConfig {
65    admin: Pubkey,
66}
67
68#[account]
69pub struct User {
70    user: Pubkey,
71}

5. Test secure update_admin instruction

In the test file, we’ll initialize an AdminConfig account and a User account from the type_checked program. Then we’ll invoke the updateAdmin instruction twice passing in the newly created accounts.

1describe("type-cosplay", () => {
2	...
3
4  it("Initialize type checked AdminConfig Account", async () => {
5    await programChecked.methods
6      .initializeAdmin()
7      .accounts({
8        adminConfig: adminAccountType.publicKey,
9      })
10      .signers([adminAccountType])
11      .rpc()
12  })
13
14  it("Initialize type checked User Account", async () => {
15    await programChecked.methods
16      .initializeUser()
17      .accounts({
18        userAccount: userAccountType.publicKey,
19        user: provider.wallet.publicKey,
20      })
21      .signers([userAccountType])
22      .rpc()
23  })
24
25  it("Invoke update instruction using User Account", async () => {
26    try {
27      await programChecked.methods
28        .updateAdmin()
29        .accounts({
30          adminConfig: userAccountType.publicKey,
31          newAdmin: newAdmin.publicKey,
32          admin: provider.wallet.publicKey,
33        })
34        .rpc()
35    } catch (err) {
36      expect(err)
37      console.log(err)
38    }
39  })
40
41  it("Invoke update instruction using AdminConfig Account", async () => {
42    await programChecked.methods
43      .updateAdmin()
44      .accounts({
45        adminConfig: adminAccountType.publicKey,
46        newAdmin: newAdmin.publicKey,
47        admin: provider.wallet.publicKey,
48      })
49      .rpc()
50  })
51})

Run anchor test. For the transaction where we pass in the User account type, we expect the instruction and return an Anchor Error for the account not being of type AdminConfig.

1'Program EU66XDppFCf2Bg7QQr59nyykj9ejWaoW93TSkk1ufXh3 invoke [1]',
2'Program log: Instruction: UpdateAdmin',
3'Program log: AnchorError caused by account: admin_config. Error Code: AccountDiscriminatorMismatch. Error Number: 3002. Error Message: 8 byte discriminator did not match what was expected.',
4'Program EU66XDppFCf2Bg7QQr59nyykj9ejWaoW93TSkk1ufXh3 consumed 4765 of 200000 compute units',
5'Program EU66XDppFCf2Bg7QQr59nyykj9ejWaoW93TSkk1ufXh3 failed: custom program error: 0xbba'

Following Anchor best practices and using Anchor types will ensure that your programs avoid this vulnerability. Always use the #[account] attribute when creating account structs, use the init constraint when initializing accounts, and use the Account type in your account validation structs.

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 account types have a discriminator and that those are checked for each account and instruction. Since standard Anchor types handle this check automatically, you're more likely to find a vulnerability in a native program.

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