Replaced print calls by actual logging

git-svn-id: https://vsmartcard.svn.sourceforge.net/svnroot/vsmartcard@473 96b47cad-a561-4643-ad3b-153ac7d7599c
This commit is contained in:
oepen
2011-08-01 12:39:57 +00:00
parent 168f4fd434
commit 25cf21afb2
5 changed files with 65 additions and 59 deletions

View File

@@ -17,7 +17,7 @@
# virtualsmartcard. If not, see <http://www.gnu.org/licenses/>. # virtualsmartcard. If not, see <http://www.gnu.org/licenses/>.
# #
import sys, getpass, anydbm, readline import sys, getpass, anydbm, readline, logging
from pickle import loads, dumps from pickle import loads, dumps
from virtualsmartcard.TLVutils import pack from virtualsmartcard.TLVutils import pack
from virtualsmartcard.utils import inttostring from virtualsmartcard.utils import inttostring
@@ -45,9 +45,13 @@ class CardGenerator(object):
self.sam = sam self.sam = sam
def __generate_iso_card(self): def __generate_iso_card(self):
print "Using default SAM. Insecure!!!" default_pin = "1234"
default_cardno = "1234567890"
logging.warning("Using default SAM parameters. PIN=%s, Card Nr=%s"
& (default_pin, default_cardno))
#TODO: Use user provided data #TODO: Use user provided data
self.sam = virtualsmartcard.SmartcardSAM.SAM("1234", "1234567890") self.sam = virtualsmartcard.SmartcardSAM.SAM(default_pin, default_cardno)
self.mf = MF(filedescriptor=FDB["DF"]) self.mf = MF(filedescriptor=FDB["DF"])
self.sam.set_MF(self.mf) self.sam.set_MF(self.mf)
@@ -74,7 +78,7 @@ class CardGenerator(object):
picture = fd.read() picture = fd.read()
fd.close() fd.close()
except IOError: except IOError:
print "Failed to open file: " + picturepath logging.warning("Failed to open file: " + picturepath)
pic_width = 0 pic_width = 0
pic_height = 0 pic_height = 0
picture = None picture = None
@@ -212,7 +216,7 @@ if __name__ == "__main__":
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if options.filename == None: if options.filename == None:
print "You have to provide a filename using the -f option" logging.error("You have to provide a filename using the -f option")
sys.exit() sys.exit()
generator = CardGenerator(options.type) generator = CardGenerator(options.type)

View File

@@ -16,14 +16,13 @@
# 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/>.
# #
import sys, binascii, utils, random import sys, binascii, utils, random, logging
from Crypto.Cipher import DES3, DES, AES, ARC4 #,IDEA no longer present in python-crypto? from Crypto.Cipher import DES3, DES, AES, ARC4 #,IDEA no longer present in python-crypto? @UnusedImport
from struct import pack from struct import pack
from binascii import b2a_hex, a2b_hex from binascii import b2a_hex, a2b_hex
from random import randint from random import randint
from virtualsmartcard.utils import inttostring, stringtoint, hexdump from virtualsmartcard.utils import inttostring, hexdump
import string import string, re
import re
try: try:
# Use PyCrypto (if available) # Use PyCrypto (if available)
@@ -166,7 +165,7 @@ def hash(hashmethod, data):
from Crypto.Hash import SHA, MD5#, RIPEMD from Crypto.Hash import SHA, MD5#, RIPEMD
hash_class = locals().get(hashmethod.upper(), None) hash_class = locals().get(hashmethod.upper(), None)
if hash_class == None: if hash_class == None:
print "Unknown Hash method %s" % hashmethod logging.error("Unknown Hash method %s" % hashmethod)
raise ValueError raise ValueError
hash = hash_class.new() hash = hash_class.new()
hash.update(data) hash.update(data)
@@ -231,7 +230,7 @@ def read_protected_string(string, password, cipherspec=None):
#Verify HMAC #Verify HMAC
checksum = crypto_checksum("HMAC", key, crypted) checksum = crypto_checksum("HMAC", key, crypted)
if checksum != hmac: if checksum != hmac:
print "Found HMAC %s expected %s" % (str(hmac), str(checksum)) logging.error("Found HMAC %s expected %s" % (str(hmac), str(checksum)))
raise ValueError, "Failed to authenticate data. Wrong password?" raise ValueError, "Failed to authenticate data. Wrong password?"
#Decrypt data #Decrypt data

View File

