repository

BlowfishCMS

A small content management system for OpenBSD

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

219 lines · 12.6 KB · download this file

package BlowfishCMS;
# Signing in to the admin. A login page checks the admin's name and password
# against the admin users (Users.pm), with lockout after repeated failures, and
# sets a signed session cookie for /admin/.
#
# Every service with an admin screen (admin, comments, mail, add-ons with
# their own service) checks that cookie with the session key, which only those
# services can read (group _bfstaff); the public pages can't. Without the
# session key nobody is signed in (blowfishctl install and httpd make one).
use v5.36;
use utf8;
use Digest::SHA qw(hmac_sha256_hex sha256_hex);
use Encode qw(encode);
use Fcntl qw(:flock);
use JSON::PP ();
our ($base,$data,$db,$q,$method,$csrf,$cookie_header,%instance);

# The secret key that signs session cookies, shared by the services with
# admin screens (the staff group may read it).
sub session_key_file { return "$base/etc/blowfishcms-session/session.key" }
# Whether sign-in is possible here at all (the session key exists).
sub session_mode { return -e session_key_file() }
# Reads the session key; it must be at least 32 characters.
sub session_key {
    open my $fh,'<',session_key_file() or die "The session key can't be read.\n";
    my $k=do {local $/;<$fh>};close $fh;$k//='';$k =~ s/\s+//g;
    die "The session key is empty.\n" unless length $k>=32;
    return $k;
}
my $session_hours=12;

