Commits

Anonymous committed f057cec Merge

merged

  • Participants
  • Parent commits 97dbfa1, 826d8fc

Comments (0)

Files changed (7)

caprunner/interpreter/__init__.py

         return self.frames.current
 
     def echo(self, string):
-        msg = "  " * len(self.frames) + str(string)
+        msg = str(len(self.frames)) + "  " * len(self.frames) + str(string)
         self._log.append( msg )
 
     def resetlog(self):
             self.echo("caught exception: %s" % type(e))
             while not isinstance(self.frame, DummyFrame):
                 # for all frames not being the current one, ip is already tainted
+                # as-in it's already pointing to the next instruction
                 if self.frame is frame:
                     ip = self.frame.ip
                 else:
-                    # This hopes that exceptions will not happend on 
+                    # This hopes that exceptions will not happend on
                     # branching bytecode ...
+                    # Else, we cannot easily find the ip of the originating instruction
                     ip = self.frame.ip - self.frame.instrsize
-                    
+
                 for handler in self.frame.handlers:
                     if ip in handler:
                         if handler.match(e):
                             self.echo("exception handled: ip = %d" % handler.handler_offs)
                             self.frame.ip = handler.handler_offs
                             self.frame.push(e)
-                            return
+                            return True
                         else:
                             self.echo("handler doesn't match exception")
                         if handler.last:
     def stableswitch(self, default, low, high, *offsets):
         index = self.frame.pop()
         try:
-            return utils.signed2(offsets[index - low])
+            return utils.signed2(offsets[index - utils.signed2(low)])
         except IndexError:
             return utils.signed2(default)
 
             # null can be casted to any reference
             return
         # First determine type to check against
-        types = {10: bool, 11: int, 12: int, 13: int}
+        types = {10: bool, # boolean
+                 11: int,  # byte
+                 12: int,  # short
+                 13: int}  # int
         if atype in types:
-            type = types[atype]
+            _type = types[atype]
         else:
-            type = self.resolver.resolveIndex(index, self.cap_file).cls
+            _type = self.resolver.resolveIndex(index, self.cap_file).cls
         # Then check it ...
-        if atype == 14:
+        if atype == 14: # reference
             if not isinstance(objectref, list):
                 raise python.lang.ClassCastException
             for elem in objectref:
-                if not isinstance(elem, list):
+                if not isinstance(elem, _type):
                     raise python.lang.ClassCastException
         else:
-            if not isinstance(objectref, type):
+            if isinstance(objectref, list):
+                for elem in objectref:
+                    if not isinstance(elem, _type):
+                        raise python.lang.ClassCastException
+            elif not isinstance(objectref, _type):
                 raise python.lang.ClassCastException
 
     def instanceof(self, atype, index):

caprunner/resolver.py

     def __init__(self, version=(3,0,1)):
         # load preprocessed pickle from all the exp files
         f = open({(2,1,2): '2.1.2.json',
+                  (2,2,1): '2.2.1.json',
                   (2,2,2): '2.2.2.json',
                   (3,0,1): '3.0.1.json'}[version])
         struct = json.loads(f.read())

caprunner/token.py

 This is a Python token, it reprsents a Token + the CardManager
 
 """
+import traceback
 
 from pythoncard.framework import Applet, ISO7816, ISOException, APDU, JCSystem, AID
 
             return [signed1((sw & 0xff00) >> 8), signed1(sw & 0x00ff)]
         except RuntimeException:
             self.echo("Caught RuntimeException")
+            for line in traceback.format_exc().splitlines():
+                self.echo(line)
             return d2a('\x6f\x00')
         except:
             self.echo("Real bad exception")

caprunner/utils.py

     return signed(value, 1)
 
 def signed2(value):
+    """
+    >>> signed2(0xffff)
+    -1
+    """
     return signed(value, 2)
 
 def signed4(value):
                     if filename.endswith('.exp'):
                         if options.verbose: print "Processing %s" % os.path.join(dirname, filename)
                         # Good to go !
-                        f = open(os.path.join(dirname, filename))
+                        f = open(os.path.join(dirname, filename), 'rb')
                         exp = ExportFile(f.read())
                         refs = process(exp, options)
                         res.append(refs)
         else:
-            f = open(path)
+            f = open(path, 'rb')
             exp = ExportFile(f.read())
             refs = process(exp, options)
             res.append(refs)
 
 from caprunner.exportfile import ExportFile
 
-f = open(sys.argv[1])
+f = open(sys.argv[1], 'rb')
 exp = ExportFile(f.read())
 exp.pprint()
 import sys
 
 from caprunner import capfile
-from caprunner.utils import s2a, a2s
+from caprunner.utils import a2s, signed1
 
 from caprunner.token import Token
 
+def hexify(hexStr):
+    """
+    Turns a string of hexadecimal nibbles into an array of numbers
+    >>> hexify("00200003083132333400000000")
+    [0, 36, 0, 3, 8, 49, 50, 51, 52, 0, 0, 0, 0]
+    """
+    bytes = []
+    hexStr = ''.join( hexStr.split() )
+    for i in xrange(0, len(hexStr), 2):
+        bytes.append( signed1( int (hexStr[i:i+2], 16 ) ) )
+    return bytes
+
 class Runner(Token):
 
     def checkreceive(self, expected, received):
         receive = []
         for line in sys.stdin:
             line = line.rstrip()
+            if '--' in line:
+                line = line[:line.find('--')]
             if len(line) == 0 and len(send) != 0 and len(receive) != 0:
                 print "==> %s" % a2s(send)
                 try:
                 send = []
                 receive = []
             if line[:4] == "==> ":
-                send.extend(s2a(line[4:]))
+                send.extend(hexify(line[4:]))
             elif line[:4] == "<== ":
-                receive.extend(s2a(line[4:]))
+                receive.extend(hexify(line[4:]))
             elif line.startswith('install:'):
                 sep1 = 8
                 sep2 = line.find(':', sep1+1)
-                data = s2a(line[sep1:sep2])
-                offset = s2a(line[sep2 + 1:])[0]
+                data = hexify(line[sep1:sep2])
+                offset = hexify(line[sep2 + 1:])[0]
                 self.install(data, offset)
             elif line.startswith('load:'):
                 self.vm.load(capfile.CAPFile(line[5:].strip()))