crypto.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 CAST as cCAST
  41. from Crypto.Cipher import DES as cDES
  42. from Crypto.Cipher import DES3 as cDES3
  43. from Crypto.Random import OSRNG
  44. from pwman.util.callback import Callback
  45. import pwman.util.config as config
  46. import cPickle
  47. import time
  48. import sys
  49. import ctypes
  50. import hashlib
  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. """
  90. Cryptographic Engine, overrides CryptoEngineOld.
  91. The main change is that _getcipher_real is now hashing the key
  92. before encrypting it.
  93. This method can eventually remove the call to _retrievedata,
  94. which used to strip the _TAG from the plain text string or return
  95. the cPickle object as string.
  96. Since we don't use cPickle to serialize object anymore, we can
  97. safely aim towards removing this method. Thus, removing also
  98. the _TAG in the beginning of each string as per recommendation of
  99. Ralf Herzog.
  100. """
  101. _timeoutcount = 0
  102. _instance = None
  103. _callback = None
  104. @classmethod
  105. def get(cls, dbver=None):
  106. """
  107. CryptoEngine.get() -> CryptoEngine
  108. Return an instance of CryptoEngine.
  109. If no instance is found, a CryptoException is raised.
  110. """
  111. if CryptoEngine._instance is None:
  112. algo = config.get_value("Encryption", "algorithm")
  113. if algo == "Dummy":
  114. CryptoEngine._instance = DummyCryptoEngine()
  115. elif dbver < 0.5:
  116. CryptoEngine._instance = CryptoEngineOld()
  117. elif dbver == 0.5:
  118. CryptoEngine._instance = CryptoEngine()
  119. return CryptoEngine._instance
  120. def __init__(self):
  121. """Initialise the Cryptographic Engine
  122. params is a dictionary. Valid keys are:
  123. algorithm: Which cipher to use
  124. callback: Callback class.
  125. keycrypted: This should be set by the database layer.
  126. timeout: Time after which key will be forgotten.
  127. Default is -1 (disabled).
  128. """
  129. algo = config.get_value("Encryption", "algorithm")
  130. if algo:
  131. self._algo = algo
  132. else:
  133. raise CryptoException("Parameters missing, no algorithm given")
  134. callback = config.get_value("Encryption", "callback")
  135. if isinstance(callback, Callback):
  136. self._callback = callback
  137. else:
  138. self._callback = None
  139. keycrypted = config.get_value("Encryption", "keycrypted")
  140. if len(keycrypted) > 0:
  141. self._keycrypted = keycrypted
  142. else:
  143. self._keycrypted = None
  144. timeout = config.get_value("Encryption", "timeout")
  145. if timeout.isdigit():
  146. self._timeout = timeout
  147. else:
  148. self._timeout = -1
  149. self._cipher = None
  150. def auth(self, key):
  151. """
  152. authenticate using a given key
  153. """
  154. tmpcipher = self._getcipher_real(key, self._algo)
  155. plainkey = tmpcipher.decrypt(str(self._keycrypted).decode('base64'))
  156. key = self._retrievedata(plainkey)
  157. key = str(key).decode('base64')
  158. self._cipher = self._getcipher_real(key, self._algo)
  159. def encrypt(self, obj):
  160. """
  161. encrypt(obj) -> ciphertext
  162. Encrypt obj and return its ciphertext. obj must be a picklable class.
  163. Can raise a CryptoException and CryptoUnsupportedException"""
  164. cipher = self._getcipher()
  165. plaintext = self._preparedata(obj, cipher.block_size)
  166. ciphertext = cipher.encrypt(plaintext)
  167. return str(ciphertext).encode('base64')
  168. def decrypt(self, ciphertext):
  169. """
  170. decrypt(ciphertext) -> obj
  171. Decrypt ciphertext and returns the obj that was encrypted.
  172. If key is bad, a CryptoBadKeyException is raised
  173. Can also raise a CryptoException and CryptoUnsupportedException"""
  174. cipher = self._getcipher()
  175. ciphertext = str(ciphertext).decode('base64')
  176. plaintext = cipher.decrypt(ciphertext)
  177. return self._retrievedata(plaintext)
  178. def set_cryptedkey(self, key):
  179. """
  180. hold _keycrypted
  181. """
  182. self._keycrypted = key
  183. def get_cryptedkey(self):
  184. """
  185. return _keycrypted
  186. """
  187. return self._keycrypted
  188. def set_callback(self, callback):
  189. """
  190. set the callback function
  191. """
  192. self._callback = callback
  193. def get_callback(self):
  194. """
  195. return call back function
  196. """
  197. return self._callback
  198. def changepassword(self):
  199. """
  200. Creates a new key. The key itself is actually stored in
  201. the database in crypted form. This key is encrypted using the
  202. password that the user provides. This makes it easy to change the
  203. password for the database.
  204. If oldKeyCrypted is none, then a new password is generated."""
  205. if self._callback is None:
  206. raise CryptoNoCallbackException("No call back class has been "
  207. "specified")
  208. if self._keycrypted is None:
  209. # Generate a new key, 32 byts in length, if that's
  210. # too long for the Cipher, _getCipherReal will sort it out
  211. random = OSRNG.new()
  212. key = str(random.read(32)).encode('base64')
  213. else:
  214. password = self._callback.getsecret(("Please enter your current "
  215. "password"))
  216. cipher = self._getcipher_real(password, self._algo)
  217. plainkey = cipher.decrypt(str(self._keycrypted).decode('base64'))
  218. key = self._retrievedata(plainkey)
  219. newpassword1 = self._callback.getnewsecret("Please enter your new \
  220. password")
  221. newpassword2 = self._callback.getnewsecret("Please enter your new \
  222. password again")
  223. while newpassword1 != newpassword2:
  224. print "Passwords do not match!"
  225. newpassword1 = self._callback.getnewsecret("Please enter your new \
  226. password")
  227. newpassword2 = self._callback.getnewsecret("Please enter your new \
  228. password again")
  229. newcipher = self._getcipher_real(newpassword1, self._algo)
  230. self._keycrypted = str(newcipher.encrypt(
  231. self._preparedata(key,
  232. newcipher.block_size)
  233. )).encode('base64')
  234. # newpassword1, newpassword2 are not needed any more so we erase
  235. # them
  236. zerome(newpassword1)
  237. zerome(newpassword2)
  238. del(newpassword1)
  239. del(newpassword2)
  240. # we also want to create the cipher if there isn't one already
  241. # so this CryptoEngine can be used from now on
  242. if self._cipher is None:
  243. self._cipher = self._getcipher_real(str(key).decode('base64'),
  244. self._algo)
  245. CryptoEngine._timeoutcount = time.time()
  246. return self._keycrypted
  247. def alive(self):
  248. """
  249. check if we have cipher
  250. """
  251. if self._cipher is not None:
  252. return True
  253. else:
  254. return False
  255. def forget(self):
  256. """
  257. discard cipher
  258. """
  259. self._cipher = None
  260. def _getcipher(self):
  261. """
  262. get cypher from user, to decrypt DB
  263. """
  264. if (self._cipher is not None
  265. and (self._timeout == -1
  266. or (time.time() -
  267. CryptoEngine._timeoutcount) < self._timeout)):
  268. return self._cipher
  269. if self._callback is None:
  270. raise CryptoNoCallbackException("No Callback exception")
  271. if self._keycrypted is None:
  272. raise CryptoNoKeyException("Encryption key has not been generated")
  273. max_tries = 5
  274. tries = 0
  275. key = None
  276. while tries < max_tries:
  277. try:
  278. password = self._callback.getsecret("Please enter your "
  279. "password")
  280. tmpcipher = self._getcipher_real(password, self._algo)
  281. plainkey = tmpcipher.decrypt(str(self._keycrypted).decode(
  282. 'base64'))
  283. key = self._retrievedata(plainkey)
  284. break
  285. except CryptoBadKeyException:
  286. print "Wrong password."
  287. tries += 1
  288. if not key:
  289. raise Exception("Wrong password entered %s times; giving up"
  290. % max_tries)
  291. key = str(key).decode('base64')
  292. self._cipher = self._getcipher_real(key,
  293. self._algo)
  294. CryptoEngine._timeoutcount = time.time()
  295. return self._cipher
  296. def _getcipher_real(self, key, algo):
  297. """
  298. do the real job of decrypting using functions
  299. form PyCrypto
  300. """
  301. if (algo == "AES"):
  302. key = hashlib.sha256(key)
  303. cipher = cAES.new(key.digest(), cAES.MODE_ECB)
  304. elif (algo == 'ARC2'):
  305. cipher = cARC2.new(key, cARC2.MODE_ECB)
  306. elif (algo == 'ARC4'):
  307. raise CryptoUnsupportedException("ARC4 is currently unsupported")
  308. elif (algo == 'Blowfish'):
  309. cipher = cBlowfish.new(key, cBlowfish.MODE_ECB)
  310. elif (algo == 'CAST'):
  311. cipher = cCAST.new(key, cCAST.MODE_ECB)
  312. elif (algo == 'DES'):
  313. if len(key) != 8:
  314. raise Exception("DES Encrypted keys must be 8 characters long!")
  315. cipher = cDES.new(key, cDES.MODE_ECB)
  316. elif (algo == 'DES3'):
  317. key = hashlib.sha224(key)
  318. cipher = cDES3.new(key.digest()[:24], cDES3.MODE_ECB)
  319. elif (algo == 'XOR'):
  320. raise CryptoUnsupportedException("XOR is currently unsupported")
  321. else:
  322. raise CryptoException("Invalid algorithm specified")
  323. return cipher
  324. def _preparedata(self, obj, blocksize):
  325. """
  326. prepare data before encrypting
  327. """
  328. return obj
  329. # plaintext = cPickle.dumps(obj)
  330. # plaintext = _TAG + obj
  331. # numblocks = (len(plaintext)/blocksize) + 1
  332. # newdatasize = blocksize*numblocks
  333. # return plaintext.ljust(newdatasize)
  334. def _retrievedata(self, plaintext):
  335. """
  336. retrieve encrypted data
  337. """
  338. return plaintext
  339. #if (plaintext.startswith(_TAG)):
  340. # plaintext = plaintext[len(_TAG):]
  341. #else:
  342. # raise CryptoBadKeyException("Error decrypting, bad key")
  343. #try:
  344. # old db version used to write stuff to db with
  345. # plaintext = cPickle.dumps(obj)
  346. # TODO: completely remove this block, and convert
  347. # the DB to a completely plain text ...
  348. # This implies that the coversion from OLD DATABASE FORMAT has
  349. # to plain strings too ...
  350. # return cPickle.loads(plaintext)
  351. #except (TypeError, ValueError, cPickle.UnpicklingError, EOFError):
  352. # return plaintext
  353. class DummyCryptoEngine(CryptoEngine):
  354. """Dummy CryptoEngine used when database doesn't ask for encryption.
  355. Only for testing and debugging the DB drivers really."""
  356. def __init__(self):
  357. pass
  358. def encrypt(self, strng):
  359. """Return the object pickled."""
  360. return strng.upper()
  361. def decrypt(self, strng):
  362. """Unpickle the object."""
  363. return strng.lower()
  364. def changepassword(self):
  365. return ''
  366. # TODO: add database that passes here
  367. class CryptoEngineOld(CryptoEngine): # pragma: no cover
  368. def _getcipher_real(self, key, algo):
  369. """
  370. do the real job of decrypting using functions
  371. form PyCrypto
  372. """
  373. if (algo == "AES"):
  374. key = self._padkey(key, [16, 24, 32])
  375. cipher = cAES.new(key, cAES.MODE_ECB)
  376. elif (algo == 'ARC2'):
  377. cipher = cARC2.new(key, cARC2.MODE_ECB)
  378. elif (algo == 'ARC4'):
  379. raise CryptoUnsupportedException("ARC4 is currently unsupported")
  380. elif (algo == 'Blowfish'):
  381. cipher = cBlowfish.new(key, cBlowfish.MODE_ECB)
  382. elif (algo == 'CAST'):
  383. cipher = cCAST.new(key, cCAST.MODE_ECB)
  384. elif (algo == 'DES'):
  385. self._padkey(key, [8])
  386. cipher = cDES.new(key, cDES.MODE_ECB)
  387. elif (algo == 'DES3'):
  388. key = self._padkey(key, [16, 24])
  389. cipher = cDES3.new(key, cDES3.MODE_ECB)
  390. elif (algo == 'XOR'):
  391. raise CryptoUnsupportedException("XOR is currently unsupported")
  392. else:
  393. raise CryptoException("Invalid algorithm specified")
  394. return cipher
  395. def _padkey(self, key, acceptable_lengths):
  396. """
  397. pad key with extra string
  398. """
  399. maxlen = max(acceptable_lengths)
  400. keylen = len(key)
  401. if (keylen > maxlen):
  402. return key[0:maxlen]
  403. acceptable_lengths.sort()
  404. acceptable_lengths.reverse()
  405. newkeylen = None
  406. for i in acceptable_lengths:
  407. if (i < keylen):
  408. break
  409. newkeylen = i
  410. return key.ljust(newkeylen)
  411. def _preparedata(self, obj, blocksize):
  412. """
  413. prepare data before encrypting
  414. """
  415. # plaintext = cPickle.dumps(obj)
  416. plaintext = _TAG + obj
  417. numblocks = (len(plaintext)/blocksize) + 1
  418. newdatasize = blocksize*numblocks
  419. return plaintext.ljust(newdatasize)
  420. def _retrievedata(self, plaintext):
  421. """
  422. retrieve encrypted data
  423. """
  424. if (plaintext.startswith(_TAG)):
  425. plaintext = plaintext[len(_TAG):]
  426. else:
  427. raise CryptoBadKeyException("Error decrypting, bad key")
  428. try:
  429. # old db version used to write stuff to db with
  430. # plaintext = cPickle.dumps(obj)
  431. # TODO: completely remove this block, and convert
  432. # the DB to a completely plain text ...
  433. # This implies that the coversion from OLD DATABASE FORMAT has
  434. # to plain strings too ...
  435. return cPickle.loads(plaintext)
  436. except (TypeError, ValueError, cPickle.UnpicklingError, EOFError):
  437. return plaintext