Removed vim folding markers

git-svn-id: https://vsmartcard.svn.sourceforge.net/svnroot/vsmartcard@526 96b47cad-a561-4643-ad3b-153ac7d7599c
This commit is contained in:
oepen
2011-09-06 12:45:47 +00:00
parent ade39a9ef8
commit 74dbdbec98
6 changed files with 103 additions and 105 deletions

View File

@@ -19,7 +19,7 @@
MAX_SHORT_LE = 0xff MAX_SHORT_LE = 0xff
MAX_EXTENDED_LE = 0xffff MAX_EXTENDED_LE = 0xffff
# Life cycle status byte {{{ # Life cycle status byte
LCB = {} LCB = {}
LCB["NOINFORMATION"] = 0x00 LCB["NOINFORMATION"] = 0x00
LCB["CREATION"] = 0x01 LCB["CREATION"] = 0x01
@@ -27,15 +27,15 @@ LCB["INITIALISATION"] = 0x03
LCB["ACTIVATED"] = 0x05 LCB["ACTIVATED"] = 0x05
LCB["DEACTIVATED"] = 0x04 LCB["DEACTIVATED"] = 0x04
LCB["TERMINATION"] = 0x0C LCB["TERMINATION"] = 0x0C
# }}}
# Channel security attribute {{{ # Channel security attribute
CS = {} CS = {}
CS["NOTSHAREABLE"] = 0x01 CS["NOTSHAREABLE"] = 0x01
CS["SECURED"] = 0x02 CS["SECURED"] = 0x02
CS["USERAUTHENTICATED"] = 0x03 CS["USERAUTHENTICATED"] = 0x03
# }}}
# Security attribute {{{ # Security attribute
# Security attribute, Access mode byte for DFs/EFs {{{ # Security attribute, Access mode byte for DFs/EFs
SA = {} SA = {}
SA["AM_DF_DELETESELF"] = SA["AM_EF_DELETEFILE"] = 0x40 SA["AM_DF_DELETESELF"] = SA["AM_EF_DELETEFILE"] = 0x40
SA["AM_DF_TERMINATEDF"] = SA["AM_EF_TERMINATEFILE"] = 0x20 SA["AM_DF_TERMINATEDF"] = SA["AM_EF_TERMINATEFILE"] = 0x20
@@ -44,8 +44,8 @@ SA["AM_DF_DEACTIVATEFILE"] = SA["AM_EF_DEACTIVATEFILE"] = 0x08
SA["AM_DF_CREATEDF"] = SA["AM_EF_WRITEBINARY"] = 0x04 SA["AM_DF_CREATEDF"] = SA["AM_EF_WRITEBINARY"] = 0x04
SA["AM_DF_CREATEEF"] = SA["AM_EF_UPDATEBINARY"] = 0x02 SA["AM_DF_CREATEEF"] = SA["AM_EF_UPDATEBINARY"] = 0x02
SA["AM_DF_DELETECHILD"] = SA["AM_EF_READBINARY"] = 0x01 SA["AM_DF_DELETECHILD"] = SA["AM_EF_READBINARY"] = 0x01
# }}}
# Security attribute in compact format, Security condition byte {{{ # Security attribute in compact format, Security condition byte
SA["CF_SC_NOCONDITION"] = 0x00 SA["CF_SC_NOCONDITION"] = 0x00
SA["CF_SC_NEVER"] = 0xFF SA["CF_SC_NEVER"] = 0xFF
SA["__CF_SC_ATLEASTONE"] = 0x80 SA["__CF_SC_ATLEASTONE"] = 0x80
@@ -59,9 +59,9 @@ SA["CF_SC_ONE_USERAUTHENTICATION"] = SA["__CF_SC_ATLEASTONE"]|SA["__CF_SC_US
SA["CF_SC_ALL_SECUREMESSAGING"] = SA["__CF_SC_ALLCONDITIONS"]|SA["__CF_SC_SECUREMESSAGING"] SA["CF_SC_ALL_SECUREMESSAGING"] = SA["__CF_SC_ALLCONDITIONS"]|SA["__CF_SC_SECUREMESSAGING"]
SA["CF_SC_ALL_EXTERNALAUTHENTICATION"] = SA["__CF_SC_ALLCONDITIONS"]|SA["__CF_SC_EXTERNALAUTHENTICATION"] SA["CF_SC_ALL_EXTERNALAUTHENTICATION"] = SA["__CF_SC_ALLCONDITIONS"]|SA["__CF_SC_EXTERNALAUTHENTICATION"]
SA["CF_SC_ALL_USERAUTHENTICATION"] = SA["__CF_SC_ALLCONDITIONS"]|SA["__CF_SC_USERAUTHENTICATION"] SA["CF_SC_ALL_USERAUTHENTICATION"] = SA["__CF_SC_ALLCONDITIONS"]|SA["__CF_SC_USERAUTHENTICATION"]
# }}}
# }}}
# Data coding byte {{{ # Data coding byte
DCB = {} DCB = {}
DCB["ONETIMEWRITE"] = 0x00 DCB["ONETIMEWRITE"] = 0x00
DCB["PROPRIETARY"] = 0x20 # we use it for XOR DCB["PROPRIETARY"] = 0x20 # we use it for XOR
@@ -69,8 +69,8 @@ DCB["WRITEOR"] = 0x40
DCB["WRITEAND"] = 0x60 DCB["WRITEAND"] = 0x60
DCB["BERTLV_FFVALID"] = 0x10 DCB["BERTLV_FFVALID"] = 0x10
DCB["BERTLV_FFINVALID"] = 0x10 DCB["BERTLV_FFINVALID"] = 0x10
# }}}
# File descriptor byte {{{ # File descriptor byte
FDB = {} FDB = {}
FDB["NOTSHAREABLEFILE"] = 0x00 FDB["NOTSHAREABLEFILE"] = 0x00
FDB["SHAREABLEFILE"] = 0x40 FDB["SHAREABLEFILE"] = 0x40
@@ -85,18 +85,17 @@ FDB["EFSTRUCTURE_LINEAR_VARIABLE_NOFURTHERINFO"] = 0x04
FDB["EFSTRUCTURE_LINEAR_VARIABLESIMPLETLV"] = 0x05 FDB["EFSTRUCTURE_LINEAR_VARIABLESIMPLETLV"] = 0x05
FDB["EFSTRUCTURE_CYCLIC_NOFURTHERINFO"] = 0x06 FDB["EFSTRUCTURE_CYCLIC_NOFURTHERINFO"] = 0x06
FDB["EFSTRUCTURE_CYCLIC_SIMPLETLV"] = 0x07 FDB["EFSTRUCTURE_CYCLIC_SIMPLETLV"] = 0x07
# }}}
# File identifier {{{ # File identifier
FID = {} FID = {}
FID["EFDIR"] = 0x2F00 FID["EFDIR"] = 0x2F00
FID["EFATR"] = 0x2F00 FID["EFATR"] = 0x2F00
FID["MF"] = 0x3F00 FID["MF"] = 0x3F00
FID["PATHSELECTION"] = 0x3FFF FID["PATHSELECTION"] = 0x3FFF
FID["RESERVED"] = 0x3FFF FID["RESERVED"] = 0x3FFF
# }}}
#Secure Messaging constants #Secure Messaging constants
#{{{
SM_Class = {} SM_Class = {}
#Basic secure messaging objects #Basic secure messaging objects
@@ -213,7 +212,7 @@ ALGO_MAPPING[0x0B] = "CC"
ALGO_MAPPING[0x0C] = "RSA" ALGO_MAPPING[0x0C] = "RSA"
ALGO_MAPPING[0x0D] = "DSA" ALGO_MAPPING[0x0D] = "DSA"
# Recerence control for select command, and record handling commands {{{ # Recerence control for select command, and record handling commands
REF = { REF = {
"IDENTIFIER_FIRST" : 0x00, "IDENTIFIER_FIRST" : 0x00,
"IDENTIFIER_LAST" : 0x01, "IDENTIFIER_LAST" : 0x01,
@@ -226,4 +225,4 @@ REF = {
"NUMBER_CONTROL" : 0x07, "NUMBER_CONTROL" : 0x07,
"REFERENCE_CONTROL" : 0x07, "REFERENCE_CONTROL" : 0x07,
} }
# }}}

View File

@@ -16,7 +16,7 @@
# You should have received a copy of the GNU General Public License along with # You should have received a copy of the GNU General Public License along with
# virtualsmartcard. If not, see <http://www.gnu.org/licenses/>. # virtualsmartcard. If not, see <http://www.gnu.org/licenses/>.
# #
# Meaning of the interindustry values of SW1-SW2 {{{ # Meaning of the interindustry values of SW1-SW2
SW = { SW = {
"NORMAL" : 0x9000, "NORMAL" : 0x9000,
"NORMAL_REST" : 0x6100, "NORMAL_REST" : 0x6100,
@@ -125,7 +125,6 @@ for i in range(0, 0xff):
SW_MESSAGES[0x6600 + i] = 'Execution error (Security-related issues)' SW_MESSAGES[0x6600 + i] = 'Execution error (Security-related issues)'
SW_MESSAGES[0x6C00 + i] = 'Checking error (Wrong Le field; %d available data bytes)' % i SW_MESSAGES[0x6C00 + i] = 'Checking error (Wrong Le field; %d available data bytes)' % i
# }}}
class SwError(Exception): class SwError(Exception):
def __init__(self, sw): def __init__(self, sw):

View File

@@ -27,7 +27,7 @@ from virtualsmartcard.TLVutils import *
from virtualsmartcard.SWutils import SW, SwError from virtualsmartcard.SWutils import SW, SwError
from virtualsmartcard.utils import stringtoint, inttostring from virtualsmartcard.utils import stringtoint, inttostring
def isEqual(list): # {{{ def isEqual(list):
"""Returns True, if all items are equal, otherwise False""" """Returns True, if all items are equal, otherwise False"""
if len(list) > 1: if len(list) > 1:
for item in list: for item in list:
@@ -35,9 +35,9 @@ def isEqual(list): # {{{
return False return False
return True return True
# }}}
def walk(start, path): # {{{
def walk(start, path):
"""Walks a path of fids and returns the last file (EF or DF). """Walks a path of fids and returns the last file (EF or DF).
start -- DF, where to look for the first fid start -- DF, where to look for the first fid
@@ -54,9 +54,9 @@ def walk(start, path): # {{{
index = index + 2 index = index + 2
return start return start
# }}}
def getfile_byrefdataobj(mf, refdataobjs): # {{{
def getfile_byrefdataobj(mf, refdataobjs):
"""Returns a list of files according to the given list of reference data """Returns a list of files according to the given list of reference data
objects. objects.
@@ -97,9 +97,9 @@ def getfile_byrefdataobj(mf, refdataobjs): # {{{
result.append(file) result.append(file)
return result return result
# }}}
def write(old, newlist, offsets, datacoding, maxsize=None): # {{{
def write(old, newlist, offsets, datacoding, maxsize=None):
"""Returns the status bytes and the result of a write operation according to """Returns the status bytes and the result of a write operation according to
the given data coding. the given data coding.
@@ -153,9 +153,9 @@ def write(old, newlist, offsets, datacoding, maxsize=None): # {{{
listindex = listindex + 1 listindex = listindex + 1
return result return result
# }}}
def get_indexes(items, reference=REF["IDENTIFIER_FIRST"], index_current=0): # {{{
def get_indexes(items, reference=REF["IDENTIFIER_FIRST"], index_current=0):
""" """
Returns all indexes of the list, which are specified by 'reference' and by Returns all indexes of the list, which are specified by 'reference' and by
the current index 'index_current' (-1 for no current item) in the correct the current index 'index_current' (-1 for no current item) in the correct
@@ -186,9 +186,9 @@ def get_indexes(items, reference=REF["IDENTIFIER_FIRST"], index_current=0): # {{
# Read next occurrence # Read next occurrence
indexes = range(index_current + 1, len(items)) indexes = range(index_current + 1, len(items))
return indexes return indexes
# }}}
def prettyprint_anything(indent, thing): # {{{
def prettyprint_anything(indent, thing):
""" """
Returns a recursively generated string representation of an object and its Returns a recursively generated string representation of an object and its
attributes. attributes.
@@ -205,9 +205,9 @@ def prettyprint_anything(indent, thing): # {{{
for item in newvalue: for item in newvalue:
s = s + "\n" + prettyprint_anything(indent + " ", item) s = s + "\n" + prettyprint_anything(indent + " ", item)
return s return s
# }}}
def make_property(prop, doc): # {{{
def make_property(prop, doc):
""" """
Assigns a property to the calling object. This is used to decorate instance Assigns a property to the calling object. This is used to decorate instance
variables with docstrings. variables with docstrings.
@@ -217,7 +217,7 @@ def make_property(prop, doc): # {{{
lambda self, value: setattr(self, "_"+prop, value), lambda self, value: setattr(self, "_"+prop, value),
lambda self: delattr(self, "_"+prop), lambda self: delattr(self, "_"+prop),
doc) doc)
# }}}
class File(object): class File(object):
@@ -390,10 +390,10 @@ class File(object):
def select(self, *argz, **args): def select(self, *argz, **args):
"""Only a template, will raise an error.""" """Only a template, will raise an error."""
raise SwError(SW["ERR_INCOMPATIBLEWITHFILE"]) raise SwError(SW["ERR_INCOMPATIBLEWITHFILE"])
# }}}
class DF(File): # {{{
class DF(File):
"""Class for a dedicated file""" """Class for a dedicated file"""
data = make_property("data", "unknown") data = make_property("data", "unknown")
content = make_property("content", "list of files of the DF") content = make_property("content", "list of files of the DF")
@@ -490,10 +490,10 @@ class DF(File): # {{{
def remove(self, file): def remove(self, file):
"""Removes 'file' from the content of the DF""" """Removes 'file' from the content of the DF"""
self.content.remove(file) self.content.remove(file)
# }}}
class MF(DF): # {{{
class MF(DF):
"""Class for a master file""" """Class for a master file"""
current = make_property("current", "the currently selected file") current = make_property("current", "the currently selected file")
firstSFT = make_property("firstSFT", "string of length 1. The first software function table from the historical bytes.") firstSFT = make_property("firstSFT", "string of length 1. The first software function table from the historical bytes.")
@@ -513,7 +513,7 @@ class MF(DF): # {{{
@staticmethod @staticmethod
def makeFirstSoftwareFunctionTable(# {{{ def makeFirstSoftwareFunctionTable(
DFSelectionByFullDFName=True, DFSelectionByPartialDFName=True, DFSelectionByFullDFName=True, DFSelectionByPartialDFName=True,
DFSelectionByPath=True, DFSelectionByFID=True, DFSelectionByPath=True, DFSelectionByFID=True,
DFSelectionByApplication_implicite=True, ShortFIDSupported=True, DFSelectionByApplication_implicite=True, ShortFIDSupported=True,
@@ -549,16 +549,16 @@ class MF(DF): # {{{
if RecordIdentifierSupported: if RecordIdentifierSupported:
fsft |= 1 fsft |= 1
return fsft return fsft
# }}}
@staticmethod @staticmethod
def makeSecondSoftwareFunctionTable(DCB=DCB["ONETIMEWRITE"]|1): # {{{ def makeSecondSoftwareFunctionTable(DCB=DCB["ONETIMEWRITE"]|1):
""" """
The second software function table from the historical bytes contains The second software function table from the historical bytes contains
the data coding byte. the data coding byte.
""" """
return DCB return DCB
# }}}
def currentDF(self): def currentDF(self):
"""Returns the current DF.""" """Returns the current DF."""
@@ -1295,10 +1295,10 @@ class MF(DF): # {{{
# FIXME: free memory of file and remove its content from the security device # FIXME: free memory of file and remove its content from the security device
return SW["NORMAL"], "" return SW["NORMAL"], ""
# }}}
class EF(File): # {{{
class EF(File):
"""Template class for an elementary file.""" """Template class for an elementary file."""
shortfid = make_property("shortfid", "integer with 1<=shortfid<=30. Short EF identifier.") shortfid = make_property("shortfid", "integer with 1<=shortfid<=30. Short EF identifier.")
datacoding = make_property("datacoding", "integer. Data coding byte.") datacoding = make_property("datacoding", "integer. Data coding byte.")
@@ -1323,10 +1323,10 @@ class EF(File): # {{{
simpletlv_data, simpletlv_data,
bertlv_data) bertlv_data)
self.datacoding = datacoding self.datacoding = datacoding
# }}}
class TransparentStructureEF(EF): # {{{
class TransparentStructureEF(EF):
"""Class for an elementary file with transparent structure.""" """Class for an elementary file with transparent structure."""
data = make_property("data", "string (encrypted). The file's data.") data = make_property("data", "string (encrypted). The file's data.")
def __init__(self, parent, fid, filedescriptor=FDB["EFSTRUCTURE_TRANSPARENT"], def __init__(self, parent, fid, filedescriptor=FDB["EFSTRUCTURE_TRANSPARENT"],
@@ -1391,10 +1391,10 @@ class TransparentStructureEF(EF): # {{{
data = data[0:erasefrom] + data[eraseto:len(data)] data = data[0:erasefrom] + data[eraseto:len(data)]
self.setdec('data', data) self.setdec('data', data)
# }}}
class Record(object): # {{{
class Record(object):
data = make_property("data", "string. The record's data.") data = make_property("data", "string. The record's data.")
identifier = make_property("identifier", "integer with 1<= identifier< = 0xfe. The record's identifier.") identifier = make_property("identifier", "integer with 1<= identifier< = 0xfe. The record's identifier.")
"""Class for a Record of an elementary of record structure""" """Class for a Record of an elementary of record structure"""
@@ -1412,10 +1412,10 @@ class Record(object): # {{{
"""Returns a string of the object using an prettyprint_anything.""" """Returns a string of the object using an prettyprint_anything."""
return prettyprint_anything("", self) return prettyprint_anything("", self)
__repr__ = __str__ __repr__ = __str__
# }}}
class RecordStructureEF(EF): # {{{
class RecordStructureEF(EF):
"""Class for an elementary file with record structure.""" """Class for an elementary file with record structure."""
records = make_property("records", "list of records (encrypted)") records = make_property("records", "list of records (encrypted)")
maxrecordsize = make_property("maxrecordsize", "integer. maximum length of a record's data.") maxrecordsize = make_property("maxrecordsize", "integer. maximum length of a record's data.")
@@ -1630,4 +1630,4 @@ class RecordStructureEF(EF): # {{{
r.data = "" r.data = ""
r.identifier = None r.identifier = None
return SW["NORMAL"] return SW["NORMAL"]
# }}}

View File

@@ -49,7 +49,7 @@ TAG["TAG_LIST"] = 0x5C
TAG["HEADER_LIST"] = 0x5D TAG["HEADER_LIST"] = 0x5D
TAG["EXTENDED_HEADER_LIST"] = 0x4D TAG["EXTENDED_HEADER_LIST"] = 0x4D
def tlv_unpack(data): # {{{ def tlv_unpack(data):
ber_class = (ord(data[0]) & 0xC0) >> 6 ber_class = (ord(data[0]) & 0xC0) >> 6
constructed = (ord(data[0]) & 0x20) != 0 ## 0 = primitive, 0x20 = constructed constructed = (ord(data[0]) & 0x20) != 0 ## 0 = primitive, 0x20 = constructed
tag = ord(data[0]) tag = ord(data[0])
@@ -76,9 +76,9 @@ def tlv_unpack(data): # {{{
rest = data[length:] rest = data[length:]
return ber_class, constructed, tag, length, value, rest return ber_class, constructed, tag, length, value, rest
# }}}
def tlv_find_tags(tlv_data, tags, num_results = None): # {{{
def tlv_find_tags(tlv_data, tags, num_results = None):
"""Find (and return) all instances of tags in the given tlv structure (as """Find (and return) all instances of tags in the given tlv structure (as
returned by unpack). If num_results is specified then at most that many returned by unpack). If num_results is specified then at most that many
results will be returned.""" results will be returned."""
@@ -99,16 +99,16 @@ def tlv_find_tags(tlv_data, tags, num_results = None): # {{{
find_recursive(tlv_data) find_recursive(tlv_data)
return results return results
# }}}
def tlv_find_tag(tlv_data, tag, num_results = None): # {{{
def tlv_find_tag(tlv_data, tag, num_results = None):
"""Find (and return) all instances of tag in the given tlv structure (as returned by unpack). """Find (and return) all instances of tag in the given tlv structure (as returned by unpack).
If num_results is specified then at most that many results will be returned.""" If num_results is specified then at most that many results will be returned."""
return tlv_find_tags(tlv_data, [tag], num_results) return tlv_find_tags(tlv_data, [tag], num_results)
# }}}
def pack(tlv_data, recalculate_length = False): # {{{
def pack(tlv_data, recalculate_length = False):
result = [] result = []
for data in tlv_data: for data in tlv_data:
@@ -143,14 +143,14 @@ def pack(tlv_data, recalculate_length = False): # {{{
result.append(value) result.append(value)
return "".join(result) return "".join(result)
# }}}
def bertlv_pack(data): # {{{
def bertlv_pack(data):
"""Packs a bertlv list of 3-tuples (tag, length, newvalue) into a string""" """Packs a bertlv list of 3-tuples (tag, length, newvalue) into a string"""
return pack(data) return pack(data)
# }}}
def unpack(data, with_marks = None, offset = 0, include_filler=False): # {{{
def unpack(data, with_marks = None, offset = 0, include_filler=False):
result = [] result = []
while len(data) > 0: while len(data) > 0:
if ord(data[0]) in (0x00, 0xFF): if ord(data[0]) in (0x00, 0xFF):
@@ -185,15 +185,15 @@ def unpack(data, with_marks = None, offset = 0, include_filler=False): # {{{
offset = stop offset = stop
return result return result
# }}}
def bertlv_unpack(data): # {{{
def bertlv_unpack(data):
"""Unpacks a bertlv coded string into a list of 3-tuples (tag, length, """Unpacks a bertlv coded string into a list of 3-tuples (tag, length,
newvalue).""" newvalue)."""
return unpack(data) return unpack(data)
# }}}
def simpletlv_pack(tlv_data, recalculate_length = False): # {{{
def simpletlv_pack(tlv_data, recalculate_length = False):
result = "" result = ""
for tag, length, value in tlv_data: for tag, length, value in tlv_data:
@@ -213,9 +213,9 @@ def simpletlv_pack(tlv_data, recalculate_length = False): # {{{
result += chr(tag) + chr(0xff)+chr(length>>8)+chr(length&0xff) + value result += chr(tag) + chr(0xff)+chr(length>>8)+chr(length&0xff) + value
return result return result
# }}}
def simpletlv_unpack(data): # {{{
def simpletlv_unpack(data):
"""Unpacks a simpletlv coded string into a list of 3-tuples (tag, length, """Unpacks a simpletlv coded string into a list of 3-tuples (tag, length,
newvalue).""" newvalue)."""
result = [] result = []
@@ -236,25 +236,25 @@ def simpletlv_unpack(data): # {{{
result.append((tag, length, newvalue)) result.append((tag, length, newvalue))
return result return result
# }}}
def decodeDiscretionaryDataObjects(tlv_data): # {{{
def decodeDiscretionaryDataObjects(tlv_data):
datalist = [] datalist = []
for (tag, length, newvalue) in (tlv_find_tags(tlv_data, for (tag, length, newvalue) in (tlv_find_tags(tlv_data,
[TAG["DISCRETIONARY_DATA"], TAG["DISCRETIONARY_TEMPLATE"]])): [TAG["DISCRETIONARY_DATA"], TAG["DISCRETIONARY_TEMPLATE"]])):
datalist.append(newvalue) datalist.append(newvalue)
return datalist return datalist
# }}}
def decodeOffsetDataObjects(tlv_data): # {{{ def decodeOffsetDataObjects(tlv_data):
offsets = [] offsets = []
for (tag, length, newvalue) in tlv_find_tag(tlv_data, for (tag, length, newvalue) in tlv_find_tag(tlv_data,
TAG["OFFSET_DATA"]): TAG["OFFSET_DATA"]):
offsets.append(stringtoint(newvalue)) offsets.append(stringtoint(newvalue))
return offsets return offsets
# }}}
def decodeTagList(tlv_data): # {{{
def decodeTagList(tlv_data):
taglist = [] taglist = []
for (t, l, data) in tlv_find_tag(tlv_data, TAG["TAG_LIST"]): for (t, l, data) in tlv_find_tag(tlv_data, TAG["TAG_LIST"]):
while data != "": while data != "":
@@ -268,9 +268,9 @@ def decodeTagList(tlv_data): # {{{
data = data[1:] data = data[1:]
taglist.append((tag, 0)) taglist.append((tag, 0))
return taglist return taglist
# }}}
def decodeHeaderList(tlv_data): # {{{
def decodeHeaderList(tlv_data):
headerlist = [] headerlist = []
for (t, l, data) in tlv_find_tag(tlv_data, TAG["HEADER_LIST"]): for (t, l, data) in tlv_find_tag(tlv_data, TAG["HEADER_LIST"]):
while data != "": while data != "":
@@ -296,22 +296,22 @@ def decodeHeaderList(tlv_data): # {{{
headerlist.append((tag, length)) headerlist.append((tag, length))
return headerlist return headerlist
# }}}
def decodeExtendedHeaderList(tlv_data): # {{{
def decodeExtendedHeaderList(tlv_data):
# TODO # TODO
return [] return []
# }}}
def encodebertlvDatalist(tag, datalist): # {{{
def encodebertlvDatalist(tag, datalist):
tlvlist = [] tlvlist = []
for data in datalist: for data in datalist:
tlvlist.append((tag, len(data), data)) tlvlist.append((tag, len(data), data))
return bertlv_pack(tlvlist) return bertlv_pack(tlvlist)
# }}}
def encodeDiscretionaryDataObjects(datalist): # {{{ def encodeDiscretionaryDataObjects(datalist):
return encodebertlvDatalist(TAG["DISCRETIONARY_DATA"], datalist) return encodebertlvDatalist(TAG["DISCRETIONARY_DATA"], datalist)
# }}}
def encodeDataOffsetObjects(datalist): # {{{ def encodeDataOffsetObjects(datalist):
return encodebertlvDatalist(TAG["OFFSET_DATA"], datalist) return encodebertlvDatalist(TAG["OFFSET_DATA"], datalist)
# }}}

View File

@@ -26,7 +26,7 @@ from virtualsmartcard.CardGenerator import CardGenerator
import socket, struct, sys, signal, atexit, smartcard, logging import socket, struct, sys, signal, atexit, smartcard, logging
class SmartcardOS(object): # {{{ class SmartcardOS(object):
"""Base class for a smart card OS""" """Base class for a smart card OS"""
mf = make_property("mf", "master file") mf = make_property("mf", "master file")
@@ -54,9 +54,9 @@ class SmartcardOS(object): # {{{
msg -- the APDU as string of characters msg -- the APDU as string of characters
""" """
return "" return ""
# }}}
class Iso7816OS(SmartcardOS): # {{{
class Iso7816OS(SmartcardOS):
def __init__(self, mf, sam, ins2handler=None, extended_length=False): def __init__(self, mf, sam, ins2handler=None, extended_length=False):
self.mf = mf self.mf = mf
self.SAM = sam self.SAM = sam
@@ -120,7 +120,7 @@ class Iso7816OS(SmartcardOS): # {{{
return self.atr return self.atr
@staticmethod @staticmethod
def makeATR(**args): # {{{ def makeATR(**args):
"""Calculate Answer to Reset (ATR) and returns the bitstring. """Calculate Answer to Reset (ATR) and returns the bitstring.
- directConvention (bool): Whether to use direct convention or - directConvention (bool): Whether to use direct convention or
@@ -203,10 +203,10 @@ class Iso7816OS(SmartcardOS): # {{{
atr += "%c" % TCK atr += "%c" % TCK
return atr return atr
# }}}
@staticmethod @staticmethod
def makeThirdSoftwareFunctionTable(commandChainging=False, def makeThirdSoftwareFunctionTable(commandChainging=False,
extendedLe=False, assignLogicalChannel=0, maximumChannels=0): # {{{ extendedLe=False, assignLogicalChannel=0, maximumChannels=0):
""" """
Returns a byte according to the third software function table from the Returns a byte according to the third software function table from the
historical bytes of the card capabilities. historical bytes of the card capabilities.
@@ -225,7 +225,7 @@ class Iso7816OS(SmartcardOS): # {{{
raise ValueError raise ValueError
tsft |= maximumChannels tsft |= maximumChannels
return inttostring(tsft) return inttostring(tsft)
# }}}
def formatResult(self, le, data, sw, sm): def formatResult(self, le, data, sw, sm):
self.lastCommandOffcut = data[le:] self.lastCommandOffcut = data[le:]
@@ -329,9 +329,9 @@ class Iso7816OS(SmartcardOS): # {{{
answer = self.formatResult(0, result, sw, False) answer = self.formatResult(0, result, sw, False)
return answer return answer
# }}}
class CryptoflexOS(Iso7816OS): # {{{ class CryptoflexOS(Iso7816OS):
def __init__(self, mf, sam, ins2handler=None, maxle=MAX_SHORT_LE): def __init__(self, mf, sam, ins2handler=None, maxle=MAX_SHORT_LE):
Iso7816OS.__init__(self, mf, sam, ins2handler, maxle) Iso7816OS.__init__(self, mf, sam, ins2handler, maxle)
self.atr = '\x3B\xE2\x00\x00\x40\x20\x49\x06' self.atr = '\x3B\xE2\x00\x00\x40\x20\x49\x06'
@@ -376,9 +376,9 @@ class CryptoflexOS(Iso7816OS): # {{{
r = Iso7816OS.formatResult(self, le, data, sw, False) r = Iso7816OS.formatResult(self, le, data, sw, False)
return r return r
# }}}
class RelayOS(SmartcardOS): # {{{
class RelayOS(SmartcardOS):
""" """
This class implements relaying of a (physical) smartcard. The RelayOS This class implements relaying of a (physical) smartcard. The RelayOS
forwards the command APDUs received from the vpcd to the real smartcard via forwards the command APDUs received from the vpcd to the real smartcard via
@@ -471,13 +471,13 @@ class RelayOS(SmartcardOS): # {{{
rapdu = rapdu + [sw1, sw2] rapdu = rapdu + [sw1, sw2]
return "".join([chr(b) for b in rapdu]) return "".join([chr(b) for b in rapdu])
# }}}
# sizeof(int) taken from asizof-package {{{ # sizeof(int) taken from asizof-package {{{
_Csizeof_short = len(struct.pack('h', 0)) _Csizeof_short = len(struct.pack('h', 0))
# }}}
VPCD_CTRL_LEN = 1 VPCD_CTRL_LEN = 1
@@ -486,7 +486,7 @@ VPCD_CTRL_ON = 1
VPCD_CTRL_RESET = 2 VPCD_CTRL_RESET = 2
VPCD_CTRL_ATR = 4 VPCD_CTRL_ATR = 4
class VirtualICC(object): # {{{ class VirtualICC(object):
""" """
This class is responsible for maintaining the communication of the virtual This class is responsible for maintaining the communication of the virtual
PCD and the emulated smartcard. vpicc and vpcd communicate via a socket. PCD and the emulated smartcard. vpicc and vpcd communicate via a socket.
@@ -627,4 +627,4 @@ class VirtualICC(object): # {{{
if self.filename != None: if self.filename != None:
self.cardGenerator.setCard(self.os.mf, self.os.SAM) self.cardGenerator.setCard(self.os.mf, self.os.SAM)
self.cardGenerator.saveCard(self.filename) self.cardGenerator.saveCard(self.filename)
# }}}

View File

@@ -19,7 +19,7 @@
import string, binascii import string, binascii
from ConstantDefinitions import MAX_SHORT_LE, MAX_EXTENDED_LE from ConstantDefinitions import MAX_SHORT_LE, MAX_EXTENDED_LE
def stringtoint(str): # {{{ def stringtoint(str):
#i = len(str) - 1 #i = len(str) - 1
#int = 0 #int = 0
#while i >= 0: #while i >= 0:
@@ -29,9 +29,9 @@ def stringtoint(str): # {{{
if str: if str:
return int(str.encode('hex'), 16) return int(str.encode('hex'), 16)
return 0 return 0
# }}}
def inttostring(i, length=None): # {{{
def inttostring(i, length=None):
#str = "" #str = ""
#while i > 0: #while i > 0:
#str = chr(i & 0xff) + str #str = chr(i & 0xff) + str
@@ -50,7 +50,7 @@ def inttostring(i, length=None): # {{{
str = chr(0)*(length-l) + str str = chr(0)*(length-l) + str
return str return str
# }}}
_myprintable = " " + string.letters + string.digits + string.punctuation _myprintable = " " + string.letters + string.digits + string.punctuation
def hexdump(data, indent = 0, short = False, linelen = 16, offset = 0): def hexdump(data, indent = 0, short = False, linelen = 16, offset = 0):