BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
336 lines · 25.5 KB · download this file
package BlowfishCMS;
# Admin users. Each has a name, a role, an email address and a bcrypt
# password. The name, role, session generation and two-step flag are in the
# catalogue (admin_users), which every service with admin screens reads to
# check a session. The password hash and email address are in the admin
# service's own folder (admin/accounts.sqlite, 0600), which no other service
# can read:
#
# owner everything: settings, themes, search, mail, add-ons, users,
# updates and backups
# editor the content: pages, pictures, music, videos, articles, links and
# comments
#
# The first owner is the admin account the site was installed with (made by
# `blowfishctl install`, which sets its password). `blowfishctl password NAME` sets
# any user's password from the server, and makes an owner of a name that
# doesn't exist yet, so a site can't be locked out for good.
#
# Sessions are signed cookies (Auth.pm) that carry the user's session
# generation: changing a password, removing someone or "sign out everywhere"
# moves it on, which ends every older session at once, in every service.
use v5.36;
use utf8;
use Encode qw(encode);
use JSON::PP ();
our ($base,$data,$db,$q,$method,$csrf,$cookie_header,%instance);
# The two roles, with how the Users screen describes them.
sub user_roles { return ([owner=>'Owner: everything, including settings, users, updates and backups'],[editor=>'Editor: pages, pictures, music, videos, articles, links and comments']) }
# A login name: starts with a lowercase letter or _, then up to 31 lowercase
# letters, digits, dots, dashes or underscores.
sub name_ok ($name) { return defined $name && $name =~ /\A[a-z_][a-z0-9_.-]{0,31}\z/ }
# An optional email address ('' is fine).
sub email_ok ($email) { return $email eq '' || $email =~ /\A[^\s\@<>"]{1,64}\@[A-Za-z0-9.-]{1,190}\.[A-Za-z]{2,}\z/ }
# The admin_users table (in the catalogue, readable by every service): name,
# role, session generation, last sign-in and whether two-step sign-in is on.
# On every migration the two-step flag is set again from the real keys in the
# admin's folder, so it can never claim two-step for someone whose key is gone.
sub ensure_user_tables {
$db->do("CREATE TABLE IF NOT EXISTS admin_users (name TEXT PRIMARY KEY, email TEXT NOT NULL DEFAULT '', role TEXT NOT NULL, hash TEXT NOT NULL, created_at TEXT NOT NULL, session_gen INTEGER NOT NULL DEFAULT 1, last_sign_in TEXT, mfa INTEGER NOT NULL DEFAULT 0)");
# Whether each user has two-step sign-in on, where every service can see it. It
# follows the keys in the admin's own folder, which backups leave out, so after
# a restore nobody is asked for a code they can't give.
$db->do('UPDATE admin_users SET mfa=? WHERE name=?',undef,mfa_enabled($_) ? 1 : 0,$_) for map {$_->[0]} @{$db->selectall_arrayref('SELECT name FROM admin_users')};
}
# The admin service's own store of password hashes and email addresses.
# undef where it can't be opened (any other service).
sub accounts_file { return "$data/admin/accounts.sqlite" }
# The admin service's private store of password hashes and email addresses
# (admin/accounts.sqlite, 0600). Opened once per worker and reused while the
# connection works (`state` keeps it). undef in any other service, which
# can't write to the admin's folder.
sub accounts_db {
state %open;my $file=accounts_file();
return $open{$file} if $open{$file} && $open{$file}->ping;
return undef unless -d "$data/admin" && -w "$data/admin";
my $a=attempt {
my $old=umask 0077;
my $h=DBI->connect("dbi:SQLite:dbname=$file",'','',{RaiseError=>1,PrintError=>0,AutoCommit=>1,sqlite_unicode=>1});
umask $old;chmod 0600,$file;
$h->do('PRAGMA busy_timeout=5000');
$h->do("CREATE TABLE IF NOT EXISTS accounts (name TEXT PRIMARY KEY, hash TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '')");
$h;
} or return undef;
return $open{$file}=$a;
}
# A user's row in the private store.
sub account_row ($name) { my $a=accounts_db() or return undef;return $a->selectrow_hashref('SELECT * FROM accounts WHERE name=?',undef,$name) }
# A user's password hash and email, from the admin's own store. (The catalogue's
# admin_users.hash and email columns are always empty; new rows give them ''.
# They stay so the release before can still be rolled back to.)
sub account_hash ($name) { my $a=account_row($name);return $a ? $a->{hash} : '' }
sub account_email ($name) { my $a=account_row($name);return $a ? $a->{email} : '' }
# Adds a user: the name and role go in the catalogue, the hash and email in
# the private store.
sub account_add ($name,$role,$hash,$email) {
my $a=accounts_db() or die "Users can only be added by the admin service.\n";
$db->do("INSERT INTO admin_users (name,email,role,hash,created_at) VALUES (?,'',?,'',?)",undef,$name,$role,now());
$a->do('INSERT OR REPLACE INTO accounts (name,hash,email) VALUES (?,?,?)',undef,$name,$hash,$email);
}
# Sets a user's password hash, and moves their session generation on, which
# signs them out everywhere.
sub account_set_hash ($name,$hash) {
my $a=accounts_db() or die "Passwords can only be set by the admin service.\n";
$a->do('INSERT OR IGNORE INTO accounts (name) VALUES (?)',undef,$name);
$a->do('UPDATE accounts SET hash=? WHERE name=?',undef,$hash,$name);
$db->do('UPDATE admin_users SET session_gen=session_gen+1 WHERE name=?',undef,$name);
}
# Sets a user's email address in the private store.
sub account_set_email ($name,$email) {
my $a=accounts_db() or die "Email addresses can only be changed by the admin service.\n";
$a->do('INSERT OR IGNORE INTO accounts (name) VALUES (?)',undef,$name);
$a->do('UPDATE accounts SET email=? WHERE name=?',undef,$email,$name);
}
# Removes a user from both stores.
sub account_remove ($name) {
$db->do('DELETE FROM admin_users WHERE name=?',undef,$name);
if (my $a=accounts_db()) {$a->do('DELETE FROM accounts WHERE name=?',undef,$name)}
}
# The catalogue for looking users up, from any service with admin screens.
# The catalogue, for looking users up (opening it if this request hasn't).
sub users_db { $db //= attempt {database()}; return $db }
# How many admin users there are (0 if the table can't be read).
sub users_table { my $d=users_db() or return 0; return (attempt {$d->selectrow_array("SELECT count(*) FROM admin_users")}) // 0 }
# One user's catalogue row by name, or undef.
sub admin_user_row ($name) {
return undef unless name_ok($name//'');
return users_table() ? users_db()->selectrow_hashref('SELECT * FROM admin_users WHERE name=?',undef,$name) : undef;
}
# Every user, owners first, then by name.
sub all_admin_users { return users_table() ? users_db()->selectall_arrayref("SELECT * FROM admin_users ORDER BY role='owner' DESC, name",{Slice=>{}}) : [] }
# How many owners there are (there must always be one).
sub owner_count { return users_db()->selectrow_array("SELECT count(*) FROM admin_users WHERE role='owner'") }
# bcrypt, as htpasswd(1) writes it.
# Makes a bcrypt hash of a password, as htpasswd does: 12-200 characters,
# cost 10 (2^10 rounds, slow on purpose so guessing is slow), and a random
# 22-character salt in bcrypt's own alphabet. The last salt character only
# carries 2 bits, so it must be one of four characters bcrypt accepts. The
# operating system's crypt() does the work; OpenBSD's knows bcrypt.
sub hash_password ($password) {
die "Use a password of at least 12 characters.\n" if length($password)<12;
die "Passwords can be up to 200 characters.\n" if length($password)>200;
my @abc=('.','/','A'..'Z','a'..'z','0'..'9');
open my $r,'<:raw','/dev/urandom' or die "No randomness available.\n";read($r,my $bytes,22);close $r;
my $salt=join '',map {$abc[ord($_) % 64]} split //,$bytes;
# The last salt character only carries two bits: keep it to the ones bcrypt accepts.
substr($salt,21,1)=('.','O','e','u')[ord(substr($bytes,21,1)) % 4];
my $hash=crypt(encode('UTF-8',$password),'$2b$10$'.$salt)//'';
die "This server can't make bcrypt passwords.\n" unless $hash =~ /\A\$2b\$10\$[.\/A-Za-z0-9]{53}\z/;
return $hash;
}
# Whether a password is right: crypt() hashes it with the stored hash's salt
# and the result must equal the stored hash. For an unknown name it hashes
# against a made-up hash anyway, so the answer takes as long either way and
# doesn't reveal which names exist. Returns the user's row, or undef.
sub check_password ($user,$password) {
my $row=admin_user_row($user);my $hash=$row ? account_hash($user) : '';
# A made-up hash keeps the timing the same for unknown names.
my $got=crypt(encode('UTF-8',$password),length $hash ? $hash : '$2b$10$'.('a' x 53))//'';
return length $hash && eq_safe($got,$hash) ? $row : undef;
}
# The signed-in user's role ('owner' or 'editor'), or '' when nobody is signed in.
# The signed-in user's role, or ''.
sub admin_role { my $u=signed_in_admin(); return '' unless length $u; my $row=admin_user_row($u); return $row ? $row->{role} : '' }
# Whether the signed-in user is an owner.
sub is_owner { return admin_role() eq 'owner' }
# Sections only owners may open.
sub owner_kinds { return qw(settings branding search addons themes users signin system setup notices) }
# The page an editor sees when they open an owners-only screen.
sub owner_only_page ($what='This part of the admin') {
admin_page('Owners only',section=>'',status=>403);
window('owners only','<p>'.h($what).' is for the site’s owners. Ask an owner if you need something changed here.</p>');
end_page();
}
# ---- The Users screen (owners) and Your account (everyone) ----------------------------
# Settings › Users (owners): the list of users and its actions: user_add,
# user_role (the last owner can't stop being one), user_password (signs
# them out everywhere), user_mfa_off (for someone who lost their phone) and
# user_remove (not yourself, not the last owner). The hidden username field
# in the password forms helps password managers know whose password it is.
sub users_admin {
my $message=param('notice',2000);my $me=signed_in_admin();
if ($method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'user_add') {
my ($name,$email,$role)=(lc param('name',32),param('email',254),param('role',10));
die "Names are 1–32 lowercase letters, numbers, dots, dashes or underscores, starting with a letter.\n" unless name_ok($name);
die "There's already a user called $name.\n" if admin_user_row($name);
die "That email address doesn't look right.\n" unless email_ok($email);
die "Choose a role.\n" unless grep {$_->[0] eq $role} user_roles();
my ($p1,$p2)=(scalar($q->param('password'))//'',scalar($q->param('password2'))//'');
die "The two passwords don't match.\n" unless $p1 eq $p2;
account_add($name,$role,hash_password($p1),$email);
redirect('/admin/?kind=users¬ice='.CGI::escape("Added $name. Give them their password in person or by another channel, not by email."));
}
my $name=param('name',32);my $row=admin_user_row($name) or die "That user no longer exists.\n";
if ($action eq 'user_role') {
my $role=param('role',10);die "Choose a role.\n" unless grep {$_->[0] eq $role} user_roles();
die "The site needs at least one owner.\n" if $row->{role} eq 'owner' && $role ne 'owner' && owner_count()<=1;
$db->do('UPDATE admin_users SET role=? WHERE name=?',undef,$role,$name);
redirect('/admin/?kind=users¬ice='.CGI::escape("$name is now ".($role eq 'owner' ? 'an owner' : 'an editor').'.'));
}
if ($action eq 'user_password') {
my ($p1,$p2)=(scalar($q->param('password'))//'',scalar($q->param('password2'))//'');
die "The two passwords don't match.\n" unless $p1 eq $p2;
account_set_hash($name,hash_password($p1));
redirect('/admin/?kind=users¬ice='.CGI::escape("New password set for $name; they've been signed out everywhere."));
}
if ($action eq 'user_mfa_off') {
die "Turn your own off under Your account.\n" if $name eq $me;
mfa_remove($name);
redirect('/admin/?kind=users¬ice='.CGI::escape("Two-step sign-in is off for $name. They sign in with their password and can set it up again."));
}
if ($action eq 'user_remove') {
die "The site needs at least one owner.\n" if $row->{role} eq 'owner' && owner_count()<=1;
die "You can't remove yourself. Ask another owner.\n" if $name eq $me;
account_remove($name);mfa_remove($name);
redirect('/admin/?kind=users¬ice='.CGI::escape("Removed $name."));
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
admin_page('Users',section=>'users',notice=>$message,intro=>'Who can sign in to the admin. Owners can do everything; editors look after the content.');
my @rows;
for my $u (@{all_admin_users()}) {
my $n=h($u->{name});my $self=$u->{name} eq $me;
# In view: the role and a new password; turning off two-step sign-in and removing them in "…".
push @rows,admin_row(title_html=>$n.($self ? ' <span class="media-label">(you)</span>' : ''),menu_for=>$u->{name},
meta=>[$u->{role} eq 'owner' ? 'owner' : 'editor',length(account_email($u->{name})) ? h(account_email($u->{name})) : 'no email address',$u->{last_sign_in} ? 'last signed in '.h(substr($u->{last_sign_in},0,10)) : 'never signed in',mfa_enabled($u->{name}) ? 'two-step on' : 'two-step off'],
actions=>'<form method="post" action="/admin/" class="inline-form" data-auto-submit>'.fields('user_role','users').hidden(name=>$u->{name}).'<label class="visually-hidden" for="role-'.$n.'">Role for '.$n.'</label><select id="role-'.$n.'" name="role">'
.join('',map {'<option value="'.$_->[0].'"'.($_->[0] eq $u->{role} ? ' selected' : '').'>'.$_->[0].'</option>'} user_roles()).'</select><button class="buttonlike no-js-only" type="submit">set role</button></form>'
.'<details class="user-password"><summary class="buttonlike">set password</summary><form method="post" action="/admin/" class="admin-form">'.fields('user_password','users').hidden(name=>$u->{name})
.'<input type="text" name="username" value="'.$n.'" autocomplete="username" hidden><label>New password<input type="password" name="password" minlength="12" maxlength="200" autocomplete="new-password" required></label><label>Again<input type="password" name="password2" minlength="12" maxlength="200" autocomplete="new-password" required></label><button class="buttonlike" type="submit">save</button></form></details>',
menu=>(!$self && mfa_enabled($u->{name}) ? '<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Turn off two-step sign-in for $u->{name}? Do this if they've lost their phone and recovery codes.").'">'.fields('user_mfa_off','users').hidden(name=>$u->{name}).'<button class="text-button" type="submit">turn off two-step</button></form>' : '')
.($self ? '' : '<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Remove $u->{name}? They'll be signed out and can't sign in again.").'">'.fields('user_remove','users').hidden(name=>$u->{name}).'<button class="text-button danger" type="submit">remove</button></form>'));
}
window('users',admin_list(\@rows).'<div class="box-part" id="add-user"><h3>Add a user</h3>'.('<form method="post" action="/admin/" class="admin-form" data-warn-unsaved>'.fields('user_add','users')
.'<div class="theme-editor__grid"><label>Name<input name="name" maxlength="32" pattern="[a-z_][a-z0-9_.\-]*" autocomplete="off" autocapitalize="none" required><span class="optional">what they type to sign in</span></label>'
.'<label>Email<input type="email" name="email" maxlength="254" autocomplete="off"></label>'
.'<label>Role<select name="role">'.join('',map {'<option value="'.$_->[0].'"'.($_->[0] eq 'editor' ? ' selected' : '').'>'.h($_->[1]).'</option>'} user_roles()).'</select></label></div>'
.'<div class="theme-editor__grid"><label>Password<input type="password" name="password" minlength="12" maxlength="200" autocomplete="new-password" required><span class="optional">at least 12 characters</span></label><label>Again<input type="password" name="password2" minlength="12" maxlength="200" autocomplete="new-password" required></label></div>'
.'<button class="buttonlike is-primary" type="submit">add user</button></form>').'</div>');
end_page();
}
# ---- The Sign-in screen (owners): rules for the whole site --------------------------------
# Settings › Sign-in (owners): the rules for the whole site:
# signin_mfa_rule who must use two-step sign-in (none, owners, everyone)
# signin_unlock clear the failed sign-ins (end a lockout)
# signin_everyone_out end every session, giving this browser a new one
# It also shows the last hour's failed sign-ins and any lockout.
sub signin_admin {
my $message=param('notice',2000);my $me=signed_in_admin();
if ($method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'signin_mfa_rule') {
my $rule=param('mfa_required',10);
die "Choose who must use two-step sign-in.\n" unless $rule =~ /\A(?:none|owners|everyone)\z/;
setting_save(mfa_required=>$rule);
my @left=grep {mfa_required_for($_) && !$_->{mfa}} @{all_admin_users()};
redirect('/admin/?kind=signin¬ice='.CGI::escape($rule eq 'none' ? 'Two-step sign-in is up to each user.'
: 'Saved. '.(@left ? join(', ',map {$_->{name}} @left).(@left==1 ? ' has' : ' have').' to set it up before using the admin again.' : 'Everyone it applies to already uses it.')).'#two-step-rule');
}
if ($action eq 'signin_unlock') {
with_attempts(sub ($s) {$s->{fails}=[];1});
redirect('/admin/?kind=signin¬ice='.CGI::escape('Failed sign-ins cleared: anyone locked out can sign in again.').'#lockout');
}
if ($action eq 'signin_everyone_out') {
# Every session ends; this browser gets a fresh one so the owner stays in.
$db->do('UPDATE admin_users SET session_gen=session_gen+1');
$cookie_header=new_session_cookie($me);
redirect('/admin/?kind=signin¬ice='.CGI::escape('Everyone has been signed out, apart from you in this browser.').'#sessions');
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
admin_page('Sign-in',section=>'signin',notice=>$message,intro=>'How people sign in to the admin. Each person’s own password and two-step sign-in are under <a href="/admin/?kind=account">your account</a>.');
my $rule=setting('mfa_required');
window('two-step sign-in','<form method="post" action="/admin/" class="admin-form" id="two-step-rule">'.fields('signin_mfa_rule','signin')
.'<p>Who must use two-step sign-in (a code from an authenticator app as well as the password). Anyone who must but hasn’t set it up is sent to set it up when they next open the admin, and can’t use anything else until they have.</p>'
.'<div class="setup-checks">'.join('',map {'<label class="checkline"><input type="radio" name="mfa_required" value="'.$_->[0].'"'.($rule eq $_->[0] ? ' checked' : '').'> '.h($_->[1]).'</label>'}
[none=>'Nobody: each user decides'],[owners=>'Owners (recommended: owners can update the server)'],[everyone=>'Everyone']).'</div>'
.'<button class="buttonlike" type="submit">save</button></form>');
# Failed sign-ins of the last hour; five from one place in 15 minutes lock that place, 30 in all lock everyone.
my ($fails,$places,$locked,$all)=with_attempts(sub ($s) {
my @f=@{$s->{fails}};my %by;push @{$by{$_->{who}}},$_ for @f;
my $locked=grep {my @r=grep {$_->{at}>time-900} @$_;@r>=5} values %by;
return (scalar @f,scalar keys %by,$locked,@f>=30 && $f[-30]{at}+900>time);
});
my $state=$all ? '<p class="admin-notice is-error">Sign-in is locked for everyone: there were 30 failed sign-ins in the last hour. It opens again by itself within 15 minutes.</p>'
: $locked ? '<p class="admin-notice is-error">'.$locked.' '.($locked==1 ? 'place is' : 'places are').' locked out for up to 15 minutes after five wrong passwords.</p>' : '';
window('lockout','<div id="lockout">'.$state.'<p>Five wrong passwords (or two-step codes) from one place within 15 minutes lock that place for 15 minutes; 30 from anywhere within an hour lock all sign-ins for 15 minutes. In the last hour: <strong>'.$fails.'</strong> failed '.($fails==1 ? 'sign-in' : 'sign-ins').($fails ? ' from '.$places.' '.($places==1 ? 'place' : 'places') : '').'.</p>'
.'<form method="post" action="/admin/" class="admin-form">'.fields('signin_unlock','signin').'<button class="buttonlike" type="submit"'.($fails ? '' : ' disabled').'>unlock: clear failed sign-ins</button></form>'
.'<p class="optional">On the server, <code>doas blowfishctl unlock</code> does the same.</p></div>');
window('sessions','<div id="sessions"><p>Signing in lasts 12 hours. A new password or removing someone signs them out everywhere; this signs everyone out at once, apart from you in this browser (after a lost laptop, say).</p>'
.'<form method="post" action="/admin/" class="delete-form" data-confirm="Sign everyone out of the admin, apart from you in this browser?">'.fields('signin_everyone_out','signin').'<button class="buttonlike" type="submit">sign everyone out</button></form></div>');
end_page();
}
# Your account (everyone): change your email or password (which needs your
# current password and signs you out elsewhere), and set up or change
# two-step sign-in (Mfa.pm).
sub account_admin {
my $message=param('notice',2000);my $me=signed_in_admin();my $row=admin_user_row($me);
if ($method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'account_email') {
my $email=param('email',254);die "That email address doesn't look right.\n" unless email_ok($email);
account_set_email($me,$email);
redirect('/admin/?kind=account¬ice=Email%20address%20saved.');
}
if ($action eq 'account_password') {
check_password($me,scalar($q->param('current'))//'') or die "Your current password isn't right.\n";
my ($p1,$p2)=(scalar($q->param('password'))//'',scalar($q->param('password2'))//'');
die "The two new passwords don't match.\n" unless $p1 eq $p2;
account_set_hash($me,hash_password($p1));
# This browser stays signed in with a fresh session; every other one is signed out.
$cookie_header=new_session_cookie($me);
redirect('/admin/?kind=account¬ice='.CGI::escape('Password changed. You’ve been signed out everywhere else.'));
}
finish() if mfa_account_action($action,$me);
die "Choose an action.\n";
} or $message=failed_action($@);
}
admin_page('Your account',section=>'account',notice=>$message,intro=>'Signed in as <strong>'.h($me).'</strong>, '.($row && $row->{role} eq 'owner' ? 'an owner' : 'an editor').'.');
window('sign-in',('<form method="post" action="/admin/" class="admin-form">'.fields('account_email','account').'<label>Email<input type="email" name="email" maxlength="254" value="'.h(account_email($me)).'"></label><button class="buttonlike" type="submit">save</button></form>').'<div class="box-part"><h3>Password</h3>'.('<form method="post" action="/admin/" class="admin-form">'.fields('account_password','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>'
.'<div class="theme-editor__grid"><label>New password<input type="password" name="password" minlength="12" maxlength="200" autocomplete="new-password" required><span class="optional">at least 12 characters</span></label><label>Again<input type="password" name="password2" minlength="12" maxlength="200" autocomplete="new-password" required></label></div>'
.'<button class="buttonlike" type="submit">change password</button></form><p class="optional">Changing it signs you out in every other browser.</p>').'</div>');
window('two-step sign-in',mfa_account_window($me));
end_page();
}
# site.pl --set-password NAME: the bcrypt hash on standard input (blowfishctl
# password). Makes an owner of a name that doesn't exist yet.
# site.pl --set-password NAME, run by `blowfishctl password`: reads a bcrypt
# hash (made by htpasswd on the server, so the password itself never reaches
# this program) from standard input and sets it, adding NAME as an owner if
# it's new. This is how a site that has lost every password gets back in.
sub set_password_cli ($name) {
die "Names are 1–32 lowercase letters, numbers, dots, dashes or underscores.\n" unless name_ok($name);
my $hash=<STDIN>//'';$hash =~ s/\s+\z//;
die "Expected a bcrypt hash on standard input.\n" unless $hash =~ /\A\$2[aby]\$\d\d\$[.\/A-Za-z0-9]{53}\z/;
$db=database(1);ensure_user_tables();
if ($db->selectrow_array('SELECT count(*) FROM admin_users WHERE name=?',undef,$name)) {
account_set_hash($name,$hash);
return "Password set for $name; their sessions have ended.";
}
account_add($name,'owner',$hash,'');
return "Added $name as an owner.";
}
1;