MatrixEditor / hiktools

Python & C++ library for working with hikvision firmware/ SADP packets/ SADP Tool functionalities
MIT License
11 stars 0 forks source link

Checksum Algorithm mismatch #4

Closed MatrixEditor closed 1 year ago

MatrixEditor commented 1 year ago

Checksum Algorithm

Although, the checksum algorithm is discovered and decompiled here, the implemented method in python always returns a wrong result.

Description of the algorithm

The call which is done in BuildSADPPacket() is the following:

 uVar7 = Checksum(
    *(ushort **)(buffer + 0x14), 
    (uint)*(byte *)((int)*(ushort **)(buffer + 0x14) + 3)
 );

Note, that the conversion to unsigned short * will produce a pointer that combine two bytes each position. Therefore, +3 at the end has the following effect:

  ubyte *buf = [0x10, 0x20, 0x30, 0x40];
  ushort *dest = (ushort *)buf;
  //           = [0x1020, 0x3040] 

The next step is to convert the returned unsigned short value into a single byte value:

  ushort *buf = [0x1020, 0x3040]
  byte dest = *((byte *)buf)
  //        = 0x10

The input buffer is the following:

  ┌───────────────────────────────────────────────┐
  │Buffer Structure                               │
  ├─────────┬─────────┬─────┬─────┬─────────┬─────┤
  │0x21 0x02│0x01 0x42│.. ..│.. ..│0x06 0x04│.. ..│
  └─────────┴─────────┴─────┴─────┴─────────┴─────┘

Basically, the algorithm adds the uint16 values starting from position 0 until a index variable is reaching 0. Even if the values are copied from a packed which was sent by the SADP Tool there is a checksum mismatch.

MatrixEditor commented 1 year ago

This issue has been fixed since patch version 1.1.0. The main algorithm implementation was correct, only the input parameters were interpreted wrong. See checksum.h for details on the arguments.