crypto_engine.py 7.6 KB

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