Commit 05cf083b authored by Ruud Schramp's avatar Ruud Schramp
Browse files

Added a small test program to dump ETSI-LI data to XML

parent f0a893d1
Loading
Loading
Loading
Loading
Loading
+16 −5
Changes for testing/asn/asn_build_gambas.py: 16 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -31,6 +31,16 @@ BUILD_DIR = Path(os.environ.get("GAMBAS_BUILD_DIR", "build/gambas-asn1"))
DEP_REWRITES = {
    "./testing/deps/33108/": "./testing/deps/33108_v17/",
}
# Schemas whose OCTET STRING fields hold a BER-encoded value that is only
# named in a comment (no CONTAINING): a --container-config sidecar tells
# gambas-asn1 to model them as Containing<inner> and decode/encode them
# eagerly (recursive: the rule applies at every occurrence of the
# generated type). "zero_padding_block" is NOT a built-in: the
# pspdu-nested-codec app registers it (Annex-G zero block padding); code
# that decodes without that registry entry just keeps the raw bytes.
CONTAINER_CONFIGS = {
    "./102232-1/LI-PS-PDU.asn": "testing/gambas/container_fields.json",
}


def buildFiles(target):
@@ -63,11 +73,12 @@ def buildTarget(target, asn1cpp_path, runtime_include):
    objDir.mkdir(parents=True, exist_ok=True)

    files = buildFiles(target)
    p = run(
        [asn1cpp_path, "-fallow-newer-modules", "--remove-stale", "-o", str(genDir)]
        + files,
        capture_output=True,
    )
    command = [asn1cpp_path, "-fallow-newer-modules", "--remove-stale", "-o", str(genDir)]
    config = CONTAINER_CONFIGS.get(primary)
    if config:
        command.append(f"--container-config={config}")
    command += files
    p = run(command, capture_output=True)
    if p.returncode != 0:
        return {
            "ok": False,
+25
Changes for testing/asn/asn_testapp_gambas.py: 25 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -76,6 +76,31 @@ if __name__ == "__main__":
        if rc != 0:
            failures += 1

        # XER dump must not print padding when recursing (inline value) and
        # must print it (as OCTET STRING bytes) when not recursing (hex);
        # either form must import back to the exact padded BER.
        xerInline = buildDir / "roundtrip-rec.xer"
        xerHex = buildDir / "roundtrip-hex.xer"
        for extra in (["--dump", "--recurse"], ["--dump", "--no-recurse"]):
            dst = xerInline if "--recurse" in extra else xerHex
            if runChecked([str(exe)] + extra + [str(out1), str(dst)]) != 0:
                failures += 1
        if xerInline.is_file() and "raw:" in xerInline.read_text():
            print("  FAIL: recurse dump should not print raw bytes/padding")
            failures += 1
        if xerHex.is_file() and "<encryptedPayload>" in xerHex.read_text():
            pass  # hex form prints the OCTET STRING (with padding) by design
        for src in (xerInline, xerHex):
            if not src.is_file():
                failures += 1
                continue
            imported = buildDir / "imported.etsi"
            if runChecked([str(exe), "--import", str(src), str(imported)]) != 0:
                failures += 1
            elif out1.read_bytes() != imported.read_bytes():
                print(f"  FAIL: importing {src.name} did not reproduce the BER")
                failures += 1

    print("")
    if failures:
        print(f"gambas-asn1 nested codec test: {failures} failure(s)")
+53 −15
Changes for testing/gambas/README.md: 53 added lines, 15 removed lines.
Original line number Diff line number Diff line
# testing/gambas — gambas-asn1 test application

`pspdu-nested-codec.cpp` — nested BER decode/re-encode roundtrip
compiled by `testing/asn/asn_testapp_gambas.py` against the library from
`pspdu-nested-codec.cpp` — nested BER decode/re-encode roundtrip compiled
by `testing/asn/asn_testapp_gambas.py` against the library from
`testing/asn/asn_build_gambas.py`. Records are generated from the schema
with the runtime's `RandomFiller` (`--generate N --seed S`), so no wire
data is committed; the tool can also process a capture file when given
one as input.
with the runtime's `RandomFiller` (`--generate N --seed S`, nesting depth
1..3), so no wire data is committed; the tool can also process a capture
file given as input.

