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.
 
 

1160 lines
31 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(100)
  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 time
  19. import threading
  20. import unittest
  21. _backend = default_backend()
  22. def loadprivkey(fname):
  23. with open(fname, encoding='ascii') as fp:
  24. data = fp.read().encode('ascii')
  25. key = load_pem_private_key(data, password=None, backend=default_backend())
  26. return key
  27. def loadprivkeyraw(fname):
  28. key = loadprivkey(fname)
  29. enc = serialization.Encoding.Raw
  30. privformat = serialization.PrivateFormat.Raw
  31. encalgo = serialization.NoEncryption()
  32. return key.private_bytes(encoding=enc, format=privformat, encryption_algorithm=encalgo)
  33. def loadpubkeyraw(fname):
  34. with open(fname, encoding='ascii') as fp:
  35. lines = fp.readlines()
  36. # XXX
  37. #self.assertEqual(len(lines), 1)
  38. keytype, keyvalue = lines[0].split()
  39. if keytype != 'ntun-x448':
  40. raise RuntimeError
  41. return base64.urlsafe_b64decode(keyvalue)
  42. def genkeypair():
  43. '''Generates a keypair, and returns a tuple of (public, private).
  44. They are encoded as raw bytes, and sutible for use w/ Noise.'''
  45. key = x448.X448PrivateKey.generate()
  46. enc = serialization.Encoding.Raw
  47. pubformat = serialization.PublicFormat.Raw
  48. privformat = serialization.PrivateFormat.Raw
  49. encalgo = serialization.NoEncryption()
  50. pub = key.public_key().public_bytes(encoding=enc, format=pubformat)
  51. priv = key.private_bytes(encoding=enc, format=privformat, encryption_algorithm=encalgo)
  52. return pub, priv
  53. def _makefut(obj):
  54. loop = asyncio.get_running_loop()
  55. fut = loop.create_future()
  56. fut.set_result(obj)
  57. return fut
  58. def _makeunix(path):
  59. '''Make a properly formed unix path socket string.'''
  60. return 'unix:%s' % path
  61. # Make sure any additions are reflected by tests in test_parsesockstr
  62. _allowedparameters = {
  63. 'unix': {
  64. 'path': str,
  65. },
  66. 'tcp': {
  67. 'host': str,
  68. 'port': int,
  69. },
  70. }
  71. def parsesockstr(sockstr):
  72. '''Parse a socket string to its parts.
  73. The format of sockstr is: 'proto:param=value[,param2=value2]'.
  74. If the proto has a default parameter, the value can be used
  75. directly, like: 'proto:value'. This is only allowed when the
  76. value can unambiguously be determined not to be a param. If
  77. there needs to be an equals '=', then you MUST use the extended
  78. version.
  79. The characters that define 'param' must be all lower case ascii
  80. characters and may contain an underscore. The first character
  81. must not be an underscore.
  82. Supported protocols:
  83. unix:
  84. Default parameter is path.
  85. The path parameter specifies the path to the
  86. unix domain socket. The path MUST start w/ a
  87. slash if it is used as a default parameter.
  88. tcp:
  89. Default parameter is host[:port].
  90. The host parameter specifies the host, and the
  91. port parameter specifies the port of the
  92. connection.
  93. '''
  94. proto, rem = sockstr.split(':', 1)
  95. if '=' not in rem:
  96. if proto == 'unix' and rem[0] != '/':
  97. raise ValueError('bare path MUST start w/ a slash (/).')
  98. if proto == 'unix':
  99. args = { 'path': rem }
  100. else:
  101. args = dict(i.split('=', 1) for i in rem.split(','))
  102. try:
  103. allowed = _allowedparameters[proto]
  104. except KeyError:
  105. raise ValueError('unsupported proto: %s' % repr(proto))
  106. extrakeys = args.keys() - allowed.keys()
  107. if extrakeys:
  108. raise ValueError('keys for proto %s not allowed: %s' % (repr(proto), extrakeys))
  109. for i in args:
  110. args[i] = allowed[i](args[i])
  111. return proto, args
  112. async def connectsockstr(sockstr):
  113. '''Wrapper for asyncio.open_*_connection.'''
  114. proto, args = parsesockstr(sockstr)
  115. if proto == 'unix':
  116. fun = asyncio.open_unix_connection
  117. elif proto == 'tcp':
  118. fun = asyncio.open_connection
  119. reader, writer = await fun(**args)
  120. return reader, writer
  121. async def listensockstr(sockstr, cb):
  122. '''Wrapper for asyncio.start_x_server.
  123. For the format of sockstr, please see parsesockstr.
  124. The cb parameter is passed to asyncio's start_server or related
  125. calls. Per those docs, the cb parameter is calls or scheduled
  126. as a task when a client establishes a connection. It is called
  127. with two arguments, the reader and writer streams. For more
  128. information, see: https://docs.python.org/3/library/asyncio-stream.html#asyncio.start_server
  129. '''
  130. proto, args = parsesockstr(sockstr)
  131. if proto == 'unix':
  132. fun = asyncio.start_unix_server
  133. elif proto == 'tcp':
  134. fun = asyncio.start_server
  135. return await fun(cb, **args)
  136. # !!python makemessagelengths.py
  137. _handshakelens = \
  138. [72, 72, 88]
  139. def _genciphfun(hash, ad):
  140. hkdf = HKDF(algorithm=hashes.SHA256(), length=32,
  141. salt=b'asdoifjsldkjdsf', info=ad, backend=_backend)
  142. key = hkdf.derive(hash)
  143. cipher = Cipher(algorithms.AES(key), modes.ECB(),
  144. backend=_backend)
  145. enctor = cipher.encryptor()
  146. def encfun(data):
  147. # Returns the two bytes for length
  148. val = len(data)
  149. encbytes = enctor.update(data[:16])
  150. mask = int.from_bytes(encbytes[:2], byteorder='big') & 0xff
  151. return (val ^ mask).to_bytes(length=2, byteorder='big')
  152. def decfun(data):
  153. # takes off the data and returns the total
  154. # length
  155. val = int.from_bytes(data[:2], byteorder='big')
  156. encbytes = enctor.update(data[2:2 + 16])
  157. mask = int.from_bytes(encbytes[:2], byteorder='big') & 0xff
  158. return val ^ mask
  159. return encfun, decfun
  160. async def NoiseForwarder(mode, encrdrwrr, ptpairfun, priv_key, pub_key=None):
  161. '''A function that forwards data between the plain text pair of
  162. streams to the encrypted session.
  163. The mode paramater must be one of 'init' or 'resp' for initiator
  164. and responder.
  165. The encrdrwrr is an await object that will return a tunle of the
  166. reader and writer streams for the encrypted side of the
  167. connection.
  168. The ptpairfun parameter is a function that will be passed the
  169. public key bytes for the remote client. This can be used to
  170. both validate that the correct client is connecting, and to
  171. pass back the correct plain text reader/writer objects that
  172. match the provided static key. The function must be an async
  173. function.
  174. In the case of the initiator, pub_key must be provided and will
  175. be used to authenticate the responder side of the connection.
  176. The priv_key parameter is used to authenticate this side of the
  177. session.
  178. Both priv_key and pub_key parameters must be 56 bytes. For example,
  179. the pair that is returned by genkeypair.
  180. '''
  181. rdr, wrr = await encrdrwrr
  182. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  183. proto.set_keypair_from_private_bytes(Keypair.STATIC, priv_key)
  184. if pub_key is not None:
  185. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC,
  186. pub_key)
  187. if mode == 'resp':
  188. proto.set_as_responder()
  189. proto.start_handshake()
  190. proto.read_message(await rdr.readexactly(_handshakelens[0]))
  191. wrr.write(proto.write_message())
  192. proto.read_message(await rdr.readexactly(_handshakelens[2]))
  193. elif mode == 'init':
  194. proto.set_as_initiator()
  195. proto.start_handshake()
  196. wrr.write(proto.write_message())
  197. proto.read_message(await rdr.readexactly(_handshakelens[1]))
  198. wrr.write(proto.write_message())
  199. if not proto.handshake_finished: # pragma: no cover
  200. raise RuntimeError('failed to finish handshake')
  201. try:
  202. reader, writer = await ptpairfun(getattr(proto.get_keypair(
  203. Keypair.REMOTE_STATIC), 'public_bytes', None))
  204. except:
  205. wrr.close()
  206. raise
  207. # generate the keys for lengths
  208. # XXX - get_handshake_hash is probably not the best option, but
  209. # this is only to obscure lengths, it is not required to be secure
  210. # as the underlying NoiseProtocol securely validates everything.
  211. # It is marginally useful as writing patterns likely expose the
  212. # true length. Adding padding could marginally help w/ this.
  213. if mode == 'resp':
  214. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toresp')
  215. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toinit')
  216. elif mode == 'init':
  217. enclenfun, _ = _genciphfun(proto.get_handshake_hash(), b'toresp')
  218. _, declenfun = _genciphfun(proto.get_handshake_hash(), b'toinit')
  219. async def decses():
  220. try:
  221. while True:
  222. try:
  223. msg = await rdr.readexactly(2 + 16)
  224. except asyncio.streams.IncompleteReadError:
  225. if rdr.at_eof():
  226. return 'dec'
  227. tlen = declenfun(msg)
  228. rmsg = await rdr.readexactly(tlen - 16)
  229. tmsg = msg[2:] + rmsg
  230. writer.write(proto.decrypt(tmsg))
  231. await writer.drain()
  232. #except:
  233. # import traceback
  234. # traceback.print_exc()
  235. # raise
  236. finally:
  237. try:
  238. writer.write_eof()
  239. except OSError as e:
  240. if e.errno != 57:
  241. raise
  242. async def encses():
  243. try:
  244. while True:
  245. # largest message
  246. ptmsg = await reader.read(65535 - 16)
  247. if not ptmsg:
  248. # eof
  249. return 'enc'
  250. encmsg = proto.encrypt(ptmsg)
  251. wrr.write(enclenfun(encmsg))
  252. wrr.write(encmsg)
  253. await wrr.drain()
  254. #except:
  255. # import traceback
  256. # traceback.print_exc()
  257. # raise
  258. finally:
  259. wrr.write_eof()
  260. res = await asyncio.gather(decses(), encses())
  261. await wrr.drain() # not sure if needed
  262. wrr.close()
  263. await writer.drain() # not sure if needed
  264. writer.close()
  265. return res
  266. # https://stackoverflow.com/questions/23033939/how-to-test-python-3-4-asyncio-code
  267. # Slightly modified to timeout and to print trace back when canceled.
  268. # This makes it easier to figure out what "froze".
  269. def async_test(f):
  270. def wrapper(*args, **kwargs):
  271. async def tbcapture():
  272. try:
  273. return await f(*args, **kwargs)
  274. except asyncio.CancelledError as e:
  275. # if we are going to be cancelled, print out a tb
  276. import traceback
  277. traceback.print_exc()
  278. raise
  279. loop = asyncio.get_event_loop()
  280. # timeout after 4 seconds
  281. loop.run_until_complete(asyncio.wait_for(tbcapture(), 4))
  282. return wrapper
  283. class Tests_misc(unittest.TestCase):
  284. def setUp(self):
  285. # setup temporary directory
  286. d = os.path.realpath(tempfile.mkdtemp())
  287. self.basetempdir = d
  288. self.tempdir = os.path.join(d, 'subdir')
  289. os.mkdir(self.tempdir)
  290. os.chdir(self.tempdir)
  291. def tearDown(self):
  292. #print('td:', time.time())
  293. shutil.rmtree(self.basetempdir)
  294. self.tempdir = None
  295. def test_parsesockstr_bad(self):
  296. badstrs = [
  297. 'unix:ff',
  298. 'randomnocolon',
  299. 'unix:somethingelse=bogus',
  300. 'tcp:port=bogus',
  301. ]
  302. for i in badstrs:
  303. with self.assertRaises(ValueError,
  304. msg='Should have failed processing: %s' % repr(i)):
  305. parsesockstr(i)
  306. def test_parsesockstr(self):
  307. results = {
  308. # Not all of these are valid when passed to a *sockstr
  309. # function
  310. 'unix:/apath': ('unix', { 'path': '/apath' }),
  311. 'unix:path=apath': ('unix', { 'path': 'apath' }),
  312. 'tcp:host=apath': ('tcp', { 'host': 'apath' }),
  313. 'tcp:host=apath,port=5': ('tcp', { 'host': 'apath',
  314. 'port': 5 }),
  315. }
  316. for s, r in results.items():
  317. self.assertEqual(parsesockstr(s), r)
  318. @async_test
  319. async def test_listensockstr_bad(self):
  320. with self.assertRaises(ValueError):
  321. ls = await listensockstr('bogus:some=arg', None)
  322. with self.assertRaises(ValueError):
  323. ls = await connectsockstr('bogus:some=arg')
  324. @async_test
  325. async def test_listenconnectsockstr(self):
  326. msgsent = b'this is a test message'
  327. msgrcv = b'testing message for receive'
  328. # That when a connection is received and receives and sends
  329. async def servconfhandle(rdr, wrr):
  330. msg = await rdr.readexactly(len(msgsent))
  331. self.assertEqual(msg, msgsent)
  332. #print(repr(wrr.get_extra_info('sockname')))
  333. wrr.write(msgrcv)
  334. await wrr.drain()
  335. wrr.close()
  336. return True
  337. # Test listensockstr
  338. for sstr, confun in [
  339. ('unix:path=ff', lambda: asyncio.open_unix_connection(path='ff')),
  340. ('tcp:port=9384', lambda: asyncio.open_connection(port=9384))
  341. ]:
  342. # that listensockstr will bind to the correct path, can call cb
  343. ls = await listensockstr(sstr, servconfhandle)
  344. # that we open a connection to the path
  345. rdr, wrr = await confun()
  346. # and send a message
  347. wrr.write(msgsent)
  348. # and receive the message
  349. rcv = await asyncio.wait_for(rdr.readexactly(len(msgrcv)), .5)
  350. self.assertEqual(rcv, msgrcv)
  351. wrr.close()
  352. # Now test that connectsockstr works similarly.
  353. rdr, wrr = await connectsockstr(sstr)
  354. # and send a message
  355. wrr.write(msgsent)
  356. # and receive the message
  357. rcv = await asyncio.wait_for(rdr.readexactly(len(msgrcv)), .5)
  358. self.assertEqual(rcv, msgrcv)
  359. wrr.close()
  360. ls.close()
  361. await ls.wait_closed()
  362. def test_genciphfun(self):
  363. enc, dec = _genciphfun(b'0' * 32, b'foobar')
  364. msg = b'this is a bunch of data'
  365. tb = enc(msg)
  366. self.assertEqual(len(msg), dec(tb + msg))
  367. for i in [ 20, 1384, 64000, 23839, 65535 ]:
  368. msg = os.urandom(i)
  369. self.assertEqual(len(msg), dec(enc(msg) + msg))
  370. def cmd_client(args):
  371. privkey = loadprivkeyraw(args.clientkey)
  372. pubkey = loadpubkeyraw(args.servkey)
  373. async def runnf(rdr, wrr):
  374. encpair = asyncio.create_task(connectsockstr(args.clienttarget))
  375. a = await NoiseForwarder('init',
  376. encpair, lambda x: _makefut((rdr, wrr)),
  377. priv_key=privkey, pub_key=pubkey)
  378. # Setup client listener
  379. ssock = listensockstr(args.clientlisten, runnf)
  380. loop = asyncio.get_event_loop()
  381. obj = loop.run_until_complete(ssock)
  382. loop.run_until_complete(obj.serve_forever())
  383. def cmd_server(args):
  384. privkey = loadprivkeyraw(args.servkey)
  385. pubkeys = [ loadpubkeyraw(x) for x in args.clientkey ]
  386. async def runnf(rdr, wrr):
  387. async def checkclientfun(clientkey):
  388. if clientkey not in pubkeys:
  389. raise RuntimeError('invalid key provided')
  390. return await connectsockstr(args.servtarget)
  391. a = await NoiseForwarder('resp', _makefut((rdr, wrr)),
  392. checkclientfun, priv_key=privkey)
  393. # Setup server listener
  394. ssock = listensockstr(args.servlisten, runnf)
  395. loop = asyncio.get_event_loop()
  396. obj = loop.run_until_complete(ssock)
  397. loop.run_until_complete(obj.serve_forever())
  398. def cmd_genkey(args):
  399. keypair = genkeypair()
  400. key = x448.X448PrivateKey.generate()
  401. # public key part
  402. enc = serialization.Encoding.Raw
  403. pubformat = serialization.PublicFormat.Raw
  404. pub = key.public_key().public_bytes(encoding=enc, format=pubformat)
  405. try:
  406. fname = args.fname + '.pub'
  407. with open(fname, 'x', encoding='ascii') as fp:
  408. print('ntun-x448', base64.urlsafe_b64encode(pub).decode('ascii'), file=fp)
  409. except FileExistsError:
  410. print('failed to create %s, file exists.' % fname, file=sys.stderr)
  411. sys.exit(2)
  412. enc = serialization.Encoding.PEM
  413. format = serialization.PrivateFormat.PKCS8
  414. encalgo = serialization.NoEncryption()
  415. with open(args.fname, 'x', encoding='ascii') as fp:
  416. fp.write(key.private_bytes(encoding=enc, format=format, encryption_algorithm=encalgo).decode('ascii'))
  417. def main():
  418. parser = argparse.ArgumentParser()
  419. subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands', help='additional help')
  420. parser_gk = subparsers.add_parser('genkey', help='generate keys')
  421. parser_gk.add_argument('fname', type=str, help='file name for the key')
  422. parser_gk.set_defaults(func=cmd_genkey)
  423. parser_serv = subparsers.add_parser('server', help='run a server')
  424. parser_serv.add_argument('--clientkey', '-c', action='append', type=str, help='file of authorized client keys, or a .pub file')
  425. parser_serv.add_argument('servkey', type=str, help='file name for the server key')
  426. parser_serv.add_argument('servlisten', type=str, help='Connection that the server listens on')
  427. parser_serv.add_argument('servtarget', type=str, help='Connection that the server connects to')
  428. parser_serv.set_defaults(func=cmd_server)
  429. parser_client = subparsers.add_parser('client', help='run a client')
  430. parser_client.add_argument('clientkey', type=str, help='file name for the client private key')
  431. parser_client.add_argument('servkey', type=str, help='file name for the server public key')
  432. parser_client.add_argument('clientlisten', type=str, help='Connection that the client listens on')
  433. parser_client.add_argument('clienttarget', type=str, help='Connection that the client connects to')
  434. parser_client.set_defaults(func=cmd_client)
  435. args = parser.parse_args()
  436. try:
  437. fun = args.func
  438. except AttributeError:
  439. parser.print_usage()
  440. sys.exit(5)
  441. fun(args)
  442. if __name__ == '__main__': # pragma: no cover
  443. main()
  444. def _asyncsockpair():
  445. '''Create a pair of sockets that are bound to each other.
  446. The function will return a tuple of two coroutine's, that
  447. each, when await'ed upon, will return the reader/writer pair.'''
  448. socka, sockb = socket.socketpair()
  449. return asyncio.open_connection(sock=socka), \
  450. asyncio.open_connection(sock=sockb)
  451. async def _awaitfile(fname):
  452. while not os.path.exists(fname):
  453. await asyncio.sleep(.01)
  454. return True
  455. class TestMain(unittest.TestCase):
  456. def setUp(self):
  457. # setup temporary directory
  458. d = os.path.realpath(tempfile.mkdtemp())
  459. self.basetempdir = d
  460. self.tempdir = os.path.join(d, 'subdir')
  461. os.mkdir(self.tempdir)
  462. # Generate key pairs
  463. self.server_key_pair = genkeypair()
  464. self.client_key_pair = genkeypair()
  465. os.chdir(self.tempdir)
  466. def tearDown(self):
  467. #print('td:', time.time())
  468. shutil.rmtree(self.basetempdir)
  469. self.tempdir = None
  470. @async_test
  471. async def test_noargs(self):
  472. proc = await self.run_with_args()
  473. await proc.wait()
  474. # XXX - not checking error message
  475. # And that it exited w/ the correct code
  476. self.assertEqual(proc.returncode, 5)
  477. def run_with_args(self, *args, pipes=True):
  478. kwargs = {}
  479. if pipes:
  480. kwargs.update(dict(
  481. stdout=asyncio.subprocess.PIPE,
  482. stderr=asyncio.subprocess.PIPE))
  483. return asyncio.create_subprocess_exec(sys.executable,
  484. # XXX - figure out how to add coverage data on these runs
  485. #'-m', 'coverage', 'run', '-p',
  486. __file__, *args, **kwargs)
  487. async def genkey(self, name):
  488. proc = await self.run_with_args('genkey', name, pipes=False)
  489. await proc.wait()
  490. self.assertEqual(proc.returncode, 0)
  491. @async_test
  492. async def test_loadpubkey(self):
  493. keypath = os.path.join(self.tempdir, 'loadpubkeytest')
  494. await self.genkey(keypath)
  495. privkey = loadprivkey(keypath)
  496. enc = serialization.Encoding.Raw
  497. pubformat = serialization.PublicFormat.Raw
  498. pubkeybytes = privkey.public_key().public_bytes(encoding=enc, format=pubformat)
  499. pubkey = loadpubkeyraw(keypath + '.pub')
  500. self.assertEqual(pubkeybytes, pubkey)
  501. privrawkey = loadprivkeyraw(keypath)
  502. enc = serialization.Encoding.Raw
  503. privformat = serialization.PrivateFormat.Raw
  504. encalgo = serialization.NoEncryption()
  505. rprivrawkey = privkey.private_bytes(encoding=enc, format=privformat, encryption_algorithm=encalgo)
  506. self.assertEqual(rprivrawkey, privrawkey)
  507. @async_test
  508. async def test_clientkeymismatch(self):
  509. # make sure that if there's a client key mismatch, we
  510. # don't connect
  511. # Generate necessar keys
  512. servkeypath = os.path.join(self.tempdir, 'server_key')
  513. await self.genkey(servkeypath)
  514. clientkeypath = os.path.join(self.tempdir, 'client_key')
  515. await self.genkey(clientkeypath)
  516. badclientkeypath = os.path.join(self.tempdir, 'badclient_key')
  517. await self.genkey(badclientkeypath)
  518. # forwards connectsion to this socket (created by client)
  519. ptclientpath = os.path.join(self.tempdir, 'incclient.sock')
  520. ptclientstr = _makeunix(ptclientpath)
  521. # this is the socket server listen to
  522. incservpath = os.path.join(self.tempdir, 'incserv.sock')
  523. incservstr = _makeunix(incservpath)
  524. # to this socket, opened by server
  525. servtargpath = os.path.join(self.tempdir, 'servtarget.sock')
  526. servtargstr = _makeunix(servtargpath)
  527. # Setup server target listener
  528. ptsockevent = asyncio.Event()
  529. # Bind to pt listener
  530. lsock = await listensockstr(servtargstr, None)
  531. # Startup the server
  532. server = await self.run_with_args('server',
  533. '-c', clientkeypath + '.pub',
  534. servkeypath, incservstr, servtargstr)
  535. # Startup the client with the "bad" key
  536. client = await self.run_with_args('client',
  537. badclientkeypath, servkeypath + '.pub', ptclientstr, incservstr)
  538. # wait for server target to be created
  539. await _awaitfile(servtargpath)
  540. # wait for server to start
  541. await _awaitfile(incservpath)
  542. # wait for client to start
  543. await _awaitfile(ptclientpath)
  544. # Connect to the client
  545. reader, writer = await connectsockstr(ptclientstr)
  546. # XXX - this might not be the best test.
  547. with self.assertRaises(asyncio.futures.TimeoutError):
  548. # make sure that we don't get the conenction
  549. await asyncio.wait_for(ptsockevent.wait(), .5)
  550. writer.close()
  551. # Make sure that when the server is terminated
  552. server.terminate()
  553. # that it's stderr
  554. stdout, stderr = await server.communicate()
  555. #print('s:', repr((stdout, stderr)))
  556. # doesn't have an exceptions never retrieved
  557. # even the example echo server has this same leak
  558. #self.assertNotIn(b'Task exception was never retrieved', stderr)
  559. lsock.close()
  560. await lsock.wait_closed()
  561. @async_test
  562. async def test_end2end(self):
  563. # Generate necessar keys
  564. servkeypath = os.path.join(self.tempdir, 'server_key')
  565. await self.genkey(servkeypath)
  566. clientkeypath = os.path.join(self.tempdir, 'client_key')
  567. await self.genkey(clientkeypath)
  568. # forwards connectsion to this socket (created by client)
  569. ptclientpath = os.path.join(self.tempdir, 'incclient.sock')
  570. ptclientstr = _makeunix(ptclientpath)
  571. # this is the socket server listen to
  572. incservpath = os.path.join(self.tempdir, 'incserv.sock')
  573. incservstr = _makeunix(incservpath)
  574. # to this socket, opened by server
  575. servtargpath = os.path.join(self.tempdir, 'servtarget.sock')
  576. servtargstr = _makeunix(servtargpath)
  577. # Setup server target listener
  578. ptsock = []
  579. ptsockevent = asyncio.Event()
  580. def ptsockaccept(reader, writer, ptsock=ptsock):
  581. ptsock.append((reader, writer))
  582. ptsockevent.set()
  583. # Bind to pt listener
  584. lsock = await listensockstr(servtargstr, ptsockaccept)
  585. # Startup the server
  586. server = await self.run_with_args('server',
  587. '-c', clientkeypath + '.pub',
  588. servkeypath, incservstr, servtargstr,
  589. pipes=False)
  590. # Startup the client
  591. client = await self.run_with_args('client',
  592. clientkeypath, servkeypath + '.pub', ptclientstr, incservstr,
  593. pipes=False)
  594. # wait for server target to be created
  595. await _awaitfile(servtargpath)
  596. # wait for server to start
  597. await _awaitfile(incservpath)
  598. # wait for client to start
  599. await _awaitfile(ptclientpath)
  600. # Connect to the client
  601. reader, writer = await connectsockstr(ptclientstr)
  602. # send a message
  603. ptmsg = b'this is a message for testing'
  604. writer.write(ptmsg)
  605. # make sure that we got the conenction
  606. await ptsockevent.wait()
  607. # get the connection
  608. endrdr, endwrr = ptsock[0]
  609. # make sure we can read back what we sent
  610. self.assertEqual(ptmsg, await endrdr.readexactly(len(ptmsg)))
  611. # test some additional messages
  612. for i in [ 129, 1287, 28792, 129872 ]:
  613. # in on direction
  614. msg = os.urandom(i)
  615. writer.write(msg)
  616. self.assertEqual(msg, await endrdr.readexactly(len(msg)))
  617. # and the other
  618. endwrr.write(msg)
  619. self.assertEqual(msg, await reader.readexactly(len(msg)))
  620. writer.close()
  621. endwrr.close()
  622. lsock.close()
  623. await lsock.wait_closed()
  624. @async_test
  625. async def test_genkey(self):
  626. # that it can generate a key
  627. proc = await self.run_with_args('genkey', 'somefile')
  628. await proc.wait()
  629. #print(await proc.communicate())
  630. self.assertEqual(proc.returncode, 0)
  631. with open('somefile.pub', encoding='ascii') as fp:
  632. lines = fp.readlines()
  633. self.assertEqual(len(lines), 1)
  634. keytype, keyvalue = lines[0].split()
  635. self.assertEqual(keytype, 'ntun-x448')
  636. key = x448.X448PublicKey.from_public_bytes(base64.urlsafe_b64decode(keyvalue))
  637. key = loadprivkey('somefile')
  638. self.assertIsInstance(key, x448.X448PrivateKey)
  639. # that a second call fails
  640. proc = await self.run_with_args('genkey', 'somefile')
  641. await proc.wait()
  642. stdoutdata, stderrdata = await proc.communicate()
  643. self.assertFalse(stdoutdata)
  644. self.assertEqual(b'failed to create somefile.pub, file exists.\n', stderrdata)
  645. # And that it exited w/ the correct code
  646. self.assertEqual(proc.returncode, 2)
  647. class TestNoiseFowarder(unittest.TestCase):
  648. def setUp(self):
  649. # setup temporary directory
  650. d = os.path.realpath(tempfile.mkdtemp())
  651. self.basetempdir = d
  652. self.tempdir = os.path.join(d, 'subdir')
  653. os.mkdir(self.tempdir)
  654. # Generate key pairs
  655. self.server_key_pair = genkeypair()
  656. self.client_key_pair = genkeypair()
  657. def tearDown(self):
  658. shutil.rmtree(self.basetempdir)
  659. self.tempdir = None
  660. @async_test
  661. async def test_clientkeymissmatch(self):
  662. # generate a key that is incorrect
  663. wrongclient_key_pair = genkeypair()
  664. # the secure socket
  665. clssockapair, clssockbpair = _asyncsockpair()
  666. reader, writer = await clssockapair
  667. async def wrongkey(v):
  668. raise ValueError('no key matches')
  669. # create the server
  670. servnf = asyncio.create_task(NoiseForwarder('resp',
  671. clssockbpair, wrongkey,
  672. priv_key=self.server_key_pair[1]))
  673. # Create client
  674. proto = NoiseConnection.from_name(
  675. b'Noise_XK_448_ChaChaPoly_SHA256')
  676. proto.set_as_initiator()
  677. # Setup wrong client key
  678. proto.set_keypair_from_private_bytes(Keypair.STATIC,
  679. wrongclient_key_pair[1])
  680. # but the correct server key
  681. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC,
  682. self.server_key_pair[0])
  683. proto.start_handshake()
  684. # Send first message
  685. message = proto.write_message()
  686. self.assertEqual(len(message), _handshakelens[0])
  687. writer.write(message)
  688. # Get response
  689. respmsg = await reader.readexactly(_handshakelens[1])
  690. proto.read_message(respmsg)
  691. # Send final reply
  692. message = proto.write_message()
  693. writer.write(message)
  694. # Make sure handshake has completed
  695. self.assertTrue(proto.handshake_finished)
  696. with self.assertRaises(ValueError):
  697. await servnf
  698. writer.close()
  699. @async_test
  700. async def test_server(self):
  701. # Test is plumbed:
  702. # (reader, writer) -> servsock ->
  703. # (rdr, wrr) NoiseForward (reader, writer) ->
  704. # servptsock -> (ptsock[0], ptsock[1])
  705. # Path that the server will sit on
  706. servsockpath = os.path.join(self.tempdir, 'servsock')
  707. servarg = _makeunix(servsockpath)
  708. # Path that the server will send pt data to
  709. servptpath = os.path.join(self.tempdir, 'servptsock')
  710. # Setup pt target listener
  711. pttarg = _makeunix(servptpath)
  712. ptsock = []
  713. ptsockevent = asyncio.Event()
  714. def ptsockaccept(reader, writer, ptsock=ptsock):
  715. ptsock.append((reader, writer))
  716. ptsockevent.set()
  717. # Bind to pt listener
  718. lsock = await listensockstr(pttarg, ptsockaccept)
  719. nfs = []
  720. event = asyncio.Event()
  721. async def runnf(rdr, wrr):
  722. ptpairfun = asyncio.create_task(connectsockstr(pttarg))
  723. a = await NoiseForwarder('resp',
  724. _makefut((rdr, wrr)), lambda x: ptpairfun,
  725. priv_key=self.server_key_pair[1])
  726. nfs.append(a)
  727. event.set()
  728. # Setup server listener
  729. ssock = await listensockstr(servarg, runnf)
  730. # Connect to server
  731. reader, writer = await connectsockstr(servarg)
  732. # Create client
  733. proto = NoiseConnection.from_name(b'Noise_XK_448_ChaChaPoly_SHA256')
  734. proto.set_as_initiator()
  735. # Setup required keys
  736. proto.set_keypair_from_private_bytes(Keypair.STATIC,
  737. self.client_key_pair[1])
  738. proto.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC,
  739. self.server_key_pair[0])
  740. proto.start_handshake()
  741. # Send first message
  742. message = proto.write_message()
  743. self.assertEqual(len(message), _handshakelens[0])
  744. writer.write(message)
  745. # Get response
  746. respmsg = await reader.readexactly(_handshakelens[1])
  747. proto.read_message(respmsg)
  748. # Send final reply
  749. message = proto.write_message()
  750. writer.write(message)
  751. # Make sure handshake has completed
  752. self.assertTrue(proto.handshake_finished)
  753. # generate the keys for lengths
  754. enclenfun, _ = _genciphfun(proto.get_handshake_hash(),
  755. b'toresp')
  756. _, declenfun = _genciphfun(proto.get_handshake_hash(),
  757. b'toinit')
  758. # write a test message
  759. ptmsg = b'this is a test message that should be a little in length'
  760. encmsg = proto.encrypt(ptmsg)
  761. writer.write(enclenfun(encmsg))
  762. writer.write(encmsg)
  763. # wait for the connection to arrive
  764. await ptsockevent.wait()
  765. ptreader, ptwriter = ptsock[0]
  766. # read the test message
  767. rptmsg = await ptreader.readexactly(len(ptmsg))
  768. self.assertEqual(rptmsg, ptmsg)
  769. # write a different message
  770. ptmsg = os.urandom(2843)
  771. encmsg = proto.encrypt(ptmsg)
  772. writer.write(enclenfun(encmsg))
  773. writer.write(encmsg)
  774. # read the test message
  775. rptmsg = await ptreader.readexactly(len(ptmsg))
  776. self.assertEqual(rptmsg, ptmsg)
  777. # now try the other way
  778. ptmsg = os.urandom(912)
  779. ptwriter.write(ptmsg)
  780. # find out how much we need to read
  781. encmsg = await reader.readexactly(2 + 16)
  782. tlen = declenfun(encmsg)
  783. # read the rest of the message
  784. rencmsg = await reader.readexactly(tlen - 16)
  785. tmsg = encmsg[2:] + rencmsg
  786. rptmsg = proto.decrypt(tmsg)
  787. self.assertEqual(rptmsg, ptmsg)
  788. # shut down sending
  789. writer.write_eof()
  790. # so pt reader should be shut down
  791. self.assertEqual(b'', await ptreader.read(1))
  792. self.assertTrue(ptreader.at_eof())
  793. # shut down pt
  794. ptwriter.write_eof()
  795. # make sure the enc reader is eof
  796. self.assertEqual(b'', await reader.read(1))
  797. self.assertTrue(reader.at_eof())
  798. await event.wait()
  799. self.assertEqual(nfs[0], [ 'dec', 'enc' ])
  800. writer.close()
  801. ptwriter.close()
  802. lsock.close()
  803. ssock.close()
  804. await lsock.wait_closed()
  805. await ssock.wait_closed()
  806. @async_test
  807. async def test_serverclient(self):
  808. # plumbing:
  809. #
  810. # ptca -> ptcb NF client clsa -> clsb NF server ptsa -> ptsb
  811. #
  812. ptcsockapair, ptcsockbpair = _asyncsockpair()
  813. ptcareader, ptcawriter = await ptcsockapair
  814. #ptcsockbpair passed directly
  815. clssockapair, clssockbpair = _asyncsockpair()
  816. #both passed directly
  817. ptssockapair, ptssockbpair = _asyncsockpair()
  818. #ptssockapair passed directly
  819. ptsbreader, ptsbwriter = await ptssockbpair
  820. async def validateclientkey(pubkey):
  821. self.assertEqual(pubkey, self.client_key_pair[0])
  822. return await ptssockapair
  823. clientnf = asyncio.create_task(NoiseForwarder('init',
  824. clssockapair, lambda x: ptcsockbpair,
  825. priv_key=self.client_key_pair[1],
  826. pub_key=self.server_key_pair[0]))
  827. servnf = asyncio.create_task(NoiseForwarder('resp',
  828. clssockbpair, validateclientkey,
  829. priv_key=self.server_key_pair[1]))
  830. # send a message
  831. msga = os.urandom(183)
  832. ptcawriter.write(msga)
  833. # make sure we get the same message
  834. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  835. # send a second message
  836. msga = os.urandom(2834)
  837. ptcawriter.write(msga)
  838. # make sure we get the same message
  839. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  840. # send a message larger than the block size
  841. msga = os.urandom(103958)
  842. ptcawriter.write(msga)
  843. # make sure we get the same message
  844. self.assertEqual(msga, await ptsbreader.readexactly(len(msga)))
  845. # send a message the other direction
  846. msga = os.urandom(103958)
  847. ptsbwriter.write(msga)
  848. # make sure we get the same message
  849. self.assertEqual(msga, await ptcareader.readexactly(len(msga)))
  850. # close down the pt writers, the rest should follow
  851. ptsbwriter.write_eof()
  852. ptcawriter.write_eof()
  853. # make sure they are closed, and there is no more data
  854. self.assertEqual(b'', await ptsbreader.read(1))
  855. self.assertTrue(ptsbreader.at_eof())
  856. self.assertEqual(b'', await ptcareader.read(1))
  857. self.assertTrue(ptcareader.at_eof())
  858. self.assertEqual([ 'dec', 'enc' ], await clientnf)
  859. self.assertEqual([ 'dec', 'enc' ], await servnf)
  860. await ptsbwriter.drain()
  861. await ptcawriter.drain()
  862. ptsbwriter.close()
  863. ptcawriter.close()