guest@websec: ~/websec/05b-mfa — zsh — 100×40 by SaKKo YouTube ENTH code:

guest@websec ~ % man 05b-mfa

05b · Multi-Factor Authentication

A second factor means a stolen password is no longer enough. It only works if the factor is really separate from the password, can’t be guessed, and every login path checks it.

Rails has no MFA built in. You pick the pieces: rotp for TOTP, encrypts for the secret, Rack::Attack for rate limits, webauthn for passkeys.
Use an authenticator app (TOTP) or passkeys. Store the TOTP secret encrypted, verify on the server with a small drift window, refuse reused codes, rate-limit attempts, confirm enrolment with a first code, and enforce it in one place that every login path goes through. Don't invent your own "random code" scheme.

What counts as a second factor

Factors are things you know (password), have (phone, security key) or are (fingerprint). Two passwords are still one factor. The point: an attacker who phished or bought your password still can’t log in.

methodstrengthweak spot
Passkey / security key (WebAuthn)bestbound to the real domain, so phishing sites get nothing
Authenticator app (TOTP)gooda live phishing page can relay the 6 digits within 30 s
Push approvalok"MFA fatigue": spam prompts until someone taps yes
SMS / email codeweakSIM swap, SS7 interception, or the email account is the same one being attacked

Why not just store a random number and compare it in the controller?

It looks like MFA. It’s the most common home-made version we see in reviews:

# ✗ home-made "2FA"
class Api::V1::SessionsController < Api::V1::AppController
  def create
    user = User.find_by!(username: params[:username])
    raise AppAuthenticationError unless user.authenticate(params[:password])
    code = rand(100000..999999).to_s
    user.update!(otp_code: code)                      # plaintext, no expiry
    update_cookies(:bearer, user.jwt("bearer"))       # session issued already!
    render json: { success: true, otp: code }         # "the app shows it to the user"
  end

  def verify_otp
    if params[:code] == current_user.otp_code         # unlimited tries, reusable
      current_user.update!(otp_verified: true)        # one flag for all sessions
      render json: { success: true }
    else
      render json: { success: false }, status: :unauthorized
    end
  end
end

Count the problems, then fix them one by one in the lab below and watch which attacks still work:

lab: attack the home-made 2FAtoggle fixes, read the results

Even with every box ticked, the home-made version is a weaker copy of SMS codes: you now own delivery, expiry, hashing, lockout and the session gate. TOTP removes the stored code entirely, so whole classes of bugs disappear.

"In the controller" is part of the bug. We have two login paths (Admin::SessionsController#create and Client::AuthController#login). A check pasted into one controller is a check missing from the other. Keep verification in the model (user.verify_otp) and make every login path call it before any session or token is issued.

Brute force is about attempts, not digits

Six digits is only a million possibilities. What protects it is how many guesses you allow. Play with the numbers:

calculator: chance an attacker guesses a codechange the limits

No limit at 10/s for a day: almost certain. Five tries per 15 minutes for a month: about 1.4%. Lock the account after 10 bad codes and alert the user: 0.001%. Rate-limit per account and per IP, and count failed OTPs separately from failed passwords.

How TOTP works

  1. At enrolment the server makes a random secret and shows it once, as a QR code of an otpauth:// URI. The phone stores it.
  2. Both sides compute T = floor(unix_time / 30).
  3. Both compute HMAC-SHA1(secret, T) and truncate it to 6 digits (RFC 6238).
  4. Nothing is sent from server to phone after enrolment. Same secret + same clock = same code.
live: a real TOTP, computed in your browsertype the phone's code into the server

Try it: press use phone’s code twice. The second is refused with replay protection on, accepted with it off. Slide the phone clock to −30 s: drift_behind: 1 still accepts; −60 s fails. You can also type the secret into a real authenticator app and watch it show the same code.

The two flows

In our Rails code

class User < ApplicationRecord
  encrypts :otp_secret                       # Active Record encryption at rest
  # ApplicationRecord: has_paper_trail skip: [:otp_secret], as_json drops "otp" columns

  def enable_two_factor!
    raise AppError.new("Two-factor authentication is already enabled. Disable it first.") if otp_required?
    self.otp_secret = ROTP::Base32.random
    self.otp_required = false                # not on until confirmed
    save!
  end

  def confirm_two_factor!(code)
    verify_otp(code) ? update!(otp_required: true) : false
  end

  def verify_otp(code)
    return false if otp_secret.blank? || code.blank?
    !totp.verify(code.to_s.strip, drift_behind: 1).nil?
  end

  def provisioning_uri
    totp.provisioning_uri(email.presence || username) if otp_secret.present?
  end

  def totp
    @totp ||= ROTP::TOTP.new(otp_secret, issuer: "MyApp")
  end
end

Good already: secret encrypted and kept out of audit logs and JSON; enrolment confirmed with a first code; verification in the model; both login paths refuse users without otp_required? and check the code before issuing a cookie or token. What to add:

1. Refuse reused codes

# migration: add_column :users, :otp_last_used_at, :bigint

def verify_otp(code)
  return false if otp_secret.blank? || code.blank?
  ts = totp.verify(code.to_s.strip, drift_behind: 1, after: otp_last_used_at)  # nil if reused
  return false unless ts
  update_columns(otp_last_used_at: ts)
  true
end

2. Rate-limit the OTP check

# config/initializers/rack_attack.rb
Rack::Attack.throttle("logins/username", limit: 5, period: 5.minutes) do |req|
  if req.post? && ["/api/v1/admin/sessions", "/api/v1/client/auth/login"].include?(req.path)
    (req.params.dig("user", "username") || req.params["username"]).to_s.downcase.presence
  end
end

3. Recovery codes, hashed and single-use

def generate_recovery_codes!
  codes = Array.new(10) { SecureRandom.alphanumeric(10).downcase }
  update!(otp_recovery_digests: codes.map { BCrypt::Password.create(_1) })   # store hashes only
  codes                                                                       # show once
end

def use_recovery_code!(code)
  digest = otp_recovery_digests.find { BCrypt::Password.new(_1) == code.to_s.strip.downcase }
  digest ? update!(otp_recovery_digests: otp_recovery_digests - [digest]) : false
end

4. Protect the off switch

disable_two_factor! should require a fresh password and a current code, log an audit event and notify the user by email. An attacker with a stolen session will go straight for it.

Checklist

  • TOTP or passkeys; SMS only as a fallback, never email-only for staff
  • secret: ROTP::Base32.random, encrypts, excluded from logs, JSON and audit trails, shown only during enrolment
  • enrolment switched on only after a correct first code
  • verification in the model; every login path calls it before issuing a session or token
  • drift window ≤ 1 step; reused time steps rejected
  • rate limit per account and per IP; alert on repeated failures
  • hashed, single-use recovery codes
  • disabling MFA or changing the phone needs re-authentication and sends a notification

Check yourself

The login endpoint returns { otp: "482913" } so the mobile app can show it. How much security does this second step add?

A second factor must reach the user through something the attacker doesn't control.

Why does enrolment ask for a first code before setting otp_required: true?

A failed scan or a typo in manual entry would otherwise lock the account on the next login.

An attacker can make 10 guesses per second with no rate limit. Roughly how long until a 6-digit TOTP falls?

Rotation doesn't help much: each guess has a ~2-in-a-million chance, and 864,000 guesses a day makes success likely. Only rate limiting fixes this.