crypto_engine.py 7.1 KB

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