# The signed-in admin's name, or '' when nobody is signed in.
# Who is signed in, from the bf_session cookie, or ''. The cookie is
# NAME.GEN.EXPIRES.NONCE.SIGNATURE. It's accepted only if:
#   - it has exactly that shape;
#   - it hasn't expired, and doesn't claim to last longer than a session can
#     (so a forged far-future expiry is refused);
#   - its signature (an HMAC of the rest, made with the session key) matches,
#     compared in constant time;
#   - the user still exists and GEN is still their session generation. A new
#     password, being removed, or "sign out everywhere" moves the generation
#     on, which ends every older session at once.
sub signed_in_admin {
    return '' unless session_mode();
    my $cookie=$q ? ($q->cookie('bf_session')//'') : '';
    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/i or return '';
    return '' unless $expires>time && $expires<=time+$session_hours*3600+60;
    my $key=attempt {session_key()} or return '';
    return '' unless eq_safe($mac,hmac_sha256_hex("$user.$gen.$expires.$nonce",$key));
    # Still a user, and no password change or sign-out everywhere since this session began.
    my $row=admin_user_row($user) or return '';
    return $gen == ($row->{session_gen}//1) ? $user : '';
}
# For admin screens: true when signed in; otherwise answers the request
# (the login page, a redirect to it, or 401 for background requests).
# The gate in front of every admin screen. Returns 1 when the request may go
# on. Otherwise it answers the request itself and returns 0:
#   - signed in, but the site requires two-step sign-in and this user hasn't
#     set it up: only Your account and sign-out are allowed, the rest send
#     them there;
#   - signed in, but the screen is for owners ($owner) and they're an editor:
#     a "for owners" page;
#   - not signed in: 401 for the admin's script or a form post (so unsaved
#     work isn't lost), otherwise the login page ($login_here) or a redirect
#     to it that returns here afterwards.
sub require_admin ($login_here=0,$owner=0) {
    if (length(my $user=signed_in_admin())) {
        if (mfa_setup_needed($user)) {
            my $kind=($ENV{DOCUMENT_URI}//'') eq '/admin/' && $q ? ($q->param('kind')//'') : '';
            unless ($kind eq 'account' || $kind eq 'logout') {
                my $why='This site requires two-step sign-in. Set it up to carry on.';
                json_response({ok=>JSON::PP::false,message=>$why},403) if ($ENV{HTTP_X_REQUESTED_WITH}//'') eq 'fetch';
                if ($method ne 'GET') {header(403,'text/plain; charset=UTF-8');print $why;return 0}
                redirect('/admin/?kind=account&notice='.CGI::escape($why).'#two-step');
            }
        }
        return 1 if !$owner || is_owner();
        owner_only_page();return 0;
    }
    unless (session_mode()) {header(403,'text/plain; charset=UTF-8');print 'Forbidden';return 0}
    if (($ENV{HTTP_X_REQUESTED_WITH}//'') eq 'fetch' || $method ne 'GET') {
        json_response({ok=>JSON::PP::false,message=>'You’ve been signed out. Sign in again (in another tab, so your work here isn’t lost), then try again.',signed_out=>JSON::PP::true},401) if ($ENV{HTTP_X_REQUESTED_WITH}//'') eq 'fetch';
        header(401,'text/plain; charset=UTF-8');print 'Signed out. Reload the page to sign in again.';return 0;
    }
    my $here=($ENV{DOCUMENT_URI}//'/admin/').(length($ENV{QUERY_STRING}//'') ? '?'.$ENV{QUERY_STRING} : '');
    if ($login_here) {login_page('',$here);return 0}
    redirect('/admin/?kind=login&next='.CGI::escape($here));
}
# The admin service's form key, for the sign-out button on screens run by
# other services (they have their own keys): the bf_csrf cookie's value.
sub admin_csrf_token {
    my $t=$q ? ($q->cookie('bf_csrf')//'') : '';
    return $t =~ /\A[a-f0-9]{32}\.\d+\.[a-f0-9]{64}\z/ ? $t : '';
}
# Where to go after signing in, but only an address inside /admin/ (and not
# the login or logout itself), so a link can't send someone off-site after
# they sign in.
sub safe_next ($next) { return ($next//'') =~ m{\A/admin(?:/[A-Za-z0-9/._-]*)?(?:\?[A-Za-z0-9=&%._+-]*)?\z} && $next !~ /\?.*kind=log(?:in|out)/ ? $next : '/admin/' }

# ---- Lockout ----------------------------------------------------------------------
# Failed sign-ins are kept for an hour in the admin's folder. Five from one
# address within 15 minutes lock that address for 15 minutes; 30 from
# anywhere within an hour lock all sign-ins for 15 minutes (lift with
# blowfishctl unlock).
sub login_attempts_file { return "$data/admin/logins.json" }
# Reads the failed sign-ins file under a lock, drops entries older than an
# hour, runs $code with it, then writes it back. The lock (flock) makes
# simultaneous sign-ins take turns, so none is lost.
sub with_attempts ($code) {
    my $file=login_attempts_file();
    open my $fh,'+>>',$file or die "Sign-in records can't be written.\n";
    flock($fh,LOCK_EX) or die "Sign-in records are busy.\n";
    seek($fh,0,0);my $raw=do {local $/;<$fh>};
    my $s=(length $raw ? (attempt {JSON::PP->new->decode($raw)}) : undef) // {};
    $s->{fails}=[grep {ref eq 'HASH' && $_->{at}>time-3600} @{$s->{fails}//[]}];
    my @r=$code->($s);
    seek($fh,0,0);truncate($fh,0);print {$fh} JSON::PP->new->encode($s);close $fh;
    return wantarray ? @r : $r[0];
}
# A failed sign-in's address, hashed: enough to count failures per address
# without storing it.
sub login_visitor { return sha256_hex('login|'.($ENV{REMOTE_ADDR}//'')) }
# Seconds until sign-in is allowed again from this address (0: allowed now).
# How long this address must wait: 15 minutes after its 5th failure within
# 15 minutes, or for everyone after 30 failures within an hour.
sub login_wait ($s) {
    my $me=login_visitor();my @mine=grep {$_->{who} eq $me && $_->{at}>time-900} @{$s->{fails}};
    my $wait=0;
    if (@mine>=5) {my $w=$mine[-5]{at}+900-time;$wait=$w if $w>$wait}
    my @all=@{$s->{fails}};
    if (@all>=30) {my $w=$all[-30]{at}+900-time;$wait=$w if $w>$wait}
    return $wait>0 ? $wait : 0;
}
# Whether a name and password match (check_password, Users.pm).
sub password_ok ($user,$password) {
    die "No admin password is set yet. On the server, run: doas blowfishctl password\n" unless users_table();
    return check_password($user,$password) ? 1 : 0;
}
# A new signed session cookie for a user: 12 hours, the user's current
# session generation, a random nonce, and the signature. Path=/admin/ keeps
# it away from public pages; Secure, HttpOnly and SameSite=Strict keep it on
# HTTPS, away from scripts and away from other sites' requests.
sub new_session_cookie ($user) {
    my $expires=time+$session_hours*3600;my $nonce=random_id();
    my $row=admin_user_row($user);my $gen=$row ? $row->{session_gen}//1 : 1;
    my $value="$user.$gen.$expires.$nonce";
    return 'bf_session='.$value.'.'.hmac_sha256_hex($value,session_key()).'; Path=/admin/; Max-Age='.($session_hours*3600).'; Secure; HttpOnly; SameSite=Strict';
}

# ---- The login page and sign-out (kind=login, kind=logout) -------------------------
# The sign-in page (a page of its own, without the admin's frame).
sub login_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">Sign in to manage the site.</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',next=>$next)
        .'<label>Name<input name="user" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="32" required autofocus></label>'
        .'<label>Password<input name="password" type="password" autocomplete="current-password" maxlength="200" required></label>'
        .'<button class="buttonlike is-primary" type="submit">sign in</button></form>'
        .'<p class="login-foot"><a href="/">← back to the site</a></p></main></body></html>';
}
# kind=login. A GET shows the page (or goes straight on if already signed
# in). A POST is either the password step or the two-step code step:
#   password  refused while locked out; if right, users with two-step
#             sign-in get a short-lived "password was right" cookie and the
#             code page, everyone else a session
#   code      checks the code for the user the short-lived cookie names
# A wrong password or code is recorded, and the answer waits a second, to
# slow down guessing.
sub login_admin {
    my $next=safe_next(param('next',300));
    if ($method ne 'POST') {
        redirect($next) if length signed_in_admin();
        login_page('',$next);return;
    }
    my $wait=with_attempts(sub ($s) {login_wait($s)});
    my $too_many='Too many failed sign-ins. Try again in '.(int($wait/60)+1).' minutes.';
    # The second step: the code from the app, after the right password.
    if (param('step',10) eq 'code') {
        my $user=mfa_pending_user();
        unless (length $user) {login_page('That took too long. Sign in again.',$next);return}
        if ($wait) {mfa_page($too_many,$next);return}
        if (my $ok=mfa_check($user,param('code',14))) {
            $cookie_header=new_session_cookie($user);
            attempt {$db->do('UPDATE admin_users SET last_sign_in=? WHERE name=?',undef,now(),$user) if users_table()};
            redirect(after_sign_in($next,$user));
        }
        with_attempts(sub ($s) {push @{$s->{fails}},{who=>login_visitor(),at=>time};1});
        sleep 1;
        mfa_page('That code isn’t right. Codes change every 30 seconds; use the one showing now.',$next);return;
    }
    my ($user,$password)=(param('user',32),scalar($q->param('password'))//'');
    die "Password too long.\n" if length($password)>200;
    if ($wait) {login_page($too_many,$next);return}
    if (password_ok($user,$password)) {
        if (mfa_enabled($user)) {$cookie_header=mfa_pending_cookie($user);mfa_page('',$next);return}
        $cookie_header=new_session_cookie($user);
        attempt {$db->do('UPDATE admin_users SET last_sign_in=? WHERE name=?',undef,now(),$user) if users_table()};
        # (One cookie per response: the CSRF cookie is set again on the next page.)
        redirect(after_sign_in($next,$user));
    }
    with_attempts(sub ($s) {push @{$s->{fails}},{who=>login_visitor(),at=>time};1});
    sleep 1;
    login_page('That name and password don’t match.',$next);
}
# kind=logout (a POST from the sign-out button): clears the session cookie;
# with "everywhere", ends this user's sessions in every browser.
sub logout_admin {
    die "Sign out with the button.\n" unless $method eq 'POST';
    $cookie_header='bf_session=; Path=/admin/; Max-Age=0; Secure; HttpOnly; SameSite=Strict';
    # Every session this user started so far ends, in every browser.
    $db->do('UPDATE admin_users SET session_gen=session_gen+1 WHERE name=?',undef,signed_in_admin()) if param('everywhere',1) eq '1';
    redirect('/admin/?kind=login');
}

1;