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.
 
 

592 lines
16 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. @async_test
  240. async def test_noargs(self):
  241. proc = await self.run_with_args()
  242. await proc.wait()
  243. # XXX - not checking error message
  244. # And that it exited w/ the correct code
  245. self.assertEqual(proc.returncode, 5)
  246. def run_with_args(self, *args):
  247. return asyncio.create_subprocess_exec(sys.executable,
  248. __file__, *args,
  249. stdout=asyncio.subprocess.PIPE,
  250. stderr=asyncio.subprocess.PIPE)
  251. def test_both(self):
  252. pass
  253. @async_test
  254. async def test_genkey(self):
  255. # that it can generate a key
  256. proc = await self.run_with_args('genkey', 'somefile')
  257. await proc.wait()
  258. self.assertEqual(proc.returncode, 0)
  259. with open('somefile.pub', encoding='ascii') as fp:
  260. lines = fp.readlines()
  261. self.assertEqual(len(lines), 1)
  262. keytype, keyvalue = lines[0].split()
  263. self.assertEqual(keytype, 'ntun-x448')
  264. key = x448.X448PublicKey.from_public_bytes(base64.urlsafe_b64decode(keyvalue))
  265. with open('somefile', encoding='ascii') as fp:
  266. data = fp.read().encode('ascii')
  267. key = load_pem_private_key(data, password=None, backend=default_backend())
  268. self.assertIsInstance(key, x448.X448PrivateKey)
  269. # that a second call fails
  270. proc = await self.run_with_args('genkey', 'somefile')
  271. await proc.wait()
  272. stdoutdata, stderrdata = await proc.communicate()
  273. self.assertFalse(stdoutdata)
  274. self.assertEqual(b'failed to create somefile.pub, file exists.\n', stderrdata)
  275. # And that it exited w/ the correct code
  276. self.assertEqual(proc.returncode, 1)
  277. class TestNoiseFowarder(unittest.TestCase):
  278. def setUp(self):
  279. # setup temporary directory
  280. d = os.path.realpath(tempfile.mkdtemp())
  281. self.basetempdir = d
  282. self.tempdir = os.path.join(d, 'subdir')
  283. os.mkdir(self.tempdir)
  284. # Generate key pairs
  285. self.server_key_pair = genkeypair()
  286. self.client_key_pair = genkeypair()
  287. def tearDown(self):
  288. shutil.rmtree(self.basetempdir)
  289. self.tempdir = None
  290. @async_test
  291. async def test_server(self):
  292. # Test is plumbed:
  293. # (reader, writer) -> servsock ->
  294. # (rdr, wrr) NoiseForward (reader, writer) ->
  295. # servptsock -> (ptsock[0], ptsock[1])
  296. # Path that the server will sit on
  297. servsockpath = os.path.join(self.tempdir, 'servsock')
  298. servarg = _makeunix(servsockpath)
  299. # Path that the server will send pt data to
  300. servptpath = os.path.join(self.tempdir, 'servptsock')
  301. # Setup pt target listener
  302. pttarg = _makeunix(servptpath)
  303. ptsock = []
  304. def ptsockaccept(reader, writer, ptsock=ptsock):
  305. ptsock.append((reader, writer))
  306. # Bind to pt listener
  307. lsock = await listensockstr(pttarg, ptsockaccept)
  308. nfs = []
  309. event = asyncio.Event()
  310. async def runnf(rdr, wrr):
  311. ptpair = asyncio.create_task(connectsockstr(pttarg))
  312. a = await NoiseForwarder('resp',
  313. _makefut((rdr, wrr)), ptpair,
  314. priv_key=self.server_key_pair[1])
  315. nfs.append(a)
  316. event.set()
  317. # Setup server listener
  318. ssock = await listensockstr(servarg, runnf)
  319. # Connect to server
  320. reader, writer = await connectsockstr(servarg)
  321. # Create client
  322. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  323. proto.set_as_initiator()
  324. # Setup required keys
  325. proto.set_keypair_from_private_bytes(Keypair.STATIC,
  326. self.client_key_pair[1])
  327. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC,
  328. self.server_key_pair[0])
  329. proto.start_handshake()
  330. # Send first message
  331. message = proto.write_message()
  332. self.assertEqual(len(message), _handshakelens[0])
  333. writer.write(message)
  334. # Get response
  335. respmsg = await reader.readexactly(_handshakelens[1])
  336. proto.read_message(respmsg)
  337. # Send final reply
  338. message = proto.write_message()
  339. writer.write(message)
  340. # Make sure handshake has completed
  341. self.assertTrue(proto.handshake_finished)
  342. # generate the keys for lengths
  343. enclenfun, _ = _genciphfun(proto.get_handshake_hash(),
  344. b'toresp')
  345. _, declenfun = _genciphfun(proto.get_handshake_hash(),
  346. b'toinit')
  347. # write a test message
  348. ptmsg = b'this is a test message that should be a little in length'
  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. ptreader, ptwriter = ptsock[0]
  355. # read the test message
  356. rptmsg = await ptreader.readexactly(len(ptmsg))
  357. self.assertEqual(rptmsg, ptmsg)
  358. # write a different message
  359. ptmsg = os.urandom(2843)
  360. encmsg = proto.encrypt(ptmsg)
  361. writer.write(enclenfun(encmsg))
  362. writer.write(encmsg)
  363. # XXX - how to sync?
  364. await asyncio.sleep(.1)
  365. # read the test message
  366. rptmsg = await ptreader.readexactly(len(ptmsg))
  367. self.assertEqual(rptmsg, ptmsg)
  368. # now try the other way
  369. ptmsg = os.urandom(912)
  370. ptwriter.write(ptmsg)
  371. # find out how much we need to read
  372. encmsg = await reader.readexactly(2 + 16)
  373. tlen = declenfun(encmsg)
  374. # read the rest of the message
  375. rencmsg = await reader.readexactly(tlen - 16)
  376. tmsg = encmsg[2:] + rencmsg
  377. rptmsg = proto.decrypt(tmsg)
  378. self.assertEqual(rptmsg, ptmsg)
  379. # shut down sending
  380. writer.write_eof()
  381. # so pt reader should be shut down
  382. self.assertEqual(b'', await ptreader.read(1))
  383. self.assertTrue(ptreader.at_eof())
  384. # shut down pt
  385. ptwriter.write_eof()
  386. # make sure the enc reader is eof
  387. self.assertEqual(b'', await reader.read(1))
  388. self.assertTrue(reader.at_eof())
  389. await event.wait()
  390. self.assertEqual(nfs[0], [ 'dec', 'enc' ])
  391. @async_test
  392. async def test_serverclient(self):
  393. # plumbing:
  394. #
  395. # ptca -> ptcb NF client clsa -> clsb NF server ptsa -> ptsb
  396. #
  397. ptcsockapair, ptcsockbpair = _asyncsockpair()
  398. ptcareader, ptcawriter = await ptcsockapair
  399. #ptcsockbpair passed directly
  400. clssockapair, clssockbpair = _asyncsockpair()
  401. #both passed directly
  402. ptssockapair, ptssockbpair = _asyncsockpair()
  403. #ptssockapair passed directly
  404. ptsbreader, ptsbwriter = await ptssockbpair
  405. clientnf = asyncio.create_task(NoiseForwarder('init',
  406. clssockapair, ptcsockbpair,
  407. priv_key=self.client_key_pair[1],
  408. pub_key=self.server_key_pair[0]))
  409. servnf = asyncio.create_task(NoiseForwarder('resp',
  410. clssockbpair, ptssockapair,
  411. priv_key=self.server_key_pair[1]))
  412. # send a message
  413. msga = os.urandom(183)
  414. ptcawriter.write(msga)
  415. # make sure we get the same message
  416. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  417. # send a second message
  418. msga = os.urandom(2834)
  419. ptcawriter.write(msga)
  420. # make sure we get the same message
  421. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  422. # send a message larger than the block size
  423. msga = os.urandom(103958)
  424. ptcawriter.write(msga)
  425. # make sure we get the same message
  426. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  427. # send a message the other direction
  428. msga = os.urandom(103958)
  429. ptsbwriter.write(msga)
  430. # make sure we get the same message
  431. self.assertEqual(msga, await ptcareader.readexactly(len(msga)))
  432. # close down the pt writers, the rest should follow
  433. ptsbwriter.write_eof()
  434. ptcawriter.write_eof()
  435. # make sure they are closed, and there is no more data
  436. self.assertEqual(b'', await ptsbreader.read(1))
  437. self.assertTrue(ptsbreader.at_eof())
  438. self.assertEqual(b'', await ptcareader.read(1))
  439. self.assertTrue(ptcareader.at_eof())
  440. self.assertEqual([ 'dec', 'enc' ], await clientnf)
  441. self.assertEqual([ 'dec', 'enc' ], await servnf)