Padding (ETSI TS 102 232-1 V3.38.1, Annex G, normative):
## Modes and XER (XML)

- step 2: "BER encode the EncryptedPayload structure and add padding to
  the resulting octet string if necessary (depending on cipher agreed)."
- default: BER in → BER out — re-derive and re-pad every nested container,
  re-decode and assert alignment/padding/value-stability.
- `--dump`: BER in → XER out. `--recurse` (default) prints the decoded
  `EncryptedPayload`, so the wire-level zero padding is **not** shown;
  `--no-recurse` prints the `encryptedPayload` OCTET STRING as hex bytes,
  which **do include** the padding.
- `--import`: XER in → BER out; accepts either dump form, re-applies the
  padding via the encoder and validates as in the default mode.

Usage: `pspdu-nested-codec [--generate N [--seed S]] [--pad-block N]
[--recurse|--no-recurse] [--dump|--import] [in] [out]` (with `--generate`
the single positional is the output).

## Nesting via the sidecar

`container_fields.json` is passed to `asn1cpp` as `--container-config`
when building the LI-PS-PDU library. It declares
`EncryptionContainer.encryptedPayload` (when `encryptionType == none`) as a
`Containing<EncryptedPayload>`, because the schema names that inner type
only in a comment (no `CONTAINING`). The eager decode is therefore applied
at *every* `EncryptionContainer` occurrence — `EncryptedPayload.payload` can
itself carry an `EncryptionContainer` — so the tool decodes/re-pads the
whole nested tree with no hand-written per-level logic.

## Padding (ETSI TS 102 232-1 V3.38.1, Annex G, normative)

- step 2: "BER encode the EncryptedPayload structure and add padding to the
  resulting octet string if necessary (depending on cipher agreed)."
- "If padding is needed, it shall be all zeros."

The block size is the agreed cipher's: AES-CBC variants in the
EncryptionType enum use a 128-bit block, so padding aligns to 16 octets
(default; `--pad-block 8` for blowfish/threedes). Padding is added only
when needed (a block-aligned value gets no padding). The decoder side
decodes the BER value first and requires everything after it to be zeros
— values may legitimately end in 0x00, so trailing zeros must not be
stripped before decoding.
Block size is the agreed cipher's: AES-CBC uses a 128-bit block → **16
octets** (default; `--pad-block 8` for blowfish/threedes). Padding is added
only when needed (a block-aligned value gets none).

The sidecar names the decoder `zero_padding_block`, which is **not** a
built-in (`zero_padding` decodes correctly but its encoder adds no padding;
`pkcs7` pads but with RFC-5690 octet values). The app registers it via
`ContainedDecoders::add` and passes it to both codecs through
`ContainedOptions`:

- decode: decode one value from the whole buffer, then require the remainder
  to be all `0x00` (never strip trailing zeros first — a value may
  legitimately end in `0x00`).
- encode: write the value, then append `0x00` up to the next block multiple.

Raw bytes are authoritative unless a contained value is modified, so the
tool marks every nested `none` container dirty to force the encoder to
re-derive and re-pad; it then re-decodes and asserts each level is
block-aligned, zero-padded, and decodes to the same value.
+12
Changes for testing/gambas/container_fields.json: 12 added lines, 0 removed lines.
Original line number Diff line number Diff line
{
  "container_fields": [
    {
      "module": "LI-PS-PDU",
      "type": "EncryptionContainer",
      "field": "encryptedPayload",
      "inner_type": "EncryptedPayload",
      "decoder": "zero_padding_block",
      "when": { "member": "encryptionType", "equals": "none" }
    }
  ]
}
+393 −164

File changed.

Preview size limit exceeded, changes collapsed.