Skip to content

Commit

Permalink
Fix CRC-16 verification for values smaller than 256 (ISK MT631)
Browse files Browse the repository at this point in the history
Based on a patch by Heinz <kheinz@gmx.de>. [GH-3]
  • Loading branch information
mtdcr committed Mar 22, 2021
1 parent e07e232 commit 79894a8
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions sml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

import logging
import re
from collections import namedtuple
from typing import Generator, Optional, Tuple
import bitstring

Expand Down Expand Up @@ -292,6 +293,8 @@ class SmlMessage(dict):
0xff01: 'SmlAttentionResponse',
}

ListItem = namedtuple('ListItem', ['length', 'value'])

def __init__(self, bits: bitstring.ConstBitStream) -> None:
super().__init__()
self._bits = bits
Expand All @@ -307,16 +310,16 @@ def __init__(self, bits: bitstring.ConstBitStream) -> None:
for key, val in zip(self.__FIELDS, values):
self[key] = val

if self['endOfSmlMsg'] is not None:
if self['endOfSmlMsg'].value is not None:
raise SmlParserError('Invalid value for endOfSmlMsg')

end = self._bits.pos
msg_bytes = self._bits[start:end].bytes
if Crc.crc16(msg_bytes[:-4]) != self['crc16']:
if Crc.crc16(msg_bytes[:-(self['crc16'].length + 1)]) != self['crc16'].value:
raise SmlParserError('CRC16 mismatch')

self['messageBody'] = SmlChoice.create(self.__CHOICES,
self['messageBody'])
self['messageBody'].value)

logger.debug("[*] CONSUMED: %s", msg_bytes.hex())
logger.debug("[*] RESULT (%d bits left): %s",
Expand Down Expand Up @@ -362,7 +365,7 @@ def _read_list(self, count: int, nesting: int = 0) -> list:
raise SmlParserError('Unknown TL field')

logger.debug('%s[+] Value: %s', nesting * ' ', value)
res.append(value)
res.append(SmlMessage.ListItem(length, value))

assert len(res) == count
return res
Expand Down

0 comments on commit 79894a8

Please sign in to comment.