crypto.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  18. #============================================================================
  19. """Encryption Module used by PwmanDatabase
  20. Supports AES, ARC2, Blowfish, CAST, DES, DES3, IDEA, RC5.
  21. Usage:
  22. import pwman.util.crypto.CryptoEngine as CryptoEngine
  23. class myCallback(CryptoEngine.Callback):
  24. def execute(self):
  25. return "mykey"
  26. params = {'encryptionAlgorithm': 'AES',
  27. 'encryptionCallback': callbackFunction}
  28. CryptoEngine.init(params)
  29. crypto = CryptoEngine.get()
  30. ciphertext = crypto.encrypt("plaintext")
  31. plaintext = cyypto.decrypt(ciphertext)
  32. """
  33. from Crypto.Cipher import *
  34. from Crypto.Util.randpool import RandomPool
  35. from pwman.util.callback import Callback
  36. import pwman.util.config as config
  37. import cPickle
  38. import time
  39. _instance = None
  40. # Use this to tell if crypto is successful or not
  41. _TAG = "PWMANCRYPTO"
  42. class CryptoException(Exception):
  43. """Generic Crypto Exception."""
  44. def __init__(self, message):
  45. self.message = message
  46. def __str__(self):
  47. return "CryptoException: " + self.message
  48. class CryptoUnsupportedException(CryptoException):
  49. """Unsupported feature requested."""
  50. def __str__(self):
  51. return "CryptoUnsupportedException: " +self.message
  52. class CryptoBadKeyException(CryptoException):
  53. """Encryption key is incorrect."""
  54. def __str__(self):
  55. return "CryptoBadKeyException: " + self.message
  56. class CryptoNoKeyException(CryptoException):
  57. """No key has been initalised."""
  58. def __str__(self):
  59. return "CryptoNoKeyException: " + self.message
  60. class CryptoNoCallbackException(CryptoException):
  61. """No Callback has been set."""
  62. def __str__(self):
  63. return "CryptoNoCallbackException: " + self.message
  64. class CryptoPasswordMismatchException(CryptoException):
  65. """Entered passwords do not match."""
  66. def __str__(self):
  67. return "CryptoPasswordMismatchException: " + self.message
  68. class CryptoEngine:
  69. """Cryptographic Engine"""
  70. _timeoutcount = 0
  71. _instance = None
  72. _callback = None
  73. def get(cls):
  74. """
  75. get() -> CryptoEngine
  76. Return an instance of CryptoEngine.
  77. If no instance is found, a CryptoException is raised.
  78. """
  79. if (CryptoEngine._instance == None):
  80. algo = config.get_value("Encryption", "algorithm")
  81. if algo == "Dummy":
  82. CryptoEngine._instance = DummyCryptoEngine()
  83. else:
  84. CryptoEngine._instance = CryptoEngine()
  85. return CryptoEngine._instance
  86. get = classmethod(get)
  87. def __init__(self):
  88. """Initialise the Cryptographic Engine
  89. params is a dictionary. Valid keys are:
  90. algorithm: Which cipher to use
  91. callback: Callback class.
  92. keycrypted: This should be set by the database layer.
  93. timeout: Time after which key will be forgotten.
  94. Default is -1 (disabled).
  95. """
  96. algo = config.get_value("Encryption", "algorithm")
  97. if len(algo) > 0:
  98. self._algo = algo
  99. else:
  100. raise CryptoException("Parameters missing [%s]" % (e) )
  101. callback = config.get_value("Encryption", "callback")
  102. if isinstance(callback, Callback):
  103. self._callback = callback
  104. else:
  105. self._callback = None
  106. keycrypted = config.get_value("Encryption", "keycrypted")
  107. if len(keycrypted) > 0:
  108. self._keycrypted = keycrypted
  109. else:
  110. self._keycrypted = None
  111. timeout = config.get_value("Encryption", "timeout")
  112. if timeout.isdigit():
  113. self._timeout = timeout
  114. else:
  115. self._timeout = -1
  116. self._cipher = None
  117. def encrypt(self, obj):
  118. """
  119. encrypt(obj) -> ciphertext
  120. Encrypt obj and return its ciphertext. obj must be a picklable class.
  121. Can raise a CryptoException and CryptoUnsupportedException"""
  122. cipher = self._getcipher()
  123. plaintext = self._preparedata(obj, cipher.block_size)
  124. ciphertext = cipher.encrypt(plaintext)
  125. return str(ciphertext).encode('base64')
  126. def decrypt(self, ciphertext):
  127. """
  128. decrypt(ciphertext) -> obj
  129. Decrypt ciphertext and returns the obj that was encrypted.
  130. If key is bad, a CryptoBadKeyException is raised
  131. Can also raise a CryptoException and CryptoUnsupportedException"""
  132. cipher = self._getcipher()
  133. ciphertext = str(ciphertext).decode('base64')
  134. plaintext = cipher.decrypt(ciphertext)
  135. return self._retrievedata(plaintext)
  136. def set_cryptedkey(self, key):
  137. self._keycrypted = key
  138. def get_cryptedkey(self):
  139. return self._keycrypted
  140. def set_callback(self, callback):
  141. self._callback = callback
  142. def get_callback(self):
  143. return self._callback
  144. def changepassword(self):
  145. """
  146. Creates a new key. The key itself is actually stored in
  147. the database in crypted form. This key is encrypted using the
  148. password that the user provides. This makes it easy to change the
  149. password for the database.
  150. If oldKeyCrypted is none, then a new password is generated."""
  151. if (self._callback == None):
  152. raise CryptoNoCallbackException("No call back class has been specified")
  153. if (self._keycrypted == None):
  154. # Generate a new key, 32 bits in length, if that's
  155. # too long for the Cipher, _getCipherReal will sort it out
  156. random = RandomPool()
  157. key = str(random.get_bytes(32)).encode('base64')
  158. else:
  159. password = self._callback.getsecret("Please enter your current password")
  160. cipher = self._getcipher_real(password, self._algo)
  161. plainkey = cipher.decrypt(str(self._keycrypted).decode('base64'))
  162. key = self._retrievedata(plainkey)
  163. newpassword1 = self._callback.getsecret("Please enter your new password");
  164. newpassword2 = self._callback.getsecret("Please enter your new password again");
  165. if (newpassword1 != newpassword2):
  166. raise CryptoPasswordMismatchException("Passwords do not match")
  167. newcipher = self._getcipher_real(newpassword1, self._algo)
  168. self._keycrypted = str(newcipher.encrypt(self._preparedata(key, newcipher.block_size))).encode('base64')
  169. # we also want to create the cipher if there isn't one already
  170. # so this CryptoEngine can be used from now on
  171. if (self._cipher == None):
  172. self._cipher = self._getcipher_real(str(key).decode('base64'), self._algo)
  173. CryptoEngine._timeoutcount = time.time()
  174. return self._keycrypted
  175. def alive(self):
  176. if (self._cipher != None):
  177. return True
  178. else:
  179. return False
  180. def forget(self):
  181. self._cipher = None
  182. def _getcipher(self):
  183. if (self._cipher != None
  184. and (self._timeout == -1
  185. or (time.time() - CryptoEngine._timeoutcount) < self._timeout)):
  186. return self._cipher
  187. if (self._callback == None):
  188. raise CryptoNoCallbackException("No Callback exception")
  189. if (self._keycrypted == None):
  190. raise CryptoNoKeyException("Encryption key has not been generated")
  191. password = self._callback.getsecret("Please enter your password")
  192. tmpcipher = self._getcipher_real(password, self._algo)
  193. plainkey = tmpcipher.decrypt(str(self._keycrypted).decode('base64'))
  194. key = self._retrievedata(plainkey)
  195. self._cipher = self._getcipher_real(str(key).decode('base64'), self._algo)
  196. CryptoEngine._timeoutcount = time.time()
  197. return self._cipher
  198. def _getcipher_real(self, key, algo):
  199. if (algo == "AES"):
  200. key = self._padkey(key, [16, 24, 32])
  201. cipher = AES.new(key, AES.MODE_ECB)
  202. elif (algo == 'ARC2'):
  203. cipher = ARC2.new(key, ARC2.MODE_ECB)
  204. elif (algo == 'ARC4'):
  205. raise CryptoUnsupportedException("ARC4 is currently unsupported")
  206. elif (algo == 'Blowfish'):
  207. cipher = Blowfish.new(key, Blowfish.MODE_ECB)
  208. elif (algo == 'CAST'):
  209. cipher = CAST.new(key, CAST.MODE_ECB)
  210. elif (algo == 'DES'):
  211. self._padkey(key, [8])
  212. cipher = DES.new(key, DES.MODE_ECB)
  213. elif (algo == 'DES3'):
  214. key = self._padkey(key, [16, 24])
  215. cipher = DES3.new(key, DES3.MODE_ECB)
  216. elif (algo == 'IDEA'):
  217. key = self._padkey(key, [16])
  218. cipher = IDEA.new(key, IDEA.MODE_ECB)
  219. elif (algo == 'RC5'):
  220. cipher = RC5.new(key, RC5.MODE_ECB)
  221. elif (algo == 'XOR'):
  222. raise CryptoUnsupportedException("XOR is currently unsupported")
  223. else:
  224. raise CryptoException("Invalid algorithm specified")
  225. return cipher
  226. def _padkey(self, key, acceptable_lengths):
  227. maxlen = max(acceptable_lengths)
  228. keylen = len(key)
  229. if (keylen > maxlen):
  230. return key[0:maxlen]
  231. acceptable_lengths.sort()
  232. acceptable_lengths.reverse()
  233. newkeylen = None
  234. for i in acceptable_lengths:
  235. if (i < keylen):
  236. break
  237. newkeylen = i
  238. return key.ljust(newkeylen)
  239. def _preparedata(self, obj, blocksize):
  240. plaintext = cPickle.dumps(obj)
  241. plaintext = _TAG + plaintext
  242. numblocks = (len(plaintext)/blocksize) + 1
  243. newdatasize = blocksize*numblocks
  244. return plaintext.ljust(newdatasize)
  245. def _retrievedata(self, plaintext):
  246. if (plaintext.startswith(_TAG)):
  247. plaintext = plaintext[len(_TAG):]
  248. else:
  249. raise CryptoBadKeyException("Error decrypting, bad key")
  250. return cPickle.loads(plaintext)
  251. class DummyCryptoEngine(CryptoEngine):
  252. """Dummy CryptoEngine used when database doesn't ask for encryption.
  253. Only for testing and debugging the DB drivers really."""
  254. def __init__(self):
  255. pass
  256. def encrypt(self, obj):
  257. """Return the object pickled."""
  258. return cPickle.dumps(obj)
  259. def decrypt(self, ciphertext):
  260. """Unpickle the object."""
  261. return cPickle.loads(str(ciphertext))
  262. def changepassword(self):
  263. return ''