Harald Welte | 21caf32 | 2022-07-16 14:06:46 +0200 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | import sys |
| 4 | import logging, colorlog |
| 5 | import argparse |
| 6 | from pprint import pprint as pp |
| 7 | |
| 8 | from pySim.apdu import * |
| 9 | from pySim.filesystem import RuntimeState |
| 10 | |
| 11 | from pySim.cards import UsimCard |
| 12 | from pySim.commands import SimCardCommands |
| 13 | from pySim.profile import CardProfile |
| 14 | from pySim.ts_102_221 import CardProfileUICCSIM |
| 15 | from pySim.ts_31_102 import CardApplicationUSIM |
| 16 | from pySim.ts_31_103 import CardApplicationISIM |
| 17 | from pySim.transport import LinkBase |
| 18 | |
| 19 | from pySim.apdu_source.gsmtap import GsmtapApduSource |
| 20 | from pySim.apdu_source.pyshark_rspro import PysharkRsproPcap, PysharkRsproLive |
| 21 | |
| 22 | from pySim.apdu.ts_102_221 import UiccSelect, UiccStatus |
| 23 | |
| 24 | log_format='%(log_color)s%(levelname)-8s%(reset)s %(name)s: %(message)s' |
| 25 | colorlog.basicConfig(level=logging.INFO, format = log_format) |
| 26 | logger = colorlog.getLogger() |
| 27 | |
| 28 | # merge all of the command sets into one global set. This will override instructions, |
| 29 | # the one from the 'last' set in the addition below will prevail. |
| 30 | from pySim.apdu.ts_102_221 import ApduCommands as UiccApduCommands |
| 31 | from pySim.apdu.ts_31_102 import ApduCommands as UsimApduCommands |
| 32 | from pySim.apdu.global_platform import ApduCommands as GpApduCommands |
| 33 | ApduCommands = UiccApduCommands + UsimApduCommands #+ GpApduCommands |
| 34 | |
| 35 | |
| 36 | class DummySimLink(LinkBase): |
| 37 | """A dummy implementation of the LinkBase abstract base class. Currently required |
| 38 | as the UsimCard doesn't work without SimCardCommands, which in turn require |
| 39 | a LinkBase implementation talking to a card. |
| 40 | |
| 41 | In the tracer, we don't actually talk to any card, so we simply drop everything |
| 42 | and claim it is successful. |
| 43 | |
| 44 | The UsimCard / SimCardCommands should be refactored to make this obsolete later.""" |
| 45 | def __init__(self, debug: bool = False, **kwargs): |
| 46 | super().__init__(**kwargs) |
| 47 | self._debug = debug |
| 48 | self._atr = h2i('3B9F96801F878031E073FE211B674A4C753034054BA9') |
| 49 | |
| 50 | def _send_apdu_raw(self, pdu): |
| 51 | #print("DummySimLink-apdu: %s" % pdu) |
| 52 | return [], '9000' |
| 53 | |
| 54 | def connect(self): |
| 55 | pass |
| 56 | |
| 57 | def disconnect(self): |
| 58 | pass |
| 59 | |
| 60 | def reset_card(self): |
| 61 | return 1 |
| 62 | |
| 63 | def get_atr(self): |
| 64 | return self._atr |
| 65 | |
| 66 | def wait_for_card(self): |
| 67 | pass |
| 68 | |
| 69 | |
| 70 | class Tracer: |
| 71 | def __init__(self, **kwargs): |
| 72 | # we assume a generic SIM + UICC + USIM + ISIM card |
| 73 | profile = CardProfileUICCSIM() |
| 74 | profile.add_application(CardApplicationUSIM()) |
| 75 | profile.add_application(CardApplicationISIM()) |
| 76 | scc = SimCardCommands(transport=DummySimLink()) |
| 77 | card = UsimCard(scc) |
| 78 | self.rs = RuntimeState(card, profile) |
| 79 | # APDU Decoder |
| 80 | self.ad = ApduDecoder(ApduCommands) |
| 81 | # parameters |
| 82 | self.suppress_status = kwargs.get('suppress_status', True) |
| 83 | self.suppress_select = kwargs.get('suppress_select', True) |
| 84 | self.source = kwargs.get('source', None) |
| 85 | |
| 86 | def format_capdu(self, inst: ApduCommand): |
| 87 | """Output a single decoded + processed ApduCommand.""" |
| 88 | print("%02u %-16s %-35s %-8s %s %s" % (inst.lchan_nr, inst._name, inst.path_str, inst.col_id, inst.col_sw, inst.processed)) |
| 89 | print("===============================") |
| 90 | |
| 91 | def main(self): |
| 92 | """Main loop of tracer: Iterates over all Apdu received from source.""" |
| 93 | while True: |
| 94 | # obtain the next APDU from the source (blocking read) |
| 95 | apdu = self.source.read() |
| 96 | #print(apdu) |
| 97 | |
| 98 | if isinstance(apdu, CardReset): |
| 99 | self.rs.reset() |
| 100 | continue |
| 101 | |
| 102 | # ask ApduDecoder to look-up (INS,CLA) + instantiate an ApduCommand derived |
| 103 | # class like 'UiccSelect' |
| 104 | inst = self.ad.input(apdu) |
| 105 | # process the APDU (may modify the RuntimeState) |
| 106 | inst.process(self.rs) |
| 107 | |
| 108 | # Avoid cluttering the log with too much verbosity |
| 109 | if self.suppress_select and isinstance(inst, UiccSelect): |
| 110 | continue |
| 111 | if self.suppress_status and isinstance(inst, UiccStatus): |
| 112 | continue |
| 113 | #print(inst) |
| 114 | self.format_capdu(inst) |
| 115 | |
| 116 | option_parser = argparse.ArgumentParser(prog='pySim-trace', description='Osmocom pySim high-level SIM card trace decoder', |
| 117 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
| 118 | |
| 119 | global_group = option_parser.add_argument_group('General Options') |
| 120 | global_group.add_argument('--no-suppress-select', help="Don't suppress displaying SELECT APDUs") |
| 121 | global_group.add_argument('--no-suppress-status', help="Don't suppress displaying STATUS APDUs") |
| 122 | |
| 123 | subparsers = option_parser.add_subparsers(help='APDU Source', dest='source', required=True) |
| 124 | |
| 125 | parser_gsmtap = subparsers.add_parser('gsmtap-udp', help='Live capture of GSMTAP-SIM on UDP port') |
| 126 | parser_gsmtap.add_argument('-i', '--bind-ip', default='127.0.0.1', |
| 127 | help='Local IP address to which to bind the UDP port') |
| 128 | parser_gsmtap.add_argument('-p', '--bind-port', default=4729, |
| 129 | help='Local UDP port') |
| 130 | |
| 131 | parser_rspro_pyshark_pcap = subparsers.add_parser('rspro-pyshark-pcap', help=""" |
| 132 | PCAP file containing RSPRO (osmo-remsim) communication; processed via pyshark. |
| 133 | REQUIRES OSMOCOM PATCHED WIRESHARK!""") |
| 134 | parser_rspro_pyshark_pcap.add_argument('-f', '--pcap-file', required=True, |
| 135 | help='Name of the PCAP[ng] file to be read') |
| 136 | |
| 137 | parser_rspro_pyshark_live = subparsers.add_parser('rspro-pyshark-live', help=""" |
| 138 | Live capture of RSPRO (osmo-remsim) communication; processed via pyshark. |
| 139 | REQUIRES OSMOCOM PATCHED WIRESHARK!""") |
| 140 | parser_rspro_pyshark_live.add_argument('-i', '--interface', required=True, |
| 141 | help='Name of the network interface to capture on') |
| 142 | |
| 143 | if __name__ == '__main__': |
| 144 | |
| 145 | opts = option_parser.parse_args() |
| 146 | pp(opts) |
| 147 | |
| 148 | logger.info('Opening source %s...' % opts.source) |
| 149 | if opts.source == 'gsmtap-udp': |
| 150 | s = GsmtapApduSource(opts.bind_ip, opts.bind_port) |
| 151 | elif opts.source == 'rspro-pyshark-pcap': |
| 152 | s = PysharkRsproPcap(opts.pcap_file) |
| 153 | elif opts.source == 'rspro-pyshark-live': |
| 154 | s = PysharkRsproLive(opts.interface) |
| 155 | |
| 156 | tracer = Tracer(source=s) |
| 157 | logger.info('Entering main loop...') |
| 158 | tracer.main() |
| 159 | |