repository

BlowfishCMS

A small content management system for OpenBSD

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

89 lines · 8.1 KB · download this file

#!/usr/bin/env python3
"""Signing in to the admin: the login page, the session cookie checked by every
service with an admin screen, lockout after failed sign-ins, signing out, and
the fallback to httpd's password prompt on installs without a session key.
Uses a fresh catalogue; never touches live data."""
import os,sys,tempfile,pathlib,sqlite3,subprocess,json,re,urllib.parse,secrets,time
script=str(pathlib.Path(sys.argv[1]).resolve())
checks=[]
def check(v,msg):
 assert v,msg
 checks.append(msg);print('PASS',msg,flush=True)
with tempfile.TemporaryDirectory(prefix='blowfish-auth-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)
 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,'--comments-init'],env=env,check=True,capture_output=True)
 def run(path,fields=None,cookie='',user='',fetch=False,ip='192.0.2.7',script_name=None,origin='https://example.org'):
  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':user,'HTTP_ORIGIN':origin,'HTTP_COOKIE':cookie,'REMOTE_ADDR':ip,**({'HTTP_X_REQUESTED_WITH':'fetch'} if fetch else {})}
  p=subprocess.run(['perl',script],input=body,env=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

 # ---- Without a session key: nobody is signed in, whatever httpd says ------------------
 check(run('/admin/',user='alice')[0]==403 and run('/admin/')[0]==403,'without a session key the admin is closed, even to a name from httpd (REMOTE_USER isn\'t trusted since 0.25)')

 # ---- With a session key: the login page --------------------------------------------
 sk=root/'etc/blowfishcms-session';sk.mkdir(parents=True);(sk/'session.key').write_text(secrets.token_hex(32)+'\n')
 hashed=subprocess.run(['perl','-e','print crypt($ARGV[0],"\\$2b\\$10\\$".join("",map {("a".."z")[rand 26]} 1..22))','correct horse battery'],capture_output=True,text=True).stdout
 subprocess.run(['perl',script,'--set-password','alice'],input=hashed,env=env,check=True,capture_output=True,text=True)
 status,html,hdr=run('/admin/?kind=pages',user='alice')
 check(status==200 and 'name="password"' in html and 'value="/admin/?kind=pages"' in html and 'Pages' not in re.sub(r'<input[^>]*>','',html),'httpd\'s name no longer counts: the admin shows the login page, remembering where you were going')
 csrf=cookie_of(hdr,'bf_csrf');ck='bf_csrf='+csrf
 check(run('/admin/',{'csrf':csrf,'kind':'pages','action':'page_create','label':'X'},cookie=ck)[0]==401,'changes without signing in are refused')
 status,body,_=run('/admin/',{'csrf':csrf,'kind':'pages','action':'nav_toggle','page':'blog'},cookie=ck,fetch=True)
 check(status==401 and json.loads(body)['signed_out'],'background saves without signing in say so')
 for path,sn in [('/admin/comments/','/admin/comments/'),('/admin/mail/','/admin/mail/')]:
  status,_,hdr=run(path,script_name=sn)
  check(status==303 and hdr['Location']=='/admin/?kind=login&next='+urllib.parse.quote(path,safe=''),'other admin screens send you to sign in first: '+path)
 login=lambda u,p,ip='192.0.2.7',nxt='/admin/?kind=pages':run('/admin/',{'csrf':csrf,'kind':'login','user':u,'password':p,'next':nxt},cookie=ck,ip=ip)
 status,html,_=login('alice','wrong')
 check(status==400 and 'don’t match' in html,'a wrong password is refused')
 check(login('bob','correct horse battery')[0]==400,'another name with the right password is refused')
 status,_,hdr=login('alice','correct horse battery')
 sess=cookie_of(hdr,'bf_session')
 check(status==303 and hdr['Location']=='/admin/?kind=pages' and sess and 'HttpOnly' in hdr['Set-Cookie'] and 'Secure' in hdr['Set-Cookie'] and 'SameSite=Strict' in hdr['Set-Cookie'] and 'Path=/admin/' in hdr['Set-Cookie'],'the right password signs in and returns you where you were going')
 good=ck+'; bf_session='+sess
 status,html,_=run('/admin/?kind=pages',cookie=good)
 check(status==200 and '<h1>Pages</h1>' in html and 'value="logout"' in html,'signed in, the admin opens, with a sign-out button')
 check(run('/admin/comments/',cookie=good,script_name='/admin/comments/')[0]==200 and run('/admin/mail/',cookie=good,script_name='/admin/mail/')[0]==200,'the same sign-in opens the comments and mail screens')
 user,gen,exp,nonce,mac=sess.split('.')
 for bad,why in [(f'{user}.{gen}.{exp}.{nonce}.'+'0'*64,'a forged signature'),(f'{user}.{gen}.{int(time.time())-10}.{nonce}.{mac}','an expired session'),(f'bob.{gen}.{exp}.{nonce}.{mac}','another name'),(f'{user}.{gen}.{int(exp)+999999}.{nonce}.{mac}','a stretched expiry'),(f'{user}.{int(gen)+1}.{exp}.{nonce}.{mac}','another session generation'),(f'{user}.{exp}.{nonce}.{mac}','an older-format cookie')]:
  check(run('/admin/?kind=pages',cookie=ck+'; bf_session='+bad)[1].count('name="password"')==1,'refused: '+why)
 # A new site: the owner lands on the setup walkthrough; once it's done, on the Overview.
 check(login('alice','correct horse battery',nxt='/admin/')[2]['Location']=='/admin/?kind=setup','on a new site, signing in opens the setup walkthrough')
 with sqlite3.connect(data/'catalog.sqlite') as c:c.execute("update site_settings set value='done' where key='setup'")
 for nxt,want in [('//evil.example/','/admin/'),('https://evil.example/admin/','/admin/'),('/admin/?kind=x-store','/admin/?kind=x-store'),('/blog/','/admin/')]:
  check(login('alice','correct horse battery',nxt=nxt)[2]['Location']==want,'after signing in, only admin addresses are followed: '+nxt)

 # ---- Lockout -------------------------------------------------------------------
 for i in range(5):login('alice','nope',ip='198.51.100.1')
 status,html,_=login('alice','correct horse battery',ip='198.51.100.1')
 check(status==400 and 'Too many failed sign-ins' in html,'five failures lock that address, even with the right password')
 check(login('alice','correct horse battery',ip='198.51.100.2')[0]==303,'other addresses can still sign in')
 for i in range(30):login('alice','nope',ip=f'203.0.113.{i+1}')
 check('Too many failed sign-ins' in login('alice','correct horse battery',ip='198.51.100.3')[1],'thirty failures from anywhere lock all sign-ins')
 (data/'admin/logins.json').unlink()
 check(login('alice','correct horse battery',ip='198.51.100.3')[0]==303,'clearing the record (blowfishctl unlock) lets you in again')

 # ---- Signing out ------------------------------------------------------------------
 status,_,hdr=run('/admin/',{'csrf':csrf,'kind':'logout'},cookie=good)
 check(status==303 and 'bf_session=;' in hdr['Set-Cookie'] and 'Max-Age=0' in hdr['Set-Cookie'],'sign out clears the session cookie')
 other=login('alice','correct horse battery')[2];other=ck+'; bf_session='+cookie_of(other,'bf_session')
 check('<h1>Pages</h1>' in run('/admin/?kind=pages',cookie=other)[1],'a second browser is signed in')
 run('/admin/',{'csrf':csrf,'kind':'logout','everywhere':'1'},cookie=other)
 check(run('/admin/?kind=pages',cookie=other)[1].count('name="password"')==1,'sign out everywhere ends every session')
 print(json.dumps({'checks':len(checks)}))