Version 6 pre-stable
This version of Silverstripe CMS has not yet been given a stable release. See the release roadmap for more information. Go to documentation for the most recent stable version.

Backup codes

Backup codes are random strings that are provided as recovery options in case a member loses their ability to verify with their registered multi-factor authentication methods, e.g. they lost their phone or security key.

Generating backup codes

Backup codes are generated by the BackupCodeGeneratorInterface service, which has a default implementation of BackupCodeGenerator. This service will hash the generated backup codes using the default Silverstripe CMS PasswordEncryptor service and algorithm, and returns an array of BackupCode instances.

You can use this service class to generate codes:

use SilverStripe\MFA\Service\BackupCodeGeneratorInterface;

// ...

$generator = Injector::inst()->get(BackupCodeGeneratorInterface::class);
$codes = $generator->generate();

Verifying backup codes

To verify a backup code, you can reconstruct a BackupCode instance from stored data on the RegisteredMethod instance and use BackupCode::isValid() to verify the input. For example:

use SilverStripe\MFA\State\BackupCode;

// ...

$storedCodeData = json_decode($registeredMethod->Data, true);
foreach ($storedCodeData as $codeCandidate) {
    // Expected structure: ['hash' => 'abc123', 'algorithm' => 'blowfish', 'salt' => 'bae']
    $candidate = json_decode($codeCandidate, true);

    $backupCode = BackupCode::create($userInputCode, $candidate['hash'], $candidate['algorithm'], $candidate['salt']);
    if ($backupCode->isValid()) {
        // The user entered a valid backup code, do as you please now.
    }
}

The default implementation of this logic is in VerifyHandler::verify().

BackupCodeGenerator

This configuration documentation applies to the default BackupCodeGenerator implementation of BackupCodeGeneratorInterface.

Configuration

You can adjust either the length of the backup code strings, or the number of them that are generated, by setting YAML configuration:

SilverStripe\MFA\Service\BackupCodeGenerator:
  # Should be 12 characters long
  backup_code_length: 12
  # I want 25 of them
  backup_code_count: 25

Adjusting the character sets

By default, backup codes will be generated using lowercase letters. If you would like to increase the entropy of your backup codes by adding extra character types, you can do so by adding an extension:

// app/src/MFA/Extension/BackupCodeGeneratorExtension.php
namespace App\MFA\Extension;

class BackupCodeGeneratorExtension extends Extension
{
    /**
     * Add some special characters into the character set for generating backup codes
     */
    protected function updateCharacterSet(&$characterSet)
    {
        $characterSet = array_merge($characterSet, ['!', '@', '#', '$', '%', '^']);
    }
}

This extension should be applied to SilverStripe\MFA\Service\BackupCodeGenerator via YAML configuration.