Mercurial > templog
comparison web/secure.py @ 185:adbf70d1449f
working
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Thu, 06 Feb 2014 22:45:16 +0800 |
parents | |
children | 101c66da848d |
comparison
equal
deleted
inserted
replaced
184:cbe14244a372 | 185:adbf70d1449f |
---|---|
1 import os | |
2 import time | |
3 import fcntl | |
4 import hmac | |
5 import binascii | |
6 import sys | |
7 | |
8 import config | |
9 | |
10 __all__ = ["get_csrf_blob", "check_csrf_blob", "setup_csrf"] | |
11 | |
12 def get_user_hash(): | |
13 return "aaa" | |
14 | |
15 def setup_csrf(): | |
16 NONCE_SIZE=16 | |
17 global _csrf_fd, _csrf_key | |
18 _csrf_fd = open('%s/csrf.dat' % config.DATA_PATH, 'r+') | |
19 | |
20 try: | |
21 fcntl.lockf(_csrf_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
22 os.fchmod(_csrf_fd.fileno(), 0600) | |
23 _csrf_fd.write("%d-%s" % (os.getpid(), binascii.hexlify(os.urandom(NONCE_SIZE)))) | |
24 _csrf_fd.flush() | |
25 _csrf_fd.seek(0) | |
26 except IOError: | |
27 pass | |
28 fcntl.lockf(_csrf_fd, fcntl.LOCK_SH) | |
29 _csrf_key = _csrf_fd.read() | |
30 # keep the lock open until we go away | |
31 | |
32 | |
33 def get_csrf_blob(): | |
34 expiry = int(config.CSRF_TIMEOUT + time.time()) | |
35 content = '%s-%s' % (get_user_hash(), expiry) | |
36 mac = hmac.new(_csrf_key, content).hexdigest() | |
37 return "%s-%s" % (content, mac) | |
38 | |
39 def check_csrf_blob(blob): | |
40 toks = blob.split('-') | |
41 if len(toks) != 3: | |
42 return False | |
43 | |
44 user, expiry, mac = toks | |
45 if user != get_user_hash(): | |
46 return False | |
47 | |
48 try: | |
49 exp = int(expiry) | |
50 except ValueError: | |
51 return False | |
52 | |
53 if exp < 1000000000: | |
54 return False | |
55 | |
56 if exp > time.time(): | |
57 return False | |
58 | |
59 check_content = "%s-%s" % (user, expiry) | |
60 check_mac = hmac.new(_csrf_key, content).hexdigest() | |
61 if mac == check_mac: | |
62 return True | |
63 | |
64 return False | |
65 |