From e3ec63e3ff1cd532185af04f7e54541cae4b161c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Alexander=20Fellinghaug?= Date: Mon, 21 Feb 2022 11:54:19 +0100 Subject: [PATCH] Fixes #4 by introducing max value checking as done in github.com/canboat/canboat --- nmea2k/raw_message.go | 11 ++++++++++- nmea2k/raw_message_test.go | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/nmea2k/raw_message.go b/nmea2k/raw_message.go index 87e0b67..5c88bc3 100644 --- a/nmea2k/raw_message.go +++ b/nmea2k/raw_message.go @@ -463,7 +463,16 @@ func (msg *RawMessage) extractNumber(field *Field, start, end, offset, width uin maxValue = 0x7FFFFFFFFFFFFFFF } - if num > maxValue { + var reserved uint64 + if maxValue >= 15 { + reserved = 2 + } else if maxValue > 1 { + reserved = 1 + } else { + reserved = 0 + } + + if num > maxValue-reserved { e = &DecodeError{data, "Field not present"} return } diff --git a/nmea2k/raw_message_test.go b/nmea2k/raw_message_test.go index 73b9ec5..cf6ad81 100644 --- a/nmea2k/raw_message_test.go +++ b/nmea2k/raw_message_test.go @@ -233,4 +233,15 @@ func TestPgn127489NumberExtraction(t *testing.T) { if ok { t.Errorf("the value for the field 'total engine hours' is invalid: (%d). Need to check maximum value during extraction. RawMessage: %+v\n", engineHours, pgnParsed.Data[6]) } + + // This RawMessage is the 'BAD' one with invalid values. Field 6 should be 'nil' with the proper validation. + msg = RawMessage{new(can.RawMessage)} + msg.Data = []byte{0x00, 0xb0, 0x09, 0xff, 0xff, 0xab, 0x7c, 0xff, 0x7f, 0x15, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x60, 0x02, 0xff, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x05} + msg.Pgn = uint32(127489) + + pgnParsed = ParsePacket(msg.RawMessage) + alternator, ok := pgnParsed.Data[4].(float64) + if ok { + t.Errorf("the value for the field 'alternator_potential' is invalid: (%f). Need to check maximum value during extraction. RawMessage: %+v\n", alternator, pgnParsed.Data[4]) + } }