PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/keystone/common/utils.py

https://github.com/dolph/keystone
Python | 270 lines | 216 code | 20 blank | 34 comment | 19 complexity | efba7f6d952e2b88b6106177cf96825c MD5 | raw file
  1. # vim: tabstop=4 shiftwidth=4 softtabstop=4
  2. # Copyright 2012 OpenStack LLC
  3. # Copyright 2010 United States Government as represented by the
  4. # Administrator of the National Aeronautics and Space Administration.
  5. # Copyright 2011 - 2012 Justin Santa Barbara
  6. # All Rights Reserved.
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  9. # not use this file except in compliance with the License. You may obtain
  10. # a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  16. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  17. # License for the specific language governing permissions and limitations
  18. # under the License.
  19. import base64
  20. import hashlib
  21. import hmac
  22. import json
  23. import os
  24. import subprocess
  25. import time
  26. import urllib
  27. import passlib.hash
  28. from keystone.common import logging
  29. from keystone import config
  30. CONF = config.CONF
  31. config.register_int('crypt_strength', default=40000)
  32. LOG = logging.getLogger(__name__)
  33. MAX_PASSWORD_LENGTH = 4096
  34. def read_cached_file(filename, cache_info, reload_func=None):
  35. """Read from a file if it has been modified.
  36. :param cache_info: dictionary to hold opaque cache.
  37. :param reload_func: optional function to be called with data when
  38. file is reloaded due to a modification.
  39. :returns: data from file
  40. """
  41. mtime = os.path.getmtime(filename)
  42. if not cache_info or mtime != cache_info.get('mtime'):
  43. with open(filename) as fap:
  44. cache_info['data'] = fap.read()
  45. cache_info['mtime'] = mtime
  46. if reload_func:
  47. reload_func(cache_info['data'])
  48. return cache_info['data']
  49. class SmarterEncoder(json.JSONEncoder):
  50. """Help for JSON encoding dict-like objects."""
  51. def default(self, obj):
  52. if not isinstance(obj, dict) and hasattr(obj, 'iteritems'):
  53. return dict(obj.iteritems())
  54. return super(SmarterEncoder, self).default(obj)
  55. class Ec2Signer(object):
  56. """Hacked up code from boto/connection.py"""
  57. def __init__(self, secret_key):
  58. secret_key = secret_key.encode()
  59. self.hmac = hmac.new(secret_key, digestmod=hashlib.sha1)
  60. if hashlib.sha256:
  61. self.hmac_256 = hmac.new(secret_key, digestmod=hashlib.sha256)
  62. def generate(self, credentials):
  63. """Generate auth string according to what SignatureVersion is given."""
  64. if credentials['params']['SignatureVersion'] == '0':
  65. return self._calc_signature_0(credentials['params'])
  66. if credentials['params']['SignatureVersion'] == '1':
  67. return self._calc_signature_1(credentials['params'])
  68. if credentials['params']['SignatureVersion'] == '2':
  69. return self._calc_signature_2(credentials['params'],
  70. credentials['verb'],
  71. credentials['host'],
  72. credentials['path'])
  73. raise Exception('Unknown Signature Version: %s' %
  74. credentials['params']['SignatureVersion'])
  75. @staticmethod
  76. def _get_utf8_value(value):
  77. """Get the UTF8-encoded version of a value."""
  78. if not isinstance(value, str) and not isinstance(value, unicode):
  79. value = str(value)
  80. if isinstance(value, unicode):
  81. return value.encode('utf-8')
  82. else:
  83. return value
  84. def _calc_signature_0(self, params):
  85. """Generate AWS signature version 0 string."""
  86. s = params['Action'] + params['Timestamp']
  87. self.hmac.update(s)
  88. return base64.b64encode(self.hmac.digest())
  89. def _calc_signature_1(self, params):
  90. """Generate AWS signature version 1 string."""
  91. keys = params.keys()
  92. keys.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  93. for key in keys:
  94. self.hmac.update(key)
  95. val = self._get_utf8_value(params[key])
  96. self.hmac.update(val)
  97. return base64.b64encode(self.hmac.digest())
  98. def _calc_signature_2(self, params, verb, server_string, path):
  99. """Generate AWS signature version 2 string."""
  100. LOG.debug('using _calc_signature_2')
  101. string_to_sign = '%s\n%s\n%s\n' % (verb, server_string, path)
  102. if self.hmac_256:
  103. current_hmac = self.hmac_256
  104. params['SignatureMethod'] = 'HmacSHA256'
  105. else:
  106. current_hmac = self.hmac
  107. params['SignatureMethod'] = 'HmacSHA1'
  108. keys = params.keys()
  109. keys.sort()
  110. pairs = []
  111. for key in keys:
  112. val = self._get_utf8_value(params[key])
  113. val = urllib.quote(val, safe='-_~')
  114. pairs.append(urllib.quote(key, safe='') + '=' + val)
  115. qs = '&'.join(pairs)
  116. LOG.debug('query string: %s', qs)
  117. string_to_sign += qs
  118. LOG.debug('string_to_sign: %s', string_to_sign)
  119. current_hmac.update(string_to_sign)
  120. b64 = base64.b64encode(current_hmac.digest())
  121. LOG.debug('len(b64)=%d', len(b64))
  122. LOG.debug('base64 encoded digest: %s', b64)
  123. return b64
  124. def trunc_password(password):
  125. """Truncate passwords to the MAX_PASSWORD_LENGTH."""
  126. if len(password) > MAX_PASSWORD_LENGTH:
  127. return password[:MAX_PASSWORD_LENGTH]
  128. else:
  129. return password
  130. def hash_password(password):
  131. """Hash a password. Hard."""
  132. password_utf8 = trunc_password(password).encode('utf-8')
  133. if passlib.hash.sha512_crypt.identify(password_utf8):
  134. return password_utf8
  135. h = passlib.hash.sha512_crypt.encrypt(password_utf8,
  136. rounds=CONF.crypt_strength)
  137. return h
  138. def ldap_hash_password(password):
  139. """Hash a password. Hard."""
  140. password_utf8 = trunc_password(password).encode('utf-8')
  141. h = passlib.hash.ldap_salted_sha1.encrypt(password_utf8)
  142. return h
  143. def ldap_check_password(password, hashed):
  144. if password is None:
  145. return False
  146. password_utf8 = trunc_password(password).encode('utf-8')
  147. return passlib.hash.ldap_salted_sha1.verify(password_utf8, hashed)
  148. def check_password(password, hashed):
  149. """Check that a plaintext password matches hashed.
  150. hashpw returns the salt value concatenated with the actual hash value.
  151. It extracts the actual salt if this value is then passed as the salt.
  152. """
  153. if password is None:
  154. return False
  155. password_utf8 = trunc_password(password).encode('utf-8')
  156. return passlib.hash.sha512_crypt.verify(password_utf8, hashed)
  157. # From python 2.7
  158. def check_output(*popenargs, **kwargs):
  159. r"""Run command with arguments and return its output as a byte string.
  160. If the exit code was non-zero it raises a CalledProcessError. The
  161. CalledProcessError object will have the return code in the returncode
  162. attribute and output in the output attribute.
  163. The arguments are the same as for the Popen constructor. Example:
  164. >>> check_output(['ls', '-l', '/dev/null'])
  165. 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
  166. The stdout argument is not allowed as it is used internally.
  167. To capture standard error in the result, use stderr=STDOUT.
  168. >>> check_output(['/bin/sh', '-c',
  169. ... 'ls -l non_existent_file ; exit 0'],
  170. ... stderr=STDOUT)
  171. 'ls: non_existent_file: No such file or directory\n'
  172. """
  173. if 'stdout' in kwargs:
  174. raise ValueError('stdout argument not allowed, it will be overridden.')
  175. LOG.debug(' '.join(popenargs[0]))
  176. process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
  177. output, unused_err = process.communicate()
  178. retcode = process.poll()
  179. if retcode:
  180. cmd = kwargs.get('args')
  181. if cmd is None:
  182. cmd = popenargs[0]
  183. raise subprocess.CalledProcessError(retcode, cmd)
  184. return output
  185. def git(*args):
  186. return check_output(['git'] + list(args))
  187. def unixtime(dt_obj):
  188. """Format datetime object as unix timestamp
  189. :param dt_obj: datetime.datetime object
  190. :returns: float
  191. """
  192. return time.mktime(dt_obj.utctimetuple())
  193. def auth_str_equal(provided, known):
  194. """Constant-time string comparison.
  195. :params provided: the first string
  196. :params known: the second string
  197. :return: True if the strings are equal.
  198. This function takes two strings and compares them. It is intended to be
  199. used when doing a comparison for authentication purposes to help guard
  200. against timing attacks. When using the function for this purpose, always
  201. provide the user-provided password as the first argument. The time this
  202. function will take is always a factor of the length of this string.
  203. """
  204. result = 0
  205. p_len = len(provided)
  206. k_len = len(known)
  207. for i in xrange(p_len):
  208. a = ord(provided[i]) if i < p_len else 0
  209. b = ord(known[i]) if i < k_len else 0
  210. result |= a ^ b
  211. return (p_len == k_len) & (result == 0)
  212. def hash_signed_token(signed_text):
  213. hash_ = hashlib.md5()
  214. hash_.update(signed_text)
  215. return hash_.hexdigest()