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.
 
 
 
 
 
 

1162 lines
28 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 contextlib
  26. import functools
  27. import itertools
  28. import os
  29. import sys
  30. import unittest
  31. from Strobe.Strobe import Strobe, KeccakF
  32. from Strobe.Strobe import AuthenticationFailed
  33. import lora_comms
  34. from lora_comms import make_pktbuf
  35. import multicast
  36. from util import *
  37. # Response to command will be the CMD and any arguments if needed.
  38. # The command is encoded as an unsigned byte
  39. CMD_TERMINATE = 1 # no args: terminate the sesssion, reply confirms
  40. # The follow commands are queue up, but will be acknoledged when queued
  41. CMD_WAITFOR = 2 # arg: (length): waits for length seconds
  42. CMD_RUNFOR = 3 # arg: (chan, length): turns on chan for length seconds
  43. CMD_PING = 4 # arg: (): a no op command
  44. CMD_SETUNSET = 5 # arg: (chan, val): sets chan to val
  45. CMD_ADV = 6 # arg: ([cnt]): advances to the next cnt (default 1) command
  46. CMD_CLEAR = 7 # arg: (): clears all future commands, but keeps current running
  47. class LORANode(object):
  48. '''Implement a LORANode initiator.'''
  49. SHARED_DOMAIN = b'com.funkthat.lora.irrigation.shared.v0.0.1'
  50. ECDHE_DOMAIN = b'com.funkthat.lora.irrigation.ecdhe.v0.0.1'
  51. MAC_LEN = 8
  52. def __init__(self, syncdatagram, shared=None, ecdhe_key=None, resp_pub=None):
  53. self.sd = syncdatagram
  54. self.st = Strobe(self.SHARED_DOMAIN, F=KeccakF(800))
  55. if shared is not None:
  56. self.st.key(shared)
  57. else:
  58. raise RuntimeError
  59. async def start(self):
  60. resp = await self.sendrecvvalid(os.urandom(16) + b'reqreset')
  61. self.st.ratchet()
  62. pkt = await self.sendrecvvalid(b'confirm')
  63. if pkt != b'confirmed':
  64. raise RuntimeError('got invalid response: %s' %
  65. repr(pkt))
  66. async def sendrecvvalid(self, msg):
  67. msg = self.st.send_enc(msg) + self.st.send_mac(self.MAC_LEN)
  68. origstate = self.st.copy()
  69. while True:
  70. resp = await self.sd.sendtillrecv(msg, .50)
  71. #_debprint('got:', resp)
  72. # skip empty messages
  73. if len(resp) == 0:
  74. continue
  75. try:
  76. decmsg = self.st.recv_enc(resp[:-self.MAC_LEN])
  77. self.st.recv_mac(resp[-self.MAC_LEN:])
  78. break
  79. except AuthenticationFailed:
  80. # didn't get a valid packet, restore
  81. # state and retry
  82. #_debprint('failed')
  83. self.st.set_state_from(origstate)
  84. #_debprint('got rep:', repr(resp), repr(decmsg))
  85. return decmsg
  86. @staticmethod
  87. def _encodeargs(*args):
  88. r = []
  89. for i in args:
  90. r.append(i.to_bytes(4, byteorder='little'))
  91. return b''.join(r)
  92. async def _sendcmd(self, cmd, *args):
  93. cmdbyte = cmd.to_bytes(1, byteorder='little')
  94. resp = await self.sendrecvvalid(cmdbyte + self._encodeargs(*args))
  95. if resp[0:1] != cmdbyte:
  96. raise RuntimeError(
  97. 'response does not match, got: %s, expected: %s' %
  98. (repr(resp[0:1]), repr(cmdbyte)))
  99. async def waitfor(self, length):
  100. return await self._sendcmd(CMD_WAITFOR, length)
  101. async def runfor(self, chan, length):
  102. return await self._sendcmd(CMD_RUNFOR, chan, length)
  103. async def setunset(self, chan, val):
  104. return await self._sendcmd(CMD_SETUNSET, chan, val)
  105. async def ping(self):
  106. return await self._sendcmd(CMD_PING)
  107. async def adv(self, cnt=None):
  108. args = ()
  109. if cnt is not None:
  110. args = (cnt, )
  111. return await self._sendcmd(CMD_ADV, *args)
  112. async def clear(self):
  113. return await self._sendcmd(CMD_CLEAR)
  114. async def terminate(self):
  115. return await self._sendcmd(CMD_TERMINATE)
  116. class SyncDatagram(object):
  117. '''Base interface for a more simple synchronous interface.'''
  118. async def recv(self, timeout=None): #pragma: no cover
  119. '''Receive a datagram. If timeout is not None, wait that many
  120. seconds, and if nothing is received in that time, raise an
  121. asyncio.TimeoutError exception.'''
  122. raise NotImplementedError
  123. async def send(self, data): #pragma: no cover
  124. raise NotImplementedError
  125. async def sendtillrecv(self, data, freq):
  126. '''Send the datagram in data, every freq seconds until a datagram
  127. is received. If timeout seconds happen w/o receiving a datagram,
  128. then raise an TimeoutError exception.'''
  129. while True:
  130. #_debprint('sending:', repr(data))
  131. await self.send(data)
  132. try:
  133. return await self.recv(freq)
  134. except asyncio.TimeoutError:
  135. pass
  136. class MulticastSyncDatagram(SyncDatagram):
  137. '''
  138. An implementation of SyncDatagram that uses the provided
  139. multicast address maddr as the source/sink of the packets.
  140. Note that once created, the start coroutine needs to be
  141. await'd before being passed to a LORANode so that everything
  142. is running.
  143. '''
  144. # Note: sent packets will be received. A similar method to
  145. # what was done in multicast.{to,from}_loragw could be done
  146. # here as well, that is passing in a set of packets to not
  147. # pass back up.
  148. def __init__(self, maddr):
  149. self.maddr = maddr
  150. self._ignpkts = set()
  151. async def start(self):
  152. self.mr = await multicast.create_multicast_receiver(self.maddr)
  153. self.mt = await multicast.create_multicast_transmitter(
  154. self.maddr)
  155. async def _recv(self):
  156. while True:
  157. pkt = await self.mr.recv()
  158. pkt = pkt[0]
  159. if pkt not in self._ignpkts:
  160. return pkt
  161. self._ignpkts.remove(pkt)
  162. async def recv(self, timeout=None): #pragma: no cover
  163. r = await asyncio.wait_for(self._recv(), timeout=timeout)
  164. return r
  165. async def send(self, data): #pragma: no cover
  166. self._ignpkts.add(bytes(data))
  167. await self.mt.send(data)
  168. def close(self):
  169. '''Shutdown communications.'''
  170. self.mr.close()
  171. self.mr = None
  172. self.mt.close()
  173. self.mt = None
  174. def listsplit(lst, item):
  175. try:
  176. idx = lst.index(item)
  177. except ValueError:
  178. return lst, []
  179. return lst[:idx], lst[idx + 1:]
  180. async def main():
  181. import argparse
  182. from loraserv import DEFAULT_MADDR as maddr
  183. parser = argparse.ArgumentParser()
  184. parser.add_argument('-f', dest='schedfile', metavar='filename', type=str,
  185. help='Use commands from the file. One command per line.')
  186. parser.add_argument('-r', dest='client', metavar='module:function', type=str,
  187. help='Create a respondant instead of sending commands. Commands will be passed to the function.')
  188. parser.add_argument('-s', dest='shared_key', metavar='shared_key', type=str, required=True,
  189. help='The shared key (encoded as UTF-8) to use.')
  190. parser.add_argument('args', metavar='CMD_ARG', type=str, nargs='*',
  191. help='Various commands to send to the device.')
  192. args = parser.parse_args()
  193. shared_key = args.shared_key.encode('utf-8')
  194. if args.client:
  195. # Run a client
  196. mr = await multicast.create_multicast_receiver(maddr)
  197. mt = await multicast.create_multicast_transmitter(maddr)
  198. from ctypes import c_uint8
  199. # seed the RNG
  200. prngseed = os.urandom(64)
  201. lora_comms.strobe_seed_prng((c_uint8 *
  202. len(prngseed))(*prngseed), len(prngseed))
  203. # Create the state for testing
  204. commstate = lora_comms.CommsState()
  205. import util_load
  206. client_func = util_load.load_application(args.client)
  207. def client_call(msg, outbuf):
  208. ret = client_func(msg._from())
  209. if len(ret) > outbuf[0].pktlen:
  210. ret = b'error, too long buffer: %d' % len(ret)
  211. outbuf[0].pktlen = min(len(ret), outbuf[0].pktlen)
  212. for i in range(outbuf[0].pktlen):
  213. outbuf[0].pkt[i] = ret[i]
  214. cb = lora_comms.process_msgfunc_t(client_call)
  215. # Initialize everything
  216. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  217. try:
  218. while True:
  219. pkt = await mr.recv()
  220. msg = pkt[0]
  221. out = lora_comms.comms_process_wrap(
  222. commstate, msg)
  223. if out:
  224. await mt.send(out)
  225. finally:
  226. mr.close()
  227. mt.close()
  228. sys.exit(0)
  229. msd = MulticastSyncDatagram(maddr)
  230. await msd.start()
  231. l = LORANode(msd, shared=shared_key)
  232. await l.start()
  233. valid_cmds = {
  234. 'waitfor', 'setunset', 'runfor', 'ping', 'adv', 'clear',
  235. 'terminate',
  236. }
  237. if args.args and args.schedfile:
  238. parser.error('only one of -f or arguments can be specified.')
  239. if args.args:
  240. cmds = list(args.args)
  241. cmdargs = []
  242. while cmds:
  243. a, cmds = listsplit(cmds, '--')
  244. cmdargs.append(a)
  245. else:
  246. with open(args.schedfile) as fp:
  247. cmdargs = [ x.split() for x in fp.readlines() ]
  248. while cmdargs:
  249. cmd, *args = cmdargs.pop(0)
  250. if cmd not in valid_cmds:
  251. print('invalid command:', repr(cmd))
  252. sys.exit(1)
  253. fun = getattr(l, cmd)
  254. await fun(*(int(x) for x in args))
  255. if __name__ == '__main__':
  256. asyncio.run(main())
  257. class MockSyncDatagram(SyncDatagram):
  258. '''A testing version of SyncDatagram. Define a method runner which
  259. implements part of the sequence. In the function, await on either
  260. self.get, to wait for the other side to send something, or await
  261. self.put w/ data to send.'''
  262. def __init__(self):
  263. self.sendq = asyncio.Queue()
  264. self.recvq = asyncio.Queue()
  265. self.task = asyncio.create_task(self.runner())
  266. self.get = self.sendq.get
  267. self.put = self.recvq.put
  268. async def drain(self):
  269. '''Wait for the runner thread to finish up.'''
  270. return await self.task
  271. async def runner(self): #pragma: no cover
  272. raise NotImplementedError
  273. async def recv(self, timeout=None):
  274. return await self.recvq.get()
  275. async def send(self, data):
  276. return await self.sendq.put(data)
  277. def __del__(self): #pragma: no cover
  278. if self.task is not None and not self.task.done():
  279. self.task.cancel()
  280. class TestSyncData(unittest.IsolatedAsyncioTestCase):
  281. async def test_syncsendtillrecv(self):
  282. class MySync(SyncDatagram):
  283. def __init__(self):
  284. self.sendq = []
  285. self.resp = [ asyncio.TimeoutError(), b'a' ]
  286. async def recv(self, timeout=None):
  287. assert timeout == 1
  288. r = self.resp.pop(0)
  289. if isinstance(r, Exception):
  290. raise r
  291. return r
  292. async def send(self, data):
  293. self.sendq.append(data)
  294. ms = MySync()
  295. r = await ms.sendtillrecv(b'foo', 1)
  296. self.assertEqual(r, b'a')
  297. self.assertEqual(ms.sendq, [ b'foo', b'foo' ])
  298. class AsyncSequence(object):
  299. '''
  300. Object used for sequencing async functions. To use, use the
  301. asynchronous context manager created by the sync method. For
  302. example:
  303. seq = AsyncSequence()
  304. async func1():
  305. async with seq.sync(1):
  306. second_fun()
  307. async func2():
  308. async with seq.sync(0):
  309. first_fun()
  310. This will make sure that function first_fun is run before running
  311. the function second_fun. If a previous block raises an Exception,
  312. it will be passed up, and all remaining blocks (and future ones)
  313. will raise a CancelledError to help ensure that any tasks are
  314. properly cleaned up.
  315. '''
  316. def __init__(self, positerfactory=lambda: itertools.count()):
  317. '''The argument positerfactory, is a factory that will
  318. create an iterator that will be used for the values that
  319. are passed to the sync method.'''
  320. self.positer = positerfactory()
  321. self.token = object()
  322. self.die = False
  323. self.waiting = {
  324. next(self.positer): self.token
  325. }
  326. async def simpsync(self, pos):
  327. async with self.sync(pos):
  328. pass
  329. @contextlib.asynccontextmanager
  330. async def sync(self, pos):
  331. '''An async context manager that will be run when it's
  332. turn arrives. It will only run when all the previous
  333. items in the iterator has been successfully run.'''
  334. if self.die:
  335. raise asyncio.CancelledError('seq cancelled')
  336. if pos in self.waiting:
  337. if self.waiting[pos] is not self.token:
  338. raise RuntimeError('pos already waiting!')
  339. else:
  340. fut = asyncio.Future()
  341. self.waiting[pos] = fut
  342. await fut
  343. # our time to shine!
  344. del self.waiting[pos]
  345. try:
  346. yield None
  347. except Exception as e:
  348. # if we got an exception, things went pear shaped,
  349. # shut everything down, and any future calls.
  350. #_debprint('dieing...', repr(e))
  351. self.die = True
  352. # cancel existing blocks
  353. while self.waiting:
  354. k, v = self.waiting.popitem()
  355. #_debprint('canceling: %s' % repr(k))
  356. if v is self.token:
  357. continue
  358. # for Python 3.9:
  359. # msg='pos %s raised exception: %s' %
  360. # (repr(pos), repr(e))
  361. v.cancel()
  362. # populate real exception up
  363. raise
  364. else:
  365. # handle next
  366. nextpos = next(self.positer)
  367. if nextpos in self.waiting:
  368. #_debprint('np:', repr(self), nextpos,
  369. # repr(self.waiting[nextpos]))
  370. self.waiting[nextpos].set_result(None)
  371. else:
  372. self.waiting[nextpos] = self.token
  373. class TestSequencing(unittest.IsolatedAsyncioTestCase):
  374. @timeout(2)
  375. async def test_seq_alreadywaiting(self):
  376. waitseq = AsyncSequence()
  377. seq = AsyncSequence()
  378. async def fun1():
  379. async with waitseq.sync(1):
  380. pass
  381. async def fun2():
  382. async with seq.sync(1):
  383. async with waitseq.sync(1): # pragma: no cover
  384. pass
  385. task1 = asyncio.create_task(fun1())
  386. task2 = asyncio.create_task(fun2())
  387. # spin things to make sure things advance
  388. await asyncio.sleep(0)
  389. async with seq.sync(0):
  390. pass
  391. with self.assertRaises(RuntimeError):
  392. await task2
  393. async with waitseq.sync(0):
  394. pass
  395. await task1
  396. @timeout(2)
  397. async def test_seqexc(self):
  398. seq = AsyncSequence()
  399. excseq = AsyncSequence()
  400. async def excfun1():
  401. async with seq.sync(1):
  402. pass
  403. async with excseq.sync(0):
  404. raise ValueError('foo')
  405. # that a block that enters first, but runs after
  406. # raises an exception
  407. async def excfun2():
  408. async with seq.sync(0):
  409. pass
  410. async with excseq.sync(1): # pragma: no cover
  411. pass
  412. # that a block that enters after, raises an
  413. # exception
  414. async def excfun3():
  415. async with seq.sync(2):
  416. pass
  417. async with excseq.sync(2): # pragma: no cover
  418. pass
  419. task1 = asyncio.create_task(excfun1())
  420. task2 = asyncio.create_task(excfun2())
  421. task3 = asyncio.create_task(excfun3())
  422. with self.assertRaises(ValueError):
  423. await task1
  424. with self.assertRaises(asyncio.CancelledError):
  425. await task2
  426. with self.assertRaises(asyncio.CancelledError):
  427. await task3
  428. @timeout(2)
  429. async def test_seq(self):
  430. # test that a seq object when created
  431. seq = AsyncSequence(lambda: itertools.count(1))
  432. col = []
  433. async def fun1():
  434. async with seq.sync(1):
  435. col.append(1)
  436. async with seq.sync(2):
  437. col.append(2)
  438. async with seq.sync(4):
  439. col.append(4)
  440. async def fun2():
  441. async with seq.sync(3):
  442. col.append(3)
  443. async with seq.sync(6):
  444. col.append(6)
  445. async def fun3():
  446. async with seq.sync(5):
  447. col.append(5)
  448. # and various functions are run
  449. task1 = asyncio.create_task(fun1())
  450. task2 = asyncio.create_task(fun2())
  451. task3 = asyncio.create_task(fun3())
  452. # and the functions complete
  453. await task3
  454. await task2
  455. await task1
  456. # that the order they ran in was correct
  457. self.assertEqual(col, list(range(1, 7)))
  458. class TestLORANode(unittest.IsolatedAsyncioTestCase):
  459. shared_domain = b'com.funkthat.lora.irrigation.shared.v0.0.1'
  460. def test_initparams(self):
  461. # make sure no keys fails
  462. with self.assertRaises(RuntimeError):
  463. l = LORANode(None)
  464. @timeout(2)
  465. async def test_lora_shared(self):
  466. _self = self
  467. shared_key = os.urandom(32)
  468. class TestSD(MockSyncDatagram):
  469. async def sendgettest(self, msg):
  470. '''Send the message, but make sure that if a
  471. bad message is sent afterward, that it replies
  472. w/ the same previous message.
  473. '''
  474. await self.put(msg)
  475. resp = await self.get()
  476. await self.put(b'bogusmsg' * 5)
  477. resp2 = await self.get()
  478. _self.assertEqual(resp, resp2)
  479. return resp
  480. async def runner(self):
  481. l = Strobe(TestLORANode.shared_domain, F=KeccakF(800))
  482. l.key(shared_key)
  483. # start handshake
  484. r = await self.get()
  485. pkt = l.recv_enc(r[:-8])
  486. l.recv_mac(r[-8:])
  487. assert pkt.endswith(b'reqreset')
  488. # make sure junk gets ignored
  489. await self.put(b'sdlfkj')
  490. # and that the packet remains the same
  491. _self.assertEqual(r, await self.get())
  492. # and a couple more times
  493. await self.put(b'0' * 24)
  494. _self.assertEqual(r, await self.get())
  495. await self.put(b'0' * 32)
  496. _self.assertEqual(r, await self.get())
  497. # send the response
  498. await self.put(l.send_enc(os.urandom(16)) +
  499. l.send_mac(8))
  500. # require no more back tracking at this point
  501. l.ratchet()
  502. # get the confirmation message
  503. r = await self.get()
  504. # test the resend capabilities
  505. await self.put(b'0' * 24)
  506. _self.assertEqual(r, await self.get())
  507. # decode confirmation message
  508. c = l.recv_enc(r[:-8])
  509. l.recv_mac(r[-8:])
  510. # assert that we got it
  511. _self.assertEqual(c, b'confirm')
  512. # send confirmed reply
  513. r = await self.sendgettest(l.send_enc(
  514. b'confirmed') + l.send_mac(8))
  515. # test and decode remaining command messages
  516. cmd = l.recv_enc(r[:-8])
  517. l.recv_mac(r[-8:])
  518. assert cmd[0] == CMD_WAITFOR
  519. assert int.from_bytes(cmd[1:],
  520. byteorder='little') == 30
  521. r = await self.sendgettest(l.send_enc(
  522. cmd[0:1]) + l.send_mac(8))
  523. cmd = l.recv_enc(r[:-8])
  524. l.recv_mac(r[-8:])
  525. assert cmd[0] == CMD_RUNFOR
  526. assert int.from_bytes(cmd[1:5],
  527. byteorder='little') == 1
  528. assert int.from_bytes(cmd[5:],
  529. byteorder='little') == 50
  530. r = await self.sendgettest(l.send_enc(
  531. cmd[0:1]) + l.send_mac(8))
  532. cmd = l.recv_enc(r[:-8])
  533. l.recv_mac(r[-8:])
  534. assert cmd[0] == CMD_TERMINATE
  535. await self.put(l.send_enc(cmd[0:1]) +
  536. l.send_mac(8))
  537. tsd = TestSD()
  538. l = LORANode(tsd, shared=shared_key)
  539. await l.start()
  540. await l.waitfor(30)
  541. await l.runfor(1, 50)
  542. await l.terminate()
  543. await tsd.drain()
  544. # Make sure all messages have been processed
  545. self.assertTrue(tsd.sendq.empty())
  546. self.assertTrue(tsd.recvq.empty())
  547. #_debprint('done')
  548. @timeout(2)
  549. async def test_ccode_badmsgs(self):
  550. # Test to make sure that various bad messages in the
  551. # handshake process are rejected even if the attacker
  552. # has the correct key. This just keeps the protocol
  553. # tight allowing for variations in the future.
  554. # seed the RNG
  555. prngseed = b'abc123'
  556. from ctypes import c_uint8
  557. lora_comms.strobe_seed_prng((c_uint8 *
  558. len(prngseed))(*prngseed), len(prngseed))
  559. # Create the state for testing
  560. commstate = lora_comms.CommsState()
  561. cb = lora_comms.process_msgfunc_t(lambda msg, outbuf: None)
  562. # Generate shared key
  563. shared_key = os.urandom(32)
  564. # Initialize everything
  565. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  566. # Create test fixture, only use it to init crypto state
  567. tsd = SyncDatagram()
  568. l = LORANode(tsd, shared=shared_key)
  569. # copy the crypto state
  570. cstate = l.st.copy()
  571. # compose an incorrect init message
  572. msg = os.urandom(16) + b'othre'
  573. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  574. out = lora_comms.comms_process_wrap(commstate, msg)
  575. self.assertFalse(out)
  576. # that varous short messages don't cause problems
  577. for i in range(10):
  578. out = lora_comms.comms_process_wrap(commstate, b'0' * i)
  579. self.assertFalse(out)
  580. # copy the crypto state
  581. cstate = l.st.copy()
  582. # compose an incorrect init message
  583. msg = os.urandom(16) + b' eqreset'
  584. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  585. out = lora_comms.comms_process_wrap(commstate, msg)
  586. self.assertFalse(out)
  587. # compose the correct init message
  588. msg = os.urandom(16) + b'reqreset'
  589. msg = l.st.send_enc(msg) + l.st.send_mac(l.MAC_LEN)
  590. out = lora_comms.comms_process_wrap(commstate, msg)
  591. l.st.recv_enc(out[:-l.MAC_LEN])
  592. l.st.recv_mac(out[-l.MAC_LEN:])
  593. l.st.ratchet()
  594. # copy the crypto state
  595. cstate = l.st.copy()
  596. # compose an incorrect confirmed message
  597. msg = b'onfirm'
  598. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  599. out = lora_comms.comms_process_wrap(commstate, msg)
  600. self.assertFalse(out)
  601. # copy the crypto state
  602. cstate = l.st.copy()
  603. # compose an incorrect confirmed message
  604. msg = b' onfirm'
  605. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  606. out = lora_comms.comms_process_wrap(commstate, msg)
  607. self.assertFalse(out)
  608. @timeout(2)
  609. async def test_ccode(self):
  610. _self = self
  611. from ctypes import c_uint8
  612. # seed the RNG
  613. prngseed = b'abc123'
  614. lora_comms.strobe_seed_prng((c_uint8 *
  615. len(prngseed))(*prngseed), len(prngseed))
  616. # Create the state for testing
  617. commstate = lora_comms.CommsState()
  618. # These are the expected messages and their arguments
  619. exptmsgs = [
  620. (CMD_WAITFOR, [ 30 ]),
  621. (CMD_RUNFOR, [ 1, 50 ]),
  622. (CMD_PING, [ ]),
  623. (CMD_TERMINATE, [ ]),
  624. ]
  625. def procmsg(msg, outbuf):
  626. msgbuf = msg._from()
  627. cmd = msgbuf[0]
  628. args = [ int.from_bytes(msgbuf[x:x + 4],
  629. byteorder='little') for x in range(1, len(msgbuf),
  630. 4) ]
  631. if exptmsgs[0] == (cmd, args):
  632. exptmsgs.pop(0)
  633. outbuf[0].pkt[0] = cmd
  634. outbuf[0].pktlen = 1
  635. else: #pragma: no cover
  636. raise RuntimeError('cmd not found')
  637. # wrap the callback function
  638. cb = lora_comms.process_msgfunc_t(procmsg)
  639. class CCodeSD(MockSyncDatagram):
  640. async def runner(self):
  641. for expectlen in [ 24, 17, 9, 9, 9, 9 ]:
  642. # get message
  643. inmsg = await self.get()
  644. # process the test message
  645. out = lora_comms.comms_process_wrap(
  646. commstate, inmsg)
  647. # make sure the reply matches length
  648. _self.assertEqual(expectlen, len(out))
  649. # save what was originally replied
  650. origmsg = out
  651. # pretend that the reply didn't make it
  652. out = lora_comms.comms_process_wrap(
  653. commstate, inmsg)
  654. # make sure that the reply matches
  655. # the previous
  656. _self.assertEqual(origmsg, out)
  657. # pass the reply back
  658. await self.put(out)
  659. # Generate shared key
  660. shared_key = os.urandom(32)
  661. # Initialize everything
  662. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  663. # Create test fixture
  664. tsd = CCodeSD()
  665. l = LORANode(tsd, shared=shared_key)
  666. # Send various messages
  667. await l.start()
  668. await l.waitfor(30)
  669. await l.runfor(1, 50)
  670. await l.ping()
  671. await l.terminate()
  672. await tsd.drain()
  673. # Make sure all messages have been processed
  674. self.assertTrue(tsd.sendq.empty())
  675. self.assertTrue(tsd.recvq.empty())
  676. # Make sure all the expected messages have been
  677. # processed.
  678. self.assertFalse(exptmsgs)
  679. #_debprint('done')
  680. @timeout(2)
  681. async def test_ccode_newsession(self):
  682. '''This test is to make sure that if an existing session
  683. is running, that a new session can be established, and that
  684. when it does, the old session becomes inactive.
  685. '''
  686. _self = self
  687. from ctypes import c_uint8
  688. seq = AsyncSequence()
  689. # seed the RNG
  690. prngseed = b'abc123'
  691. lora_comms.strobe_seed_prng((c_uint8 *
  692. len(prngseed))(*prngseed), len(prngseed))
  693. # Create the state for testing
  694. commstate = lora_comms.CommsState()
  695. # These are the expected messages and their arguments
  696. exptmsgs = [
  697. (CMD_WAITFOR, [ 30 ]),
  698. (CMD_WAITFOR, [ 70 ]),
  699. (CMD_WAITFOR, [ 40 ]),
  700. (CMD_TERMINATE, [ ]),
  701. ]
  702. def procmsg(msg, outbuf):
  703. msgbuf = msg._from()
  704. cmd = msgbuf[0]
  705. args = [ int.from_bytes(msgbuf[x:x + 4],
  706. byteorder='little') for x in range(1, len(msgbuf),
  707. 4) ]
  708. if exptmsgs[0] == (cmd, args):
  709. exptmsgs.pop(0)
  710. outbuf[0].pkt[0] = cmd
  711. outbuf[0].pktlen = 1
  712. else: #pragma: no cover
  713. raise RuntimeError('cmd not found: %d' % cmd)
  714. # wrap the callback function
  715. cb = lora_comms.process_msgfunc_t(procmsg)
  716. class FlipMsg(object):
  717. async def flipmsg(self):
  718. # get message
  719. inmsg = await self.get()
  720. # process the test message
  721. out = lora_comms.comms_process_wrap(
  722. commstate, inmsg)
  723. # pass the reply back
  724. await self.put(out)
  725. # this class always passes messages, this is
  726. # used for the first session.
  727. class CCodeSD1(MockSyncDatagram, FlipMsg):
  728. async def runner(self):
  729. for i in range(3):
  730. await self.flipmsg()
  731. async with seq.sync(0):
  732. # create bogus message
  733. inmsg = b'0'*24
  734. # process the bogus message
  735. out = lora_comms.comms_process_wrap(
  736. commstate, inmsg)
  737. # make sure there was not a response
  738. _self.assertFalse(out)
  739. await self.flipmsg()
  740. # this one is special in that it will pause after the first
  741. # message to ensure that the previous session will continue
  742. # to work, AND that if a new "new" session comes along, it
  743. # will override the previous new session that hasn't been
  744. # confirmed yet.
  745. class CCodeSD2(MockSyncDatagram, FlipMsg):
  746. async def runner(self):
  747. # pass one message from the new session
  748. async with seq.sync(1):
  749. # There might be a missing case
  750. # handled for when the confirmed
  751. # message is generated, but lost.
  752. await self.flipmsg()
  753. # and the old session is still active
  754. await l.waitfor(70)
  755. async with seq.sync(2):
  756. for i in range(3):
  757. await self.flipmsg()
  758. # Generate shared key
  759. shared_key = os.urandom(32)
  760. # Initialize everything
  761. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  762. # Create test fixture
  763. tsd = CCodeSD1()
  764. l = LORANode(tsd, shared=shared_key)
  765. # Send various messages
  766. await l.start()
  767. await l.waitfor(30)
  768. # Ensure that a new one can take over
  769. tsd2 = CCodeSD2()
  770. l2 = LORANode(tsd2, shared=shared_key)
  771. # Send various messages
  772. await l2.start()
  773. await l2.waitfor(40)
  774. await l2.terminate()
  775. await tsd.drain()
  776. await tsd2.drain()
  777. # Make sure all messages have been processed
  778. self.assertTrue(tsd.sendq.empty())
  779. self.assertTrue(tsd.recvq.empty())
  780. self.assertTrue(tsd2.sendq.empty())
  781. self.assertTrue(tsd2.recvq.empty())
  782. # Make sure all the expected messages have been
  783. # processed.
  784. self.assertFalse(exptmsgs)
  785. class TestLoRaNodeMulticast(unittest.IsolatedAsyncioTestCase):
  786. # see: https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml#multicast-addresses-1
  787. maddr = ('224.0.0.198', 48542)
  788. @timeout(2)
  789. async def test_multisyncdgram(self):
  790. # Test the implementation of the multicast version of
  791. # SyncDatagram
  792. _self = self
  793. from ctypes import c_uint8
  794. # seed the RNG
  795. prngseed = b'abc123'
  796. lora_comms.strobe_seed_prng((c_uint8 *
  797. len(prngseed))(*prngseed), len(prngseed))
  798. # Create the state for testing
  799. commstate = lora_comms.CommsState()
  800. # These are the expected messages and their arguments
  801. exptmsgs = [
  802. (CMD_WAITFOR, [ 30 ]),
  803. (CMD_PING, [ ]),
  804. (CMD_TERMINATE, [ ]),
  805. ]
  806. def procmsg(msg, outbuf):
  807. msgbuf = msg._from()
  808. cmd = msgbuf[0]
  809. args = [ int.from_bytes(msgbuf[x:x + 4],
  810. byteorder='little') for x in range(1, len(msgbuf),
  811. 4) ]
  812. if exptmsgs[0] == (cmd, args):
  813. exptmsgs.pop(0)
  814. outbuf[0].pkt[0] = cmd
  815. outbuf[0].pktlen = 1
  816. else: #pragma: no cover
  817. raise RuntimeError('cmd not found')
  818. # wrap the callback function
  819. cb = lora_comms.process_msgfunc_t(procmsg)
  820. # Generate shared key
  821. shared_key = os.urandom(32)
  822. # Initialize everything
  823. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  824. # create the object we are testing
  825. msd = MulticastSyncDatagram(self.maddr)
  826. seq = AsyncSequence()
  827. async def clienttask():
  828. mr = await multicast.create_multicast_receiver(
  829. self.maddr)
  830. mt = await multicast.create_multicast_transmitter(
  831. self.maddr)
  832. try:
  833. # make sure the above threads are running
  834. await seq.simpsync(0)
  835. while True:
  836. pkt = await mr.recv()
  837. msg = pkt[0]
  838. out = lora_comms.comms_process_wrap(
  839. commstate, msg)
  840. if out:
  841. await mt.send(out)
  842. finally:
  843. mr.close()
  844. mt.close()
  845. task = asyncio.create_task(clienttask())
  846. # start it
  847. await msd.start()
  848. # pass it to a node
  849. l = LORANode(msd, shared=shared_key)
  850. await seq.simpsync(1)
  851. # Send various messages
  852. await l.start()
  853. await l.waitfor(30)
  854. await l.ping()
  855. await l.terminate()
  856. # shut things down
  857. ln = None
  858. msd.close()
  859. task.cancel()
  860. with self.assertRaises(asyncio.CancelledError):
  861. await task