crypto_engine.py 7.7 KB

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