Signer Authorization

Lesson Objectives

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

  • Explain the security risks associated with not performing appropriate signer checks
  • Implement signer checks using long-form Rust
  • Implement signer checks using Anchor’s Signer type
  • Implement signer checks using Anchor’s #[account(signer)] constraint

TL;DR

  • Use Signer Checks to verify that specific accounts have signed a transaction. Without appropriate signer checks, accounts may be able to execute instructions they shouldn’t be authorized to perform.

  • To implement a signer check in Rust, simply check that an account’s is_signer property is true

    1if !ctx.accounts.authority.is_signer {
    2	return Err(ProgramError::MissingRequiredSignature.into());
    3}
  • In Anchor, you can use the Signer account type in your account validation struct to have Anchor automatically perform a signer check on a given account

  • Anchor also has an account constraint that will automatically verify that a given account has signed a transaction

Overview

Signer checks are used to verify that a given account’s owner has authorized a transaction. Without a signer check, operations whose execution should be limited to only specific accounts can potentially be performed by any account. In the worst case scenario, this could result in wallets being completely drained by attackers passing in whatever account they want to an instruction.

Missing Signer Check

The example below shows an oversimplified version of an instruction that updates the authority field stored on a program account.

Notice that the authority field on the UpdateAuthority account validation struct is of type AccountInfo. In Anchor, the AccountInfo account type indicates that no checks are performed on the account prior to instruction execution.

Although the has_one constraint is used to validate the authority account passed into the instruction matches the authority field stored on the vault account, there is no check to verify the authority account authorized the transaction.

This means an attacker can simply pass in the public key of the authority account and their own public key as the new_authority account to reassign themselves as the new authority of the vault account. At that point, they can interact with the program as the new authority.

1use anchor_lang::prelude::*;
2
3declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
4
5#[program]
6pub mod insecure_update{
7    use super::*;
8        ...
9        pub fn update_authority(ctx: Context<UpdateAuthority>) -> Result<()> {
10        ctx.accounts.vault.authority = ctx.accounts.new_authority.key();
11        Ok(())
12    }
13}
14
15#[derive(Accounts)]
16pub struct UpdateAuthority<'info> {
17   #[account(
18        mut,
19        has_one = authority
20    )]
21    pub vault: Account<'info, Vault>,
22    pub new_authority: AccountInfo<'info>,
23    pub authority: AccountInfo<'info>,
24}
25
26#[account]
27pub struct Vault {
28    token_account: Pubkey,
29    authority: Pubkey,
30}

Add signer authorization checks

All you need to do to validate that the authority account signed is to add a signer check within the instruction. That simply means checking that authority.is_signer is true, and returning a MissingRequiredSignature error if false.

1if !ctx.accounts.authority.is_signer {
2    return Err(ProgramError::MissingRequiredSignature.into());
3}

By adding a signer check, the instruction would only process if the account passed in as the authority account also signed the transaction. If the transaction was not signed by the account passed in as the authority account, then the transaction would fail.

1use anchor_lang::prelude::*;
2
3declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
4
5#[program]
6pub mod secure_update{
7    use super::*;
8        ...
9        pub fn update_authority(ctx: Context<UpdateAuthority>) -> Result<()> {
10            if !ctx.accounts.authority.is_signer {
11            return Err(ProgramError::MissingRequiredSignature.into());
12        }
13
14        ctx.accounts.vault.authority = ctx.accounts.new_authority.key();
15        Ok(())
16    }
17}
18
19#[derive(Accounts)]
20pub struct UpdateAuthority<'info> {
21    #[account(
22        mut,
23        has_one = authority
24    )]
25    pub vault: Account<'info, Vault>,
26    pub new_authority: AccountInfo<'info>,
27    pub authority: AccountInfo<'info>,
28}
29
30#[account]
31pub struct Vault {
32    token_account: Pubkey,
33    authority: Pubkey,
34}

Use Anchor’s Signer account type

However, putting this check into the instruction function muddles the separation between account validation and instruction logic.

Fortunately, Anchor makes it easy to perform signer checks by providing the Signer account type. Simply change the authority account’s type in the account validation struct to be of type Signer, and Anchor will check at runtime that the specified account is a signer on the transaction. This is the approach we generally recommend since it allows you to separate the signer check from instruction logic.

In the example below, if the authority account does not sign the transaction, then the transaction will fail before even reaching the instruction logic.

