BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
181 lines · 16.1 KB · download this file
#!/usr/bin/env python3
"""Two-step sign-in: setting it up with a QR code and key, the code step at
sign-in, codes used once, recovery codes, the lockout, owners turning it off
for someone who lost their phone, `site.pl --mfa-off`, and the keys kept out
of the catalogue. Uses a fresh catalogue; never touches live data."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,time,hmac,hashlib,base64,struct,stat
import html as H
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent));import signin # signs requests in (REMOTE_USER → session cookie)
script=str(pathlib.Path(sys.argv[1]).resolve())
checks=[]
def check(v,msg):
assert v,msg
checks.append(msg);print('PASS',msg,flush=True)
def bcrypt(pw):return subprocess.run(['perl','-e','print crypt($ARGV[0],"\\$2b\\$10\\$".join("",map {("a".."z")[rand 26]} 1..22))',pw],capture_output=True,text=True).stdout
with tempfile.TemporaryDirectory(prefix='blowfish-mfa-test-') as tmp:
root=pathlib.Path(tmp)
conf=root/'etc/blowfishcms.conf';conf.parent.mkdir(parents=True)
conf.write_text('domain = example.org\nadmin_user = alice\ndata = /var/db/bf\nmedia = /media/bf\ncomments = /var/db/bf-comments\ncontact = /var/db/bf-contact\nsecrets = /etc/bf\n')
data=root/'var/db/bf';(data/'admin/tmp').mkdir(parents=True)
(data/'admin/csrf.key').write_text(secrets.token_hex(32))
for kind in ['photography','music','artwork','blog','video']:(root/'media/bf'/kind).mkdir(parents=True)
(root/'var/db/bf-contact').mkdir(parents=True);(root/'var/db/bf-comments').mkdir(parents=True)
sk=root/'etc/blowfishcms-session';sk.mkdir(parents=True);(sk/'session.key').write_text(secrets.token_hex(32)+'\n')
env={**os.environ,'BLOWFISH_ROOT':str(root)}
for k in ['BLOWFISH_PAGES_SEED','BLOWFISH_ADDONS_PATH']:env.pop(k,None)
subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
subprocess.run(['perl',script,'--set-password','alice'],input=bcrypt('alice password one'),env=env,check=True,capture_output=True,text=True) # the first owner, as blowfishctl install makes it
subprocess.run(['perl',script,'--comments-init'],env=env,check=True,capture_output=True)
db=data/'catalog.sqlite'
def sql(q,a=()):
with signin.connect(db) as c:return c.execute(q,a).fetchall()
def run(path,fields=None,cookie='',fetch=False,script_name=None,ip='192.0.2.7'):
url=urllib.parse.urlsplit(path);body=urllib.parse.urlencode(fields or {}).encode() if fields is not None else b''
e={**env,'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'POST' if fields is not None else 'GET','SCRIPT_NAME':script_name or url.path,'DOCUMENT_URI':url.path,'QUERY_STRING':url.query,
'CONTENT_TYPE':'application/x-www-form-urlencoded','CONTENT_LENGTH':str(len(body)),'REMOTE_USER':'','HTTP_ORIGIN':'https://example.org','HTTP_COOKIE':cookie,'REMOTE_ADDR':ip,**({'HTTP_X_REQUESTED_WITH':'fetch'} if fetch else {})}
p=subprocess.run(['perl',script],input=body,env=signin.sign(e),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
assert p.returncode==0,(p.stderr.decode(),p.stdout[:300])
head,html=p.stdout.decode().split('\r\n\r\n',1);hdr={}
for line in head.split('\r\n'):k,v=line.split(': ',1);hdr[k]=v
return int(hdr['Status']),html,hdr
def cookie_of(hdr,name):
m=re.match(name+r'=([^;]*)',hdr.get('Set-Cookie',''));return m.group(1) if m else None
csrf=cookie_of(run('/admin/?kind=login')[2],'bf_csrf')
def sign_in(user,password,ip='192.0.2.7'):
status,_,hdr=run('/admin/',{'csrf':csrf,'kind':'login','user':user,'password':password,'next':'/admin/'},cookie='bf_csrf='+csrf,ip=ip)
s=cookie_of(hdr,'bf_session');return f'bf_csrf={csrf}; bf_session={s}' if status==303 and s else None
def act(ck,kind,fields,**o):
import html as H
status,body,hdr=run('/admin/',{'csrf':csrf,'kind':kind,**fields},cookie=ck,**o);return status,H.unescape(body),hdr
def signed_in(ck):
status,html,_=run('/admin/',cookie=ck);return status==200 and 'name="password"' not in html and '<h1>Overview</h1>' in html
sql("update site_settings set value='done' where key='setup'")
def totp(key,offset=0):
k=base64.b32decode(key.replace(' ','')+'='*((8-len(key.replace(' ',''))%8)%8));step=int(time.time()//30)+offset
mac=hmac.new(k,struct.pack('>Q',step),hashlib.sha1).digest();o=mac[-1]&15
return '%06d'%((struct.unpack('>I',mac[o:o+4])[0]&0x7fffffff)%1000000)
mfa=data/'admin/mfa'
def allow_codes(user):
# Lets a test use the current code again, where reuse isn't what it's testing.
f=mfa/f'{user}.json';d=json.loads(f.read_text());d['last_step']=0;f.write_text(json.dumps(d))
def password_step(user,password,ip):
status,html,hdr=run('/admin/',{'csrf':csrf,'kind':'login','user':user,'password':password,'next':'/admin/'},cookie='bf_csrf='+csrf,ip=ip)
return status,H.unescape(html),cookie_of(hdr,'bf_mfa'),hdr
def code_step(pending,code,ip):
status,html,hdr=run('/admin/',{'csrf':csrf,'kind':'login','step':'code','code':code,'next':'/admin/'},cookie=f'bf_csrf={csrf}; bf_mfa={pending}' if pending else 'bf_csrf='+csrf,ip=ip)
s=cookie_of(hdr,'bf_session');return status,H.unescape(html),(f'bf_csrf={csrf}; bf_session={s}' if status==303 and s else None)
alice=sign_in('alice','alice password one')
# ---- Setting it up ------------------------------------------------------------------------
html=H.unescape(run('/admin/?kind=account',cookie=alice)[1])
check('</span>sign-in</div>' in html and 'value="account_email"' in html and 'value="account_password"' in html and '</span>password</div>' not in html,'email and password share the sign-in box')
check('two-step sign-in' in html and 'Off.' in html and 'value="mfa_start"' in html,'Your account offers two-step sign-in, off to begin with')
check('Turn on two-step sign-in' in H.unescape(run('/admin/',cookie=alice)[1]),'the Overview reminds an owner to turn it on')
act(alice,'account',{'action':'mfa_start'})
html=H.unescape(run('/admin/?kind=account',cookie=alice)[1])
key=re.search(r'<code class="mfa-key">([A-Z2-7 ]+)</code>',html).group(1)
check('<svg class="qr-code"' in html and len(key.replace(' ',''))==32,'setting up shows a QR code and the key to type in')
check('That code isn’t right' in act(alice,'account',{'action':'mfa_confirm','code':'000000' if totp(key)!='000000' else '111111'})[1],'a wrong code doesn\'t turn it on')
status,html,_=act(alice,'account',{'action':'mfa_confirm','code':totp(key)})
codes=re.findall(r'<li><code>([a-z2-7]{5}-[a-z2-7]{5})</code></li>',html)
check(status==200 and len(codes)==10 and len(set(codes))==10,'the right code turns it on and shows ten recovery codes, once')
f=mfa/'alice.json'
check(f.exists() and stat.S_IMODE(f.stat().st_mode)==0o600 and key.replace(' ','').encode() not in db.read_bytes(),'the key is kept in the admin\'s own folder (0600), not in the catalogue')
check(not any(c.replace('-','') in f.read_text() for c in codes),'recovery codes are stored hashed')
check('On.' in H.unescape(run('/admin/?kind=account',cookie=alice)[1]) and 'Turn on two-step' not in H.unescape(run('/admin/',cookie=alice)[1]),'the account shows it\'s on, and the reminder goes')
check(signed_in(alice),'turning it on keeps this browser signed in')
# ---- Signing in -----------------------------------------------------------------------------
status,html,pending,hdr=password_step('alice','alice password one','192.0.2.20')
check(status==200 and 'six-digit code' in html and pending and 'bf_session' not in hdr.get('Set-Cookie',''),'after the right password, it asks for the code; there\'s no session yet')
check(password_step('alice','wrong password here','192.0.2.20')[2] is None,'a wrong password never reaches the code step')
check('took too long' in code_step(None,totp(key,1),'192.0.2.20')[1],'the code step needs the password step first')
forged=pending.split('.');forged[0]='bob';check('took too long' in code_step('.'.join(forged),totp(key,1),'192.0.2.20')[1],'the code step\'s cookie can\'t be altered')
status,html,ck=code_step(pending,'123456' if totp(key,1)!='123456' else '654321','192.0.2.20')
check(status==400 and ck is None and 'isn’t right' in html,'a wrong code is refused')
used=totp(key,1) # the same code both times (computing it again could cross into the next 30 seconds)
status,html,ck=code_step(pending,used,'192.0.2.20')
check(ck and signed_in(ck),'the right code signs in')
_,_,again=code_step(password_step('alice','alice password one','192.0.2.21')[2],used,'192.0.2.21')
check(again is None,'a code can\'t be used twice')
allow_codes('alice')
# ---- Recovery codes ------------------------------------------------------------------------------
status,html,ck=code_step(password_step('alice','alice password one','192.0.2.22')[2],codes[0].upper(),'192.0.2.22')
check(ck and signed_in(ck),'a recovery code signs in instead of a code')
_,_,again=code_step(password_step('alice','alice password one','192.0.2.22')[2],codes[0],'192.0.2.22')
check(again is None and '9 recovery codes left' in H.unescape(run('/admin/?kind=account',cookie=alice)[1]),'each recovery code works once')
check('isn’t right' in act(alice,'account',{'action':'mfa_codes','code':codes[1]})[1],'new recovery codes need a code from the app')
status,html,_=act(alice,'account',{'action':'mfa_codes','code':totp(key)})
fresh=re.findall(r'<li><code>([a-z2-7]{5}-[a-z2-7]{5})</code></li>',html)
check(len(fresh)==10 and code_step(password_step('alice','alice password one','192.0.2.23')[2],codes[1],'192.0.2.23')[2] is None,'new recovery codes replace the old ones')
allow_codes('alice')
# ---- The lockout ---------------------------------------------------------------------------------
p=password_step('alice','alice password one','192.0.2.30')[2]
for _ in range(5):code_step(p,'000001','192.0.2.30')
check('Too many failed sign-ins' in code_step(p,totp(key),'192.0.2.30')[1],'wrong codes count towards the lockout, like wrong passwords')
subprocess.run(['rm','-f',str(data/'admin/logins.json')])
# ---- Other users, and getting back in ---------------------------------------------------------------
act(alice,'users',{'action':'user_add','name':'bob','email':'','role':'editor','password':'bob password one','password2':'bob password one'})
bob=sign_in('bob','bob password one')
act(bob,'account',{'action':'mfa_start'})
bkey=re.search(r'<code class="mfa-key">([A-Z2-7 ]+)</code>',H.unescape(run('/admin/?kind=account',cookie=bob)[1])).group(1)
act(bob,'account',{'action':'mfa_confirm','code':totp(bkey)})
check(bkey!=key and sign_in('bob','bob password one') is None,'editors can turn it on too; then the password alone isn\'t enough')
html=H.unescape(run('/admin/?kind=users',cookie=alice)[1])
check(re.search(r'<h2>bob</h2><p class="media-label">editor · [^<]*two-step on',html) and 'value="user_mfa_off"' in html,'Users shows who has it on, and owners can turn it off')
check(act(bob,'users',{'action':'user_mfa_off','name':'alice'})[0]==403,'editors can\'t turn it off for others')
act(alice,'users',{'action':'user_mfa_off','name':'bob'})
check(sign_in('bob','bob password one') and not (mfa/'bob.json').exists(),'an owner turns it off for someone who lost their phone')
act(bob,'account',{'action':'mfa_start'});bkey=re.search(r'<code class="mfa-key">([A-Z2-7 ]+)</code>',H.unescape(run('/admin/?kind=account',cookie=bob)[1])).group(1)
act(bob,'account',{'action':'mfa_confirm','code':totp(bkey)})
out=subprocess.run(['perl',script,'--mfa-off','bob'],env=env,capture_output=True,text=True)
check(out.returncode==0 and 'off for bob' in out.stdout and sign_in('bob','bob password one'),'site.pl --mfa-off (blowfishctl mfa-off) turns it off from the server')
act(bob,'account',{'action':'mfa_start'});bkey=re.search(r'<code class="mfa-key">([A-Z2-7 ]+)</code>',H.unescape(run('/admin/?kind=account',cookie=bob)[1])).group(1)
act(bob,'account',{'action':'mfa_confirm','code':totp(bkey)})
act(alice,'users',{'action':'user_remove','name':'bob'})
check(not (mfa/'bob.json').exists(),'removing a user removes their key')
# ---- Requiring it ------------------------------------------------------------------------------------
flag=lambda u:(sql('select mfa from admin_users where name=?',(u,)) or [[None]])[0][0]
check(flag('alice')==1,'the catalogue notes who has it on, for the other services')
sql("update admin_users set mfa=0 where name='alice'");subprocess.run(['perl',script,'--migrate'],env=env,check=True,capture_output=True)
check(flag('alice')==1,'the migration fills that in from the keys')
html=H.unescape(run('/admin/?kind=signin',cookie=alice)[1])
check(re.search(r'name="mfa_required" value="none" checked',html),'by default nobody is required to use it')
for name,role in [('carol','owner'),('dave','editor')]:
act(alice,'users',{'action':'user_add','name':name,'email':'','role':role,'password':f'{name} password one','password2':f'{name} password one'})
carol=sign_in('carol','carol password one');dave=sign_in('dave','dave password one')
check(run('/admin/',cookie=carol)[0]==200,'while it isn\'t required, a password is enough')
status,html,hdr=act(alice,'signin',{'action':'signin_mfa_rule','mfa_required':'owners'})
check(status==303 and sql("select value from site_settings where key='mfa_required'")==[('owners',)] and 'carol' in urllib.parse.unquote(hdr['Location']) and 'dave' not in urllib.parse.unquote(hdr['Location']),'an owner requires it of owners, and is told who still has to set it up')
status,_,hdr=run('/admin/?kind=pages',cookie=carol)
check(status==303 and hdr['Location'].startswith('/admin/?kind=account') and hdr['Location'].endswith('#two-step'),'an owner without it is sent to set it up')
check(run('/admin/?kind=account',cookie=carol)[0]==200,'their account page still opens, to set it up')
check(run('/admin/',{'csrf':csrf,'kind':'pages','action':'order','order':'home'},cookie=carol)[0]==403 and run('/admin/?kind=pages',cookie=carol,fetch=True)[0]==403,'and nothing else works until they have')
check(run('/admin/mail/',cookie=carol,script_name='/admin/mail/')[0] in (302,303),'the Mail screen (its own service) sends them to set it up too')
check(run('/admin/?kind=pages',cookie=dave)[0]==200 and run('/admin/?kind=pages',cookie=alice)[0]==200,'editors, and owners who have it, carry on')
act(carol,'account',{'action':'mfa_start'})
ckey=re.search(r'<code class="mfa-key">([A-Z2-7 ]+)</code>',H.unescape(run('/admin/?kind=account',cookie=carol)[1])).group(1)
act(carol,'account',{'action':'mfa_confirm','code':totp(ckey)})
check(flag('carol')==1 and run('/admin/?kind=pages',cookie=carol)[0]==200,'once they set it up, the admin opens')
html=H.unescape(run('/admin/?kind=account',cookie=carol)[1])
check('requires two-step sign-in for you' in html and 'value="mfa_off"' not in html,'while it\'s required, it can\'t be turned off from the account page')
check('can’t be turned off' in H.unescape(act(carol,'account',{'action':'mfa_off','current':'carol password one'})[1]) and flag('carol')==1,'nor by sending the form anyway')
out=subprocess.run(['perl',script,'--mfa-off','carol'],env=env,capture_output=True,text=True)
check('set it up again when they next sign in' in out.stdout and flag('carol')==0 and run('/admin/?kind=pages',cookie=carol)[0]==303,'mfa-off from the server says they\'ll be asked to set it up again')
act(alice,'signin',{'action':'signin_mfa_rule','mfa_required':'everyone'})
check(run('/admin/?kind=pages',cookie=dave)[0]==303,'required of everyone, editors are asked too')
check('Choose who must' in H.unescape(act(alice,'signin',{'action':'signin_mfa_rule','mfa_required':'sometimes'})[1]),'only the three choices are taken')
check(act(dave,'users',{'action':'users_mfa_rule','mfa_required':'none'})[0] in (303,403) and sql("select value from site_settings where key='mfa_required'")==[('everyone',)],'editors can\'t change it')
act(alice,'signin',{'action':'signin_mfa_rule','mfa_required':'none'})
for name in ['carol','dave']:act(alice,'users',{'action':'user_remove','name':name})
# ---- Turning it off ------------------------------------------------------------------------------------
check('current password isn\'t right' in act(alice,'account',{'action':'mfa_off','current':'nope nope nope'})[1] and f.exists(),'turning it off needs the current password')
act(alice,'account',{'action':'mfa_off','current':'alice password one'})
check(not f.exists() and sign_in('alice','alice password one'),'turned off, the password alone signs in again')
print(json.dumps({'checks':len(checks)}))