add contrib/unber.py utility

This tool is a replacement for asn1c 'unber' program with a much more
useful/readable output:
* contains hexadecimal raw tag values
* contains hexdump of value, rather than HTML entities in pseudo-XML

Change-Id: I22c1a461ccba04c2c8caaab7ca29ea6ae76e2ea3
This commit is contained in:
Harald Welte 2024-01-06 20:00:14 +01:00 committed by laforge
parent 242197b53d
commit d657708df2
1 changed files with 39 additions and 0 deletions

39
contrib/unber.py Executable file
View File

@ -0,0 +1,39 @@
#!/usr/bin/env python3
# A more useful verion of the 'unber' tool provided with asn1c:
# Give a hierarchical decode of BER/DER-encoded ASN.1 TLVs
import sys
import argparse
from pySim.utils import bertlv_parse_one, bertlv_encode_tag, b2h, h2b
def process_one_level(content: bytes, indent: int):
remainder = content
while len(remainder):
tdict, l, v, remainder = bertlv_parse_one(remainder)
#print(tdict)
rawtag = bertlv_encode_tag(tdict)
if tdict['constructed']:
print("%s%s l=%d" % (indent*" ", b2h(rawtag), l))
process_one_level(v, indent + 1)
else:
print("%s%s l=%d %s" % (indent*" ", b2h(rawtag), l, b2h(v)))
option_parser = argparse.ArgumentParser(description='BER/DER data dumper')
group = option_parser.add_mutually_exclusive_group(required=True)
group.add_argument('--file', help='Input file')
group.add_argument('--hex', help='Input hexstring')
if __name__ == '__main__':
opts = option_parser.parse_args()
if opts.file:
with open(opts.file, 'rb') as f:
content = f.read()
elif opts.hex:
content = h2b(opts.hex)
process_one_level(content, 0)