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/>.
#
import sys, getpass, anydbm, readline
import sys, getpass, anydbm, readline, logging
from pickle import loads, dumps
from virtualsmartcard.TLVutils import pack
from virtualsmartcard.utils import inttostring
@@ -45,9 +45,13 @@ class CardGenerator(object):
self.sam = sam
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
self.sam = virtualsmartcard.SmartcardSAM.SAM("1234", "1234567890")
self.sam = virtualsmartcard.SmartcardSAM.SAM(default_pin, default_cardno)
self.mf = MF(filedescriptor=FDB["DF"])
self.sam.set_MF(self.mf)
@@ -74,7 +78,7 @@ class CardGenerator(object):
picture = fd.read()
fd.close()
except IOError:
print "Failed to open file: " + picturepath
logging.warning("Failed to open file: " + picturepath)
pic_width = 0
pic_height = 0
picture = None
@@ -212,7 +216,7 @@ if __name__ == "__main__":
(options, args) = parser.parse_args()
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()
generator = CardGenerator(options.type)

View File

@@ -16,14 +16,13 @@
# You should have received a copy of the GNU General Public License along with
# virtualsmartcard. If not, see <http://www.gnu.org/licenses/>.
#
import sys, binascii, utils, random
from Crypto.Cipher import DES3, DES, AES, ARC4 #,IDEA no longer present in python-crypto?
import sys, binascii, utils, random, logging
from Crypto.Cipher import DES3, DES, AES, ARC4 #,IDEA no longer present in python-crypto? @UnusedImport
from struct import pack
from binascii import b2a_hex, a2b_hex
from random import randint
from virtualsmartcard.utils import inttostring, stringtoint, hexdump
import string
import re
from virtualsmartcard.utils import inttostring, hexdump
import string, re
try:
# Use PyCrypto (if available)
@@ -166,7 +165,7 @@ def hash(hashmethod, data):
from Crypto.Hash import SHA, MD5#, RIPEMD
hash_class = locals().get(hashmethod.upper(), None)
if hash_class == None:
print "Unknown Hash method %s" % hashmethod
logging.error("Unknown Hash method %s" % hashmethod)
raise ValueError
hash = hash_class.new()
hash.update(data)
@@ -231,7 +230,7 @@ def read_protected_string(string, password, cipherspec=None):
#Verify HMAC
checksum = crypto_checksum("HMAC", key, crypted)
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?"
#Decrypt data

View File

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

View File

