crypto_engine.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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) 2014 Oz Nahum <nahumoz@gmail.com>
  18. # ============================================================================
  19. from __future__ import print_function
  20. from Crypto.Cipher import AES
  21. from Crypto.Protocol.KDF import PBKDF2
  22. import base64
  23. import os
  24. import sys
  25. import binascii
  26. import time
  27. from pwman.util.callback import Callback
  28. import pwman.util.config as config
  29. import ctypes
  30. if sys.version_info.major > 2: # pragma: no cover
  31. raw_input = input
  32. EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
  33. DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip()
  34. def zerome(string):
  35. """
  36. securely erase strings ...
  37. for windows: ctypes.cdll.msvcrt.memset
  38. """
  39. bufsize = len(string) + 1
  40. offset = sys.getsizeof(string) - bufsize
  41. ctypes.memset(id(string) + offset, 0, bufsize)
  42. class CryptoException(Exception):
  43. pass
  44. def get_digest(password, salt):
  45. """
  46. Get a digest based on clear text password
  47. """
  48. iterations = 5000
  49. return PBKDF2(password, salt, dkLen=32, count=iterations)
  50. def authenticate(password, salt, digest):
  51. """
  52. salt and digest are stored in a file or a database
  53. """
  54. dig = get_digest(password, salt)
  55. return binascii.hexlify(dig) == digest
  56. def get_cipher(password, salt):
  57. """
  58. Create a chiper object from a hashed password
  59. """
  60. iv = os.urandom(AES.block_size)
  61. dig = get_digest(password, salt)
  62. chiper = AES.new(dig, AES.MODE_ECB, iv)
  63. return chiper
  64. def prepare_data(text, block_size):
  65. """
  66. prepare data before encryption so the lenght matches the expected
  67. lenght by the algorithm.
  68. """
  69. num_blocks = len(text)//block_size + 1
  70. newdatasize = block_size*num_blocks
  71. return text.ljust(newdatasize)
  72. class CryptoEngine(object): # pagma: no cover
  73. _timeoutcount = 0
  74. _instance = None
  75. _instance_new = None
  76. _callback = None
  77. @classmethod
  78. def get(cls, dbver=0.5):
  79. if CryptoEngine._instance:
  80. return CryptoEngine._instance
  81. if CryptoEngine._instance_new:
  82. return CryptoEngine._instance_new
  83. algo = config.get_value("Encryption", "algorithm")
  84. if not algo:
  85. raise Exception("Parameters missing, no algorithm given")
  86. try:
  87. timeout = int(config.get_value("Encryption", "timeout"))
  88. except ValueError:
  89. timeout = -1
  90. kwargs = {'algorithm': algo,
  91. 'timeout': timeout}
  92. if dbver >= 0.5:
  93. CryptoEngine._instance_new = CryptoEngine(**kwargs)
  94. return CryptoEngine._instance_new
  95. def __init__(self, salt=None, digest=None, algorithm='AES',
  96. timeout=-1, reader=None):
  97. """
  98. Initialise the Cryptographic Engine
  99. """
  100. self._algo = algorithm
  101. self._digest = digest if digest else None
  102. self._salt = salt if salt else None
  103. self._timeout = timeout
  104. self._cipher = None
  105. self._reader = reader
  106. self._callback = None
  107. def authenticate(self, password):
  108. """
  109. salt and digest are stored in a file or a database
  110. """
  111. dig = get_digest(password, self._salt)
  112. if binascii.hexlify(dig) == self._digest:
  113. CryptoEngine._timeoutcount = time.time()
  114. self._cipher = get_cipher(password, self._salt)
  115. return True
  116. return False
  117. def _auth(self):
  118. """
  119. Read password from the user, if the password is correct,
  120. finish the execution an return the password and salt which
  121. are read from the file.
  122. """
  123. salt, digest = self._salt, self._digest
  124. tries = 0
  125. while tries < 5:
  126. password = self._getsecret("Please type in your master password:"
  127. ).encode('utf-8')
  128. if authenticate(password, salt, digest):
  129. return password, salt
  130. print("You entered a wrong password...")
  131. tries += 1
  132. raise CryptoException("You entered wrong password 5 times..")
  133. def encrypt(self, text):
  134. if not self._is_authenticated():
  135. p, s = self._auth()
  136. cipher = get_cipher(p, s)
  137. del(p)
  138. return EncodeAES(cipher, prepare_data(text, AES.block_size))
  139. return EncodeAES(self._cipher, prepare_data(text, AES.block_size))
  140. def decrypt(self, cipher_text):
  141. if not self._is_authenticated():
  142. p, s = self._auth()
  143. cipher = get_cipher(p, s)
  144. del(p)
  145. return DecodeAES(cipher, prepare_data(cipher_text, AES.block_size))
  146. return DecodeAES(self._cipher, prepare_data(cipher_text,
  147. AES.block_size))
  148. def forget(self):
  149. """
  150. discard cipher
  151. """
  152. self._cipher = None
  153. def _is_authenticated(self):
  154. if not self._is_timedout() and self._cipher is not None:
  155. return True
  156. return False
  157. def _is_timedout(self):
  158. if self._timeout > 0:
  159. if (time.time() - CryptoEngine._timeoutcount) > self._timeout:
  160. self._cipher = None
  161. return True
  162. return False
  163. def changepassword(self, reader=raw_input):
  164. if self._callback is None:
  165. raise CryptoException("No callback class has been "
  166. "specified")
  167. self._keycrypted = self._create_password()
  168. return self._keycrypted
  169. @property
  170. def callback(self):
  171. """
  172. return call back function
  173. """
  174. return self._callback
  175. @callback.setter
  176. def callback(self, callback):
  177. if isinstance(callback, Callback):
  178. self._callback = callback
  179. self._getsecret = callback.getsecret
  180. self._getnewsecret = callback.getnewsecret
  181. else:
  182. raise Exception("callback must be an instance of Callback!")
  183. def _create_password(self):
  184. """
  185. Create a secret password as a hash and the salt used for this hash.
  186. Change reader to manipulate how input is given.
  187. """
  188. salt = base64.b64encode(os.urandom(32))
  189. passwd = self._getsecret("Please type in the secret key:")
  190. key = self._get_digest(passwd, salt)
  191. hpk = salt+'$6$'.encode('utf8')+binascii.hexlify(key)
  192. return hpk.decode('utf-8')
  193. def _get_digest(self, password, salt):
  194. """
  195. Get a digest based on clear text password
  196. """
  197. iterations = 5000
  198. return PBKDF2(password, salt, dkLen=32, count=iterations)
  199. def set_cryptedkey(self, key):
  200. # TODO: rename this method!
  201. salt, digest = key.split('$6$')
  202. self._digest = digest.encode('utf-8')
  203. self._salt = salt.encode('utf-8')
  204. def get_cryptedkey(self):
  205. # TODO: rename this method!
  206. """
  207. return _keycrypted
  208. """
  209. return self._salt + '$6$' + self._digest