crypto_engine.py 7.4 KB

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