crypto.py 11 KB

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