1use anchor_lang::prelude::*;
2
3declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
4
5#[program]
6pub mod secure_update{
7    use super::*;
8        ...
9        pub fn update_authority(ctx: Context<UpdateAuthority>) -> Result<()> {
10        ctx.accounts.vault.authority = ctx.accounts.new_authority.key();
11        Ok(())
12    }
13}
14
15#[derive(Accounts)]
16pub struct UpdateAuthority<'info> {
17    #[account(
18        mut,
19        has_one = authority
20    )]
21    pub vault: Account<'info, Vault>,
22    pub new_authority: AccountInfo<'info>,
23    pub authority: Signer<'info>,
24}
25
26#[account]
27pub struct Vault {
28    token_account: Pubkey,
29    authority: Pubkey,
30}

Note that when you use the Signer type, no other ownership or type checks are performed.

Use Anchor’s #[account(signer)] constraint

While in most cases, the Signer account type will suffice to ensure an account has signed a transaction, the fact that no other ownership or type checks are performed means that this account can’t really be used for anything else in the instruction.

This is where the signer constraint comes in handy. The #[account(signer)] constraint allows you to verify the account signed the transaction, while also getting the benefits of using the Account type if you wanted access to it’s underlying data as well.

As an example of when this would be useful, imagine writing an instruction that you expect to be invoked via CPI that expects one of the passed in accounts to be both a signer on the transaciton and a data source. Using the Signer account type here removes the automatic deserialization and type checking you would get with the Account type. This is both inconvenient, as you need to manually deserialize the account data in the instruction logic, and may make your program vulnerable by not getting the ownership and type checking performed by the Account type.

In the example below, you can safely write logic to interact with the data stored in the authority account while also verifying that it signed the transaction.

1use anchor_lang::prelude::*;
2
3declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
4
5#[program]
6pub mod secure_update{
7    use super::*;
8        ...
9        pub fn update_authority(ctx: Context<UpdateAuthority>) -> Result<()> {
10        ctx.accounts.vault.authority = ctx.accounts.new_authority.key();
11
12        // access the data stored in authority
13        msg!("Total number of depositors: {}", ctx.accounts.authority.num_depositors);
14        Ok(())
15    }
16}
17
18#[derive(Accounts)]
19pub struct UpdateAuthority<'info> {
20    #[account(
21        mut,
22        has_one = authority
23    )]
24    pub vault: Account<'info, Vault>,
25    pub new_authority: AccountInfo<'info>,
26    #[account(signer)]
27    pub authority: Account<'info, AuthState>
28}
29
30#[account]
31pub struct Vault {
32    token_account: Pubkey,
33    authority: Pubkey,
34}
35#[account]
36pub struct AuthState{
37	amount: u64,
38	num_depositors: u64,
39	num_vaults: u64
40}

Demo

Let’s practice by creating a simple program to demonstrate how a missing signer check can allow an attacker to withdraw tokens that don’t belong to them.

This program initializes a simplified token “vault” account and demonstrates how a missing signer check could allow the vault to be drained.

1. Starter

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

The initialize_vault instruction initializes two new accounts: Vault and TokenAccount. The Vault account will be initialized using a Program Derived Address (PDA) and store the address of a token account and the authority of the vault. The authority of the token account will be the vault PDA which enables the program to sign for the transfer of tokens.

The insecure_withdraw instruction will transfer tokens in the vault account’s token account to a withdraw_destination token account. However, the authority account in the InsecureWithdraw struct has a type of UncheckedAccount. This is a wrapper around AccountInfo to explicitly indicate the account is unchecked.

Without a signer check, anyone can simply provide the public key of the authority account that matches authority stored on the vault account and the insecure_withdraw instruction would continue to process.

While this is somewhat contrived in that any DeFi program with a vault would be more sophisticated than this, it will show how the lack of a signer check can result in tokens being withdrawn by the wrong party.

