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.
 
 

570 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. if mode == 'resp':
  113. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toresp')
  114. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toinit')
  115. elif mode == 'init':
  116. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toresp')
  117. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toinit')
  118. reader, writer = await ptpair
  119. async def decses():
  120. try:
  121. while True:
  122. try:
  123. msg = await rdr.readexactly(2 + 16)
  124. except asyncio.streams.IncompleteReadError:
  125. if rdr.at_eof():
  126. return 'dec'
  127. tlen = declenfun(msg)
  128. rmsg = await rdr.readexactly(tlen - 16)
  129. tmsg = msg[2:] + rmsg
  130. writer.write(proto.decrypt(tmsg))
  131. await writer.drain()
  132. #except:
  133. # import traceback
  134. # traceback.print_exc()
  135. # raise
  136. finally:
  137. writer.write_eof()
  138. async def encses():
  139. try:
  140. while True:
  141. # largest message
  142. ptmsg = await reader.read(65535 - 16)
  143. if not ptmsg:
  144. # eof
  145. return 'enc'
  146. encmsg = proto.encrypt(ptmsg)
  147. wrr.write(enclenfun(encmsg))
  148. wrr.write(encmsg)
  149. await wrr.drain()
  150. #except:
  151. # import traceback
  152. # traceback.print_exc()
  153. # raise
  154. finally:
  155. wrr.write_eof()
  156. return await asyncio.gather(decses(), encses())
  157. # https://stackoverflow.com/questions/23033939/how-to-test-python-3-4-asyncio-code
  158. # Slightly modified to timeout
  159. def async_test(f):
  160. def wrapper(*args, **kwargs):
  161. coro = asyncio.coroutine(f)
  162. future = coro(*args, **kwargs)
  163. loop = asyncio.get_event_loop()
  164. # timeout after 2 seconds
  165. loop.run_until_complete(asyncio.wait_for(future, 2))
  166. return wrapper
  167. class Tests_misc(unittest.TestCase):
  168. def test_listensockstr(self):
  169. # XXX write test
  170. pass
  171. def test_genciphfun(self):
  172. enc, dec = _genciphfun(b'0' * 32, b'foobar')
  173. msg = b'this is a bunch of data'
  174. tb = enc(msg)
  175. self.assertEqual(len(msg), dec(tb + msg))
  176. for i in [ 20, 1384, 64000, 23839, 65535 ]:
  177. msg = os.urandom(i)
  178. self.assertEqual(len(msg), dec(enc(msg) + msg))
  179. def cmd_genkey(args):
  180. keypair = genkeypair()
  181. key = x448.X448PrivateKey.generate()
  182. # public key part
  183. enc = serialization.Encoding.Raw
  184. pubformat = serialization.PublicFormat.Raw
  185. pub = key.public_key().public_bytes(encoding=enc, format=pubformat)
  186. try:
  187. fname = args.fname + '.pub'
  188. with open(fname, 'x', encoding='ascii') as fp:
  189. print('ntun-x448', base64.urlsafe_b64encode(pub).decode('ascii'), file=fp)
  190. except FileExistsError:
  191. print('failed to create %s, file exists.' % fname, file=sys.stderr)
  192. sys.exit(1)
  193. enc = serialization.Encoding.PEM
  194. format = serialization.PrivateFormat.PKCS8
  195. encalgo = serialization.NoEncryption()
  196. with open(args.fname, 'x', encoding='ascii') as fp:
  197. fp.write(key.private_bytes(encoding=enc, format=format, encryption_algorithm=encalgo).decode('ascii'))
  198. def main():
  199. parser = argparse.ArgumentParser()
  200. subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands', help='additional help')
  201. parser_gk = subparsers.add_parser('genkey', help='generate keys')
  202. parser_gk.add_argument('fname', type=str, help='file name for the key')
  203. parser_gk.set_defaults(func=cmd_genkey)
  204. args = parser.parse_args()
  205. try:
  206. fun = args.func
  207. except AttributeError:
  208. parser.print_usage()
  209. sys.exit(5)
  210. fun(args)
  211. if __name__ == '__main__': # pragma: no cover
  212. main()
  213. def _asyncsockpair():
  214. '''Create a pair of sockets that are bound to each other.
  215. The function will return a tuple of two coroutine's, that
  216. each, when await'ed upon, will return the reader/writer pair.'''
  217. socka, sockb = socket.socketpair()
  218. return asyncio.open_connection(sock=socka), \
  219. asyncio.open_connection(sock=sockb)
  220. class TestMain(unittest.TestCase):
  221. def setUp(self):
  222. # setup temporary directory
  223. d = os.path.realpath(tempfile.mkdtemp())
  224. self.basetempdir = d
  225. self.tempdir = os.path.join(d, 'subdir')
  226. os.mkdir(self.tempdir)
  227. # Generate key pairs
  228. self.server_key_pair = genkeypair()
  229. self.client_key_pair = genkeypair()
  230. os.chdir(self.tempdir)
  231. def tearDown(self):
  232. shutil.rmtree(self.basetempdir)
  233. self.tempdir = None
  234. def test_noargs(self):
  235. sys.argv = [ 'prog' ]
  236. with self.assertRaises(SystemExit) as cm:
  237. main()
  238. # XXX - not checking error message
  239. # And that it exited w/ the correct code
  240. self.assertEqual(5, cm.exception.code)
  241. def test_genkey(self):
  242. # that it can generate a key
  243. sys.argv = [ 'prog', 'genkey', 'somefile' ]
  244. main()
  245. with open('somefile.pub', encoding='ascii') as fp:
  246. lines = fp.readlines()
  247. self.assertEqual(len(lines), 1)
  248. keytype, keyvalue = lines[0].split()
  249. self.assertEqual(keytype, 'ntun-x448')
  250. key = x448.X448PublicKey.from_public_bytes(base64.urlsafe_b64decode(keyvalue))
  251. with open('somefile', encoding='ascii') as fp:
  252. data = fp.read().encode('ascii')
  253. key = load_pem_private_key(data, password=None, backend=default_backend())
  254. self.assertIsInstance(key, x448.X448PrivateKey)
  255. # that a second call fails
  256. with self.assertRaises(SystemExit) as cm:
  257. main()
  258. # XXX - not checking error message
  259. # And that it exited w/ the correct code
  260. self.assertEqual(1, cm.exception.code)
  261. class TestNoiseFowarder(unittest.TestCase):
  262. def setUp(self):
  263. # setup temporary directory
  264. d = os.path.realpath(tempfile.mkdtemp())
  265. self.basetempdir = d
  266. self.tempdir = os.path.join(d, 'subdir')
  267. os.mkdir(self.tempdir)
  268. # Generate key pairs
  269. self.server_key_pair = genkeypair()
  270. self.client_key_pair = genkeypair()
  271. def tearDown(self):
  272. shutil.rmtree(self.basetempdir)
  273. self.tempdir = None
  274. @async_test
  275. async def test_server(self):
  276. # Test is plumbed:
  277. # (reader, writer) -> servsock ->
  278. # (rdr, wrr) NoiseForward (reader, writer) ->
  279. # servptsock -> (ptsock[0], ptsock[1])
  280. # Path that the server will sit on
  281. servsockpath = os.path.join(self.tempdir, 'servsock')
  282. servarg = _makeunix(servsockpath)
  283. # Path that the server will send pt data to
  284. servptpath = os.path.join(self.tempdir, 'servptsock')
  285. # Setup pt target listener
  286. pttarg = _makeunix(servptpath)
  287. ptsock = []
  288. def ptsockaccept(reader, writer, ptsock=ptsock):
  289. ptsock.append((reader, writer))
  290. # Bind to pt listener
  291. lsock = await listensockstr(pttarg, ptsockaccept)
  292. nfs = []
  293. event = asyncio.Event()
  294. async def runnf(rdr, wrr):
  295. ptpair = asyncio.create_task(connectsockstr(pttarg))
  296. a = await NoiseForwarder('resp',
  297. _makefut((rdr, wrr)), ptpair,
  298. priv_key=self.server_key_pair[1])
  299. nfs.append(a)
  300. event.set()
  301. # Setup server listener
  302. ssock = await listensockstr(servarg, runnf)
  303. # Connect to server
  304. reader, writer = await connectsockstr(servarg)
  305. # Create client
  306. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  307. proto.set_as_initiator()
  308. # Setup required keys
  309. proto.set_keypair_from_private_bytes(Keypair.STATIC,
  310. self.client_key_pair[1])
  311. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC,
  312. self.server_key_pair[0])
  313. proto.start_handshake()
  314. # Send first message
  315. message = proto.write_message()
  316. self.assertEqual(len(message), _handshakelens[0])
  317. writer.write(message)
  318. # Get response
  319. respmsg = await reader.readexactly(_handshakelens[1])
  320. proto.read_message(respmsg)
  321. # Send final reply
  322. message = proto.write_message()
  323. writer.write(message)
  324. # Make sure handshake has completed
  325. self.assertTrue(proto.handshake_finished)
  326. # generate the keys for lengths
  327. enclenfun, _ = _genciphfun(proto.get_handshake_hash(),
  328. b'toresp')
  329. _, declenfun = _genciphfun(proto.get_handshake_hash(),
  330. b'toinit')
  331. # write a test message
  332. ptmsg = b'this is a test message that should be a little in length'
  333. encmsg = proto.encrypt(ptmsg)
  334. writer.write(enclenfun(encmsg))
  335. writer.write(encmsg)
  336. # XXX - how to sync?
  337. await asyncio.sleep(.1)
  338. ptreader, ptwriter = ptsock[0]
  339. # read the test message
  340. rptmsg = await ptreader.readexactly(len(ptmsg))
  341. self.assertEqual(rptmsg, ptmsg)
  342. # write a different message
  343. ptmsg = os.urandom(2843)
  344. encmsg = proto.encrypt(ptmsg)
  345. writer.write(enclenfun(encmsg))
  346. writer.write(encmsg)
  347. # XXX - how to sync?
  348. await asyncio.sleep(.1)
  349. # read the test message
  350. rptmsg = await ptreader.readexactly(len(ptmsg))
  351. self.assertEqual(rptmsg, ptmsg)
  352. # now try the other way
  353. ptmsg = os.urandom(912)
  354. ptwriter.write(ptmsg)
  355. # find out how much we need to read
  356. encmsg = await reader.readexactly(2 + 16)
  357. tlen = declenfun(encmsg)
  358. # read the rest of the message
  359. rencmsg = await reader.readexactly(tlen - 16)
  360. tmsg = encmsg[2:] + rencmsg
  361. rptmsg = proto.decrypt(tmsg)
  362. self.assertEqual(rptmsg, ptmsg)
  363. # shut down sending
  364. writer.write_eof()
  365. # so pt reader should be shut down
  366. self.assertEqual(b'', await ptreader.read(1))
  367. self.assertTrue(ptreader.at_eof())
  368. # shut down pt
  369. ptwriter.write_eof()
  370. # make sure the enc reader is eof
  371. self.assertEqual(b'', await reader.read(1))
  372. self.assertTrue(reader.at_eof())
  373. await event.wait()
  374. self.assertEqual(nfs[0], [ 'dec', 'enc' ])
  375. @async_test
  376. async def test_serverclient(self):
  377. # plumbing:
  378. #
  379. # ptca -> ptcb NF client clsa -> clsb NF server ptsa -> ptsb
  380. #
  381. ptcsockapair, ptcsockbpair = _asyncsockpair()
  382. ptcareader, ptcawriter = await ptcsockapair
  383. #ptcsockbpair passed directly
  384. clssockapair, clssockbpair = _asyncsockpair()
  385. #both passed directly
  386. ptssockapair, ptssockbpair = _asyncsockpair()
  387. #ptssockapair passed directly
  388. ptsbreader, ptsbwriter = await ptssockbpair
  389. clientnf = asyncio.create_task(NoiseForwarder('init',
  390. clssockapair, ptcsockbpair,
  391. priv_key=self.client_key_pair[1],
  392. pub_key=self.server_key_pair[0]))
  393. servnf = asyncio.create_task(NoiseForwarder('resp',
  394. clssockbpair, ptssockapair,
  395. priv_key=self.server_key_pair[1]))
  396. # send a message
  397. msga = os.urandom(183)
  398. ptcawriter.write(msga)
  399. # make sure we get the same message
  400. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  401. # send a second message
  402. msga = os.urandom(2834)
  403. ptcawriter.write(msga)
  404. # make sure we get the same message
  405. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  406. # send a message larger than the block size
  407. msga = os.urandom(103958)
  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 the other direction
  412. msga = os.urandom(103958)
  413. ptsbwriter.write(msga)
  414. # make sure we get the same message
  415. self.assertEqual(msga, await ptcareader.readexactly(len(msga)))
  416. # close down the pt writers, the rest should follow
  417. ptsbwriter.write_eof()
  418. ptcawriter.write_eof()
  419. # make sure they are closed, and there is no more data
  420. self.assertEqual(b'', await ptsbreader.read(1))
  421. self.assertTrue(ptsbreader.at_eof())
  422. self.assertEqual(b'', await ptcareader.read(1))
  423. self.assertTrue(ptcareader.at_eof())
  424. self.assertEqual([ 'dec', 'enc' ], await clientnf)
  425. self.assertEqual([ 'dec', 'enc' ], await servnf)