crypto.py 16 KB

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