PageRenderTime 9ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/galaxy/web/security/__init__.py

https://github.com/dbcls/dbcls-galaxy
Python | 60 lines | 41 code | 7 blank | 12 comment | 5 complexity | 9507fa182ae407972dc51dc74611ebbc MD5 | raw file
  1. import os, os.path, logging
  2. import pkg_resources
  3. pkg_resources.require( "pycrypto" )
  4. from Crypto.Cipher import Blowfish
  5. from Crypto.Util.randpool import RandomPool
  6. from Crypto.Util import number
  7. log = logging.getLogger( __name__ )
  8. if os.path.exists( "/dev/urandom" ):
  9. # We have urandom, use it as the source of random data
  10. random_fd = os.open( "/dev/urandom", os.O_RDONLY )
  11. def get_random_bytes( nbytes ):
  12. value = os.read( random_fd, nbytes )
  13. # Normally we should get as much as we need
  14. if len( value ) == nbytes:
  15. return value.encode( "hex" )
  16. # If we don't, keep reading (this is slow and should never happen)
  17. while len( value ) < nbytes:
  18. value += os.read( random_fd, nbytes - len( value ) )
  19. return value.encode( "hex" )
  20. else:
  21. def get_random_bytes( nbytes ):
  22. nbits = nbytes * 8
  23. random_pool = RandomPool( 1064 )
  24. while random_pool.entropy < nbits:
  25. random_pool.add_event()
  26. random_pool.stir()
  27. return str( number.getRandomNumber( nbits, random_pool.get_bytes ) )
  28. class SecurityHelper( object ):
  29. # TODO: checking if histories/datasets are owned by the current user) will be moved here.
  30. def __init__( self, **config ):
  31. self.id_secret = config['id_secret']
  32. self.id_cipher = Blowfish.new( self.id_secret )
  33. def encode_id( self, id ):
  34. # Convert to string
  35. s = str( id )
  36. # Pad to a multiple of 8 with leading "!"
  37. s = ( "!" * ( 8 - len(s) % 8 ) ) + s
  38. # Encrypt
  39. return self.id_cipher.encrypt( s ).encode( 'hex' )
  40. def decode_id( self, id ):
  41. return int( self.id_cipher.decrypt( id.decode( 'hex' ) ).lstrip( "!" ) )
  42. def encode_session_key( self, session_key ):
  43. # Session keys are strings
  44. # Pad to a multiple of 8 with leading "!"
  45. s = ( "!" * ( 8 - len( session_key ) % 8 ) ) + session_key
  46. # Encrypt
  47. return self.id_cipher.encrypt( s ).encode( 'hex' )
  48. def decode_session_key( self, session_key ):
  49. # Session keys are strings
  50. return self.id_cipher.decrypt( session_key.decode( 'hex' ) ).lstrip( "!" )
  51. def get_new_session_key( self ):
  52. # Generate a unique, high entropy 128 bit random number
  53. return get_random_bytes( 16 )