crypto.py 14 KB

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