1use anchor_lang::prelude::*;
2use anchor_spl::token::{self, Mint, Token, TokenAccount};
3
4declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
5
6#[program]
7pub mod signer_authorization {
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 amount = ctx.accounts.token_account.amount;
18
19        let seeds = &[b"vault".as_ref(), &[*ctx.bumps.get("vault").unwrap()]];
20        let signer = [&seeds[..]];
21
22        let cpi_ctx = CpiContext::new_with_signer(
23            ctx.accounts.token_program.to_account_info(),
24            token::Transfer {
25                from: ctx.accounts.token_account.to_account_info(),
26                authority: ctx.accounts.vault.to_account_info(),
27                to: ctx.accounts.withdraw_destination.to_account_info(),
28            },
29            &signer,
30        );
31
32        token::transfer(cpi_ctx, amount)?;
33        Ok(())
34    }
35}
36
37#[derive(Accounts)]
38pub struct InitializeVault<'info> {
39    #[account(
40        init,
41        payer = authority,
42        space = 8 + 32 + 32,
43        seeds = [b"vault"],
44        bump
45    )]
46    pub vault: Account<'info, Vault>,
47    #[account(
48        init,
49        payer = authority,
50        token::mint = mint,
51        token::authority = vault,
52    )]
53    pub token_account: Account<'info, TokenAccount>,
54    pub mint: Account<'info, Mint>,
55    #[account(mut)]
56    pub authority: Signer<'info>,
57    pub token_program: Program<'info, Token>,
58    pub system_program: Program<'info, System>,
59    pub rent: Sysvar<'info, Rent>,
60}
61
62#[derive(Accounts)]
63pub struct InsecureWithdraw<'info> {
64    #[account(
65        seeds = [b"vault"],
66        bump,
67        has_one = token_account,
68        has_one = authority
69    )]
70    pub vault: Account<'info, Vault>,
71    #[account(mut)]
72    pub token_account: Account<'info, TokenAccount>,
73    #[account(mut)]
74    pub withdraw_destination: Account<'info, TokenAccount>,
75    pub token_program: Program<'info, Token>,
76    /// CHECK: demo missing signer check
77    pub authority: UncheckedAccount<'info>,
78}
79
80#[account]
81pub struct Vault {
82    token_account: Pubkey,
83    authority: Pubkey,
84}

2. Test insecure_withdraw instruction

The test file includes the code to invoke the initialize_vault instruction using wallet as the authority on the vault. The code then mints 100 tokens to the vault token account. Theoretically, the wallet key should be the only one that can withdraw the 100 tokens from the vault.

Now, let’s add a test to invoke insecure_withdraw on the program to show that the current version of the program allows a third party to in fact withdraw those 100 tokens.

In the test, we’ll still use the public key of wallet as the authority account, but we’ll use a different keypair to sign and send the transaction.

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

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

1signer-authorization
2  ✔ Initialize Vault (810ms)
3  ✔ Insecure withdraw  (405ms)

Since there is no signer check for the authority account, the insecure_withdraw instruction will transfer tokens from the vault token account to the withdrawDestinationFake token account as long as the public key of theauthority account matches the public key stored on the authority field of the vault account. Clearly, the insecure_withdraw instruction is as insecure as the name suggests.

3. Add secure_withdraw instruction

Let’s fix the problem in a new instruction called secure_withdraw. This instruction will be identical to the insecure_withdraw instruction, except we’ll use the Signer type in the Accounts struct to validate the authority account in the SecureWithdraw struct. If the authority account is not a signer on the transaction, then we expect the transaction to fail and return an error.

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

4. Test secure_withdraw instruction

With the instruction in place, return to the test file to test the secure_withdraw instruction. Invoke the secure_withdraw instruction, again using the public key of wallet as the authority account and the withdrawDestinationFake keypair as the signer and withdraw destination. Since the authority account is validated using the Signer type, we expect the transaction to fail the signer check and return an error.

1describe("signer-authorization", () => {
2    ...
3	it("Secure withdraw", async () => {
4    try {
5      const tx = await program.methods
6        .secureWithdraw()
7        .accounts({
8          vault: vaultPDA,
9          tokenAccount: tokenAccount.publicKey,
10          withdrawDestination: withdrawDestinationFake,
11          authority: wallet.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})

Run anchor test to see that the transaction will now return a signature verification error.

1Error: Signature verification failed

That’s it! This is a fairly simple thing to avoid, but incredibly important. Make sure to always think through who should who should be authorizing instructions and make sure that each is a signer on the transaction.

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

Challenge

At this point in the course, we hope you've started to work on programs and projects outside the Demos and Challenges provided in these lessons. For this and the remainder of the lessons on security vulnerabilities, the Challenge for each lesson will be to audit your own code for the security vulnerability discussed in the lesson.

Alternatively, you can find open source programs to audit. There are plenty of programs you can look at. A good start if you don't mind diving into native Rust would be the SPL programs.

So for this lesson, take a look at a program (whether yours or one you've found online) and audit it for signer checks. If you find a bug in somebody else's program, please alert them! If you find a bug in your own program, be sure to patch it right away.

Table of Contents