crypto_engine.py 8.0 KB

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