crypto.py 12 KB

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