laforge has submitted this change. ( https://gerrit.osmocom.org/c/pysim/+/35797?usp=email )
Change subject: global_platform 'put_key': constrain ranges of KVN + KID in argparse ......................................................................
global_platform 'put_key': constrain ranges of KVN + KID in argparse
The earlier we catch errors in user input, the better.
Change-Id: Icee656f1373a993b6883ffaab441fe178c0fe8cb --- M pySim/global_platform/__init__.py M pySim/utils.py 2 files changed, 27 insertions(+), 3 deletions(-)
Approvals: Jenkins Builder: Verified laforge: Looks good to me, approved
diff --git a/pySim/global_platform/__init__.py b/pySim/global_platform/__init__.py index 6793f71..25b0d02 100644 --- a/pySim/global_platform/__init__.py +++ b/pySim/global_platform/__init__.py @@ -501,9 +501,9 @@ return data
put_key_parser = argparse.ArgumentParser() - put_key_parser.add_argument('--old-key-version-nr', type=auto_int, default=0, help='Old Key Version Number') - put_key_parser.add_argument('--key-version-nr', type=auto_int, required=True, help='Key Version Number') - put_key_parser.add_argument('--key-id', type=auto_int, required=True, help='Key Identifier (base)') + put_key_parser.add_argument('--old-key-version-nr', type=auto_uint8, default=0, help='Old Key Version Number') + put_key_parser.add_argument('--key-version-nr', type=auto_uint8, required=True, help='Key Version Number') + put_key_parser.add_argument('--key-id', type=auto_uint7, required=True, help='Key Identifier (base)') put_key_parser.add_argument('--key-type', choices=KeyType.ksymapping.values(), action='append', required=True, help='Key Type') put_key_parser.add_argument('--key-data', type=is_hexstr, action='append', required=True, help='Key Data Block') put_key_parser.add_argument('--key-check', type=is_hexstr, action='append', help='Key Check Value') diff --git a/pySim/utils.py b/pySim/utils.py index cf95dab..a31fbe0 100644 --- a/pySim/utils.py +++ b/pySim/utils.py @@ -7,6 +7,7 @@ import abc import string import datetime +import argparse from io import BytesIO from typing import Optional, List, Dict, Any, Tuple, NewType
@@ -913,6 +914,18 @@ """Helper function for argparse to accept hexadecimal integers.""" return int(x, 0)
+def _auto_uint(x, max_val: int): + """Helper function for argparse to accept hexadecimal or decimal integers.""" + ret = int(x, 0) + if ret < 0 or ret > max_val: + raise argparse.ArgumentTypeError('Number exceeds permited value range (0, %u)' % max_val) + return ret + +def auto_uint7(x): + return _auto_uint(x, 127) + +def auto_uint8(x): + return _auto_uint(x, 255)
def expand_hex(hexstring, length): """Expand a given hexstring to a specified length by replacing "." or ".."