OLD | NEW |
(Empty) | |
| 1 # |
| 2 # Copyright 2014 the Melange authors. |
| 3 # |
| 4 # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 # you may not use this file except in compliance with the License. |
| 6 # You may obtain a copy of the License at |
| 7 # |
| 8 # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 # |
| 10 # Unless required by applicable law or agreed to in writing, software |
| 11 # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 # See the License for the specific language governing permissions and |
| 14 # limitations under the License. |
| 15 |
| 16 """Helper methods for creating & verifying XSRF tokens.""" |
| 17 |
| 18 import base64 |
| 19 import binascii |
| 20 import hmac |
| 21 import time |
| 22 |
| 23 from oauth2client._helpers import _to_bytes |
| 24 from oauth2client import util |
| 25 |
| 26 __authors__ = [ |
| 27 '"Doug Coker" <dcoker@google.com>', |
| 28 '"Joe Gregorio" <jcgregorio@google.com>', |
| 29 ] |
| 30 |
| 31 # Delimiter character |
| 32 DELIMITER = b':' |
| 33 |
| 34 # 1 hour in seconds |
| 35 DEFAULT_TIMEOUT_SECS = 60 * 60 |
| 36 |
| 37 |
| 38 @util.positional(2) |
| 39 def generate_token(key, user_id, action_id='', when=None): |
| 40 """Generates a URL-safe token for the given user, action, time tuple. |
| 41 |
| 42 Args: |
| 43 key: secret key to use. |
| 44 user_id: the user ID of the authenticated user. |
| 45 action_id: a string identifier of the action they requested |
| 46 authorization for. |
| 47 when: the time in seconds since the epoch at which the user was |
| 48 authorized for this action. If not set the current time is used. |
| 49 |
| 50 Returns: |
| 51 A string XSRF protection token. |
| 52 """ |
| 53 digester = hmac.new(_to_bytes(key, encoding='utf-8')) |
| 54 digester.update(_to_bytes(str(user_id), encoding='utf-8')) |
| 55 digester.update(DELIMITER) |
| 56 digester.update(_to_bytes(action_id, encoding='utf-8')) |
| 57 digester.update(DELIMITER) |
| 58 when = _to_bytes(str(when or int(time.time())), encoding='utf-8') |
| 59 digester.update(when) |
| 60 digest = digester.digest() |
| 61 |
| 62 token = base64.urlsafe_b64encode(digest + DELIMITER + when) |
| 63 return token |
| 64 |
| 65 |
| 66 @util.positional(3) |
| 67 def validate_token(key, token, user_id, action_id="", current_time=None): |
| 68 """Validates that the given token authorizes the user for the action. |
| 69 |
| 70 Tokens are invalid if the time of issue is too old or if the token |
| 71 does not match what generateToken outputs (i.e. the token was forged). |
| 72 |
| 73 Args: |
| 74 key: secret key to use. |
| 75 token: a string of the token generated by generateToken. |
| 76 user_id: the user ID of the authenticated user. |
| 77 action_id: a string identifier of the action they requested |
| 78 authorization for. |
| 79 |
| 80 Returns: |
| 81 A boolean - True if the user is authorized for the action, False |
| 82 otherwise. |
| 83 """ |
| 84 if not token: |
| 85 return False |
| 86 try: |
| 87 decoded = base64.urlsafe_b64decode(token) |
| 88 token_time = int(decoded.split(DELIMITER)[-1]) |
| 89 except (TypeError, ValueError, binascii.Error): |
| 90 return False |
| 91 if current_time is None: |
| 92 current_time = time.time() |
| 93 # If the token is too old it's not valid. |
| 94 if current_time - token_time > DEFAULT_TIMEOUT_SECS: |
| 95 return False |
| 96 |
| 97 # The given token should match the generated one with the same time. |
| 98 expected_token = generate_token(key, user_id, action_id=action_id, |
| 99 when=token_time) |
| 100 if len(token) != len(expected_token): |
| 101 return False |
| 102 |
| 103 # Perform constant time comparison to avoid timing attacks |
| 104 different = 0 |
| 105 for x, y in zip(bytearray(token), bytearray(expected_token)): |
| 106 different |= x ^ y |
| 107 return not different |
OLD | NEW |