crypto.py 14 KB

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