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.
 
 
 
 
 
 

1179 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 TestX25519(unittest.TestCase):
  459. def test_basic(self):
  460. aprivkey = lora_comms.x25519_genkey()
  461. apubkey = lora_comms.x25519_base(aprivkey, 1)
  462. bprivkey = lora_comms.x25519_genkey()
  463. bpubkey = lora_comms.x25519_base(bprivkey, 1)
  464. self.assertNotEqual(aprivkey, bprivkey)
  465. self.assertNotEqual(apubkey, bpubkey)
  466. ra = lora_comms.x25519_wrap(apubkey, aprivkey, bpubkey, 1)
  467. rb = lora_comms.x25519_wrap(bpubkey, bprivkey, apubkey, 1)
  468. self.assertEquals(ra, rb)
  469. class TestLORANode(unittest.IsolatedAsyncioTestCase):
  470. shared_domain = b'com.funkthat.lora.irrigation.shared.v0.0.1'
  471. def test_initparams(self):
  472. # make sure no keys fails
  473. with self.assertRaises(RuntimeError):
  474. l = LORANode(None)
  475. @timeout(2)
  476. async def test_lora(self):
  477. _self = self
  478. shared_key = os.urandom(32)
  479. class TestSD(MockSyncDatagram):
  480. async def sendgettest(self, msg):
  481. '''Send the message, but make sure that if a
  482. bad message is sent afterward, that it replies
  483. w/ the same previous message.
  484. '''
  485. await self.put(msg)
  486. resp = await self.get()
  487. await self.put(b'bogusmsg' * 5)
  488. resp2 = await self.get()
  489. _self.assertEqual(resp, resp2)
  490. return resp
  491. async def runner(self):
  492. l = Strobe(TestLORANode.shared_domain, F=KeccakF(800))
  493. l.key(shared_key)
  494. # start handshake
  495. r = await self.get()
  496. pkt = l.recv_enc(r[:-8])
  497. l.recv_mac(r[-8:])
  498. assert pkt.endswith(b'reqreset')
  499. # make sure junk gets ignored
  500. await self.put(b'sdlfkj')
  501. # and that the packet remains the same
  502. _self.assertEqual(r, await self.get())
  503. # and a couple more times
  504. await self.put(b'0' * 24)
  505. _self.assertEqual(r, await self.get())
  506. await self.put(b'0' * 32)
  507. _self.assertEqual(r, await self.get())
  508. # send the response
  509. await self.put(l.send_enc(os.urandom(16)) +
  510. l.send_mac(8))
  511. # require no more back tracking at this point
  512. l.ratchet()
  513. # get the confirmation message
  514. r = await self.get()
  515. # test the resend capabilities
  516. await self.put(b'0' * 24)
  517. _self.assertEqual(r, await self.get())
  518. # decode confirmation message
  519. c = l.recv_enc(r[:-8])
  520. l.recv_mac(r[-8:])
  521. # assert that we got it
  522. _self.assertEqual(c, b'confirm')
  523. # send confirmed reply
  524. r = await self.sendgettest(l.send_enc(
  525. b'confirmed') + l.send_mac(8))
  526. # test and decode remaining command messages
  527. cmd = l.recv_enc(r[:-8])
  528. l.recv_mac(r[-8:])
  529. assert cmd[0] == CMD_WAITFOR
  530. assert int.from_bytes(cmd[1:],
  531. byteorder='little') == 30
  532. r = await self.sendgettest(l.send_enc(
  533. cmd[0:1]) + l.send_mac(8))
  534. cmd = l.recv_enc(r[:-8])
  535. l.recv_mac(r[-8:])
  536. assert cmd[0] == CMD_RUNFOR
  537. assert int.from_bytes(cmd[1:5],
  538. byteorder='little') == 1
  539. assert int.from_bytes(cmd[5:],
  540. byteorder='little') == 50
  541. r = await self.sendgettest(l.send_enc(
  542. cmd[0:1]) + l.send_mac(8))
  543. cmd = l.recv_enc(r[:-8])
  544. l.recv_mac(r[-8:])
  545. assert cmd[0] == CMD_TERMINATE
  546. await self.put(l.send_enc(cmd[0:1]) +
  547. l.send_mac(8))
  548. tsd = TestSD()
  549. l = LORANode(tsd, shared=shared_key)
  550. await l.start()
  551. await l.waitfor(30)
  552. await l.runfor(1, 50)
  553. await l.terminate()
  554. await tsd.drain()
  555. # Make sure all messages have been processed
  556. self.assertTrue(tsd.sendq.empty())
  557. self.assertTrue(tsd.recvq.empty())
  558. #_debprint('done')
  559. @timeout(2)
  560. async def test_ccode_badmsgs(self):
  561. # Test to make sure that various bad messages in the
  562. # handshake process are rejected even if the attacker
  563. # has the correct key. This just keeps the protocol
  564. # tight allowing for variations in the future.
  565. # seed the RNG
  566. prngseed = b'abc123'
  567. from ctypes import c_uint8
  568. lora_comms.strobe_seed_prng((c_uint8 *
  569. len(prngseed))(*prngseed), len(prngseed))
  570. # Create the state for testing
  571. commstate = lora_comms.CommsState()
  572. cb = lora_comms.process_msgfunc_t(lambda msg, outbuf: None)
  573. # Generate shared key
  574. shared_key = os.urandom(32)
  575. # Initialize everything
  576. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  577. # Create test fixture, only use it to init crypto state
  578. tsd = SyncDatagram()
  579. l = LORANode(tsd, shared=shared_key)
  580. # copy the crypto state
  581. cstate = l.st.copy()
  582. # compose an incorrect init message
  583. msg = os.urandom(16) + b'othre'
  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. # that varous short messages don't cause problems
  588. for i in range(10):
  589. out = lora_comms.comms_process_wrap(commstate, b'0' * i)
  590. self.assertFalse(out)
  591. # copy the crypto state
  592. cstate = l.st.copy()
  593. # compose an incorrect init message
  594. msg = os.urandom(16) + b' eqreset'
  595. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  596. out = lora_comms.comms_process_wrap(commstate, msg)
  597. self.assertFalse(out)
  598. # compose the correct init message
  599. msg = os.urandom(16) + b'reqreset'
  600. msg = l.st.send_enc(msg) + l.st.send_mac(l.MAC_LEN)
  601. out = lora_comms.comms_process_wrap(commstate, msg)
  602. l.st.recv_enc(out[:-l.MAC_LEN])
  603. l.st.recv_mac(out[-l.MAC_LEN:])
  604. l.st.ratchet()
  605. # copy the crypto state
  606. cstate = l.st.copy()
  607. # compose an incorrect confirmed message
  608. msg = b'onfirm'
  609. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  610. out = lora_comms.comms_process_wrap(commstate, msg)
  611. self.assertFalse(out)
  612. # copy the crypto state
  613. cstate = l.st.copy()
  614. # compose an incorrect confirmed message
  615. msg = b' onfirm'
  616. msg = cstate.send_enc(msg) + cstate.send_mac(l.MAC_LEN)
  617. out = lora_comms.comms_process_wrap(commstate, msg)
  618. self.assertFalse(out)
  619. @timeout(2)
  620. async def test_ccode(self):
  621. _self = self
  622. from ctypes import c_uint8
  623. # seed the RNG
  624. prngseed = b'abc123'
  625. lora_comms.strobe_seed_prng((c_uint8 *
  626. len(prngseed))(*prngseed), len(prngseed))
  627. # Create the state for testing
  628. commstate = lora_comms.CommsState()
  629. # These are the expected messages and their arguments
  630. exptmsgs = [
  631. (CMD_WAITFOR, [ 30 ]),
  632. (CMD_RUNFOR, [ 1, 50 ]),
  633. (CMD_PING, [ ]),
  634. (CMD_TERMINATE, [ ]),
  635. ]
  636. def procmsg(msg, outbuf):
  637. msgbuf = msg._from()
  638. cmd = msgbuf[0]
  639. args = [ int.from_bytes(msgbuf[x:x + 4],
  640. byteorder='little') for x in range(1, len(msgbuf),
  641. 4) ]
  642. if exptmsgs[0] == (cmd, args):
  643. exptmsgs.pop(0)
  644. outbuf[0].pkt[0] = cmd
  645. outbuf[0].pktlen = 1
  646. else: #pragma: no cover
  647. raise RuntimeError('cmd not found')
  648. # wrap the callback function
  649. cb = lora_comms.process_msgfunc_t(procmsg)
  650. class CCodeSD(MockSyncDatagram):
  651. async def runner(self):
  652. for expectlen in [ 24, 17, 9, 9, 9, 9 ]:
  653. # get message
  654. inmsg = await self.get()
  655. # process the test message
  656. out = lora_comms.comms_process_wrap(
  657. commstate, inmsg)
  658. # make sure the reply matches length
  659. _self.assertEqual(expectlen, len(out))
  660. # save what was originally replied
  661. origmsg = out
  662. # pretend that the reply didn't make it
  663. out = lora_comms.comms_process_wrap(
  664. commstate, inmsg)
  665. # make sure that the reply matches
  666. # the previous
  667. _self.assertEqual(origmsg, out)
  668. # pass the reply back
  669. await self.put(out)
  670. # Generate shared key
  671. shared_key = os.urandom(32)
  672. # Initialize everything
  673. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  674. # Create test fixture
  675. tsd = CCodeSD()
  676. l = LORANode(tsd, shared=shared_key)
  677. # Send various messages
  678. await l.start()
  679. await l.waitfor(30)
  680. await l.runfor(1, 50)
  681. await l.ping()
  682. await l.terminate()
  683. await tsd.drain()
  684. # Make sure all messages have been processed
  685. self.assertTrue(tsd.sendq.empty())
  686. self.assertTrue(tsd.recvq.empty())
  687. # Make sure all the expected messages have been
  688. # processed.
  689. self.assertFalse(exptmsgs)
  690. #_debprint('done')
  691. @timeout(2)
  692. async def test_ccode_newsession(self):
  693. '''This test is to make sure that if an existing session
  694. is running, that a new session can be established, and that
  695. when it does, the old session becomes inactive.
  696. '''
  697. _self = self
  698. from ctypes import c_uint8
  699. seq = AsyncSequence()
  700. # seed the RNG
  701. prngseed = b'abc123'
  702. lora_comms.strobe_seed_prng((c_uint8 *
  703. len(prngseed))(*prngseed), len(prngseed))
  704. # Create the state for testing
  705. commstate = lora_comms.CommsState()
  706. # These are the expected messages and their arguments
  707. exptmsgs = [
  708. (CMD_WAITFOR, [ 30 ]),
  709. (CMD_WAITFOR, [ 70 ]),
  710. (CMD_WAITFOR, [ 40 ]),
  711. (CMD_TERMINATE, [ ]),
  712. ]
  713. def procmsg(msg, outbuf):
  714. msgbuf = msg._from()
  715. cmd = msgbuf[0]
  716. args = [ int.from_bytes(msgbuf[x:x + 4],
  717. byteorder='little') for x in range(1, len(msgbuf),
  718. 4) ]
  719. if exptmsgs[0] == (cmd, args):
  720. exptmsgs.pop(0)
  721. outbuf[0].pkt[0] = cmd
  722. outbuf[0].pktlen = 1
  723. else: #pragma: no cover
  724. raise RuntimeError('cmd not found: %d' % cmd)
  725. # wrap the callback function
  726. cb = lora_comms.process_msgfunc_t(procmsg)
  727. class FlipMsg(object):
  728. async def flipmsg(self):
  729. # get message
  730. inmsg = await self.get()
  731. # process the test message
  732. out = lora_comms.comms_process_wrap(
  733. commstate, inmsg)
  734. # pass the reply back
  735. await self.put(out)
  736. # this class always passes messages, this is
  737. # used for the first session.
  738. class CCodeSD1(MockSyncDatagram, FlipMsg):
  739. async def runner(self):
  740. for i in range(3):
  741. await self.flipmsg()
  742. async with seq.sync(0):
  743. # create bogus message
  744. inmsg = b'0'*24
  745. # process the bogus message
  746. out = lora_comms.comms_process_wrap(
  747. commstate, inmsg)
  748. # make sure there was not a response
  749. _self.assertFalse(out)
  750. await self.flipmsg()
  751. # this one is special in that it will pause after the first
  752. # message to ensure that the previous session will continue
  753. # to work, AND that if a new "new" session comes along, it
  754. # will override the previous new session that hasn't been
  755. # confirmed yet.
  756. class CCodeSD2(MockSyncDatagram, FlipMsg):
  757. async def runner(self):
  758. # pass one message from the new session
  759. async with seq.sync(1):
  760. # There might be a missing case
  761. # handled for when the confirmed
  762. # message is generated, but lost.
  763. await self.flipmsg()
  764. # and the old session is still active
  765. await l.waitfor(70)
  766. async with seq.sync(2):
  767. for i in range(3):
  768. await self.flipmsg()
  769. # Generate shared key
  770. shared_key = os.urandom(32)
  771. # Initialize everything
  772. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  773. # Create test fixture
  774. tsd = CCodeSD1()
  775. l = LORANode(tsd, shared=shared_key)
  776. # Send various messages
  777. await l.start()
  778. await l.waitfor(30)
  779. # Ensure that a new one can take over
  780. tsd2 = CCodeSD2()
  781. l2 = LORANode(tsd2, shared=shared_key)
  782. # Send various messages
  783. await l2.start()
  784. await l2.waitfor(40)
  785. await l2.terminate()
  786. await tsd.drain()
  787. await tsd2.drain()
  788. # Make sure all messages have been processed
  789. self.assertTrue(tsd.sendq.empty())
  790. self.assertTrue(tsd.recvq.empty())
  791. self.assertTrue(tsd2.sendq.empty())
  792. self.assertTrue(tsd2.recvq.empty())
  793. # Make sure all the expected messages have been
  794. # processed.
  795. self.assertFalse(exptmsgs)
  796. class TestLoRaNodeMulticast(unittest.IsolatedAsyncioTestCase):
  797. # see: https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml#multicast-addresses-1
  798. maddr = ('224.0.0.198', 48542)
  799. @timeout(2)
  800. async def test_multisyncdgram(self):
  801. # Test the implementation of the multicast version of
  802. # SyncDatagram
  803. _self = self
  804. from ctypes import c_uint8
  805. # seed the RNG
  806. prngseed = b'abc123'
  807. lora_comms.strobe_seed_prng((c_uint8 *
  808. len(prngseed))(*prngseed), len(prngseed))
  809. # Create the state for testing
  810. commstate = lora_comms.CommsState()
  811. # These are the expected messages and their arguments
  812. exptmsgs = [
  813. (CMD_WAITFOR, [ 30 ]),
  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 = lora_comms.process_msgfunc_t(procmsg)
  831. # Generate shared key
  832. shared_key = os.urandom(32)
  833. # Initialize everything
  834. lora_comms.comms_init(commstate, cb, make_pktbuf(shared_key))
  835. # create the object we are testing
  836. msd = MulticastSyncDatagram(self.maddr)
  837. seq = AsyncSequence()
  838. async def clienttask():
  839. mr = await multicast.create_multicast_receiver(
  840. self.maddr)
  841. mt = await multicast.create_multicast_transmitter(
  842. self.maddr)
  843. try:
  844. # make sure the above threads are running
  845. await seq.simpsync(0)
  846. while True:
  847. pkt = await mr.recv()
  848. msg = pkt[0]
  849. out = lora_comms.comms_process_wrap(
  850. commstate, msg)
  851. if out:
  852. await mt.send(out)
  853. finally:
  854. mr.close()
  855. mt.close()
  856. task = asyncio.create_task(clienttask())
  857. # start it
  858. await msd.start()
  859. # pass it to a node
  860. l = LORANode(msd, shared=shared_key)
  861. await seq.simpsync(1)
  862. # Send various messages
  863. await l.start()
  864. await l.waitfor(30)
  865. await l.ping()
  866. await l.terminate()
  867. # shut things down
  868. ln = None
  869. msd.close()
  870. task.cancel()
  871. with self.assertRaises(asyncio.CancelledError):
  872. await task