From 79d84b226152f609197437cc2377b7bad540f4e7 Mon Sep 17 00:00:00 2001 From: Fredrik Thulin Date: Thu, 23 Mar 2017 19:44:26 +0100 Subject: Add CRC32. --- cryptech_muxd | 54 ++++++++++++++++++++++++++++++++++++++++++++++-------- slip.c | 22 ++++++++++++++++++++++ 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/cryptech_muxd b/cryptech_muxd index 269ac15..3dcf449 100755 --- a/cryptech_muxd +++ b/cryptech_muxd @@ -58,6 +58,7 @@ import tornado.queues import tornado.locks import tornado.gen +from zlib import crc32 logger = logging.getLogger("cryptech_muxd") @@ -89,6 +90,19 @@ def client_handle_set(msg, handle): return msg[:4] + struct.pack(">L", handle) + msg[8:] +def send_checksum(msg): + "Add a CRC32 checksum at the end of the message." + crc = (~crc32(msg)) & 0xffffffff + return msg + struct.pack("")) try: - is_rpc = response[response.index(SLIP_END + RPC_reply) + len(SLIP_END + RPC_reply) + 4] == SLIP_END + reply_idx = response.index(SLIP_END + RPC_reply) + reply_len = len(SLIP_END + RPC_reply) + logger.debug("Reply index {}, length {}".format(reply_idx, reply_len)) + end_offs = reply_idx + reply_len + 8 # RPC_reply is followed by 4 bytes of version data and a CRC32 checksum + is_rpc = response[end_offs] == SLIP_END + logger.debug("Response[{} + {} + 4] = 0x{:x} (is_rpc {})".format( + reply_idx, reply_len, ord(response[end_offs]), is_rpc)) except ValueError: is_rpc = False except IndexError: diff --git a/slip.c b/slip.c index b28b7e1..279b1d3 100644 --- a/slip.c +++ b/slip.c @@ -73,15 +73,34 @@ hal_error_t hal_slip_send_char(const uint8_t c) return HAL_OK; } +static hal_error_t _send_uint32(const uint32_t val) +{ + uint32_t data = val; + + for (int i = 0; i < 4; ++i) { + uint8_t *p = (uint8_t *) &data; + check(hal_slip_send_char(p[i])); + } + + return HAL_OK; +} + /* Send a message with SLIP framing. */ hal_error_t hal_slip_send(const uint8_t * const buf, const size_t len) { + hal_crc32_t crc; + /* send an initial END character to flush out any data that may * have accumulated in the receiver due to line noise */ check(hal_serial_send_char(END)); + /* Calculate CRC32 checksum of the contents, before SLIP encoding */ + crc = hal_crc32_init(); + crc = hal_crc32_update(crc, buf, len); + crc = ~hal_crc32_finalize(crc); + /* for each byte in the packet, send the appropriate character * sequence */ @@ -91,6 +110,9 @@ hal_error_t hal_slip_send(const uint8_t * const buf, const size_t len) return ret; } + /* Transmit the CRC */ + check(_send_uint32(crc)); + /* tell the receiver that we're done sending the packet */ check(hal_serial_send_char(END)); -- cgit v1.2.3