signing.py 3.24 KB
Newer Older
Eliot Berriot's avatar
Eliot Berriot committed
1
import cryptography.exceptions
2
import datetime
3
import logging
4
5
6
7
8
import pytz

from django import forms
from django.utils import timezone
from django.utils.http import parse_http_date
Eliot Berriot's avatar
Eliot Berriot committed
9

10
11
12
import requests
import requests_http_signature

Eliot Berriot's avatar
Eliot Berriot committed
13
from . import exceptions, utils
14
15
16

logger = logging.getLogger(__name__)

17
#  the request Date should be between now - 30s and now + 30s
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
DATE_HEADER_VALID_FOR = 30


def verify_date(raw_date):
    if not raw_date:
        raise forms.ValidationError("Missing date header")

    try:
        ts = parse_http_date(raw_date)
    except ValueError as e:
        raise forms.ValidationError(str(e))
    dt = datetime.datetime.utcfromtimestamp(ts)
    dt = dt.replace(tzinfo=pytz.utc)
    delta = datetime.timedelta(seconds=DATE_HEADER_VALID_FOR)
    now = timezone.now()
    if dt < now - delta or dt > now + delta:
        raise forms.ValidationError(
Eliot Berriot's avatar
Eliot Berriot committed
35
            "Request Date {} is too far in the future or in the past".format(raw_date)
36
37
38
39
        )

    return dt

40
41

def verify(request, public_key):
Eliot Berriot's avatar
Eliot Berriot committed
42
43
44
    date = request.headers.get("Date")
    logger.debug(
        "Verifying request with date %s and headers %s", date, str(request.headers)
45
    )
Eliot Berriot's avatar
Eliot Berriot committed
46
47
48
    verify_date(date)
    try:
        return requests_http_signature.HTTPSignatureAuth.verify(
49
            request, key_resolver=lambda **kwargs: public_key, scheme="Signature"
Eliot Berriot's avatar
Eliot Berriot committed
50
51
52
53
54
55
56
57
        )
    except cryptography.exceptions.InvalidSignature:
        logger.warning(
            "Could not verify request with date %s and headers %s",
            date,
            str(request.headers),
        )
        raise
58
59
60
61
62
63
64


def verify_django(django_request, public_key):
    """
    Given a django WSGI request, create an underlying requests.PreparedRequest
    instance we can verify
    """
65
    headers = utils.clean_wsgi_headers(django_request.META)
66
67
68
69
70
    for h, v in list(headers.items()):
        # we include lower-cased version of the headers for compatibility
        # with requests_http_signature
        headers[h.lower()] = v
    try:
Eliot Berriot's avatar
Eliot Berriot committed
71
        signature = headers["Signature"]
72
73
    except KeyError:
        raise exceptions.MissingSignature
Eliot Berriot's avatar
Eliot Berriot committed
74
75
    url = "http://noop{}".format(django_request.path)
    query = django_request.META["QUERY_STRING"]
76
    if query:
Eliot Berriot's avatar
Eliot Berriot committed
77
        url += "?{}".format(query)
78
    signature_headers = signature.split('headers="')[1].split('",')[0]
Eliot Berriot's avatar
Eliot Berriot committed
79
80
    expected = signature_headers.split(" ")
    logger.debug("Signature expected headers: %s", expected)
81
    for header in expected:
82
83
84
        if header == "(request-target)":
            # this one represent the request body, so not an actual HTTP header
            continue
85
86
87
        try:
            headers[header]
        except KeyError:
Eliot Berriot's avatar
Eliot Berriot committed
88
            logger.debug("Missing header: %s", header)
89
    request = requests.Request(
Eliot Berriot's avatar
Eliot Berriot committed
90
91
        method=django_request.method, url=url, data=django_request.body, headers=headers
    )
92
93
94
95
    for h in request.headers.keys():
        v = request.headers[h]
        if v:
            request.headers[h] = str(v)
96
    request.prepare()
97
    return verify(request, public_key)
98
99
100


def get_auth(private_key, private_key_id):
101
    return requests_http_signature.HTTPSignatureHeaderAuth(
102
        headers=["(request-target)", "user-agent", "host", "date"],
Eliot Berriot's avatar
Eliot Berriot committed
103
104
        algorithm="rsa-sha256",
        key=private_key.encode("utf-8"),
105
106
        key_id=private_key_id,
    )