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