[M] Change in pysim[master]: pySim-shell: verify apdu commands in scripts and -e options up front
Hoernchen has uploaded this change for review. ( https://gerrit.osmocom.org/c/pysim/+/43727?usp=email ) Change subject: pySim-shell: verify apdu commands in scripts and -e options up front ...................................................................... pySim-shell: verify apdu commands in scripts and -e options up front Statically verify -e parameters and scripts so we don't end up with half executed command chains that leave the card in a weird state due to malformed commands. This is a structural check, and not a strict mode linter, it will not magically fix a case 4 with missing Le that looks like a valid case 3! run_script, bulk_script and the @ / @@ shortcuts are followed recursively, aliases and macros are not resolved. Change-Id: Ida84b982d7577faa5b37f121599a59bcb2feefec --- M pySim-shell.py A tests/unittests/test_shell_startup_verify.py 2 files changed, 195 insertions(+), 0 deletions(-) git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/27/43727/1 diff --git a/pySim-shell.py b/pySim-shell.py index 0169f38..a7e22e1 100755 --- a/pySim-shell.py +++ b/pySim-shell.py @@ -61,6 +61,9 @@ from pySim.exceptions import * from pySim.transport import init_reader, ApduTracer, argparse_add_reader_args, ProactiveHandler from pySim.utils import sanitize_pin_adm, tabulate_str_list, boxed_heading_str, dec_iccid, sw_match +from pySim.utils import parse_command_apdu +import contextlib +import shlex from pySim.card_handler import CardHandler, CardHandlerAuto from pySim.filesystem import CardMF, CardEF, CardDF, CardADF, LinFixedEF, TransparentEF, BerTlvEF @@ -1106,6 +1109,86 @@ # TODO: implement the basics, such as SMS Sending, ... +def verify_startup_apdus(commands: List[tuple]) -> List[str]: + """Statically verify the apdu commands among the given startup commands before anything + is executed. A structurally invalid APDU (bad hex, Lc contradicting the length of the + data field) raises in the transport layer whatever apdu_strict says, so with scripts or + stacked -e options it would abort the run midway, after the preceding commands already + ran against the card. run_script, bulk_script and the @ / @@ shortcuts are followed and + their lines verified the same way. Aliases and macros are not resolved. + + Args: + commands : list of (location, command line) tuples + Returns: + list of human readable findings, empty when all lines pass + """ + findings = [] + visited_scripts = set() + run_script_parser = cmd2.Cmd._build_run_script_parser() + + def split_line(line: str) -> List[str]: + try: + return shlex.split(line) + except ValueError: + return line.split() + + def parse_args(loc: str, line: str, parser, args: List[str]): + """argparse exits on error and on --help, report both as a finding""" + out = StringIO() + try: + with contextlib.redirect_stderr(out), contextlib.redirect_stdout(out): + return parser.parse_args(args) + except SystemExit: + lines = out.getvalue().strip().splitlines() + findings.append('%s: "%s": %s' % (loc, line, lines[-1] if lines else 'invalid arguments')) + return None + + def check_line(loc: str, line: str, base_dir: str): + tokens = split_line(line.strip()) + if not tokens or tokens[0].startswith('#'): + return + if tokens[0].startswith('@'): + # cmd2 shortcuts: @ is run_script, @@ is run_script relative to the current script + relative = tokens[0].startswith('@@') + rest = tokens[0].lstrip('@') + tokens = ['run_script'] + ([rest] if rest else []) + tokens[1:] + if not relative: + base_dir = os.getcwd() + if tokens[0] == 'run_script': + opts = parse_args(loc, line, run_script_parser, tokens[1:]) + if opts: + check_script(loc, os.path.join(base_dir, opts.script_path)) + elif tokens[0] == 'bulk_script': + opts = parse_args(loc, line, PysimApp.bulk_script_parser, tokens[1:]) + if opts: + check_script(loc, os.path.join(base_dir, opts.SCRIPT_PATH)) + elif tokens[0] == 'apdu': + opts = parse_args(loc, line, PysimApp.apdu_cmd_parser, tokens[1:]) + if opts is None: + return + try: + parse_command_apdu(h2b(opts.APDU)) + except ValueError as e: + findings.append('%s: "%s": %s' % (loc, line, e)) + + def check_script(loc: str, path: str): + rpath = os.path.realpath(path) + if rpath in visited_scripts: + return + visited_scripts.add(rpath) + try: + with open(path, 'r') as f: + lines = f.readlines() + except OSError as e: + findings.append('%s: script %s not readable (%s)' % (loc, path, e.strerror)) + return + for num, line in enumerate(lines, 1): + check_line('%s:%d' % (path, num), line.rstrip('\n'), os.path.dirname(rpath)) + + for loc, cmd in commands: + check_line(loc, cmd, os.getcwd()) + return findings + option_parser = argparse.ArgumentParser(description='interactive SIM card shell', formatter_class=argparse.ArgumentDefaultsHelpFormatter) @@ -1147,6 +1230,19 @@ # Ensure that we are able to print formatted warnings from the beginning. PySimLogger.setup(print, {logging.WARN: YELLOW}, opts.verbose) + # Refuse malformed apdu commands in startup commands and scripts before touching the card. + startup_commands = [('-e option %d' % (num + 1), cmd) for num, cmd in enumerate(opts.execute_command)] + if opts.command: + startup_commands.append(('command', '{} {}'.format(opts.command, ' '.join(opts.command_args)))) + if opts.script: + startup_commands.append(('--script', 'run_script %s' % opts.script)) + findings = verify_startup_apdus(startup_commands) + if findings: + for f in findings: + print("Error: %s" % f) + print("Malformed APDUs in startup commands, nothing executed.") + sys.exit(2) + # Init card key provider for automatic card key retrieval card_key_provider_init(opts) diff --git a/tests/unittests/test_shell_startup_verify.py b/tests/unittests/test_shell_startup_verify.py new file mode 100644 index 0000000..18d04e5 --- /dev/null +++ b/tests/unittests/test_shell_startup_verify.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 + +# (C) 2026 by sysmocom - s.f.m.c. GmbH +# All Rights Reserved +# +# Author: Eric Wild <ewild@sysmocom.de> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import importlib.util +import os +import tempfile +import unittest + +_shell_path = os.path.join(os.path.dirname(__file__), '..', '..', 'pySim-shell.py') +_spec = importlib.util.spec_from_file_location('pysim_shell', _shell_path) +pysim_shell = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(pysim_shell) +verify = pysim_shell.verify_startup_apdus + + +class VerifyStartupApdus_Test(unittest.TestCase): + + def test_valid(self): + self.assertEqual(verify([ + ('l1', 'apdu 00a4000400'), # case 2 + ('l2', 'apdu 00a40004023f00'), # case 3 + ('l3', 'apdu 00a40004023f0000'), # case 4 + ('l4', 'apdu --expect-sw 9000 00a40004023f0000'), # options before the APDU + ('l5', 'select MF'), # non-apdu lines pass through + ('l6', '# apdu zz'), # comment + ('l7', ''), + ]), []) + + def test_malformed(self): + findings = verify([ + ('l1', 'apdu 00a40004022fe20000'), # Lc 2, three body bytes + ('l2', 'apdu 00a40004052fe2'), # Lc 5, two data bytes + ('l3', 'apdu 00a4zz'), # not hex, rejected by the argparser + ('l4', 'apdu'), # missing argument + ('l5', 'apdu 00a40004023f0000'), # valid, must not be dragged down by l1-l4 + ]) + self.assertEqual(len(findings), 4) + for expect_loc, finding in zip(['l1', 'l2', 'l3', 'l4'], findings): + self.assertTrue(finding.startswith(expect_loc + ':')) + + def test_script_expansion(self): + with tempfile.TemporaryDirectory() as d: + inner = os.path.join(d, 'inner.script') + outer = os.path.join(d, 'outer.script') + with open(inner, 'w') as f: + f.write('apdu 00a40004052fe2\n') + with open(outer, 'w') as f: + f.write('select MF\nrun_script %s\nrun_script %s\napdu 00a4000403aabb\n' % (inner, outer)) + findings = verify([('--script', 'run_script %s' % outer)]) + self.assertEqual(len(findings), 2) + self.assertTrue(findings[0].startswith('%s:1:' % inner)) # via nested run_script + self.assertTrue(findings[1].startswith('%s:4:' % outer)) # self reference recursed only once + missing = verify([('--script', 'run_script %s' % os.path.join(d, 'nonexistent'))]) + self.assertEqual(len(missing), 1) + self.assertIn('not readable', missing[0]) + + def test_script_command_variants(self): + with tempfile.TemporaryDirectory() as d: + bad = os.path.join(d, 'bad.script') + with open(bad, 'w') as f: + f.write('apdu 00a40004052fe2\n') + with open(os.path.join(d, 'outer.script'), 'w') as f: + f.write('@@bad.script\n@@ bad.script\n') + for line in ('run_script -t %s %s' % (os.path.join(d, 'transcript'), bad), + 'bulk_script --tries 3 %s' % bad, + 'bulk_script %s --halt_on_error' % bad, + '@%s' % bad, + '@ %s' % bad, + 'run_script %s' % os.path.join(d, 'outer.script')): + with self.subTest(line=line): + findings = verify([('l1', line)]) + self.assertEqual(len(findings), 1) + self.assertTrue(findings[0].startswith('%s:1:' % bad)) + + def test_bad_arguments(self): + findings = verify([('l1', 'apdu -h'), ('l2', 'apdu --bogus 00a4000400'), + ('l3', 'run_script --bogus x'), ('l4', 'bulk_script')]) + self.assertEqual([f.split(':')[0] for f in findings], ['l1', 'l2', 'l3', 'l4']) + + +if __name__ == '__main__': + unittest.main() -- To view, visit https://gerrit.osmocom.org/c/pysim/+/43727?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: pysim Gerrit-Branch: master Gerrit-Change-Id: Ida84b982d7577faa5b37f121599a59bcb2feefec Gerrit-Change-Number: 43727 Gerrit-PatchSet: 1 Gerrit-Owner: Hoernchen <ewild@sysmocom.de>
participants (1)
-
Hoernchen