From 4e59d89a5dec1df4700bf732c1802cf6bfcec38b Mon Sep 17 00:00:00 2001 From: Harald Welte Date: Wed, 1 Nov 2023 23:40:07 +0100 Subject: [PATCH] pySim-shell: Validate that argument to 'apdu' command is proper hexstr Let's not even send anything to the card if it's not an even number of hexadecimal digits Change-Id: I58465244101cc1a976e5a17af2aceea1cf9f9b54 --- pySim-shell.py | 4 ++-- pySim/utils.py | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pySim-shell.py b/pySim-shell.py index c2bb15c2..d9c9f8ce 100755 --- a/pySim-shell.py +++ b/pySim-shell.py @@ -53,7 +53,7 @@ from pySim.transport import init_reader, ApduTracer, argparse_add_reader_args, P from pySim.cards import card_detect, SimCardBase, UiccCardBase from pySim.utils import h2b, b2h, i2h, swap_nibbles, rpad, JsonEncoder, bertlv_parse_one, sw_match from pySim.utils import sanitize_pin_adm, tabulate_str_list, boxed_heading_str, Hexstr, dec_iccid -from pySim.utils import is_hexstr_or_decimal +from pySim.utils import is_hexstr_or_decimal, is_hexstr from pySim.card_handler import CardHandler, CardHandlerAuto from pySim.filesystem import CardDF, CardADF, CardModel, CardApplication @@ -322,7 +322,7 @@ Online manual available at https://downloads.osmocom.org/docs/pysim/master/html/ self.equip(card, rs) apdu_cmd_parser = argparse.ArgumentParser() - apdu_cmd_parser.add_argument('APDU', type=str, help='APDU as hex string') + apdu_cmd_parser.add_argument('APDU', type=is_hexstr, help='APDU as hex string') apdu_cmd_parser.add_argument('--expect-sw', help='expect a specified status word', type=str, default=None) @cmd2.with_argparser(apdu_cmd_parser) diff --git a/pySim/utils.py b/pySim/utils.py index 92bf70ff..ea1c9e66 100644 --- a/pySim/utils.py +++ b/pySim/utils.py @@ -1478,3 +1478,12 @@ def is_hexstr_or_decimal(instr: str) -> str: if len(instr) & 1: raise ValueError('Input has un-even number of hex digits') return instr + +def is_hexstr(instr: str) -> str: + """Method that can be used as 'type' in argparse.add_argument() to validate the value consists of + an even sequence of hexadecimal digits only.""" + if not all(c in string.hexdigits for c in instr): + raise ValueError('Input must be hexadecimal') + if len(instr) & 1: + raise ValueError('Input has un-even number of hex digits') + return instr