repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

237 lines · 15.8 KB · download this file

package BlowfishCMS;
# Two-step sign-in: a password, then a six-digit code from an authenticator
# app (TOTP, RFC 6238: HMAC-SHA1, 30-second steps), or one of ten single-use
# recovery codes. Each user turns it on for themselves under Your account.
#
# The keys are kept in the admin service's own folder ($data/admin/mfa, which
# no other service can read), not in the catalogue: a copy of the catalogue or
# a backup doesn't carry them. After restoring a server, people set it up
# again; `blowfishctl mfa-off NAME` turns it off for someone locked out.
use v5.36;
use utf8;
use Digest::SHA qw(hmac_sha1 sha256_hex hmac_sha256_hex);
use Fcntl qw(:flock);
use JSON::PP ();
our ($base,$data,$db,$q,$method,$csrf,$cookie_header,%instance);

my @b32=('A'..'Z','2'..'7');
# Bytes as base32 (letters A-Z and digits 2-7, five bits per character), the
# form authenticator apps take keys in.
sub base32 ($bytes) { my $bits=unpack 'B*',$bytes;$bits.='0' x ((5-length($bits)%5)%5);return join '',map {$b32[oct "0b$_"]} $bits =~ /(.{5})/g }
# Base32 back to bytes, ignoring spaces, dashes and '=' padding; undef for
# anything that isn't base32.
sub unbase32 ($text) {
    my %v=map {($b32[$_]=>$_)} 0..31;(my $t=uc $text) =~ s/[\s=-]//g;
    return undef if $t =~ /[^A-Z2-7]/;
    my $bits=join '',map {sprintf '%05b',$v{$_}} split //,$t;
    return pack 'B*',substr($bits,0,length($bits)-length($bits)%8);
}
# The six-digit code for one 30-second step, as RFC 6238 and RFC 4226 define
# it: HMAC-SHA1 of the step number (8 bytes, big-endian) with the shared
# key; the last 4 bits of the result pick where to read 4 bytes ("dynamic
# truncation"); those, without their top bit, modulo 1,000,000.
sub totp_code ($key,$step) {
    my $mac=hmac_sha1(pack('NN',int($step/2**32),$step % 2**32),$key);
    my $off=ord(substr $mac,-1) & 0x0f;
    return sprintf '%06d',(unpack('N',substr $mac,$off,4) & 0x7fffffff) % 1000000;
}
# The admin's private folder of two-step keys, one JSON file per user:
#   key        the shared secret (base32), once set up
#   last_step  the last code step used, so no code works twice
#   recovery   the recovery codes, hashed
#   pending / pending_at   a new key being set up (for 30 minutes)
sub mfa_dir { return "$data/admin/mfa" }
sub mfa_file ($user) { return mfa_dir()."/$user.json" }
# A user's two-step file, or {} if they have none.
sub mfa_read ($user) {
    return {} unless name_ok($user//'');
    open my $fh,'<',mfa_file($user) or return {};local $/;my $raw=<$fh>;close $fh;
    my $d=attempt {JSON::PP->new->decode($raw)};return ref $d eq 'HASH' ? $d : {};
}
# Saves a user's two-step file (written to a temporary file, then renamed
# into place), and notes in the catalogue whether they now have it on.
sub mfa_write ($user,$d) {
    die "That name isn't right.\n" unless name_ok($user);
    mkdir mfa_dir(),0700 unless -d mfa_dir();
    my $file=mfa_file($user);
    open my $fh,'>',"$file.tmp" or die "The two-step keys can't be written.\n";
    chmod 0600,"$file.tmp";print {$fh} JSON::PP->new->canonical->encode($d);close $fh or die "The two-step keys can't be written.\n";
    rename "$file.tmp",$file or die "The two-step keys can't be written.\n";
    mfa_flag($user,length($d->{key}//'') ? 1 : 0);
}
# Turns two-step sign-in off for a user: deletes their file.
sub mfa_remove ($user) { return unless name_ok($user//'');unlink mfa_file($user);mfa_flag($user,0) }
# The catalogue's note of who has it on, which the other services read.
sub mfa_flag ($user,$on) { attempt {$db->do('UPDATE admin_users SET mfa=? WHERE name=?',undef,$on,$user) if $db && users_table();1} }
# Two-step sign-in can be required of owners or of everyone (Settings › Sign-in).
sub mfa_required_for ($row) {
    my $rule=setting('mfa_required');
    return 0 unless $row && ($rule eq 'everyone' || ($rule eq 'owners' && $row->{role} eq 'owner'));
    return 1;
}
# Signed in with a password alone where two-step is required: only setting it up (or signing out) is allowed.
# Whether a signed-in user must set two-step sign-in up before doing
# anything else (the site requires it of them and they haven't).
sub mfa_setup_needed ($user) {
    return 0 unless session_mode() && users_table();
    my $row=admin_user_row($user);
    return 0 unless $row && exists $row->{mfa};
    return mfa_required_for($row) && !$row->{mfa} ? 1 : 0;
}
# Whether a user has two-step sign-in on (has a key).
sub mfa_enabled ($user) { return length(mfa_read($user)->{key}//'') ? 1 : 0 }

# Checks a code from the app (or a recovery code) and uses it up.
# Checks a code at sign-in and uses it up. Locked (flock) so two attempts at
# once can't both use the same code. A six-digit code is accepted for the
# current step or the one either side (phones' clocks drift a little), but
# never for a step at or before the last one used. A ten-character code is
# tried as a recovery code: if it matches one, that one is removed. Returns
# 1, 'recovery' or 0.
sub mfa_check ($user,$code) {
    $code=lc($code//'');$code =~ s/[\s-]//g;
    my $file=mfa_file($user);return 0 unless name_ok($user//'') && -f $file;
    open my $lock,'<',$file or return 0;flock($lock,LOCK_EX);
    my $d=mfa_read($user);my $key=unbase32($d->{key}//'') or return 0;
    if ($code =~ /\A\d{6}\z/) {
        my $now=int(time/30);
        # The step before and after are allowed too, for clocks a little out; never one already used.
        for my $step ($now-1,$now,$now+1) {
            next if $step<=($d->{last_step}//0);
            if (eq_safe(totp_code($key,$step),$code)) {$d->{last_step}=$step;mfa_write($user,$d);return 1}
        }
        return 0;
    }
    if ($code =~ /\A[a-z2-7]{10}\z/) {
        my $h=sha256_hex("recovery|$code");my @left=grep {!eq_safe($_,$h)} @{$d->{recovery}//[]};
        if (@left<@{$d->{recovery}//[]}) {$d->{recovery}=\@left;mfa_write($user,$d);return 'recovery'}
    }
    return 0;
}
# Ten new recovery codes like "abcde-fghij" (random, base32, lowercase).
sub recovery_codes { return map {my $c=lc base32(random_bytes(7));substr($c,0,5).'-'.substr($c,5,5)} 1..10 }
# $n random bytes from the system's random source.
sub random_bytes ($n) {
    open my $fh,'<:raw','/dev/urandom' or die "No random source.\n";read($fh,my $b,$n)==$n or die "No random source.\n";close $fh;return $b;
}
# Recovery codes as stored: hashed, so a copy of the file doesn't give them away.
sub hash_recovery (@codes) { return [map {(my $c=$_) =~ s/-//g;sha256_hex("recovery|$c")} @codes] }

# ---- Between the password and the code -------------------------------------------
# A short-lived cookie says who has given the right password; it's only good
# for five minutes and for the code step.
my $mfa_minutes=5;
# After the right password, the bf_mfa cookie: who, their session
# generation, when it expires (5 minutes) and a signature made with the
# session key (with "mfa|" in front, so it can never pass as a session cookie).
sub mfa_pending_cookie ($user) {
    my $row=admin_user_row($user);my $gen=$row ? $row->{session_gen}//1 : 1;
    my $value="$user.$gen.".(time+$mfa_minutes*60).'.'.random_id();
    return 'bf_mfa='.$value.'.'.hmac_sha256_hex("mfa|$value",session_key()).'; Path=/admin/; Max-Age='.($mfa_minutes*60).'; Secure; HttpOnly; SameSite=Strict';
}
# Who the bf_mfa cookie says gave the right password, if it's valid, unexpired,
# still matches their session generation and they still use two-step.
sub mfa_pending_user {
    my $cookie=$q ? ($q->cookie('bf_mfa')//'') : '';
    my ($user,$gen,$expires,$nonce,$mac)=$cookie =~ /\A([a-z_][a-z0-9_.-]{0,31})\.(\d{1,9})\.(\d{10})\.([a-f0-9]{32})\.([a-f0-9]{64})\z/ or return '';
    return '' unless $expires>time && $expires<=time+$mfa_minutes*60+60;
    my $key=attempt {session_key()} or return '';
    return '' unless eq_safe($mac,hmac_sha256_hex("mfa|$user.$gen.$expires.$nonce",$key));
    my $row=admin_user_row($user) or return '';
    return $gen==($row->{session_gen}//1) && mfa_enabled($user) ? $user : '';
}
# The code step's page.
sub mfa_page ($message,$next) {
    header($message ? 400 : 200);
    my $site=setting('site_title');
    print '<!doctype html><html lang="en" class="admin"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">'
        .'<title>Sign in · '.h($site).'</title>'.icon_head().'<link rel="stylesheet" href="/css/site.css?v=18"><link rel="stylesheet" href="/css/admin.css?v=55"></head>'
        .'<body class="login-body"><main class="login-card"><h1>'.h($site).'</h1><p class="admin-top__intro">Enter the six-digit code from your authenticator app.</p>'
        .(length $message ? '<p class="panel-note admin-notice admin-notice--error" role="alert">'.h($message).'</p>' : '')
        .'<form method="post" action="/admin/" class="admin-form">'.hidden(csrf=>$csrf,kind=>'login',step=>'code',next=>$next)
        .'<label>Code<input name="code" inputmode="numeric" autocomplete="one-time-code" autocapitalize="none" spellcheck="false" maxlength="14" required autofocus></label>'
        .'<button class="buttonlike is-primary" type="submit">sign in</button></form>'
        .'<p class="login-foot">Lost your phone? Type one of your recovery codes instead.<br><a href="/admin/?kind=login">← start again</a></p></main></body></html>';
}

# ---- Your account: turning it on and off ----------------------------------------------
# Your account's two-step actions; returns 1 when it handled one:
#   mfa_start    make a new key, waiting to be confirmed
#   mfa_confirm  check a code from the app against it, then switch it on and
#                show the recovery codes
#   mfa_codes    new recovery codes (needs a current code)
#   mfa_off      turn it off (needs the password; not where it's required)
sub mfa_account_action ($action,$me) {
    if ($action eq 'mfa_start') {
        my $d=mfa_read($me);die "Two-step sign-in is already on.\n" if length($d->{key}//'');
        mfa_write($me,{%$d,pending=>base32(random_bytes(20)),pending_at=>time});
        redirect('/admin/?kind=account#two-step');
    }
    if ($action eq 'mfa_confirm') {
        my $d=mfa_read($me);
        die "Start again: press “turn on”.\n" unless length($d->{pending}//'') && ($d->{pending_at}//0)>time-1800;
        my $key=unbase32($d->{pending});my $code=param('code',10) =~ s/\s//gr;my $now=int(time/30);
        my ($used)=grep {eq_safe(totp_code($key,$_),$code)} $now-1..$now+1;
        die "That code isn’t right. Check the app shows this site, and that your phone’s clock is set automatically.\n" unless defined $used;
        my @codes=recovery_codes();
        mfa_write($me,{key=>$d->{pending},last_step=>$used,recovery=>hash_recovery(@codes),since=>time});
        mfa_show_recovery($me,'Two-step sign-in is on.',@codes);return 1;
    }
    if ($action eq 'mfa_codes') {
        die "Two-step sign-in is off.\n" unless mfa_enabled($me);
        mfa_check($me,param('code',14)) eq '1' or die "That code isn’t right.\n";
        my @codes=recovery_codes();my $d=mfa_read($me);$d->{recovery}=hash_recovery(@codes);mfa_write($me,$d);
        mfa_show_recovery($me,'New recovery codes: the old ones no longer work.',@codes);return 1;
    }
    if ($action eq 'mfa_off') {
        die "This site requires two-step sign-in for you, so it can’t be turned off. An owner decides that under Settings › Sign-in.\n" if mfa_required_for(admin_user_row($me));
        check_password($me,scalar($q->param('current'))//'') or die "Your current password isn't right.\n";
        mfa_remove($me);
        redirect('/admin/?kind=account&notice='.CGI::escape('Two-step sign-in is off.'));
    }
    return 0;
}
# Recovery codes are shown once, right after they're made.
sub mfa_show_recovery ($me,$notice,@codes) {
    admin_page('Your recovery codes',section=>'account',notice=>$notice,crumbs=>[['Your account','/admin/?kind=account']],
        intro=>'Keep these somewhere safe, away from your phone: a password manager, or printed. Each one signs you in once if you lose your phone. They won’t be shown again.');
    window('recovery codes','<ol class="recovery-codes">'.join('',map {'<li><code>'.h($_).'</code></li>'} @codes).'</ol>'
        .'<p><button class="buttonlike" type="button" data-copy="'.h(join("\n",@codes)).'">copy</button> <a class="buttonlike is-primary" href="/admin/?kind=account">done</a></p>');
    end_page();
}
# Your account's two-step panel: on (codes left, new codes, turn off),
# setting up (the QR code for the app and the key written out, then the
# code), or off (set up). The QR code holds an otpauth:// address with the
# key, the site's name and the user, which authenticator apps understand.
sub mfa_account_window ($me) {
    my $d=mfa_read($me);
    if (length($d->{key}//'')) {
        my $left=scalar @{$d->{recovery}//[]};
        return '<div id="two-step"><p><strong>On.</strong> Signing in asks for a code from your authenticator app. '.$left.' recovery code'.($left==1?'':'s').' left.</p>'
            .'<form method="post" action="/admin/" class="admin-form">'.fields('mfa_codes','account').'<label>Code from the app<input name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" required></label><button class="buttonlike" type="submit">new recovery codes</button></form>'
            .(mfa_required_for(admin_user_row($me)) ? '<p class="optional">This site requires two-step sign-in for you, so it stays on.</p>' : '<form method="post" action="/admin/" class="admin-form" data-confirm="Turn off two-step sign-in? Your password alone will sign you in.">'.fields('mfa_off','account').'<input type="text" name="username" value="'.h($me).'" autocomplete="username" hidden><label>Current password<input type="password" name="current" autocomplete="current-password" maxlength="200" required></label><button class="buttonlike danger" type="submit">turn off</button></form>').'</div>';
    }
    if (length($d->{pending}//'') && ($d->{pending_at}//0)>time-1800) {
        my $site=setting('site_title') // $instance{domain};
        my $label=CGI::escape(($site =~ s/:/ /gr).':'.$me);
        my $uri='otpauth://totp/'.$label.'?secret='.$d->{pending}.'&issuer='.CGI::escape($site =~ s/:/ /gr).'&algorithm=SHA1&digits=6&period=30';
        return '<div id="two-step" class="mfa-setup"><div class="mfa-setup__qr">'.qr_svg($uri,'QR code for your authenticator app').'</div><div>'
            .'<ol><li>Open your authenticator app (Google Authenticator, Microsoft Authenticator, 1Password, Authy…) and add an account by scanning this code.</li>'
            .'<li>Can’t scan? Enter this key instead: <code class="mfa-key">'.h(join ' ',$d->{pending} =~ /(.{1,4})/g).'</code></li>'
            .'<li>Type the six-digit code the app shows.</li></ol>'
            .'<form method="post" action="/admin/" class="admin-form">'.fields('mfa_confirm','account').'<label>Code<input name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" required autofocus></label><button class="buttonlike is-primary" type="submit">turn on</button></form></div></div>';
    }
    return '<div id="two-step"><p><strong>Off.</strong> Ask for a code from an authenticator app on your phone as well as your password, so a stolen password alone can’t get in.'
        .(is_owner() ? ' Owners can update the server from System, so this matters most for you.' : '').'</p>'
        .'<form method="post" action="/admin/">'.fields('mfa_start','account').'<button class="buttonlike is-primary" type="submit">set up</button></form></div>';
}
# site.pl --mfa-off NAME (blowfishctl mfa-off): for someone locked out.
# site.pl --mfa-off NAME (`blowfishctl mfa-off NAME`): for someone who's lost
# their phone and recovery codes.
sub mfa_off_cli ($name) {
    die "Names are 1–32 lowercase letters, numbers, dots, dashes or underscores.\n" unless name_ok($name);
    return "Two-step sign-in wasn't on for $name." unless -f mfa_file($name);
    $db=database(1);mfa_remove($name);
    return "Two-step sign-in is off for $name; their password alone signs them in.".(mfa_required_for(admin_user_row($name)) ? ' The site requires it of them, so they set it up again when they next sign in.' : '');
}
1;