NOAA-EMC / NCEPLIBS-g2c

This library contains C decoder/encoder routines for GRIB edition 2.
Other
17 stars 11 forks source link

Potential undefined value in specpack and simpack functions #487

Open LightningRS opened 4 months ago

LightningRS commented 4 months ago

During a recent analysis of our project using our internally developed static analysis tool, canalyze, we discovered a potential issue with undefined values in the specpack and simpack functions.

Execution path:

  1. In specpack.c at line 33, the input parameter MM for the specpack function is of type g2int, which is a signed integer type.
  2. In specpack.c at line 57, memory space for the tfld array is dynamically allocated.
  3. In specpack.c within lines 63-84, the tfld array is assigned values at lines 80-81.
  4. If the input parameter MM has a negative value, the for-loop starting in specpack.c at line 63 will not execute, leaving the elements of the tfld array uninitialized.
  5. In specpack.c at line 103, the simpack function is called, passing in the pointer to the uninitialized tfld array.
  6. In simpack.c at lines 56-57 the simpack function directly accesses the first element of the fld array using fld[0], at which point this value is an undefined value.

When the specpack function is called with an inadvertently negative MM value, it may lead to the aforementioned issue with undefined values.

Suggested fix: Change the type of input parameter MM for the specpack function to g2intu, which is an unsigned integer type.

edwardhartnett commented 4 months ago

Thanks for this, I will take a look and fix this for the next release...