From fa3feddf3a25e34db2ac57ff8e962f13db07bf40 Mon Sep 17 00:00:00 2001 From: Rob Austein Date: Mon, 25 May 2020 19:33:47 -0400 Subject: Untested conversion to support Python 3 --- cryptech/py11/__init__.py | 4 +- cryptech/py11/attributes.py | 164 ++++++++++++++++++++++---------------------- cryptech/py11/mutex.py | 92 ++++++++++++------------- cryptech/py11/types.py | 106 ++++++++++++++-------------- 4 files changed, 184 insertions(+), 182 deletions(-) (limited to 'cryptech') diff --git a/cryptech/py11/__init__.py b/cryptech/py11/__init__.py index 1618a76..740ecb6 100644 --- a/cryptech/py11/__init__.py +++ b/cryptech/py11/__init__.py @@ -125,7 +125,7 @@ class PKCS11 (object): self.d.C_GetSlotList(CK_TRUE, None, byref(count)) slots = (CK_SLOT_ID * count.value)() self.d.C_GetSlotList(CK_TRUE, slots, byref(count)) - return tuple(slots[i] for i in xrange(count.value)) + return tuple(slots[i] for i in range(count.value)) def C_GetTokenInfo(self, slot_id): token_info = CK_TOKEN_INFO() @@ -169,7 +169,7 @@ class PKCS11 (object): count = CK_ULONG(1) while count.value > 0: self.d.C_FindObjects(session, objects, len(objects), byref(count)) - for i in xrange(count.value): + for i in range(count.value): yield objects[i] def FindObjects(self, session, template = None, **kwargs): diff --git a/cryptech/py11/attributes.py b/cryptech/py11/attributes.py index 56473ad..c6a87da 100644 --- a/cryptech/py11/attributes.py +++ b/cryptech/py11/attributes.py @@ -2,100 +2,102 @@ # module from the Python standard library. from struct import pack, unpack +from binascii import hexlify, unhexlify from ctypes import * from .types import * from .constants import * class Attribute(object): - @classmethod - def new(cls, attribute_name, type_name): - from . import constants - from . import types - assert attribute_name.startswith("CKA_") - attribute_number = getattr(constants, attribute_name) - type_class = getattr(types, type_name, str) - if type_class is CK_BBOOL: - cls = Attribute_CK_BBOOL - elif type_class is CK_ULONG: - cls = Attribute_CK_ULONG - elif type_name == "biginteger": - cls = Attribute_biginteger - return cls(attribute_name, attribute_number, type_name, type_class) - - def __init__(self, attribute_name, attribute_number, type_name, type_class): - assert attribute_name.startswith("CKA_") - self.name = attribute_name - self.code = attribute_number - self.type_name = type_name - self.type_class = type_class - - def encode(self, x): return x - def decode(self, x): return x + @classmethod + def new(cls, attribute_name, type_name): + from . import constants + from . import types + assert attribute_name.startswith("CKA_") + attribute_number = getattr(constants, attribute_name) + type_class = getattr(types, type_name, str) + if type_class is CK_BBOOL: + cls = Attribute_CK_BBOOL + elif type_class is CK_ULONG: + cls = Attribute_CK_ULONG + elif type_name == "biginteger": + cls = Attribute_biginteger + return cls(attribute_name, attribute_number, type_name, type_class) + + def __init__(self, attribute_name, attribute_number, type_name, type_class): + assert attribute_name.startswith("CKA_") + self.name = attribute_name + self.code = attribute_number + self.type_name = type_name + self.type_class = type_class + + def encode(self, x): return x + def decode(self, x): return x class Attribute_CK_BBOOL(Attribute): - def encode(self, x): return chr(int(x)) - def decode(self, x): return bool(ord(x)) + def encode(self, x): return chr(int(x)) + def decode(self, x): return bool(ord(x)) class Attribute_CK_ULONG(Attribute): - def encode(self, x): return pack("L", x) - def decode(self, x): return unpack("L", x)[0] + def encode(self, x): return pack("L", x) + def decode(self, x): return unpack("L", x)[0] class Attribute_biginteger(Attribute): - def encode(self, x): return "\x00" if x == 0 else ("%0*x" % (((x.bit_length() + 7) / 8) * 2, x)).decode("hex") - def decode(self, x): return long(x.encode("hex"), 16) + def encode(self, x): return "\x00" if x == 0 else unhexlify("{0:0{1}x".format(x, ((x.bit_length() + 7) / 8) * 2)) + def decode(self, x): return int(hexlify(x), 16) class AttributeDB(object): - def __init__(self): - from .attribute_map import attribute_map - self.db = {} - for attribute_name, type_name in attribute_map.iteritems(): - a = Attribute.new(attribute_name, type_name) - self.db[a.name] = a - self.db[a.code] = a - - def encode(self, k, v): - return self.db[k].encode(v) if k in self.db else v - - def decode(self, k, v): - return self.db[k].decode(v) if k in self.db else v - - def getvalue_create_template(self, attributes): - attributes = tuple(self.db[a].code for a in attributes) - template = (CK_ATTRIBUTE * len(attributes))() - for i in xrange(len(attributes)): - template[i].type = attributes[i] - template[i].pValue = None - template[i].ulValueLen = 0 - return template - - def getvalue_allocate_template(self, template): - for t in template: - t.pValue = create_string_buffer(t.ulValueLen) - - def from_ctypes(self, template): - return dict((t.type, self.decode(t.type, t.pValue[:t.ulValueLen])) - for t in template) - - def to_ctypes(self, attributes): - attributes = tuple(attributes.iteritems() - if isinstance(attributes, dict) else - attributes) - template = (CK_ATTRIBUTE * len(attributes))() - for i, kv in enumerate(attributes): - k, v = kv - if k in self.db: - a = self.db[k] - k, v = a.code, a.encode(v) - template[i].type = k - template[i].pValue = create_string_buffer(v) - template[i].ulValueLen = len(v) - return template - - def attribute_name(self, code): - return self.db[code].name - - def attribute_code(self, name): - return self.db[name].code + def __init__(self): + from .attribute_map import attribute_map + self.db = {} + for attribute_name, type_name in attribute_map.items(): + a = Attribute.new(attribute_name, type_name) + self.db[a.name] = a + self.db[a.code] = a + + def encode(self, k, v): + return self.db[k].encode(v) if k in self.db else v + + def decode(self, k, v): + return self.db[k].decode(v) if k in self.db else v + + def getvalue_create_template(self, attributes): + attributes = tuple(self.db[a].code for a in attributes) + template = (CK_ATTRIBUTE * len(attributes))() + for i in range(len(attributes)): + template[i].type = attributes[i] + template[i].pValue = None + template[i].ulValueLen = 0 + return template + + def getvalue_allocate_template(self, template): + for t in template: + t.pValue = create_string_buffer(t.ulValueLen) + + def from_ctypes(self, template): + return dict((t.type, self.decode(t.type, t.pValue[:t.ulValueLen])) + for t in template) + + def to_ctypes(self, attributes): + if isinstance(attributes, dict): + attributes = tuple(iter(attributes.items())) + else: + attributes = tuple(attributes) + template = (CK_ATTRIBUTE * len(attributes))() + for i, kv in enumerate(attributes): + k, v = kv + if k in self.db: + a = self.db[k] + k, v = a.code, a.encode(v) + template[i].type = k + template[i].pValue = create_string_buffer(v) + template[i].ulValueLen = len(v) + return template + + def attribute_name(self, code): + return self.db[code].name + + def attribute_code(self, name): + return self.db[name].code diff --git a/cryptech/py11/mutex.py b/cryptech/py11/mutex.py index da2123c..d3807f6 100644 --- a/cryptech/py11/mutex.py +++ b/cryptech/py11/mutex.py @@ -33,57 +33,57 @@ encoded_format = "=L" encoded_length = len(pack(encoded_format, 0)) encoded_type = CK_BYTE * encoded_length -handle_max = unpack(encoded_format, chr(0xff) * encoded_length)[0] +handle_max = unpack(encoded_format, b"\xff" * encoded_length)[0] class Mutex(object): - def __init__(self, handle): - from threading import Lock - self.encoded = encoded_type(*handle) - self.lock = Lock() + def __init__(self, handle): + from threading import Lock + self.encoded = encoded_type(*handle) + self.lock = Lock() def p11_callback(func): - from threading import ThreadError - def wrapper(self, arg): - try: - func(self, arg) - except ThreadError, e: - print "Failed: %s" % e - return CKR_MUTEX_NOT_LOCKED.ckr_code - except Exception, e: - print "Failed: %s" % e - return CKR_FUNCTION_FAILED.ckr_code - else: - return CKR_OK - return wrapper + from threading import ThreadError + def wrapper(self, arg): + try: + func(self, arg) + except ThreadError as e: + print("Failed: %s" % e) + return CKR_MUTEX_NOT_LOCKED.ckr_code + except Exception as e: + print("Failed: %s" % e) + return CKR_FUNCTION_FAILED.ckr_code + else: + return CKR_OK + return wrapper class MutexDB(object): - def __init__(self): - self.mutexes = {} - self.next_handle = 0 - - def find_free_handle(self): - if len(self.mutexes) > handle_max: - raise RuntimeError - while self.next_handle in self.mutexes: - self.next_handle = (self.next_handle + 1) & handle_max - return pack(encoded_format, self.next_handle) - - @p11_callback - def create(self, handle_ptr): - handle = self.find_free_handle() - self.mutexes[handle] = Mutex(handle) - handle_ptr[0] = self.mutexes[handle].encoded - - @p11_callback - def destroy(self, handle): - del self.mutexes[handle[:encoded_length]] - - @p11_callback - def lock(self, handle): - self.mutexes[handle[:encoded_length]].lock.acquire() - - @p11_callback - def unlock(self, handle): - self.mutexes[handle[:encoded_length]].lock.release() + def __init__(self): + self.mutexes = {} + self.next_handle = 0 + + def find_free_handle(self): + if len(self.mutexes) > handle_max: + raise RuntimeError + while self.next_handle in self.mutexes: + self.next_handle = (self.next_handle + 1) & handle_max + return pack(encoded_format, self.next_handle) + + @p11_callback + def create(self, handle_ptr): + handle = self.find_free_handle() + self.mutexes[handle] = Mutex(handle) + handle_ptr[0] = self.mutexes[handle].encoded + + @p11_callback + def destroy(self, handle): + del self.mutexes[handle[:encoded_length]] + + @p11_callback + def lock(self, handle): + self.mutexes[handle[:encoded_length]].lock.acquire() + + @p11_callback + def unlock(self, handle): + self.mutexes[handle[:encoded_length]].lock.release() diff --git a/cryptech/py11/types.py b/cryptech/py11/types.py index 1b233e7..91e2d8b 100644 --- a/cryptech/py11/types.py +++ b/cryptech/py11/types.py @@ -49,17 +49,17 @@ CK_ULONG_PTR = POINTER(CK_ULONG) CK_VOID_PTR_PTR = POINTER(CK_VOID_PTR) class CK_VERSION (Structure): - _fields_ = [("major", c_ubyte), - ("minor", c_ubyte)] + _fields_ = [("major", c_ubyte), + ("minor", c_ubyte)] CK_VERSION_PTR = POINTER(CK_VERSION) class CK_INFO (Structure): - _fields_ = [("cryptokiVersion", CK_VERSION), - ("manufacturerID", CK_UTF8CHAR * 32), - ("flags", CK_FLAGS), - ("libraryDescription", CK_UTF8CHAR * 32), - ("libraryVersion", CK_VERSION)] + _fields_ = [("cryptokiVersion", CK_VERSION), + ("manufacturerID", CK_UTF8CHAR * 32), + ("flags", CK_FLAGS), + ("libraryDescription", CK_UTF8CHAR * 32), + ("libraryVersion", CK_VERSION)] CK_INFO_PTR = POINTER(CK_INFO) @@ -70,33 +70,33 @@ CK_SLOT_ID = CK_ULONG CK_SLOT_ID_PTR = POINTER(CK_SLOT_ID) class CK_SLOT_INFO (Structure): - _fields_ = [("slotDescription", CK_UTF8CHAR * 64), - ("manufacturerID", CK_UTF8CHAR * 32), - ("flags", CK_FLAGS), - ("hardwareVersion", CK_VERSION), - ("firmwareVersion", CK_VERSION)] + _fields_ = [("slotDescription", CK_UTF8CHAR * 64), + ("manufacturerID", CK_UTF8CHAR * 32), + ("flags", CK_FLAGS), + ("hardwareVersion", CK_VERSION), + ("firmwareVersion", CK_VERSION)] CK_SLOT_INFO_PTR = POINTER(CK_SLOT_INFO) class CK_TOKEN_INFO (Structure): - _fields_ = [("label", CK_UTF8CHAR * 32), - ("manufacturerID", CK_UTF8CHAR * 32), - ("model", CK_UTF8CHAR * 16), - ("serialNumber", CK_CHAR * 16), - ("flags", CK_FLAGS), - ("ulMaxSessionCount", CK_ULONG), - ("ulSessionCount", CK_ULONG), - ("ulMaxRwSessionCount", CK_ULONG), - ("ulRwSessionCount", CK_ULONG), - ("ulMaxPinLen", CK_ULONG), - ("ulMinPinLen", CK_ULONG), - ("ulTotalPublicMemory", CK_ULONG), - ("ulFreePublicMemory", CK_ULONG), - ("ulTotalPrivateMemory", CK_ULONG), - ("ulFreePrivateMemory", CK_ULONG), - ("hardwareVersion", CK_VERSION), - ("firmwareVersion", CK_VERSION), - ("utcTime", CK_CHAR * 16)] + _fields_ = [("label", CK_UTF8CHAR * 32), + ("manufacturerID", CK_UTF8CHAR * 32), + ("model", CK_UTF8CHAR * 16), + ("serialNumber", CK_CHAR * 16), + ("flags", CK_FLAGS), + ("ulMaxSessionCount", CK_ULONG), + ("ulSessionCount", CK_ULONG), + ("ulMaxRwSessionCount", CK_ULONG), + ("ulRwSessionCount", CK_ULONG), + ("ulMaxPinLen", CK_ULONG), + ("ulMinPinLen", CK_ULONG), + ("ulTotalPublicMemory", CK_ULONG), + ("ulFreePublicMemory", CK_ULONG), + ("ulTotalPrivateMemory",CK_ULONG), + ("ulFreePrivateMemory", CK_ULONG), + ("hardwareVersion", CK_VERSION), + ("firmwareVersion", CK_VERSION), + ("utcTime", CK_CHAR * 16)] CK_TOKEN_INFO_PTR = POINTER(CK_TOKEN_INFO) @@ -109,10 +109,10 @@ CK_USER_TYPE = CK_ULONG CK_STATE = CK_ULONG class CK_SESSION_INFO (Structure): - _fields_ = [("slotID", CK_SLOT_ID), - ("state", CK_STATE), - ("flags", CK_FLAGS), - ("ulDeviceError", CK_ULONG)] + _fields_ = [("slotID", CK_SLOT_ID), + ("state", CK_STATE), + ("flags", CK_FLAGS), + ("ulDeviceError", CK_ULONG)] CK_SESSION_INFO_PTR = POINTER(CK_SESSION_INFO) @@ -133,32 +133,32 @@ CK_CERTIFICATE_TYPE = CK_ULONG CK_ATTRIBUTE_TYPE = CK_ULONG class CK_ATTRIBUTE (Structure): - _fields_ = [("type", CK_ATTRIBUTE_TYPE), - ("pValue", CK_VOID_PTR), - ("ulValueLen", CK_ULONG)] + _fields_ = [("type", CK_ATTRIBUTE_TYPE), + ("pValue", CK_VOID_PTR), + ("ulValueLen", CK_ULONG)] CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) class CK_DATE (Structure): - _fields_ = [("year", CK_CHAR * 4), - ("month", CK_CHAR * 2), - ("day", CK_CHAR * 2)] + _fields_ = [("year", CK_CHAR * 4), + ("month", CK_CHAR * 2), + ("day", CK_CHAR * 2)] CK_MECHANISM_TYPE = CK_ULONG CK_MECHANISM_TYPE_PTR = POINTER(CK_MECHANISM_TYPE) class CK_MECHANISM (Structure): - _fields_ = [("mechanism", CK_MECHANISM_TYPE), - ("pParameter", CK_VOID_PTR), - ("ulParameterLen", CK_ULONG)] + _fields_ = [("mechanism", CK_MECHANISM_TYPE), + ("pParameter", CK_VOID_PTR), + ("ulParameterLen", CK_ULONG)] CK_MECHANISM_PTR = POINTER(CK_MECHANISM) class CK_MECHANISM_INFO (Structure): - _fields_ = [("ulMinKeySize", CK_ULONG), - ("ulMaxKeySize", CK_ULONG), - ("flags", CK_FLAGS)] + _fields_ = [("ulMinKeySize", CK_ULONG), + ("ulMaxKeySize", CK_ULONG), + ("flags", CK_FLAGS)] CK_MECHANISM_INFO_PTR = POINTER(CK_MECHANISM_INFO) @@ -172,12 +172,12 @@ CK_LOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) CK_UNLOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) class CK_C_INITIALIZE_ARGS (Structure): - _fields_ = [("CreateMutex", CK_CREATEMUTEX), - ("DestroyMutex", CK_DESTROYMUTEX), - ("LockMutex", CK_LOCKMUTEX), - ("UnlockMutex", CK_UNLOCKMUTEX), - ("flags", CK_FLAGS), - ("pReserved", CK_VOID_PTR)] + _fields_ = [("CreateMutex", CK_CREATEMUTEX), + ("DestroyMutex", CK_DESTROYMUTEX), + ("LockMutex", CK_LOCKMUTEX), + ("UnlockMutex", CK_UNLOCKMUTEX), + ("flags", CK_FLAGS), + ("pReserved", CK_VOID_PTR)] CK_C_INITIALIZE_ARGS_PTR = POINTER(CK_C_INITIALIZE_ARGS) @@ -188,7 +188,7 @@ CK_C_INITIALIZE_ARGS_PTR = POINTER(CK_C_INITIALIZE_ARGS) # gratuitous Python module loop too. class CK_FUNCTION_LIST (Structure): - pass + pass CK_FUNCTION_LIST_PTR = POINTER(CK_FUNCTION_LIST) CK_FUNCTION_LIST_PTR_PTR = POINTER(CK_FUNCTION_LIST_PTR) -- cgit v1.2.3