view web/secure.py @ 293:d15dda1b1f76

merge
author Matt Johnston <matt@ucc.asn.au>
date Sat, 06 Jul 2019 18:29:45 +0800
parents f7261dd970da
children a99631597f65
line wrap: on
line source

import re
import os
import time
import fcntl
import hmac
import binascii
import sys
import hashlib

import bottle

import config

__all__ = [
    "get_csrf_blob", 
    "check_csrf_blob", 
    "setup_csrf", 
    "check_cookie",
    "init_cookie",
]

AUTH_COOKIE = 'templogauth'
AUTH_COOKIE_LEN = 16

HASH=hashlib.sha1

CLEAN_RE = re.compile('[^a-z0-9A-Z]')

def cookie_hash(c):
    return hashlib.sha256(c).hexdigest()

def init_cookie():
    """ Generates a new httponly auth cookie if required. 
    Returns the hash of the cookie (new or existing)
    """
    c = bottle.request.get_cookie(AUTH_COOKIE)
    if not c:
        c = binascii.hexlify(os.urandom(AUTH_COOKIE_LEN))
        bottle.response.set_cookie(AUTH_COOKIE, c, secure=True, httponly=True)
    return cookie_hash(c)

def check_cookie(allowed_users):
    c = bottle.request.get_cookie(AUTH_COOKIE)
    if not c:
        return False
    return cookie_hash(c) in allowed_users

def setup_csrf():
    NONCE_SIZE=16
    global _csrf_fd, _csrf_key
    _csrf_fd = os.fdopen(os.open('%s/csrf.dat' % config.DATA_PATH, os.O_RDWR | os.O_CREAT, 0600), 'r+')

    try:
        fcntl.lockf(_csrf_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        _csrf_fd.write("%d-%s" % (os.getpid(), binascii.hexlify(os.urandom(NONCE_SIZE))))
        _csrf_fd.flush()
        _csrf_fd.seek(0)
    except IOError:
        pass
    fcntl.lockf(_csrf_fd, fcntl.LOCK_SH)
    _csrf_key = _csrf_fd.read()
    # keep the lock open until we go away


def get_csrf_blob():
    expiry = int(config.CSRF_TIMEOUT + time.time())
    content = '%s-%s' % (init_cookie(), expiry)
    mac = hmac.new(_csrf_key, content).hexdigest()
    return "%s-%s" % (content, mac)

def check_csrf_blob(blob):
    toks = blob.split('-')
    if len(toks) != 3:
        print>>sys.stderr, "wrong toks"
        return False

    user, expiry, mac = toks
    if user != init_cookie():
        print>>sys.stderr, "wrong user"
        return False

    try:
        exp = int(expiry)
    except ValueError:
        print>>sys.stderr, "failed exp"
        return False

    if exp < 1000000000:
        return False

    if exp < time.time():
        print>>sys.stderr, "expired %d %d" % (exp, time.time())
        return False

    check_content = "%s-%s" % (user, expiry)
    check_mac = hmac.new(_csrf_key, check_content).hexdigest()
    if mac == check_mac:
        print>>sys.stderr, "good hmac"
        return True

    print>>sys.stderr, "fail"
    return False