crypto_engine.py 8.0 KB

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