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