Implement a secure ICS protocol targeting LoRa Node151 microcontroller for controlling irrigation.
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.
 
 
 
 
 
 

1538 lines
38 KiB

  1. # Copyright 2021 John-Mark Gurney.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions
  5. # are met:
  6. # 1. Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # 2. Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. #
  12. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  13. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  15. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  16. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  17. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  18. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  19. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  20. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  21. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22. # SUCH DAMAGE.
  23. #
  24. import asyncio
  25. import codecs
  26. import contextlib
  27. import functools
  28. import itertools
  29. import os
  30. import pathlib
  31. import sys
  32. import unittest
  33. from Strobe.Strobe import Strobe, KeccakF
  34. from Strobe.Strobe import AuthenticationFailed
  35. import syote_comms
  36. from syote_comms import make_pktbuf, X25519
  37. import multicast
  38. from util import *
  39. # Response to command will be the CMD and any arguments if needed.
  40. # The command is encoded as an unsigned byte
  41. CMD_TERMINATE = 1 # no args: terminate the sesssion, reply confirms
  42. # The follow commands are queue up, but will be acknoledged when queued
  43. CMD_WAITFOR = 2 # arg: (length): waits for length seconds
  44. CMD_RUNFOR = 3 # arg: (chan, length): turns on chan for length seconds
  45. CMD_PING = 4 # arg: (): a no op command
  46. CMD_SETUNSET = 5 # arg: (chan, val): sets chan to val
  47. CMD_ADV = 6 # arg: ([cnt]): advances to the next cnt (default 1) command
  48. CMD_CLEAR = 7 # arg: (): clears all future commands, but keeps current running
  49. CMD_KEY = 8 # arg: ([key reports]): standard USB HID key reports, return is number added
  50. _directmap = [
  51. (40, '\n\x1b\b\t -=[]\\#;\'`,./'),
  52. (40, '\r'),
  53. ]
  54. _keymap = { chr(x): x - ord('a') + 4 for x in range(ord('a'), ord('z') + 1) } | \
  55. { '0': 39 } | \
  56. { chr(x): x - ord('1') + 30 for x in range(ord('1'), ord('9') + 1) } | \
  57. { x: i + base for base, keys in _directmap for i, x in enumerate(keys) }
  58. _shiftmaplist = '!1@2#3$4%5^6&7*8(9)0_-+=~`{[}]|\\:;"\'<,>.?/'
  59. _completemap = { x: (False, y) for x, y in _keymap.items() } | \
  60. { x.upper(): (True, y) for x, y in _keymap.items() if x != x.upper() } | \
  61. { x: (True, _keymap[y]) for x, y in zip(_shiftmaplist[::2], _shiftmaplist[1::2]) }
  62. def makekeybuf(s):
  63. blank = b'\x00' * 8
  64. # start clean
  65. ret = [ blank ]
  66. templ = bytearray([ 0 ] * 8)
  67. for i in s:
  68. shift, key = _completemap[i]
  69. if ret[-1][2] == key:
  70. ret.append(blank)
  71. templ[2] = key
  72. templ[0] = 2 if shift else 0
  73. ret.append(templ[:])
  74. # end clean
  75. ret.append(blank)
  76. return b''.join(ret)
  77. class LORANode(object):
  78. '''Implement a LORANode initiator.
  79. There are currently two implemented modes, one is shared, and then
  80. a shared key must be provided to the shared keyword argument.
  81. The other is ecdhe mode, which requires an X25519 key to be passed
  82. in to init_key, and the respondent's public key to be passed in to
  83. resp_pub.
  84. '''
  85. SHARED_DOMAIN = b'com.funkthat.lora.irrigation.shared.v0.0.1'
  86. ECDHE_DOMAIN = b'com.funkthat.lora.irrigation.ecdhe.v0.0.1'
  87. MAC_LEN = 8
  88. def __init__(self, syncdatagram, shared=None, init_key=None, resp_pub=None):
  89. self.sd = syncdatagram
  90. if shared is not None:
  91. self.st = Strobe(self.SHARED_DOMAIN, F=KeccakF(800))
  92. self.st.key(shared)
  93. self.start = self.shared_start
  94. elif init_key is not None and resp_pub is not None:
  95. self.st = Strobe(self.ECDHE_DOMAIN, F=KeccakF(800))
  96. self.key = init_key
  97. self.resp_pub = resp_pub
  98. self.st.key(init_key.getpub() + resp_pub)
  99. self.start = self.ecdhe_start
  100. else:
  101. raise RuntimeError('invalid combination of keys provided')
  102. async def shared_start(self):
  103. resp = await self.sendrecvvalid(os.urandom(16) + b'reqreset')
  104. self.st.ratchet()
  105. pkt = await self.sendrecvvalid(b'confirm')
  106. if pkt != b'confirmed':
  107. raise RuntimeError('got invalid response: %s' %
  108. repr(pkt))
  109. async def ecdhe_start(self):
  110. ephkey = X25519.gen()
  111. resp = await self.sendrecvvalid(ephkey.getpub() + b'reqreset',
  112. fun=lambda: self.st.key(ephkey.dh(self.resp_pub) + self.key.dh(self.resp_pub)))
  113. self.st.key(ephkey.dh(resp) + self.key.dh(resp))
  114. pkt = await self.sendrecvvalid(b'confirm')
  115. if pkt != b'confirmed':
  116. raise RuntimeError('got invalid response: %s' %
  117. repr(pkt))
  118. async def sendrecvvalid(self, msg, fun=None):
  119. msg = self.st.send_enc(msg) + self.st.send_mac(self.MAC_LEN)
  120. if fun is not None:
  121. fun()
  122. origstate = self.st.copy()
  123. while True:
  124. resp = await self.sd.sendtillrecv(msg, .50)
  125. #_debprint('got:', resp)
  126. # skip empty messages
  127. if len(resp) == 0:
  128. continue
  129. try:
  130. decmsg = self.st.recv_enc(resp[:-self.MAC_LEN])
  131. self.st.recv_mac(resp[-self.MAC_LEN:])
  132. break
  133. except AuthenticationFailed:
  134. # didn't get a valid packet, restore
  135. # state and retry
  136. #_debprint('failed')
  137. self.st.set_state_from(origstate)
  138. #_debprint('got rep:', repr(resp), repr(decmsg))
  139. return decmsg
  140. @staticmethod
  141. def _encodeargs(*args):
  142. r = []
  143. for i in args:
  144. if isinstance(i, bytes):
  145. r.append(i)
  146. else:
  147. r.append(i.to_bytes(4, byteorder='little'))
  148. return b''.join(r)
  149. async def _sendcmd(self, cmd, *args):
  150. cmdbyte = cmd.to_bytes(1, byteorder='little')
  151. resp = await self.sendrecvvalid(cmdbyte + self._encodeargs(*args))
  152. if resp[0:1] != cmdbyte:
  153. raise RuntimeError(
  154. 'response does not match, got: %s, expected: %s' %
  155. (repr(resp[0:1]), repr(cmdbyte)))
  156. r = resp[1:]
  157. if r:
  158. return r
  159. async def waitfor(self, length):
  160. return await self._sendcmd(CMD_WAITFOR, length)
  161. async def runfor(self, chan, length):
  162. return await self._sendcmd(CMD_RUNFOR, chan, length)
  163. async def setunset(self, chan, val):
  164. return await self._sendcmd(CMD_SETUNSET, chan, val)
  165. async def ping(self):
  166. return await self._sendcmd(CMD_PING)
  167. async def type(self, s):
  168. keys = makekeybuf(s)
  169. while keys:
  170. r = await self._sendcmd(CMD_KEY, keys[:8 * 6])
  171. r = int.from_bytes(r, byteorder='little')
  172. keys = keys[r * 8:]
  173. async def adv(self, cnt=None):
  174. args = ()
  175. if cnt is not None:
  176. args = (cnt, )
  177. return await self._sendcmd(CMD_ADV, *args)
  178. async def clear(self):
  179. return await self._sendcmd(CMD_CLEAR)
  180. async def terminate(self):
  181. return await self._sendcmd(CMD_TERMINATE)
  182. class SyncDatagram(object):
  183. '''Base interface for a more simple synchronous interface.'''
  184. async def recv(self, timeout=None): #pragma: no cover
  185. '''Receive a datagram. If timeout is not None, wait that many
  186. seconds, and if nothing is received in that time, raise an
  187. asyncio.TimeoutError exception.'''
  188. raise NotImplementedError
  189. async def send(self, data): #pragma: no cover
  190. raise NotImplementedError
  191. async def sendtillrecv(self, data, freq):
  192. '''Send the datagram in data, every freq seconds until a datagram
  193. is received. If timeout seconds happen w/o receiving a datagram,
  194. then raise an TimeoutError exception.'''
  195. while True:
  196. #_debprint('sending:', repr(data))
  197. await self.send(data)
  198. try:
  199. return await self.recv(freq)
  200. except asyncio.TimeoutError:
  201. pass
  202. class MulticastSyncDatagram(SyncDatagram):
  203. '''
  204. An implementation of SyncDatagram that uses the provided
  205. multicast address maddr as the source/sink of the packets.
  206. Note that once created, the start coroutine needs to be
  207. await'd before being passed to a LORANode so that everything
  208. is running.
  209. '''
  210. # Note: sent packets will be received. A similar method to
  211. # what was done in multicast.{to,from}_loragw could be done
  212. # here as well, that is passing in a set of packets to not
  213. # pass back up.
  214. def __init__(self, maddr):
  215. self.maddr = maddr
  216. self._ignpkts = set()
  217. async def start(self):
  218. self.mr = await multicast.create_multicast_receiver(self.maddr)
  219. self.mt = await multicast.create_multicast_transmitter(
  220. self.maddr)
  221. async def _recv(self):
  222. while True:
  223. pkt = await self.mr.recv()
  224. pkt = pkt[0]
  225. if pkt not in self._ignpkts:
  226. return pkt
  227. self._ignpkts.remove(pkt)
  228. async def recv(self, timeout=None): #pragma: no cover
  229. r = await asyncio.wait_for(self._recv(), timeout=timeout)
  230. return r
  231. async def send(self, data): #pragma: no cover
  232. self._ignpkts.add(bytes(data))
  233. await self.mt.send(data)
  234. def close(self):
  235. '''Shutdown communications.'''
  236. self.mr.close()
  237. self.mr = None
  238. self.mt.close()
  239. self.mt = None
  240. def listsplit(lst, item):
  241. try:
  242. idx = lst.index(item)
  243. except ValueError:
  244. return lst, []
  245. return lst[:idx], lst[idx + 1:]
  246. async def main():
  247. import argparse
  248. from loraserv import DEFAULT_MADDR as maddr
  249. parser = argparse.ArgumentParser(description='This is an implementation of both the server and client implementing syote secure IoT protocol.',
  250. epilog='Both -k and -p MUST be used together. One of either -s or the combone -k & -p MUST be specified.')
  251. parser.add_argument('-f', dest='schedfile', metavar='filename', type=str,
  252. help='Use commands from the file. One command per line.')
  253. parser.add_argument('-k', dest='privkey', metavar='privfile', type=str,
  254. help='File containing a hex encoded private key.')
  255. parser.add_argument('-p', dest='pubkey', metavar='pubfile', type=str,
  256. help='File containing a hex encoded public key.')
  257. parser.add_argument('-r', dest='client', metavar='module:function', type=str,
  258. help='Create a respondant instead of sending commands. Commands will be passed to the function.')
  259. parser.add_argument('-s', dest='shared_key', metavar='shared_key', type=str,
  260. help='File containing the shared key to use (note, any white space is included).')
  261. parser.add_argument('args', metavar='CMD_ARG', type=str, nargs='*',
  262. help='Various commands to send to the device.')
  263. args = parser.parse_args()
  264. # make sure a key is specified.
  265. if args.privkey is None and args.pubkey is None and \
  266. args.shared_key is None:
  267. parser.error('a key must be specified (either -k and -p, or -s)')
  268. # make sure if one is specified, both are.
  269. if (args.privkey is not None or args.pubkey is not None) and \
  270. (args.privkey is None or args.pubkey is None):
  271. parser.error('both -k and -p MUST be specified if one is.')
  272. if args.shared_key is not None:
  273. skdata = pathlib.Path(args.shared_key).read_bytes()
  274. lorakwargs = dict(shared_key=skdata)
  275. commsinitargs = (lorakwargs['shared_key'], )
  276. else:
  277. privkeydata = pathlib.Path(args.privkey).read_text().strip()
  278. privkey = X25519.frombytes(codecs.decode(privkeydata, 'hex'))
  279. pubkeydata = pathlib.Path(args.pubkey).read_text().strip()
  280. pubkey = codecs.decode(pubkeydata, 'hex')
  281. lorakwargs = dict(init_key=privkey, resp_pub=pubkey)
  282. commsinitargs = (None, make_pktbuf(privkey.getpriv()),
  283. make_pktbuf(pubkey))
  284. if args.client:
  285. # Run a client
  286. mr = await multicast.create_multicast_receiver(maddr)
  287. mt = await multicast.create_multicast_transmitter(maddr)
  288. from ctypes import c_uint8
  289. # seed the RNG
  290. prngseed = os.urandom(64)
  291. syote_comms.strobe_seed_prng((c_uint8 *
  292. len(prngseed))(*prngseed), len(prngseed))
  293. # Create the state for testing
  294. commstate = syote_comms.CommsState()
  295. import util_load
  296. client_func = util_load.load_application(args.client)
  297. def client_call(msg, outbuf):
  298. ret = client_func(msg._from())
  299. if len(ret) > outbuf[0].pktlen:
  300. ret = b'error, too long buffer: %d' % len(ret)
  301. outbuf[0].pktlen = min(len(ret), outbuf[0].pktlen)
  302. for i in range(outbuf[0].pktlen):
  303. outbuf[0].pkt[i] = ret[i]
  304. cb = syote_comms.process_msgfunc_t(client_call)
  305. # Initialize everything
  306. syote_comms.comms_init(commstate, cb, *commsinitargs)
  307. try:
  308. while True:
  309. pkt = await mr.recv()
  310. msg = pkt[0]
  311. #_debprint('procmsg:', repr(msg))
  312. out = syote_comms.comms_process_wrap(
  313. commstate, msg)
  314. #_debprint('resp:', repr(out))
  315. if out:
  316. await mt.send(out)
  317. finally:
  318. mr.close()
  319. mt.close()
  320. sys.exit(0)
  321. msd = MulticastSyncDatagram(maddr)
  322. await msd.start()
  323. l = LORANode(msd, **lorakwargs)
  324. await l.start()
  325. valid_cmds = {
  326. 'waitfor', 'setunset', 'runfor', 'ping', 'adv', 'clear',
  327. 'terminate', 'type',
  328. }
  329. if args.args and args.schedfile:
  330. parser.error('only one of -f or arguments can be specified.')
  331. if args.args:
  332. cmds = list(args.args)
  333. cmdargs = []
  334. while cmds:
  335. a, cmds = listsplit(cmds, '--')
  336. cmdargs.append(a)
  337. else:
  338. with open(args.schedfile) as fp:
  339. cmdargs = [ x.split() for x in fp.readlines() ]
  340. while cmdargs:
  341. cmd, *args = cmdargs.pop(0)
  342. if cmd not in valid_cmds:
  343. print('invalid command:', repr(cmd))
  344. sys.exit(1)
  345. fun = getattr(l, cmd)
  346. try:
  347. await fun(*(int(x) for x in args))
  348. except:
  349. await fun(*args)
  350. if __name__ == '__main__':
  351. asyncio.run(main())
  352. class MockSyncDatagram(SyncDatagram):
  353. '''A testing version of SyncDatagram. Define a method runner which
  354. implements part of the sequence. In the function, await on either
  355. self.get, to wait for the other side to send something, or await
  356. self.put w/ data to send.'''
  357. def __init__(self):
  358. self.sendq = asyncio.Queue()
  359. self.recvq = asyncio.Queue()
  360. self.task = asyncio.create_task(self.runner())
  361. self.get = self.sendq.get
  362. self.put = self.recvq.put
  363. async def drain(self):
  364. '''Wait for the runner thread to finish up.'''
  365. return await self.task
  366. async def runner(self): #pragma: no cover
  367. raise NotImplementedError
  368. async def recv(self, timeout=None):
  369. return await self.recvq.get()
  370. async def send(self, data):
  371. return await self.sendq.put(data)
  372. def __del__(self): #pragma: no cover
  373. if self.task is not None and not self.task.done():
  374. self.task.cancel()
  375. class TestSyncData(unittest.IsolatedAsyncioTestCase):
  376. async def test_syncsendtillrecv(self):
  377. class MySync(SyncDatagram):
  378. def __init__(self):
  379. self.sendq = []
  380. self.resp = [ asyncio.TimeoutError(), b'a' ]
  381. async def recv(self, timeout=None):
  382. assert timeout == 1
  383. r = self.resp.pop(0)
  384. if isinstance(r, Exception):
  385. raise r
  386. return r
  387. async def send(self, data):
  388. self.sendq.append(data)
  389. ms = MySync()
  390. r = await ms.sendtillrecv(b'foo', 1)
  391. self.assertEqual(r, b'a')
  392. self.assertEqual(ms.sendq, [ b'foo', b'foo' ])
  393. class AsyncSequence(object):
  394. '''
  395. Object used for sequencing async functions. To use, use the
  396. asynchronous context manager created by the sync method. For
  397. example:
  398. seq = AsyncSequence()
  399. async func1():
  400. async with seq.sync(1):
  401. second_fun()
  402. async func2():
  403. async with seq.sync(0):
  404. first_fun()
  405. This will make sure that function first_fun is run before running
  406. the function second_fun. If a previous block raises an Exception,
  407. it will be passed up, and all remaining blocks (and future ones)
  408. will raise a CancelledError to help ensure that any tasks are
  409. properly cleaned up.
  410. '''
  411. def __init__(self, positerfactory=lambda: itertools.count()):
  412. '''The argument positerfactory, is a factory that will
  413. create an iterator that will be used for the values that
  414. are passed to the sync method.'''
  415. self.positer = positerfactory()
  416. self.token = object()
  417. self.die = False
  418. self.waiting = {
  419. next(self.positer): self.token
  420. }
  421. async def simpsync(self, pos):
  422. async with self.sync(pos):
  423. pass
  424. @contextlib.asynccontextmanager
  425. async def sync(self, pos):
  426. '''An async context manager that will be run when it's
  427. turn arrives. It will only run when all the previous
  428. items in the iterator has been successfully run.'''
  429. if self.die:
  430. raise asyncio.CancelledError('seq cancelled')
  431. if pos in self.waiting:
  432. if self.waiting[pos] is not self.token:
  433. raise RuntimeError('pos already waiting!')
  434. else:
  435. fut = asyncio.Future()
  436. self.waiting[pos] = fut
  437. await fut
  438. # our time to shine!
  439. del self.waiting[pos]
  440. try:
  441. yield None
  442. except Exception as e:
  443. # if we got an exception, things went pear shaped,
  444. # shut everything down, and any future calls.
  445. #_debprint('dieing...', repr(e))
  446. self.die = True
  447. # cancel existing blocks
  448. while self.waiting:
  449. k, v = self.waiting.popitem()
  450. #_debprint('canceling: %s' % repr(k))
  451. if v is self.token:
  452. continue
  453. # for Python 3.9:
  454. # msg='pos %s raised exception: %s' %
  455. # (repr(pos), repr(e))
  456. v.cancel()
  457. # populate real exception up
  458. raise
  459. else:
  460. # handle next
  461. nextpos = next(self.positer)
  462. if nextpos in self.waiting:
  463. #_debprint('np:', repr(self), nextpos,
  464. # repr(self.waiting[nextpos]))
  465. self.waiting[nextpos].set_result(None)
  466. else:
  467. self.waiting[nextpos] = self.token
  468. class TestSequencing(unittest.IsolatedAsyncioTestCase):
  469. @timeout(2)
  470. async def test_seq_alreadywaiting(self):
  471. waitseq = AsyncSequence()
  472. seq = AsyncSequence()
  473. async def fun1():
  474. async with waitseq.sync(1):
  475. pass
  476. async def fun2():
  477. async with seq.sync(1):
  478. async with waitseq.sync(1): # pragma: no cover
  479. pass
  480. task1 = asyncio.create_task(fun1())
  481. task2 = asyncio.create_task(fun2())
  482. # spin things to make sure things advance
  483. await asyncio.sleep(0)
  484. async with seq.sync(0):
  485. pass
  486. with self.assertRaises(RuntimeError):
  487. await task2
  488. async with waitseq.sync(0):
  489. pass
  490. await task1
  491. @timeout(2)
  492. async def test_seqexc(self):
  493. seq = AsyncSequence()
  494. excseq = AsyncSequence()
  495. async def excfun1():
  496. async with seq.sync(1):
  497. pass
  498. async with excseq.sync(0):
  499. raise ValueError('foo')
  500. # that a block that enters first, but runs after
  501. # raises an exception
  502. async def excfun2():
  503. async with seq.sync(0):
  504. pass
  505. async with excseq.sync(1): # pragma: no cover
  506. pass
  507. # that a block that enters after, raises an
  508. # exception
  509. async def excfun3():
  510. async with seq.sync(2):
  511. pass
  512. async with excseq.sync(2): # pragma: no cover
  513. pass
  514. task1 = asyncio.create_task(excfun1())
  515. task2 = asyncio.create_task(excfun2())
  516. task3 = asyncio.create_task(excfun3())
  517. with self.assertRaises(ValueError):
  518. await task1
  519. with self.assertRaises(asyncio.CancelledError):
  520. await task2
  521. with self.assertRaises(asyncio.CancelledError):
  522. await task3
  523. @timeout(2)
  524. async def test_seq(self):
  525. # test that a seq object when created
  526. seq = AsyncSequence(lambda: itertools.count(1))
  527. col = []
  528. async def fun1():
  529. async with seq.sync(1):
  530. col.append(1)
  531. async with seq.sync(2):
  532. col.append(2)
  533. async with seq.sync(4):
  534. col.append(4)
  535. async def fun2():
  536. async with seq.sync(3):
  537. col.append(3)
  538. async with seq.sync(6):
  539. col.append(6)
  540. async def fun3():
  541. async with seq.sync(5):
  542. col.append(5)
  543. # and various functions are run
  544. task1 = asyncio.create_task(fun1())
  545. task2 = asyncio.create_task(fun2())
  546. task3 = asyncio.create_task(fun3())
  547. # and the functions complete
  548. await task3
  549. await task2
  550. await task1
  551. # that the order they ran in was correct
  552. self.assertEqual(col, list(range(1, 7)))
  553. class TestLORANode(unittest.IsolatedAsyncioTestCase):
  554. shared_domain = b'com.funkthat.lora.irrigation.shared.v0.0.1'
  555. ecdhe_domain = b'com.funkthat.lora.irrigation.ecdhe.v0.0.1'
  556. def test_initparams(self):
  557. # make sure no keys fails
  558. with self.assertRaises(RuntimeError):
  559. l = LORANode(None)
  560. @timeout(2)
  561. async def test_lora_ecdhe(self):
  562. _self = self
  563. initkey = X25519.gen()
  564. respkey = X25519.gen()
  565. class TestSD(MockSyncDatagram):
  566. async def sendgettest(self, msg):
  567. '''Send the message, but make sure that if a
  568. bad message is sent afterward, that it replies
  569. w/ the same previous message.
  570. '''
  571. await self.put(msg)
  572. resp = await self.get()
  573. await self.put(b'bogusmsg' * 5)
  574. resp2 = await self.get()
  575. _self.assertEqual(resp, resp2)
  576. return resp
  577. async def runner(self):
  578. # as respondant
  579. l = Strobe(_self.ecdhe_domain, F=KeccakF(800))
  580. l.key(initkey.getpub() + respkey.getpub())
  581. # start handshake
  582. r = await self.get()
  583. # get eph key w/ reqreset
  584. pkt = l.recv_enc(r[:-8])
  585. l.recv_mac(r[-8:])
  586. assert pkt.endswith(b'reqreset')
  587. ephpub = pkt[:-len(b'reqreset')]
  588. # make sure junk gets ignored
  589. await self.put(b'sdlfkj')
  590. # and that the packet remains the same
  591. _self.assertEqual(r, await self.get())
  592. # and a couple more times
  593. await self.put(b'0' * 24)
  594. _self.assertEqual(r, await self.get())
  595. await self.put(b'0' * 32)
  596. _self.assertEqual(r, await self.get())
  597. # update the keys
  598. l.key(respkey.dh(ephpub) + respkey.dh(initkey.getpub()))
  599. # generate our eph key
  600. ephkey = X25519.gen()
  601. # send the response
  602. await self.put(l.send_enc(ephkey.getpub()) +
  603. l.send_mac(8))
  604. l.key(ephkey.dh(ephpub) + ephkey.dh(initkey.getpub()))
  605. # get the confirmation message
  606. r = await self.get()
  607. # test the resend capabilities
  608. await self.put(b'0' * 24)
  609. _self.assertEqual(r, await self.get())
  610. # decode confirmation message
  611. c = l.recv_enc(r[:-8])
  612. l.recv_mac(r[-8:])
  613. # assert that we got it
  614. _self.assertEqual(c, b'confirm')
  615. # send confirmed reply
  616. r = await self.sendgettest(l.send_enc(
  617. b'confirmed') + l.send_mac(8))
  618. # test and decode remaining command messages
  619. cmd = l.recv_enc(r[:-8])
  620. l.recv_mac(r[-8:])
  621. assert cmd[0] == CMD_WAITFOR
  622. assert int.from_bytes(cmd[1:],
  623. byteorder='little') == 30
  624. r = await self.sendgettest(l.send_enc(
  625. cmd[0:1]) + l.send_mac(8))
  626. cmd = l.recv_enc(r[:-8])
  627. l.recv_mac(r[-8:])
  628. assert cmd[0] == CMD_RUNFOR
  629. assert int.from_bytes(cmd[1:5],
  630. byteorder='little') == 1
  631. assert int.from_bytes(cmd[5:],
  632. byteorder='little') == 50
  633. r = await self.sendgettest(l.send_enc(
  634. cmd[0:1]) + l.send_mac(8))
  635. cmd = l.recv_enc(r[:-8])
  636. l.recv_mac(r[-8:])
  637. assert cmd[0] == CMD_TERMINATE
  638. await self.put(l.send_enc(cmd[0:1]) +
  639. l.send_mac(8))
  640. tsd = TestSD()
  641. # make sure it fails w/o both specified
  642. with self.assertRaises(RuntimeError):
  643. l = LORANode(tsd, init_key=initkey)
  644. with self.assertRaises(RuntimeError):
  645. l = LORANode(tsd, resp_pub=respkey.getpub())
  646. l = LORANode(tsd, init_key=initkey, resp_pub=respkey.getpub())
  647. await l.start()
  648. await l.waitfor(30)
  649. await l.runfor(1, 50)
  650. await l.terminate()
  651. await tsd.drain()
  652. # Make sure all messages have been processed
  653. self.assertTrue(tsd.sendq.empty())
  654. self.assertTrue(tsd.recvq.empty())
  655. #_debprint('done')
  656. @timeout(2)
  657. async def test_lora_shared(self):
  658. _self = self
  659. shared_key = os.urandom(32)
  660. class TestSD(MockSyncDatagram):
  661. async def sendgettest(self, msg):
  662. '''Send the message, but make sure that if a
  663. bad message is sent afterward, that it replies
  664. w/ the same previous message.
  665. '''
  666. await self.put(msg)
  667. resp = await self.get()
  668. await self.put(b'bogusmsg' * 5)
  669. resp2 = await self.get()
  670. _self.assertEqual(resp, resp2)
  671. return resp
  672. async def runner(self):
  673. l = Strobe(TestLORANode.shared_domain, F=KeccakF(800))
  674. l.key(shared_key)
  675. # start handshake
  676. r = await self.get()
  677. pkt = l.recv_enc(r[:-8])
  678. l.recv_mac(r[-8:])
  679. assert pkt.endswith(b'reqreset')
  680. # make sure junk gets ignored
  681. await self.put(b'sdlfkj')
  682. # and that the packet remains the same
  683. _self.assertEqual(r, await self.get())
  684. # and a couple more times
  685. await self.put(b'0' * 24)
  686. _self.assertEqual(r, await self.get())
  687. await self.put(b'0' * 32)
  688. _self.assertEqual(r, await self.get())
  689. # send the response
  690. await self.put(l.send_enc(os.urandom(16)) +
  691. l.send_mac(8))
  692. # require no more back tracking at this point
  693. l.ratchet()
  694. # get the confirmation message
  695. r = await self.get()
  696. # test the resend capabilities
  697. await self.put(b'0' * 24)
  698. _self.assertEqual(r, await self.get())
  699. # decode confirmation message
  700. c = l.recv_enc(r[:-8])
  701. l.recv_mac(r[-8:])
  702. # assert that we got it
  703. _self.assertEqual(c, b'confirm')
  704. # send confirmed reply
  705. r = await self.sendgettest(l.send_enc(
  706. b'confirmed') + l.send_mac(8))
  707. # test and decode remaining command messages
  708. cmd = l.recv_enc(r[:-8])
  709. l.recv_mac(r[-8:])
  710. assert cmd[0] == CMD_WAITFOR
  711. assert int.from_bytes(cmd[1:],
  712. byteorder='little') == 30
  713. r = await self.sendgettest(l.send_enc(
  714. cmd[0:1]) + l.send_mac(8))
  715. cmd = l.recv_enc(r[:-8])
  716. l.recv_mac(r[-8:])
  717. assert cmd[0] == CMD_RUNFOR
  718. assert int.from_bytes(cmd[1:5],
  719. byteorder='little') == 1
  720. assert int.from_bytes(cmd[5:],
  721. byteorder='little') == 50
  722. r = await self.sendgettest(l.send_enc(
  723. cmd[0:1]) + l.send_mac(8))
  724. cmd = l.recv_enc(r[:-8])
  725. l.recv_mac(r[-8:])
  726. assert cmd[0] == CMD_TERMINATE
  727. await self.put(l.send_enc(cmd[0:1]) +
  728. l.send_mac(8))
  729. tsd = TestSD()
  730. l = LORANode(tsd, shared=shared_key)
  731. await l.start()
  732. await l.waitfor(30)
  733. await l.runfor(1, 50)
  734. await l.terminate()
  735. await tsd.drain()
  736. # Make sure all messages have been processed
  737. self.assertTrue(tsd.sendq.empty())
  738. self.assertTrue(tsd.recvq.empty())
  739. #_debprint('done')
  740. @timeout(2)
  741. async def test_ccode_badmsgs(self):
  742. # Test to make sure that various bad messages in the
  743. # handshake process are rejected even if the attacker
  744. # has the correct key. This just keeps the protocol
  745. # tight allowing for variations in the future.
  746. # seed the RNG
  747. prngseed = b'abc123'
  748. from ctypes import c_uint8
  749. syote_comms.strobe_seed_prng((c_uint8 *
  750. len(prngseed))(*prngseed), len(prngseed))
  751. # Create the state for testing
  752. commstate = syote_comms.CommsState()
  753. cb = syote_comms.process_msgfunc_t(lambda msg, outbuf: None)
  754. # Generate shared key
  755. shared_key = os.urandom(32)
  756. # Initialize everything
  757. syote_comms.comms_init(commstate, cb, make_pktbuf(shared_key), None, None)
  758. # Create test fixture, only use it to init crypto state
  759. tsd = SyncDatagram()
  760. l = LORANode(tsd, shared=shared_key)
  761. # copy the crypto state
  762. cstate = l.st.copy()
  763. # compose an incorrect init message
  764. msg = os.urandom(16) + b'othre'
  765. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  766. out = syote_comms.comms_process_wrap(commstate, msg)
  767. self.assertFalse(out)
  768. # that varous short messages don't cause problems
  769. for i in range(10):
  770. out = syote_comms.comms_process_wrap(commstate, b'0' * i)
  771. self.assertFalse(out)
  772. # copy the crypto state
  773. cstate = l.st.copy()
  774. # compose an incorrect init message
  775. msg = os.urandom(16) + b' eqreset'
  776. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  777. out = syote_comms.comms_process_wrap(commstate, msg)
  778. self.assertFalse(out)
  779. # compose the correct init message
  780. msg = os.urandom(16) + b'reqreset'
  781. msg = l.st.send_enc(msg) + l.st.send_mac(l.MAC_LEN)
  782. out = syote_comms.comms_process_wrap(commstate, msg)
  783. l.st.recv_enc(out[:-l.MAC_LEN])
  784. l.st.recv_mac(out[-l.MAC_LEN:])
  785. l.st.ratchet()
  786. # copy the crypto state
  787. cstate = l.st.copy()
  788. # compose an incorrect confirmed message
  789. msg = b'onfirm'
  790. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  791. out = syote_comms.comms_process_wrap(commstate, msg)
  792. self.assertFalse(out)
  793. # copy the crypto state
  794. cstate = l.st.copy()
  795. # compose an incorrect confirmed message
  796. msg = b' onfirm'
  797. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  798. out = syote_comms.comms_process_wrap(commstate, msg)
  799. self.assertFalse(out)
  800. @timeout(2)
  801. async def test_ccode_ecdhe(self):
  802. _self = self
  803. from ctypes import c_uint8
  804. # seed the RNG
  805. prngseed = b'abc123'
  806. syote_comms.strobe_seed_prng((c_uint8 *
  807. len(prngseed))(*prngseed), len(prngseed))
  808. # Create the state for testing
  809. commstate = syote_comms.CommsState()
  810. # These are the expected messages and their arguments
  811. exptmsgs = [
  812. (CMD_WAITFOR, [ 30 ]),
  813. (CMD_RUNFOR, [ 1, 50 ]),
  814. (CMD_PING, [ ]),
  815. (CMD_TERMINATE, [ ]),
  816. ]
  817. def procmsg(msg, outbuf):
  818. msgbuf = msg._from()
  819. cmd = msgbuf[0]
  820. args = [ int.from_bytes(msgbuf[x:x + 4],
  821. byteorder='little') for x in range(1, len(msgbuf),
  822. 4) ]
  823. if exptmsgs[0] == (cmd, args):
  824. exptmsgs.pop(0)
  825. outbuf[0].pkt[0] = cmd
  826. outbuf[0].pktlen = 1
  827. else: #pragma: no cover
  828. raise RuntimeError('cmd not found')
  829. # wrap the callback function
  830. cb = syote_comms.process_msgfunc_t(procmsg)
  831. class CCodeSD(MockSyncDatagram):
  832. async def runner(self):
  833. for expectlen in [ 40, 17, 9, 9, 9, 9 ]:
  834. # get message
  835. inmsg = await self.get()
  836. # process the test message
  837. out = syote_comms.comms_process_wrap(
  838. commstate, inmsg)
  839. # make sure the reply matches length
  840. _self.assertEqual(expectlen, len(out))
  841. # save what was originally replied
  842. origmsg = out
  843. # pretend that the reply didn't make it
  844. out = syote_comms.comms_process_wrap(
  845. commstate, inmsg)
  846. # make sure that the reply matches
  847. # the previous
  848. _self.assertEqual(origmsg, out)
  849. # pass the reply back
  850. await self.put(out)
  851. # Generate keys
  852. initkey = X25519.gen()
  853. respkey = X25519.gen()
  854. # Initialize everything
  855. syote_comms.comms_init(commstate, cb, None, make_pktbuf(respkey.getpriv()), make_pktbuf(initkey.getpub()))
  856. # Create test fixture
  857. tsd = CCodeSD()
  858. l = LORANode(tsd, init_key=initkey, resp_pub=respkey.getpub())
  859. # Send various messages
  860. await l.start()
  861. await l.waitfor(30)
  862. await l.runfor(1, 50)
  863. await l.ping()
  864. await l.terminate()
  865. await tsd.drain()
  866. # Make sure all messages have been processed
  867. self.assertTrue(tsd.sendq.empty())
  868. self.assertTrue(tsd.recvq.empty())
  869. # Make sure all the expected messages have been
  870. # processed.
  871. self.assertFalse(exptmsgs)
  872. #_debprint('done')
  873. @timeout(2)
  874. async def test_ccode(self):
  875. _self = self
  876. from ctypes import c_uint8, memmove
  877. # seed the RNG
  878. prngseed = b'abc123'
  879. syote_comms.strobe_seed_prng((c_uint8 *
  880. len(prngseed))(*prngseed), len(prngseed))
  881. # Create the state for testing
  882. commstate = syote_comms.CommsState()
  883. # These are the expected messages and their arguments
  884. exptmsgs = [
  885. (CMD_WAITFOR, [ 30 ]),
  886. (CMD_RUNFOR, [ 1, 50 ]),
  887. (CMD_PING, [ ]),
  888. # using big here, because Python is stupid.
  889. (CMD_KEY, b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16\x00\x00\x00\x00\x00\x02\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x17\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', CMD_KEY.to_bytes(1, byteorder='big') + (3).to_bytes(4, byteorder='little')),
  890. (CMD_KEY, b'\x00\x00\x17\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', CMD_KEY.to_bytes(1, byteorder='big') + (2).to_bytes(4, byteorder='little')),
  891. (CMD_TERMINATE, [ ]),
  892. ]
  893. def procmsg(msg, outbuf):
  894. msgbuf = msg._from()
  895. cmd = msgbuf[0]
  896. if isinstance(exptmsgs[0][1], bytes):
  897. args = msgbuf[1:]
  898. else:
  899. args = [ int.from_bytes(msgbuf[x:x + 4],
  900. byteorder='little') for x in range(1, len(msgbuf),
  901. 4) ]
  902. if exptmsgs[0][:2] == (cmd, args):
  903. if len(exptmsgs[0]) > 2:
  904. rmsg = exptmsgs[0][2]
  905. memmove(outbuf[0].pkt, rmsg, len(rmsg))
  906. outbuf[0].pktlen = len(rmsg)
  907. else:
  908. outbuf[0].pkt[0] = cmd
  909. outbuf[0].pktlen = 1
  910. exptmsgs.pop(0)
  911. else: #pragma: no cover
  912. raise RuntimeError('cmd not found, got %d, expected %d' % (cmd, exptmsgs[0][0]))
  913. # wrap the callback function
  914. cb = syote_comms.process_msgfunc_t(procmsg)
  915. class CCodeSD(MockSyncDatagram):
  916. async def runner(self):
  917. for expectlen in [ 24, 17, 9, 9, 9, 13, 13, 9 ]:
  918. # get message
  919. inmsg = await self.get()
  920. # process the test message
  921. out = syote_comms.comms_process_wrap(
  922. commstate, inmsg)
  923. # make sure the reply matches length
  924. _self.assertEqual(expectlen, len(out))
  925. # save what was originally replied
  926. origmsg = out
  927. # pretend that the reply didn't make it
  928. out = syote_comms.comms_process_wrap(
  929. commstate, inmsg)
  930. # make sure that the reply matches
  931. # the previous
  932. _self.assertEqual(origmsg, out)
  933. # pass the reply back
  934. await self.put(out)
  935. # Generate shared key
  936. shared_key = os.urandom(32)
  937. # Initialize everything
  938. syote_comms.comms_init(commstate, cb, make_pktbuf(shared_key), None, None)
  939. # Create test fixture
  940. tsd = CCodeSD()
  941. l = LORANode(tsd, shared=shared_key)
  942. # Send various messages
  943. await l.start()
  944. await l.waitfor(30)
  945. await l.runfor(1, 50)
  946. await l.ping()
  947. await l.type('sHt')
  948. await l.terminate()
  949. await tsd.drain()
  950. # Make sure all messages have been processed
  951. self.assertTrue(tsd.sendq.empty())
  952. self.assertTrue(tsd.recvq.empty())
  953. # Make sure all the expected messages have been
  954. # processed.
  955. self.assertFalse(exptmsgs)
  956. #_debprint('done')
  957. @timeout(2)
  958. async def test_ccode_newsession(self):
  959. '''This test is to make sure that if an existing session
  960. is running, that a new session can be established, and that
  961. when it does, the old session becomes inactive.
  962. '''
  963. _self = self
  964. from ctypes import c_uint8
  965. seq = AsyncSequence()
  966. # seed the RNG
  967. prngseed = b'abc123'
  968. syote_comms.strobe_seed_prng((c_uint8 *
  969. len(prngseed))(*prngseed), len(prngseed))
  970. # Create the state for testing
  971. commstate = syote_comms.CommsState()
  972. # These are the expected messages and their arguments
  973. exptmsgs = [
  974. (CMD_WAITFOR, [ 30 ]),
  975. (CMD_WAITFOR, [ 70 ]),
  976. (CMD_WAITFOR, [ 40 ]),
  977. (CMD_TERMINATE, [ ]),
  978. ]
  979. def procmsg(msg, outbuf):
  980. msgbuf = msg._from()
  981. cmd = msgbuf[0]
  982. args = [ int.from_bytes(msgbuf[x:x + 4],
  983. byteorder='little') for x in range(1, len(msgbuf),
  984. 4) ]
  985. if exptmsgs[0] == (cmd, args):
  986. exptmsgs.pop(0)
  987. outbuf[0].pkt[0] = cmd
  988. outbuf[0].pktlen = 1
  989. else: #pragma: no cover
  990. raise RuntimeError('cmd not found: %d' % cmd)
  991. # wrap the callback function
  992. cb = syote_comms.process_msgfunc_t(procmsg)
  993. class FlipMsg(object):
  994. async def flipmsg(self):
  995. # get message
  996. inmsg = await self.get()
  997. # process the test message
  998. out = syote_comms.comms_process_wrap(
  999. commstate, inmsg)
  1000. # pass the reply back
  1001. await self.put(out)
  1002. # this class always passes messages, this is
  1003. # used for the first session.
  1004. class CCodeSD1(MockSyncDatagram, FlipMsg):
  1005. async def runner(self):
  1006. for i in range(3):
  1007. await self.flipmsg()
  1008. async with seq.sync(0):
  1009. # create bogus message
  1010. inmsg = b'0'*24
  1011. # process the bogus message
  1012. out = syote_comms.comms_process_wrap(
  1013. commstate, inmsg)
  1014. # make sure there was not a response
  1015. _self.assertFalse(out)
  1016. await self.flipmsg()
  1017. # this one is special in that it will pause after the first
  1018. # message to ensure that the previous session will continue
  1019. # to work, AND that if a new "new" session comes along, it
  1020. # will override the previous new session that hasn't been
  1021. # confirmed yet.
  1022. class CCodeSD2(MockSyncDatagram, FlipMsg):
  1023. async def runner(self):
  1024. # pass one message from the new session
  1025. async with seq.sync(1):
  1026. # There might be a missing case
  1027. # handled for when the confirmed
  1028. # message is generated, but lost.
  1029. await self.flipmsg()
  1030. # and the old session is still active
  1031. await l.waitfor(70)
  1032. async with seq.sync(2):
  1033. for i in range(3):
  1034. await self.flipmsg()
  1035. # Generate shared key
  1036. shared_key = os.urandom(32)
  1037. # Initialize everything
  1038. syote_comms.comms_init(commstate, cb, make_pktbuf(shared_key), None, None)
  1039. # Create test fixture
  1040. tsd = CCodeSD1()
  1041. l = LORANode(tsd, shared=shared_key)
  1042. # Send various messages
  1043. await l.start()
  1044. await l.waitfor(30)
  1045. # Ensure that a new one can take over
  1046. tsd2 = CCodeSD2()
  1047. l2 = LORANode(tsd2, shared=shared_key)
  1048. # Send various messages
  1049. await l2.start()
  1050. await l2.waitfor(40)
  1051. await l2.terminate()
  1052. await tsd.drain()
  1053. await tsd2.drain()
  1054. # Make sure all messages have been processed
  1055. self.assertTrue(tsd.sendq.empty())
  1056. self.assertTrue(tsd.recvq.empty())
  1057. self.assertTrue(tsd2.sendq.empty())
  1058. self.assertTrue(tsd2.recvq.empty())
  1059. # Make sure all the expected messages have been
  1060. # processed.
  1061. self.assertFalse(exptmsgs)
  1062. class TestLoRaNodeMulticast(unittest.IsolatedAsyncioTestCase):
  1063. # see: https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml#multicast-addresses-1
  1064. maddr = ('224.0.0.198', 48542)
  1065. @timeout(2)
  1066. async def test_multisyncdgram(self):
  1067. # Test the implementation of the multicast version of
  1068. # SyncDatagram
  1069. _self = self
  1070. from ctypes import c_uint8
  1071. # seed the RNG
  1072. prngseed = b'abc123'
  1073. syote_comms.strobe_seed_prng((c_uint8 *
  1074. len(prngseed))(*prngseed), len(prngseed))
  1075. # Create the state for testing
  1076. commstate = syote_comms.CommsState()
  1077. # These are the expected messages and their arguments
  1078. exptmsgs = [
  1079. (CMD_WAITFOR, [ 30 ]),
  1080. (CMD_PING, [ ]),
  1081. (CMD_TERMINATE, [ ]),
  1082. ]
  1083. def procmsg(msg, outbuf):
  1084. msgbuf = msg._from()
  1085. cmd = msgbuf[0]
  1086. args = [ int.from_bytes(msgbuf[x:x + 4],
  1087. byteorder='little') for x in range(1, len(msgbuf),
  1088. 4) ]
  1089. if exptmsgs[0] == (cmd, args):
  1090. exptmsgs.pop(0)
  1091. outbuf[0].pkt[0] = cmd
  1092. outbuf[0].pktlen = 1
  1093. else: #pragma: no cover
  1094. raise RuntimeError('cmd not found')
  1095. # wrap the callback function
  1096. cb = syote_comms.process_msgfunc_t(procmsg)
  1097. # Generate shared key
  1098. shared_key = os.urandom(32)
  1099. # Initialize everything
  1100. syote_comms.comms_init(commstate, cb, make_pktbuf(shared_key), None, None)
  1101. # create the object we are testing
  1102. msd = MulticastSyncDatagram(self.maddr)
  1103. seq = AsyncSequence()
  1104. async def clienttask():
  1105. mr = await multicast.create_multicast_receiver(
  1106. self.maddr)
  1107. mt = await multicast.create_multicast_transmitter(
  1108. self.maddr)
  1109. try:
  1110. # make sure the above threads are running
  1111. await seq.simpsync(0)
  1112. while True:
  1113. pkt = await mr.recv()
  1114. msg = pkt[0]
  1115. out = syote_comms.comms_process_wrap(
  1116. commstate, msg)
  1117. if out:
  1118. await mt.send(out)
  1119. finally:
  1120. mr.close()
  1121. mt.close()
  1122. task = asyncio.create_task(clienttask())
  1123. # start it
  1124. await msd.start()
  1125. # pass it to a node
  1126. l = LORANode(msd, shared=shared_key)
  1127. await seq.simpsync(1)
  1128. # Send various messages
  1129. await l.start()
  1130. await l.waitfor(30)
  1131. await l.ping()
  1132. await l.terminate()
  1133. # shut things down
  1134. ln = None
  1135. msd.close()
  1136. task.cancel()
  1137. with self.assertRaises(asyncio.CancelledError):
  1138. await task