crypto_engine.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. 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. class CryptoException(Exception):
  34. pass
  35. def get_digest(password, salt):
  36. """
  37. Get a digest based on clear text password
  38. """
  39. iterations = 5000
  40. return PBKDF2(password, salt, dkLen=32, count=iterations)
  41. def authenticate(password, salt, digest):
  42. """
  43. salt and digest are stored in a file or a database
  44. """
  45. dig = get_digest(password, salt)
  46. return binascii.hexlify(dig) == digest
  47. def write_password(reader=raw_input):
  48. """
  49. Write a secret password as a hash and the salt used for this hash
  50. to a file
  51. """
  52. salt = base64.b64encode(os.urandom(32))
  53. passwd = reader("Please type in the secret key:")
  54. key = get_digest(passwd, salt)
  55. f = open('passwords.txt', 'wt')
  56. hpk = salt+'$6$'.encode('utf8')+binascii.hexlify(key)
  57. f.write(hpk.decode('utf-8'))
  58. f.close()
  59. def get_digest_from_file(filename):
  60. """
  61. Read a digested password and salt from the file
  62. """
  63. f = open(filename, 'rt')
  64. salt, digest = f.readline().split('$6$')
  65. return salt.encode('utf-8'), digest.encode('utf-8')
  66. def get_cipher(password, salt):
  67. """
  68. Create a chiper object from a hashed password
  69. """
  70. iv = os.urandom(AES.block_size)
  71. dig = get_digest(password, salt)
  72. chiper = AES.new(dig, AES.MODE_ECB, iv)
  73. return chiper
  74. def cli_auth(reader=raw_input):
  75. """
  76. Read password from the user, if the password is correct,
  77. finish the execution an return the password and salt which
  78. are read from the file.
  79. """
  80. salt, digest = get_digest_from_file('passwords.txt')
  81. tries = 0
  82. while tries < 5:
  83. password = reader("Please type in your master password:"
  84. ).encode('utf-8')
  85. if authenticate(password, salt, digest):
  86. return password, salt
  87. print("You entered a wrong password...")
  88. tries += 1
  89. raise CryptoException("You entered wrong password 5 times..")
  90. def prepare_data(text, block_size):
  91. """
  92. prepare data before encryption so the lenght matches the expected
  93. lenght by the algorithm.
  94. """
  95. num_blocks = len(text)//block_size + 1
  96. newdatasize = block_size*num_blocks
  97. return text.ljust(newdatasize)
  98. def save_a_secret_message(reader=raw_input):
  99. """
  100. PoC to show we can encrypt a message
  101. """
  102. secret_msg = """This is a very important message! Learn Cryptography!!!"""
  103. # the secret message will be encrypted with the secret password found
  104. # in the file
  105. passwd, salt = cli_auth(reader=reader)
  106. cipher = get_cipher(passwd, salt)
  107. # explictly destroy password, so now there is no clear text reference
  108. # to the input given by the user
  109. del(passwd)
  110. msg = EncodeAES(cipher, prepare_data(secret_msg, AES.block_size))
  111. with open('secret.enc', 'wt') as s:
  112. s.write(msg.decode())
  113. print("The cipher message is:", msg.decode())
  114. def read_a_secret_message(reader=raw_input):
  115. """
  116. PoC to show we can decrypt a message
  117. """
  118. passwd, salt = cli_auth(reader)
  119. cipher = get_cipher(passwd, salt)
  120. del(passwd)
  121. with open('secret.enc') as s:
  122. msg = s.readline()
  123. print("The decrypted secret message is:")
  124. decoded = DecodeAES(cipher, msg)
  125. print(decoded)
  126. class CryptoEngine(object): # pagma: no cover
  127. _timeoutcount = 0
  128. _instance = None
  129. _instance_new = None
  130. _callback = None
  131. @classmethod
  132. def get(cls, dbver=0.5):
  133. if CryptoEngine._instance:
  134. return CryptoEngine._instance
  135. if CryptoEngine._instance_new:
  136. return CryptoEngine._instance_new
  137. algo = config.get_value("Encryption", "algorithm")
  138. if not algo:
  139. raise Exception("Parameters missing, no algorithm given")
  140. try:
  141. timeout = int(config.get_value("Encryption", "timeout"))
  142. except ValueError:
  143. timeout = -1
  144. salt, digest = get_digest_from_file('passwords.txt')
  145. kwargs = {'algorithm': algo,
  146. 'timeout': timeout, 'salt': salt, 'digest': digest}
  147. if dbver >= 0.5:
  148. CryptoEngine._instance_new = CryptoEngine(**kwargs)
  149. return CryptoEngine._instance_new
  150. def __init__(self, salt=None, digest=None, algorithm='AES',
  151. timeout=-1, reader=raw_input):
  152. """
  153. Initialise the Cryptographic Engine
  154. """
  155. self._algo = algorithm
  156. self._digest = digest if digest else None
  157. self._salt = salt if salt else None
  158. self._timeout = timeout
  159. self._cipher = None
  160. self._reader = reader
  161. def authenticate(self, password):
  162. """
  163. salt and digest are stored in a file or a database
  164. """
  165. dig = get_digest(password, self._salt)
  166. if binascii.hexlify(dig) == self._digest:
  167. CryptoEngine._timeoutcount = time.time()
  168. self._cipher = get_cipher(password, self._salt)
  169. return True
  170. return False
  171. def encrypt(self, text):
  172. if not self._is_authenticated():
  173. p, s = cli_auth(self._reader)
  174. cipher = get_cipher(p, s)
  175. del(p)
  176. return EncodeAES(cipher, prepare_data(text, AES.block_size))
  177. return EncodeAES(self._cipher, prepare_data(text, AES.block_size))
  178. def decrypt(self, cipher_text):
  179. if not self._is_authenticated():
  180. p, s = cli_auth(self._reader)
  181. cipher = get_cipher(p, s)
  182. del(p)
  183. return DecodeAES(cipher, prepare_data(cipher_text, AES.block_size))
  184. return DecodeAES(self._cipher, prepare_data(cipher_text,
  185. AES.block_size))
  186. def _is_authenticated(self):
  187. if not self._is_timedout() and self._cipher is not None:
  188. return True
  189. return False
  190. def _is_timedout(self):
  191. if self._timeout > 0:
  192. if (time.time() - CryptoEngine._timeoutcount) > self._timeout:
  193. self._cipher = None
  194. return True
  195. return False
  196. def changepassword(self, reader=raw_input):
  197. self._keycrypted = self._create_password(reader=reader)
  198. return self._keycrypted
  199. @property
  200. def callback(self):
  201. """
  202. return call back function
  203. """
  204. return self._callback
  205. @callback.setter
  206. def callback(self, callback):
  207. if isinstance(callback, Callback):
  208. self._callback = callback
  209. self._getsecret = callback.getsecret
  210. self._getnewsecret = callback.getnewsecret
  211. else:
  212. raise Exception("callback must be an instance of Callback!")
  213. def _create_password(self, reader=raw_input):
  214. """
  215. Create a secret password as a hash and the salt used for this hash.
  216. Change reader to manipulate how input is given.
  217. """
  218. salt = base64.b64encode(os.urandom(32))
  219. passwd = reader("Please type in the secret key:")
  220. key = self._get_digest(passwd, salt)
  221. hpk = salt+'$6$'.encode('utf8')+binascii.hexlify(key)
  222. return hpk.decode('utf-8')
  223. def _get_digest(self, password, salt):
  224. """
  225. Get a digest based on clear text password
  226. """
  227. iterations = 5000
  228. return PBKDF2(password, salt, dkLen=32, count=iterations)
  229. if __name__ == '__main__': # pragma: no cover
  230. if '-i' in sys.argv:
  231. write_password()
  232. save_a_secret_message()
  233. read_a_secret_message()