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.
 
 

575 lines
15 KiB

  1. from cryptography.hazmat.backends import default_backend
  2. from cryptography.hazmat.primitives import hashes
  3. from cryptography.hazmat.primitives import serialization
  4. from cryptography.hazmat.primitives.asymmetric import x448
  5. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  6. from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  7. from cryptography.hazmat.primitives.serialization import load_pem_private_key
  8. from noise.connection import NoiseConnection, Keypair
  9. import tracemalloc; tracemalloc.start()
  10. import argparse
  11. import asyncio
  12. import base64
  13. import os.path
  14. import shutil
  15. import socket
  16. import sys
  17. import tempfile
  18. import threading
  19. import unittest
  20. _backend = default_backend()
  21. def genkeypair():
  22. '''Generates a keypair, and returns a tuple of (public, private).
  23. They are encoded as raw bytes, and sutible for use w/ Noise.'''
  24. key = x448.X448PrivateKey.generate()
  25. enc = serialization.Encoding.Raw
  26. pubformat = serialization.PublicFormat.Raw
  27. privformat = serialization.PrivateFormat.Raw
  28. encalgo = serialization.NoEncryption()
  29. pub = key.public_key().public_bytes(encoding=enc, format=pubformat)
  30. priv = key.private_bytes(encoding=enc, format=privformat, encryption_algorithm=encalgo)
  31. return pub, priv
  32. def _makefut(obj):
  33. loop = asyncio.get_running_loop()
  34. fut = loop.create_future()
  35. fut.set_result(obj)
  36. return fut
  37. def _makeunix(path):
  38. '''Make a properly formed unix path socket string.'''
  39. return 'unix:%s' % path
  40. def _parsesockstr(sockstr):
  41. proto, rem = sockstr.split(':', 1)
  42. return proto, rem
  43. async def connectsockstr(sockstr):
  44. proto, rem = _parsesockstr(sockstr)
  45. reader, writer = await asyncio.open_unix_connection(rem)
  46. return reader, writer
  47. async def listensockstr(sockstr, cb):
  48. '''Wrapper for asyncio.start_x_server.
  49. The format of sockstr is: 'proto:param=value[,param2=value2]'.
  50. If the proto has a default parameter, the value can be used
  51. directly, like: 'proto:value'. This is only allowed when the
  52. value can unambiguously be determined not to be a param.
  53. The characters that define 'param' must be all lower case ascii
  54. characters and may contain an underscore. The first character
  55. must not be and underscore.
  56. Supported protocols:
  57. unix:
  58. Default parameter is path.
  59. The path parameter specifies the path to the
  60. unix domain socket. The path MUST start w/ a
  61. slash if it is used as a default parameter.
  62. '''
  63. proto, rem = _parsesockstr(sockstr)
  64. server = await asyncio.start_unix_server(cb, path=rem)
  65. return server
  66. # !!python makemessagelengths.py
  67. _handshakelens = \
  68. [72, 72, 88]
  69. def _genciphfun(hash, ad):
  70. hkdf = HKDF(algorithm=hashes.SHA256(), length=32,
  71. salt=b'asdoifjsldkjdsf', info=ad, backend=_backend)
  72. key = hkdf.derive(hash)
  73. cipher = Cipher(algorithms.AES(key), modes.ECB(),
  74. backend=_backend)
  75. enctor = cipher.encryptor()
  76. def encfun(data):
  77. # Returns the two bytes for length
  78. val = len(data)
  79. encbytes = enctor.update(data[:16])
  80. mask = int.from_bytes(encbytes[:2], byteorder='big') & 0xff
  81. return (val ^ mask).to_bytes(length=2, byteorder='big')
  82. def decfun(data):
  83. # takes off the data and returns the total
  84. # length
  85. val = int.from_bytes(data[:2], byteorder='big')
  86. encbytes = enctor.update(data[2:2 + 16])
  87. mask = int.from_bytes(encbytes[:2], byteorder='big') & 0xff
  88. return val ^ mask
  89. return encfun, decfun
  90. async def NoiseForwarder(mode, rdrwrr, ptpair, priv_key, pub_key=None):
  91. rdr, wrr = await rdrwrr
  92. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  93. proto.set_keypair_from_private_bytes(Keypair.STATIC, priv_key)
  94. if pub_key is not None:
  95. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC,
  96. pub_key)
  97. if mode == 'resp':
  98. proto.set_as_responder()
  99. proto.start_handshake()
  100. proto.read_message(await rdr.readexactly(_handshakelens[0]))
  101. wrr.write(proto.write_message())
  102. proto.read_message(await rdr.readexactly(_handshakelens[2]))
  103. elif mode == 'init':
  104. proto.set_as_initiator()
  105. proto.start_handshake()
  106. wrr.write(proto.write_message())
  107. proto.read_message(await rdr.readexactly(_handshakelens[1]))
  108. wrr.write(proto.write_message())
  109. if not proto.handshake_finished: # pragma: no cover
  110. raise RuntimeError('failed to finish handshake')
  111. # generate the keys for lengths
  112. # XXX - get_handshake_hash is probably not the best option, but
  113. # this is only to obscure lengths, it is not required to be secure
  114. # as the underlying NoiseProtocol securely validates everything.
  115. # It is marginally useful as writing patterns likely expose the
  116. # true length. Adding padding could marginally help w/ this.
  117. if mode == 'resp':
  118. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toresp')
  119. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toinit')
  120. elif mode == 'init':
  121. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toresp')
  122. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toinit')
  123. reader, writer = await ptpair
  124. async def decses():
  125. try:
  126. while True:
  127. try:
  128. msg = await rdr.readexactly(2 + 16)
  129. except asyncio.streams.IncompleteReadError:
  130. if rdr.at_eof():
  131. return 'dec'
  132. tlen = declenfun(msg)
  133. rmsg = await rdr.readexactly(tlen - 16)
  134. tmsg = msg[2:] + rmsg
  135. writer.write(proto.decrypt(tmsg))
  136. await writer.drain()
  137. #except:
  138. # import traceback
  139. # traceback.print_exc()
  140. # raise
  141. finally:
  142. writer.write_eof()
  143. async def encses():
  144. try:
  145. while True:
  146. # largest message
  147. ptmsg = await reader.read(65535 - 16)
  148. if not ptmsg:
  149. # eof
  150. return 'enc'
  151. encmsg = proto.encrypt(ptmsg)
  152. wrr.write(enclenfun(encmsg))
  153. wrr.write(encmsg)
  154. await wrr.drain()
  155. #except:
  156. # import traceback
  157. # traceback.print_exc()
  158. # raise
  159. finally:
  160. wrr.write_eof()
  161. return await asyncio.gather(decses(), encses())
  162. # https://stackoverflow.com/questions/23033939/how-to-test-python-3-4-asyncio-code
  163. # Slightly modified to timeout
  164. def async_test(f):
  165. def wrapper(*args, **kwargs):
  166. coro = asyncio.coroutine(f)
  167. future = coro(*args, **kwargs)
  168. loop = asyncio.get_event_loop()
  169. # timeout after 2 seconds
  170. loop.run_until_complete(asyncio.wait_for(future, 2))
  171. return wrapper
  172. class Tests_misc(unittest.TestCase):
  173. def test_listensockstr(self):
  174. # XXX write test
  175. pass
  176. def test_genciphfun(self):
  177. enc, dec = _genciphfun(b'0' * 32, b'foobar')
  178. msg = b'this is a bunch of data'
  179. tb = enc(msg)
  180. self.assertEqual(len(msg), dec(tb + msg))
  181. for i in [ 20, 1384, 64000, 23839, 65535 ]:
  182. msg = os.urandom(i)
  183. self.assertEqual(len(msg), dec(enc(msg) + msg))
  184. def cmd_genkey(args):
  185. keypair = genkeypair()
  186. key = x448.X448PrivateKey.generate()
  187. # public key part
  188. enc = serialization.Encoding.Raw
  189. pubformat = serialization.PublicFormat.Raw
  190. pub = key.public_key().public_bytes(encoding=enc, format=pubformat)
  191. try:
  192. fname = args.fname + '.pub'
  193. with open(fname, 'x', encoding='ascii') as fp:
  194. print('ntun-x448', base64.urlsafe_b64encode(pub).decode('ascii'), file=fp)
  195. except FileExistsError:
  196. print('failed to create %s, file exists.' % fname, file=sys.stderr)
  197. sys.exit(1)
  198. enc = serialization.Encoding.PEM
  199. format = serialization.PrivateFormat.PKCS8
  200. encalgo = serialization.NoEncryption()
  201. with open(args.fname, 'x', encoding='ascii') as fp:
  202. fp.write(key.private_bytes(encoding=enc, format=format, encryption_algorithm=encalgo).decode('ascii'))
  203. def main():
  204. parser = argparse.ArgumentParser()
  205. subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands', help='additional help')
  206. parser_gk = subparsers.add_parser('genkey', help='generate keys')
  207. parser_gk.add_argument('fname', type=str, help='file name for the key')
  208. parser_gk.set_defaults(func=cmd_genkey)
  209. args = parser.parse_args()
  210. try:
  211. fun = args.func
  212. except AttributeError:
  213. parser.print_usage()
  214. sys.exit(5)
  215. fun(args)
  216. if __name__ == '__main__': # pragma: no cover
  217. main()
  218. def _asyncsockpair():
  219. '''Create a pair of sockets that are bound to each other.
  220. The function will return a tuple of two coroutine's, that
  221. each, when await'ed upon, will return the reader/writer pair.'''
  222. socka, sockb = socket.socketpair()
  223. return asyncio.open_connection(sock=socka), \
  224. asyncio.open_connection(sock=sockb)
  225. class TestMain(unittest.TestCase):
  226. def setUp(self):
  227. # setup temporary directory
  228. d = os.path.realpath(tempfile.mkdtemp())
  229. self.basetempdir = d
  230. self.tempdir = os.path.join(d, 'subdir')
  231. os.mkdir(self.tempdir)
  232. # Generate key pairs
  233. self.server_key_pair = genkeypair()
  234. self.client_key_pair = genkeypair()
  235. os.chdir(self.tempdir)
  236. def tearDown(self):
  237. shutil.rmtree(self.basetempdir)
  238. self.tempdir = None
  239. def test_noargs(self):
  240. sys.argv = [ 'prog' ]
  241. with self.assertRaises(SystemExit) as cm:
  242. main()
  243. # XXX - not checking error message
  244. # And that it exited w/ the correct code
  245. self.assertEqual(5, cm.exception.code)
  246. def test_genkey(self):
  247. # that it can generate a key
  248. sys.argv = [ 'prog', 'genkey', 'somefile' ]
  249. main()
  250. with open('somefile.pub', encoding='ascii') as fp:
  251. lines = fp.readlines()
  252. self.assertEqual(len(lines), 1)
  253. keytype, keyvalue = lines[0].split()
  254. self.assertEqual(keytype, 'ntun-x448')
  255. key = x448.X448PublicKey.from_public_bytes(base64.urlsafe_b64decode(keyvalue))
  256. with open('somefile', encoding='ascii') as fp:
  257. data = fp.read().encode('ascii')
  258. key = load_pem_private_key(data, password=None, backend=default_backend())
  259. self.assertIsInstance(key, x448.X448PrivateKey)
  260. # that a second call fails
  261. with self.assertRaises(SystemExit) as cm:
  262. main()
  263. # XXX - not checking error message
  264. # And that it exited w/ the correct code
  265. self.assertEqual(1, cm.exception.code)
  266. class TestNoiseFowarder(unittest.TestCase):
  267. def setUp(self):
  268. # setup temporary directory
  269. d = os.path.realpath(tempfile.mkdtemp())
  270. self.basetempdir = d
  271. self.tempdir = os.path.join(d, 'subdir')
  272. os.mkdir(self.tempdir)
  273. # Generate key pairs
  274. self.server_key_pair = genkeypair()
  275. self.client_key_pair = genkeypair()
  276. def tearDown(self):
  277. shutil.rmtree(self.basetempdir)
  278. self.tempdir = None
  279. @async_test
  280. async def test_server(self):
  281. # Test is plumbed:
  282. # (reader, writer) -> servsock ->
  283. # (rdr, wrr) NoiseForward (reader, writer) ->
  284. # servptsock -> (ptsock[0], ptsock[1])
  285. # Path that the server will sit on
  286. servsockpath = os.path.join(self.tempdir, 'servsock')
  287. servarg = _makeunix(servsockpath)
  288. # Path that the server will send pt data to
  289. servptpath = os.path.join(self.tempdir, 'servptsock')
  290. # Setup pt target listener
  291. pttarg = _makeunix(servptpath)
  292. ptsock = []
  293. def ptsockaccept(reader, writer, ptsock=ptsock):
  294. ptsock.append((reader, writer))
  295. # Bind to pt listener
  296. lsock = await listensockstr(pttarg, ptsockaccept)
  297. nfs = []
  298. event = asyncio.Event()
  299. async def runnf(rdr, wrr):
  300. ptpair = asyncio.create_task(connectsockstr(pttarg))
  301. a = await NoiseForwarder('resp',
  302. _makefut((rdr, wrr)), ptpair,
  303. priv_key=self.server_key_pair[1])
  304. nfs.append(a)
  305. event.set()
  306. # Setup server listener
  307. ssock = await listensockstr(servarg, runnf)
  308. # Connect to server
  309. reader, writer = await connectsockstr(servarg)
  310. # Create client
  311. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  312. proto.set_as_initiator()
  313. # Setup required keys
  314. proto.set_keypair_from_private_bytes(Keypair.STATIC,
  315. self.client_key_pair[1])
  316. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC,
  317. self.server_key_pair[0])
  318. proto.start_handshake()
  319. # Send first message
  320. message = proto.write_message()
  321. self.assertEqual(len(message), _handshakelens[0])
  322. writer.write(message)
  323. # Get response
  324. respmsg = await reader.readexactly(_handshakelens[1])
  325. proto.read_message(respmsg)
  326. # Send final reply
  327. message = proto.write_message()
  328. writer.write(message)
  329. # Make sure handshake has completed
  330. self.assertTrue(proto.handshake_finished)
  331. # generate the keys for lengths
  332. enclenfun, _ = _genciphfun(proto.get_handshake_hash(),
  333. b'toresp')
  334. _, declenfun = _genciphfun(proto.get_handshake_hash(),
  335. b'toinit')
  336. # write a test message
  337. ptmsg = b'this is a test message that should be a little in length'
  338. encmsg = proto.encrypt(ptmsg)
  339. writer.write(enclenfun(encmsg))
  340. writer.write(encmsg)
  341. # XXX - how to sync?
  342. await asyncio.sleep(.1)
  343. ptreader, ptwriter = ptsock[0]
  344. # read the test message
  345. rptmsg = await ptreader.readexactly(len(ptmsg))
  346. self.assertEqual(rptmsg, ptmsg)
  347. # write a different message
  348. ptmsg = os.urandom(2843)
  349. encmsg = proto.encrypt(ptmsg)
  350. writer.write(enclenfun(encmsg))
  351. writer.write(encmsg)
  352. # XXX - how to sync?
  353. await asyncio.sleep(.1)
  354. # read the test message
  355. rptmsg = await ptreader.readexactly(len(ptmsg))
  356. self.assertEqual(rptmsg, ptmsg)
  357. # now try the other way
  358. ptmsg = os.urandom(912)
  359. ptwriter.write(ptmsg)
  360. # find out how much we need to read
  361. encmsg = await reader.readexactly(2 + 16)
  362. tlen = declenfun(encmsg)
  363. # read the rest of the message
  364. rencmsg = await reader.readexactly(tlen - 16)
  365. tmsg = encmsg[2:] + rencmsg
  366. rptmsg = proto.decrypt(tmsg)
  367. self.assertEqual(rptmsg, ptmsg)
  368. # shut down sending
  369. writer.write_eof()
  370. # so pt reader should be shut down
  371. self.assertEqual(b'', await ptreader.read(1))
  372. self.assertTrue(ptreader.at_eof())
  373. # shut down pt
  374. ptwriter.write_eof()
  375. # make sure the enc reader is eof
  376. self.assertEqual(b'', await reader.read(1))
  377. self.assertTrue(reader.at_eof())
  378. await event.wait()
  379. self.assertEqual(nfs[0], [ 'dec', 'enc' ])
  380. @async_test
  381. async def test_serverclient(self):
  382. # plumbing:
  383. #
  384. # ptca -> ptcb NF client clsa -> clsb NF server ptsa -> ptsb
  385. #
  386. ptcsockapair, ptcsockbpair = _asyncsockpair()
  387. ptcareader, ptcawriter = await ptcsockapair
  388. #ptcsockbpair passed directly
  389. clssockapair, clssockbpair = _asyncsockpair()
  390. #both passed directly
  391. ptssockapair, ptssockbpair = _asyncsockpair()
  392. #ptssockapair passed directly
  393. ptsbreader, ptsbwriter = await ptssockbpair
  394. clientnf = asyncio.create_task(NoiseForwarder('init',
  395. clssockapair, ptcsockbpair,
  396. priv_key=self.client_key_pair[1],
  397. pub_key=self.server_key_pair[0]))
  398. servnf = asyncio.create_task(NoiseForwarder('resp',
  399. clssockbpair, ptssockapair,
  400. priv_key=self.server_key_pair[1]))
  401. # send a message
  402. msga = os.urandom(183)
  403. ptcawriter.write(msga)
  404. # make sure we get the same message
  405. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  406. # send a second message
  407. msga = os.urandom(2834)
  408. ptcawriter.write(msga)
  409. # make sure we get the same message
  410. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  411. # send a message larger than the block size
  412. msga = os.urandom(103958)
  413. ptcawriter.write(msga)
  414. # make sure we get the same message
  415. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  416. # send a message the other direction
  417. msga = os.urandom(103958)
  418. ptsbwriter.write(msga)
  419. # make sure we get the same message
  420. self.assertEqual(msga, await ptcareader.readexactly(len(msga)))
  421. # close down the pt writers, the rest should follow
  422. ptsbwriter.write_eof()
  423. ptcawriter.write_eof()
  424. # make sure they are closed, and there is no more data
  425. self.assertEqual(b'', await ptsbreader.read(1))
  426. self.assertTrue(ptsbreader.at_eof())
  427. self.assertEqual(b'', await ptcareader.read(1))
  428. self.assertTrue(ptcareader.at_eof())
  429. self.assertEqual([ 'dec', 'enc' ], await clientnf)
  430. self.assertEqual([ 'dec', 'enc' ], await servnf)