crypto_engine.py 7.6 KB

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