Skip to content

Commit

Permalink
fixed more Python 3 issues
Browse files Browse the repository at this point in the history
also fixes the debug output
  • Loading branch information
frankmorgner committed May 3, 2018
1 parent 3b7c04c commit 04642a3
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 70 deletions.
16 changes: 8 additions & 8 deletions virtualsmartcard/src/vpicc/virtualsmartcard/SEutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ def parse_SM_CAPDU(self, CAPDU, authenticate_header):
# if expected != "":
# raise SwError(SW["ERR_SECMESSOBJECTSMISSING"])

if isinstance(le, str):
if isinstance(le, bytes):
# FIXME: C_APDU only handles le with strings of length 1.
# Better patch utils.py to support extended length apdus
le_int = stringtoint(le)
Expand Down Expand Up @@ -702,23 +702,23 @@ def generate_public_key_pair(self, p1, p2, data):
# Encode keys
if cipher == "RSA":
# Public key
n = str(PublicKey.__getstate__()['n'])
e = str(PublicKey.__getstate__()['e'])
n = inttostring(PublicKey.__getstate__()['n'])
e = inttostring(PublicKey.__getstate__()['e'])
pk = ((0x81, len(n), n), (0x82, len(e), e))
result = bertlv_pack(pk)
# Private key
d = PublicKey.__getstate__()['d']
elif cipher == "DSA":
# DSAParams
p = str(PublicKey.__getstate__()['p'])
q = str(PublicKey.__getstate__()['q'])
g = str(PublicKey.__getstate__()['g'])
p = inttostring(PublicKey.__getstate__()['p'])
q = inttostring(PublicKey.__getstate__()['q'])
g = inttostring(PublicKey.__getstate__()['g'])
# Public key
y = str(PublicKey.__getstate__()['y'])
y = inttostring(PublicKey.__getstate__()['y'])
pk = ((0x81, len(p), p), (0x82, len(q), q), (0x83, len(g), g),
(0x84, len(y), y))
# Private key
x = str(PublicKey.__getstate__()['x'])
x = inttostring(PublicKey.__getstate__()['x'])
# Add more algorithms here
# elif cipher = "ECDSA":
else:
Expand Down
60 changes: 32 additions & 28 deletions virtualsmartcard/src/vpicc/virtualsmartcard/SmartcardFilesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,14 @@ def write(old, newlist, offsets, datacoding, maxsize=None):
while newindex < writenow:
if datacoding == DCB["WRITEOR"]:
newpiece = inttostring(
ord(result[resultindex]) | ord(new[newindex]))
result[resultindex] | new[newindex])
elif datacoding == DCB["WRITEAND"]:
newpiece = inttostring(
ord(result[resultindex]) & ord(new[newindex]))
result[resultindex] & new[newindex])
elif datacoding == DCB["PROPRIETARY"]:
# we use it for XOR
newpiece = inttostring(
ord(result[resultindex]) ^ ord(new[newindex]))
result[resultindex] ^ new[newindex])
result = (result[0:resultindex] + newpiece +
result[resultindex+1:len(result)])
newindex = newindex + 1
Expand Down Expand Up @@ -246,7 +246,7 @@ def __init__(self, parent, fid, filedescriptor,
simpletlv_data=None,
bertlv_data=None,
SAM=None,
extra_fci_data=''):
extra_fci_data=b''):
"""
The constructor is supposed to be involved by creation of a DF or EF.
"""
Expand Down Expand Up @@ -642,23 +642,23 @@ def encodeFileControlParameter(file):
l += simpletlv_unpack(r.data)[0][1]
else:
l += len(r.data)
fdm.append("%c\x02%s" % (TAG["BYTES_EXCLUDINGSTRUCTURE"],
fdm.append(b"%c\x02%s" % (TAG["BYTES_EXCLUDINGSTRUCTURE"],
inttostring(l, 2, True)))
fdm.append("%c\x02%s" % (TAG["BYTES_INCLUDINGSTRUCTURE"],
fdm.append(b"%c\x02%s" % (TAG["BYTES_INCLUDINGSTRUCTURE"],
inttostring(l, 2, True)))
l = len(records)
fdm.append("%c\x06%c%c%c%c%s" % (TAG["FILEDISCRIPTORBYTE"],
fdm.append(b"%c\x06%c%c%c%c%s" % (TAG["FILEDISCRIPTORBYTE"],
file.filedescriptor, file.datacoding,
file.maxrecordsize >> 8,
file.maxrecordsize & 0x00ff,
inttostring(l, 2)))

elif isinstance(file, DF):
# TODO number of files == number of data bytes?
fdm.append("%c\x01%c" % (TAG["FILEDISCRIPTORBYTE"],
fdm.append(b"%c\x01%c" % (TAG["FILEDISCRIPTORBYTE"],
file.filedescriptor))
if hasattr(file, 'dfname'):
fdm.append("%c%c%s" % (TAG["DFNAME"], len(file.dfname),
fdm.append(b"%c%c%s" % (TAG["DFNAME"], len(file.dfname),
file.dfname))

else:
Expand Down Expand Up @@ -748,6 +748,7 @@ def selectFile(self, p1, p2, data):
data = bertlv_pack([(tag, len(fdm), fdm)])

self.current = file
logging.info("Selected %s" % file)

return SW["NORMAL"], data

Expand Down Expand Up @@ -1309,9 +1310,9 @@ def fdb2args(value, args):
if l >= 3:
args["maxrecordsize"] = stringtoint(value[2:])
if l >= 2:
args["datacoding"] = ord(value[1])
args["datacoding"] = value[1]
if l >= 1:
args["filedescriptor"] = ord(value[0])
args["filedescriptor"] = value[0]

def shortfid2args(value, args):
s = stringtoint(value)
Expand All @@ -1323,19 +1324,6 @@ def shortfid2args(value, args):
def unknown(tag, value):
logging.debug("unknown tag 0x%x with %r" % (tag, value))

tag2cmd = {
# TODO support other tags
TAG["FILEDISCRIPTORBYTE"]: 'fdb2args(value, args)',
TAG["FILEIDENTIFIER"]: 'args["fid"] = stringtoint(value)',
TAG["DFNAME"]: 'args["dfname"] = value',
TAG["SHORTFID"]: 'shortfid2args(value, args)',
TAG["LIFECYCLESTATUS"]: 'args["lifecycle"] = ' + \
'stringtoint(value)',
TAG["BYTES_EXCLUDINGSTRUCTURE"]: 'args["data"] = bytes(0) ' + \
'* stringtoint(value)',
TAG["BYTES_INCLUDINGSTRUCTURE"]: 'args["data"] = bytes(0) ' + \
'* stringtoint(value)',
}
fcp_list = tlv_find_tags(bertlv_unpack(data),
[TAG["FILECONTROLINFORMATION"],
TAG["FILECONTROLPARAMETERS"]])
Expand All @@ -1353,9 +1341,23 @@ def unknown(tag, value):
T != TAG["FILECONTROLINFORMATION"]):
raise ValueError
for tag, _, value in tlv_data:
exec(tag2cmd.get(tag, 'unknown(tag, value)') in locals(),
globals())

if tag == TAG["FILEDISCRIPTORBYTE"]:
fdb2args(value, args)
elif tag == TAG["FILEIDENTIFIER"]:
args["fid"] = stringtoint(value)
elif tag == TAG["DFNAME"]:
args["dfname"] = value
elif tag == TAG["SHORTFID"]:
shortfid2args(value, args)
elif tag == TAG["LIFECYCLESTATUS"]:
args["lifecycle"] = stringtoint(value)
elif tag == TAG["BYTES_EXCLUDINGSTRUCTURE"]:
args["data"] = b'\x00' * stringtoint(value)
elif tag == TAG["BYTES_INCLUDINGSTRUCTURE"]:
args["data"] = b'\x00' * stringtoint(value)
else:
unknown(tag, value)
print(args)
if (args["filedescriptor"] & FDB["DF"]) == FDB["DF"]:
# FIXME: data for DF
if "data" in args:
Expand Down Expand Up @@ -1391,6 +1393,7 @@ def createFile(self, p1, p2, data):
file.parent = df
df.append(file)
self.current = file
logging.info("Created %s" % file)

return SW["NORMAL"], b""

Expand All @@ -1406,6 +1409,7 @@ def deleteFile(self, p1, p2, data):
file.parent.content.remove(file)
# FIXME: free memory of file and remove its content from the security
# device
logging.info("Deleted %s" % file)

return SW["NORMAL"], b""

Expand Down Expand Up @@ -1738,7 +1742,7 @@ def appendrecord(self, data):
raise SwError(SW["ERR_INCORRECTPARAMETERS"])

if self.hasFixedRecordSize():
data = bytes(0)*(self.maxrecordsize) + data
data = b'\x00'*(self.maxrecordsize) + data

records = self.records
if self.isCyclic():
Expand Down
34 changes: 17 additions & 17 deletions virtualsmartcard/src/vpicc/virtualsmartcard/TLVutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# virtualsmartcard. If not, see <http://www.gnu.org/licenses/>.
#

from virtualsmartcard.utils import stringtoint
from virtualsmartcard.utils import stringtoint, inttostring

TAG = {}
TAG["FILECONTROLPARAMETERS"] = 0x62
Expand Down Expand Up @@ -93,7 +93,7 @@ def find_recursive(tlv_data):
if t in tags:
results.append(d)
else:
if isinstance(v, list):
if isinstance(v, bytes) and not isinstance(v[0], int):
find_recursive(v)

if num_results is not None and len(results) >= num_results:
Expand All @@ -119,35 +119,35 @@ def pack(tlv_data, recalculate_length=False):
for data in tlv_data:
tag, length, value = data[:3]
if tag in (0xff, 0x00):
result.append(chr(tag))
result.append(inttostring(tag))
continue

if not isinstance(value, str):
if not isinstance(value, bytes):
value = pack(value, recalculate_length)

if recalculate_length:
length = len(value)

t = ""
t = b""
while tag > 0:
t = chr(tag & 0xff) + t
t = inttostring(tag & 0xff) + t
tag = tag >> 8

if length < 0x7F:
l = chr(length)
l = inttostring(length)
else:
l = ""
l = b""
while length > 0:
l = chr(length & 0xff) + l
l = inttostring(length & 0xff) + l
length = length >> 8
assert len(l) < 0x7f
l = chr(0x80 | len(l)) + l
l = inttostring(0x80 | len(l)) + l

result.append(t)
result.append(l)
result.append(value)

return "".join(result)
return b"".join(result)


def bertlv_pack(data):
Expand All @@ -158,7 +158,7 @@ def bertlv_pack(data):
def unpack(data, with_marks=None, offset=0, include_filler=False):
result = []
if isinstance(data, str):
data = map(ord, data)
data = list(map(ord, data))
while len(data) > 0:
if data[0] in (0x00, 0xFF):
if include_filler:
Expand Down Expand Up @@ -202,7 +202,7 @@ def bertlv_unpack(data):


def simpletlv_pack(tlv_data, recalculate_length=False):
result = ""
result = b""

for tag, length, value in tlv_data:
if tag >= 0xff or tag <= 0x00:
Expand All @@ -216,10 +216,10 @@ def simpletlv_pack(tlv_data, recalculate_length=False):
continue

if length < 0xff:
result += chr(tag) + chr(length) + value
result += inttostring(tag) + inttostring(length) + value
else:
result += chr(tag) + chr(0xff) + chr(length >> 8) + \
chr(length & 0xff) + value
result += inttostring(tag) + inttostring(0xff) + inttostring(length >> 8) + \
inttostring(length & 0xff) + value

return result

Expand All @@ -229,7 +229,7 @@ def simpletlv_unpack(data):
newvalue)."""
result = []
if isinstance(data, str):
data = map(ord, data)
data = list(map(ord, data))
rest = data
while rest:
tag = rest[0]
Expand Down
14 changes: 8 additions & 6 deletions virtualsmartcard/src/vpicc/virtualsmartcard/VirtualSmartcard.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import socket
import struct
import sys
import traceback
from virtualsmartcard.ConstantDefinitions import MAX_EXTENDED_LE, MAX_SHORT_LE
from virtualsmartcard.SWutils import SwError, SW
from virtualsmartcard.SmartcardFilesystem import make_property
Expand Down Expand Up @@ -282,15 +283,17 @@ def notImplemented(*argz, **args):
"""
raise SwError(SW["ERR_INSNOTSUPPORTED"])

logging.info("Command APDU (%d bytes):\n %s", len(msg),
hexdump(msg, indent=2))

try:
c = C_APDU(msg)
logging.debug("%s", str(c))
except ValueError as e:
logging.warning(str(e))
return self.formatResult(False, 0, b"",
SW["ERR_INCORRECTPARAMETERS"], False)

logging.info("Parsed APDU:\n%s", str(c))

# Handle Class Byte
# {{{
class_byte = c.cla
Expand Down Expand Up @@ -352,9 +355,8 @@ def notImplemented(*argz, **args):
answer = self.formatResult(Iso7816OS.seekable(c.ins),
c.effective_Le, result, sw, sm)
except SwError as e:
logging.debug(traceback.format_exc().rstrip())
logging.info(e.message)
import traceback
traceback.print_exception(*sys.exc_info())
sw = e.sw
result = b""
answer = self.formatResult(False, 0, result, sw, sm)
Expand Down Expand Up @@ -575,8 +577,8 @@ def run(self):
size, len(msg))

answer = self.os.execute(msg)
logging.info("Response APDU (%d Bytes):\n%s\n", len(answer),
hexdump(answer))
logging.info("Response APDU (%d bytes):\n %s\n", len(answer),
hexdump(answer, indent=2))
self.__sendToVPICC(answer)

def stop(self):
Expand Down
2 changes: 1 addition & 1 deletion virtualsmartcard/src/vpicc/virtualsmartcard/cards/nPA.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ def formatResult(self, seekable, le, data, sw, sm):
try:
sw, result = self.SAM.protect_result(sw, result)
except SwError as e:
logging.debug(traceback.format_exc().rstrip())
logging.info(e.message)
traceback.print_exception(*sys.exc_info())
sw = e.sw
result = b""
answer = self.formatResult(False, 0, result, sw, False)
Expand Down
Loading

0 comments on commit 04642a3

Please sign in to comment.