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