@@ -17,7 +17,7 @@
# virtualsmartcard. If not, see <http://www.gnu.org/licenses/>.
#
import struct, hashlib
import struct, hashlib, logging
from pickle import dumps, loads
from os import urandom
@@ -122,7 +122,7 @@ class SAM(object):
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
if p1 != 0x00:
@@ -145,7 +145,6 @@ class SAM(object):
data = data.replace("\0","") #Strip NULL charakters
self.PIN = data
print "New PIN = %s" % self.PIN
return SW["NORMAL"], ""
def internal_authenticate(self, p1, p2, data):
@@ -171,7 +170,7 @@ class SAM(object):
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
"""
if self.last_challenge is None:
@@ -190,10 +189,6 @@ class SAM(object):
self.last_challenge = None
return SW["NORMAL"], ""
else:
plain = vsCrypto.decrypt(cipher, key, data)
print plain
print "Reference: " + hexdump(reference)
print "Data: " + hexdump(data)
raise SwError(SW["WARN_NOINFO63"])
#TODO: Counter for external authenticate?
@@ -201,7 +196,7 @@ class SAM(object):
"""
Takes an encrypted challenge in the form
'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
returns this value
"""
@@ -242,7 +237,7 @@ class SAM(object):
length = 8 #Length of the challenge in Byte
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)
return SW["NORMAL"], self.last_challenge
@@ -282,7 +277,7 @@ class SAM(object):
df = self.mf.currentDF()
fid = df.select("fid", stringtoint(qualifier))
key = fid.readbinary(keylength)
if key != None:
return key
else:
@@ -1056,8 +1051,8 @@ class CryptoflexSM(Secure_Messaging):
e_in = struct.unpack("<i", data)
if e_in[0] != 65537:
print "Warning: Exponents different from 65537 are ignored!" +\
"The Exponent given is %i" % e_in[0]
logging.warning("Warning: Exponents different from 65537 are ignored!" +\
"The Exponent given is %i" % e_in[0])
#Encode Public key
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
import CardGenerator
import socket, struct, sys, signal, atexit, smartcard
import socket, struct, sys, signal, atexit, smartcard, logging
class SmartcardOS(object): # {{{
@@ -246,7 +246,7 @@ class Iso7816OS(SmartcardOS): # {{{
try:
c = C_APDU(msg)
except ValueError, e:
print e
logging.warning(str(e))
return self.formatResult(0, "", SW["ERR_INCORRECTPARAMETERS"], False)
#Handle Class Byte{{{
@@ -258,7 +258,7 @@ class Iso7816OS(SmartcardOS): # {{{
#Ugly Hack for OpenSC-explorer
if(class_byte == 0xb0):
print "Open SC APDU"
logging.debug("Open SC APDU")
SM_STATUS = "No SM"
#If Bit 8,7,6 == 0 then first industry values are used
@@ -305,7 +305,7 @@ class Iso7816OS(SmartcardOS): # {{{
else:
answer = self.formatResult(c.effective_Le, result, sw, False)
except SwError, e:
print e.message
logging.info(e.message)
#traceback.print_exception(*sys.exc_info())
sw = e.sw
result = ""
@@ -326,14 +326,14 @@ class CryptoflexOS(Iso7816OS): # {{{
try:
c = C_APDU(msg)
except ValueError, e:
print e
logging.debug("Failed to parse APDU %s" % msg)
return self.formatResult(0, 0, "", SW["ERR_INCORRECTPARAMETERS"])
try:
sw, result = self.ins2handler.get(c.ins, notImplemented)(c.p1, c.p2, c.data)
#print type(result)
except SwError, e:
print e.message
logging.info(e.message)
#traceback.print_exception(*sys.exc_info())
sw = e.sw
result = ""
@@ -366,7 +366,8 @@ class RelayOS(SmartcardOS): # {{{
def __init__(self, readernum):
readers = smartcard.System.listReaders()
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()
# XXX this is a workaround, see on sourceforge bug #3083254
# should better use
@@ -377,10 +378,10 @@ class RelayOS(SmartcardOS): # {{{
try:
self.session = smartcard.Session(self.reader)
except smartcard.Exceptions.CardConnectionException, e:
print "Error connecting to card: %s" % e.message
logging.error("Error connecting to card: %s" % e.message)
sys.exit()
print "Connected to card in '%s'" % self.reader
logging.info("Connected to card in '%s'" % self.reader)
atexit.register(self.cleanup)
@@ -388,7 +389,7 @@ class RelayOS(SmartcardOS): # {{{
try:
self.session.close()
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):
try:
@@ -399,7 +400,7 @@ class RelayOS(SmartcardOS): # {{{
self.session = smartcard.Session(self.reader)
atr = self.session.getATR()
except smartcard.Exceptions.CardConnectionException, e:
print "Error getting ATR: %s" % e.message
logging.error("Error getting ATR: %s" % e.message)
sys.exit()
return "".join([chr(b) for b in atr])
@@ -411,14 +412,14 @@ class RelayOS(SmartcardOS): # {{{
try:
self.session = smartcard.Session(self.reader)
except smartcard.Exceptions.CardConnectionException, e:
print "Error connecting to card: %s" % e.message
logging.error("Error connecting to card: %s" % e.message)
sys.exit()
def powerDown(self):
try:
self.session.close()
except smartcard.Exceptions.CardConnectionException, e:
print "Error disconnecting from card: %s" % str(e)
logging.error("Error disconnecting from card: %s" % str(e))
sys.exit()
def execute(self, msg):
@@ -430,7 +431,7 @@ class RelayOS(SmartcardOS): # {{{
try:
rapdu, sw1, sw2 = self.session.sendCommandAPDU(apdu)
except smartcard.Exceptions.CardConnectionException, e:
print "Error transmitting APDU: %s" % str(e)
logging.error("Error transmitting APDU: %s" % str(e))
sys.exit()
# 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):
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.cardGenerator = CardGenerator.CardGenerator(type)
@@ -471,7 +476,8 @@ class VirtualICC(object): # {{{
if exists(filename):
self.cardGenerator.loadCard(self.filename)
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()
@@ -483,7 +489,8 @@ class VirtualICC(object): # {{{
elif type == "relay":
self.os = RelayOS(readernum)
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"
self.os = Iso7816OS(MF, SAM)
self.type = type
@@ -493,13 +500,13 @@ class VirtualICC(object): # {{{
self.sock = self.connectToPort(host, port)
self.sock.settimeout(None)
except socket.error, e:
print "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("Failed to open socket: %s" % str(e))
logging.error("Is pcscd running at %s? Is vpcd loaded? Is a firewall blocking port %u?" % (host, port))
sys.exit()
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)
atexit.register(self.stop)
@@ -523,7 +530,7 @@ class VirtualICC(object): # {{{
# receive message size
sizestr = self.sock.recv(_Csizeof_short)
if len(sizestr) == 0:
print "Virtual PCD shut down"
logging.info("Virtual PCD shut down")
sys.exit()
size = struct.unpack('!H', sizestr)[0]
@@ -531,7 +538,7 @@ class VirtualICC(object): # {{{
if size:
msg = self.sock.recv(size)
if len(msg) == 0:
print "Virtual PCD shut down"
logging.info("Virtual PCD shut down")
else:
msg = None
@@ -541,28 +548,28 @@ class VirtualICC(object): # {{{
while True :
(size, msg) = self.__recvFromVPICC()
if not size:
print "error in communication protocol"
logging.warning("Error in communication protocol (missing size parameter)")
elif size == VPCD_CTRL_LEN:
if msg == chr(VPCD_CTRL_OFF):
print "Power Down"
logging.info("Power Down")
self.os.powerDown()
elif msg == chr(VPCD_CTRL_ON):
print "Power Up"
logging.info("Power Up")
self.os.powerUp()
elif msg == chr(VPCD_CTRL_RESET):
print "Reset"
logging.info("Reset")
self.os.reset()
elif msg == chr(VPCD_CTRL_ATR):
self.__sendToVPICC(self.os.getATR())
else:
print "unknown control command"
logging.warning("unknown control command")
else:
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)
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)
def stop(self):