crypto.py 13 KB

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