crypto.py 17 KB

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