An stunnel like program that utilizes the Noise protocol.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

327 lines
8.2 KiB

  1. from noise.connection import NoiseConnection, Keypair
  2. from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  3. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  4. from cryptography.hazmat.primitives import hashes
  5. from twistednoise import genkeypair
  6. from cryptography.hazmat.backends import default_backend
  7. import asyncio
  8. import os.path
  9. import shutil
  10. import socket
  11. import tempfile
  12. import threading
  13. import unittest
  14. _backend = default_backend()
  15. def _makeunix(path):
  16. '''Make a properly formed unix path socket string.'''
  17. return 'unix:%s' % path
  18. def _parsesockstr(sockstr):
  19. proto, rem = sockstr.split(':', 1)
  20. return proto, rem
  21. async def connectsockstr(sockstr):
  22. proto, rem = _parsesockstr(sockstr)
  23. reader, writer = await asyncio.open_unix_connection(rem)
  24. return reader, writer
  25. async def listensockstr(sockstr, cb):
  26. '''Wrapper for asyncio.start_x_server.
  27. The format of sockstr is: 'proto:param=value[,param2=value2]'.
  28. If the proto has a default parameter, the value can be used
  29. directly, like: 'proto:value'. This is only allowed when the
  30. value can unambiguously be determined not to be a param.
  31. The characters that define 'param' must be all lower case ascii
  32. characters and may contain an underscore. The first character
  33. must not be and underscore.
  34. Supported protocols:
  35. unix:
  36. Default parameter is path.
  37. The path parameter specifies the path to the
  38. unix domain socket. The path MUST start w/ a
  39. slash if it is used as a default parameter.
  40. '''
  41. proto, rem = _parsesockstr(sockstr)
  42. server = await asyncio.start_unix_server(cb, path=rem)
  43. return server
  44. # !!python makemessagelengths.py
  45. _handshakelens = \
  46. [72, 72, 88]
  47. def _genciphfun(hash, ad):
  48. hkdf = HKDF(algorithm=hashes.SHA256(), length=32,
  49. salt=b'asdoifjsldkjdsf', info=ad, backend=_backend)
  50. key = hkdf.derive(hash)
  51. cipher = Cipher(algorithms.AES(key), modes.ECB(),
  52. backend=_backend)
  53. enctor = cipher.encryptor()
  54. def encfun(data):
  55. # Returns the two bytes for length
  56. val = len(data)
  57. encbytes = enctor.update(data[:16])
  58. mask = int.from_bytes(encbytes[:2], byteorder='big') & 0xff
  59. return (val ^ mask).to_bytes(length=2, byteorder='big')
  60. def decfun(data):
  61. # takes off the data and returns the total
  62. # length
  63. val = int.from_bytes(data[:2], byteorder='big')
  64. encbytes = enctor.update(data[2:2 + 16])
  65. mask = int.from_bytes(encbytes[:2], byteorder='big') & 0xff
  66. return val ^ mask
  67. return encfun, decfun
  68. async def NoiseForwarder(mode, priv_key, rdrwrr, ptsockstr):
  69. rdr, wrr = rdrwrr
  70. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  71. proto.set_keypair_from_private_bytes(Keypair.STATIC, priv_key)
  72. proto.set_as_responder()
  73. proto.start_handshake()
  74. proto.read_message(await rdr.readexactly(_handshakelens[0]))
  75. wrr.write(proto.write_message())
  76. proto.read_message(await rdr.readexactly(_handshakelens[2]))
  77. if not proto.handshake_finished: # pragma: no cover
  78. raise RuntimeError('failed to finish handshake')
  79. # generate the keys for lengths
  80. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toresp')
  81. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toinit')
  82. reader, writer = await connectsockstr(ptsockstr)
  83. async def decses():
  84. try:
  85. while True:
  86. try:
  87. msg = await rdr.readexactly(2 + 16)
  88. except asyncio.streams.IncompleteReadError:
  89. if rdr.at_eof():
  90. return 'dec'
  91. tlen = declenfun(msg)
  92. rmsg = await rdr.readexactly(tlen - 16)
  93. tmsg = msg[2:] + rmsg
  94. writer.write(proto.decrypt(tmsg))
  95. await writer.drain()
  96. finally:
  97. writer.write_eof()
  98. async def encses():
  99. try:
  100. while True:
  101. ptmsg = await reader.read(65535 - 16) # largest message
  102. if not ptmsg:
  103. # eof
  104. return 'enc'
  105. encmsg = proto.encrypt(ptmsg)
  106. wrr.write(enclenfun(encmsg))
  107. wrr.write(encmsg)
  108. await wrr.drain()
  109. finally:
  110. wrr.write_eof()
  111. return asyncio.gather(decses(), encses())
  112. class TestListenSocket(unittest.TestCase):
  113. def test_listensockstr(self):
  114. # XXX write test
  115. pass
  116. # https://stackoverflow.com/questions/23033939/how-to-test-python-3-4-asyncio-code
  117. def async_test(f):
  118. def wrapper(*args, **kwargs):
  119. coro = asyncio.coroutine(f)
  120. future = coro(*args, **kwargs)
  121. loop = asyncio.get_event_loop()
  122. # timeout after 2 seconds
  123. loop.run_until_complete(asyncio.wait_for(future, 2))
  124. return wrapper
  125. class Tests_misc(unittest.TestCase):
  126. def test_genciphfun(self):
  127. enc, dec = _genciphfun(b'0' * 32, b'foobar')
  128. msg = b'this is a bunch of data'
  129. tb = enc(msg)
  130. self.assertEqual(len(msg), dec(tb + msg))
  131. for i in [ 20, 1384, 64000, 23839, 65535 ]:
  132. msg = os.urandom(i)
  133. self.assertEqual(len(msg), dec(enc(msg) + msg))
  134. class Tests(unittest.TestCase):
  135. def setUp(self):
  136. # setup temporary directory
  137. d = os.path.realpath(tempfile.mkdtemp())
  138. self.basetempdir = d
  139. self.tempdir = os.path.join(d, 'subdir')
  140. os.mkdir(self.tempdir)
  141. # Generate key pairs
  142. self.server_key_pair = genkeypair()
  143. self.client_key_pair = genkeypair()
  144. def tearDown(self):
  145. shutil.rmtree(self.basetempdir)
  146. self.tempdir = None
  147. @async_test
  148. async def test_server(self):
  149. # Test is plumbed:
  150. # (reader, writer) -> servsock ->
  151. # (rdr, wrr) NoiseForward (reader, writer) ->
  152. # servptsock -> (ptsock[0], ptsock[1])
  153. # Path that the server will sit on
  154. servsockpath = os.path.join(self.tempdir, 'servsock')
  155. servarg = _makeunix(servsockpath)
  156. # Path that the server will send pt data to
  157. servptpath = os.path.join(self.tempdir, 'servptsock')
  158. # Setup pt target listener
  159. pttarg = _makeunix(servptpath)
  160. ptsock = []
  161. def ptsockaccept(reader, writer, ptsock=ptsock):
  162. ptsock.append((reader, writer))
  163. # Bind to pt listener
  164. lsock = await listensockstr(pttarg, ptsockaccept)
  165. nfs = []
  166. event = asyncio.Event()
  167. async def runnf(rdr, wrr):
  168. a = await NoiseForwarder('resp', self.server_key_pair[1], (rdr, wrr), pttarg)
  169. nfs.append(a)
  170. event.set()
  171. # Setup server listener
  172. ssock = await listensockstr(servarg, runnf)
  173. # Connect to server
  174. reader, writer = await connectsockstr(servarg)
  175. # Create client
  176. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  177. proto.set_as_initiator()
  178. # Setup required keys
  179. proto.set_keypair_from_private_bytes(Keypair.STATIC, self.client_key_pair[1])
  180. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC, self.server_key_pair[0])
  181. proto.start_handshake()
  182. # Send first message
  183. message = proto.write_message()
  184. self.assertEqual(len(message), _handshakelens[0])
  185. writer.write(message)
  186. # Get response
  187. respmsg = await reader.readexactly(_handshakelens[1])
  188. proto.read_message(respmsg)
  189. # Send final reply
  190. message = proto.write_message()
  191. writer.write(message)
  192. # Make sure handshake has completed
  193. self.assertTrue(proto.handshake_finished)
  194. # generate the keys for lengths
  195. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toresp')
  196. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toinit')
  197. # write a test message
  198. ptmsg = b'this is a test message that should be a little in length'
  199. encmsg = proto.encrypt(ptmsg)
  200. writer.write(enclenfun(encmsg))
  201. writer.write(encmsg)
  202. # XXX - how to sync?
  203. await asyncio.sleep(.1)
  204. ptreader, ptwriter = ptsock[0]
  205. # read the test message
  206. rptmsg = await ptreader.readexactly(len(ptmsg))
  207. self.assertEqual(rptmsg, ptmsg)
  208. # write a different message
  209. ptmsg = os.urandom(2843)
  210. encmsg = proto.encrypt(ptmsg)
  211. writer.write(enclenfun(encmsg))
  212. writer.write(encmsg)
  213. # XXX - how to sync?
  214. await asyncio.sleep(.1)
  215. # read the test message
  216. rptmsg = await ptreader.readexactly(len(ptmsg))
  217. self.assertEqual(rptmsg, ptmsg)
  218. # now try the other way
  219. ptmsg = os.urandom(912)
  220. ptwriter.write(ptmsg)
  221. # find out how much we need to read
  222. encmsg = await reader.readexactly(2 + 16)
  223. tlen = declenfun(encmsg)
  224. # read the rest of the message
  225. rencmsg = await reader.readexactly(tlen - 16)
  226. tmsg = encmsg[2:] + rencmsg
  227. rptmsg = proto.decrypt(tmsg)
  228. self.assertEqual(rptmsg, ptmsg)
  229. # shut down sending
  230. writer.write_eof()
  231. # so pt reader should be shut down
  232. r = await ptreader.read(1)
  233. self.assertTrue(ptreader.at_eof())
  234. # shut down pt
  235. ptwriter.write_eof()
  236. # make sure the enc reader is eof
  237. r = await reader.read(1)
  238. self.assertTrue(reader.at_eof())
  239. await event.wait()
  240. self.assertEqual(await nfs[0], [ 'dec', 'enc' ])