@@ -21,6 +21,7 @@
@todo zu lange daten abschneiden und trotzdem tlv laenge beibehalten @todo zu lange daten abschneiden und trotzdem tlv laenge beibehalten
""" """
from pickle import dumps, loads from pickle import dumps, loads
import logging
from virtualsmartcard.ConstantDefinitions import * from virtualsmartcard.ConstantDefinitions import *
from virtualsmartcard.TLVutils import * from virtualsmartcard.TLVutils import *
from virtualsmartcard.SWutils import * from virtualsmartcard.SWutils import *
@@ -481,9 +482,9 @@ class DF(File): # {{{
return file return file
# not found # not found
if isinstance(value, int): if isinstance(value, int):
print "file not found %s=%x" % (attribute, value) logging.debug("file not found %s=%x" % (attribute, value))
elif isinstance(value, str): elif isinstance(value, str):
print "file not found %s=%r" % (attribute, value) logging.debug("file not found %s=%r" % (attribute, value))
raise SwError(SW["ERR_FILENOTFOUND"]) raise SwError(SW["ERR_FILENOTFOUND"])
def remove(self, file): def remove(self, file):
@@ -674,7 +675,7 @@ class MF(DF): # {{{
selected = self.select('dfname', data, p2 & selected = self.select('dfname', data, p2 &
REF["REFERENCE_CONTROL"], index_current) REF["REFERENCE_CONTROL"], index_current)
else: else:
print "unknown selection method: p1 =", p1 logging.debug("unknown selection method: p1 =%s" % p1)
selected = None selected = None
if selected == None: if selected == None:
@@ -1219,7 +1220,7 @@ class MF(DF): # {{{
if shortfid != 0: if shortfid != 0:
args["shortfid"] = shortfid args["shortfid"] = shortfid
def unknown(tag, value): def unknown(tag, value):
print "unknown tag 0x%x with %r" % tag, value logging.debug("unknown tag 0x%x with %r" % (tag, value))
tag2cmd = { tag2cmd = {
# TODO support other tags # TODO support other tags
TAG["FILEDISCRIPTORBYTE"] : 'fdb2args(value, args)', TAG["FILEDISCRIPTORBYTE"] : 'fdb2args(value, args)',
@@ -1250,7 +1251,7 @@ class MF(DF): # {{{
if (args["filedescriptor"] & FDB["DF"]) == FDB["DF"]: if (args["filedescriptor"] & FDB["DF"]) == FDB["DF"]:
# FIXME: data for DF # FIXME: data for DF
if "data" in args: if "data" in args:
print 'what to do with DF-data %r?' % args["data"] logging.debug('what to do with DF-data %r?' % args["data"])
del args["data"] del args["data"]
file = DF(**args) file = DF(**args)
elif ((args["filedescriptor"] & 7) in elif ((args["filedescriptor"] & 7) in

View File

@@ -17,7 +17,7 @@
# virtualsmartcard. If not, see <http://www.gnu.org/licenses/>. # virtualsmartcard. If not, see <http://www.gnu.org/licenses/>.
# #
import struct, hashlib import struct, hashlib, logging
from pickle import dumps, loads from pickle import dumps, loads
from os import urandom from os import urandom
@@ -122,7 +122,7 @@ class SAM(object):
equals zero, block the card until reset with correct PUK equals zero, block the card until reset with correct PUK
""" """
print "Received PIN: %s" % PIN.strip() logging.debug("Received PIN: %s" % PIN.strip())
PIN = PIN.replace("\0","") #Strip NULL charakters PIN = PIN.replace("\0","") #Strip NULL charakters
if p1 != 0x00: if p1 != 0x00:
@@ -145,7 +145,6 @@ class SAM(object):
data = data.replace("\0","") #Strip NULL charakters data = data.replace("\0","") #Strip NULL charakters
self.PIN = data self.PIN = data
print "New PIN = %s" % self.PIN
return SW["NORMAL"], "" return SW["NORMAL"], ""
def internal_authenticate(self, p1, p2, data): def internal_authenticate(self, p1, p2, data):
@@ -171,7 +170,7 @@ class SAM(object):
def external_authenticate(self, p1, p2, data): def external_authenticate(self, p1, p2, data):
""" """
Authenticate the terminal to the card. Check wether Terminal correctly Authenticate the terminal to the card. Check whether Terminal correctly
encrypted the given challenge or not encrypted the given challenge or not
""" """
if self.last_challenge is None: if self.last_challenge is None:
@@ -190,10 +189,6 @@ class SAM(object):
self.last_challenge = None self.last_challenge = None
return SW["NORMAL"], "" return SW["NORMAL"], ""
else: else:
plain = vsCrypto.decrypt(cipher, key, data)
print plain
print "Reference: " + hexdump(reference)
print "Data: " + hexdump(data)
raise SwError(SW["WARN_NOINFO63"]) raise SwError(SW["WARN_NOINFO63"])
#TODO: Counter for external authenticate? #TODO: Counter for external authenticate?
@@ -201,7 +196,7 @@ class SAM(object):
""" """
Takes an encrypted challenge in the form Takes an encrypted challenge in the form
'Terminal Challenge | Card Challenge | Card number' 'Terminal Challenge | Card Challenge | Card number'
and checks it for validity. If the challenge is succesful and checks it for validity. If the challenge is successful
the card encrypts 'Card Challenge | Terminal challenge' and the card encrypts 'Card Challenge | Terminal challenge' and
returns this value returns this value
""" """
@@ -242,7 +237,7 @@ class SAM(object):
length = 8 #Length of the challenge in Byte length = 8 #Length of the challenge in Byte
self.last_challenge = urandom(length) self.last_challenge = urandom(length)
print "Generated challenge: %s" % str(self.last_challenge) logging.debug("Generated challenge: %s" % str(self.last_challenge))
self.last_challenge = inttostring(self.last_challenge, length) self.last_challenge = inttostring(self.last_challenge, length)
return SW["NORMAL"], self.last_challenge return SW["NORMAL"], self.last_challenge
@@ -282,7 +277,7 @@ class SAM(object):
df = self.mf.currentDF() df = self.mf.currentDF()
fid = df.select("fid", stringtoint(qualifier)) fid = df.select("fid", stringtoint(qualifier))
key = fid.readbinary(keylength) key = fid.readbinary(keylength)
if key != None: if key != None:
return key return key
else: else:
@@ -1056,8 +1051,8 @@ class CryptoflexSM(Secure_Messaging):
e_in = struct.unpack("<i", data) e_in = struct.unpack("<i", data)
if e_in[0] != 65537: if e_in[0] != 65537:
print "Warning: Exponents different from 65537 are ignored!" +\ logging.warning("Warning: Exponents different from 65537 are ignored!" +\
"The Exponent given is %i" % e_in[0] "The Exponent given is %i" % e_in[0])
#Encode Public key #Encode Public key
n = PublicKey.__getstate__()['n'] n = PublicKey.__getstate__()['n']

View File

@@ -23,7 +23,7 @@ from virtualsmartcard.SmartcardFilesystem import make_property
from virtualsmartcard.utils import C_APDU, R_APDU, hexdump, inttostring from virtualsmartcard.utils import C_APDU, R_APDU, hexdump, inttostring
import CardGenerator import CardGenerator
import socket, struct, sys, signal, atexit, smartcard import socket, struct, sys, signal, atexit, smartcard, logging
class SmartcardOS(object): # {{{ class SmartcardOS(object): # {{{
@@ -246,7 +246,7 @@ class Iso7816OS(SmartcardOS): # {{{
try: try:
c = C_APDU(msg) c = C_APDU(msg)
except ValueError, e: except ValueError, e:
print e logging.warning(str(e))
return self.formatResult(0, "", SW["ERR_INCORRECTPARAMETERS"], False) return self.formatResult(0, "", SW["ERR_INCORRECTPARAMETERS"], False)
#Handle Class Byte{{{ #Handle Class Byte{{{
@@ -258,7 +258,7 @@ class Iso7816OS(SmartcardOS): # {{{
#Ugly Hack for OpenSC-explorer #Ugly Hack for OpenSC-explorer
if(class_byte == 0xb0): if(class_byte == 0xb0):
print "Open SC APDU" logging.debug("Open SC APDU")
SM_STATUS = "No SM" SM_STATUS = "No SM"
#If Bit 8,7,6 == 0 then first industry values are used #If Bit 8,7,6 == 0 then first industry values are used
@@ -305,7 +305,7 @@ class Iso7816OS(SmartcardOS): # {{{
else: else:
answer = self.formatResult(c.effective_Le, result, sw, False) answer = self.formatResult(c.effective_Le, result, sw, False)
except SwError, e: except SwError, e:
print e.message logging.info(e.message)
#traceback.print_exception(*sys.exc_info()) #traceback.print_exception(*sys.exc_info())
sw = e.sw sw = e.sw
result = "" result = ""
@@ -326,14 +326,14 @@ class CryptoflexOS(Iso7816OS): # {{{
try: try:
c = C_APDU(msg) c = C_APDU(msg)
except ValueError, e: except ValueError, e:
print e logging.debug("Failed to parse APDU %s" % msg)
return self.formatResult(0, 0, "", SW["ERR_INCORRECTPARAMETERS"]) return self.formatResult(0, 0, "", SW["ERR_INCORRECTPARAMETERS"])
try: try:
sw, result = self.ins2handler.get(c.ins, notImplemented)(c.p1, c.p2, c.data) sw, result = self.ins2handler.get(c.ins, notImplemented)(c.p1, c.p2, c.data)
#print type(result) #print type(result)
except SwError, e: except SwError, e:
print e.message logging.info(e.message)
#traceback.print_exception(*sys.exc_info()) #traceback.print_exception(*sys.exc_info())
sw = e.sw sw = e.sw
result = "" result = ""
@@ -366,7 +366,8 @@ class RelayOS(SmartcardOS): # {{{
def __init__(self, readernum): def __init__(self, readernum):
readers = smartcard.System.listReaders() readers = smartcard.System.listReaders()
if len(readers) <= readernum: if len(readers) <= readernum:
print "Invalid number of reader '%u' (only %u available)" % (readernum, len(readers)) logging.error("Invalid number of reader '%u' (only %u available)"
% (readernum, len(readers)))
sys.exit() sys.exit()
# XXX this is a workaround, see on sourceforge bug #3083254 # XXX this is a workaround, see on sourceforge bug #3083254
# should better use # should better use
@@ -377,10 +378,10 @@ class RelayOS(SmartcardOS): # {{{
try: try:
self.session = smartcard.Session(self.reader) self.session = smartcard.Session(self.reader)
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException, e:
print "Error connecting to card: %s" % e.message logging.error("Error connecting to card: %s" % e.message)
sys.exit() sys.exit()
print "Connected to card in '%s'" % self.reader logging.info("Connected to card in '%s'" % self.reader)
atexit.register(self.cleanup) atexit.register(self.cleanup)
@@ -388,7 +389,7 @@ class RelayOS(SmartcardOS): # {{{
try: try:
self.session.close() self.session.close()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException, e:
print "Error disconnecting from card: %s" % e.message logging.warning("Error disconnecting from card: %s" % e.message)
def getATR(self): def getATR(self):
try: try:
@@ -399,7 +400,7 @@ class RelayOS(SmartcardOS): # {{{
self.session = smartcard.Session(self.reader) self.session = smartcard.Session(self.reader)
atr = self.session.getATR() atr = self.session.getATR()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException, e:
print "Error getting ATR: %s" % e.message logging.error("Error getting ATR: %s" % e.message)
sys.exit() sys.exit()
return "".join([chr(b) for b in atr]) return "".join([chr(b) for b in atr])
@@ -411,14 +412,14 @@ class RelayOS(SmartcardOS): # {{{
try: try:
self.session = smartcard.Session(self.reader) self.session = smartcard.Session(self.reader)
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException, e:
print "Error connecting to card: %s" % e.message logging.error("Error connecting to card: %s" % e.message)
sys.exit() sys.exit()
def powerDown(self): def powerDown(self):
try: try:
self.session.close() self.session.close()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException, e:
print "Error disconnecting from card: %s" % str(e) logging.error("Error disconnecting from card: %s" % str(e))
sys.exit() sys.exit()
def execute(self, msg): def execute(self, msg):
@@ -430,7 +431,7 @@ class RelayOS(SmartcardOS): # {{{
try: try:
rapdu, sw1, sw2 = self.session.sendCommandAPDU(apdu) rapdu, sw1, sw2 = self.session.sendCommandAPDU(apdu)
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException, e:
print "Error transmitting APDU: %s" % str(e) logging.error("Error transmitting APDU: %s" % str(e))
sys.exit() sys.exit()
# XXX this is a workaround, see on sourceforge bug #3083586 # XXX this is a workaround, see on sourceforge bug #3083586
@@ -462,6 +463,10 @@ class VirtualICC(object): # {{{
def __init__(self, filename, type, host, port, lenlen=3, readernum=None): def __init__(self, filename, type, host, port, lenlen=3, readernum=None):
from os.path import exists from os.path import exists
logging.basicConfig(level = logging.INFO,
format = "%(asctime)s [%(levelname)s] %(message)s",
datefmt = "%d.%m.%Y %H:%M:%S")
self.filename = None self.filename = None
self.cardGenerator = CardGenerator.CardGenerator(type) self.cardGenerator = CardGenerator.CardGenerator(type)
@@ -471,7 +476,8 @@ class VirtualICC(object): # {{{
if exists(filename): if exists(filename):
self.cardGenerator.loadCard(self.filename) self.cardGenerator.loadCard(self.filename)
else: else:
print "Creating new card which will be saved in %s." % self.filename logging.info("Creating new card which will be saved in %s."
% self.filename)
MF, SAM = self.cardGenerator.getCard() MF, SAM = self.cardGenerator.getCard()
@@ -483,7 +489,8 @@ class VirtualICC(object): # {{{
elif type == "relay": elif type == "relay":
self.os = RelayOS(readernum) self.os = RelayOS(readernum)
else: else:
print "Unknown cardtype " + type + ". Will use standard ISO 7816 cardtype" logging.warning("Unknown cardtype %s. Will use standard ISO 7816 cardtype"
% type)
type = "iso7816" type = "iso7816"
self.os = Iso7816OS(MF, SAM) self.os = Iso7816OS(MF, SAM)
self.type = type self.type = type
@@ -493,13 +500,13 @@ class VirtualICC(object): # {{{
self.sock = self.connectToPort(host, port) self.sock = self.connectToPort(host, port)
self.sock.settimeout(None) self.sock.settimeout(None)
except socket.error, e: except socket.error, e:
print "Failed to open socket: %s" % str(e) logging.error("Failed to open socket: %s" % str(e))
print "Is pcscd running at %s? Is vpcd loaded? Is a firewall blocking port %u?" % (host, port) logging.error("Is pcscd running at %s? Is vpcd loaded? Is a firewall blocking port %u?" % (host, port))
sys.exit() sys.exit()
self.lenlen = lenlen self.lenlen = lenlen
print "Connected to virtual PCD at %s:%u" % (host, port) logging.info("Connected to virtual PCD at %s:%u" % (host, port))
signal.signal(signal.SIGINT, self.signalHandler) signal.signal(signal.SIGINT, self.signalHandler)
atexit.register(self.stop) atexit.register(self.stop)
@@ -523,7 +530,7 @@ class VirtualICC(object): # {{{
# receive message size # receive message size
sizestr = self.sock.recv(_Csizeof_short) sizestr = self.sock.recv(_Csizeof_short)
if len(sizestr) == 0: if len(sizestr) == 0:
print "Virtual PCD shut down" logging.info("Virtual PCD shut down")
sys.exit() sys.exit()
size = struct.unpack('!H', sizestr)[0] size = struct.unpack('!H', sizestr)[0]
@@ -531,7 +538,7 @@ class VirtualICC(object): # {{{
if size: if size:
msg = self.sock.recv(size) msg = self.sock.recv(size)
if len(msg) == 0: if len(msg) == 0:
print "Virtual PCD shut down" logging.info("Virtual PCD shut down")
else: else:
msg = None msg = None
@@ -541,28 +548,28 @@ class VirtualICC(object): # {{{
while True : while True :
(size, msg) = self.__recvFromVPICC() (size, msg) = self.__recvFromVPICC()
if not size: if not size:
print "error in communication protocol" logging.warning("Error in communication protocol (missing size parameter)")
elif size == VPCD_CTRL_LEN: elif size == VPCD_CTRL_LEN:
if msg == chr(VPCD_CTRL_OFF): if msg == chr(VPCD_CTRL_OFF):
print "Power Down" logging.info("Power Down")
self.os.powerDown() self.os.powerDown()
elif msg == chr(VPCD_CTRL_ON): elif msg == chr(VPCD_CTRL_ON):
print "Power Up" logging.info("Power Up")
self.os.powerUp() self.os.powerUp()
elif msg == chr(VPCD_CTRL_RESET): elif msg == chr(VPCD_CTRL_RESET):
print "Reset" logging.info("Reset")
self.os.reset() self.os.reset()
elif msg == chr(VPCD_CTRL_ATR): elif msg == chr(VPCD_CTRL_ATR):
self.__sendToVPICC(self.os.getATR()) self.__sendToVPICC(self.os.getATR())
else: else:
print "unknown control command" logging.warning("unknown control command")
else: else:
if size != len(msg): if size != len(msg):
print "Expected APDU of %u bytes, but received only %u" % (size, len(msg)) logging.warning("Expected APDU of %u bytes, but received only %u" % (size, len(msg)))
print "APDU (%d Bytes):\n%s" % (len(msg), hexdump(msg, short=True)) logging.info("APDU (%d Bytes):\n%s" % (len(msg), hexdump(msg, short=True)))
answer = self.os.execute(msg) answer = self.os.execute(msg)
print "RESP (%d Bytes):\n%s\n" % (len(answer), hexdump(answer, short=True)) logging.info("RESP (%d Bytes):\n%s\n" % (len(answer), hexdump(answer, short=True)))
self.__sendToVPICC(answer) self.__sendToVPICC(answer)
def stop(self): def stop(self):