crypto.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. from __future__ import print_function
  22. from Crypto.Cipher import Blowfish as cBlowfish
  23. from Crypto.Cipher import AES as cAES
  24. from Crypto.Cipher import ARC2 as cARC2
  25. from Crypto.Cipher import CAST as cCAST
  26. from Crypto.Cipher import DES as cDES
  27. from Crypto.Cipher import DES3 as cDES3
  28. from Crypto.Random import OSRNG
  29. from pwman.util.callback import Callback
  30. import pwman.util.config as config
  31. try:
  32. import cPickle
  33. except ImportError:
  34. import pickle as cPickle
  35. import time
  36. import sys
  37. import ctypes
  38. import hashlib
  39. import base64
  40. # Use this to tell if crypto is successful or not
  41. _TAG = "PWMANCRYPTO"
  42. _INSTANCE = None
  43. class CryptoException(Exception):
  44. """Generic Crypto Exception."""
  45. def __init__(self, message):
  46. self.message = message
  47. def __str__(self):
  48. return "CryptoException: " + self.message
  49. class CryptoUnsupportedException(CryptoException):
  50. """Unsupported feature requested."""
  51. def __str__(self):
  52. return "CryptoUnsupportedException: " + self.message
  53. class CryptoBadKeyException(CryptoException):
  54. """Encryption key is incorrect."""
  55. def __str__(self):
  56. return "CryptoBadKeyException: " + self.message
  57. class CryptoNoKeyException(CryptoException):
  58. """No key has been initalised."""
  59. def __str__(self):
  60. return "CryptoNoKeyException: " + self.message
  61. class CryptoNoCallbackException(CryptoException):
  62. """No Callback has been set."""
  63. def __str__(self):
  64. return "CryptoNoCallbackException: " + self.message
  65. class CryptoEngineO(object):
  66. """
  67. Cryptographic Engine, overrides CryptoEngineOld.
  68. The main change is that _getcipher_real is now hashing the key
  69. before encrypting it.
  70. This method can eventually remove the call to _retrievedata,
  71. which used to strip the _TAG from the plain text string or return
  72. the cPickle object as string.
  73. Since we don't use cPickle to serialize object anymore, we can
  74. safely aim towards removing this method. Thus, removing also
  75. the _TAG in the beginning of each string as per recommendation of
  76. Ralf Herzog.
  77. """
  78. _timeoutcount = 0
  79. _instance = None
  80. _instance_new = None
  81. _callback = None
  82. @classmethod
  83. def get(cls, dbver=0.5):
  84. """
  85. CryptoEngine.get() -> CryptoEngine
  86. Return an instance of CryptoEngine.
  87. If no instance is found, a CryptoException is raised.
  88. """
  89. if CryptoEngine._instance:
  90. return CryptoEngine._instance
  91. if CryptoEngine._instance_new:
  92. return CryptoEngine._instance_new
  93. keycrypted = config.get_value("Encryption", "keycrypted")
  94. algo = config.get_value("Encryption", "algorithm")
  95. if not algo:
  96. raise CryptoException("Parameters missing, no algorithm given")
  97. try:
  98. timeout = int(config.get_value("Encryption", "timeout"))
  99. except ValueError:
  100. timeout = -1
  101. kwargs = {'keycrypted': keycrypted, 'algorithm': algo,
  102. 'timeout': timeout}
  103. if dbver < 0.5:
  104. CryptoEngine._instance = CryptoEngineOld(**kwargs)
  105. return CryptoEngine._instance
  106. if dbver >= 0.5:
  107. CryptoEngine._instance_new = CryptoEngine(**kwargs)
  108. return CryptoEngine._instance_new
  109. def __init__(self, keycrypted=None, algorithm='AES', timeout=-1):
  110. """
  111. Initialise the Cryptographic Engine
  112. """
  113. self._algo = algorithm
  114. self._keycrypted = keycrypted if keycrypted else None
  115. self._timeout = timeout
  116. self._cipher = None
  117. def auth(self, key):
  118. """
  119. authenticate using a given key
  120. """
  121. tmpcipher = self._getcipher_real(key, self._algo)
  122. s = base64.b64decode(self._keycrypted)
  123. plainkey = tmpcipher.decrypt(s)
  124. key = self._retrievedata(plainkey)
  125. key = base64.b64decode(str(key))
  126. self._cipher = self._getcipher_real(key, self._algo)
  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. if sys.version_info.major > 2:
  136. rv = base64.b64encode(ciphertext) + b'\n'
  137. else:
  138. rv = base64.b64encode(ciphertext) + '\n'
  139. #rv = str(ciphertext).encode('base64')
  140. return rv
  141. def decrypt(self, ciphertext):
  142. """
  143. decrypt(ciphertext) -> obj
  144. Decrypt ciphertext and returns the obj that was encrypted.
  145. If key is bad, a CryptoBadKeyException is raised
  146. Can also raise a CryptoException and CryptoUnsupportedException"""
  147. cipher = self._getcipher()
  148. ciphertext = base64.b64decode(str(ciphertext))
  149. plaintext = cipher.decrypt(ciphertext)
  150. return self._retrievedata(plaintext)
  151. def set_cryptedkey(self, key):
  152. """
  153. hold _keycrypted
  154. """
  155. self._keycrypted = key
  156. def get_cryptedkey(self):
  157. """
  158. return _keycrypted
  159. """
  160. return self._keycrypted
  161. @property
  162. def callback(self):
  163. """
  164. return call back function
  165. """
  166. return self._callback
  167. @callback.setter
  168. def callback(self, callback):
  169. if isinstance(callback, Callback):
  170. self._callback = callback
  171. self._getsecret = callback.getsecret
  172. self._getnewsecret = callback.getnewsecret
  173. else:
  174. raise CryptoNoCallbackException("callback must be an instance of"
  175. " Callback!")
  176. def _get_keycrypted(self):
  177. if self._keycrypted is None:
  178. # Generate a new key, 32 byts in length, if that's
  179. # too long for the Cipher, _getCipherReal will sort it out
  180. random = OSRNG.new()
  181. randombytes = random.read(32)
  182. if sys.version_info.major > 2:
  183. key = base64.b64encode(randombytes)+b'\n'
  184. else:
  185. key = base64.b64encode(str(randombytes))+'\n'
  186. else:
  187. password = self._getsecret("Please enter your current password")
  188. cipher = self._getcipher_real(password, self._algo)
  189. plainkey = cipher.decrypt(base64.b64decode(self._keycrypted))
  190. # python2 only ...
  191. # plainkey = cipher.decrypt(str(self._keycrypted).decode('base64'))
  192. key = self._retrievedata(plainkey)
  193. return key
  194. def changepassword(self):
  195. """
  196. Creates a new key from a user given password.
  197. The key itself is actually stored in the database as
  198. a chiper text. This key is encrypted using a random byte string.
  199. """
  200. if self._callback is None:
  201. raise CryptoNoCallbackException("No call back class has been "
  202. "specified")
  203. key = self._get_keycrypted()
  204. newpassword1 = self._getnewsecret("Please enter your new password")
  205. newpassword2 = self._getnewsecret("Please enter your new password again")
  206. while newpassword1 != newpassword2:
  207. print("Passwords do not match!")
  208. newpassword1 = self._getnewsecret("Please enter your new password")
  209. newpassword2 = self._getnewsecret("Please enter your new password again")
  210. newcipher = self._getcipher_real(newpassword1, self._algo)
  211. pkey = self._preparedata(key, newcipher.block_size)
  212. ciphertext = newcipher.encrypt(pkey)
  213. if sys.version_info.major > 2:
  214. k = base64.b64encode(ciphertext) + b'\n'
  215. else:
  216. k = base64.b64encode(str(ciphertext)) + '\n'
  217. # python2 only
  218. # self._keycrypted = str(ciphertext).encode('base64')
  219. self._keycrypted = k
  220. # newpassword1, newpassword2 are not needed any more so we erase
  221. # them
  222. zerome(newpassword1)
  223. zerome(newpassword2)
  224. del(newpassword1)
  225. del(newpassword2)
  226. # we also want to create the cipher if there isn't one already
  227. # so this CryptoEngine can be used from now on
  228. if self._cipher is None:
  229. if sys.version_info.major > 2:
  230. key = base64.b64decode(key)
  231. else:
  232. key = base64.b64decode(str(key))
  233. self._cipher = self._getcipher_real(key, self._algo)
  234. CryptoEngine._timeoutcount = time.time()
  235. return self._keycrypted
  236. def alive(self):
  237. """
  238. check if we have cipher
  239. """
  240. if self._cipher is not None:
  241. return True
  242. else:
  243. return False
  244. def forget(self):
  245. """
  246. discard cipher
  247. """
  248. self._cipher = None
  249. def _pre_check_get_chiper(self):
  250. if (self._cipher is not None
  251. and (self._timeout == -1
  252. or (time.time() -
  253. CryptoEngine._timeoutcount) < self._timeout)):
  254. return self._cipher
  255. if self._callback is None:
  256. raise CryptoNoCallbackException("No Callback exception")
  257. if self._keycrypted is None:
  258. raise CryptoNoKeyException("Encryption key has not been generated")
  259. def _getcipher(self):
  260. """
  261. get cypher from user, to decrypt DB
  262. """
  263. if self._pre_check_get_chiper():
  264. return self._cipher
  265. max_tries = 5
  266. tries = 0
  267. key = None
  268. while tries < max_tries:
  269. try:
  270. password = self._getsecret("Please enter your password")
  271. tmpcipher = self._getcipher_real(password, self._algo)
  272. # python2 code only
  273. #ciphertext = str(self._keycrypted).decode('base64')
  274. tc = base64.b64decode(str(self._keycrypted))
  275. plainkey = tmpcipher.decrypt(tc)
  276. key = self._retrievedata(plainkey)
  277. break
  278. except CryptoBadKeyException:
  279. print("Wrong password.")
  280. tries += 1
  281. if not key:
  282. raise CryptoBadKeyException("Wrong password entered {x} times; "
  283. "giving up ".format(x=max_tries))
  284. try:
  285. key = base64.b64decode(str(key))
  286. #key = str(key).decode('base64')
  287. except Exception:
  288. key = cPickle.loads(key)
  289. key = base64.b64decode(str(key))
  290. #key = str(key).decode('base64')
  291. self._cipher = self._getcipher_real(key, self._algo)
  292. CryptoEngine._timeoutcount = time.time()
  293. return self._cipher
  294. def _getcipher_real(self, key, algo):
  295. """
  296. do the real job of decrypting using functions
  297. form PyCrypto
  298. """
  299. if (algo == "AES"):
  300. if sys.version_info.major > 2 and isinstance(key, str):
  301. key = key.encode('utf-8')
  302. for i in range(1000):
  303. key = hashlib.sha256(key)
  304. key = key.digest()
  305. key = hashlib.sha256(key)
  306. cipher = cAES.new(key.digest(), cAES.MODE_ECB)
  307. elif (algo == 'ARC2'):
  308. cipher = cARC2.new(key, cARC2.MODE_ECB)
  309. elif (algo == 'ARC4'):
  310. raise CryptoUnsupportedException("ARC4 is currently unsupported")
  311. elif (algo == 'Blowfish'):
  312. cipher = cBlowfish.new(key, cBlowfish.MODE_ECB)
  313. elif (algo == 'CAST'):
  314. cipher = cCAST.new(key, cCAST.MODE_ECB)
  315. elif (algo == 'DES'):
  316. if len(key) != 8:
  317. raise Exception("DES Encrypted keys must be 8 characters "
  318. "long!")
  319. cipher = cDES.new(key, cDES.MODE_ECB)
  320. elif (algo == 'DES3'):
  321. key = hashlib.sha224(key)
  322. cipher = cDES3.new(key.digest()[:24], cDES3.MODE_ECB)
  323. elif (algo == 'XOR'):
  324. raise CryptoUnsupportedException("XOR is currently unsupported")
  325. else:
  326. raise CryptoException("Invalid algorithm specified")
  327. return cipher
  328. def _preparedata(self, obj, blocksize):
  329. """
  330. prepare data before encrypting
  331. """
  332. plaintext = 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 sys.version_info.major > 2:
  341. return plaintext
  342. try:
  343. plaintext.decode('utf-8')
  344. except UnicodeDecodeError:
  345. raise CryptoBadKeyException("Error decrypting, bad key")
  346. return plaintext
  347. class CryptoEngineOld(CryptoEngineO):
  348. def _getcipher_real(self, key, algo):
  349. """
  350. do the real job of decrypting using functions
  351. form PyCrypto
  352. """
  353. if (algo == "AES"):
  354. key = self._padkey(key, [16, 24, 32])
  355. cipher = cAES.new(key, cAES.MODE_ECB)
  356. elif (algo == 'ARC2'):
  357. cipher = cARC2.new(key, cARC2.MODE_ECB)
  358. elif (algo == 'ARC4'):
  359. raise CryptoUnsupportedException("ARC4 is currently unsupported")
  360. elif (algo == 'Blowfish'):
  361. cipher = cBlowfish.new(key, cBlowfish.MODE_ECB)
  362. elif (algo == 'CAST'):
  363. cipher = cCAST.new(key, cCAST.MODE_ECB)
  364. elif (algo == 'DES'):
  365. self._padkey(key, [8])
  366. cipher = cDES.new(key, cDES.MODE_ECB)
  367. elif (algo == 'DES3'):
  368. key = self._padkey(key, [16, 24])
  369. cipher = cDES3.new(key, cDES3.MODE_ECB)
  370. elif (algo == 'XOR'):
  371. raise CryptoUnsupportedException("XOR is currently unsupported")
  372. else:
  373. raise CryptoException("Invalid algorithm specified")
  374. return cipher
  375. def _padkey(self, key, acceptable_lengths):
  376. """
  377. pad key with extra string
  378. """
  379. maxlen = max(acceptable_lengths)
  380. keylen = len(key)
  381. if (keylen > maxlen):
  382. return key[0:maxlen]
  383. acceptable_lengths.sort()
  384. acceptable_lengths.reverse()
  385. newkeylen = None
  386. for i in acceptable_lengths:
  387. if (i < keylen):
  388. break
  389. newkeylen = i
  390. return key.ljust(newkeylen)
  391. def _preparedata(self, obj, blocksize):
  392. """
  393. prepare data before encrypting
  394. """
  395. plaintext = _TAG + obj
  396. numblocks = (len(plaintext)/blocksize) + 1
  397. newdatasize = blocksize*numblocks
  398. return plaintext.ljust(newdatasize)
  399. def _retrievedata(self, plaintext):
  400. """
  401. retrieve encrypted data
  402. """
  403. # startswith(_TAG) is to make sure the decryption
  404. # is correct! However this method is SHIT! It is dangerous,
  405. # and exposes the datebase.
  406. # Instead we sould make sure that the string is composed of legal
  407. # printable stuff and not garbage
  408. # string.printable is one such set
  409. try:
  410. plaintext.decode('utf-8')
  411. except UnicodeDecodeError:
  412. raise CryptoBadKeyException("Error decrypting, bad key")
  413. if (plaintext.startswith(_TAG)):
  414. plaintext = plaintext[len(_TAG):]
  415. try:
  416. # old db version used to write stuff to db with
  417. # plaintext = cPickle.dumps(obj)
  418. # DONE: completely remove this block, and convert
  419. # the DB to a completely plain text ...
  420. # See the above CryptoEngine
  421. # This implies that the coversion from OLD DATABASE FORMAT has
  422. # plain strings too ...
  423. return cPickle.loads(plaintext)
  424. except (TypeError, ValueError, cPickle.UnpicklingError, EOFError):
  425. return plaintext