crypto_engine.py 7.1 KB

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