#!/usr/bin/python3 import os from urllib.parse import parse_qs from base64 import b64decode auth = os.getenv("HTTP_AUTHORIZATION") query = os.getenv("QUERY_STRING") or "user=foo&pass=bar&realm=NetSurf+Authentication+Test" query = parse_qs(query) username = query.get("user", ["foo"])[0] password = query.get("pass", query.get("password", ["bar"]))[0] realm = query.get("realm", ["NetSurf Authentication Test"])[0] gotuser = None gotpass = None def badauth(reason="NOAUTH"): print('Status: 401') print('WWW-Authenticate: Basic realm="{}"'.format(realm)) print('Content-Type: text/plain') print('') print('result=BAD, username={}/{}, password={}/{}, reason={}'.format(gotuser, username, gotpass, password, reason)) raise SystemExit if not auth: badauth("NOAUTH") else: if not auth.startswith("Basic "): badauth("NOTBASIC") enc = auth[6:] dec = b64decode(enc).decode('utf-8') if ":" not in dec: badauth("NOCOLON") bits = dec.rsplit(':', maxsplit=1) gotuser = bits[0] gotpass = bits[1] if gotuser != username: badauth("BADUSER") if gotpass != password: badauth("BADPASS") print('Content-Type: text/plain') print('') print("result=GOOD, username={}, password={}".format(username, password))