-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticator.py
245 lines (199 loc) · 9.15 KB
/
authenticator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import urllib
import urlparse
from datetime import timedelta
from functools import wraps
from hashlib import sha256
from hmac import new as hmac_new
import arrow
import six
from flask import request, g
from twisted.logger import Logger
log = Logger()
from .models.session_model import WBSessionModel
try:
from hmac import compare_digest
except ImportError:
def compare_digest(a, b):
l = min(len(a), len(b))
result = True
for i in range(0, l):
result = result and (a[i] == b[i]);
if len(a) != len(b):
result = False
return result
class HMACAuthenticator(object):
"""Analyze a request and find from which user it originates."""
@staticmethod
def get_authorization_headers(session_id, secret, path,
query_string=None, method='GET',
content_type='', body='',
host='localhost'):
canonical_uri = urllib.quote(path.strip())
if query_string is not None:
canonical_query_string = urlparse.parse_qsl(query_string, True, True)
canonical_query_string.sort() # will sort by name, then by value
canonical_query_string = urllib.urlencode(canonical_query_string)
else:
canonical_query_string = ''
payload_hash = sha256(body).hexdigest()
now = arrow.utcnow().format("YYYYMMDDTHHmmssZ")
headers = {
'content-type': content_type,
'host': host,
'x-woodbox-content-sha256': payload_hash,
'x-woodbox-timestamp': now
}
signed_headers = sorted(['content-type', 'host','x-woodbox-content-sha256','x-woodbox-timestamp'])
canonical_headers = []
for h in signed_headers:
canonical_headers.append(h+':'+headers[h])
canonical_headers = '\n'.join(canonical_headers).encode('utf-8')
signed_headers = ';'.join(signed_headers)
canonical_request = '\n'.join([method, path,
canonical_query_string,
canonical_headers,
signed_headers, payload_hash])
string_to_sign = '\n'.join(['WOODBOX-HMAC-SHA256', now, sha256(canonical_request).hexdigest()])
signing_key = secret.encode('utf-8')
signature = hmac_new(signing_key, string_to_sign, sha256).hexdigest()
auth = {
'Credential': session_id,
'SignedHeaders': signed_headers,
'Signature': signature
}
auth = [k+'='+v for k,v in auth.iteritems()]
auth = ','.join(auth)
auth_str = ' '.join(['Woodbox-HMAC-SHA256', auth]);
auth_headers = {
'Authorization': auth_str,
'x-woodbox-content-sha256': payload_hash,
'x-woodbox-timestamp': now
}
return auth_headers
@staticmethod
def parse_authorization_header(header):
method, _, args = header.partition(' ')
method = method.strip()
args = args.split(',')
args_dict = dict()
for arg in args:
name, _, value = arg.partition('=')
args_dict[name.strip().lower()] = value.strip()
return (method, args_dict)
@staticmethod
def verify(algo, auth, headers):
"""
Expected headers:
Content-Type: application/vnd.api+json
Authorization: Woodbox-HMAC-SHA256 Credential=2a241ea1e4672ee91f2ef8051e00eb52f03e39c97404a487,SignedHeaders=host;x-woodbox-content-sha256;x-woodbox-timestamp,Signature=422a358ac3e9e27b00838b6aa4192d74788a0d1634b418a13e0a18aaf7ca65f8
x-woodbox-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-woodbox-timestamp: 20160122T211203Z
"""
# Check that we know the authentication algorithm.
if algo.lower() not in frozenset(['hmac-sha256']):
g.user = None
g.user_reason = 'Unknown authentication method: ' + algo
return False
# Check that we have all the required authentication parameters.
try:
# Values were stripped in parse_authorization_header().
credential = auth['credential'] # session_id
signed_headers = sorted(auth['signedheaders'].lower().split(';'))
signature = auth['signature']
except KeyError as e:
g.user = None
g.user_reason = 'Missing parameter: {}'.format(e.args[0])
return False
# Required headers are the headers that MUST be included in the canonical headers.
required_headers = set(['host', 'x-woodbox-content-sha256', 'x-woodbox-timestamp'])
for h in six.iterkeys(headers):
if h[:10] == 'x-woodbox-':
required_headers.add(h)
elif h == 'content-type':
required_headers.add(h)
# Check that all required headers were signed.
if required_headers > set(signed_headers):
g.user = None
missing = (required_headers - set(signed_headers))
g.user_reason = 'Some required headers were not signed: ' + ', '.join(missing)
return False
# Check that all signed headers are part of the request.
missing_headers = set(signed_headers) - set(six.iterkeys(headers))
if missing_headers:
g.user = None
g.user_reason = 'Missing headers: ' + ', '.join(missing_headers)
return False
# Check the age of the request. It must not be older than 5 minutes.
request_time = arrow.get(headers['x-woodbox-timestamp'], ["YYYYMMDDTHHmmssZ", "YYYYMMDDTHHmmss"])
now = arrow.utcnow()
max_age = timedelta(minutes=5)
if abs(request_time - now) > max_age:
g.user = None
g.user_reason = 'Request is too old.'
return False
# FIXME Implement a nonce to prevent replay attacks.
# Check the content hash.
payload_hash = sha256(request.data).hexdigest()
if payload_hash != headers['x-woodbox-content-sha256']:
g.user = None
g.user_reason = 'Content hash does not match.'
return False
# Load the session
session = WBSessionModel.query.filter_by(session_id=credential).first()
if not session:
g.user = None
g.user_reason = 'Invalid credential.'
return False
method = request.method.strip()
canonical_uri = urllib.quote(request.path.strip())
# Build the canonical query string
canonical_query_string = []
args = request.args.items(multi=True)
args.sort()
canonical_query_string = urllib.urlencode(args)
# Build the canonical headers string.
canonical_headers = []
for h in signed_headers:
canonical_headers.append(h+':'+headers[h])
canonical_headers = '\n'.join(canonical_headers).encode('utf-8')
signed_headers = ';'.join(signed_headers)
canonical_request = '\n'.join([method, canonical_uri,
canonical_query_string, canonical_headers, signed_headers,
payload_hash])
timestamp = headers['x-woodbox-timestamp']
string_to_sign = '\n'.join(['WOODBOX-HMAC-SHA256', timestamp, sha256(canonical_request).hexdigest()])
signing_key = session.secret.encode('utf-8')
computed_signature = hmac_new(signing_key, string_to_sign, sha256).hexdigest()
# Compare our signature with the signature in the request.
if compare_digest(signature.encode('ascii', 'ignore'), computed_signature.encode('ascii', 'ignore')):
g.user = session.user_id
g.user_reason = 'Authenticated'
success = True
else:
g.user = None
g.user_reason = 'Signature do not match'
log.debug("Authentication failure: signature do not match.\nExpected signature: {expected}\nComputed signature: {computed}\n\nString to sign:\n{sts}\n\nCanonical request:\n{cr}",
expected=signature.encode('ascii', 'ignore'),
computed=computed_signature.encode('ascii', 'ignore'),
sts=string_to_sign,
cr=canonical_request)
success = False
log.info("User {user} authenticated ({reason})", user=g.user, reason=g.user_reason)
return success
@staticmethod
def authenticate(f):
@wraps(f)
def wrapper(*args, **kwargs):
headers = dict()
for h in six.iterkeys(request.headers):
headers[h.lower().strip()] = request.headers[h].strip()
g.user = None
g.user_reason = "No valid authorization header."
if 'authorization' in headers:
method, auth = HMACAuthenticator.parse_authorization_header(headers['authorization'])
if method[:8].lower() == 'woodbox-':
HMACAuthenticator.verify(method[8:].lower(), auth, headers)
return f(*args, **kwargs)
return wrapper