srsRAN_Project icon indicating copy to clipboard operation
srsRAN_Project copied to clipboard

Problem in ASN.1 UPER Enumerated Unpacking

Open zhouxt1 opened this issue 2 months ago • 1 comments

Hi,

I found that the enum_unpack in lib/asn1/asn1_utils.cpp has some issues.

SRSASN_CODE pack_enum(bit_ref& bref, uint32_t enum_val, uint32_t nbits, uint32_t nof_noext)
{
  bool ext = enum_val >= nof_noext;
  HANDLE_CODE(bref.pack((bool)ext, 1));
  SRSASN_CODE ret;
  if (not ext) {
    ret = bref.pack(enum_val, nbits);
    // Potential fix: add some checks if enum_val is within the root
  } else {
    ret = pack_norm_small_non_neg_whole_number(bref, enum_val - nof_noext);
  }
  return ret;
}

The issue can be explained with this small example,

S1 ::= ENUMERATED { e1, e2, e3, ..., e4 }

The correct encoding of e4 should be [ 1 | 0000000 ] in binary. However, here the code would accept [ 0 | 11 ] as e4 instead of rejecting it.

To fix it, simply add a check to see if enum_val is within the root.

zhouxt1 avatar Oct 20 '25 21:10 zhouxt1

Sorry, I included the wrong function. Here's the correct one,

ValOrError unpack_enum(uint32_t nof_types, uint32_t nof_exts, bool has_ext, cbit_ref& bref)
{
  ValOrError ret;
  if (has_ext) {
    uint32_t nof_bits = (uint32_t)std::ceil(std::log2(nof_types - nof_exts));
    bool     ext;
    ret.code = bref.unpack(ext, 1);
    if (ret.code != SRSASN_SUCCESS) {
      return ret;
    }
    if (not ext) {
      ret.code = bref.unpack(ret.val, nof_bits);
      // Suggestion: Could check if ret.val < (nof_types - nof_exts); otherwise fails
    } else {
      ret.code = unpack_norm_small_non_neg_whole_number(ret.val, bref);
      ret.val += nof_types - nof_exts;
    }
  } else {
    uint32_t nof_bits = (uint32_t)std::ceil(std::log2(nof_types));
    ret.code          = bref.unpack(ret.val, nof_bits);
  }
  if (ret.val >= nof_types) {
    log_error("The provided enum is not within the range of possible values ({}>={})",
              (unsigned)ret.val,
              (unsigned)nof_types);
    ret.code = SRSASN_ERROR_DECODE_FAIL;
  }
  return ret;
}

zhouxt1 avatar Oct 20 '25 22:10 zhouxt1