From ffcbdae25224b1eda141f3bd895a11334403ac8f Mon Sep 17 00:00:00 2001 From: "Young, Shawn" Date: Tue, 12 May 2015 09:22:58 -0500 Subject: [PATCH 001/109] Initial empty repository From 7887f16d6c0385d5e124c3653ed89dc5b86f0671 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 12 May 2015 10:22:12 -0400 Subject: [PATCH 002/109] LA-1060 Initial commit of pycryptoki Change-Id: I7f0f8151f98189c4a59487aac820e4153d713cc8 --- .gitignore | 110 + README.txt | 6 + __init__.py | 0 pycryptoki/__init__.py | 0 pycryptoki/attributes.py | 483 ++++ pycryptoki/audit_handling.py | 35 + pycryptoki/backup.py | 57 + pycryptoki/cryptoki.py | 2265 +++++++++++++++++ pycryptoki/cryptoki_helpers.py | 210 ++ pycryptoki/daemon/__init__.py | 0 pycryptoki/daemon/pycryptoki_daemon.py | 297 +++ pycryptoki/daemon/pycryptoki_daemon.py.bak | 295 +++ pycryptoki/daemon/rpyc_pycryptoki.py | 312 +++ pycryptoki/default_templates.py | 857 +++++++ pycryptoki/defaults.py | 42 + pycryptoki/dictionary_handling.py | 16 + pycryptoki/encryption.py | 406 +++ pycryptoki/hsm_management.py | 192 ++ pycryptoki/key_generator.py | 150 ++ pycryptoki/key_management.py | 61 + pycryptoki/key_usage.py | 32 + pycryptoki/logging_filters.py | 26 + pycryptoki/luna_threading.py | 146 ++ pycryptoki/mechanism.py | 136 + pycryptoki/misc.py | 151 ++ pycryptoki/object_attr_lookup.py | 71 + pycryptoki/policy_management.py | 50 + pycryptoki/pycryptoki_client.py | 113 + pycryptoki/session_management.py | 358 +++ pycryptoki/setup/__init__.py | 0 pycryptoki/setup/distribute.py | 37 + pycryptoki/setup/initialize.py | 403 +++ pycryptoki/setup/make_and_install.py | 29 + pycryptoki/setup/setup_tools.sh | 32 + pycryptoki/setup/verify_version.py | 36 + pycryptoki/sign_verify.py | 249 ++ pycryptoki/test_functions.py | 206 ++ pycryptoki/tests/__init__.py | 0 pycryptoki/tests/run_tests_in_folder.py | 9 + pycryptoki/tests/setup_for_tests.py | 43 + pycryptoki/tests/stress/__init__.py | 0 pycryptoki/tests/stress/conftest.py | 32 + pycryptoki/tests/stress/setup.cfg | 3 + pycryptoki/tests/stress/test_multi_reset.py | 341 +++ pycryptoki/tests/stress/vreset_thread.py | 54 + pycryptoki/tests/test_cka_start_and_end.py | 358 +++ pycryptoki/tests/test_digest_data.py | 53 + pycryptoki/tests/test_encrypt_decrypt.py | 72 + pycryptoki/tests/test_get_token_info.py | 47 + pycryptoki/tests/test_hsm_management.py | 226 ++ pycryptoki/tests/test_key_management.py | 106 + pycryptoki/tests/test_key_usage.py | 69 + pycryptoki/tests/test_keys.py | 167 ++ pycryptoki/tests/test_object_create.py | 59 + pycryptoki/tests/test_sign_verify.py | 95 + .../tests/test_supporting_operations.py | 62 + .../tests/test_usage_limit_and_count.py | 326 +++ pycryptoki/tests/test_wrap_unwrap.py | 87 + pycryptoki/token_management.py | 103 + pycryptoki/utils/__init__.py | 0 pycryptoki/utils/common_utils.py | 6 + setup.py | 17 + 62 files changed, 10204 insertions(+) create mode 100644 .gitignore create mode 100755 README.txt create mode 100755 __init__.py create mode 100755 pycryptoki/__init__.py create mode 100755 pycryptoki/attributes.py create mode 100755 pycryptoki/audit_handling.py create mode 100755 pycryptoki/backup.py create mode 100755 pycryptoki/cryptoki.py create mode 100755 pycryptoki/cryptoki_helpers.py create mode 100755 pycryptoki/daemon/__init__.py create mode 100755 pycryptoki/daemon/pycryptoki_daemon.py create mode 100755 pycryptoki/daemon/pycryptoki_daemon.py.bak create mode 100755 pycryptoki/daemon/rpyc_pycryptoki.py create mode 100755 pycryptoki/default_templates.py create mode 100755 pycryptoki/defaults.py create mode 100755 pycryptoki/dictionary_handling.py create mode 100755 pycryptoki/encryption.py create mode 100755 pycryptoki/hsm_management.py create mode 100755 pycryptoki/key_generator.py create mode 100755 pycryptoki/key_management.py create mode 100755 pycryptoki/key_usage.py create mode 100755 pycryptoki/logging_filters.py create mode 100755 pycryptoki/luna_threading.py create mode 100755 pycryptoki/mechanism.py create mode 100755 pycryptoki/misc.py create mode 100755 pycryptoki/object_attr_lookup.py create mode 100755 pycryptoki/policy_management.py create mode 100755 pycryptoki/pycryptoki_client.py create mode 100755 pycryptoki/session_management.py create mode 100755 pycryptoki/setup/__init__.py create mode 100755 pycryptoki/setup/distribute.py create mode 100755 pycryptoki/setup/initialize.py create mode 100755 pycryptoki/setup/make_and_install.py create mode 100755 pycryptoki/setup/setup_tools.sh create mode 100755 pycryptoki/setup/verify_version.py create mode 100755 pycryptoki/sign_verify.py create mode 100755 pycryptoki/test_functions.py create mode 100755 pycryptoki/tests/__init__.py create mode 100755 pycryptoki/tests/run_tests_in_folder.py create mode 100755 pycryptoki/tests/setup_for_tests.py create mode 100755 pycryptoki/tests/stress/__init__.py create mode 100755 pycryptoki/tests/stress/conftest.py create mode 100755 pycryptoki/tests/stress/setup.cfg create mode 100755 pycryptoki/tests/stress/test_multi_reset.py create mode 100755 pycryptoki/tests/stress/vreset_thread.py create mode 100755 pycryptoki/tests/test_cka_start_and_end.py create mode 100755 pycryptoki/tests/test_digest_data.py create mode 100755 pycryptoki/tests/test_encrypt_decrypt.py create mode 100755 pycryptoki/tests/test_get_token_info.py create mode 100755 pycryptoki/tests/test_hsm_management.py create mode 100755 pycryptoki/tests/test_key_management.py create mode 100755 pycryptoki/tests/test_key_usage.py create mode 100755 pycryptoki/tests/test_keys.py create mode 100755 pycryptoki/tests/test_object_create.py create mode 100755 pycryptoki/tests/test_sign_verify.py create mode 100755 pycryptoki/tests/test_supporting_operations.py create mode 100755 pycryptoki/tests/test_usage_limit_and_count.py create mode 100755 pycryptoki/tests/test_wrap_unwrap.py create mode 100755 pycryptoki/token_management.py create mode 100755 pycryptoki/utils/__init__.py create mode 100755 pycryptoki/utils/common_utils.py create mode 100755 setup.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..63a623f --- /dev/null +++ b/.gitignore @@ -0,0 +1,110 @@ +# Created by https://www.gitignore.io + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties + + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + diff --git a/README.txt b/README.txt new file mode 100755 index 0000000..7bd92fe --- /dev/null +++ b/README.txt @@ -0,0 +1,6 @@ +PyCryptoki is a module dedicated to testing the cryptoki library. In order to +achieve this goal it parses the cryptoki.h header file and creates automatically +generated python code to interface with the libCryptoki2.so DLL. + +More setup information can be found on the wiki: +http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Pages/pycryptoki.aspx \ No newline at end of file diff --git a/__init__.py b/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/pycryptoki/__init__.py b/pycryptoki/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py new file mode 100755 index 0000000..0cc809a --- /dev/null +++ b/pycryptoki/attributes.py @@ -0,0 +1,483 @@ +""" +This module contains a wrapper around the key attributes and the template struct +generation to make it possible to create templates in python and easily +convert them into templates in C. +""" +from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ + CK_BYTE, C_GetAttributeValue, CK_OBJECT_HANDLE, CK_DATE, CK_CHAR, CK_CHAR_PTR +from ctypes import cast, c_void_p, create_string_buffer, c_bool, c_char_p, \ + c_ulong, pointer, POINTER, byref, sizeof, c_int, c_ubyte +from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ + CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_VALUE, CKA_CERTIFICATE_TYPE, \ + CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ + CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER, \ + CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE, \ + CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, \ + CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT, \ + CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, \ + CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_ECDSA_PARAMS, CKA_EC_POINT, CKA_LOCAL, \ + CKA_MODIFIABLE, CKA_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_NEVER_EXTRACTABLE, \ + CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_PKC_TCTRUST, CKA_PKC_CITS, CKA_OUID, \ + CKA_X9_31_GENERATED, CKA_PKC_ECC, CKR_OK +from pycryptoki.cryptoki import CK_ULONG_PTR, CK_ATTRIBUTE_PTR, CK_BYTE_PTR +from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ + CKA_GENERIC_3 +from pycryptoki.dictionary_handling import CDict +import logging + +''' +List class for handling attributes with lists of a certain type +''' +class CList: + list_type = None + + def __init__(self, list_type): + self.list_type = list_type + +class NonAsciiString: + data = None + def __init__(self, data): + self.data = data + +def get_byte_list_from_python_list(python_byte_list): + ''' + Helper method to create a C style byte list from a python + style list of integers. + @param python_byte_list: A list of integers to convert to a C style list of integers + @return: The pointer to the C representation of the python byte list + ''' + list_val = create_string_buffer("", len(python_byte_list)) + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(python_byte_list)): + list_val[j] = chr(python_byte_list[j]) + return ptr + + +date_attrb = {'year' : str, + 'month' : str, + 'day' : str} + +''' +A mapping of attributes to what type they have. This is used when converting +a python dictionary to a C struct or vice versa +''' +key_attributes = {CKA_USAGE_LIMIT : long, + CKA_USAGE_COUNT : long, + CKA_CLASS : long, + CKA_TOKEN : bool, + CKA_PRIVATE : bool, + CKA_LABEL : str, + CKA_APPLICATION : None, + CKA_VALUE : CList(str), + CKA_CERTIFICATE_TYPE : long, # TODO guessing + CKA_ISSUER : None, + CKA_SERIAL_NUMBER : None, + CKA_KEY_TYPE : long, + CKA_SUBJECT : str, + CKA_ID : None, + CKA_SENSITIVE : bool, + CKA_ENCRYPT : bool, + CKA_DECRYPT : bool, + CKA_WRAP : bool, + CKA_UNWRAP : bool, + CKA_SIGN : bool, + CKA_SIGN_RECOVER : None, + CKA_VERIFY : bool, + CKA_VERIFY_RECOVER : None, + CKA_DERIVE : bool, + CKA_START_DATE : CDict(date_attrb), + CKA_END_DATE : CDict(date_attrb), + CKA_MODULUS : None, + CKA_MODULUS_BITS : long, + CKA_PUBLIC_EXPONENT : int, #Python has no concept of byte + CKA_PRIVATE_EXPONENT : None, + CKA_PRIME_1 : None, + CKA_PRIME_2 : None, + CKA_EXPONENT_1 : None, + CKA_EXPONENT_2 : None, + CKA_COEFFICIENT : None, + CKA_PRIME : CList(str), + CKA_SUBPRIME : CList(str), + CKA_BASE : CList(str), + CKA_PRIME_BITS : long, + CKA_SUBPRIME_BITS : long, + CKA_VALUE_BITS : long, + CKA_VALUE_LEN: long, + CKA_ECDSA_PARAMS : CList(str), + CKA_EC_POINT : None, + CKA_LOCAL : None, + CKA_MODIFIABLE : bool, + CKA_EXTRACTABLE : bool, + CKA_ALWAYS_SENSITIVE : bool, + CKA_NEVER_EXTRACTABLE : bool, + CKA_CCM_PRIVATE : None, + CKA_FINGERPRINT_SHA1 : NonAsciiString, + CKA_FINGERPRINT_SHA256 : NonAsciiString, + CKA_PKC_TCTRUST : None, + CKA_PKC_CITS : None, + CKA_OUID : NonAsciiString, + CKA_X9_31_GENERATED : None, + CKA_PKC_ECC : None, + CKA_EKM_UID : None, + CKA_GENERIC_1 : None, + CKA_GENERIC_2 : None, + CKA_GENERIC_3 : None} + + +role_attributes = {} + +def to_byte_array(val): + """ + Converts an arbitrarily sized integer into a byte array. + + It'll zero-pad the bit length so it's a multiple of 8, then convert + the int to binary, split the binary string into sections of 8, then + place each section into a slot in a c_ubyte array (converting to small + int). + + :param val: Big Integer to convert. + :return: c_ubyte array + """ + width = val.bit_length() + width += 8 - ((width % 8) or 8) + + fmt = "{:0%sb}" % width + str_val = fmt.format(val) + n = 8 + str_array = [str_val[i:i+n] for i in range(0, len(str_val), n)] + + return (CK_BYTE * len(str_array))(*[int(x, 2) for x in str_array]) + + + +class Attributes: + ''' + A wrapper around all of the attributes necessary to create a key. + Has a python dictionary object containing python types, the corresponding + C struct can then be generated with a simple method call. + ''' + attributes = {} + + def __init__(self, attributes_list=None): + ''' + Initializes a Attributes object, the attributes_list argument is optional + since the attributes object can be populated from the board later + + @param attributes_list: The list of python style attributes to create the class with. + ''' + + if attributes_list is not None: + #take either strings or ints as the key to the dictionary (used mainly to accomodate xmlrpc easily) + attributes_list_new = {} + for key, value in attributes_list.iteritems(): + if isinstance(key, str): + attributes_list_new[int(key)] = value + else: + break + if len(attributes_list_new) > 0: + attributes_list = attributes_list_new + + for key in attributes_list: + self._input_check(key, attributes_list[key]) + self.attributes = attributes_list + + def add_attribute(self, key, value): + ''' + Add an attribute to the dictionary in place + @param key: The type of the attribute + @param value: The value of the attribute + ''' + if isinstance(key, str): + #take either strings or ints for the key (used mainly to accomodate xmlrpc easily) + key = int(key) + + self._input_check(key, value) + self.attributes[key] = value + + def _input_check(self, key, value): + ''' + Checks to see if the type is supported (yet) + + @param key: They key of the attribute to check + @param value: The actual value of the input to check + @return: Returns true if the variable is a of a type that has been accounted for in the key_attributes dictionary + ''' + if isinstance(value, bool) or isinstance(value, int) or isinstance(value, CDict) or isinstance(value, long) or isinstance(value, str) or isinstance(value, list) or isinstance(value, CList) or isinstance(value, NonAsciiString): + return True + else: + raise Exception("Argument type not supported. ") + + def get_c_struct(self): + ''' + Assembles and returns a proper C struct from the dictionary of python attributes + + @return: Returns a Ctypes struct representing the python attributes stored in this class + ''' + c_struct = (CK_ATTRIBUTE * len(self.attributes))() + + i = 0 + for key in self.attributes: + value = self.attributes[key] + self._input_check(key, value) + + #Get the proper type for what your data is, originally I had + #this automatically detected from the python type but passing in + #int's vs longs was problematic + item_type = lookup_attributes(key) + + if item_type == bool: + byte_val = CK_BBOOL(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(byte_val), c_void_p), CK_ULONG(sizeof(byte_val))) + elif item_type == long: + long_val = CK_ULONG(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(long_val), c_void_p), CK_ULONG(sizeof(long_val))) + elif item_type == int: + ck_byte_array = to_byte_array(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), + cast(pointer(ck_byte_array), c_void_p), + CK_ULONG(sizeof(ck_byte_array))) + elif item_type == str: + string_val = create_string_buffer(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(string_val, c_void_p), CK_ULONG(len(string_val))) + elif isinstance(item_type, CDict): + date = CK_DATE() + + date.year = convert_string_to_CK_CHAR(value.dict_val['year']) + date.month = convert_string_to_CK_CHAR(value.dict_val['month']) + date.day = convert_string_to_CK_CHAR(value.dict_val['day']) + + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(date), c_void_p), CK_ULONG(sizeof(date))) + elif isinstance(item_type, CList): + if item_type.list_type == str: + list_val = create_string_buffer("", len(value)) + + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(value)): + list_val[j] = chr(value[j]) + + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(len(value))) + elif item_type.list_type == long: + list_val = (CK_ULONG * len(value))() + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(value)): + list_val[j] = CK_ULONG(value[j]) + + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(sizeof(CK_ULONG(0)) * len(value))) + elif item_type == NonAsciiString: + list_val = (CK_CHAR * len(value))() + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(value)): + list_val[j] = CK_CHAR(ord(value[j]) - 0x30) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(sizeof(CK_CHAR(0)) * len(value))) + else: + raise Exception("Argument type " + str(item_type) + " not supported. ") + i = i + 1 + + return c_struct + + def retrieve_key_attributes(self, h_session, h_object): + ''' + Gets all of the key's attributes from the board given the key's handle, + and populates the KeyAttribute object with all of those attributes. + + @param h_session: Current session + @param h_object: The handle of the object to fetch the attributes for + ''' + #Clean before starting + self.attributes = {} + + for key in key_attributes: + attribute = CK_ATTRIBUTE() + attribute.type = CK_ULONG(key) + attribute.pValue = c_void_p(0) + retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), byref(attribute), CK_ULONG(1)) + if retCode == CKR_OK: + attr_type = lookup_attributes(key) + + if isinstance(attr_type, CList): + if attr_type.list_type == str: + pb_value = (CK_BYTE * attribute.usValueLen)() + elif attr_type.list_type == long: + pb_value = (CK_ULONG * attribute.usValueLen)() + else: + pb_value = create_string_buffer(attribute.usValueLen) + + attribute.pValue = cast(pb_value, c_void_p) + retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), byref(attribute), CK_ULONG(1)) + if retCode == CKR_OK: + if attr_type == bool: + self.add_attribute(attribute.type, attr_type(cast(attribute.pValue, POINTER(c_bool)).contents.value)) + elif attr_type == str: + string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] + self.add_attribute(attribute.type, attr_type(string)) + elif attr_type == long: + self.add_attribute(attribute.type, (attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value))) + elif attr_type == int: + self.add_attribute(attribute.type, attr_type(cast(attribute.pValue, POINTER(c_int)).contents.value)) + elif isinstance(attr_type, CList): + value = [] + i = 0 + while i < attribute.usValueLen: + value.append(pb_value[i]) + i = i + 1 + + self.add_attribute(attribute.type, value) + elif attr_type == NonAsciiString: + value = '' + i = 0 + while i < attribute.usValueLen: + value += '%02x'% cast(pb_value, CK_CHAR_PTR)[i] + i = i + 1 + + self.add_attribute(attribute.type, value) + elif attr_type == None: + #raise Exception("Attribute of type " + str(attribute.type) + "'s value type not yet determined") # Add type to all_attributes + pass + + def get_attributes(self): + ''' + Returns the python dictionary of attributes + @return: The python dictionary of attributes + ''' + return self.attributes + + def __eq__(self, other): + ''' + Overriding the == sign to properly compare equality in KeyAttribute objects + @param other: Another KeyAttribute to compare against + @return: True if the attributes are equal + ''' + other_attribs = other.get_attributes() + self_attribs = self.get_attributes() + for key in self.attributes: + if key in self_attribs and key in other_attribs: #TODO we are only checking if the key exists in both, maybe this is a bad idea + if self_attribs[key] != other_attribs[key]: + return False + return True + + def debug_print(self): + ''' + Simple method to print out all the keys and values in a KeyAttribute object + ''' + for key in self.attributes: + print "key: " + str(key) + ", value: " + str(self.attributes[key]) + +def get_attribute_py_value(attribute): + ''' + Gets the python version of the value of a attribute from the + C format + + @param attribute: The ctypes style variable representing the value of an attribute + @return: Returns the python version of the ctypes style variable + ''' + key = attribute.type + attr_type = lookup_attributes(key) + if attr_type == bool: + return attr_type(cast(attribute.pValue, POINTER(c_bool)).contents.value) + elif attr_type == str: + string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] + return attr_type(string) + elif attr_type == long: + return attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value) + elif attr_type == int: + return attr_type(cast(attribute.pValue, POINTER(c_int)).contents.value) + elif isinstance(attr_type, CDict): + py_date = {} + + c_date = cast(attribute.pValue, POINTER(CK_DATE)) + + py_date['year'] = convert_CK_CHAR_to_string(cast(c_date.year, CK_CHAR_PTR)) + py_date['month'] = convert_CK_CHAR_to_string(cast(c_date.month, CK_CHAR_PTR)) + py_date['day'] = convert_CK_CHAR_to_string(cast(c_date.day, CK_CHAR_PTR)) + return py_date + + + elif isinstance(attr_type, CList): + if attr_type.list_type == str: + value = [] + try: + for i in range(0, attribute.usValueLen): + value.append(attribute.pValue[i]) + return value + except OverflowError: + return value + + elif attr_type.list_type == long: + value = [] + for i in range(0, attribute.usValueLen / sizeof(CK_ULONG(0))): + value.append(cast(attribute.pValue, CK_ULONG_PTR)[i]) + return value + elif attr_type == NonAsciiString: + value = '' + for i in range(0, attribute.usValueLen / sizeof(CK_CHAR(0))): + value += '%02x'% cast(attribute.pValue, CK_CHAR_PTR)[i] + return value + elif attr_type == None: + #raise Exception("Attribute of type " + str(attribute.type) + "'s value type not yet determined") # Add type to all_attributes + pass + + +def c_struct_to_python(c_struct): + ''' + Converts a struct in C to a dictionary in python. + + @param c_struct: The c struct to convert into a dictionary in python + @return: Returns a python dictionary which represents the C struct passed in + ''' + py_struct = {} + for i in range(0, len(c_struct)): + obj_type = c_struct[i].type + + value = get_attribute_py_value(c_struct[i]) + + py_struct[obj_type] = value + + return py_struct + +def lookup_attributes(key): + ''' + Utility function to look through the lists of attributes and figure out + the type of variable for a given attribute represented by a key + + @param key: The key representing the attribute + @return: The python type that can represent the attribute + ''' + + ret_val = None + if key in key_attributes: + ret_val = key_attributes[key] + elif key in role_attributes: + ret_val = role_attributes[key] + + return ret_val + +def convert_string_to_CK_CHAR(string): + byte_array = (c_ubyte * len (string))() + i = 0 + for char in string: + byte_array[i] = ord(char) + i = i +1 + + return byte_array + +def convert_CK_CHAR_to_string(byte_array): + string = "" + + for b in byte_array: + string = string + chr(b) + return string + +def convert_ck_char_array_to_string(ck_char_array): + string = "" + + for b in ck_char_array: + string = string + b + return string + +def convert_CK_BYTE_array_to_string(byte_array): + string = "" + + for b in byte_array: + string = string + "%02x"%(b) + return string + diff --git a/pycryptoki/audit_handling.py b/pycryptoki/audit_handling.py new file mode 100755 index 0000000..9bb956d --- /dev/null +++ b/pycryptoki/audit_handling.py @@ -0,0 +1,35 @@ +""" +Methods responsible for managing a user's session and login/c_logout +""" +from cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR +from ctypes import cast, c_ulong, byref +from pycryptoki.test_functions import LunaException, check_luna_exception, \ + make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def ca_init_audit(slot, audit_pin, audit_label): + if audit_pin == '': + ret = CA_InitAudit(CK_SLOT_ID(slot), None, CK_ULONG(0), cast(audit_label, CK_CHAR_PTR)) + else: + ret = CA_InitAudit(CK_SLOT_ID(slot), cast(audit_pin, CK_CHAR_PTR), CK_ULONG(len(audit_pin)), cast(audit_label, CK_CHAR_PTR)) + return ret +ca_init_audit_ex = make_error_handle_function(ca_init_audit) + +def ca_time_sync(h_session, ultime): + + ret = CA_TimeSync(h_session, CK_ULONG(ultime)) + return ret +ca_time_sync_ex = make_error_handle_function(ca_time_sync) + +def ca_get_time(h_session): + + hsm_time = c_ulong() + + ret = CA_GetTime(h_session, byref(hsm_time)) + return ret, hsm_time +ca_get_time_ex = make_error_handle_function(ca_get_time) + + + diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py new file mode 100755 index 0000000..2feb0c2 --- /dev/null +++ b/pycryptoki/backup.py @@ -0,0 +1,57 @@ +from ctypes import byref +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CA_OpenSecureToken, CK_ULONG_PTR, \ + CA_CloseSecureToken, CA_Extract, CA_Insert, CK_MECHANISM, CK_ULONG +from pycryptoki.mechanism import get_c_struct_from_mechanism, \ + get_python_dict_from_c_mechanism +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +''' +CK_SESSION_HANDLE hSession, + CK_ULONG storagePath, + CK_ULONG devID, + CK_ULONG mode, + CK_ULONG_PTR numberOfElems, + CK_ULONG_PTR phID +''' +def ca_open_secure_token(h_session, storage_path, dev_ID, mode): + number_of_elems = CK_ULONG(0) + ph_ID = CK_ULONG(0) + ret = CA_OpenSecureToken(h_session, storage_path, dev_ID, mode, byref(number_of_elems), byref(ph_ID)) + + return ret, number_of_elems.value, ph_ID.value +ca_open_secure_token_ex = make_error_handle_function(ca_open_secure_token) + +''' +CK_SESSION_HANDLE hSession, CK_ULONG hID +''' +def ca_close_secure_token(h_session, h_ID): + + ret = CA_CloseSecureToken(h_session, h_ID) + return ret +ca_close_secure_token_ex = make_error_handle_function(ca_close_secure_token) + + +def ca_extract(h_session, py_mechanism_dict, params_type_string): + + c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) + + ret = CA_Extract(h_session, c_mechanism) + + py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) + return ret, py_dictionary +ca_extract_ex = make_error_handle_function(ca_extract) + +# CA_Insert( CK_SESSION_HANDLE hSession, +# CK_MECHANISM_PTR pMechanism ) + +def ca_insert(h_session, py_mechanism_dict, params_type_string): + + c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) + ret = CA_Insert(h_session, c_mechanism) + py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) + return ret, py_dictionary +ca_insert_ex = make_error_handle_function(ca_insert) diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py new file mode 100755 index 0000000..2a9740b --- /dev/null +++ b/pycryptoki/cryptoki.py @@ -0,0 +1,2265 @@ +''' +THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE +This file should NOT be checked into MKS or modified in any way, this file was +created by setup/initialize.py. Any changes to this file will be wiped out when +it is regenerated. + +This file contains all of the ctypes definitions for the cryptoki library. +The ctypes definitions outline the structures for the cryptoki C API. +''' + + +from pycryptoki.cryptoki_helpers import make_late_binding_function +from ctypes import * + +class CK_FUNCTION_LIST(Structure): + pass +class CK_VERSION(Structure): + pass +CK_BYTE = c_ubyte +CK_VERSION._fields_ = [ + ('major', CK_BYTE), + ('minor', CK_BYTE), +] +CK_ULONG = c_ulong +CK_RV = CK_ULONG +CK_VOID_PTR = c_void_p +CK_C_Initialize = CFUNCTYPE(CK_RV, CK_VOID_PTR) +CK_C_Finalize = CFUNCTYPE(CK_RV, CK_VOID_PTR) +class CK_INFO(Structure): + pass +CK_INFO_PTR = POINTER(CK_INFO) +CK_C_GetInfo = CFUNCTYPE(CK_RV, CK_INFO_PTR) +CK_FUNCTION_LIST_PTR = POINTER(CK_FUNCTION_LIST) +CK_FUNCTION_LIST_PTR_PTR = POINTER(CK_FUNCTION_LIST_PTR) +CK_C_GetFunctionList = CFUNCTYPE(CK_RV, CK_FUNCTION_LIST_PTR_PTR) +CK_BBOOL = CK_BYTE +CK_SLOT_ID = CK_ULONG +CK_SLOT_ID_PTR = POINTER(CK_SLOT_ID) +CK_ULONG_PTR = POINTER(CK_ULONG) +CK_C_GetSlotList = CFUNCTYPE(CK_RV, CK_BBOOL, CK_SLOT_ID_PTR, CK_ULONG_PTR) +class CK_SLOT_INFO(Structure): + pass +CK_SLOT_INFO_PTR = POINTER(CK_SLOT_INFO) +CK_C_GetSlotInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_INFO_PTR) +class CK_TOKEN_INFO(Structure): + pass +CK_TOKEN_INFO_PTR = POINTER(CK_TOKEN_INFO) +CK_C_GetTokenInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_TOKEN_INFO_PTR) +CK_MECHANISM_TYPE = CK_ULONG +CK_MECHANISM_TYPE_PTR = POINTER(CK_MECHANISM_TYPE) +CK_C_GetMechanismList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE_PTR, CK_ULONG_PTR) +class CK_MECHANISM_INFO(Structure): + pass +CK_MECHANISM_INFO_PTR = POINTER(CK_MECHANISM_INFO) +CK_C_GetMechanismInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE, CK_MECHANISM_INFO_PTR) +CK_UTF8CHAR = CK_BYTE +CK_UTF8CHAR_PTR = POINTER(CK_UTF8CHAR) +CK_C_InitToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR) +CK_SESSION_HANDLE = CK_ULONG +CK_C_InitPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG) +CK_C_SetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, CK_ULONG) +CK_FLAGS = CK_ULONG +CK_NOTIFICATION = CK_ULONG +CK_NOTIFY = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) +CK_SESSION_HANDLE_PTR = POINTER(CK_SESSION_HANDLE) +CK_C_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) +CK_C_CloseSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_CloseAllSessions = CFUNCTYPE(CK_RV, CK_SLOT_ID) +class CK_SESSION_INFO(Structure): + pass +CK_SESSION_INFO_PTR = POINTER(CK_SESSION_INFO) +CK_C_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_INFO_PTR) +CK_BYTE_PTR = POINTER(CK_BYTE) +CK_C_GetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_OBJECT_HANDLE = CK_ULONG +CK_C_SetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE) +CK_USER_TYPE = CK_ULONG +CK_C_Login = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG) +CK_C_Logout = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +class CK_ATTRIBUTE(Structure): + pass +CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) +CK_OBJECT_HANDLE_PTR = POINTER(CK_OBJECT_HANDLE) +CK_C_CreateObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_CopyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_DestroyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_C_GetObjectSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR) +CK_C_GetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_C_SetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_C_FindObjectsInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_C_FindObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG_PTR) +CK_C_FindObjectsFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +class CK_MECHANISM(Structure): + pass +CK_MECHANISM_PTR = POINTER(CK_MECHANISM) +CK_C_EncryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Encrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_EncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_EncryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Decrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DigestInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) +CK_C_Digest = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_DigestKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_C_DigestFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Sign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_SignFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_SignRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_VerifyInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Verify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_C_VerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_VerifyFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_VerifyRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_VerifyRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DigestEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptDigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptVerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_GenerateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_GenerateKeyPair = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_C_WrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_UnwrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_DeriveKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_SeedRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_GenerateRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_GetFunctionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_CancelFunction = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, CK_SLOT_ID_PTR, CK_VOID_PTR) +CK_FUNCTION_LIST._fields_ = [ + ('version', CK_VERSION), + ('C_Initialize', CK_C_Initialize), + ('C_Finalize', CK_C_Finalize), + ('C_GetInfo', CK_C_GetInfo), + ('C_GetFunctionList', CK_C_GetFunctionList), + ('C_GetSlotList', CK_C_GetSlotList), + ('C_GetSlotInfo', CK_C_GetSlotInfo), + ('C_GetTokenInfo', CK_C_GetTokenInfo), + ('C_GetMechanismList', CK_C_GetMechanismList), + ('C_GetMechanismInfo', CK_C_GetMechanismInfo), + ('C_InitToken', CK_C_InitToken), + ('C_InitPIN', CK_C_InitPIN), + ('C_SetPIN', CK_C_SetPIN), + ('C_OpenSession', CK_C_OpenSession), + ('C_CloseSession', CK_C_CloseSession), + ('C_CloseAllSessions', CK_C_CloseAllSessions), + ('C_GetSessionInfo', CK_C_GetSessionInfo), + ('C_GetOperationState', CK_C_GetOperationState), + ('C_SetOperationState', CK_C_SetOperationState), + ('C_Login', CK_C_Login), + ('C_Logout', CK_C_Logout), + ('C_CreateObject', CK_C_CreateObject), + ('C_CopyObject', CK_C_CopyObject), + ('C_DestroyObject', CK_C_DestroyObject), + ('C_GetObjectSize', CK_C_GetObjectSize), + ('C_GetAttributeValue', CK_C_GetAttributeValue), + ('C_SetAttributeValue', CK_C_SetAttributeValue), + ('C_FindObjectsInit', CK_C_FindObjectsInit), + ('C_FindObjects', CK_C_FindObjects), + ('C_FindObjectsFinal', CK_C_FindObjectsFinal), + ('C_EncryptInit', CK_C_EncryptInit), + ('C_Encrypt', CK_C_Encrypt), + ('C_EncryptUpdate', CK_C_EncryptUpdate), + ('C_EncryptFinal', CK_C_EncryptFinal), + ('C_DecryptInit', CK_C_DecryptInit), + ('C_Decrypt', CK_C_Decrypt), + ('C_DecryptUpdate', CK_C_DecryptUpdate), + ('C_DecryptFinal', CK_C_DecryptFinal), + ('C_DigestInit', CK_C_DigestInit), + ('C_Digest', CK_C_Digest), + ('C_DigestUpdate', CK_C_DigestUpdate), + ('C_DigestKey', CK_C_DigestKey), + ('C_DigestFinal', CK_C_DigestFinal), + ('C_SignInit', CK_C_SignInit), + ('C_Sign', CK_C_Sign), + ('C_SignUpdate', CK_C_SignUpdate), + ('C_SignFinal', CK_C_SignFinal), + ('C_SignRecoverInit', CK_C_SignRecoverInit), + ('C_SignRecover', CK_C_SignRecover), + ('C_VerifyInit', CK_C_VerifyInit), + ('C_Verify', CK_C_Verify), + ('C_VerifyUpdate', CK_C_VerifyUpdate), + ('C_VerifyFinal', CK_C_VerifyFinal), + ('C_VerifyRecoverInit', CK_C_VerifyRecoverInit), + ('C_VerifyRecover', CK_C_VerifyRecover), + ('C_DigestEncryptUpdate', CK_C_DigestEncryptUpdate), + ('C_DecryptDigestUpdate', CK_C_DecryptDigestUpdate), + ('C_SignEncryptUpdate', CK_C_SignEncryptUpdate), + ('C_DecryptVerifyUpdate', CK_C_DecryptVerifyUpdate), + ('C_GenerateKey', CK_C_GenerateKey), + ('C_GenerateKeyPair', CK_C_GenerateKeyPair), + ('C_WrapKey', CK_C_WrapKey), + ('C_UnwrapKey', CK_C_UnwrapKey), + ('C_DeriveKey', CK_C_DeriveKey), + ('C_SeedRandom', CK_C_SeedRandom), + ('C_GenerateRandom', CK_C_GenerateRandom), + ('C_GetFunctionStatus', CK_C_GetFunctionStatus), + ('C_CancelFunction', CK_C_CancelFunction), + ('C_WaitForSlotEvent', CK_C_WaitForSlotEvent), +] +C_Initialize = make_late_binding_function('C_Initialize') +C_Initialize.restype = CK_RV +C_Initialize.argtypes = [CK_VOID_PTR] +C_Finalize = make_late_binding_function('C_Finalize') +C_Finalize.restype = CK_RV +C_Finalize.argtypes = [CK_VOID_PTR] +C_GetInfo = make_late_binding_function('C_GetInfo') +C_GetInfo.restype = CK_RV +C_GetInfo.argtypes = [CK_INFO_PTR] +C_GetFunctionList = make_late_binding_function('C_GetFunctionList') +C_GetFunctionList.restype = CK_RV +C_GetFunctionList.argtypes = [CK_FUNCTION_LIST_PTR_PTR] +C_GetSlotList = make_late_binding_function('C_GetSlotList') +C_GetSlotList.restype = CK_RV +C_GetSlotList.argtypes = [CK_BBOOL, CK_SLOT_ID_PTR, CK_ULONG_PTR] +C_GetSlotInfo = make_late_binding_function('C_GetSlotInfo') +C_GetSlotInfo.restype = CK_RV +C_GetSlotInfo.argtypes = [CK_SLOT_ID, CK_SLOT_INFO_PTR] +C_GetTokenInfo = make_late_binding_function('C_GetTokenInfo') +C_GetTokenInfo.restype = CK_RV +C_GetTokenInfo.argtypes = [CK_SLOT_ID, CK_TOKEN_INFO_PTR] +C_GetMechanismList = make_late_binding_function('C_GetMechanismList') +C_GetMechanismList.restype = CK_RV +C_GetMechanismList.argtypes = [CK_SLOT_ID, CK_MECHANISM_TYPE_PTR, CK_ULONG_PTR] +C_GetMechanismInfo = make_late_binding_function('C_GetMechanismInfo') +C_GetMechanismInfo.restype = CK_RV +C_GetMechanismInfo.argtypes = [CK_SLOT_ID, CK_MECHANISM_TYPE, CK_MECHANISM_INFO_PTR] +C_InitToken = make_late_binding_function('C_InitToken') +C_InitToken.restype = CK_RV +C_InitToken.argtypes = [CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR] +C_InitPIN = make_late_binding_function('C_InitPIN') +C_InitPIN.restype = CK_RV +C_InitPIN.argtypes = [CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG] +C_SetPIN = make_late_binding_function('C_SetPIN') +C_SetPIN.restype = CK_RV +C_SetPIN.argtypes = [CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, CK_ULONG] +C_OpenSession = make_late_binding_function('C_OpenSession') +C_OpenSession.restype = CK_RV +C_OpenSession.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] +C_CloseSession = make_late_binding_function('C_CloseSession') +C_CloseSession.restype = CK_RV +C_CloseSession.argtypes = [CK_SESSION_HANDLE] +C_CloseAllSessions = make_late_binding_function('C_CloseAllSessions') +C_CloseAllSessions.restype = CK_RV +C_CloseAllSessions.argtypes = [CK_SLOT_ID] +C_GetSessionInfo = make_late_binding_function('C_GetSessionInfo') +C_GetSessionInfo.restype = CK_RV +C_GetSessionInfo.argtypes = [CK_SESSION_HANDLE, CK_SESSION_INFO_PTR] +C_GetOperationState = make_late_binding_function('C_GetOperationState') +C_GetOperationState.restype = CK_RV +C_GetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_SetOperationState = make_late_binding_function('C_SetOperationState') +C_SetOperationState.restype = CK_RV +C_SetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE] +C_Login = make_late_binding_function('C_Login') +C_Login.restype = CK_RV +C_Login.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG] +C_Logout = make_late_binding_function('C_Logout') +C_Logout.restype = CK_RV +C_Logout.argtypes = [CK_SESSION_HANDLE] +C_CreateObject = make_late_binding_function('C_CreateObject') +C_CreateObject.restype = CK_RV +C_CreateObject.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_CopyObject = make_late_binding_function('C_CopyObject') +C_CopyObject.restype = CK_RV +C_CopyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_DestroyObject = make_late_binding_function('C_DestroyObject') +C_DestroyObject.restype = CK_RV +C_DestroyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] +C_GetObjectSize = make_late_binding_function('C_GetObjectSize') +C_GetObjectSize.restype = CK_RV +C_GetObjectSize.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR] +C_GetAttributeValue = make_late_binding_function('C_GetAttributeValue') +C_GetAttributeValue.restype = CK_RV +C_GetAttributeValue.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] +C_SetAttributeValue = make_late_binding_function('C_SetAttributeValue') +C_SetAttributeValue.restype = CK_RV +C_SetAttributeValue.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] +C_FindObjectsInit = make_late_binding_function('C_FindObjectsInit') +C_FindObjectsInit.restype = CK_RV +C_FindObjectsInit.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] +C_FindObjects = make_late_binding_function('C_FindObjects') +C_FindObjects.restype = CK_RV +C_FindObjects.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG_PTR] +C_FindObjectsFinal = make_late_binding_function('C_FindObjectsFinal') +C_FindObjectsFinal.restype = CK_RV +C_FindObjectsFinal.argtypes = [CK_SESSION_HANDLE] +C_EncryptInit = make_late_binding_function('C_EncryptInit') +C_EncryptInit.restype = CK_RV +C_EncryptInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Encrypt = make_late_binding_function('C_Encrypt') +C_Encrypt.restype = CK_RV +C_Encrypt.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_EncryptUpdate = make_late_binding_function('C_EncryptUpdate') +C_EncryptUpdate.restype = CK_RV +C_EncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_EncryptFinal = make_late_binding_function('C_EncryptFinal') +C_EncryptFinal.restype = CK_RV +C_EncryptFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptInit = make_late_binding_function('C_DecryptInit') +C_DecryptInit.restype = CK_RV +C_DecryptInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Decrypt = make_late_binding_function('C_Decrypt') +C_Decrypt.restype = CK_RV +C_Decrypt.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptUpdate = make_late_binding_function('C_DecryptUpdate') +C_DecryptUpdate.restype = CK_RV +C_DecryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptFinal = make_late_binding_function('C_DecryptFinal') +C_DecryptFinal.restype = CK_RV +C_DecryptFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_DigestInit = make_late_binding_function('C_DigestInit') +C_DigestInit.restype = CK_RV +C_DigestInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] +C_Digest = make_late_binding_function('C_Digest') +C_Digest.restype = CK_RV +C_Digest.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DigestUpdate = make_late_binding_function('C_DigestUpdate') +C_DigestUpdate.restype = CK_RV +C_DigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_DigestKey = make_late_binding_function('C_DigestKey') +C_DigestKey.restype = CK_RV +C_DigestKey.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] +C_DigestFinal = make_late_binding_function('C_DigestFinal') +C_DigestFinal.restype = CK_RV +C_DigestFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignInit = make_late_binding_function('C_SignInit') +C_SignInit.restype = CK_RV +C_SignInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Sign = make_late_binding_function('C_Sign') +C_Sign.restype = CK_RV +C_Sign.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignUpdate = make_late_binding_function('C_SignUpdate') +C_SignUpdate.restype = CK_RV +C_SignUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_SignFinal = make_late_binding_function('C_SignFinal') +C_SignFinal.restype = CK_RV +C_SignFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignRecoverInit = make_late_binding_function('C_SignRecoverInit') +C_SignRecoverInit.restype = CK_RV +C_SignRecoverInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_SignRecover = make_late_binding_function('C_SignRecover') +C_SignRecover.restype = CK_RV +C_SignRecover.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_VerifyInit = make_late_binding_function('C_VerifyInit') +C_VerifyInit.restype = CK_RV +C_VerifyInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Verify = make_late_binding_function('C_Verify') +C_Verify.restype = CK_RV +C_Verify.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +C_VerifyUpdate = make_late_binding_function('C_VerifyUpdate') +C_VerifyUpdate.restype = CK_RV +C_VerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_VerifyFinal = make_late_binding_function('C_VerifyFinal') +C_VerifyFinal.restype = CK_RV +C_VerifyFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_VerifyRecoverInit = make_late_binding_function('C_VerifyRecoverInit') +C_VerifyRecoverInit.restype = CK_RV +C_VerifyRecoverInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_VerifyRecover = make_late_binding_function('C_VerifyRecover') +C_VerifyRecover.restype = CK_RV +C_VerifyRecover.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DigestEncryptUpdate = make_late_binding_function('C_DigestEncryptUpdate') +C_DigestEncryptUpdate.restype = CK_RV +C_DigestEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptDigestUpdate = make_late_binding_function('C_DecryptDigestUpdate') +C_DecryptDigestUpdate.restype = CK_RV +C_DecryptDigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignEncryptUpdate = make_late_binding_function('C_SignEncryptUpdate') +C_SignEncryptUpdate.restype = CK_RV +C_SignEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptVerifyUpdate = make_late_binding_function('C_DecryptVerifyUpdate') +C_DecryptVerifyUpdate.restype = CK_RV +C_DecryptVerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_GenerateKey = make_late_binding_function('C_GenerateKey') +C_GenerateKey.restype = CK_RV +C_GenerateKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_GenerateKeyPair = make_late_binding_function('C_GenerateKeyPair') +C_GenerateKeyPair.restype = CK_RV +C_GenerateKeyPair.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +C_WrapKey = make_late_binding_function('C_WrapKey') +C_WrapKey.restype = CK_RV +C_WrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_UnwrapKey = make_late_binding_function('C_UnwrapKey') +C_UnwrapKey.restype = CK_RV +C_UnwrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_DeriveKey = make_late_binding_function('C_DeriveKey') +C_DeriveKey.restype = CK_RV +C_DeriveKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_SeedRandom = make_late_binding_function('C_SeedRandom') +C_SeedRandom.restype = CK_RV +C_SeedRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_GenerateRandom = make_late_binding_function('C_GenerateRandom') +C_GenerateRandom.restype = CK_RV +C_GenerateRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_GetFunctionStatus = make_late_binding_function('C_GetFunctionStatus') +C_GetFunctionStatus.restype = CK_RV +C_GetFunctionStatus.argtypes = [CK_SESSION_HANDLE] +C_CancelFunction = make_late_binding_function('C_CancelFunction') +C_CancelFunction.restype = CK_RV +C_CancelFunction.argtypes = [CK_SESSION_HANDLE] +C_WaitForSlotEvent = make_late_binding_function('C_WaitForSlotEvent') +C_WaitForSlotEvent.restype = CK_RV +C_WaitForSlotEvent.argtypes = [CK_FLAGS, CK_SLOT_ID_PTR, CK_VOID_PTR] +CK_CHAR = CK_BYTE +CK_LONG = c_long +CK_CHAR_PTR = POINTER(CK_CHAR) +CK_VOID_PTR_PTR = POINTER(CK_VOID_PTR) +CK_VERSION_PTR = POINTER(CK_VERSION) +CK_INFO._fields_ = [ + ('cryptokiVersion', CK_VERSION), + ('manufacturerID', CK_UTF8CHAR * 32), + ('flags', CK_FLAGS), + ('libraryDescription', CK_UTF8CHAR * 32), + ('libraryVersion', CK_VERSION), +] +CK_SLOT_INFO._fields_ = [ + ('slotDescription', CK_UTF8CHAR * 64), + ('manufacturerID', CK_UTF8CHAR * 32), + ('flags', CK_FLAGS), + ('hardwareVersion', CK_VERSION), + ('firmwareVersion', CK_VERSION), +] +CK_TOKEN_INFO._fields_ = [ + ('label', CK_UTF8CHAR * 32), + ('manufacturerID', CK_UTF8CHAR * 32), + ('model', CK_UTF8CHAR * 16), + ('serialNumber', CK_CHAR * 16), + ('flags', CK_FLAGS), + ('usMaxSessionCount', CK_ULONG), + ('usSessionCount', CK_ULONG), + ('usMaxRwSessionCount', CK_ULONG), + ('usRwSessionCount', CK_ULONG), + ('usMaxPinLen', CK_ULONG), + ('usMinPinLen', 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_STATE = CK_ULONG +CK_SESSION_INFO._fields_ = [ + ('slotID', CK_SLOT_ID), + ('state', CK_STATE), + ('flags', CK_FLAGS), + ('usDeviceError', CK_ULONG), +] +CK_OBJECT_CLASS = CK_ULONG +CK_OBJECT_CLASS_PTR = POINTER(CK_OBJECT_CLASS) +CK_HW_FEATURE_TYPE = CK_ULONG +CK_KEY_TYPE = CK_ULONG +CK_CERTIFICATE_TYPE = CK_ULONG +CK_ATTRIBUTE_TYPE = CK_ULONG +CK_ATTRIBUTE._fields_ = [ + ('type', CK_ATTRIBUTE_TYPE), + ('pValue', CK_VOID_PTR), + ('usValueLen', CK_ULONG), +] +class CK_DATE(Structure): + pass +CK_DATE._fields_ = [ + ('year', CK_CHAR * 4), + ('month', CK_CHAR * 2), + ('day', CK_CHAR * 2), +] +CK_MECHANISM._fields_ = [ + ('mechanism', CK_MECHANISM_TYPE), + ('pParameter', CK_VOID_PTR), + ('usParameterLen', CK_ULONG), +] +CK_MECHANISM_INFO._fields_ = [ + ('ulMinKeySize', CK_ULONG), + ('ulMaxKeySize', CK_ULONG), + ('flags', CK_FLAGS), +] +CK_CREATEMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR_PTR) +CK_DESTROYMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) +CK_LOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) +CK_UNLOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) +class CK_C_INITIALIZE_ARGS(Structure): + pass +CK_C_INITIALIZE_ARGS._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) +CK_RSA_PKCS_MGF_TYPE = CK_ULONG +CK_RSA_PKCS_MGF_TYPE_PTR = POINTER(CK_RSA_PKCS_MGF_TYPE) +CK_RSA_PKCS_OAEP_SOURCE_TYPE = CK_ULONG +CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR = POINTER(CK_RSA_PKCS_OAEP_SOURCE_TYPE) +class CK_RSA_PKCS_OAEP_PARAMS(Structure): + pass +CK_RSA_PKCS_OAEP_PARAMS._fields_ = [ + ('hashAlg', CK_MECHANISM_TYPE), + ('mgf', CK_RSA_PKCS_MGF_TYPE), + ('source', CK_RSA_PKCS_OAEP_SOURCE_TYPE), + ('pSourceData', CK_VOID_PTR), + ('ulSourceDataLen', CK_ULONG), +] +CK_RSA_PKCS_OAEP_PARAMS_PTR = POINTER(CK_RSA_PKCS_OAEP_PARAMS) +class CK_RSA_PKCS_PSS_PARAMS(Structure): + pass +CK_RSA_PKCS_PSS_PARAMS._fields_ = [ + ('hashAlg', CK_MECHANISM_TYPE), + ('mgf', CK_RSA_PKCS_MGF_TYPE), + ('usSaltLen', CK_ULONG), +] +CK_RSA_PKCS_PSS_PARAMS_PTR = POINTER(CK_RSA_PKCS_PSS_PARAMS) +CK_EC_KDF_TYPE = CK_ULONG +class CK_ECDH1_DERIVE_PARAMS(Structure): + pass +CK_ECDH1_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), +] +CK_ECDH1_DERIVE_PARAMS_PTR = POINTER(CK_ECDH1_DERIVE_PARAMS) +class CK_ECDH2_DERIVE_PARAMS(Structure): + pass +CK_ECDH2_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), +] +CK_ECDH2_DERIVE_PARAMS_PTR = POINTER(CK_ECDH2_DERIVE_PARAMS) +class CK_ECMQV_DERIVE_PARAMS(Structure): + pass +CK_ECMQV_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), + ('publicKey', CK_OBJECT_HANDLE), +] +CK_ECMQV_DERIVE_PARAMS_PTR = POINTER(CK_ECMQV_DERIVE_PARAMS) +CK_X9_42_DH_KDF_TYPE = CK_ULONG +CK_X9_42_DH_KDF_TYPE_PTR = POINTER(CK_X9_42_DH_KDF_TYPE) +class CK_X9_42_DH1_DERIVE_PARAMS(Structure): + pass +CK_X9_42_DH1_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_X9_42_DH_KDF_TYPE), + ('ulOtherInfoLen', CK_ULONG), + ('pOtherInfo', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), +] +CK_X9_42_DH1_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH1_DERIVE_PARAMS) +class CK_X9_42_DH2_DERIVE_PARAMS(Structure): + pass +CK_X9_42_DH2_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_X9_42_DH_KDF_TYPE), + ('ulOtherInfoLen', CK_ULONG), + ('pOtherInfo', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), +] +CK_X9_42_DH2_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH2_DERIVE_PARAMS) +class CK_X9_42_MQV_DERIVE_PARAMS(Structure): + pass +CK_X9_42_MQV_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_X9_42_DH_KDF_TYPE), + ('ulOtherInfoLen', CK_ULONG), + ('pOtherInfo', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), + ('publicKey', CK_OBJECT_HANDLE), +] +CK_X9_42_MQV_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_MQV_DERIVE_PARAMS) +class CK_KEA_DERIVE_PARAMS(Structure): + pass +CK_KEA_DERIVE_PARAMS._fields_ = [ + ('isSender', CK_BBOOL), + ('ulRandomLen', CK_ULONG), + ('pRandomA', CK_BYTE_PTR), + ('pRandomB', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), +] +CK_KEA_DERIVE_PARAMS_PTR = POINTER(CK_KEA_DERIVE_PARAMS) +CK_RC2_PARAMS = CK_ULONG +CK_RC2_PARAMS_PTR = POINTER(CK_RC2_PARAMS) +class CK_RC2_CBC_PARAMS(Structure): + pass +CK_RC2_CBC_PARAMS._fields_ = [ + ('usEffectiveBits', CK_ULONG), + ('iv', CK_BYTE * 8), +] +CK_RC2_CBC_PARAMS_PTR = POINTER(CK_RC2_CBC_PARAMS) +class CK_RC2_MAC_GENERAL_PARAMS(Structure): + pass +CK_RC2_MAC_GENERAL_PARAMS._fields_ = [ + ('usEffectiveBits', CK_ULONG), + ('ulMacLength', CK_ULONG), +] +CK_RC2_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC2_MAC_GENERAL_PARAMS) +class CK_RC5_PARAMS(Structure): + pass +CK_RC5_PARAMS._fields_ = [ + ('ulWordsize', CK_ULONG), + ('ulRounds', CK_ULONG), +] +CK_RC5_PARAMS_PTR = POINTER(CK_RC5_PARAMS) +class CK_RC5_CBC_PARAMS(Structure): + pass +CK_RC5_CBC_PARAMS._fields_ = [ + ('ulWordsize', CK_ULONG), + ('ulRounds', CK_ULONG), + ('pIv', CK_BYTE_PTR), + ('ulIvLen', CK_ULONG), +] +CK_RC5_CBC_PARAMS_PTR = POINTER(CK_RC5_CBC_PARAMS) +class CK_RC5_MAC_GENERAL_PARAMS(Structure): + pass +CK_RC5_MAC_GENERAL_PARAMS._fields_ = [ + ('ulWordsize', CK_ULONG), + ('ulRounds', CK_ULONG), + ('ulMacLength', CK_ULONG), +] +CK_RC5_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC5_MAC_GENERAL_PARAMS) +CK_MAC_GENERAL_PARAMS = CK_ULONG +CK_MAC_GENERAL_PARAMS_PTR = POINTER(CK_MAC_GENERAL_PARAMS) +class CK_DES_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +CK_DES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 8), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_DES_CBC_ENCRYPT_DATA_PARAMS) +class CK_AES_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +CK_AES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 16), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_AES_CBC_ENCRYPT_DATA_PARAMS) +class CK_SKIPJACK_PRIVATE_WRAP_PARAMS(Structure): + pass +CK_SKIPJACK_PRIVATE_WRAP_PARAMS._fields_ = [ + ('usPasswordLen', CK_ULONG), + ('pPassword', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPAndGLen', CK_ULONG), + ('ulQLen', CK_ULONG), + ('ulRandomLen', CK_ULONG), + ('pRandomA', CK_BYTE_PTR), + ('pPrimeP', CK_BYTE_PTR), + ('pBaseG', CK_BYTE_PTR), + ('pSubprimeQ', CK_BYTE_PTR), +] +CK_SKIPJACK_PRIVATE_WRAP_PTR = POINTER(CK_SKIPJACK_PRIVATE_WRAP_PARAMS) +class CK_SKIPJACK_RELAYX_PARAMS(Structure): + pass +CK_SKIPJACK_RELAYX_PARAMS._fields_ = [ + ('ulOldWrappedXLen', CK_ULONG), + ('pOldWrappedX', CK_BYTE_PTR), + ('ulOldPasswordLen', CK_ULONG), + ('pOldPassword', CK_BYTE_PTR), + ('ulOldPublicDataLen', CK_ULONG), + ('pOldPublicData', CK_BYTE_PTR), + ('ulOldRandomLen', CK_ULONG), + ('pOldRandomA', CK_BYTE_PTR), + ('ulNewPasswordLen', CK_ULONG), + ('pNewPassword', CK_BYTE_PTR), + ('ulNewPublicDataLen', CK_ULONG), + ('pNewPublicData', CK_BYTE_PTR), + ('ulNewRandomLen', CK_ULONG), + ('pNewRandomA', CK_BYTE_PTR), +] +CK_SKIPJACK_RELAYX_PARAMS_PTR = POINTER(CK_SKIPJACK_RELAYX_PARAMS) +class CK_PBE_PARAMS(Structure): + pass +CK_PBE_PARAMS._fields_ = [ + ('pInitVector', CK_BYTE_PTR), + ('pPassword', CK_UTF8CHAR_PTR), + ('usPasswordLen', CK_ULONG), + ('pSalt', CK_BYTE_PTR), + ('usSaltLen', CK_ULONG), + ('usIteration', CK_ULONG), +] +CK_PBE_PARAMS_PTR = POINTER(CK_PBE_PARAMS) +class CK_KEY_WRAP_SET_OAEP_PARAMS(Structure): + pass +CK_KEY_WRAP_SET_OAEP_PARAMS._fields_ = [ + ('bBC', CK_BYTE), + ('pX', CK_BYTE_PTR), + ('ulXLen', CK_ULONG), +] +CK_KEY_WRAP_SET_OAEP_PARAMS_PTR = POINTER(CK_KEY_WRAP_SET_OAEP_PARAMS) +class CK_SSL3_RANDOM_DATA(Structure): + pass +CK_SSL3_RANDOM_DATA._fields_ = [ + ('pClientRandom', CK_BYTE_PTR), + ('ulClientRandomLen', CK_ULONG), + ('pServerRandom', CK_BYTE_PTR), + ('ulServerRandomLen', CK_ULONG), +] +class CK_SSL3_MASTER_KEY_DERIVE_PARAMS(Structure): + pass +CK_SSL3_MASTER_KEY_DERIVE_PARAMS._fields_ = [ + ('RandomInfo', CK_SSL3_RANDOM_DATA), + ('pVersion', CK_VERSION_PTR), +] +CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_SSL3_MASTER_KEY_DERIVE_PARAMS) +class CK_SSL3_KEY_MAT_OUT(Structure): + pass +CK_SSL3_KEY_MAT_OUT._fields_ = [ + ('hClientMacSecret', CK_OBJECT_HANDLE), + ('hServerMacSecret', CK_OBJECT_HANDLE), + ('hClientKey', CK_OBJECT_HANDLE), + ('hServerKey', CK_OBJECT_HANDLE), + ('pIVClient', CK_BYTE_PTR), + ('pIVServer', CK_BYTE_PTR), +] +CK_SSL3_KEY_MAT_OUT_PTR = POINTER(CK_SSL3_KEY_MAT_OUT) +class CK_SSL3_KEY_MAT_PARAMS(Structure): + pass +CK_SSL3_KEY_MAT_PARAMS._fields_ = [ + ('ulMacSizeInBits', CK_ULONG), + ('ulKeySizeInBits', CK_ULONG), + ('ulIVSizeInBits', CK_ULONG), + ('bIsExport', CK_BBOOL), + ('RandomInfo', CK_SSL3_RANDOM_DATA), + ('pReturnedKeyMaterial', CK_SSL3_KEY_MAT_OUT_PTR), +] +CK_SSL3_KEY_MAT_PARAMS_PTR = POINTER(CK_SSL3_KEY_MAT_PARAMS) +class CK_TLS_PRF_PARAMS(Structure): + pass +CK_TLS_PRF_PARAMS._fields_ = [ + ('pSeed', CK_BYTE_PTR), + ('ulSeedLen', CK_ULONG), + ('pLabel', CK_BYTE_PTR), + ('ulLabelLen', CK_ULONG), + ('pOutput', CK_BYTE_PTR), + ('pulOutputLen', CK_ULONG_PTR), +] +CK_TLS_PRF_PARAMS_PTR = POINTER(CK_TLS_PRF_PARAMS) +class CK_WTLS_RANDOM_DATA(Structure): + pass +CK_WTLS_RANDOM_DATA._fields_ = [ + ('pClientRandom', CK_BYTE_PTR), + ('ulClientRandomLen', CK_ULONG), + ('pServerRandom', CK_BYTE_PTR), + ('ulServerRandomLen', CK_ULONG), +] +CK_WTLS_RANDOM_DATA_PTR = POINTER(CK_WTLS_RANDOM_DATA) +class CK_WTLS_MASTER_KEY_DERIVE_PARAMS(Structure): + pass +CK_WTLS_MASTER_KEY_DERIVE_PARAMS._fields_ = [ + ('DigestMechanism', CK_MECHANISM_TYPE), + ('RandomInfo', CK_WTLS_RANDOM_DATA), + ('pVersion', CK_BYTE_PTR), +] +CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_WTLS_MASTER_KEY_DERIVE_PARAMS) +class CK_WTLS_PRF_PARAMS(Structure): + pass +CK_WTLS_PRF_PARAMS._fields_ = [ + ('DigestMechanism', CK_MECHANISM_TYPE), + ('pSeed', CK_BYTE_PTR), + ('ulSeedLen', CK_ULONG), + ('pLabel', CK_BYTE_PTR), + ('ulLabelLen', CK_ULONG), + ('pOutput', CK_BYTE_PTR), + ('pulOutputLen', CK_ULONG_PTR), +] +CK_WTLS_PRF_PARAMS_PTR = POINTER(CK_WTLS_PRF_PARAMS) +class CK_WTLS_KEY_MAT_OUT(Structure): + pass +CK_WTLS_KEY_MAT_OUT._fields_ = [ + ('hMacSecret', CK_OBJECT_HANDLE), + ('hKey', CK_OBJECT_HANDLE), + ('pIV', CK_BYTE_PTR), +] +CK_WTLS_KEY_MAT_OUT_PTR = POINTER(CK_WTLS_KEY_MAT_OUT) +class CK_WTLS_KEY_MAT_PARAMS(Structure): + pass +CK_WTLS_KEY_MAT_PARAMS._fields_ = [ + ('DigestMechanism', CK_MECHANISM_TYPE), + ('ulMacSizeInBits', CK_ULONG), + ('ulKeySizeInBits', CK_ULONG), + ('ulIVSizeInBits', CK_ULONG), + ('ulSequenceNumber', CK_ULONG), + ('bIsExport', CK_BBOOL), + ('RandomInfo', CK_WTLS_RANDOM_DATA), + ('pReturnedKeyMaterial', CK_WTLS_KEY_MAT_OUT_PTR), +] +CK_WTLS_KEY_MAT_PARAMS_PTR = POINTER(CK_WTLS_KEY_MAT_PARAMS) +class CK_CMS_SIG_PARAMS(Structure): + pass +CK_CMS_SIG_PARAMS._fields_ = [ + ('certificateHandle', CK_OBJECT_HANDLE), + ('pSigningMechanism', CK_MECHANISM_PTR), + ('pDigestMechanism', CK_MECHANISM_PTR), + ('pContentType', CK_UTF8CHAR_PTR), + ('pRequestedAttributes', CK_BYTE_PTR), + ('ulRequestedAttributesLen', CK_ULONG), + ('pRequiredAttributes', CK_BYTE_PTR), + ('ulRequiredAttributesLen', CK_ULONG), +] +CK_CMS_SIG_PARAMS_PTR = POINTER(CK_CMS_SIG_PARAMS) +class CK_KEY_DERIVATION_STRING_DATA(Structure): + pass +CK_KEY_DERIVATION_STRING_DATA._fields_ = [ + ('pData', CK_BYTE_PTR), + ('ulLen', CK_ULONG), +] +CK_KEY_DERIVATION_STRING_DATA_PTR = POINTER(CK_KEY_DERIVATION_STRING_DATA) +CK_EXTRACT_PARAMS = CK_ULONG +CK_EXTRACT_PARAMS_PTR = POINTER(CK_EXTRACT_PARAMS) +CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE = CK_ULONG +CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR = POINTER(CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE) +CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE = CK_ULONG +CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR = POINTER(CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE) +class CK_PKCS5_PBKD2_PARAMS(Structure): + pass +CK_PKCS5_PBKD2_PARAMS._fields_ = [ + ('saltSource', CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE), + ('pSaltSourceData', CK_VOID_PTR), + ('ulSaltSourceDataLen', CK_ULONG), + ('iterations', CK_ULONG), + ('prf', CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE), + ('pPrfData', CK_VOID_PTR), + ('ulPrfDataLen', CK_ULONG), + ('pPassword', CK_UTF8CHAR_PTR), + ('usPasswordLen', CK_ULONG), +] +CK_PKCS5_PBKD2_PARAMS_PTR = POINTER(CK_PKCS5_PBKD2_PARAMS) +CK_OTP_PARAM_TYPE = CK_ULONG +CK_PARAM_TYPE = CK_OTP_PARAM_TYPE +class CK_OTP_PARAM(Structure): + pass +CK_OTP_PARAM._fields_ = [ + ('type', CK_OTP_PARAM_TYPE), + ('pValue', CK_VOID_PTR), + ('usValueLen', CK_ULONG), +] +CK_OTP_PARAM_PTR = POINTER(CK_OTP_PARAM) +class CK_OTP_PARAMS(Structure): + pass +CK_OTP_PARAMS._fields_ = [ + ('pParams', CK_OTP_PARAM_PTR), + ('ulCount', CK_ULONG), +] +CK_OTP_PARAMS_PTR = POINTER(CK_OTP_PARAMS) +class CK_OTP_SIGNATURE_INFO(Structure): + pass +CK_OTP_SIGNATURE_INFO._fields_ = [ + ('pParams', CK_OTP_PARAM_PTR), + ('ulCount', CK_ULONG), +] +CK_OTP_SIGNATURE_INFO_PTR = POINTER(CK_OTP_SIGNATURE_INFO) +class CK_KIP_PARAMS(Structure): + pass +CK_KIP_PARAMS._fields_ = [ + ('pMechanism', CK_MECHANISM_PTR), + ('hKey', CK_OBJECT_HANDLE), + ('pSeed', CK_BYTE_PTR), + ('ulSeedLen', CK_ULONG), +] +CK_KIP_PARAMS_PTR = POINTER(CK_KIP_PARAMS) +class CK_AES_CTR_PARAMS(Structure): + pass +CK_AES_CTR_PARAMS._fields_ = [ + ('ulCounterBits', CK_ULONG), + ('cb', CK_BYTE * 16), +] +CK_AES_CTR_PARAMS_PTR = POINTER(CK_AES_CTR_PARAMS) +class CK_CAMELLIA_CTR_PARAMS(Structure): + pass +CK_CAMELLIA_CTR_PARAMS._fields_ = [ + ('ulCounterBits', CK_ULONG), + ('cb', CK_BYTE * 16), +] +CK_CAMELLIA_CTR_PARAMS_PTR = POINTER(CK_CAMELLIA_CTR_PARAMS) +class CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 16), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS) +class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +CK_ARIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 16), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_ARIA_CBC_ENCRYPT_DATA_PARAMS) +CK_USHORT = c_ulong +CK_USHORT_PTR = POINTER(CK_USHORT) +class CK_AES_GCM_PARAMS(Structure): + pass +CK_AES_GCM_PARAMS._fields_ = [ + ('pIv', CK_BYTE_PTR), + ('ulIvLen', CK_ULONG), + ('ulIvBits', CK_ULONG), + ('pAAD', CK_BYTE_PTR), + ('ulAADLen', CK_ULONG), + ('ulTagBits', CK_ULONG), +] +CK_AES_GCM_PARAMS_PTR = CK_AES_GCM_PARAMS +class CK_XOR_BASE_DATA_KDF_PARAMS(Structure): + pass +CK_XOR_BASE_DATA_KDF_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), +] +CK_XOR_BASE_DATA_KDF_PARAMS_PTR = POINTER(CK_XOR_BASE_DATA_KDF_PARAMS) +CK_EC_DH_PRIMITIVE = CK_ULONG +CK_EC_ENC_SCHEME = CK_ULONG +CK_EC_MAC_SCHEME = CK_ULONG +class CK_ECIES_PARAMS(Structure): + pass +CK_ECIES_PARAMS._fields_ = [ + ('dhPrimitive', CK_EC_DH_PRIMITIVE), + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen1', CK_ULONG), + ('pSharedData1', CK_BYTE_PTR), + ('encScheme', CK_EC_ENC_SCHEME), + ('ulEncKeyLenInBits', CK_ULONG), + ('macScheme', CK_EC_MAC_SCHEME), + ('ulMacKeyLenInBits', CK_ULONG), + ('ulMacLenInBits', CK_ULONG), + ('ulSharedDataLen2', CK_ULONG), + ('pSharedData2', CK_BYTE_PTR), +] +CK_ECIES_PARAMS_PTR = POINTER(CK_ECIES_PARAMS) +CK_KDF_PRF_TYPE = CK_ULONG +CK_KDF_PRF_ENCODING_SCHEME = CK_ULONG +class CK_KDF_PRF_PARAMS(Structure): + pass +CK_KDF_PRF_PARAMS._fields_ = [ + ('prfType', CK_KDF_PRF_TYPE), + ('pLabel', CK_BYTE_PTR), + ('ulLabelLen', CK_ULONG), + ('pContext', CK_BYTE_PTR), + ('ulContextLen', CK_ULONG), + ('ulCounter', CK_ULONG), + ('ulEncodingScheme', CK_KDF_PRF_ENCODING_SCHEME), +] +CK_PRF_KDF_PARAMS = CK_KDF_PRF_PARAMS +CK_KDF_PRF_PARAMS_PTR = POINTER(CK_PRF_KDF_PARAMS) +CK_SEED_CTR_PARAMS = CK_AES_CTR_PARAMS +CK_SEED_CTR_PARAMS_PTR = POINTER(CK_SEED_CTR_PARAMS) +CK_ARIA_CTR_PARAMS = CK_AES_CTR_PARAMS +CK_ARIA_CTR_PARAMS_PTR = POINTER(CK_ARIA_CTR_PARAMS) +class CK_DES_CTR_PARAMS(Structure): + pass +CK_DES_CTR_PARAMS._fields_ = [ + ('ulCounterBits', CK_ULONG), + ('cb', CK_BYTE * 8), +] +CK_DES_CTR_PARAMS_PTR = POINTER(CK_DES_CTR_PARAMS) +CK_AES_GMAC_PARAMS = CK_AES_GCM_PARAMS +CK_AES_GMAC_PARAMS_PTR = POINTER(CK_AES_GMAC_PARAMS) +class CA_MOFN_GENERATION(Structure): + pass +CA_MOFN_GENERATION._fields_ = [ + ('ulWeight', CK_ULONG), + ('pVector', CK_BYTE_PTR), + ('ulVectorLen', CK_ULONG), +] +CA_MOFN_GENERATION_PTR = POINTER(CA_MOFN_GENERATION) +class CA_MOFN_ACTIVATION(Structure): + pass +CA_MOFN_ACTIVATION._fields_ = [ + ('pVector', CK_BYTE_PTR), + ('ulVectorLen', CK_ULONG), +] +CA_MOFN_ACTIVATION_PTR = POINTER(CA_MOFN_ACTIVATION) +class CA_M_OF_N_STATUS(Structure): + pass +CA_M_OF_N_STATUS._fields_ = [ + ('ulID', CK_ULONG), + ('ulM', CK_ULONG), + ('ulN', CK_ULONG), + ('ulSecretSize', CK_ULONG), + ('ulFlag', CK_ULONG), +] +CA_MOFN_STATUS = CA_M_OF_N_STATUS +CA_MOFN_STATUS_PTR = POINTER(CA_MOFN_STATUS) +CKCA_MODULE_ID = CK_ULONG +CKCA_MODULE_ID_PTR = POINTER(CKCA_MODULE_ID) +class CKCA_MODULE_INFO(Structure): + pass +CKCA_MODULE_INFO._fields_ = [ + ('ulModuleSize', CK_ULONG), + ('developerName', CK_CHAR * 32), + ('moduleDescription', CK_CHAR * 32), + ('moduleVersion', CK_VERSION), +] +CKCA_MODULE_INFO_PTR = POINTER(CKCA_MODULE_INFO) +class CK_HA_MEMBER(Structure): + pass +CK_HA_MEMBER._fields_ = [ + ('memberSerial', CK_ULONG), + ('memberStatus', CK_RV), +] +class CK_HA_STATUS(Structure): + pass +CK_HA_STATUS._fields_ = [ + ('groupSerial', CK_ULONG), + ('memberList', CK_HA_MEMBER * 32), + ('listSize', CK_ULONG), +] +CK_HA_MEMBER_PTR = POINTER(CK_HA_MEMBER) +CK_HA_STATE_PTR = POINTER(CK_HA_STATUS) +CKA_SIM_AUTH_FORM = CK_ULONG +class CK_AES_CBC_PAD_EXTRACT_PARAMS(Structure): + pass +CK_AES_CBC_PAD_EXTRACT_PARAMS._fields_ = [ + ('ulType', CK_ULONG), + ('ulHandle', CK_ULONG), + ('ulDeleteAfterExtract', CK_ULONG), + ('pBuffer', CK_BYTE_PTR), + ('pulBufferLen', CK_ULONG_PTR), + ('ulStorage', CK_ULONG), + ('pedId', CK_ULONG), + ('pbFileName', CK_BYTE_PTR), +] +CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_EXTRACT_PARAMS) +class CK_AES_CBC_PAD_INSERT_PARAMS(Structure): + pass +CK_AES_CBC_PAD_INSERT_PARAMS._fields_ = [ + ('ulStorageType', CK_ULONG), + ('ulContainerState', CK_ULONG), + ('pBuffer', CK_BYTE_PTR), + ('ulBufferLen', CK_ULONG), + ('pulType', CK_ULONG_PTR), + ('pulHandle', CK_ULONG_PTR), + ('ulStorage', CK_ULONG), + ('pedId', CK_ULONG), + ('pbFileName', CK_BYTE_PTR), +] +CK_AES_CBC_PAD_INSERT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_INSERT_PARAMS) +class CK_CLUSTER_STATE(Structure): + pass +CK_CLUSTER_STATE._fields_ = [ + ('bMembers', CK_BYTE * 32 * 8), + ('ulMemberStatus', CK_ULONG * 8), +] +CK_CLUSTER_STATE_PTR = POINTER(CK_CLUSTER_STATE) +class CK_LKM_TOKEN_ID_S(Structure): + pass +CK_LKM_TOKEN_ID_S._fields_ = [ + ('id', CK_BYTE * 20), +] +CK_LKM_TOKEN_ID = CK_LKM_TOKEN_ID_S +CK_LKM_TOKEN_ID_PTR = POINTER(CK_LKM_TOKEN_ID) +class CK_SFNT_CA_FUNCTION_LIST(Structure): + pass +CK_SFNT_CA_FUNCTION_LIST_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST) +CK_SFNT_CA_FUNCTION_LIST_PTR_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST_PTR) +CK_CA_GetFunctionList = CFUNCTYPE(CK_RV, CK_SFNT_CA_FUNCTION_LIST_PTR_PTR) +CK_CA_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, POINTER(CK_ULONG), CK_SLOT_ID_PTR, CK_VOID_PTR) +CK_CA_InitIndirectToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_SESSION_HANDLE) +CK_CA_InitIndirectPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_SESSION_HANDLE) +CK_CA_ResetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG) +CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_Deactivate = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE) +CK_CA_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) +CK_CA_IndirectLogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE) +CK_CA_InitializeRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_DeleteRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_GetRemotePEDVectorStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_ConfigureRemotePED = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_DismantleRemotePED = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) +CK_CA_Restart = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_RestartForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) +CK_CA_CloseApplicationID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG) +CK_CA_CloseApplicationIDForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG) +CK_CA_OpenApplicationID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG) +CK_CA_OpenApplicationIDForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG) +CK_CA_SetApplicationID = CFUNCTYPE(CK_RV, CK_ULONG, CK_ULONG) +CK_CA_ManualKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_SetLKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_CA_SetKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_CA_SetCloningDomain = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG) +CK_CA_ClonePrivateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) +CK_CA_CloneObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) +CK_CA_GenerateCloningKEV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsTargetInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsSource = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsTarget = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR) +CK_CA_SetMofN = CFUNCTYPE(CK_RV, CK_BBOOL) +CK_CA_GenerateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_GenerateCloneableMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_ModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_CloneMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) +CK_CA_CloneModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) +CK_CA_ActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CA_MOFN_ACTIVATION_PTR, CK_ULONG) +CK_CA_DeactivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_GetMofNStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CA_MOFN_STATUS_PTR) +CK_CA_DuplicateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_IsMofNEnabled = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_IsMofNRequired = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GenerateTokenKeys = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_CA_GetTokenCertificateInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetModuleList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetModuleInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR) +CK_CA_LoadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_LoadEncryptedModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_UnloadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID) +CK_CA_PerformModuleCall = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) +CK_C_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_FirmwareUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) +CK_CA_FirmwareRollback = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_CapabilityUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) +CK_CA_GetUserContainerNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_SetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetTokenInsertionCount = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetRollbackFirmwareVersion = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetFPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetExtendedTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetConfigurationElementDescription = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_GetHSMCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetHSMCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetHSMPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetHSMPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetContainerCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetContainerPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_SetTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_SetExtendedTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_SetHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_SetHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetDestructiveHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_SetDestructiveHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetContainerPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG) +CK_CA_SetContainerPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_RetrieveLicenseList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_QueryLicense = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_GetContainerStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_ReadCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_WriteCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetPrimarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID_PTR) +CK_CA_GetSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID_PTR) +CK_CA_SwitchSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG) +CK_CA_CloseSecondarySession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG) +CK_CA_CloseAllSecondarySessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_ChoosePrimarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_ChooseSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_CloneObjectToAllSessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_CA_CloneAllObjectsToSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID) +CK_CA_ResetDevice = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS) +CK_CA_FactoryReset = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS) +CK_CA_SetPedId = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) +CK_CA_GetPedId = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG)) +CK_CA_SpRawRead = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_SpRawWrite = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_CheckOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)) +CK_CA_DestroyMultipleObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR) +CK_CA_HAInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_CA_HAGetMasterPublic = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAGetLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAAnswerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HALogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAAnswerMofNChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetHAState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_HA_STATE_PTR) +CK_CA_GetTokenCertificates = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_ExtractMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_InsertMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) +CK_CA_MultisignValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) +CK_CA_SIMExtract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_SIMInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_SIMMultiSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) +CK_CA_Extract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) +CK_CA_Insert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) +CK_CA_GetObjectUID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)) +CK_CA_GetObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_DeleteContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_MTKSetStorage = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_MTKRestore = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_MTKResplit = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_MTKZeroize = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_MTKGetState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetTSV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_InvokeServiceInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_InvokeService = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_InvokeServiceFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_InvokeServiceAsynch = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_InvokeServiceSinglePart = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_EncodeECParamsFromFile = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_GetHSMStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetContainerSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_CreateContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_DeleteContainerWithHandle = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_GetContainerList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_GetNumberOfAllowedContainers = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetTunnelSlotNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_ID_PTR) +CK_CA_GetClusterState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CLUSTER_STATE_PTR) +CK_CA_LockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_UnlockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_LKMInitiatorChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMReceiverResponse = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMInitiatorComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_LKMReceiverComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_ModifyUsageCount = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_LogVerify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_LogVerifyFile = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LogExternal = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG) +CK_CA_LogImportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) +CK_CA_LogExportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) +CK_CA_LogSetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR) +CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR) +CK_CA_LogEraseAll = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)) +CK_CA_InitAudit = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR) +CK_CA_GetTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR) +CK_CA_TimeSync = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_SFNT_CA_FUNCTION_LIST._fields_ = [ + ('version', CK_VERSION), + ('CA_GetFunctionList', CK_CA_GetFunctionList), + ('CA_WaitForSlotEvent', CK_CA_WaitForSlotEvent), + ('CA_InitIndirectToken', CK_CA_InitIndirectToken), + ('CA_InitIndirectPIN', CK_CA_InitIndirectPIN), + ('CA_ResetPIN', CK_CA_ResetPIN), + ('CA_CreateLoginChallenge', CK_CA_CreateLoginChallenge), + ('CA_Deactivate', CK_CA_Deactivate), + ('CA_OpenSession', CK_CA_OpenSession), + ('CA_IndirectLogin', CK_CA_IndirectLogin), + ('CA_InitializeRemotePEDVector', CK_CA_InitializeRemotePEDVector), + ('CA_DeleteRemotePEDVector', CK_CA_DeleteRemotePEDVector), + ('CA_GetRemotePEDVectorStatus', CK_CA_GetRemotePEDVectorStatus), + ('CA_ConfigureRemotePED', CK_CA_ConfigureRemotePED), + ('CA_DismantleRemotePED', CK_CA_DismantleRemotePED), + ('CA_Restart', CK_CA_Restart), + ('CA_RestartForContainer', CK_CA_RestartForContainer), + ('CA_CloseApplicationID', CK_CA_CloseApplicationID), + ('CA_CloseApplicationIDForContainer', CK_CA_CloseApplicationIDForContainer), + ('CA_OpenApplicationID', CK_CA_OpenApplicationID), + ('CA_OpenApplicationIDForContainer', CK_CA_OpenApplicationIDForContainer), + ('CA_SetApplicationID', CK_CA_SetApplicationID), + ('CA_ManualKCV', CK_CA_ManualKCV), + ('CA_SetLKCV', CK_CA_SetLKCV), + ('CA_SetKCV', CK_CA_SetKCV), + ('CA_SetCloningDomain', CK_CA_SetCloningDomain), + ('CA_ClonePrivateKey', CK_CA_ClonePrivateKey), + ('CA_CloneObject', CK_CA_CloneObject), + ('CA_GenerateCloningKEV', CK_CA_GenerateCloningKEV), + ('CA_CloneAsTargetInit', CK_CA_CloneAsTargetInit), + ('CA_CloneAsSource', CK_CA_CloneAsSource), + ('CA_CloneAsTarget', CK_CA_CloneAsTarget), + ('CA_SetMofN', CK_CA_SetMofN), + ('CA_GenerateMofN', CK_CA_GenerateMofN), + ('CA_GenerateCloneableMofN', CK_CA_GenerateCloneableMofN), + ('CA_ModifyMofN', CK_CA_ModifyMofN), + ('CA_CloneMofN', CK_CA_CloneMofN), + ('CA_CloneModifyMofN', CK_CA_CloneModifyMofN), + ('CA_ActivateMofN', CK_CA_ActivateMofN), + ('CA_DeactivateMofN', CK_CA_DeactivateMofN), + ('CA_GetMofNStatus', CK_CA_GetMofNStatus), + ('CA_DuplicateMofN', CK_CA_DuplicateMofN), + ('CA_IsMofNEnabled', CK_CA_IsMofNEnabled), + ('CA_IsMofNRequired', CK_CA_IsMofNRequired), + ('CA_GenerateTokenKeys', CK_CA_GenerateTokenKeys), + ('CA_GetTokenCertificateInfo', CK_CA_GetTokenCertificateInfo), + ('CA_SetTokenCertificateSignature', CK_CA_SetTokenCertificateSignature), + ('CA_GetModuleList', CK_CA_GetModuleList), + ('CA_GetModuleInfo', CK_CA_GetModuleInfo), + ('CA_LoadModule', CK_CA_LoadModule), + ('CA_LoadEncryptedModule', CK_CA_LoadEncryptedModule), + ('CA_UnloadModule', CK_CA_UnloadModule), + ('CA_PerformModuleCall', CK_CA_PerformModuleCall), + ('C_PerformSelfTest', CK_C_PerformSelfTest), + ('CA_FirmwareUpdate', CK_CA_FirmwareUpdate), + ('CA_FirmwareRollback', CK_CA_FirmwareRollback), + ('CA_CapabilityUpdate', CK_CA_CapabilityUpdate), + ('CA_GetUserContainerNumber', CK_CA_GetUserContainerNumber), + ('CA_GetUserContainerName', CK_CA_GetUserContainerName), + ('CA_SetUserContainerName', CK_CA_SetUserContainerName), + ('CA_GetTokenInsertionCount', CK_CA_GetTokenInsertionCount), + ('CA_GetRollbackFirmwareVersion', CK_CA_GetRollbackFirmwareVersion), + ('CA_GetFPV', CK_CA_GetFPV), + ('CA_GetTPV', CK_CA_GetTPV), + ('CA_GetExtendedTPV', CK_CA_GetExtendedTPV), + ('CA_GetConfigurationElementDescription', CK_CA_GetConfigurationElementDescription), + ('CA_GetHSMCapabilitySet', CK_CA_GetHSMCapabilitySet), + ('CA_GetHSMCapabilitySetting', CK_CA_GetHSMCapabilitySetting), + ('CA_GetHSMPolicySet', CK_CA_GetHSMPolicySet), + ('CA_GetHSMPolicySetting', CK_CA_GetHSMPolicySetting), + ('CA_GetContainerCapabilitySet', CK_CA_GetContainerCapabilitySet), + ('CA_GetContainerCapabilitySetting', CK_CA_GetContainerCapabilitySetting), + ('CA_GetContainerPolicySet', CK_CA_GetContainerPolicySet), + ('CA_GetContainerPolicySetting', CK_CA_GetContainerPolicySetting), + ('CA_SetTPV', CK_CA_SetTPV), + ('CA_SetExtendedTPV', CK_CA_SetExtendedTPV), + ('CA_SetHSMPolicy', CK_CA_SetHSMPolicy), + ('CA_SetHSMPolicies', CK_CA_SetHSMPolicies), + ('CA_SetDestructiveHSMPolicy', CK_CA_SetDestructiveHSMPolicy), + ('CA_SetDestructiveHSMPolicies', CK_CA_SetDestructiveHSMPolicies), + ('CA_SetContainerPolicy', CK_CA_SetContainerPolicy), + ('CA_SetContainerPolicies', CK_CA_SetContainerPolicies), + ('CA_RetrieveLicenseList', CK_CA_RetrieveLicenseList), + ('CA_QueryLicense', CK_CA_QueryLicense), + ('CA_GetContainerStatus', CK_CA_GetContainerStatus), + ('CA_GetSessionInfo', CK_CA_GetSessionInfo), + ('CA_ReadCommonStore', CK_CA_ReadCommonStore), + ('CA_WriteCommonStore', CK_CA_WriteCommonStore), + ('CA_GetPrimarySlot', CK_CA_GetPrimarySlot), + ('CA_GetSecondarySlot', CK_CA_GetSecondarySlot), + ('CA_SwitchSecondarySlot', CK_CA_SwitchSecondarySlot), + ('CA_CloseSecondarySession', CK_CA_CloseSecondarySession), + ('CA_CloseAllSecondarySessions', CK_CA_CloseAllSecondarySessions), + ('CA_ChoosePrimarySlot', CK_CA_ChoosePrimarySlot), + ('CA_ChooseSecondarySlot', CK_CA_ChooseSecondarySlot), + ('CA_CloneObjectToAllSessions', CK_CA_CloneObjectToAllSessions), + ('CA_CloneAllObjectsToSession', CK_CA_CloneAllObjectsToSession), + ('CA_ResetDevice', CK_CA_ResetDevice), + ('CA_FactoryReset', CK_CA_FactoryReset), + ('CA_SetPedId', CK_CA_SetPedId), + ('CA_GetPedId', CK_CA_GetPedId), + ('CA_SpRawRead', CK_CA_SpRawRead), + ('CA_SpRawWrite', CK_CA_SpRawWrite), + ('CA_CheckOperationState', CK_CA_CheckOperationState), + ('CA_DestroyMultipleObjects', CK_CA_DestroyMultipleObjects), + ('CA_HAInit', CK_CA_HAInit), + ('CA_HAGetMasterPublic', CK_CA_HAGetMasterPublic), + ('CA_HAGetLoginChallenge', CK_CA_HAGetLoginChallenge), + ('CA_HAAnswerLoginChallenge', CK_CA_HAAnswerLoginChallenge), + ('CA_HALogin', CK_CA_HALogin), + ('CA_HAAnswerMofNChallenge', CK_CA_HAAnswerMofNChallenge), + ('CA_HAActivateMofN', CK_CA_HAActivateMofN), + ('CA_GetHAState', CK_CA_GetHAState), + ('CA_GetTokenCertificates', CK_CA_GetTokenCertificates), + ('CA_ExtractMaskedObject', CK_CA_ExtractMaskedObject), + ('CA_InsertMaskedObject', CK_CA_InsertMaskedObject), + ('CA_MultisignValue', CK_CA_MultisignValue), + ('CA_SIMExtract', CK_CA_SIMExtract), + ('CA_SIMInsert', CK_CA_SIMInsert), + ('CA_SIMMultiSign', CK_CA_SIMMultiSign), + ('CA_Extract', CK_CA_Extract), + ('CA_Insert', CK_CA_Insert), + ('CA_GetObjectUID', CK_CA_GetObjectUID), + ('CA_GetObjectHandle', CK_CA_GetObjectHandle), + ('CA_DeleteContainer', CK_CA_DeleteContainer), + ('CA_MTKSetStorage', CK_CA_MTKSetStorage), + ('CA_MTKRestore', CK_CA_MTKRestore), + ('CA_MTKResplit', CK_CA_MTKResplit), + ('CA_MTKZeroize', CK_CA_MTKZeroize), + ('CA_MTKGetState', CK_CA_MTKGetState), + ('CA_GetTSV', CK_CA_GetTSV), + ('CA_InvokeServiceInit', CK_CA_InvokeServiceInit), + ('CA_InvokeService', CK_CA_InvokeService), + ('CA_InvokeServiceFinal', CK_CA_InvokeServiceFinal), + ('CA_InvokeServiceAsynch', CK_CA_InvokeServiceAsynch), + ('CA_InvokeServiceSinglePart', CK_CA_InvokeServiceSinglePart), + ('CA_EncodeECPrimeParams', CK_CA_EncodeECPrimeParams), + ('CA_EncodeECChar2Params', CK_CA_EncodeECChar2Params), + ('CA_EncodeECParamsFromFile', CK_CA_EncodeECParamsFromFile), + ('CA_GetHSMStorageInformation', CK_CA_GetHSMStorageInformation), + ('CA_GetContainerStorageInformation', CK_CA_GetContainerStorageInformation), + ('CA_SetContainerSize', CK_CA_SetContainerSize), + ('CA_CreateContainer', CK_CA_CreateContainer), + ('CA_DeleteContainerWithHandle', CK_CA_DeleteContainerWithHandle), + ('CA_GetContainerList', CK_CA_GetContainerList), + ('CA_GetContainerName', CK_CA_GetContainerName), + ('CA_GetNumberOfAllowedContainers', CK_CA_GetNumberOfAllowedContainers), + ('CA_GetTunnelSlotNumber', CK_CA_GetTunnelSlotNumber), + ('CA_GetClusterState', CK_CA_GetClusterState), + ('CA_LockClusteredSlot', CK_CA_LockClusteredSlot), + ('CA_UnlockClusteredSlot', CK_CA_UnlockClusteredSlot), + ('CA_LKMInitiatorChallenge', CK_CA_LKMInitiatorChallenge), + ('CA_LKMReceiverResponse', CK_CA_LKMReceiverResponse), + ('CA_LKMInitiatorComplete', CK_CA_LKMInitiatorComplete), + ('CA_LKMReceiverComplete', CK_CA_LKMReceiverComplete), + ('CA_ModifyUsageCount', CK_CA_ModifyUsageCount), + ('CA_LogVerify', CK_CA_LogVerify), + ('CA_LogVerifyFile', CK_CA_LogVerifyFile), + ('CA_LogExternal', CK_CA_LogExternal), + ('CA_LogImportSecret', CK_CA_LogImportSecret), + ('CA_LogExportSecret', CK_CA_LogExportSecret), + ('CA_LogSetConfig', CK_CA_LogSetConfig), + ('CA_LogGetConfig', CK_CA_LogGetConfig), + ('CA_LogEraseAll', CK_CA_LogEraseAll), + ('CA_LogGetStatus', CK_CA_LogGetStatus), + ('CA_InitAudit', CK_CA_InitAudit), + ('CA_GetTime', CK_CA_GetTime), + ('CA_TimeSync', CK_CA_TimeSync), +] +CA_GetFunctionList = make_late_binding_function('CA_GetFunctionList') +CA_GetFunctionList.restype = CK_RV +CA_GetFunctionList.argtypes = [CK_SFNT_CA_FUNCTION_LIST_PTR_PTR] +CA_WaitForSlotEvent = make_late_binding_function('CA_WaitForSlotEvent') +CA_WaitForSlotEvent.restype = CK_RV +CA_WaitForSlotEvent.argtypes = [CK_FLAGS, POINTER(CK_ULONG), CK_SLOT_ID_PTR, CK_VOID_PTR] +CA_InitIndirectToken = make_late_binding_function('CA_InitIndirectToken') +CA_InitIndirectToken.restype = CK_RV +CA_InitIndirectToken.argtypes = [CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_SESSION_HANDLE] +CA_InitIndirectPIN = make_late_binding_function('CA_InitIndirectPIN') +CA_InitIndirectPIN.restype = CK_RV +CA_InitIndirectPIN.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_SESSION_HANDLE] +CA_ResetPIN = make_late_binding_function('CA_ResetPIN') +CA_ResetPIN.restype = CK_RV +CA_ResetPIN.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG] +CA_CreateLoginChallenge = make_late_binding_function('CA_CreateLoginChallenge') +CA_CreateLoginChallenge.restype = CK_RV +CA_CreateLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR] +CA_Deactivate = make_late_binding_function('CA_Deactivate') +CA_Deactivate.restype = CK_RV +CA_Deactivate.argtypes = [CK_SLOT_ID, CK_USER_TYPE] +CA_OpenSession = make_late_binding_function('CA_OpenSession') +CA_OpenSession.restype = CK_RV +CA_OpenSession.argtypes = [CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] +CA_IndirectLogin = make_late_binding_function('CA_IndirectLogin') +CA_IndirectLogin.restype = CK_RV +CA_IndirectLogin.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE] +CA_InitializeRemotePEDVector = make_late_binding_function('CA_InitializeRemotePEDVector') +CA_InitializeRemotePEDVector.restype = CK_RV +CA_InitializeRemotePEDVector.argtypes = [CK_SESSION_HANDLE] +CA_DeleteRemotePEDVector = make_late_binding_function('CA_DeleteRemotePEDVector') +CA_DeleteRemotePEDVector.restype = CK_RV +CA_DeleteRemotePEDVector.argtypes = [CK_SESSION_HANDLE] +CA_GetRemotePEDVectorStatus = make_late_binding_function('CA_GetRemotePEDVectorStatus') +CA_GetRemotePEDVectorStatus.restype = CK_RV +CA_GetRemotePEDVectorStatus.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_ConfigureRemotePED = make_late_binding_function('CA_ConfigureRemotePED') +CA_ConfigureRemotePED.restype = CK_RV +CA_ConfigureRemotePED.argtypes = [CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_ULONG_PTR] +CA_DismantleRemotePED = make_late_binding_function('CA_DismantleRemotePED') +CA_DismantleRemotePED.restype = CK_RV +CA_DismantleRemotePED.argtypes = [CK_SLOT_ID, CK_ULONG] +CA_Restart = make_late_binding_function('CA_Restart') +CA_Restart.restype = CK_RV +CA_Restart.argtypes = [CK_SLOT_ID] +CA_RestartForContainer = make_late_binding_function('CA_RestartForContainer') +CA_RestartForContainer.restype = CK_RV +CA_RestartForContainer.argtypes = [CK_SLOT_ID, CK_ULONG] +CA_CloseApplicationID = make_late_binding_function('CA_CloseApplicationID') +CA_CloseApplicationID.restype = CK_RV +CA_CloseApplicationID.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG] +CA_CloseApplicationIDForContainer = make_late_binding_function('CA_CloseApplicationIDForContainer') +CA_CloseApplicationIDForContainer.restype = CK_RV +CA_CloseApplicationIDForContainer.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG] +CA_OpenApplicationID = make_late_binding_function('CA_OpenApplicationID') +CA_OpenApplicationID.restype = CK_RV +CA_OpenApplicationID.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG] +CA_OpenApplicationIDForContainer = make_late_binding_function('CA_OpenApplicationIDForContainer') +CA_OpenApplicationIDForContainer.restype = CK_RV +CA_OpenApplicationIDForContainer.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG] +CA_SetApplicationID = make_late_binding_function('CA_SetApplicationID') +CA_SetApplicationID.restype = CK_RV +CA_SetApplicationID.argtypes = [CK_ULONG, CK_ULONG] +CA_ManualKCV = make_late_binding_function('CA_ManualKCV') +CA_ManualKCV.restype = CK_RV +CA_ManualKCV.argtypes = [CK_SESSION_HANDLE] +CA_SetLKCV = make_late_binding_function('CA_SetLKCV') +CA_SetLKCV.restype = CK_RV +CA_SetLKCV.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +CA_SetKCV = make_late_binding_function('CA_SetKCV') +CA_SetKCV.restype = CK_RV +CA_SetKCV.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +CA_SetCloningDomain = make_late_binding_function('CA_SetCloningDomain') +CA_SetCloningDomain.restype = CK_RV +CA_SetCloningDomain.argtypes = [CK_BYTE_PTR, CK_ULONG] +CA_ClonePrivateKey = make_late_binding_function('CA_ClonePrivateKey') +CA_ClonePrivateKey.restype = CK_RV +CA_ClonePrivateKey.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR] +CA_CloneObject = make_late_binding_function('CA_CloneObject') +CA_CloneObject.restype = CK_RV +CA_CloneObject.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR] +CA_GenerateCloningKEV = make_late_binding_function('CA_GenerateCloningKEV') +CA_GenerateCloningKEV.restype = CK_RV +CA_GenerateCloningKEV.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +CA_CloneAsTargetInit = make_late_binding_function('CA_CloneAsTargetInit') +CA_CloneAsTargetInit.restype = CK_RV +CA_CloneAsTargetInit.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR] +CA_CloneAsSource = make_late_binding_function('CA_CloneAsSource') +CA_CloneAsSource.restype = CK_RV +CA_CloneAsSource.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR] +CA_CloneAsTarget = make_late_binding_function('CA_CloneAsTarget') +CA_CloneAsTarget.restype = CK_RV +CA_CloneAsTarget.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR] +CA_SetMofN = make_late_binding_function('CA_SetMofN') +CA_SetMofN.restype = CK_RV +CA_SetMofN.argtypes = [CK_BBOOL] +CA_GenerateMofN = make_late_binding_function('CA_GenerateMofN') +CA_GenerateMofN.restype = CK_RV +CA_GenerateMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] +CA_GenerateCloneableMofN = make_late_binding_function('CA_GenerateCloneableMofN') +CA_GenerateCloneableMofN.restype = CK_RV +CA_GenerateCloneableMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] +CA_ModifyMofN = make_late_binding_function('CA_ModifyMofN') +CA_ModifyMofN.restype = CK_RV +CA_ModifyMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] +CA_CloneMofN = make_late_binding_function('CA_CloneMofN') +CA_CloneMofN.restype = CK_RV +CA_CloneMofN.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR] +CA_CloneModifyMofN = make_late_binding_function('CA_CloneModifyMofN') +CA_CloneModifyMofN.restype = CK_RV +CA_CloneModifyMofN.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR] +CA_ActivateMofN = make_late_binding_function('CA_ActivateMofN') +CA_ActivateMofN.restype = CK_RV +CA_ActivateMofN.argtypes = [CK_SESSION_HANDLE, CA_MOFN_ACTIVATION_PTR, CK_ULONG] +CA_DeactivateMofN = make_late_binding_function('CA_DeactivateMofN') +CA_DeactivateMofN.restype = CK_RV +CA_DeactivateMofN.argtypes = [CK_SESSION_HANDLE] +CA_GetMofNStatus = make_late_binding_function('CA_GetMofNStatus') +CA_GetMofNStatus.restype = CK_RV +CA_GetMofNStatus.argtypes = [CK_SLOT_ID, CA_MOFN_STATUS_PTR] +CA_DuplicateMofN = make_late_binding_function('CA_DuplicateMofN') +CA_DuplicateMofN.restype = CK_RV +CA_DuplicateMofN.argtypes = [CK_SESSION_HANDLE] +CA_IsMofNEnabled = make_late_binding_function('CA_IsMofNEnabled') +CA_IsMofNEnabled.restype = CK_RV +CA_IsMofNEnabled.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_IsMofNRequired = make_late_binding_function('CA_IsMofNRequired') +CA_IsMofNRequired.restype = CK_RV +CA_IsMofNRequired.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GenerateTokenKeys = make_late_binding_function('CA_GenerateTokenKeys') +CA_GenerateTokenKeys.restype = CK_RV +CA_GenerateTokenKeys.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] +CA_GetTokenCertificateInfo = make_late_binding_function('CA_GetTokenCertificateInfo') +CA_GetTokenCertificateInfo.restype = CK_RV +CA_GetTokenCertificateInfo.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_SetTokenCertificateSignature = make_late_binding_function('CA_SetTokenCertificateSignature') +CA_SetTokenCertificateSignature.restype = CK_RV +CA_SetTokenCertificateSignature.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_GetModuleList = make_late_binding_function('CA_GetModuleList') +CA_GetModuleList.restype = CK_RV +CA_GetModuleList.argtypes = [CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR] +CA_GetModuleInfo = make_late_binding_function('CA_GetModuleInfo') +CA_GetModuleInfo.restype = CK_RV +CA_GetModuleInfo.argtypes = [CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR] +CA_LoadModule = make_late_binding_function('CA_LoadModule') +CA_LoadModule.restype = CK_RV +CA_LoadModule.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] +CA_LoadEncryptedModule = make_late_binding_function('CA_LoadEncryptedModule') +CA_LoadEncryptedModule.restype = CK_RV +CA_LoadEncryptedModule.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] +CA_UnloadModule = make_late_binding_function('CA_UnloadModule') +CA_UnloadModule.restype = CK_RV +CA_UnloadModule.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID] +CA_PerformModuleCall = make_late_binding_function('CA_PerformModuleCall') +CA_PerformModuleCall.restype = CK_RV +CA_PerformModuleCall.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR] +C_PerformSelfTest = make_late_binding_function('C_PerformSelfTest') +C_PerformSelfTest.restype = CK_RV +C_PerformSelfTest.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_FirmwareUpdate = make_late_binding_function('CA_FirmwareUpdate') +CA_FirmwareUpdate.restype = CK_RV +CA_FirmwareUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR] +CA_FirmwareRollback = make_late_binding_function('CA_FirmwareRollback') +CA_FirmwareRollback.restype = CK_RV +CA_FirmwareRollback.argtypes = [CK_SESSION_HANDLE] +CA_CapabilityUpdate = make_late_binding_function('CA_CapabilityUpdate') +CA_CapabilityUpdate.restype = CK_RV +CA_CapabilityUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR] +CA_GetUserContainerNumber = make_late_binding_function('CA_GetUserContainerNumber') +CA_GetUserContainerNumber.restype = CK_RV +CA_GetUserContainerNumber.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetUserContainerName = make_late_binding_function('CA_GetUserContainerName') +CA_GetUserContainerName.restype = CK_RV +CA_GetUserContainerName.argtypes = [CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR] +CA_SetUserContainerName = make_late_binding_function('CA_SetUserContainerName') +CA_SetUserContainerName.restype = CK_RV +CA_SetUserContainerName.argtypes = [CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG] +CA_GetTokenInsertionCount = make_late_binding_function('CA_GetTokenInsertionCount') +CA_GetTokenInsertionCount.restype = CK_RV +CA_GetTokenInsertionCount.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetRollbackFirmwareVersion = make_late_binding_function('CA_GetRollbackFirmwareVersion') +CA_GetRollbackFirmwareVersion.restype = CK_RV +CA_GetRollbackFirmwareVersion.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetFPV = make_late_binding_function('CA_GetFPV') +CA_GetFPV.restype = CK_RV +CA_GetFPV.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetTPV = make_late_binding_function('CA_GetTPV') +CA_GetTPV.restype = CK_RV +CA_GetTPV.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetExtendedTPV = make_late_binding_function('CA_GetExtendedTPV') +CA_GetExtendedTPV.restype = CK_RV +CA_GetExtendedTPV.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetConfigurationElementDescription = make_late_binding_function('CA_GetConfigurationElementDescription') +CA_GetConfigurationElementDescription.restype = CK_RV +CA_GetConfigurationElementDescription.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR] +CA_GetHSMCapabilitySet = make_late_binding_function('CA_GetHSMCapabilitySet') +CA_GetHSMCapabilitySet.restype = CK_RV +CA_GetHSMCapabilitySet.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetHSMCapabilitySetting = make_late_binding_function('CA_GetHSMCapabilitySetting') +CA_GetHSMCapabilitySetting.restype = CK_RV +CA_GetHSMCapabilitySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR] +CA_GetHSMPolicySet = make_late_binding_function('CA_GetHSMPolicySet') +CA_GetHSMPolicySet.restype = CK_RV +CA_GetHSMPolicySet.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetHSMPolicySetting = make_late_binding_function('CA_GetHSMPolicySetting') +CA_GetHSMPolicySetting.restype = CK_RV +CA_GetHSMPolicySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR] +CA_GetContainerCapabilitySet = make_late_binding_function('CA_GetContainerCapabilitySet') +CA_GetContainerCapabilitySet.restype = CK_RV +CA_GetContainerCapabilitySet.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerCapabilitySetting = make_late_binding_function('CA_GetContainerCapabilitySetting') +CA_GetContainerCapabilitySetting.restype = CK_RV +CA_GetContainerCapabilitySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR] +CA_GetContainerPolicySet = make_late_binding_function('CA_GetContainerPolicySet') +CA_GetContainerPolicySet.restype = CK_RV +CA_GetContainerPolicySet.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerPolicySetting = make_late_binding_function('CA_GetContainerPolicySetting') +CA_GetContainerPolicySetting.restype = CK_RV +CA_GetContainerPolicySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR] +CA_SetTPV = make_late_binding_function('CA_SetTPV') +CA_SetTPV.restype = CK_RV +CA_SetTPV.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_SetExtendedTPV = make_late_binding_function('CA_SetExtendedTPV') +CA_SetExtendedTPV.restype = CK_RV +CA_SetExtendedTPV.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_SetHSMPolicy = make_late_binding_function('CA_SetHSMPolicy') +CA_SetHSMPolicy.restype = CK_RV +CA_SetHSMPolicy.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_SetHSMPolicies = make_late_binding_function('CA_SetHSMPolicies') +CA_SetHSMPolicies.restype = CK_RV +CA_SetHSMPolicies.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_SetDestructiveHSMPolicy = make_late_binding_function('CA_SetDestructiveHSMPolicy') +CA_SetDestructiveHSMPolicy.restype = CK_RV +CA_SetDestructiveHSMPolicy.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_SetDestructiveHSMPolicies = make_late_binding_function('CA_SetDestructiveHSMPolicies') +CA_SetDestructiveHSMPolicies.restype = CK_RV +CA_SetDestructiveHSMPolicies.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_SetContainerPolicy = make_late_binding_function('CA_SetContainerPolicy') +CA_SetContainerPolicy.restype = CK_RV +CA_SetContainerPolicy.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG] +CA_SetContainerPolicies = make_late_binding_function('CA_SetContainerPolicies') +CA_SetContainerPolicies.restype = CK_RV +CA_SetContainerPolicies.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_RetrieveLicenseList = make_late_binding_function('CA_RetrieveLicenseList') +CA_RetrieveLicenseList.restype = CK_RV +CA_RetrieveLicenseList.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] +CA_QueryLicense = make_late_binding_function('CA_QueryLicense') +CA_QueryLicense.restype = CK_RV +CA_QueryLicense.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR] +CA_GetContainerStatus = make_late_binding_function('CA_GetContainerStatus') +CA_GetContainerStatus.restype = CK_RV +CA_GetContainerStatus.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetSessionInfo = make_late_binding_function('CA_GetSessionInfo') +CA_GetSessionInfo.restype = CK_RV +CA_GetSessionInfo.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_ReadCommonStore = make_late_binding_function('CA_ReadCommonStore') +CA_ReadCommonStore.restype = CK_RV +CA_ReadCommonStore.argtypes = [CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_WriteCommonStore = make_late_binding_function('CA_WriteCommonStore') +CA_WriteCommonStore.restype = CK_RV +CA_WriteCommonStore.argtypes = [CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_GetPrimarySlot = make_late_binding_function('CA_GetPrimarySlot') +CA_GetPrimarySlot.restype = CK_RV +CA_GetPrimarySlot.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID_PTR] +CA_GetSecondarySlot = make_late_binding_function('CA_GetSecondarySlot') +CA_GetSecondarySlot.restype = CK_RV +CA_GetSecondarySlot.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID_PTR] +CA_SwitchSecondarySlot = make_late_binding_function('CA_SwitchSecondarySlot') +CA_SwitchSecondarySlot.restype = CK_RV +CA_SwitchSecondarySlot.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG] +CA_CloseSecondarySession = make_late_binding_function('CA_CloseSecondarySession') +CA_CloseSecondarySession.restype = CK_RV +CA_CloseSecondarySession.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG] +CA_CloseAllSecondarySessions = make_late_binding_function('CA_CloseAllSecondarySessions') +CA_CloseAllSecondarySessions.restype = CK_RV +CA_CloseAllSecondarySessions.argtypes = [CK_SESSION_HANDLE] +CA_ChoosePrimarySlot = make_late_binding_function('CA_ChoosePrimarySlot') +CA_ChoosePrimarySlot.restype = CK_RV +CA_ChoosePrimarySlot.argtypes = [CK_SESSION_HANDLE] +CA_ChooseSecondarySlot = make_late_binding_function('CA_ChooseSecondarySlot') +CA_ChooseSecondarySlot.restype = CK_RV +CA_ChooseSecondarySlot.argtypes = [CK_SESSION_HANDLE] +CA_CloneObjectToAllSessions = make_late_binding_function('CA_CloneObjectToAllSessions') +CA_CloneObjectToAllSessions.restype = CK_RV +CA_CloneObjectToAllSessions.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] +CA_CloneAllObjectsToSession = make_late_binding_function('CA_CloneAllObjectsToSession') +CA_CloneAllObjectsToSession.restype = CK_RV +CA_CloneAllObjectsToSession.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID] +CA_ResetDevice = make_late_binding_function('CA_ResetDevice') +CA_ResetDevice.restype = CK_RV +CA_ResetDevice.argtypes = [CK_SLOT_ID, CK_FLAGS] +CA_FactoryReset = make_late_binding_function('CA_FactoryReset') +CA_FactoryReset.restype = CK_RV +CA_FactoryReset.argtypes = [CK_SLOT_ID, CK_FLAGS] +CA_SetPedId = make_late_binding_function('CA_SetPedId') +CA_SetPedId.restype = CK_RV +CA_SetPedId.argtypes = [CK_SLOT_ID, CK_ULONG] +CA_GetPedId = make_late_binding_function('CA_GetPedId') +CA_GetPedId.restype = CK_RV +CA_GetPedId.argtypes = [CK_SLOT_ID, POINTER(CK_ULONG)] +CA_SpRawRead = make_late_binding_function('CA_SpRawRead') +CA_SpRawRead.restype = CK_RV +CA_SpRawRead.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_SpRawWrite = make_late_binding_function('CA_SpRawWrite') +CA_SpRawWrite.restype = CK_RV +CA_SpRawWrite.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_CheckOperationState = make_late_binding_function('CA_CheckOperationState') +CA_CheckOperationState.restype = CK_RV +CA_CheckOperationState.argtypes = [CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)] +CA_DestroyMultipleObjects = make_late_binding_function('CA_DestroyMultipleObjects') +CA_DestroyMultipleObjects.restype = CK_RV +CA_DestroyMultipleObjects.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR] +CA_HAInit = make_late_binding_function('CA_HAInit') +CA_HAInit.restype = CK_RV +CA_HAInit.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] +CA_HAGetMasterPublic = make_late_binding_function('CA_HAGetMasterPublic') +CA_HAGetMasterPublic.restype = CK_RV +CA_HAGetMasterPublic.argtypes = [CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HAGetLoginChallenge = make_late_binding_function('CA_HAGetLoginChallenge') +CA_HAGetLoginChallenge.restype = CK_RV +CA_HAGetLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HAAnswerLoginChallenge = make_late_binding_function('CA_HAAnswerLoginChallenge') +CA_HAAnswerLoginChallenge.restype = CK_RV +CA_HAAnswerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HALogin = make_late_binding_function('CA_HALogin') +CA_HALogin.restype = CK_RV +CA_HALogin.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HAAnswerMofNChallenge = make_late_binding_function('CA_HAAnswerMofNChallenge') +CA_HAAnswerMofNChallenge.restype = CK_RV +CA_HAAnswerMofNChallenge.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HAActivateMofN = make_late_binding_function('CA_HAActivateMofN') +CA_HAActivateMofN.restype = CK_RV +CA_HAActivateMofN.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +CA_GetHAState = make_late_binding_function('CA_GetHAState') +CA_GetHAState.restype = CK_RV +CA_GetHAState.argtypes = [CK_SLOT_ID, CK_HA_STATE_PTR] +CA_GetTokenCertificates = make_late_binding_function('CA_GetTokenCertificates') +CA_GetTokenCertificates.restype = CK_RV +CA_GetTokenCertificates.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_ExtractMaskedObject = make_late_binding_function('CA_ExtractMaskedObject') +CA_ExtractMaskedObject.restype = CK_RV +CA_ExtractMaskedObject.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_InsertMaskedObject = make_late_binding_function('CA_InsertMaskedObject') +CA_InsertMaskedObject.restype = CK_RV +CA_InsertMaskedObject.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG] +CA_MultisignValue = make_late_binding_function('CA_MultisignValue') +CA_MultisignValue.restype = CK_RV +CA_MultisignValue.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] +CA_SIMExtract = make_late_binding_function('CA_SIMExtract') +CA_SIMExtract.restype = CK_RV +CA_SIMExtract.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR] +CA_SIMInsert = make_late_binding_function('CA_SIMInsert') +CA_SIMInsert.restype = CK_RV +CA_SIMInsert.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR] +CA_SIMMultiSign = make_late_binding_function('CA_SIMMultiSign') +CA_SIMMultiSign.restype = CK_RV +CA_SIMMultiSign.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] +CA_Extract = make_late_binding_function('CA_Extract') +CA_Extract.restype = CK_RV +CA_Extract.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] +CA_Insert = make_late_binding_function('CA_Insert') +CA_Insert.restype = CK_RV +CA_Insert.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] +CA_GetObjectUID = make_late_binding_function('CA_GetObjectUID') +CA_GetObjectUID.restype = CK_RV +CA_GetObjectUID.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)] +CA_GetObjectHandle = make_late_binding_function('CA_GetObjectHandle') +CA_GetObjectHandle.restype = CK_RV +CA_GetObjectHandle.argtypes = [CK_SLOT_ID, CK_ULONG, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR] +CA_DeleteContainer = make_late_binding_function('CA_DeleteContainer') +CA_DeleteContainer.restype = CK_RV +CA_DeleteContainer.argtypes = [CK_SESSION_HANDLE] +CA_MTKSetStorage = make_late_binding_function('CA_MTKSetStorage') +CA_MTKSetStorage.restype = CK_RV +CA_MTKSetStorage.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_MTKRestore = make_late_binding_function('CA_MTKRestore') +CA_MTKRestore.restype = CK_RV +CA_MTKRestore.argtypes = [CK_SLOT_ID] +CA_MTKResplit = make_late_binding_function('CA_MTKResplit') +CA_MTKResplit.restype = CK_RV +CA_MTKResplit.argtypes = [CK_SLOT_ID] +CA_MTKZeroize = make_late_binding_function('CA_MTKZeroize') +CA_MTKZeroize.restype = CK_RV +CA_MTKZeroize.argtypes = [CK_SLOT_ID] +CA_MTKGetState = make_late_binding_function('CA_MTKGetState') +CA_MTKGetState.restype = CK_RV +CA_MTKGetState.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetTSV = make_late_binding_function('CA_GetTSV') +CA_GetTSV.restype = CK_RV +CA_GetTSV.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_InvokeServiceInit = make_late_binding_function('CA_InvokeServiceInit') +CA_InvokeServiceInit.restype = CK_RV +CA_InvokeServiceInit.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_InvokeService = make_late_binding_function('CA_InvokeService') +CA_InvokeService.restype = CK_RV +CA_InvokeService.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR] +CA_InvokeServiceFinal = make_late_binding_function('CA_InvokeServiceFinal') +CA_InvokeServiceFinal.restype = CK_RV +CA_InvokeServiceFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +CA_InvokeServiceAsynch = make_late_binding_function('CA_InvokeServiceAsynch') +CA_InvokeServiceAsynch.restype = CK_RV +CA_InvokeServiceAsynch.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_InvokeServiceSinglePart = make_late_binding_function('CA_InvokeServiceSinglePart') +CA_InvokeServiceSinglePart.restype = CK_RV +CA_InvokeServiceSinglePart.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_EncodeECPrimeParams = make_late_binding_function('CA_EncodeECPrimeParams') +CA_EncodeECPrimeParams.restype = CK_RV +CA_EncodeECPrimeParams.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_EncodeECChar2Params = make_late_binding_function('CA_EncodeECChar2Params') +CA_EncodeECChar2Params.restype = CK_RV +CA_EncodeECChar2Params.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_EncodeECParamsFromFile = make_late_binding_function('CA_EncodeECParamsFromFile') +CA_EncodeECParamsFromFile.restype = CK_RV +CA_EncodeECParamsFromFile.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR] +CA_GetHSMStorageInformation = make_late_binding_function('CA_GetHSMStorageInformation') +CA_GetHSMStorageInformation.restype = CK_RV +CA_GetHSMStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerStorageInformation = make_late_binding_function('CA_GetContainerStorageInformation') +CA_GetContainerStorageInformation.restype = CK_RV +CA_GetContainerStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_SetContainerSize = make_late_binding_function('CA_SetContainerSize') +CA_SetContainerSize.restype = CK_RV +CA_SetContainerSize.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_CreateContainer = make_late_binding_function('CA_CreateContainer') +CA_CreateContainer.restype = CK_RV +CA_CreateContainer.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR] +CA_InitAudit = make_late_binding_function('CA_InitAudit') +CA_InitAudit.restype = CK_RV +CA_InitAudit.argtypes = [CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR] +CA_LogVerify = make_late_binding_function('CA_LogVerify') +CA_LogVerify.restype = CK_RV +CA_LogVerify.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG_PTR] +CA_LogVerifyFile = make_late_binding_function('CA_LogVerifyFile') +CA_LogVerifyFile.restype = CK_RV +CA_LogVerifyFile.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG_PTR] +CA_LogExternal = make_late_binding_function('CA_LogExternal') +CA_LogExternal.restype = CK_RV +CA_LogExternal.argtypes = [CK_SLOT_ID, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG] +CA_LogImportSecret = make_late_binding_function('CA_LogImportSecret') +CA_LogImportSecret.restype = CK_RV +CA_LogImportSecret.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR] +CA_LogExportSecret = make_late_binding_function('CA_LogExportSecret') +CA_LogExportSecret.restype = CK_RV +CA_LogExportSecret.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR] +CA_TimeSync = make_late_binding_function('CA_TimeSync') +CA_TimeSync.restype = CK_RV +CA_TimeSync.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_GetTime = make_late_binding_function('CA_GetTime') +CA_GetTime.restype = CK_RV +CA_GetTime.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR] +CA_LogSetConfig = make_late_binding_function('CA_LogSetConfig') +CA_LogSetConfig.restype = CK_RV +CA_LogSetConfig.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR] +CA_LogGetConfig = make_late_binding_function('CA_LogGetConfig') +CA_LogGetConfig.restype = CK_RV +CA_LogGetConfig.argtypes = [CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR] +CA_LogEraseAll = make_late_binding_function('CA_LogEraseAll') +CA_LogEraseAll.restype = CK_RV +CA_LogEraseAll.argtypes = [CK_SESSION_HANDLE] +CA_LogGetStatus = make_late_binding_function('CA_LogGetStatus') +CA_LogGetStatus.restype = CK_RV +CA_LogGetStatus.argtypes = [CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)] +CA_DeleteContainerWithHandle = make_late_binding_function('CA_DeleteContainerWithHandle') +CA_DeleteContainerWithHandle.restype = CK_RV +CA_DeleteContainerWithHandle.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_GetContainerList = make_late_binding_function('CA_GetContainerList') +CA_GetContainerList.restype = CK_RV +CA_GetContainerList.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerName = make_late_binding_function('CA_GetContainerName') +CA_GetContainerName.restype = CK_RV +CA_GetContainerName.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_GetNumberOfAllowedContainers = make_late_binding_function('CA_GetNumberOfAllowedContainers') +CA_GetNumberOfAllowedContainers.restype = CK_RV +CA_GetNumberOfAllowedContainers.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetTunnelSlotNumber = make_late_binding_function('CA_GetTunnelSlotNumber') +CA_GetTunnelSlotNumber.restype = CK_RV +CA_GetTunnelSlotNumber.argtypes = [CK_SLOT_ID, CK_SLOT_ID_PTR] +CA_GetClusterState = make_late_binding_function('CA_GetClusterState') +CA_GetClusterState.restype = CK_RV +CA_GetClusterState.argtypes = [CK_SLOT_ID, CK_CLUSTER_STATE_PTR] +CA_LockClusteredSlot = make_late_binding_function('CA_LockClusteredSlot') +CA_LockClusteredSlot.restype = CK_RV +CA_LockClusteredSlot.argtypes = [CK_SLOT_ID] +CA_UnlockClusteredSlot = make_late_binding_function('CA_UnlockClusteredSlot') +CA_UnlockClusteredSlot.restype = CK_RV +CA_UnlockClusteredSlot.argtypes = [CK_SLOT_ID] +CA_LKMInitiatorChallenge = make_late_binding_function('CA_LKMInitiatorChallenge') +CA_LKMInitiatorChallenge.restype = CK_RV +CA_LKMInitiatorChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR] +CA_LKMReceiverResponse = make_late_binding_function('CA_LKMReceiverResponse') +CA_LKMReceiverResponse.restype = CK_RV +CA_LKMReceiverResponse.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR] +CA_LKMInitiatorComplete = make_late_binding_function('CA_LKMInitiatorComplete') +CA_LKMInitiatorComplete.restype = CK_RV +CA_LKMInitiatorComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +CA_LKMReceiverComplete = make_late_binding_function('CA_LKMReceiverComplete') +CA_LKMReceiverComplete.restype = CK_RV +CA_LKMReceiverComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +CA_ModifyUsageCount = make_late_binding_function('CA_ModifyUsageCount') +CA_ModifyUsageCount.restype = CK_RV +CA_ModifyUsageCount.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG] +CK_GetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(c_int)) +CK_ResetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_SinglePartSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_SinglePartDecrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +__all__ = ['CA_InvokeService', 'CA_GetSecondarySlot', + 'CK_OTP_SIGNATURE_INFO', 'C_FindObjectsFinal', + 'CK_C_EncryptFinal', + 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE', + 'CK_CA_HAAnswerMofNChallenge', 'CK_CA_InvokeServiceInit', + 'CK_ECDH1_DERIVE_PARAMS', 'C_UnwrapKey', + 'CA_DismantleRemotePED', 'CA_PerformModuleCall', + 'CA_SetApplicationID', 'CK_OTP_PARAM', + 'CA_LoadEncryptedModule', 'CA_MTKZeroize', + 'CK_C_VerifyInit', 'CK_LKM_TOKEN_ID_PTR', + 'CK_RC2_PARAMS_PTR', 'CK_WTLS_PRF_PARAMS_PTR', + 'CK_C_CancelFunction', 'CK_CA_GetContainerStatus', + 'CK_CA_FactoryReset', 'CK_CA_Restart', + 'CK_C_VerifyRecover', 'CK_CA_SetDestructiveHSMPolicy', + 'CK_CA_SpRawRead', 'C_SetAttributeValue', + 'CK_RC2_CBC_PARAMS_PTR', 'CA_CloseAllSecondarySessions', + 'CK_C_GetOperationState', 'CK_C_SetOperationState', + 'CK_CA_CloseApplicationIDForContainer', 'C_VerifyFinal', + 'CK_CA_LogVerifyFile', 'CK_TOKEN_INFO', + 'CK_RSA_PKCS_OAEP_PARAMS', + 'CK_CA_CloseAllSecondarySessions', 'CK_DATE', + 'CA_ReadCommonStore', + 'CA_GetConfigurationElementDescription', + 'CK_WTLS_PRF_PARAMS', 'CK_RC2_MAC_GENERAL_PARAMS', + 'CK_CA_CapabilityUpdate', 'CK_SESSION_HANDLE', + 'CK_RC5_PARAMS', 'CK_SLOT_INFO', 'C_GetInfo', + 'CK_CA_SpRawWrite', 'CK_C_EncryptInit', 'C_Login', + 'CK_CA_CloneAllObjectsToSession', 'C_GetMechanismInfo', + 'CK_CA_GetConfigurationElementDescription', 'CK_C_SetPIN', + 'CA_QueryLicense', 'C_Logout', 'C_Finalize', + 'C_CreateObject', 'CK_ATTRIBUTE_PTR', 'CK_VERSION', + 'CK_CA_GetFPV', 'CK_SESSION_HANDLE_PTR', + 'CK_CA_FirmwareUpdate', 'CK_CA_OpenSession', + 'CK_RC2_MAC_GENERAL_PARAMS_PTR', 'CA_CloseApplicationID', + 'C_WaitForSlotEvent', 'CA_Restart', 'CK_HW_FEATURE_TYPE', + 'CA_CloneAsTargetInit', 'C_FindObjects', 'CK_C_Logout', + 'CK_VOID_PTR', 'CK_C_Sign', 'CK_CA_GetTunnelSlotNumber', + 'CA_HAGetLoginChallenge', 'CA_CreateContainer', + 'CA_EncodeECParamsFromFile', 'CK_CA_ReadCommonStore', + 'CA_LogSetConfig', 'CK_MECHANISM_INFO', 'CK_C_GetInfo', + 'CKCA_MODULE_ID_PTR', 'CK_C_INITIALIZE_ARGS', 'CK_LONG', + 'CA_MOFN_GENERATION', 'CKCA_MODULE_ID', + 'CA_GetTokenCertificateInfo', 'C_Decrypt', 'CA_InitAudit', + 'CK_C_SignEncryptUpdate', 'CA_GetExtendedTPV', + 'CK_SFNT_CA_FUNCTION_LIST_PTR', + 'CK_SKIPJACK_PRIVATE_WRAP_PTR', 'CA_GetContainerPolicySet', + 'CK_EXTRACT_PARAMS_PTR', 'CA_LoadModule', + 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CA_FirmwareRollback', + 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR', 'CK_CA_SetKCV', + 'CK_CA_GetObjectUID', 'CK_OBJECT_HANDLE_PTR', + 'CA_LogExportSecret', 'CA_Deactivate', + 'C_DecryptDigestUpdate', + 'CA_OpenApplicationIDForContainer', 'C_SetOperationState', + 'CK_X9_42_DH_KDF_TYPE', 'CK_AES_GCM_PARAMS', + 'CK_CA_ConfigureRemotePED', 'CK_HA_STATE_PTR', + 'CA_HAActivateMofN', 'CK_CA_MultisignValue', + 'CA_SetHSMPolicies', 'CA_GetHSMCapabilitySet', + 'CA_UnloadModule', 'CK_KIP_PARAMS', 'CK_CA_HAInit', + 'CA_LKMReceiverResponse', 'CK_CERTIFICATE_TYPE', + 'CK_XOR_BASE_DATA_KDF_PARAMS', 'CK_OTP_PARAM_PTR', + 'CK_C_InitPIN', 'CK_AES_CBC_PAD_EXTRACT_PARAMS', + 'CK_X9_42_MQV_DERIVE_PARAMS', 'CK_CA_GetHAState', + 'CA_SetContainerPolicy', 'C_CloseAllSessions', + 'CA_Extract', 'CK_OBJECT_CLASS', + 'CK_SKIPJACK_RELAYX_PARAMS_PTR', 'C_VerifyRecover', + 'CA_GetModuleInfo', 'CK_FLAGS', 'CK_TLS_PRF_PARAMS', + 'CK_CA_FirmwareRollback', 'CK_WTLS_KEY_MAT_OUT', + 'CK_CMS_SIG_PARAMS', 'CK_CA_GetExtendedTPV', + 'CA_GetObjectHandle', 'CK_CA_GetContainerName', + 'CA_GetRemotePEDVectorStatus', 'CK_C_GetFunctionList', + 'CK_CA_SetHSMPolicy', 'CK_SLOT_ID', 'CK_CA_LogGetStatus', + 'CA_CapabilityUpdate', 'CK_CA_SIMMultiSign', + 'CK_C_DigestEncryptUpdate', 'C_GetSlotInfo', + 'CK_HA_MEMBER', 'C_VerifyRecoverInit', + 'CA_GetTokenInsertionCount', 'C_DigestKey', + 'CK_C_OpenSession', 'CK_CA_ResetDevice', + 'CK_CA_LogExternal', 'CA_IndirectLogin', + 'C_FindObjectsInit', 'CA_SIMExtract', + 'CK_C_FindObjectsInit', 'CK_RSA_PKCS_OAEP_SOURCE_TYPE', + 'CK_UNLOCKMUTEX', 'CK_CA_GetNumberOfAllowedContainers', + 'CK_CA_SIMExtract', 'CK_ULONG_PTR', 'CK_CA_MTKResplit', + 'CK_CA_GetFunctionList', 'CKCA_MODULE_INFO', + 'CK_CA_HAGetMasterPublic', 'C_PerformSelfTest', + 'CK_CA_CloneAsTarget', 'CK_CA_RetrieveLicenseList', + 'CK_UTF8CHAR_PTR', 'CA_LogEraseAll', 'CA_CloneAsSource', + 'CK_ECMQV_DERIVE_PARAMS', 'CK_CA_LKMReceiverComplete', + 'CA_InvokeServiceSinglePart', 'CK_KDF_PRF_ENCODING_SCHEME', + 'CK_C_Finalize', 'CA_MOFN_ACTIVATION_PTR', 'CK_KEY_TYPE', + 'CK_RSA_PKCS_PSS_PARAMS', 'CA_GetFunctionList', + 'CK_FUNCTION_LIST', 'CK_C_DecryptInit', + 'CK_CA_UnloadModule', 'CA_GetTPV', 'CA_OpenSession', + 'CA_InvokeServiceFinal', 'CK_CA_EncodeECParamsFromFile', + 'CA_LockClusteredSlot', 'CK_CA_RestartForContainer', + 'CK_INFO_PTR', 'CA_FactoryReset', + 'CA_SetUserContainerName', 'CK_TLS_PRF_PARAMS_PTR', + 'CA_DestroyMultipleObjects', 'CK_PBE_PARAMS', + 'CK_CA_InsertMaskedObject', 'CA_GetHSMStorageInformation', + 'CA_EncodeECPrimeParams', 'C_OpenSession', + 'CK_CA_SetUserContainerName', + 'CA_DeleteContainerWithHandle', 'CA_CloneObject', + 'CA_MOFN_ACTIVATION', 'CA_GetNumberOfAllowedContainers', + 'CA_WaitForSlotEvent', 'CA_ChoosePrimarySlot', + 'CK_CA_GetContainerCapabilitySet', + 'CK_WTLS_RANDOM_DATA_PTR', 'C_VerifyInit', + 'CK_C_CloseAllSessions', 'CK_RSA_PKCS_PSS_PARAMS_PTR', + 'CK_USER_TYPE', 'C_GetMechanismList', 'C_GetObjectSize', + 'C_GenerateRandom', 'CK_CA_DeleteContainerWithHandle', + 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR', 'CK_LOCKMUTEX', + 'CK_CA_SetHSMPolicies', 'CK_CA_GetRemotePEDVectorStatus', + 'CK_ARIA_CTR_PARAMS', 'C_GetAttributeValue', + 'CK_CA_GetTime', 'CA_OpenApplicationID', + 'CK_CA_GenerateCloningKEV', 'CK_C_DecryptUpdate', + 'CK_CAMELLIA_CTR_PARAMS', 'CA_LogVerifyFile', + 'CA_M_OF_N_STATUS', 'CK_C_CloseSession', + 'CK_EC_ENC_SCHEME', 'CK_C_INITIALIZE_ARGS_PTR', + 'CK_CA_SetLKCV', 'CK_MECHANISM_INFO_PTR', + 'CA_DuplicateMofN', 'CK_CA_GetModuleList', + 'CK_DES_CTR_PARAMS', 'CK_AES_CBC_PAD_INSERT_PARAMS_PTR', + 'C_GetFunctionStatus', 'CK_CA_PerformModuleCall', + 'CA_GetClusterState', 'CK_OTP_PARAMS_PTR', + 'CK_C_SignRecoverInit', 'CK_CA_SetExtendedTPV', + 'CK_CA_SinglePartSign', 'CK_CA_CloseSecondarySession', + 'CK_C_SignFinal', 'CA_SetDestructiveHSMPolicy', + 'CA_ResetPIN', 'CK_CA_GetHSMPolicySet', 'CK_CA_MTKRestore', + 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS', 'CK_C_Digest', + 'CK_WTLS_KEY_MAT_OUT_PTR', 'CK_AES_GMAC_PARAMS', + 'CK_OBJECT_HANDLE', 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS', + 'C_SeedRandom', 'C_WrapKey', 'CA_RestartForContainer', + 'CK_PKCS5_PBKD2_PARAMS', 'CK_MAC_GENERAL_PARAMS', + 'CK_C_VerifyUpdate', 'CK_C_Verify', 'CA_CloneMofN', + 'CK_CA_SwitchSecondarySlot', 'CK_ATTRIBUTE_TYPE', + 'CK_CA_GetTokenCertificates', + 'CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CK_CA_GetMofNStatus', 'CK_CA_GetRollbackFirmwareVersion', + 'CK_CA_WriteCommonStore', 'CA_GetPedId', + 'CA_InitIndirectToken', + 'CK_CA_GetContainerCapabilitySetting', + 'CK_CA_GenerateMofN', 'CK_C_GetMechanismInfo', + 'CK_CA_GetPrimarySlot', 'CK_C_DigestFinal', + 'CK_X9_42_DH2_DERIVE_PARAMS', 'CA_LogExternal', + 'CA_ClonePrivateKey', 'CA_ManualKCV', 'CK_EC_MAC_SCHEME', + 'CK_CA_GetTokenCertificateInfo', 'CK_CA_DeleteContainer', + 'CK_CA_GetContainerPolicySet', 'C_CancelFunction', + 'CK_HA_STATUS', 'CK_CA_OpenApplicationIDForContainer', + 'CK_C_DigestKey', 'CA_ConfigureRemotePED', 'C_Initialize', + 'C_DestroyObject', 'CK_RSA_PKCS_OAEP_PARAMS_PTR', + 'CA_DeleteContainer', 'CK_ECDH1_DERIVE_PARAMS_PTR', + 'C_InitToken', 'CK_C_WrapKey', 'CA_EncodeECChar2Params', + 'CK_CA_ActivateMofN', + 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR', + 'CA_SpRawWrite', 'C_GetSessionInfo', + 'CK_CA_InitIndirectPIN', 'CA_DeleteRemotePEDVector', + 'CK_CA_UnlockClusteredSlot', 'CK_CA_CloneModifyMofN', + 'CK_KDF_PRF_PARAMS', 'CK_CA_DestroyMultipleObjects', + 'C_GetSlotList', 'CK_ULONG', 'CK_SSL3_KEY_MAT_OUT_PTR', + 'CK_CA_GetHSMPolicySetting', 'CK_C_GenerateRandom', + 'CK_CA_ModifyUsageCount', 'CA_MTKResplit', 'CK_CHAR', + 'CK_STATE', 'CK_CA_GetHSMCapabilitySetting', + 'CK_KEY_WRAP_SET_OAEP_PARAMS', 'CA_GetPrimarySlot', + 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR', + 'CK_X9_42_DH1_DERIVE_PARAMS', 'CA_GetMofNStatus', + 'CK_C_EncryptUpdate', 'CK_DESTROYMUTEX', + 'CK_CMS_SIG_PARAMS_PTR', 'CK_CA_CheckOperationState', + 'CK_C_UnwrapKey', 'CK_CA_GetContainerList', + 'CK_WTLS_KEY_MAT_PARAMS_PTR', 'CA_MultisignValue', + 'CK_ECMQV_DERIVE_PARAMS_PTR', 'CK_CA_InitIndirectToken', + 'CA_GetTSV', 'CA_InitIndirectPIN', 'CK_CA_SetPedId', + 'CA_GenerateMofN', 'CK_CA_DeactivateMofN', 'C_DeriveKey', + 'C_Verify', 'CK_CA_Extract', 'C_DigestUpdate', + 'CK_CA_GetHSMStorageInformation', 'CA_SpRawRead', + 'CK_C_SetAttributeValue', 'CK_CA_GetHSMCapabilitySet', + 'C_SignFinal', 'CA_SIMMultiSign', 'CK_C_GenerateKey', + 'C_DecryptFinal', 'CA_UnlockClusteredSlot', + 'CK_CA_CloneAsSource', 'CK_C_GetSlotList', + 'CK_FUNCTION_LIST_PTR', 'CK_AES_CTR_PARAMS_PTR', + 'CA_FirmwareUpdate', 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE', + 'CK_USHORT_PTR', 'CA_CloseSecondarySession', + 'CK_PKCS5_PBKD2_PARAMS_PTR', 'CK_DES_CTR_PARAMS_PTR', + 'CA_ActivateMofN', 'CK_RSA_PKCS_MGF_TYPE', + 'CK_EXTRACT_PARAMS', 'CK_C_DeriveKey', 'CA_SIMInsert', + 'CK_SFNT_CA_FUNCTION_LIST', 'CK_RC5_CBC_PARAMS_PTR', + 'CK_CA_OpenApplicationID', 'CK_AES_GMAC_PARAMS_PTR', + 'CK_RC5_MAC_GENERAL_PARAMS', 'CK_CA_InvokeService', + 'CK_CAMELLIA_CTR_PARAMS_PTR', + 'CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR', + 'CA_RetrieveLicenseList', 'CA_GetHSMPolicySetting', + 'CK_SEED_CTR_PARAMS', 'CK_ResetTotalOperations', + 'CA_HALogin', 'CA_MOFN_GENERATION_PTR', + 'CK_AES_GCM_PARAMS_PTR', 'CK_C_VerifyRecoverInit', + 'CK_CA_SetContainerSize', 'CK_LKM_TOKEN_ID', + 'CK_CA_HALogin', 'CA_CloneObjectToAllSessions', + 'CA_Insert', 'CK_ECDH2_DERIVE_PARAMS_PTR', + 'CK_CA_ChoosePrimarySlot', 'CA_LogGetConfig', + 'CK_C_DecryptDigestUpdate', 'CK_SSL3_KEY_MAT_PARAMS', + 'CK_CA_LogSetConfig', 'CK_CA_IndirectLogin', + 'CK_CA_InvokeServiceAsynch', 'CA_MTKSetStorage', + 'CK_CA_WaitForSlotEvent', 'CK_OTP_SIGNATURE_INFO_PTR', + 'CA_HAAnswerMofNChallenge', 'CK_CA_InitAudit', + 'CK_SSL3_RANDOM_DATA', 'CK_WTLS_RANDOM_DATA', + 'CK_DES_CBC_ENCRYPT_DATA_PARAMS', 'CK_RC5_CBC_PARAMS', + 'CK_C_SeedRandom', 'CK_USHORT', + 'CK_CA_SetContainerPolicies', 'CK_CLUSTER_STATE', + 'CA_MTKRestore', 'CK_C_CreateObject', 'CK_TOKEN_INFO_PTR', + 'CA_SetMofN', 'CA_CloneModifyMofN', + 'CK_CA_LoadEncryptedModule', 'CK_C_DecryptFinal', + 'CK_AES_CBC_PAD_INSERT_PARAMS', 'CK_CA_SetContainerPolicy', + 'CK_ECIES_PARAMS', 'CK_CA_CloneObject', 'CA_SetTPV', + 'C_GenerateKeyPair', 'CK_SFNT_CA_FUNCTION_LIST_PTR_PTR', + 'CK_CA_MTKSetStorage', 'CKA_SIM_AUTH_FORM', + 'CK_CA_LKMInitiatorChallenge', 'CK_CA_HAActivateMofN', + 'CK_KEY_DERIVATION_STRING_DATA', 'CK_MECHANISM_PTR', + 'CK_C_SignRecover', 'CA_LKMInitiatorComplete', + 'CA_SetTokenCertificateSignature', + 'CA_GetUserContainerName', 'CK_HA_MEMBER_PTR', + 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS', + 'CK_CA_ExtractMaskedObject', 'CK_C_GetFunctionStatus', + 'CK_CA_GetContainerPolicySetting', 'CK_PRF_KDF_PARAMS', + 'CK_CA_Deactivate', 'CK_SLOT_INFO_PTR', + 'CK_X9_42_DH1_DERIVE_PARAMS_PTR', 'CK_CLUSTER_STATE_PTR', + 'CK_C_GetTokenInfo', 'CK_C_VerifyFinal', + 'CA_CheckOperationState', 'C_GetTokenInfo', 'C_Digest', + 'CA_CloneAsTarget', 'CA_SetCloningDomain', + 'CK_OTP_PARAM_TYPE', 'CA_GetUserContainerNumber', + 'CK_KEY_WRAP_SET_OAEP_PARAMS_PTR', 'CA_GetObjectUID', + 'CK_VERSION_PTR', 'CA_HAAnswerLoginChallenge', + 'CK_CA_GetSessionInfo', 'CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR', + 'C_SignEncryptUpdate', 'CA_GetHSMCapabilitySetting', + 'CK_CA_GetSecondarySlot', 'CK_CA_DuplicateMofN', + 'C_DecryptInit', 'CK_RC5_PARAMS_PTR', + 'CK_KEA_DERIVE_PARAMS', 'CK_C_DigestInit', 'CA_ModifyMofN', + 'CK_MECHANISM_TYPE_PTR', 'CA_MTKGetState', + 'CK_CA_LogExportSecret', + 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS', 'CA_InvokeServiceInit', + 'CK_XOR_BASE_DATA_KDF_PARAMS_PTR', 'CK_SESSION_INFO', + 'C_SignUpdate', 'CK_CA_CloneObjectToAllSessions', + 'C_SignInit', 'CK_MECHANISM_TYPE', + 'CK_WTLS_KEY_MAT_PARAMS', 'CA_SetKCV', + 'CK_CA_CreateContainer', 'CA_ExtractMaskedObject', + 'C_EncryptInit', 'C_DigestEncryptUpdate', 'CK_OTP_PARAMS', + 'CK_SEED_CTR_PARAMS_PTR', 'CK_KDF_PRF_PARAMS_PTR', + 'CA_GetContainerCapabilitySet', 'CK_CA_LogGetConfig', + 'C_DigestFinal', 'CK_CA_HAAnswerLoginChallenge', + 'CK_CA_LockClusteredSlot', + 'CK_CA_GetContainerStorageInformation', 'CK_ATTRIBUTE', + 'CK_CA_SetDestructiveHSMPolicies', + 'CK_RSA_PKCS_MGF_TYPE_PTR', 'CK_SKIPJACK_RELAYX_PARAMS', + 'CK_PBE_PARAMS_PTR', 'CK_MECHANISM', + 'CA_GetContainerCapabilitySetting', + 'CA_GetContainerStatus', 'CA_InvokeServiceAsynch', + 'CK_CA_CloneAsTargetInit', 'C_Encrypt', + 'CK_LKM_TOKEN_ID_S', 'CK_C_WaitForSlotEvent', + 'CK_C_SignUpdate', 'CK_CA_LogVerify', + 'CK_CA_SetApplicationID', 'CK_CA_GetTSV', + 'CK_AES_CBC_ENCRYPT_DATA_PARAMS', 'CK_ARIA_CTR_PARAMS_PTR', + 'C_EncryptFinal', 'CA_LKMReceiverComplete', + 'CK_C_DecryptVerifyUpdate', 'CK_CA_GetUserContainerNumber', + 'CK_EC_KDF_TYPE', 'CK_KEY_DERIVATION_STRING_DATA_PTR', + 'CA_InitializeRemotePEDVector', 'CA_LogVerify', + 'CA_GetFPV', 'CA_HAInit', 'C_CloseSession', + 'CA_GetHAState', 'CA_SetDestructiveHSMPolicies', + 'C_SignRecoverInit', 'CK_EC_DH_PRIMITIVE', + 'CK_CA_ManualKCV', 'CK_C_Login', 'CA_IsMofNEnabled', + 'CK_CA_InvokeServiceSinglePart', 'CA_LogGetStatus', + 'CK_CA_QueryLicense', 'CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CK_C_FindObjectsFinal', 'CK_CREATEMUTEX', + 'CK_SLOT_ID_PTR', 'CA_IsMofNRequired', + 'CK_FUNCTION_LIST_PTR_PTR', 'CA_HAGetMasterPublic', + 'CK_CA_LKMInitiatorComplete', 'CK_CA_LogEraseAll', + 'CA_CloseApplicationIDForContainer', + 'CK_CA_GenerateTokenKeys', 'CK_BYTE', + 'CK_SSL3_KEY_MAT_OUT', 'CA_SetContainerPolicies', + 'C_DecryptVerifyUpdate', 'CA_GenerateCloningKEV', + 'CA_SetHSMPolicy', 'CK_CA_GetTPV', + 'CK_CA_SinglePartDecrypt', 'CK_GetTotalOperations', + 'CK_UTF8CHAR', 'CK_CA_GetObjectHandle', 'CK_CA_Insert', + 'CK_CA_SetTokenCertificateSignature', 'CK_RV', 'CK_NOTIFY', + 'CK_CA_InitializeRemotePEDVector', 'CKCA_MODULE_INFO_PTR', + 'CK_C_FindObjects', 'C_DigestInit', + 'CA_GetContainerStorageInformation', 'CK_BYTE_PTR', + 'CA_ModifyUsageCount', 'CK_CA_TimeSync', 'CA_SetPedId', + 'CA_GetHSMPolicySet', 'CK_CA_ModifyMofN', 'C_CopyObject', + 'CK_CA_CloseApplicationID', 'CA_GetContainerPolicySetting', + 'CK_SSL3_KEY_MAT_PARAMS_PTR', 'C_VerifyUpdate', + 'CK_NOTIFICATION', 'CK_CA_LogImportSecret', + 'CA_GenerateTokenKeys', 'CK_X9_42_MQV_DERIVE_PARAMS_PTR', + 'CK_CA_SetMofN', 'CK_C_GetAttributeValue', + 'CK_CA_InvokeServiceFinal', 'CA_TimeSync', + 'CA_LKMInitiatorChallenge', 'CK_CA_ResetPIN', + 'CA_GetContainerList', 'CK_C_GetMechanismList', + 'CA_CreateLoginChallenge', 'C_EncryptUpdate', + 'CK_X9_42_DH_KDF_TYPE_PTR', + 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CK_CA_EncodeECPrimeParams', 'CK_CA_HAGetLoginChallenge', + 'CK_VOID_PTR_PTR', 'CA_MOFN_STATUS', 'CK_C_SignInit', + 'CK_C_Decrypt', 'CK_CA_CloneMofN', 'CK_SESSION_INFO_PTR', + 'CK_CA_IsMofNRequired', 'CK_CA_SIMInsert', + 'CK_C_CopyObject', 'CK_CA_CreateLoginChallenge', + 'CK_KDF_PRF_TYPE', 'CA_GenerateCloneableMofN', + 'CK_CHAR_PTR', 'C_Sign', 'C_SetPIN', 'CK_C_GetObjectSize', + 'CA_ResetDevice', 'CK_CA_GetTokenInsertionCount', + 'CK_C_DigestUpdate', 'CA_GetSessionInfo', + 'C_GetFunctionList', 'CK_CA_SetCloningDomain', + 'CA_DeactivateMofN', 'CK_C_Initialize', + 'C_GetOperationState', 'CK_C_GetSessionInfo', + 'CA_GetModuleList', 'CK_C_Encrypt', 'CK_BBOOL', + 'CK_CA_EncodeECChar2Params', 'CK_CA_GetModuleInfo', + 'C_GenerateKey', 'CK_CA_SetTPV', 'CA_GetTokenCertificates', + 'C_InitPIN', 'C_DecryptUpdate', + 'CK_SKIPJACK_PRIVATE_WRAP_PARAMS', 'CK_KIP_PARAMS_PTR', + 'CK_RC2_CBC_PARAMS', 'CK_C_GetSlotInfo', + 'CA_GetRollbackFirmwareVersion', 'CK_C_DestroyObject', + 'CK_C_GenerateKeyPair', 'CK_C_InitToken', + 'CK_CA_LKMReceiverResponse', 'CA_GetTime', + 'CA_ChooseSecondarySlot', 'CK_CA_GetUserContainerName', + 'CK_CA_MTKZeroize', 'CK_CA_GetClusterState', + 'CK_AES_CTR_PARAMS', 'CA_SetContainerSize', + 'C_SignRecover', 'CA_SetExtendedTPV', + 'CK_ECDH2_DERIVE_PARAMS', 'CA_InsertMaskedObject', + 'CA_CloneAllObjectsToSession', 'CK_ECIES_PARAMS_PTR', + 'CK_X9_42_DH2_DERIVE_PARAMS_PTR', 'CK_CA_GetPedId', + 'CA_WriteCommonStore', 'CK_CA_MTKGetState', + 'CK_CA_DeleteRemotePEDVector', 'CK_KEA_DERIVE_PARAMS_PTR', + 'CA_LogImportSecret', 'CA_SwitchSecondarySlot', + 'CK_MAC_GENERAL_PARAMS_PTR', 'CK_CA_DismantleRemotePED', + 'CK_CA_GenerateCloneableMofN', + 'CK_RC5_MAC_GENERAL_PARAMS_PTR', 'CK_PARAM_TYPE', + 'CK_C_PerformSelfTest', 'CK_CA_ClonePrivateKey', 'CK_INFO', + 'CA_GetTunnelSlotNumber', 'CA_GetContainerName', + 'CK_CA_LoadModule', 'CK_OBJECT_CLASS_PTR', + 'CK_CA_ChooseSecondarySlot', 'CK_CA_IsMofNEnabled', + 'CA_MOFN_STATUS_PTR', 'CK_RC2_PARAMS', 'CA_SetLKCV'] diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py new file mode 100755 index 0000000..b6af1b9 --- /dev/null +++ b/pycryptoki/cryptoki_helpers.py @@ -0,0 +1,210 @@ +from ctypes import CDLL +from pycryptoki.defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE +import os +import re +import sys + +def parse_chrystoki_conf(): + ''' + The autogeneration of cryptoki.py now prepends a method which sets the DLL's path to + be called every time cryptoki.py is imported. This method parses Cryptoki's configuration + file in python for the DLL's location. While originally it was desired to reuse the C code + which parses Cryptoki.conf this was not possible because Pycryptoki can only call functions + on the dll, you cannot do something like instantiate a class and then call a function on that class. + + ex: ckdemo does: + ChrystokiConfiguration conf; + char* libName = conf.LibraryFileName(); + + Option 1: + Create a new api function and make it visible in the DLL. It's not very good to put functions + that are customer visible in the API that are going to be used for testing tools. In addition + it would be necessary to store a copy of the DLL in the pycryptoki package and load this DLL + every time pycryptoki is run. This is therefore not a great option. + + Option 2: + Write a short program in C++ that compiles against luna's source code. Then python can call + this file to get the output. This would work however it create a dependency that portions of + pycryptoki must be compiled, in addition when distributing pycryptoki to the testing team it + would be necessary to distribute platform dependent code. + + Creating a compilation dependency between pycryptoki and the C code is not a good idea since + it will be necessary to make a C program in the setup for pycryptoki which increases the + complexity of the setup. + + Option 3: + Parse the file in python. + + This option was chosen because it was fairly easy to do and supported across all platforms. + It is also the simplest approach. The disadvantage to this is the configuration file may be + parsed differently in C than in python. Therefore lot of error checking was added to the parsing + process as well as printing of which DLL was found in each run of the Cryptoki library.. + ''' + + env_conf_path = os.environ.get("ChrystokiConfigurationPath") + conf_path = None + if CHRYSTOKI_DLL_FILE != None: + #Use this value for the location of the DLL + dll_path = CHRYSTOKI_DLL_FILE + print "Using DLL Path from defaults.py:" + dll_path + return dll_path + elif CHRYSTOKI_CONFIG_FILE != None: + conf_path = CHRYSTOKI_CONFIG_FILE + print "Using Chrystoki.conf location from defaults.py: " + conf_path + elif env_conf_path != None: + if 'win' in sys.platform: + env_conf_path = env_conf_path.replace('\\\\', '~').replace('~', '\\') + 'crystoki.ini' + else: + env_conf_path = os.path.join(env_conf_path, 'Chrystoki.conf') + conf_path = env_conf_path + + print "Using Chrystoki.conf location from environment variable ChrystokiConfigurationPath: " + conf_path + + if conf_path == None: + conf_path = '/etc/Chrystoki.conf' + print "No DLL Path or Chyrstoki.conf path set in defaults.py looking up DLL path in " + str(conf_path) + + print "Searching " + str(conf_path) + " for Chrystoki DLL path..." + + chrystoki_conf_text = _get_chrystoki_conf_file_text(conf_path) + + dll_path = _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text) + + print "Using DLL at location: " + dll_path + + return dll_path + +def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): + ''' + Parses the chrystoki configuration file for the section that specifies the location + of the DLL and returns the DLL location. + + @param conf_path: The path to the configuration file + @param chrystoki_conf_text: The output of the read in chrystoki configuration file + @return: The path to the chrystoki DLL + ''' + if 'win' in sys.platform: + chrystoki2_segments = re.findall("\s*\[Chrystoki2\]\s*([^\r\n]*)", chrystoki_conf_text) + + if len(chrystoki2_segments) > 1: + print chrystoki2_segments + raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + elif len(chrystoki2_segments) < 1: + print chrystoki2_segments + raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) + + chrystoki2 = chrystoki2_segments[0].split('\n') + dll_path = "" + for line in chrystoki2: + lib_nt_line = re.findall("^\s*LibNT\s*=\s*([^\n]+)", line) + + if len(lib_nt_line) > 1: + raise Exception("Found more than one LibNT pattern on the same line") + elif len(lib_nt_line) == 1: + if (dll_path != ""): + raise Exception("Found more than one instance of LibNT in the file.") + dll_path = lib_nt_line[0].strip().strip(';').strip().strip("'").strip('"') + + if dll_path == "": + raise Exception("Error finding LibNT declaration in configuration file: " + str(conf_path)) + else: + chrystoki2_segments = re.findall("\s*Chrystoki2\s*=\s*\{([^\}]*)", chrystoki_conf_text) + + if len(chrystoki2_segments) > 1: + print chrystoki2_segments + raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + elif len(chrystoki2_segments) < 1: + print chrystoki2_segments + raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) + + chrystoki2 = chrystoki2_segments[0].split('\n') + dll_path = "" + for line in chrystoki2: + is_64bits = sys.maxsize > 2**32 + if is_64bits: + lib_unix_line = re.findall("^\s*LibUNIX64\s*=\s*([^\n]+)", line) + else: + lib_unix_line = re.findall("^\s*LibUNIX\s*=\s*([^\n]+)", line) + + if len(lib_unix_line) > 1: + raise Exception("Found more than one LibUNIX pattern on the same line") + elif len(lib_unix_line) == 1: + if (dll_path != ""): + raise Exception("Found more than one instance of LibUNIX in the file.") + dll_path = lib_unix_line[0].strip().strip(';').strip().strip("'").strip('"') + + if dll_path == "": + raise Exception("Error finding LibUNIX declaration in configuration file: " + str(conf_path)) + + return dll_path + +def _get_chrystoki_conf_file_text(conf_path): + ''' + Reads in the chrystoki configuration and returns the text in the file + ''' + + try: + chrystoki_conf_file = open(conf_path, "r") + chrystoki_conf_text = chrystoki_conf_file.read(); + except IOError: + raise Exception("Could not find/read Chrystoki configuration file at path " + str(conf_path)) + return chrystoki_conf_text + +class CryptokiDLLException(Exception): + ''' + Custom exception class used to print an error when a call to the Cryptoki DLL failed. + The late binding makes debugging a little bit more difficult because function calls + have to pass through an additional layer of abstraction. This custom exception prints + out a quick message detailing exactly what function failed. + + ''' + def __init__(self, additional_info, orig_error): + self.msg = additional_info + self.original_error = orig_error + + def __str__(self): + return self.msg + "\n" + str(self.original_error) + +class CryptokiDLLSingleton(object): + ''' + A singleton class which holds an instance of the loaded cryptoki DLL object. + ''' + + _instance = None + loaded_dll_library = None + def __new__(cls, *args, **kwargs): + if not cls._instance: + cls._instance = super(CryptokiDLLSingleton, cls).__new__(cls, *args, **kwargs) + + dll_path = parse_chrystoki_conf() + cls._instance.dll_path = dll_path + if 'win' in sys.platform: + import ctypes + cls._instance.loaded_dll_library = ctypes.WinDLL(dll_path) + else: + cls._instance.loaded_dll_library = CDLL(dll_path) + return cls._instance + + def get_dll(self): + if self.loaded_dll_library == None or self.loaded_dll_library == "": + raise Exception("DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read /etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") + return self.loaded_dll_library + +def make_late_binding_function(function_name): + ''' + A function factory for creating a function that will bind to the cryptoki + DLL only when the function is called. + ''' + + def luna_function(*args, **kwargs): + late_binded_function = eval("CryptokiDLLSingleton().get_dll()." + function_name) + late_binded_function.restype = luna_function.restype + late_binded_function.argtypes = luna_function.argtypes + + try: + return_value = late_binded_function(*args, **kwargs) + return return_value + except Exception as e: + raise CryptokiDLLException("Call to '" + function_name + str(args) + str(kwargs) + "' failed.", e) + + return luna_function diff --git a/pycryptoki/daemon/__init__.py b/pycryptoki/daemon/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/pycryptoki/daemon/pycryptoki_daemon.py b/pycryptoki/daemon/pycryptoki_daemon.py new file mode 100755 index 0000000..c3ea9be --- /dev/null +++ b/pycryptoki/daemon/pycryptoki_daemon.py @@ -0,0 +1,297 @@ +''' +xmlrpc server daemon that wraps pycryptoki so pycryptoki can be used over +the network +''' +from ConfigParser import ConfigParser +from SimpleXMLRPCServer import SimpleXMLRPCServer +from StringIO import StringIO +from optparse import OptionParser +import xmlrpclib +from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ + ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ + ca_insert, ca_insert_ex +from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ + c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex +from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ + c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ + c_derive_key, c_derive_key_ex +from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ + c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ + c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ + c_create_object_ex +from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ + c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex +from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ + ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ + ca_set_container_policy, ca_set_container_policy_ex +from pycryptoki.session_management import c_initialize, c_initialize_ex, \ + c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, c_get_session_info, c_get_session_info_ex, \ + c_get_token_info, c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ + c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ + c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ + ca_create_container_ex, login, login_ex +from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex +from pycryptoki.token_management import c_init_token, c_init_token_ex, \ + c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ + c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex +from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ + ca_init_audit_ex, ca_time_sync, ca_time_sync_ex +from _ctypes import pointer +from ctypes import cast +import ctypes +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR +from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex,\ + ca_settokencertificatesignature, ca_settokencertificatesignature_ex, \ + ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ + ca_initializeremotepedvector, ca_initializeremotepedvector_ex, ca_deleteremotepedvector, \ + ca_deleteremotepedvector_ex, ca_mtkrestore, ca_mtkrestore_ex, ca_mtkresplit, \ + ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex +from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ + ca_modifyusagecount, ca_modifyusagecount_ex +from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, \ + ca_duplicatemofn_ex + +''' +All the functions the server supports +''' +pycryptoki_functions = {"c_wrap_key" : c_wrap_key, + "c_wrap_key_ex" : c_wrap_key_ex, + "c_unwrap_key" : c_unwrap_key, + "c_unwrap_key_ex" : c_unwrap_key_ex, + "c_destroy_object" : c_destroy_object, + "c_destroy_object_ex" : c_destroy_object_ex, + "c_generate_random" : c_generate_random, + "c_generate_random_ex" : c_generate_random_ex, + "c_seed_random" : c_seed_random, + "c_seed_random_ex" : c_seed_random_ex, + "c_digest" : c_digest, + "c_digest_ex" : c_digest_ex, + "c_set_ped_id" : c_set_ped_id, + "c_set_ped_id_ex" : c_set_ped_id_ex, + "c_get_ped_id" : c_get_ped_id, + "c_get_ped_id_ex" : c_get_ped_id_ex, + "ca_set_hsm_policy" : ca_set_hsm_policy, + "ca_set_hsm_policy_ex" : ca_set_hsm_policy_ex, + "ca_set_destructive_hsm_policy" : ca_set_destructive_hsm_policy, + "ca_set_destructive_hsm_policy_ex" : ca_set_destructive_hsm_policy_ex, + "ca_set_container_policy" : ca_set_container_policy, + "ca_set_container_policy_ex" : ca_set_container_policy_ex, + "c_initialize" : c_initialize, + "c_initialize_ex" : c_initialize_ex, + "c_finalize" : c_finalize, + "c_finalize_ex" : c_finalize_ex, + "c_open_session" : c_open_session, + "c_open_session_ex" : c_open_session_ex, + "login" : login, + "login_ex" : login_ex, + "c_get_session_info" : c_get_session_info, + "c_get_session_info_ex" : c_get_session_info_ex, + "c_get_token_info" : c_get_token_info, + "c_get_token_info_ex" : c_get_token_info_ex, + "c_close_session" : c_close_session, + "c_close_session_ex" : c_close_session_ex, + "c_logout" : c_logout, + "c_logout_ex" : c_logout_ex, + "c_init_pin" : c_init_pin, + "c_init_pin_ex" : c_init_pin_ex, + "ca_factory_reset" : ca_factory_reset, + "ca_factory_reset_ex" : ca_factory_reset_ex, + "c_set_pin" : c_set_pin, + "c_set_pin_ex" : c_set_pin_ex, + "c_close_all_sessions" : c_close_all_sessions, + "c_close_all_sessions_ex" : c_close_all_sessions_ex, + "ca_create_container" : ca_create_container, + "ca_create_container_ex" : ca_create_container_ex, + "c_init_token" : c_init_token, + "c_init_token_ex" : c_init_token_ex, + "c_get_mechanism_list" : c_get_mechanism_list, + "c_get_mechanism_list_ex" : c_get_mechanism_list_ex, + "c_get_mechanism_info" : c_get_mechanism_info, + "c_get_mechanism_info_ex" : c_get_mechanism_info_ex, + "get_token_by_label" : get_token_by_label, + "get_token_by_label_ex" : get_token_by_label_ex, + "ca_close_secure_token" : ca_close_secure_token, + "ca_close_secure_token" : ca_close_secure_token_ex, + "ca_open_secure_token" : ca_open_secure_token, + "ca_open_secure_token_ex" : ca_open_secure_token_ex, + "ca_extract" : ca_extract, + "ca_extract_ex" : ca_extract_ex, + "ca_insert" : ca_insert, + "ca_insert_ex" : ca_insert_ex, + "c_set_attribute_value" : c_set_attribute_value, + "c_set_attribute_value_ex" : c_set_attribute_value_ex, + "c_generate_key" : c_generate_key, + "c_generate_key_ex" : c_generate_key_ex, + "c_generate_key_pair" : c_generate_key_pair, + "c_generate_key_pair_ex" : c_generate_key_pair_ex, + "c_create_object" : c_create_object, + "c_create_object_ex" : c_create_object_ex, + "ca_get_time": ca_get_time, + "ca_get_time_ex": ca_get_time_ex, + "ca_init_audit": ca_init_audit, + "ca_init_audit_ex": ca_init_audit_ex, + "ca_time_sync": ca_time_sync, + "ca_time_sync_ex": ca_time_sync_ex, + "c_performselftest" : c_performselftest, + "c_performselftest_ex" : c_performselftest_ex, + "ca_settokencertificatesignature" : ca_settokencertificatesignature, + "ca_settokencertificatesignature_ex" : ca_settokencertificatesignature_ex, + "ca_hainit" : ca_hainit, + "ca_hainit_ex" : ca_hainit_ex, + "ca_createloginchallenge" : ca_createloginchallenge, + "ca_createloginchallenge_ex" : ca_createloginchallenge_ex, + "ca_initializeremotepedvector" : ca_initializeremotepedvector, + "ca_initializeremotepedvector_ex" : ca_initializeremotepedvector_ex, + "ca_deleteremotepedvector" : ca_deleteremotepedvector, + "ca_deleteremotepedvector_ex" : ca_deleteremotepedvector_ex, + "ca_mtkrestore" : ca_mtkrestore, + "ca_mtkrestore_ex" : ca_mtkrestore_ex, + "ca_mtkresplit" : ca_mtkresplit, + "ca_mtkresplit_ex" : ca_mtkresplit_ex, + "ca_mtkzeroize" : ca_mtkzeroize, + "ca_mtkzeroize_ex" : ca_mtkzeroize_ex, + "ca_generatemofn" : ca_generatemofn, + "ca_generatemofn_ex" : ca_generatemofn_ex, + "ca_modifyusagecount" : ca_modifyusagecount, + "ca_modifyusagecount_ex" : ca_modifyusagecount_ex, + "ca_clonemofn" : ca_clonemofn, + "ca_clonemofn_ex" : ca_clonemofn_ex, + "ca_duplicatemofn" : ca_duplicatemofn, + "ca_duplicatemofn_ex" : ca_duplicatemofn_ex, + } + +''' +Functions with arguments/return values that need specialized +serialization/deserialization +''' +functions_needing_serialization = { + "c_find_objects" : c_find_objects, + "c_find_objects_ex" : c_find_objects_ex, + "c_get_attribute_value" : c_get_attribute_value, + "c_get_attribute_value_ex" : c_get_attribute_value_ex, + "c_sign": c_sign, + "c_sign_ex": c_sign_ex, + "c_encrypt": c_encrypt, + "c_encrypt_ex": c_encrypt_ex, + "c_verify" : c_verify, + "c_verify_ex" : c_verify_ex, + "c_derive_key" : c_derive_key, + "c_derive_key_ex" : c_derive_key_ex, + "c_decrypt_ex" : c_decrypt_ex, + "c_decrypt" : c_decrypt + } + + +def initialize_server(ip, port): + print "Initializing Server" + server = SimpleXMLRPCServer((ip, port)) + server.logRequests = 0 + + #Dynamically add functions to server + for key, value in pycryptoki_functions.iteritems(): + server.register_function(value, key) + + #For functions that need better serialization, do it + for key, value in functions_needing_serialization.iteritems(): + server.register_function(eval(key + "_serialize"), key) + + return server + + +def serialize_dict(dictionary): + ''' + Helper function to convert a dictionary with to + for xmlrpc + ''' + serialized_dictionary = {} + for key, value in dictionary.iteritems(): + serialized_dictionary[str(key)] = value + return serialized_dictionary + +def c_get_attribute_value_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + ret, dictionary = c_get_attribute_value(h_session, h_object, template) + return ret, serialize_dict(dictionary) + +def c_get_attribute_value_ex_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + dictionary = c_get_attribute_value_ex(h_session, h_object, template) + return serialize_dict(dictionary) + +def c_find_objects_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + ret, dictionary = c_find_objects(h_session, h_object, template) + return ret, serialize_dict(dictionary) + +def c_find_objects_ex_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + dictionary = c_find_objects_ex(h_session, h_object, template) + return serialize_dict(dictionary) + +def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) + +def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) + +def c_sign_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + ret, signature = c_sign(h_session, sign_flavor, data_to_sign, h_key, mech) + return ret, xmlrpclib.Binary(signature) + +def c_sign_ex_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + signature = c_sign_ex(h_session, sign_flavor, data_to_sign, h_key, mech) + return xmlrpclib.Binary(signature) + +def c_encrypt_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + ret, enc_data = c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech) + return ret, xmlrpclib.Binary(enc_data) + +def c_encrypt_ex_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + enc_data = c_encrypt_ex(h_session, encryption_flavor, h_key, data_to_encrypt, mech) + return xmlrpclib.Binary(enc_data) + +def c_verify_serialize( h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + return c_verify(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) + +def c_verify_ex_serialize(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + return c_verify_ex(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) + +def c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + return c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) + +def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + return c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) + +if __name__ == '__main__': + #Setup argument parser + resources_config_parser = ConfigParser(); + parser = OptionParser() + parser.add_option("-i", "--ip_address", dest="i", + help="pycryptoki daemon IP address", metavar="") + parser.add_option("-p", "--port", dest="p", + help="pycryptoki daemon IP port", metavar="") + (options, args) = parser.parse_args() + + #Default arguments + ip = options.i if options.i != None else 'localhost' + port = int( options.p if options.p != None else '8001') + print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) + + server = initialize_server(ip, port) + + # run until we die + print "Starting Server" + server.serve_forever() diff --git a/pycryptoki/daemon/pycryptoki_daemon.py.bak b/pycryptoki/daemon/pycryptoki_daemon.py.bak new file mode 100755 index 0000000..fdc2be4 --- /dev/null +++ b/pycryptoki/daemon/pycryptoki_daemon.py.bak @@ -0,0 +1,295 @@ +''' +xmlrpc server daemon that wraps pycryptoki so pycryptoki can be used over +the network +''' +from ConfigParser import ConfigParser +from SimpleXMLRPCServer import SimpleXMLRPCServer +from StringIO import StringIO +from optparse import OptionParser +import xmlrpclib +from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ + ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ + ca_insert, ca_insert_ex +from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ + c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex +from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ + c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ + c_derive_key, c_derive_key_ex +from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ + c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ + c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ + c_create_object_ex +from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ + c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex +from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ + ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ + ca_set_container_policy, ca_set_container_policy_ex +from pycryptoki.session_management import c_initialize, c_initialize_ex, \ + c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, c_get_token_info, \ + c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ + c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ + c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ + ca_create_container_ex, login, login_ex +from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex +from pycryptoki.token_management import c_init_token, c_init_token_ex, \ + c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ + c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex +from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ + ca_init_audit_ex, ca_time_sync, ca_time_sync_ex +from _ctypes import pointer +from ctypes import cast +import ctypes +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR +from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex,\ + ca_settokencertificatesignature, ca_c_settokencertificatesignature_ex, \ + ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ + ca_initializeremotepedvector, ca_initializeremotepedvector_ex, ca_deleteremotepedvector, \ + ca_deleteremotepedvector_ex, ca_mtkrestore, ca_mtkrestore_ex, ca_mtkresplit, \ + ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex +from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ + ca_modifyusagecount, ca_modifyusagecount_ex +from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, \ + ca_duplicatemofn_ex + +''' +All the functions the server supports +''' +pycryptoki_functions = {"c_wrap_key" : c_wrap_key, + "c_wrap_key_ex" : c_wrap_key_ex, + "c_unwrap_key" : c_unwrap_key, + "c_unwrap_key_ex" : c_unwrap_key_ex, + "c_destroy_object" : c_destroy_object, + "c_destroy_object_ex" : c_destroy_object_ex, + "c_generate_random" : c_generate_random, + "c_generate_random_ex" : c_generate_random_ex, + "c_seed_random" : c_seed_random, + "c_seed_random_ex" : c_seed_random_ex, + "c_digest" : c_digest, + "c_digest_ex" : c_digest_ex, + "c_set_ped_id" : c_set_ped_id, + "c_set_ped_id_ex" : c_set_ped_id_ex, + "c_get_ped_id" : c_get_ped_id, + "c_get_ped_id_ex" : c_get_ped_id_ex, + "ca_set_hsm_policy" : ca_set_hsm_policy, + "ca_set_hsm_policy_ex" : ca_set_hsm_policy_ex, + "ca_set_destructive_hsm_policy" : ca_set_destructive_hsm_policy, + "ca_set_destructive_hsm_policy_ex" : ca_set_destructive_hsm_policy_ex, + "ca_set_container_policy" : ca_set_container_policy, + "ca_set_container_policy_ex" : ca_set_container_policy_ex, + "c_initialize" : c_initialize, + "c_initialize_ex" : c_initialize_ex, + "c_finalize" : c_finalize, + "c_finalize_ex" : c_finalize_ex, + "c_open_session" : c_open_session, + "c_open_session_ex" : c_open_session_ex, + "login" : login, + "login_ex" : login_ex, + "c_get_token_info" : c_get_token_info, + "c_get_token_info_ex" : c_get_token_info_ex, + "c_close_session" : c_close_session, + "c_close_session_ex" : c_close_session_ex, + "c_logout" : c_logout, + "c_logout_ex" : c_logout_ex, + "c_init_pin" : c_init_pin, + "c_init_pin_ex" : c_init_pin_ex, + "ca_factory_reset" : ca_factory_reset, + "ca_factory_reset_ex" : ca_factory_reset_ex, + "c_set_pin" : c_set_pin, + "c_set_pin_ex" : c_set_pin_ex, + "c_close_all_sessions" : c_close_all_sessions, + "c_close_all_sessions_ex" : c_close_all_sessions_ex, + "ca_create_container" : ca_create_container, + "ca_create_container_ex" : ca_create_container_ex, + "c_init_token" : c_init_token, + "c_init_token_ex" : c_init_token_ex, + "c_get_mechanism_list" : c_get_mechanism_list, + "c_get_mechanism_list_ex" : c_get_mechanism_list_ex, + "c_get_mechanism_info" : c_get_mechanism_info, + "c_get_mechanism_info_ex" : c_get_mechanism_info_ex, + "get_token_by_label" : get_token_by_label, + "get_token_by_label_ex" : get_token_by_label_ex, + "ca_close_secure_token" : ca_close_secure_token, + "ca_close_secure_token" : ca_close_secure_token_ex, + "ca_open_secure_token" : ca_open_secure_token, + "ca_open_secure_token_ex" : ca_open_secure_token_ex, + "ca_extract" : ca_extract, + "ca_extract_ex" : ca_extract_ex, + "ca_insert" : ca_insert, + "ca_insert_ex" : ca_insert_ex, + "c_set_attribute_value" : c_set_attribute_value, + "c_set_attribute_value_ex" : c_set_attribute_value_ex, + "c_generate_key" : c_generate_key, + "c_generate_key_ex" : c_generate_key_ex, + "c_generate_key_pair" : c_generate_key_pair, + "c_generate_key_pair_ex" : c_generate_key_pair_ex, + "c_create_object" : c_create_object, + "c_create_object_ex" : c_create_object_ex, + "ca_get_time": ca_get_time, + "ca_get_time_ex": ca_get_time_ex, + "ca_init_audit": ca_init_audit, + "ca_init_audit_ex": ca_init_audit_ex, + "ca_time_sync": ca_time_sync, + "ca_time_sync_ex": ca_time_sync_ex, + "c_performselftest" : c_performselftest, + "c_performselftest_ex" : c_performselftest_ex, + "ca_settokencertificatesignature" : ca_settokencertificatesignature, + "ca_settokencertificatesignature_ex" : ca_c_settokencertificatesignature_ex, + "ca_hainit" : ca_hainit, + "ca_hainit_ex" : ca_hainit_ex, + "ca_createloginchallenge" : ca_createloginchallenge, + "ca_createloginchallenge_ex" : ca_createloginchallenge_ex, + "ca_initializeremotepedvector" : ca_initializeremotepedvector, + "ca_initializeremotepedvector_ex" : ca_initializeremotepedvector_ex, + "ca_deleteremotepedvector" : ca_deleteremotepedvector, + "ca_deleteremotepedvector_ex" : ca_deleteremotepedvector_ex, + "ca_mtkrestore" : ca_mtkrestore, + "ca_mtkrestore_ex" : ca_mtkrestore_ex, + "ca_mtkresplit" : ca_mtkresplit, + "ca_mtkresplit_ex" : ca_mtkresplit_ex, + "ca_mtkzeroize" : ca_mtkzeroize, + "ca_mtkzeroize_ex" : ca_mtkzeroize_ex, + "ca_generatemofn" : ca_generatemofn, + "ca_generatemofn_ex" : ca_generatemofn_ex, + "ca_modifyusagecount" : ca_modifyusagecount, + "ca_modifyusagecount_ex" : ca_modifyusagecount_ex, + "ca_clonemofn" : ca_clonemofn, + "ca_clonemofn_ex" : ca_clonemofn_ex, + "ca_duplicatemofn" : ca_duplicatemofn, + "ca_duplicatemofn_ex" : ca_duplicatemofn_ex, + } + +''' +Functions with arguments/return values that need specialized +serialization/deserialization +''' +functions_needing_serialization = { + "c_find_objects" : c_find_objects, + "c_find_objects_ex" : c_find_objects_ex, + "c_get_attribute_value" : c_get_attribute_value, + "c_get_attribute_value_ex" : c_get_attribute_value_ex, + "c_sign": c_sign, + "c_sign_ex": c_sign_ex, + "c_encrypt": c_encrypt, + "c_encrypt_ex": c_encrypt_ex, + "c_verify" : c_verify, + "c_verify_ex" : c_verify_ex, + "c_derive_key" : c_derive_key, + "c_derive_key_ex" : c_derive_key_ex, + "c_decrypt_ex" : c_decrypt_ex, + "c_decrypt" : c_decrypt + } + + +def initialize_server(ip, port): + print "Initializing Server" + server = SimpleXMLRPCServer((ip, port)) + server.logRequests = 0 + + #Dynamically add functions to server + for key, value in pycryptoki_functions.iteritems(): + server.register_function(value, key) + + #For functions that need better serialization, do it + for key, value in functions_needing_serialization.iteritems(): + server.register_function(eval(key + "_serialize"), key) + + return server + + +def serialize_dict(dictionary): + ''' + Helper function to convert a dictionary with to + for xmlrpc + ''' + serialized_dictionary = {} + for key, value in dictionary.iteritems(): + serialized_dictionary[str(key)] = value + return serialized_dictionary + +def c_get_attribute_value_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + ret, dictionary = c_get_attribute_value(h_session, h_object, template) + return ret, serialize_dict(dictionary) + +def c_get_attribute_value_ex_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + dictionary = c_get_attribute_value_ex(h_session, h_object, template) + return serialize_dict(dictionary) + +def c_find_objects_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + ret, dictionary = c_find_objects(h_session, h_object, template) + return ret, serialize_dict(dictionary) + +def c_find_objects_ex_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + dictionary = c_find_objects_ex(h_session, h_object, template) + return serialize_dict(dictionary) + +def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) + +def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) + +def c_sign_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + ret, signature = c_sign(h_session, sign_flavor, data_to_sign, h_key, mech) + return ret, xmlrpclib.Binary(signature) + +def c_sign_ex_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + signature = c_sign_ex(h_session, sign_flavor, data_to_sign, h_key, mech) + return xmlrpclib.Binary(signature) + +def c_encrypt_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + ret, enc_data = c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech) + return ret, xmlrpclib.Binary(enc_data) + +def c_encrypt_ex_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + enc_data = c_encrypt_ex(h_session, encryption_flavor, h_key, data_to_encrypt, mech) + return xmlrpclib.Binary(enc_data) + +def c_verify_serialize( h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + return c_verify(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) + +def c_verify_ex_serialize(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + return c_verify_ex(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) + +def c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + return c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) + +def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + return c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) + +if __name__ == '__main__': + #Setup argument parser + resources_config_parser = ConfigParser(); + parser = OptionParser() + parser.add_option("-i", "--ip_address", dest="i", + help="pycryptoki daemon IP address", metavar="") + parser.add_option("-p", "--port", dest="p", + help="pycryptoki daemon IP port", metavar="") + (options, args) = parser.parse_args() + + #Default arguments + ip = options.i if options.i != None else 'localhost' + port = int( options.p if options.p != None else '8001') + print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) + + server = initialize_server(ip, port) + + # run until we die + print "Starting Server" + server.serve_forever() diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py new file mode 100755 index 0000000..5dd301b --- /dev/null +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -0,0 +1,312 @@ +""" +This is the rpy +""" + +import logging +from optparse import OptionParser +from _ctypes import pointer +from ctypes import cast +import ctypes + +import rpyc +import pycryptoki + +from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ + ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ + ca_insert, ca_insert_ex +from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ + c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex +from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ + c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ + c_derive_key, c_derive_key_ex, c_copy_object_ex, c_copy_object +from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ + c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ + c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ + c_create_object_ex, c_digestkey, c_digestkey_ex +from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ + c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex +from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ + ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ + ca_set_container_policy, ca_set_container_policy_ex +from pycryptoki.session_management import c_initialize, c_initialize_ex, \ + c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, \ + c_get_session_info, c_get_session_info_ex, c_get_token_info, \ + c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ + c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ + c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ + ca_create_container_ex, login, login_ex, ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID_ex, \ + ca_closeapplicationID, ca_restart, ca_restart_ex, ca_delete_container_with_handle_ex, \ + ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex +from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex +from pycryptoki.token_management import c_init_token, c_init_token_ex, \ + c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ + c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex +from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ + ca_init_audit_ex, ca_time_sync, ca_time_sync_ex +from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex, \ + ca_settokencertificatesignature, ca_settokencertificatesignature_ex, \ + ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ + ca_initializeremotepedvector, ca_initializeremotepedvector_ex, \ + ca_deleteremotepedvector, ca_deleteremotepedvector_ex, ca_mtkrestore, \ + ca_mtkrestore_ex, ca_mtkresplit, ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex +from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ + ca_modifyusagecount, ca_modifyusagecount_ex +from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, \ + ca_duplicatemofn, ca_duplicatemofn_ex + +from pycryptoki.cryptoki import * + + +logger = logging.getLogger(__name__) + + +class PycryptokiService(rpyc.SlaveService): + """ + This is the core service to expose to the daemon. + Add in a static method preceded by 'exposed_' and it'll be visible to anything + connecting to the daemon. + + If you're working with pointers, you'll need to create the pointer in a function here + rather than passing in a pointer from the client (pointers getting pickled makes no sense). + + """ + def _rpyc_getattr(self, name): + if name.startswith("exposed_"): + name = name + elif name in pycryptoki.cryptoki.__all__: + return getattr(pycryptoki.cryptoki, name) + else: + name = "exposed_" + name + return getattr(self, name) + + #encryption.py + exposed_c_wrap_key = staticmethod(c_wrap_key) + exposed_c_wrap_key_ex = staticmethod(c_wrap_key_ex) + exposed_c_unwrap_key = staticmethod(c_unwrap_key) + exposed_c_unwrap_key_ex = staticmethod(c_unwrap_key_ex) + exposed_c_encrypt = staticmethod(c_encrypt) + exposed_c_encrypt_ex = staticmethod(c_encrypt_ex) + exposed_c_decrypt = staticmethod(c_decrypt) + exposed_c_decrypt_ex = staticmethod(c_decrypt_ex) + + #sign_verify.py + exposed_c_sign = staticmethod(c_sign) + exposed_c_sign_ex = staticmethod(c_sign_ex) + exposed_c_verify = staticmethod(c_verify) + exposed_c_verify_ex = staticmethod(c_verify_ex) + + #token_management.py + exposed_c_init_token = staticmethod(c_init_token) + exposed_c_init_token_ex = staticmethod(c_init_token_ex) + exposed_c_get_mechanism_list = staticmethod(c_get_mechanism_list) + exposed_c_get_mechanism_list_ex = staticmethod(c_get_mechanism_list_ex) + exposed_c_get_mechanism_info = staticmethod(c_get_mechanism_info) + exposed_c_get_mechanism_info_ex = staticmethod(c_get_mechanism_info_ex) + + #session_management.py + exposed_c_initialize = staticmethod(c_initialize) + exposed_c_initialize_ex = staticmethod(c_initialize_ex) + exposed_c_finalize = staticmethod(c_finalize) + exposed_c_finalize_ex = staticmethod(c_finalize_ex) + exposed_c_open_session = staticmethod(c_open_session) + exposed_c_open_session_ex = staticmethod(c_open_session_ex) + exposed_login = staticmethod(login) + exposed_login_ex = staticmethod(login_ex) + exposed_c_get_session_info = staticmethod(c_get_session_info) + exposed_c_get_session_info_ex = staticmethod(c_get_session_info_ex) + exposed_c_get_token_info = staticmethod(c_get_token_info) + exposed_c_get_token_info_ex = staticmethod(c_get_token_info_ex) + exposed_c_close_session = staticmethod(c_close_session) + exposed_c_close_session_ex = staticmethod(c_close_session_ex) + exposed_c_logout = staticmethod(c_logout) + exposed_c_logout_ex = staticmethod(c_logout_ex) + exposed_c_set_pin = staticmethod(c_set_pin) + exposed_c_set_pin_ex = staticmethod(c_set_pin_ex) + exposed_c_init_pin = staticmethod(c_init_pin) + exposed_c_init_pin_ex = staticmethod(c_init_pin_ex) + exposed_ca_factory_reset = staticmethod(ca_factory_reset) + exposed_ca_factory_reset_ex = staticmethod(ca_factory_reset_ex) + exposed_get_token_by_label = staticmethod(get_token_by_label) + exposed_get_token_by_label_ex = staticmethod(get_token_by_label_ex) + exposed_ca_close_secure_token = staticmethod(ca_close_secure_token) + exposed_ca_close_secure_token_ex = staticmethod(ca_close_secure_token_ex) + exposed_ca_open_secure_token = staticmethod(ca_open_secure_token) + exposed_ca_open_secure_token_ex = staticmethod(ca_open_secure_token_ex) + exposed_c_close_all_sessions = staticmethod(c_close_all_sessions) + exposed_c_close_all_sessions_ex = staticmethod(c_close_all_sessions_ex) + exposed_ca_create_container = staticmethod(ca_create_container) + exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) + exposed_ca_openapplicationID_ex = staticmethod(ca_openapplicationID_ex) + exposed_ca_openapplicationID = staticmethod(ca_openapplicationID) + exposed_ca_closeapplicationID_ex = staticmethod(ca_closeapplicationID_ex) + exposed_ca_closeapplicationID = staticmethod(ca_closeapplicationID) + exposed_ca_setapplicationID_ex = staticmethod(ca_setapplicationID_ex) + exposed_ca_setapplicationID = staticmethod(ca_setapplicationID) + exposed_ca_restart_ex = staticmethod(ca_restart_ex) + exposed_ca_restart = staticmethod(ca_restart) + exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) + exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) + + #policy_management.py + exposed_ca_set_hsm_policy = staticmethod(ca_set_hsm_policy) + exposed_ca_set_hsm_policy_ex = staticmethod(ca_set_hsm_policy_ex) + exposed_ca_set_destructive_hsm_policy = staticmethod(ca_set_destructive_hsm_policy) + exposed_ca_set_destructive_hsm_policy_ex = staticmethod(ca_set_destructive_hsm_policy_ex) + exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) + exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) + + #object_attr_lookup.py + exposed_c_find_objects = staticmethod(c_find_objects) + exposed_c_find_objects_ex = staticmethod(c_find_objects_ex) + exposed_c_get_attribute_value = staticmethod(c_get_attribute_value) + exposed_c_get_attribute_value_ex = staticmethod(c_get_attribute_value_ex) + exposed_c_set_attribute_value = staticmethod(c_set_attribute_value) + exposed_c_set_attribute_value_ex = staticmethod(c_set_attribute_value_ex) + + #misc.py + exposed_c_generate_random = staticmethod(c_generate_random) + exposed_c_generate_random_ex = staticmethod(c_generate_random_ex) + exposed_c_seed_random = staticmethod(c_seed_random) + exposed_c_seed_random_ex = staticmethod(c_seed_random_ex) + exposed_c_digest = staticmethod(c_digest) + exposed_c_digest_ex = staticmethod(c_digest_ex) + exposed_c_set_ped_id = staticmethod(c_set_ped_id) + exposed_c_set_ped_id_ex = staticmethod(c_set_ped_id_ex) + exposed_c_get_ped_id = staticmethod(c_get_ped_id) + exposed_c_get_ped_id_ex = staticmethod(c_get_ped_id_ex) + exposed_c_create_object = staticmethod(c_create_object) + exposed_c_create_object_ex = staticmethod(c_create_object_ex) + exposed_c_digest_key = staticmethod(c_digestkey) + exposed_c_digest_key_ex = staticmethod(c_digestkey_ex) + + #key_generator.py + exposed_c_generate_key = staticmethod(c_generate_key) + exposed_c_generate_key_ex = staticmethod(c_generate_key_ex) + exposed_c_generate_key_pair = staticmethod(c_generate_key_pair) + exposed_c_generate_key_pair_ex = staticmethod(c_generate_key_pair_ex) + exposed_c_destroy_object = staticmethod(c_destroy_object) + exposed_c_destroy_object_ex = staticmethod(c_destroy_object_ex) + exposed_c_copy_object = staticmethod(c_copy_object) + exposed_c_copy_object_ex = staticmethod(c_copy_object_ex) + + #backup.py + exposed_ca_extract = staticmethod(ca_extract) + exposed_ca_extract_ex = staticmethod(ca_extract_ex) + exposed_ca_insert = staticmethod(ca_insert) + exposed_ca_insert_ex = staticmethod(ca_insert_ex) + + #audit_handling.py + exposed_ca_get_time = staticmethod(ca_get_time) + exposed_ca_get_time_ex = staticmethod(ca_get_time_ex) + exposed_ca_init_audit = staticmethod(ca_init_audit) + exposed_ca_init_audit_ex = staticmethod(ca_init_audit_ex) + exposed_ca_time_sync = staticmethod(ca_time_sync) + exposed_ca_time_sync_ex = staticmethod(ca_time_sync_ex) + + #hsm_management.py + exposed_c_performselftest = staticmethod(c_performselftest) + exposed_c_performselftest_ex = staticmethod(c_performselftest_ex) + exposed_ca_settokencertificatesignature = staticmethod(ca_settokencertificatesignature) + exposed_ca_settokencertificatesignature_ex = staticmethod(ca_settokencertificatesignature_ex) + exposed_ca_hainit = staticmethod(ca_hainit) + exposed_ca_hainit_ex = staticmethod(ca_hainit_ex) + exposed_ca_createloginchallenge = staticmethod(ca_createloginchallenge) + exposed_ca_createloginchallenge_ex = staticmethod(ca_createloginchallenge_ex) + exposed_ca_initializeremotepedvector = staticmethod(ca_initializeremotepedvector) + exposed_ca_initializeremotepedvector_ex = staticmethod(ca_initializeremotepedvector_ex) + exposed_ca_deleteremotepedvector = staticmethod(ca_deleteremotepedvector) + exposed_ca_deleteremotepedvector_ex = staticmethod(ca_deleteremotepedvector_ex) + exposed_ca_mtkrestore = staticmethod(ca_mtkrestore) + exposed_ca_mtkrestore_ex = staticmethod(ca_mtkrestore_ex) + exposed_ca_mtkresplit = staticmethod(ca_mtkresplit) + exposed_ca_mtkresplit_ex = staticmethod(ca_mtkresplit_ex) + exposed_ca_mtkzeroize = staticmethod(ca_mtkzeroize) + exposed_ca_mtkzeroize_ex = staticmethod(ca_mtkzeroize_ex) + + #key_management.py + exposed_ca_generatemofn = staticmethod(ca_generatemofn) + exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) + exposed_ca_modifyusagecount = staticmethod(ca_modifyusagecount) + exposed_ca_modifyusagecount_ex = staticmethod(ca_modifyusagecount_ex) + + #key_usage.py + exposed_ca_clonemofn = staticmethod(ca_clonemofn) + exposed_ca_clonemofn_ex = staticmethod(ca_clonemofn_ex) + exposed_ca_duplicatemofn = staticmethod(ca_duplicatemofn) + exposed_ca_duplicatemofn_ex = staticmethod(ca_duplicatemofn_ex) + + @staticmethod + def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): + """ + #key_generator.py + + Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side + because it involves pointers. + """ + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) + + @staticmethod + def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): + """ + #key_generator.py + + Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side + because it involves pointers. + """ + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) + + +if __name__ == '__main__': + from rpyc.utils.server import ThreadedServer + + parser = OptionParser() + parser.add_option("-i", "--ip_address", dest="i", + help="pycryptoki daemon IP address", metavar="") + parser.add_option("-p", "--port", dest="p", + help="pycryptoki daemon IP port", metavar="") + (options, args) = parser.parse_args() + + #Default arguments + ip = options.i if options.i != None else 'localhost' + port = int(options.p if options.p != None else '8001') + print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) + + t = ThreadedServer(PycryptokiService, + hostname=ip, + port=port, + logger=logger, + protocol_config={'allow_public_attrs': True, + 'allow_all_attrs': True, + 'allow_getattr': True, + 'allow_setattr': True, + 'allow_delattr': True}) + print "Starting Server" + t.start() + + + + + + + + + + + + + + diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py new file mode 100755 index 0000000..50945d7 --- /dev/null +++ b/pycryptoki/default_templates.py @@ -0,0 +1,857 @@ +""" +File containing a number of templates taken from CKDemo and manually converted into python format. +See the attributes.py file for methods to convert them into the proper C format. +""" + +from defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ + CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ + CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ + CKK_DES2, CKK_DES3, CKK_CAST3, CKK_GENERIC_SECRET, CKA_MODIFIABLE, \ + CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ + CKA_VALUE_BITS, CKK_CAST5, CKK_RC2, CKK_RC4, CKK_RC5, CKA_ECDSA_PARAMS, CKK_AES, \ + CKK_SEED, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, CKK_ARIA, CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ + CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ + CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, CKM_ARIA_KEY_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN, \ + CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN, \ + CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, \ + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, \ + CKM_SHA1_RSA_PKCS, CKM_SHA224_RSA_PKCS, \ + CKM_SHA256_RSA_PKCS, CKM_SHA384_RSA_PKCS, CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS_PSS, \ + CKM_SHA1_RSA_PKCS_PSS, CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, \ + CKM_SHA384_RSA_PKCS_PSS, CKM_SHA512_RSA_PKCS_PSS, CKM_RSA_X9_31_KEY_PAIR_GEN, \ + CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31, CKM_SHA224_RSA_X9_31, CKM_SHA256_RSA_X9_31, \ + CKM_SHA384_RSA_X9_31, CKM_SHA512_RSA_X9_31, CKM_RSA_PKCS_OAEP, CKM_DSA_KEY_PAIR_GEN, \ + CKM_DSA, CKM_DSA_SHA1, CKM_DSA_SHA224, CKM_DSA_SHA256, CKM_DSA_PARAMETER_GEN, \ + CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, CKM_ECDSA_SHA256, \ + CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, \ + CKM_SHA_1_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, \ + CKM_ECDSA +from pycryptoki.defines import CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE, CKC_X_509, \ + CKA_SUBJECT, CKA_VALUE, CKO_DATA, CKA_TOKEN +import copy + +CKM_DES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 8, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES Key"} + +CKM_DES_UNWRAP_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_SIGN : True, + CKA_WRAP : True, + CKA_DERIVE : True, + CKA_LABEL : "DES Key"} + + +CKM_DES2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES2, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES2 Key"} +CKM_DES3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES3, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 24, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES3 Key"} + +CKM_CAST3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_CAST3, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 8, #1-8 + CKA_EXTRACTABLE :True, + CKA_LABEL : "CAST3 Key"} + +CKM_GENERIC_SECRET_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_GENERIC_SECRET, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "GENERIC SECRET Key"} + +CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_MODIFIABLE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT : 3, #byte + CKA_LABEL : "RSA Public Key"} +CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_MODIFIABLE : True, + CKA_EXTRACTABLE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_LABEL : "RSA Private Key"} + +dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, + 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, 0x6d, 0x1f, 0xf2, + 0x70, 0xf1, 0x59, 0x78, 0x5d, 0x75, 0x69, 0x21, 0xdb, 0xff, 0x97, 0x73, 0xae, 0x08, 0x48, 0x3b, + 0x66, 0x2f, 0xc0, 0x7d, 0xf7, 0x51, 0x2f, 0xf6, 0x8b, 0x2e, 0x55, 0x65, 0xfd, 0x79, 0x82, 0xe2, + 0x0c, 0x24, 0x48, 0x32, 0xab, 0xa1, 0x21, 0xcc, 0x07, 0x99, 0xcc, 0x09, 0xf2, 0xd5, 0x41, 0x4d, + 0x5f, 0x39, 0x66, 0x21, 0x13, 0x65, 0xf5, 0x1b, 0x83, 0xe9, 0xff, 0xcc, 0xcb, 0x3d, 0x88, 0xcd, + 0xf2, 0x38, 0xf7, 0xc2, 0x73, 0x91, 0x31, 0xca, 0x7a, 0xad, 0xff, 0x66, 0x2f, 0xec, 0x1f, 0xb0, + 0xe1, 0xd3, 0x11, 0xa4, 0x04, 0x26, 0x03, 0x76, 0xfd, 0x01, 0x1f, 0xe0, 0x0d, 0x02, 0x04, 0xc3] +dsa_sub_prime_1024_160 = [0xd3, 0x80, 0x73, 0x53, 0xb5, 0x1c, 0x5f, 0x71, 0xb2, 0x2a, 0xc3, 0xd0, 0xc7, 0xe3, 0x94, 0x14, + 0x8f, 0xce, 0xdc, 0x61] +dsa_base_1024_160 = [0x42, 0xe3, 0x77, 0x8e, 0x6e, 0xc3, 0x1b, 0x0d, 0xb0, 0x7a, 0x6b, 0x37, 0x0d, 0x7f, 0xb6, 0xfb, + 0x4a, 0x0b, 0xca, 0x6d, 0xea, 0xac, 0x37, 0x1f, 0x6a, 0xdb, 0xcb, 0xeb, 0xa3, 0x8d, 0xdf, 0x76, + 0xa4, 0x7c, 0x3c, 0x3d, 0x79, 0x27, 0x6a, 0x0e, 0x57, 0x9c, 0xe4, 0xe3, 0x47, 0x18, 0x0f, 0xd9, + 0xb4, 0xad, 0x46, 0x1d, 0x6c, 0xf0, 0xea, 0xc5, 0x1f, 0xb0, 0x8c, 0xf4, 0x52, 0xf6, 0x24, 0x57, + 0x00, 0x51, 0xe5, 0x18, 0xa7, 0x5a, 0x5b, 0xb9, 0xc3, 0x57, 0x8a, 0x14, 0xfd, 0x4f, 0x27, 0xf7, + 0x95, 0xb2, 0x2a, 0xce, 0xa6, 0x2b, 0x1f, 0xdf, 0x10, 0x32, 0xc1, 0x26, 0x6d, 0xa0, 0x81, 0xc7, + 0xfb, 0x99, 0xc4, 0x26, 0x66, 0x26, 0x58, 0x70, 0x93, 0xfd, 0x38, 0x16, 0x17, 0x23, 0x8e, 0xe1, + 0x57, 0x8f, 0xc3, 0x25, 0x54, 0x8d, 0xc1, 0xc0, 0x8e, 0x5f, 0x93, 0x22, 0xc3, 0xb1, 0x20, 0x5e] + +dsa_prime_2048_224 = [0xa2, 0x15, 0xdc, 0xa3, 0xf7, 0x87, 0x34, 0x2c, 0x91, 0x90, 0x87, 0x83, 0x70, 0x79, 0x73, 0x38, + 0x9f, 0x3e, 0x02, 0xf2, 0xc9, 0x68, 0xfe, 0x67, 0xca, 0xb9, 0x4f, 0x5d, 0x6f, 0x92, 0x8c, 0xe8, + 0x6c, 0x8d, 0x62, 0x25, 0x37, 0x4c, 0xa1, 0xbf, 0x7f, 0x27, 0x77, 0x44, 0x8c, 0xc7, 0xc0, 0xc5, + 0xed, 0x66, 0xd1, 0x20, 0x11, 0x7f, 0xec, 0x10, 0xed, 0x81, 0x55, 0x51, 0x45, 0x36, 0xe1, 0xaa, + 0x31, 0x6b, 0x8d, 0xd4, 0x58, 0x27, 0xa0, 0xf0, 0x0e, 0x5d, 0x91, 0x8c, 0x0f, 0xdd, 0x21, 0x8a, + 0xcd, 0x6c, 0x26, 0x3c, 0x1c, 0x2e, 0x55, 0xf6, 0xd0, 0xa7, 0x0f, 0x1b, 0xc9, 0x7f, 0x4b, 0xb0, + 0x4f, 0xff, 0xee, 0x4b, 0x78, 0xb4, 0xdf, 0x34, 0x90, 0xad, 0x98, 0xab, 0xad, 0x0a, 0x4b, 0xfe, + 0x1d, 0xaf, 0xaf, 0x6c, 0x09, 0xdd, 0xda, 0xdf, 0xb8, 0x88, 0x96, 0x94, 0x51, 0x3b, 0x86, 0x5c, + 0x07, 0xa4, 0xf5, 0xf9, 0x27, 0xbe, 0x72, 0x39, 0xe8, 0xd7, 0x67, 0x14, 0xe0, 0x3b, 0x7b, 0xfa, + 0xfb, 0x92, 0x94, 0x00, 0x0f, 0xbb, 0x3f, 0x7a, 0x75, 0x0b, 0x39, 0xca, 0x50, 0x63, 0x0e, 0xe7, + 0xd0, 0xbc, 0x45, 0xa9, 0xc9, 0x87, 0xae, 0x38, 0xae, 0x03, 0x7a, 0x11, 0xb1, 0xd1, 0x3d, 0xf5, + 0x51, 0x76, 0xd9, 0xd8, 0xab, 0x9e, 0xc0, 0xa4, 0x1b, 0x78, 0xa6, 0x36, 0x9e, 0xb5, 0x19, 0x88, + 0xfe, 0x9f, 0xbd, 0x97, 0xa1, 0x0d, 0x48, 0xe2, 0xeb, 0x21, 0x8e, 0xc6, 0x92, 0xb3, 0x1c, 0xfc, + 0xc9, 0x58, 0x3c, 0x7a, 0x41, 0x1d, 0x7d, 0xfa, 0x0a, 0xb3, 0x15, 0xfb, 0x0c, 0x75, 0xe2, 0x10, + 0x9e, 0xb1, 0xe2, 0xee, 0x75, 0xf4, 0x1d, 0x0a, 0x01, 0x65, 0x46, 0xda, 0x70, 0xa6, 0x31, 0xac, + 0x77, 0x8a, 0x2a, 0xe3, 0x25, 0x1f, 0x11, 0x39, 0xe5, 0x74, 0xe2, 0x6d, 0x2c, 0xc6, 0x5c, 0x47] +dsa_sub_prime_2048_224 = [0xd3, 0x76, 0x83, 0x74, 0x55, 0x3d, 0x49, 0x17, 0x19, 0x92, 0x74, 0xba, 0x05, 0x63, 0xbe, 0xff, + 0xa2, 0xa4, 0x5f, 0x05, 0xae, 0x83, 0xdf, 0x9b, 0x34, 0x81, 0x55, 0xbf] +dsa_base_2048_224 = [0x4e, 0x1f, 0x73, 0x4e, 0x08, 0x92, 0xd0, 0x4d, 0x80, 0x89, 0x93, 0xe6, 0x3d, 0xad, 0xef, 0xb3, + 0xfa, 0xa2, 0x48, 0x4c, 0x88, 0x83, 0x8d, 0x38, 0xd8, 0xea, 0x64, 0xca, 0x28, 0xd6, 0xc0, 0x89, + 0xbe, 0x4b, 0x88, 0x14, 0x66, 0x83, 0xec, 0xbd, 0x8b, 0x8d, 0xc6, 0xfb, 0x17, 0x81, 0xca, 0x1d, + 0x83, 0xf3, 0x7f, 0x38, 0xd2, 0x36, 0x03, 0x2b, 0x17, 0x51, 0x16, 0x6a, 0xe4, 0x3f, 0x22, 0xb5, + 0x2d, 0xd6, 0x03, 0x40, 0x1e, 0x89, 0xfe, 0xf6, 0xc9, 0xd0, 0x21, 0x5f, 0x49, 0xa2, 0xcf, 0x97, + 0x33, 0x7b, 0xe2, 0x61, 0x28, 0x8f, 0xd9, 0xac, 0xfb, 0xb6, 0xc2, 0xc0, 0xc5, 0xea, 0x70, 0x9d, + 0x14, 0x76, 0x02, 0x74, 0x41, 0x75, 0x4c, 0xcd, 0x71, 0x00, 0x79, 0x05, 0x52, 0x55, 0x97, 0xd7, + 0xae, 0xc7, 0x71, 0xeb, 0x01, 0x2b, 0x0b, 0xfc, 0xd3, 0x4f, 0x87, 0x16, 0xc7, 0xcc, 0xb1, 0x91, + 0x3d, 0x4f, 0xa6, 0x10, 0x50, 0x4b, 0x67, 0x79, 0x01, 0xdb, 0x37, 0x80, 0x01, 0x9a, 0xa6, 0x92, + 0x23, 0xfb, 0xcd, 0x94, 0x33, 0x6f, 0x2b, 0xf0, 0x2b, 0x44, 0x09, 0x39, 0x39, 0xcc, 0x0d, 0x96, + 0x11, 0xe8, 0xf5, 0xc6, 0x28, 0x50, 0x2e, 0x2b, 0x81, 0x08, 0x3f, 0xc1, 0x28, 0x2f, 0x65, 0x2e, + 0x16, 0x48, 0xc4, 0xe2, 0xb0, 0x29, 0x54, 0x99, 0x19, 0xc5, 0x78, 0xbf, 0x3b, 0xf3, 0x84, 0x70, + 0xc7, 0x8b, 0x5a, 0xcb, 0x10, 0x55, 0xfe, 0x4b, 0x71, 0xef, 0xf5, 0xdb, 0x85, 0xa6, 0xf5, 0xe8, + 0x00, 0xf5, 0xc2, 0xb4, 0xa6, 0x48, 0x39, 0x83, 0x6e, 0xd1, 0xb0, 0xad, 0xea, 0x2d, 0x7e, 0x2e, + 0x22, 0x98, 0xaa, 0x10, 0x7f, 0xa0, 0xec, 0x23, 0x70, 0x87, 0xf5, 0xda, 0x6b, 0x5e, 0x0d, 0x8b, + 0x46, 0xc8, 0x88, 0x61, 0xc3, 0xc1, 0xf5, 0xdb, 0x02, 0x2a, 0x62, 0x7a, 0xd5, 0x95, 0xe5, 0xe2] + +dsa_prime_2048_256 = [ 0xad, 0x78, 0xd1, 0x93, 0x08, 0x76, 0x4f, 0x04, 0xeb, 0x6a, 0xa3, 0x82, 0x09, 0x38, 0x0f, 0xf6, + 0xc9, 0x87, 0x5e, 0x27, 0xb2, 0x7c, 0xc1, 0x4b, 0x78, 0x29, 0xbe, 0x2e, 0xcd, 0xae, 0x26, 0x88, + 0xf4, 0x5d, 0xe8, 0x09, 0xd1, 0x16, 0x06, 0x61, 0xd4, 0x81, 0x65, 0x00, 0x5d, 0x76, 0x7e, 0xf1, + 0x24, 0x73, 0x01, 0x8f, 0x92, 0xd4, 0x07, 0xe7, 0xf3, 0xf7, 0x3a, 0xb9, 0x8b, 0x8e, 0xc8, 0xf4, + 0x13, 0x2b, 0x52, 0xb8, 0x2a, 0x08, 0x57, 0xbc, 0x15, 0xe5, 0x8e, 0x2a, 0x16, 0xda, 0x5e, 0xff, + 0xd2, 0x4e, 0xc7, 0x24, 0xa9, 0x70, 0x74, 0xd2, 0xb4, 0xc1, 0xc0, 0xec, 0x81, 0xcb, 0x83, 0xe9, + 0x29, 0x2a, 0xfd, 0x3b, 0xb9, 0x83, 0xec, 0x23, 0xd1, 0xf9, 0x13, 0xec, 0x1a, 0x68, 0x3f, 0x44, + 0x9b, 0x85, 0x7a, 0x5e, 0x6a, 0x38, 0x91, 0xe0, 0xc6, 0xc8, 0x15, 0x23, 0xf3, 0x98, 0xf7, 0x29, + 0x7f, 0x7b, 0x07, 0x14, 0x3f, 0x6f, 0xfa, 0x11, 0x71, 0x65, 0xff, 0xd9, 0xdc, 0x71, 0x23, 0xd3, + 0x40, 0xec, 0x3b, 0x5f, 0x47, 0x9c, 0x4d, 0x53, 0x4c, 0x4f, 0x61, 0x31, 0xae, 0xda, 0x2e, 0xb6, + 0xd3, 0xd2, 0x01, 0x2c, 0x63, 0x9b, 0xaa, 0x61, 0x79, 0x13, 0xe9, 0xcc, 0xef, 0x57, 0xb1, 0x7a, + 0xd1, 0xd2, 0xe3, 0xfd, 0x92, 0x29, 0x43, 0x4a, 0xc4, 0x50, 0x8c, 0x36, 0xe8, 0xa5, 0xca, 0x9a, + 0xf6, 0x43, 0x3e, 0x75, 0x32, 0x16, 0x8b, 0xe8, 0x98, 0x9c, 0x60, 0x00, 0x83, 0xb6, 0xf4, 0xc9, + 0xa2, 0x36, 0xe8, 0xf6, 0xe3, 0x8a, 0x68, 0x64, 0x61, 0x1d, 0x7b, 0xe2, 0x3c, 0xf2, 0x48, 0x77, + 0x7d, 0xe5, 0xd1, 0xd0, 0x7a, 0x8d, 0x34, 0xdd, 0x1c, 0xc2, 0xbe, 0x99, 0xa4, 0xda, 0xbf, 0xd1, + 0x30, 0x4b, 0xc1, 0xc9, 0x73, 0xc1, 0x07, 0x78, 0x04, 0x0f, 0xdd, 0x7f, 0xa2, 0xfa, 0xc1, 0x0f] +dsa_sub_prime_2048_256 = [ 0xac, 0x66, 0x19, 0x0a, 0x7f, 0x8d, 0x6b, 0x5f, 0xc3, 0x77, 0x06, 0x35, 0x58, 0x2f, 0x9b, 0xc1, + 0x4a, 0x56, 0x91, 0x55, 0xf9, 0x79, 0x3b, 0x79, 0x8e, 0x2e, 0xdb, 0xfc, 0x69, 0x4e, 0x6a, 0xfd] +dsa_base_2048_256 = [0xa6, 0x37, 0x45, 0x31, 0xe5, 0x54, 0x8a, 0x58, 0xa6, 0xd0, 0x20, 0x33, 0xdf, 0x60, 0xbf, 0xf8, + 0xa3, 0x5c, 0xa4, 0x1b, 0x37, 0xe4, 0xc9, 0xea, 0xb0, 0xf2, 0x53, 0x22, 0x19, 0x60, 0xaa, 0x6f, + 0xb2, 0x6b, 0xad, 0x24, 0x04, 0xad, 0x38, 0x57, 0x70, 0x3c, 0x4e, 0x71, 0x6e, 0x35, 0x0d, 0x4b, + 0xcc, 0xbc, 0x4d, 0xad, 0xd9, 0x1d, 0x30, 0x5e, 0xc4, 0x3a, 0x62, 0xfe, 0x2e, 0x82, 0x52, 0xcb, + 0x97, 0x37, 0xb6, 0x0a, 0xf4, 0xc5, 0x5d, 0xf7, 0xfa, 0xe4, 0x95, 0x18, 0xeb, 0x0d, 0x1b, 0xcc, + 0x0e, 0xda, 0x06, 0x50, 0x28, 0xa5, 0x1a, 0x87, 0x51, 0x21, 0xcd, 0xd5, 0xea, 0x60, 0xa1, 0x39, + 0x39, 0x82, 0x33, 0xa5, 0xd1, 0x9b, 0x0d, 0xb3, 0x5c, 0xc3, 0xeb, 0x7d, 0xa3, 0x23, 0xa8, 0xf3, + 0xb2, 0x95, 0xd3, 0x5c, 0x31, 0xb6, 0xaa, 0x55, 0xd4, 0x22, 0xaa, 0xb5, 0x5f, 0x47, 0x0f, 0xd2, + 0x79, 0xa3, 0xd3, 0x55, 0xb2, 0xa5, 0xd7, 0x5b, 0xd0, 0x37, 0x1d, 0x92, 0x58, 0xf6, 0xda, 0x07, + 0x48, 0x9e, 0x02, 0x9d, 0xfb, 0xd6, 0x71, 0x10, 0x7e, 0x0b, 0x2c, 0x94, 0xff, 0xc3, 0xdc, 0xa7, + 0x40, 0x4b, 0x81, 0x34, 0x19, 0xdb, 0x55, 0xc3, 0x46, 0xf8, 0xc3, 0x4d, 0xe7, 0x8a, 0x0d, 0x1c, + 0x69, 0xd2, 0x6f, 0x91, 0xb2, 0xd3, 0xcf, 0xc5, 0x20, 0xfe, 0x0a, 0xc0, 0x6d, 0x95, 0x5b, 0xd2, + 0x50, 0xa6, 0xb8, 0x6f, 0xe1, 0x32, 0xc0, 0x57, 0x13, 0x0b, 0x26, 0xd8, 0x22, 0x9d, 0xe3, 0xad, + 0x06, 0x79, 0xb4, 0xfc, 0xf5, 0x00, 0xb5, 0x5c, 0x76, 0x5d, 0xf9, 0x86, 0xb6, 0x69, 0x4f, 0x6c, + 0x02, 0x2d, 0x92, 0x7d, 0x9c, 0x48, 0x58, 0x7b, 0x17, 0x95, 0x7c, 0xe3, 0x97, 0x4d, 0x93, 0x7a, + 0x4c, 0x26, 0xc1, 0xa1, 0xe0, 0x6c, 0xbb, 0xc3, 0x01, 0x70, 0x9f, 0x14, 0x29, 0x3f, 0xe0, 0x5e] + +dsa_prime_3072_256 = [0xa0, 0x38, 0x3e, 0xe6, 0x92, 0xf8, 0xf5, 0xba, 0xdd, 0xf9, 0x31, 0x7b, 0x16, 0xed, 0xd2, 0x84, + 0xa3, 0x63, 0x19, 0xb0, 0x53, 0xf7, 0x3a, 0xd4, 0x31, 0xae, 0x4b, 0x5d, 0xb2, 0xc6, 0x63, 0x0b, + 0x5a, 0xbf, 0xe8, 0xc5, 0xcb, 0x9d, 0x23, 0x06, 0x50, 0xdc, 0x72, 0xee, 0xfb, 0xe6, 0xf2, 0x61, + 0xdb, 0x2f, 0x43, 0xe6, 0x83, 0x81, 0x58, 0x8c, 0xfd, 0x4a, 0x74, 0x51, 0xbb, 0xbb, 0x30, 0xc5, + 0x95, 0x21, 0xd7, 0x8e, 0xa7, 0x6d, 0xc0, 0x70, 0xcf, 0x81, 0x78, 0x33, 0x19, 0x9f, 0xf7, 0x15, + 0xcb, 0xd1, 0x12, 0xa2, 0x58, 0x50, 0x69, 0x35, 0x44, 0x66, 0x2e, 0x12, 0xbb, 0x27, 0x93, 0xa8, + 0x14, 0x84, 0x77, 0x64, 0xac, 0x27, 0x7c, 0x5c, 0xf0, 0x6b, 0x3e, 0x04, 0x4a, 0x45, 0x91, 0x3e, + 0xdd, 0x61, 0x92, 0x29, 0xdd, 0xd7, 0x28, 0x93, 0x14, 0xd0, 0x0b, 0xb6, 0xa7, 0xda, 0xf1, 0x7e, + 0xb8, 0x63, 0xf3, 0x1d, 0xc2, 0x2c, 0xcc, 0x05, 0xf6, 0x14, 0xc1, 0xbb, 0x0c, 0xea, 0x4c, 0x45, + 0x4f, 0xc6, 0xa0, 0x29, 0xc0, 0xd2, 0x56, 0x8d, 0x1c, 0x5e, 0xef, 0x7f, 0x7c, 0x41, 0xf1, 0xb6, + 0x59, 0xce, 0xd9, 0x24, 0xdd, 0x0e, 0xab, 0xc7, 0xc9, 0xbc, 0x3a, 0x55, 0x90, 0xd4, 0x03, 0x12, + 0xe3, 0xec, 0x13, 0xa2, 0xca, 0xa1, 0x80, 0xed, 0x6b, 0x0c, 0x7d, 0x54, 0xd1, 0x63, 0xca, 0x1f, + 0x32, 0xcd, 0x89, 0x27, 0xa0, 0xfd, 0x39, 0x4e, 0x51, 0xde, 0xf2, 0xa3, 0x1e, 0x83, 0xfc, 0x53, + 0x73, 0xbe, 0xf8, 0xd2, 0x5f, 0x65, 0x32, 0xef, 0x51, 0x5f, 0x86, 0x7b, 0x0b, 0x31, 0x73, 0x8f, + 0xf2, 0x7f, 0xac, 0xad, 0x0d, 0xfb, 0x40, 0xe7, 0x6b, 0x68, 0x3a, 0x3b, 0x11, 0xc9, 0x9f, 0x59, + 0xc8, 0xa4, 0x98, 0xba, 0x2b, 0x88, 0x08, 0x70, 0x0f, 0x20, 0x15, 0x14, 0x5c, 0x77, 0xdb, 0xa4, + 0x20, 0xc5, 0xf0, 0xdb, 0x95, 0xac, 0x88, 0x03, 0x6a, 0x40, 0x90, 0x4a, 0x53, 0xb3, 0x80, 0xaa, + 0x0c, 0x75, 0x80, 0x5a, 0x0d, 0xfd, 0xad, 0x4c, 0xbe, 0xaa, 0x48, 0x91, 0xab, 0xd8, 0x4d, 0x24, + 0xbb, 0x64, 0x4d, 0x96, 0xc5, 0x9f, 0x33, 0x9e, 0x01, 0x6b, 0xb4, 0x32, 0x1f, 0xf4, 0xee, 0x33, + 0xe4, 0x03, 0xce, 0xa0, 0xde, 0x9e, 0xd9, 0x59, 0xcc, 0x6c, 0x1b, 0xba, 0x2c, 0x7d, 0xc7, 0x44, + 0xde, 0x7a, 0x22, 0x5f, 0x65, 0xfb, 0x0a, 0x78, 0xee, 0x57, 0xba, 0x7d, 0x2a, 0x92, 0xf2, 0x47, + 0x50, 0xda, 0xa6, 0x8c, 0x8a, 0x6a, 0x83, 0x06, 0xc3, 0x5c, 0x49, 0x0d, 0x2d, 0x2f, 0x58, 0x92, + 0xbe, 0x12, 0x41, 0x86, 0x0a, 0xd5, 0x45, 0x3b, 0x1b, 0xe3, 0x2b, 0x0e, 0xc7, 0x29, 0x98, 0x3e, + 0x3c, 0x97, 0xd3, 0x28, 0x73, 0xfc, 0x82, 0xc7, 0xb4, 0xf4, 0x6b, 0xfd, 0xa5, 0x14, 0x9e, 0x8f] +dsa_sub_prime_3072_256 = [0xf3, 0x96, 0x52, 0xd0, 0x0e, 0xf7, 0x96, 0x2d, 0xae, 0x7d, 0x8a, 0x13, 0xa8, 0x09, 0xa8, 0x14, + 0xc5, 0xe4, 0xf9, 0xba, 0x8e, 0x6d, 0xea, 0x3d, 0x18, 0xf3, 0x51, 0x48, 0x04, 0xfc, 0xe1, 0x37] +dsa_base_3072_256 = [ 0x07, 0x1f, 0x94, 0x97, 0xf8, 0x58, 0x85, 0x5e, 0xa6, 0x1f, 0xa8, 0x05, 0x97, 0x34, 0xc0, 0x12, + 0x2a, 0xc9, 0x1c, 0xb9, 0xf8, 0x1d, 0xfd, 0x8f, 0xa6, 0xec, 0xc0, 0x83, 0xf6, 0x0c, 0xb3, 0x0e, + 0xa8, 0x0b, 0x15, 0x56, 0xe5, 0xc3, 0x90, 0xd0, 0x06, 0x73, 0x24, 0x68, 0x28, 0xd4, 0xbc, 0xed, + 0xa1, 0x84, 0x89, 0x15, 0xab, 0x86, 0xff, 0x24, 0x56, 0x8e, 0x40, 0x02, 0x03, 0x99, 0xbd, 0xb9, + 0xf6, 0x75, 0x12, 0x59, 0x51, 0xad, 0x1e, 0x57, 0x1d, 0xd4, 0xf2, 0x23, 0x46, 0x14, 0x89, 0xab, + 0x65, 0x45, 0x04, 0x40, 0xe2, 0x2b, 0x01, 0xb8, 0xf5, 0x9b, 0x9b, 0x38, 0x69, 0x2f, 0x12, 0x0b, + 0x98, 0x34, 0xdd, 0x28, 0xeb, 0x9f, 0xf0, 0x8a, 0xfc, 0x44, 0x98, 0xe1, 0x72, 0xeb, 0x3d, 0x54, + 0xb2, 0x8a, 0x8e, 0xb1, 0x00, 0xab, 0x50, 0xa5, 0x66, 0x7b, 0x9a, 0x9e, 0x8a, 0xad, 0x3f, 0x68, + 0xf1, 0xde, 0xb1, 0x04, 0x60, 0x4a, 0x3d, 0x2e, 0x0f, 0x25, 0x0a, 0x9c, 0x18, 0x8b, 0x74, 0x61, + 0xec, 0xd7, 0xde, 0xc6, 0x56, 0xb5, 0x77, 0xe8, 0x46, 0x7e, 0x46, 0x4e, 0x11, 0xac, 0x49, 0x44, + 0x97, 0x88, 0x65, 0xcd, 0xf5, 0x63, 0xaa, 0xb6, 0xa2, 0xe6, 0x8a, 0x29, 0x53, 0x95, 0x2b, 0x0a, + 0x68, 0xe8, 0x81, 0x48, 0x6e, 0x76, 0x34, 0xd4, 0x91, 0x8d, 0xf9, 0x70, 0xa7, 0xce, 0x0d, 0x60, + 0x8a, 0x92, 0x70, 0x8e, 0x49, 0x52, 0x12, 0xfd, 0x4b, 0x26, 0x79, 0x0d, 0x5c, 0x07, 0xdd, 0x5a, + 0xb5, 0x5a, 0xe8, 0x20, 0x9b, 0x63, 0x19, 0x05, 0x55, 0xc0, 0x43, 0xb7, 0x80, 0x2f, 0xae, 0x78, + 0x79, 0x7e, 0x4f, 0x63, 0xf1, 0xcb, 0x18, 0x09, 0xaf, 0x4a, 0xfc, 0x60, 0xb2, 0xb4, 0xaf, 0x78, + 0xba, 0xb3, 0xad, 0x9c, 0xcc, 0x39, 0x10, 0x08, 0x96, 0x43, 0x8e, 0x67, 0x91, 0xae, 0xec, 0x90, + 0xe8, 0x99, 0xf9, 0x76, 0x59, 0x45, 0x4f, 0x4c, 0x75, 0x96, 0x33, 0xb0, 0xd8, 0x57, 0xb5, 0x05, + 0x12, 0x45, 0x15, 0xc7, 0x5e, 0x3a, 0x64, 0x90, 0xe7, 0x16, 0x8c, 0x73, 0xfa, 0x15, 0x68, 0xe8, + 0xc9, 0x04, 0xb0, 0x42, 0x49, 0xfa, 0x31, 0xa8, 0x3c, 0x6d, 0x83, 0x8a, 0xf7, 0xd4, 0x2d, 0x48, + 0x71, 0x09, 0x89, 0xf9, 0xfb, 0xc9, 0xc3, 0x7b, 0x2c, 0x87, 0x91, 0x57, 0xc9, 0xe9, 0x81, 0x8e, + 0xa4, 0xdd, 0xb7, 0x7a, 0x1f, 0xbc, 0x66, 0x3e, 0xd8, 0x2d, 0xe8, 0x38, 0xc3, 0xab, 0x3b, 0x82, + 0xc5, 0x7d, 0xd0, 0xff, 0xbf, 0xa4, 0x95, 0xe6, 0xea, 0xd3, 0x3e, 0x44, 0x05, 0xd0, 0x58, 0xe9, + 0xb3, 0x7b, 0x3a, 0x71, 0xce, 0xbd, 0xe4, 0x2f, 0x4d, 0x33, 0x46, 0xb4, 0xc5, 0xf9, 0xd6, 0x49, + 0x8b, 0x73, 0xbc, 0x1b, 0x9f, 0x0d, 0x3d, 0x0c, 0x49, 0x29, 0x42, 0x99, 0x70, 0xe9, 0xc5, 0xeb] + +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_1024_160, + CKA_SUBPRIME : dsa_sub_prime_1024_160, + CKA_BASE : dsa_base_1024_160, + CKA_LABEL : "DSA 1024_160 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_2048_224, + CKA_SUBPRIME : dsa_sub_prime_2048_224, + CKA_BASE : dsa_base_2048_224, + CKA_LABEL : "DSA 2048_224 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_2048_256, + CKA_SUBPRIME : dsa_sub_prime_2048_256, + CKA_BASE : dsa_base_2048_256, + CKA_LABEL : "DSA 2048_256 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_3072_256, + CKA_SUBPRIME : dsa_sub_prime_3072_256, + CKA_BASE : dsa_base_3072_256, + CKA_LABEL : "DSA 3072_256 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "DSA Public Key"} + +dh_prime = [0xF4, 0x88, 0xFD, 0x58, 0x4E, 0x49, 0xDB, 0xCD, 0x20, 0xB4, 0x9D, 0xE4, 0x91, 0x07, 0x36, 0x6B, + 0x33, 0x6C, 0x38, 0x0D, 0x45, 0x1D, 0x0F, 0x7C, 0x88, 0xB3, 0x1C, 0x7C, 0x5B, 0x2D, 0x8E, 0xF6, + 0xF3, 0xC9, 0x23, 0xC0, 0x43, 0xF0, 0xA5, 0x5B, 0x18, 0x8D, 0x8E, 0xBB, 0x55, 0x8C, 0xB8, 0x5D, + 0x38, 0xD3, 0x34, 0xFD, 0x7C, 0x17, 0x57, 0x43, 0xA3, 0x1D, 0x18, 0x6C, 0xDE, 0x33, 0x21, 0x2C, + 0xB5, 0x2A, 0xFF, 0x3C, 0xE1, 0xB1, 0x29, 0x40, 0x18, 0x11, 0x8D, 0x7C, 0x84, 0xA7, 0x0A, 0x72, + 0xD6, 0x86, 0xC4, 0x03, 0x19, 0xC8, 0x07, 0x29, 0x7A, 0xCA, 0x95, 0x0C, 0xD9, 0x96, 0x9F, 0xAB, + 0xD0, 0x0A, 0x50, 0x9B, 0x02, 0x46, 0xD3, 0x08, 0x3D, 0x66, 0xA4, 0x5D, 0x41, 0x9F, 0x9C, 0x7C, + 0xBD, 0x89, 0x4B, 0x22, 0x19, 0x26, 0xBA, 0xAB, 0xA2, 0x5E, 0xC3, 0x55, 0xE9, 0x2F, 0x78, 0xC7] +dh_prime_2048= [0xF1, 0x20, 0xB5, 0x5B, 0x3A, 0xE4, 0xD0, 0xF6, 0xEF, 0xA4, 0xF2, 0x9F, 0xC4, 0xDF, 0x86, 0x84, + 0x57, 0x54, 0x14, 0x90, 0x98, 0xBD, 0x3E, 0x57, 0x86, 0xE8, 0xC9, 0xA0, 0x30, 0xAF, 0xE6, 0xA7, + 0x6D, 0x7E, 0x4F, 0xDA, 0x20, 0x87, 0x46, 0x0C, 0xED, 0x88, 0xDC, 0xDB, 0x95, 0xDE, 0xD3, 0x4F, + 0xC7, 0x18, 0x80, 0x3A, 0x0D, 0xD2, 0xF1, 0x54, 0x5C, 0xD2, 0x29, 0x78, 0x3C, 0xE4, 0x40, 0x0C, + 0x1A, 0x6B, 0x36, 0x73, 0x42, 0xE1, 0xB3, 0xD3, 0xEB, 0x95, 0xDB, 0x7A, 0x06, 0xD6, 0x54, 0x11, + 0xDB, 0x0B, 0xB3, 0x00, 0x52, 0xA5, 0x74, 0x77, 0x5B, 0x47, 0x2A, 0x6E, 0x31, 0xCB, 0x8A, 0x5D, + 0x1C, 0x8A, 0x7D, 0x93, 0x7A, 0xC3, 0x62, 0x44, 0xC3, 0x29, 0x40, 0x6D, 0x3E, 0x47, 0x62, 0x2F, + 0x93, 0xCD, 0xF3, 0xED, 0xA6, 0x1E, 0x1D, 0x57, 0x4E, 0xFF, 0x5F, 0x46, 0x92, 0xCC, 0xFC, 0x7E, + 0x98, 0x8C, 0xE8, 0xB0, 0xAA, 0x33, 0x70, 0x96, 0x3D, 0xC1, 0x5B, 0x10, 0x2A, 0x07, 0x34, 0x84, + 0x4E, 0xCD, 0xEB, 0xD7, 0x15, 0x63, 0x8C, 0xC4, 0x67, 0xB0, 0xC1, 0xB9, 0xB8, 0x45, 0xB0, 0x3B, + 0x3A, 0x76, 0x83, 0x2C, 0xF5, 0x28, 0xB3, 0xF7, 0x10, 0x23, 0x7E, 0xAA, 0xF6, 0xE6, 0x8B, 0xE7, + 0x57, 0x35, 0x1F, 0x51, 0x34, 0x58, 0x5E, 0x0C, 0x2D, 0x36, 0xCF, 0xA3, 0x85, 0x34, 0xB0, 0x14, + 0x7D, 0xD0, 0x8C, 0x34, 0xBB, 0xC1, 0x8D, 0x49, 0x8C, 0xDA, 0x41, 0x48, 0x66, 0xDB, 0x41, 0xE1, + 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, + 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, + 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] +CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_DERIVE : True, + CKA_PRIME : dh_prime, + CKA_BASE : [0x02], + CKA_LABEL : "DH Public Key"} +CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS : len(dh_prime) * 8, #long + CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DERIVE : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "DH Private Key"} + +CKM_CAST5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_CAST5, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, # 1-16 + CKA_EXTRACTABLE :True, + CKA_LABEL : "CAST5 Key"} + +CKM_RC2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_RC2, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 64, #1-128 + CKA_EXTRACTABLE :True, + CKA_LABEL : "RC2 Key"} + +CKM_RC4_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_RC4, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 256, #1-256 + CKA_EXTRACTABLE :True, + CKA_LABEL : "RC4 Key"} + +CKM_RC5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_RC5, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 255, #1-255 + CKA_EXTRACTABLE :True, + CKA_LABEL : "RC5 Key"} + +CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP = {CKA_TOKEN : True, + CKA_DERIVE : True, + CKA_ENCRYPT : 0x1001, #TODO, is encrypt both a long and a boolean, uh oh + CKA_LABEL : "SSL3 Pre Master Key"} + + +''' +Curve dictionary for ECDSA with oids as lists, taken from Components/tools/common/CommonData.cpp +''' +curve_list = { + 'secp112r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x06], # [0] OID_secp112r1 + 'secp112r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x07], # [7] OID_secp112r2 + 'secp128r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1C], # [14] OID_secp128r1 + 'secp128r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1D], # [21] OID_secp128r2 + 'secp160k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x09], # [28] OID_secp160k1 + 'secp160r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x08], # [35] OID_secp160r1 + 'secp160r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1E], # [42] OID_secp160r2 + 'secp192k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1F], # [49] OID_secp192k1 + 'secp224k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x20], # [56] OID_secp224k1 + 'secp224r1(P-224)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x21], # [63] OID_secp224r1 + 'secp256k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], # [70] OID_secp256k1 + 'secp384r1(P-384)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], # [77] OID_secp384r1 + 'secp521r1(P-521)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], # [84] OID_secp521r1 + + 'X9_62_prime192v1(P-192)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01], # [91] OID_X9_62_prime192v1 + 'X9_62_prime192v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], # [101] OID_X9_62_prime192v2 + 'X9_62_prime192v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], # [111] OID_X9_62_prime192v3 + 'X9_62_prime239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], # [121] OID_X9_62_prime239v1 + 'X9_62_prime239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], # [131] OID_X9_62_prime239v2 + 'X9_62_prime239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], # [141] OID_X9_62_prime239v3 + 'X9_62_prime256v1(P-256)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], # [151] OID_X9_62_prime256v1 + + 'sect113r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x04], # [161] OID_sect113r1 + 'sect113r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x05], # [168] OID_sect113r2 + 'sect131r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x16], # [175] OID_sect131r1 + 'sect131r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x17], # [182] OID_sect131r2 + 'sect163k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x01], # [189] OID_sect163k1 + 'sect163r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x02], # [196] OID_sect163r1 + 'sect163r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0F], # [203] OID_sect163r2 + 'sect193r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x18], # [210] OID_sect193r1 + 'sect193r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x19], # [217] OID_sect193r2 + 'sect233k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1A], # [224] OID_sect233k1 + 'sect233r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1B], # [231] OID_sect233r1 + 'sect239k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x03], # [238] OID_sect239k1 + 'sect283k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x10], # [245] OID_sect283k1 + 'sect283r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x11], # [252] OID_sect283r1 + 'sect409k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x24], # [259] OID_sect409k1 + 'sect409r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x25], # [266] OID_sect409r1 + 'sect571k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x26], # [273] OID_sect571k1 + 'sect571r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x27], # [280] OID_sect571r1 + + 'X9_62_c2pnb163v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], # [287] OID_X9_62_c2pnb163v1 + 'X9_62_c2pnb163v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], # [297] OID_X9_62_c2pnb163v2 + 'X9_62_c2pnb163v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], # [307] OID_X9_62_c2pnb163v3 + 'X9_62_c2pnb176v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], # [317] OID_X9_62_c2pnb176v1 + 'X9_62_c2tnb191v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], # [327] OID_X9_62_c2tnb191v1 + 'X9_62_c2tnb191v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], # [337] OID_X9_62_c2tnb191v2 + 'X9_62_c2tnb191v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], # [347] OID_X9_62_c2tnb191v3 + 'X9_62_c2pnb208w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], # [357] OID_X9_62_c2pnb208w1 + 'X9_62_c2tnb239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], # [367] OID_X9_62_c2tnb239v1 + 'X9_62_c2tnb239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], # [377] OID_X9_62_c2tnb239v2 + 'X9_62_c2tnb239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], # [387] OID_X9_62_c2tnb239v3 + 'X9_62_c2pnb272w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], # [397] OID_X9_62_c2pnb272w1 + 'X9_62_c2pnb304w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], # [407] OID_X9_62_c2pnb304w1 + 'X9_62_c2tnb359v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], # [417] OID_X9_62_c2tnb359v1 + 'X9_62_c2pnb368w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], # [427] OID_X9_62_c2pnb368w1 + 'X9_62_c2tnb431r1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], # [437] OID_X9_62_c2tnb431r1 + + 'brainpoolP160r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], # [447] brainpoolP160r1 + 'brainpoolP160t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], # [458] brainpoolP160t1 + 'brainpoolP192r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], # [469] brainpoolP192r1 + 'brainpoolP192t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], # [480] brainpoolP192t1 + 'brainpoolP224r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], # [491] brainpoolP224r1 + 'brainpoolP224t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], # [502] brainpoolP224t1 + 'brainpoolP256r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], # [513] brainpoolP256r1 + 'brainpoolP256t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], # [524] brainpoolP256t1 + 'brainpoolP320r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], # [535] brainpoolP320r1 + 'brainpoolP320t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], # [546] brainpoolP320t1 + 'brainpoolP384r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], # [557] brainpoolP384r1 + 'brainpoolP384t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], # [568] brainpoolP384t1 + 'brainpoolP512r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], # [579] brainpoolP512r1 + 'brainpoolP512t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], # [590] brainpoolP512t1 + 'microsoftPlayReadP160' : [0x30, 0x81, 0x95, 0x02, 0x01, 0x01, 0x30, 0x20, + 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, + 0x01, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x27, 0x18, 0x28, 0x18, + 0x31, 0x41, 0x59, 0x26, 0x14, 0x14, 0x24, 0xf7, + 0x30, 0x2c, 0x04, 0x14, 0x37, 0xa5, 0xab, 0xcc, + 0xd2, 0x77, 0xbc, 0xe8, 0x76, 0x32, 0xff, 0x3d, + 0x47, 0x80, 0xc0, 0x09, 0xeb, 0xe4, 0x14, 0x97, + 0x04, 0x14, 0x0d, 0xd8, 0xda, 0xbf, 0x72, 0x5e, + 0x2f, 0x32, 0x28, 0xe8, 0x5f, 0x1a, 0xd7, 0x8f, + 0xde, 0xdf, 0x93, 0x28, 0x23, 0x9e, 0x04, 0x29, + 0x04, 0x87, 0x23, 0x94, 0x7f, 0xd6, 0xa3, 0xa1, + 0xe5, 0x35, 0x10, 0xc0, 0x7d, 0xba, 0x38, 0xda, + 0xf0, 0x10, 0x9f, 0xa1, 0x20, 0x44, 0x57, 0x44, + 0x91, 0x10, 0x75, 0x52, 0x2d, 0x8c, 0x3c, 0x58, + 0x56, 0xd4, 0xed, 0x7a, 0xcd, 0xa3, 0x79, 0x93, + 0x6f, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x27, 0x16, 0xb2, 0x6e, + 0xec, 0x14, 0x90, 0x44, 0x28, 0xc2, 0xa6, 0x75] + } + +CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_DERIVE : True, + CKA_ECDSA_PARAMS : curve_list['secp112r1'], + CKA_LABEL : "ECDSA Public Key"} + +CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_DERIVE : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "ECDSA Private Key"} + +CKM_AES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_AES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 24, #16, 24, 32 + CKA_EXTRACTABLE :True, + CKA_LABEL : "AES Key"} + +CKM_SEED_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_SEED, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "SEED Key"} + +kcdsa_prime_1024_160 = [0xdc, 0x02, 0xf3, 0xe0, 0x51, 0x4e, 0xf4, 0x72, 0x36, 0x51, 0x09, 0x72, 0x5c, 0x12, 0x00, 0x50, + 0x69, 0x7d, 0xfc, 0x1d, 0xcb, 0xb4, 0x1f, 0xbc, 0x49, 0x63, 0xc4, 0x15, 0x45, 0x97, 0xb7, 0xae, + 0x8d, 0x4a, 0x35, 0x3c, 0xe2, 0xfb, 0x1f, 0xbf, 0x77, 0x7b, 0x89, 0xe5, 0x56, 0xc5, 0x15, 0x6b, + 0x1a, 0x4a, 0x82, 0xcc, 0xe2, 0xb8, 0xec, 0x4d, 0x61, 0x86, 0xd4, 0xa3, 0xf6, 0xc5, 0x65, 0xae, + 0x8c, 0xf6, 0x04, 0x62, 0x1d, 0x63, 0xec, 0x9f, 0x1e, 0x91, 0x31, 0x39, 0x1d, 0xc0, 0x55, 0xbc, + 0xac, 0xc5, 0x1a, 0xc8, 0x5c, 0x02, 0x93, 0xd7, 0xca, 0x74, 0x4f, 0xe9, 0xa2, 0x04, 0x5c, 0x3c, + 0xc1, 0xb6, 0xe1, 0x4d, 0xcd, 0xfa, 0xbb, 0x7d, 0xf8, 0xa7, 0xb1, 0x94, 0xd5, 0x08, 0xe1, 0x99, + 0xc1, 0x81, 0x62, 0x93, 0xd6, 0x8c, 0x7a, 0x5c, 0x0f, 0x8a, 0xc7, 0x14, 0xb5, 0xd6, 0xf5, 0xa3] +kcdsa_sub_prime_1024_160 = [0xc8, 0xf6, 0x2e, 0x10, 0xf0, 0xa4, 0xe5, 0x43, 0x1b, 0x8e, 0x1b, 0x0f, 0x53, 0xf6, 0x27, 0xec, + 0x6a, 0xd3, 0xa6, 0xa5] +kcdsa_base_1024_160 = [0x9b, 0x8b, 0x4b, 0x16, 0x53, 0x65, 0x03, 0x18, 0x47, 0x19, 0xac, 0x4d, 0x13, 0x2d, 0x14, 0x57, + 0x2d, 0xca, 0x56, 0x45, 0x3f, 0x05, 0x68, 0x68, 0x3b, 0x04, 0x17, 0x27, 0x6f, 0x93, 0x88, 0xdc, + 0x0a, 0x79, 0xe7, 0x76, 0x45, 0x4a, 0x97, 0x7a, 0x02, 0xc0, 0x1a, 0xc7, 0x7a, 0x07, 0x1f, 0x6b, + 0x99, 0x81, 0x67, 0xb8, 0xb9, 0x89, 0xce, 0xfd, 0x88, 0x7a, 0x26, 0x71, 0xf9, 0x44, 0x12, 0xcc, + 0x94, 0xac, 0x62, 0xe7, 0x61, 0xc9, 0x5a, 0xdb, 0x38, 0xf7, 0x8b, 0x76, 0x73, 0xcc, 0x09, 0x0a, + 0x62, 0xcf, 0xab, 0x4b, 0x03, 0x29, 0x0d, 0x34, 0x92, 0xb9, 0x09, 0x83, 0x68, 0x9b, 0x30, 0x82, + 0x1f, 0xcf, 0xb0, 0xdb, 0x83, 0x71, 0x24, 0x2c, 0x73, 0xf3, 0xa6, 0x4f, 0x56, 0xb2, 0x13, 0xfd, + 0xdb, 0xbc, 0xcf, 0x77, 0x5d, 0x01, 0x1f, 0xb8, 0x35, 0x85, 0x4f, 0x88, 0xb0, 0x58, 0x92, 0x07] +kcdsa_prime_2048_256 = [0xec, 0xfe, 0xa3, 0x3f, 0xa2, 0x27, 0xc3, 0xb1, 0xa7, 0xdf, 0xd7, 0xf1, 0xbb, 0x48, 0x7c, 0xd4, + 0x26, 0xab, 0x0a, 0x2b, 0x2b, 0x3a, 0xf1, 0x8f, 0xef, 0x9d, 0x61, 0xcd, 0x4f, 0x7b, 0xbb, 0x8d, + 0x7d, 0x8d, 0x4c, 0x84, 0x13, 0x7a, 0xaf, 0xe5, 0xb5, 0xba, 0x9d, 0xe4, 0xd2, 0xb5, 0x8b, 0x00, + 0x39, 0xbc, 0x66, 0x9c, 0x7c, 0x3d, 0x98, 0x7e, 0x0a, 0x74, 0x1b, 0x06, 0xcf, 0x97, 0xb5, 0x3e, + 0xcb, 0x1e, 0x1d, 0x22, 0x51, 0xe6, 0xd4, 0xe2, 0x72, 0xa7, 0x72, 0xd3, 0x4c, 0x3f, 0xfc, 0xd4, + 0xd5, 0x7c, 0x3f, 0x44, 0xa2, 0x1b, 0xfc, 0x97, 0xad, 0x34, 0xb2, 0x8f, 0xd3, 0xcf, 0x77, 0x89, + 0x7a, 0xce, 0x64, 0xc6, 0x92, 0xaa, 0x69, 0x13, 0xed, 0x22, 0xa2, 0x3b, 0x45, 0x19, 0x98, 0x88, + 0x29, 0x05, 0x7c, 0xd2, 0x33, 0xaf, 0xa1, 0xf7, 0xab, 0x66, 0x40, 0xca, 0x05, 0x7e, 0x16, 0x99, + 0x7a, 0x92, 0xaa, 0x5e, 0x07, 0xc0, 0xc7, 0x3c, 0x82, 0xb4, 0x96, 0x02, 0x23, 0x66, 0x99, 0x97, + 0xa3, 0x40, 0xf1, 0x36, 0x9b, 0x33, 0xc7, 0xbe, 0xe9, 0xac, 0xce, 0x85, 0xf8, 0xbd, 0x6a, 0x26, + 0x0f, 0x79, 0xe7, 0x9e, 0xee, 0xee, 0xd6, 0x82, 0xc8, 0x7d, 0x4b, 0xe7, 0x4c, 0x2f, 0x44, 0x9a, + 0x1b, 0x68, 0x3f, 0xba, 0xe4, 0xfd, 0x19, 0xca, 0xd0, 0x97, 0xd3, 0x71, 0x12, 0x8c, 0x86, 0xbe, + 0x93, 0x84, 0xb7, 0x35, 0x2a, 0xd1, 0x3a, 0x9a, 0x27, 0x8f, 0x36, 0x4f, 0x08, 0x9e, 0x38, 0xdf, + 0x25, 0xe8, 0x4a, 0x70, 0x4d, 0xe4, 0xfb, 0x16, 0x40, 0xa5, 0x19, 0xfc, 0x62, 0x91, 0x76, 0x1d, + 0xab, 0x11, 0xe2, 0xf7, 0x80, 0xe7, 0x1a, 0x62, 0x2e, 0x9a, 0xbf, 0x85, 0xfe, 0x19, 0x4a, 0x45, + 0x79, 0x3b, 0xfa, 0xb3, 0xa1, 0xe9, 0x8a, 0x1d, 0xfd, 0x57, 0xb5, 0xc7, 0x09, 0x79, 0xb8, 0x1b] +kcdsa_sub_prime_2048_256 = [0xe5, 0x7d, 0x48, 0xd4, 0x44, 0x3d, 0x60, 0xb2, 0x6f, 0x48, 0x82, 0x3d, 0x1d, 0xea, 0xce, 0xf2, + 0xb4, 0x4a, 0x6c, 0x47, 0x5b, 0x12, 0x43, 0x47, 0xb4, 0x81, 0x47, 0xf8, 0xa2, 0xfd, 0x33, 0xd3] +kcdsa_base_2048_256 = [0x68, 0x90, 0xea, 0x6f, 0x5a, 0x56, 0x4f, 0xd2, 0xa1, 0xfe, 0x07, 0xd7, 0xbc, 0xa5, 0xab, 0x80, + 0xf9, 0x5a, 0x5f, 0x47, 0xe9, 0x7f, 0xfc, 0x9a, 0xea, 0x67, 0x13, 0xf8, 0xad, 0x36, 0xe1, 0xfc, + 0x02, 0x42, 0x17, 0xcd, 0xf9, 0xbe, 0x5c, 0xe9, 0xa6, 0xcd, 0xdb, 0x6b, 0x5c, 0x1e, 0x7e, 0x22, + 0x0e, 0xd5, 0x7f, 0x2b, 0x0c, 0x9b, 0xf7, 0xe2, 0xd5, 0x23, 0xc1, 0x45, 0x0b, 0x46, 0x7e, 0x64, + 0x80, 0xc9, 0x6f, 0x9b, 0x20, 0x76, 0xd0, 0x3f, 0xae, 0x8c, 0x4d, 0x99, 0x3e, 0x9c, 0xe6, 0x6b, + 0xc9, 0xb8, 0x39, 0xa5, 0x58, 0x15, 0x6c, 0x69, 0x79, 0x2a, 0xfa, 0x34, 0x76, 0x17, 0x64, 0x6a, + 0x2a, 0x29, 0x4d, 0xce, 0xe4, 0x07, 0x78, 0xa3, 0xcb, 0x93, 0x7a, 0x78, 0x2a, 0x51, 0x91, 0xbd, + 0x42, 0x97, 0x3b, 0x07, 0x31, 0xca, 0x4f, 0x62, 0x2a, 0x63, 0xe0, 0x69, 0x45, 0x31, 0xc8, 0x75, + 0x3e, 0x3a, 0xb0, 0xe8, 0x8d, 0xdc, 0x86, 0x1c, 0x75, 0x1c, 0x25, 0x2e, 0x74, 0x18, 0x89, 0xb3, + 0x3e, 0x39, 0x0e, 0x1c, 0xa5, 0xc4, 0x75, 0x1f, 0x31, 0x1e, 0x19, 0x61, 0x5b, 0xbe, 0xa7, 0x18, + 0x9b, 0x04, 0xf2, 0x29, 0xc8, 0xe7, 0x40, 0x84, 0x39, 0xd2, 0x28, 0xa5, 0x30, 0x5b, 0x22, 0x78, + 0x33, 0xab, 0xa8, 0x30, 0x98, 0x1c, 0x33, 0xec, 0xfe, 0xe7, 0x90, 0x8c, 0x6d, 0x39, 0x54, 0x42, + 0x9b, 0xef, 0x30, 0xde, 0xa1, 0x15, 0xfe, 0xe6, 0xd0, 0x3f, 0x13, 0xf0, 0xa0, 0x2e, 0xb2, 0x19, + 0xe4, 0xb9, 0xb0, 0xba, 0xac, 0x32, 0xc2, 0x24, 0x0b, 0x2a, 0x47, 0x17, 0xda, 0x7c, 0x11, 0x6c, + 0xe2, 0x09, 0x24, 0x71, 0x30, 0xac, 0x14, 0x0c, 0xd3, 0xab, 0xdc, 0xe7, 0x78, 0xa4, 0x27, 0x27, + 0xf3, 0x2c, 0xfa, 0xfd, 0xae, 0x9e, 0x51, 0x68, 0x47, 0xb2, 0x6c, 0xe4, 0xcb, 0xb7, 0x66, 0x03] +CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, #1024_160 or 2048_256 + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : kcdsa_prime_1024_160, + CKA_SUBPRIME : kcdsa_sub_prime_1024_160, + CKA_BASE : kcdsa_base_1024_160, + CKA_LABEL : "KCDSA Public Key"} +CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, #1024_160 or 2048_256 + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : kcdsa_prime_2048_256, + CKA_SUBPRIME : kcdsa_sub_prime_2048_256, + CKA_BASE : kcdsa_base_2048_256, + CKA_LABEL : "KCDSA Public Key"} +CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "KCDSA Private Key"} + +CKM_DSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_PRIME_BITS : 1024, # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 + CKA_SUBPRIME_BITS : 160, #0-512 + CKA_LABEL : "DSA Parameter Key"} + +CKM_KCDSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, #primelength 0-4096, subprimelength 0-512 + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_PRIME_BITS : 2048, #0-4096 + CKA_SUBPRIME_BITS : 256, #0-512 + CKA_LABEL : "KCDSA Parameter Key"} + +CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_MODIFIABLE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_MODULUS_BITS : 1024, #long 1-MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT : 3, #byte + CKA_LABEL : "RSA Public Key"} +CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_MODIFIABLE : True, + CKA_EXTRACTABLE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_LABEL : "RSA Private Key"} + +dhX9_42Prime = [0xE0, 0x01, 0xE8, 0x96, 0x7D, 0xB4, 0x93, 0x53, 0xE1, 0x6F, 0x8E, 0x89, 0x22, 0x0C, 0xCE, 0xFC, + 0x5C, 0x5F, 0x12, 0xE3, 0xDF, 0xF8, 0xF1, 0xD1, 0x49, 0x90, 0x12, 0xE6, 0xEF, 0x53, 0xE3, 0x1F, + 0x02, 0xEA, 0xCC, 0x5A, 0xDD, 0xF3, 0x37, 0x89, 0x35, 0xC9, 0x5B, 0x21, 0xEA, 0x3D, 0x6F, 0x1C, + 0xD7, 0xCE, 0x63, 0x75, 0x52, 0xEC, 0x38, 0x6C, 0x0E, 0x34, 0xF7, 0x36, 0xAD, 0x95, 0x17, 0xEF, + 0xFE, 0x5E, 0x4D, 0xA7, 0xA8, 0x6A, 0xF9, 0x0E, 0x2C, 0x22, 0x8F, 0xE4, 0xB9, 0xE6, 0xD8, 0xF8, + 0xF0, 0x2D, 0x20, 0xAF, 0x78, 0xAB, 0xB6, 0x92, 0xAC, 0xBC, 0x4B, 0x23, 0xFA, 0xF2, 0xC5, 0xCC, + 0xD4, 0x9A, 0x0C, 0x9A, 0x8B, 0xCD, 0x91, 0xAC, 0x0C, 0x55, 0x92, 0x01, 0xE6, 0xC2, 0xFD, 0x1F, + 0x47, 0xC2, 0xCB, 0x2A, 0x88, 0xA8, 0x3C, 0x21, 0x0F, 0xC0, 0x54, 0xDB, 0x29, 0x2D, 0xBC, 0x45] +dhX9_42Base = [0x86, 0x47, 0x17, 0xA3, 0x9E, 0x6A, 0xEA, 0x7E, 0x87, 0xC4, 0x32, 0xEE, 0x77, 0x43, 0x15, 0x16, + 0x96, 0x70, 0xC4, 0x99] +dhX9_42SubPrime = [0x1C, 0xE0, 0xF6, 0x69, 0x26, 0x46, 0x11, 0x97, 0xEF, 0x45, 0xC4, 0x65, 0x8B, 0x83, 0xB8, 0xAB, + 0x04, 0xA9, 0x22, 0x42, 0x68, 0x50, 0x4D, 0x05, 0xB8, 0x19, 0x83, 0x99, 0xDD, 0x71, 0x37, 0x18, + 0xCC, 0x1F, 0x24, 0x5D, 0x47, 0x6C, 0xCF, 0x61, 0xA2, 0xF9, 0x34, 0x93, 0xF4, 0x1F, 0x55, 0x52, + 0x48, 0x65, 0x57, 0xE6, 0xD4, 0xCA, 0xA8, 0x00, 0xD6, 0xD0, 0xDB, 0x3C, 0xBF, 0x5A, 0x95, 0x4B, + 0x20, 0x8A, 0x4E, 0xBA, 0xF7, 0xE6, 0x49, 0xFB, 0x61, 0x24, 0xD8, 0xA2, 0x1E, 0xF2, 0xF2, 0x2B, + 0xAA, 0xAE, 0x29, 0x21, 0x10, 0x19, 0x10, 0x51, 0x46, 0x47, 0x31, 0xB6, 0xCC, 0x3C, 0x93, 0xDC, + 0x6E, 0x80, 0xBA, 0x16, 0x0B, 0x66, 0x64, 0xA5, 0x6C, 0xFA, 0x96, 0xEA, 0xF1, 0xB2, 0x83, 0x39, + 0x8E, 0xB4, 0x61, 0x64, 0xE5, 0xE9, 0x43, 0x84, 0xEE, 0x02, 0x24, 0xE7, 0x1F, 0x03, 0x7C, 0x23] +CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE: True, + CKA_SENSITIVE : True, + CKA_DERIVE : True, + CKA_PRIME : dhX9_42Prime, + CKA_BASE : dhX9_42Base, + CKA_SUBPRIME : dhX9_42SubPrime, + CKA_LABEL : "DH X9.42 Public Key"} +CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DERIVE : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "DH X9.42 Private Key"} + +CKM_ARIA_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_ARIA, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 24, #16, 24, 32 + CKA_EXTRACTABLE :True, + CKA_LABEL : "ARIA Key"} + +CKM_DH_PKCS_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_PRIME_BITS : 512, #between 512 and 2048 in 256bit increments (&0xff) + CKA_LABEL : "SH PKCS Parameter Key"} + +''' +The simple certificate object taken from CKDemo when +you select the Create Object option and choose certificate +''' +CERTIFICATE_TEMPLATE = { CKA_CLASS: CKO_CERTIFICATE, + CKA_CERTIFICATE_TYPE : CKC_X_509, + CKA_TOKEN : True, + CKA_LABEL : "Created certificate object", + CKA_SUBJECT : "", + CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} + +''' +The simple data object template taken from CKDemo when you select +the Create Object option and choose data +''' +DATA_TEMPLATE = { CKA_CLASS : CKO_DATA, + CKA_TOKEN : True, + CKA_LABEL : "Created data object", + CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} + +KEY_GENERATOR_TEMPLATES = {CKM_DES_KEY_GEN : CKM_DES_KEY_GEN_TEMP, + CKM_DES2_KEY_GEN : CKM_DES2_KEY_GEN_TEMP, + CKM_DES3_KEY_GEN: CKM_DES3_KEY_GEN_TEMP, + CKM_CAST3_KEY_GEN: CKM_CAST3_KEY_GEN_TEMP, + CKM_GENERIC_SECRET_KEY_GEN: CKM_GENERIC_SECRET_KEY_GEN_TEMP, + CKM_CAST5_KEY_GEN: CKM_CAST5_KEY_GEN_TEMP, + CKM_RC2_KEY_GEN: CKM_RC2_KEY_GEN_TEMP, + CKM_RC4_KEY_GEN: CKM_RC4_KEY_GEN_TEMP, + CKM_RC5_KEY_GEN: CKM_RC5_KEY_GEN_TEMP, + CKM_AES_KEY_GEN: CKM_AES_KEY_GEN_TEMP, + CKM_SEED_KEY_GEN: CKM_SEED_KEY_GEN_TEMP, + CKM_ARIA_KEY_GEN: CKM_ARIA_KEY_GEN_TEMP, + CKM_DH_PKCS_PARAMETER_GEN: CKM_DH_PKCS_PARAMETER_GEN_TEMP} + +KEY_PAIR_GENERATOR_TEMPLATES = { #Note lacks multiple sizes of the same kinds of keys + CKM_RSA_PKCS_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), #pkcs template is good for x9.31 + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_DSA_KEY_PAIR_GEN : (CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_DH_PKCS_KEY_PAIR_GEN : (CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_ECDSA_KEY_PAIR_GEN : (CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_KCDSA_KEY_PAIR_GEN : (CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP)} + +''' +This list is not complete +''' +MECHANISM_LOOKUP = {CKM_RSA_PKCS_KEY_PAIR_GEN: "CKM_RSA_PKCS_KEY_PAIR_GEN", + CKM_RSA_PKCS: "CKM_RSA_PKCS", + CKM_SHA1_RSA_PKCS: "CKM_SHA1_RSA_PKCS", + CKM_SHA224_RSA_PKCS: "CKM_SHA224_RSA_PKCS", + CKM_SHA256_RSA_PKCS: "CKM_SHA256_RSA_PKCS", + CKM_SHA384_RSA_PKCS: "CKM_SHA384_RSA_PKCS", + CKM_SHA512_RSA_PKCS: "CKM_SHA512_RSA_PKCS", + CKM_RSA_PKCS_PSS: "CKM_RSA_PKCS_PSS", + CKM_SHA1_RSA_PKCS_PSS: "CKM_SHA1_RSA_PKCS_PSS", + CKM_SHA224_RSA_PKCS_PSS: "CKM_SHA224_RSA_PKCS_PSS", + CKM_SHA256_RSA_PKCS_PSS: "CKM_SHA256_RSA_PKCS_PSS", + CKM_SHA384_RSA_PKCS_PSS: "CKM_SHA384_RSA_PKCS_PSS", + CKM_SHA512_RSA_PKCS_PSS: "CKM_SHA512_RSA_PKCS_PSS", + CKM_RSA_X9_31_KEY_PAIR_GEN: "CKM_RSA_X9_31_KEY_PAIR_GEN", + CKM_RSA_X9_31: "CKM_RSA_X9_31", + CKM_SHA1_RSA_X9_31: "CKM_SHA1_RSA_X9_31", + CKM_SHA224_RSA_X9_31: "CKM_SHA224_RSA_X9_31", + CKM_SHA256_RSA_X9_31: "CKM_SHA256_RSA_X9_31", + CKM_SHA384_RSA_X9_31: "CKM_SHA384_RSA_X9_31", + CKM_SHA512_RSA_X9_31: "CKM_SHA512_RSA_X9_31", + CKM_RSA_PKCS_OAEP: "CKM_RSA_PKCS_OAEP", + CKM_DSA_KEY_PAIR_GEN: "CKM_DSA_KEY_PAIR_GEN", + CKM_DSA: "CKM_DSA", + CKM_DSA_SHA1: "CKM_DSA_SHA1", + CKM_DSA_SHA224: "CKM_DSA_SHA224", + CKM_DSA_SHA256: "CKM_DSA_SHA256", + CKM_DSA_PARAMETER_GEN: "CKM_DSA_PARAMETER_GEN", + CKM_ECDSA_KEY_PAIR_GEN: "CKM_ECDSA_KEY_PAIR_GEN", + CKM_ECDSA: "CKM_ECDSA", + CKM_ECDSA_SHA1: "CKM_ECDSA_SHA1", + CKM_ECDSA_SHA224: "CKM_ECDSA_SHA224", + CKM_ECDSA_SHA256: "CKM_ECDSA_SHA256", + CKM_ECDSA_SHA384: "CKM_ECDSA_SHA384", + CKM_ECDSA_SHA512: "CKM_ECDSA_SHA512", + CKM_ECDH1_DERIVE: "CKM_ECDH1_DERIVE", + CKM_ECDH1_COFACTOR_DERIVE: "CKM_ECDH1_DERIVE", + CKM_SHA_1_HMAC: "CKM_SHA_1_HMAC", + CKM_SHA224_HMAC: "CKM_SHA224_HMAC", + CKM_SHA256_HMAC: "CKM_SHA256_HMAC", + CKM_SHA384_HMAC: "CKM_SHA384_HMAC", + CKM_SHA512_HMAC: "CKM_SHA512_HMAC", + CKM_GENERIC_SECRET_KEY_GEN: "CKM_GENERIC_SECRET_KEY_GEN", + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} + +def get_default_key_template(mechanism): + ''' + Gets a default template for the given key gen mechanism, returns a deep copy + ''' + return copy.deepcopy(KEY_GENERATOR_TEMPLATES[mechanism]) + +def get_default_key_pair_template(mechanism): + ''' + Gets the default template for the given key pair gen mechanism, returns a deep copy + ''' + pub, priv = KEY_PAIR_GENERATOR_TEMPLATES[mechanism] + return copy.deepcopy(pub), copy.deepcopy(priv) + + diff --git a/pycryptoki/defaults.py b/pycryptoki/defaults.py new file mode 100755 index 0000000..6431db2 --- /dev/null +++ b/pycryptoki/defaults.py @@ -0,0 +1,42 @@ +''' +A file containing commonly used strings or other data similar to a config file +''' + +#The location of the cryptoki file, if specified as None the environment variable +#ChrystokiConfigurationPath will be used or it will revert to using /etc/Chrystoki.conf +CHRYSTOKI_CONFIG_FILE = None + +#The location of the DLL file, if not specified it will try to look up the file in +#the Chrystoki config file specified be the variable CHRYSTOKI_CONFIG_FILE +CHRYSTOKI_DLL_FILE = None + +ADMIN_PARTITION_LABEL = 'no label' +AUDITOR_LABEL = 'auditorlabel' + +ADMINISTRATOR_USERNAME = 'Administrator' +ADMINISTRATOR_PASSWORD = 'adminpassword' + +AUDITOR_USERNAME = 'Auditor' +AUDITOR_PASSWORD = 'auditorpassword' + +CO_USERNAME = 'Crypto Officer' +CO_PASSWORD = 'copassword' + +DEFAULT_USERNAME = 'default_user' +DEFAULT_LABEL = 'default_label' +DEFAULT_PASSWORD = 'default' + +DEFAULT_UTILS_PATH = '/usr/safenet/lunaclient/sbin' +FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + +user_credentials = {ADMINISTRATOR_USERNAME : ADMINISTRATOR_PASSWORD, + AUDITOR_USERNAME : AUDITOR_PASSWORD, + CO_USERNAME : CO_PASSWORD, + DEFAULT_USERNAME : DEFAULT_PASSWORD} + +DES3_KEY_SIZE = 120 + +MANUFACTURER_ID = "SafeNet Inc." +MODEL = "Luna K6" + +ADMIN_SLOT = 1 \ No newline at end of file diff --git a/pycryptoki/dictionary_handling.py b/pycryptoki/dictionary_handling.py new file mode 100755 index 0000000..dfe1e30 --- /dev/null +++ b/pycryptoki/dictionary_handling.py @@ -0,0 +1,16 @@ +''' +Created on Oct 3, 2012 + +@author: root +''' + +class CDict: + + dict_val = None + + + + def __init__(self, dict_val): + self.dict_val = dict_val + + \ No newline at end of file diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py new file mode 100755 index 0000000..5d5f03e --- /dev/null +++ b/pycryptoki/encryption.py @@ -0,0 +1,406 @@ +""" +Methods related to encrypting data/files. +""" +from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ + C_EncryptInit, CK_BYTE_PTR, C_Encrypt, CK_RSA_PKCS_OAEP_PARAMS +from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer +from defines import CKM_DES_CBC, CKM_DES3_CBC, CKM_CAST3_CBC, CKM_DES_ECB, \ + CKM_DES3_ECB, CKM_CAST3_ECB, CKM_RC2_ECB, CKM_RC2_CBC, CKM_CAST5_ECB, \ + CKM_CAST5_CBC, CKM_RC4, CKM_RC5_ECB, CKM_RC5_CBC, CKM_RSA_X_509, CKM_DES_CBC_PAD, \ + CKM_DES3_CBC_PAD, CKM_DES3_CBC_PAD_IPSEC, CKM_RC2_CBC_PAD, CKM_RC5_CBC_PAD, \ + CKM_CAST3_CBC_PAD, CKM_CAST5_CBC_PAD, CKM_SEED_ECB, CKM_SEED_CBC, \ + CKM_SEED_CBC_PAD, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, \ + CKM_AES_CBC_PAD_IPSEC, CKM_ARIA_ECB, CKM_ARIA_CBC, CKM_ARIA_CBC_PAD, \ + CKM_RSA_PKCS, CKM_DES_CFB8, CKM_DES_CFB64, CKM_DES_OFB64, CKM_AES_CFB8, \ + CKM_AES_CFB128, CKM_AES_OFB, CKM_ARIA_CFB8, CKM_ARIA_CFB128, CKM_ARIA_OFB, \ + CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ + CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED +from pycryptoki.attributes import get_byte_list_from_python_list, \ + convert_CK_CHAR_to_string, convert_ck_char_array_to_string, Attributes +from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ + C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ + C_DecryptUpdate, C_DecryptFinal +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def get_encryption_mechanism(encryption_flavor): + ''' + Returns the CK_MECHANISM() object associated with a given encryption flavor + #TODO: Only works with one kind of encryption mechanism currently. + + @param encryption_flavor: The flavor of the encryption that the mechanism needs + to encrypt for. + @return: Returns a CTypes CK_Mechanism given the encryption flavour that you have passed in + ''' + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(encryption_flavor) + mech.pParameter = 0 + mech.usParameterLen = CK_ULONG(0) + + iv_required = 1 + RC2_params_required = 2 + RC2CBC_params_required = 3 + RC5_params_required = 4 + RC5CBC_params_required = 5 + IV16_required = 6 + GCM_params_required = 7 + xorkdf_params_required = 8 + OAEP_params_required = 9 + ECIES_params_required = 10 + + encryption_flavors = {CKM_DES_CBC : iv_required, + CKM_DES3_CBC : iv_required, + CKM_CAST3_CBC : iv_required, + CKM_DES_ECB : 0, + CKM_DES3_ECB : 0, + CKM_CAST3_ECB : 0, + CKM_RC2_ECB : RC2_params_required, + CKM_RC2_CBC : RC2CBC_params_required , + CKM_CAST5_ECB : 0, + CKM_CAST5_CBC : iv_required, + CKM_RC4 : 0, + CKM_RC5_ECB : RC5_params_required, + CKM_RC5_CBC : RC5CBC_params_required, + CKM_RSA_X_509 : 0, + CKM_DES_CBC_PAD : iv_required, + CKM_DES3_CBC_PAD : iv_required, + CKM_DES3_CBC_PAD_IPSEC : iv_required, + CKM_RC2_CBC_PAD : RC2CBC_params_required, + CKM_RC5_CBC_PAD : RC5CBC_params_required, + CKM_CAST3_CBC_PAD : iv_required, + CKM_CAST5_CBC_PAD : iv_required, + CKM_SEED_ECB : 0, + CKM_SEED_CBC : IV16_required, + CKM_SEED_CBC_PAD : IV16_required, + CKM_AES_ECB : 0, + CKM_AES_CBC : IV16_required, + CKM_AES_CBC_PAD : IV16_required, + CKM_AES_CBC_PAD_IPSEC : IV16_required, + CKM_ARIA_ECB : IV16_required, + CKM_ARIA_CBC : IV16_required, + CKM_ARIA_CBC_PAD : IV16_required, + CKM_RSA_PKCS : 0, + CKM_DES_CFB8 : iv_required, + CKM_DES_CFB64 : iv_required, + CKM_DES_OFB64 : iv_required, + CKM_AES_CFB8 : iv_required, + CKM_AES_CFB128 : iv_required, + CKM_AES_OFB : iv_required, + CKM_ARIA_CFB8 : iv_required, + CKM_ARIA_CFB128 : iv_required, + CKM_ARIA_OFB : iv_required, + CKM_AES_GCM : GCM_params_required, + CKM_XOR_BASE_AND_DATA_W_KDF : xorkdf_params_required, + CKM_RSA_PKCS_OAEP : OAEP_params_required, + CKM_ECIES : ECIES_params_required} + + iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] + iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + + params = encryption_flavors.get(encryption_flavor) + if params == iv_required: + mech.pParameter = get_byte_list_from_python_list(iv) + mech.usParameterLen = CK_ULONG(len(iv)) + elif params == RC2_params_required: + num_of_effective_bits = 0 + rc2_params = (c_char * 2)() + rc2_params[0] = c_char(int(num_of_effective_bits, 8) & 0xff) + rc2_params[1] = c_char(int((num_of_effective_bits >> 8), 8) & 0xff) + rc2_params = create_string_buffer("", 2) + mech.pParameter = cast(rc2_params, c_void_p) + mech.usParameterLen = CK_ULONG(len(rc2_params)) + pass + elif params == RC2CBC_params_required: + num_of_effective_bits = 0 + pass + elif params == RC5_params_required: + num_rounds = 0 + pass + elif params == RC5CBC_params_required: + num_rounds = 0 + pass + elif params == IV16_required: + mech.pParameter = get_byte_list_from_python_list(iv16) + mech.usParameterLen = CK_ULONG(len(iv16)) + elif params == GCM_params_required: + pass + elif params == xorkdf_params_required: + pass + elif params == OAEP_params_required: + p = CK_RSA_PKCS_OAEP_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA_1) + p.mgf = CK_ULONG(CKG_MGF1_SHA1) + p.source = CK_ULONG(CKZ_DATA_SPECIFIED) + p.pSourceData = 0 + p.ulSourceDataLen = 0 + + mech.pParameter = cast(pointer(p), CK_VOID_PTR) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif params == ECIES_params_required: + pass + + return mech + +def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + ''' + Encrypts data with a given key and encryption flavor + encryption flavors + @param session: Current session + @param encryption_flavor: The flavor of encryption to use + @param h_key: The key handle to encrypt the data with + @param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param mech: The mechanism to use, if None will try to look up a + default mechanism based on the encryption flavor + @return: Returns the result code of the operation, a python string representing the encrypted data + ''' + + if mech == None: + mech = get_encryption_mechanism(encryption_flavor) + + #if a list is passed out do an encrypt operation on each string in the list, otherwise just do one encrypt operation + is_multi_part_operation = isinstance(data_to_encrypt, list) or isinstance(data_to_encrypt, tuple) + + #Initialize encryption + ret = C_EncryptInit(h_session, byref(mech), CK_ULONG(h_key)) + if ret != CKR_OK: return ret, None + + if is_multi_part_operation: + encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, C_EncryptFinal, data_to_encrypt) + else: + plain_data_length = len(data_to_encrypt) + plain_data = get_c_data_to_sign_or_encrypt(data_to_encrypt) + + #Get the length of the encrypted data + encrypted_data_length = CK_ULONG() + ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), None, byref(encrypted_data_length)) + if ret != CKR_OK: return ret, None + + output = create_string_buffer("", encrypted_data_length.value) + encrypted_data = cast(output, CK_BYTE_PTR) + + #Encrypt data + ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), encrypted_data, byref(encrypted_data_length)) + + #Convert encrypted data into a python string + ck_char_array = encrypted_data._objects.values()[0] + encrypted_python_string = convert_ck_char_array_to_string(ck_char_array) + + return ret, encrypted_python_string + +c_encrypt_ex = make_error_handle_function(c_encrypt) + +def _split_string_into_list(python_string, block_size): + ''' + Splits a string into a list of equal size chunks + + @param python_string: The string to divide + @param block_size: The size of the blocks to divide the string into + @return: A list of strings of block_size + ''' + return_list = [] + total_length = len(python_string) + for index in range(0, (total_length / block_size)): + start_index = index * block_size + end_index = min(start_index + block_size, total_length) + return_list.append(python_string[start_index : end_index]) + + return return_list + +def _get_string_from_list(list_of_strings): + ''' + Takes a list of strings and returns a single concatenated string. + + @param list_of_strings: A list of strings to be concatenated + @return: Single string representing the concatenated list + ''' + large_string = '' + for substring in list_of_strings: + large_string += substring + + return large_string + +def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech = None): + ''' + Decrypts some data + + @param h_session: The session to use + @param decryption_flavor: The decryption flavor to create a new mechanism with if no mechanism + is provided + @param h_key: The handle of the key to use to decrypt + @param mech: The mechanism, if none is provided a blank one will be provided based on the decryption_flavor + + @return: The result code, a python string of the decrypted data + ''' + + #Get the mechanism + if mech == None: + mech = get_encryption_mechanism(decryption_flavor) + + #Initialize Decrypt + ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) + if ret != CKR_OK: return ret, None + + #if a list is passed out do a decrypt operation on each string in the list, otherwise just do one decrypt operation + is_multi_part_operation = isinstance(encrypted_data, list) or isinstance(encrypted_data, tuple) + + if is_multi_part_operation: + python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, encrypted_data) + else: + + #Get the length of the final data + # NOTE: The "Conventions for functions returning output in a variable-length buffer" + # section of the PKCS#11 spec says that the length returned in this + # case (no output buffer given to C_Decrypt) can exceed the precise + # number of bytes needed. So the python string that's returned in the + # end needs to be adjusted based on the second called to C_Decrypt + # which will have the right length + plain_data_len = CK_ULONG() + c_encrypted_data = get_c_data_to_sign_or_encrypt(encrypted_data) + encrypted_data_len = len(encrypted_data) + ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), None, byref(plain_data_len)) + + if ret != CKR_OK: return ret, None + + output = create_string_buffer("", plain_data_len.value) + plain_data = cast(output, CK_BYTE_PTR) + + #Decrypt data + ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), plain_data, byref(plain_data_len)) + if ret != CKR_OK: return ret, None + + #Convert the decrypted data to a python readable format + ck_char_array = plain_data._objects.values()[0] + python_string = convert_ck_char_array_to_string(ck_char_array) + # Adjust the string based on the updated plain_data_len + python_string = python_string[:plain_data_len.value] + + return ret, python_string + +c_decrypt_ex= make_error_handle_function(c_decrypt) + +def do_multipart_operation(h_session, c_update_function, c_finalize_function, input_data_list): + ''' + Some code which will do a multipart encrypt or decrypt since they are the same + with just different functions called + ''' + max_data_chunk_size = 0xfff0 + plain_data_len = len(_get_string_from_list(input_data_list)) + + remaining_length = plain_data_len + python_string = '' + i = 0 + while remaining_length > 0: + current_chunk = input_data_list[i] + + #Prepare arguments for decrypt update operation + current_chunk_len = min(len(current_chunk), remaining_length) + + if current_chunk_len > max_data_chunk_size: + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + + out_data = create_string_buffer('', max_data_chunk_size) + out_data_len = CK_ULONG(max_data_chunk_size) + if (out_data_len.value > 0): + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + + ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len), cast(out_data, CK_BYTE_PTR), byref(out_data_len)) + if ret != CKR_OK: return ret, None + + remaining_length -= current_chunk_len + + #Get the output + ck_char_array = out_data._objects.values()[0] + python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + i += 1 + + #Finalizing multipart decrypt operation + out_data_len = CK_ULONG(max_data_chunk_size) + output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) + ret = c_finalize_function(h_session, output, byref(out_data_len)) + + #Get output + ck_char_array = output._objects.values()[0] + if (out_data_len.value > 0): + python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + + return python_string + +def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech = None): + ''' + Function which wraps a key + + @param h_session: The session to use + @param h_wrapping_key: The handle of the key to use to wrap another key + @param h_key: The key to wrap + @param encryption_flavor: The encryption flavor to create a new mechanism with if no mechanism + is provided + @param mech: The mechanism, if none is provided a blank one will be provided based on the encryption flavor + + @return: The result code, a ctypes byte array representing the new key + ''' + if mech == None: + mech = get_encryption_mechanism(encryption_flavor) + + #Get the size of the key + wrapped_key_length = CK_ULONG() + ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), None, byref(wrapped_key_length)) + if ret != CKR_OK: return ret, None + + #Actually wrap the key + output = create_string_buffer("", wrapped_key_length.value) + wrapped_key_output = cast(output, CK_BYTE_PTR) + ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), wrapped_key_output, byref(wrapped_key_length)) + + return ret, wrapped_key_output._objects.values()[0] +c_wrap_key_ex = make_error_handle_function(c_wrap_key) + +def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech = None): + ''' + Function which unwraps a key + @param h_session: The session to use + @param h_wrapping_key: The wrapping key handle + @param wapped_key: The wrapped key in a ctypes CK_CHAR_PTR array + @param key_template: The python template representing the new key's template + @param encryption_flavor: If the mechanism is not specified it will create a + default one based on the encryption flavor + @param mech: The mechanism to use, if null a default one will be created based on the encryption_flavor + + @return: The result code, the handle of the unwrapped key + ''' + if mech == None: + mech = get_encryption_mechanism(encryption_flavor) + + c_template = Attributes(key_template).get_c_struct() + byte_wrapped_key = cast(wrapped_key, CK_BYTE_PTR) + h_output_key = CK_ULONG() + ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), byte_wrapped_key, CK_ULONG(len(wrapped_key)), + c_template, CK_ULONG(len(key_template)), byref(h_output_key)) + + return ret, h_output_key.value +c_unwrap_key_ex = make_error_handle_function(c_unwrap_key) + +def get_c_data_to_sign_or_encrypt(python_data): + ''' + Function which gets the C data representation of some python data + + @param python_data: The python data to get a c representation of + + @return: A C byte pointer pointing to the C representation of the + python data + ''' + + c_data_to_sign = None + if isinstance(python_data, str): + c_data_to_sign = create_string_buffer(python_data) + c_data_to_sign = cast(c_data_to_sign, CK_BYTE_PTR) + else: + raise Exception("Please extend this function to support the type of data " + type(python_data)) + + return c_data_to_sign + diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py new file mode 100755 index 0000000..cbd35f2 --- /dev/null +++ b/pycryptoki/hsm_management.py @@ -0,0 +1,192 @@ +""" +Methods responsible for pycryptoki 'hsm management' set of commands. +""" +from ctypes import byref, create_string_buffer, cast +from pycryptoki.cryptoki import CK_SLOT_ID, CK_USER_TYPE, \ + CA_PerformSelfTest, CA_SetTokenCertificateSignature, CA_HAInit, \ + CA_CreateLoginChallenge, CA_InitializeRemotePEDVector, \ + CA_DeleteRemotePEDVector, CA_MTKRestore, CA_MTKResplit, CA_MTKZeroize, CK_ULONG, CK_BYTE_PTR, CK_BYTE, CK_CHAR_PTR, CK_CHAR +from pycryptoki.attributes import Attributes +from pycryptoki.test_functions import make_error_handle_function + + +def c_performselftest(slot, + test_type, + input_data, + input_data_len): + ''' + Test: Performs a self test for specified test type on a given slot. + + @param slot: slot number + @param test_type: type of test CK_ULONG + @param input_data: pointer to input data CK_BYTE_PTR + @param input_length: input data length CK_ULONG + @param output_data: pointer to output data CK_BYTE_PTR + @param output_length: output data length CK_ULONG_PTR + @return: the result code + + [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] + ''' + + test_type = CK_ULONG(test_type) + input_length = CK_ULONG(input_data_len) + input_data = (CK_BYTE * input_data)() + output_data = cast(create_string_buffer('', input_data_len), CK_BYTE_PTR) + output_data_len = CK_ULONG() + + ret = CA_PerformSelfTest(slot, + test_type, + input_data, + input_length, + output_data, + byref(output_data_len)) + return ret, output_data +c_performselftest_ex = make_error_handle_function(c_performselftest) + + +def ca_settokencertificatesignature(h_session, + access_level, + customer_id, + pub_template, + signature, + signature_len): + ''' + Completes the installation of a certificate on a token. + The caller must supply a public key and a signature for token certificate. + The public key is provided through the template; it must contain a key + type, a modulus and a public exponent. + + @param h_session: the current session + @param access_level: the access level + @param customer_id: the customer ID + @param pub_template: the public template + @param pub_template_length: the public template length + @param signature: the signature + @param signature_length: the length in bytes of the signature + @return: the result code + ''' + + access_level = CK_ULONG(access_level) + customer_id = CK_ULONG(customer_id) + + key_attributes = Attributes(pub_template) + pub_template_len = CK_ULONG(len(pub_template)) + signature = (CK_BYTE * signature)() + signature_length = CK_ULONG(signature_len) + ret = CA_SetTokenCertificateSignature(h_session, + access_level, + customer_id, + key_attributes.get_c_struct(), + pub_template_len, + signature, + signature_length) + return ret +ca_settokencertificatesignature_ex = \ + make_error_handle_function(ca_settokencertificatesignature) + + +def ca_hainit(h_session, h_key): + ''' + Creates a login key pair on the primary token. + + @param h_session: the current session + @param h_key: the login private key + @return: the result code + ''' + ret = CA_HAInit(h_session, h_key) + + return ret +ca_hainit_ex = make_error_handle_function(ca_hainit) + + +def ca_createloginchallenge(h_session, + user_type, + challenge): + ''' + Creates a login challenge for the given user. + + @param h_session: the current session + @param user_type: user type + @param challenge_length: challenge length + @param challenge: challenge + @param output_data_length: PIN length + @param output_data: PIN itself + @return: the result code + ''' + + challenge_length = CK_ULONG(len(challenge)) + challenge = cast(create_string_buffer(challenge), CK_CHAR_PTR) + output_data_length = CK_ULONG() + output_data = (CK_CHAR)() + ret = CA_CreateLoginChallenge(h_session, + CK_USER_TYPE(user_type), + challenge_length, + challenge, + output_data_length, + output_data) + return ret, output_data +ca_createloginchallenge_ex = \ + make_error_handle_function(ca_createloginchallenge) + + +def ca_initializeremotepedvector(h_session): + ''' + Initializes a remote PED vector + + @param h_session: the current session + @return: the result code + ''' + ret = CA_InitializeRemotePEDVector(h_session) + return ret +ca_initializeremotepedvector_ex = \ + make_error_handle_function(ca_initializeremotepedvector) + + +def ca_deleteremotepedvector(h_session): + ''' + Deletes a remote PED vector + + @param h_session: the current session + @return: the result code + ''' + ret = CA_DeleteRemotePEDVector(h_session) + return ret +ca_deleteremotepedvector_ex = \ + make_error_handle_function(ca_deleteremotepedvector) + + +def ca_mtkrestore(slot): + ''' + Restore the MTK + + @param slot: slot number + @return: the result code + ''' + ret = CA_MTKRestore(CK_SLOT_ID(slot)) + return ret +ca_mtkrestore_ex = make_error_handle_function(ca_mtkrestore) + + +def ca_mtkresplit(slot): + ''' + Resplit the MTK + + @param slot: slot number + @return: the result code + ''' + ret = CA_MTKResplit(CK_SLOT_ID(slot)) + return ret +ca_mtkresplit_ex = make_error_handle_function(ca_mtkresplit) + + +def ca_mtkzeroize(slot): + ''' + Zeroize the MTK + + @param slot: slot number + @return: the result code + ''' + ret = CA_MTKZeroize(CK_SLOT_ID(slot)) + return ret +ca_mtkzeroize_ex = make_error_handle_function(ca_mtkzeroize) + diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py new file mode 100755 index 0000000..e3749e1 --- /dev/null +++ b/pycryptoki/key_generator.py @@ -0,0 +1,150 @@ +""" +Methods used to generate keys. +""" + +from cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, CK_MECHANISM, \ + CK_MECHANISM_TYPE, CK_VOID_PTR, C_GenerateKey, C_GenerateKeyPair, C_CopyObject +from ctypes import byref, pointer, cast +from default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP +from defines import CKR_OK, CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CA_ClonePrivateKey, C_DeriveKey, \ + CK_SESSION_HANDLE +from pycryptoki.test_functions import make_error_handle_function + +def c_destroy_object(h_session, h_object_value): + ''' + Deletes the object corresponsing to the passed in object handle + @param h_session: Current session + @param h_object_value: The handle of the object to delete + + @return: The resutl code from the C_DestroyObject operation + ''' + ret = C_DestroyObject(h_session, CK_OBJECT_HANDLE(h_object_value)) + return ret +c_destroy_object_ex = make_error_handle_function(c_destroy_object) + + +def c_copy_object(h_session, h_object, template=None): + + """ + Method to call the C_CopyObject cryptoki command. + + :param h_session: Handle to the session + :param h_object: Handle to the object to be cloned + :param template: Template for the new object. Defaults to None + :return: Handle to the new cloned object. + """ + attributes = Attributes(template) + if template is None: + template_size = CK_ULONG(0) + else: + template_size = CK_ULONG(len(template)) + + h_new_object = CK_OBJECT_HANDLE() + + ret = C_CopyObject(h_session, h_object, attributes.get_c_struct(), template_size, h_new_object) + + return ret, h_new_object.value +c_copy_object_ex = make_error_handle_function(c_copy_object) + +def _get_mechanism(flavor): + ''' + Method used to get the CK_MECHANISM variable for key generation. + + @param flavor: The key flavor of the mechanism + + @return: Returns a blank mechanism of type flavor + ''' + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(flavor) + mech.pParameter = CK_VOID_PTR(0) + mech.usParameterLen = CK_ULONG(0) + return mech + +def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP): #TODO + ''' + Generates a symmetric key of a given flavor given the correct template. + + @param h_session: Current session + @param flavor: The flavour of the DES key to generate + @param template: The template to use to generate the key + + @return: Returns the result code and the key's handle + ''' + # INITALIZE VARIABLES + mech = _get_mechanism(flavor) + + key_attributes = Attributes(template) + us_public_template_size = CK_ULONG(len(template)) + + # ACTUALLY GENERATE KEY + h_key = CK_OBJECT_HANDLE() + ret = C_GenerateKey(h_session, byref(mech), key_attributes.get_c_struct(), us_public_template_size, byref(h_key)); + + return ret, h_key.value +c_generate_key_ex = make_error_handle_function(c_generate_key) + +def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None): + ''' + Generates a private and public key pair for a given flavor, and given public and private + key templates. The return value will be the handle for the key. + + @param h_session: Current session + @param flavor: The flavor of the key to generate + @param pbkey_template: The public key template to use for key generation + @param prkey_template: The private key template to use for key generation + @param mech: The mechanism to generate the key with + + @return: Returns the result code, the public key's handle, and the private key's handle + ''' + # INITALIZE VARIABLES + if mech is None: + mech = _get_mechanism(flavor) + + pbkey_template_size = len(pbkey_template) + pbkey_attributes = Attributes(pbkey_template) + + prkey_template_size = len(prkey_template) + prkey_attributes = Attributes(prkey_template) + + h_pbkey= CK_OBJECT_HANDLE() + h_prkey = CK_OBJECT_HANDLE() + ret = C_GenerateKeyPair(h_session, byref(mech), pbkey_attributes.get_c_struct(), pbkey_template_size, + prkey_attributes.get_c_struct(), prkey_template_size, byref(h_pbkey), byref(h_prkey)) + + return ret, h_pbkey.value, h_prkey.value +c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) + +def c_derive_key(h_session, h_base_key, template, mech_flavor, mech = None): + ''' + Calls C_DeriveKey + + @param h_session: The session handle to use + @param h_base_key: The base key + @param template: A python template of attributes (ex. CKM_DES_KEY_GEN_TEMP) + @param mech: The mechanism to use, if None a default mechanism will be used + + @return: The result code, The derived key's handle + ''' + + if mech == None: + mech = _get_mechanism(mech_flavor) + + h_key = CK_OBJECT_HANDLE() + c_template = Attributes(template).get_c_struct() + ret = C_DeriveKey(h_session, mech, CK_OBJECT_HANDLE(h_base_key), c_template, CK_ULONG(len(template)), byref(h_key)) + return ret, h_key.value +c_derive_key_ex = make_error_handle_function(c_derive_key) + +def clear_keys(h_session): + ''' + Quick hacked together function that can be used to clear the first 10 000 keys. + @param h_session:Current session + ''' + for i in range(1,10000): + c_destroy_object(h_session, i) diff --git a/pycryptoki/key_management.py b/pycryptoki/key_management.py new file mode 100755 index 0000000..c3d9bf5 --- /dev/null +++ b/pycryptoki/key_management.py @@ -0,0 +1,61 @@ +""" +Methods responsible for key management +""" +from pycryptoki.cryptoki import CA_GenerateMofN, CA_ModifyUsageCount, \ + CK_VOID_PTR, CK_ULONG, CA_MOFN_GENERATION, CK_BYTE, CA_MOFN_GENERATION_PTR +from pycryptoki.test_functions import make_error_handle_function + +def ca_generatemofn(h_session, + m_value, + vector_value, + vector_count, + is_secure_port_used): + ''' + Generates MofN secret information on a token. + + @param h_session: the current session + @param m_value: m + @param vectors: vectors + @param vector_count: number of vectors + @param is_secure_port_used: is secure port used + @return: the result code + ''' + reserved = CK_VOID_PTR(0) + + m_value = CK_ULONG(m_value) + vector_count = CK_ULONG(vector_count) + is_secure_port_used = CK_ULONG(is_secure_port_used) + + vector_value = (CK_BYTE * vector_value)() + vector = (CA_MOFN_GENERATION * 2)() + vector[0].ulWeight = CK_ULONG(1) + vector[0].pVector = vector_value + vector[0].ulVectorLen = CK_ULONG(16) + vector[1].ulWeight = CK_ULONG(1) + vector[1].pVector = (CK_BYTE * 16)() + vector[1].ulVectorLen = CK_ULONG(16) + vectors = CA_MOFN_GENERATION_PTR(vector) + + ret = CA_GenerateMofN(h_session, + m_value, + vectors, + vector_count, + is_secure_port_used, + reserved) + return ret +ca_generatemofn_ex = make_error_handle_function(ca_generatemofn) + + +def ca_modifyusagecount(h_session, h_object, command_type, value): + ''' + Modifies CKA_USAGE_COUNT attribute of the object. + + @param h_session: the current session + @param h_object: object + @param command_type: command type + @param value: value + @return: the result code + ''' + ret = CA_ModifyUsageCount(h_session, h_object, command_type, CK_ULONG(value)) + return ret +ca_modifyusagecount_ex = make_error_handle_function(ca_modifyusagecount) diff --git a/pycryptoki/key_usage.py b/pycryptoki/key_usage.py new file mode 100755 index 0000000..25a30c9 --- /dev/null +++ b/pycryptoki/key_usage.py @@ -0,0 +1,32 @@ +""" +Methods responsible for key usage +""" +from pycryptoki.cryptoki import CA_CloneMofN, CA_DuplicateMofN, \ + CK_VOID_PTR, CK_SESSION_HANDLE +from pycryptoki.test_functions import make_error_handle_function + +def ca_clonemofn(h_session): + ''' + Clones MofN secret from one token to another. + + @param h_session: the current session + @return: the result code + ''' + h_primary_session = CK_SESSION_HANDLE(0) + reserved = CK_VOID_PTR(0) + + ret = CA_CloneMofN(h_session, h_primary_session, reserved) + return ret +ca_clonemofn_ex = make_error_handle_function(ca_clonemofn) + +def ca_duplicatemofn(h_session): + ''' + Duplicates a set of M of N vectors. + + @param h_session: the current session + @return: the result code + ''' + ret = CA_DuplicateMofN(h_session) + return ret +ca_duplicatemofn_ex = make_error_handle_function(ca_duplicatemofn) + diff --git a/pycryptoki/logging_filters.py b/pycryptoki/logging_filters.py new file mode 100755 index 0000000..88d5064 --- /dev/null +++ b/pycryptoki/logging_filters.py @@ -0,0 +1,26 @@ +import logging +import os + +class OnlyTestsFilter(logging.Filter): + + def filter(self, record): + + file_path = os.path.realpath(__file__) + dir_path = os.path.dirname(file_path) + dir_members = os.listdir(dir_path) + files = [] + for filename in dir_members: + split_file = filename.split(".") + if len(split_file) > 1 and split_file[1] == 'py': + files.append(os.path.join(split_file[0])) + + should_show = True + + for python_file in files: + if python_file in record.getMessage(): + should_show = False + + return should_show + + + diff --git a/pycryptoki/luna_threading.py b/pycryptoki/luna_threading.py new file mode 100755 index 0000000..da52ffe --- /dev/null +++ b/pycryptoki/luna_threading.py @@ -0,0 +1,146 @@ +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, MANUFACTURER_ID, MODEL +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKR_OK +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_open_session_ex, c_get_token_info_ex, \ + c_open_session, c_close_session +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.token_management import get_token_by_label_ex, \ + c_get_mechanism_list_ex, c_get_mechanism_info_ex +import logging +import sys +import threading +import time + + +logger = logging.getLogger(__name__) + +CREATE_AND_REMOVE_KEYS = 2 +OPEN_AND_CLOSE_SESSIONS = 3 +GET_TOKEN_INFO = 4 +GET_MECHANISM_INFO = 5 + + +class TestThread(threading.Thread): + ''' + A member of the threading class which, when given the proper parameters, will + perform some functions on the HSM in it's own thread. If one of the tests fails it will be reported when all the + threads finish. + ''' + def __init__(self, queue, thread_name, token_label, thread_type, max_time = 60): #60 seconds + ''' + @param queue: The queue that the threads will be placed into, this is required to signal + to the queue that the task is done + @param thread_name: The name of the thread for debug printing purposes + @param token_label: The token label to perform multithreaded operations on + @param thread_type: The a numeric value specifyingoperation the thread will do, see the variables + described above the TestThread class declaration ex. GET_TOKEN_INFO + @param max_time: The amount of time to spend doing the test in seconds + ''' + + self.thread_name = thread_name + self.thread_type = thread_type + self.max_time = max_time + self.queue = queue + self.token_label = token_label + threading.Thread.__init__(self) + + def run(self): + ''' + Called by the inheirited threading class to run the actual thread + ''' + logger.debug("Starting thread " + self.thread_name + " type " + str(self.thread_type)) + self._return = True + + try: + #For a given amount of time run the operations in a separate thread + start_time = time.time() + while ((time.time() - start_time) < self.max_time) and ((not self.starting_slot >= self.ending_slot) or (self.starting_slot == -1 and self.ending_slot == -1)): + if self.thread_type == CREATE_AND_REMOVE_KEYS: + self.create_and_remove_keys() + elif self.thread_type == OPEN_AND_CLOSE_SESSIONS: + self.open_and_close_sessions() + elif self.thread_type == GET_TOKEN_INFO: + self.get_token_info() + elif self.thread_type == GET_MECHANISM_INFO: + self.get_mechanism_info() + else: + raise Exception("Unknown thread type " + str(self.thread_type)) + + logger.debug("Exiting thread " + self.thread_name + " type " + str(self.thread_type)) + except Exception as e: + self._return = e + self.queue.task_done() + print sys.exc_info()[0] + raise + return + + if (self._return == True): + self._return = True + self.queue.task_done() + + def get_token_info(self): + ''' + Test that will get the token info and verify that the fields have been + set to something other than null + ''' + slot = get_token_by_label_ex(self.token_label) + token_info = c_get_token_info_ex(slot) + + assert token_info['label'] == ADMIN_PARTITION_LABEL + assert token_info['manufacturerID'] == MANUFACTURER_ID + assert token_info['model'] == MODEL + assert token_info['serialNumber'] != 0 + assert token_info['flags'] != 0 + assert token_info['ulTotalPrivateMemory'] == 0 + assert token_info['ulSessionCount'] != 0 + assert token_info['ulRwSessionCount'] != 0 + assert token_info['ulMaxPinLen'] != 0 + assert token_info['ulMinPinLen'] != 0 +# token_info['hardwareVersion'] = c_token_info.hardwareVersion +# token_info['firmwareVersion'] = c_token_info.firmwareVersion + + def create_and_remove_keys(self): + ''' + Test that will create a bunch of keys and verify the attributes on + those keys + ''' + slot = get_token_by_label_ex(self.token_label) + h_session = c_open_session_ex(slot) + + logger.debug(self.thread_name + " Generating keys") + key_handle = c_generate_key_ex(h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + key_handle_public, key_handle_private = c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + + logger.debug(self.thread_name + " Verifying keys") + verify_object_attributes(h_session, key_handle, CKM_DES_KEY_GEN_TEMP) + verify_object_attributes(h_session, key_handle_public, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP) + verify_object_attributes(h_session, key_handle_private, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + + def open_and_close_sessions(self): + ''' + Test that will open and close sessions repeatedly + ''' + slot = get_token_by_label_ex(self.token_label) + + ret, h_session = c_open_session(slot) + assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] + + ret = c_close_session(h_session) + assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] + + def get_mechanism_info(self): + ''' + Test that will get the mechanism info repeatedly and verify it is non null + ''' + slot = get_token_by_label_ex(self.token_label) + mechanism_list = c_get_mechanism_list_ex(slot) + + assert len(mechanism_list) > 0, "The mechanism list should have a non zero length" + for mechanism in mechanism_list: + mech_info = c_get_mechanism_info_ex(slot, mechanism) + assert (mech_info.ulMinKeySize > 0 or mech_info.ulMaxKeySize > 0 or mech_info.flags > 0) and mech_info.ulMinKeySize <= mech_info.ulMaxKeySize, "Verifing that all fields are not 0 should be good enough for now" + diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py new file mode 100755 index 0000000..cb6dd81 --- /dev/null +++ b/pycryptoki/mechanism.py @@ -0,0 +1,136 @@ +from ctypes import c_void_p, cast, pointer, POINTER, sizeof, c_char_p, \ + create_string_buffer +from pycryptoki.cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ + CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR +from pycryptoki.defines import CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, \ + CK_CRYPTOKI_ELEMENT, CK_STORAGE_HOST, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL + + +CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, + 'ulType' : CK_CRYPTOKI_ELEMENT, + 'ulHandle' : 5, + 'ulDeleteAfterExtract' : 0, + 'pBuffer' : 0, + 'pulBufferLen' : 0, + 'ulStorage' : CK_STORAGE_HOST, + 'pedId' : 0, + 'pbFileName' : 0, + 'ctxID' : 3 + } + +CK_AES_CBC_PAD_INSERT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, + 'ulType' : CK_CRYPTOKI_ELEMENT, + 'ulContainerState' : 0, + 'pBuffer' : 0, + 'pulBufferLen' : 0, + 'ulStorageType' : CK_STORAGE_HOST, + 'pulType' : 0, + 'pulHandle' : 0, + 'ctxID' : 3, + 'pedID' : 3, + 'pbFileName' : 0, + 'ulStorage' : CK_STORAGE_HOST, + } + +supported_parameters = {'CK_AES_CBC_PAD_EXTRACT_PARAMS' : CK_AES_CBC_PAD_EXTRACT_PARAMS, + 'CK_AES_CBC_PAD_INSERT_PARAMS' : CK_AES_CBC_PAD_INSERT_PARAMS} + +def get_c_struct_from_mechanism(python_dictionary, params_type_string): + ''' + Gets a c struct from a python dictionary representing that struct + + @param python_dictionary: The python dictionary representing the C struct, + see CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP for an example + @param params_type_string: A string representing the parameter struct. + ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' + @return: A C struct + ''' + params_type = supported_parameters[params_type_string] + params = params_type() + mech = CK_MECHANISM() + mech.mechanism = python_dictionary['mechanism'] + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params_type)) + + #Automatically handle the simpler fields + for entry in params_type._fields_: + key_name = entry[0] + key_type = entry[1] + + if key_type == CK_ULONG: + setattr(params, key_name, CK_ULONG(python_dictionary[key_name])) + elif key_type == CK_ULONG_PTR: + setattr(params, key_name, pointer(CK_ULONG(python_dictionary[key_name]))) + else: + continue + + #Explicitly handle the more complex fields + if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: + if (len(python_dictionary['pBuffer']) == 0): + params.pBuffer = None + else: + params.pBuffer = (CK_BYTE * len(python_dictionary['pBuffer']))() + #params.pbFileName = 0 #TODO convert byte pointer to serializable type + pass + elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: + #params.pbFileName = TODO + params.pBuffer = cast(create_string_buffer(python_dictionary['pBuffer']), CK_BYTE_PTR) + params.ulBufferLen = len(python_dictionary['pBuffer']) + pass + else: + raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") + + return mech + +def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): + ''' + Gets a python dictionary from a c mechanism's struct for serialization + and easier test case writing + + @param c_mechanism: The c mechanism to convert to a python dictionary + @param params_type_string: A string representing the parameter struct. + ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' + + @return: A python dictionary representing the c struct + ''' + python_dictionary = {} + python_dictionary['mechanism'] = c_mechanism.mechanism + + params_type = supported_parameters[params_type_string] + params_struct = cast(c_mechanism.pParameter, POINTER(params_type)).contents + + #Automatically handle the simpler fields + for entry in params_type._fields_: + key_name = entry[0] + key_type = entry[1] + + if key_type == CK_ULONG: + python_dictionary[key_name] = getattr(params_struct, key_name) + elif key_type == CK_ULONG_PTR: + python_dictionary[key_name] = getattr(params_struct, key_name).contents.value + else: + continue + + #Explicitly handle the more complex fields + if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: + bufferLength = params_struct.pulBufferLen.contents.value + if params_struct.pBuffer == None: + bufferString = None + else: + char_p_string = cast(params_struct.pBuffer, c_char_p).value + if char_p_string != None: + bufferString = char_p_string[0:bufferLength] + else: + bufferString = None + python_dictionary['pBuffer'] = bufferString + python_dictionary['pbFileName'] = 0 #TODO + elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: + python_dictionary['pbFileName'] = 0 #TODO + python_dictionary['pBuffer'] = 0 #TODO + else: + raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") + + return python_dictionary + +if __name__ == '__main__': + pass \ No newline at end of file diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py new file mode 100755 index 0000000..be1dcdd --- /dev/null +++ b/pycryptoki/misc.py @@ -0,0 +1,151 @@ +from ctypes import create_string_buffer, cast, byref +from pycryptoki.attributes import convert_ck_char_array_to_string, \ + convert_string_to_CK_CHAR, Attributes +from pycryptoki.cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ + C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ + CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey +from pycryptoki.defines import CKR_OK +from pycryptoki.encryption import get_c_data_to_sign_or_encrypt +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.sign_verify import do_multipart_sign_or_digest +from pycryptoki.test_functions import make_error_handle_function + +def c_generate_random(h_session, length): + ''' + Generates a sequence of random numbers + + @param h_session: The current session + @param length: The length in bytes of the random number sequence + + @return: The result code, A string of random data + ''' + random_data = cast(create_string_buffer("", length), CK_BYTE_PTR) + ret = C_GenerateRandom(h_session, random_data, CK_ULONG(length)) + + random_string = convert_ck_char_array_to_string(random_data._objects.values()[0]) + return ret, random_string +c_generate_random_ex = make_error_handle_function(c_generate_random) + +def c_seed_random(h_session, seed): + ''' + Seeds the random number generator + + @param h_session: The current session + @param seed: A python string of some seed + + @return: The result code + ''' + seed_bytes = cast(convert_string_to_CK_CHAR(seed), CK_BYTE_PTR) + seed_length = CK_ULONG(len(seed)) + ret = C_SeedRandom(h_session, seed_bytes, seed_length) + return ret; +c_seed_random_ex = make_error_handle_function(c_seed_random) + +def c_digest(h_session, data_to_digest, digest_flavor, mech = None): + ''' + Digests some data + + @param h_session: Current session + @param data_to_digest: The data to digest, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, + SHA224, SHA256, SHA384, SHA512) + @param mech: The mechanism to be used. If None a blank one with the digest_flavour will be used + + @return: The result code, a python string of the digested data + ''' + + #Get mechanism if none provided + if mech == None: + mech = _get_mechanism(digest_flavor) + + #Initialize Digestion + ret = C_DigestInit(h_session, mech) + if ret != CKR_OK: return ret + + #if a list is passed out do an digest operation on each string in the list, otherwise just do one digest operation + is_multi_part_operation = isinstance(data_to_digest, list) or isinstance(data_to_digest, tuple) + + if is_multi_part_operation: + ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, C_DigestFinal, data_to_digest) + else: + #Get arguments + digest_data_length = len(data_to_digest) + c_data_to_digest = get_c_data_to_sign_or_encrypt(data_to_digest) + + #Get the length of the digested data + digest_length = CK_ULONG() + ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), None, byref(digest_length)) + if ret != CKR_OK: return ret, None + + output = create_string_buffer("", digest_length.value) + digested_data = cast(output, CK_BYTE_PTR) + + #Digest data + ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), digested_data, byref(digest_length)) + + #Convert Digested data into a python string + ck_char_array = digested_data._objects.values()[0] + digested_python_string = convert_ck_char_array_to_string(ck_char_array) + + return ret, digested_python_string +c_digest_ex = make_error_handle_function(c_digest) + +def c_digestkey(h_session, h_key, digest_flavor, mech = None): +#Get mechanism if none provided + if mech == None: + mech = _get_mechanism(digest_flavor) + + #Initialize Digestion + ret = C_DigestInit(h_session, mech) + if ret != CKR_OK: return ret + + ret = C_DigestKey(h_session, h_key) + + return ret +c_digestkey_ex = make_error_handle_function(c_digestkey) + + + +def c_create_object(h_session, template): + ''' + Creates an object based on a given python template + + @param h_session: The session handle to use + @param template: The python template which the object will be based on + + @return: The result code, the handle of the object + ''' + c_template = Attributes(template).get_c_struct() + new_object_handle = CK_ULONG() + ret = C_CreateObject(h_session, c_template, CK_ULONG(len(template)), byref(new_object_handle)) + + return ret, new_object_handle.value +c_create_object_ex = make_error_handle_function(c_create_object) + +def c_set_ped_id(slot, id): + ''' + Set the PED ID for the given slot. + @param slot : slot number + @parm id : PED ID to use + + @return: The result code + ''' + ret = CA_SetPedId(CK_SLOT_ID(slot), CK_ULONG(id)) + return ret; +c_set_ped_id_ex = make_error_handle_function(c_set_ped_id) + +def c_get_ped_id(slot): + ''' + Get the PED ID for the given slot. + @param slot : slot number + + @return: The result code and ID + ''' + pedId = CK_ULONG() + ret = CA_GetPedId(CK_SLOT_ID(slot), byref(pedId)) + return ret, pedId.value +c_get_ped_id_ex = make_error_handle_function(c_get_ped_id) diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py new file mode 100755 index 0000000..bce309c --- /dev/null +++ b/pycryptoki/object_attr_lookup.py @@ -0,0 +1,71 @@ +from ctypes import byref, sizeof +from pycryptoki.attributes import Attributes, c_struct_to_python +from pycryptoki.cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ + C_FindObjects, C_FindObjectsFinal, C_GetAttributeValue, C_SetAttributeValue +from pycryptoki.defines import CKR_OK, CKA_CLASS, CKA_LABEL, CKA_VALUE +from pycryptoki.test_functions import LunaException, make_error_handle_function + +def c_find_objects(h_session, objects_find, template_attributes, num_entries): + ''' + Calls c_find_objects and c_find_objects_init to get a python dictionary + of the objects found. + + @param h_session: The current session + @param objects_find: A python dictionary of the object template to look for + @param template_attributes: A python dictionary of the attributes to look for + @param num_entries: The number of entries to return + + @return: Returns a python dictionary of the templates of the objects found + ''' + attributes = [] + struct = Attributes(objects_find).get_c_struct() + ret = C_FindObjectsInit(h_session, struct, CK_ULONG(len(objects_find))) + if ret != CKR_OK: return ret, -1, None; + + h_ary = (CK_OBJECT_HANDLE * num_entries)() + us_total = CK_ULONG(num_entries) + ret = C_FindObjects(h_session, h_ary, CK_ULONG(num_entries), byref(us_total)) + if ret != CKR_OK: return ret, -1, None; + + #todo get attribute value for all of them + for i in range(0, us_total.value): + attribute = c_get_attribute_value_ex(h_session, h_ary[i], template_attributes) + attributes.append(attribute) + + + ret = C_FindObjectsFinal(h_session) + + return ret, h_ary[0], attributes +c_find_objects_ex = make_error_handle_function(c_find_objects) + +def c_get_attribute_value(h_session, h_object, template): + ''' + Calls C_GetAttrributeValue to get an attribute value based on a python template + @param h_session: The current session + @param h_object: The handle of the object to get attributes for + @param template: A python dictionary representing the template of the attributes to be retrieved + + @return: A python dictionary representing the attributes returned from the HSM/library + ''' + c_struct = Attributes(template).get_c_struct() + ret = C_GetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) + if ret != CKR_OK: return ret; + + return ret, c_struct_to_python(c_struct) +c_get_attribute_value_ex = make_error_handle_function(c_get_attribute_value) + +def c_set_attribute_value(h_session, h_object, template): + ''' + Calls C_SetAttributeValue to set an attribute value based on a python template + @param h_session: The current session + @param h_object: The handle of the object to get attributes for + @param template: A python dictionary representing the template of the attributes to be written + + @return: A python dictionary representing the attributes returned from the HSM/library + ''' + c_struct = Attributes(template).get_c_struct() + ret = C_SetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) + if ret != CKR_OK: return ret; + + return ret, c_struct_to_python(c_struct) +c_set_attribute_value_ex = make_error_handle_function(c_set_attribute_value) diff --git a/pycryptoki/policy_management.py b/pycryptoki/policy_management.py new file mode 100755 index 0000000..7bb8f12 --- /dev/null +++ b/pycryptoki/policy_management.py @@ -0,0 +1,50 @@ +from pycryptoki.cryptoki import CA_SetHSMPolicy, CA_SetContainerPolicy, CK_ULONG, \ + CA_SetDestructiveHSMPolicy +from pycryptoki.test_functions import make_error_handle_function + +def ca_set_hsm_policy(h_session, policy_id, policy_val): + ''' + Sets the HSM policies by calling CA_SetHSMPolicy + + @param h_session: The session handle of the administrator setting the HSM policy + @param policy_id: The ID of the policy being set + @param policy_val: The value of the policy being set + + @return: The result code + ''' + ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret +ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) + +def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): + ''' + Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy + + @param h_session: The session handle of the administrator setting the HSM policy + @param policy_id: The ID of the policy being set + @param policy_val: The value of the policy being set + + @return: The result code + ''' + ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret +ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) + +def ca_set_container_policy(h_session, container_number, policy_id, policy_val): + ''' + Sets a policy on the container. + + NOTE: With per partition SO this method should generally not be used. Instead + ca_set_partition_policies should be used + + @param h_session: The session handle of the entity with permission to change the policy + @param container_number: The container number to set the policy on. + @param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) + @param policy_val: The value to set the policy to + + @return: The result code + ''' + ret = CA_SetContainerPolicy(h_session, CK_ULONG(container_number), CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret +ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) + diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py new file mode 100755 index 0000000..57280f3 --- /dev/null +++ b/pycryptoki/pycryptoki_client.py @@ -0,0 +1,113 @@ +''' +Contains both a local and remote pycryptoki client +''' +import xmlrpclib +from pycryptoki.daemon.pycryptoki_daemon import pycryptoki_functions,\ + functions_needing_serialization +from pycryptoki.session_management import c_finalize, c_initialize_ex, c_initialize + +from LunaTAP.util.UtilityMethods import get_logger +import rpyc + +log = get_logger(__name__) + + +class RemotePycryptokiClient(): + ''' + Class forwards pycryptoki calls over xmlrpc. Some functions need more serialization + so they are directly handled, others are handled automagically by __get_attr__ + ''' + + def __init__(self, ip=None, port=None): + self.ip = ip + self.port = port + self.started = False + self.start() + + def kill(self): + #maybe we should be reloading cryptoki dll? + if self.started and not self.connection.closed: + log.info("Stopping remote pycryptoki connection.") + self.connection.close() + self.started = False + + def start(self): + if not self.started: + log.info("Starting remote pycryptoki connection") + self.connection = rpyc.classic.connect(self.ip, port=self.port) + self.server = self.connection.root + self.started = True + + def cleanup(self): + pass + + + def __getattr__(self, name): + ''' + This is the python default attribute handler, if an attribute + is not found it's probably a pycryptoki call that we forward + automagically to the server + ''' + if not self.started: + self.start() + if hasattr(self.server, name): + def wrapper(*args, **kwargs): + log.info("Running remote pycryptoki command: " + "{0}(args={1}, kwargs={2})".format(name, args, kwargs)) + return getattr(self.server, name)(*args, **kwargs) + return wrapper + else: + raise AttributeError(name) + + +class LocalPycryptokiClient(object): + ''' + Class forwards calls to pycryptoki to local client but looks identical to remote + client + ''' + + def __init__(self): + '''Nothing really to do''' + pass + + def __getattr__(self, name): + ''' + Function that overrides python attribute lookup; automagically calls + functions in pycryptoki if they're listed in the daemon + ''' + log.info("Running local pycryptoki command: {0}".format(name)) + if pycryptoki_functions.has_key(name): + if 'c_initialize' in name: + return object.__getattribute__(self, name) + return pycryptoki_functions[name] + elif functions_needing_serialization.has_key(name): + return functions_needing_serialization[name] + else: + return object.__getattribute__(self, name) + + def c_initialize_ex(self): + c_finalize() + return c_initialize_ex() + + def c_initialize(self): + c_finalize() + return c_initialize() + + def kill(self): + #nothing to do here, maybe we should unload and reload the dll + pass + + def cleanup(self): + #nothing to do here + pass + + +def deserialize_dict(dictionary): + ''' + Helper function to convert a dictionary with to + for xmlrpc + ''' + deserialized_dictionary = {} + for key, value in dictionary.iteritems(): + deserialized_dictionary[int(key)] = value + return deserialized_dictionary \ No newline at end of file diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py new file mode 100755 index 0000000..c43b36f --- /dev/null +++ b/pycryptoki/session_management.py @@ -0,0 +1,358 @@ +""" +Methods responsible for managing a user's session and login/c_logout +""" +from cryptoki import C_Initialize, CK_ULONG, C_GetSlotList, CK_BBOOL, CK_SLOT_ID, \ + CK_SLOT_INFO, C_GetSlotInfo, C_CloseAllSessions, C_GetSessionInfo, CK_SESSION_HANDLE, \ + CK_SESSION_INFO, C_OpenSession, CK_FLAGS, CK_NOTIFY, C_Login, CK_USER_TYPE, C_Logout, \ + C_CloseSession, C_InitPIN, CA_FactoryReset, \ + C_GetTokenInfo, CK_TOKEN_INFO, C_Finalize, C_SetPIN, CA_DeleteContainerWithHandle, CA_OpenApplicationID, \ + CA_CloseApplicationID, CA_Restart, CA_SetApplicationID +from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ + byref, pointer +from defines import CKR_OK +from pycryptoki.cryptoki import CA_CreateContainer, CK_VOID_PTR, \ + CK_BYTE_PTR +from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION +from pycryptoki.test_functions import make_error_handle_function +import logging +import re + +logger = logging.getLogger(__name__) + + +def c_initialize(): + ''' + Calls C_Initialize to c_initialize the board + + @return: The result code + ''' + # INITIALIZE + logger.info("C_Initialize: Initializing HSM") + ret = C_Initialize(0) + return ret; +c_initialize_ex = make_error_handle_function(c_initialize) + + +def c_finalize(): + ''' + Calls C_Finalize + + @return: The result code + ''' + logger.info("C_Finalize: Finalizing HSM") + ret = C_Finalize(0) + return ret; +c_finalize_ex = make_error_handle_function(c_finalize) + +def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): + ''' + Opens a session on a given slot + + @param slot_num: The slot to get a session on + @param flags: The flags to open the session with + @return: The result code, the session handle + ''' + #OPEN SESSION + arg3 = create_string_buffer("Application") + h_session = CK_SESSION_HANDLE() + arg3 = cast(arg3, c_void_p) #CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) + ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), pointer(h_session)) + logger.info("C_OpenSession: Opening Session. slot=" + str(slot_num)) + + return ret, h_session.value +c_open_session_ex = make_error_handle_function(c_open_session) + +def login(h_session, slot_num=1, password="userpin", user_type=1): + ''' + Login to the HSM + @param h_session: Current session + @param slot_num: Slot index to login on + @param password: Password to login with + @param user_type: User type to login as + + @return: The result code + ''' + # LOGIN + user_type = long(user_type) + pb_password = c_char_p(password) + logger.info("C_Login: Logging In. user_type=" + str(user_type) + ", slot=" + str(slot_num) + ", password=" + password) + ret = C_Login(h_session, CK_USER_TYPE(user_type), cast(pb_password, CK_BYTE_PTR), CK_ULONG(len(password))) + return ret; +login_ex = make_error_handle_function(login) + +def get_slot_info(description): + ''' + Returns a slot with a certain descriptor + + Limitation: Only returns the first slot it finds that fits the description + @param description: The name of the slot to find + + @return: THe result code, a Python dictionary representing the slots + ''' + ret, slot_dict = get_slot_dict() + + return_dict = {} + + for key in slot_dict: + if re.match(description, slot_dict[key]): + return_dict[key] = slot_dict[key] + + return ret, return_dict +get_slot_info_ex = make_error_handle_function(get_slot_info) + +def c_get_session_info(session): + ''' + :param session: + :return: + ''' + session_info = {} + c_session_info = CK_SESSION_INFO() + ret = C_GetSessionInfo(CK_SESSION_HANDLE(session), byref(c_session_info)) + + if (ret == CKR_OK): + session_info['state'] = c_session_info.state + session_info['flags'] = c_session_info.flags + session_info['slotID'] = c_session_info.slotID + session_info['usDeviceError'] = c_session_info.usDeviceError + + return ret, session_info +c_get_session_info_ex = make_error_handle_function(c_get_session_info) + +def c_get_token_info(slot_id): + ''' + Gets the token info for a given slot id + @param slot_id: Slot index to get the token info for + + @return: The result code, A python dictionary representing the token info + ''' + token_info = {} + c_token_info = CK_TOKEN_INFO() + logger.info("Getting token info. slot=" + str(slot_id)) + ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) + + if (ret == CKR_OK): + token_info['label'] = str(cast(c_token_info.label, c_char_p).value)[0:32].strip() + token_info['manufacturerID'] = str(cast(c_token_info.manufacturerID, c_char_p).value)[0:32].strip() + token_info['model'] = str(cast(c_token_info.model, c_char_p).value)[0:16].strip() + token_info['serialNumber'] = int(str(cast(c_token_info.serialNumber, c_char_p).value)[0:16].strip()) + token_info['flags'] = c_token_info.flags + token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory + token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory + token_info['ulMaxSessionCount'] = c_token_info.usMaxSessionCount + token_info['ulSessionCount'] = c_token_info.usSessionCount + token_info['ulMaxRwSessionCount'] = c_token_info.usMaxRwSessionCount + token_info['ulRwSessionCount'] = c_token_info.usRwSessionCount + token_info['ulMaxPinLen'] = c_token_info.usMaxPinLen + token_info['ulMinPinLen'] = c_token_info.usMinPinLen + token_info['ulTotalPublicMemory'] = c_token_info.ulTotalPublicMemory + token_info['ulFreePublicMemory'] = c_token_info.ulFreePublicMemory + token_info['hardwareVersion'] = c_token_info.hardwareVersion + token_info['firmwareVersion'] = c_token_info.firmwareVersion + token_info['utcTime'] = str(cast(c_token_info.utcTime, c_char_p).value)[0:16].strip() + + return ret, token_info +c_get_token_info_ex = make_error_handle_function(c_get_token_info) + +def get_slot_dict(): + ''' + Compiles a dictionary of the available slots + + @return: A python dictionary of the available slots + ''' + us_count = CK_ULONG(0) + ret = C_GetSlotList(CK_BBOOL(0), None, byref(us_count)) + if ret != CKR_OK: return ret + num_slots = (us_count.value + 1) + slot_list = (CK_SLOT_ID * num_slots)() + ret = C_GetSlotList(CK_BBOOL(0), slot_list, byref(us_count)) + if ret != CKR_OK: return ret + slot_info = CK_SLOT_INFO() + slot_dict = {} + for slot in slot_list: + C_GetSlotInfo(slot, byref(slot_info)) + slot_description = str(cast(slot_info.slotDescription, c_char_p).value)[0:63].strip() + slot_dict[slot] = slot_description + + return ret, slot_dict +get_slot_dict_ex = make_error_handle_function(get_slot_dict) + +def c_close_session(h_session): + ''' + Closes a session + @param h_session: The session to close + + @return: The result code + ''' + # CLOSE SESSION + logger.info("C_CloseSession: Closing session " + str(h_session)) + ret = C_CloseSession(h_session) + return ret +c_close_session_ex = make_error_handle_function(c_close_session) + +def c_logout(h_session): + ''' + Logs out of a given session + @param h_session: The session to log out from + + @return: The result code + ''' + logger.info("C_Logout: Logging out of session " + str(h_session)) + ret = C_Logout(h_session) + return ret +c_logout_ex = make_error_handle_function(c_logout) + +def c_init_pin(h_session, pin): + ''' + Initializes the PIN + @param h_session: Current session + @param pin: pin to c_initialize + + @return: THe result code + ''' + + logger.info("C_InitPIN: Initializing PIN to " + str(pin)) + if pin == '': + ret = C_InitPIN(h_session, None, CK_ULONG(0)) + else: + ret = C_InitPIN(h_session, cast(create_string_buffer(pin), CK_BYTE_PTR), CK_ULONG(len(pin))) + return ret +c_init_pin_ex = make_error_handle_function(c_init_pin) + +def ca_factory_reset(slot): + ''' + Does a factory reset on a given slot + @param slot: The slot to do a factory reset on + + @return: The result code + ''' + logger.info("CA_FactoryReset: Factory Reset. slot=" + str(slot)) + ret = CA_FactoryReset(CK_SLOT_ID(slot), CK_ULONG(0)) + return ret +ca_factory_reset_ex = make_error_handle_function(ca_factory_reset) + +def c_set_pin(h_session, old_pass, new_pass): + ''' + Allows a user to change their PIN + @param h_session: Session of the user + @param old_pass: The user's old password + @param new_pass: The user's desired new password + + @return: The result code + ''' + logger.info("C_SetPIN: Changing password. old_pass=" + str(old_pass) + ", new_pass=" + str(new_pass)) + if old_pass == '' and new_pass == '': + ret = C_SetPIN(h_session, None, CK_ULONG(0), + None, CK_ULONG(0)) + return ret + else: + ret = C_SetPIN(h_session, cast(create_string_buffer(old_pass), CK_BYTE_PTR), CK_ULONG(len(old_pass)), + cast(create_string_buffer(new_pass), CK_BYTE_PTR), CK_ULONG(len(new_pass))) + return ret +c_set_pin_ex = make_error_handle_function(c_set_pin) + +def c_close_all_sessions(slot): + ''' + Closes all the sessions on a given slot + @param slot: The slot to close all sessions on + + @return The result code + ''' + + logger.info("C_CloseAllSessions: Closing all sessions. slot=" + str(slot)) + ret = C_CloseAllSessions(CK_ULONG(slot)) + return ret +c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) + +def ca_create_container(h_session, storage_size, password='userpin', label='Inserted Token'): + ''' + Inserts a token into a slot without a Security Officer on the token + @param h_session: Current session + @param storage_size: The storage size of the token (0 for undefined/unlimited) + @param password: The password associated with the token + @param label: The label associated with the token + + @return: The result code, The container number + ''' + + if password == '': + container_number = CK_ULONG() + logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) + ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), None, + CK_ULONG(0), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) + logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) + return ret, container_number.value + else: + container_number = CK_ULONG() + logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) + ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), cast(create_string_buffer(password), CK_BYTE_PTR), + CK_ULONG(len(password)), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) + logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) + return ret, container_number.value +ca_create_container_ex = make_error_handle_function(ca_create_container) + +def ca_delete_container_with_handle(h_session, container_handle): + container_number = CK_ULONG(container_handle) + logger.info("CA_DeleteContainerWithHandle: Attempting to delete container with handle: {0}".format(container_handle)) + + ret = CA_DeleteContainerWithHandle(h_session, container_number) + + logger.info("CA_DeleteContainerWithHandle: Ret Value: {0}".format(ret)) + + return ret +ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) + + +def ca_openapplicationID(slot, id_high, id_low): + uid_high = CK_ULONG(id_high) + uid_low = CK_ULONG(id_low) + + logger.info("CA_OpenApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) + + ret = CA_OpenApplicationID(CK_ULONG(slot), uid_high, uid_low) + + logger.info("CA_OpenApplicationID: Ret Value: {0}".format(ret)) + + return ret +ca_openapplicationID_ex= make_error_handle_function(ca_openapplicationID) + + +def ca_closeapplicationID(slot, id_high, id_low): + uid_high = CK_ULONG(id_high) + uid_low = CK_ULONG(id_low) + + logger.info("CA_CloseApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) + + ret = CA_CloseApplicationID(CK_ULONG(slot), uid_high, uid_low) + + logger.info("CA_CloseApplicationID: Ret Value: {0}".format(ret)) + + return ret +ca_closeapplicationID_ex= make_error_handle_function(ca_closeapplicationID) + + +def ca_setapplicationID(id_high, id_low): + """ + Set the App ID for the current application. + """ + uid_high = CK_ULONG(id_high) + uid_low = CK_ULONG(id_low) + + logger.info("CA_SetApplicationID: Attempting to set App ID {0}:{1}".format(id_high, id_low)) + + ret = CA_SetApplicationID(uid_high, uid_low) + + logger.info("CA_SetApplicationID: Ret Value: {0}".format(ret)) + + return ret +ca_setapplicationID_ex= make_error_handle_function(ca_setapplicationID) + + +def ca_restart(slot): + logger.info("CA_Restart: attempting to restart") + + ret = CA_Restart(CK_ULONG(slot)) + + logger.info("CA_Restart: Ret Value: {0}".format(ret)) + + return ret +ca_restart_ex = make_error_handle_function(ca_restart) diff --git a/pycryptoki/setup/__init__.py b/pycryptoki/setup/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/pycryptoki/setup/distribute.py b/pycryptoki/setup/distribute.py new file mode 100755 index 0000000..6dcda37 --- /dev/null +++ b/pycryptoki/setup/distribute.py @@ -0,0 +1,37 @@ +import argparse +import os +import sys +import initialize + +print "PyCryptoki Source Code Distribution" +print "Use -h for argument information." + +parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and creates a source tarball in pycryptoki/dist..") +parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") +parser.add_argument('-dll', metavar='', required=True, help="The path to the libCryptoki2.so which will be opened and parsed, this must be the dll corresponding to Luna's components sandbox.") + +print "-------------------------------------------------------" +print " Autogenerating Python Bindings to Cryptoki" +print "-------------------------------------------------------" + +args = parser.parse_args() +options = vars(args) + +#Create all of the necessary automatically generated source +xml_output = 'h2xmlout_tmp.xml' + +if not (options['dll'] == None): + dll_path = options['dll'] +else: + if "linux" in sys.platform: + dll_path = '/usr/lib/libCryptoki2.so' + else: + raise Exception("Platform not yet supported.") + +initialize.initialize(options['lib'], dll_path) + +print "-------------------------------------------------------" +print " Packaging Source Distribution" +print "-------------------------------------------------------" +os.chdir("../../") +os.system('python setup.py sdist') \ No newline at end of file diff --git a/pycryptoki/setup/initialize.py b/pycryptoki/setup/initialize.py new file mode 100755 index 0000000..f8b9d28 --- /dev/null +++ b/pycryptoki/setup/initialize.py @@ -0,0 +1,403 @@ +""" +Setup script that will automatically generate the cryptoki.py and defines.py files. +This will get your library from your LUNA_LIBRARY environment variable and generate these +files. These files contains the defines that are in the C code and in addition contain the +CTypes formatted structs contained in the C code. + +Cryptoki.py contains the CTypes templates for the C Structs that are in the cryptoki C code. +Defines.py is a crude wrapper around a number of header files that uses a bad regular expression to +harvest the defines. + +Download gccxml from CVS (note: CVS seems to be blocked on the CVS network, you can get this from smb://172.20.11.83/ftp/forMike) +Compile gccxml +1) Recursively run dos2unix on gccxml source tree (find . -name *.* -exec dos2unix {} \;) +2) Create a folder in the same directory as gccxml is in called gccxml-build (ex /home/mhughes/gccxml and /home/mhughes/gccxml-build) +3) cd gccxml-build +4) cmake ../gccxml -DCMAKE_INSTALL_PREFIX:PATH=/home/mhughes/gccxml-build +5) make +6) make install +7) Add gccxml folder to your path + +Install python +Install python packages needed for ctypes +1) sudo pip install ctypes +2) sudo easy_install ctypeslib==dev + +Make sure pycryptoki and pycryptoki/utils are in your PYTHONPATH. In eclipse: +1) Right click on your project +2) Select Properties +3) Select PyDev - PYTHONPATH +4) Add source folder +5) Add pycryptoki and pycryptoki/utils + +Set you LUNA_LIBRARY environment variable to the path to your library. It is assumed that your +dll is in the proper path in the library +""" +from ctypeslib import h2xml, xml2py +import argparse +import os +import platform +import re +import stat +import sys + +ret_list = [] +header_files = [os.path.join("interfaces", "Include", "firmware", "luna2if.h")] +dll_path_var_name = 'DLL_PATH' +cryptoki_filename = os.path.join("..", "cryptoki.py") + +def is_nextgen_check(library_path): + ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') + return os.path.exists(ctlib_path) + +def initialize(library_path=None, dll_path=None): + ''' + Creates the cryptoki.py, defines.py and return_values.py files. + :param library_path: The path to the MKS Components sandbox + ''' + xml_output = 'h2xmlout_tmp.xml' + + library_path = parse_library(library_path, xml_output) + cryptoki_dll_path = dll_path + convert_to_python_binding(cryptoki_dll_path, xml_output, cryptoki_filename) + print "Finished!" + +def change_cryptoki_dll_path(new_dll_path): + if not os.path.exists(cryptoki_filename): + raise Exception("Error... cryptoki.py not found.") + + print "Removing references to DLL in cryptoki.py to achieve late binding to DLL" + + #Read in the current file + cryptoki_file = open(cryptoki_filename, "r") + file_contents = cryptoki_file.read() + cryptoki_file.close() + + #Create a backup + try: + os.remove(cryptoki_filename + ".bak") + except: + #Don't care this was only removing the old backup if one existed + pass + + print "Creating backup: cryptoki.py.bak" + os.rename(cryptoki_filename, cryptoki_filename + ".bak") + + #Find the previous path + print re.findall("CDLL\((.*)\)", file_contents)[0] + current_path = re.findall("CDLL\((.*)\)", file_contents)[0] + + if "win" in platform.system(): + current_path = current_path.replace("\\", '~').replace('~', '\\\\\\\\') + + new_contents = file_contents.replace(current_path, new_dll_path) + + #Remove all references to DLL to load it later + new_contents = re.sub("_libraries\s*=\s*{}\s*", "", new_contents) + new_contents = re.sub("_libraries\[DLL_PATH\]\s*=\s*CDLL\(DLL_PATH\)\s*", "", new_contents) + + #Windows needs to have _pack_ = 1 for every single struct, has to be declared before _fields_ is set + struct_names = re.findall("(\S+)\._fields_\s=\s", new_contents) + fields = re.compile("\S+\._fields_\s=\s[^\]]*]", re.MULTILINE | re.DOTALL) + field_declaration = re.findall(fields, new_contents) + + assert len(field_declaration) == len(struct_names) + for i in range(0, len(field_declaration)): + add_pack_string = "if 'win' in sys.platform:\n " + struct_names[i] + "._pack_ = 1\n" + field_declaration[i] + + new_contents = new_contents.replace(field_declaration[i], add_pack_string) + + with open(cryptoki_filename, 'w') as new_file: + new_file.write(new_contents) + + +def change_cryptoki_dll_binding(): + + print "Replacing ctypes cryptoki function definitions, in " + cryptoki_filename + ", with factory functions for later binding to the DLL" + + #Read in the current file + cryptoki_file = open(cryptoki_filename, "r") + file_contents = cryptoki_file.read() + cryptoki_file.close() + + #Find all of the lines declaring functions on the DLL + found = re.findall("_libraries\[DLL_PATH\]\.(\S*)", file_contents) + + #Replace all of the functions to have a late binding + new_contents = file_contents + for function_name in found: + new_contents = re.sub("_libraries\[DLL_PATH\]\." + function_name + "\s", "make_late_binding_function('" + function_name + "')\n", new_contents) + + #Write the final contents out + with open(cryptoki_filename, 'w') as new_file: + new_file.write(new_contents) + +def parse_library(library_path, xml_output): + defines_filename = os.path.join("..", "defines.py") + return_vals_filename = os.path.join("..", "return_values.py") + + if library_path == None: + if not os.environ.has_key('LUNA_LIBRARY'): + raise Exception("LUNA_LIBRARY environment variable is not set, it needs to be set to the path of your luna source code.") + + library_path = os.environ['LUNA_LIBRARY'] + print "Using LUNA_LIBRARY Environment variable as location of Luna's Library: " + library_path + else: + print "Using argument 1 as location of Luna's Library: " + library_path + + + #If we are on a next gen branch then throw an error if the library is not compiled because + #we will be missing an automatically generated header file + if os.path.exists(os.path.join(library_path, 'CoreLibrary', 'ctToken_lib', 'source')): + if os.path.exists(os.path.join(library_path, 'interfaces', 'include', 'cryptoki', 'sfnt_ext_list_members.h')): + raise Exception("Error: sfnt_ext_list_members.h not found. You need to compile the Components library before being able to generate the Python to C Ctypes binding.") + + _parse_headers(xml_output, library_path) + + #Add all of the header files that you would like the script to parse, + #it should be noted that the script just does simple regular expression matching + #and is very simple and could break on previously unencountered syntaxes. It is + #just a hack to make life easier + token_path = os.path.join("tools", "ekmtest", "token.h") + if os.path.exists(os.path.join(library_path, token_path)): + header_files.append(token_path) + + #if it has this library it is next gen + if is_nextgen_check(library_path): + header_files.append(os.path.join("interfaces", "Include", "RSA", "pkcs11t.h")) + header_files.append(os.path.join("CoreLibrary", "includes", "cryptoki_v2.h")) + else: + header_files.append(os.path.join("interfaces", "Include", "cryptoki", "RSA", "pkcs11t.h")) + header_files.append(os.path.join("interfaces", "Include", "cryptoki", "cryptoki_v2.h")) + + _get_defines(library_path, defines_filename, header_files) + _output_return_values(return_vals_filename, ret_list) + return library_path + +def _parse_headers(xml_output, library_path=None): + ''' + Using h2xml this function parses the cryptoki header file and generates xml + output which describes the library + :param xml_output:The filename to output the xml to + :param library_path:The path to the root of the cryptoki library + ''' + + print "Parsing luna source with GCC-XML to generate XML representation of C source" + + if os.path.exists(xml_output): + os.remove(xml_output) + + #Create a file to pull everything in + temp_include_filename = 'master_header_file.h' + if os.path.exists(temp_include_filename): + os.remove(temp_include_filename) + + ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') + is_nextgen = is_nextgen_check(library_path) + + master_include_file = open(temp_include_filename, 'w'); + if is_nextgen: + master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'pkcs11Utils', 'Utils.h"') + '\n') + else: + master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source', 'Utils.h"') + '\n') + master_include_file.write('#include "cryptoki.h"\n') + master_include_file.close() + + args = ['h2xml.py', os.path.join(os.getcwd(), temp_include_filename), '-o', xml_output, + '-I', os.path.join(library_path, 'interfaces', 'Include'), + '-I', os.path.join(library_path, 'interfaces', 'Include', 'cryptoki'), + '-I', os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source')] + + if is_nextgen: + args.append('-I') + args.append(ctlib_path) + args.append('-I') + args.append(os.path.join(library_path, 'CoreLibrary', 'util_vob', 'Include')) + + if "linux" in sys.platform: + print "Detected linux OS" + args.append('-D') + args.append('OS_LINUX') + else: + #Your operating system probably just needs to be added, might not need any special parameters + raise Exception("Error: Could not generate python to c ctypes library. Unsupported Operating System, a build on linux should work everywhere so just use it.") + + if (which("gccxml") == None and which("gccxml.exe") == None): + raise Exception("No gccxml executable found in path.") + + h2xml.compile_to_xml(args) + + if os.path.exists(temp_include_filename): + os.remove(temp_include_filename) + +def convert_to_python_binding(cryptoki_dll_path, temp_file, output_filename): + ''' + Using xml2py.py in ctypeslib this function generates the python file based + upon the xml output of h2xml. This python file is the binding between python + and C. + :param cryptoki_dll_path: The path to libCryptoki.so + :param temp_file: The xml output of h2xml.py + :param output_filename: The filename to output the binding to + ''' + print "Parsing GCC-XML output to generate python code for binding to C, writing to " + output_filename + + if os.path.exists(output_filename): + os.chmod(output_filename, stat.S_IWRITE) + os.remove(output_filename) + + args = ['xml2py.py', temp_file, '-l', cryptoki_dll_path, '-o', output_filename] + xml2py.main(args) + + change_cryptoki_dll_path(dll_path_var_name) + initial_function = '\nfrom pycryptoki.cryptoki_helpers import make_late_binding_function\nimport sys\n' + + change_cryptoki_dll_binding() + + _prepend_to_file(output_filename, initial_function) + + comment = "This file contains all of the ctypes definitions for the cryptoki library.\n" + comment = comment + "The ctypes definitions outline the structures for the cryptoki C API.\n" + _prepend_auto_file_warning(output_filename, comment) + +def _store_defines(head_filename, output_filename): + ''' + Converts all of the simple defines (defines to numbers) in a c header file to a + variable declaration in python and appends these declarations to an output file. + + This is a really hackish way of getting the defines which actually hard codes out + defines that are formatted wrong and cause errors. Done this way to get it done real + quick and imports 99% of what is needed. + + :param head_filename: The filename of the header to get the defines from + :param output_filename: The .py file to append the python style defines in + ''' + print "Getting defines from: " + str(head_filename) + + #Read in file + head_file = open(head_filename, "r") + text = head_file.read(); + + #Find all the simple defines (defines to numbers) + regex_list = re.findall(r"#define[ \t\r\f\v]+([A-Z]+[A-Za-z_0-9]+[ \t\r\f\v]+[^~\n]*)[\n]", text) + #regex_list = re.findall(r"#define[ \t\r\f\v]([\S]+[ \t\r\f\v]*[0-9]+[0-9A-Za-z]*)[\n]", text) + + #Put an equals sign in them so they are properly formatted and append them to the file + out_file = open(output_filename, "a") + out_file.write("'''" + head_filename + "'''\n") + + for entry in regex_list: + if not (entry.find("CK_POINTER") > -1 or entry.find("CK_PTR") > -1 + or entry.find("CK_ENTRY") > -1 or entry.find("C_VERSION") > -1 + or entry.find("LUNA_PARTITION_HDR_HMAC_SIZE") > -1 + or entry.find("FW_VERSION_CONF_ROLES") > -1): #XXX This is to account for function calls, should be accounted for in the regex above + entry = entry.replace('\t', ' ') #clean up tabs + entry = entry.replace(' ', '=', 1) + entry = entry.replace('//', '#') + entry = entry.replace('/*', '#') + out_file.write(entry + "\n") + + dict_entry = entry.split('=') + if 'CKR' in dict_entry[0][0:3]: + ret_list.append(dict_entry[0]) + + #Cleanup + out_file.close() + head_file.close() + +def _output_return_values(output_filename, ret_list): + ''' + Creates a file which contains a dictionary for looking up + the String values of the various defines in cryptoki. + + :param output_filename: The filename to output the dictionary to + :param ret_list: The list of return values generated when getting the + defines + ''' + + print "Creating dictionary of return value strings by scraping Luna's source, writing to: " + output_filename + + if os.path.exists(output_filename): + os.remove(output_filename) + + ret_vals_file = open(output_filename, "a") + ret_vals_file.write("from defines import *\n\n") + + ret_vals_file.write("ret_vals_dictionary = { \n") + for entry in ret_list: + ret_vals_file.write("\t" + entry + " : '" + entry + "'") + if not ret_list[len(ret_list) - 1] == entry: + ret_vals_file.write(',') + ret_vals_file.write('\n') + ret_vals_file.write("}") + ret_vals_file.close() + + comment = "This file contains a dictionary lookup for the readable string values\n" + comment = comment + "of defines whose variable name starts with CKR_. This convention means they are\n" + comment = comment + "a return value for the cryptoki C API.\n\n" + _prepend_auto_file_warning(output_filename, comment) + +def _get_defines(path_to_library, out_filename, header_files): + ''' + Gets all of the defines in a set of c files specified in the header_files variable as a list + of strings. That list is relative to the path_to_library variable. Everything is stored in + out_filename in python format. + :param path_to_library: The path to the MKS Components sandbox + :param out_filename: The .py filename to save the python style defines to + :param header_files: The header files to harvest the defines from + ''' + + print "Scraping Luna's source to convert C defines to python, writing to: " + str(out_filename) + if (os.path.exists(out_filename)): + os.remove(out_filename) + + for header_file in header_files: + head_filename = os.path.join(path_to_library, header_file) + _store_defines(head_filename=head_filename, output_filename=out_filename) + + comment = "This file contains defines which have been automatically scraped from the\n" + comment = comment + "cryptoki API header files. The defines are stored as variables in python.\n" + comment = comment + "If you add any new defines you can rerun initialize.py to regenerate this file.\n" + comment = comment + "If you need to scrape another header file add the desired file to the header_files\n" + comment = comment + "array in initialize.py and rerun initialize.py.\n" + _prepend_auto_file_warning(out_filename, comment) + +def _prepend_auto_file_warning(filename, comment): + beginning_comment = "'''\n" + beginning_comment = beginning_comment + "THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE\n" + beginning_comment = beginning_comment + "This file should NOT be checked into MKS or modified in any way, this file was\n" + beginning_comment = beginning_comment + "created by setup/initialize.py. Any changes to this file will be wiped out when\n" + beginning_comment = beginning_comment + "it is regenerated.\n\n" + beginning_comment = beginning_comment + comment + beginning_comment = beginning_comment + "'''\n\n" + + _prepend_to_file(filename, beginning_comment) + +def _prepend_to_file(filename, text_to_prepend): + with file(filename, 'r') as original: data = original.read() + with file(filename, 'w') as modified: modified.write(text_to_prepend + data) + +def which(program): + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + + return None + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding.") + parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") + parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") + args = parser.parse_args() + options = vars(args) + + initialize(options['lib'], options['dll']) + diff --git a/pycryptoki/setup/make_and_install.py b/pycryptoki/setup/make_and_install.py new file mode 100755 index 0000000..a59c105 --- /dev/null +++ b/pycryptoki/setup/make_and_install.py @@ -0,0 +1,29 @@ +''' +Script used to automatically generate python code bindings to the cryptoki library +and install the pycryptoki module in the system. +''' +import argparse +from pycryptoki.setup.initialize import initialize +import os +import sys + +parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and installs pycryptoki package.") +parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") +parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") + +print "-------------------------------------------------------" +print " Autogenerating Python Bindings to Cryptoki" +print "-------------------------------------------------------" + +options = vars(parser.parse_args()) +initialize(options['lib'], options['dll']) + +print "" +print "-------------------------------------------------------" +print " Installing PyCryptoki Python Module" +print "-------------------------------------------------------" +if "linux" in sys.platform: + os.chdir(os.path.join("..", "..")) + os.system('sudo python setup.py install') +else: + raise Exception("Unsupported operating system, you'll have to add support for it.") \ No newline at end of file diff --git a/pycryptoki/setup/setup_tools.sh b/pycryptoki/setup/setup_tools.sh new file mode 100755 index 0000000..6e3103f --- /dev/null +++ b/pycryptoki/setup/setup_tools.sh @@ -0,0 +1,32 @@ + +if [ $# -ne 2 ] + then + echo "ERROR: No username and password specified to access gccxml source code from the wiki. Argument 1 must be the username to the safenet wiki, Argument 2 must be the password to the safenet wiki." + echo "Example ./setup_tools.sh mhughes mypassword" + exit -1 +fi +#Set up CMake +wget http://www.cmake.org/files/v2.8/cmake-2.8.8.tar.gz +tar -xzvf cmake-2.8.8.tar.gz +cd cmake-2.8.8 +./configure +gmake +gmake install +cd .. + +#Set up gcc-xml +wget http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Files/gccxml.tar.gz --user=$1 --password=$2 +tar -xzvf gccxml.tar.gz +cd gccxml +find . -name *.* \ tr -d '\r' +cd .. +mkdir gccxml-build +cd gccxml-build +../cmake-2.8.8/bin/cmake ../gccxml -DCMAKE_INSTALL_PREFIX:PATH=. +make +make install + +#Update the user's path +cd bin +export PATH=$PATH:$PWD +echo "export PATH=\$PATH:${PWD}" >> ~/.bashrc diff --git a/pycryptoki/setup/verify_version.py b/pycryptoki/setup/verify_version.py new file mode 100755 index 0000000..3d55cd7 --- /dev/null +++ b/pycryptoki/setup/verify_version.py @@ -0,0 +1,36 @@ +''' +This function just goes through and imports every file and reports back which files have errors +in them for the purpose of compatibility between python versions. + +''' +import os, os.path + +def verify_import(): + failed_files = "" + for root, dirs, files in os.walk("../."): + for f in files: + fullpath = os.path.join(root, f) + if (fullpath.endswith("py")): + split_path = fullpath.split('/') + folder_names = "" + verify = True + if (len(split_path) > 3): + + for folder in split_path[2:len(split_path) - 1]: + if folder == "setup": + verify = False + folder_names = folder_names + str(folder) + "." + if verify: + print fullpath + cmd = "from pycryptoki." + folder_names + str(f).split(".")[0] + " import *" + print "\t" + cmd + try: + exec cmd + except Exception as e: + print "\tERROR:" + print "\t" + str(e) + failed_files = failed_files + str(f) + "\n\t" + print "\n------SUMMARY------" + print "Failed:\n\t" + failed_files +if __name__ == '__main__': + verify_import() \ No newline at end of file diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py new file mode 100755 index 0000000..48a3e55 --- /dev/null +++ b/pycryptoki/sign_verify.py @@ -0,0 +1,249 @@ +from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ + CK_BYTE_PTR, C_SignInit, C_Sign +from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p +from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ + CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ + CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ + CKM_SHA512, CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, \ + CKG_MGF1_SHA512 +from pycryptoki.attributes import convert_ck_char_array_to_string +from pycryptoki.cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ + C_SignFinal, C_VerifyUpdate, C_VerifyFinal, CK_RSA_PKCS_PSS_PARAMS +from pycryptoki.encryption import _get_string_from_list, \ + get_c_data_to_sign_or_encrypt +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def get_mechanism_for_sigver(flavour): + """ + Tries to build a default mechanism if none is provided, + most mechanisms just need the .pParameter field to be null. + If they don't the mechanism can be instantiated here. + """ + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(flavour) + + default_salt_len = 8 + if flavour == CKM_RSA_PKCS_PSS or \ + flavour == CKM_SHA1_RSA_PKCS_PSS: + + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA_1) + p.mgf = CK_ULONG(CKG_MGF1_SHA1) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA224_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA224) + p.mgf = CK_ULONG(CKG_MGF1_SHA224) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA256_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA256) + p.mgf = CK_ULONG(CKG_MGF1_SHA256) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA384_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA384) + p.mgf = CK_ULONG(CKG_MGF1_SHA384) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA512_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA512) + p.mgf = CK_ULONG(CKG_MGF1_SHA512) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + else: + mech.pParameter = CK_VOID_PTR(0) + mech.usParameterLen = CK_ULONG(0) + return mech + +def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech = None): + ''' + Performs a C_SignInit and C_Sign operation on some data + + @param h_session: The current session + @param sign_flavor: The flavour of signing to do + @param data_to_sign: The data to sign, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param h_key: The key to sign the data with + @param mech: The mechanism to use, if None a blank mechanism will be created based on the sign_flavor + + @return The result code, A python string represeting the signature + ''' + + #Get the mechanism + if (mech == None): + mech = get_mechanism_for_sigver(sign_flavor) + + #Initialize the sign operation + ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) + if ret != CKR_OK: return ret, None + + #if a list is passed out do a sign operation on each string in the list, otherwise just do one sign operation + is_multi_part_operation = isinstance(data_to_sign, list) or isinstance(data_to_sign, tuple) + + if is_multi_part_operation: + ret, signature_string = do_multipart_sign_or_digest(h_session, C_SignUpdate, C_SignFinal, data_to_sign) + else: + #Prepare the data to sign + c_data_to_sign = get_c_data_to_sign_or_encrypt(data_to_sign) + plain_date_len = CK_ULONG(len(data_to_sign)) + + #Get the length of the output + sign_len = CK_ULONG() + ret = C_Sign(h_session, c_data_to_sign, plain_date_len, None, byref(sign_len)) + if ret != CKR_OK: return ret, None + + #Actually get the signature + signature_buffer = create_string_buffer("", sign_len.value) + signature = cast(signature_buffer, CK_BYTE_PTR) + ret = C_Sign(h_session, c_data_to_sign, plain_date_len, signature, byref(sign_len)) + + ck_char_array = signature._objects.values()[0] + signature_string = '' + if sign_len.value > 0: + signature_string = convert_ck_char_array_to_string(ck_char_array)[0:(sign_len.value)] + + return ret, signature_string +c_sign_ex = make_error_handle_function(c_sign) + +def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, input_data_list): + ''' + Does a multipart sign or digest operation + ''' + max_data_chunk_size = 0xfff0 + plain_data_len = len(_get_string_from_list(input_data_list)) + + remaining_length = plain_data_len + python_string = '' + i = 0 + while remaining_length > 0: + current_chunk = input_data_list[i] + + #Prepare arguments for decrypt update operation + current_chunk_len = min(len(current_chunk), remaining_length) + + if current_chunk_len > max_data_chunk_size: + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + + ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len)) + if ret != CKR_OK: return ret, None + + remaining_length -= current_chunk_len + + i += 1 + + #Finalizing multipart decrypt operation + out_data_len = CK_ULONG(max_data_chunk_size) + output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) + ret = c_final_function(h_session, output, byref(out_data_len)) + + #Get output + ck_char_array = output._objects.values()[0] + if (out_data_len.value > 0): + python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + + return ret, python_string + +def do_multipart_verify(h_session, input_data_list, signature): + ''' + Does a multipart verify operation + ''' + max_data_chunk_size = 0xfff0 + plain_data_len = len(_get_string_from_list(input_data_list)) + + remaining_length = plain_data_len + i = 0 + while remaining_length > 0: + current_chunk = input_data_list[i] + + #Prepare arguments for decrypt update operation + current_chunk_len = min(len(current_chunk), remaining_length) + + if current_chunk_len > max_data_chunk_size: + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + + ret = C_VerifyUpdate(h_session, data_chunk, CK_ULONG(current_chunk_len)) + if ret != CKR_OK: return ret + + remaining_length -= current_chunk_len + + i += 1 + + #Finalizing multipart decrypt operation + out_data_len = CK_ULONG(len(signature)) + output = cast(get_c_data_to_sign_or_encrypt(signature), CK_BYTE_PTR) + ret = C_VerifyFinal(h_session, output, out_data_len) + + return ret + +def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + ''' + Returns the result code of C_Verify which indicates whether or not the signature is + valid. + + @param h_session: The current session + @param h_key: The key handle to verify the signature against + @param verify_flavor: The flavour of the mechanism to verify against + @param data_to_verify: The data to verify, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param signature: The signature of the data + @param mech: The mechanism to use, if None is specified the mechanism will + try to be automatically obtained + + @returns The result code + ''' + + #Get the mechanism + if mech == None: + mech = get_mechanism_for_sigver(verify_flavor) + + #Initialize the verify operation + ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) + if ret != CKR_OK: return ret + + #if a list is passed out do a verify operation on each string in the list, otherwise just do one verify operation + is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(data_to_verify, tuple) + + if is_multi_part_operation: + ret = do_multipart_verify(h_session, data_to_verify, signature) + else: + #Prepare the data to verify + c_data_to_verify = get_c_data_to_sign_or_encrypt(data_to_verify) + plain_date_len = CK_ULONG(len(data_to_verify)) + + c_signature = get_c_data_to_sign_or_encrypt(signature) + + #Actually verify the data + ret = C_Verify(h_session, c_data_to_verify, plain_date_len, c_signature, CK_ULONG(len(signature))) + + return ret + +c_verify_ex = make_error_handle_function(c_verify) + diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py new file mode 100755 index 0000000..91d28af --- /dev/null +++ b/pycryptoki/test_functions.py @@ -0,0 +1,206 @@ +from ctypes import byref +from defines import CKR_OK +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize +from pycryptoki.defines import CKR_OBJECT_HANDLE_INVALID +from return_values import ret_vals_dictionary +import inspect +import logging + +logger = logging.getLogger(__name__) + +def assert_test_return_value(value, expected_value, message, print_on_success=True): + ''' + Asserts a pass or fail based on whether the value parameter is equal to the expected_value parameter. + Used to test the results of pkcs11 functions and looks up human readable strings for the various error codes. + Prints out results in a consistent format. + @param value: The return value of the pkcs11 function + @param expected_value: The expected return value to be tested against + @param message: Message to print on success/failure + @param print_on_success: Whether or not to print if the test case passes + ''' + if value in ret_vals_dictionary: + code = ret_vals_dictionary[value] + else: + code = "Unknown Code=" + str(hex(value)) + + if expected_value in ret_vals_dictionary: + exp_code = ret_vals_dictionary[expected_value] + else: + exp_code = "Unknown Code=" + str(hex(value)) + + assert value==expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + "\n\tFound: " + code + + if print_on_success: + logger.info(exp_code + ": " + message) + + +def assert_test_case(result, message, print_on_success=False): + ''' + Simple wrapper around assert that allows for a consistent way to report successes/failures + @param result: A boolean representing the result of the test + @param message: The message to print on test failure + ''' + assert result, "\nERROR: " + message + if print_on_success: + logger.info("PASSED: " + message) + +class LunaException(Exception): + ''' + A class representing an exception in luna, it's in place because + it has some nice functionailty to print out the contents of the error + ''' + def __init__(self, error_code, function_name, arguments): + ''' + @param error_code: The error code of the error + @param function_name: The name of the function + @param arguments: The arguments passed into the function + ''' + self.error_code = error_code + self.function_name = function_name + self.arguments = arguments + + if self.error_code in ret_vals_dictionary: + self.error_string = ret_vals_dictionary[self.error_code] + else: + self.error_string = "Unknown Code=" + str(hex(self.error_code)) + + def __str__(self): + return "\n\tFunction: " + str(self.function_name) + "\n\tError: " + str(self.error_string) \ + + "\n\tError Code: " + str(hex(self.error_code)) + "\n\tArguments: " + str(self.arguments) + +class LunaReturn(): + def __init__(self, return_code, return_data): + self.return_code = return_code + self.return_data = return_data + +def verify_object_attributes(h_session, h_object, expected_template): + ''' + Verifies that an object generated has the correct attributes on the board. + The expected attributes are passed in alongside the handle of the object. + + @param h_session: Current session + @param h_object: Handle of the object to verify the attributes against + @param expected_template: The expected template to compare against + ''' + + # VERIFY OBJECT EXISTS + h_object = CK_OBJECT_HANDLE(h_object) + us_size = CK_ULONG() + ret = C_GetObjectSize(h_session, h_object, byref(us_size)) + assert_test_case(ret == CKR_OK, "Object " + str(h_object) + " exists") + assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.") + + # VERIFY ATTRIBUTES are the same as the ones passed in + attr = Attributes() + attr.retrieve_key_attributes(h_session, h_object.value) + expected_attributes = Attributes(expected_template) + assert_test_case(attr == expected_attributes, "Object " + str(h_object.value) + " attributes match expected attributes") + +def verify_object_exists(h_session, h_object, should_exist=True): + ''' + Queries the HSM to determine if an object exists. Asserts whether or not + it exists. + + @param h_session: The current session + @param h_object: The object to verify if it exists + @param should_exist: Whether or not the parameter should exist (Use to determine how this function asserts) + ''' + # VERIFY OBJECT EXISTS + h_object = CK_OBJECT_HANDLE(h_object) + us_size = CK_ULONG() + + if should_exist: + expected_ret = CKR_OK + out = "Verifying object " + str(h_object) + " exists." + else: + expected_ret = CKR_OBJECT_HANDLE_INVALID + out = "Verifying object " + str(h_object) + " doesn't exist." + + try: + ret = C_GetObjectSize(h_session, h_object, byref(us_size)) + except LunaException as e: + assert_test_case(e.error_code == expected_ret, out) + else: + assert_test_case(ret == expected_ret, out) + + if should_exist: + assert_test_return_value(ret, CKR_OK, "Getting object " + str(h_object.value) + "'s size", True) + assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.", False) + else: + assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, "Getting object " + str(h_object.value) + "'s size", True) + assert_test_case(us_size.value <= 0, "Object " + str(h_object.value) + " size is greater than zero.", False) + +def check_luna_exception(ret, luna_function, *args): + ''' + + ''' + arg_spec = inspect.getargspec(luna_function).args + arg_string = "(" + i = 0 + if (len(arg_spec) > 0): + for argument in args: + arg_string = arg_string + arg_spec[i] + "=" + str(argument) + + if i != (len(args) - 1): + arg_string = arg_string + ", " + i = i + 1 + + arg_string = arg_string + ")" + if ret != CKR_OK: raise LunaException(ret, luna_function.__name__, arg_string) + +def make_error_handle_function(luna_function): + ''' + This function is a helper function that creates a new function which checks the + result code returned from a function in luna. It is called by calling: + + c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) + + This code will create a c_generate_key_pair_ex which will call c_generate_key_pair and check the + first argument. The first argument is the return code of c_generate_key_pair. If the return + code != CKR_OK then c_generate_key_pair_ex will raise a LunaException. You can call c_generate_key_pair_ex + as if it is c_generate_key_pair: + + c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + + The return values of c_generate_pair are (ret, public_key_handle, private_key_handle) + + The return values of c_generate_pair_ex are (public_key_handle, private_key_handle) + + This lets you create two versions of a function. One version is for setup and + the other version is for testing the result. + + Directly testing the result: + ret = c_initialize() + assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" + + Expecting the call to go through without error. The test case should have an error (not a failure): + c_initialize_ex() + + This should therefore make for shorter test cases + ''' + + def luna_function_exception_handle(*args, **kwargs): + return_tuple = luna_function(*args, **kwargs); + if isinstance(return_tuple, tuple): + if (len(return_tuple) > 2): + return_data = return_tuple[1:] + ret = return_tuple[0] + elif (len(return_tuple) == 2): + return_data = return_tuple[1] + ret = return_tuple[0] + else: + return_data = return_tuple[0] + ret = return_tuple[0] + elif isinstance(return_tuple, long): + ret = return_tuple + return_data = return_tuple + else: + raise Exception("Functions wrapped by the exception handler should return a tuple or just the long representing Luna's return code.") + + check_luna_exception(ret, luna_function, args) + return return_data + return luna_function_exception_handle + + diff --git a/pycryptoki/tests/__init__.py b/pycryptoki/tests/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/pycryptoki/tests/run_tests_in_folder.py b/pycryptoki/tests/run_tests_in_folder.py new file mode 100755 index 0000000..88b751a --- /dev/null +++ b/pycryptoki/tests/run_tests_in_folder.py @@ -0,0 +1,9 @@ +''' +Created on Aug 30, 2012 + +@author: mhughes +''' +import pytest + +if __name__ == '__main__': + pytest.cmdline.main(args=[]) diff --git a/pycryptoki/tests/setup_for_tests.py b/pycryptoki/tests/setup_for_tests.py new file mode 100755 index 0000000..ffd04e6 --- /dev/null +++ b/pycryptoki/tests/setup_for_tests.py @@ -0,0 +1,43 @@ +''' +Created on Sep 18, 2012 + +@author: mhughes +''' +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD, \ + CO_PASSWORD +from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ + CKF_SO_SESSION +from pycryptoki.session_management import ca_factory_reset_ex, c_open_session_ex, \ + c_close_all_sessions_ex, login_ex, c_init_pin_ex, c_logout_ex, c_initialize_ex, \ + c_finalize_ex +from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex +import logging + +logger = logging.getLogger(__name__) + +def setup_for_tests(should_factory_reset, initialize_admin_token, initialize_users): + c_initialize_ex() + + #Factory Reset + slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + if should_factory_reset: + c_close_all_sessions_ex(slot) + ca_factory_reset_ex(slot) + + #Initialize the Admin Token + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + if initialize_admin_token: + h_session = c_open_session_ex(slot, session_flags) + c_init_token_ex(slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) + + + if initialize_users and initialize_admin_token: + slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + c_close_all_sessions_ex(slot) + h_session = c_open_session_ex(slot, session_flags) + login_ex(h_session, slot, ADMINISTRATOR_PASSWORD, 0) + c_init_pin_ex(h_session, CO_PASSWORD) + c_logout_ex(h_session) + c_close_all_sessions_ex(slot) + + c_finalize_ex() \ No newline at end of file diff --git a/pycryptoki/tests/stress/__init__.py b/pycryptoki/tests/stress/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/pycryptoki/tests/stress/conftest.py b/pycryptoki/tests/stress/conftest.py new file mode 100755 index 0000000..336ed7f --- /dev/null +++ b/pycryptoki/tests/stress/conftest.py @@ -0,0 +1,32 @@ +''' + This allows for configuration of the designated test/testdir + - Currently this adds custom command args (see below) to py.test interface for this test/directory +''' + +from pycryptoki.defaults import DEFAULT_UTILS_PATH +from pycryptoki.utils.common_utils import setLogFile + + +def pytest_addoption(parser): + parser.addoption("--tslot", help="This is the token slot we wish to target ", + type=int, default=1) + parser.addoption("--vdevice", metavar='device', + help="Target device we want to use i.e. /dev/viper0 or /dev/viper1", + default="/dev/viper0") + parser.addoption("--upath", metavar='path', + help="Path to where the utils are stored: vrest, dumpit", + default=DEFAULT_UTILS_PATH) + parser.addoption("--logfile", help="name of log to store output", + default=setLogFile()) + +def pytest_funcarg__logfile(request): + return request.config.option.logfile + +def pytest_funcarg__vdevice(request): + return request.config.option.vdevice + +def pytest_funcarg__upath(request): + return request.config.option.upath + +def pytest_funcarg__tslot(request): + return request.config.option.tslot \ No newline at end of file diff --git a/pycryptoki/tests/stress/setup.cfg b/pycryptoki/tests/stress/setup.cfg new file mode 100755 index 0000000..ba68f97 --- /dev/null +++ b/pycryptoki/tests/stress/setup.cfg @@ -0,0 +1,3 @@ +# content of setup.cfg +[pytest] +addopts = -s \ No newline at end of file diff --git a/pycryptoki/tests/stress/test_multi_reset.py b/pycryptoki/tests/stress/test_multi_reset.py new file mode 100755 index 0000000..966a394 --- /dev/null +++ b/pycryptoki/tests/stress/test_multi_reset.py @@ -0,0 +1,341 @@ +from ctypes import * +from pycryptoki.cryptoki import CK_SLOT_ID, CA_GetObjectUID, \ + CA_GetUserContainerNumber, CA_GetObjectHandle, \ + CK_ULONG, CK_BYTE +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ + CKM_GENERIC_SECRET_KEY_GEN_TEMP, \ + CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, CKM_RC4_KEY_GEN_TEMP, \ + CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, \ + CKM_ARIA_KEY_GEN_TEMP, CKM_DH_PKCS_PARAMETER_GEN_TEMP +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, \ + CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN, \ + CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, CKM_RC5_KEY_GEN, \ + CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ + CKM_ARIA_KEY_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKR_OK, \ + CKR_DEVICE_ERROR, CK_CRYPTOKI_ELEMENT +from pycryptoki.defaults import DEFAULT_PASSWORD, DEFAULT_LABEL +from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ + CKF_SO_SESSION +from pycryptoki.key_generator import c_destroy_object, c_generate_key +from pycryptoki.session_management import c_initialize, c_finalize, \ + c_close_all_sessions_ex, ca_factory_reset_ex, c_open_session_ex, login_ex, \ + c_get_token_info_ex, c_init_pin_ex, c_logout_ex, c_close_session_ex, c_finalize_ex +from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex +from pycryptoki.test_functions import verify_object_attributes, verify_object_exists +from pycryptoki.utils.common_utils import setLogFile +from pycryptoki.tests.stress.vreset_thread import ResetThread +from pycryptoki.defaults import DEFAULT_UTILS_PATH, FORMAT +from random import randint +import logging +import os +import threading +import argparse +import sys + + +#Global Scope +logger = logging.getLogger(__name__) + +class MultiResetDuringKeyGen(): + def __init__(self, slot): + self.slot = slot + self.h_session = 0 + #Setup events + self.trigger = threading.Event() + self.complete = threading.Event() + #Keygen options - 13 options randomly selected + self.keytype_and_template_list = [(CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), + (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), + (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), + (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), + (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), + (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), + (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP), + (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP)] + + def close_off(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + c_finalize_ex() + + def getDefltLabel(self): + label = DEFAULT_LABEL+str(self.slot) + return label + + def gen_verify_clean(self, vdevice, upath): + ''' + This method is the core of the test case. + The purpose being to continually generate keys until a random reset causes a DEVICE_ERROR to be returned + at which point we capture the exception generated, and verify the objects that were created. + Once a certain number of keys (currently set to 20000) are generated we delete and repeat the process + ''' + cntNum = CK_ULONG() + generated_objects = [] + logger.info("--- Starting Test ---") + rthread = ResetThread(self.trigger, self.complete,vdevice, upath, logger) + ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) + logger.info("Container Number:[%s]" % str(cntNum)) + if (ret != CKR_OK): + rthread.join(1) + logger.info("Error: could not get container number[%s]" % str(cntNum)) + exit(-1) + rthread.start() + self.trigger.set() + self.complete.clear() + for outer in range (1, 1000): + logger.info("**** Iteration: %d *****" % outer) + for num in range (1, 20000): + # Creation stage + ouid = (CK_BYTE*12)() + try: + type_of_keygen = randint(0,12) + #Generate random key type with associated template + gen_ret, hdl = c_generate_key(self.h_session, self.keytype_and_template_list[type_of_keygen][0], self.keytype_and_template_list[type_of_keygen][1]) + if (gen_ret == CKR_DEVICE_ERROR): + raise Exception('keygen') + ouid_ret = CA_GetObjectUID(CK_SLOT_ID(self.slot),cntNum,CK_ULONG(CK_CRYPTOKI_ELEMENT),CK_ULONG(hdl),ouid) + if (ouid_ret == CKR_DEVICE_ERROR): + raise Exception('ouid') + if (ouid_ret == CKR_OK and gen_ret == CKR_OK): + self.trigger.set() + #Store off the object OUID and the template used for keygen + generated_objects.append((ouid,self.keytype_and_template_list[type_of_keygen][1])) + logger.debug("Entry Info: hdl[%d]:num[%d]:ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % + (hdl,num,ouid[0],ouid[1],ouid[2],ouid[3],ouid[4],ouid[5],ouid[6], + ouid[7],ouid[8], ouid[9], ouid[10], ouid[11])) + except Exception as e: + self.trigger.clear() + msg = e.args[0] + logger.info("Exception:[%s] on entry [%d]" % (msg,num)) + if (msg != 'keygen' and msg != 'ouid'): + rthread.join(1) + logger.info("Unexpected exception:[%s] - exiting!" % msg) + exit(-1); + if (msg == 'keygen'): + logger.info("Create: Keygen errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) + if (msg == 'ouid'): + logger.info("Create: OUID lookup errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) + logger.info("Waiting to verify %d objects" % len(generated_objects)) + self.complete.wait() + self.complete.clear() + self.h_session = c_open_session_ex(self.slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) + login_ex(self.h_session, self.slot, DEFAULT_PASSWORD, 1) + logger.info("Start verification of %d objects" % len(generated_objects)) + ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) + logger.info("Container Number:[%s]" % str(cntNum)) + if (ret != CKR_OK): + rthread.join(1) + logger.info("Error: could not get container number[%s]" % str(cntNum)) + exit(-1) + ''' + Verify object that are generated + TODO: Make this set of operations more intensive. + For example: + Encrypt/Decrypt data blob on alternating vreset iterations. + Create EC keys, keypairs etc + ''' + for kouid, temp in generated_objects: + + key = CK_ULONG() + oType = CK_ULONG() + ret = CA_GetObjectHandle(CK_SLOT_ID(self.slot), cntNum, + kouid, byref(oType), + byref(key)) + if (ret != CKR_OK): + logger.debug("Verify: Error: could not get handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" + % (key.value,kouid[0],kouid[1],kouid[2],kouid[3],kouid[4],kouid[5],kouid[6], + kouid[7],kouid[8], kouid[9], kouid[10], kouid[11])) + rthread.join(1) + sys.exc_clear() + exit(-1) + logger.debug("Verify: handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" + % (key.value,kouid[0],kouid[1],kouid[2],kouid[3],kouid[4],kouid[5],kouid[6], + kouid[7],kouid[8], kouid[9], kouid[10], kouid[11])) + verify_object_exists(self.h_session, key.value, True) + verify_object_attributes(self.h_session, key.value, temp) + logger.info("Completed verification of %d objects" % len(generated_objects)) + # Clear the memory of the exception + sys.exc_clear() + continue + #Clean-up the objects for this iteration + self.trigger.clear() + delcount = 0 + store_count = len(generated_objects) + #Delete objects which are generated + while len(generated_objects): + key = CK_ULONG() + oType = CK_ULONG() + douid, temp = generated_objects.pop() + try: + gethdl_ret = CA_GetObjectHandle(CK_SLOT_ID(self.slot), cntNum, + douid, byref(oType), + byref(key)) + if (gethdl_ret == CKR_DEVICE_ERROR): + raise Exception('get_hdl') + dest_ret = c_destroy_object(self.h_session, key.value) + if (dest_ret == CKR_DEVICE_ERROR): + raise Exception('destroy') + if (dest_ret == CKR_OK and gethdl_ret == CKR_OK): + delcount+=1 + except Exception as e: + self.trigger.clear() + msg = e.args[0] + logger.info("Exception:[%s] on entry [%d]" % (msg,delcount)) + if (msg != 'get_hdl' and msg != 'destroy'): + rthread.join(1) + logger.info("Unexpected exception:[%s] - exiting!" % msg) + exit(-1); + if (msg == 'get_hdl'): + logger.info("Delete: Error: could not get handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" + % (key.value, douid[0],douid[1],douid[2],douid[3],douid[4],douid[5],douid[6], + douid[7],douid[8], douid[9], douid[10], douid[11])) + if (msg == 'destroy'): + logger.info("Delete: Error: failed to delete entry [%d] with ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" + % (key.value, douid[0],douid[1],douid[2],douid[3],douid[4],douid[5],douid[6], + douid[7],douid[8], douid[9], douid[10], douid[11])) + self.complete.wait() + self.complete.clear() + self.h_session = c_open_session_ex(CK_SLOT_ID(self.slot), CKF_SERIAL_SESSION | CKF_RW_SESSION) + login_ex(self.h_session, self.slot, DEFAULT_PASSWORD, 1) + ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) + logger.debug("Container Number:[%s]" % str(cntNum)) + if (ret != CKR_OK): + rthread.join(1) + logger.info("Error: could not get container number[%s]" % str(cntNum)) + exit(-1) + # Clear the memory of the exception + sys.exc_clear() + continue + logger.info("Deleted: %d of %d Objects" % (delcount,store_count)) + self.trigger.set() + rthread.join(1) + logger.info("--- Ending Test ---") + + def setup_for_test(self, initialize_admin_token, initialize_users, slot): + ''' + A common setup for the configurable roles tests + + :param initialize_admin_token: Whether or not to initialize the admin partition + :param initialize_users: Whether or not to initialize the PIN's of the users + :param slot: Token slot to target + ''' + c_initialize(); + + #Factory Reset + logger.info(slot) + # NOTE: This is required always. + c_close_all_sessions_ex(slot) + ca_factory_reset_ex(slot) + + #Initialize the Token + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + if initialize_admin_token: + h_session = c_open_session_ex(slot, session_flags) + c_init_token_ex(slot, DEFAULT_PASSWORD, self.getDefltLabel() ) + c_finalize() + c_initialize() + if initialize_users and initialize_admin_token: + islot = get_token_by_label_ex(self.getDefltLabel()) + logger.info("Slot by Label:" + str(islot)) + c_close_all_sessions_ex(islot) + self.h_session = c_open_session_ex(islot, session_flags) + logger.info("Session Handle:" + str(self.h_session)) + login_ex(self.h_session, islot, DEFAULT_PASSWORD, 0) + logger.info(c_get_token_info_ex(islot)) + c_init_pin_ex(self.h_session, DEFAULT_PASSWORD) + c_logout_ex(self.h_session) + c_close_all_sessions_ex(islot) + self.h_session = c_open_session_ex(islot, CKF_SERIAL_SESSION | CKF_RW_SESSION) + login_ex(h_session, islot, DEFAULT_PASSWORD, 1) + logger.info(c_get_token_info_ex(islot)) + +''' +Get the command line args provided as input for test application/case +''' +def get_cmd_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--tslot", help="This is the token slot we wish to target ", + type=int, default=1) + parser.add_argument("--vdevice", metavar='device', + help="Target device we want to use i.e. viper0 or viper1", + default="/dev/viper0") + parser.add_argument("--upath", metavar='path', + help="Path to where the utils are stored: vrest, dumpit", + default=DEFAULT_UTILS_PATH) + parser.add_argument("--logfile", help="name of log to store output", + default=setLogFile()) + args = parser.parse_args() + print args + # Check if basic dependencies are present + populated_dev_path = args.vdevice + try: + os.stat(populated_dev_path) + except OSError as e: + print "Startup: Exception: Device node [%s] not present in [%s] - [%s]" % (args.vdevice,populated_dev_path, e.args) + exit(-1) + valid_vreset_path = args.upath + "/vreset" + try: + os.stat(valid_vreset_path) + except OSError as e: + print "Startup: Exception: Invalid utils path [%s] or vreset not present [%s]" % (args.upath, e.args) + exit(-1) + valid_dumpit_path = args.upath + "/dumpit" + try: + os.stat(valid_dumpit_path) + except OSError as e: + print "Startup: Exception: Invalid utils path [%s] or dumpit not present[%s]" % (args.upath, e.args) + exit(-1) + return args + +''' + Setup logging structure + ''' +def config_logging(args): + print args + logging.basicConfig(format=FORMAT,filename=args.logfile,level=logging.DEBUG,) + + # define a Handler which writes INFO messages or higher to the sys.stderr + console = logging.StreamHandler() + console.setLevel(logging.INFO) + # set a format for logging + formatter = logging.Formatter(FORMAT) + # tell the handler to use this format + console.setFormatter(formatter) + # add the handler to the root logger + logging.getLogger('').addHandler(console) + +''' +PyTest Entry Point: +NOTE: In order to enable console output to the py.test when running this test provide the following in setup.cfg + # content of setup.cfg + [pytest] + addopts = -s +''' +def test_gen_verify_clean(): + args = get_cmd_args() + config_logging(args) + Reset = MultiResetDuringKeyGen(args.tslot) + Reset.setup_for_test(True, True, args.tslot) + Reset.gen_verify_clean(args.vdevice, args.upath) + Reset.close_off() + +''' +Application Entry Point: +Call directly from the command line: + python +''' +if __name__ == '__main__': + test_gen_verify_clean() + + + + + + + diff --git a/pycryptoki/tests/stress/vreset_thread.py b/pycryptoki/tests/stress/vreset_thread.py new file mode 100755 index 0000000..364bc9e --- /dev/null +++ b/pycryptoki/tests/stress/vreset_thread.py @@ -0,0 +1,54 @@ +import os +import threading +import time +import subprocess +from random import randint + +# Reset Thread class - wanted to be able to stop thread on error +class ResetThread(threading.Thread): + ''' + Input parameters for this class are: + trigger: the event to initiate the reset operation - thread waits on this event + complete: the event to tell the external world that the reset has complete + device: the target device node to reset + upath: the path to the driver utils i.e. vreset and dumpit + ''' + def __init__(self, trigger, complete, device, upath, logger): + super(ResetThread, self).__init__() + self.trigger = trigger + self.complete = complete + self.stoprequest = threading.Event() + self.count = 0 + self.device = device + self.upath = upath + self.logger = logger + + def run(self): + while not self.stoprequest.isSet(): + self.count += 1 + self.trigger.wait() + delay = randint(1,20) + time.sleep(delay) + self.logger.info("Trigger vreset: %d on device [%s]" % (self.count, self.device)) + cmd = self.upath + "/vreset " + self.device + val = os.system(cmd) + if val == 0: + self.complete.set() + else: + self.complete.clear() + self.logger.info("-----Vreset Failed: [%d] on device [%s]-------" % (val,self.device)) + proc_dump = subprocess.Popen([self.upath + str("/dumpit"), self.device], stdout=subprocess.PIPE, shell=True) + (dump_out, dump_err) = proc_dump.communicate() + self.logger.debug("DUMPIT OUTPUT: stdout") + self.logger.debug(dump_out) + self.logger.debug("DUMPIT ERROR: stderr") + self.logger.debug(dump_err) + tail_proc = subprocess.Popen([str("tail -n 100 "), str("/var/log/messages")], stdout=subprocess.PIPE, shell=True) + (tail_out, tail_err) = tail_proc.communicate() + self.logger.debug("TAIL OUTPUT: stdout") + self.logger.debug(tail_out) + self.logger.debug("TAIL ERROR: stderr") + self.logger.debug(tail_err) + def join(self, timeout=None): + self.stoprequest.set() + super(ResetThread, self).join(timeout) \ No newline at end of file diff --git a/pycryptoki/tests/test_cka_start_and_end.py b/pycryptoki/tests/test_cka_start_and_end.py new file mode 100755 index 0000000..dcb4600 --- /dev/null +++ b/pycryptoki/tests/test_cka_start_and_end.py @@ -0,0 +1,358 @@ +from ctypes import * +from datetime import datetime +import math +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL +from pycryptoki.defines import CKF_SERIAL_SESSION,CKM_DES_KEY_GEN, CKU_USER, \ + CKA_END_DATE, CKU_AUDIT, CKF_AUDIT_SESSION +from pycryptoki.defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ + CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ + CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ + CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ + CKK_AES, CKM_DES_ECB, CKU_SO, CKR_KEY_NOT_ACTIVE, CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKM_RSA_PKCS, CKM_AES_ECB, CKM_AES_KEY_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA_SHA1 +from pycryptoki.default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.session_management import c_initialize_ex, login, c_finalize, c_open_session_ex, login_ex, \ + c_logout_ex, c_close_session_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +from pycryptoki.attributes import date_attrb +from pycryptoki.dictionary_handling import CDict +from pycryptoki.encryption import c_encrypt, c_encrypt_ex +from pycryptoki.audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex +from pycryptoki.sign_verify import c_sign_ex, c_sign +import logging +import os +import pytest + +logger = logging.getLogger(__name__) +class TestCKAStartEndDate(): + + h_session = 0 + admin_slot = 0 + + def setup(self): + setup_for_tests(True, True, True) + c_initialize_ex() + self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + c_finalize() + + + def test_symmetric_key_expiry_des(self): + """ + Test: Verify that user is not able to use the symmetric object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a DES Key des1 + Use des1 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use des1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the symmetric object after date specified in \ + CKA_END_DATE attribute") + + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 8, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES Key", + CKA_END_DATE : CDict(end_d)} + + + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + + + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, "a" * 512) + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(h_session2) + + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val = c_encrypt(h_session, CKM_DES_ECB, h_key, "This is some data to sign .. ") + + assert return_val == CKR_KEY_NOT_ACTIVE, "return value should be CKR_KEY_NOT_ACTIVE" + c_logout_ex(h_session) + c_close_session_ex(h_session) + + + def test_symmetric_key_expiry_aes(self): + """ + Test: Verify that user is not able to use the symmetric aes object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a AES key aes1 + Use aes1 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use aes1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the symmetric aes object after date specified in \ + CKA_END_DATE attribute") + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_AES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "AES Key", + CKA_END_DATE : CDict(end_d)} + + + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + + + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(h_session2) + + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val = c_encrypt(h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") + logger.info("Called C_Encrypt, return code: " + str(return_val)) + assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" + + + def test_asymmetric_key_expiry_rsa(self): + """ + Test: Verify that user is not able to use the rsa asymmetric object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a rsa Key rsa1 + Use des1 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use rsa1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the rsa asymmetric object after date specified in \ + CKA_END_DATE attribute") + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_MODIFIABLE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT : 3, #byte + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "RSA Public Key"} + + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_MODIFIABLE : True, + CKA_EXTRACTABLE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "RSA Private Key"} + + + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(h_session2) +# print datetime.fromtimestamp(float(hsm_time.value)) + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val = c_encrypt(h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") + logger.info("Called C_Encrypt, return code: " + str(return_val)) + assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" + + + def test_asymmetric_key_expiry_dsa(self): + """ + Test: Verify that user is not able to use the dsa asymmetric object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a DSA Key dsa1 + Use dsa11 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use dsa1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the dsa asymmetric object after date specified in \ + CKA_END_DATE attribute") + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_1024_160, + CKA_SUBPRIME : dsa_sub_prime_1024_160, + CKA_BASE : dsa_base_1024_160, + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "DSA 1024_160 Public Key"} + + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_EXTRACTABLE : True, + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "DSA Public Key"} + + + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_DSA_KEY_PAIR_GEN, + pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + prkey_template=CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + c_sign_ex(self.h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) + + + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(self.h_session) +# print datetime.fromtimestamp(float(hsm_time.value)) + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val, sig = c_sign(h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) + logger.info("Called C_Sign, return code: " + str(return_val)) + assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" + + + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) + + \ No newline at end of file diff --git a/pycryptoki/tests/test_digest_data.py b/pycryptoki/tests/test_digest_data.py new file mode 100755 index 0000000..9234c26 --- /dev/null +++ b/pycryptoki/tests/test_digest_data.py @@ -0,0 +1,53 @@ +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_MD2, CKR_OK +from pycryptoki.encryption import _get_string_from_list +from pycryptoki.misc import c_digest +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestDigestData(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_digest_data(self): + ''' + Calls C_Digest on some data and makes sure there is no failure + ''' + data_to_digest = "Some arbitrary string" + ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) + assert ret == CKR_OK, "Digesting should occur with no errors" + assert len(digested_data) > 0, "The digested data should have a length" + assert data_to_digest != digested_data, "The digested data should not be the same as the original string" + + def test_multipart_digest_data(self): + data_to_digest = ["Some arbitrary string", "Some second arbitrary string"] + ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) + assert ret == CKR_OK, "Digesting should occur with no errors" + assert len(digested_data) > 0, "The digested data should have a length" + assert _get_string_from_list(data_to_digest) != digested_data, "The digested data should not be the same as the original string" + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_encrypt_decrypt.py b/pycryptoki/tests/test_encrypt_decrypt.py new file mode 100755 index 0000000..061da03 --- /dev/null +++ b/pycryptoki/tests/test_encrypt_decrypt.py @@ -0,0 +1,72 @@ +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ + CKM_DES_CBC_PAD, CKM_DES_CBC_ENCRYPT_DATA +from pycryptoki.encryption import c_encrypt, c_decrypt, _split_string_into_list, \ + _get_string_from_list +from pycryptoki.key_generator import c_generate_key_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestEncryptData(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_encrypt_decrypt_string(self): + ''' + Tests encrypting and decrypting a string with a key + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + data_to_encrypt = "a" * (0xfff0) + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] + + ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data) + assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] + assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) + + def test_multipart_encrypt_decrypt(self): + ''' + Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore doing it in multiple + parts + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + data_to_encrypt = ['a' * 512, 'b' * 512, 'c' * 512, 'd' * 512] + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] + assert len(encrypted_data) == len(_get_string_from_list(data_to_encrypt)) + + encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) + + ret, decrypted_data = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data_chunks) + assert ret == CKR_OK, "Decryption should succeed, instead it returned " + ret_vals_dictionary[ret] + assert _get_string_from_list(data_to_encrypt) == decrypted_data, "The data before encryption should match the data after encryption" + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_get_token_info.py b/pycryptoki/tests/test_get_token_info.py new file mode 100755 index 0000000..1019a4c --- /dev/null +++ b/pycryptoki/tests/test_get_token_info.py @@ -0,0 +1,47 @@ +from ctypes import byref +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD +from pycryptoki.defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ + CKF_RESTORE_KEY_NOT_NEEDED, CKF_TOKEN_INITIALIZED +from pycryptoki.session_management import c_finalize, ca_factory_reset_ex, \ + c_get_token_info_ex, c_close_all_sessions, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestGetTokenInfo(): + + def setup(self): + setup_for_tests(True, False, False) + c_initialize_ex() + + def teardown(self): + c_finalize() + + def test_initial_flags(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL); + + #Get to clean state + c_close_all_sessions(admin_slot) + ca_factory_reset_ex(admin_slot) + + #Look at flags before initialization + flags = c_get_token_info_ex(admin_slot)['flags'] + expected_flags = CKF_TOKEN_PRESENT | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED + assert flags == expected_flags, "After factory reset found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) + + c_init_token_ex(admin_slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL); + + #Test flags after initialization + flags = c_get_token_info_ex(admin_slot)['flags'] + expected_flags = expected_flags | CKF_TOKEN_INITIALIZED + assert flags == expected_flags, "After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) + logger.info("After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags))) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) + \ No newline at end of file diff --git a/pycryptoki/tests/test_hsm_management.py b/pycryptoki/tests/test_hsm_management.py new file mode 100755 index 0000000..6282f1b --- /dev/null +++ b/pycryptoki/tests/test_hsm_management.py @@ -0,0 +1,226 @@ +""" +Test methods for pycryptoki 'hsm management' set of commands. +""" +from ctypes import create_string_buffer, cast +from pycryptoki.cryptoki import CK_ULONG, CK_BYTE, CK_BYTE_PTR +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKU_CRYPTO_USER, CKR_OK, \ + CKR_ATTRIBUTE_VALUE_INVALID, CKR_CANCEL, CKR_USER_NOT_AUTHORIZED, \ + CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_AES, CKA_TOKEN, \ + CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, \ + CKA_VERIFY, CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, \ + CKA_EXTRACTABLE, CKA_LABEL, LUNA_TTYPE_CRYPTO, LUNA_TTYPE_RNG, \ + LUNA_DSS_SIGVERIFY_TEST +from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +from pycryptoki.hsm_management import c_performselftest, \ + ca_settokencertificatesignature, ca_hainit, ca_createloginchallenge, \ + ca_initializeremotepedvector, ca_deleteremotepedvector, ca_mtkrestore, \ + ca_mtkresplit, ca_mtkzeroize +from pycryptoki.key_generator import c_generate_key_pair +import logging +import os +import pytest + + +class TestAlgorithm(): + """ Test algorithm class """ + h_session = 0 + admin_slot = 0 + + @classmethod + def setup_class(self): + """ Setup class """ + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + """ Finalize tests """ + c_finalize_ex() + + def setup(self): + """ Setup test """ + self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + """ Teardown test """ + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + + @pytest.mark.parametrize(("test_type"), + [LUNA_TTYPE_CRYPTO, + LUNA_TTYPE_RNG, + LUNA_DSS_SIGVERIFY_TEST]) + def test_performselftest(self, test_type): + ''' + Tests performs self test + + @param test_type: test type + ''' + input_data = (CK_BYTE*1000)() + input_length = CK_ULONG(1000) + output_data = (CK_BYTE*1000)() + output_length = CK_ULONG(0) + + ret = c_performselftest(self.admin_slot, + test_type, + input_data, + input_length, + output_data, + output_length) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + + def test_settokencertsignature(self): + ''' + Tests set token certificate signature + To do: fix attribute value + ''' + gen_temp = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_AES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "AES Key"} + + access_level = CK_ULONG(1) + customer_id = CK_ULONG(1) + pub_template = gen_temp + pub_template_length = CK_ULONG(len(pub_template)) + signature = (CK_BYTE*4000)() + signature_length = CK_ULONG(4000) + + ret = ca_settokencertificatesignature(self.h_session, + access_level, + customer_id, + pub_template, + pub_template_length, + signature, + signature_length) + assert ret == CKR_ATTRIBUTE_VALUE_INVALID, \ + "Return code should be " + \ + ret_vals_dictionary[CKR_ATTRIBUTE_VALUE_INVALID] + \ + " not " + ret_vals_dictionary[ret] + + + def test_hainit(self): + ''' + Tests performs HA init + ''' + ret, pubkey_h, prikey_h = c_generate_key_pair(self.h_session, + CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + assert pubkey_h > 0, \ + "The public key handle returned should be non zero" + assert prikey_h > 0, \ + "The private key handle returned should be non zero" + + ret = ca_hainit(self.h_session, prikey_h) + + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + + def test_createloginchallenge(self): + ''' + Test create login challenge. + This test requires PED based HSM. + If performing this test on PWD based HSM return value is CKR_CANCEL. + ''' + user_type = CKU_CRYPTO_USER + challenge_length = CK_ULONG(12) + challenge = cast(create_string_buffer("password1234", 12), CK_BYTE_PTR) + output_data_length = CK_ULONG(0) + output_data = (CK_BYTE*1)() + + ret = ca_createloginchallenge(self.h_session, + user_type, + challenge_length, + challenge, + output_data_length, + output_data) + assert (ret == CKR_OK or ret == CKR_CANCEL), \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + + def test_initializeremotepedvector(self): + ''' + Tests to initialize remote ped vector + ''' + ret = ca_initializeremotepedvector(self.h_session) + # since not SO return value must be CKR_USER_NOT_AUTHORIZED + assert ret == CKR_USER_NOT_AUTHORIZED, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + + def test_deleteremotepedvector(self): + ''' + Tests to delete remote ped vector + ''' + ret = ca_deleteremotepedvector(self.h_session) + # since not SO return value must be CKR_USER_NOT_AUTHORIZED + assert ret == CKR_USER_NOT_AUTHORIZED, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + + def test_mtkrestore(self): + ''' + Tests MTK restore + ''' + ret = ca_mtkrestore(self.admin_slot) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + + def test_mtkresplit(self): + ''' + Tests MTK resplit + ''' + ret = ca_mtkresplit(self.admin_slot) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + + def test_mtkzeroize(self): + ''' + Tests MTK zeroize + ''' + ret = ca_mtkzeroize(self.admin_slot) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_key_management.py b/pycryptoki/tests/test_key_management.py new file mode 100755 index 0000000..a94692f --- /dev/null +++ b/pycryptoki/tests/test_key_management.py @@ -0,0 +1,106 @@ +""" +Test methods for pycryptoki 'key management' set of commands. +""" +from pycryptoki.cryptoki import CK_ULONG, CK_BYTE, CA_MOFN_GENERATION, \ + CA_MOFN_GENERATION_PTR +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_OK, CKR_USER_NOT_AUTHORIZED, \ + CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, \ + CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET +from pycryptoki.default_templates import CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +from pycryptoki.key_management import ca_generatemofn, ca_modifyusagecount +from pycryptoki.key_generator import c_generate_key +import logging +import os +import pytest + + +class TestAlgorithm(): + """ Test algorithm class """ + h_session = 0 + admin_slot = 0 + + @classmethod + def setup_class(self): + """ Setup class """ + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + """ Finalize tests """ + c_finalize_ex() + + def setup(self): + """ Setup test """ + self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + """ Teardown test """ + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + + def test_generatemofn(self): + ''' + Test generate M of N + ''' + m_value = CK_ULONG(1) + value = (CK_BYTE*16)() + vector_count = CK_ULONG(2) + vector = (CA_MOFN_GENERATION*2)() + vector[0].ulWeight = CK_ULONG(1) + vector[0].pVector = value + vector[0].ulVectorLen = CK_ULONG(16) + vector[1].ulWeight = CK_ULONG(1) + vector[1].pVector = (CK_BYTE*16)() + vector[1].ulVectorLen = CK_ULONG(16) + vectors = CA_MOFN_GENERATION_PTR(vector) + is_secure_port_used = CK_ULONG(0) + + ret = ca_generatemofn(self.h_session, + m_value, + vectors, + vector_count, + is_secure_port_used) + assert ret == CKR_USER_NOT_AUTHORIZED, \ + "Return code should be " + \ + ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ + " not " + ret_vals_dictionary[ret] + + + @pytest.mark.parametrize("command_type", + [CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, + CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET]) + def test_modifyusagecount(self, command_type): + ''' + Test modify usage count + ''' + ret, key_handle = c_generate_key(self.h_session, + CKM_DES_KEY_GEN, + CKM_DES_KEY_GEN_TEMP) + assert ret == CKR_OK, "Return code should be " + \ + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + assert key_handle > 0, "The key handle returned should be non zero" + + value = CK_ULONG(0) + + ret = ca_modifyusagecount(self.h_session, + key_handle, + command_type, + value) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_key_usage.py b/pycryptoki/tests/test_key_usage.py new file mode 100755 index 0000000..9f54034 --- /dev/null +++ b/pycryptoki/tests/test_key_usage.py @@ -0,0 +1,69 @@ +""" +Test methods for pycryptoki 'hsm usage' set of commands. +""" +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_SESSION_HANDLE_INVALID, \ + CKR_USER_NOT_AUTHORIZED +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +from pycryptoki.key_usage import ca_clonemofn, ca_duplicatemofn +import logging +import os +import pytest + +class TestAlgorithm(): + """ Test algorithm class """ + h_session = 0 + admin_slot = 0 + + @classmethod + def setup_class(self): + """ Setup class """ + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + """ Finalize tests """ + c_finalize_ex() + + def setup(self): + """ Setup test """ + self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + """ Teardown test """ + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + + def test_clonemofn(self): + ''' + Test clone M of N + ''' + ret = ca_clonemofn(self.h_session) + assert ret == CKR_SESSION_HANDLE_INVALID, \ + "Return code should be " + \ + ret_vals_dictionary[CKR_SESSION_HANDLE_INVALID] + \ + " not " + ret_vals_dictionary[ret] + + + def test_duplicatemofn(self): + ''' + Test duplicate M of N + ''' + ret = ca_duplicatemofn(self.h_session) + assert ret == CKR_USER_NOT_AUTHORIZED, \ + "Return code should be " + \ + ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ + " not " + ret_vals_dictionary[ret] + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_keys.py b/pycryptoki/tests/test_keys.py new file mode 100755 index 0000000..b07c1d2 --- /dev/null +++ b/pycryptoki/tests/test_keys.py @@ -0,0 +1,167 @@ +from ctypes import cast, pointer +from pycryptoki.cryptoki import CK_VOID_PTR, CK_ULONG +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ + CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ + CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP, \ + CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, CKM_DSA_PARAMETER_GEN_TEMP, \ + CKM_KCDSA_PARAMETER_GEN_TEMP, CKM_ARIA_KEY_GEN_TEMP, \ + CKM_DH_PKCS_PARAMETER_GEN_TEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, \ + CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, \ + CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP, curve_list +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKR_OK, \ + CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ + CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ + CKM_RC5_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ + CKM_DSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN, CKM_ARIA_KEY_GEN, \ + CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ + CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ + CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN, \ + CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS +from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, \ + c_derive_key, c_generate_key_ex, _get_mechanism +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import ctypes +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestKeys(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), + (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), + (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), + (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), + (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), + (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), + (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), +# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), +# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX +# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) +# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX + ]) + def test_generate_key(self, key_type, key_template): + ''' + Tests generating a key, asserts that the operation returns correctly with key handles + greater than 0 + + @param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) + @param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) + ''' + ret, key_handle = c_generate_key(self.h_session, key_type, key_template) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + assert key_handle > 0, "The key handle returned should be non zero" + + + @pytest.mark.parametrize(("key_type", "public_key_template", "private_key_template"), [ + (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), + (CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP), +# (CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP) #XXX + ]) + def test_generate_key_pair(self, key_type, public_key_template, private_key_template): + ''' + Tests generating a key pair, asserts that the operation returns correctly with key handles + greater than 0. + + @param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) + @param public_key_template: The template to use for public key generation (ex. CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 + @param private_key_template: The template to use for private key generation (ex. CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 + ''' + ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, key_type, public_key_template, private_key_template) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + assert public_key_handle > 0, "The public key handle returned should be non zero" + assert private_key_handle > 0, "The private key handle returned should be non zero" + + @pytest.mark.parametrize(("curve_type"), curve_list.keys()) + def test_generate_ecdsa_key_pairs(self, curve_type): + print curve_list.keys() + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] + ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + assert public_key_handle > 0, "The public key handle returned should be non zero" + assert private_key_handle > 0, "The private key handle returned should be non zero" + + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), + (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), + (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), + (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), + (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), + (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), + (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), +# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), +# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX +# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) +# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX + ]) + def test_derive_key(self, key_type, key_template): + ''' + Tests deriving a key + ''' + h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) + h_second_key = c_generate_key_ex(self.h_session, key_type, key_template) + + mech = _get_mechanism(CKM_CONCATENATE_BASE_AND_KEY) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + ret, h_derived_key = c_derive_key(self.h_session, h_base_key, key_template, None, mech) + assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_derived_key, key_template) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_object_create.py b/pycryptoki/tests/test_object_create.py new file mode 100755 index 0000000..5e6a432 --- /dev/null +++ b/pycryptoki/tests/test_object_create.py @@ -0,0 +1,59 @@ +from pycryptoki.default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_OK +from pycryptoki.misc import c_create_object +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestObjectCloning(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_certificate_create(self): + ''' + Tests C_CreateObject with a certificate template and verifies the object's + attributes + ''' + + ret, h_object = c_create_object(self.h_session, CERTIFICATE_TEMPLATE) + assert ret == CKR_OK, "The result code of creating a certificate should be CKR_OK, not " + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_object, CERTIFICATE_TEMPLATE) + + def test_data_create(self): + ''' + Tests C_CreateObject with a data template and verifies the object's + attributes + ''' + ret, h_object = c_create_object(self.h_session, DATA_TEMPLATE) + assert ret == CKR_OK, "The result of creating a data object should be CKR_OK, not" + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_sign_verify.py b/pycryptoki/tests/test_sign_verify.py new file mode 100755 index 0000000..b01f81c --- /dev/null +++ b/pycryptoki/tests/test_sign_verify.py @@ -0,0 +1,95 @@ +from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_OK, CKM_RSA_PKCS, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKR_SIGNATURE_INVALID, CKM_DSA_KEY_PAIR_GEN, CKM_DSA +from pycryptoki.key_generator import c_generate_key_pair_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.sign_verify import c_sign, c_verify +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest +logger = logging.getLogger(__name__) + +class TestSignVerify(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ + (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_RSA_PKCS), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) + ]) + def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): + ''' + Verifies that signing a string and verifying that string works + + @param key_type: The handle of the key to sign the data with + @param pub_key_template: The template for the public key to be generated + @param priv_key_template: The template for the private key to be generated + @param sign_flavor: The flavor of the signature + ''' + + #Generate a key for the test + h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) + + data_to_sign = "This is some test string to sign." + ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) + assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] + + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) + assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] + + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) + ]) + def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): + ''' + Verifies that signing a string and verifying that string works doing the operation + in multiple parts with c_sign_update and c_verify_update + + @param key_type: The handle of the key to sign the data with + @param pub_key_template: The template for the public key to be generated + @param priv_key_template: The template for the private key to be generated + @param sign_flavor: The flavor of the signature + ''' + + #Generate a key for the test + h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) + + data_to_sign = ["a" * 1024, "b" * 1024] + ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) + assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] + + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) + assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_supporting_operations.py b/pycryptoki/tests/test_supporting_operations.py new file mode 100755 index 0000000..bd2da55 --- /dev/null +++ b/pycryptoki/tests/test_supporting_operations.py @@ -0,0 +1,62 @@ +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_OK +from pycryptoki.misc import c_generate_random_ex, c_seed_random, \ + c_generate_random +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestSupportingOperations(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_rng(self): + ''' + Tests generating a random number + ''' + length = 15 + ret, random_string = c_generate_random(self.h_session, length) + assert ret == CKR_OK, "C_GenerateRandom should return CKR_OK, instead it returned " + ret_vals_dictionary[ret] + assert len(random_string) == length, "The length of the random string should be the same as the length of the requested data." + + def test_seeded_rng(self): + ''' + Tests that seeding the random number generator with the same data will + generate the same random number + ''' + seed = "k" * 1024 + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, it returned " + ret_vals_dictionary[ret] + + random_string_one = c_generate_random_ex(self.h_session, 10) + + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator a second time shouldn't return an error, it returned " + ret_vals_dictionary[ret] + + random_string_two = c_generate_random_ex(self.h_session, 10) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_usage_limit_and_count.py b/pycryptoki/tests/test_usage_limit_and_count.py new file mode 100755 index 0000000..a1cb586 --- /dev/null +++ b/pycryptoki/tests/test_usage_limit_and_count.py @@ -0,0 +1,326 @@ +''' +Created on Aug 15, 2012 + +@author: root +''' + +from ctypes import * +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CK_ULONG, C_SetAttributeValue +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP +from pycryptoki.defaults import CO_PASSWORD, ADMIN_PARTITION_LABEL +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ + CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ + CKM_DES_ECB, CKM_RSA_PKCS, CKR_OK, CKR_KEY_NOT_ACTIVE, CKU_USER, CKM_AES_ECB +from pycryptoki.encryption import c_encrypt, c_encrypt_ex +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.session_management import login_ex +from pycryptoki.object_attr_lookup import c_get_attribute_value_ex +from pycryptoki.session_management import c_initialize_ex, c_open_session_ex, c_logout_ex, \ + c_close_session_ex, c_finalize +from pycryptoki.test_functions import LunaException +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + + +logger = logging.getLogger(__name__) + +class TestUsageLimitAndCount(): + + h_session = 0 + + def setup(self): + setup_for_tests(True, True, True) + c_initialize_ex() + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + c_finalize() + + def test_set_attribute_usage_limit_sym(self): + """ Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + an symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 5 + Use C_getAttributeValue to verify """ + + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + an symmetric crypto object") + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 5} + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + usage_limit = 5 + + + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) +# print c_struct[CKA_USAGE_LIMIT] + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value + logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(int(usage_val_out))) + assert usage_limit== usage_val_out, "reported USAGE LIMIT does not match" + + + + + def test_usage_limit_attribute_check_sym_des(self): + """ + Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use des key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + """ + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + usage_count = 2 + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) + + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + + + + def test_usage_limit_attribute_check_sym_aes(self): + + """ + Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use aes key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + """ + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + usage_count = 2 + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_AES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) + + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + + + def test_set_attribute_usage_limit_Assym(self): + """ + Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + an assymetric crypto object + Procedure: + Generate a RSA key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 on RSA public key + Use C_getAttributeValue to verify + """ + + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + an assymetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + usage_limit = 2 + + return_val = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) + if return_val != CKR_OK: raise LunaException(return_val, 'C_SetAttributeValue', "Setting up attribute") + + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value + logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + + + + + + def test_usage_limit_attribute_check_Assym(self): + """ + Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the assymetric crypto object + Procedure: + Generate a RSA Key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + """ + + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the assymetric crypto object") + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + usage_count = 2 + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) + + + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): + + """ + Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT + Procedure: + Generate a 3DES key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key 3 times for encryption + """ + + logger.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + return_val = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_val != CKR_OK: raise LunaException(return_val, 'C_setAttributeValue', "Setting up limit attribute") + + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + + return_val = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + logger.info("Called C_Encrypt, return code: " + str(return_val)) + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) + + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + + + + + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): + + """ + Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT + Procedure: + Generate a RSA Key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key 3 times for encryption + """ + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + return_val = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + logger.info("Called C_Encrypt, return code: " + str(return_val)) + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + + + +if __name__ == "__main__": + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) + diff --git a/pycryptoki/tests/test_wrap_unwrap.py b/pycryptoki/tests/test_wrap_unwrap.py new file mode 100755 index 0000000..cca4c8a --- /dev/null +++ b/pycryptoki/tests/test_wrap_unwrap.py @@ -0,0 +1,87 @@ +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_DES_UNWRAP_TEMP +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ + CKA_LABEL, CKM_DES_ECB +from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt +from pycryptoki.key_generator import c_generate_key, c_generate_key_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestWrappingKeys(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_wrap_unwrap_key(self): + ''' + Tests the attributes of an unwrapped key are idential to the original key + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + #Wrap the key + ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) + assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) + assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Verify all of the attributes against the originally generated attributes + verify_object_attributes(self.h_session, h_unwrapped_key, CKM_DES_KEY_GEN_TEMP) + + def test_encrypt_wrap_unwrap_decrypt_key(self): + ''' + Tests encrypting some data with a key. Then wrapping and unwrapping the key + and using the unwrapped key to decrypt the data. It then compares the data to the + original data. + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + #Encrypt some data + data_to_encrypt = "a" * 512 + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] + + #Wrap the key + ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) + assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) + assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Decrypt the data + ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_unwrapped_key, encrypted_data) + assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] + assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py new file mode 100755 index 0000000..42de99a --- /dev/null +++ b/pycryptoki/token_management.py @@ -0,0 +1,103 @@ +''' +Created on Aug 24, 2012 + +@author: mhughes +''' +from ctypes import byref, cast, create_string_buffer +from pycryptoki.cryptoki import C_InitToken, CK_ULONG, CK_CHAR_PTR, \ + C_GetSlotList, CK_BBOOL, CK_SLOT_ID, C_GetMechanismList, CK_MECHANISM_TYPE, \ + CK_MECHANISM_TYPE_PTR, CK_MECHANISM_INFO, C_GetMechanismInfo +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT +from pycryptoki.defines import CKR_OK +from pycryptoki.session_management import c_get_token_info, get_slot_info +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def c_init_token(slot_num, password, token_label='Main Token'): + ''' + Initializes at token at a given slot with the proper password and label + @param slot_num: The index of the slot to c_initialize a token in + @param password: The password to c_initialize the slot with + @param token_label: The label to c_initialize the slot with + + @return: The result code + ''' + if password == '': + logger.info("C_InitToken: Initializing token. slot=" + str( + slot_num) + ", label='" + token_label + "', password='" + password + "'") + ret = C_InitToken(CK_ULONG(slot_num), None, + CK_ULONG(0), cast(create_string_buffer(token_label), CK_CHAR_PTR)) + return ret + else: + logger.info("C_InitToken: Initializing token. slot="+ str(slot_num) + ", label='" + token_label + "', password='" + password + "'") + ret = C_InitToken(CK_ULONG(slot_num), cast(create_string_buffer(password), CK_CHAR_PTR), CK_ULONG(len(password)), cast(create_string_buffer(token_label), CK_CHAR_PTR)) + return ret +c_init_token_ex = make_error_handle_function(c_init_token) + +def get_token_by_label(label): + ''' + Iterates through all the tokens and returns the first token that + has a label that is identical to the one that is passed in + + @param label:The label of the token to search for + @return: The result code, The slot of the token + ''' + + if label == ADMIN_PARTITION_LABEL: #XXX the admin partition's label changes depending on the boards state +# ret, slot_info = get_slot_info("Viper") +# return ret, slot_info.keys()[1] + return CKR_OK, ADMIN_SLOT + + us_count = CK_ULONG(0) + ret = C_GetSlotList(CK_BBOOL(1), None, byref(us_count)) + if ret != CKR_OK: return ret, None + num_slots = us_count.value + slot_list = (CK_SLOT_ID * num_slots)() + ret = C_GetSlotList(CK_BBOOL(1), slot_list, byref(us_count)) + if ret != CKR_OK: return ret, None + + for slot in slot_list: + ret, token_info = c_get_token_info(slot) + if token_info['label'] == label: + return ret, slot + + raise Exception("Slot with label " + str(label) + " not found.") +get_token_by_label_ex = make_error_handle_function(get_token_by_label) + +def c_get_mechanism_list(slot): + ''' + Gets the list of mechanisms from the HSM + + @param slot: The slot number to get the mechanism list on + @return: The result code, A python dictionary representing the mechanism list + ''' + count = CK_ULONG() + ret = C_GetMechanismList(CK_SLOT_ID(slot), None, byref(count)) + last_count = count + if ret != CKR_OK: return ret, None + mech_list = (CK_MECHANISM_TYPE * count.value)() + ret = C_GetMechanismList(CK_SLOT_ID(slot), CK_MECHANISM_TYPE_PTR(mech_list), byref(count)) + if ret != CKR_OK: return ret, None + if last_count != count: raise Exception("Mechanism list count was not consistent between function calls") + + ret_list = [] + for i in range(0, count.value): + ret_list.append(mech_list[i]) + return ret, ret_list +c_get_mechanism_list_ex = make_error_handle_function(c_get_mechanism_list) + +def c_get_mechanism_info(slot, mechanism_type): + ''' + Gets a mechanism's info + + @param slot: The slot to query + @param mechanism_type: The type of the mechanism to get the information for + + @return: The result code, The mechanism info + ''' + mech_info = CK_MECHANISM_INFO() + ret = C_GetMechanismInfo(CK_ULONG(slot), CK_MECHANISM_TYPE(mechanism_type), byref(mech_info)) + return ret, mech_info +c_get_mechanism_info_ex = make_error_handle_function(c_get_mechanism_info) \ No newline at end of file diff --git a/pycryptoki/utils/__init__.py b/pycryptoki/utils/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/pycryptoki/utils/common_utils.py b/pycryptoki/utils/common_utils.py new file mode 100755 index 0000000..3913fa7 --- /dev/null +++ b/pycryptoki/utils/common_utils.py @@ -0,0 +1,6 @@ +import datetime +#Utility to set a default logfile name +def setLogFile(): + dt = str(datetime.datetime.now()).strip() + logname = "./test_" + dt + ".log" + return logname diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..bd830f2 --- /dev/null +++ b/setup.py @@ -0,0 +1,17 @@ +''' +Script used by distutils to automatically generate a source code +distribution of this python module (a .tar.gz file containing +all of the source code). + +To generate this file run: +python setup.py sdist +''' +from distutils.core import setup +setup(name='pycryptoki', + description="A python wrapper around the C cryptoki library.", + author='Michael Hughes', + author_email='michael.hughes@safenet-inc.com', + url='http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Pages/pycryptoki.aspx', + version='1.0', + packages=['pycryptoki', 'pycryptoki.setup', 'pycryptoki.tests', 'pycryptoki.daemon'] + ) \ No newline at end of file From 87ba00232661f423adbdb98565bc99ce3f5b916f Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 12 May 2015 12:33:04 -0400 Subject: [PATCH 003/109] LA-1062 From trunk instead of 5.4 Change-Id: I15c9f3d98d13463561b50ca535d7cd2703580725 --- .gitreview | 4 + pycryptoki/attributes.py | 1000 ++-- pycryptoki/audit_handling.py | 70 +- pycryptoki/backup.py | 114 +- pycryptoki/cryptoki.py | 4696 +++++++++++------ pycryptoki/cryptoki_helpers.py | 420 +- pycryptoki/daemon/pycryptoki_daemon.py | 558 +- pycryptoki/daemon/pycryptoki_daemon.py.bak | 295 -- pycryptoki/daemon/rpyc_pycryptoki.py | 623 ++- pycryptoki/default_templates.py | 1713 +++--- pycryptoki/defaults.py | 82 +- pycryptoki/defines.py | 1807 +++++++ pycryptoki/dictionary_handling.py | 30 +- pycryptoki/encryption.py | 811 ++- pycryptoki/hsm_management.py | 4 +- pycryptoki/key_generator.py | 300 +- pycryptoki/logging_filters.py | 52 +- pycryptoki/luna_threading.py | 292 +- pycryptoki/mechanism.py | 270 +- pycryptoki/misc.py | 302 +- pycryptoki/object_attr_lookup.py | 142 +- pycryptoki/policy_management.py | 100 +- pycryptoki/pycryptoki_client.py | 224 +- pycryptoki/return_values.py | 174 + pycryptoki/session_management.py | 716 +-- pycryptoki/setup/distribute.py | 72 +- pycryptoki/setup/initialize.py | 806 +-- pycryptoki/setup/make_and_install.py | 56 +- pycryptoki/setup/verify_version.py | 70 +- pycryptoki/sign_verify.py | 498 +- pycryptoki/test_functions.py | 412 +- pycryptoki/tests/run_tests_in_folder.py | 18 +- pycryptoki/tests/setup_for_tests.py | 84 +- pycryptoki/tests/test_cka_start_and_end.py | 714 +-- pycryptoki/tests/test_digest_data.py | 104 +- pycryptoki/tests/test_encrypt_decrypt.py | 142 +- pycryptoki/tests/test_get_token_info.py | 92 +- pycryptoki/tests/test_keys.py | 332 +- pycryptoki/tests/test_object_create.py | 116 +- pycryptoki/tests/test_sign_verify.py | 188 +- .../tests/test_supporting_operations.py | 122 +- .../tests/test_usage_limit_and_count.py | 652 +-- pycryptoki/tests/test_wrap_unwrap.py | 172 +- pycryptoki/token_management.py | 204 +- setup.py | 11 +- 45 files changed, 11319 insertions(+), 8345 deletions(-) create mode 100644 .gitreview mode change 100755 => 100644 pycryptoki/cryptoki.py delete mode 100755 pycryptoki/daemon/pycryptoki_daemon.py.bak create mode 100644 pycryptoki/defines.py create mode 100644 pycryptoki/return_values.py diff --git a/.gitreview b/.gitreview new file mode 100644 index 0000000..d24b732 --- /dev/null +++ b/.gitreview @@ -0,0 +1,4 @@ +[gerrit] +host=172.20.10.212 +project=Auto/pycryptoki + diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 0cc809a..8f38ec7 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -1,483 +1,517 @@ -""" -This module contains a wrapper around the key attributes and the template struct -generation to make it possible to create templates in python and easily -convert them into templates in C. -""" -from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ - CK_BYTE, C_GetAttributeValue, CK_OBJECT_HANDLE, CK_DATE, CK_CHAR, CK_CHAR_PTR -from ctypes import cast, c_void_p, create_string_buffer, c_bool, c_char_p, \ - c_ulong, pointer, POINTER, byref, sizeof, c_int, c_ubyte -from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ - CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_VALUE, CKA_CERTIFICATE_TYPE, \ - CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ - CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER, \ - CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE, \ - CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, \ - CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT, \ - CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, \ - CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_ECDSA_PARAMS, CKA_EC_POINT, CKA_LOCAL, \ - CKA_MODIFIABLE, CKA_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_NEVER_EXTRACTABLE, \ - CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_PKC_TCTRUST, CKA_PKC_CITS, CKA_OUID, \ - CKA_X9_31_GENERATED, CKA_PKC_ECC, CKR_OK -from pycryptoki.cryptoki import CK_ULONG_PTR, CK_ATTRIBUTE_PTR, CK_BYTE_PTR -from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ - CKA_GENERIC_3 -from pycryptoki.dictionary_handling import CDict -import logging - -''' -List class for handling attributes with lists of a certain type -''' -class CList: - list_type = None - - def __init__(self, list_type): - self.list_type = list_type - -class NonAsciiString: - data = None - def __init__(self, data): - self.data = data - -def get_byte_list_from_python_list(python_byte_list): - ''' - Helper method to create a C style byte list from a python - style list of integers. - @param python_byte_list: A list of integers to convert to a C style list of integers - @return: The pointer to the C representation of the python byte list - ''' - list_val = create_string_buffer("", len(python_byte_list)) - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(python_byte_list)): - list_val[j] = chr(python_byte_list[j]) - return ptr - - -date_attrb = {'year' : str, - 'month' : str, - 'day' : str} - -''' -A mapping of attributes to what type they have. This is used when converting -a python dictionary to a C struct or vice versa -''' -key_attributes = {CKA_USAGE_LIMIT : long, - CKA_USAGE_COUNT : long, - CKA_CLASS : long, - CKA_TOKEN : bool, - CKA_PRIVATE : bool, - CKA_LABEL : str, - CKA_APPLICATION : None, - CKA_VALUE : CList(str), - CKA_CERTIFICATE_TYPE : long, # TODO guessing - CKA_ISSUER : None, - CKA_SERIAL_NUMBER : None, - CKA_KEY_TYPE : long, - CKA_SUBJECT : str, - CKA_ID : None, - CKA_SENSITIVE : bool, - CKA_ENCRYPT : bool, - CKA_DECRYPT : bool, - CKA_WRAP : bool, - CKA_UNWRAP : bool, - CKA_SIGN : bool, - CKA_SIGN_RECOVER : None, - CKA_VERIFY : bool, - CKA_VERIFY_RECOVER : None, - CKA_DERIVE : bool, - CKA_START_DATE : CDict(date_attrb), - CKA_END_DATE : CDict(date_attrb), - CKA_MODULUS : None, - CKA_MODULUS_BITS : long, - CKA_PUBLIC_EXPONENT : int, #Python has no concept of byte - CKA_PRIVATE_EXPONENT : None, - CKA_PRIME_1 : None, - CKA_PRIME_2 : None, - CKA_EXPONENT_1 : None, - CKA_EXPONENT_2 : None, - CKA_COEFFICIENT : None, - CKA_PRIME : CList(str), - CKA_SUBPRIME : CList(str), - CKA_BASE : CList(str), - CKA_PRIME_BITS : long, - CKA_SUBPRIME_BITS : long, - CKA_VALUE_BITS : long, - CKA_VALUE_LEN: long, - CKA_ECDSA_PARAMS : CList(str), - CKA_EC_POINT : None, - CKA_LOCAL : None, - CKA_MODIFIABLE : bool, - CKA_EXTRACTABLE : bool, - CKA_ALWAYS_SENSITIVE : bool, - CKA_NEVER_EXTRACTABLE : bool, - CKA_CCM_PRIVATE : None, - CKA_FINGERPRINT_SHA1 : NonAsciiString, - CKA_FINGERPRINT_SHA256 : NonAsciiString, - CKA_PKC_TCTRUST : None, - CKA_PKC_CITS : None, - CKA_OUID : NonAsciiString, - CKA_X9_31_GENERATED : None, - CKA_PKC_ECC : None, - CKA_EKM_UID : None, - CKA_GENERIC_1 : None, - CKA_GENERIC_2 : None, - CKA_GENERIC_3 : None} - - -role_attributes = {} - -def to_byte_array(val): - """ - Converts an arbitrarily sized integer into a byte array. - - It'll zero-pad the bit length so it's a multiple of 8, then convert - the int to binary, split the binary string into sections of 8, then - place each section into a slot in a c_ubyte array (converting to small - int). - - :param val: Big Integer to convert. - :return: c_ubyte array - """ - width = val.bit_length() - width += 8 - ((width % 8) or 8) - - fmt = "{:0%sb}" % width - str_val = fmt.format(val) - n = 8 - str_array = [str_val[i:i+n] for i in range(0, len(str_val), n)] - - return (CK_BYTE * len(str_array))(*[int(x, 2) for x in str_array]) - - - -class Attributes: - ''' - A wrapper around all of the attributes necessary to create a key. - Has a python dictionary object containing python types, the corresponding - C struct can then be generated with a simple method call. - ''' - attributes = {} - - def __init__(self, attributes_list=None): - ''' - Initializes a Attributes object, the attributes_list argument is optional - since the attributes object can be populated from the board later - - @param attributes_list: The list of python style attributes to create the class with. - ''' - - if attributes_list is not None: - #take either strings or ints as the key to the dictionary (used mainly to accomodate xmlrpc easily) - attributes_list_new = {} - for key, value in attributes_list.iteritems(): - if isinstance(key, str): - attributes_list_new[int(key)] = value - else: - break - if len(attributes_list_new) > 0: - attributes_list = attributes_list_new - - for key in attributes_list: - self._input_check(key, attributes_list[key]) - self.attributes = attributes_list - - def add_attribute(self, key, value): - ''' - Add an attribute to the dictionary in place - @param key: The type of the attribute - @param value: The value of the attribute - ''' - if isinstance(key, str): - #take either strings or ints for the key (used mainly to accomodate xmlrpc easily) - key = int(key) - - self._input_check(key, value) - self.attributes[key] = value - - def _input_check(self, key, value): - ''' - Checks to see if the type is supported (yet) - - @param key: They key of the attribute to check - @param value: The actual value of the input to check - @return: Returns true if the variable is a of a type that has been accounted for in the key_attributes dictionary - ''' - if isinstance(value, bool) or isinstance(value, int) or isinstance(value, CDict) or isinstance(value, long) or isinstance(value, str) or isinstance(value, list) or isinstance(value, CList) or isinstance(value, NonAsciiString): - return True - else: - raise Exception("Argument type not supported. ") - - def get_c_struct(self): - ''' - Assembles and returns a proper C struct from the dictionary of python attributes - - @return: Returns a Ctypes struct representing the python attributes stored in this class - ''' - c_struct = (CK_ATTRIBUTE * len(self.attributes))() - - i = 0 - for key in self.attributes: - value = self.attributes[key] - self._input_check(key, value) - - #Get the proper type for what your data is, originally I had - #this automatically detected from the python type but passing in - #int's vs longs was problematic - item_type = lookup_attributes(key) - - if item_type == bool: - byte_val = CK_BBOOL(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(byte_val), c_void_p), CK_ULONG(sizeof(byte_val))) - elif item_type == long: - long_val = CK_ULONG(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(long_val), c_void_p), CK_ULONG(sizeof(long_val))) - elif item_type == int: - ck_byte_array = to_byte_array(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), - cast(pointer(ck_byte_array), c_void_p), - CK_ULONG(sizeof(ck_byte_array))) - elif item_type == str: - string_val = create_string_buffer(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(string_val, c_void_p), CK_ULONG(len(string_val))) - elif isinstance(item_type, CDict): - date = CK_DATE() - - date.year = convert_string_to_CK_CHAR(value.dict_val['year']) - date.month = convert_string_to_CK_CHAR(value.dict_val['month']) - date.day = convert_string_to_CK_CHAR(value.dict_val['day']) - - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(date), c_void_p), CK_ULONG(sizeof(date))) - elif isinstance(item_type, CList): - if item_type.list_type == str: - list_val = create_string_buffer("", len(value)) - - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(value)): - list_val[j] = chr(value[j]) - - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(len(value))) - elif item_type.list_type == long: - list_val = (CK_ULONG * len(value))() - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(value)): - list_val[j] = CK_ULONG(value[j]) - - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(sizeof(CK_ULONG(0)) * len(value))) - elif item_type == NonAsciiString: - list_val = (CK_CHAR * len(value))() - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(value)): - list_val[j] = CK_CHAR(ord(value[j]) - 0x30) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(sizeof(CK_CHAR(0)) * len(value))) - else: - raise Exception("Argument type " + str(item_type) + " not supported. ") - i = i + 1 - - return c_struct - - def retrieve_key_attributes(self, h_session, h_object): - ''' - Gets all of the key's attributes from the board given the key's handle, - and populates the KeyAttribute object with all of those attributes. - - @param h_session: Current session - @param h_object: The handle of the object to fetch the attributes for - ''' - #Clean before starting - self.attributes = {} - - for key in key_attributes: - attribute = CK_ATTRIBUTE() - attribute.type = CK_ULONG(key) - attribute.pValue = c_void_p(0) - retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), byref(attribute), CK_ULONG(1)) - if retCode == CKR_OK: - attr_type = lookup_attributes(key) - - if isinstance(attr_type, CList): - if attr_type.list_type == str: - pb_value = (CK_BYTE * attribute.usValueLen)() - elif attr_type.list_type == long: - pb_value = (CK_ULONG * attribute.usValueLen)() - else: - pb_value = create_string_buffer(attribute.usValueLen) - - attribute.pValue = cast(pb_value, c_void_p) - retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), byref(attribute), CK_ULONG(1)) - if retCode == CKR_OK: - if attr_type == bool: - self.add_attribute(attribute.type, attr_type(cast(attribute.pValue, POINTER(c_bool)).contents.value)) - elif attr_type == str: - string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] - self.add_attribute(attribute.type, attr_type(string)) - elif attr_type == long: - self.add_attribute(attribute.type, (attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value))) - elif attr_type == int: - self.add_attribute(attribute.type, attr_type(cast(attribute.pValue, POINTER(c_int)).contents.value)) - elif isinstance(attr_type, CList): - value = [] - i = 0 - while i < attribute.usValueLen: - value.append(pb_value[i]) - i = i + 1 - - self.add_attribute(attribute.type, value) - elif attr_type == NonAsciiString: - value = '' - i = 0 - while i < attribute.usValueLen: - value += '%02x'% cast(pb_value, CK_CHAR_PTR)[i] - i = i + 1 - - self.add_attribute(attribute.type, value) - elif attr_type == None: - #raise Exception("Attribute of type " + str(attribute.type) + "'s value type not yet determined") # Add type to all_attributes - pass - - def get_attributes(self): - ''' - Returns the python dictionary of attributes - @return: The python dictionary of attributes - ''' - return self.attributes - - def __eq__(self, other): - ''' - Overriding the == sign to properly compare equality in KeyAttribute objects - @param other: Another KeyAttribute to compare against - @return: True if the attributes are equal - ''' - other_attribs = other.get_attributes() - self_attribs = self.get_attributes() - for key in self.attributes: - if key in self_attribs and key in other_attribs: #TODO we are only checking if the key exists in both, maybe this is a bad idea - if self_attribs[key] != other_attribs[key]: - return False - return True - - def debug_print(self): - ''' - Simple method to print out all the keys and values in a KeyAttribute object - ''' - for key in self.attributes: - print "key: " + str(key) + ", value: " + str(self.attributes[key]) - -def get_attribute_py_value(attribute): - ''' - Gets the python version of the value of a attribute from the - C format - - @param attribute: The ctypes style variable representing the value of an attribute - @return: Returns the python version of the ctypes style variable - ''' - key = attribute.type - attr_type = lookup_attributes(key) - if attr_type == bool: - return attr_type(cast(attribute.pValue, POINTER(c_bool)).contents.value) - elif attr_type == str: - string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] - return attr_type(string) - elif attr_type == long: - return attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value) - elif attr_type == int: - return attr_type(cast(attribute.pValue, POINTER(c_int)).contents.value) - elif isinstance(attr_type, CDict): - py_date = {} - - c_date = cast(attribute.pValue, POINTER(CK_DATE)) - - py_date['year'] = convert_CK_CHAR_to_string(cast(c_date.year, CK_CHAR_PTR)) - py_date['month'] = convert_CK_CHAR_to_string(cast(c_date.month, CK_CHAR_PTR)) - py_date['day'] = convert_CK_CHAR_to_string(cast(c_date.day, CK_CHAR_PTR)) - return py_date - - - elif isinstance(attr_type, CList): - if attr_type.list_type == str: - value = [] - try: - for i in range(0, attribute.usValueLen): - value.append(attribute.pValue[i]) - return value - except OverflowError: - return value - - elif attr_type.list_type == long: - value = [] - for i in range(0, attribute.usValueLen / sizeof(CK_ULONG(0))): - value.append(cast(attribute.pValue, CK_ULONG_PTR)[i]) - return value - elif attr_type == NonAsciiString: - value = '' - for i in range(0, attribute.usValueLen / sizeof(CK_CHAR(0))): - value += '%02x'% cast(attribute.pValue, CK_CHAR_PTR)[i] - return value - elif attr_type == None: - #raise Exception("Attribute of type " + str(attribute.type) + "'s value type not yet determined") # Add type to all_attributes - pass - - -def c_struct_to_python(c_struct): - ''' - Converts a struct in C to a dictionary in python. - - @param c_struct: The c struct to convert into a dictionary in python - @return: Returns a python dictionary which represents the C struct passed in - ''' - py_struct = {} - for i in range(0, len(c_struct)): - obj_type = c_struct[i].type - - value = get_attribute_py_value(c_struct[i]) - - py_struct[obj_type] = value - - return py_struct - -def lookup_attributes(key): - ''' - Utility function to look through the lists of attributes and figure out - the type of variable for a given attribute represented by a key - - @param key: The key representing the attribute - @return: The python type that can represent the attribute - ''' - - ret_val = None - if key in key_attributes: - ret_val = key_attributes[key] - elif key in role_attributes: - ret_val = role_attributes[key] - - return ret_val - -def convert_string_to_CK_CHAR(string): - byte_array = (c_ubyte * len (string))() - i = 0 - for char in string: - byte_array[i] = ord(char) - i = i +1 - - return byte_array - -def convert_CK_CHAR_to_string(byte_array): - string = "" - - for b in byte_array: - string = string + chr(b) - return string - -def convert_ck_char_array_to_string(ck_char_array): - string = "" - - for b in ck_char_array: - string = string + b - return string - -def convert_CK_BYTE_array_to_string(byte_array): - string = "" - - for b in byte_array: - string = string + "%02x"%(b) - return string - +""" +This module contains a wrapper around the key attributes and the template struct +generation to make it possible to create templates in python and easily +convert them into templates in C. +""" +from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ + CK_BYTE, C_GetAttributeValue, CK_OBJECT_HANDLE, CK_DATE, CK_CHAR, CK_CHAR_PTR +from ctypes import cast, c_void_p, create_string_buffer, c_bool, c_char_p, \ + c_ulong, pointer, POINTER, byref, sizeof, c_int, c_ubyte +from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ + CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_VALUE, CKA_CERTIFICATE_TYPE, \ + CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ + CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER, \ + CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE, \ + CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, \ + CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT, \ + CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, \ + CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_ECDSA_PARAMS, CKA_EC_POINT, CKA_LOCAL, \ + CKA_MODIFIABLE, CKA_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_NEVER_EXTRACTABLE, \ + CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_PKC_TCTRUST, CKA_PKC_CITS, \ + CKA_OUID, \ + CKA_X9_31_GENERATED, CKA_PKC_ECC, CKR_OK +from pycryptoki.cryptoki import CK_ULONG_PTR, CK_ATTRIBUTE_PTR, CK_BYTE_PTR +from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ + CKA_GENERIC_3 +from pycryptoki.dictionary_handling import CDict +import logging + +''' +List class for handling attributes with lists of a certain type +''' + + +class CList: + list_type = None + + def __init__(self, list_type): + self.list_type = list_type + + +class NonAsciiString: + data = None + + def __init__(self, data): + self.data = data + + +def get_byte_list_from_python_list(python_byte_list): + ''' + Helper method to create a C style byte list from a python + style list of integers. + @param python_byte_list: A list of integers to convert to a C style list of integers + @return: The pointer to the C representation of the python byte list + ''' + list_val = create_string_buffer("", len(python_byte_list)) + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(python_byte_list)): + list_val[j] = chr(python_byte_list[j]) + return ptr + + +date_attrb = {'year': str, + 'month': str, + 'day': str} + +''' +A mapping of attributes to what type they have. This is used when converting +a python dictionary to a C struct or vice versa +''' +key_attributes = {CKA_USAGE_LIMIT: long, + CKA_USAGE_COUNT: long, + CKA_CLASS: long, + CKA_TOKEN: bool, + CKA_PRIVATE: bool, + CKA_LABEL: str, + CKA_APPLICATION: None, + CKA_VALUE: CList(str), + CKA_CERTIFICATE_TYPE: long, # TODO guessing + CKA_ISSUER: None, + CKA_SERIAL_NUMBER: None, + CKA_KEY_TYPE: long, + CKA_SUBJECT: str, + CKA_ID: None, + CKA_SENSITIVE: bool, + CKA_ENCRYPT: bool, + CKA_DECRYPT: bool, + CKA_WRAP: bool, + CKA_UNWRAP: bool, + CKA_SIGN: bool, + CKA_SIGN_RECOVER: None, + CKA_VERIFY: bool, + CKA_VERIFY_RECOVER: None, + CKA_DERIVE: bool, + CKA_START_DATE: CDict(date_attrb), + CKA_END_DATE: CDict(date_attrb), + CKA_MODULUS: None, + CKA_MODULUS_BITS: long, + CKA_PUBLIC_EXPONENT: int, # Python has no concept of byte + CKA_PRIVATE_EXPONENT: None, + CKA_PRIME_1: None, + CKA_PRIME_2: None, + CKA_EXPONENT_1: None, + CKA_EXPONENT_2: None, + CKA_COEFFICIENT: None, + CKA_PRIME: CList(str), + CKA_SUBPRIME: CList(str), + CKA_BASE: CList(str), + CKA_PRIME_BITS: long, + CKA_SUBPRIME_BITS: long, + CKA_VALUE_BITS: long, + CKA_VALUE_LEN: long, + CKA_ECDSA_PARAMS: CList(str), + CKA_EC_POINT: None, + CKA_LOCAL: None, + CKA_MODIFIABLE: bool, + CKA_EXTRACTABLE: bool, + CKA_ALWAYS_SENSITIVE: bool, + CKA_NEVER_EXTRACTABLE: bool, + CKA_CCM_PRIVATE: None, + CKA_FINGERPRINT_SHA1: NonAsciiString, + CKA_FINGERPRINT_SHA256: NonAsciiString, + CKA_PKC_TCTRUST: None, + CKA_PKC_CITS: None, + CKA_OUID: NonAsciiString, + CKA_X9_31_GENERATED: None, + CKA_PKC_ECC: None, + CKA_EKM_UID: None, + CKA_GENERIC_1: None, + CKA_GENERIC_2: None, + CKA_GENERIC_3: None} + +role_attributes = {} + + +def to_byte_array(val): + """ + Converts an arbitrarily sized integer into a byte array. + + It'll zero-pad the bit length so it's a multiple of 8, then convert + the int to binary, split the binary string into sections of 8, then + place each section into a slot in a c_ubyte array (converting to small + int). + + :param val: Big Integer to convert. + :return: c_ubyte array + """ + width = val.bit_length() + width += 8 - ((width % 8) or 8) + + fmt = "{:0%sb}" % width + str_val = fmt.format(val) + n = 8 + str_array = [str_val[i:i + n] for i in range(0, len(str_val), n)] + + return (CK_BYTE * len(str_array))(*[int(x, 2) for x in str_array]) + + +class Attributes: + ''' + A wrapper around all of the attributes necessary to create a key. + Has a python dictionary object containing python types, the corresponding + C struct can then be generated with a simple method call. + ''' + attributes = {} + + def __init__(self, attributes_list=None): + ''' + Initializes a Attributes object, the attributes_list argument is optional + since the attributes object can be populated from the board later + + @param attributes_list: The list of python style attributes to create the class with. + ''' + + if attributes_list is not None: + # take either strings or ints as the key to the dictionary (used mainly to accomodate + # xmlrpc easily) + attributes_list_new = {} + for key, value in attributes_list.iteritems(): + if isinstance(key, str): + attributes_list_new[int(key)] = value + else: + break + if len(attributes_list_new) > 0: + attributes_list = attributes_list_new + + for key in attributes_list: + self._input_check(key, attributes_list[key]) + self.attributes = attributes_list + + def add_attribute(self, key, value): + ''' + Add an attribute to the dictionary in place + @param key: The type of the attribute + @param value: The value of the attribute + ''' + if isinstance(key, str): + # take either strings or ints for the key (used mainly to accomodate xmlrpc easily) + key = int(key) + + self._input_check(key, value) + self.attributes[key] = value + + def _input_check(self, key, value): + ''' + Checks to see if the type is supported (yet) + + @param key: They key of the attribute to check + @param value: The actual value of the input to check + @return: Returns true if the variable is a of a type that has been accounted for in the + key_attributes dictionary + ''' + if isinstance(value, bool) or isinstance(value, int) or isinstance(value, + CDict) or isinstance( + value, long) or isinstance(value, str) or isinstance(value, list) or isinstance( + value, CList) or isinstance(value, NonAsciiString): + return True + else: + raise Exception( + "Argument type not supported. ") + + def get_c_struct(self): + ''' + Assembles and returns a proper C struct from the dictionary of python attributes + + @return: Returns a Ctypes struct representing the python attributes stored in this class + ''' + c_struct = (CK_ATTRIBUTE * len(self.attributes))() + + i = 0 + for key in self.attributes: + value = self.attributes[key] + self._input_check(key, value) + + # Get the proper type for what your data is, originally I had + #this automatically detected from the python type but passing in + #int's vs longs was problematic + item_type = lookup_attributes(key) + + if item_type == bool: + byte_val = CK_BBOOL(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), + cast(pointer(byte_val), c_void_p), + CK_ULONG(sizeof(byte_val))) + elif item_type == long: + long_val = CK_ULONG(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), + cast(pointer(long_val), c_void_p), + CK_ULONG(sizeof(long_val))) + elif item_type == int: + ck_byte_array = to_byte_array(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), + cast(pointer(ck_byte_array), c_void_p), + CK_ULONG(sizeof(ck_byte_array))) + elif item_type == str: + string_val = create_string_buffer(value) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(string_val, c_void_p), + CK_ULONG(len(string_val))) + elif isinstance(item_type, CDict): + date = CK_DATE() + + date.year = convert_string_to_CK_CHAR(value.dict_val['year']) + date.month = convert_string_to_CK_CHAR(value.dict_val['month']) + date.day = convert_string_to_CK_CHAR(value.dict_val['day']) + + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(date), c_void_p), + CK_ULONG(sizeof(date))) + elif isinstance(item_type, CList): + if item_type.list_type == str: + list_val = create_string_buffer("", len(value)) + + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(value)): + list_val[j] = chr(value[j]) + + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(len(value))) + elif item_type.list_type == long: + list_val = (CK_ULONG * len(value))() + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(value)): + list_val[j] = CK_ULONG(value[j]) + + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, + CK_ULONG(sizeof(CK_ULONG(0)) * len(value))) + elif item_type == NonAsciiString: + list_val = (CK_CHAR * len(value))() + ptr = cast(pointer(list_val), c_void_p) + for j in range(0, len(value)): + list_val[j] = CK_CHAR(ord(value[j]) - 0x30) + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, + CK_ULONG(sizeof(CK_CHAR(0)) * len(value))) + else: + raise Exception("Argument type " + str(item_type) + " not supported. ") + i = i + 1 + + return c_struct + + def retrieve_key_attributes(self, h_session, h_object): + ''' + Gets all of the key's attributes from the board given the key's handle, + and populates the KeyAttribute object with all of those attributes. + + @param h_session: Current session + @param h_object: The handle of the object to fetch the attributes for + ''' + # Clean before starting + self.attributes = {} + + for key in key_attributes: + attribute = CK_ATTRIBUTE() + attribute.type = CK_ULONG(key) + attribute.pValue = c_void_p(0) + retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), byref(attribute), + CK_ULONG(1)) + if retCode == CKR_OK: + attr_type = lookup_attributes(key) + + if isinstance(attr_type, CList): + if attr_type.list_type == str: + pb_value = (CK_BYTE * attribute.usValueLen)() + elif attr_type.list_type == long: + pb_value = (CK_ULONG * attribute.usValueLen)() + else: + pb_value = create_string_buffer(attribute.usValueLen) + + attribute.pValue = cast(pb_value, c_void_p) + retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), + byref(attribute), CK_ULONG(1)) + if retCode == CKR_OK: + if attr_type == bool: + self.add_attribute(attribute.type, attr_type( + cast(attribute.pValue, POINTER(c_bool)).contents.value)) + elif attr_type == str: + string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] + self.add_attribute(attribute.type, attr_type(string)) + elif attr_type == long: + self.add_attribute(attribute.type, ( + attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value))) + elif attr_type == int: + self.add_attribute(attribute.type, attr_type( + cast(attribute.pValue, POINTER(c_int)).contents.value)) + elif isinstance(attr_type, CList): + value = [] + i = 0 + while i < attribute.usValueLen: + value.append(pb_value[i]) + i = i + 1 + + self.add_attribute(attribute.type, value) + elif attr_type == NonAsciiString: + value = '' + i = 0 + while i < attribute.usValueLen: + value += '%02x' % cast(pb_value, CK_CHAR_PTR)[i] + i = i + 1 + + self.add_attribute(attribute.type, value) + elif attr_type == None: + #raise Exception("Attribute of type " + str(attribute.type) + "'s value + # type not yet determined") # Add type to all_attributes + pass + + def get_attributes(self): + ''' + Returns the python dictionary of attributes + @return: The python dictionary of attributes + ''' + return self.attributes + + def __eq__(self, other): + ''' + Overriding the == sign to properly compare equality in KeyAttribute objects + @param other: Another KeyAttribute to compare against + @return: True if the attributes are equal + ''' + other_attribs = other.get_attributes() + self_attribs = self.get_attributes() + for key in self.attributes: + if key in self_attribs and key in other_attribs: # TODO we are only checking if the + # key exists in both, maybe this is a bad idea + if self_attribs[key] != other_attribs[key]: + return False + return True + + def debug_print(self): + ''' + Simple method to print out all the keys and values in a KeyAttribute object + ''' + for key in self.attributes: + print "key: " + str(key) + ", value: " + str(self.attributes[key]) + + +def get_attribute_py_value(attribute): + ''' + Gets the python version of the value of a attribute from the + C format + + @param attribute: The ctypes style variable representing the value of an attribute + @return: Returns the python version of the ctypes style variable + ''' + key = attribute.type + attr_type = lookup_attributes(key) + if attr_type == bool: + return attr_type(cast(attribute.pValue, POINTER(c_bool)).contents.value) + elif attr_type == str: + string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] + return attr_type(string) + elif attr_type == long: + return attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value) + elif attr_type == int: + return attr_type(cast(attribute.pValue, POINTER(c_int)).contents.value) + elif isinstance(attr_type, CDict): + py_date = {} + + c_date = cast(attribute.pValue, POINTER(CK_DATE)) + + py_date['year'] = convert_CK_CHAR_to_string(cast(c_date.year, CK_CHAR_PTR)) + py_date['month'] = convert_CK_CHAR_to_string(cast(c_date.month, CK_CHAR_PTR)) + py_date['day'] = convert_CK_CHAR_to_string(cast(c_date.day, CK_CHAR_PTR)) + return py_date + + elif isinstance(attr_type, CList): + if attr_type.list_type == str: + value = [] + try: + for i in range(0, attribute.usValueLen): + value.append(attribute.pValue[i]) + return value + except OverflowError: + return value + + elif attr_type.list_type == long: + value = [] + for i in range(0, attribute.usValueLen / sizeof(CK_ULONG(0))): + value.append(cast(attribute.pValue, CK_ULONG_PTR)[i]) + return value + elif attr_type == NonAsciiString: + value = '' + for i in range(0, attribute.usValueLen / sizeof(CK_CHAR(0))): + value += '%02x' % cast(attribute.pValue, CK_CHAR_PTR)[i] + return value + elif attr_type == None: + # raise Exception("Attribute of type " + str(attribute.type) + "'s value type not yet + # determined") # Add type to all_attributes + pass + + +def c_struct_to_python(c_struct): + ''' + Converts a struct in C to a dictionary in python. + + @param c_struct: The c struct to convert into a dictionary in python + @return: Returns a python dictionary which represents the C struct passed in + ''' + py_struct = {} + for i in range(0, len(c_struct)): + obj_type = c_struct[i].type + + value = get_attribute_py_value(c_struct[i]) + + py_struct[obj_type] = value + + return py_struct + + +def lookup_attributes(key): + ''' + Utility function to look through the lists of attributes and figure out + the type of variable for a given attribute represented by a key + + @param key: The key representing the attribute + @return: The python type that can represent the attribute + ''' + + ret_val = None + if key in key_attributes: + ret_val = key_attributes[key] + elif key in role_attributes: + ret_val = role_attributes[key] + + return ret_val + + +def convert_string_to_CK_CHAR(string): + byte_array = (c_ubyte * len (string))() + i = 0 + for char in string: + byte_array[i] = ord(char) + i = i + 1 + + return byte_array + + +def convert_CK_CHAR_to_string(byte_array): + string = "" + + for b in byte_array: + string = string + chr(b) + return string + + +def convert_ck_char_array_to_string(ck_char_array): + string = "" + + for b in ck_char_array: + string = string + b + return string + + +def convert_CK_BYTE_array_to_string(byte_array): + string = "" + + for b in byte_array: + string = string + "%02x" % (b) + return string + + diff --git a/pycryptoki/audit_handling.py b/pycryptoki/audit_handling.py index 9bb956d..dd0517b 100755 --- a/pycryptoki/audit_handling.py +++ b/pycryptoki/audit_handling.py @@ -1,35 +1,35 @@ -""" -Methods responsible for managing a user's session and login/c_logout -""" -from cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR -from ctypes import cast, c_ulong, byref -from pycryptoki.test_functions import LunaException, check_luna_exception, \ - make_error_handle_function -import logging - -logger = logging.getLogger(__name__) - -def ca_init_audit(slot, audit_pin, audit_label): - if audit_pin == '': - ret = CA_InitAudit(CK_SLOT_ID(slot), None, CK_ULONG(0), cast(audit_label, CK_CHAR_PTR)) - else: - ret = CA_InitAudit(CK_SLOT_ID(slot), cast(audit_pin, CK_CHAR_PTR), CK_ULONG(len(audit_pin)), cast(audit_label, CK_CHAR_PTR)) - return ret -ca_init_audit_ex = make_error_handle_function(ca_init_audit) - -def ca_time_sync(h_session, ultime): - - ret = CA_TimeSync(h_session, CK_ULONG(ultime)) - return ret -ca_time_sync_ex = make_error_handle_function(ca_time_sync) - -def ca_get_time(h_session): - - hsm_time = c_ulong() - - ret = CA_GetTime(h_session, byref(hsm_time)) - return ret, hsm_time -ca_get_time_ex = make_error_handle_function(ca_get_time) - - - +""" +Methods responsible for managing a user's session and login/c_logout +""" +from cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR +from ctypes import cast, c_ulong, byref +from pycryptoki.test_functions import LunaException, check_luna_exception, \ + make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def ca_init_audit(slot, audit_pin, audit_label): + if audit_pin == '': + ret = CA_InitAudit(CK_SLOT_ID(slot), None, CK_ULONG(0), cast(audit_label, CK_CHAR_PTR)) + else: + ret = CA_InitAudit(CK_SLOT_ID(slot), cast(audit_pin, CK_CHAR_PTR), CK_ULONG(len(audit_pin)), cast(audit_label, CK_CHAR_PTR)) + return ret +ca_init_audit_ex = make_error_handle_function(ca_init_audit) + +def ca_time_sync(h_session, ultime): + + ret = CA_TimeSync(h_session, CK_ULONG(ultime)) + return ret +ca_time_sync_ex = make_error_handle_function(ca_time_sync) + +def ca_get_time(h_session): + + hsm_time = c_ulong() + + ret = CA_GetTime(h_session, byref(hsm_time)) + return ret, hsm_time +ca_get_time_ex = make_error_handle_function(ca_get_time) + + + diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index 2feb0c2..f6cb024 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -1,57 +1,57 @@ -from ctypes import byref -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CA_OpenSecureToken, CK_ULONG_PTR, \ - CA_CloseSecureToken, CA_Extract, CA_Insert, CK_MECHANISM, CK_ULONG -from pycryptoki.mechanism import get_c_struct_from_mechanism, \ - get_python_dict_from_c_mechanism -from pycryptoki.test_functions import make_error_handle_function -import logging - -logger = logging.getLogger(__name__) - -''' -CK_SESSION_HANDLE hSession, - CK_ULONG storagePath, - CK_ULONG devID, - CK_ULONG mode, - CK_ULONG_PTR numberOfElems, - CK_ULONG_PTR phID -''' -def ca_open_secure_token(h_session, storage_path, dev_ID, mode): - number_of_elems = CK_ULONG(0) - ph_ID = CK_ULONG(0) - ret = CA_OpenSecureToken(h_session, storage_path, dev_ID, mode, byref(number_of_elems), byref(ph_ID)) - - return ret, number_of_elems.value, ph_ID.value -ca_open_secure_token_ex = make_error_handle_function(ca_open_secure_token) - -''' -CK_SESSION_HANDLE hSession, CK_ULONG hID -''' -def ca_close_secure_token(h_session, h_ID): - - ret = CA_CloseSecureToken(h_session, h_ID) - return ret -ca_close_secure_token_ex = make_error_handle_function(ca_close_secure_token) - - -def ca_extract(h_session, py_mechanism_dict, params_type_string): - - c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) - - ret = CA_Extract(h_session, c_mechanism) - - py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) - return ret, py_dictionary -ca_extract_ex = make_error_handle_function(ca_extract) - -# CA_Insert( CK_SESSION_HANDLE hSession, -# CK_MECHANISM_PTR pMechanism ) - -def ca_insert(h_session, py_mechanism_dict, params_type_string): - - c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) - ret = CA_Insert(h_session, c_mechanism) - py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) - return ret, py_dictionary -ca_insert_ex = make_error_handle_function(ca_insert) +from ctypes import byref +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CA_OpenSecureToken, CK_ULONG_PTR, \ + CA_CloseSecureToken, CA_Extract, CA_Insert, CK_MECHANISM, CK_ULONG +from pycryptoki.mechanism import get_c_struct_from_mechanism, \ + get_python_dict_from_c_mechanism +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +''' +CK_SESSION_HANDLE hSession, + CK_ULONG storagePath, + CK_ULONG devID, + CK_ULONG mode, + CK_ULONG_PTR numberOfElems, + CK_ULONG_PTR phID +''' +def ca_open_secure_token(h_session, storage_path, dev_ID, mode): + number_of_elems = CK_ULONG(0) + ph_ID = CK_ULONG(0) + ret = CA_OpenSecureToken(h_session, storage_path, dev_ID, mode, byref(number_of_elems), byref(ph_ID)) + + return ret, number_of_elems.value, ph_ID.value +ca_open_secure_token_ex = make_error_handle_function(ca_open_secure_token) + +''' +CK_SESSION_HANDLE hSession, CK_ULONG hID +''' +def ca_close_secure_token(h_session, h_ID): + + ret = CA_CloseSecureToken(h_session, h_ID) + return ret +ca_close_secure_token_ex = make_error_handle_function(ca_close_secure_token) + + +def ca_extract(h_session, py_mechanism_dict, params_type_string): + + c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) + + ret = CA_Extract(h_session, c_mechanism) + + py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) + return ret, py_dictionary +ca_extract_ex = make_error_handle_function(ca_extract) + +# CA_Insert( CK_SESSION_HANDLE hSession, +# CK_MECHANISM_PTR pMechanism ) + +def ca_insert(h_session, py_mechanism_dict, params_type_string): + + c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) + ret = CA_Insert(h_session, c_mechanism) + py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) + return ret, py_dictionary +ca_insert_ex = make_error_handle_function(ca_insert) diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py old mode 100755 new mode 100644 index 2a9740b..463264d --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -10,1421 +10,1227 @@ from pycryptoki.cryptoki_helpers import make_late_binding_function +import sys from ctypes import * -class CK_FUNCTION_LIST(Structure): +LUNA_RET_CB_PROT_DATA_INVALID = -2147481047 +LUNA_RET_SAVED_STATE_INVALID = 23068672 +LUNA_RET_STATE_UNSAVEABLE = 25165824 +LUNA_RET_LOG_FILE_NOT_OPEN = -2147480320 +RC_OBJECT_NOT_IN_LIST = -1073740790 +LUNA_INVALID_PACKET_LAYOUT = -2147482352 +LUNA_RET_ATTRIBUTE_TYPE_INVALID = 1179648 +RC_INVALID_INDEX = -1073740789 +LUNA_HIFN_UNKNOWN_ALGORITHM = -2147482353 +LUNA_RET_LOG_NO_KCV = -2147480316 +LUNA_RET_MM_ITERATOR_PAST_END = 3211269 +LUNA_RET_HIFN_DMA_ERROR = -2147482357 +LUNA_RET_DEVICE_TIMEOUT = -2147483636 +RC_PARTITION_LOCKED = -1073737728 +LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES = 68103 +RC_PARTITION_NOT_ACTIVATED = -1073737727 +RC_FAILED_TO_CREATE_THREAD = -1073733632 +RC_CALLBACK_ERROR = -1073733631 +RC_UNKNOWN_CALLBACK_COMMAND = -1073733630 +RC_SHUTTING_DOWN = -1073733629 +RC_REMOTE_SIDE_DISCONNECTED = -1073733628 +RC_SOCKET_CLOSED = -1073733627 +LUNA_RET_SFNT3120_CRC = 3147811 +RC_INVALID_COMMAND = -1073733626 +RC_UNKNOWN_COMMAND = -1073733625 +RC_UNKNOWN_COMMAND_VERSION = -1073733624 +RC_FILE_LOCK_FAILED = -1073733623 +RC_FILE_LOCK_ERROR = -1073733616 +RC_FAILED_TO_CREATE_PROCESS = -1073733615 +RC_USB_PED_NOT_FOUND = -1073733614 +RC_USB_PED_NOT_RESPONDING = -1073733613 +RC_USB_PED_OPERATION_CANCELLED = -1073733612 +RC_USB_PED_TOO_MANY_CONNECTED = -1073733611 +MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED = 32 +RC_USB_PED_OUT_OF_SYNC = -1073733610 +RC_UNABLE_TO_CONNECT = -1073737472 +LUNA_RET_SM_ACCESS_REALLOC_ERROR = 3211521 +LUNA_RET_CCM_UPDATE_DENIED = -2147482875 +LUNA_RET_UNWRAPPING_ERROR = -2147483384 +LUNA_RET_CHALLENGE_TYPE_INVALID = 2099968 +LUNA_RET_INVALID_PRIVATE_KEY_TYPE = -2147483383 +RC_SOCKET_WOULDBLOCK = -1073740538 +LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST = 3145993 +LUNA_RET_KCV_PARAMETER_MISSING = -2147483381 +LUNA_RET_CB_RETRY = -2147481083 +LUNA_RET_CB_ABORTED = -2147481082 +LUNA_RET_CB_NO_MEMORY = -2147481085 +LUNA_RET_CB_SYS_ERROR = -2147481081 +LUNA_RET_CB_HIOS_HANDLE_INVALID = -2147481072 +LUNA_RET_CB_PARAM_INVALID = -2147481086 +LUNA_RET_CB_HIOS_ID_INVALID = -2147481071 +LUNA_RET_CB_HIOS_CLOSED = -2147481070 +LUNA_RET_CB_NOT_SUPPORTED = -2147481087 +LUNA_RET_CB_HIOS_CANCELED = -2147481069 +LUNA_RET_CB_HIOS_IO_ERROR = -2147481068 +LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS = 2100229 +LUNA_RET_CB_HIOS_SEND_TIMEOUT = -2147481067 +LUNA_RET_CB_HIOS_RECV_TIMEOUT = -2147481066 +LUNA_RET_STORAGE_TYPE_INCONSISTENT = 2100228 +LUNA_RET_CB_HIOS_STATE_INVALID = -2147481065 +LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL = -2147481064 +LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST = 2100227 +LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL = -2147481063 +LUNA_RET_CB_HANDLE_INVALID = -2147481056 +LUNA_RET_OH_OBJECT_ALREADY_EXISTS = 68610 +LUNA_RET_OH_OBJECT_TYPE_INVALID = 3148801 +LUNA_RET_CB_REMOTE_CLOSED = -2147481053 +LUNA_RET_OH_OBJECT_VERSION_INVALID = 3148800 +LUNA_RET_CB_MUST_READ = -2147481051 +LUNA_RET_CHALLENGE_INVALID = 2099972 +LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE = -2147481049 +LUNA_RET_CB_SYNC_ERROR = -2147481048 +LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT = 68355 +LUNA_RET_CHALLENGE_RESPONSE_INCORRECT = 10488579 +LUNA_RET_SM_UNKNOWN_ACCESS_TYPE = -2147482621 +LUNA_RET_CHALLENGE_NOT_REQUIRED = 68354 +LUNA_RET_CHALLENGE_REQUIRES_PED = 68353 +LUNA_RET_LOG_BAD_FILE_NAME = -2147480318 +LUNA_RET_POLICY_NOT_FOUND = 2099730 +LUNA_RET_LOG_FULL = -2147480317 +LUNA_RET_BAD_SN = 2099729 +LUNA_RET_RM_CONFIG_ILLEGAL = 2099728 +LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE = 2099727 +LUNA_RET_LOG_BAD_RECORD_HMAC = -2147480315 +LUNA_RET_BAD_FW_VERSION = 2099726 +LUNA_RET_BAD_PPID = 2099725 +LUNA_RET_LOG_BAD_TIME = -2147480314 +LUNA_RET_LOG_AUDIT_NOT_INITIALIZED = -2147480313 +LUNA_RET_OPERATION_RESTRICTED = 68107 +LUNA_RET_RM_POLICY_WRITE_RESTRICTED = 68106 +LUNA_RET_LOG_RESYNC_NEEDED = -2147480312 +LUNA_RET_LICENSE_CAPACITY_EXCEEDED = 68105 +LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS = -2147480311 +LUNA_RET_LICENSE_ID_UNKNOWN = 2099720 +RC_SOCKET_ADDRESS_IN_USE = -1073740537 +LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD = -2147480310 +LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL = 68102 +LUNA_RET_USER_ALREADY_ACTIVATED = -2147480309 +LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE = 2099717 +LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE = 2099716 +LUNA_RET_RM_BAD_HSM_PARAMS = 3148291 +LUNA_RET_TOKEN_LOCKED_OUT_CL = 3145984 +LUNA_RET_RETRY = 3145761 +RC_SSL_WANT_WRITE_ERROR = -1073740018 +LUNA_RET_RM_NO_MEMORY = 3213826 +LUNA_RET_RM_ELEMENT_ID_INVALID = 2099713 +LUNA_RET_RM_ELEMENT_VALUE_INVALID = 2099712 +RC_RC_ERROR = -1073741824 +LUNA_RET_KEY_NOT_ACTIVE = -2147481340 +MSG_NVRAM_WRITE_FAILED = 26 +RC_MEMORY_ALLOCATION = -1073741823 +LUNA_RET_HSM_STORAGE_FULL = -2147481342 +RC_GENERAL_ERROR = -1073741822 +LUNA_RET_HA_NOT_SUPPORTED = -2147481344 +LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE = 68108 +RC_POINTER_INVALID = -1073741821 +MSG_FACTORY_RESET = 53 +LUNA_RET_ECC_UNKNOWN_CURVE = -2147482107 +LUNA_RET_DAK_MISSING = -2147483369 +RC_SLOT_ID_INVALID = -1073741567 +RC_UNEXPECTED = -1073741820 +MSG_BAD_HMAC = 51 +LUNA_RET_ECC_SELF_TEST_FAILURE = -2147482108 +MSG_LOG_WAS_TRUNCATED = 50 +RC_OPERATION_WOULD_BLOCK = -1073741819 +MSG_ZEROIZING_AFTER_DECOMMISSION = 48 +RC_BUFFER_TOO_SMALL = -1073741818 +MSG_RESTART = 47 +LUNA_RET_PE1746_ERROR = 3147911 +RC_CANCEL = -1073741568 +MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED = 45 +LUNA_RET_ISES_TEST_VS_BSAFE_FAILED = 3147910 +MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED = 44 +MSG_GENERATING_NEW_TVK_FAILED = 43 +LUNA_RET_ISES_CMD_FAILED = 3147908 +RC_DATA_INVALID = -1073741566 +LUNA_RET_ISES_RNG_TEST_FAILED = 3147907 +RC_PIN_INVALID = -1073741565 +LUNA_RET_ISES_LNAU_TEST_FAILED = 3147906 +MSG_TVK_WAS_CORRUPTED = 39 +LUNA_RET_ISES_INIT_FAILED = 3147905 +MSG_RTC_ROLLED_BACK = 37 +LUNA_RET_ISES_ERROR = 3147904 +MSG_TVK_TIMESTAMP_IS_TOO_OLD = 36 +LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT = 3147812 +MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK = 35 +MSG_TVK_TIMESTAMP_CORRUPTED = 34 +RC_NON_CRYPTOKI_ELEMENT_CLONE = -1073741562 +MSG_TVK_TIMESTAMP_RECOVERY_FAILED = 33 +LUNA_RET_SFNT3120_SELFTEST_FAILED = 3147810 +LUNA_RET_SFNT3120_ERROR = 3147809 +MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER = 31 +MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET = 30 +RC_PIN_LOCKED = -1073741560 +MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY = 29 +LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT = 3147790 +MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING = 28 +LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS = 3147789 +MSG_TVK_WAS_LOST_DUE_TO_TAMPER = 27 +RC_KEY_NEEDED = -1073741558 +MSG_NVRAM_READ_FAILED = 25 +LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH = 3147787 +RC_USER_NAME_IN_USE = -1073741557 +LUNA_RET_HIFN6500_INVALID_PARAMETERS = 3147786 +LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS = 3147788 +MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED = 23 +LUNA_RET_HIFN_DESTINATION_COUNT_INVALID = -2147482366 +LUNA_RET_HIFN6500_ALU_TIMEOUT = 3147785 +RC_DER_CLASS_INVALID = -1073741312 +MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF = 21 +LUNA_RET_HIFN6500_RNG_UNDERFLOW = 3147784 +RC_MANUFACTURING_NO_CONFIG_AVAILABLE = -1073741056 +MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF = 19 +LUNA_RET_HIFN6500_RNG_FAILED = 3147782 +RC_MANUFACTURING_TOKEN_NOT_PRESENT = -1073741055 +MSG_RTC_LOST_ALL_POWER = 17 +LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED = 3147781 +MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT = 15 +MSG_RTC_TAMPER_2_SIGNAL = 14 +RC_OPERATION_TIMED_OUT = -1073741053 +MSG_RTC_EXTERNAL_TAMPER_LATCHED = 13 +MSG_RTC_RECONFIGURING_FAILED = 12 +LUNA_RET_HIFN6500_NOT_PRESENT = 3147777 +LUNA_RET_INVALID_BOARD_TYPE = -2147481856 +MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS = 10 +LUNA_RET_INVALID_IP_PACKET = -2147482112 +MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS = 8 +LUNA_RET_MTK_SPLIT_INVALID = -2147482317 +MSG_RTC_CANT_CLEAN_TAMPER_1 = 7 +LUNA_RET_MTK_STATE_INVALID = -2147482318 +RC_FILE_NAME_INVALID = -1073740798 +MSG_RTC_CANT_INITIALIZE_I2C = 5 +MSG_RTC_CANT_CLEAN_TAMPER_2 = 9 +MSG_RTC_MSG_NVRAM_WRITE_FAILED = 4 +LUNA_RET_HIFN_DMA_INVALID_REVISION = -2147482320 +LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO = -2147482342 +RC_FILE_ERROR = -1073740796 +LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO = -2147482343 +RC_OBJECT_ID_INVALID = -1073740795 +LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO = -2147482344 +LUNA_RET_HIFN_DESTINATION_OVERRUN = -2147482345 +RC_SOCKET_ADDRESS_INVALID = -1073740794 +LUNA_RET_HIFN_END_MARKER_NOT_PRESENT = -2147482346 +RC_LISTEN_SOCKET_INVALID = -1073740793 +LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID = -2147482347 +LUNA_RET_HIFN_INVALID_PAD_ALGORITHM = -2147482348 +RC_CACHE_DIRTY = -1073740792 +LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID = -2147482349 +RC_CACHE_NOT_MAPPED = -1073740791 +LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID = -2147482350 +MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC = 0 +LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM = -2147482351 +LUNA_RET_HIFN_DMA_TIMED_OUT = -2147482354 +RC_OBJECT_ALREADY_EXISTS = -1073740788 +LUNA_RET_HIFN_DMA_NOT_IDLE = -2147482355 +RC_SEMAPHORE_ERROR = -1073740787 +LUNA2_RET_HIFN_RESET_ERROR = -2147482356 +RC_ENDOFLIST = -1073740786 +RC_NOT_PARTITION_BACKUP_TOKEN = -1073740782 +MSG_RTC_BATTERY_LOW = 18 +LUNA_RET_HIFN6500_RNG_TIMEOUT = 3147783 +LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED = -2147482622 +RC_SOCKET_BAD_FD = -1073740536 +LUNA_RET_MM_FATAL_ERROR = 3211270 +RC_MANUFACTURING_SERIAL_NUMBER_INVALID = -1073741054 +LUNA_RET_RNG_SELF_TEST_FAILURE = 3145744 +LUNA_RET_HIFN6500_DATA_LINES_BROKEN = 3147779 +MSG_TVK_TIMESTAMP_UPDATE_FAILED = 38 +LUNA_RET_INVALID_ACCESS_LEVEL = -2147483376 +MSG_RTC_CANT_CLEAN_POWER_LOSS = 11 +LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID = -2147482358 +RC_ASSIGNING_SAME_VALUE = -1073740785 +LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID = -2147482359 +LUNA_RET_HIFN_INVALID_ENCRYPT_MODE = -2147482360 +RC_GROUP_NAME_INVALID = -1073740784 +LUNA_RET_SM_UNKNOWN_SESSION_TYPE = -2147482618 +RC_CLIENT_DISCONNECTED = -1073740539 +LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED = -2147482617 +LUNA_RET_HA_USER_NOT_INITIALIZED = -2147481343 +RC_SERVER_DISCONNECTED = -1073740540 +LUNA_RET_SM_CONTEXT_NOT_ALLOCATED = -2147482616 +LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW = -2147482615 +RC_CLIENT_MESSAGE_ERROR = -1073740541 +LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE = -2147482614 +RC_SOCKET_READ_ERROR = -1073740542 +LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE = -2147482613 +LUNA_RET_HIFN_NOT_PRESENT = -2147482368 +RC_SOCKET_WRITE_ERROR = -1073740543 +LUNA_RET_HIFN_SOURCE_COUNT_INVALID = -2147482367 +LUNA_RET_ECC_RESULT_AT_INF = -2147482106 +RC_SOCKET_ERROR = -1073740544 +LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL = -2147481341 +LUNA_RET_HIFN_INVALID_MAC_ALGORITHM = -2147482365 +RC_SIM_NOT_SUPPORTED = -1073740781 +LUNA_RET_HIFN_INVALID_MAC_MODE = -2147482364 +LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID = -2147482363 +LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID = -2147482362 +RC_NOT_HSM_BACKUP_TOKEN = -1073740783 +LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM = -2147482361 +LUNA_RET_RC4_SELF_TEST_FAILURE = 3145741 +MSG_ZEROIZING_AFTER_NO_SECURE_DATA = 49 +LUNA_RET_ECC_BUFFER_OVERFLOW = -2147482110 +LUNA_RET_ECC_NOT_SUPPORTED = -2147482111 +MSG_RESYNC = 46 +LastFirmwareCode = -1073741825 +LUNA_RET_ISES_CMD_PARAMETER_INVALID = 3147909 +MSG_GENERATING_NEW_TVK_PASSED = 42 +LUNA_RET_LOG_FILE_WRITE_ERROR = -2147480319 +RC_SSL_GET_CERTIFICATE_ERROR = -1073740023 +RC_TOKEN_NOT_PRESENT = -1073741564 +MSG_LAST = 54 +LUNA_RET_SM_NOT_LOGGED_IN = 16842753 +LUNA_RET_USER_PIN_NOT_INITIALIZED = 16908288 +LUNA_RET_USER_NOT_LOGGED_IN = 16842752 +LUNA_RET_USER_TYPE_INVALID = 16973824 +LUNA_RET_RSA_SELF_TEST_FAILURE = 3145739 +LUNA_RET_WRAPPED_KEY_INVALID = 17825792 +RC_DATA_CORRUPTED = -1073740799 +LUNA_RET_SM_SESSION_READ_ONLY_EXISTS = 11993088 +LUNA_RET_WRAPPED_KEY_LEN_RANGE = 17956864 +LUNA_RET_WRAPPING_KEY_HANDLE_INVALID = 18022400 +LUNA_RET_SM_OTHER_USER_LOGGED_IN = 16777217 +LUNA_RET_WRAPPING_KEY_SIZE_RANGE = 18087936 +RC_FUNCTION_NOT_SUPPORTED = -1073741563 +LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT = 18153472 +LUNA_RET_USER_ALREADY_LOGGED_IN = 16777216 +LUNA_RET_CERT_VERSION_NOT_SUPPORTED = 3146496 +LUNA_RET_ERROR = -2147483648 +LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT = 15859712 +LUNA_RET_CONTAINER_HANDLE_INVALID = -2147483647 +LUNA_RET_INVALID_PADDING_TYPE = -2147483646 +LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE = 15794176 +LUNA_RET_AGAIN = -2147483642 +LUNA_RET_NOT_FOUND = -2147483641 +LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID = 15728640 +LUNA_RET_TOO_MANY_CONTAINERS = -2147483640 +LUNA_RET_CONTAINER_LOCKED = -2147483639 +LUNA_RET_SIGNATURE_LEN_RANGE = 12648448 +LUNA_RET_CONTAINER_IS_DISABLED = -2147483638 +LUNA_RET_SECURITY_PARAMETER_MISSING = -2147483637 +LUNA_RET_SIGNATURE_INVALID = 12582912 +RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR = -1073740026 +LUNA_RET_NO_OFFBOARD_STORAGE = 5505025 +LUNA_RET_SM_SESSION_HANDLE_INVALID = 11730944 +LUNA_RET_OBJECT_DELETED = -2147483635 +LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS = 11665408 +RC_SESSION_SCRIPT_EXISTS = -1073739519 +LUNA_RET_SM_PIN_EXPIRED = 10682368 +LUNA_RET_INVALID_FUF_TARGET = -2147483634 +LUNA_RET_UM_PIN_LEN_RANGE = 10616832 +LUNA_RET_INVALID_FUF_HEADER = -2147483633 +LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED = 10485762 +LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED = 10485761 +LUNA_RET_FUNCTION_NOT_SUPPORTED = 5505024 +LUNA_RET_INVALID_FUF_VERSION = -2147483632 +LUNA_RET_UM_PIN_INCORRECT = 10485760 +LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS = -2147483392 +LUNA_RET_OPERATION_NOT_INITIALIZED = 9502720 +RC_PORT_INVALID = -1073739520 +LUNA_RET_OPERATION_ACTIVE = 9437184 +RC_CHALLENGE_BUFFER_SIZE = -1073741561 +LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED = -2147483391 +LUNA_RET_MECHANISM_PARAM_INVALID = 7405568 +LUNA_RET_INVALID_CERTIFICATE_DATA = -2147483390 +LUNA_RET_MECHANISM_INVALID = 7340032 +LUNA_RET_KEY_HANDLE_INVALID = 6291456 +LUNA_RET_INVALID_CERTIFICATE_TYPE = -2147483389 +LUNA_RET_FUNCTION_CANCELED = 5242880 +LUNA_RET_INVALID_CERTIFICATE_VERSION = -2147483388 +LUNA_RET_ENCRYPTED_DATA_LEN_RANGE = 4259840 +RC_CERT_TYPE_INVALID = -1073739776 +LUNA_RET_ENCRYPTED_DATA_INVALID = 4194304 +LUNA_RET_INVALID_MODULUS_SIZE = -2147483387 +LUNA_RET_SM_MEMORY_ALLOCATION_ERROR = 3211523 +LUNA_RET_WRAPPING_ERROR = -2147483385 +LUNA_RET_SM_SESSION_REALLOC_ERROR = 3211522 +LUNA_RET_TEST_VS_BSAFE_FAILED = 3147808 +LUNA_RET_SPLIT_DATA_INVALID = -2147483128 +RC_VERSION_INVALID = -1073741559 +MSG_ZEROIZING = 52 +MSG_RTC_MSG_NVRAM_READ_FAILED = 24 +LUNA_RET_TOKEN_LOCKED_OUT_STC = 3145994 +RC_SSL_FAILED_HANDSHAKE = -1073740015 +LUNA_RET_TOKEN_LOCKED_OUT_CCM = 3145992 +LUNA_RET_TSN_MISMATCH = -2147483382 +LUNA_RET_TOKEN_LOCKED_OUT_OH = 3145991 +LUNA_RET_TOKEN_LOCKED_OUT_PM = 3145990 +LUNA_RET_TOKEN_LOCKED_OUT_CA = 3145989 +LUNA_RET_TWC_PARAMETER_MISSING = -2147483380 +LUNA_RET_TOKEN_LOCKED_OUT_RN = 3145988 +LUNA_RET_TUK_PARAMETER_MISSING = -2147483379 +LUNA_RET_TOKEN_LOCKED_OUT_SM = 3145987 +RC_SSL_SYSCALL_ERROR = -1073740016 +LUNA_RET_TOKEN_LOCKED_OUT_UM = 3145986 +LUNA_RET_CPK_PARAMETER_MISSING = -2147483378 +LUNA_RET_TOKEN_LOCKED_OUT_MM = 3145985 +LUNA_RET_MASKING_NOT_SUPPORTED = -2147483377 +LUNA_RET_RIPEMD160_SELF_TEST_FAILURE = 3145780 +LUNA_RET_INCOMPATIBLE = 3145764 +LUNA_RET_MAC_MISSING = -2147483375 +LUNA_RET_SELF_TEST_FAILURE = 3145763 +RC_SSL_WANT_X509_LOOKUP_ERROR = -1073740017 +LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE = 3145762 +LUNA_RET_DAC_POLICY_PID_MISMATCH = -2147483374 +LUNA_RET_DAC_MISSING = -2147483373 +LUNA_RET_NOT_READY = 3145760 +LUNA_RET_TIMEOUT = 3145759 +LUNA_RET_BAD_DAC = -2147483372 +LUNA_RET_COUNTER_WRAPAROUND = 3145758 +LUNA_RET_SSK_MISSING = -2147483371 +LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL = 3145757 +LUNA_RET_KCDSA_SELF_TEST_FAILURE = 3145756 +LUNA_RET_BAD_MAC = -2147483370 +LUNA_RET_KCDSA_PARAM_GEN_FAILURE = 3145755 +LUNA_RET_HAS160_SELF_TEST_FAILURE = 3145754 +LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE = 3145753 +LUNA_RET_BAD_DAK = -2147483368 +LUNA_RET_AES_SELF_TEST_FAILURE = 3145752 +LUNA_RET_HOK_MISSING = -2147483367 +LUNA_RET_SEED_SELF_TEST_FAILURE = 3145751 +MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK = 41 +MSG_RTC_MSG_NVRAM_ZAPPING_FAILED = 3 +RC_SSL_WANT_READ_ERROR = -1073740019 +LUNA_RET_DSA_SELF_TEST_FAILURE = 3145750 +LUNA_RET_CITS_DAK_MISSING = -2147483366 +LUNA_RET_DSA_PARAM_GEN_FAILURE = 3145749 +LUNA_RET_SIM_AUTHORIZATION_FAILED = -2147483365 +LUNA_RET_SM_UNKNOWN_TOSM_STATE = 3145748 +LUNA_RET_SM_TSV_MISSING = 3145747 +LUNA_RET_SIM_VERSION_UNSUPPORTED = -2147483364 +LUNA_RET_UM_TSN_MISSING = 3145746 +LUNA_RET_SIM_CORRUPT_DATA = -2147483363 +LUNA_RET_SM_UNKNOWN_COMMAND = 3145745 +RC_SSL_GET_PEER_CERT_ERROR = -1073740020 +LUNA_RET_ECC_MIC_MISSING = -2147483362 +LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD = 3145743 +LUNA_RET_ECC_HOK_MISSING = -2147483361 +LUNA_RET_RC5_SELF_TEST_FAILURE = 3145742 +LUNA_RET_ECC_HOC_MISSING = -2147483360 +LUNA_RET_RC2_SELF_TEST_FAILURE = 3145740 +LUNA_RET_ECC_DAK_MISSING = -2147483359 +RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR = -1073740021 +LUNA_RET_SHA_SELF_TEST_FAILURE = 3145738 +MSG_RTC_EXTERNAL_TAMPER_DETECTED = 1 +LUNA_RET_ECC_DAC_MISSING = -2147483358 +LUNA_RET_ECC_POINT_INVALID = -2147482109 +LUNA_RET_MD5_SELF_TEST_FAILURE = 3145737 +LUNA_RET_ROOT_CERT_MISSING = -2147483357 +LUNA_RET_MD2_SELF_TEST_FAILURE = 3145736 +LUNA_RET_CAST5_SELF_TEST_FAILURE = 3145735 +LUNA_RET_HOC_MISSING = -2147483356 +LUNA_RET_CAST3_SELF_TEST_FAILURE = 3145734 +LUNA_RET_INVALID_CERTIFICATE_FUNCTION = -2147483355 +LUNA_RET_CAST_SELF_TEST_FAILURE = 3145733 +RC_SSL_INVALID_CERT_STRUCTURE = -1073740022 +LUNA_RET_DES_SELF_TEST_FAILURE = 3145732 +LUNA_RET_SIM_AUTHFORM_INVALID = 2097438 +LUNA_RET_RNG_ERROR = 3145731 +LUNA_RET_N_TOO_LARGE = -2147483136 +LUNA_RET_TOKEN_LOCKED_OUT = 3145730 +LUNA_RET_UNKNOWN_COMMAND = 3145729 +LUNA_RET_N_TOO_SMALL = -2147483135 +LUNA_RET_DEVICE_ERROR = 3145728 +LUNA_RET_M_TOO_LARGE = -2147483134 +LUNA_RET_GENERAL_ERROR = 327680 +LUNA_RET_DATA_LEN_RANGE = 2162688 +LUNA_RET_M_TOO_SMALL = -2147483133 +LUNA_RET_410_BUFFER_TOO_SMALL = 2097174 +LUNA_RET_WEIGHT_TOO_LARGE = -2147483132 +LUNA_RET_BUFFER_TOO_SMALL = 22020096 +LUNA_RET_CL_COMMAND_NON_BACKUP = 5505026 +LUNA_RET_WEIGHT_TOO_SMALL = -2147483131 +LUNA_RET_TOTAL_WEIGHT_INVALID = -2147483130 +RC_SSL_LOAD_CLIENT_CERT_ERROR = -1073740024 +LUNA_RET_NO_RNG_SEED = 2097173 +LUNA_RET_MISSING_SPLITS = -2147483129 +LUNA_RET_SM_DATA_INVALID = 2097154 +LUNA_RET_TPV_INVALID = 2097153 +LUNA_RET_DATA_INVALID = 2097152 +LUNA_RET_SPLIT_ID_INVALID = -2147483127 +LUNA_RET_INVALID_ENTRY_TYPE = 458753 +LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE = -2147483126 +LUNA_RET_ARGUMENTS_BAD = 458752 +RC_SSL_CREATE_SSL_ERROR = -1073740025 +LUNA_RET_KEY_NOT_UNWRAPPABLE = 6881281 +LUNA_RET_M_OF_N_ACTIVATION_REQUIRED = -2147483125 +LUNA_RET_KEY_NOT_WRAPPABLE = 6881280 +LUNA_RET_TOO_MANY_WEIGHTS = -2147483122 +LUNA_RET_KEY_EXTRACTABLE = 6946817 +LUNA_RET_MISSING_WEIGHT_VALUE = -2147483121 +LUNA_RET_KEY_UNEXTRACTABLE = 6946816 +LUNA_RET_MISSING_VALUE_FOR_M = -2147483120 +LUNA_RET_KEY_PARITY = 6488066 +LUNA_RET_KEY_INVALID_FOR_OPERATION = 6488065 +LUNA_RET_MISSING_VALUE_FOR_N = -2147483119 +LUNA_RET_MISSING_NUMBER_OF_VECTORS = -2147483118 +LUNA_RET_SM_KEY_SIZE_ERROR = 6422529 +LUNA_RET_KEY_SIZE_RANGE = 6422528 +LUNA_RET_KEY_SENSITIVE = 6356992 +RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR = -1073740027 +LUNA_RET_VECTOR_TOO_LARGE = -2147483116 +LUNA_RET_SM_BAD_CONTEXT_NUMBER = -2147482619 +MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK = 40 +LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED = 13697048 +LUNA_RET_VECTOR_TOO_SMALL = -2147483115 +LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL = 6815745 +LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 +LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631510 +RC_SSL_LOAD_SERVER_CERT_ERROR = -1073740028 +LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE = 1245205 +LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 +LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631508 +LUNA_RET_M_OF_N_PARAMETER_EXIST = -2147483112 +LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY = 13697042 +LUNA_RET_ATTRIBUTE_NOT_FOUND = 1179664 +LUNA_RET_VECTOR_OF_DIFFERENT_SET = -2147483110 +LUNA_RET_MAX_OBJECT_COUNT = 8519681 +LUNA_RET_OBJECT_HANDLE_INVALID = 8519680 +LUNA_RET_ATTRIBUTE_SENSITIVE = 1114112 +LUNA_RET_VECTOR_DUPLICATE = -2147483109 +LUNA_RET_ATTRIBUTE_READ_ONLY = 1048576 +LUNA_RET_ATTRIBUTE_VALUE_INVALID = 1245184 +LUNA_RET_VECTOR_TYPE_INVALID = -2147483108 +LUNA_RET_TEMPLATE_INCONSISTENT = 13697024 +LUNA_RET_TEMPLATE_INCOMPLETE = 13631488 +RC_SSL_CIPHER_LIST_ERROR = -1073740030 +LUNA_RET_VECTOR_VERSION_INVALID = -2147483111 +LUNA_RET_MISSING_COMMAND_PARAMETER = -2147483107 +LUNA_RET_MM_INVALID_USAGE = 3211268 +LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE = 3211267 +LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED = -2147483106 +LUNA_RET_MM_USAGE_ALREADY_SET = 3211266 +LUNA_RET_MM_INVALID_HANDLE = 3211265 +LUNA_RET_MM_NOT_ENOUGH_MEMORY = 3211264 +LUNA_RET_M_OF_N_IS_NOT_REQUIRED = -2147483105 +LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE = 3146246 +LUNA_RET_CL_COMMAND_MALFORMED = 3146245 +RC_SSL_CTX_ERROR = -1073740031 +LUNA_RET_CL_NO_TRANSMISSION = 3146244 +LUNA_RET_M_OF_N_IS_NOT_INITIALZED = -2147483104 +LUNA_RET_CL_TRANSMISSION_ERROR = 3146243 +LUNA_RET_CL_QUEUE_OVERLAP_ERROR = 3146242 +LUNA_RET_CL_QUEUE_LOCATION_ERROR = 3146241 +LUNA_RET_M_OF_N_SECRET_INVALID = -2147483103 +LUNA_RET_CL_ALIGNMENT_ERROR = 3146240 +LUNA_RET_PED_CLIENT_NOT_RUNNING = 3146055 +LUNA_RET_PED_DEK_INVALID = 3146054 +LUNA_RET_CCM_NOT_PRESENT = -2147482880 +LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL = 3146053 +LUNA_RET_PED_ERROR = 3146052 +RC_SSL_ERROR = -1073740032 +LUNA_RET_CCM_NOT_SUPPORTED = -2147482879 +LUNA_RET_PED_UNSUPPORTED_PROTOCOL = 3146049 +LUNA_RET_PED_ID_INVALID = 3146048 +LUNA_RET_SP_RX_ERROR = 3146034 +LUNA_RET_CCM_UNREMOVABLE = -2147482878 +LUNA_RET_SP_TX_ERROR = 3146033 +LUNA_RET_PED_UNPLUGGED = 3146050 +LUNA_RET_FORMER_INVALID_ENTRY_TYPE = 3146032 +LUNA_RET_TOKEN_NOT_PRESENT = 14680064 +LUNA_RET_CCM_CERT_INVALID = -2147482877 +LUNA_RET_FLAGS_INVALID = 262144 +LUNA_RET_CANCEL = 65536 +RC_INVALID_ENUM_OPTION = -1073740287 +RC_OK = 0 +MSG_RTC_CONFIGURATION_CORRUPTED = 22 +LUNA_RET_KEY_INDIGESTIBLE = 6750208 +MSG_RTC_ZEROIZED_ON_POWER_LOSS = 20 +MSG_RTC_TAMPER_CIRCUITS_RE_ARMED = 16 +LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN = 3147780 +LUNA_RET_KEY_TYPE_INCONSISTENT = 6488064 +LUNA_RET_HIFN6500_RESET_TIMEOUT = 3147778 +RC_RESET_FAILED = -1073741052 +LUNA_RET_MISSING_VECTOR = -2147483117 +RC_TOKEN_STATE_INVALID = -1073740800 +LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION = 1048601 +LUNA_RET_CB_TIMEOUT = -2147481084 +MSG_RTC_CANT_ACCESS = 6 +LUNA_RET_MTK_ZEROIZED = -2147482319 +RC_FILE_READ_ONLY = -1073740797 +LUNA_RET_SM_BAD_ACCESS_HANDLE = -2147482620 +MSG_RTC_CANT_GET_TAMPER_TIMER = 2 +LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE = 1245203 +LUNA_RET_OK = 0 +LUNA_RET_CCM_SIGN_INVALID = -2147482876 +LUNA_RET_CB_ID_INVALID = -2147481055 +RC_NO_BUFFER = -1073740288 +LUNA_RET_CB_REMOTE_ABORT = -2147481054 +LUNA_RET_CCM_FWUPDATE_DENIED = -2147482874 +RC_INVALID_CERT_HOST = -1073740534 +LUNA_RET_CCM_TOO_LARGE = 2162689 +LUNA_RET_CAN_NOT_CREATE_SECRET_KEY = 13697041 +RC_SSL_CERT_VERIFICATION_LOCATION_ERROR = -1073740029 +LUNA_RET_CB_REMOTE_ABANDONED = -2147481052 +LUNA_RET_SM_ACCESS_ID_INVALID = -2147482624 +RC_HOST_RESOLUTION_ERROR = -1073740535 +LUNA_RET_CB_MUST_WRITE = -2147481050 +LUNA_RET_SM_ACCESS_ALREADY_EXISTS = -2147482623 + +# values for enumeration 'ResultCodeValue' +ResultCodeValue = c_int # enum + +# values for unnamed enumeration +CK_USHORT = c_ulong +CK_USHORT_PTR = POINTER(CK_USHORT) +class CK_AES_GCM_PARAMS(Structure): + pass +CK_BYTE = c_ubyte +CK_BYTE_PTR = POINTER(CK_BYTE) +CK_ULONG = c_ulong +if 'win' in sys.platform: + CK_AES_GCM_PARAMS._pack_ = 1 +CK_AES_GCM_PARAMS._fields_ = [ + ('pIv', CK_BYTE_PTR), + ('ulIvLen', CK_ULONG), + ('ulIvBits', CK_ULONG), + ('pAAD', CK_BYTE_PTR), + ('ulAADLen', CK_ULONG), + ('ulTagBits', CK_ULONG), +] +CK_AES_GCM_PARAMS_PTR = CK_AES_GCM_PARAMS +class CK_XOR_BASE_DATA_KDF_PARAMS(Structure): + pass +CK_EC_KDF_TYPE = CK_ULONG +if 'win' in sys.platform: + CK_XOR_BASE_DATA_KDF_PARAMS._pack_ = 1 +CK_XOR_BASE_DATA_KDF_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), +] +CK_XOR_BASE_DATA_KDF_PARAMS_PTR = POINTER(CK_XOR_BASE_DATA_KDF_PARAMS) +CK_EC_DH_PRIMITIVE = CK_ULONG +CK_EC_ENC_SCHEME = CK_ULONG +CK_EC_MAC_SCHEME = CK_ULONG +class CK_ECIES_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_ECIES_PARAMS._pack_ = 1 +CK_ECIES_PARAMS._fields_ = [ + ('dhPrimitive', CK_EC_DH_PRIMITIVE), + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen1', CK_ULONG), + ('pSharedData1', CK_BYTE_PTR), + ('encScheme', CK_EC_ENC_SCHEME), + ('ulEncKeyLenInBits', CK_ULONG), + ('macScheme', CK_EC_MAC_SCHEME), + ('ulMacKeyLenInBits', CK_ULONG), + ('ulMacLenInBits', CK_ULONG), + ('ulSharedDataLen2', CK_ULONG), + ('pSharedData2', CK_BYTE_PTR), +] +CK_ECIES_PARAMS_PTR = POINTER(CK_ECIES_PARAMS) +CK_KDF_PRF_TYPE = CK_ULONG +CK_KDF_PRF_ENCODING_SCHEME = CK_ULONG +class CK_KDF_PRF_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_KDF_PRF_PARAMS._pack_ = 1 +CK_KDF_PRF_PARAMS._fields_ = [ + ('prfType', CK_KDF_PRF_TYPE), + ('pLabel', CK_BYTE_PTR), + ('ulLabelLen', CK_ULONG), + ('pContext', CK_BYTE_PTR), + ('ulContextLen', CK_ULONG), + ('ulCounter', CK_ULONG), + ('ulEncodingScheme', CK_KDF_PRF_ENCODING_SCHEME), +] +CK_PRF_KDF_PARAMS = CK_KDF_PRF_PARAMS +CK_KDF_PRF_PARAMS_PTR = POINTER(CK_PRF_KDF_PARAMS) +class CK_AES_CTR_PARAMS(Structure): + pass +CK_SEED_CTR_PARAMS = CK_AES_CTR_PARAMS +CK_SEED_CTR_PARAMS_PTR = POINTER(CK_SEED_CTR_PARAMS) +CK_ARIA_CTR_PARAMS = CK_AES_CTR_PARAMS +CK_ARIA_CTR_PARAMS_PTR = POINTER(CK_ARIA_CTR_PARAMS) +class CK_DES_CTR_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_DES_CTR_PARAMS._pack_ = 1 +CK_DES_CTR_PARAMS._fields_ = [ + ('ulCounterBits', CK_ULONG), + ('cb', CK_BYTE * 8), +] +CK_DES_CTR_PARAMS_PTR = POINTER(CK_DES_CTR_PARAMS) +CK_AES_GMAC_PARAMS = CK_AES_GCM_PARAMS +CK_AES_GMAC_PARAMS_PTR = POINTER(CK_AES_GMAC_PARAMS) +class CA_ROLE_STATE(Structure): + pass +if 'win' in sys.platform: + CA_ROLE_STATE._pack_ = 1 +CA_ROLE_STATE._fields_ = [ + ('flags', CK_BYTE), + ('loginAttemptsLeft', CK_BYTE), + ('primaryAuthMech', CK_BYTE), + ('secondaryAuthMech', CK_BYTE), +] +class CA_MOFN_GENERATION(Structure): + pass +if 'win' in sys.platform: + CA_MOFN_GENERATION._pack_ = 1 +CA_MOFN_GENERATION._fields_ = [ + ('ulWeight', CK_ULONG), + ('pVector', CK_BYTE_PTR), + ('ulVectorLen', CK_ULONG), +] +CA_MOFN_GENERATION_PTR = POINTER(CA_MOFN_GENERATION) +class CA_MOFN_ACTIVATION(Structure): + pass +if 'win' in sys.platform: + CA_MOFN_ACTIVATION._pack_ = 1 +CA_MOFN_ACTIVATION._fields_ = [ + ('pVector', CK_BYTE_PTR), + ('ulVectorLen', CK_ULONG), +] +CA_MOFN_ACTIVATION_PTR = POINTER(CA_MOFN_ACTIVATION) +class CA_M_OF_N_STATUS(Structure): + pass +if 'win' in sys.platform: + CA_M_OF_N_STATUS._pack_ = 1 +CA_M_OF_N_STATUS._fields_ = [ + ('ulID', CK_ULONG), + ('ulM', CK_ULONG), + ('ulN', CK_ULONG), + ('ulSecretSize', CK_ULONG), + ('ulFlag', CK_ULONG), +] +CA_MOFN_STATUS = CA_M_OF_N_STATUS +CA_MOFN_STATUS_PTR = POINTER(CA_MOFN_STATUS) +CKCA_MODULE_ID = CK_ULONG +CKCA_MODULE_ID_PTR = POINTER(CKCA_MODULE_ID) +class CKCA_MODULE_INFO(Structure): pass +CK_CHAR = CK_BYTE class CK_VERSION(Structure): pass -CK_BYTE = c_ubyte +if 'win' in sys.platform: + CK_VERSION._pack_ = 1 CK_VERSION._fields_ = [ ('major', CK_BYTE), ('minor', CK_BYTE), ] -CK_ULONG = c_ulong +if 'win' in sys.platform: + CKCA_MODULE_INFO._pack_ = 1 +CKCA_MODULE_INFO._fields_ = [ + ('ulModuleSize', CK_ULONG), + ('developerName', CK_CHAR * 32), + ('moduleDescription', CK_CHAR * 32), + ('moduleVersion', CK_VERSION), +] +CKCA_MODULE_INFO_PTR = POINTER(CKCA_MODULE_INFO) +class CK_HA_MEMBER(Structure): + pass CK_RV = CK_ULONG -CK_VOID_PTR = c_void_p -CK_C_Initialize = CFUNCTYPE(CK_RV, CK_VOID_PTR) -CK_C_Finalize = CFUNCTYPE(CK_RV, CK_VOID_PTR) -class CK_INFO(Structure): +if 'win' in sys.platform: + CK_HA_MEMBER._pack_ = 1 +CK_HA_MEMBER._fields_ = [ + ('memberSerial', CK_CHAR * 20), + ('memberStatus', CK_RV), +] +class CK_HA_STATUS(Structure): + pass +if 'win' in sys.platform: + CK_HA_STATUS._pack_ = 1 +CK_HA_STATUS._fields_ = [ + ('groupSerial', CK_CHAR * 20), + ('memberList', CK_HA_MEMBER * 32), + ('listSize', CK_ULONG), +] +CK_HA_MEMBER_PTR = POINTER(CK_HA_MEMBER) +CK_HA_STATE_PTR = POINTER(CK_HA_STATUS) +CKA_SIM_AUTH_FORM = CK_ULONG +class CT_Token(Structure): + pass +if 'win' in sys.platform: + CT_Token._pack_ = 1 +CT_Token._fields_ = [ +] +CT_TokenHndle = POINTER(CT_Token) +class CK_AES_CBC_PAD_EXTRACT_PARAMS(Structure): pass -CK_INFO_PTR = POINTER(CK_INFO) -CK_C_GetInfo = CFUNCTYPE(CK_RV, CK_INFO_PTR) -CK_FUNCTION_LIST_PTR = POINTER(CK_FUNCTION_LIST) -CK_FUNCTION_LIST_PTR_PTR = POINTER(CK_FUNCTION_LIST_PTR) -CK_C_GetFunctionList = CFUNCTYPE(CK_RV, CK_FUNCTION_LIST_PTR_PTR) -CK_BBOOL = CK_BYTE -CK_SLOT_ID = CK_ULONG -CK_SLOT_ID_PTR = POINTER(CK_SLOT_ID) CK_ULONG_PTR = POINTER(CK_ULONG) -CK_C_GetSlotList = CFUNCTYPE(CK_RV, CK_BBOOL, CK_SLOT_ID_PTR, CK_ULONG_PTR) -class CK_SLOT_INFO(Structure): +if 'win' in sys.platform: + CK_AES_CBC_PAD_EXTRACT_PARAMS._pack_ = 1 +CK_AES_CBC_PAD_EXTRACT_PARAMS._fields_ = [ + ('ulType', CK_ULONG), + ('ulHandle', CK_ULONG), + ('ulDeleteAfterExtract', CK_ULONG), + ('pBuffer', CK_BYTE_PTR), + ('pulBufferLen', CK_ULONG_PTR), + ('ulStorage', CK_ULONG), + ('pedId', CK_ULONG), + ('pbFileName', CK_BYTE_PTR), + ('ctxID', CK_ULONG), +] +CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_EXTRACT_PARAMS) +class CK_AES_CBC_PAD_INSERT_PARAMS(Structure): pass -CK_SLOT_INFO_PTR = POINTER(CK_SLOT_INFO) -CK_C_GetSlotInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_INFO_PTR) -class CK_TOKEN_INFO(Structure): +if 'win' in sys.platform: + CK_AES_CBC_PAD_INSERT_PARAMS._pack_ = 1 +CK_AES_CBC_PAD_INSERT_PARAMS._fields_ = [ + ('ulStorageType', CK_ULONG), + ('ulContainerState', CK_ULONG), + ('pBuffer', CK_BYTE_PTR), + ('ulBufferLen', CK_ULONG), + ('pulType', CK_ULONG_PTR), + ('pulHandle', CK_ULONG_PTR), + ('ulStorage', CK_ULONG), + ('pedId', CK_ULONG), + ('pbFileName', CK_BYTE_PTR), + ('ctxID', CK_ULONG), +] +CK_AES_CBC_PAD_INSERT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_INSERT_PARAMS) +class CK_CLUSTER_STATE(Structure): pass -CK_TOKEN_INFO_PTR = POINTER(CK_TOKEN_INFO) -CK_C_GetTokenInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_TOKEN_INFO_PTR) -CK_MECHANISM_TYPE = CK_ULONG -CK_MECHANISM_TYPE_PTR = POINTER(CK_MECHANISM_TYPE) -CK_C_GetMechanismList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE_PTR, CK_ULONG_PTR) -class CK_MECHANISM_INFO(Structure): +if 'win' in sys.platform: + CK_CLUSTER_STATE._pack_ = 1 +CK_CLUSTER_STATE._fields_ = [ + ('bMembers', CK_BYTE * 32 * 8), + ('ulMemberStatus', CK_ULONG * 8), +] +CK_CLUSTER_STATE_PTR = POINTER(CK_CLUSTER_STATE) +class CK_LKM_TOKEN_ID_S(Structure): pass -CK_MECHANISM_INFO_PTR = POINTER(CK_MECHANISM_INFO) -CK_C_GetMechanismInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE, CK_MECHANISM_INFO_PTR) -CK_UTF8CHAR = CK_BYTE -CK_UTF8CHAR_PTR = POINTER(CK_UTF8CHAR) -CK_C_InitToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR) -CK_SESSION_HANDLE = CK_ULONG -CK_C_InitPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG) -CK_C_SetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, CK_ULONG) +if 'win' in sys.platform: + CK_LKM_TOKEN_ID_S._pack_ = 1 +CK_LKM_TOKEN_ID_S._fields_ = [ + ('id', CK_BYTE * 20), +] +CK_LKM_TOKEN_ID = CK_LKM_TOKEN_ID_S +CK_LKM_TOKEN_ID_PTR = POINTER(CK_LKM_TOKEN_ID) +class CK_SFNT_CA_FUNCTION_LIST(Structure): + pass +CK_SFNT_CA_FUNCTION_LIST_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST) +CK_SFNT_CA_FUNCTION_LIST_PTR_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST_PTR) +CK_SLOT_ID = CK_ULONG +CK_C_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_GetFunctionList = CFUNCTYPE(CK_RV, CK_SFNT_CA_FUNCTION_LIST_PTR_PTR) CK_FLAGS = CK_ULONG +CK_SLOT_ID_PTR = POINTER(CK_SLOT_ID) +CK_VOID_PTR = c_void_p +CK_CA_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, POINTER(CK_ULONG), CK_SLOT_ID_PTR, CK_VOID_PTR) +CK_CHAR_PTR = POINTER(CK_CHAR) +CK_SESSION_HANDLE = CK_ULONG +CK_CA_InitIndirectToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_SESSION_HANDLE) +CK_CA_InitIndirectPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_SESSION_HANDLE) +CK_CA_ResetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG) +CK_USER_TYPE = CK_ULONG +CK_CA_InitRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG) +CK_CA_InitSlotRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG) +CK_CA_RoleStateGet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE, POINTER(CA_ROLE_STATE)) +CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_Deactivate = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE) +CK_CA_FindAdminSlotForSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_SLOT_ID), POINTER(CK_SLOT_ID)) +CK_CA_TokenInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CT_TokenHndle, CK_SLOT_ID) +CK_CA_TokenInsertNoAuth = CFUNCTYPE(CK_RV, CT_TokenHndle, CK_SLOT_ID) +CK_CA_TokenZeroize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_FLAGS) +CK_CA_TokenDelete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID) CK_NOTIFICATION = CK_ULONG CK_NOTIFY = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) CK_SESSION_HANDLE_PTR = POINTER(CK_SESSION_HANDLE) -CK_C_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) -CK_C_CloseSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_C_CloseAllSessions = CFUNCTYPE(CK_RV, CK_SLOT_ID) -class CK_SESSION_INFO(Structure): - pass -CK_SESSION_INFO_PTR = POINTER(CK_SESSION_INFO) -CK_C_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_INFO_PTR) -CK_BYTE_PTR = POINTER(CK_BYTE) -CK_C_GetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) +CK_CA_IndirectLogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE) +CK_CA_InitializeRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_DeleteRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_GetRemotePEDVectorStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_ConfigureRemotePED = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_DismantleRemotePED = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) +CK_CA_Restart = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_RestartForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) +CK_CA_CloseApplicationID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG) +CK_CA_CloseApplicationIDForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG) +CK_CA_OpenApplicationID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG) +CK_CA_OpenApplicationIDForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG) +CK_CA_SetApplicationID = CFUNCTYPE(CK_RV, CK_ULONG, CK_ULONG) +CK_CA_ManualKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_SetLKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_CA_SetKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_CA_SetRDK = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_BYTE), CK_ULONG) +CK_CA_SetCloningDomain = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG) CK_OBJECT_HANDLE = CK_ULONG -CK_C_SetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE) -CK_USER_TYPE = CK_ULONG -CK_C_Login = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG) -CK_C_Logout = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -class CK_ATTRIBUTE(Structure): - pass -CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) CK_OBJECT_HANDLE_PTR = POINTER(CK_OBJECT_HANDLE) -CK_C_CreateObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_CopyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_DestroyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) -CK_C_GetObjectSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR) -CK_C_GetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) -CK_C_SetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) -CK_C_FindObjectsInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) -CK_C_FindObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG_PTR) -CK_C_FindObjectsFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_ClonePrivateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) +CK_CA_CloneObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) +CK_CA_GenerateCloningKEV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_BBOOL = CK_BYTE +CK_CA_CloneAsTargetInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsSource = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsTarget = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR) +CK_CA_SetMofN = CFUNCTYPE(CK_RV, CK_BBOOL) +CK_CA_GenerateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_GenerateCloneableMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_ModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_CloneMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) +CK_CA_CloneModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) +CK_CA_ActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CA_MOFN_ACTIVATION_PTR, CK_ULONG) +CK_CA_DeactivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_GetMofNStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CA_MOFN_STATUS_PTR) +CK_CA_DuplicateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_IsMofNEnabled = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_IsMofNRequired = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +class CK_ATTRIBUTE(Structure): + pass +CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) +CK_CA_GenerateTokenKeys = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_CA_GetTokenCertificateInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetModuleList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetModuleInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR) +CK_CA_LoadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_LoadEncryptedModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_UnloadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID) +CK_CA_PerformModuleCall = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_FirmwareUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) +CK_CA_FirmwareRollback = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_CapabilityUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) +CK_CA_GetUserContainerNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_SetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetTokenInsertionCount = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetRollbackFirmwareVersion = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetFPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetExtendedTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetConfigurationElementDescription = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_GetHSMCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetHSMCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetHSMPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetHSMPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetContainerCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetContainerPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_SetTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_SetExtendedTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_SetHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_SetHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetDestructiveHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_SetDestructiveHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetContainerPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG) +CK_CA_SetContainerPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetTokenCapabilities = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetTokenPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetTokenPolicies = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_RetrieveLicenseList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_QueryLicense = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_GetContainerStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetTokenStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_ReadCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_WriteCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetPrimarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID_PTR) +CK_CA_GetSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID_PTR) +CK_CA_SwitchSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG) +CK_CA_CloseSecondarySession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG) +CK_CA_CloseAllSecondarySessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_ChoosePrimarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_ChooseSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_CloneObjectToAllSessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_CA_CloneAllObjectsToSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID) +CK_CA_ResetDevice = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS) +CK_CA_Zeroize = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS) +CK_CA_FactoryReset = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS) +CK_CA_SetPedId = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) +CK_CA_GetPedId = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG)) +CK_CA_SpRawRead = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_SpRawWrite = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_CheckOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)) +CK_CA_DestroyMultipleObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR) +CK_CA_OpenSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_CloseSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_ListSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) class CK_MECHANISM(Structure): pass CK_MECHANISM_PTR = POINTER(CK_MECHANISM) -CK_C_EncryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_Encrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_EncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_EncryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_Decrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DigestInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) -CK_C_Digest = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_C_DigestKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) -CK_C_DigestFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_SignInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_Sign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_SignUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_C_SignFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_SignRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_SignRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_VerifyInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_Verify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_C_VerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_C_VerifyFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_C_VerifyRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_VerifyRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DigestEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptDigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_SignEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptVerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_GenerateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_GenerateKeyPair = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) -CK_C_WrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_UnwrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_DeriveKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_SeedRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_C_GenerateRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_C_GetFunctionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_C_CancelFunction = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_C_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, CK_SLOT_ID_PTR, CK_VOID_PTR) -CK_FUNCTION_LIST._fields_ = [ +CK_CA_GetSecureElementMeta = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) +CK_CA_HAInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_CA_HAGetMasterPublic = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAGetLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAAnswerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HALogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAAnswerMofNChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetHAState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_HA_STATE_PTR) +CK_CA_GetTokenCertificates = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_ExtractMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_InsertMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) +CK_CA_MultisignValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) +CK_CA_SIMExtract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_SIMInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_SIMMultiSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) +CK_CA_Extract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) +CK_CA_Insert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) +CK_CA_GetTokenObjectUID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)) +CK_CA_GetTokenObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetObjectUID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)) +CK_CA_GetObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_DeleteContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_MTKSetStorage = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_MTKRestore = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_MTKResplit = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_MTKZeroize = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_MTKGetState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetTSV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_InvokeServiceInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_InvokeService = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_InvokeServiceFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_InvokeServiceAsynch = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_InvokeServiceSinglePart = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_EncodeECParamsFromFile = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR) +class HSM_STATS_PARAMS(Structure): + pass +CK_CA_GetHSMStats = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, POINTER(HSM_STATS_PARAMS)) +CK_CA_GetHSMStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetTokenStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetContainerSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_CreateContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_InitAudit = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR) +CK_CA_LogVerify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_LogVerifyFile = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LogExternal = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SESSION_HANDLE, POINTER(CK_CHAR), CK_ULONG) +CK_CA_LogImportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) +CK_CA_LogExportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) +CK_CA_TimeSync = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_GetTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR) +CK_CA_LogSetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR) +CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR) +CK_CA_LogEraseAll = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)) +CK_CA_DeleteContainerWithHandle = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_GetContainerList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_GetNumberOfAllowedContainers = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetTunnelSlotNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_ID_PTR) +CK_CA_GetClusterState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CLUSTER_STATE_PTR) +CK_CA_LockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_UnlockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) +CK_CA_LKMInitiatorChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMReceiverResponse = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMInitiatorComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_LKMReceiverComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_ModifyUsageCount = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_EnableUnauthTokenInsertion = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetUnauthTokenInsertionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_ULONG), POINTER(CK_ULONG)) +CK_CA_DisableUnauthTokenInsertion = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_STCRegister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG) +CK_CA_STCDeregister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR)) +CK_CA_STCGetPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetClientsList = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_STCGetClientInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetPartPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetAdminPubKey = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +if 'win' in sys.platform: + CK_SFNT_CA_FUNCTION_LIST._pack_ = 1 +CK_SFNT_CA_FUNCTION_LIST._fields_ = [ ('version', CK_VERSION), - ('C_Initialize', CK_C_Initialize), - ('C_Finalize', CK_C_Finalize), - ('C_GetInfo', CK_C_GetInfo), - ('C_GetFunctionList', CK_C_GetFunctionList), - ('C_GetSlotList', CK_C_GetSlotList), - ('C_GetSlotInfo', CK_C_GetSlotInfo), - ('C_GetTokenInfo', CK_C_GetTokenInfo), - ('C_GetMechanismList', CK_C_GetMechanismList), - ('C_GetMechanismInfo', CK_C_GetMechanismInfo), - ('C_InitToken', CK_C_InitToken), - ('C_InitPIN', CK_C_InitPIN), - ('C_SetPIN', CK_C_SetPIN), - ('C_OpenSession', CK_C_OpenSession), - ('C_CloseSession', CK_C_CloseSession), - ('C_CloseAllSessions', CK_C_CloseAllSessions), - ('C_GetSessionInfo', CK_C_GetSessionInfo), - ('C_GetOperationState', CK_C_GetOperationState), - ('C_SetOperationState', CK_C_SetOperationState), - ('C_Login', CK_C_Login), - ('C_Logout', CK_C_Logout), - ('C_CreateObject', CK_C_CreateObject), - ('C_CopyObject', CK_C_CopyObject), - ('C_DestroyObject', CK_C_DestroyObject), - ('C_GetObjectSize', CK_C_GetObjectSize), - ('C_GetAttributeValue', CK_C_GetAttributeValue), - ('C_SetAttributeValue', CK_C_SetAttributeValue), - ('C_FindObjectsInit', CK_C_FindObjectsInit), - ('C_FindObjects', CK_C_FindObjects), - ('C_FindObjectsFinal', CK_C_FindObjectsFinal), - ('C_EncryptInit', CK_C_EncryptInit), - ('C_Encrypt', CK_C_Encrypt), - ('C_EncryptUpdate', CK_C_EncryptUpdate), - ('C_EncryptFinal', CK_C_EncryptFinal), - ('C_DecryptInit', CK_C_DecryptInit), - ('C_Decrypt', CK_C_Decrypt), - ('C_DecryptUpdate', CK_C_DecryptUpdate), - ('C_DecryptFinal', CK_C_DecryptFinal), - ('C_DigestInit', CK_C_DigestInit), - ('C_Digest', CK_C_Digest), - ('C_DigestUpdate', CK_C_DigestUpdate), - ('C_DigestKey', CK_C_DigestKey), - ('C_DigestFinal', CK_C_DigestFinal), - ('C_SignInit', CK_C_SignInit), - ('C_Sign', CK_C_Sign), - ('C_SignUpdate', CK_C_SignUpdate), - ('C_SignFinal', CK_C_SignFinal), - ('C_SignRecoverInit', CK_C_SignRecoverInit), - ('C_SignRecover', CK_C_SignRecover), - ('C_VerifyInit', CK_C_VerifyInit), - ('C_Verify', CK_C_Verify), - ('C_VerifyUpdate', CK_C_VerifyUpdate), - ('C_VerifyFinal', CK_C_VerifyFinal), - ('C_VerifyRecoverInit', CK_C_VerifyRecoverInit), - ('C_VerifyRecover', CK_C_VerifyRecover), - ('C_DigestEncryptUpdate', CK_C_DigestEncryptUpdate), - ('C_DecryptDigestUpdate', CK_C_DecryptDigestUpdate), - ('C_SignEncryptUpdate', CK_C_SignEncryptUpdate), - ('C_DecryptVerifyUpdate', CK_C_DecryptVerifyUpdate), - ('C_GenerateKey', CK_C_GenerateKey), - ('C_GenerateKeyPair', CK_C_GenerateKeyPair), - ('C_WrapKey', CK_C_WrapKey), - ('C_UnwrapKey', CK_C_UnwrapKey), - ('C_DeriveKey', CK_C_DeriveKey), - ('C_SeedRandom', CK_C_SeedRandom), - ('C_GenerateRandom', CK_C_GenerateRandom), - ('C_GetFunctionStatus', CK_C_GetFunctionStatus), - ('C_CancelFunction', CK_C_CancelFunction), - ('C_WaitForSlotEvent', CK_C_WaitForSlotEvent), -] -C_Initialize = make_late_binding_function('C_Initialize') -C_Initialize.restype = CK_RV -C_Initialize.argtypes = [CK_VOID_PTR] -C_Finalize = make_late_binding_function('C_Finalize') -C_Finalize.restype = CK_RV -C_Finalize.argtypes = [CK_VOID_PTR] -C_GetInfo = make_late_binding_function('C_GetInfo') -C_GetInfo.restype = CK_RV -C_GetInfo.argtypes = [CK_INFO_PTR] -C_GetFunctionList = make_late_binding_function('C_GetFunctionList') -C_GetFunctionList.restype = CK_RV -C_GetFunctionList.argtypes = [CK_FUNCTION_LIST_PTR_PTR] -C_GetSlotList = make_late_binding_function('C_GetSlotList') -C_GetSlotList.restype = CK_RV -C_GetSlotList.argtypes = [CK_BBOOL, CK_SLOT_ID_PTR, CK_ULONG_PTR] -C_GetSlotInfo = make_late_binding_function('C_GetSlotInfo') -C_GetSlotInfo.restype = CK_RV -C_GetSlotInfo.argtypes = [CK_SLOT_ID, CK_SLOT_INFO_PTR] -C_GetTokenInfo = make_late_binding_function('C_GetTokenInfo') -C_GetTokenInfo.restype = CK_RV -C_GetTokenInfo.argtypes = [CK_SLOT_ID, CK_TOKEN_INFO_PTR] -C_GetMechanismList = make_late_binding_function('C_GetMechanismList') -C_GetMechanismList.restype = CK_RV -C_GetMechanismList.argtypes = [CK_SLOT_ID, CK_MECHANISM_TYPE_PTR, CK_ULONG_PTR] -C_GetMechanismInfo = make_late_binding_function('C_GetMechanismInfo') -C_GetMechanismInfo.restype = CK_RV -C_GetMechanismInfo.argtypes = [CK_SLOT_ID, CK_MECHANISM_TYPE, CK_MECHANISM_INFO_PTR] -C_InitToken = make_late_binding_function('C_InitToken') -C_InitToken.restype = CK_RV -C_InitToken.argtypes = [CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR] -C_InitPIN = make_late_binding_function('C_InitPIN') -C_InitPIN.restype = CK_RV -C_InitPIN.argtypes = [CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG] -C_SetPIN = make_late_binding_function('C_SetPIN') -C_SetPIN.restype = CK_RV -C_SetPIN.argtypes = [CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, CK_ULONG] -C_OpenSession = make_late_binding_function('C_OpenSession') -C_OpenSession.restype = CK_RV -C_OpenSession.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] -C_CloseSession = make_late_binding_function('C_CloseSession') -C_CloseSession.restype = CK_RV -C_CloseSession.argtypes = [CK_SESSION_HANDLE] -C_CloseAllSessions = make_late_binding_function('C_CloseAllSessions') -C_CloseAllSessions.restype = CK_RV -C_CloseAllSessions.argtypes = [CK_SLOT_ID] -C_GetSessionInfo = make_late_binding_function('C_GetSessionInfo') -C_GetSessionInfo.restype = CK_RV -C_GetSessionInfo.argtypes = [CK_SESSION_HANDLE, CK_SESSION_INFO_PTR] -C_GetOperationState = make_late_binding_function('C_GetOperationState') -C_GetOperationState.restype = CK_RV -C_GetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] -C_SetOperationState = make_late_binding_function('C_SetOperationState') -C_SetOperationState.restype = CK_RV -C_SetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE] -C_Login = make_late_binding_function('C_Login') -C_Login.restype = CK_RV -C_Login.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG] -C_Logout = make_late_binding_function('C_Logout') -C_Logout.restype = CK_RV -C_Logout.argtypes = [CK_SESSION_HANDLE] -C_CreateObject = make_late_binding_function('C_CreateObject') -C_CreateObject.restype = CK_RV -C_CreateObject.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] -C_CopyObject = make_late_binding_function('C_CopyObject') -C_CopyObject.restype = CK_RV -C_CopyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] -C_DestroyObject = make_late_binding_function('C_DestroyObject') -C_DestroyObject.restype = CK_RV -C_DestroyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] -C_GetObjectSize = make_late_binding_function('C_GetObjectSize') -C_GetObjectSize.restype = CK_RV -C_GetObjectSize.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR] -C_GetAttributeValue = make_late_binding_function('C_GetAttributeValue') -C_GetAttributeValue.restype = CK_RV -C_GetAttributeValue.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] -C_SetAttributeValue = make_late_binding_function('C_SetAttributeValue') -C_SetAttributeValue.restype = CK_RV -C_SetAttributeValue.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] -C_FindObjectsInit = make_late_binding_function('C_FindObjectsInit') -C_FindObjectsInit.restype = CK_RV -C_FindObjectsInit.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] -C_FindObjects = make_late_binding_function('C_FindObjects') -C_FindObjects.restype = CK_RV -C_FindObjects.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG_PTR] -C_FindObjectsFinal = make_late_binding_function('C_FindObjectsFinal') -C_FindObjectsFinal.restype = CK_RV -C_FindObjectsFinal.argtypes = [CK_SESSION_HANDLE] -C_EncryptInit = make_late_binding_function('C_EncryptInit') -C_EncryptInit.restype = CK_RV -C_EncryptInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] -C_Encrypt = make_late_binding_function('C_Encrypt') -C_Encrypt.restype = CK_RV -C_Encrypt.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_EncryptUpdate = make_late_binding_function('C_EncryptUpdate') -C_EncryptUpdate.restype = CK_RV -C_EncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_EncryptFinal = make_late_binding_function('C_EncryptFinal') -C_EncryptFinal.restype = CK_RV -C_EncryptFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] -C_DecryptInit = make_late_binding_function('C_DecryptInit') -C_DecryptInit.restype = CK_RV -C_DecryptInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] -C_Decrypt = make_late_binding_function('C_Decrypt') -C_Decrypt.restype = CK_RV -C_Decrypt.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_DecryptUpdate = make_late_binding_function('C_DecryptUpdate') -C_DecryptUpdate.restype = CK_RV -C_DecryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_DecryptFinal = make_late_binding_function('C_DecryptFinal') -C_DecryptFinal.restype = CK_RV -C_DecryptFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] -C_DigestInit = make_late_binding_function('C_DigestInit') -C_DigestInit.restype = CK_RV -C_DigestInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] -C_Digest = make_late_binding_function('C_Digest') -C_Digest.restype = CK_RV -C_Digest.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_DigestUpdate = make_late_binding_function('C_DigestUpdate') -C_DigestUpdate.restype = CK_RV -C_DigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] -C_DigestKey = make_late_binding_function('C_DigestKey') -C_DigestKey.restype = CK_RV -C_DigestKey.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] -C_DigestFinal = make_late_binding_function('C_DigestFinal') -C_DigestFinal.restype = CK_RV -C_DigestFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] -C_SignInit = make_late_binding_function('C_SignInit') -C_SignInit.restype = CK_RV -C_SignInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] -C_Sign = make_late_binding_function('C_Sign') -C_Sign.restype = CK_RV -C_Sign.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_SignUpdate = make_late_binding_function('C_SignUpdate') -C_SignUpdate.restype = CK_RV -C_SignUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] -C_SignFinal = make_late_binding_function('C_SignFinal') -C_SignFinal.restype = CK_RV -C_SignFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] -C_SignRecoverInit = make_late_binding_function('C_SignRecoverInit') -C_SignRecoverInit.restype = CK_RV -C_SignRecoverInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] -C_SignRecover = make_late_binding_function('C_SignRecover') -C_SignRecover.restype = CK_RV -C_SignRecover.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_VerifyInit = make_late_binding_function('C_VerifyInit') -C_VerifyInit.restype = CK_RV -C_VerifyInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] -C_Verify = make_late_binding_function('C_Verify') -C_Verify.restype = CK_RV -C_Verify.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] -C_VerifyUpdate = make_late_binding_function('C_VerifyUpdate') -C_VerifyUpdate.restype = CK_RV -C_VerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] -C_VerifyFinal = make_late_binding_function('C_VerifyFinal') -C_VerifyFinal.restype = CK_RV -C_VerifyFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] -C_VerifyRecoverInit = make_late_binding_function('C_VerifyRecoverInit') -C_VerifyRecoverInit.restype = CK_RV -C_VerifyRecoverInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] -C_VerifyRecover = make_late_binding_function('C_VerifyRecover') -C_VerifyRecover.restype = CK_RV -C_VerifyRecover.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_DigestEncryptUpdate = make_late_binding_function('C_DigestEncryptUpdate') -C_DigestEncryptUpdate.restype = CK_RV -C_DigestEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_DecryptDigestUpdate = make_late_binding_function('C_DecryptDigestUpdate') -C_DecryptDigestUpdate.restype = CK_RV -C_DecryptDigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_SignEncryptUpdate = make_late_binding_function('C_SignEncryptUpdate') -C_SignEncryptUpdate.restype = CK_RV -C_SignEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_DecryptVerifyUpdate = make_late_binding_function('C_DecryptVerifyUpdate') -C_DecryptVerifyUpdate.restype = CK_RV -C_DecryptVerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] -C_GenerateKey = make_late_binding_function('C_GenerateKey') -C_GenerateKey.restype = CK_RV -C_GenerateKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] -C_GenerateKeyPair = make_late_binding_function('C_GenerateKeyPair') -C_GenerateKeyPair.restype = CK_RV -C_GenerateKeyPair.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] -C_WrapKey = make_late_binding_function('C_WrapKey') -C_WrapKey.restype = CK_RV -C_WrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] -C_UnwrapKey = make_late_binding_function('C_UnwrapKey') -C_UnwrapKey.restype = CK_RV -C_UnwrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] -C_DeriveKey = make_late_binding_function('C_DeriveKey') -C_DeriveKey.restype = CK_RV -C_DeriveKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] -C_SeedRandom = make_late_binding_function('C_SeedRandom') -C_SeedRandom.restype = CK_RV -C_SeedRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] -C_GenerateRandom = make_late_binding_function('C_GenerateRandom') -C_GenerateRandom.restype = CK_RV -C_GenerateRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] -C_GetFunctionStatus = make_late_binding_function('C_GetFunctionStatus') -C_GetFunctionStatus.restype = CK_RV -C_GetFunctionStatus.argtypes = [CK_SESSION_HANDLE] -C_CancelFunction = make_late_binding_function('C_CancelFunction') -C_CancelFunction.restype = CK_RV -C_CancelFunction.argtypes = [CK_SESSION_HANDLE] -C_WaitForSlotEvent = make_late_binding_function('C_WaitForSlotEvent') -C_WaitForSlotEvent.restype = CK_RV -C_WaitForSlotEvent.argtypes = [CK_FLAGS, CK_SLOT_ID_PTR, CK_VOID_PTR] -CK_CHAR = CK_BYTE -CK_LONG = c_long -CK_CHAR_PTR = POINTER(CK_CHAR) -CK_VOID_PTR_PTR = POINTER(CK_VOID_PTR) -CK_VERSION_PTR = POINTER(CK_VERSION) -CK_INFO._fields_ = [ - ('cryptokiVersion', CK_VERSION), - ('manufacturerID', CK_UTF8CHAR * 32), - ('flags', CK_FLAGS), - ('libraryDescription', CK_UTF8CHAR * 32), - ('libraryVersion', CK_VERSION), -] -CK_SLOT_INFO._fields_ = [ - ('slotDescription', CK_UTF8CHAR * 64), - ('manufacturerID', CK_UTF8CHAR * 32), - ('flags', CK_FLAGS), - ('hardwareVersion', CK_VERSION), - ('firmwareVersion', CK_VERSION), -] -CK_TOKEN_INFO._fields_ = [ - ('label', CK_UTF8CHAR * 32), - ('manufacturerID', CK_UTF8CHAR * 32), - ('model', CK_UTF8CHAR * 16), - ('serialNumber', CK_CHAR * 16), - ('flags', CK_FLAGS), - ('usMaxSessionCount', CK_ULONG), - ('usSessionCount', CK_ULONG), - ('usMaxRwSessionCount', CK_ULONG), - ('usRwSessionCount', CK_ULONG), - ('usMaxPinLen', CK_ULONG), - ('usMinPinLen', 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_STATE = CK_ULONG -CK_SESSION_INFO._fields_ = [ - ('slotID', CK_SLOT_ID), - ('state', CK_STATE), - ('flags', CK_FLAGS), - ('usDeviceError', CK_ULONG), -] -CK_OBJECT_CLASS = CK_ULONG -CK_OBJECT_CLASS_PTR = POINTER(CK_OBJECT_CLASS) -CK_HW_FEATURE_TYPE = CK_ULONG -CK_KEY_TYPE = CK_ULONG -CK_CERTIFICATE_TYPE = CK_ULONG -CK_ATTRIBUTE_TYPE = CK_ULONG -CK_ATTRIBUTE._fields_ = [ - ('type', CK_ATTRIBUTE_TYPE), - ('pValue', CK_VOID_PTR), - ('usValueLen', CK_ULONG), -] -class CK_DATE(Structure): - pass -CK_DATE._fields_ = [ - ('year', CK_CHAR * 4), - ('month', CK_CHAR * 2), - ('day', CK_CHAR * 2), -] -CK_MECHANISM._fields_ = [ - ('mechanism', CK_MECHANISM_TYPE), - ('pParameter', CK_VOID_PTR), - ('usParameterLen', CK_ULONG), -] -CK_MECHANISM_INFO._fields_ = [ - ('ulMinKeySize', CK_ULONG), - ('ulMaxKeySize', CK_ULONG), - ('flags', CK_FLAGS), -] -CK_CREATEMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR_PTR) -CK_DESTROYMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) -CK_LOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) -CK_UNLOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) -class CK_C_INITIALIZE_ARGS(Structure): - pass -CK_C_INITIALIZE_ARGS._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) -CK_RSA_PKCS_MGF_TYPE = CK_ULONG -CK_RSA_PKCS_MGF_TYPE_PTR = POINTER(CK_RSA_PKCS_MGF_TYPE) -CK_RSA_PKCS_OAEP_SOURCE_TYPE = CK_ULONG -CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR = POINTER(CK_RSA_PKCS_OAEP_SOURCE_TYPE) -class CK_RSA_PKCS_OAEP_PARAMS(Structure): - pass -CK_RSA_PKCS_OAEP_PARAMS._fields_ = [ - ('hashAlg', CK_MECHANISM_TYPE), - ('mgf', CK_RSA_PKCS_MGF_TYPE), - ('source', CK_RSA_PKCS_OAEP_SOURCE_TYPE), - ('pSourceData', CK_VOID_PTR), - ('ulSourceDataLen', CK_ULONG), -] -CK_RSA_PKCS_OAEP_PARAMS_PTR = POINTER(CK_RSA_PKCS_OAEP_PARAMS) -class CK_RSA_PKCS_PSS_PARAMS(Structure): - pass -CK_RSA_PKCS_PSS_PARAMS._fields_ = [ - ('hashAlg', CK_MECHANISM_TYPE), - ('mgf', CK_RSA_PKCS_MGF_TYPE), - ('usSaltLen', CK_ULONG), -] -CK_RSA_PKCS_PSS_PARAMS_PTR = POINTER(CK_RSA_PKCS_PSS_PARAMS) -CK_EC_KDF_TYPE = CK_ULONG -class CK_ECDH1_DERIVE_PARAMS(Structure): - pass -CK_ECDH1_DERIVE_PARAMS._fields_ = [ - ('kdf', CK_EC_KDF_TYPE), - ('ulSharedDataLen', CK_ULONG), - ('pSharedData', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), -] -CK_ECDH1_DERIVE_PARAMS_PTR = POINTER(CK_ECDH1_DERIVE_PARAMS) -class CK_ECDH2_DERIVE_PARAMS(Structure): - pass -CK_ECDH2_DERIVE_PARAMS._fields_ = [ - ('kdf', CK_EC_KDF_TYPE), - ('ulSharedDataLen', CK_ULONG), - ('pSharedData', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), - ('ulPrivateDataLen', CK_ULONG), - ('hPrivateData', CK_OBJECT_HANDLE), - ('ulPublicDataLen2', CK_ULONG), - ('pPublicData2', CK_BYTE_PTR), -] -CK_ECDH2_DERIVE_PARAMS_PTR = POINTER(CK_ECDH2_DERIVE_PARAMS) -class CK_ECMQV_DERIVE_PARAMS(Structure): - pass -CK_ECMQV_DERIVE_PARAMS._fields_ = [ - ('kdf', CK_EC_KDF_TYPE), - ('ulSharedDataLen', CK_ULONG), - ('pSharedData', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), - ('ulPrivateDataLen', CK_ULONG), - ('hPrivateData', CK_OBJECT_HANDLE), - ('ulPublicDataLen2', CK_ULONG), - ('pPublicData2', CK_BYTE_PTR), - ('publicKey', CK_OBJECT_HANDLE), -] -CK_ECMQV_DERIVE_PARAMS_PTR = POINTER(CK_ECMQV_DERIVE_PARAMS) -CK_X9_42_DH_KDF_TYPE = CK_ULONG -CK_X9_42_DH_KDF_TYPE_PTR = POINTER(CK_X9_42_DH_KDF_TYPE) -class CK_X9_42_DH1_DERIVE_PARAMS(Structure): - pass -CK_X9_42_DH1_DERIVE_PARAMS._fields_ = [ - ('kdf', CK_X9_42_DH_KDF_TYPE), - ('ulOtherInfoLen', CK_ULONG), - ('pOtherInfo', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), -] -CK_X9_42_DH1_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH1_DERIVE_PARAMS) -class CK_X9_42_DH2_DERIVE_PARAMS(Structure): - pass -CK_X9_42_DH2_DERIVE_PARAMS._fields_ = [ - ('kdf', CK_X9_42_DH_KDF_TYPE), - ('ulOtherInfoLen', CK_ULONG), - ('pOtherInfo', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), - ('ulPrivateDataLen', CK_ULONG), - ('hPrivateData', CK_OBJECT_HANDLE), - ('ulPublicDataLen2', CK_ULONG), - ('pPublicData2', CK_BYTE_PTR), -] -CK_X9_42_DH2_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH2_DERIVE_PARAMS) -class CK_X9_42_MQV_DERIVE_PARAMS(Structure): - pass -CK_X9_42_MQV_DERIVE_PARAMS._fields_ = [ - ('kdf', CK_X9_42_DH_KDF_TYPE), - ('ulOtherInfoLen', CK_ULONG), - ('pOtherInfo', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), - ('ulPrivateDataLen', CK_ULONG), - ('hPrivateData', CK_OBJECT_HANDLE), - ('ulPublicDataLen2', CK_ULONG), - ('pPublicData2', CK_BYTE_PTR), - ('publicKey', CK_OBJECT_HANDLE), -] -CK_X9_42_MQV_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_MQV_DERIVE_PARAMS) -class CK_KEA_DERIVE_PARAMS(Structure): - pass -CK_KEA_DERIVE_PARAMS._fields_ = [ - ('isSender', CK_BBOOL), - ('ulRandomLen', CK_ULONG), - ('pRandomA', CK_BYTE_PTR), - ('pRandomB', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), -] -CK_KEA_DERIVE_PARAMS_PTR = POINTER(CK_KEA_DERIVE_PARAMS) -CK_RC2_PARAMS = CK_ULONG -CK_RC2_PARAMS_PTR = POINTER(CK_RC2_PARAMS) -class CK_RC2_CBC_PARAMS(Structure): - pass -CK_RC2_CBC_PARAMS._fields_ = [ - ('usEffectiveBits', CK_ULONG), - ('iv', CK_BYTE * 8), -] -CK_RC2_CBC_PARAMS_PTR = POINTER(CK_RC2_CBC_PARAMS) -class CK_RC2_MAC_GENERAL_PARAMS(Structure): - pass -CK_RC2_MAC_GENERAL_PARAMS._fields_ = [ - ('usEffectiveBits', CK_ULONG), - ('ulMacLength', CK_ULONG), -] -CK_RC2_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC2_MAC_GENERAL_PARAMS) -class CK_RC5_PARAMS(Structure): - pass -CK_RC5_PARAMS._fields_ = [ - ('ulWordsize', CK_ULONG), - ('ulRounds', CK_ULONG), -] -CK_RC5_PARAMS_PTR = POINTER(CK_RC5_PARAMS) -class CK_RC5_CBC_PARAMS(Structure): - pass -CK_RC5_CBC_PARAMS._fields_ = [ - ('ulWordsize', CK_ULONG), - ('ulRounds', CK_ULONG), - ('pIv', CK_BYTE_PTR), - ('ulIvLen', CK_ULONG), -] -CK_RC5_CBC_PARAMS_PTR = POINTER(CK_RC5_CBC_PARAMS) -class CK_RC5_MAC_GENERAL_PARAMS(Structure): - pass -CK_RC5_MAC_GENERAL_PARAMS._fields_ = [ - ('ulWordsize', CK_ULONG), - ('ulRounds', CK_ULONG), - ('ulMacLength', CK_ULONG), -] -CK_RC5_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC5_MAC_GENERAL_PARAMS) -CK_MAC_GENERAL_PARAMS = CK_ULONG -CK_MAC_GENERAL_PARAMS_PTR = POINTER(CK_MAC_GENERAL_PARAMS) -class CK_DES_CBC_ENCRYPT_DATA_PARAMS(Structure): - pass -CK_DES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ - ('iv', CK_BYTE * 8), - ('pData', CK_BYTE_PTR), - ('length', CK_ULONG), -] -CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_DES_CBC_ENCRYPT_DATA_PARAMS) -class CK_AES_CBC_ENCRYPT_DATA_PARAMS(Structure): - pass -CK_AES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ - ('iv', CK_BYTE * 16), - ('pData', CK_BYTE_PTR), - ('length', CK_ULONG), -] -CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_AES_CBC_ENCRYPT_DATA_PARAMS) -class CK_SKIPJACK_PRIVATE_WRAP_PARAMS(Structure): - pass -CK_SKIPJACK_PRIVATE_WRAP_PARAMS._fields_ = [ - ('usPasswordLen', CK_ULONG), - ('pPassword', CK_BYTE_PTR), - ('ulPublicDataLen', CK_ULONG), - ('pPublicData', CK_BYTE_PTR), - ('ulPAndGLen', CK_ULONG), - ('ulQLen', CK_ULONG), - ('ulRandomLen', CK_ULONG), - ('pRandomA', CK_BYTE_PTR), - ('pPrimeP', CK_BYTE_PTR), - ('pBaseG', CK_BYTE_PTR), - ('pSubprimeQ', CK_BYTE_PTR), -] -CK_SKIPJACK_PRIVATE_WRAP_PTR = POINTER(CK_SKIPJACK_PRIVATE_WRAP_PARAMS) -class CK_SKIPJACK_RELAYX_PARAMS(Structure): - pass -CK_SKIPJACK_RELAYX_PARAMS._fields_ = [ - ('ulOldWrappedXLen', CK_ULONG), - ('pOldWrappedX', CK_BYTE_PTR), - ('ulOldPasswordLen', CK_ULONG), - ('pOldPassword', CK_BYTE_PTR), - ('ulOldPublicDataLen', CK_ULONG), - ('pOldPublicData', CK_BYTE_PTR), - ('ulOldRandomLen', CK_ULONG), - ('pOldRandomA', CK_BYTE_PTR), - ('ulNewPasswordLen', CK_ULONG), - ('pNewPassword', CK_BYTE_PTR), - ('ulNewPublicDataLen', CK_ULONG), - ('pNewPublicData', CK_BYTE_PTR), - ('ulNewRandomLen', CK_ULONG), - ('pNewRandomA', CK_BYTE_PTR), -] -CK_SKIPJACK_RELAYX_PARAMS_PTR = POINTER(CK_SKIPJACK_RELAYX_PARAMS) -class CK_PBE_PARAMS(Structure): - pass -CK_PBE_PARAMS._fields_ = [ - ('pInitVector', CK_BYTE_PTR), - ('pPassword', CK_UTF8CHAR_PTR), - ('usPasswordLen', CK_ULONG), - ('pSalt', CK_BYTE_PTR), - ('usSaltLen', CK_ULONG), - ('usIteration', CK_ULONG), -] -CK_PBE_PARAMS_PTR = POINTER(CK_PBE_PARAMS) -class CK_KEY_WRAP_SET_OAEP_PARAMS(Structure): - pass -CK_KEY_WRAP_SET_OAEP_PARAMS._fields_ = [ - ('bBC', CK_BYTE), - ('pX', CK_BYTE_PTR), - ('ulXLen', CK_ULONG), -] -CK_KEY_WRAP_SET_OAEP_PARAMS_PTR = POINTER(CK_KEY_WRAP_SET_OAEP_PARAMS) -class CK_SSL3_RANDOM_DATA(Structure): - pass -CK_SSL3_RANDOM_DATA._fields_ = [ - ('pClientRandom', CK_BYTE_PTR), - ('ulClientRandomLen', CK_ULONG), - ('pServerRandom', CK_BYTE_PTR), - ('ulServerRandomLen', CK_ULONG), -] -class CK_SSL3_MASTER_KEY_DERIVE_PARAMS(Structure): - pass -CK_SSL3_MASTER_KEY_DERIVE_PARAMS._fields_ = [ - ('RandomInfo', CK_SSL3_RANDOM_DATA), - ('pVersion', CK_VERSION_PTR), -] -CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_SSL3_MASTER_KEY_DERIVE_PARAMS) -class CK_SSL3_KEY_MAT_OUT(Structure): - pass -CK_SSL3_KEY_MAT_OUT._fields_ = [ - ('hClientMacSecret', CK_OBJECT_HANDLE), - ('hServerMacSecret', CK_OBJECT_HANDLE), - ('hClientKey', CK_OBJECT_HANDLE), - ('hServerKey', CK_OBJECT_HANDLE), - ('pIVClient', CK_BYTE_PTR), - ('pIVServer', CK_BYTE_PTR), -] -CK_SSL3_KEY_MAT_OUT_PTR = POINTER(CK_SSL3_KEY_MAT_OUT) -class CK_SSL3_KEY_MAT_PARAMS(Structure): - pass -CK_SSL3_KEY_MAT_PARAMS._fields_ = [ - ('ulMacSizeInBits', CK_ULONG), - ('ulKeySizeInBits', CK_ULONG), - ('ulIVSizeInBits', CK_ULONG), - ('bIsExport', CK_BBOOL), - ('RandomInfo', CK_SSL3_RANDOM_DATA), - ('pReturnedKeyMaterial', CK_SSL3_KEY_MAT_OUT_PTR), -] -CK_SSL3_KEY_MAT_PARAMS_PTR = POINTER(CK_SSL3_KEY_MAT_PARAMS) -class CK_TLS_PRF_PARAMS(Structure): - pass -CK_TLS_PRF_PARAMS._fields_ = [ - ('pSeed', CK_BYTE_PTR), - ('ulSeedLen', CK_ULONG), - ('pLabel', CK_BYTE_PTR), - ('ulLabelLen', CK_ULONG), - ('pOutput', CK_BYTE_PTR), - ('pulOutputLen', CK_ULONG_PTR), -] -CK_TLS_PRF_PARAMS_PTR = POINTER(CK_TLS_PRF_PARAMS) -class CK_WTLS_RANDOM_DATA(Structure): - pass -CK_WTLS_RANDOM_DATA._fields_ = [ - ('pClientRandom', CK_BYTE_PTR), - ('ulClientRandomLen', CK_ULONG), - ('pServerRandom', CK_BYTE_PTR), - ('ulServerRandomLen', CK_ULONG), -] -CK_WTLS_RANDOM_DATA_PTR = POINTER(CK_WTLS_RANDOM_DATA) -class CK_WTLS_MASTER_KEY_DERIVE_PARAMS(Structure): - pass -CK_WTLS_MASTER_KEY_DERIVE_PARAMS._fields_ = [ - ('DigestMechanism', CK_MECHANISM_TYPE), - ('RandomInfo', CK_WTLS_RANDOM_DATA), - ('pVersion', CK_BYTE_PTR), -] -CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_WTLS_MASTER_KEY_DERIVE_PARAMS) -class CK_WTLS_PRF_PARAMS(Structure): - pass -CK_WTLS_PRF_PARAMS._fields_ = [ - ('DigestMechanism', CK_MECHANISM_TYPE), - ('pSeed', CK_BYTE_PTR), - ('ulSeedLen', CK_ULONG), - ('pLabel', CK_BYTE_PTR), - ('ulLabelLen', CK_ULONG), - ('pOutput', CK_BYTE_PTR), - ('pulOutputLen', CK_ULONG_PTR), -] -CK_WTLS_PRF_PARAMS_PTR = POINTER(CK_WTLS_PRF_PARAMS) -class CK_WTLS_KEY_MAT_OUT(Structure): - pass -CK_WTLS_KEY_MAT_OUT._fields_ = [ - ('hMacSecret', CK_OBJECT_HANDLE), - ('hKey', CK_OBJECT_HANDLE), - ('pIV', CK_BYTE_PTR), -] -CK_WTLS_KEY_MAT_OUT_PTR = POINTER(CK_WTLS_KEY_MAT_OUT) -class CK_WTLS_KEY_MAT_PARAMS(Structure): - pass -CK_WTLS_KEY_MAT_PARAMS._fields_ = [ - ('DigestMechanism', CK_MECHANISM_TYPE), - ('ulMacSizeInBits', CK_ULONG), - ('ulKeySizeInBits', CK_ULONG), - ('ulIVSizeInBits', CK_ULONG), - ('ulSequenceNumber', CK_ULONG), - ('bIsExport', CK_BBOOL), - ('RandomInfo', CK_WTLS_RANDOM_DATA), - ('pReturnedKeyMaterial', CK_WTLS_KEY_MAT_OUT_PTR), -] -CK_WTLS_KEY_MAT_PARAMS_PTR = POINTER(CK_WTLS_KEY_MAT_PARAMS) -class CK_CMS_SIG_PARAMS(Structure): - pass -CK_CMS_SIG_PARAMS._fields_ = [ - ('certificateHandle', CK_OBJECT_HANDLE), - ('pSigningMechanism', CK_MECHANISM_PTR), - ('pDigestMechanism', CK_MECHANISM_PTR), - ('pContentType', CK_UTF8CHAR_PTR), - ('pRequestedAttributes', CK_BYTE_PTR), - ('ulRequestedAttributesLen', CK_ULONG), - ('pRequiredAttributes', CK_BYTE_PTR), - ('ulRequiredAttributesLen', CK_ULONG), -] -CK_CMS_SIG_PARAMS_PTR = POINTER(CK_CMS_SIG_PARAMS) -class CK_KEY_DERIVATION_STRING_DATA(Structure): - pass -CK_KEY_DERIVATION_STRING_DATA._fields_ = [ - ('pData', CK_BYTE_PTR), - ('ulLen', CK_ULONG), -] -CK_KEY_DERIVATION_STRING_DATA_PTR = POINTER(CK_KEY_DERIVATION_STRING_DATA) -CK_EXTRACT_PARAMS = CK_ULONG -CK_EXTRACT_PARAMS_PTR = POINTER(CK_EXTRACT_PARAMS) -CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE = CK_ULONG -CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR = POINTER(CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE) -CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE = CK_ULONG -CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR = POINTER(CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE) -class CK_PKCS5_PBKD2_PARAMS(Structure): - pass -CK_PKCS5_PBKD2_PARAMS._fields_ = [ - ('saltSource', CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE), - ('pSaltSourceData', CK_VOID_PTR), - ('ulSaltSourceDataLen', CK_ULONG), - ('iterations', CK_ULONG), - ('prf', CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE), - ('pPrfData', CK_VOID_PTR), - ('ulPrfDataLen', CK_ULONG), - ('pPassword', CK_UTF8CHAR_PTR), - ('usPasswordLen', CK_ULONG), -] -CK_PKCS5_PBKD2_PARAMS_PTR = POINTER(CK_PKCS5_PBKD2_PARAMS) -CK_OTP_PARAM_TYPE = CK_ULONG -CK_PARAM_TYPE = CK_OTP_PARAM_TYPE -class CK_OTP_PARAM(Structure): - pass -CK_OTP_PARAM._fields_ = [ - ('type', CK_OTP_PARAM_TYPE), - ('pValue', CK_VOID_PTR), - ('usValueLen', CK_ULONG), -] -CK_OTP_PARAM_PTR = POINTER(CK_OTP_PARAM) -class CK_OTP_PARAMS(Structure): - pass -CK_OTP_PARAMS._fields_ = [ - ('pParams', CK_OTP_PARAM_PTR), - ('ulCount', CK_ULONG), -] -CK_OTP_PARAMS_PTR = POINTER(CK_OTP_PARAMS) -class CK_OTP_SIGNATURE_INFO(Structure): - pass -CK_OTP_SIGNATURE_INFO._fields_ = [ - ('pParams', CK_OTP_PARAM_PTR), - ('ulCount', CK_ULONG), -] -CK_OTP_SIGNATURE_INFO_PTR = POINTER(CK_OTP_SIGNATURE_INFO) -class CK_KIP_PARAMS(Structure): - pass -CK_KIP_PARAMS._fields_ = [ - ('pMechanism', CK_MECHANISM_PTR), - ('hKey', CK_OBJECT_HANDLE), - ('pSeed', CK_BYTE_PTR), - ('ulSeedLen', CK_ULONG), -] -CK_KIP_PARAMS_PTR = POINTER(CK_KIP_PARAMS) -class CK_AES_CTR_PARAMS(Structure): - pass -CK_AES_CTR_PARAMS._fields_ = [ - ('ulCounterBits', CK_ULONG), - ('cb', CK_BYTE * 16), -] -CK_AES_CTR_PARAMS_PTR = POINTER(CK_AES_CTR_PARAMS) -class CK_CAMELLIA_CTR_PARAMS(Structure): - pass -CK_CAMELLIA_CTR_PARAMS._fields_ = [ - ('ulCounterBits', CK_ULONG), - ('cb', CK_BYTE * 16), -] -CK_CAMELLIA_CTR_PARAMS_PTR = POINTER(CK_CAMELLIA_CTR_PARAMS) -class CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS(Structure): - pass -CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ - ('iv', CK_BYTE * 16), - ('pData', CK_BYTE_PTR), - ('length', CK_ULONG), -] -CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS) -class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): - pass -CK_ARIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ - ('iv', CK_BYTE * 16), - ('pData', CK_BYTE_PTR), - ('length', CK_ULONG), -] -CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_ARIA_CBC_ENCRYPT_DATA_PARAMS) -CK_USHORT = c_ulong -CK_USHORT_PTR = POINTER(CK_USHORT) -class CK_AES_GCM_PARAMS(Structure): - pass -CK_AES_GCM_PARAMS._fields_ = [ - ('pIv', CK_BYTE_PTR), - ('ulIvLen', CK_ULONG), - ('ulIvBits', CK_ULONG), - ('pAAD', CK_BYTE_PTR), - ('ulAADLen', CK_ULONG), - ('ulTagBits', CK_ULONG), -] -CK_AES_GCM_PARAMS_PTR = CK_AES_GCM_PARAMS -class CK_XOR_BASE_DATA_KDF_PARAMS(Structure): - pass -CK_XOR_BASE_DATA_KDF_PARAMS._fields_ = [ - ('kdf', CK_EC_KDF_TYPE), - ('ulSharedDataLen', CK_ULONG), - ('pSharedData', CK_BYTE_PTR), -] -CK_XOR_BASE_DATA_KDF_PARAMS_PTR = POINTER(CK_XOR_BASE_DATA_KDF_PARAMS) -CK_EC_DH_PRIMITIVE = CK_ULONG -CK_EC_ENC_SCHEME = CK_ULONG -CK_EC_MAC_SCHEME = CK_ULONG -class CK_ECIES_PARAMS(Structure): - pass -CK_ECIES_PARAMS._fields_ = [ - ('dhPrimitive', CK_EC_DH_PRIMITIVE), - ('kdf', CK_EC_KDF_TYPE), - ('ulSharedDataLen1', CK_ULONG), - ('pSharedData1', CK_BYTE_PTR), - ('encScheme', CK_EC_ENC_SCHEME), - ('ulEncKeyLenInBits', CK_ULONG), - ('macScheme', CK_EC_MAC_SCHEME), - ('ulMacKeyLenInBits', CK_ULONG), - ('ulMacLenInBits', CK_ULONG), - ('ulSharedDataLen2', CK_ULONG), - ('pSharedData2', CK_BYTE_PTR), -] -CK_ECIES_PARAMS_PTR = POINTER(CK_ECIES_PARAMS) -CK_KDF_PRF_TYPE = CK_ULONG -CK_KDF_PRF_ENCODING_SCHEME = CK_ULONG -class CK_KDF_PRF_PARAMS(Structure): - pass -CK_KDF_PRF_PARAMS._fields_ = [ - ('prfType', CK_KDF_PRF_TYPE), - ('pLabel', CK_BYTE_PTR), - ('ulLabelLen', CK_ULONG), - ('pContext', CK_BYTE_PTR), - ('ulContextLen', CK_ULONG), - ('ulCounter', CK_ULONG), - ('ulEncodingScheme', CK_KDF_PRF_ENCODING_SCHEME), -] -CK_PRF_KDF_PARAMS = CK_KDF_PRF_PARAMS -CK_KDF_PRF_PARAMS_PTR = POINTER(CK_PRF_KDF_PARAMS) -CK_SEED_CTR_PARAMS = CK_AES_CTR_PARAMS -CK_SEED_CTR_PARAMS_PTR = POINTER(CK_SEED_CTR_PARAMS) -CK_ARIA_CTR_PARAMS = CK_AES_CTR_PARAMS -CK_ARIA_CTR_PARAMS_PTR = POINTER(CK_ARIA_CTR_PARAMS) -class CK_DES_CTR_PARAMS(Structure): - pass -CK_DES_CTR_PARAMS._fields_ = [ - ('ulCounterBits', CK_ULONG), - ('cb', CK_BYTE * 8), -] -CK_DES_CTR_PARAMS_PTR = POINTER(CK_DES_CTR_PARAMS) -CK_AES_GMAC_PARAMS = CK_AES_GCM_PARAMS -CK_AES_GMAC_PARAMS_PTR = POINTER(CK_AES_GMAC_PARAMS) -class CA_MOFN_GENERATION(Structure): - pass -CA_MOFN_GENERATION._fields_ = [ - ('ulWeight', CK_ULONG), - ('pVector', CK_BYTE_PTR), - ('ulVectorLen', CK_ULONG), -] -CA_MOFN_GENERATION_PTR = POINTER(CA_MOFN_GENERATION) -class CA_MOFN_ACTIVATION(Structure): - pass -CA_MOFN_ACTIVATION._fields_ = [ - ('pVector', CK_BYTE_PTR), - ('ulVectorLen', CK_ULONG), -] -CA_MOFN_ACTIVATION_PTR = POINTER(CA_MOFN_ACTIVATION) -class CA_M_OF_N_STATUS(Structure): - pass -CA_M_OF_N_STATUS._fields_ = [ - ('ulID', CK_ULONG), - ('ulM', CK_ULONG), - ('ulN', CK_ULONG), - ('ulSecretSize', CK_ULONG), - ('ulFlag', CK_ULONG), -] -CA_MOFN_STATUS = CA_M_OF_N_STATUS -CA_MOFN_STATUS_PTR = POINTER(CA_MOFN_STATUS) -CKCA_MODULE_ID = CK_ULONG -CKCA_MODULE_ID_PTR = POINTER(CKCA_MODULE_ID) -class CKCA_MODULE_INFO(Structure): - pass -CKCA_MODULE_INFO._fields_ = [ - ('ulModuleSize', CK_ULONG), - ('developerName', CK_CHAR * 32), - ('moduleDescription', CK_CHAR * 32), - ('moduleVersion', CK_VERSION), -] -CKCA_MODULE_INFO_PTR = POINTER(CKCA_MODULE_INFO) -class CK_HA_MEMBER(Structure): - pass -CK_HA_MEMBER._fields_ = [ - ('memberSerial', CK_ULONG), - ('memberStatus', CK_RV), -] -class CK_HA_STATUS(Structure): - pass -CK_HA_STATUS._fields_ = [ - ('groupSerial', CK_ULONG), - ('memberList', CK_HA_MEMBER * 32), - ('listSize', CK_ULONG), -] -CK_HA_MEMBER_PTR = POINTER(CK_HA_MEMBER) -CK_HA_STATE_PTR = POINTER(CK_HA_STATUS) -CKA_SIM_AUTH_FORM = CK_ULONG -class CK_AES_CBC_PAD_EXTRACT_PARAMS(Structure): - pass -CK_AES_CBC_PAD_EXTRACT_PARAMS._fields_ = [ - ('ulType', CK_ULONG), - ('ulHandle', CK_ULONG), - ('ulDeleteAfterExtract', CK_ULONG), - ('pBuffer', CK_BYTE_PTR), - ('pulBufferLen', CK_ULONG_PTR), - ('ulStorage', CK_ULONG), - ('pedId', CK_ULONG), - ('pbFileName', CK_BYTE_PTR), -] -CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_EXTRACT_PARAMS) -class CK_AES_CBC_PAD_INSERT_PARAMS(Structure): - pass -CK_AES_CBC_PAD_INSERT_PARAMS._fields_ = [ - ('ulStorageType', CK_ULONG), - ('ulContainerState', CK_ULONG), - ('pBuffer', CK_BYTE_PTR), - ('ulBufferLen', CK_ULONG), - ('pulType', CK_ULONG_PTR), - ('pulHandle', CK_ULONG_PTR), - ('ulStorage', CK_ULONG), - ('pedId', CK_ULONG), - ('pbFileName', CK_BYTE_PTR), -] -CK_AES_CBC_PAD_INSERT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_INSERT_PARAMS) -class CK_CLUSTER_STATE(Structure): - pass -CK_CLUSTER_STATE._fields_ = [ - ('bMembers', CK_BYTE * 32 * 8), - ('ulMemberStatus', CK_ULONG * 8), -] -CK_CLUSTER_STATE_PTR = POINTER(CK_CLUSTER_STATE) -class CK_LKM_TOKEN_ID_S(Structure): - pass -CK_LKM_TOKEN_ID_S._fields_ = [ - ('id', CK_BYTE * 20), -] -CK_LKM_TOKEN_ID = CK_LKM_TOKEN_ID_S -CK_LKM_TOKEN_ID_PTR = POINTER(CK_LKM_TOKEN_ID) -class CK_SFNT_CA_FUNCTION_LIST(Structure): - pass -CK_SFNT_CA_FUNCTION_LIST_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST) -CK_SFNT_CA_FUNCTION_LIST_PTR_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST_PTR) -CK_CA_GetFunctionList = CFUNCTYPE(CK_RV, CK_SFNT_CA_FUNCTION_LIST_PTR_PTR) -CK_CA_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, POINTER(CK_ULONG), CK_SLOT_ID_PTR, CK_VOID_PTR) -CK_CA_InitIndirectToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_SESSION_HANDLE) -CK_CA_InitIndirectPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_SESSION_HANDLE) -CK_CA_ResetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG) -CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) -CK_CA_Deactivate = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE) -CK_CA_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) -CK_CA_IndirectLogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE) -CK_CA_InitializeRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_DeleteRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_GetRemotePEDVectorStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_ConfigureRemotePED = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_ULONG_PTR) -CK_CA_DismantleRemotePED = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) -CK_CA_Restart = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_RestartForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) -CK_CA_CloseApplicationID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG) -CK_CA_CloseApplicationIDForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG) -CK_CA_OpenApplicationID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG) -CK_CA_OpenApplicationIDForContainer = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG) -CK_CA_SetApplicationID = CFUNCTYPE(CK_RV, CK_ULONG, CK_ULONG) -CK_CA_ManualKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_SetLKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_CA_SetKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_CA_SetCloningDomain = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG) -CK_CA_ClonePrivateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) -CK_CA_CloneObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) -CK_CA_GenerateCloningKEV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_CloneAsTargetInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_CloneAsSource = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_CloneAsTarget = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR) -CK_CA_SetMofN = CFUNCTYPE(CK_RV, CK_BBOOL) -CK_CA_GenerateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) -CK_CA_GenerateCloneableMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) -CK_CA_ModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) -CK_CA_CloneMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) -CK_CA_CloneModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) -CK_CA_ActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CA_MOFN_ACTIVATION_PTR, CK_ULONG) -CK_CA_DeactivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_GetMofNStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CA_MOFN_STATUS_PTR) -CK_CA_DuplicateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_IsMofNEnabled = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_IsMofNRequired = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GenerateTokenKeys = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) -CK_CA_GetTokenCertificateInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_GetModuleList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetModuleInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR) -CK_CA_LoadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) -CK_CA_LoadEncryptedModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) -CK_CA_UnloadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID) -CK_CA_PerformModuleCall = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) -CK_C_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_FirmwareUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) -CK_CA_FirmwareRollback = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_CapabilityUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) -CK_CA_GetUserContainerNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_SetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG) -CK_CA_GetTokenInsertionCount = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GetRollbackFirmwareVersion = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GetFPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GetTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GetExtendedTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetConfigurationElementDescription = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR) -CK_CA_GetHSMCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetHSMCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetHSMPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetHSMPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetContainerCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetContainerCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetContainerPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetContainerPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) -CK_CA_SetTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_SetExtendedTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_SetHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_SetHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_SetDestructiveHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_SetDestructiveHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_SetContainerPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG) -CK_CA_SetContainerPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_RetrieveLicenseList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_QueryLicense = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR) -CK_CA_GetContainerStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_ReadCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_WriteCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_GetPrimarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID_PTR) -CK_CA_GetSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID_PTR) -CK_CA_SwitchSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG) -CK_CA_CloseSecondarySession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG) -CK_CA_CloseAllSecondarySessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_ChoosePrimarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_ChooseSecondarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_CloneObjectToAllSessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) -CK_CA_CloneAllObjectsToSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID) -CK_CA_ResetDevice = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS) -CK_CA_FactoryReset = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS) -CK_CA_SetPedId = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG) -CK_CA_GetPedId = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG)) -CK_CA_SpRawRead = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_SpRawWrite = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_CheckOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)) -CK_CA_DestroyMultipleObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR) -CK_CA_HAInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) -CK_CA_HAGetMasterPublic = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAGetLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAAnswerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HALogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAAnswerMofNChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) -CK_CA_GetHAState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_HA_STATE_PTR) -CK_CA_GetTokenCertificates = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_ExtractMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_InsertMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) -CK_CA_MultisignValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) -CK_CA_SIMExtract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR) -CK_CA_SIMInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR) -CK_CA_SIMMultiSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) -CK_CA_Extract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) -CK_CA_Insert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) -CK_CA_GetObjectUID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)) -CK_CA_GetObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_DeleteContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_MTKSetStorage = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_MTKRestore = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_MTKResplit = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_MTKZeroize = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_MTKGetState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GetTSV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_InvokeServiceInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_InvokeService = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) -CK_CA_InvokeServiceFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_InvokeServiceAsynch = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_InvokeServiceSinglePart = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_EncodeECParamsFromFile = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR) -CK_CA_GetHSMStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetContainerStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_SetContainerSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_CreateContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR) -CK_CA_DeleteContainerWithHandle = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_GetContainerList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_GetNumberOfAllowedContainers = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) -CK_CA_GetTunnelSlotNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_ID_PTR) -CK_CA_GetClusterState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CLUSTER_STATE_PTR) -CK_CA_LockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_UnlockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_LKMInitiatorChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR) -CK_CA_LKMReceiverResponse = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR) -CK_CA_LKMInitiatorComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) -CK_CA_LKMReceiverComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) -CK_CA_ModifyUsageCount = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_LogVerify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG_PTR) -CK_CA_LogVerifyFile = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG_PTR) -CK_CA_LogExternal = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG) -CK_CA_LogImportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) -CK_CA_LogExportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) -CK_CA_LogSetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR) -CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR) -CK_CA_LogEraseAll = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)) -CK_CA_InitAudit = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR) -CK_CA_GetTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR) -CK_CA_TimeSync = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_SFNT_CA_FUNCTION_LIST._fields_ = [ - ('version', CK_VERSION), - ('CA_GetFunctionList', CK_CA_GetFunctionList), - ('CA_WaitForSlotEvent', CK_CA_WaitForSlotEvent), - ('CA_InitIndirectToken', CK_CA_InitIndirectToken), - ('CA_InitIndirectPIN', CK_CA_InitIndirectPIN), - ('CA_ResetPIN', CK_CA_ResetPIN), - ('CA_CreateLoginChallenge', CK_CA_CreateLoginChallenge), - ('CA_Deactivate', CK_CA_Deactivate), - ('CA_OpenSession', CK_CA_OpenSession), - ('CA_IndirectLogin', CK_CA_IndirectLogin), - ('CA_InitializeRemotePEDVector', CK_CA_InitializeRemotePEDVector), - ('CA_DeleteRemotePEDVector', CK_CA_DeleteRemotePEDVector), - ('CA_GetRemotePEDVectorStatus', CK_CA_GetRemotePEDVectorStatus), - ('CA_ConfigureRemotePED', CK_CA_ConfigureRemotePED), - ('CA_DismantleRemotePED', CK_CA_DismantleRemotePED), - ('CA_Restart', CK_CA_Restart), - ('CA_RestartForContainer', CK_CA_RestartForContainer), - ('CA_CloseApplicationID', CK_CA_CloseApplicationID), - ('CA_CloseApplicationIDForContainer', CK_CA_CloseApplicationIDForContainer), - ('CA_OpenApplicationID', CK_CA_OpenApplicationID), - ('CA_OpenApplicationIDForContainer', CK_CA_OpenApplicationIDForContainer), - ('CA_SetApplicationID', CK_CA_SetApplicationID), - ('CA_ManualKCV', CK_CA_ManualKCV), - ('CA_SetLKCV', CK_CA_SetLKCV), - ('CA_SetKCV', CK_CA_SetKCV), - ('CA_SetCloningDomain', CK_CA_SetCloningDomain), - ('CA_ClonePrivateKey', CK_CA_ClonePrivateKey), - ('CA_CloneObject', CK_CA_CloneObject), - ('CA_GenerateCloningKEV', CK_CA_GenerateCloningKEV), - ('CA_CloneAsTargetInit', CK_CA_CloneAsTargetInit), - ('CA_CloneAsSource', CK_CA_CloneAsSource), - ('CA_CloneAsTarget', CK_CA_CloneAsTarget), - ('CA_SetMofN', CK_CA_SetMofN), - ('CA_GenerateMofN', CK_CA_GenerateMofN), - ('CA_GenerateCloneableMofN', CK_CA_GenerateCloneableMofN), - ('CA_ModifyMofN', CK_CA_ModifyMofN), - ('CA_CloneMofN', CK_CA_CloneMofN), - ('CA_CloneModifyMofN', CK_CA_CloneModifyMofN), - ('CA_ActivateMofN', CK_CA_ActivateMofN), - ('CA_DeactivateMofN', CK_CA_DeactivateMofN), - ('CA_GetMofNStatus', CK_CA_GetMofNStatus), - ('CA_DuplicateMofN', CK_CA_DuplicateMofN), - ('CA_IsMofNEnabled', CK_CA_IsMofNEnabled), - ('CA_IsMofNRequired', CK_CA_IsMofNRequired), - ('CA_GenerateTokenKeys', CK_CA_GenerateTokenKeys), - ('CA_GetTokenCertificateInfo', CK_CA_GetTokenCertificateInfo), - ('CA_SetTokenCertificateSignature', CK_CA_SetTokenCertificateSignature), - ('CA_GetModuleList', CK_CA_GetModuleList), - ('CA_GetModuleInfo', CK_CA_GetModuleInfo), - ('CA_LoadModule', CK_CA_LoadModule), - ('CA_LoadEncryptedModule', CK_CA_LoadEncryptedModule), - ('CA_UnloadModule', CK_CA_UnloadModule), - ('CA_PerformModuleCall', CK_CA_PerformModuleCall), - ('C_PerformSelfTest', CK_C_PerformSelfTest), - ('CA_FirmwareUpdate', CK_CA_FirmwareUpdate), - ('CA_FirmwareRollback', CK_CA_FirmwareRollback), - ('CA_CapabilityUpdate', CK_CA_CapabilityUpdate), - ('CA_GetUserContainerNumber', CK_CA_GetUserContainerNumber), - ('CA_GetUserContainerName', CK_CA_GetUserContainerName), - ('CA_SetUserContainerName', CK_CA_SetUserContainerName), - ('CA_GetTokenInsertionCount', CK_CA_GetTokenInsertionCount), - ('CA_GetRollbackFirmwareVersion', CK_CA_GetRollbackFirmwareVersion), - ('CA_GetFPV', CK_CA_GetFPV), - ('CA_GetTPV', CK_CA_GetTPV), - ('CA_GetExtendedTPV', CK_CA_GetExtendedTPV), - ('CA_GetConfigurationElementDescription', CK_CA_GetConfigurationElementDescription), - ('CA_GetHSMCapabilitySet', CK_CA_GetHSMCapabilitySet), - ('CA_GetHSMCapabilitySetting', CK_CA_GetHSMCapabilitySetting), - ('CA_GetHSMPolicySet', CK_CA_GetHSMPolicySet), - ('CA_GetHSMPolicySetting', CK_CA_GetHSMPolicySetting), - ('CA_GetContainerCapabilitySet', CK_CA_GetContainerCapabilitySet), - ('CA_GetContainerCapabilitySetting', CK_CA_GetContainerCapabilitySetting), - ('CA_GetContainerPolicySet', CK_CA_GetContainerPolicySet), - ('CA_GetContainerPolicySetting', CK_CA_GetContainerPolicySetting), - ('CA_SetTPV', CK_CA_SetTPV), - ('CA_SetExtendedTPV', CK_CA_SetExtendedTPV), - ('CA_SetHSMPolicy', CK_CA_SetHSMPolicy), - ('CA_SetHSMPolicies', CK_CA_SetHSMPolicies), - ('CA_SetDestructiveHSMPolicy', CK_CA_SetDestructiveHSMPolicy), - ('CA_SetDestructiveHSMPolicies', CK_CA_SetDestructiveHSMPolicies), - ('CA_SetContainerPolicy', CK_CA_SetContainerPolicy), - ('CA_SetContainerPolicies', CK_CA_SetContainerPolicies), - ('CA_RetrieveLicenseList', CK_CA_RetrieveLicenseList), - ('CA_QueryLicense', CK_CA_QueryLicense), - ('CA_GetContainerStatus', CK_CA_GetContainerStatus), - ('CA_GetSessionInfo', CK_CA_GetSessionInfo), - ('CA_ReadCommonStore', CK_CA_ReadCommonStore), - ('CA_WriteCommonStore', CK_CA_WriteCommonStore), - ('CA_GetPrimarySlot', CK_CA_GetPrimarySlot), - ('CA_GetSecondarySlot', CK_CA_GetSecondarySlot), - ('CA_SwitchSecondarySlot', CK_CA_SwitchSecondarySlot), - ('CA_CloseSecondarySession', CK_CA_CloseSecondarySession), - ('CA_CloseAllSecondarySessions', CK_CA_CloseAllSecondarySessions), - ('CA_ChoosePrimarySlot', CK_CA_ChoosePrimarySlot), - ('CA_ChooseSecondarySlot', CK_CA_ChooseSecondarySlot), - ('CA_CloneObjectToAllSessions', CK_CA_CloneObjectToAllSessions), - ('CA_CloneAllObjectsToSession', CK_CA_CloneAllObjectsToSession), - ('CA_ResetDevice', CK_CA_ResetDevice), - ('CA_FactoryReset', CK_CA_FactoryReset), - ('CA_SetPedId', CK_CA_SetPedId), - ('CA_GetPedId', CK_CA_GetPedId), - ('CA_SpRawRead', CK_CA_SpRawRead), - ('CA_SpRawWrite', CK_CA_SpRawWrite), - ('CA_CheckOperationState', CK_CA_CheckOperationState), - ('CA_DestroyMultipleObjects', CK_CA_DestroyMultipleObjects), - ('CA_HAInit', CK_CA_HAInit), - ('CA_HAGetMasterPublic', CK_CA_HAGetMasterPublic), - ('CA_HAGetLoginChallenge', CK_CA_HAGetLoginChallenge), - ('CA_HAAnswerLoginChallenge', CK_CA_HAAnswerLoginChallenge), - ('CA_HALogin', CK_CA_HALogin), - ('CA_HAAnswerMofNChallenge', CK_CA_HAAnswerMofNChallenge), - ('CA_HAActivateMofN', CK_CA_HAActivateMofN), - ('CA_GetHAState', CK_CA_GetHAState), - ('CA_GetTokenCertificates', CK_CA_GetTokenCertificates), - ('CA_ExtractMaskedObject', CK_CA_ExtractMaskedObject), - ('CA_InsertMaskedObject', CK_CA_InsertMaskedObject), - ('CA_MultisignValue', CK_CA_MultisignValue), - ('CA_SIMExtract', CK_CA_SIMExtract), - ('CA_SIMInsert', CK_CA_SIMInsert), - ('CA_SIMMultiSign', CK_CA_SIMMultiSign), - ('CA_Extract', CK_CA_Extract), - ('CA_Insert', CK_CA_Insert), - ('CA_GetObjectUID', CK_CA_GetObjectUID), - ('CA_GetObjectHandle', CK_CA_GetObjectHandle), - ('CA_DeleteContainer', CK_CA_DeleteContainer), - ('CA_MTKSetStorage', CK_CA_MTKSetStorage), - ('CA_MTKRestore', CK_CA_MTKRestore), - ('CA_MTKResplit', CK_CA_MTKResplit), - ('CA_MTKZeroize', CK_CA_MTKZeroize), - ('CA_MTKGetState', CK_CA_MTKGetState), - ('CA_GetTSV', CK_CA_GetTSV), - ('CA_InvokeServiceInit', CK_CA_InvokeServiceInit), - ('CA_InvokeService', CK_CA_InvokeService), - ('CA_InvokeServiceFinal', CK_CA_InvokeServiceFinal), - ('CA_InvokeServiceAsynch', CK_CA_InvokeServiceAsynch), - ('CA_InvokeServiceSinglePart', CK_CA_InvokeServiceSinglePart), - ('CA_EncodeECPrimeParams', CK_CA_EncodeECPrimeParams), - ('CA_EncodeECChar2Params', CK_CA_EncodeECChar2Params), - ('CA_EncodeECParamsFromFile', CK_CA_EncodeECParamsFromFile), - ('CA_GetHSMStorageInformation', CK_CA_GetHSMStorageInformation), - ('CA_GetContainerStorageInformation', CK_CA_GetContainerStorageInformation), - ('CA_SetContainerSize', CK_CA_SetContainerSize), - ('CA_CreateContainer', CK_CA_CreateContainer), - ('CA_DeleteContainerWithHandle', CK_CA_DeleteContainerWithHandle), - ('CA_GetContainerList', CK_CA_GetContainerList), - ('CA_GetContainerName', CK_CA_GetContainerName), - ('CA_GetNumberOfAllowedContainers', CK_CA_GetNumberOfAllowedContainers), - ('CA_GetTunnelSlotNumber', CK_CA_GetTunnelSlotNumber), - ('CA_GetClusterState', CK_CA_GetClusterState), - ('CA_LockClusteredSlot', CK_CA_LockClusteredSlot), - ('CA_UnlockClusteredSlot', CK_CA_UnlockClusteredSlot), - ('CA_LKMInitiatorChallenge', CK_CA_LKMInitiatorChallenge), - ('CA_LKMReceiverResponse', CK_CA_LKMReceiverResponse), - ('CA_LKMInitiatorComplete', CK_CA_LKMInitiatorComplete), - ('CA_LKMReceiverComplete', CK_CA_LKMReceiverComplete), - ('CA_ModifyUsageCount', CK_CA_ModifyUsageCount), - ('CA_LogVerify', CK_CA_LogVerify), - ('CA_LogVerifyFile', CK_CA_LogVerifyFile), - ('CA_LogExternal', CK_CA_LogExternal), - ('CA_LogImportSecret', CK_CA_LogImportSecret), - ('CA_LogExportSecret', CK_CA_LogExportSecret), - ('CA_LogSetConfig', CK_CA_LogSetConfig), - ('CA_LogGetConfig', CK_CA_LogGetConfig), - ('CA_LogEraseAll', CK_CA_LogEraseAll), - ('CA_LogGetStatus', CK_CA_LogGetStatus), - ('CA_InitAudit', CK_CA_InitAudit), - ('CA_GetTime', CK_CA_GetTime), - ('CA_TimeSync', CK_CA_TimeSync), + ('C_PerformSelfTest', CK_C_PerformSelfTest), + ('CA_GetFunctionList', CK_CA_GetFunctionList), + ('CA_WaitForSlotEvent', CK_CA_WaitForSlotEvent), + ('CA_InitIndirectToken', CK_CA_InitIndirectToken), + ('CA_InitIndirectPIN', CK_CA_InitIndirectPIN), + ('CA_ResetPIN', CK_CA_ResetPIN), + ('CA_InitRolePIN', CK_CA_InitRolePIN), + ('CA_InitSlotRolePIN', CK_CA_InitSlotRolePIN), + ('CA_RoleStateGet', CK_CA_RoleStateGet), + ('CA_CreateLoginChallenge', CK_CA_CreateLoginChallenge), + ('CA_Deactivate', CK_CA_Deactivate), + ('CA_FindAdminSlotForSlot', CK_CA_FindAdminSlotForSlot), + ('CA_TokenInsert', CK_CA_TokenInsert), + ('CA_TokenInsertNoAuth', CK_CA_TokenInsertNoAuth), + ('CA_TokenZeroize', CK_CA_TokenZeroize), + ('CA_TokenDelete', CK_CA_TokenDelete), + ('CA_OpenSession', CK_CA_OpenSession), + ('CA_IndirectLogin', CK_CA_IndirectLogin), + ('CA_InitializeRemotePEDVector', CK_CA_InitializeRemotePEDVector), + ('CA_DeleteRemotePEDVector', CK_CA_DeleteRemotePEDVector), + ('CA_GetRemotePEDVectorStatus', CK_CA_GetRemotePEDVectorStatus), + ('CA_ConfigureRemotePED', CK_CA_ConfigureRemotePED), + ('CA_DismantleRemotePED', CK_CA_DismantleRemotePED), + ('CA_Restart', CK_CA_Restart), + ('CA_RestartForContainer', CK_CA_RestartForContainer), + ('CA_CloseApplicationID', CK_CA_CloseApplicationID), + ('CA_CloseApplicationIDForContainer', CK_CA_CloseApplicationIDForContainer), + ('CA_OpenApplicationID', CK_CA_OpenApplicationID), + ('CA_OpenApplicationIDForContainer', CK_CA_OpenApplicationIDForContainer), + ('CA_SetApplicationID', CK_CA_SetApplicationID), + ('CA_ManualKCV', CK_CA_ManualKCV), + ('CA_SetLKCV', CK_CA_SetLKCV), + ('CA_SetKCV', CK_CA_SetKCV), + ('CA_SetRDK', CK_CA_SetRDK), + ('CA_SetCloningDomain', CK_CA_SetCloningDomain), + ('CA_ClonePrivateKey', CK_CA_ClonePrivateKey), + ('CA_CloneObject', CK_CA_CloneObject), + ('CA_GenerateCloningKEV', CK_CA_GenerateCloningKEV), + ('CA_CloneAsTargetInit', CK_CA_CloneAsTargetInit), + ('CA_CloneAsSource', CK_CA_CloneAsSource), + ('CA_CloneAsTarget', CK_CA_CloneAsTarget), + ('CA_SetMofN', CK_CA_SetMofN), + ('CA_GenerateMofN', CK_CA_GenerateMofN), + ('CA_GenerateCloneableMofN', CK_CA_GenerateCloneableMofN), + ('CA_ModifyMofN', CK_CA_ModifyMofN), + ('CA_CloneMofN', CK_CA_CloneMofN), + ('CA_CloneModifyMofN', CK_CA_CloneModifyMofN), + ('CA_ActivateMofN', CK_CA_ActivateMofN), + ('CA_DeactivateMofN', CK_CA_DeactivateMofN), + ('CA_GetMofNStatus', CK_CA_GetMofNStatus), + ('CA_DuplicateMofN', CK_CA_DuplicateMofN), + ('CA_IsMofNEnabled', CK_CA_IsMofNEnabled), + ('CA_IsMofNRequired', CK_CA_IsMofNRequired), + ('CA_GenerateTokenKeys', CK_CA_GenerateTokenKeys), + ('CA_GetTokenCertificateInfo', CK_CA_GetTokenCertificateInfo), + ('CA_SetTokenCertificateSignature', CK_CA_SetTokenCertificateSignature), + ('CA_GetModuleList', CK_CA_GetModuleList), + ('CA_GetModuleInfo', CK_CA_GetModuleInfo), + ('CA_LoadModule', CK_CA_LoadModule), + ('CA_LoadEncryptedModule', CK_CA_LoadEncryptedModule), + ('CA_UnloadModule', CK_CA_UnloadModule), + ('CA_PerformModuleCall', CK_CA_PerformModuleCall), + ('CA_FirmwareUpdate', CK_CA_FirmwareUpdate), + ('CA_FirmwareRollback', CK_CA_FirmwareRollback), + ('CA_CapabilityUpdate', CK_CA_CapabilityUpdate), + ('CA_GetUserContainerNumber', CK_CA_GetUserContainerNumber), + ('CA_GetUserContainerName', CK_CA_GetUserContainerName), + ('CA_SetUserContainerName', CK_CA_SetUserContainerName), + ('CA_GetTokenInsertionCount', CK_CA_GetTokenInsertionCount), + ('CA_GetRollbackFirmwareVersion', CK_CA_GetRollbackFirmwareVersion), + ('CA_GetFPV', CK_CA_GetFPV), + ('CA_GetTPV', CK_CA_GetTPV), + ('CA_GetExtendedTPV', CK_CA_GetExtendedTPV), + ('CA_GetConfigurationElementDescription', CK_CA_GetConfigurationElementDescription), + ('CA_GetHSMCapabilitySet', CK_CA_GetHSMCapabilitySet), + ('CA_GetHSMCapabilitySetting', CK_CA_GetHSMCapabilitySetting), + ('CA_GetHSMPolicySet', CK_CA_GetHSMPolicySet), + ('CA_GetHSMPolicySetting', CK_CA_GetHSMPolicySetting), + ('CA_GetContainerCapabilitySet', CK_CA_GetContainerCapabilitySet), + ('CA_GetContainerCapabilitySetting', CK_CA_GetContainerCapabilitySetting), + ('CA_GetContainerPolicySet', CK_CA_GetContainerPolicySet), + ('CA_GetContainerPolicySetting', CK_CA_GetContainerPolicySetting), + ('CA_SetTPV', CK_CA_SetTPV), + ('CA_SetExtendedTPV', CK_CA_SetExtendedTPV), + ('CA_SetHSMPolicy', CK_CA_SetHSMPolicy), + ('CA_SetHSMPolicies', CK_CA_SetHSMPolicies), + ('CA_SetDestructiveHSMPolicy', CK_CA_SetDestructiveHSMPolicy), + ('CA_SetDestructiveHSMPolicies', CK_CA_SetDestructiveHSMPolicies), + ('CA_SetContainerPolicy', CK_CA_SetContainerPolicy), + ('CA_SetContainerPolicies', CK_CA_SetContainerPolicies), + ('CA_GetTokenCapabilities', CK_CA_GetTokenCapabilities), + ('CA_SetTokenPolicies', CK_CA_SetTokenPolicies), + ('CA_GetTokenPolicies', CK_CA_GetTokenPolicies), + ('CA_RetrieveLicenseList', CK_CA_RetrieveLicenseList), + ('CA_QueryLicense', CK_CA_QueryLicense), + ('CA_GetContainerStatus', CK_CA_GetContainerStatus), + ('CA_GetTokenStatus', CK_CA_GetTokenStatus), + ('CA_GetSessionInfo', CK_CA_GetSessionInfo), + ('CA_ReadCommonStore', CK_CA_ReadCommonStore), + ('CA_WriteCommonStore', CK_CA_WriteCommonStore), + ('CA_GetPrimarySlot', CK_CA_GetPrimarySlot), + ('CA_GetSecondarySlot', CK_CA_GetSecondarySlot), + ('CA_SwitchSecondarySlot', CK_CA_SwitchSecondarySlot), + ('CA_CloseSecondarySession', CK_CA_CloseSecondarySession), + ('CA_CloseAllSecondarySessions', CK_CA_CloseAllSecondarySessions), + ('CA_ChoosePrimarySlot', CK_CA_ChoosePrimarySlot), + ('CA_ChooseSecondarySlot', CK_CA_ChooseSecondarySlot), + ('CA_CloneObjectToAllSessions', CK_CA_CloneObjectToAllSessions), + ('CA_CloneAllObjectsToSession', CK_CA_CloneAllObjectsToSession), + ('CA_ResetDevice', CK_CA_ResetDevice), + ('CA_Zeroize', CK_CA_Zeroize), + ('CA_FactoryReset', CK_CA_FactoryReset), + ('CA_SetPedId', CK_CA_SetPedId), + ('CA_GetPedId', CK_CA_GetPedId), + ('CA_SpRawRead', CK_CA_SpRawRead), + ('CA_SpRawWrite', CK_CA_SpRawWrite), + ('CA_CheckOperationState', CK_CA_CheckOperationState), + ('CA_DestroyMultipleObjects', CK_CA_DestroyMultipleObjects), + ('CA_OpenSecureToken', CK_CA_OpenSecureToken), + ('CA_CloseSecureToken', CK_CA_CloseSecureToken), + ('CA_ListSecureToken', CK_CA_ListSecureToken), + ('CA_GetSecureElementMeta', CK_CA_GetSecureElementMeta), + ('CA_HAInit', CK_CA_HAInit), + ('CA_HAGetMasterPublic', CK_CA_HAGetMasterPublic), + ('CA_HAGetLoginChallenge', CK_CA_HAGetLoginChallenge), + ('CA_HAAnswerLoginChallenge', CK_CA_HAAnswerLoginChallenge), + ('CA_HALogin', CK_CA_HALogin), + ('CA_HAAnswerMofNChallenge', CK_CA_HAAnswerMofNChallenge), + ('CA_HAActivateMofN', CK_CA_HAActivateMofN), + ('CA_GetHAState', CK_CA_GetHAState), + ('CA_GetTokenCertificates', CK_CA_GetTokenCertificates), + ('CA_ExtractMaskedObject', CK_CA_ExtractMaskedObject), + ('CA_InsertMaskedObject', CK_CA_InsertMaskedObject), + ('CA_MultisignValue', CK_CA_MultisignValue), + ('CA_SIMExtract', CK_CA_SIMExtract), + ('CA_SIMInsert', CK_CA_SIMInsert), + ('CA_SIMMultiSign', CK_CA_SIMMultiSign), + ('CA_Extract', CK_CA_Extract), + ('CA_Insert', CK_CA_Insert), + ('CA_GetTokenObjectUID', CK_CA_GetTokenObjectUID), + ('CA_GetTokenObjectHandle', CK_CA_GetTokenObjectHandle), + ('CA_GetObjectUID', CK_CA_GetObjectUID), + ('CA_GetObjectHandle', CK_CA_GetObjectHandle), + ('CA_DeleteContainer', CK_CA_DeleteContainer), + ('CA_MTKSetStorage', CK_CA_MTKSetStorage), + ('CA_MTKRestore', CK_CA_MTKRestore), + ('CA_MTKResplit', CK_CA_MTKResplit), + ('CA_MTKZeroize', CK_CA_MTKZeroize), + ('CA_MTKGetState', CK_CA_MTKGetState), + ('CA_GetTSV', CK_CA_GetTSV), + ('CA_InvokeServiceInit', CK_CA_InvokeServiceInit), + ('CA_InvokeService', CK_CA_InvokeService), + ('CA_InvokeServiceFinal', CK_CA_InvokeServiceFinal), + ('CA_InvokeServiceAsynch', CK_CA_InvokeServiceAsynch), + ('CA_InvokeServiceSinglePart', CK_CA_InvokeServiceSinglePart), + ('CA_EncodeECPrimeParams', CK_CA_EncodeECPrimeParams), + ('CA_EncodeECChar2Params', CK_CA_EncodeECChar2Params), + ('CA_EncodeECParamsFromFile', CK_CA_EncodeECParamsFromFile), + ('CA_GetHSMStats', CK_CA_GetHSMStats), + ('CA_GetHSMStorageInformation', CK_CA_GetHSMStorageInformation), + ('CA_GetTokenStorageInformation', CK_CA_GetTokenStorageInformation), + ('CA_GetContainerStorageInformation', CK_CA_GetContainerStorageInformation), + ('CA_SetContainerSize', CK_CA_SetContainerSize), + ('CA_CreateContainer', CK_CA_CreateContainer), + ('CA_InitAudit', CK_CA_InitAudit), + ('CA_LogVerify', CK_CA_LogVerify), + ('CA_LogVerifyFile', CK_CA_LogVerifyFile), + ('CA_LogExternal', CK_CA_LogExternal), + ('CA_LogImportSecret', CK_CA_LogImportSecret), + ('CA_LogExportSecret', CK_CA_LogExportSecret), + ('CA_TimeSync', CK_CA_TimeSync), + ('CA_GetTime', CK_CA_GetTime), + ('CA_LogSetConfig', CK_CA_LogSetConfig), + ('CA_LogGetConfig', CK_CA_LogGetConfig), + ('CA_LogEraseAll', CK_CA_LogEraseAll), + ('CA_LogGetStatus', CK_CA_LogGetStatus), + ('CA_DeleteContainerWithHandle', CK_CA_DeleteContainerWithHandle), + ('CA_GetContainerList', CK_CA_GetContainerList), + ('CA_GetContainerName', CK_CA_GetContainerName), + ('CA_GetNumberOfAllowedContainers', CK_CA_GetNumberOfAllowedContainers), + ('CA_GetTunnelSlotNumber', CK_CA_GetTunnelSlotNumber), + ('CA_GetClusterState', CK_CA_GetClusterState), + ('CA_LockClusteredSlot', CK_CA_LockClusteredSlot), + ('CA_UnlockClusteredSlot', CK_CA_UnlockClusteredSlot), + ('CA_LKMInitiatorChallenge', CK_CA_LKMInitiatorChallenge), + ('CA_LKMReceiverResponse', CK_CA_LKMReceiverResponse), + ('CA_LKMInitiatorComplete', CK_CA_LKMInitiatorComplete), + ('CA_LKMReceiverComplete', CK_CA_LKMReceiverComplete), + ('CA_ModifyUsageCount', CK_CA_ModifyUsageCount), + ('CA_EnableUnauthTokenInsertion', CK_CA_EnableUnauthTokenInsertion), + ('CA_GetUnauthTokenInsertionStatus', CK_CA_GetUnauthTokenInsertionStatus), + ('CA_DisableUnauthTokenInsertion', CK_CA_DisableUnauthTokenInsertion), + ('CA_STCRegister', CK_CA_STCRegister), + ('CA_STCDeregister', CK_CA_STCDeregister), + ('CA_STCGetPubKey', CK_CA_STCGetPubKey), + ('CA_STCGetClientsList', CK_CA_STCGetClientsList), + ('CA_STCGetClientInfo', CK_CA_STCGetClientInfo), + ('CA_STCGetPartPubKey', CK_CA_STCGetPartPubKey), + ('CA_STCGetAdminPubKey', CK_CA_STCGetAdminPubKey), ] CA_GetFunctionList = make_late_binding_function('CA_GetFunctionList') CA_GetFunctionList.restype = CK_RV @@ -1582,9 +1388,6 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CA_PerformModuleCall = make_late_binding_function('CA_PerformModuleCall') CA_PerformModuleCall.restype = CK_RV CA_PerformModuleCall.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR] -C_PerformSelfTest = make_late_binding_function('C_PerformSelfTest') -C_PerformSelfTest.restype = CK_RV -C_PerformSelfTest.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CA_FirmwareUpdate = make_late_binding_function('CA_FirmwareUpdate') CA_FirmwareUpdate.restype = CK_RV CA_FirmwareUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR] @@ -1738,6 +1541,18 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CA_DestroyMultipleObjects = make_late_binding_function('CA_DestroyMultipleObjects') CA_DestroyMultipleObjects.restype = CK_RV CA_DestroyMultipleObjects.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR] +CA_OpenSecureToken = make_late_binding_function('CA_OpenSecureToken') +CA_OpenSecureToken.restype = CK_RV +CA_OpenSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_CloseSecureToken = make_late_binding_function('CA_CloseSecureToken') +CA_CloseSecureToken.restype = CK_RV +CA_CloseSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_ListSecureToken = make_late_binding_function('CA_ListSecureToken') +CA_ListSecureToken.restype = CK_RV +CA_ListSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_GetSecureElementMeta = make_late_binding_function('CA_GetSecureElementMeta') +CA_GetSecureElementMeta.restype = CK_RV +CA_GetSecureElementMeta.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG] CA_HAInit = make_late_binding_function('CA_HAInit') CA_HAInit.restype = CK_RV CA_HAInit.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] @@ -1840,6 +1655,16 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CA_EncodeECParamsFromFile = make_late_binding_function('CA_EncodeECParamsFromFile') CA_EncodeECParamsFromFile.restype = CK_RV CA_EncodeECParamsFromFile.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR] +if 'win' in sys.platform: + HSM_STATS_PARAMS._pack_ = 1 +HSM_STATS_PARAMS._fields_ = [ + ('ulId', CK_ULONG), + ('ulHighValue', CK_ULONG), + ('ulLowValue', CK_ULONG), +] +CA_GetHSMStats = make_late_binding_function('CA_GetHSMStats') +CA_GetHSMStats.restype = CK_RV +CA_GetHSMStats.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, POINTER(HSM_STATS_PARAMS)] CA_GetHSMStorageInformation = make_late_binding_function('CA_GetHSMStorageInformation') CA_GetHSMStorageInformation.restype = CK_RV CA_GetHSMStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] @@ -1863,7 +1688,7 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CA_LogVerifyFile.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG_PTR] CA_LogExternal = make_late_binding_function('CA_LogExternal') CA_LogExternal.restype = CK_RV -CA_LogExternal.argtypes = [CK_SLOT_ID, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG] +CA_LogExternal.argtypes = [CK_SLOT_ID, CK_SESSION_HANDLE, POINTER(CK_CHAR), CK_ULONG] CA_LogImportSecret = make_late_binding_function('CA_LogImportSecret') CA_LogImportSecret.restype = CK_RV CA_LogImportSecret.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR] @@ -1927,339 +1752,1800 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CA_ModifyUsageCount = make_late_binding_function('CA_ModifyUsageCount') CA_ModifyUsageCount.restype = CK_RV CA_ModifyUsageCount.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG] +C_PerformSelfTest = make_late_binding_function('C_PerformSelfTest') +C_PerformSelfTest.restype = CK_RV +C_PerformSelfTest.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CK_GetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(c_int)) CK_ResetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_SinglePartSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_SinglePartDecrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -__all__ = ['CA_InvokeService', 'CA_GetSecondarySlot', - 'CK_OTP_SIGNATURE_INFO', 'C_FindObjectsFinal', - 'CK_C_EncryptFinal', +class CK_FUNCTION_LIST(Structure): + pass +CK_C_Initialize = CFUNCTYPE(CK_RV, CK_VOID_PTR) +CK_C_Finalize = CFUNCTYPE(CK_RV, CK_VOID_PTR) +class CK_INFO(Structure): + pass +CK_INFO_PTR = POINTER(CK_INFO) +CK_C_GetInfo = CFUNCTYPE(CK_RV, CK_INFO_PTR) +CK_FUNCTION_LIST_PTR = POINTER(CK_FUNCTION_LIST) +CK_FUNCTION_LIST_PTR_PTR = POINTER(CK_FUNCTION_LIST_PTR) +CK_C_GetFunctionList = CFUNCTYPE(CK_RV, CK_FUNCTION_LIST_PTR_PTR) +CK_C_GetSlotList = CFUNCTYPE(CK_RV, CK_BBOOL, CK_SLOT_ID_PTR, CK_ULONG_PTR) +class CK_SLOT_INFO(Structure): + pass +CK_SLOT_INFO_PTR = POINTER(CK_SLOT_INFO) +CK_C_GetSlotInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_INFO_PTR) +class CK_TOKEN_INFO(Structure): + pass +CK_TOKEN_INFO_PTR = POINTER(CK_TOKEN_INFO) +CK_C_GetTokenInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_TOKEN_INFO_PTR) +CK_MECHANISM_TYPE = CK_ULONG +CK_MECHANISM_TYPE_PTR = POINTER(CK_MECHANISM_TYPE) +CK_C_GetMechanismList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE_PTR, CK_ULONG_PTR) +class CK_MECHANISM_INFO(Structure): + pass +CK_MECHANISM_INFO_PTR = POINTER(CK_MECHANISM_INFO) +CK_C_GetMechanismInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE, CK_MECHANISM_INFO_PTR) +CK_UTF8CHAR = CK_BYTE +CK_UTF8CHAR_PTR = POINTER(CK_UTF8CHAR) +CK_C_InitToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR) +CK_C_InitPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG) +CK_C_SetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, CK_ULONG) +CK_C_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) +CK_C_CloseSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_CloseAllSessions = CFUNCTYPE(CK_RV, CK_SLOT_ID) +class CK_SESSION_INFO(Structure): + pass +CK_SESSION_INFO_PTR = POINTER(CK_SESSION_INFO) +CK_C_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_INFO_PTR) +CK_C_GetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE) +CK_C_Login = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG) +CK_C_Logout = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_CreateObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_CopyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_DestroyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_C_GetObjectSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR) +CK_C_GetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_C_SetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_C_FindObjectsInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_C_FindObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG_PTR) +CK_C_FindObjectsFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_EncryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Encrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_EncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_EncryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Decrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DigestInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) +CK_C_Digest = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_DigestKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) +CK_C_DigestFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Sign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_SignFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_SignRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_VerifyInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_Verify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_C_VerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_VerifyFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_VerifyRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) +CK_C_VerifyRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DigestEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptDigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptVerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_GenerateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_GenerateKeyPair = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_C_WrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_UnwrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_DeriveKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_SeedRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_GenerateRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_C_GetFunctionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_CancelFunction = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_C_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, CK_SLOT_ID_PTR, CK_VOID_PTR) +if 'win' in sys.platform: + CK_FUNCTION_LIST._pack_ = 1 +CK_FUNCTION_LIST._fields_ = [ + ('version', CK_VERSION), + ('C_Initialize', CK_C_Initialize), + ('C_Finalize', CK_C_Finalize), + ('C_GetInfo', CK_C_GetInfo), + ('C_GetFunctionList', CK_C_GetFunctionList), + ('C_GetSlotList', CK_C_GetSlotList), + ('C_GetSlotInfo', CK_C_GetSlotInfo), + ('C_GetTokenInfo', CK_C_GetTokenInfo), + ('C_GetMechanismList', CK_C_GetMechanismList), + ('C_GetMechanismInfo', CK_C_GetMechanismInfo), + ('C_InitToken', CK_C_InitToken), + ('C_InitPIN', CK_C_InitPIN), + ('C_SetPIN', CK_C_SetPIN), + ('C_OpenSession', CK_C_OpenSession), + ('C_CloseSession', CK_C_CloseSession), + ('C_CloseAllSessions', CK_C_CloseAllSessions), + ('C_GetSessionInfo', CK_C_GetSessionInfo), + ('C_GetOperationState', CK_C_GetOperationState), + ('C_SetOperationState', CK_C_SetOperationState), + ('C_Login', CK_C_Login), + ('C_Logout', CK_C_Logout), + ('C_CreateObject', CK_C_CreateObject), + ('C_CopyObject', CK_C_CopyObject), + ('C_DestroyObject', CK_C_DestroyObject), + ('C_GetObjectSize', CK_C_GetObjectSize), + ('C_GetAttributeValue', CK_C_GetAttributeValue), + ('C_SetAttributeValue', CK_C_SetAttributeValue), + ('C_FindObjectsInit', CK_C_FindObjectsInit), + ('C_FindObjects', CK_C_FindObjects), + ('C_FindObjectsFinal', CK_C_FindObjectsFinal), + ('C_EncryptInit', CK_C_EncryptInit), + ('C_Encrypt', CK_C_Encrypt), + ('C_EncryptUpdate', CK_C_EncryptUpdate), + ('C_EncryptFinal', CK_C_EncryptFinal), + ('C_DecryptInit', CK_C_DecryptInit), + ('C_Decrypt', CK_C_Decrypt), + ('C_DecryptUpdate', CK_C_DecryptUpdate), + ('C_DecryptFinal', CK_C_DecryptFinal), + ('C_DigestInit', CK_C_DigestInit), + ('C_Digest', CK_C_Digest), + ('C_DigestUpdate', CK_C_DigestUpdate), + ('C_DigestKey', CK_C_DigestKey), + ('C_DigestFinal', CK_C_DigestFinal), + ('C_SignInit', CK_C_SignInit), + ('C_Sign', CK_C_Sign), + ('C_SignUpdate', CK_C_SignUpdate), + ('C_SignFinal', CK_C_SignFinal), + ('C_SignRecoverInit', CK_C_SignRecoverInit), + ('C_SignRecover', CK_C_SignRecover), + ('C_VerifyInit', CK_C_VerifyInit), + ('C_Verify', CK_C_Verify), + ('C_VerifyUpdate', CK_C_VerifyUpdate), + ('C_VerifyFinal', CK_C_VerifyFinal), + ('C_VerifyRecoverInit', CK_C_VerifyRecoverInit), + ('C_VerifyRecover', CK_C_VerifyRecover), + ('C_DigestEncryptUpdate', CK_C_DigestEncryptUpdate), + ('C_DecryptDigestUpdate', CK_C_DecryptDigestUpdate), + ('C_SignEncryptUpdate', CK_C_SignEncryptUpdate), + ('C_DecryptVerifyUpdate', CK_C_DecryptVerifyUpdate), + ('C_GenerateKey', CK_C_GenerateKey), + ('C_GenerateKeyPair', CK_C_GenerateKeyPair), + ('C_WrapKey', CK_C_WrapKey), + ('C_UnwrapKey', CK_C_UnwrapKey), + ('C_DeriveKey', CK_C_DeriveKey), + ('C_SeedRandom', CK_C_SeedRandom), + ('C_GenerateRandom', CK_C_GenerateRandom), + ('C_GetFunctionStatus', CK_C_GetFunctionStatus), + ('C_CancelFunction', CK_C_CancelFunction), + ('C_WaitForSlotEvent', CK_C_WaitForSlotEvent), +] +C_Initialize = make_late_binding_function('C_Initialize') +C_Initialize.restype = CK_RV +C_Initialize.argtypes = [CK_VOID_PTR] +C_Finalize = make_late_binding_function('C_Finalize') +C_Finalize.restype = CK_RV +C_Finalize.argtypes = [CK_VOID_PTR] +C_GetInfo = make_late_binding_function('C_GetInfo') +C_GetInfo.restype = CK_RV +C_GetInfo.argtypes = [CK_INFO_PTR] +C_GetFunctionList = make_late_binding_function('C_GetFunctionList') +C_GetFunctionList.restype = CK_RV +C_GetFunctionList.argtypes = [CK_FUNCTION_LIST_PTR_PTR] +C_GetSlotList = make_late_binding_function('C_GetSlotList') +C_GetSlotList.restype = CK_RV +C_GetSlotList.argtypes = [CK_BBOOL, CK_SLOT_ID_PTR, CK_ULONG_PTR] +C_GetSlotInfo = make_late_binding_function('C_GetSlotInfo') +C_GetSlotInfo.restype = CK_RV +C_GetSlotInfo.argtypes = [CK_SLOT_ID, CK_SLOT_INFO_PTR] +C_GetTokenInfo = make_late_binding_function('C_GetTokenInfo') +C_GetTokenInfo.restype = CK_RV +C_GetTokenInfo.argtypes = [CK_SLOT_ID, CK_TOKEN_INFO_PTR] +C_GetMechanismList = make_late_binding_function('C_GetMechanismList') +C_GetMechanismList.restype = CK_RV +C_GetMechanismList.argtypes = [CK_SLOT_ID, CK_MECHANISM_TYPE_PTR, CK_ULONG_PTR] +C_GetMechanismInfo = make_late_binding_function('C_GetMechanismInfo') +C_GetMechanismInfo.restype = CK_RV +C_GetMechanismInfo.argtypes = [CK_SLOT_ID, CK_MECHANISM_TYPE, CK_MECHANISM_INFO_PTR] +C_InitToken = make_late_binding_function('C_InitToken') +C_InitToken.restype = CK_RV +C_InitToken.argtypes = [CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR] +C_InitPIN = make_late_binding_function('C_InitPIN') +C_InitPIN.restype = CK_RV +C_InitPIN.argtypes = [CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG] +C_SetPIN = make_late_binding_function('C_SetPIN') +C_SetPIN.restype = CK_RV +C_SetPIN.argtypes = [CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, CK_ULONG] +C_OpenSession = make_late_binding_function('C_OpenSession') +C_OpenSession.restype = CK_RV +C_OpenSession.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] +C_CloseSession = make_late_binding_function('C_CloseSession') +C_CloseSession.restype = CK_RV +C_CloseSession.argtypes = [CK_SESSION_HANDLE] +C_CloseAllSessions = make_late_binding_function('C_CloseAllSessions') +C_CloseAllSessions.restype = CK_RV +C_CloseAllSessions.argtypes = [CK_SLOT_ID] +C_GetSessionInfo = make_late_binding_function('C_GetSessionInfo') +C_GetSessionInfo.restype = CK_RV +C_GetSessionInfo.argtypes = [CK_SESSION_HANDLE, CK_SESSION_INFO_PTR] +C_GetOperationState = make_late_binding_function('C_GetOperationState') +C_GetOperationState.restype = CK_RV +C_GetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_SetOperationState = make_late_binding_function('C_SetOperationState') +C_SetOperationState.restype = CK_RV +C_SetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE] +C_Login = make_late_binding_function('C_Login') +C_Login.restype = CK_RV +C_Login.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG] +C_Logout = make_late_binding_function('C_Logout') +C_Logout.restype = CK_RV +C_Logout.argtypes = [CK_SESSION_HANDLE] +C_CreateObject = make_late_binding_function('C_CreateObject') +C_CreateObject.restype = CK_RV +C_CreateObject.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_CopyObject = make_late_binding_function('C_CopyObject') +C_CopyObject.restype = CK_RV +C_CopyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_DestroyObject = make_late_binding_function('C_DestroyObject') +C_DestroyObject.restype = CK_RV +C_DestroyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] +C_GetObjectSize = make_late_binding_function('C_GetObjectSize') +C_GetObjectSize.restype = CK_RV +C_GetObjectSize.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR] +C_GetAttributeValue = make_late_binding_function('C_GetAttributeValue') +C_GetAttributeValue.restype = CK_RV +C_GetAttributeValue.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] +C_SetAttributeValue = make_late_binding_function('C_SetAttributeValue') +C_SetAttributeValue.restype = CK_RV +C_SetAttributeValue.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] +C_FindObjectsInit = make_late_binding_function('C_FindObjectsInit') +C_FindObjectsInit.restype = CK_RV +C_FindObjectsInit.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG] +C_FindObjects = make_late_binding_function('C_FindObjects') +C_FindObjects.restype = CK_RV +C_FindObjects.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG_PTR] +C_FindObjectsFinal = make_late_binding_function('C_FindObjectsFinal') +C_FindObjectsFinal.restype = CK_RV +C_FindObjectsFinal.argtypes = [CK_SESSION_HANDLE] +C_EncryptInit = make_late_binding_function('C_EncryptInit') +C_EncryptInit.restype = CK_RV +C_EncryptInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Encrypt = make_late_binding_function('C_Encrypt') +C_Encrypt.restype = CK_RV +C_Encrypt.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_EncryptUpdate = make_late_binding_function('C_EncryptUpdate') +C_EncryptUpdate.restype = CK_RV +C_EncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_EncryptFinal = make_late_binding_function('C_EncryptFinal') +C_EncryptFinal.restype = CK_RV +C_EncryptFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptInit = make_late_binding_function('C_DecryptInit') +C_DecryptInit.restype = CK_RV +C_DecryptInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Decrypt = make_late_binding_function('C_Decrypt') +C_Decrypt.restype = CK_RV +C_Decrypt.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptUpdate = make_late_binding_function('C_DecryptUpdate') +C_DecryptUpdate.restype = CK_RV +C_DecryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptFinal = make_late_binding_function('C_DecryptFinal') +C_DecryptFinal.restype = CK_RV +C_DecryptFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_DigestInit = make_late_binding_function('C_DigestInit') +C_DigestInit.restype = CK_RV +C_DigestInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] +C_Digest = make_late_binding_function('C_Digest') +C_Digest.restype = CK_RV +C_Digest.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DigestUpdate = make_late_binding_function('C_DigestUpdate') +C_DigestUpdate.restype = CK_RV +C_DigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_DigestKey = make_late_binding_function('C_DigestKey') +C_DigestKey.restype = CK_RV +C_DigestKey.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] +C_DigestFinal = make_late_binding_function('C_DigestFinal') +C_DigestFinal.restype = CK_RV +C_DigestFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignInit = make_late_binding_function('C_SignInit') +C_SignInit.restype = CK_RV +C_SignInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Sign = make_late_binding_function('C_Sign') +C_Sign.restype = CK_RV +C_Sign.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignUpdate = make_late_binding_function('C_SignUpdate') +C_SignUpdate.restype = CK_RV +C_SignUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_SignFinal = make_late_binding_function('C_SignFinal') +C_SignFinal.restype = CK_RV +C_SignFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignRecoverInit = make_late_binding_function('C_SignRecoverInit') +C_SignRecoverInit.restype = CK_RV +C_SignRecoverInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_SignRecover = make_late_binding_function('C_SignRecover') +C_SignRecover.restype = CK_RV +C_SignRecover.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_VerifyInit = make_late_binding_function('C_VerifyInit') +C_VerifyInit.restype = CK_RV +C_VerifyInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_Verify = make_late_binding_function('C_Verify') +C_Verify.restype = CK_RV +C_Verify.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +C_VerifyUpdate = make_late_binding_function('C_VerifyUpdate') +C_VerifyUpdate.restype = CK_RV +C_VerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_VerifyFinal = make_late_binding_function('C_VerifyFinal') +C_VerifyFinal.restype = CK_RV +C_VerifyFinal.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_VerifyRecoverInit = make_late_binding_function('C_VerifyRecoverInit') +C_VerifyRecoverInit.restype = CK_RV +C_VerifyRecoverInit.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE] +C_VerifyRecover = make_late_binding_function('C_VerifyRecover') +C_VerifyRecover.restype = CK_RV +C_VerifyRecover.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DigestEncryptUpdate = make_late_binding_function('C_DigestEncryptUpdate') +C_DigestEncryptUpdate.restype = CK_RV +C_DigestEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptDigestUpdate = make_late_binding_function('C_DecryptDigestUpdate') +C_DecryptDigestUpdate.restype = CK_RV +C_DecryptDigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_SignEncryptUpdate = make_late_binding_function('C_SignEncryptUpdate') +C_SignEncryptUpdate.restype = CK_RV +C_SignEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptVerifyUpdate = make_late_binding_function('C_DecryptVerifyUpdate') +C_DecryptVerifyUpdate.restype = CK_RV +C_DecryptVerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_GenerateKey = make_late_binding_function('C_GenerateKey') +C_GenerateKey.restype = CK_RV +C_GenerateKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_GenerateKeyPair = make_late_binding_function('C_GenerateKeyPair') +C_GenerateKeyPair.restype = CK_RV +C_GenerateKeyPair.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +C_WrapKey = make_late_binding_function('C_WrapKey') +C_WrapKey.restype = CK_RV +C_WrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_UnwrapKey = make_late_binding_function('C_UnwrapKey') +C_UnwrapKey.restype = CK_RV +C_UnwrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_DeriveKey = make_late_binding_function('C_DeriveKey') +C_DeriveKey.restype = CK_RV +C_DeriveKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_SeedRandom = make_late_binding_function('C_SeedRandom') +C_SeedRandom.restype = CK_RV +C_SeedRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_GenerateRandom = make_late_binding_function('C_GenerateRandom') +C_GenerateRandom.restype = CK_RV +C_GenerateRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +C_GetFunctionStatus = make_late_binding_function('C_GetFunctionStatus') +C_GetFunctionStatus.restype = CK_RV +C_GetFunctionStatus.argtypes = [CK_SESSION_HANDLE] +C_CancelFunction = make_late_binding_function('C_CancelFunction') +C_CancelFunction.restype = CK_RV +C_CancelFunction.argtypes = [CK_SESSION_HANDLE] +C_WaitForSlotEvent = make_late_binding_function('C_WaitForSlotEvent') +C_WaitForSlotEvent.restype = CK_RV +C_WaitForSlotEvent.argtypes = [CK_FLAGS, CK_SLOT_ID_PTR, CK_VOID_PTR] +CK_LONG = c_long +CK_VOID_PTR_PTR = POINTER(CK_VOID_PTR) +CK_VERSION_PTR = POINTER(CK_VERSION) +if 'win' in sys.platform: + CK_INFO._pack_ = 1 +CK_INFO._fields_ = [ + ('cryptokiVersion', CK_VERSION), + ('manufacturerID', CK_UTF8CHAR * 32), + ('flags', CK_FLAGS), + ('libraryDescription', CK_UTF8CHAR * 32), + ('libraryVersion', CK_VERSION), +] +if 'win' in sys.platform: + CK_SLOT_INFO._pack_ = 1 +CK_SLOT_INFO._fields_ = [ + ('slotDescription', CK_UTF8CHAR * 64), + ('manufacturerID', CK_UTF8CHAR * 32), + ('flags', CK_FLAGS), + ('hardwareVersion', CK_VERSION), + ('firmwareVersion', CK_VERSION), +] +if 'win' in sys.platform: + CK_TOKEN_INFO._pack_ = 1 +CK_TOKEN_INFO._fields_ = [ + ('label', CK_UTF8CHAR * 32), + ('manufacturerID', CK_UTF8CHAR * 32), + ('model', CK_UTF8CHAR * 16), + ('serialNumber', CK_CHAR * 16), + ('flags', CK_FLAGS), + ('usMaxSessionCount', CK_ULONG), + ('usSessionCount', CK_ULONG), + ('usMaxRwSessionCount', CK_ULONG), + ('usRwSessionCount', CK_ULONG), + ('usMaxPinLen', CK_ULONG), + ('usMinPinLen', 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_STATE = CK_ULONG +if 'win' in sys.platform: + CK_SESSION_INFO._pack_ = 1 +CK_SESSION_INFO._fields_ = [ + ('slotID', CK_SLOT_ID), + ('state', CK_STATE), + ('flags', CK_FLAGS), + ('usDeviceError', CK_ULONG), +] +CK_OBJECT_CLASS = CK_ULONG +CK_OBJECT_CLASS_PTR = POINTER(CK_OBJECT_CLASS) +CK_HW_FEATURE_TYPE = CK_ULONG +CK_KEY_TYPE = CK_ULONG +CK_CERTIFICATE_TYPE = CK_ULONG +CK_ATTRIBUTE_TYPE = CK_ULONG +if 'win' in sys.platform: + CK_ATTRIBUTE._pack_ = 1 +CK_ATTRIBUTE._fields_ = [ + ('type', CK_ATTRIBUTE_TYPE), + ('pValue', CK_VOID_PTR), + ('usValueLen', CK_ULONG), +] +class CK_DATE(Structure): + pass +if 'win' in sys.platform: + CK_DATE._pack_ = 1 +CK_DATE._fields_ = [ + ('year', CK_CHAR * 4), + ('month', CK_CHAR * 2), + ('day', CK_CHAR * 2), +] +if 'win' in sys.platform: + CK_MECHANISM._pack_ = 1 +CK_MECHANISM._fields_ = [ + ('mechanism', CK_MECHANISM_TYPE), + ('pParameter', CK_VOID_PTR), + ('usParameterLen', CK_ULONG), +] +if 'win' in sys.platform: + CK_MECHANISM_INFO._pack_ = 1 +CK_MECHANISM_INFO._fields_ = [ + ('ulMinKeySize', CK_ULONG), + ('ulMaxKeySize', CK_ULONG), + ('flags', CK_FLAGS), +] +CK_CREATEMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR_PTR) +CK_DESTROYMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) +CK_LOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) +CK_UNLOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) +class CK_C_INITIALIZE_ARGS(Structure): + pass +if 'win' in sys.platform: + CK_C_INITIALIZE_ARGS._pack_ = 1 +CK_C_INITIALIZE_ARGS._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) +CK_RSA_PKCS_MGF_TYPE = CK_ULONG +CK_RSA_PKCS_MGF_TYPE_PTR = POINTER(CK_RSA_PKCS_MGF_TYPE) +CK_RSA_PKCS_OAEP_SOURCE_TYPE = CK_ULONG +CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR = POINTER(CK_RSA_PKCS_OAEP_SOURCE_TYPE) +class CK_RSA_PKCS_OAEP_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_RSA_PKCS_OAEP_PARAMS._pack_ = 1 +CK_RSA_PKCS_OAEP_PARAMS._fields_ = [ + ('hashAlg', CK_MECHANISM_TYPE), + ('mgf', CK_RSA_PKCS_MGF_TYPE), + ('source', CK_RSA_PKCS_OAEP_SOURCE_TYPE), + ('pSourceData', CK_VOID_PTR), + ('ulSourceDataLen', CK_ULONG), +] +CK_RSA_PKCS_OAEP_PARAMS_PTR = POINTER(CK_RSA_PKCS_OAEP_PARAMS) +class CK_RSA_PKCS_PSS_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_RSA_PKCS_PSS_PARAMS._pack_ = 1 +CK_RSA_PKCS_PSS_PARAMS._fields_ = [ + ('hashAlg', CK_MECHANISM_TYPE), + ('mgf', CK_RSA_PKCS_MGF_TYPE), + ('usSaltLen', CK_ULONG), +] +CK_RSA_PKCS_PSS_PARAMS_PTR = POINTER(CK_RSA_PKCS_PSS_PARAMS) +class CK_ECDH1_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_ECDH1_DERIVE_PARAMS._pack_ = 1 +CK_ECDH1_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), +] +CK_ECDH1_DERIVE_PARAMS_PTR = POINTER(CK_ECDH1_DERIVE_PARAMS) +class CK_ECDH2_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_ECDH2_DERIVE_PARAMS._pack_ = 1 +CK_ECDH2_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), +] +CK_ECDH2_DERIVE_PARAMS_PTR = POINTER(CK_ECDH2_DERIVE_PARAMS) +class CK_ECMQV_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_ECMQV_DERIVE_PARAMS._pack_ = 1 +CK_ECMQV_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_EC_KDF_TYPE), + ('ulSharedDataLen', CK_ULONG), + ('pSharedData', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), + ('publicKey', CK_OBJECT_HANDLE), +] +CK_ECMQV_DERIVE_PARAMS_PTR = POINTER(CK_ECMQV_DERIVE_PARAMS) +CK_X9_42_DH_KDF_TYPE = CK_ULONG +CK_X9_42_DH_KDF_TYPE_PTR = POINTER(CK_X9_42_DH_KDF_TYPE) +class CK_X9_42_DH1_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_X9_42_DH1_DERIVE_PARAMS._pack_ = 1 +CK_X9_42_DH1_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_X9_42_DH_KDF_TYPE), + ('ulOtherInfoLen', CK_ULONG), + ('pOtherInfo', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), +] +CK_X9_42_DH1_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH1_DERIVE_PARAMS) +class CK_X9_42_DH2_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_X9_42_DH2_DERIVE_PARAMS._pack_ = 1 +CK_X9_42_DH2_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_X9_42_DH_KDF_TYPE), + ('ulOtherInfoLen', CK_ULONG), + ('pOtherInfo', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), +] +CK_X9_42_DH2_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH2_DERIVE_PARAMS) +class CK_X9_42_MQV_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_X9_42_MQV_DERIVE_PARAMS._pack_ = 1 +CK_X9_42_MQV_DERIVE_PARAMS._fields_ = [ + ('kdf', CK_X9_42_DH_KDF_TYPE), + ('ulOtherInfoLen', CK_ULONG), + ('pOtherInfo', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPrivateDataLen', CK_ULONG), + ('hPrivateData', CK_OBJECT_HANDLE), + ('ulPublicDataLen2', CK_ULONG), + ('pPublicData2', CK_BYTE_PTR), + ('publicKey', CK_OBJECT_HANDLE), +] +CK_X9_42_MQV_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_MQV_DERIVE_PARAMS) +class CK_KEA_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_KEA_DERIVE_PARAMS._pack_ = 1 +CK_KEA_DERIVE_PARAMS._fields_ = [ + ('isSender', CK_BBOOL), + ('ulRandomLen', CK_ULONG), + ('pRandomA', CK_BYTE_PTR), + ('pRandomB', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), +] +CK_KEA_DERIVE_PARAMS_PTR = POINTER(CK_KEA_DERIVE_PARAMS) +CK_RC2_PARAMS = CK_ULONG +CK_RC2_PARAMS_PTR = POINTER(CK_RC2_PARAMS) +class CK_RC2_CBC_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_RC2_CBC_PARAMS._pack_ = 1 +CK_RC2_CBC_PARAMS._fields_ = [ + ('usEffectiveBits', CK_ULONG), + ('iv', CK_BYTE * 8), +] +CK_RC2_CBC_PARAMS_PTR = POINTER(CK_RC2_CBC_PARAMS) +class CK_RC2_MAC_GENERAL_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_RC2_MAC_GENERAL_PARAMS._pack_ = 1 +CK_RC2_MAC_GENERAL_PARAMS._fields_ = [ + ('usEffectiveBits', CK_ULONG), + ('ulMacLength', CK_ULONG), +] +CK_RC2_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC2_MAC_GENERAL_PARAMS) +class CK_RC5_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_RC5_PARAMS._pack_ = 1 +CK_RC5_PARAMS._fields_ = [ + ('ulWordsize', CK_ULONG), + ('ulRounds', CK_ULONG), +] +CK_RC5_PARAMS_PTR = POINTER(CK_RC5_PARAMS) +class CK_RC5_CBC_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_RC5_CBC_PARAMS._pack_ = 1 +CK_RC5_CBC_PARAMS._fields_ = [ + ('ulWordsize', CK_ULONG), + ('ulRounds', CK_ULONG), + ('pIv', CK_BYTE_PTR), + ('ulIvLen', CK_ULONG), +] +CK_RC5_CBC_PARAMS_PTR = POINTER(CK_RC5_CBC_PARAMS) +class CK_RC5_MAC_GENERAL_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_RC5_MAC_GENERAL_PARAMS._pack_ = 1 +CK_RC5_MAC_GENERAL_PARAMS._fields_ = [ + ('ulWordsize', CK_ULONG), + ('ulRounds', CK_ULONG), + ('ulMacLength', CK_ULONG), +] +CK_RC5_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC5_MAC_GENERAL_PARAMS) +CK_MAC_GENERAL_PARAMS = CK_ULONG +CK_MAC_GENERAL_PARAMS_PTR = POINTER(CK_MAC_GENERAL_PARAMS) +class CK_DES_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_DES_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 +CK_DES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 8), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_DES_CBC_ENCRYPT_DATA_PARAMS) +class CK_AES_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_AES_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 +CK_AES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 16), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_AES_CBC_ENCRYPT_DATA_PARAMS) +class CK_SKIPJACK_PRIVATE_WRAP_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_SKIPJACK_PRIVATE_WRAP_PARAMS._pack_ = 1 +CK_SKIPJACK_PRIVATE_WRAP_PARAMS._fields_ = [ + ('usPasswordLen', CK_ULONG), + ('pPassword', CK_BYTE_PTR), + ('ulPublicDataLen', CK_ULONG), + ('pPublicData', CK_BYTE_PTR), + ('ulPAndGLen', CK_ULONG), + ('ulQLen', CK_ULONG), + ('ulRandomLen', CK_ULONG), + ('pRandomA', CK_BYTE_PTR), + ('pPrimeP', CK_BYTE_PTR), + ('pBaseG', CK_BYTE_PTR), + ('pSubprimeQ', CK_BYTE_PTR), +] +CK_SKIPJACK_PRIVATE_WRAP_PTR = POINTER(CK_SKIPJACK_PRIVATE_WRAP_PARAMS) +class CK_SKIPJACK_RELAYX_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_SKIPJACK_RELAYX_PARAMS._pack_ = 1 +CK_SKIPJACK_RELAYX_PARAMS._fields_ = [ + ('ulOldWrappedXLen', CK_ULONG), + ('pOldWrappedX', CK_BYTE_PTR), + ('ulOldPasswordLen', CK_ULONG), + ('pOldPassword', CK_BYTE_PTR), + ('ulOldPublicDataLen', CK_ULONG), + ('pOldPublicData', CK_BYTE_PTR), + ('ulOldRandomLen', CK_ULONG), + ('pOldRandomA', CK_BYTE_PTR), + ('ulNewPasswordLen', CK_ULONG), + ('pNewPassword', CK_BYTE_PTR), + ('ulNewPublicDataLen', CK_ULONG), + ('pNewPublicData', CK_BYTE_PTR), + ('ulNewRandomLen', CK_ULONG), + ('pNewRandomA', CK_BYTE_PTR), +] +CK_SKIPJACK_RELAYX_PARAMS_PTR = POINTER(CK_SKIPJACK_RELAYX_PARAMS) +class CK_PBE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_PBE_PARAMS._pack_ = 1 +CK_PBE_PARAMS._fields_ = [ + ('pInitVector', CK_BYTE_PTR), + ('pPassword', CK_UTF8CHAR_PTR), + ('usPasswordLen', CK_ULONG), + ('pSalt', CK_BYTE_PTR), + ('usSaltLen', CK_ULONG), + ('usIteration', CK_ULONG), +] +CK_PBE_PARAMS_PTR = POINTER(CK_PBE_PARAMS) +class CK_KEY_WRAP_SET_OAEP_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_KEY_WRAP_SET_OAEP_PARAMS._pack_ = 1 +CK_KEY_WRAP_SET_OAEP_PARAMS._fields_ = [ + ('bBC', CK_BYTE), + ('pX', CK_BYTE_PTR), + ('ulXLen', CK_ULONG), +] +CK_KEY_WRAP_SET_OAEP_PARAMS_PTR = POINTER(CK_KEY_WRAP_SET_OAEP_PARAMS) +class CK_SSL3_RANDOM_DATA(Structure): + pass +if 'win' in sys.platform: + CK_SSL3_RANDOM_DATA._pack_ = 1 +CK_SSL3_RANDOM_DATA._fields_ = [ + ('pClientRandom', CK_BYTE_PTR), + ('ulClientRandomLen', CK_ULONG), + ('pServerRandom', CK_BYTE_PTR), + ('ulServerRandomLen', CK_ULONG), +] +class CK_SSL3_MASTER_KEY_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_SSL3_MASTER_KEY_DERIVE_PARAMS._pack_ = 1 +CK_SSL3_MASTER_KEY_DERIVE_PARAMS._fields_ = [ + ('RandomInfo', CK_SSL3_RANDOM_DATA), + ('pVersion', CK_VERSION_PTR), +] +CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_SSL3_MASTER_KEY_DERIVE_PARAMS) +class CK_SSL3_KEY_MAT_OUT(Structure): + pass +if 'win' in sys.platform: + CK_SSL3_KEY_MAT_OUT._pack_ = 1 +CK_SSL3_KEY_MAT_OUT._fields_ = [ + ('hClientMacSecret', CK_OBJECT_HANDLE), + ('hServerMacSecret', CK_OBJECT_HANDLE), + ('hClientKey', CK_OBJECT_HANDLE), + ('hServerKey', CK_OBJECT_HANDLE), + ('pIVClient', CK_BYTE_PTR), + ('pIVServer', CK_BYTE_PTR), +] +CK_SSL3_KEY_MAT_OUT_PTR = POINTER(CK_SSL3_KEY_MAT_OUT) +class CK_SSL3_KEY_MAT_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_SSL3_KEY_MAT_PARAMS._pack_ = 1 +CK_SSL3_KEY_MAT_PARAMS._fields_ = [ + ('ulMacSizeInBits', CK_ULONG), + ('ulKeySizeInBits', CK_ULONG), + ('ulIVSizeInBits', CK_ULONG), + ('bIsExport', CK_BBOOL), + ('RandomInfo', CK_SSL3_RANDOM_DATA), + ('pReturnedKeyMaterial', CK_SSL3_KEY_MAT_OUT_PTR), +] +CK_SSL3_KEY_MAT_PARAMS_PTR = POINTER(CK_SSL3_KEY_MAT_PARAMS) +class CK_TLS_PRF_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_TLS_PRF_PARAMS._pack_ = 1 +CK_TLS_PRF_PARAMS._fields_ = [ + ('pSeed', CK_BYTE_PTR), + ('ulSeedLen', CK_ULONG), + ('pLabel', CK_BYTE_PTR), + ('ulLabelLen', CK_ULONG), + ('pOutput', CK_BYTE_PTR), + ('pulOutputLen', CK_ULONG_PTR), +] +CK_TLS_PRF_PARAMS_PTR = POINTER(CK_TLS_PRF_PARAMS) +class CK_WTLS_RANDOM_DATA(Structure): + pass +if 'win' in sys.platform: + CK_WTLS_RANDOM_DATA._pack_ = 1 +CK_WTLS_RANDOM_DATA._fields_ = [ + ('pClientRandom', CK_BYTE_PTR), + ('ulClientRandomLen', CK_ULONG), + ('pServerRandom', CK_BYTE_PTR), + ('ulServerRandomLen', CK_ULONG), +] +CK_WTLS_RANDOM_DATA_PTR = POINTER(CK_WTLS_RANDOM_DATA) +class CK_WTLS_MASTER_KEY_DERIVE_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_WTLS_MASTER_KEY_DERIVE_PARAMS._pack_ = 1 +CK_WTLS_MASTER_KEY_DERIVE_PARAMS._fields_ = [ + ('DigestMechanism', CK_MECHANISM_TYPE), + ('RandomInfo', CK_WTLS_RANDOM_DATA), + ('pVersion', CK_BYTE_PTR), +] +CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_WTLS_MASTER_KEY_DERIVE_PARAMS) +class CK_WTLS_PRF_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_WTLS_PRF_PARAMS._pack_ = 1 +CK_WTLS_PRF_PARAMS._fields_ = [ + ('DigestMechanism', CK_MECHANISM_TYPE), + ('pSeed', CK_BYTE_PTR), + ('ulSeedLen', CK_ULONG), + ('pLabel', CK_BYTE_PTR), + ('ulLabelLen', CK_ULONG), + ('pOutput', CK_BYTE_PTR), + ('pulOutputLen', CK_ULONG_PTR), +] +CK_WTLS_PRF_PARAMS_PTR = POINTER(CK_WTLS_PRF_PARAMS) +class CK_WTLS_KEY_MAT_OUT(Structure): + pass +if 'win' in sys.platform: + CK_WTLS_KEY_MAT_OUT._pack_ = 1 +CK_WTLS_KEY_MAT_OUT._fields_ = [ + ('hMacSecret', CK_OBJECT_HANDLE), + ('hKey', CK_OBJECT_HANDLE), + ('pIV', CK_BYTE_PTR), +] +CK_WTLS_KEY_MAT_OUT_PTR = POINTER(CK_WTLS_KEY_MAT_OUT) +class CK_WTLS_KEY_MAT_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_WTLS_KEY_MAT_PARAMS._pack_ = 1 +CK_WTLS_KEY_MAT_PARAMS._fields_ = [ + ('DigestMechanism', CK_MECHANISM_TYPE), + ('ulMacSizeInBits', CK_ULONG), + ('ulKeySizeInBits', CK_ULONG), + ('ulIVSizeInBits', CK_ULONG), + ('ulSequenceNumber', CK_ULONG), + ('bIsExport', CK_BBOOL), + ('RandomInfo', CK_WTLS_RANDOM_DATA), + ('pReturnedKeyMaterial', CK_WTLS_KEY_MAT_OUT_PTR), +] +CK_WTLS_KEY_MAT_PARAMS_PTR = POINTER(CK_WTLS_KEY_MAT_PARAMS) +class CK_CMS_SIG_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_CMS_SIG_PARAMS._pack_ = 1 +CK_CMS_SIG_PARAMS._fields_ = [ + ('certificateHandle', CK_OBJECT_HANDLE), + ('pSigningMechanism', CK_MECHANISM_PTR), + ('pDigestMechanism', CK_MECHANISM_PTR), + ('pContentType', CK_UTF8CHAR_PTR), + ('pRequestedAttributes', CK_BYTE_PTR), + ('ulRequestedAttributesLen', CK_ULONG), + ('pRequiredAttributes', CK_BYTE_PTR), + ('ulRequiredAttributesLen', CK_ULONG), +] +CK_CMS_SIG_PARAMS_PTR = POINTER(CK_CMS_SIG_PARAMS) +class CK_KEY_DERIVATION_STRING_DATA(Structure): + pass +if 'win' in sys.platform: + CK_KEY_DERIVATION_STRING_DATA._pack_ = 1 +CK_KEY_DERIVATION_STRING_DATA._fields_ = [ + ('pData', CK_BYTE_PTR), + ('ulLen', CK_ULONG), +] +CK_KEY_DERIVATION_STRING_DATA_PTR = POINTER(CK_KEY_DERIVATION_STRING_DATA) +CK_EXTRACT_PARAMS = CK_ULONG +CK_EXTRACT_PARAMS_PTR = POINTER(CK_EXTRACT_PARAMS) +CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE = CK_ULONG +CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR = POINTER(CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE) +CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE = CK_ULONG +CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR = POINTER(CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE) +class CK_PKCS5_PBKD2_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_PKCS5_PBKD2_PARAMS._pack_ = 1 +CK_PKCS5_PBKD2_PARAMS._fields_ = [ + ('saltSource', CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE), + ('pSaltSourceData', CK_VOID_PTR), + ('ulSaltSourceDataLen', CK_ULONG), + ('iterations', CK_ULONG), + ('prf', CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE), + ('pPrfData', CK_VOID_PTR), + ('ulPrfDataLen', CK_ULONG), + ('pPassword', CK_UTF8CHAR_PTR), + ('usPasswordLen', CK_ULONG), +] +CK_PKCS5_PBKD2_PARAMS_PTR = POINTER(CK_PKCS5_PBKD2_PARAMS) +CK_OTP_PARAM_TYPE = CK_ULONG +CK_PARAM_TYPE = CK_OTP_PARAM_TYPE +class CK_OTP_PARAM(Structure): + pass +if 'win' in sys.platform: + CK_OTP_PARAM._pack_ = 1 +CK_OTP_PARAM._fields_ = [ + ('type', CK_OTP_PARAM_TYPE), + ('pValue', CK_VOID_PTR), + ('usValueLen', CK_ULONG), +] +CK_OTP_PARAM_PTR = POINTER(CK_OTP_PARAM) +class CK_OTP_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_OTP_PARAMS._pack_ = 1 +CK_OTP_PARAMS._fields_ = [ + ('pParams', CK_OTP_PARAM_PTR), + ('ulCount', CK_ULONG), +] +CK_OTP_PARAMS_PTR = POINTER(CK_OTP_PARAMS) +class CK_OTP_SIGNATURE_INFO(Structure): + pass +if 'win' in sys.platform: + CK_OTP_SIGNATURE_INFO._pack_ = 1 +CK_OTP_SIGNATURE_INFO._fields_ = [ + ('pParams', CK_OTP_PARAM_PTR), + ('ulCount', CK_ULONG), +] +CK_OTP_SIGNATURE_INFO_PTR = POINTER(CK_OTP_SIGNATURE_INFO) +class CK_KIP_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_KIP_PARAMS._pack_ = 1 +CK_KIP_PARAMS._fields_ = [ + ('pMechanism', CK_MECHANISM_PTR), + ('hKey', CK_OBJECT_HANDLE), + ('pSeed', CK_BYTE_PTR), + ('ulSeedLen', CK_ULONG), +] +CK_KIP_PARAMS_PTR = POINTER(CK_KIP_PARAMS) +if 'win' in sys.platform: + CK_AES_CTR_PARAMS._pack_ = 1 +CK_AES_CTR_PARAMS._fields_ = [ + ('ulCounterBits', CK_ULONG), + ('cb', CK_BYTE * 16), +] +CK_AES_CTR_PARAMS_PTR = POINTER(CK_AES_CTR_PARAMS) +class CK_CAMELLIA_CTR_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_CAMELLIA_CTR_PARAMS._pack_ = 1 +CK_CAMELLIA_CTR_PARAMS._fields_ = [ + ('ulCounterBits', CK_ULONG), + ('cb', CK_BYTE * 16), +] +CK_CAMELLIA_CTR_PARAMS_PTR = POINTER(CK_CAMELLIA_CTR_PARAMS) +class CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 +CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 16), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS) +class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): + pass +if 'win' in sys.platform: + CK_ARIA_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 +CK_ARIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ + ('iv', CK_BYTE * 16), + ('pData', CK_BYTE_PTR), + ('length', CK_ULONG), +] +CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_ARIA_CBC_ENCRYPT_DATA_PARAMS) + +# values for enumeration 'fwResultCode' +fwResultCode = c_int # enum + +# values for enumeration 'eInitMsgs' +eInitMsgs = c_int # enum +SInt8 = c_byte +SInt16 = c_short +SInt32 = c_long +SInt = c_int +SInt64 = c_longlong +UInt8 = c_ubyte +UInt16 = c_ushort +UInt32 = c_ulong +UInt = c_uint +ULong = c_ulong +UInt64 = c_ulonglong +Int8 = c_char +Int16 = c_short +Int32 = c_long +Int = c_int +Int64 = c_longlong +Float32 = c_float +Float64 = c_double +Float = Float64 +Byte = UInt8 +BYTE = UInt8 +HalfWord = UInt16 +Word = UInt32 +PointerDifference = SInt32 +SizeType = UInt +Boolean = UInt8 +class swapper(Union): + pass +if 'win' in sys.platform: + swapper._pack_ = 1 +swapper._fields_ = [ + ('bytes', c_char * 4), + ('words', c_int), +] +HANDLE = c_int +__all__ = ['RC_MANUFACTURING_NO_CONFIG_AVAILABLE', + 'CK_ECMQV_DERIVE_PARAMS_PTR', + 'LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID', + 'CA_InvokeService', 'CK_VERSION_PTR', + 'CA_GetSecondarySlot', 'LUNA_RET_TOKEN_LOCKED_OUT_CA', + 'RC_RESET_FAILED', 'HSM_STATS_PARAMS', + 'LUNA_RET_TOKEN_LOCKED_OUT_CL', + 'CK_CA_SetDestructiveHSMPolicy', 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE', - 'CK_CA_HAAnswerMofNChallenge', 'CK_CA_InvokeServiceInit', - 'CK_ECDH1_DERIVE_PARAMS', 'C_UnwrapKey', - 'CA_DismantleRemotePED', 'CA_PerformModuleCall', - 'CA_SetApplicationID', 'CK_OTP_PARAM', - 'CA_LoadEncryptedModule', 'CA_MTKZeroize', - 'CK_C_VerifyInit', 'CK_LKM_TOKEN_ID_PTR', - 'CK_RC2_PARAMS_PTR', 'CK_WTLS_PRF_PARAMS_PTR', - 'CK_C_CancelFunction', 'CK_CA_GetContainerStatus', - 'CK_CA_FactoryReset', 'CK_CA_Restart', - 'CK_C_VerifyRecover', 'CK_CA_SetDestructiveHSMPolicy', - 'CK_CA_SpRawRead', 'C_SetAttributeValue', - 'CK_RC2_CBC_PARAMS_PTR', 'CA_CloseAllSecondarySessions', - 'CK_C_GetOperationState', 'CK_C_SetOperationState', - 'CK_CA_CloseApplicationIDForContainer', 'C_VerifyFinal', - 'CK_CA_LogVerifyFile', 'CK_TOKEN_INFO', - 'CK_RSA_PKCS_OAEP_PARAMS', - 'CK_CA_CloseAllSecondarySessions', 'CK_DATE', - 'CA_ReadCommonStore', + 'CK_CA_HAAnswerMofNChallenge', 'LUNA_RET_CB_TIMEOUT', + 'CK_X9_42_DH2_DERIVE_PARAMS_PTR', 'ResultCodeValue', + 'LUNA_RET_WRAPPING_KEY_SIZE_RANGE', 'LUNA_RET_BAD_DAC', + 'CK_KEA_DERIVE_PARAMS_PTR', + 'CK_CA_DisableUnauthTokenInsertion', + 'RC_SSL_CREATE_SSL_ERROR', 'C_UnwrapKey', 'BYTE', + 'LUNA_RET_BAD_DAK', 'CK_CA_GetRemotePEDVectorStatus', + 'CA_PerformModuleCall', + 'LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID', + 'LUNA_HIFN_UNKNOWN_ALGORITHM', 'LUNA_RET_HA_NOT_SUPPORTED', + 'CK_CA_STCGetAdminPubKey', 'CA_OpenSession', + 'LUNA_RET_VECTOR_OF_DIFFERENT_SET', 'CA_MTKZeroize', + 'RC_NO_BUFFER', 'CK_LKM_TOKEN_ID_PTR', + 'RC_USER_NAME_IN_USE', 'CA_SetContainerPolicy', + 'CK_WTLS_PRF_PARAMS_PTR', 'C_FindObjectsFinal', + 'CA_SetPedId', 'CK_C_CancelFunction', + 'LUNA_RET_ECC_NOT_SUPPORTED', 'CK_CA_FactoryReset', + 'MSG_GENERATING_NEW_TVK_FAILED', 'CK_C_GetSessionInfo', + 'CK_C_VerifyRecover', 'CK_C_EncryptFinal', + 'RC_UNABLE_TO_CONNECT', 'CK_CA_ModifyMofN', + 'C_SetAttributeValue', + 'RC_SSL_CERT_VERIFICATION_LOCATION_ERROR', + 'CK_RC2_CBC_PARAMS_PTR', + 'LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE', + 'CA_ManualKCV', 'LUNA_RET_SM_ACCESS_ID_INVALID', + 'LUNA_RET_CL_QUEUE_LOCATION_ERROR', + 'RC_SSL_INVALID_CERT_STRUCTURE', 'CK_RSA_PKCS_OAEP_PARAMS', + 'LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE', + 'LUNA_RET_HA_USER_NOT_INITIALIZED', + 'LUNA_RET_MD5_SELF_TEST_FAILURE', + 'LUNA_RET_OPERATION_NOT_INITIALIZED', 'CA_Deactivate', + 'LUNA_RET_LOG_BAD_TIME', 'CA_GetHSMCapabilitySetting', + 'LUNA_RET_SM_CONTEXT_NOT_ALLOCATED', 'LUNA_RET_CB_ABORTED', + 'MSG_NVRAM_READ_FAILED', + 'CK_CA_CloseApplicationIDForContainer', + 'CA_EncodeECPrimeParams', 'RC_FILE_READ_ONLY', + 'LUNA_RET_HOK_MISSING', 'RC_USB_PED_OUT_OF_SYNC', + 'CK_CA_GetContainerCapabilitySet', + 'LUNA_RET_WEIGHT_TOO_SMALL', + 'LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO', + 'CK_SSL3_KEY_MAT_PARAMS_PTR', 'CK_DATE', 'C_CloseSession', + 'LUNA_RET_TEMPLATE_INCONSISTENT', + 'RC_NON_CRYPTOKI_ELEMENT_CLONE', 'CA_GetConfigurationElementDescription', - 'CK_WTLS_PRF_PARAMS', 'CK_RC2_MAC_GENERAL_PARAMS', - 'CK_CA_CapabilityUpdate', 'CK_SESSION_HANDLE', - 'CK_RC5_PARAMS', 'CK_SLOT_INFO', 'C_GetInfo', - 'CK_CA_SpRawWrite', 'CK_C_EncryptInit', 'C_Login', - 'CK_CA_CloneAllObjectsToSession', 'C_GetMechanismInfo', - 'CK_CA_GetConfigurationElementDescription', 'CK_C_SetPIN', - 'CA_QueryLicense', 'C_Logout', 'C_Finalize', - 'C_CreateObject', 'CK_ATTRIBUTE_PTR', 'CK_VERSION', - 'CK_CA_GetFPV', 'CK_SESSION_HANDLE_PTR', - 'CK_CA_FirmwareUpdate', 'CK_CA_OpenSession', - 'CK_RC2_MAC_GENERAL_PARAMS_PTR', 'CA_CloseApplicationID', - 'C_WaitForSlotEvent', 'CA_Restart', 'CK_HW_FEATURE_TYPE', - 'CA_CloneAsTargetInit', 'C_FindObjects', 'CK_C_Logout', - 'CK_VOID_PTR', 'CK_C_Sign', 'CK_CA_GetTunnelSlotNumber', - 'CA_HAGetLoginChallenge', 'CA_CreateContainer', - 'CA_EncodeECParamsFromFile', 'CK_CA_ReadCommonStore', - 'CA_LogSetConfig', 'CK_MECHANISM_INFO', 'CK_C_GetInfo', - 'CKCA_MODULE_ID_PTR', 'CK_C_INITIALIZE_ARGS', 'CK_LONG', - 'CA_MOFN_GENERATION', 'CKCA_MODULE_ID', - 'CA_GetTokenCertificateInfo', 'C_Decrypt', 'CA_InitAudit', - 'CK_C_SignEncryptUpdate', 'CA_GetExtendedTPV', - 'CK_SFNT_CA_FUNCTION_LIST_PTR', - 'CK_SKIPJACK_PRIVATE_WRAP_PTR', 'CA_GetContainerPolicySet', - 'CK_EXTRACT_PARAMS_PTR', 'CA_LoadModule', - 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR', - 'CA_FirmwareRollback', - 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR', 'CK_CA_SetKCV', - 'CK_CA_GetObjectUID', 'CK_OBJECT_HANDLE_PTR', - 'CA_LogExportSecret', 'CA_Deactivate', - 'C_DecryptDigestUpdate', - 'CA_OpenApplicationIDForContainer', 'C_SetOperationState', - 'CK_X9_42_DH_KDF_TYPE', 'CK_AES_GCM_PARAMS', - 'CK_CA_ConfigureRemotePED', 'CK_HA_STATE_PTR', - 'CA_HAActivateMofN', 'CK_CA_MultisignValue', - 'CA_SetHSMPolicies', 'CA_GetHSMCapabilitySet', - 'CA_UnloadModule', 'CK_KIP_PARAMS', 'CK_CA_HAInit', - 'CA_LKMReceiverResponse', 'CK_CERTIFICATE_TYPE', - 'CK_XOR_BASE_DATA_KDF_PARAMS', 'CK_OTP_PARAM_PTR', - 'CK_C_InitPIN', 'CK_AES_CBC_PAD_EXTRACT_PARAMS', - 'CK_X9_42_MQV_DERIVE_PARAMS', 'CK_CA_GetHAState', - 'CA_SetContainerPolicy', 'C_CloseAllSessions', - 'CA_Extract', 'CK_OBJECT_CLASS', - 'CK_SKIPJACK_RELAYX_PARAMS_PTR', 'C_VerifyRecover', - 'CA_GetModuleInfo', 'CK_FLAGS', 'CK_TLS_PRF_PARAMS', - 'CK_CA_FirmwareRollback', 'CK_WTLS_KEY_MAT_OUT', - 'CK_CMS_SIG_PARAMS', 'CK_CA_GetExtendedTPV', - 'CA_GetObjectHandle', 'CK_CA_GetContainerName', - 'CA_GetRemotePEDVectorStatus', 'CK_C_GetFunctionList', - 'CK_CA_SetHSMPolicy', 'CK_SLOT_ID', 'CK_CA_LogGetStatus', - 'CA_CapabilityUpdate', 'CK_CA_SIMMultiSign', - 'CK_C_DigestEncryptUpdate', 'C_GetSlotInfo', - 'CK_HA_MEMBER', 'C_VerifyRecoverInit', - 'CA_GetTokenInsertionCount', 'C_DigestKey', - 'CK_C_OpenSession', 'CK_CA_ResetDevice', - 'CK_CA_LogExternal', 'CA_IndirectLogin', - 'C_FindObjectsInit', 'CA_SIMExtract', - 'CK_C_FindObjectsInit', 'CK_RSA_PKCS_OAEP_SOURCE_TYPE', - 'CK_UNLOCKMUTEX', 'CK_CA_GetNumberOfAllowedContainers', - 'CK_CA_SIMExtract', 'CK_ULONG_PTR', 'CK_CA_MTKResplit', - 'CK_CA_GetFunctionList', 'CKCA_MODULE_INFO', - 'CK_CA_HAGetMasterPublic', 'C_PerformSelfTest', + 'LUNA_RET_PED_UNPLUGGED', 'CK_WTLS_PRF_PARAMS', + 'CK_RC2_MAC_GENERAL_PARAMS', + 'LUNA_RET_HIFN6500_RNG_TIMEOUT', + 'LUNA_RET_VECTOR_TOO_LARGE', + 'MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED', + 'LUNA_RET_KCV_PARAMETER_MISSING', 'CA_GetMofNStatus', + 'LUNA_RET_KEY_INDIGESTIBLE', 'LUNA_RET_HSM_STORAGE_FULL', + 'CK_SLOT_INFO', 'CA_ConfigureRemotePED', 'CA_GetTPV', + 'LUNA_RET_PED_ID_INVALID', 'CK_C_EncryptInit', + 'CK_CA_LogImportSecret', + 'MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK', + 'LUNA_RET_CAN_NOT_CREATE_SECRET_KEY', + 'CK_CA_GetHSMPolicySetting', + 'CK_CA_GetUnauthTokenInsertionStatus', + 'LUNA_RET_KCDSA_SELF_TEST_FAILURE', + 'LUNA_RET_TOKEN_LOCKED_OUT_STC', 'CK_C_SetPIN', + 'CA_QueryLicense', 'CK_C_INITIALIZE_ARGS', + 'LUNA_RET_M_OF_N_ACTIVATION_REQUIRED', 'C_Logout', + 'LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE', + 'LUNA_RET_KEY_TYPE_INCONSISTENT', + 'LUNA_RET_SPLIT_ID_INVALID', + 'CK_AES_CBC_PAD_EXTRACT_PARAMS', + 'LUNA_RET_MECHANISM_INVALID', + 'MSG_TVK_WAS_LOST_DUE_TO_TAMPER', 'LUNA_RET_DEVICE_ERROR', + 'RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR', 'CK_ATTRIBUTE_PTR', + 'CK_VERSION', 'CK_C_GetOperationState', 'fwResultCode', + 'RC_DATA_CORRUPTED', 'LUNA_RET_KEY_UNEXTRACTABLE', + 'RC_USB_PED_NOT_FOUND', 'CK_CA_GetFPV', + 'CK_SESSION_HANDLE_PTR', 'Int32', + 'LUNA_RET_CL_QUEUE_OVERLAP_ERROR', 'LUNA_RET_BAD_SN', + 'CA_GetTokenInsertionCount', 'CK_CA_InitRolePIN', + 'CK_MECHANISM_PTR', 'LUNA_RET_CB_HIOS_RECV_TIMEOUT', + 'CK_ECDH2_DERIVE_PARAMS_PTR', 'CK_RC5_CBC_PARAMS', + 'C_WaitForSlotEvent', 'CK_C_CloseSession', + 'CA_LKMInitiatorComplete', 'CA_CloneAsTargetInit', + 'CK_WTLS_KEY_MAT_OUT', 'CA_GetContainerList', + 'LUNA_RET_TOKEN_LOCKED_OUT_CCM', 'MSG_NVRAM_WRITE_FAILED', + 'LUNA_RET_M_OF_N_PARAMETER_EXIST', + 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS', 'UInt64', + 'LUNA_RET_TOKEN_LOCKED_OUT_MM', + 'LUNA_RET_RC2_SELF_TEST_FAILURE', 'CK_VOID_PTR', + 'CK_C_Sign', 'CK_CA_GetTunnelSlotNumber', + 'CA_HAGetLoginChallenge', 'CA_EncodeECChar2Params', + 'LUNA_RET_MTK_ZEROIZED', 'CK_CA_ReadCommonStore', + 'LUNA_RET_ECC_UNKNOWN_CURVE', 'RC_SSL_WANT_READ_ERROR', + 'LUNA_RET_CCM_UPDATE_DENIED', + 'LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT', + 'LUNA_RET_GENERAL_ERROR', 'SInt32', + 'MSG_TVK_TIMESTAMP_RECOVERY_FAILED', 'CKCA_MODULE_ID_PTR', + 'LUNA_RET_SM_ACCESS_ALREADY_EXISTS', 'CK_LONG', + 'CA_Extract', 'CA_MOFN_GENERATION', 'RC_FILE_LOCK_ERROR', + 'CA_GetTokenCertificateInfo', + 'LUNA_RET_LICENSE_CAPACITY_EXCEEDED', + 'LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE', 'C_Decrypt', + 'MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER', + 'LUNA_RET_INVALID_PADDING_TYPE', 'CK_C_VerifyInit', + 'CK_CA_ResetPIN', 'CK_C_SignEncryptUpdate', + 'CK_C_Initialize', 'MSG_RTC_LOST_ALL_POWER', + 'LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT', + 'CK_SFNT_CA_FUNCTION_LIST_PTR', 'RC_SSL_SYSCALL_ERROR', + 'RC_CACHE_DIRTY', 'CK_SKIPJACK_PRIVATE_WRAP_PTR', + 'LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH', + 'CK_MAC_GENERAL_PARAMS_PTR', 'CK_EXTRACT_PARAMS_PTR', + 'LUNA_RET_RM_CONFIG_ILLEGAL', 'CA_LoadModule', + 'LUNA_RET_ECC_DAK_MISSING', 'LUNA_RET_BAD_MAC', + 'LUNA_RET_RM_NO_MEMORY', 'RC_GROUP_NAME_INVALID', + 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR', 'CA_LogGetConfig', + 'LUNA_RET_CB_RETRY', 'LUNA_RET_MM_INVALID_USAGE', + 'CK_CA_GetObjectUID', 'MSG_RESTART', + 'CK_OBJECT_HANDLE_PTR', 'LUNA_RET_ISES_RNG_TEST_FAILED', + 'CK_ECDH1_DERIVE_PARAMS', + 'MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC', + 'RC_FILE_NAME_INVALID', 'LUNA_RET_BUFFER_TOO_SMALL', + 'CK_CA_SIMExtract', 'C_DecryptDigestUpdate', + 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS', 'C_EncryptUpdate', + 'CK_CA_LogExportSecret', 'C_SetOperationState', + 'LUNA_RET_MISSING_VALUE_FOR_M', + 'LUNA_RET_MISSING_VALUE_FOR_N', 'CK_CA_InvokeServiceFinal', + 'CK_AES_GCM_PARAMS', 'CK_CA_ConfigureRemotePED', + 'LUNA_RET_CL_TRANSMISSION_ERROR', + 'LUNA_RET_OBJECT_HANDLE_INVALID', + 'CA_HAAnswerLoginChallenge', 'CK_FLAGS', + 'CK_CA_MultisignValue', 'CA_SetHSMPolicies', + 'RC_FAILED_TO_CREATE_THREAD', 'LUNA_RET_KEY_NOT_ACTIVE', + 'HANDLE', 'CK_CA_STCDeregister', 'CA_UnloadModule', + 'LUNA_RET_DATA_INVALID', 'CK_XOR_BASE_DATA_KDF_PARAMS_PTR', + 'Float64', 'CK_CA_GetContainerStatus', 'CA_HAActivateMofN', + 'LUNA_RET_PED_DEK_INVALID', 'CK_CA_HAInit', 'Int', + 'CA_LKMReceiverResponse', 'LUNA_RET_LOG_RESYNC_NEEDED', + 'CK_CA_SpRawWrite', 'CK_XOR_BASE_DATA_KDF_PARAMS', + 'LUNA_RET_TUK_PARAMETER_MISSING', 'CK_OTP_PARAM_PTR', + 'CK_C_InitPIN', 'RC_SOCKET_ERROR', 'CK_RC2_PARAMS_PTR', + 'LUNA_RET_HIFN6500_RESET_TIMEOUT', + 'CA_GetNumberOfAllowedContainers', 'LUNA_RET_N_TOO_LARGE', + 'RC_SSL_WANT_WRITE_ERROR', 'CK_CA_GetHAState', + 'CK_CA_InitAudit', 'C_CloseAllSessions', + 'LUNA_RET_KEY_PARITY', 'RC_SSL_GET_CERTIFICATE_ERROR', + 'CA_InitAudit', 'CK_OTP_PARAMS_PTR', 'CA_M_OF_N_STATUS', + 'C_SignUpdate', 'CK_SKIPJACK_RELAYX_PARAMS_PTR', + 'LUNA_RET_STATE_UNSAVEABLE', 'CK_C_VerifyRecoverInit', + 'LUNA_RET_MAC_MISSING', 'C_VerifyRecover', + 'CA_GetModuleInfo', + 'LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID', + 'CK_TLS_PRF_PARAMS', 'LUNA_RET_OPERATION_RESTRICTED', + 'PointerDifference', 'LUNA_RET_SM_UNKNOWN_ACCESS_TYPE', + 'MSG_RTC_CANT_INITIALIZE_I2C', + 'LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL', + 'CK_SSL3_RANDOM_DATA', + 'LUNA_RET_STORAGE_TYPE_INCONSISTENT', 'CK_C_GetInfo', + 'C_InitPIN', 'CK_C_Login', 'CK_WTLS_KEY_MAT_PARAMS', + 'CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CK_CA_GetExtendedTPV', 'CA_GetObjectHandle', + 'CK_C_Decrypt', 'CA_GetRemotePEDVectorStatus', + 'CK_C_GetFunctionList', + 'LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE', + 'LUNA_RET_TOKEN_LOCKED_OUT_PM', 'LUNA_RET_HIFN_DMA_ERROR', + 'LUNA_RET_CANCEL', 'LUNA_RET_RNG_SELF_TEST_FAILURE', + 'CK_CA_TokenDelete', 'CK_SLOT_ID', 'CK_CA_LogGetStatus', + 'CK_CA_FindAdminSlotForSlot', 'CA_CapabilityUpdate', + 'CA_GetExtendedTPV', 'CK_C_DigestEncryptUpdate', + 'CK_CA_IsMofNRequired', 'CA_FirmwareUpdate', + 'RC_CERT_TYPE_INVALID', 'C_VerifyRecoverInit', + 'LUNA_RET_PED_CLIENT_NOT_RUNNING', + 'LUNA_RET_HIFN6500_RNG_UNDERFLOW', 'RC_OBJECT_NOT_IN_LIST', + 'CK_HA_MEMBER_PTR', 'CA_SetApplicationID', + 'LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE', 'CT_Token', + 'C_DigestKey', 'CK_C_OpenSession', + 'LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT', + 'MSG_TVK_TIMESTAMP_CORRUPTED', + 'LUNA_RET_MM_INVALID_HANDLE', 'CK_CA_LogExternal', + 'SInt16', 'CA_IndirectLogin', + 'LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT', + 'LUNA_RET_INVALID_PRIVATE_KEY_TYPE', 'CA_SIMExtract', + 'CK_CA_CloseSecureToken', 'CK_SKIPJACK_RELAYX_PARAMS', + 'CA_SetDestructiveHSMPolicy', 'CK_C_FindObjectsInit', + 'CA_OpenSecureToken', + 'LUNA_RET_WRAPPING_KEY_HANDLE_INVALID', + 'LUNA_RET_SM_UNKNOWN_COMMAND', + 'CK_RSA_PKCS_OAEP_SOURCE_TYPE', 'CK_UNLOCKMUTEX', + 'CK_CA_GetNumberOfAllowedContainers', 'CK_OTP_PARAM', + 'LUNA_RET_INVALID_FUF_TARGET', 'LUNA_RET_ARGUMENTS_BAD', + 'C_DigestEncryptUpdate', + 'RC_MANUFACTURING_TOKEN_NOT_PRESENT', 'RC_SLOT_ID_INVALID', + 'CK_CA_MTKResplit', 'LUNA_INVALID_PACKET_LAYOUT', + 'CK_OTP_PARAMS', 'SInt8', 'CK_CA_GetFunctionList', + 'LastFirmwareCode', 'LUNA_RET_MD2_SELF_TEST_FAILURE', + 'RC_PARTITION_LOCKED', 'CA_GetSecureElementMeta', 'CK_CA_CloneAsTarget', 'CK_CA_RetrieveLicenseList', - 'CK_UTF8CHAR_PTR', 'CA_LogEraseAll', 'CA_CloneAsSource', - 'CK_ECMQV_DERIVE_PARAMS', 'CK_CA_LKMReceiverComplete', - 'CA_InvokeServiceSinglePart', 'CK_KDF_PRF_ENCODING_SCHEME', - 'CK_C_Finalize', 'CA_MOFN_ACTIVATION_PTR', 'CK_KEY_TYPE', - 'CK_RSA_PKCS_PSS_PARAMS', 'CA_GetFunctionList', - 'CK_FUNCTION_LIST', 'CK_C_DecryptInit', - 'CK_CA_UnloadModule', 'CA_GetTPV', 'CA_OpenSession', + 'CK_CA_HALogin', 'LUNA_RET_NOT_FOUND', + 'CK_C_SetOperationState', + 'MSG_RTC_CONFIGURATION_CORRUPTED', + 'CK_CA_InvokeServiceInit', 'LUNA_RET_SAVED_STATE_INVALID', + 'CA_CloneAsSource', 'CK_ECMQV_DERIVE_PARAMS', + 'CK_CA_LKMReceiverComplete', 'CA_InvokeServiceSinglePart', + 'CK_KDF_PRF_ENCODING_SCHEME', 'LUNA_RET_MAX_OBJECT_COUNT', + 'CA_MOFN_ACTIVATION_PTR', + 'MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS', + 'LUNA_RET_M_TOO_LARGE', 'UInt16', + 'LUNA_RET_CB_HIOS_HANDLE_INVALID', 'RC_PIN_INVALID', + 'CK_CA_SetHSMPolicy', 'RC_SOCKET_CLOSED', + 'CK_CA_LockClusteredSlot', 'RC_ENDOFLIST', 'UInt32', + 'LUNA_RET_LOG_NO_KCV', 'CK_C_DecryptInit', + 'LUNA_RET_DAC_POLICY_PID_MISMATCH', 'CK_CA_GetTokenStatus', + 'LUNA2_RET_HIFN_RESET_ERROR', 'RC_UNEXPECTED', + 'LUNA_RET_HIFN6500_ALU_TIMEOUT', 'CK_C_InitToken', 'CA_InvokeServiceFinal', 'CK_CA_EncodeECParamsFromFile', - 'CA_LockClusteredSlot', 'CK_CA_RestartForContainer', - 'CK_INFO_PTR', 'CA_FactoryReset', - 'CA_SetUserContainerName', 'CK_TLS_PRF_PARAMS_PTR', - 'CA_DestroyMultipleObjects', 'CK_PBE_PARAMS', - 'CK_CA_InsertMaskedObject', 'CA_GetHSMStorageInformation', - 'CA_EncodeECPrimeParams', 'C_OpenSession', - 'CK_CA_SetUserContainerName', - 'CA_DeleteContainerWithHandle', 'CA_CloneObject', - 'CA_MOFN_ACTIVATION', 'CA_GetNumberOfAllowedContainers', + 'CA_LockClusteredSlot', 'LUNA_RET_SM_NOT_LOGGED_IN', + 'CK_CA_SIMInsert', 'CK_CA_RestartForContainer', + 'LUNA_RET_MISSING_COMMAND_PARAMETER', + 'LUNA_RET_KEY_EXTRACTABLE', + 'LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE', 'CA_FactoryReset', + 'CA_LoadEncryptedModule', 'CA_SetUserContainerName', + 'CK_TLS_PRF_PARAMS_PTR', + 'MSG_RTC_MSG_NVRAM_ZAPPING_FAILED', + 'CK_CA_InsertMaskedObject', 'RC_MEMORY_ALLOCATION', + 'CK_CA_OpenSecureToken', 'LUNA_RET_SM_PIN_EXPIRED', + 'C_VerifyFinal', 'C_DeriveKey', 'C_OpenSession', + 'CK_CA_SetUserContainerName', 'RC_OBJECT_ALREADY_EXISTS', + 'LUNA_RET_SM_SESSION_REALLOC_ERROR', + 'MSG_ZEROIZING_AFTER_DECOMMISSION', 'CA_MOFN_ACTIVATION', + 'MSG_GENERATING_NEW_TVK_PASSED', 'C_Sign', + 'LUNA_RET_HIFN_INVALID_MAC_ALGORITHM', 'CA_WaitForSlotEvent', 'CA_ChoosePrimarySlot', - 'CK_CA_GetContainerCapabilitySet', - 'CK_WTLS_RANDOM_DATA_PTR', 'C_VerifyInit', - 'CK_C_CloseAllSessions', 'CK_RSA_PKCS_PSS_PARAMS_PTR', - 'CK_USER_TYPE', 'C_GetMechanismList', 'C_GetObjectSize', - 'C_GenerateRandom', 'CK_CA_DeleteContainerWithHandle', - 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR', 'CK_LOCKMUTEX', - 'CK_CA_SetHSMPolicies', 'CK_CA_GetRemotePEDVectorStatus', + 'CK_TOKEN_INFO', 'RC_BUFFER_TOO_SMALL', + 'RC_CLIENT_DISCONNECTED', 'CK_ECDH1_DERIVE_PARAMS_PTR', + 'LUNA_RET_INVALID_BOARD_TYPE', 'LUNA_RET_UNWRAPPING_ERROR', + 'RC_SERVER_DISCONNECTED', 'LUNA_RET_CB_PROT_DATA_INVALID', + 'LUNA_RET_LICENSE_ID_UNKNOWN', + 'LUNA_RET_KCDSA_PARAM_GEN_FAILURE', + 'CK_C_CloseAllSessions', 'LUNA_RET_CL_ALIGNMENT_ERROR', + 'LUNA_RET_HIFN_DMA_INVALID_REVISION', + 'LUNA_RET_TOKEN_NOT_PRESENT', 'CK_VOID_PTR_PTR', + 'CK_RSA_PKCS_PSS_PARAMS_PTR', 'CK_USER_TYPE', + 'C_DigestUpdate', 'C_GetMechanismList', 'CA_ResetDevice', + 'CK_C_DigestFinal', 'LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO', + 'LUNA_RET_SM_BAD_CONTEXT_NUMBER', 'RC_OPERATION_TIMED_OUT', + 'LUNA_RET_CL_COMMAND_MALFORMED', 'LUNA_RET_SFNT3120_ERROR', + 'LUNA_RET_LOG_BAD_RECORD_HMAC', 'CKCA_MODULE_ID', + 'LUNA_RET_MECHANISM_PARAM_INVALID', + 'LUNA_RET_SIM_VERSION_UNSUPPORTED', 'CK_CA_LoadModule', + 'LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION', + 'RC_UNKNOWN_COMMAND_VERSION', 'RC_CLIENT_MESSAGE_ERROR', + 'LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE', 'CK_ARIA_CTR_PARAMS', 'C_GetAttributeValue', - 'CK_CA_GetTime', 'CA_OpenApplicationID', - 'CK_CA_GenerateCloningKEV', 'CK_C_DecryptUpdate', - 'CK_CAMELLIA_CTR_PARAMS', 'CA_LogVerifyFile', - 'CA_M_OF_N_STATUS', 'CK_C_CloseSession', - 'CK_EC_ENC_SCHEME', 'CK_C_INITIALIZE_ARGS_PTR', - 'CK_CA_SetLKCV', 'CK_MECHANISM_INFO_PTR', + 'CK_CA_GetTime', 'MSG_ZEROIZING_AFTER_NO_SECURE_DATA', + 'CA_OpenApplicationID', 'LUNA_RET_TEMPLATE_INCOMPLETE', + 'LUNA_RET_CB_MUST_READ', 'LUNA_RET_WRAPPING_ERROR', + 'LUNA_RET_CCM_NOT_PRESENT', 'CA_ReadCommonStore', + 'CK_CA_GenerateCloningKEV', 'MSG_RTC_CANT_ACCESS', + 'CA_SwitchSecondarySlot', 'CK_CAMELLIA_CTR_PARAMS', + 'eInitMsgs', 'LUNA_RET_RETRY', + 'LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', + 'CA_LogVerifyFile', + 'RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR', 'CA_Restart', + 'CK_HA_MEMBER', 'CK_EC_ENC_SCHEME', + 'CK_C_INITIALIZE_ARGS_PTR', 'CK_CA_SetLKCV', + 'LUNA_RET_CB_HIOS_CANCELED', 'CK_MECHANISM_INFO_PTR', 'CA_DuplicateMofN', 'CK_CA_GetModuleList', - 'CK_DES_CTR_PARAMS', 'CK_AES_CBC_PAD_INSERT_PARAMS_PTR', - 'C_GetFunctionStatus', 'CK_CA_PerformModuleCall', - 'CA_GetClusterState', 'CK_OTP_PARAMS_PTR', - 'CK_C_SignRecoverInit', 'CK_CA_SetExtendedTPV', - 'CK_CA_SinglePartSign', 'CK_CA_CloseSecondarySession', - 'CK_C_SignFinal', 'CA_SetDestructiveHSMPolicy', - 'CA_ResetPIN', 'CK_CA_GetHSMPolicySet', 'CK_CA_MTKRestore', - 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS', 'CK_C_Digest', - 'CK_WTLS_KEY_MAT_OUT_PTR', 'CK_AES_GMAC_PARAMS', - 'CK_OBJECT_HANDLE', 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS', - 'C_SeedRandom', 'C_WrapKey', 'CA_RestartForContainer', - 'CK_PKCS5_PBKD2_PARAMS', 'CK_MAC_GENERAL_PARAMS', - 'CK_C_VerifyUpdate', 'CK_C_Verify', 'CA_CloneMofN', - 'CK_CA_SwitchSecondarySlot', 'CK_ATTRIBUTE_TYPE', - 'CK_CA_GetTokenCertificates', - 'CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR', - 'CK_CA_GetMofNStatus', 'CK_CA_GetRollbackFirmwareVersion', + 'LUNA_RET_CB_REMOTE_ABORT', 'CK_MAC_GENERAL_PARAMS', + 'LUNA_RET_TOKEN_LOCKED_OUT_SM', 'LUNA_RET_OK', + 'CK_AES_CBC_PAD_INSERT_PARAMS_PTR', 'C_GetFunctionStatus', + 'CK_CA_PerformModuleCall', 'CA_GetClusterState', + 'LUNA_RET_SIGNATURE_LEN_RANGE', 'CK_C_SignRecoverInit', + 'MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF', + 'C_GenerateKey', 'RC_DER_CLASS_INVALID', + 'CK_CA_SetExtendedTPV', 'CA_RetrieveLicenseList', + 'CK_CA_CloseSecondarySession', 'CK_CA_ResetDevice', + 'CA_DismantleRemotePED', 'CK_CA_FirmwareUpdate', + 'LUNA_RET_CB_HANDLE_INVALID', 'CA_ResetPIN', + 'CK_CA_GetHSMPolicySet', 'CK_CA_MTKRestore', + 'CK_OBJECT_CLASS', 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS', + 'CK_UTF8CHAR_PTR', 'CK_WTLS_KEY_MAT_OUT_PTR', + 'LUNA_RET_CONTAINER_LOCKED', + 'MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING', + 'CK_AES_GMAC_PARAMS', 'CK_OBJECT_HANDLE', + 'LUNA_RET_NOT_READY', 'CK_PBE_PARAMS_PTR', + 'LUNA_RET_ISES_TEST_VS_BSAFE_FAILED', 'C_SeedRandom', + 'swapper', 'CK_X9_42_DH_KDF_TYPE', 'Word', + 'LUNA_RET_SM_TSV_MISSING', 'C_WrapKey', + 'LUNA_RET_TOKEN_LOCKED_OUT', 'CK_CA_FirmwareRollback', + 'RC_GENERAL_ERROR', 'CA_RestartForContainer', 'Boolean', + 'LUNA_RET_KEY_HANDLE_INVALID', 'LUNA_RET_RNG_ERROR', + 'RC_OPERATION_WOULD_BLOCK', 'CK_DES_CTR_PARAMS', + 'C_PerformSelfTest', 'CK_CA_GetTokenCertificates', + 'RC_PARTITION_NOT_ACTIVATED', 'CK_CA_CapabilityUpdate', + 'LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE', + 'CK_ATTRIBUTE_TYPE', 'LUNA_RET_CB_HIOS_ID_INVALID', + 'CA_CloneMofN', 'CA_MTKGetState', 'CK_C_Verify', + 'CK_SESSION_HANDLE', 'CK_CA_GetMofNStatus', + 'CK_CA_GetRollbackFirmwareVersion', 'CK_CA_WriteCommonStore', 'CA_GetPedId', - 'CA_InitIndirectToken', - 'CK_CA_GetContainerCapabilitySetting', - 'CK_CA_GenerateMofN', 'CK_C_GetMechanismInfo', - 'CK_CA_GetPrimarySlot', 'CK_C_DigestFinal', - 'CK_X9_42_DH2_DERIVE_PARAMS', 'CA_LogExternal', - 'CA_ClonePrivateKey', 'CA_ManualKCV', 'CK_EC_MAC_SCHEME', - 'CK_CA_GetTokenCertificateInfo', 'CK_CA_DeleteContainer', - 'CK_CA_GetContainerPolicySet', 'C_CancelFunction', - 'CK_HA_STATUS', 'CK_CA_OpenApplicationIDForContainer', - 'CK_C_DigestKey', 'CA_ConfigureRemotePED', 'C_Initialize', - 'C_DestroyObject', 'CK_RSA_PKCS_OAEP_PARAMS_PTR', - 'CA_DeleteContainer', 'CK_ECDH1_DERIVE_PARAMS_PTR', - 'C_InitToken', 'CK_C_WrapKey', 'CA_EncodeECChar2Params', - 'CK_CA_ActivateMofN', + 'CK_OTP_PARAM_TYPE', 'LUNA_RET_VECTOR_DUPLICATE', + 'LUNA_RET_PE1746_ERROR', 'CA_InitIndirectToken', + 'CK_CA_GetContainerCapabilitySetting', 'CK_C_GetSlotInfo', + 'CK_CA_TokenInsert', 'CK_CA_GenerateMofN', + 'RC_SESSION_SCRIPT_EXISTS', 'CK_CA_GetPrimarySlot', + 'LUNA_RET_CITS_DAK_MISSING', + 'CA_SetDestructiveHSMPolicies', + 'LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE', + 'LUNA_RET_UNKNOWN_COMMAND', 'CA_LogExternal', + 'CA_ClonePrivateKey', 'CK_AES_CBC_PAD_INSERT_PARAMS', + 'CK_EC_MAC_SCHEME', 'CK_C_GetMechanismInfo', + 'CK_MECHANISM_TYPE_PTR', 'CK_CA_GetTokenCertificateInfo', + 'LUNA_RET_TSN_MISMATCH', 'RC_FILE_LOCK_FAILED', + 'LUNA_RET_SP_RX_ERROR', 'RC_UNKNOWN_COMMAND', + 'C_CancelFunction', 'CK_HA_STATUS', + 'CK_CA_STCGetClientInfo', 'MSG_RTC_ZEROIZED_ON_POWER_LOSS', + 'LUNA_RET_CONTAINER_IS_DISABLED', + 'RC_LISTEN_SOCKET_INVALID', 'LUNA_RET_ECC_DAC_MISSING', + 'CK_C_DigestKey', 'C_GetInfo', 'C_Initialize', + 'RC_INVALID_COMMAND', 'C_DestroyObject', + 'C_GetOperationState', 'LUNA_RET_TOO_MANY_CONTAINERS', + 'LUNA_RET_ROOT_CERT_MISSING', + 'LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED', + 'LUNA_RET_WRAPPED_KEY_INVALID', 'CA_DeleteContainer', + 'CA_GetContainerPolicySetting', 'C_InitToken', + 'CK_C_WrapKey', 'LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL', + 'LUNA_RET_RM_ELEMENT_VALUE_INVALID', + 'LUNA_RET_VECTOR_TOO_SMALL', 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR', - 'CA_SpRawWrite', 'C_GetSessionInfo', + 'RC_SOCKET_WRITE_ERROR', + 'MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY', 'CA_SpRawWrite', + 'LUNA_RET_CCM_SIGN_INVALID', 'C_Login', 'C_GetSlotInfo', 'CK_CA_InitIndirectPIN', 'CA_DeleteRemotePEDVector', - 'CK_CA_UnlockClusteredSlot', 'CK_CA_CloneModifyMofN', - 'CK_KDF_PRF_PARAMS', 'CK_CA_DestroyMultipleObjects', - 'C_GetSlotList', 'CK_ULONG', 'CK_SSL3_KEY_MAT_OUT_PTR', - 'CK_CA_GetHSMPolicySetting', 'CK_C_GenerateRandom', - 'CK_CA_ModifyUsageCount', 'CA_MTKResplit', 'CK_CHAR', - 'CK_STATE', 'CK_CA_GetHSMCapabilitySetting', - 'CK_KEY_WRAP_SET_OAEP_PARAMS', 'CA_GetPrimarySlot', - 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR', - 'CK_X9_42_DH1_DERIVE_PARAMS', 'CA_GetMofNStatus', - 'CK_C_EncryptUpdate', 'CK_DESTROYMUTEX', + 'CK_CA_CloneAllObjectsToSession', + 'CK_CA_UnlockClusteredSlot', 'CK_CA_GetTokenCapabilities', + 'MSG_TVK_TIMESTAMP_UPDATE_FAILED', + 'LUNA_RET_ISES_CMD_PARAMETER_INVALID', + 'CK_CA_CloneModifyMofN', 'CK_KDF_PRF_PARAMS', + 'LUNA_RET_UM_PIN_INCORRECT', 'C_GetSlotList', + 'LUNA_RET_INVALID_CERTIFICATE_VERSION', 'CK_ULONG', + 'CK_SSL3_KEY_MAT_OUT_PTR', 'C_GetMechanismInfo', + 'CK_C_GenerateRandom', 'CK_CA_ActivateMofN', + 'CK_WTLS_RANDOM_DATA', 'CA_MTKResplit', 'CK_CHAR', + 'CA_HALogin', 'CA_GetHSMStats', 'LUNA_RET_BAD_PPID', + 'CK_STATE', 'UInt8', 'CK_CA_GetHSMCapabilitySetting', + 'CK_KEY_WRAP_SET_OAEP_PARAMS', + 'LUNA_RET_USER_TYPE_INVALID', + 'LUNA_RET_VECTOR_VERSION_INVALID', 'CA_GetPrimarySlot', + 'CK_CA_GetConfigurationElementDescription', + 'LUNA_RET_MM_FATAL_ERROR', 'LUNA_RET_ATTRIBUTE_SENSITIVE', + 'LUNA_RET_HIFN_DMA_TIMED_OUT', + 'CK_CA_CloneObjectToAllSessions', 'RC_VERSION_INVALID', + 'LUNA_RET_SHA_SELF_TEST_FAILURE', + 'LUNA_RET_MISSING_WEIGHT_VALUE', 'CA_MultisignValue', + 'LUNA_RET_SIGNATURE_INVALID', + 'LUNA_RET_M_OF_N_IS_NOT_REQUIRED', + 'LUNA_RET_CONTAINER_HANDLE_INVALID', + 'LUNA_RET_HIFN_NOT_PRESENT', + 'LUNA_RET_TOO_MANY_VECTORS_PROVIDED', 'CK_CMS_SIG_PARAMS_PTR', 'CK_CA_CheckOperationState', - 'CK_C_UnwrapKey', 'CK_CA_GetContainerList', - 'CK_WTLS_KEY_MAT_PARAMS_PTR', 'CA_MultisignValue', - 'CK_ECMQV_DERIVE_PARAMS_PTR', 'CK_CA_InitIndirectToken', - 'CA_GetTSV', 'CA_InitIndirectPIN', 'CK_CA_SetPedId', - 'CA_GenerateMofN', 'CK_CA_DeactivateMofN', 'C_DeriveKey', - 'C_Verify', 'CK_CA_Extract', 'C_DigestUpdate', - 'CK_CA_GetHSMStorageInformation', 'CA_SpRawRead', - 'CK_C_SetAttributeValue', 'CK_CA_GetHSMCapabilitySet', - 'C_SignFinal', 'CA_SIMMultiSign', 'CK_C_GenerateKey', - 'C_DecryptFinal', 'CA_UnlockClusteredSlot', - 'CK_CA_CloneAsSource', 'CK_C_GetSlotList', - 'CK_FUNCTION_LIST_PTR', 'CK_AES_CTR_PARAMS_PTR', - 'CA_FirmwareUpdate', 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE', - 'CK_USHORT_PTR', 'CA_CloseSecondarySession', - 'CK_PKCS5_PBKD2_PARAMS_PTR', 'CK_DES_CTR_PARAMS_PTR', - 'CA_ActivateMofN', 'CK_RSA_PKCS_MGF_TYPE', - 'CK_EXTRACT_PARAMS', 'CK_C_DeriveKey', 'CA_SIMInsert', - 'CK_SFNT_CA_FUNCTION_LIST', 'CK_RC5_CBC_PARAMS_PTR', + 'CK_CA_Zeroize', 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS', + 'LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID', + 'LUNA_RET_LOG_FILE_NOT_OPEN', 'CK_CA_GetContainerList', + 'CK_WTLS_KEY_MAT_PARAMS_PTR', 'LUNA_RET_ECC_HOC_MISSING', + 'LUNA_RET_KEY_NOT_UNWRAPPABLE', 'LUNA_RET_CCM_UNREMOVABLE', + 'CK_CA_InitIndirectToken', 'CA_GetTSV', + 'CA_InitIndirectPIN', + 'LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS', + 'LUNA_RET_SIM_AUTHORIZATION_FAILED', 'CK_CA_SetPedId', + 'CA_GenerateMofN', 'CK_CA_DeactivateMofN', 'C_EncryptInit', + 'C_Verify', 'CK_CA_Extract', 'LUNA_RET_SFNT3120_CRC', + 'CA_CloseApplicationIDForContainer', + 'CK_CA_GetHSMStorageInformation', 'CK_C_GenerateKeyPair', + 'RC_USB_PED_TOO_MANY_CONNECTED', 'CA_SpRawRead', + 'RC_SOCKET_READ_ERROR', 'MSG_BAD_HMAC', + 'CA_DestroyMultipleObjects', 'LUNA_RET_CCM_TOO_LARGE', + 'SInt64', 'CK_CA_GetHSMCapabilitySet', 'CK_C_SignFinal', + 'CK_CA_GetContainerPolicySet', 'RC_INVALID_CERT_HOST', + 'C_SignFinal', 'LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE', + 'CA_SIMMultiSign', 'LUNA_RET_INVALID_CERTIFICATE_DATA', + 'LUNA_RET_LOG_FILE_WRITE_ERROR', 'CK_C_FindObjectsFinal', + 'CK_C_GenerateKey', 'SizeType', 'LUNA_RET_M_TOO_SMALL', + 'Byte', 'CA_UnlockClusteredSlot', 'CK_CA_CloneAsSource', + 'CK_C_GetSlotList', 'CK_FUNCTION_LIST_PTR', + 'LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD', + 'LUNA_RET_FORMER_INVALID_ENTRY_TYPE', 'SInt', + 'LUNA_RET_KEY_NOT_WRAPPABLE', 'RC_FILE_ERROR', + 'CK_AES_CTR_PARAMS_PTR', + 'LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST', + 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE', 'CK_USHORT_PTR', + 'LUNA_RET_HIFN_INVALID_PAD_ALGORITHM', + 'CK_C_DecryptVerifyUpdate', 'CK_PKCS5_PBKD2_PARAMS_PTR', + 'C_CreateObject', 'RC_RC_ERROR', + 'LUNA_RET_OH_OBJECT_TYPE_INVALID', 'CA_ActivateMofN', + 'CK_RSA_PKCS_MGF_TYPE', 'LUNA_RET_TWC_PARAMETER_MISSING', + 'LUNA_RET_AES_SELF_TEST_FAILURE', 'CK_EXTRACT_PARAMS', + 'CKCA_MODULE_INFO', 'RC_OK', + 'LUNA_RET_OH_OBJECT_VERSION_INVALID', 'C_GetSessionInfo', + 'LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST', + 'CK_SFNT_CA_FUNCTION_LIST', 'LUNA_RET_CB_REMOTE_CLOSED', + 'CK_RC5_PARAMS', 'CA_LogVerify', + 'LUNA_RET_MM_ITERATOR_PAST_END', 'CK_RC5_CBC_PARAMS_PTR', 'CK_CA_OpenApplicationID', 'CK_AES_GMAC_PARAMS_PTR', 'CK_RC5_MAC_GENERAL_PARAMS', 'CK_CA_InvokeService', 'CK_CAMELLIA_CTR_PARAMS_PTR', 'CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR', - 'CA_RetrieveLicenseList', 'CA_GetHSMPolicySetting', - 'CK_SEED_CTR_PARAMS', 'CK_ResetTotalOperations', - 'CA_HALogin', 'CA_MOFN_GENERATION_PTR', - 'CK_AES_GCM_PARAMS_PTR', 'CK_C_VerifyRecoverInit', - 'CK_CA_SetContainerSize', 'CK_LKM_TOKEN_ID', - 'CK_CA_HALogin', 'CA_CloneObjectToAllSessions', - 'CA_Insert', 'CK_ECDH2_DERIVE_PARAMS_PTR', - 'CK_CA_ChoosePrimarySlot', 'CA_LogGetConfig', - 'CK_C_DecryptDigestUpdate', 'CK_SSL3_KEY_MAT_PARAMS', + 'MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF', + 'LUNA_RET_SM_SESSION_HANDLE_INVALID', 'CA_MTKSetStorage', + 'RC_FAILED_TO_CREATE_PROCESS', 'CA_GetHSMCapabilitySet', + 'LUNA_RET_HOC_MISSING', 'CA_GetHSMPolicySetting', + 'LUNA_RET_LOG_BAD_FILE_NAME', 'CK_OTP_SIGNATURE_INFO_PTR', + 'LUNA_RET_CAST3_SELF_TEST_FAILURE', 'CK_SEED_CTR_PARAMS', + 'CK_CA_TokenZeroize', 'CK_ResetTotalOperations', + 'LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS', + 'MSG_TVK_TIMESTAMP_IS_TOO_OLD', 'CA_MOFN_GENERATION_PTR', + 'CK_CA_InitSlotRolePIN', 'CK_AES_GCM_PARAMS_PTR', + 'RC_FUNCTION_NOT_SUPPORTED', 'LUNA_RET_SPLIT_DATA_INVALID', + 'LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL', + 'CK_LKM_TOKEN_ID', 'LUNA_RET_ECC_RESULT_AT_INF', + 'LUNA_RET_CB_HIOS_STATE_INVALID', + 'CK_CA_TokenInsertNoAuth', 'MSG_TVK_WAS_CORRUPTED', + 'CA_CloneObjectToAllSessions', 'CA_Insert', + 'CK_CA_SIMMultiSign', 'CK_CA_ChoosePrimarySlot', + 'CK_CA_OpenApplicationIDForContainer', + 'CK_KEY_DERIVATION_STRING_DATA_PTR', + 'LUNA_RET_CB_NOT_SUPPORTED', + 'CK_CA_EnableUnauthTokenInsertion', + 'LUNA_RET_HIFN6500_DATA_LINES_BROKEN', 'MSG_RESYNC', + 'LUNA_RET_CHALLENGE_RESPONSE_INCORRECT', 'CK_CA_LogSetConfig', 'CK_CA_IndirectLogin', - 'CK_CA_InvokeServiceAsynch', 'CA_MTKSetStorage', - 'CK_CA_WaitForSlotEvent', 'CK_OTP_SIGNATURE_INFO_PTR', - 'CA_HAAnswerMofNChallenge', 'CK_CA_InitAudit', - 'CK_SSL3_RANDOM_DATA', 'CK_WTLS_RANDOM_DATA', - 'CK_DES_CBC_ENCRYPT_DATA_PARAMS', 'CK_RC5_CBC_PARAMS', - 'CK_C_SeedRandom', 'CK_USHORT', - 'CK_CA_SetContainerPolicies', 'CK_CLUSTER_STATE', - 'CA_MTKRestore', 'CK_C_CreateObject', 'CK_TOKEN_INFO_PTR', - 'CA_SetMofN', 'CA_CloneModifyMofN', - 'CK_CA_LoadEncryptedModule', 'CK_C_DecryptFinal', - 'CK_AES_CBC_PAD_INSERT_PARAMS', 'CK_CA_SetContainerPolicy', - 'CK_ECIES_PARAMS', 'CK_CA_CloneObject', 'CA_SetTPV', - 'C_GenerateKeyPair', 'CK_SFNT_CA_FUNCTION_LIST_PTR_PTR', + 'CK_CA_InvokeServiceAsynch', + 'RC_MANUFACTURING_SERIAL_NUMBER_INVALID', + 'LUNA_RET_TEST_VS_BSAFE_FAILED', 'CK_CA_GetTokenPolicies', + 'LUNA_RET_CERT_VERSION_NOT_SUPPORTED', + 'MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET', + 'CK_KIP_PARAMS', 'LUNA_RET_POLICY_NOT_FOUND', + 'LUNA_RET_INCOMPATIBLE', 'RC_SOCKET_BAD_FD', + 'LUNA_RET_SM_UNKNOWN_SESSION_TYPE', + 'LUNA_RET_SM_SESSION_READ_ONLY_EXISTS', + 'LUNA_RET_DEVICE_TIMEOUT', + 'LUNA_RET_SECURITY_PARAMETER_MISSING', 'MSG_LAST', + 'LUNA_RET_ENCRYPTED_DATA_INVALID', 'CK_PKCS5_PBKD2_PARAMS', + 'CK_C_Logout', 'CK_MECHANISM_TYPE', + 'CK_DES_CBC_ENCRYPT_DATA_PARAMS', 'CK_USHORT', + 'LUNA_RET_SEED_SELF_TEST_FAILURE', 'CA_SetMofN', + 'LUNA_RET_INVALID_CERTIFICATE_TYPE', + 'CK_CA_SetContainerPolicies', 'LUNA_RET_LOG_FULL', + 'CK_CLUSTER_STATE', 'LUNA_RET_MISSING_SPLITS', + 'LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL', + 'LUNA_RET_KEY_SENSITIVE', + 'MSG_RTC_EXTERNAL_TAMPER_DETECTED', + 'CA_CloseApplicationID', 'C_DecryptFinal', + 'CA_CloneModifyMofN', 'CK_CA_LoadEncryptedModule', + 'CK_LOCKMUTEX', 'LUNA_RET_HIFN6500_RNG_FAILED', + 'LUNA_RET_FLAGS_INVALID', + 'MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED', + 'LUNA_RET_TOO_MANY_WEIGHTS', 'CK_CA_SetContainerPolicy', + 'CK_ECIES_PARAMS', 'LUNA_RET_USER_ALREADY_ACTIVATED', + 'RC_INVALID_ENUM_OPTION', 'LUNA_RET_USER_NOT_LOGGED_IN', + 'LUNA_RET_INVALID_IP_PACKET', 'CA_SetTPV', 'CK_C_Finalize', + 'LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS', + 'CK_CA_RoleStateGet', 'CK_SFNT_CA_FUNCTION_LIST_PTR_PTR', 'CK_CA_MTKSetStorage', 'CKA_SIM_AUTH_FORM', 'CK_CA_LKMInitiatorChallenge', 'CK_CA_HAActivateMofN', - 'CK_KEY_DERIVATION_STRING_DATA', 'CK_MECHANISM_PTR', - 'CK_C_SignRecover', 'CA_LKMInitiatorComplete', - 'CA_SetTokenCertificateSignature', - 'CA_GetUserContainerName', 'CK_HA_MEMBER_PTR', - 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS', + 'CK_KEY_DERIVATION_STRING_DATA', + 'LUNA_RET_COUNTER_WRAPAROUND', + 'LUNA_RET_INVALID_ENTRY_TYPE', 'CK_C_SignRecover', + 'LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE', + 'MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED', + 'CK_HW_FEATURE_TYPE', 'CA_SetTokenCertificateSignature', + 'CA_GetUserContainerName', 'RC_POINTER_INVALID', + 'RC_NOT_HSM_BACKUP_TOKEN', 'CK_C_CreateObject', 'CK_CA_ExtractMaskedObject', 'CK_C_GetFunctionStatus', - 'CK_CA_GetContainerPolicySetting', 'CK_PRF_KDF_PARAMS', - 'CK_CA_Deactivate', 'CK_SLOT_INFO_PTR', - 'CK_X9_42_DH1_DERIVE_PARAMS_PTR', 'CK_CLUSTER_STATE_PTR', - 'CK_C_GetTokenInfo', 'CK_C_VerifyFinal', - 'CA_CheckOperationState', 'C_GetTokenInfo', 'C_Digest', - 'CA_CloneAsTarget', 'CA_SetCloningDomain', - 'CK_OTP_PARAM_TYPE', 'CA_GetUserContainerNumber', - 'CK_KEY_WRAP_SET_OAEP_PARAMS_PTR', 'CA_GetObjectUID', - 'CK_VERSION_PTR', 'CA_HAAnswerLoginChallenge', - 'CK_CA_GetSessionInfo', 'CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR', - 'C_SignEncryptUpdate', 'CA_GetHSMCapabilitySetting', + 'CA_ROLE_STATE', 'CK_CA_UnloadModule', + 'LUNA_RET_SM_BAD_ACCESS_HANDLE', + 'MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS', + 'CK_CA_HAGetMasterPublic', 'CK_PRF_KDF_PARAMS', + 'CK_CA_Deactivate', 'CA_GetTokenCertificates', + 'LUNA_RET_ECC_POINT_INVALID', 'RC_SOCKET_ADDRESS_INVALID', + 'LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN', 'CA_MTKRestore', + 'CK_CLUSTER_STATE_PTR', 'CK_C_GetTokenInfo', + 'LUNA_RET_CB_HIOS_IO_ERROR', + 'CA_CloseAllSecondarySessions', 'CA_CheckOperationState', + 'LUNA_RET_M_OF_N_SECRET_INVALID', 'CK_RSA_PKCS_PSS_PARAMS', + 'LUNA_RET_SP_TX_ERROR', 'C_GetTokenInfo', + 'LUNA_RET_SM_UNKNOWN_TOSM_STATE', 'CK_CA_SetTokenPolicies', + 'RC_SOCKET_ADDRESS_IN_USE', + 'LUNA_RET_CL_COMMAND_NON_BACKUP', 'CK_CA_SetRDK', + 'CA_ListSecureToken', 'CK_SSL3_KEY_MAT_PARAMS', + 'RC_NOT_PARTITION_BACKUP_TOKEN', + 'LUNA_RET_RC4_SELF_TEST_FAILURE', + 'LUNA_RET_HIFN_INVALID_ENCRYPT_MODE', 'CK_CA_GetHSMStats', + 'CK_OTP_SIGNATURE_INFO', + 'LUNA_RET_M_OF_N_IS_NOT_INITIALZED', + 'LUNA_RET_CB_REMOTE_ABANDONED', 'CA_ChooseSecondarySlot', + 'LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID', + 'RC_SEMAPHORE_ERROR', 'LUNA_RET_CB_PARAM_INVALID', + 'CA_GetFunctionList', 'CK_C_DeriveKey', + 'CA_OpenApplicationIDForContainer', + 'LUNA_RET_DSA_PARAM_GEN_FAILURE', 'CK_KEY_TYPE', + 'CK_C_DecryptFinal', 'UInt', 'CA_GetObjectUID', + 'LUNA_RET_PED_UNSUPPORTED_PROTOCOL', 'CK_CA_ManualKCV', + 'LUNA_RET_TIMEOUT', 'CK_RC2_MAC_GENERAL_PARAMS_PTR', + 'CK_CA_GetSessionInfo', 'RC_CACHE_NOT_MAPPED', + 'CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR', + 'LUNA_RET_SFNT3120_SELFTEST_FAILED', + 'LUNA_RET_TOKEN_LOCKED_OUT_OH', 'C_SignEncryptUpdate', + 'RC_SHUTTING_DOWN', 'CA_DeleteContainerWithHandle', 'CK_CA_GetSecondarySlot', 'CK_CA_DuplicateMofN', - 'C_DecryptInit', 'CK_RC5_PARAMS_PTR', - 'CK_KEA_DERIVE_PARAMS', 'CK_C_DigestInit', 'CA_ModifyMofN', - 'CK_MECHANISM_TYPE_PTR', 'CA_MTKGetState', - 'CK_CA_LogExportSecret', - 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS', 'CA_InvokeServiceInit', - 'CK_XOR_BASE_DATA_KDF_PARAMS_PTR', 'CK_SESSION_INFO', - 'C_SignUpdate', 'CK_CA_CloneObjectToAllSessions', - 'C_SignInit', 'CK_MECHANISM_TYPE', - 'CK_WTLS_KEY_MAT_PARAMS', 'CA_SetKCV', - 'CK_CA_CreateContainer', 'CA_ExtractMaskedObject', - 'C_EncryptInit', 'C_DigestEncryptUpdate', 'CK_OTP_PARAMS', - 'CK_SEED_CTR_PARAMS_PTR', 'CK_KDF_PRF_PARAMS_PTR', - 'CA_GetContainerCapabilitySet', 'CK_CA_LogGetConfig', - 'C_DigestFinal', 'CK_CA_HAAnswerLoginChallenge', - 'CK_CA_LockClusteredSlot', - 'CK_CA_GetContainerStorageInformation', 'CK_ATTRIBUTE', + 'RC_UNKNOWN_CALLBACK_COMMAND', + 'CK_CA_GetTokenObjectHandle', + 'LUNA_RET_CPK_PARAMETER_MISSING', + 'LUNA_RET_INVALID_MODULUS_SIZE', 'CK_RC5_PARAMS_PTR', + 'CK_KEA_DERIVE_PARAMS', 'CK_C_DigestInit', + 'LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID', + 'CA_ModifyMofN', 'CA_CloneObject', + 'CK_CA_STCGetClientsList', 'C_DecryptUpdate', + 'CK_CA_STCGetPubKey', 'LUNA_RET_CHALLENGE_NOT_REQUIRED', + 'MSG_RTC_CANT_GET_TAMPER_TIMER', + 'LUNA_RET_KEY_INVALID_FOR_OPERATION', 'CK_CA_CloneObject', + 'LUNA_RET_RM_BAD_HSM_PARAMS', + 'LUNA_RET_INVALID_CERTIFICATE_FUNCTION', + 'CK_CA_GetContainerPolicySetting', + 'CK_CA_LKMReceiverResponse', 'Int64', + 'CA_InvokeServiceInit', 'LUNA_RET_SM_DATA_INVALID', + 'CA_GetTime', 'CK_TOKEN_INFO_PTR', + 'LUNA_RET_VECTOR_TYPE_INVALID', 'CK_SESSION_INFO', + 'LUNA_RET_SM_MEMORY_ALLOCATION_ERROR', + 'RC_ASSIGNING_SAME_VALUE', + 'LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED', + 'LUNA_RET_ISES_CMD_FAILED', + 'CK_CA_SetTokenCertificateSignature', + 'LUNA_RET_CCM_NOT_SUPPORTED', 'CA_SetKCV', + 'CK_CA_CreateContainer', + 'LUNA_RET_ENCRYPTED_DATA_LEN_RANGE', + 'CA_ExtractMaskedObject', 'LUNA_RET_OPERATION_ACTIVE', + 'C_GenerateKeyPair', 'LUNA_RET_DAC_MISSING', + 'CK_ULONG_PTR', 'CK_C_Encrypt', + 'LUNA_RET_SIM_AUTHFORM_INVALID', 'CK_SEED_CTR_PARAMS_PTR', + 'LUNA_RET_INVALID_FUF_HEADER', 'RC_USB_PED_NOT_RESPONDING', + 'CK_KDF_PRF_PARAMS_PTR', + 'LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED', + 'LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES', + 'CA_GetHSMStorageInformation', 'C_DigestFinal', + 'LUNA_RET_CB_MUST_WRITE', 'CK_CA_HAAnswerLoginChallenge', + 'CA_SIMInsert', 'CK_INFO', + 'LUNA_RET_SM_OTHER_USER_LOGGED_IN', + 'LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS', + 'LUNA_RET_ATTRIBUTE_VALUE_INVALID', 'Float32', + 'RC_TOKEN_NOT_PRESENT', + 'CK_CA_GetContainerStorageInformation', + 'CK_CA_QueryLicense', + 'LUNA_RET_HIFN_END_MARKER_NOT_PRESENT', + 'LUNA_RET_CB_HIOS_CLOSED', 'CK_ATTRIBUTE', 'CK_CA_SetDestructiveHSMPolicies', - 'CK_RSA_PKCS_MGF_TYPE_PTR', 'CK_SKIPJACK_RELAYX_PARAMS', - 'CK_PBE_PARAMS_PTR', 'CK_MECHANISM', - 'CA_GetContainerCapabilitySetting', - 'CA_GetContainerStatus', 'CA_InvokeServiceAsynch', - 'CK_CA_CloneAsTargetInit', 'C_Encrypt', - 'CK_LKM_TOKEN_ID_S', 'CK_C_WaitForSlotEvent', - 'CK_C_SignUpdate', 'CK_CA_LogVerify', - 'CK_CA_SetApplicationID', 'CK_CA_GetTSV', - 'CK_AES_CBC_ENCRYPT_DATA_PARAMS', 'CK_ARIA_CTR_PARAMS_PTR', - 'C_EncryptFinal', 'CA_LKMReceiverComplete', - 'CK_C_DecryptVerifyUpdate', 'CK_CA_GetUserContainerNumber', - 'CK_EC_KDF_TYPE', 'CK_KEY_DERIVATION_STRING_DATA_PTR', - 'CA_InitializeRemotePEDVector', 'CA_LogVerify', - 'CA_GetFPV', 'CA_HAInit', 'C_CloseSession', - 'CA_GetHAState', 'CA_SetDestructiveHSMPolicies', - 'C_SignRecoverInit', 'CK_EC_DH_PRIMITIVE', - 'CK_CA_ManualKCV', 'CK_C_Login', 'CA_IsMofNEnabled', - 'CK_CA_InvokeServiceSinglePart', 'CA_LogGetStatus', - 'CK_CA_QueryLicense', 'CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR', - 'CK_C_FindObjectsFinal', 'CK_CREATEMUTEX', - 'CK_SLOT_ID_PTR', 'CA_IsMofNRequired', - 'CK_FUNCTION_LIST_PTR_PTR', 'CA_HAGetMasterPublic', - 'CK_CA_LKMInitiatorComplete', 'CK_CA_LogEraseAll', - 'CA_CloseApplicationIDForContainer', - 'CK_CA_GenerateTokenKeys', 'CK_BYTE', - 'CK_SSL3_KEY_MAT_OUT', 'CA_SetContainerPolicies', - 'C_DecryptVerifyUpdate', 'CA_GenerateCloningKEV', - 'CA_SetHSMPolicy', 'CK_CA_GetTPV', - 'CK_CA_SinglePartDecrypt', 'CK_GetTotalOperations', - 'CK_UTF8CHAR', 'CK_CA_GetObjectHandle', 'CK_CA_Insert', - 'CK_CA_SetTokenCertificateSignature', 'CK_RV', 'CK_NOTIFY', - 'CK_CA_InitializeRemotePEDVector', 'CKCA_MODULE_INFO_PTR', - 'CK_C_FindObjects', 'C_DigestInit', - 'CA_GetContainerStorageInformation', 'CK_BYTE_PTR', - 'CA_ModifyUsageCount', 'CK_CA_TimeSync', 'CA_SetPedId', - 'CA_GetHSMPolicySet', 'CK_CA_ModifyMofN', 'C_CopyObject', - 'CK_CA_CloseApplicationID', 'CA_GetContainerPolicySetting', - 'CK_SSL3_KEY_MAT_PARAMS_PTR', 'C_VerifyUpdate', - 'CK_NOTIFICATION', 'CK_CA_LogImportSecret', - 'CA_GenerateTokenKeys', 'CK_X9_42_MQV_DERIVE_PARAMS_PTR', - 'CK_CA_SetMofN', 'CK_C_GetAttributeValue', - 'CK_CA_InvokeServiceFinal', 'CA_TimeSync', - 'CA_LKMInitiatorChallenge', 'CK_CA_ResetPIN', - 'CA_GetContainerList', 'CK_C_GetMechanismList', - 'CA_CreateLoginChallenge', 'C_EncryptUpdate', - 'CK_X9_42_DH_KDF_TYPE_PTR', + 'CK_RSA_PKCS_MGF_TYPE_PTR', 'CK_UTF8CHAR', + 'CK_C_DecryptDigestUpdate', 'CA_LogSetConfig', + 'CK_CA_SwitchSecondarySlot', 'RC_CANCEL', 'CK_MECHANISM', + 'CK_WTLS_RANDOM_DATA_PTR', 'LUNA_RET_UM_TSN_MISSING', + 'CA_GetContainerCapabilitySetting', 'CK_MECHANISM_INFO', + 'CK_FUNCTION_LIST', + 'LUNA_RET_HIFN_DESTINATION_COUNT_INVALID', 'C_FindObjects', + 'C_VerifyInit', 'Int16', 'CA_GetContainerStatus', + 'RC_SSL_WANT_X509_LOOKUP_ERROR', 'LUNA_RET_NO_RNG_SEED', + 'RC_SOCKET_WOULDBLOCK', 'CA_InvokeServiceAsynch', + 'CK_CA_CloneAsTargetInit', + 'LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL', + 'LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED', + 'MSG_LOG_WAS_TRUNCATED', 'CK_C_WaitForSlotEvent', + 'CK_KEY_WRAP_SET_OAEP_PARAMS_PTR', 'RC_SSL_CTX_ERROR', + 'CK_C_SignUpdate', 'CK_CREATEMUTEX', 'CK_CA_LogVerify', + 'CK_CA_SetApplicationID', 'CK_CA_STCRegister', + 'CK_CA_GetTSV', 'CK_AES_CBC_ENCRYPT_DATA_PARAMS', + 'CK_ARIA_CTR_PARAMS_PTR', 'CA_IsMofNEnabled', + 'C_EncryptFinal', 'CK_KIP_PARAMS_PTR', + 'RC_OBJECT_ID_INVALID', 'C_FindObjectsInit', + 'CA_LKMReceiverComplete', + 'LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM', + 'CK_CA_GetUserContainerNumber', 'CK_C_SeedRandom', + 'LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED', + 'LUNA_RET_CCM_FWUPDATE_DENIED', 'CK_EC_KDF_TYPE', + 'CK_CA_OpenSession', 'CA_GetSessionInfo', + 'MSG_FACTORY_RESET', + 'LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM', + 'LUNA_RET_HAS160_SELF_TEST_FAILURE', + 'RC_HOST_RESOLUTION_ERROR', + 'RC_USB_PED_OPERATION_CANCELLED', 'CA_GetFPV', + 'LUNA_RET_MM_USAGE_ALREADY_SET', 'CA_HAInit', + 'LUNA_RET_CCM_CERT_INVALID', 'LUNA_RET_MISSING_VECTOR', + 'CA_GetHAState', 'CK_CA_SetKCV', 'C_SignRecoverInit', + 'C_DigestInit', 'LUNA_RET_ATTRIBUTE_TYPE_INVALID', + 'LUNA_RET_CB_SYS_ERROR', 'CK_EC_DH_PRIMITIVE', + 'RC_SSL_LOAD_CLIENT_CERT_ERROR', + 'LUNA_RET_INVALID_VECTOR_SIZE', 'MSG_RTC_BATTERY_LOW', + 'CK_CA_LogGetConfig', 'LUNA_RET_TOKEN_LOCKED_OUT_RN', + 'CK_PBE_PARAMS', 'C_SignInit', + 'CK_CA_InvokeServiceSinglePart', + 'LUNA_RET_HIFN6500_NOT_PRESENT', 'ULong', + 'CK_CA_WaitForSlotEvent', 'CA_LogGetStatus', + 'LUNA_RET_CB_HIOS_SEND_TIMEOUT', + 'LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED', + 'CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'LUNA_RET_HIFN_DMA_NOT_IDLE', + 'LUNA_RET_TOTAL_WEIGHT_INVALID', + 'CK_RSA_PKCS_OAEP_PARAMS_PTR', 'CA_HAGetMasterPublic', + 'LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED', + 'LUNA_RET_CAST5_SELF_TEST_FAILURE', 'CK_SLOT_ID_PTR', + 'LUNA_RET_410_BUFFER_TOO_SMALL', 'CK_C_Digest', + 'LUNA_RET_HIFN_DESTINATION_OVERRUN', + 'MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK', + 'CK_CA_GetPedId', 'LUNA_RET_USER_ALREADY_LOGGED_IN', + 'CK_FUNCTION_LIST_PTR_PTR', + 'LUNA_RET_FUNCTION_NOT_SUPPORTED', + 'CK_CA_LKMInitiatorComplete', 'MSG_RTC_ROLLED_BACK', + 'CK_CA_DeleteRemotePEDVector', + 'MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT', + 'RC_SSL_FAILED_HANDSHAKE', 'CK_BYTE', + 'CK_SSL3_KEY_MAT_OUT', 'CK_C_DecryptUpdate', + 'CK_CA_LogVerifyFile', 'CK_CA_DeleteContainer', + 'CK_CA_HAGetLoginChallenge', 'CA_GenerateCloningKEV', + 'LUNA_RET_ISES_ERROR', 'LUNA_RET_ISES_LNAU_TEST_FAILED', + 'LUNA_RET_ECC_MIC_MISSING', 'CK_CA_GetTPV', + 'MSG_RTC_CANT_CLEAN_POWER_LOSS', 'CK_GetTotalOperations', + 'CK_CA_LogEraseAll', 'CK_SLOT_INFO_PTR', + 'CK_CA_GetObjectHandle', 'RC_CALLBACK_ERROR', + 'LUNA_RET_ATTRIBUTE_NOT_FOUND', 'CA_CloseSecondarySession', + 'C_Encrypt', 'CK_RV', 'RC_PORT_INVALID', 'CK_NOTIFY', + 'CK_CA_InitializeRemotePEDVector', + 'LUNA_RET_MM_NOT_ENOUGH_MEMORY', 'C_Finalize', + 'CK_C_FindObjects', 'CK_CA_SetContainerSize', + 'RC_SSL_GET_PEER_CERT_ERROR', + 'LUNA_RET_ATTRIBUTE_READ_ONLY', + 'CA_GetContainerStorageInformation', + 'CA_GetContainerPolicySet', + 'LUNA_RET_HIFN_INVALID_MAC_MODE', 'RC_SSL_ERROR', + 'LUNA_RET_DSA_SELF_TEST_FAILURE', 'CK_BYTE_PTR', + 'CA_ModifyUsageCount', 'CK_CA_TimeSync', + 'LUNA_RET_N_TOO_SMALL', 'CK_CA_GenerateTokenKeys', + 'CK_DES_CTR_PARAMS_PTR', 'CA_GetHSMPolicySet', + 'LUNA_RET_SM_KEY_SIZE_ERROR', + 'LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE', 'C_CopyObject', + 'CK_CA_CloseApplicationID', 'LUNA_RET_ECC_BUFFER_OVERFLOW', + 'LUNA_RET_OH_OBJECT_ALREADY_EXISTS', 'CK_CA_Insert', + 'CK_CA_CloseAllSecondarySessions', 'RC_DATA_INVALID', + 'C_VerifyUpdate', 'CK_NOTIFICATION', + 'LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS', + 'LUNA_RET_TOKEN_LOCKED_OUT_UM', 'C_SignRecover', + 'LUNA_RET_SSK_MISSING', 'CK_C_VerifyUpdate', + 'RC_REMOTE_SIDE_DISCONNECTED', 'CK_C_GetAttributeValue', + 'CA_CreateContainer', 'CA_LogImportSecret', 'CA_TimeSync', + 'CA_LKMInitiatorChallenge', 'LUNA_RET_UM_PIN_LEN_RANGE', + 'CK_C_VerifyFinal', 'HalfWord', 'CK_C_GetMechanismList', + 'CA_CreateLoginChallenge', 'RC_PIN_LOCKED', + 'RC_SSL_LOAD_SERVER_CERT_ERROR', 'LUNA_RET_PED_ERROR', + 'LUNA_RET_MISSING_NUMBER_OF_VECTORS', + 'CA_SetContainerPolicies', 'CK_X9_42_DH_KDF_TYPE_PTR', 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR', - 'CK_CA_EncodeECPrimeParams', 'CK_CA_HAGetLoginChallenge', - 'CK_VOID_PTR_PTR', 'CA_MOFN_STATUS', 'CK_C_SignInit', - 'CK_C_Decrypt', 'CK_CA_CloneMofN', 'CK_SESSION_INFO_PTR', - 'CK_CA_IsMofNRequired', 'CK_CA_SIMInsert', - 'CK_C_CopyObject', 'CK_CA_CreateLoginChallenge', - 'CK_KDF_PRF_TYPE', 'CA_GenerateCloneableMofN', - 'CK_CHAR_PTR', 'C_Sign', 'C_SetPIN', 'CK_C_GetObjectSize', - 'CA_ResetDevice', 'CK_CA_GetTokenInsertionCount', - 'CK_C_DigestUpdate', 'CA_GetSessionInfo', - 'C_GetFunctionList', 'CK_CA_SetCloningDomain', - 'CA_DeactivateMofN', 'CK_C_Initialize', - 'C_GetOperationState', 'CK_C_GetSessionInfo', - 'CA_GetModuleList', 'CK_C_Encrypt', 'CK_BBOOL', - 'CK_CA_EncodeECChar2Params', 'CK_CA_GetModuleInfo', - 'C_GenerateKey', 'CK_CA_SetTPV', 'CA_GetTokenCertificates', - 'C_InitPIN', 'C_DecryptUpdate', - 'CK_SKIPJACK_PRIVATE_WRAP_PARAMS', 'CK_KIP_PARAMS_PTR', - 'CK_RC2_CBC_PARAMS', 'CK_C_GetSlotInfo', - 'CA_GetRollbackFirmwareVersion', 'CK_C_DestroyObject', - 'CK_C_GenerateKeyPair', 'CK_C_InitToken', - 'CK_CA_LKMReceiverResponse', 'CA_GetTime', - 'CA_ChooseSecondarySlot', 'CK_CA_GetUserContainerName', + 'CK_CA_EncodeECPrimeParams', 'C_DecryptVerifyUpdate', + 'CK_C_UnwrapKey', 'LUNA_RET_USER_PIN_NOT_INITIALIZED', + 'CA_MOFN_STATUS', 'CK_C_SignInit', + 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CK_CA_GetContainerName', 'CK_CA_CloneMofN', + 'LUNA_RET_DES_SELF_TEST_FAILURE', 'CK_SESSION_INFO_PTR', + 'LUNA_RET_ERROR', 'CA_GenerateTokenKeys', + 'LUNA_RET_ECC_SELF_TEST_FAILURE', + 'LUNA_RET_CHALLENGE_REQUIRES_PED', 'CK_C_CopyObject', + 'CK_CA_CreateLoginChallenge', 'CK_CERTIFICATE_TYPE', + 'MSG_ZEROIZING', 'CA_FirmwareRollback', 'Float', + 'CK_KDF_PRF_TYPE', 'LUNA_RET_CL_NO_TRANSMISSION', + 'CK_CA_DestroyMultipleObjects', 'LUNA_RET_OBJECT_DELETED', + 'CK_CA_GenerateCloneableMofN', 'RC_SIM_NOT_SUPPORTED', + 'CA_GenerateCloneableMofN', 'CK_CMS_SIG_PARAMS', + 'CK_X9_42_DH1_DERIVE_PARAMS_PTR', 'CK_CHAR_PTR', + 'CT_TokenHndle', 'LUNA_RET_MASKING_NOT_SUPPORTED', + 'C_Digest', 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR', + 'MSG_RTC_MSG_NVRAM_READ_FAILED', + 'CA_HAAnswerMofNChallenge', 'C_SetPIN', + 'CK_C_GetObjectSize', 'LUNA_RET_WEIGHT_TOO_LARGE', + 'LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW', + 'LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE', + 'CK_RC5_MAC_GENERAL_PARAMS_PTR', 'CK_C_DigestUpdate', + 'LUNA_RET_KEY_SIZE_RANGE', + 'LUNA_RET_RSA_SELF_TEST_FAILURE', + 'CK_X9_42_DH1_DERIVE_PARAMS', 'C_GetFunctionList', + 'CK_CA_SetCloningDomain', 'CA_EncodeECParamsFromFile', + 'LUNA_RET_TPV_INVALID', 'LUNA_RET_ECC_HOK_MISSING', + 'CA_LogEraseAll', 'CA_DeactivateMofN', + 'LUNA_RET_RM_POLICY_WRITE_RESTRICTED', + 'CK_C_PerformSelfTest', 'LUNA_RET_CHALLENGE_INVALID', + 'CA_CloneAsTarget', 'CK_CA_Restart', + 'LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT', 'CK_INFO_PTR', + 'CA_GetModuleList', 'CK_CA_ModifyUsageCount', + 'CA_LogExportSecret', 'CK_BBOOL', + 'CK_CA_EncodeECChar2Params', 'CA_IsMofNRequired', + 'MSG_RTC_TAMPER_2_SIGNAL', 'CK_CA_GetModuleInfo', + 'LUNA_RET_RIPEMD160_SELF_TEST_FAILURE', 'CK_CA_SetTPV', + 'RC_TOKEN_STATE_INVALID', 'RC_KEY_NEEDED', 'C_DecryptInit', + 'LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID', + 'LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE', + 'LUNA_RET_BAD_FW_VERSION', 'LUNA_RET_DATA_LEN_RANGE', + 'CK_C_DestroyObject', 'LUNA_RET_CB_NO_MEMORY', + 'LUNA_RET_CAST_SELF_TEST_FAILURE', + 'CK_X9_42_DH2_DERIVE_PARAMS', + 'CK_SKIPJACK_PRIVATE_WRAP_PARAMS', + 'CK_X9_42_MQV_DERIVE_PARAMS_PTR', 'Int8', + 'LUNA_RET_DAK_MISSING', 'CK_RC2_CBC_PARAMS', + 'LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY', + 'CK_X9_42_MQV_DERIVE_PARAMS', + 'CA_GetRollbackFirmwareVersion', 'RC_INVALID_INDEX', + 'LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED', + 'LUNA_RET_RC5_SELF_TEST_FAILURE', + 'MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED', + 'LUNA_RET_MTK_SPLIT_INVALID', + 'CK_CA_GetTokenStorageInformation', 'CK_C_EncryptUpdate', + 'MSG_RTC_CANT_CLEAN_TAMPER_1', + 'MSG_RTC_CANT_CLEAN_TAMPER_2', + 'LUNA_RET_MTK_STATE_INVALID', + 'MSG_RTC_TAMPER_CIRCUITS_RE_ARMED', + 'MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK', + 'MSG_RTC_RECONFIGURING_FAILED', 'CK_DESTROYMUTEX', + 'RC_CHALLENGE_BUFFER_SIZE', + 'LUNA_RET_HIFN_SOURCE_COUNT_INVALID', + 'LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID', + 'LUNA_RET_SIM_CORRUPT_DATA', + 'MSG_RTC_MSG_NVRAM_WRITE_FAILED', + 'CK_CA_GetTokenObjectUID', 'LUNA_RET_CB_ID_INVALID', + 'LUNA_RET_CB_SYNC_ERROR', 'CK_CA_GetUserContainerName', 'CK_CA_MTKZeroize', 'CK_CA_GetClusterState', - 'CK_AES_CTR_PARAMS', 'CA_SetContainerSize', - 'C_SignRecover', 'CA_SetExtendedTPV', - 'CK_ECDH2_DERIVE_PARAMS', 'CA_InsertMaskedObject', - 'CA_CloneAllObjectsToSession', 'CK_ECIES_PARAMS_PTR', - 'CK_X9_42_DH2_DERIVE_PARAMS_PTR', 'CK_CA_GetPedId', - 'CA_WriteCommonStore', 'CK_CA_MTKGetState', - 'CK_CA_DeleteRemotePEDVector', 'CK_KEA_DERIVE_PARAMS_PTR', - 'CA_LogImportSecret', 'CA_SwitchSecondarySlot', - 'CK_MAC_GENERAL_PARAMS_PTR', 'CK_CA_DismantleRemotePED', - 'CK_CA_GenerateCloneableMofN', - 'CK_RC5_MAC_GENERAL_PARAMS_PTR', 'CK_PARAM_TYPE', - 'CK_C_PerformSelfTest', 'CK_CA_ClonePrivateKey', 'CK_INFO', - 'CA_GetTunnelSlotNumber', 'CA_GetContainerName', - 'CK_CA_LoadModule', 'CK_OBJECT_CLASS_PTR', - 'CK_CA_ChooseSecondarySlot', 'CK_CA_IsMofNEnabled', - 'CA_MOFN_STATUS_PTR', 'CK_RC2_PARAMS', 'CA_SetLKCV'] + 'CA_GetContainerName', 'CK_AES_CTR_PARAMS', + 'CA_SetContainerSize', 'CK_LKM_TOKEN_ID_S', + 'CA_SetExtendedTPV', 'CK_CA_GetSecureElementMeta', + 'CA_GetUserContainerNumber', 'CK_ECDH2_DERIVE_PARAMS', + 'LUNA_RET_AGAIN', 'CA_InsertMaskedObject', + 'LUNA_RET_NO_OFFBOARD_STORAGE', + 'CA_CloneAllObjectsToSession', + 'LUNA_RET_LOG_AUDIT_NOT_INITIALIZED', + 'CK_CA_STCGetPartPubKey', + 'LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL', + 'RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR', + 'CK_ECIES_PARAMS_PTR', + 'LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE', + 'LUNA_RET_SM_ACCESS_REALLOC_ERROR', 'CKCA_MODULE_INFO_PTR', + 'CA_WriteCommonStore', 'CA_InitializeRemotePEDVector', + 'MSG_RTC_EXTERNAL_TAMPER_LATCHED', 'CK_CA_MTKGetState', + 'LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD', 'CK_CA_SetMofN', + 'LUNA_RET_SELF_TEST_FAILURE', + 'LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL', + 'LUNA_RET_HIFN6500_INVALID_PARAMETERS', + 'CA_CloseSecureToken', 'CK_CA_SpRawRead', + 'CK_CA_IsMofNEnabled', 'CK_C_SetAttributeValue', + 'C_GetObjectSize', 'RC_SSL_CIPHER_LIST_ERROR', + 'CK_CA_DismantleRemotePED', 'LUNA_RET_FUNCTION_CANCELED', + 'LUNA_RET_INVALID_ACCESS_LEVEL', + 'CK_CA_GetTokenInsertionCount', + 'LUNA_RET_INVALID_FUF_VERSION', + 'LUNA_RET_ISES_INIT_FAILED', + 'LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO', 'CK_PARAM_TYPE', + 'CK_CA_ListSecureToken', 'LUNA_RET_CHALLENGE_TYPE_INVALID', + 'C_GenerateRandom', 'CA_GetContainerCapabilitySet', + 'CK_CA_ClonePrivateKey', 'CK_CA_DeleteContainerWithHandle', + 'CK_HA_STATE_PTR', 'CA_GetTunnelSlotNumber', + 'LUNA_RET_RM_ELEMENT_ID_INVALID', 'CA_SetHSMPolicy', + 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR', + 'CA_SetCloningDomain', 'CK_OBJECT_CLASS_PTR', + 'CK_CA_ChooseSecondarySlot', 'CK_CA_SetHSMPolicies', + 'LUNA_RET_WRAPPED_KEY_LEN_RANGE', 'CA_MOFN_STATUS_PTR', + 'CA_SetLKCV', 'CK_RC2_PARAMS', + 'LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE'] diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index b6af1b9..15b2eaa 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -1,210 +1,210 @@ -from ctypes import CDLL -from pycryptoki.defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE -import os -import re -import sys - -def parse_chrystoki_conf(): - ''' - The autogeneration of cryptoki.py now prepends a method which sets the DLL's path to - be called every time cryptoki.py is imported. This method parses Cryptoki's configuration - file in python for the DLL's location. While originally it was desired to reuse the C code - which parses Cryptoki.conf this was not possible because Pycryptoki can only call functions - on the dll, you cannot do something like instantiate a class and then call a function on that class. - - ex: ckdemo does: - ChrystokiConfiguration conf; - char* libName = conf.LibraryFileName(); - - Option 1: - Create a new api function and make it visible in the DLL. It's not very good to put functions - that are customer visible in the API that are going to be used for testing tools. In addition - it would be necessary to store a copy of the DLL in the pycryptoki package and load this DLL - every time pycryptoki is run. This is therefore not a great option. - - Option 2: - Write a short program in C++ that compiles against luna's source code. Then python can call - this file to get the output. This would work however it create a dependency that portions of - pycryptoki must be compiled, in addition when distributing pycryptoki to the testing team it - would be necessary to distribute platform dependent code. - - Creating a compilation dependency between pycryptoki and the C code is not a good idea since - it will be necessary to make a C program in the setup for pycryptoki which increases the - complexity of the setup. - - Option 3: - Parse the file in python. - - This option was chosen because it was fairly easy to do and supported across all platforms. - It is also the simplest approach. The disadvantage to this is the configuration file may be - parsed differently in C than in python. Therefore lot of error checking was added to the parsing - process as well as printing of which DLL was found in each run of the Cryptoki library.. - ''' - - env_conf_path = os.environ.get("ChrystokiConfigurationPath") - conf_path = None - if CHRYSTOKI_DLL_FILE != None: - #Use this value for the location of the DLL - dll_path = CHRYSTOKI_DLL_FILE - print "Using DLL Path from defaults.py:" + dll_path - return dll_path - elif CHRYSTOKI_CONFIG_FILE != None: - conf_path = CHRYSTOKI_CONFIG_FILE - print "Using Chrystoki.conf location from defaults.py: " + conf_path - elif env_conf_path != None: - if 'win' in sys.platform: - env_conf_path = env_conf_path.replace('\\\\', '~').replace('~', '\\') + 'crystoki.ini' - else: - env_conf_path = os.path.join(env_conf_path, 'Chrystoki.conf') - conf_path = env_conf_path - - print "Using Chrystoki.conf location from environment variable ChrystokiConfigurationPath: " + conf_path - - if conf_path == None: - conf_path = '/etc/Chrystoki.conf' - print "No DLL Path or Chyrstoki.conf path set in defaults.py looking up DLL path in " + str(conf_path) - - print "Searching " + str(conf_path) + " for Chrystoki DLL path..." - - chrystoki_conf_text = _get_chrystoki_conf_file_text(conf_path) - - dll_path = _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text) - - print "Using DLL at location: " + dll_path - - return dll_path - -def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): - ''' - Parses the chrystoki configuration file for the section that specifies the location - of the DLL and returns the DLL location. - - @param conf_path: The path to the configuration file - @param chrystoki_conf_text: The output of the read in chrystoki configuration file - @return: The path to the chrystoki DLL - ''' - if 'win' in sys.platform: - chrystoki2_segments = re.findall("\s*\[Chrystoki2\]\s*([^\r\n]*)", chrystoki_conf_text) - - if len(chrystoki2_segments) > 1: - print chrystoki2_segments - raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) - elif len(chrystoki2_segments) < 1: - print chrystoki2_segments - raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) - - chrystoki2 = chrystoki2_segments[0].split('\n') - dll_path = "" - for line in chrystoki2: - lib_nt_line = re.findall("^\s*LibNT\s*=\s*([^\n]+)", line) - - if len(lib_nt_line) > 1: - raise Exception("Found more than one LibNT pattern on the same line") - elif len(lib_nt_line) == 1: - if (dll_path != ""): - raise Exception("Found more than one instance of LibNT in the file.") - dll_path = lib_nt_line[0].strip().strip(';').strip().strip("'").strip('"') - - if dll_path == "": - raise Exception("Error finding LibNT declaration in configuration file: " + str(conf_path)) - else: - chrystoki2_segments = re.findall("\s*Chrystoki2\s*=\s*\{([^\}]*)", chrystoki_conf_text) - - if len(chrystoki2_segments) > 1: - print chrystoki2_segments - raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) - elif len(chrystoki2_segments) < 1: - print chrystoki2_segments - raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) - - chrystoki2 = chrystoki2_segments[0].split('\n') - dll_path = "" - for line in chrystoki2: - is_64bits = sys.maxsize > 2**32 - if is_64bits: - lib_unix_line = re.findall("^\s*LibUNIX64\s*=\s*([^\n]+)", line) - else: - lib_unix_line = re.findall("^\s*LibUNIX\s*=\s*([^\n]+)", line) - - if len(lib_unix_line) > 1: - raise Exception("Found more than one LibUNIX pattern on the same line") - elif len(lib_unix_line) == 1: - if (dll_path != ""): - raise Exception("Found more than one instance of LibUNIX in the file.") - dll_path = lib_unix_line[0].strip().strip(';').strip().strip("'").strip('"') - - if dll_path == "": - raise Exception("Error finding LibUNIX declaration in configuration file: " + str(conf_path)) - - return dll_path - -def _get_chrystoki_conf_file_text(conf_path): - ''' - Reads in the chrystoki configuration and returns the text in the file - ''' - - try: - chrystoki_conf_file = open(conf_path, "r") - chrystoki_conf_text = chrystoki_conf_file.read(); - except IOError: - raise Exception("Could not find/read Chrystoki configuration file at path " + str(conf_path)) - return chrystoki_conf_text - -class CryptokiDLLException(Exception): - ''' - Custom exception class used to print an error when a call to the Cryptoki DLL failed. - The late binding makes debugging a little bit more difficult because function calls - have to pass through an additional layer of abstraction. This custom exception prints - out a quick message detailing exactly what function failed. - - ''' - def __init__(self, additional_info, orig_error): - self.msg = additional_info - self.original_error = orig_error - - def __str__(self): - return self.msg + "\n" + str(self.original_error) - -class CryptokiDLLSingleton(object): - ''' - A singleton class which holds an instance of the loaded cryptoki DLL object. - ''' - - _instance = None - loaded_dll_library = None - def __new__(cls, *args, **kwargs): - if not cls._instance: - cls._instance = super(CryptokiDLLSingleton, cls).__new__(cls, *args, **kwargs) - - dll_path = parse_chrystoki_conf() - cls._instance.dll_path = dll_path - if 'win' in sys.platform: - import ctypes - cls._instance.loaded_dll_library = ctypes.WinDLL(dll_path) - else: - cls._instance.loaded_dll_library = CDLL(dll_path) - return cls._instance - - def get_dll(self): - if self.loaded_dll_library == None or self.loaded_dll_library == "": - raise Exception("DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read /etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") - return self.loaded_dll_library - -def make_late_binding_function(function_name): - ''' - A function factory for creating a function that will bind to the cryptoki - DLL only when the function is called. - ''' - - def luna_function(*args, **kwargs): - late_binded_function = eval("CryptokiDLLSingleton().get_dll()." + function_name) - late_binded_function.restype = luna_function.restype - late_binded_function.argtypes = luna_function.argtypes - - try: - return_value = late_binded_function(*args, **kwargs) - return return_value - except Exception as e: - raise CryptokiDLLException("Call to '" + function_name + str(args) + str(kwargs) + "' failed.", e) - - return luna_function +from ctypes import CDLL +from pycryptoki.defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE +import os +import re +import sys + +def parse_chrystoki_conf(): + ''' + The autogeneration of cryptoki.py now prepends a method which sets the DLL's path to + be called every time cryptoki.py is imported. This method parses Cryptoki's configuration + file in python for the DLL's location. While originally it was desired to reuse the C code + which parses Cryptoki.conf this was not possible because Pycryptoki can only call functions + on the dll, you cannot do something like instantiate a class and then call a function on that class. + + ex: ckdemo does: + ChrystokiConfiguration conf; + char* libName = conf.LibraryFileName(); + + Option 1: + Create a new api function and make it visible in the DLL. It's not very good to put functions + that are customer visible in the API that are going to be used for testing tools. In addition + it would be necessary to store a copy of the DLL in the pycryptoki package and load this DLL + every time pycryptoki is run. This is therefore not a great option. + + Option 2: + Write a short program in C++ that compiles against luna's source code. Then python can call + this file to get the output. This would work however it create a dependency that portions of + pycryptoki must be compiled, in addition when distributing pycryptoki to the testing team it + would be necessary to distribute platform dependent code. + + Creating a compilation dependency between pycryptoki and the C code is not a good idea since + it will be necessary to make a C program in the setup for pycryptoki which increases the + complexity of the setup. + + Option 3: + Parse the file in python. + + This option was chosen because it was fairly easy to do and supported across all platforms. + It is also the simplest approach. The disadvantage to this is the configuration file may be + parsed differently in C than in python. Therefore lot of error checking was added to the parsing + process as well as printing of which DLL was found in each run of the Cryptoki library.. + ''' + + env_conf_path = os.environ.get("ChrystokiConfigurationPath") + conf_path = None + if CHRYSTOKI_DLL_FILE != None: + #Use this value for the location of the DLL + dll_path = CHRYSTOKI_DLL_FILE + print "Using DLL Path from defaults.py:" + dll_path + return dll_path + elif CHRYSTOKI_CONFIG_FILE != None: + conf_path = CHRYSTOKI_CONFIG_FILE + print "Using Chrystoki.conf location from defaults.py: " + conf_path + elif env_conf_path != None: + if 'win' in sys.platform: + env_conf_path = env_conf_path.replace('\\\\', '~').replace('~', '\\') + 'crystoki.ini' + else: + env_conf_path = os.path.join(env_conf_path, 'Chrystoki.conf') + conf_path = env_conf_path + + print "Using Chrystoki.conf location from environment variable ChrystokiConfigurationPath: " + conf_path + + if conf_path == None: + conf_path = '/etc/Chrystoki.conf' + print "No DLL Path or Chyrstoki.conf path set in defaults.py looking up DLL path in " + str(conf_path) + + print "Searching " + str(conf_path) + " for Chrystoki DLL path..." + + chrystoki_conf_text = _get_chrystoki_conf_file_text(conf_path) + + dll_path = _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text) + + print "Using DLL at location: " + dll_path + + return dll_path + +def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): + ''' + Parses the chrystoki configuration file for the section that specifies the location + of the DLL and returns the DLL location. + + @param conf_path: The path to the configuration file + @param chrystoki_conf_text: The output of the read in chrystoki configuration file + @return: The path to the chrystoki DLL + ''' + if 'win' in sys.platform: + chrystoki2_segments = re.findall("\s*\[Chrystoki2\]\s*([^\r\n]*)", chrystoki_conf_text) + + if len(chrystoki2_segments) > 1: + print chrystoki2_segments + raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + elif len(chrystoki2_segments) < 1: + print chrystoki2_segments + raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) + + chrystoki2 = chrystoki2_segments[0].split('\n') + dll_path = "" + for line in chrystoki2: + lib_nt_line = re.findall("^\s*LibNT\s*=\s*([^\n]+)", line) + + if len(lib_nt_line) > 1: + raise Exception("Found more than one LibNT pattern on the same line") + elif len(lib_nt_line) == 1: + if (dll_path != ""): + raise Exception("Found more than one instance of LibNT in the file.") + dll_path = lib_nt_line[0].strip().strip(';').strip().strip("'").strip('"') + + if dll_path == "": + raise Exception("Error finding LibNT declaration in configuration file: " + str(conf_path)) + else: + chrystoki2_segments = re.findall("\s*Chrystoki2\s*=\s*\{([^\}]*)", chrystoki_conf_text) + + if len(chrystoki2_segments) > 1: + print chrystoki2_segments + raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + elif len(chrystoki2_segments) < 1: + print chrystoki2_segments + raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) + + chrystoki2 = chrystoki2_segments[0].split('\n') + dll_path = "" + for line in chrystoki2: + is_64bits = sys.maxsize > 2**32 + if is_64bits: + lib_unix_line = re.findall("^\s*LibUNIX64\s*=\s*([^\n]+)", line) + else: + lib_unix_line = re.findall("^\s*LibUNIX\s*=\s*([^\n]+)", line) + + if len(lib_unix_line) > 1: + raise Exception("Found more than one LibUNIX pattern on the same line") + elif len(lib_unix_line) == 1: + if (dll_path != ""): + raise Exception("Found more than one instance of LibUNIX in the file.") + dll_path = lib_unix_line[0].strip().strip(';').strip().strip("'").strip('"') + + if dll_path == "": + raise Exception("Error finding LibUNIX declaration in configuration file: " + str(conf_path)) + + return dll_path + +def _get_chrystoki_conf_file_text(conf_path): + ''' + Reads in the chrystoki configuration and returns the text in the file + ''' + + try: + chrystoki_conf_file = open(conf_path, "r") + chrystoki_conf_text = chrystoki_conf_file.read(); + except IOError: + raise Exception("Could not find/read Chrystoki configuration file at path " + str(conf_path)) + return chrystoki_conf_text + +class CryptokiDLLException(Exception): + ''' + Custom exception class used to print an error when a call to the Cryptoki DLL failed. + The late binding makes debugging a little bit more difficult because function calls + have to pass through an additional layer of abstraction. This custom exception prints + out a quick message detailing exactly what function failed. + + ''' + def __init__(self, additional_info, orig_error): + self.msg = additional_info + self.original_error = orig_error + + def __str__(self): + return self.msg + "\n" + str(self.original_error) + +class CryptokiDLLSingleton(object): + ''' + A singleton class which holds an instance of the loaded cryptoki DLL object. + ''' + + _instance = None + loaded_dll_library = None + def __new__(cls, *args, **kwargs): + if not cls._instance: + cls._instance = super(CryptokiDLLSingleton, cls).__new__(cls, *args, **kwargs) + + dll_path = parse_chrystoki_conf() + cls._instance.dll_path = dll_path + if 'win' in sys.platform: + import ctypes + cls._instance.loaded_dll_library = ctypes.WinDLL(dll_path) + else: + cls._instance.loaded_dll_library = CDLL(dll_path) + return cls._instance + + def get_dll(self): + if self.loaded_dll_library == None or self.loaded_dll_library == "": + raise Exception("DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read /etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") + return self.loaded_dll_library + +def make_late_binding_function(function_name): + ''' + A function factory for creating a function that will bind to the cryptoki + DLL only when the function is called. + ''' + + def luna_function(*args, **kwargs): + late_binded_function = eval("CryptokiDLLSingleton().get_dll()." + function_name) + late_binded_function.restype = luna_function.restype + late_binded_function.argtypes = luna_function.argtypes + + try: + return_value = late_binded_function(*args, **kwargs) + return return_value + except Exception as e: + raise CryptokiDLLException("Call to '" + function_name + str(args) + str(kwargs) + "' failed.", e) + + return luna_function diff --git a/pycryptoki/daemon/pycryptoki_daemon.py b/pycryptoki/daemon/pycryptoki_daemon.py index c3ea9be..f53cd91 100755 --- a/pycryptoki/daemon/pycryptoki_daemon.py +++ b/pycryptoki/daemon/pycryptoki_daemon.py @@ -1,297 +1,261 @@ -''' -xmlrpc server daemon that wraps pycryptoki so pycryptoki can be used over -the network -''' -from ConfigParser import ConfigParser -from SimpleXMLRPCServer import SimpleXMLRPCServer -from StringIO import StringIO -from optparse import OptionParser -import xmlrpclib -from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ - ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ - ca_insert, ca_insert_ex -from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ - c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex -from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ - c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ - c_derive_key, c_derive_key_ex -from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ - c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ - c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ - c_create_object_ex -from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ - c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex -from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ - ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ - ca_set_container_policy, ca_set_container_policy_ex -from pycryptoki.session_management import c_initialize, c_initialize_ex, \ - c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, c_get_session_info, c_get_session_info_ex, \ - c_get_token_info, c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ - c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ - c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ - ca_create_container_ex, login, login_ex -from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex -from pycryptoki.token_management import c_init_token, c_init_token_ex, \ - c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ - c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex -from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ - ca_init_audit_ex, ca_time_sync, ca_time_sync_ex -from _ctypes import pointer -from ctypes import cast -import ctypes -from pycryptoki.key_generator import _get_mechanism -from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR -from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex,\ - ca_settokencertificatesignature, ca_settokencertificatesignature_ex, \ - ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ - ca_initializeremotepedvector, ca_initializeremotepedvector_ex, ca_deleteremotepedvector, \ - ca_deleteremotepedvector_ex, ca_mtkrestore, ca_mtkrestore_ex, ca_mtkresplit, \ - ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex -from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ - ca_modifyusagecount, ca_modifyusagecount_ex -from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, \ - ca_duplicatemofn_ex - -''' -All the functions the server supports -''' -pycryptoki_functions = {"c_wrap_key" : c_wrap_key, - "c_wrap_key_ex" : c_wrap_key_ex, - "c_unwrap_key" : c_unwrap_key, - "c_unwrap_key_ex" : c_unwrap_key_ex, - "c_destroy_object" : c_destroy_object, - "c_destroy_object_ex" : c_destroy_object_ex, - "c_generate_random" : c_generate_random, - "c_generate_random_ex" : c_generate_random_ex, - "c_seed_random" : c_seed_random, - "c_seed_random_ex" : c_seed_random_ex, - "c_digest" : c_digest, - "c_digest_ex" : c_digest_ex, - "c_set_ped_id" : c_set_ped_id, - "c_set_ped_id_ex" : c_set_ped_id_ex, - "c_get_ped_id" : c_get_ped_id, - "c_get_ped_id_ex" : c_get_ped_id_ex, - "ca_set_hsm_policy" : ca_set_hsm_policy, - "ca_set_hsm_policy_ex" : ca_set_hsm_policy_ex, - "ca_set_destructive_hsm_policy" : ca_set_destructive_hsm_policy, - "ca_set_destructive_hsm_policy_ex" : ca_set_destructive_hsm_policy_ex, - "ca_set_container_policy" : ca_set_container_policy, - "ca_set_container_policy_ex" : ca_set_container_policy_ex, - "c_initialize" : c_initialize, - "c_initialize_ex" : c_initialize_ex, - "c_finalize" : c_finalize, - "c_finalize_ex" : c_finalize_ex, - "c_open_session" : c_open_session, - "c_open_session_ex" : c_open_session_ex, - "login" : login, - "login_ex" : login_ex, - "c_get_session_info" : c_get_session_info, - "c_get_session_info_ex" : c_get_session_info_ex, - "c_get_token_info" : c_get_token_info, - "c_get_token_info_ex" : c_get_token_info_ex, - "c_close_session" : c_close_session, - "c_close_session_ex" : c_close_session_ex, - "c_logout" : c_logout, - "c_logout_ex" : c_logout_ex, - "c_init_pin" : c_init_pin, - "c_init_pin_ex" : c_init_pin_ex, - "ca_factory_reset" : ca_factory_reset, - "ca_factory_reset_ex" : ca_factory_reset_ex, - "c_set_pin" : c_set_pin, - "c_set_pin_ex" : c_set_pin_ex, - "c_close_all_sessions" : c_close_all_sessions, - "c_close_all_sessions_ex" : c_close_all_sessions_ex, - "ca_create_container" : ca_create_container, - "ca_create_container_ex" : ca_create_container_ex, - "c_init_token" : c_init_token, - "c_init_token_ex" : c_init_token_ex, - "c_get_mechanism_list" : c_get_mechanism_list, - "c_get_mechanism_list_ex" : c_get_mechanism_list_ex, - "c_get_mechanism_info" : c_get_mechanism_info, - "c_get_mechanism_info_ex" : c_get_mechanism_info_ex, - "get_token_by_label" : get_token_by_label, - "get_token_by_label_ex" : get_token_by_label_ex, - "ca_close_secure_token" : ca_close_secure_token, - "ca_close_secure_token" : ca_close_secure_token_ex, - "ca_open_secure_token" : ca_open_secure_token, - "ca_open_secure_token_ex" : ca_open_secure_token_ex, - "ca_extract" : ca_extract, - "ca_extract_ex" : ca_extract_ex, - "ca_insert" : ca_insert, - "ca_insert_ex" : ca_insert_ex, - "c_set_attribute_value" : c_set_attribute_value, - "c_set_attribute_value_ex" : c_set_attribute_value_ex, - "c_generate_key" : c_generate_key, - "c_generate_key_ex" : c_generate_key_ex, - "c_generate_key_pair" : c_generate_key_pair, - "c_generate_key_pair_ex" : c_generate_key_pair_ex, - "c_create_object" : c_create_object, - "c_create_object_ex" : c_create_object_ex, - "ca_get_time": ca_get_time, - "ca_get_time_ex": ca_get_time_ex, - "ca_init_audit": ca_init_audit, - "ca_init_audit_ex": ca_init_audit_ex, - "ca_time_sync": ca_time_sync, - "ca_time_sync_ex": ca_time_sync_ex, - "c_performselftest" : c_performselftest, - "c_performselftest_ex" : c_performselftest_ex, - "ca_settokencertificatesignature" : ca_settokencertificatesignature, - "ca_settokencertificatesignature_ex" : ca_settokencertificatesignature_ex, - "ca_hainit" : ca_hainit, - "ca_hainit_ex" : ca_hainit_ex, - "ca_createloginchallenge" : ca_createloginchallenge, - "ca_createloginchallenge_ex" : ca_createloginchallenge_ex, - "ca_initializeremotepedvector" : ca_initializeremotepedvector, - "ca_initializeremotepedvector_ex" : ca_initializeremotepedvector_ex, - "ca_deleteremotepedvector" : ca_deleteremotepedvector, - "ca_deleteremotepedvector_ex" : ca_deleteremotepedvector_ex, - "ca_mtkrestore" : ca_mtkrestore, - "ca_mtkrestore_ex" : ca_mtkrestore_ex, - "ca_mtkresplit" : ca_mtkresplit, - "ca_mtkresplit_ex" : ca_mtkresplit_ex, - "ca_mtkzeroize" : ca_mtkzeroize, - "ca_mtkzeroize_ex" : ca_mtkzeroize_ex, - "ca_generatemofn" : ca_generatemofn, - "ca_generatemofn_ex" : ca_generatemofn_ex, - "ca_modifyusagecount" : ca_modifyusagecount, - "ca_modifyusagecount_ex" : ca_modifyusagecount_ex, - "ca_clonemofn" : ca_clonemofn, - "ca_clonemofn_ex" : ca_clonemofn_ex, - "ca_duplicatemofn" : ca_duplicatemofn, - "ca_duplicatemofn_ex" : ca_duplicatemofn_ex, - } - -''' -Functions with arguments/return values that need specialized -serialization/deserialization -''' -functions_needing_serialization = { - "c_find_objects" : c_find_objects, - "c_find_objects_ex" : c_find_objects_ex, - "c_get_attribute_value" : c_get_attribute_value, - "c_get_attribute_value_ex" : c_get_attribute_value_ex, - "c_sign": c_sign, - "c_sign_ex": c_sign_ex, - "c_encrypt": c_encrypt, - "c_encrypt_ex": c_encrypt_ex, - "c_verify" : c_verify, - "c_verify_ex" : c_verify_ex, - "c_derive_key" : c_derive_key, - "c_derive_key_ex" : c_derive_key_ex, - "c_decrypt_ex" : c_decrypt_ex, - "c_decrypt" : c_decrypt - } - - -def initialize_server(ip, port): - print "Initializing Server" - server = SimpleXMLRPCServer((ip, port)) - server.logRequests = 0 - - #Dynamically add functions to server - for key, value in pycryptoki_functions.iteritems(): - server.register_function(value, key) - - #For functions that need better serialization, do it - for key, value in functions_needing_serialization.iteritems(): - server.register_function(eval(key + "_serialize"), key) - - return server - - -def serialize_dict(dictionary): - ''' - Helper function to convert a dictionary with to - for xmlrpc - ''' - serialized_dictionary = {} - for key, value in dictionary.iteritems(): - serialized_dictionary[str(key)] = value - return serialized_dictionary - -def c_get_attribute_value_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - ret, dictionary = c_get_attribute_value(h_session, h_object, template) - return ret, serialize_dict(dictionary) - -def c_get_attribute_value_ex_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - dictionary = c_get_attribute_value_ex(h_session, h_object, template) - return serialize_dict(dictionary) - -def c_find_objects_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - ret, dictionary = c_find_objects(h_session, h_object, template) - return ret, serialize_dict(dictionary) - -def c_find_objects_ex_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - dictionary = c_find_objects_ex(h_session, h_object, template) - return serialize_dict(dictionary) - -def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) - -def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) - -def c_sign_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): - ret, signature = c_sign(h_session, sign_flavor, data_to_sign, h_key, mech) - return ret, xmlrpclib.Binary(signature) - -def c_sign_ex_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): - signature = c_sign_ex(h_session, sign_flavor, data_to_sign, h_key, mech) - return xmlrpclib.Binary(signature) - -def c_encrypt_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - ret, enc_data = c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech) - return ret, xmlrpclib.Binary(enc_data) - -def c_encrypt_ex_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - enc_data = c_encrypt_ex(h_session, encryption_flavor, h_key, data_to_encrypt, mech) - return xmlrpclib.Binary(enc_data) - -def c_verify_serialize( h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - return c_verify(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) - -def c_verify_ex_serialize(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - return c_verify_ex(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) - -def c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): - return c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) - -def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): - return c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) - -if __name__ == '__main__': - #Setup argument parser - resources_config_parser = ConfigParser(); - parser = OptionParser() - parser.add_option("-i", "--ip_address", dest="i", - help="pycryptoki daemon IP address", metavar="") - parser.add_option("-p", "--port", dest="p", - help="pycryptoki daemon IP port", metavar="") - (options, args) = parser.parse_args() - - #Default arguments - ip = options.i if options.i != None else 'localhost' - port = int( options.p if options.p != None else '8001') - print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) - - server = initialize_server(ip, port) - - # run until we die - print "Starting Server" - server.serve_forever() +#!/usr/bin/env python +''' +xmlrpc server daemon that wraps pycryptoki so pycryptoki can be used over +the network +''' +from ConfigParser import ConfigParser +from SimpleXMLRPCServer import SimpleXMLRPCServer +from StringIO import StringIO +from optparse import OptionParser +import xmlrpclib +from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ + ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ + ca_insert, ca_insert_ex +from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ + c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex +from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ + c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ + c_derive_key, c_derive_key_ex +from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ + c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ + c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ + c_create_object_ex +from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ + c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex +from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ + ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ + ca_set_container_policy, ca_set_container_policy_ex +from pycryptoki.session_management import c_initialize, c_initialize_ex, \ + c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, c_get_token_info, \ + c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ + c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ + c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ + ca_create_container_ex, login, login_ex +from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex +from pycryptoki.token_management import c_init_token, c_init_token_ex, \ + c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ + c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex +from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ + ca_init_audit_ex, ca_time_sync, ca_time_sync_ex +from _ctypes import pointer +from ctypes import cast +import ctypes +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR + + +''' +All the functions the server supports +''' +pycryptoki_functions = {"c_wrap_key" : c_wrap_key, + "c_wrap_key_ex" : c_wrap_key_ex, + "c_unwrap_key" : c_unwrap_key, + "c_unwrap_key_ex" : c_unwrap_key_ex, + "c_destroy_object" : c_destroy_object, + "c_destroy_object_ex" : c_destroy_object_ex, + "c_generate_random" : c_generate_random, + "c_generate_random_ex" : c_generate_random_ex, + "c_seed_random" : c_seed_random, + "c_seed_random_ex" : c_seed_random_ex, + "c_digest" : c_digest, + "c_digest_ex" : c_digest_ex, + "c_set_ped_id" : c_set_ped_id, + "c_set_ped_id_ex" : c_set_ped_id_ex, + "c_get_ped_id" : c_get_ped_id, + "c_get_ped_id_ex" : c_get_ped_id_ex, + "ca_set_hsm_policy" : ca_set_hsm_policy, + "ca_set_hsm_policy_ex" : ca_set_hsm_policy_ex, + "ca_set_destructive_hsm_policy" : ca_set_destructive_hsm_policy, + "ca_set_destructive_hsm_policy_ex" : ca_set_destructive_hsm_policy_ex, + "ca_set_container_policy" : ca_set_container_policy, + "ca_set_container_policy_ex" : ca_set_container_policy_ex, + "c_initialize" : c_initialize, + "c_initialize_ex" : c_initialize_ex, + "c_finalize" : c_finalize, + "c_finalize_ex" : c_finalize_ex, + "c_open_session" : c_open_session, + "c_open_session_ex" : c_open_session_ex, + "login" : login, + "login_ex" : login_ex, + "c_get_token_info" : c_get_token_info, + "c_get_token_info_ex" : c_get_token_info_ex, + "c_close_session" : c_close_session, + "c_close_session_ex" : c_close_session_ex, + "c_logout" : c_logout, + "c_logout_ex" : c_logout_ex, + "c_init_pin" : c_init_pin, + "c_init_pin_ex" : c_init_pin_ex, + "ca_factory_reset" : ca_factory_reset, + "ca_factory_reset_ex" : ca_factory_reset_ex, + "c_set_pin" : c_set_pin, + "c_set_pin_ex" : c_set_pin_ex, + "c_close_all_sessions" : c_close_all_sessions, + "c_close_all_sessions_ex" : c_close_all_sessions_ex, + "ca_create_container" : ca_create_container, + "ca_create_container_ex" : ca_create_container_ex, + "c_init_token" : c_init_token, + "c_init_token_ex" : c_init_token_ex, + "c_get_mechanism_list" : c_get_mechanism_list, + "c_get_mechanism_list_ex" : c_get_mechanism_list_ex, + "c_get_mechanism_info" : c_get_mechanism_info, + "c_get_mechanism_info_ex" : c_get_mechanism_info_ex, + "get_token_by_label" : get_token_by_label, + "get_token_by_label_ex" : get_token_by_label_ex, + "ca_close_secure_token" : ca_close_secure_token, + "ca_close_secure_token" : ca_close_secure_token_ex, + "ca_open_secure_token" : ca_open_secure_token, + "ca_open_secure_token_ex" : ca_open_secure_token_ex, + "ca_extract" : ca_extract, + "ca_extract_ex" : ca_extract_ex, + "ca_insert" : ca_insert, + "ca_insert_ex" : ca_insert_ex, + "c_set_attribute_value" : c_set_attribute_value, + "c_set_attribute_value_ex" : c_set_attribute_value_ex, + "c_generate_key" : c_generate_key, + "c_generate_key_ex" : c_generate_key_ex, + "c_generate_key_pair" : c_generate_key_pair, + "c_generate_key_pair_ex" : c_generate_key_pair_ex, + "c_create_object" : c_create_object, + "c_create_object_ex" : c_create_object_ex, + "ca_get_time": ca_get_time, + "ca_get_time_ex": ca_get_time_ex, + "ca_init_audit": ca_init_audit, + "ca_init_audit_ex": ca_init_audit_ex, + "ca_time_sync": ca_time_sync, + "ca_time_sync_ex": ca_time_sync_ex + } + +''' +Functions with arguments/return values that need specialized +serialization/deserialization +''' +functions_needing_serialization = { + "c_find_objects" : c_find_objects, + "c_find_objects_ex" : c_find_objects_ex, + "c_get_attribute_value" : c_get_attribute_value, + "c_get_attribute_value_ex" : c_get_attribute_value_ex, + "c_sign": c_sign, + "c_sign_ex": c_sign_ex, + "c_encrypt": c_encrypt, + "c_encrypt_ex": c_encrypt_ex, + "c_verify" : c_verify, + "c_verify_ex" : c_verify_ex, + "c_derive_key" : c_derive_key, + "c_derive_key_ex" : c_derive_key_ex, + "c_decrypt_ex" : c_decrypt_ex, + "c_decrypt" : c_decrypt + } + + +def initialize_server(ip, port): + print "Initializing Server" + server = SimpleXMLRPCServer((ip, port)) + server.logRequests = 0 + + #Dynamically add functions to server + for key, value in pycryptoki_functions.iteritems(): + server.register_function(value, key) + + #For functions that need better serialization, do it + for key, value in functions_needing_serialization.iteritems(): + server.register_function(eval(key + "_serialize"), key) + + return server + + +def serialize_dict(dictionary): + ''' + Helper function to convert a dictionary with to + for xmlrpc + ''' + serialized_dictionary = {} + for key, value in dictionary.iteritems(): + serialized_dictionary[str(key)] = value + return serialized_dictionary + +def c_get_attribute_value_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + ret, dictionary = c_get_attribute_value(h_session, h_object, template) + return ret, serialize_dict(dictionary) + +def c_get_attribute_value_ex_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + dictionary = c_get_attribute_value_ex(h_session, h_object, template) + return serialize_dict(dictionary) + +def c_find_objects_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + ret, dictionary = c_find_objects(h_session, h_object, template) + return ret, serialize_dict(dictionary) + +def c_find_objects_ex_serialize(h_session, h_object, template): + ''' returns dictionary with k,v pairs of for xmlrpc''' + dictionary = c_find_objects_ex(h_session, h_object, template) + return serialize_dict(dictionary) + +def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) + +def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) + +def c_sign_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + ret, signature = c_sign(h_session, sign_flavor, data_to_sign, h_key, mech) + return ret, xmlrpclib.Binary(signature) + +def c_sign_ex_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + signature = c_sign_ex(h_session, sign_flavor, data_to_sign, h_key, mech) + return xmlrpclib.Binary(signature) + +def c_encrypt_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + ret, enc_data = c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech) + return ret, xmlrpclib.Binary(enc_data) + +def c_encrypt_ex_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + enc_data = c_encrypt_ex(h_session, encryption_flavor, h_key, data_to_encrypt, mech) + return xmlrpclib.Binary(enc_data) + +def c_verify_serialize( h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + return c_verify(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) + +def c_verify_ex_serialize(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + return c_verify_ex(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) + +def c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + return c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) + +def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + return c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) + +if __name__ == '__main__': + #Setup argument parser + resources_config_parser = ConfigParser(); + parser = OptionParser() + parser.add_option("-i", "--ip_address", dest="i", + help="pycryptoki daemon IP address", metavar="") + parser.add_option("-p", "--port", dest="p", + help="pycryptoki daemon IP port", metavar="") + (options, args) = parser.parse_args() + + #Default arguments + ip = options.i if options.i != None else 'localhost' + port = int( options.p if options.p != None else '8001') + print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) + + server = initialize_server(ip, port) + + # run until we die + print "Starting Server" + server.serve_forever() diff --git a/pycryptoki/daemon/pycryptoki_daemon.py.bak b/pycryptoki/daemon/pycryptoki_daemon.py.bak deleted file mode 100755 index fdc2be4..0000000 --- a/pycryptoki/daemon/pycryptoki_daemon.py.bak +++ /dev/null @@ -1,295 +0,0 @@ -''' -xmlrpc server daemon that wraps pycryptoki so pycryptoki can be used over -the network -''' -from ConfigParser import ConfigParser -from SimpleXMLRPCServer import SimpleXMLRPCServer -from StringIO import StringIO -from optparse import OptionParser -import xmlrpclib -from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ - ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ - ca_insert, ca_insert_ex -from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ - c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex -from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ - c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ - c_derive_key, c_derive_key_ex -from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ - c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ - c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ - c_create_object_ex -from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ - c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex -from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ - ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ - ca_set_container_policy, ca_set_container_policy_ex -from pycryptoki.session_management import c_initialize, c_initialize_ex, \ - c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, c_get_token_info, \ - c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ - c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ - c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ - ca_create_container_ex, login, login_ex -from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex -from pycryptoki.token_management import c_init_token, c_init_token_ex, \ - c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ - c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex -from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ - ca_init_audit_ex, ca_time_sync, ca_time_sync_ex -from _ctypes import pointer -from ctypes import cast -import ctypes -from pycryptoki.key_generator import _get_mechanism -from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR -from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex,\ - ca_settokencertificatesignature, ca_c_settokencertificatesignature_ex, \ - ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ - ca_initializeremotepedvector, ca_initializeremotepedvector_ex, ca_deleteremotepedvector, \ - ca_deleteremotepedvector_ex, ca_mtkrestore, ca_mtkrestore_ex, ca_mtkresplit, \ - ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex -from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ - ca_modifyusagecount, ca_modifyusagecount_ex -from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, \ - ca_duplicatemofn_ex - -''' -All the functions the server supports -''' -pycryptoki_functions = {"c_wrap_key" : c_wrap_key, - "c_wrap_key_ex" : c_wrap_key_ex, - "c_unwrap_key" : c_unwrap_key, - "c_unwrap_key_ex" : c_unwrap_key_ex, - "c_destroy_object" : c_destroy_object, - "c_destroy_object_ex" : c_destroy_object_ex, - "c_generate_random" : c_generate_random, - "c_generate_random_ex" : c_generate_random_ex, - "c_seed_random" : c_seed_random, - "c_seed_random_ex" : c_seed_random_ex, - "c_digest" : c_digest, - "c_digest_ex" : c_digest_ex, - "c_set_ped_id" : c_set_ped_id, - "c_set_ped_id_ex" : c_set_ped_id_ex, - "c_get_ped_id" : c_get_ped_id, - "c_get_ped_id_ex" : c_get_ped_id_ex, - "ca_set_hsm_policy" : ca_set_hsm_policy, - "ca_set_hsm_policy_ex" : ca_set_hsm_policy_ex, - "ca_set_destructive_hsm_policy" : ca_set_destructive_hsm_policy, - "ca_set_destructive_hsm_policy_ex" : ca_set_destructive_hsm_policy_ex, - "ca_set_container_policy" : ca_set_container_policy, - "ca_set_container_policy_ex" : ca_set_container_policy_ex, - "c_initialize" : c_initialize, - "c_initialize_ex" : c_initialize_ex, - "c_finalize" : c_finalize, - "c_finalize_ex" : c_finalize_ex, - "c_open_session" : c_open_session, - "c_open_session_ex" : c_open_session_ex, - "login" : login, - "login_ex" : login_ex, - "c_get_token_info" : c_get_token_info, - "c_get_token_info_ex" : c_get_token_info_ex, - "c_close_session" : c_close_session, - "c_close_session_ex" : c_close_session_ex, - "c_logout" : c_logout, - "c_logout_ex" : c_logout_ex, - "c_init_pin" : c_init_pin, - "c_init_pin_ex" : c_init_pin_ex, - "ca_factory_reset" : ca_factory_reset, - "ca_factory_reset_ex" : ca_factory_reset_ex, - "c_set_pin" : c_set_pin, - "c_set_pin_ex" : c_set_pin_ex, - "c_close_all_sessions" : c_close_all_sessions, - "c_close_all_sessions_ex" : c_close_all_sessions_ex, - "ca_create_container" : ca_create_container, - "ca_create_container_ex" : ca_create_container_ex, - "c_init_token" : c_init_token, - "c_init_token_ex" : c_init_token_ex, - "c_get_mechanism_list" : c_get_mechanism_list, - "c_get_mechanism_list_ex" : c_get_mechanism_list_ex, - "c_get_mechanism_info" : c_get_mechanism_info, - "c_get_mechanism_info_ex" : c_get_mechanism_info_ex, - "get_token_by_label" : get_token_by_label, - "get_token_by_label_ex" : get_token_by_label_ex, - "ca_close_secure_token" : ca_close_secure_token, - "ca_close_secure_token" : ca_close_secure_token_ex, - "ca_open_secure_token" : ca_open_secure_token, - "ca_open_secure_token_ex" : ca_open_secure_token_ex, - "ca_extract" : ca_extract, - "ca_extract_ex" : ca_extract_ex, - "ca_insert" : ca_insert, - "ca_insert_ex" : ca_insert_ex, - "c_set_attribute_value" : c_set_attribute_value, - "c_set_attribute_value_ex" : c_set_attribute_value_ex, - "c_generate_key" : c_generate_key, - "c_generate_key_ex" : c_generate_key_ex, - "c_generate_key_pair" : c_generate_key_pair, - "c_generate_key_pair_ex" : c_generate_key_pair_ex, - "c_create_object" : c_create_object, - "c_create_object_ex" : c_create_object_ex, - "ca_get_time": ca_get_time, - "ca_get_time_ex": ca_get_time_ex, - "ca_init_audit": ca_init_audit, - "ca_init_audit_ex": ca_init_audit_ex, - "ca_time_sync": ca_time_sync, - "ca_time_sync_ex": ca_time_sync_ex, - "c_performselftest" : c_performselftest, - "c_performselftest_ex" : c_performselftest_ex, - "ca_settokencertificatesignature" : ca_settokencertificatesignature, - "ca_settokencertificatesignature_ex" : ca_c_settokencertificatesignature_ex, - "ca_hainit" : ca_hainit, - "ca_hainit_ex" : ca_hainit_ex, - "ca_createloginchallenge" : ca_createloginchallenge, - "ca_createloginchallenge_ex" : ca_createloginchallenge_ex, - "ca_initializeremotepedvector" : ca_initializeremotepedvector, - "ca_initializeremotepedvector_ex" : ca_initializeremotepedvector_ex, - "ca_deleteremotepedvector" : ca_deleteremotepedvector, - "ca_deleteremotepedvector_ex" : ca_deleteremotepedvector_ex, - "ca_mtkrestore" : ca_mtkrestore, - "ca_mtkrestore_ex" : ca_mtkrestore_ex, - "ca_mtkresplit" : ca_mtkresplit, - "ca_mtkresplit_ex" : ca_mtkresplit_ex, - "ca_mtkzeroize" : ca_mtkzeroize, - "ca_mtkzeroize_ex" : ca_mtkzeroize_ex, - "ca_generatemofn" : ca_generatemofn, - "ca_generatemofn_ex" : ca_generatemofn_ex, - "ca_modifyusagecount" : ca_modifyusagecount, - "ca_modifyusagecount_ex" : ca_modifyusagecount_ex, - "ca_clonemofn" : ca_clonemofn, - "ca_clonemofn_ex" : ca_clonemofn_ex, - "ca_duplicatemofn" : ca_duplicatemofn, - "ca_duplicatemofn_ex" : ca_duplicatemofn_ex, - } - -''' -Functions with arguments/return values that need specialized -serialization/deserialization -''' -functions_needing_serialization = { - "c_find_objects" : c_find_objects, - "c_find_objects_ex" : c_find_objects_ex, - "c_get_attribute_value" : c_get_attribute_value, - "c_get_attribute_value_ex" : c_get_attribute_value_ex, - "c_sign": c_sign, - "c_sign_ex": c_sign_ex, - "c_encrypt": c_encrypt, - "c_encrypt_ex": c_encrypt_ex, - "c_verify" : c_verify, - "c_verify_ex" : c_verify_ex, - "c_derive_key" : c_derive_key, - "c_derive_key_ex" : c_derive_key_ex, - "c_decrypt_ex" : c_decrypt_ex, - "c_decrypt" : c_decrypt - } - - -def initialize_server(ip, port): - print "Initializing Server" - server = SimpleXMLRPCServer((ip, port)) - server.logRequests = 0 - - #Dynamically add functions to server - for key, value in pycryptoki_functions.iteritems(): - server.register_function(value, key) - - #For functions that need better serialization, do it - for key, value in functions_needing_serialization.iteritems(): - server.register_function(eval(key + "_serialize"), key) - - return server - - -def serialize_dict(dictionary): - ''' - Helper function to convert a dictionary with to - for xmlrpc - ''' - serialized_dictionary = {} - for key, value in dictionary.iteritems(): - serialized_dictionary[str(key)] = value - return serialized_dictionary - -def c_get_attribute_value_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - ret, dictionary = c_get_attribute_value(h_session, h_object, template) - return ret, serialize_dict(dictionary) - -def c_get_attribute_value_ex_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - dictionary = c_get_attribute_value_ex(h_session, h_object, template) - return serialize_dict(dictionary) - -def c_find_objects_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - ret, dictionary = c_find_objects(h_session, h_object, template) - return ret, serialize_dict(dictionary) - -def c_find_objects_ex_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' - dictionary = c_find_objects_ex(h_session, h_object, template) - return serialize_dict(dictionary) - -def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) - -def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) - -def c_sign_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): - ret, signature = c_sign(h_session, sign_flavor, data_to_sign, h_key, mech) - return ret, xmlrpclib.Binary(signature) - -def c_sign_ex_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): - signature = c_sign_ex(h_session, sign_flavor, data_to_sign, h_key, mech) - return xmlrpclib.Binary(signature) - -def c_encrypt_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - ret, enc_data = c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech) - return ret, xmlrpclib.Binary(enc_data) - -def c_encrypt_ex_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - enc_data = c_encrypt_ex(h_session, encryption_flavor, h_key, data_to_encrypt, mech) - return xmlrpclib.Binary(enc_data) - -def c_verify_serialize( h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - return c_verify(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) - -def c_verify_ex_serialize(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - return c_verify_ex(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) - -def c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): - return c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) - -def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): - return c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) - -if __name__ == '__main__': - #Setup argument parser - resources_config_parser = ConfigParser(); - parser = OptionParser() - parser.add_option("-i", "--ip_address", dest="i", - help="pycryptoki daemon IP address", metavar="") - parser.add_option("-p", "--port", dest="p", - help="pycryptoki daemon IP port", metavar="") - (options, args) = parser.parse_args() - - #Default arguments - ip = options.i if options.i != None else 'localhost' - port = int( options.p if options.p != None else '8001') - print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) - - server = initialize_server(ip, port) - - # run until we die - print "Starting Server" - server.serve_forever() diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 5dd301b..f74b84e 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -1,312 +1,311 @@ -""" -This is the rpy -""" - -import logging -from optparse import OptionParser -from _ctypes import pointer -from ctypes import cast -import ctypes - -import rpyc -import pycryptoki - -from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ - ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ - ca_insert, ca_insert_ex -from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ - c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex -from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ - c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ - c_derive_key, c_derive_key_ex, c_copy_object_ex, c_copy_object -from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ - c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ - c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ - c_create_object_ex, c_digestkey, c_digestkey_ex -from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ - c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex -from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ - ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ - ca_set_container_policy, ca_set_container_policy_ex -from pycryptoki.session_management import c_initialize, c_initialize_ex, \ - c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, \ - c_get_session_info, c_get_session_info_ex, c_get_token_info, \ - c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ - c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ - c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ - ca_create_container_ex, login, login_ex, ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID_ex, \ - ca_closeapplicationID, ca_restart, ca_restart_ex, ca_delete_container_with_handle_ex, \ - ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex -from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex -from pycryptoki.token_management import c_init_token, c_init_token_ex, \ - c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ - c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex -from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ - ca_init_audit_ex, ca_time_sync, ca_time_sync_ex -from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR -from pycryptoki.key_generator import _get_mechanism -from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex, \ - ca_settokencertificatesignature, ca_settokencertificatesignature_ex, \ - ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ - ca_initializeremotepedvector, ca_initializeremotepedvector_ex, \ - ca_deleteremotepedvector, ca_deleteremotepedvector_ex, ca_mtkrestore, \ - ca_mtkrestore_ex, ca_mtkresplit, ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex -from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ - ca_modifyusagecount, ca_modifyusagecount_ex -from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, \ - ca_duplicatemofn, ca_duplicatemofn_ex - -from pycryptoki.cryptoki import * - - -logger = logging.getLogger(__name__) - - -class PycryptokiService(rpyc.SlaveService): - """ - This is the core service to expose to the daemon. - Add in a static method preceded by 'exposed_' and it'll be visible to anything - connecting to the daemon. - - If you're working with pointers, you'll need to create the pointer in a function here - rather than passing in a pointer from the client (pointers getting pickled makes no sense). - - """ - def _rpyc_getattr(self, name): - if name.startswith("exposed_"): - name = name - elif name in pycryptoki.cryptoki.__all__: - return getattr(pycryptoki.cryptoki, name) - else: - name = "exposed_" + name - return getattr(self, name) - - #encryption.py - exposed_c_wrap_key = staticmethod(c_wrap_key) - exposed_c_wrap_key_ex = staticmethod(c_wrap_key_ex) - exposed_c_unwrap_key = staticmethod(c_unwrap_key) - exposed_c_unwrap_key_ex = staticmethod(c_unwrap_key_ex) - exposed_c_encrypt = staticmethod(c_encrypt) - exposed_c_encrypt_ex = staticmethod(c_encrypt_ex) - exposed_c_decrypt = staticmethod(c_decrypt) - exposed_c_decrypt_ex = staticmethod(c_decrypt_ex) - - #sign_verify.py - exposed_c_sign = staticmethod(c_sign) - exposed_c_sign_ex = staticmethod(c_sign_ex) - exposed_c_verify = staticmethod(c_verify) - exposed_c_verify_ex = staticmethod(c_verify_ex) - - #token_management.py - exposed_c_init_token = staticmethod(c_init_token) - exposed_c_init_token_ex = staticmethod(c_init_token_ex) - exposed_c_get_mechanism_list = staticmethod(c_get_mechanism_list) - exposed_c_get_mechanism_list_ex = staticmethod(c_get_mechanism_list_ex) - exposed_c_get_mechanism_info = staticmethod(c_get_mechanism_info) - exposed_c_get_mechanism_info_ex = staticmethod(c_get_mechanism_info_ex) - - #session_management.py - exposed_c_initialize = staticmethod(c_initialize) - exposed_c_initialize_ex = staticmethod(c_initialize_ex) - exposed_c_finalize = staticmethod(c_finalize) - exposed_c_finalize_ex = staticmethod(c_finalize_ex) - exposed_c_open_session = staticmethod(c_open_session) - exposed_c_open_session_ex = staticmethod(c_open_session_ex) - exposed_login = staticmethod(login) - exposed_login_ex = staticmethod(login_ex) - exposed_c_get_session_info = staticmethod(c_get_session_info) - exposed_c_get_session_info_ex = staticmethod(c_get_session_info_ex) - exposed_c_get_token_info = staticmethod(c_get_token_info) - exposed_c_get_token_info_ex = staticmethod(c_get_token_info_ex) - exposed_c_close_session = staticmethod(c_close_session) - exposed_c_close_session_ex = staticmethod(c_close_session_ex) - exposed_c_logout = staticmethod(c_logout) - exposed_c_logout_ex = staticmethod(c_logout_ex) - exposed_c_set_pin = staticmethod(c_set_pin) - exposed_c_set_pin_ex = staticmethod(c_set_pin_ex) - exposed_c_init_pin = staticmethod(c_init_pin) - exposed_c_init_pin_ex = staticmethod(c_init_pin_ex) - exposed_ca_factory_reset = staticmethod(ca_factory_reset) - exposed_ca_factory_reset_ex = staticmethod(ca_factory_reset_ex) - exposed_get_token_by_label = staticmethod(get_token_by_label) - exposed_get_token_by_label_ex = staticmethod(get_token_by_label_ex) - exposed_ca_close_secure_token = staticmethod(ca_close_secure_token) - exposed_ca_close_secure_token_ex = staticmethod(ca_close_secure_token_ex) - exposed_ca_open_secure_token = staticmethod(ca_open_secure_token) - exposed_ca_open_secure_token_ex = staticmethod(ca_open_secure_token_ex) - exposed_c_close_all_sessions = staticmethod(c_close_all_sessions) - exposed_c_close_all_sessions_ex = staticmethod(c_close_all_sessions_ex) - exposed_ca_create_container = staticmethod(ca_create_container) - exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) - exposed_ca_openapplicationID_ex = staticmethod(ca_openapplicationID_ex) - exposed_ca_openapplicationID = staticmethod(ca_openapplicationID) - exposed_ca_closeapplicationID_ex = staticmethod(ca_closeapplicationID_ex) - exposed_ca_closeapplicationID = staticmethod(ca_closeapplicationID) - exposed_ca_setapplicationID_ex = staticmethod(ca_setapplicationID_ex) - exposed_ca_setapplicationID = staticmethod(ca_setapplicationID) - exposed_ca_restart_ex = staticmethod(ca_restart_ex) - exposed_ca_restart = staticmethod(ca_restart) - exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) - exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) - - #policy_management.py - exposed_ca_set_hsm_policy = staticmethod(ca_set_hsm_policy) - exposed_ca_set_hsm_policy_ex = staticmethod(ca_set_hsm_policy_ex) - exposed_ca_set_destructive_hsm_policy = staticmethod(ca_set_destructive_hsm_policy) - exposed_ca_set_destructive_hsm_policy_ex = staticmethod(ca_set_destructive_hsm_policy_ex) - exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) - exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) - - #object_attr_lookup.py - exposed_c_find_objects = staticmethod(c_find_objects) - exposed_c_find_objects_ex = staticmethod(c_find_objects_ex) - exposed_c_get_attribute_value = staticmethod(c_get_attribute_value) - exposed_c_get_attribute_value_ex = staticmethod(c_get_attribute_value_ex) - exposed_c_set_attribute_value = staticmethod(c_set_attribute_value) - exposed_c_set_attribute_value_ex = staticmethod(c_set_attribute_value_ex) - - #misc.py - exposed_c_generate_random = staticmethod(c_generate_random) - exposed_c_generate_random_ex = staticmethod(c_generate_random_ex) - exposed_c_seed_random = staticmethod(c_seed_random) - exposed_c_seed_random_ex = staticmethod(c_seed_random_ex) - exposed_c_digest = staticmethod(c_digest) - exposed_c_digest_ex = staticmethod(c_digest_ex) - exposed_c_set_ped_id = staticmethod(c_set_ped_id) - exposed_c_set_ped_id_ex = staticmethod(c_set_ped_id_ex) - exposed_c_get_ped_id = staticmethod(c_get_ped_id) - exposed_c_get_ped_id_ex = staticmethod(c_get_ped_id_ex) - exposed_c_create_object = staticmethod(c_create_object) - exposed_c_create_object_ex = staticmethod(c_create_object_ex) - exposed_c_digest_key = staticmethod(c_digestkey) - exposed_c_digest_key_ex = staticmethod(c_digestkey_ex) - - #key_generator.py - exposed_c_generate_key = staticmethod(c_generate_key) - exposed_c_generate_key_ex = staticmethod(c_generate_key_ex) - exposed_c_generate_key_pair = staticmethod(c_generate_key_pair) - exposed_c_generate_key_pair_ex = staticmethod(c_generate_key_pair_ex) - exposed_c_destroy_object = staticmethod(c_destroy_object) - exposed_c_destroy_object_ex = staticmethod(c_destroy_object_ex) - exposed_c_copy_object = staticmethod(c_copy_object) - exposed_c_copy_object_ex = staticmethod(c_copy_object_ex) - - #backup.py - exposed_ca_extract = staticmethod(ca_extract) - exposed_ca_extract_ex = staticmethod(ca_extract_ex) - exposed_ca_insert = staticmethod(ca_insert) - exposed_ca_insert_ex = staticmethod(ca_insert_ex) - - #audit_handling.py - exposed_ca_get_time = staticmethod(ca_get_time) - exposed_ca_get_time_ex = staticmethod(ca_get_time_ex) - exposed_ca_init_audit = staticmethod(ca_init_audit) - exposed_ca_init_audit_ex = staticmethod(ca_init_audit_ex) - exposed_ca_time_sync = staticmethod(ca_time_sync) - exposed_ca_time_sync_ex = staticmethod(ca_time_sync_ex) - - #hsm_management.py - exposed_c_performselftest = staticmethod(c_performselftest) - exposed_c_performselftest_ex = staticmethod(c_performselftest_ex) - exposed_ca_settokencertificatesignature = staticmethod(ca_settokencertificatesignature) - exposed_ca_settokencertificatesignature_ex = staticmethod(ca_settokencertificatesignature_ex) - exposed_ca_hainit = staticmethod(ca_hainit) - exposed_ca_hainit_ex = staticmethod(ca_hainit_ex) - exposed_ca_createloginchallenge = staticmethod(ca_createloginchallenge) - exposed_ca_createloginchallenge_ex = staticmethod(ca_createloginchallenge_ex) - exposed_ca_initializeremotepedvector = staticmethod(ca_initializeremotepedvector) - exposed_ca_initializeremotepedvector_ex = staticmethod(ca_initializeremotepedvector_ex) - exposed_ca_deleteremotepedvector = staticmethod(ca_deleteremotepedvector) - exposed_ca_deleteremotepedvector_ex = staticmethod(ca_deleteremotepedvector_ex) - exposed_ca_mtkrestore = staticmethod(ca_mtkrestore) - exposed_ca_mtkrestore_ex = staticmethod(ca_mtkrestore_ex) - exposed_ca_mtkresplit = staticmethod(ca_mtkresplit) - exposed_ca_mtkresplit_ex = staticmethod(ca_mtkresplit_ex) - exposed_ca_mtkzeroize = staticmethod(ca_mtkzeroize) - exposed_ca_mtkzeroize_ex = staticmethod(ca_mtkzeroize_ex) - - #key_management.py - exposed_ca_generatemofn = staticmethod(ca_generatemofn) - exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) - exposed_ca_modifyusagecount = staticmethod(ca_modifyusagecount) - exposed_ca_modifyusagecount_ex = staticmethod(ca_modifyusagecount_ex) - - #key_usage.py - exposed_ca_clonemofn = staticmethod(ca_clonemofn) - exposed_ca_clonemofn_ex = staticmethod(ca_clonemofn_ex) - exposed_ca_duplicatemofn = staticmethod(ca_duplicatemofn) - exposed_ca_duplicatemofn_ex = staticmethod(ca_duplicatemofn_ex) - - @staticmethod - def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): - """ - #key_generator.py - - Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side - because it involves pointers. - """ - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) - - @staticmethod - def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): - """ - #key_generator.py - - Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side - because it involves pointers. - """ - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) - - -if __name__ == '__main__': - from rpyc.utils.server import ThreadedServer - - parser = OptionParser() - parser.add_option("-i", "--ip_address", dest="i", - help="pycryptoki daemon IP address", metavar="") - parser.add_option("-p", "--port", dest="p", - help="pycryptoki daemon IP port", metavar="") - (options, args) = parser.parse_args() - - #Default arguments - ip = options.i if options.i != None else 'localhost' - port = int(options.p if options.p != None else '8001') - print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) - - t = ThreadedServer(PycryptokiService, - hostname=ip, - port=port, - logger=logger, - protocol_config={'allow_public_attrs': True, - 'allow_all_attrs': True, - 'allow_getattr': True, - 'allow_setattr': True, - 'allow_delattr': True}) - print "Starting Server" - t.start() - - - - - - - - - - - - - - +#!/usr/bin/env python +""" +RPYC version of of the pycryptoki daemon +""" +from optparse import OptionParser +from _ctypes import pointer +from ctypes import cast +import ctypes + +import rpyc +import pycryptoki + +from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token,\ + ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex,\ + ca_insert, ca_insert_ex +from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt,\ + c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex +from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex,\ + c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex,\ + c_derive_key, c_derive_key_ex, c_copy_object_ex, c_copy_object +from pycryptoki.misc import c_generate_random, c_generate_random_ex,\ + c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id,\ + c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object,\ + c_create_object_ex, c_digestkey, c_digestkey_ex +from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex,\ + c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex +from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex,\ + ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex,\ + ca_set_container_policy, ca_set_container_policy_ex +from pycryptoki.session_management import c_initialize, c_initialize_ex,\ + c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, \ + c_get_session_info, c_get_session_info_ex, c_get_token_info, \ + c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex,\ + c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin,\ + c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container,\ + ca_create_container_ex, login, login_ex, ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID_ex,\ + ca_closeapplicationID, ca_restart, ca_restart_ex, ca_delete_container_with_handle_ex, \ + ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex +from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex +from pycryptoki.token_management import c_init_token, c_init_token_ex,\ + c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info,\ + c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex +from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit,\ + ca_init_audit_ex, ca_time_sync, ca_time_sync_ex +from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex, \ + ca_settokencertificatesignature, ca_settokencertificatesignature_ex, \ + ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ + ca_initializeremotepedvector, ca_initializeremotepedvector_ex, \ + ca_deleteremotepedvector, ca_deleteremotepedvector_ex, ca_mtkrestore, \ + ca_mtkrestore_ex, ca_mtkresplit, ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex +from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ + ca_modifyusagecount, ca_modifyusagecount_ex +from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, \ + ca_duplicatemofn, ca_duplicatemofn_ex + +from pycryptoki.cryptoki import * +import logging + +logger = logging.getLogger(__name__) + + +class PycryptokiService(rpyc.SlaveService): + """ + This is the core service to expose to the daemon. + Add in a static method preceded by 'exposed_' and it'll be visible to anything + connecting to the daemon. + + If you're working with pointers, you'll need to create the pointer in a function here + rather than passing in a pointer from the client (pointers getting pickled makes no sense). + + """ + def _rpyc_getattr(self, name): + if name.startswith("exposed_"): + name = name + elif name in pycryptoki.cryptoki.__all__: + return getattr(pycryptoki.cryptoki, name) + else: + name = "exposed_" + name + return getattr(self, name) + + #encryption.py + exposed_c_wrap_key = staticmethod(c_wrap_key) + exposed_c_wrap_key_ex = staticmethod(c_wrap_key_ex) + exposed_c_unwrap_key = staticmethod(c_unwrap_key) + exposed_c_unwrap_key_ex = staticmethod(c_unwrap_key_ex) + exposed_c_encrypt = staticmethod(c_encrypt) + exposed_c_encrypt_ex = staticmethod(c_encrypt_ex) + exposed_c_decrypt = staticmethod(c_decrypt) + exposed_c_decrypt_ex = staticmethod(c_decrypt_ex) + + #sign_verify.py + exposed_c_sign = staticmethod(c_sign) + exposed_c_sign_ex = staticmethod(c_sign_ex) + exposed_c_verify = staticmethod(c_verify) + exposed_c_verify_ex = staticmethod(c_verify_ex) + + #token_management.py + exposed_c_init_token = staticmethod(c_init_token) + exposed_c_init_token_ex = staticmethod(c_init_token_ex) + exposed_c_get_mechanism_list = staticmethod(c_get_mechanism_list) + exposed_c_get_mechanism_list_ex = staticmethod(c_get_mechanism_list_ex) + exposed_c_get_mechanism_info = staticmethod(c_get_mechanism_info) + exposed_c_get_mechanism_info_ex = staticmethod(c_get_mechanism_info_ex) + + #session_management.py + exposed_c_initialize = staticmethod(c_initialize) + exposed_c_initialize_ex = staticmethod(c_initialize_ex) + exposed_c_finalize = staticmethod(c_finalize) + exposed_c_finalize_ex = staticmethod(c_finalize_ex) + exposed_c_open_session = staticmethod(c_open_session) + exposed_c_open_session_ex = staticmethod(c_open_session_ex) + exposed_login = staticmethod(login) + exposed_login_ex = staticmethod(login_ex) + exposed_c_get_session_info = staticmethod(c_get_session_info) + exposed_c_get_session_info_ex = staticmethod(c_get_session_info_ex) + exposed_c_get_token_info = staticmethod(c_get_token_info) + exposed_c_get_token_info_ex = staticmethod(c_get_token_info_ex) + exposed_c_close_session = staticmethod(c_close_session) + exposed_c_close_session_ex = staticmethod(c_close_session_ex) + exposed_c_logout = staticmethod(c_logout) + exposed_c_logout_ex = staticmethod(c_logout_ex) + exposed_c_set_pin = staticmethod(c_set_pin) + exposed_c_set_pin_ex = staticmethod(c_set_pin_ex) + exposed_c_init_pin = staticmethod(c_init_pin) + exposed_c_init_pin_ex = staticmethod(c_init_pin_ex) + exposed_ca_factory_reset = staticmethod(ca_factory_reset) + exposed_ca_factory_reset_ex = staticmethod(ca_factory_reset_ex) + exposed_get_token_by_label = staticmethod(get_token_by_label) + exposed_get_token_by_label_ex = staticmethod(get_token_by_label_ex) + exposed_ca_close_secure_token = staticmethod(ca_close_secure_token) + exposed_ca_close_secure_token_ex = staticmethod(ca_close_secure_token_ex) + exposed_ca_open_secure_token = staticmethod(ca_open_secure_token) + exposed_ca_open_secure_token_ex = staticmethod(ca_open_secure_token_ex) + exposed_c_close_all_sessions = staticmethod(c_close_all_sessions) + exposed_c_close_all_sessions_ex = staticmethod(c_close_all_sessions_ex) + exposed_ca_create_container = staticmethod(ca_create_container) + exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) + exposed_ca_openapplicationID_ex = staticmethod(ca_openapplicationID_ex) + exposed_ca_openapplicationID = staticmethod(ca_openapplicationID) + exposed_ca_closeapplicationID_ex = staticmethod(ca_closeapplicationID_ex) + exposed_ca_closeapplicationID = staticmethod(ca_closeapplicationID) + exposed_ca_setapplicationID_ex = staticmethod(ca_setapplicationID_ex) + exposed_ca_setapplicationID = staticmethod(ca_setapplicationID) + exposed_ca_restart_ex = staticmethod(ca_restart_ex) + exposed_ca_restart = staticmethod(ca_restart) + exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) + exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) + + #policy_management.py + exposed_ca_set_hsm_policy = staticmethod(ca_set_hsm_policy) + exposed_ca_set_hsm_policy_ex = staticmethod(ca_set_hsm_policy_ex) + exposed_ca_set_destructive_hsm_policy = staticmethod(ca_set_destructive_hsm_policy) + exposed_ca_set_destructive_hsm_policy_ex = staticmethod(ca_set_destructive_hsm_policy_ex) + exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) + exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) + + #object_attr_lookup.py + exposed_c_find_objects = staticmethod(c_find_objects) + exposed_c_find_objects_ex = staticmethod(c_find_objects_ex) + exposed_c_get_attribute_value = staticmethod(c_get_attribute_value) + exposed_c_get_attribute_value_ex = staticmethod(c_get_attribute_value_ex) + exposed_c_set_attribute_value = staticmethod(c_set_attribute_value) + exposed_c_set_attribute_value_ex = staticmethod(c_set_attribute_value_ex) + + #misc.py + exposed_c_generate_random = staticmethod(c_generate_random) + exposed_c_generate_random_ex = staticmethod(c_generate_random_ex) + exposed_c_seed_random = staticmethod(c_seed_random) + exposed_c_seed_random_ex = staticmethod(c_seed_random_ex) + exposed_c_digest = staticmethod(c_digest) + exposed_c_digest_ex = staticmethod(c_digest_ex) + exposed_c_set_ped_id = staticmethod(c_set_ped_id) + exposed_c_set_ped_id_ex = staticmethod(c_set_ped_id_ex) + exposed_c_get_ped_id = staticmethod(c_get_ped_id) + exposed_c_get_ped_id_ex = staticmethod(c_get_ped_id_ex) + exposed_c_create_object = staticmethod(c_create_object) + exposed_c_create_object_ex = staticmethod(c_create_object_ex) + exposed_c_digest_key = staticmethod(c_digestkey) + exposed_c_digest_key_ex = staticmethod(c_digestkey_ex) + + #key_generator.py + exposed_c_generate_key = staticmethod(c_generate_key) + exposed_c_generate_key_ex = staticmethod(c_generate_key_ex) + exposed_c_generate_key_pair = staticmethod(c_generate_key_pair) + exposed_c_generate_key_pair_ex = staticmethod(c_generate_key_pair_ex) + exposed_c_destroy_object = staticmethod(c_destroy_object) + exposed_c_destroy_object_ex = staticmethod(c_destroy_object_ex) + exposed_c_copy_object = staticmethod(c_copy_object) + exposed_c_copy_object_ex = staticmethod(c_copy_object_ex) + + #backup.py + exposed_ca_extract = staticmethod(ca_extract) + exposed_ca_extract_ex = staticmethod(ca_extract_ex) + exposed_ca_insert = staticmethod(ca_insert) + exposed_ca_insert_ex = staticmethod(ca_insert_ex) + + #audit_handling.py + exposed_ca_get_time = staticmethod(ca_get_time) + exposed_ca_get_time_ex = staticmethod(ca_get_time_ex) + exposed_ca_init_audit = staticmethod(ca_init_audit) + exposed_ca_init_audit_ex = staticmethod(ca_init_audit_ex) + exposed_ca_time_sync = staticmethod(ca_time_sync) + exposed_ca_time_sync_ex = staticmethod(ca_time_sync_ex) + + #hsm_management.py + exposed_c_performselftest = staticmethod(c_performselftest) + exposed_c_performselftest_ex = staticmethod(c_performselftest_ex) + exposed_ca_settokencertificatesignature = staticmethod(ca_settokencertificatesignature) + exposed_ca_settokencertificatesignature_ex = staticmethod(ca_settokencertificatesignature_ex) + exposed_ca_hainit = staticmethod(ca_hainit) + exposed_ca_hainit_ex = staticmethod(ca_hainit_ex) + exposed_ca_createloginchallenge = staticmethod(ca_createloginchallenge) + exposed_ca_createloginchallenge_ex = staticmethod(ca_createloginchallenge_ex) + exposed_ca_initializeremotepedvector = staticmethod(ca_initializeremotepedvector) + exposed_ca_initializeremotepedvector_ex = staticmethod(ca_initializeremotepedvector_ex) + exposed_ca_deleteremotepedvector = staticmethod(ca_deleteremotepedvector) + exposed_ca_deleteremotepedvector_ex = staticmethod(ca_deleteremotepedvector_ex) + exposed_ca_mtkrestore = staticmethod(ca_mtkrestore) + exposed_ca_mtkrestore_ex = staticmethod(ca_mtkrestore_ex) + exposed_ca_mtkresplit = staticmethod(ca_mtkresplit) + exposed_ca_mtkresplit_ex = staticmethod(ca_mtkresplit_ex) + exposed_ca_mtkzeroize = staticmethod(ca_mtkzeroize) + exposed_ca_mtkzeroize_ex = staticmethod(ca_mtkzeroize_ex) + + #key_management.py + exposed_ca_generatemofn = staticmethod(ca_generatemofn) + exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) + exposed_ca_modifyusagecount = staticmethod(ca_modifyusagecount) + exposed_ca_modifyusagecount_ex = staticmethod(ca_modifyusagecount_ex) + + #key_usage.py + exposed_ca_clonemofn = staticmethod(ca_clonemofn) + exposed_ca_clonemofn_ex = staticmethod(ca_clonemofn_ex) + exposed_ca_duplicatemofn = staticmethod(ca_duplicatemofn) + exposed_ca_duplicatemofn_ex = staticmethod(ca_duplicatemofn_ex) + + @staticmethod + def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): + """ + #key_generator.py + + Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side + because it involves pointers. + """ + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) + + @staticmethod + def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): + """ + #key_generator.py + + Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side + because it involves pointers. + """ + if mech: + mech = _get_mechanism(mech) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) + + +if __name__ == '__main__': + from rpyc.utils.server import ThreadedServer + + parser = OptionParser() + parser.add_option("-i", "--ip_address", dest="i", + help="pycryptoki daemon IP address", metavar="") + parser.add_option("-p", "--port", dest="p", + help="pycryptoki daemon IP port", metavar="") + (options, args) = parser.parse_args() + + #Default arguments + ip = options.i if options.i != None else 'localhost' + port = int(options.p if options.p != None else '8001') + print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) + + t = ThreadedServer(PycryptokiService, + hostname=ip, + port=port, + logger=logger, + protocol_config={'allow_public_attrs': True, + 'allow_all_attrs': True, + 'allow_getattr': True, + 'allow_setattr': True, + 'allow_delattr': True}) + print "Starting Server" + t.start() + + + + + + + + + + + + + + diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py index 50945d7..5fd143b 100755 --- a/pycryptoki/default_templates.py +++ b/pycryptoki/default_templates.py @@ -1,857 +1,856 @@ -""" -File containing a number of templates taken from CKDemo and manually converted into python format. -See the attributes.py file for methods to convert them into the proper C format. -""" - -from defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ - CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ - CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ - CKK_DES2, CKK_DES3, CKK_CAST3, CKK_GENERIC_SECRET, CKA_MODIFIABLE, \ - CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ - CKA_VALUE_BITS, CKK_CAST5, CKK_RC2, CKK_RC4, CKK_RC5, CKA_ECDSA_PARAMS, CKK_AES, \ - CKK_SEED, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, CKK_ARIA, CKM_RSA_PKCS_KEY_PAIR_GEN, \ - CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ - CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ - CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, CKM_ARIA_KEY_GEN, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN, \ - CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN, \ - CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, \ - CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, \ - CKM_SHA1_RSA_PKCS, CKM_SHA224_RSA_PKCS, \ - CKM_SHA256_RSA_PKCS, CKM_SHA384_RSA_PKCS, CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS_PSS, \ - CKM_SHA1_RSA_PKCS_PSS, CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, \ - CKM_SHA384_RSA_PKCS_PSS, CKM_SHA512_RSA_PKCS_PSS, CKM_RSA_X9_31_KEY_PAIR_GEN, \ - CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31, CKM_SHA224_RSA_X9_31, CKM_SHA256_RSA_X9_31, \ - CKM_SHA384_RSA_X9_31, CKM_SHA512_RSA_X9_31, CKM_RSA_PKCS_OAEP, CKM_DSA_KEY_PAIR_GEN, \ - CKM_DSA, CKM_DSA_SHA1, CKM_DSA_SHA224, CKM_DSA_SHA256, CKM_DSA_PARAMETER_GEN, \ - CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, CKM_ECDSA_SHA256, \ - CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, \ - CKM_SHA_1_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, \ - CKM_ECDSA -from pycryptoki.defines import CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE, CKC_X_509, \ - CKA_SUBJECT, CKA_VALUE, CKO_DATA, CKA_TOKEN -import copy - -CKM_DES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 8, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES Key"} - -CKM_DES_UNWRAP_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_SIGN : True, - CKA_WRAP : True, - CKA_DERIVE : True, - CKA_LABEL : "DES Key"} - - -CKM_DES2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES2, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES2 Key"} -CKM_DES3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES3, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 24, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES3 Key"} - -CKM_CAST3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_CAST3, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 8, #1-8 - CKA_EXTRACTABLE :True, - CKA_LABEL : "CAST3 Key"} - -CKM_GENERIC_SECRET_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_GENERIC_SECRET, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "GENERIC SECRET Key"} - -CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_MODIFIABLE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS - CKA_PUBLIC_EXPONENT : 3, #byte - CKA_LABEL : "RSA Public Key"} -CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_MODIFIABLE : True, - CKA_EXTRACTABLE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_LABEL : "RSA Private Key"} - -dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, - 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, 0x6d, 0x1f, 0xf2, - 0x70, 0xf1, 0x59, 0x78, 0x5d, 0x75, 0x69, 0x21, 0xdb, 0xff, 0x97, 0x73, 0xae, 0x08, 0x48, 0x3b, - 0x66, 0x2f, 0xc0, 0x7d, 0xf7, 0x51, 0x2f, 0xf6, 0x8b, 0x2e, 0x55, 0x65, 0xfd, 0x79, 0x82, 0xe2, - 0x0c, 0x24, 0x48, 0x32, 0xab, 0xa1, 0x21, 0xcc, 0x07, 0x99, 0xcc, 0x09, 0xf2, 0xd5, 0x41, 0x4d, - 0x5f, 0x39, 0x66, 0x21, 0x13, 0x65, 0xf5, 0x1b, 0x83, 0xe9, 0xff, 0xcc, 0xcb, 0x3d, 0x88, 0xcd, - 0xf2, 0x38, 0xf7, 0xc2, 0x73, 0x91, 0x31, 0xca, 0x7a, 0xad, 0xff, 0x66, 0x2f, 0xec, 0x1f, 0xb0, - 0xe1, 0xd3, 0x11, 0xa4, 0x04, 0x26, 0x03, 0x76, 0xfd, 0x01, 0x1f, 0xe0, 0x0d, 0x02, 0x04, 0xc3] -dsa_sub_prime_1024_160 = [0xd3, 0x80, 0x73, 0x53, 0xb5, 0x1c, 0x5f, 0x71, 0xb2, 0x2a, 0xc3, 0xd0, 0xc7, 0xe3, 0x94, 0x14, - 0x8f, 0xce, 0xdc, 0x61] -dsa_base_1024_160 = [0x42, 0xe3, 0x77, 0x8e, 0x6e, 0xc3, 0x1b, 0x0d, 0xb0, 0x7a, 0x6b, 0x37, 0x0d, 0x7f, 0xb6, 0xfb, - 0x4a, 0x0b, 0xca, 0x6d, 0xea, 0xac, 0x37, 0x1f, 0x6a, 0xdb, 0xcb, 0xeb, 0xa3, 0x8d, 0xdf, 0x76, - 0xa4, 0x7c, 0x3c, 0x3d, 0x79, 0x27, 0x6a, 0x0e, 0x57, 0x9c, 0xe4, 0xe3, 0x47, 0x18, 0x0f, 0xd9, - 0xb4, 0xad, 0x46, 0x1d, 0x6c, 0xf0, 0xea, 0xc5, 0x1f, 0xb0, 0x8c, 0xf4, 0x52, 0xf6, 0x24, 0x57, - 0x00, 0x51, 0xe5, 0x18, 0xa7, 0x5a, 0x5b, 0xb9, 0xc3, 0x57, 0x8a, 0x14, 0xfd, 0x4f, 0x27, 0xf7, - 0x95, 0xb2, 0x2a, 0xce, 0xa6, 0x2b, 0x1f, 0xdf, 0x10, 0x32, 0xc1, 0x26, 0x6d, 0xa0, 0x81, 0xc7, - 0xfb, 0x99, 0xc4, 0x26, 0x66, 0x26, 0x58, 0x70, 0x93, 0xfd, 0x38, 0x16, 0x17, 0x23, 0x8e, 0xe1, - 0x57, 0x8f, 0xc3, 0x25, 0x54, 0x8d, 0xc1, 0xc0, 0x8e, 0x5f, 0x93, 0x22, 0xc3, 0xb1, 0x20, 0x5e] - -dsa_prime_2048_224 = [0xa2, 0x15, 0xdc, 0xa3, 0xf7, 0x87, 0x34, 0x2c, 0x91, 0x90, 0x87, 0x83, 0x70, 0x79, 0x73, 0x38, - 0x9f, 0x3e, 0x02, 0xf2, 0xc9, 0x68, 0xfe, 0x67, 0xca, 0xb9, 0x4f, 0x5d, 0x6f, 0x92, 0x8c, 0xe8, - 0x6c, 0x8d, 0x62, 0x25, 0x37, 0x4c, 0xa1, 0xbf, 0x7f, 0x27, 0x77, 0x44, 0x8c, 0xc7, 0xc0, 0xc5, - 0xed, 0x66, 0xd1, 0x20, 0x11, 0x7f, 0xec, 0x10, 0xed, 0x81, 0x55, 0x51, 0x45, 0x36, 0xe1, 0xaa, - 0x31, 0x6b, 0x8d, 0xd4, 0x58, 0x27, 0xa0, 0xf0, 0x0e, 0x5d, 0x91, 0x8c, 0x0f, 0xdd, 0x21, 0x8a, - 0xcd, 0x6c, 0x26, 0x3c, 0x1c, 0x2e, 0x55, 0xf6, 0xd0, 0xa7, 0x0f, 0x1b, 0xc9, 0x7f, 0x4b, 0xb0, - 0x4f, 0xff, 0xee, 0x4b, 0x78, 0xb4, 0xdf, 0x34, 0x90, 0xad, 0x98, 0xab, 0xad, 0x0a, 0x4b, 0xfe, - 0x1d, 0xaf, 0xaf, 0x6c, 0x09, 0xdd, 0xda, 0xdf, 0xb8, 0x88, 0x96, 0x94, 0x51, 0x3b, 0x86, 0x5c, - 0x07, 0xa4, 0xf5, 0xf9, 0x27, 0xbe, 0x72, 0x39, 0xe8, 0xd7, 0x67, 0x14, 0xe0, 0x3b, 0x7b, 0xfa, - 0xfb, 0x92, 0x94, 0x00, 0x0f, 0xbb, 0x3f, 0x7a, 0x75, 0x0b, 0x39, 0xca, 0x50, 0x63, 0x0e, 0xe7, - 0xd0, 0xbc, 0x45, 0xa9, 0xc9, 0x87, 0xae, 0x38, 0xae, 0x03, 0x7a, 0x11, 0xb1, 0xd1, 0x3d, 0xf5, - 0x51, 0x76, 0xd9, 0xd8, 0xab, 0x9e, 0xc0, 0xa4, 0x1b, 0x78, 0xa6, 0x36, 0x9e, 0xb5, 0x19, 0x88, - 0xfe, 0x9f, 0xbd, 0x97, 0xa1, 0x0d, 0x48, 0xe2, 0xeb, 0x21, 0x8e, 0xc6, 0x92, 0xb3, 0x1c, 0xfc, - 0xc9, 0x58, 0x3c, 0x7a, 0x41, 0x1d, 0x7d, 0xfa, 0x0a, 0xb3, 0x15, 0xfb, 0x0c, 0x75, 0xe2, 0x10, - 0x9e, 0xb1, 0xe2, 0xee, 0x75, 0xf4, 0x1d, 0x0a, 0x01, 0x65, 0x46, 0xda, 0x70, 0xa6, 0x31, 0xac, - 0x77, 0x8a, 0x2a, 0xe3, 0x25, 0x1f, 0x11, 0x39, 0xe5, 0x74, 0xe2, 0x6d, 0x2c, 0xc6, 0x5c, 0x47] -dsa_sub_prime_2048_224 = [0xd3, 0x76, 0x83, 0x74, 0x55, 0x3d, 0x49, 0x17, 0x19, 0x92, 0x74, 0xba, 0x05, 0x63, 0xbe, 0xff, - 0xa2, 0xa4, 0x5f, 0x05, 0xae, 0x83, 0xdf, 0x9b, 0x34, 0x81, 0x55, 0xbf] -dsa_base_2048_224 = [0x4e, 0x1f, 0x73, 0x4e, 0x08, 0x92, 0xd0, 0x4d, 0x80, 0x89, 0x93, 0xe6, 0x3d, 0xad, 0xef, 0xb3, - 0xfa, 0xa2, 0x48, 0x4c, 0x88, 0x83, 0x8d, 0x38, 0xd8, 0xea, 0x64, 0xca, 0x28, 0xd6, 0xc0, 0x89, - 0xbe, 0x4b, 0x88, 0x14, 0x66, 0x83, 0xec, 0xbd, 0x8b, 0x8d, 0xc6, 0xfb, 0x17, 0x81, 0xca, 0x1d, - 0x83, 0xf3, 0x7f, 0x38, 0xd2, 0x36, 0x03, 0x2b, 0x17, 0x51, 0x16, 0x6a, 0xe4, 0x3f, 0x22, 0xb5, - 0x2d, 0xd6, 0x03, 0x40, 0x1e, 0x89, 0xfe, 0xf6, 0xc9, 0xd0, 0x21, 0x5f, 0x49, 0xa2, 0xcf, 0x97, - 0x33, 0x7b, 0xe2, 0x61, 0x28, 0x8f, 0xd9, 0xac, 0xfb, 0xb6, 0xc2, 0xc0, 0xc5, 0xea, 0x70, 0x9d, - 0x14, 0x76, 0x02, 0x74, 0x41, 0x75, 0x4c, 0xcd, 0x71, 0x00, 0x79, 0x05, 0x52, 0x55, 0x97, 0xd7, - 0xae, 0xc7, 0x71, 0xeb, 0x01, 0x2b, 0x0b, 0xfc, 0xd3, 0x4f, 0x87, 0x16, 0xc7, 0xcc, 0xb1, 0x91, - 0x3d, 0x4f, 0xa6, 0x10, 0x50, 0x4b, 0x67, 0x79, 0x01, 0xdb, 0x37, 0x80, 0x01, 0x9a, 0xa6, 0x92, - 0x23, 0xfb, 0xcd, 0x94, 0x33, 0x6f, 0x2b, 0xf0, 0x2b, 0x44, 0x09, 0x39, 0x39, 0xcc, 0x0d, 0x96, - 0x11, 0xe8, 0xf5, 0xc6, 0x28, 0x50, 0x2e, 0x2b, 0x81, 0x08, 0x3f, 0xc1, 0x28, 0x2f, 0x65, 0x2e, - 0x16, 0x48, 0xc4, 0xe2, 0xb0, 0x29, 0x54, 0x99, 0x19, 0xc5, 0x78, 0xbf, 0x3b, 0xf3, 0x84, 0x70, - 0xc7, 0x8b, 0x5a, 0xcb, 0x10, 0x55, 0xfe, 0x4b, 0x71, 0xef, 0xf5, 0xdb, 0x85, 0xa6, 0xf5, 0xe8, - 0x00, 0xf5, 0xc2, 0xb4, 0xa6, 0x48, 0x39, 0x83, 0x6e, 0xd1, 0xb0, 0xad, 0xea, 0x2d, 0x7e, 0x2e, - 0x22, 0x98, 0xaa, 0x10, 0x7f, 0xa0, 0xec, 0x23, 0x70, 0x87, 0xf5, 0xda, 0x6b, 0x5e, 0x0d, 0x8b, - 0x46, 0xc8, 0x88, 0x61, 0xc3, 0xc1, 0xf5, 0xdb, 0x02, 0x2a, 0x62, 0x7a, 0xd5, 0x95, 0xe5, 0xe2] - -dsa_prime_2048_256 = [ 0xad, 0x78, 0xd1, 0x93, 0x08, 0x76, 0x4f, 0x04, 0xeb, 0x6a, 0xa3, 0x82, 0x09, 0x38, 0x0f, 0xf6, - 0xc9, 0x87, 0x5e, 0x27, 0xb2, 0x7c, 0xc1, 0x4b, 0x78, 0x29, 0xbe, 0x2e, 0xcd, 0xae, 0x26, 0x88, - 0xf4, 0x5d, 0xe8, 0x09, 0xd1, 0x16, 0x06, 0x61, 0xd4, 0x81, 0x65, 0x00, 0x5d, 0x76, 0x7e, 0xf1, - 0x24, 0x73, 0x01, 0x8f, 0x92, 0xd4, 0x07, 0xe7, 0xf3, 0xf7, 0x3a, 0xb9, 0x8b, 0x8e, 0xc8, 0xf4, - 0x13, 0x2b, 0x52, 0xb8, 0x2a, 0x08, 0x57, 0xbc, 0x15, 0xe5, 0x8e, 0x2a, 0x16, 0xda, 0x5e, 0xff, - 0xd2, 0x4e, 0xc7, 0x24, 0xa9, 0x70, 0x74, 0xd2, 0xb4, 0xc1, 0xc0, 0xec, 0x81, 0xcb, 0x83, 0xe9, - 0x29, 0x2a, 0xfd, 0x3b, 0xb9, 0x83, 0xec, 0x23, 0xd1, 0xf9, 0x13, 0xec, 0x1a, 0x68, 0x3f, 0x44, - 0x9b, 0x85, 0x7a, 0x5e, 0x6a, 0x38, 0x91, 0xe0, 0xc6, 0xc8, 0x15, 0x23, 0xf3, 0x98, 0xf7, 0x29, - 0x7f, 0x7b, 0x07, 0x14, 0x3f, 0x6f, 0xfa, 0x11, 0x71, 0x65, 0xff, 0xd9, 0xdc, 0x71, 0x23, 0xd3, - 0x40, 0xec, 0x3b, 0x5f, 0x47, 0x9c, 0x4d, 0x53, 0x4c, 0x4f, 0x61, 0x31, 0xae, 0xda, 0x2e, 0xb6, - 0xd3, 0xd2, 0x01, 0x2c, 0x63, 0x9b, 0xaa, 0x61, 0x79, 0x13, 0xe9, 0xcc, 0xef, 0x57, 0xb1, 0x7a, - 0xd1, 0xd2, 0xe3, 0xfd, 0x92, 0x29, 0x43, 0x4a, 0xc4, 0x50, 0x8c, 0x36, 0xe8, 0xa5, 0xca, 0x9a, - 0xf6, 0x43, 0x3e, 0x75, 0x32, 0x16, 0x8b, 0xe8, 0x98, 0x9c, 0x60, 0x00, 0x83, 0xb6, 0xf4, 0xc9, - 0xa2, 0x36, 0xe8, 0xf6, 0xe3, 0x8a, 0x68, 0x64, 0x61, 0x1d, 0x7b, 0xe2, 0x3c, 0xf2, 0x48, 0x77, - 0x7d, 0xe5, 0xd1, 0xd0, 0x7a, 0x8d, 0x34, 0xdd, 0x1c, 0xc2, 0xbe, 0x99, 0xa4, 0xda, 0xbf, 0xd1, - 0x30, 0x4b, 0xc1, 0xc9, 0x73, 0xc1, 0x07, 0x78, 0x04, 0x0f, 0xdd, 0x7f, 0xa2, 0xfa, 0xc1, 0x0f] -dsa_sub_prime_2048_256 = [ 0xac, 0x66, 0x19, 0x0a, 0x7f, 0x8d, 0x6b, 0x5f, 0xc3, 0x77, 0x06, 0x35, 0x58, 0x2f, 0x9b, 0xc1, - 0x4a, 0x56, 0x91, 0x55, 0xf9, 0x79, 0x3b, 0x79, 0x8e, 0x2e, 0xdb, 0xfc, 0x69, 0x4e, 0x6a, 0xfd] -dsa_base_2048_256 = [0xa6, 0x37, 0x45, 0x31, 0xe5, 0x54, 0x8a, 0x58, 0xa6, 0xd0, 0x20, 0x33, 0xdf, 0x60, 0xbf, 0xf8, - 0xa3, 0x5c, 0xa4, 0x1b, 0x37, 0xe4, 0xc9, 0xea, 0xb0, 0xf2, 0x53, 0x22, 0x19, 0x60, 0xaa, 0x6f, - 0xb2, 0x6b, 0xad, 0x24, 0x04, 0xad, 0x38, 0x57, 0x70, 0x3c, 0x4e, 0x71, 0x6e, 0x35, 0x0d, 0x4b, - 0xcc, 0xbc, 0x4d, 0xad, 0xd9, 0x1d, 0x30, 0x5e, 0xc4, 0x3a, 0x62, 0xfe, 0x2e, 0x82, 0x52, 0xcb, - 0x97, 0x37, 0xb6, 0x0a, 0xf4, 0xc5, 0x5d, 0xf7, 0xfa, 0xe4, 0x95, 0x18, 0xeb, 0x0d, 0x1b, 0xcc, - 0x0e, 0xda, 0x06, 0x50, 0x28, 0xa5, 0x1a, 0x87, 0x51, 0x21, 0xcd, 0xd5, 0xea, 0x60, 0xa1, 0x39, - 0x39, 0x82, 0x33, 0xa5, 0xd1, 0x9b, 0x0d, 0xb3, 0x5c, 0xc3, 0xeb, 0x7d, 0xa3, 0x23, 0xa8, 0xf3, - 0xb2, 0x95, 0xd3, 0x5c, 0x31, 0xb6, 0xaa, 0x55, 0xd4, 0x22, 0xaa, 0xb5, 0x5f, 0x47, 0x0f, 0xd2, - 0x79, 0xa3, 0xd3, 0x55, 0xb2, 0xa5, 0xd7, 0x5b, 0xd0, 0x37, 0x1d, 0x92, 0x58, 0xf6, 0xda, 0x07, - 0x48, 0x9e, 0x02, 0x9d, 0xfb, 0xd6, 0x71, 0x10, 0x7e, 0x0b, 0x2c, 0x94, 0xff, 0xc3, 0xdc, 0xa7, - 0x40, 0x4b, 0x81, 0x34, 0x19, 0xdb, 0x55, 0xc3, 0x46, 0xf8, 0xc3, 0x4d, 0xe7, 0x8a, 0x0d, 0x1c, - 0x69, 0xd2, 0x6f, 0x91, 0xb2, 0xd3, 0xcf, 0xc5, 0x20, 0xfe, 0x0a, 0xc0, 0x6d, 0x95, 0x5b, 0xd2, - 0x50, 0xa6, 0xb8, 0x6f, 0xe1, 0x32, 0xc0, 0x57, 0x13, 0x0b, 0x26, 0xd8, 0x22, 0x9d, 0xe3, 0xad, - 0x06, 0x79, 0xb4, 0xfc, 0xf5, 0x00, 0xb5, 0x5c, 0x76, 0x5d, 0xf9, 0x86, 0xb6, 0x69, 0x4f, 0x6c, - 0x02, 0x2d, 0x92, 0x7d, 0x9c, 0x48, 0x58, 0x7b, 0x17, 0x95, 0x7c, 0xe3, 0x97, 0x4d, 0x93, 0x7a, - 0x4c, 0x26, 0xc1, 0xa1, 0xe0, 0x6c, 0xbb, 0xc3, 0x01, 0x70, 0x9f, 0x14, 0x29, 0x3f, 0xe0, 0x5e] - -dsa_prime_3072_256 = [0xa0, 0x38, 0x3e, 0xe6, 0x92, 0xf8, 0xf5, 0xba, 0xdd, 0xf9, 0x31, 0x7b, 0x16, 0xed, 0xd2, 0x84, - 0xa3, 0x63, 0x19, 0xb0, 0x53, 0xf7, 0x3a, 0xd4, 0x31, 0xae, 0x4b, 0x5d, 0xb2, 0xc6, 0x63, 0x0b, - 0x5a, 0xbf, 0xe8, 0xc5, 0xcb, 0x9d, 0x23, 0x06, 0x50, 0xdc, 0x72, 0xee, 0xfb, 0xe6, 0xf2, 0x61, - 0xdb, 0x2f, 0x43, 0xe6, 0x83, 0x81, 0x58, 0x8c, 0xfd, 0x4a, 0x74, 0x51, 0xbb, 0xbb, 0x30, 0xc5, - 0x95, 0x21, 0xd7, 0x8e, 0xa7, 0x6d, 0xc0, 0x70, 0xcf, 0x81, 0x78, 0x33, 0x19, 0x9f, 0xf7, 0x15, - 0xcb, 0xd1, 0x12, 0xa2, 0x58, 0x50, 0x69, 0x35, 0x44, 0x66, 0x2e, 0x12, 0xbb, 0x27, 0x93, 0xa8, - 0x14, 0x84, 0x77, 0x64, 0xac, 0x27, 0x7c, 0x5c, 0xf0, 0x6b, 0x3e, 0x04, 0x4a, 0x45, 0x91, 0x3e, - 0xdd, 0x61, 0x92, 0x29, 0xdd, 0xd7, 0x28, 0x93, 0x14, 0xd0, 0x0b, 0xb6, 0xa7, 0xda, 0xf1, 0x7e, - 0xb8, 0x63, 0xf3, 0x1d, 0xc2, 0x2c, 0xcc, 0x05, 0xf6, 0x14, 0xc1, 0xbb, 0x0c, 0xea, 0x4c, 0x45, - 0x4f, 0xc6, 0xa0, 0x29, 0xc0, 0xd2, 0x56, 0x8d, 0x1c, 0x5e, 0xef, 0x7f, 0x7c, 0x41, 0xf1, 0xb6, - 0x59, 0xce, 0xd9, 0x24, 0xdd, 0x0e, 0xab, 0xc7, 0xc9, 0xbc, 0x3a, 0x55, 0x90, 0xd4, 0x03, 0x12, - 0xe3, 0xec, 0x13, 0xa2, 0xca, 0xa1, 0x80, 0xed, 0x6b, 0x0c, 0x7d, 0x54, 0xd1, 0x63, 0xca, 0x1f, - 0x32, 0xcd, 0x89, 0x27, 0xa0, 0xfd, 0x39, 0x4e, 0x51, 0xde, 0xf2, 0xa3, 0x1e, 0x83, 0xfc, 0x53, - 0x73, 0xbe, 0xf8, 0xd2, 0x5f, 0x65, 0x32, 0xef, 0x51, 0x5f, 0x86, 0x7b, 0x0b, 0x31, 0x73, 0x8f, - 0xf2, 0x7f, 0xac, 0xad, 0x0d, 0xfb, 0x40, 0xe7, 0x6b, 0x68, 0x3a, 0x3b, 0x11, 0xc9, 0x9f, 0x59, - 0xc8, 0xa4, 0x98, 0xba, 0x2b, 0x88, 0x08, 0x70, 0x0f, 0x20, 0x15, 0x14, 0x5c, 0x77, 0xdb, 0xa4, - 0x20, 0xc5, 0xf0, 0xdb, 0x95, 0xac, 0x88, 0x03, 0x6a, 0x40, 0x90, 0x4a, 0x53, 0xb3, 0x80, 0xaa, - 0x0c, 0x75, 0x80, 0x5a, 0x0d, 0xfd, 0xad, 0x4c, 0xbe, 0xaa, 0x48, 0x91, 0xab, 0xd8, 0x4d, 0x24, - 0xbb, 0x64, 0x4d, 0x96, 0xc5, 0x9f, 0x33, 0x9e, 0x01, 0x6b, 0xb4, 0x32, 0x1f, 0xf4, 0xee, 0x33, - 0xe4, 0x03, 0xce, 0xa0, 0xde, 0x9e, 0xd9, 0x59, 0xcc, 0x6c, 0x1b, 0xba, 0x2c, 0x7d, 0xc7, 0x44, - 0xde, 0x7a, 0x22, 0x5f, 0x65, 0xfb, 0x0a, 0x78, 0xee, 0x57, 0xba, 0x7d, 0x2a, 0x92, 0xf2, 0x47, - 0x50, 0xda, 0xa6, 0x8c, 0x8a, 0x6a, 0x83, 0x06, 0xc3, 0x5c, 0x49, 0x0d, 0x2d, 0x2f, 0x58, 0x92, - 0xbe, 0x12, 0x41, 0x86, 0x0a, 0xd5, 0x45, 0x3b, 0x1b, 0xe3, 0x2b, 0x0e, 0xc7, 0x29, 0x98, 0x3e, - 0x3c, 0x97, 0xd3, 0x28, 0x73, 0xfc, 0x82, 0xc7, 0xb4, 0xf4, 0x6b, 0xfd, 0xa5, 0x14, 0x9e, 0x8f] -dsa_sub_prime_3072_256 = [0xf3, 0x96, 0x52, 0xd0, 0x0e, 0xf7, 0x96, 0x2d, 0xae, 0x7d, 0x8a, 0x13, 0xa8, 0x09, 0xa8, 0x14, - 0xc5, 0xe4, 0xf9, 0xba, 0x8e, 0x6d, 0xea, 0x3d, 0x18, 0xf3, 0x51, 0x48, 0x04, 0xfc, 0xe1, 0x37] -dsa_base_3072_256 = [ 0x07, 0x1f, 0x94, 0x97, 0xf8, 0x58, 0x85, 0x5e, 0xa6, 0x1f, 0xa8, 0x05, 0x97, 0x34, 0xc0, 0x12, - 0x2a, 0xc9, 0x1c, 0xb9, 0xf8, 0x1d, 0xfd, 0x8f, 0xa6, 0xec, 0xc0, 0x83, 0xf6, 0x0c, 0xb3, 0x0e, - 0xa8, 0x0b, 0x15, 0x56, 0xe5, 0xc3, 0x90, 0xd0, 0x06, 0x73, 0x24, 0x68, 0x28, 0xd4, 0xbc, 0xed, - 0xa1, 0x84, 0x89, 0x15, 0xab, 0x86, 0xff, 0x24, 0x56, 0x8e, 0x40, 0x02, 0x03, 0x99, 0xbd, 0xb9, - 0xf6, 0x75, 0x12, 0x59, 0x51, 0xad, 0x1e, 0x57, 0x1d, 0xd4, 0xf2, 0x23, 0x46, 0x14, 0x89, 0xab, - 0x65, 0x45, 0x04, 0x40, 0xe2, 0x2b, 0x01, 0xb8, 0xf5, 0x9b, 0x9b, 0x38, 0x69, 0x2f, 0x12, 0x0b, - 0x98, 0x34, 0xdd, 0x28, 0xeb, 0x9f, 0xf0, 0x8a, 0xfc, 0x44, 0x98, 0xe1, 0x72, 0xeb, 0x3d, 0x54, - 0xb2, 0x8a, 0x8e, 0xb1, 0x00, 0xab, 0x50, 0xa5, 0x66, 0x7b, 0x9a, 0x9e, 0x8a, 0xad, 0x3f, 0x68, - 0xf1, 0xde, 0xb1, 0x04, 0x60, 0x4a, 0x3d, 0x2e, 0x0f, 0x25, 0x0a, 0x9c, 0x18, 0x8b, 0x74, 0x61, - 0xec, 0xd7, 0xde, 0xc6, 0x56, 0xb5, 0x77, 0xe8, 0x46, 0x7e, 0x46, 0x4e, 0x11, 0xac, 0x49, 0x44, - 0x97, 0x88, 0x65, 0xcd, 0xf5, 0x63, 0xaa, 0xb6, 0xa2, 0xe6, 0x8a, 0x29, 0x53, 0x95, 0x2b, 0x0a, - 0x68, 0xe8, 0x81, 0x48, 0x6e, 0x76, 0x34, 0xd4, 0x91, 0x8d, 0xf9, 0x70, 0xa7, 0xce, 0x0d, 0x60, - 0x8a, 0x92, 0x70, 0x8e, 0x49, 0x52, 0x12, 0xfd, 0x4b, 0x26, 0x79, 0x0d, 0x5c, 0x07, 0xdd, 0x5a, - 0xb5, 0x5a, 0xe8, 0x20, 0x9b, 0x63, 0x19, 0x05, 0x55, 0xc0, 0x43, 0xb7, 0x80, 0x2f, 0xae, 0x78, - 0x79, 0x7e, 0x4f, 0x63, 0xf1, 0xcb, 0x18, 0x09, 0xaf, 0x4a, 0xfc, 0x60, 0xb2, 0xb4, 0xaf, 0x78, - 0xba, 0xb3, 0xad, 0x9c, 0xcc, 0x39, 0x10, 0x08, 0x96, 0x43, 0x8e, 0x67, 0x91, 0xae, 0xec, 0x90, - 0xe8, 0x99, 0xf9, 0x76, 0x59, 0x45, 0x4f, 0x4c, 0x75, 0x96, 0x33, 0xb0, 0xd8, 0x57, 0xb5, 0x05, - 0x12, 0x45, 0x15, 0xc7, 0x5e, 0x3a, 0x64, 0x90, 0xe7, 0x16, 0x8c, 0x73, 0xfa, 0x15, 0x68, 0xe8, - 0xc9, 0x04, 0xb0, 0x42, 0x49, 0xfa, 0x31, 0xa8, 0x3c, 0x6d, 0x83, 0x8a, 0xf7, 0xd4, 0x2d, 0x48, - 0x71, 0x09, 0x89, 0xf9, 0xfb, 0xc9, 0xc3, 0x7b, 0x2c, 0x87, 0x91, 0x57, 0xc9, 0xe9, 0x81, 0x8e, - 0xa4, 0xdd, 0xb7, 0x7a, 0x1f, 0xbc, 0x66, 0x3e, 0xd8, 0x2d, 0xe8, 0x38, 0xc3, 0xab, 0x3b, 0x82, - 0xc5, 0x7d, 0xd0, 0xff, 0xbf, 0xa4, 0x95, 0xe6, 0xea, 0xd3, 0x3e, 0x44, 0x05, 0xd0, 0x58, 0xe9, - 0xb3, 0x7b, 0x3a, 0x71, 0xce, 0xbd, 0xe4, 0x2f, 0x4d, 0x33, 0x46, 0xb4, 0xc5, 0xf9, 0xd6, 0x49, - 0x8b, 0x73, 0xbc, 0x1b, 0x9f, 0x0d, 0x3d, 0x0c, 0x49, 0x29, 0x42, 0x99, 0x70, 0xe9, 0xc5, 0xeb] - -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_1024_160, - CKA_SUBPRIME : dsa_sub_prime_1024_160, - CKA_BASE : dsa_base_1024_160, - CKA_LABEL : "DSA 1024_160 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_2048_224, - CKA_SUBPRIME : dsa_sub_prime_2048_224, - CKA_BASE : dsa_base_2048_224, - CKA_LABEL : "DSA 2048_224 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_2048_256, - CKA_SUBPRIME : dsa_sub_prime_2048_256, - CKA_BASE : dsa_base_2048_256, - CKA_LABEL : "DSA 2048_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_3072_256, - CKA_SUBPRIME : dsa_sub_prime_3072_256, - CKA_BASE : dsa_base_3072_256, - CKA_LABEL : "DSA 3072_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "DSA Public Key"} - -dh_prime = [0xF4, 0x88, 0xFD, 0x58, 0x4E, 0x49, 0xDB, 0xCD, 0x20, 0xB4, 0x9D, 0xE4, 0x91, 0x07, 0x36, 0x6B, - 0x33, 0x6C, 0x38, 0x0D, 0x45, 0x1D, 0x0F, 0x7C, 0x88, 0xB3, 0x1C, 0x7C, 0x5B, 0x2D, 0x8E, 0xF6, - 0xF3, 0xC9, 0x23, 0xC0, 0x43, 0xF0, 0xA5, 0x5B, 0x18, 0x8D, 0x8E, 0xBB, 0x55, 0x8C, 0xB8, 0x5D, - 0x38, 0xD3, 0x34, 0xFD, 0x7C, 0x17, 0x57, 0x43, 0xA3, 0x1D, 0x18, 0x6C, 0xDE, 0x33, 0x21, 0x2C, - 0xB5, 0x2A, 0xFF, 0x3C, 0xE1, 0xB1, 0x29, 0x40, 0x18, 0x11, 0x8D, 0x7C, 0x84, 0xA7, 0x0A, 0x72, - 0xD6, 0x86, 0xC4, 0x03, 0x19, 0xC8, 0x07, 0x29, 0x7A, 0xCA, 0x95, 0x0C, 0xD9, 0x96, 0x9F, 0xAB, - 0xD0, 0x0A, 0x50, 0x9B, 0x02, 0x46, 0xD3, 0x08, 0x3D, 0x66, 0xA4, 0x5D, 0x41, 0x9F, 0x9C, 0x7C, - 0xBD, 0x89, 0x4B, 0x22, 0x19, 0x26, 0xBA, 0xAB, 0xA2, 0x5E, 0xC3, 0x55, 0xE9, 0x2F, 0x78, 0xC7] -dh_prime_2048= [0xF1, 0x20, 0xB5, 0x5B, 0x3A, 0xE4, 0xD0, 0xF6, 0xEF, 0xA4, 0xF2, 0x9F, 0xC4, 0xDF, 0x86, 0x84, - 0x57, 0x54, 0x14, 0x90, 0x98, 0xBD, 0x3E, 0x57, 0x86, 0xE8, 0xC9, 0xA0, 0x30, 0xAF, 0xE6, 0xA7, - 0x6D, 0x7E, 0x4F, 0xDA, 0x20, 0x87, 0x46, 0x0C, 0xED, 0x88, 0xDC, 0xDB, 0x95, 0xDE, 0xD3, 0x4F, - 0xC7, 0x18, 0x80, 0x3A, 0x0D, 0xD2, 0xF1, 0x54, 0x5C, 0xD2, 0x29, 0x78, 0x3C, 0xE4, 0x40, 0x0C, - 0x1A, 0x6B, 0x36, 0x73, 0x42, 0xE1, 0xB3, 0xD3, 0xEB, 0x95, 0xDB, 0x7A, 0x06, 0xD6, 0x54, 0x11, - 0xDB, 0x0B, 0xB3, 0x00, 0x52, 0xA5, 0x74, 0x77, 0x5B, 0x47, 0x2A, 0x6E, 0x31, 0xCB, 0x8A, 0x5D, - 0x1C, 0x8A, 0x7D, 0x93, 0x7A, 0xC3, 0x62, 0x44, 0xC3, 0x29, 0x40, 0x6D, 0x3E, 0x47, 0x62, 0x2F, - 0x93, 0xCD, 0xF3, 0xED, 0xA6, 0x1E, 0x1D, 0x57, 0x4E, 0xFF, 0x5F, 0x46, 0x92, 0xCC, 0xFC, 0x7E, - 0x98, 0x8C, 0xE8, 0xB0, 0xAA, 0x33, 0x70, 0x96, 0x3D, 0xC1, 0x5B, 0x10, 0x2A, 0x07, 0x34, 0x84, - 0x4E, 0xCD, 0xEB, 0xD7, 0x15, 0x63, 0x8C, 0xC4, 0x67, 0xB0, 0xC1, 0xB9, 0xB8, 0x45, 0xB0, 0x3B, - 0x3A, 0x76, 0x83, 0x2C, 0xF5, 0x28, 0xB3, 0xF7, 0x10, 0x23, 0x7E, 0xAA, 0xF6, 0xE6, 0x8B, 0xE7, - 0x57, 0x35, 0x1F, 0x51, 0x34, 0x58, 0x5E, 0x0C, 0x2D, 0x36, 0xCF, 0xA3, 0x85, 0x34, 0xB0, 0x14, - 0x7D, 0xD0, 0x8C, 0x34, 0xBB, 0xC1, 0x8D, 0x49, 0x8C, 0xDA, 0x41, 0x48, 0x66, 0xDB, 0x41, 0xE1, - 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, - 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, - 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] -CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_DERIVE : True, - CKA_PRIME : dh_prime, - CKA_BASE : [0x02], - CKA_LABEL : "DH Public Key"} -CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS : len(dh_prime) * 8, #long - CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DERIVE : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "DH Private Key"} - -CKM_CAST5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_CAST5, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, # 1-16 - CKA_EXTRACTABLE :True, - CKA_LABEL : "CAST5 Key"} - -CKM_RC2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_RC2, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 64, #1-128 - CKA_EXTRACTABLE :True, - CKA_LABEL : "RC2 Key"} - -CKM_RC4_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_RC4, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 256, #1-256 - CKA_EXTRACTABLE :True, - CKA_LABEL : "RC4 Key"} - -CKM_RC5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_RC5, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 255, #1-255 - CKA_EXTRACTABLE :True, - CKA_LABEL : "RC5 Key"} - -CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP = {CKA_TOKEN : True, - CKA_DERIVE : True, - CKA_ENCRYPT : 0x1001, #TODO, is encrypt both a long and a boolean, uh oh - CKA_LABEL : "SSL3 Pre Master Key"} - - -''' -Curve dictionary for ECDSA with oids as lists, taken from Components/tools/common/CommonData.cpp -''' -curve_list = { - 'secp112r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x06], # [0] OID_secp112r1 - 'secp112r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x07], # [7] OID_secp112r2 - 'secp128r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1C], # [14] OID_secp128r1 - 'secp128r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1D], # [21] OID_secp128r2 - 'secp160k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x09], # [28] OID_secp160k1 - 'secp160r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x08], # [35] OID_secp160r1 - 'secp160r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1E], # [42] OID_secp160r2 - 'secp192k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1F], # [49] OID_secp192k1 - 'secp224k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x20], # [56] OID_secp224k1 - 'secp224r1(P-224)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x21], # [63] OID_secp224r1 - 'secp256k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], # [70] OID_secp256k1 - 'secp384r1(P-384)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], # [77] OID_secp384r1 - 'secp521r1(P-521)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], # [84] OID_secp521r1 - - 'X9_62_prime192v1(P-192)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01], # [91] OID_X9_62_prime192v1 - 'X9_62_prime192v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], # [101] OID_X9_62_prime192v2 - 'X9_62_prime192v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], # [111] OID_X9_62_prime192v3 - 'X9_62_prime239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], # [121] OID_X9_62_prime239v1 - 'X9_62_prime239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], # [131] OID_X9_62_prime239v2 - 'X9_62_prime239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], # [141] OID_X9_62_prime239v3 - 'X9_62_prime256v1(P-256)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], # [151] OID_X9_62_prime256v1 - - 'sect113r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x04], # [161] OID_sect113r1 - 'sect113r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x05], # [168] OID_sect113r2 - 'sect131r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x16], # [175] OID_sect131r1 - 'sect131r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x17], # [182] OID_sect131r2 - 'sect163k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x01], # [189] OID_sect163k1 - 'sect163r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x02], # [196] OID_sect163r1 - 'sect163r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0F], # [203] OID_sect163r2 - 'sect193r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x18], # [210] OID_sect193r1 - 'sect193r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x19], # [217] OID_sect193r2 - 'sect233k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1A], # [224] OID_sect233k1 - 'sect233r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1B], # [231] OID_sect233r1 - 'sect239k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x03], # [238] OID_sect239k1 - 'sect283k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x10], # [245] OID_sect283k1 - 'sect283r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x11], # [252] OID_sect283r1 - 'sect409k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x24], # [259] OID_sect409k1 - 'sect409r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x25], # [266] OID_sect409r1 - 'sect571k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x26], # [273] OID_sect571k1 - 'sect571r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x27], # [280] OID_sect571r1 - - 'X9_62_c2pnb163v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], # [287] OID_X9_62_c2pnb163v1 - 'X9_62_c2pnb163v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], # [297] OID_X9_62_c2pnb163v2 - 'X9_62_c2pnb163v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], # [307] OID_X9_62_c2pnb163v3 - 'X9_62_c2pnb176v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], # [317] OID_X9_62_c2pnb176v1 - 'X9_62_c2tnb191v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], # [327] OID_X9_62_c2tnb191v1 - 'X9_62_c2tnb191v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], # [337] OID_X9_62_c2tnb191v2 - 'X9_62_c2tnb191v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], # [347] OID_X9_62_c2tnb191v3 - 'X9_62_c2pnb208w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], # [357] OID_X9_62_c2pnb208w1 - 'X9_62_c2tnb239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], # [367] OID_X9_62_c2tnb239v1 - 'X9_62_c2tnb239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], # [377] OID_X9_62_c2tnb239v2 - 'X9_62_c2tnb239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], # [387] OID_X9_62_c2tnb239v3 - 'X9_62_c2pnb272w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], # [397] OID_X9_62_c2pnb272w1 - 'X9_62_c2pnb304w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], # [407] OID_X9_62_c2pnb304w1 - 'X9_62_c2tnb359v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], # [417] OID_X9_62_c2tnb359v1 - 'X9_62_c2pnb368w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], # [427] OID_X9_62_c2pnb368w1 - 'X9_62_c2tnb431r1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], # [437] OID_X9_62_c2tnb431r1 - - 'brainpoolP160r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], # [447] brainpoolP160r1 - 'brainpoolP160t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], # [458] brainpoolP160t1 - 'brainpoolP192r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], # [469] brainpoolP192r1 - 'brainpoolP192t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], # [480] brainpoolP192t1 - 'brainpoolP224r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], # [491] brainpoolP224r1 - 'brainpoolP224t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], # [502] brainpoolP224t1 - 'brainpoolP256r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], # [513] brainpoolP256r1 - 'brainpoolP256t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], # [524] brainpoolP256t1 - 'brainpoolP320r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], # [535] brainpoolP320r1 - 'brainpoolP320t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], # [546] brainpoolP320t1 - 'brainpoolP384r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], # [557] brainpoolP384r1 - 'brainpoolP384t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], # [568] brainpoolP384t1 - 'brainpoolP512r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], # [579] brainpoolP512r1 - 'brainpoolP512t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], # [590] brainpoolP512t1 - 'microsoftPlayReadP160' : [0x30, 0x81, 0x95, 0x02, 0x01, 0x01, 0x30, 0x20, - 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, - 0x01, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, - 0x01, 0x23, 0x45, 0x67, 0x27, 0x18, 0x28, 0x18, - 0x31, 0x41, 0x59, 0x26, 0x14, 0x14, 0x24, 0xf7, - 0x30, 0x2c, 0x04, 0x14, 0x37, 0xa5, 0xab, 0xcc, - 0xd2, 0x77, 0xbc, 0xe8, 0x76, 0x32, 0xff, 0x3d, - 0x47, 0x80, 0xc0, 0x09, 0xeb, 0xe4, 0x14, 0x97, - 0x04, 0x14, 0x0d, 0xd8, 0xda, 0xbf, 0x72, 0x5e, - 0x2f, 0x32, 0x28, 0xe8, 0x5f, 0x1a, 0xd7, 0x8f, - 0xde, 0xdf, 0x93, 0x28, 0x23, 0x9e, 0x04, 0x29, - 0x04, 0x87, 0x23, 0x94, 0x7f, 0xd6, 0xa3, 0xa1, - 0xe5, 0x35, 0x10, 0xc0, 0x7d, 0xba, 0x38, 0xda, - 0xf0, 0x10, 0x9f, 0xa1, 0x20, 0x44, 0x57, 0x44, - 0x91, 0x10, 0x75, 0x52, 0x2d, 0x8c, 0x3c, 0x58, - 0x56, 0xd4, 0xed, 0x7a, 0xcd, 0xa3, 0x79, 0x93, - 0x6f, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, - 0x01, 0x23, 0x45, 0x67, 0x27, 0x16, 0xb2, 0x6e, - 0xec, 0x14, 0x90, 0x44, 0x28, 0xc2, 0xa6, 0x75] - } - -CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_DERIVE : True, - CKA_ECDSA_PARAMS : curve_list['secp112r1'], - CKA_LABEL : "ECDSA Public Key"} - -CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_DERIVE : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "ECDSA Private Key"} - -CKM_AES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_AES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 24, #16, 24, 32 - CKA_EXTRACTABLE :True, - CKA_LABEL : "AES Key"} - -CKM_SEED_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_SEED, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "SEED Key"} - -kcdsa_prime_1024_160 = [0xdc, 0x02, 0xf3, 0xe0, 0x51, 0x4e, 0xf4, 0x72, 0x36, 0x51, 0x09, 0x72, 0x5c, 0x12, 0x00, 0x50, - 0x69, 0x7d, 0xfc, 0x1d, 0xcb, 0xb4, 0x1f, 0xbc, 0x49, 0x63, 0xc4, 0x15, 0x45, 0x97, 0xb7, 0xae, - 0x8d, 0x4a, 0x35, 0x3c, 0xe2, 0xfb, 0x1f, 0xbf, 0x77, 0x7b, 0x89, 0xe5, 0x56, 0xc5, 0x15, 0x6b, - 0x1a, 0x4a, 0x82, 0xcc, 0xe2, 0xb8, 0xec, 0x4d, 0x61, 0x86, 0xd4, 0xa3, 0xf6, 0xc5, 0x65, 0xae, - 0x8c, 0xf6, 0x04, 0x62, 0x1d, 0x63, 0xec, 0x9f, 0x1e, 0x91, 0x31, 0x39, 0x1d, 0xc0, 0x55, 0xbc, - 0xac, 0xc5, 0x1a, 0xc8, 0x5c, 0x02, 0x93, 0xd7, 0xca, 0x74, 0x4f, 0xe9, 0xa2, 0x04, 0x5c, 0x3c, - 0xc1, 0xb6, 0xe1, 0x4d, 0xcd, 0xfa, 0xbb, 0x7d, 0xf8, 0xa7, 0xb1, 0x94, 0xd5, 0x08, 0xe1, 0x99, - 0xc1, 0x81, 0x62, 0x93, 0xd6, 0x8c, 0x7a, 0x5c, 0x0f, 0x8a, 0xc7, 0x14, 0xb5, 0xd6, 0xf5, 0xa3] -kcdsa_sub_prime_1024_160 = [0xc8, 0xf6, 0x2e, 0x10, 0xf0, 0xa4, 0xe5, 0x43, 0x1b, 0x8e, 0x1b, 0x0f, 0x53, 0xf6, 0x27, 0xec, - 0x6a, 0xd3, 0xa6, 0xa5] -kcdsa_base_1024_160 = [0x9b, 0x8b, 0x4b, 0x16, 0x53, 0x65, 0x03, 0x18, 0x47, 0x19, 0xac, 0x4d, 0x13, 0x2d, 0x14, 0x57, - 0x2d, 0xca, 0x56, 0x45, 0x3f, 0x05, 0x68, 0x68, 0x3b, 0x04, 0x17, 0x27, 0x6f, 0x93, 0x88, 0xdc, - 0x0a, 0x79, 0xe7, 0x76, 0x45, 0x4a, 0x97, 0x7a, 0x02, 0xc0, 0x1a, 0xc7, 0x7a, 0x07, 0x1f, 0x6b, - 0x99, 0x81, 0x67, 0xb8, 0xb9, 0x89, 0xce, 0xfd, 0x88, 0x7a, 0x26, 0x71, 0xf9, 0x44, 0x12, 0xcc, - 0x94, 0xac, 0x62, 0xe7, 0x61, 0xc9, 0x5a, 0xdb, 0x38, 0xf7, 0x8b, 0x76, 0x73, 0xcc, 0x09, 0x0a, - 0x62, 0xcf, 0xab, 0x4b, 0x03, 0x29, 0x0d, 0x34, 0x92, 0xb9, 0x09, 0x83, 0x68, 0x9b, 0x30, 0x82, - 0x1f, 0xcf, 0xb0, 0xdb, 0x83, 0x71, 0x24, 0x2c, 0x73, 0xf3, 0xa6, 0x4f, 0x56, 0xb2, 0x13, 0xfd, - 0xdb, 0xbc, 0xcf, 0x77, 0x5d, 0x01, 0x1f, 0xb8, 0x35, 0x85, 0x4f, 0x88, 0xb0, 0x58, 0x92, 0x07] -kcdsa_prime_2048_256 = [0xec, 0xfe, 0xa3, 0x3f, 0xa2, 0x27, 0xc3, 0xb1, 0xa7, 0xdf, 0xd7, 0xf1, 0xbb, 0x48, 0x7c, 0xd4, - 0x26, 0xab, 0x0a, 0x2b, 0x2b, 0x3a, 0xf1, 0x8f, 0xef, 0x9d, 0x61, 0xcd, 0x4f, 0x7b, 0xbb, 0x8d, - 0x7d, 0x8d, 0x4c, 0x84, 0x13, 0x7a, 0xaf, 0xe5, 0xb5, 0xba, 0x9d, 0xe4, 0xd2, 0xb5, 0x8b, 0x00, - 0x39, 0xbc, 0x66, 0x9c, 0x7c, 0x3d, 0x98, 0x7e, 0x0a, 0x74, 0x1b, 0x06, 0xcf, 0x97, 0xb5, 0x3e, - 0xcb, 0x1e, 0x1d, 0x22, 0x51, 0xe6, 0xd4, 0xe2, 0x72, 0xa7, 0x72, 0xd3, 0x4c, 0x3f, 0xfc, 0xd4, - 0xd5, 0x7c, 0x3f, 0x44, 0xa2, 0x1b, 0xfc, 0x97, 0xad, 0x34, 0xb2, 0x8f, 0xd3, 0xcf, 0x77, 0x89, - 0x7a, 0xce, 0x64, 0xc6, 0x92, 0xaa, 0x69, 0x13, 0xed, 0x22, 0xa2, 0x3b, 0x45, 0x19, 0x98, 0x88, - 0x29, 0x05, 0x7c, 0xd2, 0x33, 0xaf, 0xa1, 0xf7, 0xab, 0x66, 0x40, 0xca, 0x05, 0x7e, 0x16, 0x99, - 0x7a, 0x92, 0xaa, 0x5e, 0x07, 0xc0, 0xc7, 0x3c, 0x82, 0xb4, 0x96, 0x02, 0x23, 0x66, 0x99, 0x97, - 0xa3, 0x40, 0xf1, 0x36, 0x9b, 0x33, 0xc7, 0xbe, 0xe9, 0xac, 0xce, 0x85, 0xf8, 0xbd, 0x6a, 0x26, - 0x0f, 0x79, 0xe7, 0x9e, 0xee, 0xee, 0xd6, 0x82, 0xc8, 0x7d, 0x4b, 0xe7, 0x4c, 0x2f, 0x44, 0x9a, - 0x1b, 0x68, 0x3f, 0xba, 0xe4, 0xfd, 0x19, 0xca, 0xd0, 0x97, 0xd3, 0x71, 0x12, 0x8c, 0x86, 0xbe, - 0x93, 0x84, 0xb7, 0x35, 0x2a, 0xd1, 0x3a, 0x9a, 0x27, 0x8f, 0x36, 0x4f, 0x08, 0x9e, 0x38, 0xdf, - 0x25, 0xe8, 0x4a, 0x70, 0x4d, 0xe4, 0xfb, 0x16, 0x40, 0xa5, 0x19, 0xfc, 0x62, 0x91, 0x76, 0x1d, - 0xab, 0x11, 0xe2, 0xf7, 0x80, 0xe7, 0x1a, 0x62, 0x2e, 0x9a, 0xbf, 0x85, 0xfe, 0x19, 0x4a, 0x45, - 0x79, 0x3b, 0xfa, 0xb3, 0xa1, 0xe9, 0x8a, 0x1d, 0xfd, 0x57, 0xb5, 0xc7, 0x09, 0x79, 0xb8, 0x1b] -kcdsa_sub_prime_2048_256 = [0xe5, 0x7d, 0x48, 0xd4, 0x44, 0x3d, 0x60, 0xb2, 0x6f, 0x48, 0x82, 0x3d, 0x1d, 0xea, 0xce, 0xf2, - 0xb4, 0x4a, 0x6c, 0x47, 0x5b, 0x12, 0x43, 0x47, 0xb4, 0x81, 0x47, 0xf8, 0xa2, 0xfd, 0x33, 0xd3] -kcdsa_base_2048_256 = [0x68, 0x90, 0xea, 0x6f, 0x5a, 0x56, 0x4f, 0xd2, 0xa1, 0xfe, 0x07, 0xd7, 0xbc, 0xa5, 0xab, 0x80, - 0xf9, 0x5a, 0x5f, 0x47, 0xe9, 0x7f, 0xfc, 0x9a, 0xea, 0x67, 0x13, 0xf8, 0xad, 0x36, 0xe1, 0xfc, - 0x02, 0x42, 0x17, 0xcd, 0xf9, 0xbe, 0x5c, 0xe9, 0xa6, 0xcd, 0xdb, 0x6b, 0x5c, 0x1e, 0x7e, 0x22, - 0x0e, 0xd5, 0x7f, 0x2b, 0x0c, 0x9b, 0xf7, 0xe2, 0xd5, 0x23, 0xc1, 0x45, 0x0b, 0x46, 0x7e, 0x64, - 0x80, 0xc9, 0x6f, 0x9b, 0x20, 0x76, 0xd0, 0x3f, 0xae, 0x8c, 0x4d, 0x99, 0x3e, 0x9c, 0xe6, 0x6b, - 0xc9, 0xb8, 0x39, 0xa5, 0x58, 0x15, 0x6c, 0x69, 0x79, 0x2a, 0xfa, 0x34, 0x76, 0x17, 0x64, 0x6a, - 0x2a, 0x29, 0x4d, 0xce, 0xe4, 0x07, 0x78, 0xa3, 0xcb, 0x93, 0x7a, 0x78, 0x2a, 0x51, 0x91, 0xbd, - 0x42, 0x97, 0x3b, 0x07, 0x31, 0xca, 0x4f, 0x62, 0x2a, 0x63, 0xe0, 0x69, 0x45, 0x31, 0xc8, 0x75, - 0x3e, 0x3a, 0xb0, 0xe8, 0x8d, 0xdc, 0x86, 0x1c, 0x75, 0x1c, 0x25, 0x2e, 0x74, 0x18, 0x89, 0xb3, - 0x3e, 0x39, 0x0e, 0x1c, 0xa5, 0xc4, 0x75, 0x1f, 0x31, 0x1e, 0x19, 0x61, 0x5b, 0xbe, 0xa7, 0x18, - 0x9b, 0x04, 0xf2, 0x29, 0xc8, 0xe7, 0x40, 0x84, 0x39, 0xd2, 0x28, 0xa5, 0x30, 0x5b, 0x22, 0x78, - 0x33, 0xab, 0xa8, 0x30, 0x98, 0x1c, 0x33, 0xec, 0xfe, 0xe7, 0x90, 0x8c, 0x6d, 0x39, 0x54, 0x42, - 0x9b, 0xef, 0x30, 0xde, 0xa1, 0x15, 0xfe, 0xe6, 0xd0, 0x3f, 0x13, 0xf0, 0xa0, 0x2e, 0xb2, 0x19, - 0xe4, 0xb9, 0xb0, 0xba, 0xac, 0x32, 0xc2, 0x24, 0x0b, 0x2a, 0x47, 0x17, 0xda, 0x7c, 0x11, 0x6c, - 0xe2, 0x09, 0x24, 0x71, 0x30, 0xac, 0x14, 0x0c, 0xd3, 0xab, 0xdc, 0xe7, 0x78, 0xa4, 0x27, 0x27, - 0xf3, 0x2c, 0xfa, 0xfd, 0xae, 0x9e, 0x51, 0x68, 0x47, 0xb2, 0x6c, 0xe4, 0xcb, 0xb7, 0x66, 0x03] -CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, #1024_160 or 2048_256 - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : kcdsa_prime_1024_160, - CKA_SUBPRIME : kcdsa_sub_prime_1024_160, - CKA_BASE : kcdsa_base_1024_160, - CKA_LABEL : "KCDSA Public Key"} -CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, #1024_160 or 2048_256 - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : kcdsa_prime_2048_256, - CKA_SUBPRIME : kcdsa_sub_prime_2048_256, - CKA_BASE : kcdsa_base_2048_256, - CKA_LABEL : "KCDSA Public Key"} -CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "KCDSA Private Key"} - -CKM_DSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_PRIME_BITS : 1024, # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 - CKA_SUBPRIME_BITS : 160, #0-512 - CKA_LABEL : "DSA Parameter Key"} - -CKM_KCDSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, #primelength 0-4096, subprimelength 0-512 - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_PRIME_BITS : 2048, #0-4096 - CKA_SUBPRIME_BITS : 256, #0-512 - CKA_LABEL : "KCDSA Parameter Key"} - -CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_MODIFIABLE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_MODULUS_BITS : 1024, #long 1-MAX_RSA_KEY_NBITS - CKA_PUBLIC_EXPONENT : 3, #byte - CKA_LABEL : "RSA Public Key"} -CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_MODIFIABLE : True, - CKA_EXTRACTABLE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_LABEL : "RSA Private Key"} - -dhX9_42Prime = [0xE0, 0x01, 0xE8, 0x96, 0x7D, 0xB4, 0x93, 0x53, 0xE1, 0x6F, 0x8E, 0x89, 0x22, 0x0C, 0xCE, 0xFC, - 0x5C, 0x5F, 0x12, 0xE3, 0xDF, 0xF8, 0xF1, 0xD1, 0x49, 0x90, 0x12, 0xE6, 0xEF, 0x53, 0xE3, 0x1F, - 0x02, 0xEA, 0xCC, 0x5A, 0xDD, 0xF3, 0x37, 0x89, 0x35, 0xC9, 0x5B, 0x21, 0xEA, 0x3D, 0x6F, 0x1C, - 0xD7, 0xCE, 0x63, 0x75, 0x52, 0xEC, 0x38, 0x6C, 0x0E, 0x34, 0xF7, 0x36, 0xAD, 0x95, 0x17, 0xEF, - 0xFE, 0x5E, 0x4D, 0xA7, 0xA8, 0x6A, 0xF9, 0x0E, 0x2C, 0x22, 0x8F, 0xE4, 0xB9, 0xE6, 0xD8, 0xF8, - 0xF0, 0x2D, 0x20, 0xAF, 0x78, 0xAB, 0xB6, 0x92, 0xAC, 0xBC, 0x4B, 0x23, 0xFA, 0xF2, 0xC5, 0xCC, - 0xD4, 0x9A, 0x0C, 0x9A, 0x8B, 0xCD, 0x91, 0xAC, 0x0C, 0x55, 0x92, 0x01, 0xE6, 0xC2, 0xFD, 0x1F, - 0x47, 0xC2, 0xCB, 0x2A, 0x88, 0xA8, 0x3C, 0x21, 0x0F, 0xC0, 0x54, 0xDB, 0x29, 0x2D, 0xBC, 0x45] -dhX9_42Base = [0x86, 0x47, 0x17, 0xA3, 0x9E, 0x6A, 0xEA, 0x7E, 0x87, 0xC4, 0x32, 0xEE, 0x77, 0x43, 0x15, 0x16, - 0x96, 0x70, 0xC4, 0x99] -dhX9_42SubPrime = [0x1C, 0xE0, 0xF6, 0x69, 0x26, 0x46, 0x11, 0x97, 0xEF, 0x45, 0xC4, 0x65, 0x8B, 0x83, 0xB8, 0xAB, - 0x04, 0xA9, 0x22, 0x42, 0x68, 0x50, 0x4D, 0x05, 0xB8, 0x19, 0x83, 0x99, 0xDD, 0x71, 0x37, 0x18, - 0xCC, 0x1F, 0x24, 0x5D, 0x47, 0x6C, 0xCF, 0x61, 0xA2, 0xF9, 0x34, 0x93, 0xF4, 0x1F, 0x55, 0x52, - 0x48, 0x65, 0x57, 0xE6, 0xD4, 0xCA, 0xA8, 0x00, 0xD6, 0xD0, 0xDB, 0x3C, 0xBF, 0x5A, 0x95, 0x4B, - 0x20, 0x8A, 0x4E, 0xBA, 0xF7, 0xE6, 0x49, 0xFB, 0x61, 0x24, 0xD8, 0xA2, 0x1E, 0xF2, 0xF2, 0x2B, - 0xAA, 0xAE, 0x29, 0x21, 0x10, 0x19, 0x10, 0x51, 0x46, 0x47, 0x31, 0xB6, 0xCC, 0x3C, 0x93, 0xDC, - 0x6E, 0x80, 0xBA, 0x16, 0x0B, 0x66, 0x64, 0xA5, 0x6C, 0xFA, 0x96, 0xEA, 0xF1, 0xB2, 0x83, 0x39, - 0x8E, 0xB4, 0x61, 0x64, 0xE5, 0xE9, 0x43, 0x84, 0xEE, 0x02, 0x24, 0xE7, 0x1F, 0x03, 0x7C, 0x23] -CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE: True, - CKA_SENSITIVE : True, - CKA_DERIVE : True, - CKA_PRIME : dhX9_42Prime, - CKA_BASE : dhX9_42Base, - CKA_SUBPRIME : dhX9_42SubPrime, - CKA_LABEL : "DH X9.42 Public Key"} -CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DERIVE : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "DH X9.42 Private Key"} - -CKM_ARIA_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_ARIA, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 24, #16, 24, 32 - CKA_EXTRACTABLE :True, - CKA_LABEL : "ARIA Key"} - -CKM_DH_PKCS_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_PRIME_BITS : 512, #between 512 and 2048 in 256bit increments (&0xff) - CKA_LABEL : "SH PKCS Parameter Key"} - -''' -The simple certificate object taken from CKDemo when -you select the Create Object option and choose certificate -''' -CERTIFICATE_TEMPLATE = { CKA_CLASS: CKO_CERTIFICATE, - CKA_CERTIFICATE_TYPE : CKC_X_509, - CKA_TOKEN : True, - CKA_LABEL : "Created certificate object", - CKA_SUBJECT : "", - CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} - -''' -The simple data object template taken from CKDemo when you select -the Create Object option and choose data -''' -DATA_TEMPLATE = { CKA_CLASS : CKO_DATA, - CKA_TOKEN : True, - CKA_LABEL : "Created data object", - CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} - -KEY_GENERATOR_TEMPLATES = {CKM_DES_KEY_GEN : CKM_DES_KEY_GEN_TEMP, - CKM_DES2_KEY_GEN : CKM_DES2_KEY_GEN_TEMP, - CKM_DES3_KEY_GEN: CKM_DES3_KEY_GEN_TEMP, - CKM_CAST3_KEY_GEN: CKM_CAST3_KEY_GEN_TEMP, - CKM_GENERIC_SECRET_KEY_GEN: CKM_GENERIC_SECRET_KEY_GEN_TEMP, - CKM_CAST5_KEY_GEN: CKM_CAST5_KEY_GEN_TEMP, - CKM_RC2_KEY_GEN: CKM_RC2_KEY_GEN_TEMP, - CKM_RC4_KEY_GEN: CKM_RC4_KEY_GEN_TEMP, - CKM_RC5_KEY_GEN: CKM_RC5_KEY_GEN_TEMP, - CKM_AES_KEY_GEN: CKM_AES_KEY_GEN_TEMP, - CKM_SEED_KEY_GEN: CKM_SEED_KEY_GEN_TEMP, - CKM_ARIA_KEY_GEN: CKM_ARIA_KEY_GEN_TEMP, - CKM_DH_PKCS_PARAMETER_GEN: CKM_DH_PKCS_PARAMETER_GEN_TEMP} - -KEY_PAIR_GENERATOR_TEMPLATES = { #Note lacks multiple sizes of the same kinds of keys - CKM_RSA_PKCS_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), #pkcs template is good for x9.31 - CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_DSA_KEY_PAIR_GEN : (CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_DH_PKCS_KEY_PAIR_GEN : (CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_ECDSA_KEY_PAIR_GEN : (CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_KCDSA_KEY_PAIR_GEN : (CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP)} - -''' -This list is not complete -''' -MECHANISM_LOOKUP = {CKM_RSA_PKCS_KEY_PAIR_GEN: "CKM_RSA_PKCS_KEY_PAIR_GEN", - CKM_RSA_PKCS: "CKM_RSA_PKCS", - CKM_SHA1_RSA_PKCS: "CKM_SHA1_RSA_PKCS", - CKM_SHA224_RSA_PKCS: "CKM_SHA224_RSA_PKCS", - CKM_SHA256_RSA_PKCS: "CKM_SHA256_RSA_PKCS", - CKM_SHA384_RSA_PKCS: "CKM_SHA384_RSA_PKCS", - CKM_SHA512_RSA_PKCS: "CKM_SHA512_RSA_PKCS", - CKM_RSA_PKCS_PSS: "CKM_RSA_PKCS_PSS", - CKM_SHA1_RSA_PKCS_PSS: "CKM_SHA1_RSA_PKCS_PSS", - CKM_SHA224_RSA_PKCS_PSS: "CKM_SHA224_RSA_PKCS_PSS", - CKM_SHA256_RSA_PKCS_PSS: "CKM_SHA256_RSA_PKCS_PSS", - CKM_SHA384_RSA_PKCS_PSS: "CKM_SHA384_RSA_PKCS_PSS", - CKM_SHA512_RSA_PKCS_PSS: "CKM_SHA512_RSA_PKCS_PSS", - CKM_RSA_X9_31_KEY_PAIR_GEN: "CKM_RSA_X9_31_KEY_PAIR_GEN", - CKM_RSA_X9_31: "CKM_RSA_X9_31", - CKM_SHA1_RSA_X9_31: "CKM_SHA1_RSA_X9_31", - CKM_SHA224_RSA_X9_31: "CKM_SHA224_RSA_X9_31", - CKM_SHA256_RSA_X9_31: "CKM_SHA256_RSA_X9_31", - CKM_SHA384_RSA_X9_31: "CKM_SHA384_RSA_X9_31", - CKM_SHA512_RSA_X9_31: "CKM_SHA512_RSA_X9_31", - CKM_RSA_PKCS_OAEP: "CKM_RSA_PKCS_OAEP", - CKM_DSA_KEY_PAIR_GEN: "CKM_DSA_KEY_PAIR_GEN", - CKM_DSA: "CKM_DSA", - CKM_DSA_SHA1: "CKM_DSA_SHA1", - CKM_DSA_SHA224: "CKM_DSA_SHA224", - CKM_DSA_SHA256: "CKM_DSA_SHA256", - CKM_DSA_PARAMETER_GEN: "CKM_DSA_PARAMETER_GEN", - CKM_ECDSA_KEY_PAIR_GEN: "CKM_ECDSA_KEY_PAIR_GEN", - CKM_ECDSA: "CKM_ECDSA", - CKM_ECDSA_SHA1: "CKM_ECDSA_SHA1", - CKM_ECDSA_SHA224: "CKM_ECDSA_SHA224", - CKM_ECDSA_SHA256: "CKM_ECDSA_SHA256", - CKM_ECDSA_SHA384: "CKM_ECDSA_SHA384", - CKM_ECDSA_SHA512: "CKM_ECDSA_SHA512", - CKM_ECDH1_DERIVE: "CKM_ECDH1_DERIVE", - CKM_ECDH1_COFACTOR_DERIVE: "CKM_ECDH1_DERIVE", - CKM_SHA_1_HMAC: "CKM_SHA_1_HMAC", - CKM_SHA224_HMAC: "CKM_SHA224_HMAC", - CKM_SHA256_HMAC: "CKM_SHA256_HMAC", - CKM_SHA384_HMAC: "CKM_SHA384_HMAC", - CKM_SHA512_HMAC: "CKM_SHA512_HMAC", - CKM_GENERIC_SECRET_KEY_GEN: "CKM_GENERIC_SECRET_KEY_GEN", - CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", - CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} - -def get_default_key_template(mechanism): - ''' - Gets a default template for the given key gen mechanism, returns a deep copy - ''' - return copy.deepcopy(KEY_GENERATOR_TEMPLATES[mechanism]) - -def get_default_key_pair_template(mechanism): - ''' - Gets the default template for the given key pair gen mechanism, returns a deep copy - ''' - pub, priv = KEY_PAIR_GENERATOR_TEMPLATES[mechanism] - return copy.deepcopy(pub), copy.deepcopy(priv) - - +""" +File containing a number of templates taken from CKDemo and manually converted into python format. +See the attributes.py file for methods to convert them into the proper C format. +""" + +from defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ + CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ + CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ + CKK_DES2, CKK_DES3, CKK_CAST3, CKK_GENERIC_SECRET, CKA_MODIFIABLE, \ + CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ + CKA_VALUE_BITS, CKK_CAST5, CKK_RC2, CKK_RC4, CKK_RC5, CKA_ECDSA_PARAMS, CKK_AES, \ + CKK_SEED, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, CKK_ARIA, CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ + CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ + CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, CKM_ARIA_KEY_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN, \ + CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN, \ + CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, \ + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, \ + CKM_SHA1_RSA_PKCS, CKM_SHA224_RSA_PKCS, \ + CKM_SHA256_RSA_PKCS, CKM_SHA384_RSA_PKCS, CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS_PSS, \ + CKM_SHA1_RSA_PKCS_PSS, CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, \ + CKM_SHA384_RSA_PKCS_PSS, CKM_SHA512_RSA_PKCS_PSS, CKM_RSA_X9_31_KEY_PAIR_GEN, \ + CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31, CKM_SHA224_RSA_X9_31, CKM_SHA256_RSA_X9_31, \ + CKM_SHA384_RSA_X9_31, CKM_SHA512_RSA_X9_31, CKM_RSA_PKCS_OAEP, CKM_DSA_KEY_PAIR_GEN, \ + CKM_DSA, CKM_DSA_SHA1, CKM_DSA_SHA224, CKM_DSA_SHA256, CKM_DSA_PARAMETER_GEN, \ + CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, CKM_ECDSA_SHA256, \ + CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, \ + CKM_SHA_1_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, \ + CKM_ECDSA +from pycryptoki.defines import CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE, CKC_X_509, \ + CKA_SUBJECT, CKA_VALUE, CKO_DATA, CKA_TOKEN +import copy + +CKM_DES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 8, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES Key"} + +CKM_DES_UNWRAP_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_SIGN : True, + CKA_WRAP : True, + CKA_DERIVE : True, + CKA_LABEL : "DES Key"} + + +CKM_DES2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES2, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES2 Key"} +CKM_DES3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES3, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 24, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES3 Key"} + +CKM_CAST3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_CAST3, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 8, #1-8 + CKA_EXTRACTABLE :True, + CKA_LABEL : "CAST3 Key"} + +CKM_GENERIC_SECRET_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_GENERIC_SECRET, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "GENERIC SECRET Key"} + +CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_MODIFIABLE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT : 3, #byte + CKA_LABEL : "RSA Public Key"} +CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_MODIFIABLE : True, + CKA_EXTRACTABLE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_LABEL : "RSA Private Key"} + +dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, + 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, 0x6d, 0x1f, 0xf2, + 0x70, 0xf1, 0x59, 0x78, 0x5d, 0x75, 0x69, 0x21, 0xdb, 0xff, 0x97, 0x73, 0xae, 0x08, 0x48, 0x3b, + 0x66, 0x2f, 0xc0, 0x7d, 0xf7, 0x51, 0x2f, 0xf6, 0x8b, 0x2e, 0x55, 0x65, 0xfd, 0x79, 0x82, 0xe2, + 0x0c, 0x24, 0x48, 0x32, 0xab, 0xa1, 0x21, 0xcc, 0x07, 0x99, 0xcc, 0x09, 0xf2, 0xd5, 0x41, 0x4d, + 0x5f, 0x39, 0x66, 0x21, 0x13, 0x65, 0xf5, 0x1b, 0x83, 0xe9, 0xff, 0xcc, 0xcb, 0x3d, 0x88, 0xcd, + 0xf2, 0x38, 0xf7, 0xc2, 0x73, 0x91, 0x31, 0xca, 0x7a, 0xad, 0xff, 0x66, 0x2f, 0xec, 0x1f, 0xb0, + 0xe1, 0xd3, 0x11, 0xa4, 0x04, 0x26, 0x03, 0x76, 0xfd, 0x01, 0x1f, 0xe0, 0x0d, 0x02, 0x04, 0xc3] +dsa_sub_prime_1024_160 = [0xd3, 0x80, 0x73, 0x53, 0xb5, 0x1c, 0x5f, 0x71, 0xb2, 0x2a, 0xc3, 0xd0, 0xc7, 0xe3, 0x94, 0x14, + 0x8f, 0xce, 0xdc, 0x61] +dsa_base_1024_160 = [0x42, 0xe3, 0x77, 0x8e, 0x6e, 0xc3, 0x1b, 0x0d, 0xb0, 0x7a, 0x6b, 0x37, 0x0d, 0x7f, 0xb6, 0xfb, + 0x4a, 0x0b, 0xca, 0x6d, 0xea, 0xac, 0x37, 0x1f, 0x6a, 0xdb, 0xcb, 0xeb, 0xa3, 0x8d, 0xdf, 0x76, + 0xa4, 0x7c, 0x3c, 0x3d, 0x79, 0x27, 0x6a, 0x0e, 0x57, 0x9c, 0xe4, 0xe3, 0x47, 0x18, 0x0f, 0xd9, + 0xb4, 0xad, 0x46, 0x1d, 0x6c, 0xf0, 0xea, 0xc5, 0x1f, 0xb0, 0x8c, 0xf4, 0x52, 0xf6, 0x24, 0x57, + 0x00, 0x51, 0xe5, 0x18, 0xa7, 0x5a, 0x5b, 0xb9, 0xc3, 0x57, 0x8a, 0x14, 0xfd, 0x4f, 0x27, 0xf7, + 0x95, 0xb2, 0x2a, 0xce, 0xa6, 0x2b, 0x1f, 0xdf, 0x10, 0x32, 0xc1, 0x26, 0x6d, 0xa0, 0x81, 0xc7, + 0xfb, 0x99, 0xc4, 0x26, 0x66, 0x26, 0x58, 0x70, 0x93, 0xfd, 0x38, 0x16, 0x17, 0x23, 0x8e, 0xe1, + 0x57, 0x8f, 0xc3, 0x25, 0x54, 0x8d, 0xc1, 0xc0, 0x8e, 0x5f, 0x93, 0x22, 0xc3, 0xb1, 0x20, 0x5e] + +dsa_prime_2048_224 = [0xa2, 0x15, 0xdc, 0xa3, 0xf7, 0x87, 0x34, 0x2c, 0x91, 0x90, 0x87, 0x83, 0x70, 0x79, 0x73, 0x38, + 0x9f, 0x3e, 0x02, 0xf2, 0xc9, 0x68, 0xfe, 0x67, 0xca, 0xb9, 0x4f, 0x5d, 0x6f, 0x92, 0x8c, 0xe8, + 0x6c, 0x8d, 0x62, 0x25, 0x37, 0x4c, 0xa1, 0xbf, 0x7f, 0x27, 0x77, 0x44, 0x8c, 0xc7, 0xc0, 0xc5, + 0xed, 0x66, 0xd1, 0x20, 0x11, 0x7f, 0xec, 0x10, 0xed, 0x81, 0x55, 0x51, 0x45, 0x36, 0xe1, 0xaa, + 0x31, 0x6b, 0x8d, 0xd4, 0x58, 0x27, 0xa0, 0xf0, 0x0e, 0x5d, 0x91, 0x8c, 0x0f, 0xdd, 0x21, 0x8a, + 0xcd, 0x6c, 0x26, 0x3c, 0x1c, 0x2e, 0x55, 0xf6, 0xd0, 0xa7, 0x0f, 0x1b, 0xc9, 0x7f, 0x4b, 0xb0, + 0x4f, 0xff, 0xee, 0x4b, 0x78, 0xb4, 0xdf, 0x34, 0x90, 0xad, 0x98, 0xab, 0xad, 0x0a, 0x4b, 0xfe, + 0x1d, 0xaf, 0xaf, 0x6c, 0x09, 0xdd, 0xda, 0xdf, 0xb8, 0x88, 0x96, 0x94, 0x51, 0x3b, 0x86, 0x5c, + 0x07, 0xa4, 0xf5, 0xf9, 0x27, 0xbe, 0x72, 0x39, 0xe8, 0xd7, 0x67, 0x14, 0xe0, 0x3b, 0x7b, 0xfa, + 0xfb, 0x92, 0x94, 0x00, 0x0f, 0xbb, 0x3f, 0x7a, 0x75, 0x0b, 0x39, 0xca, 0x50, 0x63, 0x0e, 0xe7, + 0xd0, 0xbc, 0x45, 0xa9, 0xc9, 0x87, 0xae, 0x38, 0xae, 0x03, 0x7a, 0x11, 0xb1, 0xd1, 0x3d, 0xf5, + 0x51, 0x76, 0xd9, 0xd8, 0xab, 0x9e, 0xc0, 0xa4, 0x1b, 0x78, 0xa6, 0x36, 0x9e, 0xb5, 0x19, 0x88, + 0xfe, 0x9f, 0xbd, 0x97, 0xa1, 0x0d, 0x48, 0xe2, 0xeb, 0x21, 0x8e, 0xc6, 0x92, 0xb3, 0x1c, 0xfc, + 0xc9, 0x58, 0x3c, 0x7a, 0x41, 0x1d, 0x7d, 0xfa, 0x0a, 0xb3, 0x15, 0xfb, 0x0c, 0x75, 0xe2, 0x10, + 0x9e, 0xb1, 0xe2, 0xee, 0x75, 0xf4, 0x1d, 0x0a, 0x01, 0x65, 0x46, 0xda, 0x70, 0xa6, 0x31, 0xac, + 0x77, 0x8a, 0x2a, 0xe3, 0x25, 0x1f, 0x11, 0x39, 0xe5, 0x74, 0xe2, 0x6d, 0x2c, 0xc6, 0x5c, 0x47] +dsa_sub_prime_2048_224 = [0xd3, 0x76, 0x83, 0x74, 0x55, 0x3d, 0x49, 0x17, 0x19, 0x92, 0x74, 0xba, 0x05, 0x63, 0xbe, 0xff, + 0xa2, 0xa4, 0x5f, 0x05, 0xae, 0x83, 0xdf, 0x9b, 0x34, 0x81, 0x55, 0xbf] +dsa_base_2048_224 = [0x4e, 0x1f, 0x73, 0x4e, 0x08, 0x92, 0xd0, 0x4d, 0x80, 0x89, 0x93, 0xe6, 0x3d, 0xad, 0xef, 0xb3, + 0xfa, 0xa2, 0x48, 0x4c, 0x88, 0x83, 0x8d, 0x38, 0xd8, 0xea, 0x64, 0xca, 0x28, 0xd6, 0xc0, 0x89, + 0xbe, 0x4b, 0x88, 0x14, 0x66, 0x83, 0xec, 0xbd, 0x8b, 0x8d, 0xc6, 0xfb, 0x17, 0x81, 0xca, 0x1d, + 0x83, 0xf3, 0x7f, 0x38, 0xd2, 0x36, 0x03, 0x2b, 0x17, 0x51, 0x16, 0x6a, 0xe4, 0x3f, 0x22, 0xb5, + 0x2d, 0xd6, 0x03, 0x40, 0x1e, 0x89, 0xfe, 0xf6, 0xc9, 0xd0, 0x21, 0x5f, 0x49, 0xa2, 0xcf, 0x97, + 0x33, 0x7b, 0xe2, 0x61, 0x28, 0x8f, 0xd9, 0xac, 0xfb, 0xb6, 0xc2, 0xc0, 0xc5, 0xea, 0x70, 0x9d, + 0x14, 0x76, 0x02, 0x74, 0x41, 0x75, 0x4c, 0xcd, 0x71, 0x00, 0x79, 0x05, 0x52, 0x55, 0x97, 0xd7, + 0xae, 0xc7, 0x71, 0xeb, 0x01, 0x2b, 0x0b, 0xfc, 0xd3, 0x4f, 0x87, 0x16, 0xc7, 0xcc, 0xb1, 0x91, + 0x3d, 0x4f, 0xa6, 0x10, 0x50, 0x4b, 0x67, 0x79, 0x01, 0xdb, 0x37, 0x80, 0x01, 0x9a, 0xa6, 0x92, + 0x23, 0xfb, 0xcd, 0x94, 0x33, 0x6f, 0x2b, 0xf0, 0x2b, 0x44, 0x09, 0x39, 0x39, 0xcc, 0x0d, 0x96, + 0x11, 0xe8, 0xf5, 0xc6, 0x28, 0x50, 0x2e, 0x2b, 0x81, 0x08, 0x3f, 0xc1, 0x28, 0x2f, 0x65, 0x2e, + 0x16, 0x48, 0xc4, 0xe2, 0xb0, 0x29, 0x54, 0x99, 0x19, 0xc5, 0x78, 0xbf, 0x3b, 0xf3, 0x84, 0x70, + 0xc7, 0x8b, 0x5a, 0xcb, 0x10, 0x55, 0xfe, 0x4b, 0x71, 0xef, 0xf5, 0xdb, 0x85, 0xa6, 0xf5, 0xe8, + 0x00, 0xf5, 0xc2, 0xb4, 0xa6, 0x48, 0x39, 0x83, 0x6e, 0xd1, 0xb0, 0xad, 0xea, 0x2d, 0x7e, 0x2e, + 0x22, 0x98, 0xaa, 0x10, 0x7f, 0xa0, 0xec, 0x23, 0x70, 0x87, 0xf5, 0xda, 0x6b, 0x5e, 0x0d, 0x8b, + 0x46, 0xc8, 0x88, 0x61, 0xc3, 0xc1, 0xf5, 0xdb, 0x02, 0x2a, 0x62, 0x7a, 0xd5, 0x95, 0xe5, 0xe2] + +dsa_prime_2048_256 = [ 0xad, 0x78, 0xd1, 0x93, 0x08, 0x76, 0x4f, 0x04, 0xeb, 0x6a, 0xa3, 0x82, 0x09, 0x38, 0x0f, 0xf6, + 0xc9, 0x87, 0x5e, 0x27, 0xb2, 0x7c, 0xc1, 0x4b, 0x78, 0x29, 0xbe, 0x2e, 0xcd, 0xae, 0x26, 0x88, + 0xf4, 0x5d, 0xe8, 0x09, 0xd1, 0x16, 0x06, 0x61, 0xd4, 0x81, 0x65, 0x00, 0x5d, 0x76, 0x7e, 0xf1, + 0x24, 0x73, 0x01, 0x8f, 0x92, 0xd4, 0x07, 0xe7, 0xf3, 0xf7, 0x3a, 0xb9, 0x8b, 0x8e, 0xc8, 0xf4, + 0x13, 0x2b, 0x52, 0xb8, 0x2a, 0x08, 0x57, 0xbc, 0x15, 0xe5, 0x8e, 0x2a, 0x16, 0xda, 0x5e, 0xff, + 0xd2, 0x4e, 0xc7, 0x24, 0xa9, 0x70, 0x74, 0xd2, 0xb4, 0xc1, 0xc0, 0xec, 0x81, 0xcb, 0x83, 0xe9, + 0x29, 0x2a, 0xfd, 0x3b, 0xb9, 0x83, 0xec, 0x23, 0xd1, 0xf9, 0x13, 0xec, 0x1a, 0x68, 0x3f, 0x44, + 0x9b, 0x85, 0x7a, 0x5e, 0x6a, 0x38, 0x91, 0xe0, 0xc6, 0xc8, 0x15, 0x23, 0xf3, 0x98, 0xf7, 0x29, + 0x7f, 0x7b, 0x07, 0x14, 0x3f, 0x6f, 0xfa, 0x11, 0x71, 0x65, 0xff, 0xd9, 0xdc, 0x71, 0x23, 0xd3, + 0x40, 0xec, 0x3b, 0x5f, 0x47, 0x9c, 0x4d, 0x53, 0x4c, 0x4f, 0x61, 0x31, 0xae, 0xda, 0x2e, 0xb6, + 0xd3, 0xd2, 0x01, 0x2c, 0x63, 0x9b, 0xaa, 0x61, 0x79, 0x13, 0xe9, 0xcc, 0xef, 0x57, 0xb1, 0x7a, + 0xd1, 0xd2, 0xe3, 0xfd, 0x92, 0x29, 0x43, 0x4a, 0xc4, 0x50, 0x8c, 0x36, 0xe8, 0xa5, 0xca, 0x9a, + 0xf6, 0x43, 0x3e, 0x75, 0x32, 0x16, 0x8b, 0xe8, 0x98, 0x9c, 0x60, 0x00, 0x83, 0xb6, 0xf4, 0xc9, + 0xa2, 0x36, 0xe8, 0xf6, 0xe3, 0x8a, 0x68, 0x64, 0x61, 0x1d, 0x7b, 0xe2, 0x3c, 0xf2, 0x48, 0x77, + 0x7d, 0xe5, 0xd1, 0xd0, 0x7a, 0x8d, 0x34, 0xdd, 0x1c, 0xc2, 0xbe, 0x99, 0xa4, 0xda, 0xbf, 0xd1, + 0x30, 0x4b, 0xc1, 0xc9, 0x73, 0xc1, 0x07, 0x78, 0x04, 0x0f, 0xdd, 0x7f, 0xa2, 0xfa, 0xc1, 0x0f] +dsa_sub_prime_2048_256 = [ 0xac, 0x66, 0x19, 0x0a, 0x7f, 0x8d, 0x6b, 0x5f, 0xc3, 0x77, 0x06, 0x35, 0x58, 0x2f, 0x9b, 0xc1, + 0x4a, 0x56, 0x91, 0x55, 0xf9, 0x79, 0x3b, 0x79, 0x8e, 0x2e, 0xdb, 0xfc, 0x69, 0x4e, 0x6a, 0xfd] +dsa_base_2048_256 = [0xa6, 0x37, 0x45, 0x31, 0xe5, 0x54, 0x8a, 0x58, 0xa6, 0xd0, 0x20, 0x33, 0xdf, 0x60, 0xbf, 0xf8, + 0xa3, 0x5c, 0xa4, 0x1b, 0x37, 0xe4, 0xc9, 0xea, 0xb0, 0xf2, 0x53, 0x22, 0x19, 0x60, 0xaa, 0x6f, + 0xb2, 0x6b, 0xad, 0x24, 0x04, 0xad, 0x38, 0x57, 0x70, 0x3c, 0x4e, 0x71, 0x6e, 0x35, 0x0d, 0x4b, + 0xcc, 0xbc, 0x4d, 0xad, 0xd9, 0x1d, 0x30, 0x5e, 0xc4, 0x3a, 0x62, 0xfe, 0x2e, 0x82, 0x52, 0xcb, + 0x97, 0x37, 0xb6, 0x0a, 0xf4, 0xc5, 0x5d, 0xf7, 0xfa, 0xe4, 0x95, 0x18, 0xeb, 0x0d, 0x1b, 0xcc, + 0x0e, 0xda, 0x06, 0x50, 0x28, 0xa5, 0x1a, 0x87, 0x51, 0x21, 0xcd, 0xd5, 0xea, 0x60, 0xa1, 0x39, + 0x39, 0x82, 0x33, 0xa5, 0xd1, 0x9b, 0x0d, 0xb3, 0x5c, 0xc3, 0xeb, 0x7d, 0xa3, 0x23, 0xa8, 0xf3, + 0xb2, 0x95, 0xd3, 0x5c, 0x31, 0xb6, 0xaa, 0x55, 0xd4, 0x22, 0xaa, 0xb5, 0x5f, 0x47, 0x0f, 0xd2, + 0x79, 0xa3, 0xd3, 0x55, 0xb2, 0xa5, 0xd7, 0x5b, 0xd0, 0x37, 0x1d, 0x92, 0x58, 0xf6, 0xda, 0x07, + 0x48, 0x9e, 0x02, 0x9d, 0xfb, 0xd6, 0x71, 0x10, 0x7e, 0x0b, 0x2c, 0x94, 0xff, 0xc3, 0xdc, 0xa7, + 0x40, 0x4b, 0x81, 0x34, 0x19, 0xdb, 0x55, 0xc3, 0x46, 0xf8, 0xc3, 0x4d, 0xe7, 0x8a, 0x0d, 0x1c, + 0x69, 0xd2, 0x6f, 0x91, 0xb2, 0xd3, 0xcf, 0xc5, 0x20, 0xfe, 0x0a, 0xc0, 0x6d, 0x95, 0x5b, 0xd2, + 0x50, 0xa6, 0xb8, 0x6f, 0xe1, 0x32, 0xc0, 0x57, 0x13, 0x0b, 0x26, 0xd8, 0x22, 0x9d, 0xe3, 0xad, + 0x06, 0x79, 0xb4, 0xfc, 0xf5, 0x00, 0xb5, 0x5c, 0x76, 0x5d, 0xf9, 0x86, 0xb6, 0x69, 0x4f, 0x6c, + 0x02, 0x2d, 0x92, 0x7d, 0x9c, 0x48, 0x58, 0x7b, 0x17, 0x95, 0x7c, 0xe3, 0x97, 0x4d, 0x93, 0x7a, + 0x4c, 0x26, 0xc1, 0xa1, 0xe0, 0x6c, 0xbb, 0xc3, 0x01, 0x70, 0x9f, 0x14, 0x29, 0x3f, 0xe0, 0x5e] + +dsa_prime_3072_256 = [0xa0, 0x38, 0x3e, 0xe6, 0x92, 0xf8, 0xf5, 0xba, 0xdd, 0xf9, 0x31, 0x7b, 0x16, 0xed, 0xd2, 0x84, + 0xa3, 0x63, 0x19, 0xb0, 0x53, 0xf7, 0x3a, 0xd4, 0x31, 0xae, 0x4b, 0x5d, 0xb2, 0xc6, 0x63, 0x0b, + 0x5a, 0xbf, 0xe8, 0xc5, 0xcb, 0x9d, 0x23, 0x06, 0x50, 0xdc, 0x72, 0xee, 0xfb, 0xe6, 0xf2, 0x61, + 0xdb, 0x2f, 0x43, 0xe6, 0x83, 0x81, 0x58, 0x8c, 0xfd, 0x4a, 0x74, 0x51, 0xbb, 0xbb, 0x30, 0xc5, + 0x95, 0x21, 0xd7, 0x8e, 0xa7, 0x6d, 0xc0, 0x70, 0xcf, 0x81, 0x78, 0x33, 0x19, 0x9f, 0xf7, 0x15, + 0xcb, 0xd1, 0x12, 0xa2, 0x58, 0x50, 0x69, 0x35, 0x44, 0x66, 0x2e, 0x12, 0xbb, 0x27, 0x93, 0xa8, + 0x14, 0x84, 0x77, 0x64, 0xac, 0x27, 0x7c, 0x5c, 0xf0, 0x6b, 0x3e, 0x04, 0x4a, 0x45, 0x91, 0x3e, + 0xdd, 0x61, 0x92, 0x29, 0xdd, 0xd7, 0x28, 0x93, 0x14, 0xd0, 0x0b, 0xb6, 0xa7, 0xda, 0xf1, 0x7e, + 0xb8, 0x63, 0xf3, 0x1d, 0xc2, 0x2c, 0xcc, 0x05, 0xf6, 0x14, 0xc1, 0xbb, 0x0c, 0xea, 0x4c, 0x45, + 0x4f, 0xc6, 0xa0, 0x29, 0xc0, 0xd2, 0x56, 0x8d, 0x1c, 0x5e, 0xef, 0x7f, 0x7c, 0x41, 0xf1, 0xb6, + 0x59, 0xce, 0xd9, 0x24, 0xdd, 0x0e, 0xab, 0xc7, 0xc9, 0xbc, 0x3a, 0x55, 0x90, 0xd4, 0x03, 0x12, + 0xe3, 0xec, 0x13, 0xa2, 0xca, 0xa1, 0x80, 0xed, 0x6b, 0x0c, 0x7d, 0x54, 0xd1, 0x63, 0xca, 0x1f, + 0x32, 0xcd, 0x89, 0x27, 0xa0, 0xfd, 0x39, 0x4e, 0x51, 0xde, 0xf2, 0xa3, 0x1e, 0x83, 0xfc, 0x53, + 0x73, 0xbe, 0xf8, 0xd2, 0x5f, 0x65, 0x32, 0xef, 0x51, 0x5f, 0x86, 0x7b, 0x0b, 0x31, 0x73, 0x8f, + 0xf2, 0x7f, 0xac, 0xad, 0x0d, 0xfb, 0x40, 0xe7, 0x6b, 0x68, 0x3a, 0x3b, 0x11, 0xc9, 0x9f, 0x59, + 0xc8, 0xa4, 0x98, 0xba, 0x2b, 0x88, 0x08, 0x70, 0x0f, 0x20, 0x15, 0x14, 0x5c, 0x77, 0xdb, 0xa4, + 0x20, 0xc5, 0xf0, 0xdb, 0x95, 0xac, 0x88, 0x03, 0x6a, 0x40, 0x90, 0x4a, 0x53, 0xb3, 0x80, 0xaa, + 0x0c, 0x75, 0x80, 0x5a, 0x0d, 0xfd, 0xad, 0x4c, 0xbe, 0xaa, 0x48, 0x91, 0xab, 0xd8, 0x4d, 0x24, + 0xbb, 0x64, 0x4d, 0x96, 0xc5, 0x9f, 0x33, 0x9e, 0x01, 0x6b, 0xb4, 0x32, 0x1f, 0xf4, 0xee, 0x33, + 0xe4, 0x03, 0xce, 0xa0, 0xde, 0x9e, 0xd9, 0x59, 0xcc, 0x6c, 0x1b, 0xba, 0x2c, 0x7d, 0xc7, 0x44, + 0xde, 0x7a, 0x22, 0x5f, 0x65, 0xfb, 0x0a, 0x78, 0xee, 0x57, 0xba, 0x7d, 0x2a, 0x92, 0xf2, 0x47, + 0x50, 0xda, 0xa6, 0x8c, 0x8a, 0x6a, 0x83, 0x06, 0xc3, 0x5c, 0x49, 0x0d, 0x2d, 0x2f, 0x58, 0x92, + 0xbe, 0x12, 0x41, 0x86, 0x0a, 0xd5, 0x45, 0x3b, 0x1b, 0xe3, 0x2b, 0x0e, 0xc7, 0x29, 0x98, 0x3e, + 0x3c, 0x97, 0xd3, 0x28, 0x73, 0xfc, 0x82, 0xc7, 0xb4, 0xf4, 0x6b, 0xfd, 0xa5, 0x14, 0x9e, 0x8f] +dsa_sub_prime_3072_256 = [0xf3, 0x96, 0x52, 0xd0, 0x0e, 0xf7, 0x96, 0x2d, 0xae, 0x7d, 0x8a, 0x13, 0xa8, 0x09, 0xa8, 0x14, + 0xc5, 0xe4, 0xf9, 0xba, 0x8e, 0x6d, 0xea, 0x3d, 0x18, 0xf3, 0x51, 0x48, 0x04, 0xfc, 0xe1, 0x37] +dsa_base_3072_256 = [ 0x07, 0x1f, 0x94, 0x97, 0xf8, 0x58, 0x85, 0x5e, 0xa6, 0x1f, 0xa8, 0x05, 0x97, 0x34, 0xc0, 0x12, + 0x2a, 0xc9, 0x1c, 0xb9, 0xf8, 0x1d, 0xfd, 0x8f, 0xa6, 0xec, 0xc0, 0x83, 0xf6, 0x0c, 0xb3, 0x0e, + 0xa8, 0x0b, 0x15, 0x56, 0xe5, 0xc3, 0x90, 0xd0, 0x06, 0x73, 0x24, 0x68, 0x28, 0xd4, 0xbc, 0xed, + 0xa1, 0x84, 0x89, 0x15, 0xab, 0x86, 0xff, 0x24, 0x56, 0x8e, 0x40, 0x02, 0x03, 0x99, 0xbd, 0xb9, + 0xf6, 0x75, 0x12, 0x59, 0x51, 0xad, 0x1e, 0x57, 0x1d, 0xd4, 0xf2, 0x23, 0x46, 0x14, 0x89, 0xab, + 0x65, 0x45, 0x04, 0x40, 0xe2, 0x2b, 0x01, 0xb8, 0xf5, 0x9b, 0x9b, 0x38, 0x69, 0x2f, 0x12, 0x0b, + 0x98, 0x34, 0xdd, 0x28, 0xeb, 0x9f, 0xf0, 0x8a, 0xfc, 0x44, 0x98, 0xe1, 0x72, 0xeb, 0x3d, 0x54, + 0xb2, 0x8a, 0x8e, 0xb1, 0x00, 0xab, 0x50, 0xa5, 0x66, 0x7b, 0x9a, 0x9e, 0x8a, 0xad, 0x3f, 0x68, + 0xf1, 0xde, 0xb1, 0x04, 0x60, 0x4a, 0x3d, 0x2e, 0x0f, 0x25, 0x0a, 0x9c, 0x18, 0x8b, 0x74, 0x61, + 0xec, 0xd7, 0xde, 0xc6, 0x56, 0xb5, 0x77, 0xe8, 0x46, 0x7e, 0x46, 0x4e, 0x11, 0xac, 0x49, 0x44, + 0x97, 0x88, 0x65, 0xcd, 0xf5, 0x63, 0xaa, 0xb6, 0xa2, 0xe6, 0x8a, 0x29, 0x53, 0x95, 0x2b, 0x0a, + 0x68, 0xe8, 0x81, 0x48, 0x6e, 0x76, 0x34, 0xd4, 0x91, 0x8d, 0xf9, 0x70, 0xa7, 0xce, 0x0d, 0x60, + 0x8a, 0x92, 0x70, 0x8e, 0x49, 0x52, 0x12, 0xfd, 0x4b, 0x26, 0x79, 0x0d, 0x5c, 0x07, 0xdd, 0x5a, + 0xb5, 0x5a, 0xe8, 0x20, 0x9b, 0x63, 0x19, 0x05, 0x55, 0xc0, 0x43, 0xb7, 0x80, 0x2f, 0xae, 0x78, + 0x79, 0x7e, 0x4f, 0x63, 0xf1, 0xcb, 0x18, 0x09, 0xaf, 0x4a, 0xfc, 0x60, 0xb2, 0xb4, 0xaf, 0x78, + 0xba, 0xb3, 0xad, 0x9c, 0xcc, 0x39, 0x10, 0x08, 0x96, 0x43, 0x8e, 0x67, 0x91, 0xae, 0xec, 0x90, + 0xe8, 0x99, 0xf9, 0x76, 0x59, 0x45, 0x4f, 0x4c, 0x75, 0x96, 0x33, 0xb0, 0xd8, 0x57, 0xb5, 0x05, + 0x12, 0x45, 0x15, 0xc7, 0x5e, 0x3a, 0x64, 0x90, 0xe7, 0x16, 0x8c, 0x73, 0xfa, 0x15, 0x68, 0xe8, + 0xc9, 0x04, 0xb0, 0x42, 0x49, 0xfa, 0x31, 0xa8, 0x3c, 0x6d, 0x83, 0x8a, 0xf7, 0xd4, 0x2d, 0x48, + 0x71, 0x09, 0x89, 0xf9, 0xfb, 0xc9, 0xc3, 0x7b, 0x2c, 0x87, 0x91, 0x57, 0xc9, 0xe9, 0x81, 0x8e, + 0xa4, 0xdd, 0xb7, 0x7a, 0x1f, 0xbc, 0x66, 0x3e, 0xd8, 0x2d, 0xe8, 0x38, 0xc3, 0xab, 0x3b, 0x82, + 0xc5, 0x7d, 0xd0, 0xff, 0xbf, 0xa4, 0x95, 0xe6, 0xea, 0xd3, 0x3e, 0x44, 0x05, 0xd0, 0x58, 0xe9, + 0xb3, 0x7b, 0x3a, 0x71, 0xce, 0xbd, 0xe4, 0x2f, 0x4d, 0x33, 0x46, 0xb4, 0xc5, 0xf9, 0xd6, 0x49, + 0x8b, 0x73, 0xbc, 0x1b, 0x9f, 0x0d, 0x3d, 0x0c, 0x49, 0x29, 0x42, 0x99, 0x70, 0xe9, 0xc5, 0xeb] + +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_1024_160, + CKA_SUBPRIME : dsa_sub_prime_1024_160, + CKA_BASE : dsa_base_1024_160, + CKA_LABEL : "DSA 1024_160 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_2048_224, + CKA_SUBPRIME : dsa_sub_prime_2048_224, + CKA_BASE : dsa_base_2048_224, + CKA_LABEL : "DSA 2048_224 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_2048_256, + CKA_SUBPRIME : dsa_sub_prime_2048_256, + CKA_BASE : dsa_base_2048_256, + CKA_LABEL : "DSA 2048_256 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_3072_256, + CKA_SUBPRIME : dsa_sub_prime_3072_256, + CKA_BASE : dsa_base_3072_256, + CKA_LABEL : "DSA 3072_256 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "DSA Public Key"} + +dh_prime = [0xF4, 0x88, 0xFD, 0x58, 0x4E, 0x49, 0xDB, 0xCD, 0x20, 0xB4, 0x9D, 0xE4, 0x91, 0x07, 0x36, 0x6B, + 0x33, 0x6C, 0x38, 0x0D, 0x45, 0x1D, 0x0F, 0x7C, 0x88, 0xB3, 0x1C, 0x7C, 0x5B, 0x2D, 0x8E, 0xF6, + 0xF3, 0xC9, 0x23, 0xC0, 0x43, 0xF0, 0xA5, 0x5B, 0x18, 0x8D, 0x8E, 0xBB, 0x55, 0x8C, 0xB8, 0x5D, + 0x38, 0xD3, 0x34, 0xFD, 0x7C, 0x17, 0x57, 0x43, 0xA3, 0x1D, 0x18, 0x6C, 0xDE, 0x33, 0x21, 0x2C, + 0xB5, 0x2A, 0xFF, 0x3C, 0xE1, 0xB1, 0x29, 0x40, 0x18, 0x11, 0x8D, 0x7C, 0x84, 0xA7, 0x0A, 0x72, + 0xD6, 0x86, 0xC4, 0x03, 0x19, 0xC8, 0x07, 0x29, 0x7A, 0xCA, 0x95, 0x0C, 0xD9, 0x96, 0x9F, 0xAB, + 0xD0, 0x0A, 0x50, 0x9B, 0x02, 0x46, 0xD3, 0x08, 0x3D, 0x66, 0xA4, 0x5D, 0x41, 0x9F, 0x9C, 0x7C, + 0xBD, 0x89, 0x4B, 0x22, 0x19, 0x26, 0xBA, 0xAB, 0xA2, 0x5E, 0xC3, 0x55, 0xE9, 0x2F, 0x78, 0xC7] +dh_prime_2048= [0xF1, 0x20, 0xB5, 0x5B, 0x3A, 0xE4, 0xD0, 0xF6, 0xEF, 0xA4, 0xF2, 0x9F, 0xC4, 0xDF, 0x86, 0x84, + 0x57, 0x54, 0x14, 0x90, 0x98, 0xBD, 0x3E, 0x57, 0x86, 0xE8, 0xC9, 0xA0, 0x30, 0xAF, 0xE6, 0xA7, + 0x6D, 0x7E, 0x4F, 0xDA, 0x20, 0x87, 0x46, 0x0C, 0xED, 0x88, 0xDC, 0xDB, 0x95, 0xDE, 0xD3, 0x4F, + 0xC7, 0x18, 0x80, 0x3A, 0x0D, 0xD2, 0xF1, 0x54, 0x5C, 0xD2, 0x29, 0x78, 0x3C, 0xE4, 0x40, 0x0C, + 0x1A, 0x6B, 0x36, 0x73, 0x42, 0xE1, 0xB3, 0xD3, 0xEB, 0x95, 0xDB, 0x7A, 0x06, 0xD6, 0x54, 0x11, + 0xDB, 0x0B, 0xB3, 0x00, 0x52, 0xA5, 0x74, 0x77, 0x5B, 0x47, 0x2A, 0x6E, 0x31, 0xCB, 0x8A, 0x5D, + 0x1C, 0x8A, 0x7D, 0x93, 0x7A, 0xC3, 0x62, 0x44, 0xC3, 0x29, 0x40, 0x6D, 0x3E, 0x47, 0x62, 0x2F, + 0x93, 0xCD, 0xF3, 0xED, 0xA6, 0x1E, 0x1D, 0x57, 0x4E, 0xFF, 0x5F, 0x46, 0x92, 0xCC, 0xFC, 0x7E, + 0x98, 0x8C, 0xE8, 0xB0, 0xAA, 0x33, 0x70, 0x96, 0x3D, 0xC1, 0x5B, 0x10, 0x2A, 0x07, 0x34, 0x84, + 0x4E, 0xCD, 0xEB, 0xD7, 0x15, 0x63, 0x8C, 0xC4, 0x67, 0xB0, 0xC1, 0xB9, 0xB8, 0x45, 0xB0, 0x3B, + 0x3A, 0x76, 0x83, 0x2C, 0xF5, 0x28, 0xB3, 0xF7, 0x10, 0x23, 0x7E, 0xAA, 0xF6, 0xE6, 0x8B, 0xE7, + 0x57, 0x35, 0x1F, 0x51, 0x34, 0x58, 0x5E, 0x0C, 0x2D, 0x36, 0xCF, 0xA3, 0x85, 0x34, 0xB0, 0x14, + 0x7D, 0xD0, 0x8C, 0x34, 0xBB, 0xC1, 0x8D, 0x49, 0x8C, 0xDA, 0x41, 0x48, 0x66, 0xDB, 0x41, 0xE1, + 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, + 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, + 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] +CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_DERIVE : True, + CKA_PRIME : dh_prime, + CKA_BASE : [0x02], + CKA_LABEL : "DH Public Key"} +CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS : len(dh_prime) * 8, #long + CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DERIVE : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "DH Private Key"} + +CKM_CAST5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_CAST5, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, # 1-16 + CKA_EXTRACTABLE :True, + CKA_LABEL : "CAST5 Key"} + +CKM_RC2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_RC2, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 64, #1-128 + CKA_EXTRACTABLE :True, + CKA_LABEL : "RC2 Key"} + +CKM_RC4_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_RC4, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 256, #1-256 + CKA_EXTRACTABLE :True, + CKA_LABEL : "RC4 Key"} + +CKM_RC5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_RC5, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 255, #1-255 + CKA_EXTRACTABLE :True, + CKA_LABEL : "RC5 Key"} + +CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP = {CKA_TOKEN : True, + CKA_DERIVE : True, + CKA_ENCRYPT : 0x1001, #TODO, is encrypt both a long and a boolean, uh oh + CKA_LABEL : "SSL3 Pre Master Key"} + + +''' +Curve dictionary for ECDSA with oids as lists, taken from Components/tools/common/CommonData.cpp +''' +curve_list = { + 'secp112r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x06], # [0] OID_secp112r1 + 'secp112r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x07], # [7] OID_secp112r2 + 'secp128r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1C], # [14] OID_secp128r1 + 'secp128r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1D], # [21] OID_secp128r2 + 'secp160k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x09], # [28] OID_secp160k1 + 'secp160r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x08], # [35] OID_secp160r1 + 'secp160r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1E], # [42] OID_secp160r2 + 'secp192k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1F], # [49] OID_secp192k1 + 'secp224k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x20], # [56] OID_secp224k1 + 'secp224r1(P-224)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x21], # [63] OID_secp224r1 + 'secp256k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], # [70] OID_secp256k1 + 'secp384r1(P-384)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], # [77] OID_secp384r1 + 'secp521r1(P-521)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], # [84] OID_secp521r1 + + 'X9_62_prime192v1(P-192)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01], # [91] OID_X9_62_prime192v1 + 'X9_62_prime192v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], # [101] OID_X9_62_prime192v2 + 'X9_62_prime192v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], # [111] OID_X9_62_prime192v3 + 'X9_62_prime239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], # [121] OID_X9_62_prime239v1 + 'X9_62_prime239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], # [131] OID_X9_62_prime239v2 + 'X9_62_prime239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], # [141] OID_X9_62_prime239v3 + 'X9_62_prime256v1(P-256)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], # [151] OID_X9_62_prime256v1 + + 'sect113r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x04], # [161] OID_sect113r1 + 'sect113r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x05], # [168] OID_sect113r2 + 'sect131r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x16], # [175] OID_sect131r1 + 'sect131r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x17], # [182] OID_sect131r2 + 'sect163k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x01], # [189] OID_sect163k1 + 'sect163r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x02], # [196] OID_sect163r1 + 'sect163r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0F], # [203] OID_sect163r2 + 'sect193r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x18], # [210] OID_sect193r1 + 'sect193r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x19], # [217] OID_sect193r2 + 'sect233k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1A], # [224] OID_sect233k1 + 'sect233r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1B], # [231] OID_sect233r1 + 'sect239k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x03], # [238] OID_sect239k1 + 'sect283k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x10], # [245] OID_sect283k1 + 'sect283r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x11], # [252] OID_sect283r1 + 'sect409k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x24], # [259] OID_sect409k1 + 'sect409r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x25], # [266] OID_sect409r1 + 'sect571k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x26], # [273] OID_sect571k1 + 'sect571r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x27], # [280] OID_sect571r1 + + 'X9_62_c2pnb163v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], # [287] OID_X9_62_c2pnb163v1 + 'X9_62_c2pnb163v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], # [297] OID_X9_62_c2pnb163v2 + 'X9_62_c2pnb163v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], # [307] OID_X9_62_c2pnb163v3 + 'X9_62_c2pnb176v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], # [317] OID_X9_62_c2pnb176v1 + 'X9_62_c2tnb191v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], # [327] OID_X9_62_c2tnb191v1 + 'X9_62_c2tnb191v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], # [337] OID_X9_62_c2tnb191v2 + 'X9_62_c2tnb191v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], # [347] OID_X9_62_c2tnb191v3 + 'X9_62_c2pnb208w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], # [357] OID_X9_62_c2pnb208w1 + 'X9_62_c2tnb239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], # [367] OID_X9_62_c2tnb239v1 + 'X9_62_c2tnb239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], # [377] OID_X9_62_c2tnb239v2 + 'X9_62_c2tnb239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], # [387] OID_X9_62_c2tnb239v3 + 'X9_62_c2pnb272w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], # [397] OID_X9_62_c2pnb272w1 + 'X9_62_c2pnb304w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], # [407] OID_X9_62_c2pnb304w1 + 'X9_62_c2tnb359v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], # [417] OID_X9_62_c2tnb359v1 + 'X9_62_c2pnb368w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], # [427] OID_X9_62_c2pnb368w1 + 'X9_62_c2tnb431r1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], # [437] OID_X9_62_c2tnb431r1 + + 'brainpoolP160r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], # [447] brainpoolP160r1 + 'brainpoolP160t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], # [458] brainpoolP160t1 + 'brainpoolP192r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], # [469] brainpoolP192r1 + 'brainpoolP192t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], # [480] brainpoolP192t1 + 'brainpoolP224r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], # [491] brainpoolP224r1 + 'brainpoolP224t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], # [502] brainpoolP224t1 + 'brainpoolP256r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], # [513] brainpoolP256r1 + 'brainpoolP256t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], # [524] brainpoolP256t1 + 'brainpoolP320r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], # [535] brainpoolP320r1 + 'brainpoolP320t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], # [546] brainpoolP320t1 + 'brainpoolP384r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], # [557] brainpoolP384r1 + 'brainpoolP384t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], # [568] brainpoolP384t1 + 'brainpoolP512r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], # [579] brainpoolP512r1 + 'brainpoolP512t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], # [590] brainpoolP512t1 + 'microsoftPlayReadP160' : [0x30, 0x81, 0x95, 0x02, 0x01, 0x01, 0x30, 0x20, + 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, + 0x01, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x27, 0x18, 0x28, 0x18, + 0x31, 0x41, 0x59, 0x26, 0x14, 0x14, 0x24, 0xf7, + 0x30, 0x2c, 0x04, 0x14, 0x37, 0xa5, 0xab, 0xcc, + 0xd2, 0x77, 0xbc, 0xe8, 0x76, 0x32, 0xff, 0x3d, + 0x47, 0x80, 0xc0, 0x09, 0xeb, 0xe4, 0x14, 0x97, + 0x04, 0x14, 0x0d, 0xd8, 0xda, 0xbf, 0x72, 0x5e, + 0x2f, 0x32, 0x28, 0xe8, 0x5f, 0x1a, 0xd7, 0x8f, + 0xde, 0xdf, 0x93, 0x28, 0x23, 0x9e, 0x04, 0x29, + 0x04, 0x87, 0x23, 0x94, 0x7f, 0xd6, 0xa3, 0xa1, + 0xe5, 0x35, 0x10, 0xc0, 0x7d, 0xba, 0x38, 0xda, + 0xf0, 0x10, 0x9f, 0xa1, 0x20, 0x44, 0x57, 0x44, + 0x91, 0x10, 0x75, 0x52, 0x2d, 0x8c, 0x3c, 0x58, + 0x56, 0xd4, 0xed, 0x7a, 0xcd, 0xa3, 0x79, 0x93, + 0x6f, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x27, 0x16, 0xb2, 0x6e, + 0xec, 0x14, 0x90, 0x44, 0x28, 0xc2, 0xa6, 0x75] + } + +CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_DERIVE : True, + CKA_ECDSA_PARAMS : curve_list['secp112r1'], + CKA_LABEL : "ECDSA Public Key"} +CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_DERIVE : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "ECDSA Private Key"} + +CKM_AES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_AES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 24, #16, 24, 32 + CKA_EXTRACTABLE :True, + CKA_LABEL : "AES Key"} + +CKM_SEED_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_SEED, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "SEED Key"} + +kcdsa_prime_1024_160 = [0xdc, 0x02, 0xf3, 0xe0, 0x51, 0x4e, 0xf4, 0x72, 0x36, 0x51, 0x09, 0x72, 0x5c, 0x12, 0x00, 0x50, + 0x69, 0x7d, 0xfc, 0x1d, 0xcb, 0xb4, 0x1f, 0xbc, 0x49, 0x63, 0xc4, 0x15, 0x45, 0x97, 0xb7, 0xae, + 0x8d, 0x4a, 0x35, 0x3c, 0xe2, 0xfb, 0x1f, 0xbf, 0x77, 0x7b, 0x89, 0xe5, 0x56, 0xc5, 0x15, 0x6b, + 0x1a, 0x4a, 0x82, 0xcc, 0xe2, 0xb8, 0xec, 0x4d, 0x61, 0x86, 0xd4, 0xa3, 0xf6, 0xc5, 0x65, 0xae, + 0x8c, 0xf6, 0x04, 0x62, 0x1d, 0x63, 0xec, 0x9f, 0x1e, 0x91, 0x31, 0x39, 0x1d, 0xc0, 0x55, 0xbc, + 0xac, 0xc5, 0x1a, 0xc8, 0x5c, 0x02, 0x93, 0xd7, 0xca, 0x74, 0x4f, 0xe9, 0xa2, 0x04, 0x5c, 0x3c, + 0xc1, 0xb6, 0xe1, 0x4d, 0xcd, 0xfa, 0xbb, 0x7d, 0xf8, 0xa7, 0xb1, 0x94, 0xd5, 0x08, 0xe1, 0x99, + 0xc1, 0x81, 0x62, 0x93, 0xd6, 0x8c, 0x7a, 0x5c, 0x0f, 0x8a, 0xc7, 0x14, 0xb5, 0xd6, 0xf5, 0xa3] +kcdsa_sub_prime_1024_160 = [0xc8, 0xf6, 0x2e, 0x10, 0xf0, 0xa4, 0xe5, 0x43, 0x1b, 0x8e, 0x1b, 0x0f, 0x53, 0xf6, 0x27, 0xec, + 0x6a, 0xd3, 0xa6, 0xa5] +kcdsa_base_1024_160 = [0x9b, 0x8b, 0x4b, 0x16, 0x53, 0x65, 0x03, 0x18, 0x47, 0x19, 0xac, 0x4d, 0x13, 0x2d, 0x14, 0x57, + 0x2d, 0xca, 0x56, 0x45, 0x3f, 0x05, 0x68, 0x68, 0x3b, 0x04, 0x17, 0x27, 0x6f, 0x93, 0x88, 0xdc, + 0x0a, 0x79, 0xe7, 0x76, 0x45, 0x4a, 0x97, 0x7a, 0x02, 0xc0, 0x1a, 0xc7, 0x7a, 0x07, 0x1f, 0x6b, + 0x99, 0x81, 0x67, 0xb8, 0xb9, 0x89, 0xce, 0xfd, 0x88, 0x7a, 0x26, 0x71, 0xf9, 0x44, 0x12, 0xcc, + 0x94, 0xac, 0x62, 0xe7, 0x61, 0xc9, 0x5a, 0xdb, 0x38, 0xf7, 0x8b, 0x76, 0x73, 0xcc, 0x09, 0x0a, + 0x62, 0xcf, 0xab, 0x4b, 0x03, 0x29, 0x0d, 0x34, 0x92, 0xb9, 0x09, 0x83, 0x68, 0x9b, 0x30, 0x82, + 0x1f, 0xcf, 0xb0, 0xdb, 0x83, 0x71, 0x24, 0x2c, 0x73, 0xf3, 0xa6, 0x4f, 0x56, 0xb2, 0x13, 0xfd, + 0xdb, 0xbc, 0xcf, 0x77, 0x5d, 0x01, 0x1f, 0xb8, 0x35, 0x85, 0x4f, 0x88, 0xb0, 0x58, 0x92, 0x07] +kcdsa_prime_2048_256 = [0xec, 0xfe, 0xa3, 0x3f, 0xa2, 0x27, 0xc3, 0xb1, 0xa7, 0xdf, 0xd7, 0xf1, 0xbb, 0x48, 0x7c, 0xd4, + 0x26, 0xab, 0x0a, 0x2b, 0x2b, 0x3a, 0xf1, 0x8f, 0xef, 0x9d, 0x61, 0xcd, 0x4f, 0x7b, 0xbb, 0x8d, + 0x7d, 0x8d, 0x4c, 0x84, 0x13, 0x7a, 0xaf, 0xe5, 0xb5, 0xba, 0x9d, 0xe4, 0xd2, 0xb5, 0x8b, 0x00, + 0x39, 0xbc, 0x66, 0x9c, 0x7c, 0x3d, 0x98, 0x7e, 0x0a, 0x74, 0x1b, 0x06, 0xcf, 0x97, 0xb5, 0x3e, + 0xcb, 0x1e, 0x1d, 0x22, 0x51, 0xe6, 0xd4, 0xe2, 0x72, 0xa7, 0x72, 0xd3, 0x4c, 0x3f, 0xfc, 0xd4, + 0xd5, 0x7c, 0x3f, 0x44, 0xa2, 0x1b, 0xfc, 0x97, 0xad, 0x34, 0xb2, 0x8f, 0xd3, 0xcf, 0x77, 0x89, + 0x7a, 0xce, 0x64, 0xc6, 0x92, 0xaa, 0x69, 0x13, 0xed, 0x22, 0xa2, 0x3b, 0x45, 0x19, 0x98, 0x88, + 0x29, 0x05, 0x7c, 0xd2, 0x33, 0xaf, 0xa1, 0xf7, 0xab, 0x66, 0x40, 0xca, 0x05, 0x7e, 0x16, 0x99, + 0x7a, 0x92, 0xaa, 0x5e, 0x07, 0xc0, 0xc7, 0x3c, 0x82, 0xb4, 0x96, 0x02, 0x23, 0x66, 0x99, 0x97, + 0xa3, 0x40, 0xf1, 0x36, 0x9b, 0x33, 0xc7, 0xbe, 0xe9, 0xac, 0xce, 0x85, 0xf8, 0xbd, 0x6a, 0x26, + 0x0f, 0x79, 0xe7, 0x9e, 0xee, 0xee, 0xd6, 0x82, 0xc8, 0x7d, 0x4b, 0xe7, 0x4c, 0x2f, 0x44, 0x9a, + 0x1b, 0x68, 0x3f, 0xba, 0xe4, 0xfd, 0x19, 0xca, 0xd0, 0x97, 0xd3, 0x71, 0x12, 0x8c, 0x86, 0xbe, + 0x93, 0x84, 0xb7, 0x35, 0x2a, 0xd1, 0x3a, 0x9a, 0x27, 0x8f, 0x36, 0x4f, 0x08, 0x9e, 0x38, 0xdf, + 0x25, 0xe8, 0x4a, 0x70, 0x4d, 0xe4, 0xfb, 0x16, 0x40, 0xa5, 0x19, 0xfc, 0x62, 0x91, 0x76, 0x1d, + 0xab, 0x11, 0xe2, 0xf7, 0x80, 0xe7, 0x1a, 0x62, 0x2e, 0x9a, 0xbf, 0x85, 0xfe, 0x19, 0x4a, 0x45, + 0x79, 0x3b, 0xfa, 0xb3, 0xa1, 0xe9, 0x8a, 0x1d, 0xfd, 0x57, 0xb5, 0xc7, 0x09, 0x79, 0xb8, 0x1b] +kcdsa_sub_prime_2048_256 = [0xe5, 0x7d, 0x48, 0xd4, 0x44, 0x3d, 0x60, 0xb2, 0x6f, 0x48, 0x82, 0x3d, 0x1d, 0xea, 0xce, 0xf2, + 0xb4, 0x4a, 0x6c, 0x47, 0x5b, 0x12, 0x43, 0x47, 0xb4, 0x81, 0x47, 0xf8, 0xa2, 0xfd, 0x33, 0xd3] +kcdsa_base_2048_256 = [0x68, 0x90, 0xea, 0x6f, 0x5a, 0x56, 0x4f, 0xd2, 0xa1, 0xfe, 0x07, 0xd7, 0xbc, 0xa5, 0xab, 0x80, + 0xf9, 0x5a, 0x5f, 0x47, 0xe9, 0x7f, 0xfc, 0x9a, 0xea, 0x67, 0x13, 0xf8, 0xad, 0x36, 0xe1, 0xfc, + 0x02, 0x42, 0x17, 0xcd, 0xf9, 0xbe, 0x5c, 0xe9, 0xa6, 0xcd, 0xdb, 0x6b, 0x5c, 0x1e, 0x7e, 0x22, + 0x0e, 0xd5, 0x7f, 0x2b, 0x0c, 0x9b, 0xf7, 0xe2, 0xd5, 0x23, 0xc1, 0x45, 0x0b, 0x46, 0x7e, 0x64, + 0x80, 0xc9, 0x6f, 0x9b, 0x20, 0x76, 0xd0, 0x3f, 0xae, 0x8c, 0x4d, 0x99, 0x3e, 0x9c, 0xe6, 0x6b, + 0xc9, 0xb8, 0x39, 0xa5, 0x58, 0x15, 0x6c, 0x69, 0x79, 0x2a, 0xfa, 0x34, 0x76, 0x17, 0x64, 0x6a, + 0x2a, 0x29, 0x4d, 0xce, 0xe4, 0x07, 0x78, 0xa3, 0xcb, 0x93, 0x7a, 0x78, 0x2a, 0x51, 0x91, 0xbd, + 0x42, 0x97, 0x3b, 0x07, 0x31, 0xca, 0x4f, 0x62, 0x2a, 0x63, 0xe0, 0x69, 0x45, 0x31, 0xc8, 0x75, + 0x3e, 0x3a, 0xb0, 0xe8, 0x8d, 0xdc, 0x86, 0x1c, 0x75, 0x1c, 0x25, 0x2e, 0x74, 0x18, 0x89, 0xb3, + 0x3e, 0x39, 0x0e, 0x1c, 0xa5, 0xc4, 0x75, 0x1f, 0x31, 0x1e, 0x19, 0x61, 0x5b, 0xbe, 0xa7, 0x18, + 0x9b, 0x04, 0xf2, 0x29, 0xc8, 0xe7, 0x40, 0x84, 0x39, 0xd2, 0x28, 0xa5, 0x30, 0x5b, 0x22, 0x78, + 0x33, 0xab, 0xa8, 0x30, 0x98, 0x1c, 0x33, 0xec, 0xfe, 0xe7, 0x90, 0x8c, 0x6d, 0x39, 0x54, 0x42, + 0x9b, 0xef, 0x30, 0xde, 0xa1, 0x15, 0xfe, 0xe6, 0xd0, 0x3f, 0x13, 0xf0, 0xa0, 0x2e, 0xb2, 0x19, + 0xe4, 0xb9, 0xb0, 0xba, 0xac, 0x32, 0xc2, 0x24, 0x0b, 0x2a, 0x47, 0x17, 0xda, 0x7c, 0x11, 0x6c, + 0xe2, 0x09, 0x24, 0x71, 0x30, 0xac, 0x14, 0x0c, 0xd3, 0xab, 0xdc, 0xe7, 0x78, 0xa4, 0x27, 0x27, + 0xf3, 0x2c, 0xfa, 0xfd, 0xae, 0x9e, 0x51, 0x68, 0x47, 0xb2, 0x6c, 0xe4, 0xcb, 0xb7, 0x66, 0x03] +CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, #1024_160 or 2048_256 + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : kcdsa_prime_1024_160, + CKA_SUBPRIME : kcdsa_sub_prime_1024_160, + CKA_BASE : kcdsa_base_1024_160, + CKA_LABEL : "KCDSA Public Key"} +CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, #1024_160 or 2048_256 + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : kcdsa_prime_2048_256, + CKA_SUBPRIME : kcdsa_sub_prime_2048_256, + CKA_BASE : kcdsa_base_2048_256, + CKA_LABEL : "KCDSA Public Key"} +CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "KCDSA Private Key"} + +CKM_DSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_PRIME_BITS : 1024, # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 + CKA_SUBPRIME_BITS : 160, #0-512 + CKA_LABEL : "DSA Parameter Key"} + +CKM_KCDSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, #primelength 0-4096, subprimelength 0-512 + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_PRIME_BITS : 2048, #0-4096 + CKA_SUBPRIME_BITS : 256, #0-512 + CKA_LABEL : "KCDSA Parameter Key"} + +CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_MODIFIABLE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_MODULUS_BITS : 1024, #long 1-MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT : 3, #byte + CKA_LABEL : "RSA Public Key"} +CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_MODIFIABLE : True, + CKA_EXTRACTABLE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_LABEL : "RSA Private Key"} + +dhX9_42Prime = [0xE0, 0x01, 0xE8, 0x96, 0x7D, 0xB4, 0x93, 0x53, 0xE1, 0x6F, 0x8E, 0x89, 0x22, 0x0C, 0xCE, 0xFC, + 0x5C, 0x5F, 0x12, 0xE3, 0xDF, 0xF8, 0xF1, 0xD1, 0x49, 0x90, 0x12, 0xE6, 0xEF, 0x53, 0xE3, 0x1F, + 0x02, 0xEA, 0xCC, 0x5A, 0xDD, 0xF3, 0x37, 0x89, 0x35, 0xC9, 0x5B, 0x21, 0xEA, 0x3D, 0x6F, 0x1C, + 0xD7, 0xCE, 0x63, 0x75, 0x52, 0xEC, 0x38, 0x6C, 0x0E, 0x34, 0xF7, 0x36, 0xAD, 0x95, 0x17, 0xEF, + 0xFE, 0x5E, 0x4D, 0xA7, 0xA8, 0x6A, 0xF9, 0x0E, 0x2C, 0x22, 0x8F, 0xE4, 0xB9, 0xE6, 0xD8, 0xF8, + 0xF0, 0x2D, 0x20, 0xAF, 0x78, 0xAB, 0xB6, 0x92, 0xAC, 0xBC, 0x4B, 0x23, 0xFA, 0xF2, 0xC5, 0xCC, + 0xD4, 0x9A, 0x0C, 0x9A, 0x8B, 0xCD, 0x91, 0xAC, 0x0C, 0x55, 0x92, 0x01, 0xE6, 0xC2, 0xFD, 0x1F, + 0x47, 0xC2, 0xCB, 0x2A, 0x88, 0xA8, 0x3C, 0x21, 0x0F, 0xC0, 0x54, 0xDB, 0x29, 0x2D, 0xBC, 0x45] +dhX9_42Base = [0x86, 0x47, 0x17, 0xA3, 0x9E, 0x6A, 0xEA, 0x7E, 0x87, 0xC4, 0x32, 0xEE, 0x77, 0x43, 0x15, 0x16, + 0x96, 0x70, 0xC4, 0x99] +dhX9_42SubPrime = [0x1C, 0xE0, 0xF6, 0x69, 0x26, 0x46, 0x11, 0x97, 0xEF, 0x45, 0xC4, 0x65, 0x8B, 0x83, 0xB8, 0xAB, + 0x04, 0xA9, 0x22, 0x42, 0x68, 0x50, 0x4D, 0x05, 0xB8, 0x19, 0x83, 0x99, 0xDD, 0x71, 0x37, 0x18, + 0xCC, 0x1F, 0x24, 0x5D, 0x47, 0x6C, 0xCF, 0x61, 0xA2, 0xF9, 0x34, 0x93, 0xF4, 0x1F, 0x55, 0x52, + 0x48, 0x65, 0x57, 0xE6, 0xD4, 0xCA, 0xA8, 0x00, 0xD6, 0xD0, 0xDB, 0x3C, 0xBF, 0x5A, 0x95, 0x4B, + 0x20, 0x8A, 0x4E, 0xBA, 0xF7, 0xE6, 0x49, 0xFB, 0x61, 0x24, 0xD8, 0xA2, 0x1E, 0xF2, 0xF2, 0x2B, + 0xAA, 0xAE, 0x29, 0x21, 0x10, 0x19, 0x10, 0x51, 0x46, 0x47, 0x31, 0xB6, 0xCC, 0x3C, 0x93, 0xDC, + 0x6E, 0x80, 0xBA, 0x16, 0x0B, 0x66, 0x64, 0xA5, 0x6C, 0xFA, 0x96, 0xEA, 0xF1, 0xB2, 0x83, 0x39, + 0x8E, 0xB4, 0x61, 0x64, 0xE5, 0xE9, 0x43, 0x84, 0xEE, 0x02, 0x24, 0xE7, 0x1F, 0x03, 0x7C, 0x23] +CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE: True, + CKA_SENSITIVE : True, + CKA_DERIVE : True, + CKA_PRIME : dhX9_42Prime, + CKA_BASE : dhX9_42Base, + CKA_SUBPRIME : dhX9_42SubPrime, + CKA_LABEL : "DH X9.42 Public Key"} +CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DERIVE : True, + CKA_EXTRACTABLE : True, + CKA_LABEL : "DH X9.42 Private Key"} + +CKM_ARIA_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_ARIA, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 24, #16, 24, 32 + CKA_EXTRACTABLE :True, + CKA_LABEL : "ARIA Key"} + +CKM_DH_PKCS_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_PRIME_BITS : 512, #between 512 and 2048 in 256bit increments (&0xff) + CKA_LABEL : "SH PKCS Parameter Key"} + +''' +The simple certificate object taken from CKDemo when +you select the Create Object option and choose certificate +''' +CERTIFICATE_TEMPLATE = { CKA_CLASS: CKO_CERTIFICATE, + CKA_CERTIFICATE_TYPE : CKC_X_509, + CKA_TOKEN : True, + CKA_LABEL : "Created certificate object", + CKA_SUBJECT : "", + CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} + +''' +The simple data object template taken from CKDemo when you select +the Create Object option and choose data +''' +DATA_TEMPLATE = { CKA_CLASS : CKO_DATA, + CKA_TOKEN : True, + CKA_LABEL : "Created data object", + CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} + +KEY_GENERATOR_TEMPLATES = {CKM_DES_KEY_GEN : CKM_DES_KEY_GEN_TEMP, + CKM_DES2_KEY_GEN : CKM_DES2_KEY_GEN_TEMP, + CKM_DES3_KEY_GEN: CKM_DES3_KEY_GEN_TEMP, + CKM_CAST3_KEY_GEN: CKM_CAST3_KEY_GEN_TEMP, + CKM_GENERIC_SECRET_KEY_GEN: CKM_GENERIC_SECRET_KEY_GEN_TEMP, + CKM_CAST5_KEY_GEN: CKM_CAST5_KEY_GEN_TEMP, + CKM_RC2_KEY_GEN: CKM_RC2_KEY_GEN_TEMP, + CKM_RC4_KEY_GEN: CKM_RC4_KEY_GEN_TEMP, + CKM_RC5_KEY_GEN: CKM_RC5_KEY_GEN_TEMP, + CKM_AES_KEY_GEN: CKM_AES_KEY_GEN_TEMP, + CKM_SEED_KEY_GEN: CKM_SEED_KEY_GEN_TEMP, + CKM_ARIA_KEY_GEN: CKM_ARIA_KEY_GEN_TEMP, + CKM_DH_PKCS_PARAMETER_GEN: CKM_DH_PKCS_PARAMETER_GEN_TEMP} + +KEY_PAIR_GENERATOR_TEMPLATES = { #Note lacks multiple sizes of the same kinds of keys + CKM_RSA_PKCS_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), #pkcs template is good for x9.31 + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_DSA_KEY_PAIR_GEN : (CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_DH_PKCS_KEY_PAIR_GEN : (CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_ECDSA_KEY_PAIR_GEN : (CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_KCDSA_KEY_PAIR_GEN : (CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP)} + +''' +This list is not complete +''' +MECHANISM_LOOKUP = {CKM_RSA_PKCS_KEY_PAIR_GEN: "CKM_RSA_PKCS_KEY_PAIR_GEN", + CKM_RSA_PKCS: "CKM_RSA_PKCS", + CKM_SHA1_RSA_PKCS: "CKM_SHA1_RSA_PKCS", + CKM_SHA224_RSA_PKCS: "CKM_SHA224_RSA_PKCS", + CKM_SHA256_RSA_PKCS: "CKM_SHA256_RSA_PKCS", + CKM_SHA384_RSA_PKCS: "CKM_SHA384_RSA_PKCS", + CKM_SHA512_RSA_PKCS: "CKM_SHA512_RSA_PKCS", + CKM_RSA_PKCS_PSS: "CKM_RSA_PKCS_PSS", + CKM_SHA1_RSA_PKCS_PSS: "CKM_SHA1_RSA_PKCS_PSS", + CKM_SHA224_RSA_PKCS_PSS: "CKM_SHA224_RSA_PKCS_PSS", + CKM_SHA256_RSA_PKCS_PSS: "CKM_SHA256_RSA_PKCS_PSS", + CKM_SHA384_RSA_PKCS_PSS: "CKM_SHA384_RSA_PKCS_PSS", + CKM_SHA512_RSA_PKCS_PSS: "CKM_SHA512_RSA_PKCS_PSS", + CKM_RSA_X9_31_KEY_PAIR_GEN: "CKM_RSA_X9_31_KEY_PAIR_GEN", + CKM_RSA_X9_31: "CKM_RSA_X9_31", + CKM_SHA1_RSA_X9_31: "CKM_SHA1_RSA_X9_31", + CKM_SHA224_RSA_X9_31: "CKM_SHA224_RSA_X9_31", + CKM_SHA256_RSA_X9_31: "CKM_SHA256_RSA_X9_31", + CKM_SHA384_RSA_X9_31: "CKM_SHA384_RSA_X9_31", + CKM_SHA512_RSA_X9_31: "CKM_SHA512_RSA_X9_31", + CKM_RSA_PKCS_OAEP: "CKM_RSA_PKCS_OAEP", + CKM_DSA_KEY_PAIR_GEN: "CKM_DSA_KEY_PAIR_GEN", + CKM_DSA: "CKM_DSA", + CKM_DSA_SHA1: "CKM_DSA_SHA1", + CKM_DSA_SHA224: "CKM_DSA_SHA224", + CKM_DSA_SHA256: "CKM_DSA_SHA256", + CKM_DSA_PARAMETER_GEN: "CKM_DSA_PARAMETER_GEN", + CKM_ECDSA_KEY_PAIR_GEN: "CKM_ECDSA_KEY_PAIR_GEN", + CKM_ECDSA: "CKM_ECDSA", + CKM_ECDSA_SHA1: "CKM_ECDSA_SHA1", + CKM_ECDSA_SHA224: "CKM_ECDSA_SHA224", + CKM_ECDSA_SHA256: "CKM_ECDSA_SHA256", + CKM_ECDSA_SHA384: "CKM_ECDSA_SHA384", + CKM_ECDSA_SHA512: "CKM_ECDSA_SHA512", + CKM_ECDH1_DERIVE: "CKM_ECDH1_DERIVE", + CKM_ECDH1_COFACTOR_DERIVE: "CKM_ECDH1_DERIVE", + CKM_SHA_1_HMAC: "CKM_SHA_1_HMAC", + CKM_SHA224_HMAC: "CKM_SHA224_HMAC", + CKM_SHA256_HMAC: "CKM_SHA256_HMAC", + CKM_SHA384_HMAC: "CKM_SHA384_HMAC", + CKM_SHA512_HMAC: "CKM_SHA512_HMAC", + CKM_GENERIC_SECRET_KEY_GEN: "CKM_GENERIC_SECRET_KEY_GEN", + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} + +def get_default_key_template(mechanism): + ''' + Gets a default template for the given key gen mechanism, returns a deep copy + ''' + return copy.deepcopy(KEY_GENERATOR_TEMPLATES[mechanism]) + +def get_default_key_pair_template(mechanism): + ''' + Gets the default template for the given key pair gen mechanism, returns a deep copy + ''' + pub, priv = KEY_PAIR_GENERATOR_TEMPLATES[mechanism] + return copy.deepcopy(pub), copy.deepcopy(priv) + + diff --git a/pycryptoki/defaults.py b/pycryptoki/defaults.py index 6431db2..457872c 100755 --- a/pycryptoki/defaults.py +++ b/pycryptoki/defaults.py @@ -1,42 +1,42 @@ -''' -A file containing commonly used strings or other data similar to a config file -''' - -#The location of the cryptoki file, if specified as None the environment variable -#ChrystokiConfigurationPath will be used or it will revert to using /etc/Chrystoki.conf -CHRYSTOKI_CONFIG_FILE = None - -#The location of the DLL file, if not specified it will try to look up the file in -#the Chrystoki config file specified be the variable CHRYSTOKI_CONFIG_FILE -CHRYSTOKI_DLL_FILE = None - -ADMIN_PARTITION_LABEL = 'no label' -AUDITOR_LABEL = 'auditorlabel' - -ADMINISTRATOR_USERNAME = 'Administrator' -ADMINISTRATOR_PASSWORD = 'adminpassword' - -AUDITOR_USERNAME = 'Auditor' -AUDITOR_PASSWORD = 'auditorpassword' - -CO_USERNAME = 'Crypto Officer' -CO_PASSWORD = 'copassword' - -DEFAULT_USERNAME = 'default_user' -DEFAULT_LABEL = 'default_label' -DEFAULT_PASSWORD = 'default' - -DEFAULT_UTILS_PATH = '/usr/safenet/lunaclient/sbin' -FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" - -user_credentials = {ADMINISTRATOR_USERNAME : ADMINISTRATOR_PASSWORD, - AUDITOR_USERNAME : AUDITOR_PASSWORD, - CO_USERNAME : CO_PASSWORD, - DEFAULT_USERNAME : DEFAULT_PASSWORD} - -DES3_KEY_SIZE = 120 - -MANUFACTURER_ID = "SafeNet Inc." -MODEL = "Luna K6" - +''' +A file containing commonly used strings or other data similar to a config file +''' + +#The location of the cryptoki file, if specified as None the environment variable +#ChrystokiConfigurationPath will be used or it will revert to using /etc/Chrystoki.conf +CHRYSTOKI_CONFIG_FILE = None + +#The location of the DLL file, if not specified it will try to look up the file in +#the Chrystoki config file specified be the variable CHRYSTOKI_CONFIG_FILE +CHRYSTOKI_DLL_FILE = None + +ADMIN_PARTITION_LABEL = 'no label' +AUDITOR_LABEL = 'auditorlabel' + +ADMINISTRATOR_USERNAME = 'Administrator' +ADMINISTRATOR_PASSWORD = 'adminpassword' + +AUDITOR_USERNAME = 'Auditor' +AUDITOR_PASSWORD = 'auditorpassword' + +CO_USERNAME = 'Crypto Officer' +CO_PASSWORD = 'copassword' + +DEFAULT_USERNAME = 'default_user' +DEFAULT_LABEL = 'default_label' +DEFAULT_PASSWORD = 'default' + +DEFAULT_UTILS_PATH = '/usr/safenet/lunaclient/sbin' +FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + +user_credentials = {ADMINISTRATOR_USERNAME : ADMINISTRATOR_PASSWORD, + AUDITOR_USERNAME : AUDITOR_PASSWORD, + CO_USERNAME : CO_PASSWORD, + DEFAULT_USERNAME : DEFAULT_PASSWORD} + +DES3_KEY_SIZE = 120 + +MANUFACTURER_ID = "SafeNet Inc." +MODEL = "Luna K6" + ADMIN_SLOT = 1 \ No newline at end of file diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py new file mode 100644 index 0000000..27a0ec8 --- /dev/null +++ b/pycryptoki/defines.py @@ -0,0 +1,1807 @@ +''' +THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE +This file should NOT be checked into MKS or modified in any way, this file was +created by setup/initialize.py. Any changes to this file will be wiped out when +it is regenerated. + +This file contains defines which have been automatically scraped from the +cryptoki API header files. The defines are stored as variables in python. +If you add any new defines you can rerun initialize.py to regenerate this file. +If you need to scrape another header file add the desired file to the header_files +array in initialize.py and rerun initialize.py. +''' + +'''/home/new_builds/689/101/interfaces/Include/firmware/luna2if.h''' +LUNA_MAX_UPDATE_DATA_SIZE= (64 * 1024) +LUNA_GEN_KCV_FLAG_NONE= 0x0000 +LUNA_GEN_KCV_FLAG_CONSOLIDATE= 0x0001 +LUNA_MECH_RSA_PKCS_KEY_PAIR_GEN= 0x00000000 +LUNA_MECH_RSA_PKCS= 0x00000001 +LUNA_MECH_RSA_X_509= 0x00000002 +LUNA_MECH_MD5_RSA_PKCS= 0x00000005 +LUNA_MECH_SHA1_RSA_PKCS= 0x00000006 +LUNA_MECH_RSA_PKCS_OAEP= 0x00000009 +LUNA_MECH_RSA_X9_31_KEY_PAIR_GEN= 0x0000000A +LUNA_MECH_RSA_X9_31= 0x0000000B +LUNA_MECH_SHA1_RSA_X9_31= 0x0000000C +LUNA_MECH_RSA_PKCS_PSS= 0x0000000D +LUNA_MECH_SHA1_RSA_PKCS_PSS= 0x0000000E +LUNA_MECH_DSA_KEY_PAIR_GEN= 0x00000010 +LUNA_MECH_DSA= 0x00000011 +LUNA_MECH_SHA1_DSA= 0x00000012 +LUNA_MECH_DH_PKCS_KEY_PAIR_GEN= 0x00000020 +LUNA_MECH_DH_PKCS_DERIVE= 0x00000021 +LUNA_MECH_SHA256_RSA_PKCS= 0x00000040 +LUNA_MECH_SHA384_RSA_PKCS= 0x00000041 +LUNA_MECH_SHA512_RSA_PKCS= 0x00000042 +LUNA_MECH_SHA256_RSA_PKCS_PSS= 0x00000043 +LUNA_MECH_SHA384_RSA_PKCS_PSS= 0x00000044 +LUNA_MECH_SHA512_RSA_PKCS_PSS= 0x00000045 +LUNA_MECH_RC2_KEY_GEN= 0x00000100 +LUNA_MECH_RC2_ECB= 0x00000101 +LUNA_MECH_RC2_CBC= 0x00000102 +LUNA_MECH_RC2_MAC= 0x00000103 +LUNA_MECH_RC2_CBC_PAD= 0x00000105 +LUNA_MECH_RC4_KEY_GEN= 0x00000110 +LUNA_MECH_RC4= 0x00000111 +LUNA_MECH_DES_KEY_GEN= 0x00000120 +LUNA_MECH_DES_ECB= 0x00000121 +LUNA_MECH_DES_CBC= 0x00000122 +LUNA_MECH_DES_MAC= 0x00000123 +LUNA_MECH_DES_CBC_PAD= 0x00000125 +LUNA_MECH_DES2_KEY_GEN= 0x00000130 +LUNA_MECH_DES3_KEY_GEN= 0x00000131 +LUNA_MECH_DES3_ECB= 0x00000132 +LUNA_MECH_DES3_CBC= 0x00000133 +LUNA_MECH_DES3_MAC= 0x00000134 +LUNA_MECH_DES3_CBC_PAD= 0x00000135 +LUNA_MECH_MD2= 0x00000200 +LUNA_MECH_MD5= 0x00000210 +LUNA_MECH_SHA_1= 0x00000220 +LUNA_MECH_SHA256= 0x00000250 +LUNA_MECH_HMAC_SHA256= 0x00000251 +LUNA_MECH_SHA384= 0x00000260 +LUNA_MECH_HMAC_SHA384= 0x00000261 +LUNA_MECH_SHA512= 0x00000270 +LUNA_MECH_HMAC_SHA512= 0x00000271 +LUNA_MECH_SHA256_KEY_DERIVATION= 0x00000393 +LUNA_MECH_SHA384_KEY_DERIVATION= 0x00000394 +LUNA_MECH_SHA512_KEY_DERIVATION= 0x00000395 +LUNA_MECH_PKCS5_PBKD2= 0x000003B0 +LUNA_MECH_KEY_WRAP_SET_OAEP= 0x00000401 +LUNA_MECH_EC_KEY_PAIR_GEN= 0x00001040 +LUNA_MECH_ECDSA= 0x00001041 +LUNA_MECH_SHA1_ECDSA= 0x00001042 +LUNA_MECH_SHA224_ECDSA= 0x00001043 +LUNA_MECH_SHA256_ECDSA= 0x00001044 +LUNA_MECH_SHA384_ECDSA= 0x00001045 +LUNA_MECH_SHA512_ECDSA= 0x00001046 +LUNA_MECH_ECDH1_DERIVE= 0x00001050 +LUNA_MECH_ECDH1_COFACTOR_DERIVE= 0x00001051 +LUNA_MECH_ECMQV_DERIVE= 0x00001052 +LUNA_MECH_AES_KEY_GEN= 0x00001080 +LUNA_MECH_AES_ECB= 0x00001081 +LUNA_MECH_AES_CBC= 0x00001082 +LUNA_MECH_AES_MAC= 0x00001083 +LUNA_MECH_AES_MAC_GENERAL= 0x00001084 +LUNA_MECH_AES_CBC_PAD= 0x00001085 +LUNA_MECH_DES_ECB_ENCRYPT_DATA= 0x00001100 +LUNA_MECH_DES_CBC_ENCRYPT_DATA= 0x00001101 +LUNA_MECH_DES3_ECB_ENCRYPT_DATA= 0x00001102 +LUNA_MECH_DES3_CBC_ENCRYPT_DATA= 0x00001103 +LUNA_MECH_AES_ECB_ENCRYPT_DATA= 0x00001104 +LUNA_MECH_AES_CBC_ENCRYPT_DATA= 0x00001105 +LUNA_MECH_ARIA_KEY_GEN= 0x00001200 +LUNA_MECH_ARIA_ECB= 0x00001201 +LUNA_MECH_ARIA_CBC= 0x00001202 +LUNA_MECH_ARIA_MAC= 0x00001203 +LUNA_MECH_ARIA_MAC_GENERAL= 0x00001204 +LUNA_MECH_ARIA_CBC_PAD= 0x00001205 +LUNA_MECH_ARIA_ECB_ENCRYPT_DATA= 0x00001206 +LUNA_MECH_ARIA_CBC_ENCRYPT_DATA= 0x00001207 +LUNA_MECH_DSA_PARAMETER_GEN= 0x00002000 +LUNA_MECH_DH_PKCS_PARAMETER_GEN= 0x00002001 +LUNA_MECH_X9_42_DH_PARAMETER_GEN= 0x00002002 +LUNA_MECH_CAST_KEY_GEN= 0x00008001 +LUNA_MECH_CAST_ECB= 0x00008002 +LUNA_MECH_CAST_CBC= 0x00008003 +LUNA_MECH_CAST_MAC= 0x00008004 +LUNA_MECH_CAST_CBC_PAD= 0x00008005 +LUNA_MECH_CAST3_KEY_GEN= 0x00008101 +LUNA_MECH_CAST3_ECB= 0x00008102 +LUNA_MECH_CAST3_CBC= 0x00008103 +LUNA_MECH_CAST3_MAC= 0x00008104 +LUNA_MECH_CAST3_CBC_PAD= 0x00008105 +LUNA_MECH_CAST5_KEY_GEN= 0x00008501 +LUNA_MECH_CAST5_ECB= 0x00008502 +LUNA_MECH_CAST5_CBC= 0x00008503 +LUNA_MECH_CAST5_MAC= 0x00008504 +LUNA_MECH_CAST5_CBC_PAD= 0x00008505 +LUNA_MECH_RC5_KEY_GEN= 0x00008600 +LUNA_MECH_RC5_ECB= 0x00008601 +LUNA_MECH_RC5_CBC= 0x00008602 +LUNA_MECH_RC5_MAC= 0x00008603 +LUNA_MECH_RC5_CBC_PAD= 0x00008605 +LUNA_MECH_MD2_DES_CBC= 0x00008201 +LUNA_MECH_MD5_DES_CBC= 0x00008202 +LUNA_MECH_SHA1_DES3_CBC= 0x00008203 +LUNA_MECH_MD5_CAST_CBC= 0x00008204 +LUNA_MECH_MD5_CAST3_CBC= 0x00008205 +LUNA_MECH_SHA1_CAST5_CBC= 0x00008206 +LUNA_MECH_SHA1_DES2_CBC= 0x00008207 +LUNA_MECH_SHA1_RC4_128= 0x00008208 +LUNA_MECH_SHA1_RC4_40= 0x00008209 +LUNA_MECH_SHA1_RC2_128_CBC= 0x0000820A +LUNA_MECH_SHA1_RC2_40_CBC= 0x0000820B +LUNA_MECH_SHA1_DES2_CBC_OLD= 0x0000820C # Added for compatibility with legacy apps +LUNA_MECH_SHA1_DES3_CBC_OLD= 0x0000820D # Added for compatibility with legacy apps +LUNA_MECH_CONCATENATE_BASE_AND_KEY= 0x00008301 # Added for SPKM & SSL Support +LUNA_MECH_CONCATENATE_KEY_AND_BASE= 0x00008302 # Added for SPKM & SSL Support +LUNA_MECH_CONCATENATE_BASE_AND_DATA= 0x00008303 # Added for SPKM & SSL Support +LUNA_MECH_CONCATENATE_DATA_AND_BASE= 0x00008304 # Added for SPKM & SSL Support +LUNA_MECH_XOR_BASE_AND_DATA= 0x00008305 # Added for SPKM & SSL Support +LUNA_MECH_XOR_BASE_AND_KEY= 0x0000860B # Added for F/W Update Support +LUNA_MECH_EXTRACT_KEY_FROM_KEY= 0x00008306 # Added for SPKM & SSL Support +LUNA_MECH_MD2_KEY_DERIVATION= 0x00008307 # Added for SPKM & SSL Support +LUNA_MECH_MD5_KEY_DERIVATION= 0x00008308 # Added for SPKM & SSL Support +LUNA_MECH_SHA1_KEY_DERIVATION= 0x00008309 # Added for SPKM & SSL Support +LUNA_MECH_GENERIC_SECRET_KEY_GEN= 0x0000830A # Added for SPKM & SSL Support +LUNA_MECH_SSL3_MASTER_KEY_DERIVE= 0x0000830B # Added for SSL Support +LUNA_MECH_SSL3_KEY_AND_MAC_DERIVE= 0x0000830C # Added for SSL Support +LUNA_MECH_SSL3_MD5_MAC= 0x0000830D # Added for SSL Support +LUNA_MECH_SSL3_SHA1_MAC= 0x0000830E # Added for SSL Support +LUNA_MECH_HMAC_SHA1= 0x0000830F # Added for SSL Support +LUNA_MECH_HMAC_SHA1_80= 0x00008310 # Added for SSL Support +LUNA_MECH_HMAC_MD5= 0x00008311 # Added for SSL Support +LUNA_MECH_HMAC_MD5_80= 0x00008312 # Added for SSL Support +LUNA_MECH_SSL3_PRE_MASTER_KEY_GEN= 0x00008313 # Added for SSL Support +LUNA_MECH_DES3_CFB8= 0x00008314 +LUNA_MECH_DES3_CFB64= 0x00008315 +LUNA_MECH_DES3_OFB= 0x00008316 +LUNA_MECH_DES3_CTR= 0x00008317 +LUNA_MECH_DES3_GCM= 0x00008318 +LUNA_MECH_AES_CFB8= 0x00008319 +LUNA_MECH_AES_CFB128= 0x0000831a +LUNA_MECH_AES_OFB= 0x0000831b +LUNA_MECH_AES_CTR= 0x0000831c +LUNA_MECH_AES_GCM= 0x0000831d +LUNA_MECH_ARIA_CFB8= 0x0000831e +LUNA_MECH_ARIA_CFB128= 0x0000831f +LUNA_MECH_ARIA_OFB= 0x00008320 +LUNA_MECH_ARIA_CTR= 0x00008321 +LUNA_MECH_ARIA_GCM= 0x00008322 +LUNA_MECH_2DES_DERIVE= 0x000083FF # Added for Gemplus +LUNA_MECH_INDIRECT_LOGIN_REENCRYPT= 0x00008400 # Added for indirect login support. Obsolete as of f/w 5.0 +LUNA_MECH_LZS= 0x00008400 # Added for Compression Support +LUNA_MECH_LOOP_BACK= 0x80000000 +LUNA_MECH_NONE= LUNA_MECH_LOOP_BACK # Added for IPSEC Support +LUNA_MECH_UNKNOWN= 0xFFFFFFFF # Added for error detection +LUNA_MECH_SEED_KEY_GEN= 0x00008701 +LUNA_MECH_SEED_ECB= 0x00008702 +LUNA_MECH_SEED_CBC= 0x00008703 +LUNA_MECH_SEED_CBC_PAD= 0x00008704 +LUNA_MECH_SEED_MAC= 0x00008705 +LUNA_MECH_HAS160= 0x00008706 +LUNA_MECH_KCDSA_KEY_PAIR_GEN= 0x00008707 +LUNA_MECH_HAS160_KCDSA= 0x00008708 +LUNA_MECH_SHA1_KCDSA= 0x00008709 +LUNA_MECH_SHA224_KCDSA= 0x0000870A +LUNA_MECH_SHA256_KCDSA= 0x0000870B +LUNA_MECH_SHA384_KCDSA= 0x0000870C +LUNA_MECH_SHA512_KCDSA= 0x0000870D +LUNA_MECH_HMAC_HAS160= 0x0000870E +LUNA_MECH_KCDSA_PARAMETER_GEN= 0x0000870F +LUNA_MECH_AES_CBC_PAD_EXTRACT= 0x00009000 +LUNA_MECH_AES_CBC_PAD_INSERT= 0x00009001 +LUNA_MECH_AES_CBC_PAD_EXTRACT_FLATTENED= 0x00009002 +LUNA_MECH_AES_CBC_PAD_INSERT_FLATTENED= 0x00009003 +LUNA_MECH_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL= 0x00009004 +LUNA_MECH_AES_CBC_PAD_INSERT_DOMAIN_CTRL= 0x00009005 +LUNA_MASKING_STORAGE_HOST= 0x00000000 +LUNA_MASKING_STORAGE_PED_USB_MEMORY= 0x00000001 +LUNA_MASKING_STORAGE_HSM_USB_MEMORY= 0x00000002 +LUNA_MASKING_FLAG_DELETE_AFTER_EXTRACT=0x1 # Flag "Delete After Extract" */ +LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC= 0x80009000 +LUNA_MECH_AES_CBC_PAD_INSERT_PUBLIC= 0x80009001 +LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC_FLATTENED= 0x80009002 +LUNA_MECH_AES_CBC_PAD_INSERT_PUBLIC_FLATTENED= 0x80009003 +LUNA_MECH_SHA224_RSA_PKCS= 0x80000110 +LUNA_MECH_SHA224_RSA_PKCS_PSS= 0x80000111 +LUNA_MECH_SHA224= 0x80000112 +LUNA_MECH_HMAC_SHA224= 0x80000113 +LUNA_MECH_SHA224_KEY_DERIVATION= 0x80000115 +LUNA_MECH_HMAC_RIPEMD160= 0x80000116 +LUNA_MECH_RIPEMD160= 0x80000117 +LUNA_MECH_SHA224_DSA= 0x80000122 +LUNA_MECH_SHA256_DSA= 0x80000123 +LUNA_MECH_DES3_CMAC= 0x80000126 +LUNA_MECH_ARIA_CMAC= 0x80000127 +LUNA_MECH_AES_CMAC= 0x80000128 +LUNA_MECH_SEED_CMAC= 0x80000129 +LUNA_MECH_DES3_CBC_PAD_IPSEC= 0x80000130 +LUNA_MECH_AES_CBC_PAD_IPSEC= 0x80000131 +LUNA_MECH_XOR_BASE_AND_DATA_W_KDF= 0x80000132 +LUNA_MECH_ARIA_L_ECB= 0x80000133 +LUNA_MECH_ARIA_L_CBC= 0x80000134 +LUNA_MECH_ARIA_L_CBC_PAD= 0x80000135 +LUNA_MECH_ARIA_L_MAC= 0x80000136 +LUNA_MECH_SHA224_RSA_X9_31= 0x80000137 +LUNA_MECH_SHA256_RSA_X9_31= 0x80000138 +LUNA_MECH_SHA384_RSA_X9_31= 0x80000139 +LUNA_MECH_SHA512_RSA_X9_31= 0x8000013a +LUNA_MECH_SHA1_RSA_X9_31_NON_FIPS= 0x8000013b +LUNA_MECH_SHA224_RSA_X9_31_NON_FIPS= 0x8000013c +LUNA_MECH_SHA256_RSA_X9_31_NON_FIPS= 0x8000013d +LUNA_MECH_SHA384_RSA_X9_31_NON_FIPS= 0x8000013e +LUNA_MECH_SHA512_RSA_X9_31_NON_FIPS= 0x8000013f +LUNA_MECH_RSA_X9_31_NON_FIPS= 0x80000140 +LUNA_MECH_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN= 0x80000141 +LUNA_MECH_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN= 0x80000142 +LUNA_MECH_AES_GMAC= 0x80000143 +LUNA_MECH_SEED_CTR= 0x80008144 +LUNA_MECH_ECIES= 0x80000A00 +LUNA_MECH_NIST_PRF_KDF= 0x80000A02 +LUNA_MECH_PRF_KDF= 0x80000A03 +LUNA_MECH_FLAG_HW= 0x00000001 +LUNA_MECH_FLAG_ENCRYPT= 0x00000100 +LUNA_MECH_FLAG_DECRYPT= 0x00000200 +LUNA_MECH_FLAG_DIGEST= 0x00000400 +LUNA_MECH_FLAG_SIGN= 0x00000800 +LUNA_MECH_FLAG_SIGN_RECOVER= 0x00001000 +LUNA_MECH_FLAG_VERIFY= 0x00002000 +LUNA_MECH_FLAG_VERIFY_RECOVER= 0x00004000 +LUNA_MECH_FLAG_GENERATE= 0x00008000 +LUNA_MECH_FLAG_GENERATE_KEY_PAIR= 0x00010000 +LUNA_MECH_FLAG_WRAP= 0x00020000 +LUNA_MECH_FLAG_UNWRAP= 0x00040000 +LUNA_MECH_FLAG_DERIVE= 0x00080000 +LUNA_MECH_FLAG_EC_F_P= 0x00100000 +LUNA_MECH_FLAG_EC_F_2M= 0x00200000 +LUNA_MECH_FLAG_EC_ECPARAMETERS= 0x00400000 +LUNA_MECH_FLAG_EC_NAMEDCURVE= 0x00800000 +LUNA_MECH_FLAG_EC_UNCOMPRESS= 0x01000000 +LUNA_MECH_FLAG_EC_COMPRESS= 0x02000000 +LUNA_MECH_FLAG_EXTENSION= 0x80000000 +LUNA_MGF_MGF1_SHA1= 0x00000001 +LUNA_MGF_MGF1_SHA256= 0x00000002 +LUNA_MGF_MGF1_SHA384= 0x00000003 +LUNA_MGF_MGF1_SHA512= 0x00000004 +LUNA_MGF_MGF1_SHA224= 0x00000005 +LUNA_OAEP_SOURCES_DATA_SPECIFIED= 0x00000001 +LUNA_ATTR_UNKNOWN= 0xFFFFFFFF # Added for error detection */ +LUNA_ATTR_CLASS= 0x00000000 +LUNA_ATTR_TOKEN= 0x00000001 +LUNA_ATTR_PRIVATE= 0x00000002 +LUNA_ATTR_LABEL= 0x00000003 +LUNA_ATTR_APPLICATION= 0x00000010 +LUNA_ATTR_VALUE= 0x00000011 +LUNA_ATTR_CERTIFICATE_TYPE= 0x00000080 +LUNA_ATTR_ISSUER= 0x00000081 +LUNA_ATTR_SERIAL_NUMBER= 0x00000082 +LUNA_ATTR_KEY_TYPE= 0x00000100 +LUNA_ATTR_SUBJECT= 0x00000101 +LUNA_ATTR_ID= 0x00000102 +LUNA_ATTR_SENSITIVE= 0x00000103 +LUNA_ATTR_ENCRYPT= 0x00000104 +LUNA_ATTR_DECRYPT= 0x00000105 +LUNA_ATTR_WRAP= 0x00000106 +LUNA_ATTR_UNWRAP= 0x00000107 +LUNA_ATTR_SIGN= 0x00000108 +LUNA_ATTR_SIGN_RECOVER= 0x00000109 +LUNA_ATTR_VERIFY= 0x0000010A +LUNA_ATTR_VERIFY_RECOVER= 0x0000010B +LUNA_ATTR_DERIVE= 0x0000010C +LUNA_ATTR_START_DATE= 0x00000110 +LUNA_ATTR_END_DATE= 0x00000111 +LUNA_ATTR_MODULUS= 0x00000120 +LUNA_ATTR_MODULUS_BITS= 0x00000121 +LUNA_ATTR_PUBLIC_EXPONENT= 0x00000122 +LUNA_ATTR_PRIVATE_EXPONENT= 0x00000123 +LUNA_ATTR_PRIME_1= 0x00000124 +LUNA_ATTR_PRIME_2= 0x00000125 +LUNA_ATTR_EXPONENT_1= 0x00000126 +LUNA_ATTR_EXPONENT_2= 0x00000127 +LUNA_ATTR_COEFFICIENT= 0x00000128 +LUNA_ATTR_PRIME= 0x00000130 +LUNA_ATTR_SUBPRIME= 0x00000131 +LUNA_ATTR_BASE= 0x00000132 +LUNA_ATTR_PRIME_BITS= 0x00000133 +LUNA_ATTR_SUBPRIME_BITS= 0x00000134 +LUNA_ATTR_VALUE_BITS= 0x00000160 +LUNA_ATTR_VALUE_LEN= 0x00000161 +LUNA_ATTR_EXTRACTABLE= 0x00000162 +LUNA_ATTR_LOCAL= 0x00000163 +LUNA_ATTR_NEVER_EXTRACTABLE= 0x00000164 +LUNA_ATTR_ALWAYS_SENSITIVE= 0x00000165 +LUNA_ATTR_MODIFIABLE= 0x00000170 +LUNA_ATTR_ECDSA_PARAMS= 0x00000180 +LUNA_ATTR_EC_POINT= 0x00000181 +LUNA_ATTR_VENDOR_DEFINED= 0x80000000 +LUNA_ATTR_CCM_PRIVATE= (LUNA_ATTR_VENDOR_DEFINED | 0x00000001) +LUNA_ATTR_FINGERPRINT_SHA1= (LUNA_ATTR_VENDOR_DEFINED | 0x00000002) +LUNA_ATTR_PKC_TCTRUST= (LUNA_ATTR_VENDOR_DEFINED | 0x00000003) +LUNA_ATTR_PKC_CITS= (LUNA_ATTR_VENDOR_DEFINED | 0x00000004) +LUNA_ATTR_OUID= (LUNA_ATTR_VENDOR_DEFINED | 0x00000005) +LUNA_ATTR_X9_31_GENERATED= (LUNA_ATTR_VENDOR_DEFINED | 0x00000006) +LUNA_ATTR_PKC_ECC= (LUNA_ATTR_VENDOR_DEFINED | 0x00000007) +LUNA_ATTR_EKM_UID= (LUNA_ATTR_VENDOR_DEFINED | 0x00000008) +LUNA_ATTR_USAGE_COUNT= (LUNA_ATTR_VENDOR_DEFINED | 0x00000101) +LUNA_ATTR_USAGE_COUNT_LIMIT= (LUNA_ATTR_VENDOR_DEFINED | 0x00000200) +LUNA_ATTR_GENERIC_1= (LUNA_ATTR_VENDOR_DEFINED | 0x00001000) +LUNA_ATTR_GENERIC_2= (LUNA_ATTR_VENDOR_DEFINED | 0x00001001) +LUNA_ATTR_GENERIC_3= (LUNA_ATTR_VENDOR_DEFINED | 0x00001002) +LUNA_ATTR_FINGERPRINT_SHA256= (LUNA_ATTR_VENDOR_DEFINED | 0x00001003) +LUNA_ATTR_UNKNOWN= 0xFFFFFFFF +LUNA_OBJ_DATA= 0x00000000 +LUNA_OBJ_CERTIFICATE= 0x00000001 +LUNA_OBJ_SECRET_KEY= 0x00000002 +LUNA_OBJ_PUBLIC_KEY= 0x00000003 +LUNA_OBJ_PRIVATE_KEY= 0x00000004 +LUNA_OBJ_DOMAIN_PARAMETERS= 0x00000005 +LUNA_OBJ_VENDOR_DEFINED= 0x80000000 +LUNA_OBJ_UNKNOWN= 0xFFFFFFFF # Added for error detection */ +LUNA_KEY_RSA= 0x00000000 +LUNA_KEY_DSA= 0x00000001 +LUNA_KEY_DH= 0x00000002 +LUNA_KEY_GENERIC_SECRET= 0x00000003 +LUNA_KEY_RC2= 0x00000004 +LUNA_KEY_RC4= 0x00000005 +LUNA_KEY_DES= 0x00000006 +LUNA_KEY_DES2= 0x00000007 +LUNA_KEY_DES3= 0x00000008 +LUNA_KEY_CAST= 0x00000009 +LUNA_KEY_CAST3= 0x0000000A +LUNA_CERT_X_509= 0x0000000B +LUNA_KEY_CAST5= 0x0000000C +LUNA_KEY_RC5= 0x0000000D +LUNA_KEY_ECDSA= 0x0000000E +LUNA_KEY_KEA= 0x0000000F +LUNA_KEY_IDEA= 0x00000010 +LUNA_KEY_SKIPJACK= 0x00000011 +LUNA_KEY_BATON= 0x00000012 +LUNA_KEY_JUNIPER= 0x00000013 +LUNA_KEY_CDMF= 0x00000014 +LUNA_KEY_AES= 0x0000001F +LUNA_KEY_ARIA= 0x00000020 +LUNA_KEY_VENDOR_DEFINED= 0x80000000 +LUNA_KEY_KCDSA= (LUNA_KEY_VENDOR_DEFINED + 0x10) +LUNA_KEY_SEED= (LUNA_KEY_VENDOR_DEFINED + 0x11) +LUNA_KEY_UNKNOWN= 0xFFFFFFFF # Added for error detection */ +LUNA_CERT_UNKNOWN= 0xFFFFFFFF # Added for error detection */ +LUNA_CVK_CERTIFICATE= 0x00000000 +LUNA_TWC_CERTIFICATE= 0x00000001 +LUNA_TUK_PRIVATE_KEY= 0x00000000 +LUNA_HOK_PRIVATE_KEY= 0x00000001 +LUNA_DAK_PRIVATE_KEY= 0x00000002 +LUNA_ECC_HOK_PRIVATE_KEY= 0x00000003 +LUNA_ECC_DAK_PRIVATE_KEY= 0x00000004 +LUNA_TUK3_PRIVATE_KEY= 0x00000005 +LUNA_VVK_PUBLIC_KEY= 0x00000001 +LUNA_GT_LABEL= 0x00000000 +LUNA_GT_MFG= 0x00000001 +LUNA_GT_MODEL= 0x00000002 +LUNA_GT_TSN= 0x00000003 +LUNA_GT_S_N= 0x00000003 #to remain backward compatible. LUNA_GT_TSN should be used. +LUNA_GT_FLAGS= 0x00000004 +LUNA_GT_SESSIONS= 0x00000005 +LUNA_GT_SRAM= 0x00000007 +LUNA_GT_FLASH= 0x00000008 +LUNA_GT_TPC= 0x00000009 +LUNA_GT_CAV= 0x0000000C +LUNA_GT_FWV= 0x0000000D +LUNA_GT_TSV= 0x0000000E +LUNA_GT_TWC= 0x0000000F +LUNA_GT_M_OF_N_INFO= 0x00000010 +LUNA_GT_M_OF_N_STATUS= 0x00000011 +LUNA_GT_TWK= 0x00000012 +LUNA_GT_USER_ILD= 0x00000014 +LUNA_GT_SO_ILD= 0x00000015 +LUNA_GT_ROOT_CERT= 0x00000017 +LUNA_GT_HW_ORIGIN_CERT= 0x00000018 # retrieves HOC+MIC +LUNA_GT_TCTRUST_DAC= 0x00000019 +LUNA_GT_TCTRUST_MAC= 0x0000001A +LUNA_GT_CITS_DAC= 0x0000001B +LUNA_GT_PPID= 0x0000001C +LUNA_GT_HARDWARE_PLATFORM= 0x0000001D +LUNA_GT_DEFAULT_MIN_MAX_PIN_LEN= 0x0000001E +LUNA_GT_TWC2= 0x0000001F +LUNA_GT_RPV_STATUS= 0x00000020 +LUNA_GT_ECC_MIC= 0x00000021 +LUNA_GT_ECC_HOC= 0x00000022 +LUNA_GT_ECC_DAC= 0x00000023 +LUNA_GT_ROLLBACK_FWV= 0x00000024 +LUNA_GT_MIC= 0x00000025 +LUNA_GT_HOC= 0x00000026 # retrieves HOC only +LUNA_GT_CITS_MAC= 0x00000027 +LUNA_GT_SP_RAWREAD= 0x00000030 +LUNA_GT_SP_RAWWRITE= 0x00000031 +LUNA_GT_PED_CALLBACK_PROTOCOL= 0x00000032 +LUNA_GT_TWK3= 0x00000033 +LUNA_GT_TWC3= 0x00000034 +LUNA_GT_HSM_STORAGE_INFO= 0x00000035 +LUNA_GT_NUMBER_OF_CONTAINERS_ALLOWED= 0x00000036 +LUNA_GT_MAX_SINGLE_PART_SIZE= 0x00000037 +LUNA_GT_PARTITION_ROLE_POLICIES= 0x00000038 +LUNA_GT_PARTITION_ROLE_DESCRIPTORS= 0x00000039 +LUNA_GT_ADMIN_PARTITION_HANDLE= 0x0000003A +LUNA_GT_TIME_OF_DAY= 0x0000003B +LUNA_GT_MONO_COUNTER= 0x0000003C +LUNA_GT_TEMP_K2= 0x0000003D +LUNA_GT_PIN= 0x00000006 +LUNA_GT_TPV= 0x0000000A +LUNA_GT_FPV= 0x0000000B +LUNA_GT_EXTENDED_TPV= 0x00000013 +LUNA_GT_EXTENDED_FPV= 0x00000016 +LUNA_TF_RNG= 0x00000001 +LUNA_TF_WRITE_PROTECTED= 0x00000002 +LUNA_TF_LOGIN_REQUIRED= 0x00000004 +LUNA_TF_USER_PIN_INITIALIZED= 0x00000008 +LUNA_TF_EXCLUSIVE_EXISTS= 0x00000010 +LUNA_TF_TOKEN_INITIALIZED= 0x00000400 +LUNA_CF_CONTAINER_ENABLED= 0x01000000 +LUNA_CF_KCV_CREATED= 0x02000000 +LUNA_CF_LKCV_CREATED= 0x04000000 +LUNA_CF_HA_INITIALIZED= 0x08000000 +LUNA_CF_PARTITION_INITIALIZED= 0x00000400 +LUNA_CF_CONTAINER_ACTIVATED= 0x00000001 +LUNA_CF_USER_PIN_INITIALIZED= 0x00008000 +LUNA_CF_SO_PIN_LOCKED= 0x00010000 +LUNA_CF_SO_PIN_TO_BE_CHANGED= 0x00020000 +LUNA_CF_USER_PIN_LOCKED= 0x00040000 +LUNA_CF_LIMITED_USER_PIN_LOCKED= 0x00080000 +LUNA_CF_LIMITED_USER_CREATED= 0x00200000 +LUNA_CF_USER_PIN_TO_BE_CHANGED= 0x00400000 +LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED= 0x00800000 +LUNA_FLAG_M_OF_N_REQUIRED= 0x00000001 +LUNA_FLAG_M_OF_N_ACTIVATED= 0x00000002 +LUNA_FLAG_M_OF_N_GENERATED= 0x00000004 +LUNA_FLAG_M_OF_N_CLONEABLE= 0x00000008 +LUNA_ISAKMP_DECRYPT= 0x00000500 +LUNA_ISAKMP_ENCRYPT_FIXED_IV= 0x00000501 +LUNA_ISAKMP_ENCRYPT_GEN_IV= 0x00000502 +LUNA_ENTRY_DATA_AREA= 0x00000000 +LUNA_ENTRY_SECURE_PORT= 0x00000001 +LUNA_ENTRY_INDIRECT= 0x00000002 # Obsolete as of f/w 5.0 +LUNA_ENTRY_RANDOM= 0x00000003 # only used for pin creation +LUNA_ENTRY_CHALLENGE_RESPONSE= 0x00000004 # only used for login +LUNA_ENTRY_REMOTE_AUTHENTICATION= 0x00000005 +LUNA_ENTRY_NONE= 0x000000FF # to indicate that nothing yet set. +LUNA_PED_ID_SCP= 0x0000 +LUNA_PED_ID_MAX= 0xFFFE +LUNA_UTYPE_NONE= 0xFFFFFFFF +LUNA_UTYPE_USER= 0x00000000 +LUNA_UTYPE_SO= 0x00000001 +LUNA_UTYPE_LIMITED_USER= 0x00000005 +LUNA_UTYPE_DOMAIN= 0x00000006 +LUNA_UTYPE_MTK= 0x00000007 +LUNA_UTYPE_AUDIT= 0x00000008 +LUNA_UTYPE_CFG_BASE= 0x80000000 +LUNA_REMOTE_AUTH_LOGIN= 0x00000000 +LUNA_REMOTE_AUTH_M_OF_N= 0x00000001 +LUNA_STYPE_R_W= 0x00000000 +LUNA_STYPE_R_W_EXCLUSIVE= 0x00000001 +LUNA_STYPE_R_O= 0x00000002 +LUNA_STYPE_R_O_EXCLUSIVE= 0x00000003 +LUNA_SACCESS_PUBLIC= 0x00000001 +LUNA_SACCESS_USER= 0x00000002 +LUNA_SACCESS_SO= 0x00000003 +LUNA_PAD_RFC_1423= 0x00000000 +LUNA_TTYPE_H_W= 0x00000000 +LUNA_TTYPE_CRYPTO= 0x00000001 +LUNA_TTYPE_RNG= 0x00000002 +LUNA_DSS_PRIMALITY_TEST= 0x00000003 +LUNA_DSS_PQG_TEST= 0x00000004 +LUNA_DSS_KEY_TEST= 0x00000005 +LUNA_DSS_SIG_TEST= 0x00000006 +LUNA_DSS_SIGVERIFY_TEST= 0x00000007 +LUNA_DSS_PQGVERIFY_TEST= 0x00000008 +LUNA_HIFN6500_TEST= 0x00000009 +LUNA_TTYPE_RNG_GEN= 0x0000000a +LUNA_TTYPE_AES_OFB= 0x0000000b +LUNA_ECDSA_KEY_TEST= 0x0000000c +LUNA_ECDSA_SIG_TEST= 0x0000000d +LUNA_ECDSA_SIGVERIFY_TEST= 0x0000000e +LUNA_TTYPE_RSA_X_931_KEY_GEN_TEST= 0x0000000f +LUNA_TTYPE_ARIA_OFB= 0x00000010 +LUNA_TTYPE_COMMUNICATION_PERFORMANCE_TEST= 0x00000011 +LUNA_DSS2_G_GEN_TEST= 0x00000012 +LUNA_TTYPE_RSA_1863_AUX_PRIME_KEY_GEN_TEST= 0x00000013 +LUNA_TTYPE_RSA_1863_ONLY_PRIME_KEY_GEN_TEST=0x00000014 +LUNA_CTYPE_KCV= 0x00000000 +LUNA_CTYPE_MOFN=0x00000001 +HA_CMD_GET_LOGIN_CHALLENGE= 0x01 +HA_CMD_ANSWER_LOGIN_CHALLENGE= 0x02 +HA_CMD_LOGIN= 0x03 +HA_CMD_GET_MOFN_CHALLENGE= 0x11 +HA_CMD_ANSWER_MOFN_CHALLENGE= 0x12 +HA_CMD_MOFN_ACTIVATE= 0x13 +LUNA_MASKING_KEY_PID= 24 +LUNA_MAC_PID= 43 # Manufacturer Authentication Certificate +LUNA_DAC_FIPS2_MEETS_PID= 44 # Device Authentication Certificate, FIPS2, "meets requirements" +LUNA_DAC_FIPS2_EVAL_PID= 45 # Device Authentication Certificate, FIPS2, "evaluated to" +LUNA_DAC_FIPS3_MEETS_PID= 46 # Device Authentication Certificate, FIPS3, "meets requirements" +LUNA_DAC_FIPS3_EVAL_PID= 47 # Device Authentication Certificate, FIPS3, "evaluated to" +LUNA_CUST_MAC_PID= 48 # Customer Manufacturer Authentication Certificate +LUNA_CUST_DAC_FIPS2_MEETS_PID=49 # Customer Device Authentication Certificate, FIPS2, "meets requirements" +LUNA_CUST_DAC_FIPS2_EVAL_PID= 50 # Customer Device Authentication Certificate, FIPS2, "evaluated to" +LUNA_CUST_DAC_FIPS3_MEETS_PID=51 # Customer Device Authentication Certificate, FIPS3, "meets requirements" +LUNA_CUST_DAC_FIPS3_EVAL_PID= 52 # Customer Device Authentication Certificate, FIPS3, "evaluated to" +LUNA_SSK_PID= 54 # Secure Signing Key +LUNA_ECC_MIC_PID= 60 # ECC Manufacturer Authentication Certificate +LUNA_ECC_HOK_PID= 61 # ECC Hardware Origin Key +LUNA_ECC_HOC_PID= 62 # ECC Hardware Origin Certificate +LUNA_ECC_DAK_PID= 63 # ECC Device Authentication Key +LUNA_ECC_DAC_PID= 64 # ECC Device Authentication Certificate +CA_MASK_DES3_RC4= 0x00000001 +CA_MASK_SHA1_AES_RC4= 0x00000002 +LUNA_MAX_CHALLENGE_SIZE=64 +LUNA_MAX_CHALLENGE_RESPONSE_SIZE=64 +LUNA_CHALLENGE_CLASS_AUTHENTICATION= 0x00000000 +LUNA_CHALLENGE_CLASS_SIM= 0x00000001 +LUNA_CHALLENGE_TYPE_NULL= 0x00000000 +LUNA_CHALLENGE_TYPE_SECRET_HASH= 0x00000001 # Obsolete -- didn't satisfy NIST +LUNA_CHALLENGE_TYPE_ENCRYPTED_SECRET_HASH= 0x00000002 +LUNA_CHALLENGE_TYPE_SO= LUNA_UTYPE_SO +LUNA_CHALLENGE_TYPE_USER= LUNA_UTYPE_USER +LUNA_CHALLENGE_TYPE_LIMITED_USER= LUNA_UTYPE_LIMITED_USER +LUNA_CHALLENGE_TYPE_AUDIT= LUNA_UTYPE_AUDIT +LUNA_SIM_NO_AUTHORIZATION=0 # no authorization needed +LUNA_SIM_PASSWORD= 1 # plain-text passwords +LUNA_SIM_CHALLENGE= 2 # challenge secrets emitted through the secure port +LUNA_SIM_SECURE_PORT= 3 # PED keys +LUNA_SIM_PORTABLE_NO_AUTHORIZATION=4 # no authorization needed +LUNA_SIM_PORTABLE_PASSWORD= 5 # plain-text passwords +LUNA_SIM_PORTABLE_CHALLENGE= 6 # challenge secrets emitted through the secure port +LUNA_SIM_PORTABLE_SECURE_PORT= 7 # PED keys +MAX_SIM_OBJECTS=2048 +CONTAINER_CONFIG_PRIVATE_KEY_CLONING= 0 +CONTAINER_CONFIG_PRIVATE_KEY_WRAPPING= 1 +CONTAINER_CONFIG_PRIVATE_KEY_UNWRAPPING= 2 +CONTAINER_CONFIG_PRIVATE_KEY_MASKING= 3 +CONTAINER_CONFIG_SECRET_KEY_CLONING= 4 +CONTAINER_CONFIG_SECRET_KEY_WRAPPING= 5 +CONTAINER_CONFIG_SECRET_KEY_UNWRAPPING= 6 +CONTAINER_CONFIG_SECRET_KEY_MASKING= 7 +CONTAINER_CONFIG_OBSOLETE_1= 8 +CONTAINER_CONFIG_OBSOLETE_2= 9 +CONTAINER_CONFIG_MULTIPURPOSE_KEYS= 10 +CONTAINER_CONFIG_CHANGE_KEY_ATTRIBUTES= 11 +CONTAINER_CONFIG_OBSOLETE_3= 12 +CONTAINER_CONFIG_OBSOLETE_4= 13 +CONTAINER_CONFIG_FAILED_CHALLENGE_COUNTER= 15 +CONTAINER_CONFIG_NO_RSA_BLINDING= 16 +CONTAINER_CONFIG_NONLOCAL_SIGNING_KEYS= 17 +CONTAINER_CONFIG_RAW_RSA_OPERATIONS= 18 +CONTAINER_CONFIG_KEY_STORAGE_SPACE= 19 # Obsolete as of f/w 6.0.2 +CONTAINER_CONFIG_MAX_FAILED_USER_LOGINS_ALLOWED=20 +CONTAINER_CONFIG_HIGH_AVAILABILITY= 21 +CONTAINER_CONFIG_ACTIVATION= 22 +CONTAINER_CONFIG_AUTO_ACTIVATION= 23 +CONTAINER_CONFIG_INDIRECT_LOGIN= 24 # Obsolete as of f/w 5.0 +CONTAINER_CONFIG_MINIMUM_PIN_LENGTH= 25 +CONTAINER_CONFIG_MAXIMUM_PIN_LENGTH= 26 +CONTAINER_CONFIG_OBSOLETE_5= 27 # CONTAINER_CONFIG_RA_TYPE_WRAPPING +CONTAINER_CONFIG_KEY_MANAGEMENT_FUNCTIONS= 28 +CONTAINER_CONFIG_RSA_SIGNATURE_CONFIRMATION= 29 +CONTAINER_CONFIG_REMOTE_AUTHENTICATION= 30 +CONTAINER_CONFIG_PRIVATE_KEY_UNMASKING= 31 +CONTAINER_CONFIG_SECRET_KEY_UNMASKING= 32 +CONTAINER_CONFIG_RSA_PKCS_MECHANISM= 33 +CONTAINER_CONFIG_CBC_PAD_WRAP_UNWRAP_KEYS_OF_ANY_SIZE= 34 +HSM_CONFIG_ENABLE_PIN_AUTHENTICATION= 0 +HSM_CONFIG_ENABLE_PED_AUTHENTICATION= 1 +HSM_CONFIG_PERFORMANCE_LEVEL= 2 +HSM_CONFIG_M_OF_N= 3 # Obsolete +HSM_CONFIG_DOMESTIC= 4 +HSM_CONFIG_CAV_USED= 5 +HSM_CONFIG_MASKING= 6 +HSM_CONFIG_CLONING= 7 +HSM_CONFIG_SPECIAL_CLONING= 8 # Obsolete +HSM_CONFIG_NONBACKUP_TOKEN= 9 +HSM_CONFIG_OBSOLETE_2= 10 +HSM_CONFIG_ECC= 11 +HSM_CONFIG_NONFIPS_ALGORITHMS= 12 +HSM_CONFIG_MOFN_AUTO_ACTIVATION= 13 # Obsolete +HSM_CONFIG_OBSOLETE_3= 14 +HSM_CONFIG_SO_CAN_RESET_PIN= 15 +HSM_CONFIG_NETWORK_REPLICATION= 16 +HSM_CONFIG_KOREAN= 17 +HSM_CONFIG_FIPS_EVALUATED= 18 +HSM_CONFIG_MANUFACT_TOKEN= 19 +HSM_CONFIG_REMOTE_AUTHENTICATION= 20 +HSM_CONFIG_FORCE_USER_PIN_CHANGE= 21 +HSM_CONFIG_OFFBOARD_STORAGE= 22 +HSM_CONFIG_ENABLE_PARTITION_GROUPS= 23 +HSM_CONFIG_ENABLE_NONFIPS_ACCELERATOR= 24 +HSM_CONFIG_ENABLE_REMOTE_PED_USAGE= 25 +HSM_CONFIG_STORE_MTK_SPLIT_EXTERNALLY= 26 +HSM_CONFIG_STORAGE_SIZE= 27 +HSM_CONFIG_HA_MODE_CGX= 28 +HSM_CONFIG_ENABLE_ACCELERATION= 29 +HSM_CONFIG_UNMASKING= 30 +HSM_CONFIG_ENABLE_FW5_COMPATIBILITY= 31 +HSM_CONFIG_ALLOWS_PUBLIC_CRYPTO= 32 +HSM_CONFIG_MAX_PARTITIONS= 33 +HSM_CONFIG_ENABLE_ECIES= 34 +HSM_CONFIG_ENABLE_SINGLE_DOMAIN= 35 +HSM_CONFIG_ALLOW_UNIFIED_PED_KEY= 36 +HSM_CONFIG_ALLOW_MOFN= 37 +LUNA_CLONING_PART2_OVERHEAD= 76 +LUNA_FLATTENED_OBJECT_OVERHEAD= 3264 +LEGACY_TWC_ACCESS_LEVEL= 1 +LUNA_LICENSE_TYPE_CONTAINER_PERSONALITY=0 +LUNA_LICENSE_TYPE_HSM_UPGRADE=1 +LUNA_LICENSE_TYPE=2 +LICENSE_DESCRIPTION_SIZE=60 +PERSONALITY_NAME_SIZE=60 +UPGRADE_DESCRIPTION_SIZE=60 +LUNA_MAX_ROLE_NAME_LEN= 24 +LUNA_MAX_PRP_LABEL_LEN= 24 +LUNA_MAX_ROLES_PER_PARTITION= 4 +LUNA_MAX_PRP_PER_SET= 3 +LUNA_NULL_ELEMENT= 0x00000000 +LUNA_CRYPTOKI_ELEMENT= 0x00000001 +LUNA_PARAM_ELEMENT= 0x00000002 +LUNA_CONTAINER_ACTIVATION_ELEMENT= 0x00000003 +LUNA_MOFN_ACTIVATION_ELEMENT= 0x00000004 +LUNA_CONTAINER_ELEMENT= 0x00000005 +LUNA_UNKNOWN_ELEMENT= (-1) +LUNA_FW4_CRYPTOKI_ELEMENT= 0x00000000 +LUNA_FW4_PARAM_ELEMENT= 0x00000001 +LUNA_FW4_CONTAINER_ACTIVATION_ELEMENT= 0x00000002 +LUNA_FW4_MOFN_ACTIVATION_ELEMENT= 0x00000003 +LUNA_HW_UNDEFINED= 0x00000000 +LUNA_HW_K3_PCI= 0x00000001 +LUNA_HW_K4_PCI= 0x00000002 +LUNA_HW_G3_PCMCIA= 0x00000003 +LUNA_HW_G4_PCMCIA= 0x00000004 +LUNA_HW_G5_USB= 0x00000005 +LUNA_HW_K5_PCI= 0x00000006 +LUNA_HW_PS_PCI= 0x00000007 +LUNA_HW_SSM= 0x00000008 +LUNA_HW_K6_PCI= 0x00000009 +LUNA_STORAGE_SHIFT= 0 +LUNA_STORAGE_MASK= (0x03 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_DEFAULT= (0x00 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_FLASH= (0x01 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_RAM= (0x02 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_CACHE= (0x03 << LUNA_STORAGE_SHIFT) +LUNA_PARTITION_TYPE_SHIFT= 2 +LUNA_PARTITION_TYPE_MASK= (0x03 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_PARTITION_TYPE_STANDALONE= (0x00 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_PARTITION_TYPE_GROUP= (0x01 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_PARTITION_TYPE_ADMIN= (0x03 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_CONTAINER_TYPE_GROUP= LUNA_PARTITION_TYPE_GROUP +LUNA_CONTAINER_TYPE_STANDALONE= LUNA_PARTITION_TYPE_STANDALONE +LUNA_INSERTION_UNINITIALIZED= 0x10 +LUNA_ENABLE_MEMBER_CONTAINER= 0x01 +LUNA_DISABLE_MEMBER_CONTAINER= 0x02 +LUNA_UNAUTH_CMD_CONTEXT_CREATE= 0x01 +LUNA_UNAUTH_CMD_CONTEXT_DELETE= 0x02 +LUNA_UNAUTH_CMD_CONTEXT_GET= 0x03 +LUNA_PKCS5_PBKD2_HMAC_SHA1= 0x00000001 +LUNA_SALT_SOURCE_SPECIFIED= 0x00000001 +LUNA_KDF_NULL= 0x00000001 +LUNA_KDF_SHA1_KDF= 0x00000002 +LUNA_KDF_SHA1_KDF_ASN1_X9_42= 0x00000003 +LUNA_KDF_SHA1_KDF_CONCATENATE_X9_42= 0x00000004 +LUNA_KDF_SHA1_KDF_CONCATENATE_NIST= 0x80000001 +LUNA_KDF_SHA1_KDF_ASN1_NIST= 0x80000002 +LUNA_KDF_SHA224_KDF= 0x80000003 +LUNA_KDF_SHA256_KDF= 0x80000004 +LUNA_KDF_SHA384_KDF= 0x80000005 +LUNA_KDF_SHA512_KDF= 0x80000006 +LUNA_KDF_RIPEMD160_KDF= 0x80000007 +LUNA_KDF_SHA1_NIST_KDF= 0x00000012 +LUNA_KDF_SHA224_NIST_KDF= 0x80000013 +LUNA_KDF_SHA256_NIST_KDF= 0x80000014 +LUNA_KDF_SHA384_NIST_KDF= 0x80000015 +LUNA_KDF_SHA512_NIST_KDF= 0x80000016 +LUNA_KDF_RIPEMD160_NIST_KDF= 0x80000017 +LUNA_KDF_SHA1_SES_KDF= 0x82000000 +LUNA_KDF_SHA224_SES_KDF= 0x83000000 +LUNA_KDF_SHA256_SES_KDF= 0x84000000 +LUNA_KDF_SHA384_SES_KDF= 0x85000000 +LUNA_KDF_SHA512_SES_KDF= 0x86000000 +LUNA_KDF_RIPEMD160_SES_KDF= 0x87000000 +LUNA_KDF_SES_ENC_CTR= 0x00000001 +LUNA_KDF_SES_AUTH_CTR= 0x00000002 +LUNA_KDF_SES_ALT_ENC_CTR= 0x00000003 +LUNA_KDF_SES_ALT_AUTH_CTR= 0x00000004 +LUNA_KDF_SES_MAX_CTR_MASK= 0x0000FFFF +LUNA_PRF_KDF_DES3_CMAC= 0x00000001 +LUNA_PRF_KDF_AES_CMAC= 0x00000002 +LUNA_PRF_KDF_ARIA_CMAC= 0x00000003 +LUNA_PRF_KDF_SEED_CMAC= 0x00000004 +LUNA_PRF_KDF_ENCODING_SCHEME_1= 0x00000000 +LUNA_PRF_KDF_ENCODING_SCHEME_2= 0x00000001 +CB_CMD_TEST= 0x00000000 +CB_CMD_TEST_UPLOAD= 0x00000001 +CB_CMD_TEST_DOWNLOAD= 0x00000002 +CB_CMD_TEST_PING= 0x00000003 +CB_CMD_RPED_READ= 0x00000001 +CB_CMD_RPED_WRITE= 0x00000002 +CB_CMD_RPED_GET_STATUS= 0x00000003 +CB_CMD_RPED_RESET_PED= 0x00000004 +CB_CMD_LOG= 0x00000005 +LUNA_PED_CMD_GET_RAW_DATA= 0x00000000 +LUNA_PED_CMD_SET_RAW_DATA= 0x00000001 +MTK_STATE_FLAG_RESPLIT_ABORTED= 0x00000001 +MTK_STATE_FLAG_HARD_ZEROIZE= 0x00000002 +MTK_STATE_FLAG_SOFT_ZEROIZE= 0x00000004 +MTK_STATE_FLAG_LOCKED= 0x00000008 +LUNA_TSV_DOMESTIC_FLAG= 0x80 +LUNA_TSV_MISSING_MTK_FLAG= 0x40 +LUNA_TSV_CLONING_ENABLED_FLAG= 0x20 +LUNA_TSV_ERASURE_FLAG= 0x10 +LUNA_TSV_AUDIT_CONTAINER_ZEROIZED= 0x08 +LUNA_TSV_TLO_FLAG= 0x04 +LUNA_TSV_CVK_FLAG= 0x02 +LUNA_TSV_HOK_FLAG= 0x01 +LUNA_TSV_TUK_FLAG_LO= 0x80 +LUNA_TSV_TWC_FLAG_LO= 0x40 +LUNA_TSV_KCV_FLAG_LO= 0x20 +LUNA_TSV_FLAG_LO_VOLATILE_MASK= 0x1F +LUNA_TSV_MASKING_KEY_SET= 0x10 +LUNA_TSV_VOLATILE_TOKENRW_MASK= 0x0C +LUNA_TSV_VOLATILE_TOKENRW_IS_NULL= 0x00 +LUNA_TSV_VOLATILE_TOKENRW_IS_READ_ONLY= 0x04 +LUNA_TSV_VOLATILE_TOKENRW_IS_READ_WRITE=0x08 +LUNA_TSV_VOLATILE_ACCESS_MASK= 0x03 +LUNA_TSV_VOLATILE_ACCESS_IS_NULL= 0x00 +LUNA_TSV_VOLATILE_ACCESS_IS_PUBLIC= 0x01 +LUNA_TSV_VOLATILE_ACCESS_IS_USER= 0x02 +LUNA_TSV_VOLATILE_ACCESS_IS_SO= 0x03 +LUNA_TSV_VOLATILE_ACCESS_IS_AUDIT= 0x04 +LUNA_TSV_FATAL_ERROR_MASK= 0xF0 +LUNA_TSV_CRC_ERROR_FLAG= 0x80 +LUNA_TSV_RNG_ERROR_FLAG= 0x40 +LUNA_TSV_MEM_ERROR_FLAG= 0x20 +LUNA_TSV_DEV_ERROR_FLAG= 0x10 +LUNA_TSV_TOSM_MASK= 0x0F +LUNA_TSV_TOSM_BLANK= 0x00 +LUNA_TSV_TOSM_ZEROIZED= 0x01 +LUNA_TSV_TOSM_FUNCTIONAL= 0x02 +LUNA_TSV_TOSM_ERROR= 0x03 +LUNA_MODIFY_USAGE_COUNT_TYPE_INCREMENT= 0x00000001 +LUNA_MODIFY_USAGE_COUNT_TYPE_SET= 0x00000002 +LUNA_CKDHP_ECDH1_COFACTOR= 0x00000001 +LUNA_CKDHP_MODIFIED= 0x00000002 # Not implemented */ +LUNA_CKDHP_ECDH1= 0x00000003 +LUNA_CKES_XOR= 0x00000001 +LUNA_CKES_DES3_CBC_PAD= 0x00000002 +LUNA_CKES_AES_CBC_PAD= 0x00000003 +LUNA_CKES_DES3_CBC= 0x00000004 +LUNA_CKES_AES_CBC= 0x00000005 +LUNA_CKMS_HMAC_SHA1= 0x00000001 +LUNA_CKMS_SHA1= 0x00000002 +LUNA_CKMS_HMAC_SHA224= 0x00000003 +LUNA_CKMS_SHA224= 0x00000004 +LUNA_CKMS_HMAC_SHA256= 0x00000005 +LUNA_CKMS_SHA256= 0x00000006 +LUNA_CKMS_HMAC_SHA384= 0x00000007 +LUNA_CKMS_SHA384= 0x00000008 +LUNA_CKMS_HMAC_SHA512= 0x00000009 +LUNA_CKMS_SHA512= 0x0000000a +LUNA_CKMS_HMAC_RIPEMD160= 0x0000000b +LUNA_CKMS_RIPEMD160= 0x0000000c +LUNA_LOG_WRITE= 0x000000c1 +LUNA_LOG_POLL_HOST= 0x000000c2 # This one is both internal and external, between the host & f/w, so it's defined above +LUNA_LOG_SET_CONFIG= 0x000000c5 # This one is both internal and external, between the host & f/w, so it's defined above +LUNA_LOG_RESYNC= 0x000000c8 +LUNA_STATS_NONE= 0 +LUNA_STATS_BOOT_TIME= 1 +LUNA_STATS_CPU_UP_TIME= 2 +LUNA_STATS_CPU_IDLE_TIME= 3 +LUNA_STATS_ICD_COMMANDS_COUNT= 4 +LUNA_STATS_UNKNOWN= 0xffffffff +LUNA_STC_CLIENT_NOT_SUPPORTED= 0x00000000 +LUNA_STC_CLIENT_FULL= 0x00000001 # lunapci functionality +LUNA_STC_CLIENT_LIMITED= 0x00000002 # lunaSA client functionality +LUNA_STC_CLIENT_RBS= 0x00000003 # Remote backup server functionality +'''/home/new_builds/689/101/tools/ekmtest/token.h''' +MAX_BUF_SIZE= 32000 +MAX_SLOT_COUNT= 20 +MAX_SESSION_COUNT= 20 +MAX_KEY_HANDLES= 10000000 +SIGNING_PART_SIZE= 0x8000 +BENCHMARK= 1 +MAX_RSA_KEY_NBITS= 8192 +LAST_MENU_ITEM= 204 +MAX_FILE_NAME_SIZE= 512 # bytes */ +XOR_KDF_MAX_SHARED_DATALEN= 512 # max. amount of shared data allowed +'''/home/new_builds/689/101/interfaces/Include/RSA/pkcs11t.h''' +CRYPTOKI_VERSION_MAJOR=2 +CRYPTOKI_VERSION_MINOR=20 +CRYPTOKI_VERSION_AMENDMENT=3 +CK_TRUE=1 +CK_FALSE=0 +FALSE=CK_FALSE +TRUE=CK_TRUE +CK_EFFECTIVELY_INFINITE= 0 +CK_INVALID_HANDLE=0 +CKN_SURRENDER= 0 +CKN_OTP_CHANGED= 1 +CKF_TOKEN_PRESENT= 0x00000001 # a token is there */ +CKF_REMOVABLE_DEVICE= 0x00000002 # removable devices*/ +CKF_HW_SLOT= 0x00000004 # hardware slot */ +CKF_RNG= 0x00000001 # has random # +CKF_WRITE_PROTECTED= 0x00000002 # token is +CKF_LOGIN_REQUIRED= 0x00000004 # user must +CKF_USER_PIN_INITIALIZED= 0x00000008 # normal user's +CKF_RESTORE_KEY_NOT_NEEDED= 0x00000020 +CKF_CLOCK_ON_TOKEN= 0x00000040 +CKF_PROTECTED_AUTHENTICATION_PATH=0x00000100 +CKF_DUAL_CRYPTO_OPERATIONS= 0x00000200 +CKF_TOKEN_INITIALIZED= 0x00000400 +CKF_SECONDARY_AUTHENTICATION= 0x00000800 +CKF_USER_PIN_COUNT_LOW= 0x00010000 +CKF_USER_PIN_FINAL_TRY= 0x00020000 +CKF_USER_PIN_LOCKED= 0x00040000 +CKF_USER_PIN_TO_BE_CHANGED= 0x00080000 +CKF_SO_PIN_COUNT_LOW= 0x00100000 +CKF_SO_PIN_FINAL_TRY= 0x00200000 +CKF_SO_PIN_LOCKED= 0x00400000 +CKF_SO_PIN_TO_BE_CHANGED= 0x00800000 +CKU_SO= 0 +CKU_USER= 1 +CKU_CONTEXT_SPECIFIC= 2 +CKS_RO_PUBLIC_SESSION= 0 +CKS_RO_USER_FUNCTIONS= 1 +CKS_RW_PUBLIC_SESSION= 2 +CKS_RW_USER_FUNCTIONS= 3 +CKS_RW_SO_FUNCTIONS= 4 +CKS_RW_AUDIT_FUNCTIONS= CKS_RW_SO_FUNCTIONS +CKF_RW_SESSION= 0x00000002 # session is r/w */ +CKF_SERIAL_SESSION= 0x00000004 # no parallel */ +CKO_DATA= 0x00000000 +CKO_CERTIFICATE= 0x00000001 +CKO_PUBLIC_KEY= 0x00000002 +CKO_PRIVATE_KEY= 0x00000003 +CKO_SECRET_KEY= 0x00000004 +CKO_HW_FEATURE= 0x00000005 +CKO_DOMAIN_PARAMETERS=0x00000006 +CKO_MECHANISM= 0x00000007 +CKO_OTP_KEY= 0x00000008 +CKO_VENDOR_DEFINED= 0x80000000 +CKH_MONOTONIC_COUNTER= 0x00000001 +CKH_CLOCK= 0x00000002 +CKH_USER_INTERFACE= 0x00000003 +CKH_VENDOR_DEFINED= 0x80000000 +CKK_RSA= 0x00000000 +CKK_DSA= 0x00000001 +CKK_DH= 0x00000002 +CKK_ECDSA= 0x00000003 +CKK_EC= 0x00000003 +CKK_X9_42_DH= 0x00000004 +CKK_KEA= 0x00000005 +CKK_GENERIC_SECRET= 0x00000010 +CKK_RC2= 0x00000011 +CKK_RC4= 0x00000012 +CKK_DES= 0x00000013 +CKK_DES2= 0x00000014 +CKK_DES3= 0x00000015 +CKK_CAST= 0x00000016 +CKK_CAST3= 0x00000017 +CKK_CAST5= 0x00000018 +CKK_CAST128= 0x00000018 +CKK_RC5= 0x00000019 +CKK_IDEA= 0x0000001A +CKK_SKIPJACK= 0x0000001B +CKK_BATON= 0x0000001C +CKK_JUNIPER= 0x0000001D +CKK_CDMF= 0x0000001E +CKK_AES= 0x0000001F +CKK_BLOWFISH= 0x00000020 +CKK_TWOFISH= 0x00000021 +CKK_SECURID= 0x00000022 +CKK_HOTP= 0x00000023 +CKK_ACTI= 0x00000024 +CKK_CAMELLIA= 0x00000025 +CKK_ARIA= 0x00000026 +CKK_VENDOR_DEFINED= 0x80000000 +CKC_X_509= 0x00000000 +CKC_X_509_ATTR_CERT=0x00000001 +CKC_WTLS= 0x00000002 +CKC_VENDOR_DEFINED= 0x80000000 +CKF_ARRAY_ATTRIBUTE= 0x40000000 +CK_OTP_FORMAT_DECIMAL= 0 +CK_OTP_FORMAT_HEXADECIMAL= 1 +CK_OTP_FORMAT_ALPHANUMERIC=2 +CK_OTP_FORMAT_BINARY= 3 +CK_OTP_PARAM_IGNORED= 0 +CK_OTP_PARAM_OPTIONAL= 1 +CK_OTP_PARAM_MANDATORY= 2 +CKA_CLASS= 0x00000000 +CKA_TOKEN= 0x00000001 +CKA_PRIVATE= 0x00000002 +CKA_LABEL= 0x00000003 +CKA_APPLICATION= 0x00000010 +CKA_VALUE= 0x00000011 +CKA_OBJECT_ID= 0x00000012 +CKA_CERTIFICATE_TYPE= 0x00000080 +CKA_ISSUER= 0x00000081 +CKA_SERIAL_NUMBER= 0x00000082 +CKA_AC_ISSUER= 0x00000083 +CKA_OWNER= 0x00000084 +CKA_ATTR_TYPES= 0x00000085 +CKA_TRUSTED= 0x00000086 +CKA_CERTIFICATE_CATEGORY= 0x00000087 +CKA_JAVA_MIDP_SECURITY_DOMAIN= 0x00000088 +CKA_URL= 0x00000089 +CKA_HASH_OF_SUBJECT_PUBLIC_KEY= 0x0000008A +CKA_HASH_OF_ISSUER_PUBLIC_KEY= 0x0000008B +CKA_CHECK_VALUE= 0x00000090 +CKA_KEY_TYPE= 0x00000100 +CKA_SUBJECT= 0x00000101 +CKA_ID= 0x00000102 +CKA_SENSITIVE= 0x00000103 +CKA_ENCRYPT= 0x00000104 +CKA_DECRYPT= 0x00000105 +CKA_WRAP= 0x00000106 +CKA_UNWRAP= 0x00000107 +CKA_SIGN= 0x00000108 +CKA_SIGN_RECOVER= 0x00000109 +CKA_VERIFY= 0x0000010A +CKA_VERIFY_RECOVER= 0x0000010B +CKA_DERIVE= 0x0000010C +CKA_START_DATE= 0x00000110 +CKA_END_DATE= 0x00000111 +CKA_MODULUS= 0x00000120 +CKA_MODULUS_BITS= 0x00000121 +CKA_PUBLIC_EXPONENT= 0x00000122 +CKA_PRIVATE_EXPONENT= 0x00000123 +CKA_PRIME_1= 0x00000124 +CKA_PRIME_2= 0x00000125 +CKA_EXPONENT_1= 0x00000126 +CKA_EXPONENT_2= 0x00000127 +CKA_COEFFICIENT= 0x00000128 +CKA_PRIME= 0x00000130 +CKA_SUBPRIME= 0x00000131 +CKA_BASE= 0x00000132 +CKA_PRIME_BITS= 0x00000133 +CKA_SUBPRIME_BITS= 0x00000134 +CKA_SUB_PRIME_BITS= CKA_SUBPRIME_BITS +CKA_VALUE_BITS= 0x00000160 +CKA_VALUE_LEN= 0x00000161 +CKA_EXTRACTABLE= 0x00000162 +CKA_LOCAL= 0x00000163 +CKA_NEVER_EXTRACTABLE= 0x00000164 +CKA_ALWAYS_SENSITIVE= 0x00000165 +CKA_KEY_GEN_MECHANISM= 0x00000166 +CKA_MODIFIABLE= 0x00000170 +CKA_ECDSA_PARAMS= 0x00000180 +CKA_EC_PARAMS= 0x00000180 +CKA_EC_POINT= 0x00000181 +CKA_SECONDARY_AUTH= 0x00000200 +CKA_AUTH_PIN_FLAGS= 0x00000201 +CKA_ALWAYS_AUTHENTICATE= 0x00000202 +CKA_WRAP_WITH_TRUSTED= 0x00000210 +CKA_WRAP_TEMPLATE= (CKF_ARRAY_ATTRIBUTE|0x00000211) +CKA_UNWRAP_TEMPLATE= (CKF_ARRAY_ATTRIBUTE|0x00000212) +CKA_OTP_FORMAT= 0x00000220 +CKA_OTP_LENGTH= 0x00000221 +CKA_OTP_TIME_INTERVAL= 0x00000222 +CKA_OTP_USER_FRIENDLY_MODE= 0x00000223 +CKA_OTP_CHALLENGE_REQUIREMENT=0x00000224 +CKA_OTP_TIME_REQUIREMENT= 0x00000225 +CKA_OTP_COUNTER_REQUIREMENT= 0x00000226 +CKA_OTP_PIN_REQUIREMENT= 0x00000227 +CKA_OTP_COUNTER= 0x0000022E +CKA_OTP_TIME= 0x0000022F +CKA_OTP_USER_IDENTIFIER= 0x0000022A +CKA_OTP_SERVICE_IDENTIFIER= 0x0000022B +CKA_OTP_SERVICE_LOGO= 0x0000022C +CKA_OTP_SERVICE_LOGO_TYPE= 0x0000022D +CKA_HW_FEATURE_TYPE= 0x00000300 +CKA_RESET_ON_INIT= 0x00000301 +CKA_HAS_RESET= 0x00000302 +CKA_PIXEL_X= 0x00000400 +CKA_PIXEL_Y= 0x00000401 +CKA_RESOLUTION= 0x00000402 +CKA_CHAR_ROWS= 0x00000403 +CKA_CHAR_COLUMNS= 0x00000404 +CKA_COLOR= 0x00000405 +CKA_BITS_PER_PIXEL= 0x00000406 +CKA_CHAR_SETS= 0x00000480 +CKA_ENCODING_METHODS= 0x00000481 +CKA_MIME_TYPES= 0x00000482 +CKA_MECHANISM_TYPE= 0x00000500 +CKA_REQUIRED_CMS_ATTRIBUTES= 0x00000501 +CKA_DEFAULT_CMS_ATTRIBUTES= 0x00000502 +CKA_SUPPORTED_CMS_ATTRIBUTES= 0x00000503 +CKA_ALLOWED_MECHANISMS= (CKF_ARRAY_ATTRIBUTE|0x00000600) +CKA_VENDOR_DEFINED= 0x80000000 +CKM_RSA_PKCS_KEY_PAIR_GEN= 0x00000000 +CKM_RSA_PKCS= 0x00000001 +CKM_RSA_9796= 0x00000002 +CKM_RSA_X_509= 0x00000003 +CKM_MD2_RSA_PKCS= 0x00000004 +CKM_MD5_RSA_PKCS= 0x00000005 +CKM_SHA1_RSA_PKCS= 0x00000006 +CKM_RIPEMD128_RSA_PKCS= 0x00000007 +CKM_RIPEMD160_RSA_PKCS= 0x00000008 +CKM_RSA_PKCS_OAEP= 0x00000009 +CKM_RSA_X9_31_KEY_PAIR_GEN= 0x0000000A +CKM_RSA_X9_31= 0x0000000B +CKM_SHA1_RSA_X9_31= 0x0000000C +CKM_RSA_PKCS_PSS= 0x0000000D +CKM_SHA1_RSA_PKCS_PSS= 0x0000000E +CKM_DSA_KEY_PAIR_GEN= 0x00000010 +CKM_DSA= 0x00000011 +CKM_DSA_SHA1= 0x00000012 +CKM_DH_PKCS_KEY_PAIR_GEN= 0x00000020 +CKM_DH_PKCS_DERIVE= 0x00000021 +CKM_X9_42_DH_KEY_PAIR_GEN= 0x00000030 +CKM_X9_42_DH_DERIVE= 0x00000031 +CKM_X9_42_DH_HYBRID_DERIVE= 0x00000032 +CKM_X9_42_MQV_DERIVE= 0x00000033 +CKM_SHA256_RSA_PKCS= 0x00000040 +CKM_SHA384_RSA_PKCS= 0x00000041 +CKM_SHA512_RSA_PKCS= 0x00000042 +CKM_SHA256_RSA_PKCS_PSS= 0x00000043 +CKM_SHA384_RSA_PKCS_PSS= 0x00000044 +CKM_SHA512_RSA_PKCS_PSS= 0x00000045 +CKM_SHA224_RSA_PKCS= 0x00000046 +CKM_SHA224_RSA_PKCS_PSS= 0x00000047 +CKM_RC2_KEY_GEN= 0x00000100 +CKM_RC2_ECB= 0x00000101 +CKM_RC2_CBC= 0x00000102 +CKM_RC2_MAC= 0x00000103 +CKM_RC2_MAC_GENERAL= 0x00000104 +CKM_RC2_CBC_PAD= 0x00000105 +CKM_RC4_KEY_GEN= 0x00000110 +CKM_RC4= 0x00000111 +CKM_DES_KEY_GEN= 0x00000120 +CKM_DES_ECB= 0x00000121 +CKM_DES_CBC= 0x00000122 +CKM_DES_MAC= 0x00000123 +CKM_DES_MAC_GENERAL= 0x00000124 +CKM_DES_CBC_PAD= 0x00000125 +CKM_DES2_KEY_GEN= 0x00000130 +CKM_DES3_KEY_GEN= 0x00000131 +CKM_DES3_ECB= 0x00000132 +CKM_DES3_CBC= 0x00000133 +CKM_DES3_MAC= 0x00000134 +CKM_DES3_MAC_GENERAL= 0x00000135 +CKM_DES3_CBC_PAD= 0x00000136 +CKM_DES3_CMAC_GENERAL= 0x00000137 +CKM_DES3_CMAC= 0x00000138 +CKM_CDMF_KEY_GEN= 0x00000140 +CKM_CDMF_ECB= 0x00000141 +CKM_CDMF_CBC= 0x00000142 +CKM_CDMF_MAC= 0x00000143 +CKM_CDMF_MAC_GENERAL= 0x00000144 +CKM_CDMF_CBC_PAD= 0x00000145 +CKM_DES_OFB64= 0x00000150 +CKM_DES_OFB8= 0x00000151 +CKM_DES_CFB64= 0x00000152 +CKM_DES_CFB8= 0x00000153 +CKM_MD2= 0x00000200 +CKM_MD2_HMAC= 0x00000201 +CKM_MD2_HMAC_GENERAL= 0x00000202 +CKM_MD5= 0x00000210 +CKM_MD5_HMAC= 0x00000211 +CKM_MD5_HMAC_GENERAL= 0x00000212 +CKM_SHA_1= 0x00000220 +CKM_SHA_1_HMAC= 0x00000221 +CKM_SHA_1_HMAC_GENERAL= 0x00000222 +CKM_RIPEMD128= 0x00000230 +CKM_RIPEMD128_HMAC= 0x00000231 +CKM_RIPEMD128_HMAC_GENERAL= 0x00000232 +CKM_RIPEMD160= 0x00000240 +CKM_RIPEMD160_HMAC= 0x00000241 +CKM_RIPEMD160_HMAC_GENERAL= 0x00000242 +CKM_SHA256= 0x00000250 +CKM_SHA256_HMAC= 0x00000251 +CKM_SHA256_HMAC_GENERAL= 0x00000252 +CKM_SHA224= 0x00000255 +CKM_SHA224_HMAC= 0x00000256 +CKM_SHA224_HMAC_GENERAL= 0x00000257 +CKM_SHA384= 0x00000260 +CKM_SHA384_HMAC= 0x00000261 +CKM_SHA384_HMAC_GENERAL= 0x00000262 +CKM_SHA512= 0x00000270 +CKM_SHA512_HMAC= 0x00000271 +CKM_SHA512_HMAC_GENERAL= 0x00000272 +CKM_SECURID_KEY_GEN= 0x00000280 +CKM_SECURID= 0x00000282 +CKM_HOTP_KEY_GEN= 0x00000290 +CKM_HOTP= 0x00000291 +CKM_ACTI= 0x000002A0 +CKM_ACTI_KEY_GEN= 0x000002A1 +CKM_CAST_KEY_GEN= 0x00000300 +CKM_CAST_ECB= 0x00000301 +CKM_CAST_CBC= 0x00000302 +CKM_CAST_MAC= 0x00000303 +CKM_CAST_MAC_GENERAL= 0x00000304 +CKM_CAST_CBC_PAD= 0x00000305 +CKM_CAST3_KEY_GEN= 0x00000310 +CKM_CAST3_ECB= 0x00000311 +CKM_CAST3_CBC= 0x00000312 +CKM_CAST3_MAC= 0x00000313 +CKM_CAST3_MAC_GENERAL= 0x00000314 +CKM_CAST3_CBC_PAD= 0x00000315 +CKM_CAST5_KEY_GEN= 0x00000320 +CKM_CAST128_KEY_GEN= 0x00000320 +CKM_CAST5_ECB= 0x00000321 +CKM_CAST128_ECB= 0x00000321 +CKM_CAST5_CBC= 0x00000322 +CKM_CAST128_CBC= 0x00000322 +CKM_CAST5_MAC= 0x00000323 +CKM_CAST128_MAC= 0x00000323 +CKM_CAST5_MAC_GENERAL= 0x00000324 +CKM_CAST128_MAC_GENERAL= 0x00000324 +CKM_CAST5_CBC_PAD= 0x00000325 +CKM_CAST128_CBC_PAD= 0x00000325 +CKM_RC5_KEY_GEN= 0x00000330 +CKM_RC5_ECB= 0x00000331 +CKM_RC5_CBC= 0x00000332 +CKM_RC5_MAC= 0x00000333 +CKM_RC5_MAC_GENERAL= 0x00000334 +CKM_RC5_CBC_PAD= 0x00000335 +CKM_IDEA_KEY_GEN= 0x00000340 +CKM_IDEA_ECB= 0x00000341 +CKM_IDEA_CBC= 0x00000342 +CKM_IDEA_MAC= 0x00000343 +CKM_IDEA_MAC_GENERAL= 0x00000344 +CKM_IDEA_CBC_PAD= 0x00000345 +CKM_GENERIC_SECRET_KEY_GEN= 0x00000350 +CKM_CONCATENATE_BASE_AND_KEY= 0x00000360 +CKM_CONCATENATE_BASE_AND_DATA= 0x00000362 +CKM_CONCATENATE_DATA_AND_BASE= 0x00000363 +CKM_XOR_BASE_AND_DATA= 0x00000364 +CKM_EXTRACT_KEY_FROM_KEY= 0x00000365 +CKM_SSL3_PRE_MASTER_KEY_GEN= 0x00000370 +CKM_SSL3_MASTER_KEY_DERIVE= 0x00000371 +CKM_SSL3_KEY_AND_MAC_DERIVE= 0x00000372 +CKM_SSL3_MASTER_KEY_DERIVE_DH= 0x00000373 +CKM_TLS_PRE_MASTER_KEY_GEN= 0x00000374 +CKM_TLS_MASTER_KEY_DERIVE= 0x00000375 +CKM_TLS_KEY_AND_MAC_DERIVE= 0x00000376 +CKM_TLS_MASTER_KEY_DERIVE_DH= 0x00000377 +CKM_TLS_PRF= 0x00000378 +CKM_SSL3_MD5_MAC= 0x00000380 +CKM_SSL3_SHA1_MAC= 0x00000381 +CKM_MD5_KEY_DERIVATION= 0x00000390 +CKM_MD2_KEY_DERIVATION= 0x00000391 +CKM_SHA1_KEY_DERIVATION= 0x00000392 +CKM_SHA256_KEY_DERIVATION= 0x00000393 +CKM_SHA384_KEY_DERIVATION= 0x00000394 +CKM_SHA512_KEY_DERIVATION= 0x00000395 +CKM_SHA224_KEY_DERIVATION= 0x00000396 +CKM_PBE_MD2_DES_CBC= 0x000003A0 +CKM_PBE_MD5_DES_CBC= 0x000003A1 +CKM_PBE_MD5_CAST_CBC= 0x000003A2 +CKM_PBE_MD5_CAST3_CBC= 0x000003A3 +CKM_PBE_MD5_CAST5_CBC= 0x000003A4 +CKM_PBE_MD5_CAST128_CBC= 0x000003A4 +CKM_PBE_SHA1_CAST5_CBC= 0x000003A5 +CKM_PBE_SHA1_CAST128_CBC= 0x000003A5 +CKM_PBE_SHA1_RC4_128= 0x000003A6 +CKM_PBE_SHA1_RC4_40= 0x000003A7 +CKM_PBE_SHA1_DES3_EDE_CBC= 0x000003A8 +CKM_PBE_SHA1_DES2_EDE_CBC= 0x000003A9 +CKM_PBE_SHA1_RC2_128_CBC= 0x000003AA +CKM_PBE_SHA1_RC2_40_CBC= 0x000003AB +CKM_PKCS5_PBKD2= 0x000003B0 +CKM_PBA_SHA1_WITH_SHA1_HMAC= 0x000003C0 +CKM_WTLS_PRE_MASTER_KEY_GEN= 0x000003D0 +CKM_WTLS_MASTER_KEY_DERIVE= 0x000003D1 +CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC= 0x000003D2 +CKM_WTLS_PRF= 0x000003D3 +CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE= 0x000003D4 +CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE= 0x000003D5 +CKM_KEY_WRAP_LYNKS= 0x00000400 +CKM_KEY_WRAP_SET_OAEP= 0x00000401 +CKM_CMS_SIG= 0x00000500 +CKM_KIP_DERIVE= 0x00000510 +CKM_KIP_WRAP= 0x00000511 +CKM_KIP_MAC= 0x00000512 +CKM_CAMELLIA_KEY_GEN= 0x00000550 +CKM_CAMELLIA_ECB= 0x00000551 +CKM_CAMELLIA_CBC= 0x00000552 +CKM_CAMELLIA_MAC= 0x00000553 +CKM_CAMELLIA_MAC_GENERAL= 0x00000554 +CKM_CAMELLIA_CBC_PAD= 0x00000555 +CKM_CAMELLIA_ECB_ENCRYPT_DATA= 0x00000556 +CKM_CAMELLIA_CBC_ENCRYPT_DATA= 0x00000557 +CKM_CAMELLIA_CTR= 0x00000558 +CKM_ARIA_KEY_GEN= 0x00000560 +CKM_ARIA_ECB= 0x00000561 +CKM_ARIA_CBC= 0x00000562 +CKM_ARIA_MAC= 0x00000563 +CKM_ARIA_MAC_GENERAL= 0x00000564 +CKM_ARIA_CBC_PAD= 0x00000565 +CKM_ARIA_ECB_ENCRYPT_DATA= 0x00000566 +CKM_ARIA_CBC_ENCRYPT_DATA= 0x00000567 +CKM_SKIPJACK_KEY_GEN= 0x00001000 +CKM_SKIPJACK_ECB64= 0x00001001 +CKM_SKIPJACK_CBC64= 0x00001002 +CKM_SKIPJACK_OFB64= 0x00001003 +CKM_SKIPJACK_CFB64= 0x00001004 +CKM_SKIPJACK_CFB32= 0x00001005 +CKM_SKIPJACK_CFB16= 0x00001006 +CKM_SKIPJACK_CFB8= 0x00001007 +CKM_SKIPJACK_WRAP= 0x00001008 +CKM_SKIPJACK_PRIVATE_WRAP= 0x00001009 +CKM_SKIPJACK_RELAYX= 0x0000100a +CKM_KEA_KEY_PAIR_GEN= 0x00001010 +CKM_KEA_KEY_DERIVE= 0x00001011 +CKM_FORTEZZA_TIMESTAMP= 0x00001020 +CKM_BATON_KEY_GEN= 0x00001030 +CKM_BATON_ECB128= 0x00001031 +CKM_BATON_ECB96= 0x00001032 +CKM_BATON_CBC128= 0x00001033 +CKM_BATON_COUNTER= 0x00001034 +CKM_BATON_SHUFFLE= 0x00001035 +CKM_BATON_WRAP= 0x00001036 +CKM_ECDSA_KEY_PAIR_GEN= 0x00001040 +CKM_EC_KEY_PAIR_GEN= 0x00001040 +CKM_ECDSA= 0x00001041 +CKM_ECDSA_SHA1= 0x00001042 +CKM_ECDH1_DERIVE= 0x00001050 +CKM_ECDH1_COFACTOR_DERIVE= 0x00001051 +CKM_ECMQV_DERIVE= 0x00001052 +CKM_JUNIPER_KEY_GEN= 0x00001060 +CKM_JUNIPER_ECB128= 0x00001061 +CKM_JUNIPER_CBC128= 0x00001062 +CKM_JUNIPER_COUNTER= 0x00001063 +CKM_JUNIPER_SHUFFLE= 0x00001064 +CKM_JUNIPER_WRAP= 0x00001065 +CKM_FASTHASH= 0x00001070 +CKM_AES_KEY_GEN= 0x00001080 +CKM_AES_ECB= 0x00001081 +CKM_AES_CBC= 0x00001082 +CKM_AES_MAC= 0x00001083 +CKM_AES_MAC_GENERAL= 0x00001084 +CKM_AES_CBC_PAD= 0x00001085 +CKM_AES_CTR= 0x00001086 +CKM_AES_CMAC_GENERAL= 0x00001089 +CKM_AES_CMAC= 0x0000108A +CKM_BLOWFISH_KEY_GEN= 0x00001090 +CKM_BLOWFISH_CBC= 0x00001091 +CKM_TWOFISH_KEY_GEN= 0x00001092 +CKM_TWOFISH_CBC= 0x00001093 +CKM_DES_ECB_ENCRYPT_DATA= 0x00001100 +CKM_DES_CBC_ENCRYPT_DATA= 0x00001101 +CKM_DES3_ECB_ENCRYPT_DATA= 0x00001102 +CKM_DES3_CBC_ENCRYPT_DATA= 0x00001103 +CKM_AES_ECB_ENCRYPT_DATA= 0x00001104 +CKM_AES_CBC_ENCRYPT_DATA= 0x00001105 +CKM_DSA_PARAMETER_GEN= 0x00002000 +CKM_DH_PKCS_PARAMETER_GEN= 0x00002001 +CKM_X9_42_DH_PARAMETER_GEN= 0x00002002 +CKM_VENDOR_DEFINED= 0x80000000 +CKF_HW= 0x00000001 # performed by HW */ +CKF_ENCRYPT= 0x00000100 +CKF_DECRYPT= 0x00000200 +CKF_DIGEST= 0x00000400 +CKF_SIGN= 0x00000800 +CKF_SIGN_RECOVER= 0x00001000 +CKF_VERIFY= 0x00002000 +CKF_VERIFY_RECOVER= 0x00004000 +CKF_GENERATE= 0x00008000 +CKF_GENERATE_KEY_PAIR= 0x00010000 +CKF_WRAP= 0x00020000 +CKF_UNWRAP= 0x00040000 +CKF_DERIVE= 0x00080000 +CKF_EC_F_P= 0x00100000 +CKF_EC_F_2M= 0x00200000 +CKF_EC_ECPARAMETERS= 0x00400000 +CKF_EC_NAMEDCURVE= 0x00800000 +CKF_EC_UNCOMPRESS= 0x01000000 +CKF_EC_COMPRESS= 0x02000000 +CKF_EXTENSION= 0x80000000 # FALSE for this version */ +CKR_OK= 0x00000000 +CKR_CANCEL= 0x00000001 +CKR_HOST_MEMORY= 0x00000002 +CKR_SLOT_ID_INVALID= 0x00000003 +CKR_GENERAL_ERROR= 0x00000005 +CKR_FUNCTION_FAILED= 0x00000006 +CKR_ARGUMENTS_BAD= 0x00000007 +CKR_NO_EVENT= 0x00000008 +CKR_NEED_TO_CREATE_THREADS= 0x00000009 +CKR_CANT_LOCK= 0x0000000A +CKR_ATTRIBUTE_READ_ONLY= 0x00000010 +CKR_ATTRIBUTE_SENSITIVE= 0x00000011 +CKR_ATTRIBUTE_TYPE_INVALID= 0x00000012 +CKR_ATTRIBUTE_VALUE_INVALID= 0x00000013 +CKR_DATA_INVALID= 0x00000020 +CKR_DATA_LEN_RANGE= 0x00000021 +CKR_DEVICE_ERROR= 0x00000030 +CKR_DEVICE_MEMORY= 0x00000031 +CKR_DEVICE_REMOVED= 0x00000032 +CKR_ENCRYPTED_DATA_INVALID= 0x00000040 +CKR_ENCRYPTED_DATA_LEN_RANGE= 0x00000041 +CKR_FUNCTION_CANCELED= 0x00000050 +CKR_FUNCTION_NOT_PARALLEL= 0x00000051 +CKR_FUNCTION_NOT_SUPPORTED= 0x00000054 +CKR_KEY_HANDLE_INVALID= 0x00000060 +CKR_KEY_SIZE_RANGE= 0x00000062 +CKR_KEY_TYPE_INCONSISTENT= 0x00000063 +CKR_KEY_NOT_NEEDED= 0x00000064 +CKR_KEY_CHANGED= 0x00000065 +CKR_KEY_NEEDED= 0x00000066 +CKR_KEY_INDIGESTIBLE= 0x00000067 +CKR_KEY_FUNCTION_NOT_PERMITTED= 0x00000068 +CKR_KEY_NOT_WRAPPABLE= 0x00000069 +CKR_KEY_UNEXTRACTABLE= 0x0000006A +CKR_MECHANISM_INVALID= 0x00000070 +CKR_MECHANISM_PARAM_INVALID= 0x00000071 +CKR_OBJECT_HANDLE_INVALID= 0x00000082 +CKR_OPERATION_ACTIVE= 0x00000090 +CKR_OPERATION_NOT_INITIALIZED= 0x00000091 +CKR_PIN_INCORRECT= 0x000000A0 +CKR_PIN_INVALID= 0x000000A1 +CKR_PIN_LEN_RANGE= 0x000000A2 +CKR_PIN_EXPIRED= 0x000000A3 +CKR_PIN_LOCKED= 0x000000A4 +CKR_SESSION_CLOSED= 0x000000B0 +CKR_SESSION_COUNT= 0x000000B1 +CKR_SESSION_HANDLE_INVALID= 0x000000B3 +CKR_SESSION_PARALLEL_NOT_SUPPORTED= 0x000000B4 +CKR_SESSION_READ_ONLY= 0x000000B5 +CKR_SESSION_EXISTS= 0x000000B6 +CKR_SESSION_READ_ONLY_EXISTS= 0x000000B7 +CKR_SESSION_READ_WRITE_SO_EXISTS= 0x000000B8 +CKR_SIGNATURE_INVALID= 0x000000C0 +CKR_SIGNATURE_LEN_RANGE= 0x000000C1 +CKR_TEMPLATE_INCOMPLETE= 0x000000D0 +CKR_TEMPLATE_INCONSISTENT= 0x000000D1 +CKR_TOKEN_NOT_PRESENT= 0x000000E0 +CKR_TOKEN_NOT_RECOGNIZED= 0x000000E1 +CKR_TOKEN_WRITE_PROTECTED= 0x000000E2 +CKR_UNWRAPPING_KEY_HANDLE_INVALID= 0x000000F0 +CKR_UNWRAPPING_KEY_SIZE_RANGE= 0x000000F1 +CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT= 0x000000F2 +CKR_USER_ALREADY_LOGGED_IN= 0x00000100 +CKR_USER_NOT_LOGGED_IN= 0x00000101 +CKR_USER_PIN_NOT_INITIALIZED= 0x00000102 +CKR_USER_TYPE_INVALID= 0x00000103 +CKR_USER_ANOTHER_ALREADY_LOGGED_IN= 0x00000104 +CKR_USER_TOO_MANY_TYPES= 0x00000105 +CKR_WRAPPED_KEY_INVALID= 0x00000110 +CKR_WRAPPED_KEY_LEN_RANGE= 0x00000112 +CKR_WRAPPING_KEY_HANDLE_INVALID= 0x00000113 +CKR_WRAPPING_KEY_SIZE_RANGE= 0x00000114 +CKR_WRAPPING_KEY_TYPE_INCONSISTENT= 0x00000115 +CKR_RANDOM_SEED_NOT_SUPPORTED= 0x00000120 +CKR_RANDOM_NO_RNG= 0x00000121 +CKR_DOMAIN_PARAMS_INVALID= 0x00000130 +CKR_BUFFER_TOO_SMALL= 0x00000150 +CKR_SAVED_STATE_INVALID= 0x00000160 +CKR_INFORMATION_SENSITIVE= 0x00000170 +CKR_STATE_UNSAVEABLE= 0x00000180 +CKR_CRYPTOKI_NOT_INITIALIZED= 0x00000190 +CKR_CRYPTOKI_ALREADY_INITIALIZED= 0x00000191 +CKR_MUTEX_BAD= 0x000001A0 +CKR_MUTEX_NOT_LOCKED= 0x000001A1 +CKR_NEW_PIN_MODE= 0x000001B0 +CKR_NEXT_OTP= 0x000001B1 +CKR_FUNCTION_REJECTED= 0x00000200 +CKR_VENDOR_DEFINED= 0x80000000 +CKF_LIBRARY_CANT_CREATE_OS_THREADS=0x00000001 +CKF_OS_LOCKING_OK= 0x00000002 +CKF_DONT_BLOCK= 1 +CKG_MGF1_SHA1= 0x00000001 +CKG_MGF1_SHA256= 0x00000002 +CKG_MGF1_SHA384= 0x00000003 +CKG_MGF1_SHA512= 0x00000004 +CKG_MGF1_SHA224= 0x00000005 +CKZ_DATA_SPECIFIED= 0x00000001 +CKD_NULL= 0x00000001 +CKD_SHA1_KDF= 0x00000002 +CKD_SHA1_KDF_ASN1= 0x00000003 +CKD_SHA1_KDF_CONCATENATE=0x00000004 +CKP_PKCS5_PBKD2_HMAC_SHA1=0x00000001 +CKZ_SALT_SPECIFIED= 0x00000001 +CK_OTP_VALUE= 0 +CK_OTP_PIN= 1 +CK_OTP_CHALLENGE= 2 +CK_OTP_TIME= 3 +CK_OTP_COUNTER= 4 +CK_OTP_FLAGS= 5 +CK_OTP_OUTPUT_LENGTH= 6 +CK_OTP_OUTPUT_FORMAT= 7 +CKF_NEXT_OTP= 0x00000001 +CKF_EXCLUDE_TIME= 0x00000002 +CKF_EXCLUDE_COUNTER= 0x00000004 +CKF_EXCLUDE_CHALLENGE=0x00000008 +CKF_EXCLUDE_PIN= 0x00000010 +CKF_USER_FRIENDLY_OTP=0x00000020 +'''/home/new_builds/689/101/CoreLibrary/includes/cryptoki_v2.h''' +NULL_PTR= 0 +C_LIBRARY_VERSION= 0x510 # v5.10 decimal */ +CK_TOKEN_SERIAL_NUMBER_SIZE= 16 +CK_EFFECTIVELY_INFINITE= 0 +CKU_CRYPTO_OFFICER=CKU_USER +CKU_LIMITED_USER=0x80000001 +CKU_LIMITED_USER_OLD=0x8000001 +CKU_CRYPTO_USER=CKU_LIMITED_USER +CKU_AUDIT= 0x80000002 +CKU_INVALID_USER_TYPE=0xffffffff +CKU_VENDOR_DEFINED= 0x80000000 +CKF_EXCLUSIVE_SESSION= 0x0001 +CKF_EXCLUSIVE_EXISTS= 0x0010 +CKF_SO_SESSION= 0x8000 +CKF_AUDIT_SESSION= 0x10000 +CKF_ADMIN_TOKEN= 0x10000000 +CKF_ENTRUST_READY= 0x00000001 +CKF_NO_CLEAR_PINS= 0x00000002 +CKF_AUTH_PROTECTION= 0x00000004 +CKF_NO_PUBLIC_CRYPTO= 0x00000008 +CKF_TAMPER_BEFORE_UPGRADE=0x00000010 +CKF_INCREASED_SECURITY= 0x00000020 +CKF_FIPS_ALGORITHMS= 0x00000040 +CKF_FULL_SMS_ENC= 0x00000080 +CKF_FULL_SMS_SIGN= 0x00000100 +CKF_PURE_P11= 0x00000200 +CKF_DES_EVEN_PARITY_ALLOWED=0x00000400 +CKF_USER_ECC_DP_ALLOWED= 0x00000800 +CKF_MODE_LOCKED= 0x10000000 +CKA_START_DATE_OLD_XXX= 0x0083 # Kept temporarily for backward compatibility with Beta version. Use CKA_START_DATE +CKA_END_DATE_OLD_XXX= 0x0084 # Kept temporarily for backward compatibility with Beta version. Use CKA_END_DATE +CKD_SHA224_KDF= 0x00000005 +CKD_SHA224_KDF_OLD= 0x80000003 +CKD_SHA256_KDF= 0x00000006 +CKD_SHA256_KDF_OLD= 0x80000004 +CKD_SHA384_KDF= 0x00000007 +CKD_SHA384_KDF_OLD= 0x80000005 +CKD_SHA512_KDF= 0x00000008 +CKD_SHA512_KDF_OLD= 0x80000006 +CKD_RIPEMD160_KDF= 0x80000007 +CKD_SHA1_NIST_KDF= 0x00000012 +CKD_SHA224_NIST_KDF= 0x80000013 +CKD_SHA256_NIST_KDF= 0x80000014 +CKD_SHA384_NIST_KDF= 0x80000015 +CKD_SHA512_NIST_KDF= 0x80000016 +CKD_RIPEMD160_NIST_KDF= 0x80000017 +CKD_SHA1_SES_KDF= 0x82000000 +CKD_SHA224_SES_KDF= 0x83000000 +CKD_SHA256_SES_KDF= 0x84000000 +CKD_SHA384_SES_KDF= 0x85000000 +CKD_SHA512_SES_KDF= 0x86000000 +CKD_RIPEMD160_SES_KDF= 0x87000000 +CKD_SES_ENC_CTR= 0x00000001 +CKD_SES_AUTH_CTR= 0x00000002 +CKD_SES_ALT_ENC_CTR= 0x00000003 +CKD_SES_ALT_AUTH_CTR= 0x00000004 +CKD_SHA1_KDF_ASN1= 0x00000003 # not supported +CKD_SHA1_KDF_CONCATENATE= 0x00000004 +CKD_SHA1_KDF_CONCATENATE_X9_42=CKD_SHA1_KDF_CONCATENATE +CKD_SHA1_KDF_CONCATENATE_NIST= 0x80000001 +CKD_SHA1_KDF_ASN1_X9_42= CKD_SHA1_KDF_ASN1 # not supported +CKD_SHA1_KDF_ASN1_NIST= 0x80000002 # not supported +CKK_KCDSA= CKK_VENDOR_DEFINED + 0x10 +CKK_SEED= CKK_VENDOR_DEFINED + 0x11 +CKA_CCM_PRIVATE= (CKA_VENDOR_DEFINED | 0x0001) +CKA_FINGERPRINT_SHA1= (CKA_VENDOR_DEFINED | 0x0002) +CKA_PKC_TCTRUST= (CKA_VENDOR_DEFINED | 0x0003) +CKA_PKC_CITS= (CKA_VENDOR_DEFINED | 0x0004) +CKA_OUID= (CKA_VENDOR_DEFINED | 0x0005) +CKA_X9_31_GENERATED= (CKA_VENDOR_DEFINED | 0x0006) +CKA_PKC_ECC= (CKA_VENDOR_DEFINED | 0x0007) +CKA_EKM_UID= (CKA_VENDOR_DEFINED | 0x0008) +CKA_TOKEN_ROLE_POLICIES= (CKA_VENDOR_DEFINED | 0x0010) +CKA_ROLE_DESCRIPTORS= (CKA_VENDOR_DEFINED | 0x0011) +CKA_USER_VALUE= (CKA_VENDOR_DEFINED | 0x0012) +CKA_INITIALIZER= (CKA_VENDOR_DEFINED | 0x0013) +CKA_POLICY= (CKA_VENDOR_DEFINED | 0x0014) +CKA_ACTIVE= (CKA_VENDOR_DEFINED | 0x0015) +CKA_INITIALIZED= (CKA_VENDOR_DEFINED | 0x0016) +CKA_PIN_TO_BE_CHANGED= (CKA_VENDOR_DEFINED | 0x0017) +CKA_LOCKED_OUT= (CKA_VENDOR_DEFINED | 0x0018) +CKA_ACTIVATED= (CKA_VENDOR_DEFINED | 0x0019) +CKA_HAS_DOMAIN= (CKA_VENDOR_DEFINED | 0x001A) +CKA_LOGIN_ATTEMPTS_LEFT= (CKA_VENDOR_DEFINED | 0x001B) +CKA_PRIMARY_AUTH_METHOD= (CKA_VENDOR_DEFINED | 0x001C) +CKA_SECONDARY_AUTH_METHOD=(CKA_VENDOR_DEFINED | 0x001D) +CKA_USAGE_COUNT= (CKA_VENDOR_DEFINED + 0x0101) +CKA_SLOT_ID= (CKA_VENDOR_DEFINED + 0x0151) +CKA_MAX_SESSIONS= (CKA_VENDOR_DEFINED | 0x0155) +CKA_MIN_PIN_LEN= (CKA_VENDOR_DEFINED | 0x0156) +CKA_FLAGS= (CKA_VENDOR_DEFINED | 0x0159) +CKA_USAGE_LIMIT= (CKA_VENDOR_DEFINED + 0x0200) +CKA_SECURITY_MODE= (CKA_VENDOR_DEFINED + 0x0140) +CKA_TRANSPORT_MODE= (CKA_VENDOR_DEFINED + 0x0141) +CKA_BATCH= (CKA_VENDOR_DEFINED + 0x0142) +CKA_HW_STATUS= (CKA_VENDOR_DEFINED + 0x0143) +CKA_FREE_MEM= (CKA_VENDOR_DEFINED + 0x0144) +CKA_TAMPER_CMD= (CKA_VENDOR_DEFINED + 0x0145) +CKA_DATE_OF_MANUFACTURE=(CKA_VENDOR_DEFINED + 0x0146) +CKA_HALT_CMD= (CKA_VENDOR_DEFINED + 0x0147) +CKA_APPLICATION_COUNT=(CKA_VENDOR_DEFINED + 0x0148) +CKA_FW_VERSION= (CKA_VENDOR_DEFINED + 0x0149) +CKA_RESCAN_PERIPHERALS_CMD=(CKA_VENDOR_DEFINED + 0x014A) +CKA_RTC_AAC_ENABLED= (CKA_VENDOR_DEFINED + 0x014B) +CKA_RTC_AAC_GUARD_SECONDS= (CKA_VENDOR_DEFINED + 0x014C) +CKA_RTC_AAC_GUARD_COUNT= (CKA_VENDOR_DEFINED + 0x014D) +CKA_RTC_AAC_GUARD_DURATION=(CKA_VENDOR_DEFINED + 0x014E) +CKA_HW_EXT_INFO_STR= (CKA_VENDOR_DEFINED + 0x014F) +CKA_TEMPERATURE_STR= (CKA_VENDOR_DEFINED + 0x0150) +CKA_GENERIC_1= (CKA_VENDOR_DEFINED + 0x1000) +CKA_GENERIC_2= (CKA_VENDOR_DEFINED + 0x1001) +CKA_GENERIC_3= (CKA_VENDOR_DEFINED + 0x1002) +CKA_FINGERPRINT_SHA256= (CKA_VENDOR_DEFINED + 0x1003) +CKM_VENDOR_DEFINED_OLD_XXX= 0x00008000 +CKM_CAST_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 0 # Entrust added capabilities +CKM_CAST_ECB_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 1 # Entrust added capabilities +CKM_CAST_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 2 # Entrust added capabilities +CKM_CAST_MAC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 3 # Entrust added capabilities +CKM_CAST3_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 4 # Entrust added capabilities +CKM_CAST3_ECB_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 5 # Entrust added capabilities +CKM_CAST3_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 6 # Entrust added capabilities +CKM_CAST3_MAC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 7 # Entrust added capabilities +CKM_PBE_MD2_DES_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 8 # Password based encryption +CKM_PBE_MD5_DES_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 9 # Password based encryption +CKM_PBE_MD5_CAST_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 10 # Password based encryption +CKM_PBE_MD5_CAST3_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 11 # Password based encryption +CKM_CONCATENATE_BASE_AND_KEY_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 12 # SPKM & SLL added capabilities +CKM_CONCATENATE_KEY_AND_BASE_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 13 # SPKM & SLL added capabilities +CKM_CONCATENATE_BASE_AND_DATA_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 14 # SPKM & SLL added capabilities +CKM_CONCATENATE_DATA_AND_BASE_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 15 # SPKM & SLL added capabilities +CKM_XOR_BASE_AND_DATA_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 16 # SPKM & SLL added capabilities +CKM_EXTRACT_KEY_FROM_KEY_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 17 # SPKM & SLL added capabilities +CKM_MD5_KEY_DERIVATION_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 18 # SPKM & SLL added capabilities +CKM_MD2_KEY_DERIVATION_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 19 # SPKM & SLL added capabilities +CKM_SHA1_KEY_DERIVATION_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 20 # SPKM & SLL added capabilities +CKM_GENERIC_SECRET_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 21 # Generation of secret keys +CKM_CAST5_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 22 # Entrust added capabilities +CKM_CAST5_ECB_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 23 # Entrust added capabilities +CKM_CAST5_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 24 # Entrust added capabilities +CKM_CAST5_MAC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 25 # Entrust added capabilities +CKM_PBE_SHA1_CAST5_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 26 # Entrust added capabilities +CKM_KEY_TRANSLATION= CKM_VENDOR_DEFINED_OLD_XXX + 27 # Entrust added capabilities +CKM_XOR_BASE_AND_KEY= CKM_VENDOR_DEFINED + 27 +CKM_2DES_KEY_DERIVATION= CKM_VENDOR_DEFINED_OLD_XXX + 28 # Custom Gemplus Capabilities +CKM_INDIRECT_LOGIN_REENCRYPT= CKM_VENDOR_DEFINED_OLD_XXX + 29 # Used for indirect login +CKM_PBE_SHA1_DES3_EDE_CBC_OLD= CKM_VENDOR_DEFINED_OLD_XXX + 30 +CKM_PBE_SHA1_DES2_EDE_CBC_OLD= CKM_VENDOR_DEFINED_OLD_XXX + 31 +CKM_HAS160= (CKM_VENDOR_DEFINED + 0x100) +CKM_KCDSA_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x101) +CKM_KCDSA_HAS160= (CKM_VENDOR_DEFINED + 0x102) +CKM_SEED_KEY_GEN= (CKM_VENDOR_DEFINED + 0x103) +CKM_SEED_ECB= (CKM_VENDOR_DEFINED + 0x104) +CKM_SEED_CBC= (CKM_VENDOR_DEFINED + 0x105) +CKM_SEED_CBC_PAD= (CKM_VENDOR_DEFINED + 0x106) +CKM_SEED_MAC= (CKM_VENDOR_DEFINED + 0x107) +CKM_SEED_MAC_GENERAL= (CKM_VENDOR_DEFINED + 0x108) +CKM_KCDSA_SHA1= (CKM_VENDOR_DEFINED + 0x109) +CKM_KCDSA_SHA224= (CKM_VENDOR_DEFINED + 0x10A) +CKM_KCDSA_SHA256= (CKM_VENDOR_DEFINED + 0x10B) +CKM_KCDSA_SHA384= (CKM_VENDOR_DEFINED + 0x10C) +CKM_KCDSA_SHA512= (CKM_VENDOR_DEFINED + 0x10D) +CKM_KCDSA_PARAMETER_GEN= (CKM_VENDOR_DEFINED + 0x10F) +CKM_SHA224_RSA_PKCS_OLD= (CKM_VENDOR_DEFINED + 0x110) +CKM_SHA224_RSA_PKCS_PSS_OLD= (CKM_VENDOR_DEFINED + 0x111) +CKM_SHA224_OLD= (CKM_VENDOR_DEFINED + 0x112) +CKM_SHA224_HMAC_OLD= (CKM_VENDOR_DEFINED + 0x113) +CKM_SHA224_HMAC_GENERAL_OLD= (CKM_VENDOR_DEFINED + 0x114) +CKM_SHA224_KEY_DERIVATION_OLD= (CKM_VENDOR_DEFINED + 0x115) +CKM_DES3_CTR= (CKM_VENDOR_DEFINED + 0x116) +CKM_AES_CFB8= (CKM_VENDOR_DEFINED + 0x118) +CKM_AES_CFB128= (CKM_VENDOR_DEFINED + 0x119) +CKM_AES_OFB= (CKM_VENDOR_DEFINED + 0x11a) +CKM_AES_CTR= (CKM_VENDOR_DEFINED + 0x11b) +CKM_AES_GCM= (CKM_VENDOR_DEFINED + 0x11c) +CKM_ARIA_CFB8= (CKM_VENDOR_DEFINED + 0x11d) +CKM_ARIA_CFB128= (CKM_VENDOR_DEFINED + 0x11e) +CKM_ARIA_OFB= (CKM_VENDOR_DEFINED + 0x11f) +CKM_ARIA_CTR= (CKM_VENDOR_DEFINED + 0x120) +CKM_ARIA_GCM= (CKM_VENDOR_DEFINED + 0x121) +CKM_ECDSA_SHA224= (CKM_VENDOR_DEFINED + 0x122) +CKM_ECDSA_SHA256= (CKM_VENDOR_DEFINED + 0x123) +CKM_ECDSA_SHA384= (CKM_VENDOR_DEFINED + 0x124) +CKM_ECDSA_SHA512= (CKM_VENDOR_DEFINED + 0x125) +CKM_AES_GMAC= (CKM_VENDOR_DEFINED + 0x126) +CKM_ARIA_CMAC= (CKM_VENDOR_DEFINED + 0x128) +CKM_ARIA_CMAC_GENERAL= (CKM_VENDOR_DEFINED + 0x129) +CKM_SEED_CMAC= (CKM_VENDOR_DEFINED + 0x12c) +CKM_SEED_CMAC_GENERAL= (CKM_VENDOR_DEFINED + 0x12d) +CKM_DES3_CBC_PAD_IPSEC_OLD= 0x00000137 +CKM_DES3_CBC_PAD_IPSEC= (CKM_VENDOR_DEFINED + 0x12e) +CKM_AES_CBC_PAD_IPSEC_OLD= 0x00001089 +CKM_AES_CBC_PAD_IPSEC= (CKM_VENDOR_DEFINED + 0x12f) +CKM_ARIA_L_ECB= (CKM_VENDOR_DEFINED + 0x130) +CKM_ARIA_L_CBC= (CKM_VENDOR_DEFINED + 0x131) +CKM_ARIA_L_CBC_PAD= (CKM_VENDOR_DEFINED + 0x132) +CKM_ARIA_L_MAC= (CKM_VENDOR_DEFINED + 0x133) +CKM_ARIA_L_MAC_GENERAL= (CKM_VENDOR_DEFINED + 0x134) +CKM_SHA224_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x135) +CKM_SHA256_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x136) +CKM_SHA384_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x137) +CKM_SHA512_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x138) +CKM_SHA1_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x139) +CKM_SHA224_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13a) +CKM_SHA256_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13b) +CKM_SHA384_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13c) +CKM_SHA512_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13d) +CKM_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13e) +CKM_DSA_SHA224= (CKM_VENDOR_DEFINED + 0x140) #DH -moved here to keep ECDSA SHA 2 same as FW4 +CKM_DSA_SHA256= (CKM_VENDOR_DEFINED + 0x141) +CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x142) +CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x143) +CKM_SEED_CTR= (CKM_VENDOR_DEFINED + 0x144) +CKM_AES_CBC_PAD_EXTRACT= (CKM_VENDOR_DEFINED + 0x200) +CKM_AES_CBC_PAD_INSERT= (CKM_VENDOR_DEFINED + 0x201) +CKM_AES_CBC_PAD_EXTRACT_FLATTENED= (CKM_VENDOR_DEFINED + 0x202) +CKM_AES_CBC_PAD_INSERT_FLATTENED= (CKM_VENDOR_DEFINED + 0x203) +CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL= (CKM_VENDOR_DEFINED + 0x204) +CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL= (CKM_VENDOR_DEFINED + 0x205) +CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM=(CKM_VENDOR_DEFINED + 0x502) +CKM_ECIES= (CKM_VENDOR_DEFINED + 0xA00) +CKM_XOR_BASE_AND_DATA_W_KDF= (CKM_VENDOR_DEFINED + 0xA01) +CKM_NIST_PRF_KDF= (CKM_VENDOR_DEFINED + 0xA02) +CKM_PRF_KDF= (CKM_VENDOR_DEFINED + 0xA03) +CKDHP_STANDARD= 0x00000001 +CKDHP_ECDH1_COFACTOR= 0x00000001 +CKDHP_MODIFIED= 0x00000002 # Not implemented */ +CKDHP_ECDH1= 0x00000003 +CKES_XOR= 0x00000001 +CKES_DES3_CBC_PAD= 0x00000002 +CKES_AES_CBC_PAD= 0x00000003 +CKES_DES3_CBC= 0x00000004 +CKES_AES_CBC= 0x00000005 +CKMS_HMAC_SHA1= 0x00000001 +CKMS_SHA1= 0x00000002 +CKMS_HMAC_SHA224= 0x00000003 +CKMS_SHA224= 0x00000004 +CKMS_HMAC_SHA256= 0x00000005 +CKMS_SHA256= 0x00000006 +CKMS_HMAC_SHA384= 0x00000007 +CKMS_SHA384= 0x00000008 +CKMS_HMAC_SHA512= 0x00000009 +CKMS_SHA512= 0x0000000a +CKMS_HMAC_RIPEMD160= 0x0000000b +CKMS_RIPEMD160= 0x0000000c +CK_NIST_PRF_KDF_DES3_CMAC= 0x00000001 +CK_NIST_PRF_KDF_AES_CMAC= 0x00000002 +CK_PRF_KDF_ARIA_CMAC= 0x00000003 +CK_PRF_KDF_SEED_CMAC= 0x00000004 +LUNA_PRF_KDF_ENCODING_SCHEME_1= 0x00000000 +LUNA_PRF_KDF_ENCODING_SCHEME_2= 0x00000001 +CKR_INSERTION_CALLBACK_NOT_SUPPORTED=0x00000141 +CKR_FUNCTION_PARALLEL= 0x0052 +CKR_SESSION_EXCLUSIVE_EXISTS= 0x00B2 +CKR_RC_ERROR= (CKR_VENDOR_DEFINED + 0x04) +CKR_CONTAINER_HANDLE_INVALID= (CKR_VENDOR_DEFINED + 0x05) +CKR_TOO_MANY_CONTAINERS= (CKR_VENDOR_DEFINED + 0x06) +CKR_USER_LOCKED_OUT= (CKR_VENDOR_DEFINED + 0x07) +CKR_CLONING_PARAMETER_ALREADY_EXISTS=(CKR_VENDOR_DEFINED + 0x08) +CKR_CLONING_PARAMETER_MISSING= (CKR_VENDOR_DEFINED + 0x09) +CKR_CERTIFICATE_DATA_MISSING= (CKR_VENDOR_DEFINED + 0x0a) +CKR_CERTIFICATE_DATA_INVALID= (CKR_VENDOR_DEFINED + 0x0b) +CKR_ACCEL_DEVICE_ERROR= (CKR_VENDOR_DEFINED + 0x0c) +CKR_WRAPPING_ERROR= (CKR_VENDOR_DEFINED + 0x0d) +CKR_UNWRAPPING_ERROR= (CKR_VENDOR_DEFINED + 0x0e) +CKR_MAC_MISSING= (CKR_VENDOR_DEFINED + 0x0f) +CKR_DAC_POLICY_PID_MISMATCH= (CKR_VENDOR_DEFINED + 0x10) +CKR_DAC_MISSING= (CKR_VENDOR_DEFINED + 0x11) +CKR_BAD_DAC= (CKR_VENDOR_DEFINED + 0x12) +CKR_SSK_MISSING= (CKR_VENDOR_DEFINED + 0x13) +CKR_BAD_MAC= (CKR_VENDOR_DEFINED + 0x14) +CKR_DAK_MISSING= (CKR_VENDOR_DEFINED + 0x15) +CKR_BAD_DAK= (CKR_VENDOR_DEFINED + 0x16) +CKR_SIM_AUTHORIZATION_FAILED= (CKR_VENDOR_DEFINED + 0x17) +CKR_SIM_VERSION_UNSUPPORTED= (CKR_VENDOR_DEFINED + 0x18) +CKR_SIM_CORRUPT_DATA= (CKR_VENDOR_DEFINED + 0x19) +CKR_USER_NOT_AUTHORIZED= (CKR_VENDOR_DEFINED + 0x1a) +CKR_MAX_OBJECT_COUNT_EXCEEDED= (CKR_VENDOR_DEFINED + 0x1b) +CKR_SO_LOGIN_FAILURE_THRESHOLD= (CKR_VENDOR_DEFINED + 0x1c) +CKR_SIM_AUTHFORM_INVALID= (CKR_VENDOR_DEFINED + 0x1d) +CKR_CITS_DAK_MISSING= (CKR_VENDOR_DEFINED + 0x1e) +CKR_UNABLE_TO_CONNECT= (CKR_VENDOR_DEFINED + 0x1f) +CKR_PARTITION_DISABLED= (CKR_VENDOR_DEFINED + 0x20) +CKR_CALLBACK_ERROR= (CKR_VENDOR_DEFINED + 0x21) +CKR_SECURITY_PARAMETER_MISSING= (CKR_VENDOR_DEFINED + 0x22) +CKR_SP_TIMEOUT= (CKR_VENDOR_DEFINED + 0x23) +CKR_TIMEOUT= (CKR_VENDOR_DEFINED + 0x24) +CKR_ECC_UNKNOWN_CURVE= (CKR_VENDOR_DEFINED + 0x25) +CKR_MTK_ZEROIZED= (CKR_VENDOR_DEFINED + 0x26) +CKR_MTK_STATE_INVALID= (CKR_VENDOR_DEFINED + 0x27) +CKR_INVALID_ENTRY_TYPE= (CKR_VENDOR_DEFINED + 0x28) +CKR_MTK_SPLIT_INVALID= (CKR_VENDOR_DEFINED + 0x29) +CKR_HSM_STORAGE_FULL= (CKR_VENDOR_DEFINED + 0x2a) +CKR_DEVICE_TIMEOUT= (CKR_VENDOR_DEFINED + 0x2b) +CKR_CONTAINER_OBJECT_STORAGE_FULL= (CKR_VENDOR_DEFINED + 0x2C) +CKR_PED_CLIENT_NOT_RUNNING= (CKR_VENDOR_DEFINED + 0x2D) +CKR_PED_UNPLUGGED= (CKR_VENDOR_DEFINED + 0x2E) +CKR_ECC_POINT_INVALID= (CKR_VENDOR_DEFINED + 0x2F) +CKR_OPERATION_NOT_ALLOWED= (CKR_VENDOR_DEFINED + 0x30) +CKR_LICENSE_CAPACITY_EXCEEDED= (CKR_VENDOR_DEFINED + 0x31) +CKR_LOG_FILE_NOT_OPEN= (CKR_VENDOR_DEFINED + 0x32) +CKR_LOG_FILE_WRITE_ERROR= (CKR_VENDOR_DEFINED + 0x33) +CKR_LOG_BAD_FILE_NAME= (CKR_VENDOR_DEFINED + 0x34) +CKR_LOG_FULL= (CKR_VENDOR_DEFINED + 0x35) +CKR_LOG_NO_KCV= (CKR_VENDOR_DEFINED + 0x36) +CKR_LOG_BAD_RECORD_HMAC= (CKR_VENDOR_DEFINED + 0x37) +CKR_LOG_BAD_TIME= (CKR_VENDOR_DEFINED + 0x38) +CKR_LOG_AUDIT_NOT_INITIALIZED= (CKR_VENDOR_DEFINED + 0x39) +CKR_LOG_RESYNC_NEEDED= (CKR_VENDOR_DEFINED + 0x3A) +CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS= (CKR_VENDOR_DEFINED + 0x3B) +CKR_AUDIT_LOGIN_FAILURE_THRESHOLD= (CKR_VENDOR_DEFINED + 0x3C) +CKR_INVALID_FUF_TARGET= (CKR_VENDOR_DEFINED + 0x3D) +CKR_INVALID_FUF_HEADER= (CKR_VENDOR_DEFINED + 0x3E) +CKR_INVALID_FUF_VERSION= (CKR_VENDOR_DEFINED + 0x3F) +CKR_ECC_ECC_RESULT_AT_INF= (CKR_VENDOR_DEFINED + 0x40) +CKR_AGAIN= (CKR_VENDOR_DEFINED + 0x41) +CKR_TOKEN_COPIED= (CKR_VENDOR_DEFINED + 0x42) +CKR_SLOT_NOT_EMPTY= (CKR_VENDOR_DEFINED + 0x43) +CKR_USER_ALREADY_ACTIVATED= (CKR_VENDOR_DEFINED + 0x44) +CKR_OBJECT_READ_ONLY= (CKR_VENDOR_DEFINED + 0x114) +CKR_KEY_NOT_ACTIVE= (CKR_VENDOR_DEFINED + 0x136) +CKO_TOKEN_ROLE_POLICY_SET= (CKO_VENDOR_DEFINED + 0x0001) +CKO_TOKEN_ROLE_POLICY= (CKO_VENDOR_DEFINED + 0x0002) +CKO_TOKEN_ROLE_DESCRIPTOR= (CKO_VENDOR_DEFINED + 0x0003) +CKO_TOKEN_ROLE_STATE= (CKO_VENDOR_DEFINED + 0x0004) +CKO_CERTIFICATE_REQUEST= (CKO_VENDOR_DEFINED + 0x0201) +CKO_CRL= (CKO_VENDOR_DEFINED + 0x0202) +CKO_ADAPTER= (CKO_VENDOR_DEFINED + 0x020A) +CKO_SLOT= (CKO_VENDOR_DEFINED + 0x020B) +CKO_FM= (CKO_VENDOR_DEFINED + 0x020C) +CKS_RO_SO_FUNCTIONS= 5 # still in PKCS #11 space */ +CKS_RO_VENDOR_DEFINED= 0x80000000 +CKS_RW_AUDIT_FUNCTIONS= CKS_RW_SO_FUNCTIONS +CAF_ROLE_STATE_INITIALIZED= 0x01 +CAF_ROLE_STATE_LOCKED_OUT= 0x02 +CAF_ROLE_STATE_ACTIVATED= 0x04 +CAF_ROLE_STATE_HAS_RDK= 0x08 +CAF_ROLE_STATE_PIN_CHANGE= 0x10 +CKA_ROLE_AUTH_NONE= 0x00 +CKA_ROLE_AUTH_PASSWORD= 0x01 +CKA_ROLE_AUTH_PED= 0x02 +CKA_ROLE_AUTH_INVALID= 0xFF +CAF_M_OF_N_REQUIRED= 0x00000001 +CAF_M_OF_N_ACTIVATED= 0x00000002 +CAF_M_OF_N_GENERATED= 0x00000004 +CAF_M_OF_N_CLONEABLE= 0x00000008 +CKCAO_Encrypt=0 +CKCAO_Decrypt=1 +CKCAO_Sign= 2 +CKCAO_Verify= 3 +CKCAO_Digest= 4 +CK_HA_MAX_MEMBERS= 32 +CKHSC_CERT_TYPE_TCTRUST_MAC= 0x00000001 +CKHSC_CERT_TYPE_TCTRUST_DAC= 0x00000002 +CKHSC_CERT_TYPE_CITS_ROOT= 0x00000003 +CKHSC_CERT_TYPE_CITS_MICHOC= 0x00000004 +CKHSC_CERT_TYPE_CITS_DAC= 0x00000005 +CKHSC_CERT_TYPE_ECC_MIC= 0x00000006 +CKHSC_CERT_TYPE_ECC_HOC= 0x00000007 +CKHSC_CERT_TYPE_ECC_DAC= 0x00000008 +CKHSC_CERT_TYPE_TWC= 0x00000009 +CKHSC_CERT_TYPE_TWC2= 0x0000000A +CKHSC_CERT_TYPE_TWC3= 0x0000000B +CKA_SIM_NO_AUTHORIZATION=0 # no authorization needed +CKA_SIM_PASSWORD= 1 # plain-text passwords +CKA_SIM_CHALLENGE= 2 # challenge secrets emitted through the secure port +CKA_SIM_SECURE_PORT= 3 # PED keys +CKA_SIM_PORTABLE_NO_AUTHORIZATION=4 # no authorization needed, portable +CKA_SIM_PORTABLE_PASSWORD= 5 # plain-text passwords, portable +CKA_SIM_PORTABLE_CHALLENGE= 6 # challenge secrets emitted through the secure port, portable +CKA_SIM_PORTABLE_SECURE_PORT= 7 # PED keys, portable +CK_NULL_ELEMENT= (-1) +CK_CRYPTOKI_ELEMENT= 0x00000000 +CK_PARAM_ELEMENT= 0x00000001 +CK_CONTAINER_ACTIVATION_ELEMENT=0x00000002 +CK_MOFN_ACTIVATION_ELEMENT= 0x00000003 +CK_CONTAINER_ELEMENT= 0x00000004 +CK_CLONING_PART1_OVERHEAD= 8192 +CK_CLONING_PART2_OVERHEAD= 76 +CK_FLATTENED_OBJECT_OVERHEAD= 3264 +CK_STORAGE_HOST= 0x00000000 +CK_STORAGE_PED_USB_MEMORY= 0x00000001 +CK_STORAGE_HSM_USB_MEMORY= 0x00000002 +CK_MTK_STATE_FLAG_RESPLIT_ABORTED= 0x00000001 +CK_MTK_STATE_FLAG_HARD_ZEROIZE= 0x00000002 +CK_MTK_STATE_FLAG_SOFT_ZEROIZE= 0x00000004 +CK_MTK_STATE_FLAG_LOCKED= 0x00000008 +CK_MAX_CLUSTER_MEMBERS= 8 +AKEP2_XDH_SIZE= 128 # size of LKM public key +AKEP2_MAX_DIGEST_SIZE= 32 +AKEP2_NID_SIZE= 20 +CK_PED_ID_LOCAL= 0x0000 +CK_PED_ID_MAX= 0xFFFE +CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT= 0x00000001 +CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET= 0x00000002 diff --git a/pycryptoki/dictionary_handling.py b/pycryptoki/dictionary_handling.py index dfe1e30..c362fc6 100755 --- a/pycryptoki/dictionary_handling.py +++ b/pycryptoki/dictionary_handling.py @@ -1,16 +1,16 @@ -''' -Created on Oct 3, 2012 - -@author: root -''' - -class CDict: - - dict_val = None - - - - def __init__(self, dict_val): - self.dict_val = dict_val - +''' +Created on Oct 3, 2012 + +@author: root +''' + +class CDict: + + dict_val = None + + + + def __init__(self, dict_val): + self.dict_val = dict_val + \ No newline at end of file diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 5d5f03e..50c26e0 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -1,406 +1,405 @@ -""" -Methods related to encrypting data/files. -""" -from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ - C_EncryptInit, CK_BYTE_PTR, C_Encrypt, CK_RSA_PKCS_OAEP_PARAMS -from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer -from defines import CKM_DES_CBC, CKM_DES3_CBC, CKM_CAST3_CBC, CKM_DES_ECB, \ - CKM_DES3_ECB, CKM_CAST3_ECB, CKM_RC2_ECB, CKM_RC2_CBC, CKM_CAST5_ECB, \ - CKM_CAST5_CBC, CKM_RC4, CKM_RC5_ECB, CKM_RC5_CBC, CKM_RSA_X_509, CKM_DES_CBC_PAD, \ - CKM_DES3_CBC_PAD, CKM_DES3_CBC_PAD_IPSEC, CKM_RC2_CBC_PAD, CKM_RC5_CBC_PAD, \ - CKM_CAST3_CBC_PAD, CKM_CAST5_CBC_PAD, CKM_SEED_ECB, CKM_SEED_CBC, \ - CKM_SEED_CBC_PAD, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, \ - CKM_AES_CBC_PAD_IPSEC, CKM_ARIA_ECB, CKM_ARIA_CBC, CKM_ARIA_CBC_PAD, \ - CKM_RSA_PKCS, CKM_DES_CFB8, CKM_DES_CFB64, CKM_DES_OFB64, CKM_AES_CFB8, \ - CKM_AES_CFB128, CKM_AES_OFB, CKM_ARIA_CFB8, CKM_ARIA_CFB128, CKM_ARIA_OFB, \ - CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ - CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED -from pycryptoki.attributes import get_byte_list_from_python_list, \ - convert_CK_CHAR_to_string, convert_ck_char_array_to_string, Attributes -from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ - C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ - C_DecryptUpdate, C_DecryptFinal -from pycryptoki.test_functions import make_error_handle_function -import logging - -logger = logging.getLogger(__name__) - -def get_encryption_mechanism(encryption_flavor): - ''' - Returns the CK_MECHANISM() object associated with a given encryption flavor - #TODO: Only works with one kind of encryption mechanism currently. - - @param encryption_flavor: The flavor of the encryption that the mechanism needs - to encrypt for. - @return: Returns a CTypes CK_Mechanism given the encryption flavour that you have passed in - ''' - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(encryption_flavor) - mech.pParameter = 0 - mech.usParameterLen = CK_ULONG(0) - - iv_required = 1 - RC2_params_required = 2 - RC2CBC_params_required = 3 - RC5_params_required = 4 - RC5CBC_params_required = 5 - IV16_required = 6 - GCM_params_required = 7 - xorkdf_params_required = 8 - OAEP_params_required = 9 - ECIES_params_required = 10 - - encryption_flavors = {CKM_DES_CBC : iv_required, - CKM_DES3_CBC : iv_required, - CKM_CAST3_CBC : iv_required, - CKM_DES_ECB : 0, - CKM_DES3_ECB : 0, - CKM_CAST3_ECB : 0, - CKM_RC2_ECB : RC2_params_required, - CKM_RC2_CBC : RC2CBC_params_required , - CKM_CAST5_ECB : 0, - CKM_CAST5_CBC : iv_required, - CKM_RC4 : 0, - CKM_RC5_ECB : RC5_params_required, - CKM_RC5_CBC : RC5CBC_params_required, - CKM_RSA_X_509 : 0, - CKM_DES_CBC_PAD : iv_required, - CKM_DES3_CBC_PAD : iv_required, - CKM_DES3_CBC_PAD_IPSEC : iv_required, - CKM_RC2_CBC_PAD : RC2CBC_params_required, - CKM_RC5_CBC_PAD : RC5CBC_params_required, - CKM_CAST3_CBC_PAD : iv_required, - CKM_CAST5_CBC_PAD : iv_required, - CKM_SEED_ECB : 0, - CKM_SEED_CBC : IV16_required, - CKM_SEED_CBC_PAD : IV16_required, - CKM_AES_ECB : 0, - CKM_AES_CBC : IV16_required, - CKM_AES_CBC_PAD : IV16_required, - CKM_AES_CBC_PAD_IPSEC : IV16_required, - CKM_ARIA_ECB : IV16_required, - CKM_ARIA_CBC : IV16_required, - CKM_ARIA_CBC_PAD : IV16_required, - CKM_RSA_PKCS : 0, - CKM_DES_CFB8 : iv_required, - CKM_DES_CFB64 : iv_required, - CKM_DES_OFB64 : iv_required, - CKM_AES_CFB8 : iv_required, - CKM_AES_CFB128 : iv_required, - CKM_AES_OFB : iv_required, - CKM_ARIA_CFB8 : iv_required, - CKM_ARIA_CFB128 : iv_required, - CKM_ARIA_OFB : iv_required, - CKM_AES_GCM : GCM_params_required, - CKM_XOR_BASE_AND_DATA_W_KDF : xorkdf_params_required, - CKM_RSA_PKCS_OAEP : OAEP_params_required, - CKM_ECIES : ECIES_params_required} - - iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] - iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] - - params = encryption_flavors.get(encryption_flavor) - if params == iv_required: - mech.pParameter = get_byte_list_from_python_list(iv) - mech.usParameterLen = CK_ULONG(len(iv)) - elif params == RC2_params_required: - num_of_effective_bits = 0 - rc2_params = (c_char * 2)() - rc2_params[0] = c_char(int(num_of_effective_bits, 8) & 0xff) - rc2_params[1] = c_char(int((num_of_effective_bits >> 8), 8) & 0xff) - rc2_params = create_string_buffer("", 2) - mech.pParameter = cast(rc2_params, c_void_p) - mech.usParameterLen = CK_ULONG(len(rc2_params)) - pass - elif params == RC2CBC_params_required: - num_of_effective_bits = 0 - pass - elif params == RC5_params_required: - num_rounds = 0 - pass - elif params == RC5CBC_params_required: - num_rounds = 0 - pass - elif params == IV16_required: - mech.pParameter = get_byte_list_from_python_list(iv16) - mech.usParameterLen = CK_ULONG(len(iv16)) - elif params == GCM_params_required: - pass - elif params == xorkdf_params_required: - pass - elif params == OAEP_params_required: - p = CK_RSA_PKCS_OAEP_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA_1) - p.mgf = CK_ULONG(CKG_MGF1_SHA1) - p.source = CK_ULONG(CKZ_DATA_SPECIFIED) - p.pSourceData = 0 - p.ulSourceDataLen = 0 - - mech.pParameter = cast(pointer(p), CK_VOID_PTR) - mech.usParameterLen = CK_ULONG(sizeof(p)) - elif params == ECIES_params_required: - pass - - return mech - -def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - ''' - Encrypts data with a given key and encryption flavor - encryption flavors - @param session: Current session - @param encryption_flavor: The flavor of encryption to use - @param h_key: The key handle to encrypt the data with - @param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param mech: The mechanism to use, if None will try to look up a - default mechanism based on the encryption flavor - @return: Returns the result code of the operation, a python string representing the encrypted data - ''' - - if mech == None: - mech = get_encryption_mechanism(encryption_flavor) - - #if a list is passed out do an encrypt operation on each string in the list, otherwise just do one encrypt operation - is_multi_part_operation = isinstance(data_to_encrypt, list) or isinstance(data_to_encrypt, tuple) - - #Initialize encryption - ret = C_EncryptInit(h_session, byref(mech), CK_ULONG(h_key)) - if ret != CKR_OK: return ret, None - - if is_multi_part_operation: - encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, C_EncryptFinal, data_to_encrypt) - else: - plain_data_length = len(data_to_encrypt) - plain_data = get_c_data_to_sign_or_encrypt(data_to_encrypt) - - #Get the length of the encrypted data - encrypted_data_length = CK_ULONG() - ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), None, byref(encrypted_data_length)) - if ret != CKR_OK: return ret, None - - output = create_string_buffer("", encrypted_data_length.value) - encrypted_data = cast(output, CK_BYTE_PTR) - - #Encrypt data - ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), encrypted_data, byref(encrypted_data_length)) - - #Convert encrypted data into a python string - ck_char_array = encrypted_data._objects.values()[0] - encrypted_python_string = convert_ck_char_array_to_string(ck_char_array) - - return ret, encrypted_python_string - -c_encrypt_ex = make_error_handle_function(c_encrypt) - -def _split_string_into_list(python_string, block_size): - ''' - Splits a string into a list of equal size chunks - - @param python_string: The string to divide - @param block_size: The size of the blocks to divide the string into - @return: A list of strings of block_size - ''' - return_list = [] - total_length = len(python_string) - for index in range(0, (total_length / block_size)): - start_index = index * block_size - end_index = min(start_index + block_size, total_length) - return_list.append(python_string[start_index : end_index]) - - return return_list - -def _get_string_from_list(list_of_strings): - ''' - Takes a list of strings and returns a single concatenated string. - - @param list_of_strings: A list of strings to be concatenated - @return: Single string representing the concatenated list - ''' - large_string = '' - for substring in list_of_strings: - large_string += substring - - return large_string - -def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech = None): - ''' - Decrypts some data - - @param h_session: The session to use - @param decryption_flavor: The decryption flavor to create a new mechanism with if no mechanism - is provided - @param h_key: The handle of the key to use to decrypt - @param mech: The mechanism, if none is provided a blank one will be provided based on the decryption_flavor - - @return: The result code, a python string of the decrypted data - ''' - - #Get the mechanism - if mech == None: - mech = get_encryption_mechanism(decryption_flavor) - - #Initialize Decrypt - ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) - if ret != CKR_OK: return ret, None - - #if a list is passed out do a decrypt operation on each string in the list, otherwise just do one decrypt operation - is_multi_part_operation = isinstance(encrypted_data, list) or isinstance(encrypted_data, tuple) - - if is_multi_part_operation: - python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, encrypted_data) - else: - - #Get the length of the final data - # NOTE: The "Conventions for functions returning output in a variable-length buffer" - # section of the PKCS#11 spec says that the length returned in this - # case (no output buffer given to C_Decrypt) can exceed the precise - # number of bytes needed. So the python string that's returned in the - # end needs to be adjusted based on the second called to C_Decrypt - # which will have the right length - plain_data_len = CK_ULONG() - c_encrypted_data = get_c_data_to_sign_or_encrypt(encrypted_data) - encrypted_data_len = len(encrypted_data) - ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), None, byref(plain_data_len)) - - if ret != CKR_OK: return ret, None - - output = create_string_buffer("", plain_data_len.value) - plain_data = cast(output, CK_BYTE_PTR) - - #Decrypt data - ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), plain_data, byref(plain_data_len)) - if ret != CKR_OK: return ret, None - - #Convert the decrypted data to a python readable format - ck_char_array = plain_data._objects.values()[0] - python_string = convert_ck_char_array_to_string(ck_char_array) - # Adjust the string based on the updated plain_data_len - python_string = python_string[:plain_data_len.value] - - return ret, python_string - -c_decrypt_ex= make_error_handle_function(c_decrypt) - -def do_multipart_operation(h_session, c_update_function, c_finalize_function, input_data_list): - ''' - Some code which will do a multipart encrypt or decrypt since they are the same - with just different functions called - ''' - max_data_chunk_size = 0xfff0 - plain_data_len = len(_get_string_from_list(input_data_list)) - - remaining_length = plain_data_len - python_string = '' - i = 0 - while remaining_length > 0: - current_chunk = input_data_list[i] - - #Prepare arguments for decrypt update operation - current_chunk_len = min(len(current_chunk), remaining_length) - - if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - - out_data = create_string_buffer('', max_data_chunk_size) - out_data_len = CK_ULONG(max_data_chunk_size) - if (out_data_len.value > 0): - data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) - - ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len), cast(out_data, CK_BYTE_PTR), byref(out_data_len)) - if ret != CKR_OK: return ret, None - - remaining_length -= current_chunk_len - - #Get the output - ck_char_array = out_data._objects.values()[0] - python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] - i += 1 - - #Finalizing multipart decrypt operation - out_data_len = CK_ULONG(max_data_chunk_size) - output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) - ret = c_finalize_function(h_session, output, byref(out_data_len)) - - #Get output - ck_char_array = output._objects.values()[0] - if (out_data_len.value > 0): - python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] - - return python_string - -def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech = None): - ''' - Function which wraps a key - - @param h_session: The session to use - @param h_wrapping_key: The handle of the key to use to wrap another key - @param h_key: The key to wrap - @param encryption_flavor: The encryption flavor to create a new mechanism with if no mechanism - is provided - @param mech: The mechanism, if none is provided a blank one will be provided based on the encryption flavor - - @return: The result code, a ctypes byte array representing the new key - ''' - if mech == None: - mech = get_encryption_mechanism(encryption_flavor) - - #Get the size of the key - wrapped_key_length = CK_ULONG() - ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), None, byref(wrapped_key_length)) - if ret != CKR_OK: return ret, None - - #Actually wrap the key - output = create_string_buffer("", wrapped_key_length.value) - wrapped_key_output = cast(output, CK_BYTE_PTR) - ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), wrapped_key_output, byref(wrapped_key_length)) - - return ret, wrapped_key_output._objects.values()[0] -c_wrap_key_ex = make_error_handle_function(c_wrap_key) - -def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech = None): - ''' - Function which unwraps a key - @param h_session: The session to use - @param h_wrapping_key: The wrapping key handle - @param wapped_key: The wrapped key in a ctypes CK_CHAR_PTR array - @param key_template: The python template representing the new key's template - @param encryption_flavor: If the mechanism is not specified it will create a - default one based on the encryption flavor - @param mech: The mechanism to use, if null a default one will be created based on the encryption_flavor - - @return: The result code, the handle of the unwrapped key - ''' - if mech == None: - mech = get_encryption_mechanism(encryption_flavor) - - c_template = Attributes(key_template).get_c_struct() - byte_wrapped_key = cast(wrapped_key, CK_BYTE_PTR) - h_output_key = CK_ULONG() - ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), byte_wrapped_key, CK_ULONG(len(wrapped_key)), - c_template, CK_ULONG(len(key_template)), byref(h_output_key)) - - return ret, h_output_key.value -c_unwrap_key_ex = make_error_handle_function(c_unwrap_key) - -def get_c_data_to_sign_or_encrypt(python_data): - ''' - Function which gets the C data representation of some python data - - @param python_data: The python data to get a c representation of - - @return: A C byte pointer pointing to the C representation of the - python data - ''' - - c_data_to_sign = None - if isinstance(python_data, str): - c_data_to_sign = create_string_buffer(python_data) - c_data_to_sign = cast(c_data_to_sign, CK_BYTE_PTR) - else: - raise Exception("Please extend this function to support the type of data " + type(python_data)) - - return c_data_to_sign - +""" +Methods related to encrypting data/files. +""" +from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ + C_EncryptInit, CK_BYTE_PTR, C_Encrypt, CK_RSA_PKCS_OAEP_PARAMS +from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer +from defines import CKM_DES_CBC, CKM_DES3_CBC, CKM_CAST3_CBC, CKM_DES_ECB, \ + CKM_DES3_ECB, CKM_CAST3_ECB, CKM_RC2_ECB, CKM_RC2_CBC, CKM_CAST5_ECB, \ + CKM_CAST5_CBC, CKM_RC4, CKM_RC5_ECB, CKM_RC5_CBC, CKM_RSA_X_509, CKM_DES_CBC_PAD, \ + CKM_DES3_CBC_PAD, CKM_DES3_CBC_PAD_IPSEC, CKM_RC2_CBC_PAD, CKM_RC5_CBC_PAD, \ + CKM_CAST3_CBC_PAD, CKM_CAST5_CBC_PAD, CKM_SEED_ECB, CKM_SEED_CBC, \ + CKM_SEED_CBC_PAD, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, \ + CKM_AES_CBC_PAD_IPSEC, CKM_ARIA_ECB, CKM_ARIA_CBC, CKM_ARIA_CBC_PAD, \ + CKM_RSA_PKCS, CKM_DES_CFB8, CKM_DES_CFB64, CKM_DES_OFB64, CKM_AES_CFB8, \ + CKM_AES_CFB128, CKM_AES_OFB, CKM_ARIA_CFB8, CKM_ARIA_CFB128, CKM_ARIA_OFB, \ + CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ + CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED +from pycryptoki.attributes import get_byte_list_from_python_list, \ + convert_CK_CHAR_to_string, convert_ck_char_array_to_string, Attributes +from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ + C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ + C_DecryptUpdate, C_DecryptFinal +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def get_encryption_mechanism(encryption_flavor): + ''' + Returns the CK_MECHANISM() object associated with a given encryption flavor + #TODO: Only works with one kind of encryption mechanism currently. + + @param encryption_flavor: The flavor of the encryption that the mechanism needs + to encrypt for. + @return: Returns a CTypes CK_Mechanism given the encryption flavour that you have passed in + ''' + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(encryption_flavor) + mech.pParameter = 0 + mech.usParameterLen = CK_ULONG(0) + + iv_required = 1 + RC2_params_required = 2 + RC2CBC_params_required = 3 + RC5_params_required = 4 + RC5CBC_params_required = 5 + IV16_required = 6 + GCM_params_required = 7 + xorkdf_params_required = 8 + OAEP_params_required = 9 + ECIES_params_required = 10 + + encryption_flavors = {CKM_DES_CBC : iv_required, + CKM_DES3_CBC : iv_required, + CKM_CAST3_CBC : iv_required, + CKM_DES_ECB : 0, + CKM_DES3_ECB : 0, + CKM_CAST3_ECB : 0, + CKM_RC2_ECB : RC2_params_required, + CKM_RC2_CBC : RC2CBC_params_required , + CKM_CAST5_ECB : 0, + CKM_CAST5_CBC : iv_required, + CKM_RC4 : 0, + CKM_RC5_ECB : RC5_params_required, + CKM_RC5_CBC : RC5CBC_params_required, + CKM_RSA_X_509 : 0, + CKM_DES_CBC_PAD : iv_required, + CKM_DES3_CBC_PAD : iv_required, + CKM_DES3_CBC_PAD_IPSEC : iv_required, + CKM_RC2_CBC_PAD : RC2CBC_params_required, + CKM_RC5_CBC_PAD : RC5CBC_params_required, + CKM_CAST3_CBC_PAD : iv_required, + CKM_CAST5_CBC_PAD : iv_required, + CKM_SEED_ECB : 0, + CKM_SEED_CBC : IV16_required, + CKM_SEED_CBC_PAD : IV16_required, + CKM_AES_ECB : 0, + CKM_AES_CBC : IV16_required, + CKM_AES_CBC_PAD : IV16_required, + CKM_AES_CBC_PAD_IPSEC : IV16_required, + CKM_ARIA_ECB : IV16_required, + CKM_ARIA_CBC : IV16_required, + CKM_ARIA_CBC_PAD : IV16_required, + CKM_RSA_PKCS : 0, + CKM_DES_CFB8 : iv_required, + CKM_DES_CFB64 : iv_required, + CKM_DES_OFB64 : iv_required, + CKM_AES_CFB8 : iv_required, + CKM_AES_CFB128 : iv_required, + CKM_AES_OFB : iv_required, + CKM_ARIA_CFB8 : iv_required, + CKM_ARIA_CFB128 : iv_required, + CKM_ARIA_OFB : iv_required, + CKM_AES_GCM : GCM_params_required, + CKM_XOR_BASE_AND_DATA_W_KDF : xorkdf_params_required, + CKM_RSA_PKCS_OAEP : OAEP_params_required, + CKM_ECIES : ECIES_params_required} + + iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] + iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + + params = encryption_flavors.get(encryption_flavor) + if params == iv_required: + mech.pParameter = get_byte_list_from_python_list(iv) + mech.usParameterLen = CK_ULONG(len(iv)) + elif params == RC2_params_required: + num_of_effective_bits = 0 + rc2_params = (c_char * 2)() + rc2_params[0] = c_char(int(num_of_effective_bits, 8) & 0xff) + rc2_params[1] = c_char(int((num_of_effective_bits >> 8), 8) & 0xff) + rc2_params = create_string_buffer("", 2) + mech.pParameter = cast(rc2_params, c_void_p) + mech.usParameterLen = CK_ULONG(len(rc2_params)) + pass + elif params == RC2CBC_params_required: + num_of_effective_bits = 0 + pass + elif params == RC5_params_required: + num_rounds = 0 + pass + elif params == RC5CBC_params_required: + num_rounds = 0 + pass + elif params == IV16_required: + mech.pParameter = get_byte_list_from_python_list(iv16) + mech.usParameterLen = CK_ULONG(len(iv16)) + elif params == GCM_params_required: + pass + elif params == xorkdf_params_required: + pass + elif params == OAEP_params_required: + p = CK_RSA_PKCS_OAEP_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA_1) + p.mgf = CK_ULONG(CKG_MGF1_SHA1) + p.source = CK_ULONG(CKZ_DATA_SPECIFIED) + p.pSourceData = 0 + p.ulSourceDataLen = 0 + + mech.pParameter = cast(pointer(p), CK_VOID_PTR) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif params == ECIES_params_required: + pass + + return mech + +def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + ''' + Encrypts data with a given key and encryption flavor + encryption flavors + @param session: Current session + @param encryption_flavor: The flavor of encryption to use + @param h_key: The key handle to encrypt the data with + @param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param mech: The mechanism to use, if None will try to look up a + default mechanism based on the encryption flavor + @return: Returns the result code of the operation, a python string representing the encrypted data + ''' + + if mech == None: + mech = get_encryption_mechanism(encryption_flavor) + + #if a list is passed out do an encrypt operation on each string in the list, otherwise just do one encrypt operation + is_multi_part_operation = isinstance(data_to_encrypt, list) or isinstance(data_to_encrypt, tuple) + + #Initialize encryption + ret = C_EncryptInit(h_session, byref(mech), CK_ULONG(h_key)) + if ret != CKR_OK: return ret, None + + if is_multi_part_operation: + encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, C_EncryptFinal, data_to_encrypt) + else: + plain_data_length = len(data_to_encrypt) + plain_data = get_c_data_to_sign_or_encrypt(data_to_encrypt) + + #Get the length of the encrypted data + encrypted_data_length = CK_ULONG() + ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), None, byref(encrypted_data_length)) + if ret != CKR_OK: return ret, None + + output = create_string_buffer("", encrypted_data_length.value) + encrypted_data = cast(output, CK_BYTE_PTR) + + #Encrypt data + ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), encrypted_data, byref(encrypted_data_length)) + + #Convert encrypted data into a python string + ck_char_array = encrypted_data._objects.values()[0] + encrypted_python_string = convert_ck_char_array_to_string(ck_char_array) + + return ret, encrypted_python_string + +c_encrypt_ex = make_error_handle_function(c_encrypt) + +def _split_string_into_list(python_string, block_size): + ''' + Splits a string into a list of equal size chunks + + @param python_string: The string to divide + @param block_size: The size of the blocks to divide the string into + @return: A list of strings of block_size + ''' + return_list = [] + total_length = len(python_string) + for index in range(0, (total_length / block_size)): + start_index = index * block_size + end_index = min(start_index + block_size, total_length) + return_list.append(python_string[start_index : end_index]) + + return return_list + +def _get_string_from_list(list_of_strings): + ''' + Takes a list of strings and returns a single concatenated string. + + @param list_of_strings: A list of strings to be concatenated + @return: Single string representing the concatenated list + ''' + large_string = '' + for substring in list_of_strings: + large_string += substring + + return large_string + +def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech = None): + ''' + Decrypts some data + + @param h_session: The session to use + @param decryption_flavor: The decryption flavor to create a new mechanism with if no mechanism + is provided + @param h_key: The handle of the key to use to decrypt + @param mech: The mechanism, if none is provided a blank one will be provided based on the decryption_flavor + + @return: The result code, a python string of the decrypted data + ''' + + #Get the mechanism + if mech == None: + mech = get_encryption_mechanism(decryption_flavor) + + #Initialize Decrypt + ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) + if ret != CKR_OK: return ret, None + + #if a list is passed out do a decrypt operation on each string in the list, otherwise just do one decrypt operation + is_multi_part_operation = isinstance(encrypted_data, list) or isinstance(encrypted_data, tuple) + + if is_multi_part_operation: + python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, encrypted_data) + else: + + #Get the length of the final data + # NOTE: The "Conventions for functions returning output in a variable-length buffer" + # section of the PKCS#11 spec says that the length returned in this + # case (no output buffer given to C_Decrypt) can exceed the precise + # number of bytes needed. So the python string that's returned in the + # end needs to be adjusted based on the second called to C_Decrypt + # which will have the right length + plain_data_len = CK_ULONG() + c_encrypted_data = get_c_data_to_sign_or_encrypt(encrypted_data) + encrypted_data_len = len(encrypted_data) + ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), None, byref(plain_data_len)) + + if ret != CKR_OK: return ret, None + + output = create_string_buffer("", plain_data_len.value) + plain_data = cast(output, CK_BYTE_PTR) + + #Decrypt data + ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), plain_data, byref(plain_data_len)) + if ret != CKR_OK: return ret, None + + #Convert the decrypted data to a python readable format + ck_char_array = plain_data._objects.values()[0] + python_string = convert_ck_char_array_to_string(ck_char_array) + # Adjust the string based on the updated plain_data_len + python_string = python_string[:plain_data_len.value] + + return ret, python_string + +c_decrypt_ex= make_error_handle_function(c_decrypt) + +def do_multipart_operation(h_session, c_update_function, c_finalize_function, input_data_list): + ''' + Some code which will do a multipart encrypt or decrypt since they are the same + with just different functions called + ''' + max_data_chunk_size = 0xfff0 + plain_data_len = len(_get_string_from_list(input_data_list)) + + remaining_length = plain_data_len + python_string = '' + i = 0 + while remaining_length > 0: + current_chunk = input_data_list[i] + + #Prepare arguments for decrypt update operation + current_chunk_len = min(len(current_chunk), remaining_length) + + if current_chunk_len > max_data_chunk_size: + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + + out_data = create_string_buffer('', max_data_chunk_size) + out_data_len = CK_ULONG(max_data_chunk_size) + if (out_data_len.value > 0): + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + + ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len), cast(out_data, CK_BYTE_PTR), byref(out_data_len)) + if ret != CKR_OK: return ret, None + + remaining_length -= current_chunk_len + + #Get the output + ck_char_array = out_data._objects.values()[0] + python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + i += 1 + + #Finalizing multipart decrypt operation + out_data_len = CK_ULONG(max_data_chunk_size) + output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) + ret = c_finalize_function(h_session, output, byref(out_data_len)) + + #Get output + ck_char_array = output._objects.values()[0] + if (out_data_len.value > 0): + python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + + return python_string + +def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech = None): + ''' + Function which wraps a key + + @param h_session: The session to use + @param h_wrapping_key: The handle of the key to use to wrap another key + @param h_key: The key to wrap + @param encryption_flavor: The encryption flavor to create a new mechanism with if no mechanism + is provided + @param mech: The mechanism, if none is provided a blank one will be provided based on the encryption flavor + + @return: The result code, a ctypes byte array representing the new key + ''' + if mech == None: + mech = get_encryption_mechanism(encryption_flavor) + + #Get the size of the key + wrapped_key_length = CK_ULONG() + ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), None, byref(wrapped_key_length)) + if ret != CKR_OK: return ret, None + + #Actually wrap the key + output = create_string_buffer("", wrapped_key_length.value) + wrapped_key_output = cast(output, CK_BYTE_PTR) + ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), wrapped_key_output, byref(wrapped_key_length)) + + return ret, wrapped_key_output._objects.values()[0] +c_wrap_key_ex = make_error_handle_function(c_wrap_key) + +def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech = None): + ''' + Function which unwraps a key + @param h_session: The session to use + @param h_wrapping_key: The wrapping key handle + @param wapped_key: The wrapped key in a ctypes CK_CHAR_PTR array + @param key_template: The python template representing the new key's template + @param encryption_flavor: If the mechanism is not specified it will create a + default one based on the encryption flavor + @param mech: The mechanism to use, if null a default one will be created based on the encryption_flavor + + @return: The result code, the handle of the unwrapped key + ''' + if mech == None: + mech = get_encryption_mechanism(encryption_flavor) + + c_template = Attributes(key_template).get_c_struct() + byte_wrapped_key = cast(wrapped_key, CK_BYTE_PTR) + h_output_key = CK_ULONG() + ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), byte_wrapped_key, CK_ULONG(len(wrapped_key)), + c_template, CK_ULONG(len(key_template)), byref(h_output_key)) + + return ret, h_output_key.value +c_unwrap_key_ex = make_error_handle_function(c_unwrap_key) + +def get_c_data_to_sign_or_encrypt(python_data): + ''' + Function which gets the C data representation of some python data + + @param python_data: The python data to get a c representation of + + @return: A C byte pointer pointing to the C representation of the + python data + ''' + + c_data_to_sign = None + if isinstance(python_data, str): + c_data_to_sign = create_string_buffer(python_data) + c_data_to_sign = cast(c_data_to_sign, CK_BYTE_PTR) + else: + raise Exception("Please extend this function to support the type of data " + type(python_data)) + + return c_data_to_sign diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index cbd35f2..c47f991 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -3,7 +3,7 @@ """ from ctypes import byref, create_string_buffer, cast from pycryptoki.cryptoki import CK_SLOT_ID, CK_USER_TYPE, \ - CA_PerformSelfTest, CA_SetTokenCertificateSignature, CA_HAInit, \ + C_PerformSelfTest, CA_SetTokenCertificateSignature, CA_HAInit, \ CA_CreateLoginChallenge, CA_InitializeRemotePEDVector, \ CA_DeleteRemotePEDVector, CA_MTKRestore, CA_MTKResplit, CA_MTKZeroize, CK_ULONG, CK_BYTE_PTR, CK_BYTE, CK_CHAR_PTR, CK_CHAR from pycryptoki.attributes import Attributes @@ -34,7 +34,7 @@ def c_performselftest(slot, output_data = cast(create_string_buffer('', input_data_len), CK_BYTE_PTR) output_data_len = CK_ULONG() - ret = CA_PerformSelfTest(slot, + ret = C_PerformSelfTest(slot, test_type, input_data, input_length, diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index e3749e1..8513eaa 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -1,150 +1,150 @@ -""" -Methods used to generate keys. -""" - -from cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, CK_MECHANISM, \ - CK_MECHANISM_TYPE, CK_VOID_PTR, C_GenerateKey, C_GenerateKeyPair, C_CopyObject -from ctypes import byref, pointer, cast -from default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP -from defines import CKR_OK, CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CA_ClonePrivateKey, C_DeriveKey, \ - CK_SESSION_HANDLE -from pycryptoki.test_functions import make_error_handle_function - -def c_destroy_object(h_session, h_object_value): - ''' - Deletes the object corresponsing to the passed in object handle - @param h_session: Current session - @param h_object_value: The handle of the object to delete - - @return: The resutl code from the C_DestroyObject operation - ''' - ret = C_DestroyObject(h_session, CK_OBJECT_HANDLE(h_object_value)) - return ret -c_destroy_object_ex = make_error_handle_function(c_destroy_object) - - -def c_copy_object(h_session, h_object, template=None): - - """ - Method to call the C_CopyObject cryptoki command. - - :param h_session: Handle to the session - :param h_object: Handle to the object to be cloned - :param template: Template for the new object. Defaults to None - :return: Handle to the new cloned object. - """ - attributes = Attributes(template) - if template is None: - template_size = CK_ULONG(0) - else: - template_size = CK_ULONG(len(template)) - - h_new_object = CK_OBJECT_HANDLE() - - ret = C_CopyObject(h_session, h_object, attributes.get_c_struct(), template_size, h_new_object) - - return ret, h_new_object.value -c_copy_object_ex = make_error_handle_function(c_copy_object) - -def _get_mechanism(flavor): - ''' - Method used to get the CK_MECHANISM variable for key generation. - - @param flavor: The key flavor of the mechanism - - @return: Returns a blank mechanism of type flavor - ''' - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(flavor) - mech.pParameter = CK_VOID_PTR(0) - mech.usParameterLen = CK_ULONG(0) - return mech - -def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP): #TODO - ''' - Generates a symmetric key of a given flavor given the correct template. - - @param h_session: Current session - @param flavor: The flavour of the DES key to generate - @param template: The template to use to generate the key - - @return: Returns the result code and the key's handle - ''' - # INITALIZE VARIABLES - mech = _get_mechanism(flavor) - - key_attributes = Attributes(template) - us_public_template_size = CK_ULONG(len(template)) - - # ACTUALLY GENERATE KEY - h_key = CK_OBJECT_HANDLE() - ret = C_GenerateKey(h_session, byref(mech), key_attributes.get_c_struct(), us_public_template_size, byref(h_key)); - - return ret, h_key.value -c_generate_key_ex = make_error_handle_function(c_generate_key) - -def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None): - ''' - Generates a private and public key pair for a given flavor, and given public and private - key templates. The return value will be the handle for the key. - - @param h_session: Current session - @param flavor: The flavor of the key to generate - @param pbkey_template: The public key template to use for key generation - @param prkey_template: The private key template to use for key generation - @param mech: The mechanism to generate the key with - - @return: Returns the result code, the public key's handle, and the private key's handle - ''' - # INITALIZE VARIABLES - if mech is None: - mech = _get_mechanism(flavor) - - pbkey_template_size = len(pbkey_template) - pbkey_attributes = Attributes(pbkey_template) - - prkey_template_size = len(prkey_template) - prkey_attributes = Attributes(prkey_template) - - h_pbkey= CK_OBJECT_HANDLE() - h_prkey = CK_OBJECT_HANDLE() - ret = C_GenerateKeyPair(h_session, byref(mech), pbkey_attributes.get_c_struct(), pbkey_template_size, - prkey_attributes.get_c_struct(), prkey_template_size, byref(h_pbkey), byref(h_prkey)) - - return ret, h_pbkey.value, h_prkey.value -c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) - -def c_derive_key(h_session, h_base_key, template, mech_flavor, mech = None): - ''' - Calls C_DeriveKey - - @param h_session: The session handle to use - @param h_base_key: The base key - @param template: A python template of attributes (ex. CKM_DES_KEY_GEN_TEMP) - @param mech: The mechanism to use, if None a default mechanism will be used - - @return: The result code, The derived key's handle - ''' - - if mech == None: - mech = _get_mechanism(mech_flavor) - - h_key = CK_OBJECT_HANDLE() - c_template = Attributes(template).get_c_struct() - ret = C_DeriveKey(h_session, mech, CK_OBJECT_HANDLE(h_base_key), c_template, CK_ULONG(len(template)), byref(h_key)) - return ret, h_key.value -c_derive_key_ex = make_error_handle_function(c_derive_key) - -def clear_keys(h_session): - ''' - Quick hacked together function that can be used to clear the first 10 000 keys. - @param h_session:Current session - ''' - for i in range(1,10000): - c_destroy_object(h_session, i) +""" +Methods used to generate keys. +""" + +from cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, CK_MECHANISM, \ + CK_MECHANISM_TYPE, CK_VOID_PTR, C_GenerateKey, C_GenerateKeyPair, C_CopyObject +from ctypes import byref, pointer, cast +from default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP +from defines import CKR_OK, CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CA_ClonePrivateKey, C_DeriveKey, \ + CK_SESSION_HANDLE +from pycryptoki.test_functions import make_error_handle_function + +def c_destroy_object(h_session, h_object_value): + ''' + Deletes the object corresponsing to the passed in object handle + @param h_session: Current session + @param h_object_value: The handle of the object to delete + + @return: The resutl code from the C_DestroyObject operation + ''' + ret = C_DestroyObject(h_session, CK_OBJECT_HANDLE(h_object_value)) + return ret +c_destroy_object_ex = make_error_handle_function(c_destroy_object) + + +def c_copy_object(h_session, h_object, template=None): + + """ + Method to call the C_CopyObject cryptoki command. + + :param h_session: Handle to the session + :param h_object: Handle to the object to be cloned + :param template: Template for the new object. Defaults to None + :return: Handle to the new cloned object. + """ + attributes = Attributes(template) + if template is None: + template_size = CK_ULONG(0) + else: + template_size = CK_ULONG(len(template)) + + h_new_object = CK_OBJECT_HANDLE() + + ret = C_CopyObject(h_session, h_object, attributes.get_c_struct(), template_size, h_new_object) + + return ret, h_new_object.value +c_copy_object_ex = make_error_handle_function(c_copy_object) + +def _get_mechanism(flavor): + ''' + Method used to get the CK_MECHANISM variable for key generation. + + @param flavor: The key flavor of the mechanism + + @return: Returns a blank mechanism of type flavor + ''' + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(flavor) + mech.pParameter = CK_VOID_PTR(0) + mech.usParameterLen = CK_ULONG(0) + return mech + +def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP): #TODO + ''' + Generates a symmetric key of a given flavor given the correct template. + + @param h_session: Current session + @param flavor: The flavour of the DES key to generate + @param template: The template to use to generate the key + + @return: Returns the result code and the key's handle + ''' + # INITALIZE VARIABLES + mech = _get_mechanism(flavor) + + key_attributes = Attributes(template) + us_public_template_size = CK_ULONG(len(template)) + + # ACTUALLY GENERATE KEY + h_key = CK_OBJECT_HANDLE() + ret = C_GenerateKey(h_session, byref(mech), key_attributes.get_c_struct(), us_public_template_size, byref(h_key)); + + return ret, h_key.value +c_generate_key_ex = make_error_handle_function(c_generate_key) + +def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None): + ''' + Generates a private and public key pair for a given flavor, and given public and private + key templates. The return value will be the handle for the key. + + @param h_session: Current session + @param flavor: The flavor of the key to generate + @param pbkey_template: The public key template to use for key generation + @param prkey_template: The private key template to use for key generation + @param mech: The mechanism to generate the key with + + @return: Returns the result code, the public key's handle, and the private key's handle + ''' + # INITALIZE VARIABLES + if mech is None: + mech = _get_mechanism(flavor) + + pbkey_template_size = len(pbkey_template) + pbkey_attributes = Attributes(pbkey_template) + + prkey_template_size = len(prkey_template) + prkey_attributes = Attributes(prkey_template) + + h_pbkey= CK_OBJECT_HANDLE() + h_prkey = CK_OBJECT_HANDLE() + ret = C_GenerateKeyPair(h_session, byref(mech), pbkey_attributes.get_c_struct(), pbkey_template_size, + prkey_attributes.get_c_struct(), prkey_template_size, byref(h_pbkey), byref(h_prkey)) + + return ret, h_pbkey.value, h_prkey.value +c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) + +def c_derive_key(h_session, h_base_key, template, mech_flavor, mech = None): + ''' + Calls C_DeriveKey + + @param h_session: The session handle to use + @param h_base_key: The base key + @param template: A python template of attributes (ex. CKM_DES_KEY_GEN_TEMP) + @param mech: The mechanism to use, if None a default mechanism will be used + + @return: The result code, The derived key's handle + ''' + + if mech == None: + mech = _get_mechanism(mech_flavor) + + h_key = CK_OBJECT_HANDLE() + c_template = Attributes(template).get_c_struct() + ret = C_DeriveKey(h_session, mech, CK_OBJECT_HANDLE(h_base_key), c_template, CK_ULONG(len(template)), byref(h_key)) + return ret, h_key.value +c_derive_key_ex = make_error_handle_function(c_derive_key) + +def clear_keys(h_session): + ''' + Quick hacked together function that can be used to clear the first 10 000 keys. + @param h_session:Current session + ''' + for i in range(1,10000): + c_destroy_object(h_session, i) diff --git a/pycryptoki/logging_filters.py b/pycryptoki/logging_filters.py index 88d5064..d3a8560 100755 --- a/pycryptoki/logging_filters.py +++ b/pycryptoki/logging_filters.py @@ -1,26 +1,26 @@ -import logging -import os - -class OnlyTestsFilter(logging.Filter): - - def filter(self, record): - - file_path = os.path.realpath(__file__) - dir_path = os.path.dirname(file_path) - dir_members = os.listdir(dir_path) - files = [] - for filename in dir_members: - split_file = filename.split(".") - if len(split_file) > 1 and split_file[1] == 'py': - files.append(os.path.join(split_file[0])) - - should_show = True - - for python_file in files: - if python_file in record.getMessage(): - should_show = False - - return should_show - - - +import logging +import os + +class OnlyTestsFilter(logging.Filter): + + def filter(self, record): + + file_path = os.path.realpath(__file__) + dir_path = os.path.dirname(file_path) + dir_members = os.listdir(dir_path) + files = [] + for filename in dir_members: + split_file = filename.split(".") + if len(split_file) > 1 and split_file[1] == 'py': + files.append(os.path.join(split_file[0])) + + should_show = True + + for python_file in files: + if python_file in record.getMessage(): + should_show = False + + return should_show + + + diff --git a/pycryptoki/luna_threading.py b/pycryptoki/luna_threading.py index da52ffe..408030b 100755 --- a/pycryptoki/luna_threading.py +++ b/pycryptoki/luna_threading.py @@ -1,146 +1,146 @@ -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, MANUFACTURER_ID, MODEL -from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, \ - CKR_OK -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_open_session_ex, c_get_token_info_ex, \ - c_open_session, c_close_session -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.token_management import get_token_by_label_ex, \ - c_get_mechanism_list_ex, c_get_mechanism_info_ex -import logging -import sys -import threading -import time - - -logger = logging.getLogger(__name__) - -CREATE_AND_REMOVE_KEYS = 2 -OPEN_AND_CLOSE_SESSIONS = 3 -GET_TOKEN_INFO = 4 -GET_MECHANISM_INFO = 5 - - -class TestThread(threading.Thread): - ''' - A member of the threading class which, when given the proper parameters, will - perform some functions on the HSM in it's own thread. If one of the tests fails it will be reported when all the - threads finish. - ''' - def __init__(self, queue, thread_name, token_label, thread_type, max_time = 60): #60 seconds - ''' - @param queue: The queue that the threads will be placed into, this is required to signal - to the queue that the task is done - @param thread_name: The name of the thread for debug printing purposes - @param token_label: The token label to perform multithreaded operations on - @param thread_type: The a numeric value specifyingoperation the thread will do, see the variables - described above the TestThread class declaration ex. GET_TOKEN_INFO - @param max_time: The amount of time to spend doing the test in seconds - ''' - - self.thread_name = thread_name - self.thread_type = thread_type - self.max_time = max_time - self.queue = queue - self.token_label = token_label - threading.Thread.__init__(self) - - def run(self): - ''' - Called by the inheirited threading class to run the actual thread - ''' - logger.debug("Starting thread " + self.thread_name + " type " + str(self.thread_type)) - self._return = True - - try: - #For a given amount of time run the operations in a separate thread - start_time = time.time() - while ((time.time() - start_time) < self.max_time) and ((not self.starting_slot >= self.ending_slot) or (self.starting_slot == -1 and self.ending_slot == -1)): - if self.thread_type == CREATE_AND_REMOVE_KEYS: - self.create_and_remove_keys() - elif self.thread_type == OPEN_AND_CLOSE_SESSIONS: - self.open_and_close_sessions() - elif self.thread_type == GET_TOKEN_INFO: - self.get_token_info() - elif self.thread_type == GET_MECHANISM_INFO: - self.get_mechanism_info() - else: - raise Exception("Unknown thread type " + str(self.thread_type)) - - logger.debug("Exiting thread " + self.thread_name + " type " + str(self.thread_type)) - except Exception as e: - self._return = e - self.queue.task_done() - print sys.exc_info()[0] - raise - return - - if (self._return == True): - self._return = True - self.queue.task_done() - - def get_token_info(self): - ''' - Test that will get the token info and verify that the fields have been - set to something other than null - ''' - slot = get_token_by_label_ex(self.token_label) - token_info = c_get_token_info_ex(slot) - - assert token_info['label'] == ADMIN_PARTITION_LABEL - assert token_info['manufacturerID'] == MANUFACTURER_ID - assert token_info['model'] == MODEL - assert token_info['serialNumber'] != 0 - assert token_info['flags'] != 0 - assert token_info['ulTotalPrivateMemory'] == 0 - assert token_info['ulSessionCount'] != 0 - assert token_info['ulRwSessionCount'] != 0 - assert token_info['ulMaxPinLen'] != 0 - assert token_info['ulMinPinLen'] != 0 -# token_info['hardwareVersion'] = c_token_info.hardwareVersion -# token_info['firmwareVersion'] = c_token_info.firmwareVersion - - def create_and_remove_keys(self): - ''' - Test that will create a bunch of keys and verify the attributes on - those keys - ''' - slot = get_token_by_label_ex(self.token_label) - h_session = c_open_session_ex(slot) - - logger.debug(self.thread_name + " Generating keys") - key_handle = c_generate_key_ex(h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - key_handle_public, key_handle_private = c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - - logger.debug(self.thread_name + " Verifying keys") - verify_object_attributes(h_session, key_handle, CKM_DES_KEY_GEN_TEMP) - verify_object_attributes(h_session, key_handle_public, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP) - verify_object_attributes(h_session, key_handle_private, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - - def open_and_close_sessions(self): - ''' - Test that will open and close sessions repeatedly - ''' - slot = get_token_by_label_ex(self.token_label) - - ret, h_session = c_open_session(slot) - assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] - - ret = c_close_session(h_session) - assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] - - def get_mechanism_info(self): - ''' - Test that will get the mechanism info repeatedly and verify it is non null - ''' - slot = get_token_by_label_ex(self.token_label) - mechanism_list = c_get_mechanism_list_ex(slot) - - assert len(mechanism_list) > 0, "The mechanism list should have a non zero length" - for mechanism in mechanism_list: - mech_info = c_get_mechanism_info_ex(slot, mechanism) - assert (mech_info.ulMinKeySize > 0 or mech_info.ulMaxKeySize > 0 or mech_info.flags > 0) and mech_info.ulMinKeySize <= mech_info.ulMaxKeySize, "Verifing that all fields are not 0 should be good enough for now" - +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, MANUFACTURER_ID, MODEL +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKR_OK +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_open_session_ex, c_get_token_info_ex, \ + c_open_session, c_close_session +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.token_management import get_token_by_label_ex, \ + c_get_mechanism_list_ex, c_get_mechanism_info_ex +import logging +import sys +import threading +import time + + +logger = logging.getLogger(__name__) + +CREATE_AND_REMOVE_KEYS = 2 +OPEN_AND_CLOSE_SESSIONS = 3 +GET_TOKEN_INFO = 4 +GET_MECHANISM_INFO = 5 + + +class TestThread(threading.Thread): + ''' + A member of the threading class which, when given the proper parameters, will + perform some functions on the HSM in it's own thread. If one of the tests fails it will be reported when all the + threads finish. + ''' + def __init__(self, queue, thread_name, token_label, thread_type, max_time = 60): #60 seconds + ''' + @param queue: The queue that the threads will be placed into, this is required to signal + to the queue that the task is done + @param thread_name: The name of the thread for debug printing purposes + @param token_label: The token label to perform multithreaded operations on + @param thread_type: The a numeric value specifyingoperation the thread will do, see the variables + described above the TestThread class declaration ex. GET_TOKEN_INFO + @param max_time: The amount of time to spend doing the test in seconds + ''' + + self.thread_name = thread_name + self.thread_type = thread_type + self.max_time = max_time + self.queue = queue + self.token_label = token_label + threading.Thread.__init__(self) + + def run(self): + ''' + Called by the inheirited threading class to run the actual thread + ''' + logger.debug("Starting thread " + self.thread_name + " type " + str(self.thread_type)) + self._return = True + + try: + #For a given amount of time run the operations in a separate thread + start_time = time.time() + while ((time.time() - start_time) < self.max_time) and ((not self.starting_slot >= self.ending_slot) or (self.starting_slot == -1 and self.ending_slot == -1)): + if self.thread_type == CREATE_AND_REMOVE_KEYS: + self.create_and_remove_keys() + elif self.thread_type == OPEN_AND_CLOSE_SESSIONS: + self.open_and_close_sessions() + elif self.thread_type == GET_TOKEN_INFO: + self.get_token_info() + elif self.thread_type == GET_MECHANISM_INFO: + self.get_mechanism_info() + else: + raise Exception("Unknown thread type " + str(self.thread_type)) + + logger.debug("Exiting thread " + self.thread_name + " type " + str(self.thread_type)) + except Exception as e: + self._return = e + self.queue.task_done() + print sys.exc_info()[0] + raise + return + + if (self._return == True): + self._return = True + self.queue.task_done() + + def get_token_info(self): + ''' + Test that will get the token info and verify that the fields have been + set to something other than null + ''' + slot = get_token_by_label_ex(self.token_label) + token_info = c_get_token_info_ex(slot) + + assert token_info['label'] == ADMIN_PARTITION_LABEL + assert token_info['manufacturerID'] == MANUFACTURER_ID + assert token_info['model'] == MODEL + assert token_info['serialNumber'] != 0 + assert token_info['flags'] != 0 + assert token_info['ulTotalPrivateMemory'] == 0 + assert token_info['ulSessionCount'] != 0 + assert token_info['ulRwSessionCount'] != 0 + assert token_info['ulMaxPinLen'] != 0 + assert token_info['ulMinPinLen'] != 0 +# token_info['hardwareVersion'] = c_token_info.hardwareVersion +# token_info['firmwareVersion'] = c_token_info.firmwareVersion + + def create_and_remove_keys(self): + ''' + Test that will create a bunch of keys and verify the attributes on + those keys + ''' + slot = get_token_by_label_ex(self.token_label) + h_session = c_open_session_ex(slot) + + logger.debug(self.thread_name + " Generating keys") + key_handle = c_generate_key_ex(h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + key_handle_public, key_handle_private = c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + + logger.debug(self.thread_name + " Verifying keys") + verify_object_attributes(h_session, key_handle, CKM_DES_KEY_GEN_TEMP) + verify_object_attributes(h_session, key_handle_public, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP) + verify_object_attributes(h_session, key_handle_private, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + + def open_and_close_sessions(self): + ''' + Test that will open and close sessions repeatedly + ''' + slot = get_token_by_label_ex(self.token_label) + + ret, h_session = c_open_session(slot) + assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] + + ret = c_close_session(h_session) + assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] + + def get_mechanism_info(self): + ''' + Test that will get the mechanism info repeatedly and verify it is non null + ''' + slot = get_token_by_label_ex(self.token_label) + mechanism_list = c_get_mechanism_list_ex(slot) + + assert len(mechanism_list) > 0, "The mechanism list should have a non zero length" + for mechanism in mechanism_list: + mech_info = c_get_mechanism_info_ex(slot, mechanism) + assert (mech_info.ulMinKeySize > 0 or mech_info.ulMaxKeySize > 0 or mech_info.flags > 0) and mech_info.ulMinKeySize <= mech_info.ulMaxKeySize, "Verifing that all fields are not 0 should be good enough for now" + diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index cb6dd81..67e2cae 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -1,136 +1,136 @@ -from ctypes import c_void_p, cast, pointer, POINTER, sizeof, c_char_p, \ - create_string_buffer -from pycryptoki.cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ - CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR -from pycryptoki.defines import CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, \ - CK_CRYPTOKI_ELEMENT, CK_STORAGE_HOST, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL - - -CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, - 'ulType' : CK_CRYPTOKI_ELEMENT, - 'ulHandle' : 5, - 'ulDeleteAfterExtract' : 0, - 'pBuffer' : 0, - 'pulBufferLen' : 0, - 'ulStorage' : CK_STORAGE_HOST, - 'pedId' : 0, - 'pbFileName' : 0, - 'ctxID' : 3 - } - -CK_AES_CBC_PAD_INSERT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, - 'ulType' : CK_CRYPTOKI_ELEMENT, - 'ulContainerState' : 0, - 'pBuffer' : 0, - 'pulBufferLen' : 0, - 'ulStorageType' : CK_STORAGE_HOST, - 'pulType' : 0, - 'pulHandle' : 0, - 'ctxID' : 3, - 'pedID' : 3, - 'pbFileName' : 0, - 'ulStorage' : CK_STORAGE_HOST, - } - -supported_parameters = {'CK_AES_CBC_PAD_EXTRACT_PARAMS' : CK_AES_CBC_PAD_EXTRACT_PARAMS, - 'CK_AES_CBC_PAD_INSERT_PARAMS' : CK_AES_CBC_PAD_INSERT_PARAMS} - -def get_c_struct_from_mechanism(python_dictionary, params_type_string): - ''' - Gets a c struct from a python dictionary representing that struct - - @param python_dictionary: The python dictionary representing the C struct, - see CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP for an example - @param params_type_string: A string representing the parameter struct. - ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' - @return: A C struct - ''' - params_type = supported_parameters[params_type_string] - params = params_type() - mech = CK_MECHANISM() - mech.mechanism = python_dictionary['mechanism'] - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params_type)) - - #Automatically handle the simpler fields - for entry in params_type._fields_: - key_name = entry[0] - key_type = entry[1] - - if key_type == CK_ULONG: - setattr(params, key_name, CK_ULONG(python_dictionary[key_name])) - elif key_type == CK_ULONG_PTR: - setattr(params, key_name, pointer(CK_ULONG(python_dictionary[key_name]))) - else: - continue - - #Explicitly handle the more complex fields - if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: - if (len(python_dictionary['pBuffer']) == 0): - params.pBuffer = None - else: - params.pBuffer = (CK_BYTE * len(python_dictionary['pBuffer']))() - #params.pbFileName = 0 #TODO convert byte pointer to serializable type - pass - elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: - #params.pbFileName = TODO - params.pBuffer = cast(create_string_buffer(python_dictionary['pBuffer']), CK_BYTE_PTR) - params.ulBufferLen = len(python_dictionary['pBuffer']) - pass - else: - raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") - - return mech - -def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): - ''' - Gets a python dictionary from a c mechanism's struct for serialization - and easier test case writing - - @param c_mechanism: The c mechanism to convert to a python dictionary - @param params_type_string: A string representing the parameter struct. - ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' - - @return: A python dictionary representing the c struct - ''' - python_dictionary = {} - python_dictionary['mechanism'] = c_mechanism.mechanism - - params_type = supported_parameters[params_type_string] - params_struct = cast(c_mechanism.pParameter, POINTER(params_type)).contents - - #Automatically handle the simpler fields - for entry in params_type._fields_: - key_name = entry[0] - key_type = entry[1] - - if key_type == CK_ULONG: - python_dictionary[key_name] = getattr(params_struct, key_name) - elif key_type == CK_ULONG_PTR: - python_dictionary[key_name] = getattr(params_struct, key_name).contents.value - else: - continue - - #Explicitly handle the more complex fields - if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: - bufferLength = params_struct.pulBufferLen.contents.value - if params_struct.pBuffer == None: - bufferString = None - else: - char_p_string = cast(params_struct.pBuffer, c_char_p).value - if char_p_string != None: - bufferString = char_p_string[0:bufferLength] - else: - bufferString = None - python_dictionary['pBuffer'] = bufferString - python_dictionary['pbFileName'] = 0 #TODO - elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: - python_dictionary['pbFileName'] = 0 #TODO - python_dictionary['pBuffer'] = 0 #TODO - else: - raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") - - return python_dictionary - -if __name__ == '__main__': +from ctypes import c_void_p, cast, pointer, POINTER, sizeof, c_char_p, \ + create_string_buffer +from pycryptoki.cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ + CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR +from pycryptoki.defines import CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, \ + CK_CRYPTOKI_ELEMENT, CK_STORAGE_HOST, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL + + +CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, + 'ulType' : CK_CRYPTOKI_ELEMENT, + 'ulHandle' : 5, + 'ulDeleteAfterExtract' : 0, + 'pBuffer' : 0, + 'pulBufferLen' : 0, + 'ulStorage' : CK_STORAGE_HOST, + 'pedId' : 0, + 'pbFileName' : 0, + 'ctxID' : 3 + } + +CK_AES_CBC_PAD_INSERT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, + 'ulType' : CK_CRYPTOKI_ELEMENT, + 'ulContainerState' : 0, + 'pBuffer' : 0, + 'pulBufferLen' : 0, + 'ulStorageType' : CK_STORAGE_HOST, + 'pulType' : 0, + 'pulHandle' : 0, + 'ctxID' : 3, + 'pedID' : 3, + 'pbFileName' : 0, + 'ulStorage' : CK_STORAGE_HOST, + } + +supported_parameters = {'CK_AES_CBC_PAD_EXTRACT_PARAMS' : CK_AES_CBC_PAD_EXTRACT_PARAMS, + 'CK_AES_CBC_PAD_INSERT_PARAMS' : CK_AES_CBC_PAD_INSERT_PARAMS} + +def get_c_struct_from_mechanism(python_dictionary, params_type_string): + ''' + Gets a c struct from a python dictionary representing that struct + + @param python_dictionary: The python dictionary representing the C struct, + see CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP for an example + @param params_type_string: A string representing the parameter struct. + ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' + @return: A C struct + ''' + params_type = supported_parameters[params_type_string] + params = params_type() + mech = CK_MECHANISM() + mech.mechanism = python_dictionary['mechanism'] + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params_type)) + + #Automatically handle the simpler fields + for entry in params_type._fields_: + key_name = entry[0] + key_type = entry[1] + + if key_type == CK_ULONG: + setattr(params, key_name, CK_ULONG(python_dictionary[key_name])) + elif key_type == CK_ULONG_PTR: + setattr(params, key_name, pointer(CK_ULONG(python_dictionary[key_name]))) + else: + continue + + #Explicitly handle the more complex fields + if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: + if (len(python_dictionary['pBuffer']) == 0): + params.pBuffer = None + else: + params.pBuffer = (CK_BYTE * len(python_dictionary['pBuffer']))() + #params.pbFileName = 0 #TODO convert byte pointer to serializable type + pass + elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: + #params.pbFileName = TODO + params.pBuffer = cast(create_string_buffer(python_dictionary['pBuffer']), CK_BYTE_PTR) + params.ulBufferLen = len(python_dictionary['pBuffer']) + pass + else: + raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") + + return mech + +def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): + ''' + Gets a python dictionary from a c mechanism's struct for serialization + and easier test case writing + + @param c_mechanism: The c mechanism to convert to a python dictionary + @param params_type_string: A string representing the parameter struct. + ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' + + @return: A python dictionary representing the c struct + ''' + python_dictionary = {} + python_dictionary['mechanism'] = c_mechanism.mechanism + + params_type = supported_parameters[params_type_string] + params_struct = cast(c_mechanism.pParameter, POINTER(params_type)).contents + + #Automatically handle the simpler fields + for entry in params_type._fields_: + key_name = entry[0] + key_type = entry[1] + + if key_type == CK_ULONG: + python_dictionary[key_name] = getattr(params_struct, key_name) + elif key_type == CK_ULONG_PTR: + python_dictionary[key_name] = getattr(params_struct, key_name).contents.value + else: + continue + + #Explicitly handle the more complex fields + if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: + bufferLength = params_struct.pulBufferLen.contents.value + if params_struct.pBuffer == None: + bufferString = None + else: + char_p_string = cast(params_struct.pBuffer, c_char_p).value + if char_p_string != None: + bufferString = char_p_string[0:bufferLength] + else: + bufferString = None + python_dictionary['pBuffer'] = bufferString + python_dictionary['pbFileName'] = 0 #TODO + elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: + python_dictionary['pbFileName'] = 0 #TODO + python_dictionary['pBuffer'] = 0 #TODO + else: + raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") + + return python_dictionary + +if __name__ == '__main__': pass \ No newline at end of file diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index be1dcdd..046617d 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -1,151 +1,151 @@ -from ctypes import create_string_buffer, cast, byref -from pycryptoki.attributes import convert_ck_char_array_to_string, \ - convert_string_to_CK_CHAR, Attributes -from pycryptoki.cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ - C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ - CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey -from pycryptoki.defines import CKR_OK -from pycryptoki.encryption import get_c_data_to_sign_or_encrypt -from pycryptoki.key_generator import _get_mechanism -from pycryptoki.sign_verify import do_multipart_sign_or_digest -from pycryptoki.test_functions import make_error_handle_function - -def c_generate_random(h_session, length): - ''' - Generates a sequence of random numbers - - @param h_session: The current session - @param length: The length in bytes of the random number sequence - - @return: The result code, A string of random data - ''' - random_data = cast(create_string_buffer("", length), CK_BYTE_PTR) - ret = C_GenerateRandom(h_session, random_data, CK_ULONG(length)) - - random_string = convert_ck_char_array_to_string(random_data._objects.values()[0]) - return ret, random_string -c_generate_random_ex = make_error_handle_function(c_generate_random) - -def c_seed_random(h_session, seed): - ''' - Seeds the random number generator - - @param h_session: The current session - @param seed: A python string of some seed - - @return: The result code - ''' - seed_bytes = cast(convert_string_to_CK_CHAR(seed), CK_BYTE_PTR) - seed_length = CK_ULONG(len(seed)) - ret = C_SeedRandom(h_session, seed_bytes, seed_length) - return ret; -c_seed_random_ex = make_error_handle_function(c_seed_random) - -def c_digest(h_session, data_to_digest, digest_flavor, mech = None): - ''' - Digests some data - - @param h_session: Current session - @param data_to_digest: The data to digest, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, - SHA224, SHA256, SHA384, SHA512) - @param mech: The mechanism to be used. If None a blank one with the digest_flavour will be used - - @return: The result code, a python string of the digested data - ''' - - #Get mechanism if none provided - if mech == None: - mech = _get_mechanism(digest_flavor) - - #Initialize Digestion - ret = C_DigestInit(h_session, mech) - if ret != CKR_OK: return ret - - #if a list is passed out do an digest operation on each string in the list, otherwise just do one digest operation - is_multi_part_operation = isinstance(data_to_digest, list) or isinstance(data_to_digest, tuple) - - if is_multi_part_operation: - ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, C_DigestFinal, data_to_digest) - else: - #Get arguments - digest_data_length = len(data_to_digest) - c_data_to_digest = get_c_data_to_sign_or_encrypt(data_to_digest) - - #Get the length of the digested data - digest_length = CK_ULONG() - ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), None, byref(digest_length)) - if ret != CKR_OK: return ret, None - - output = create_string_buffer("", digest_length.value) - digested_data = cast(output, CK_BYTE_PTR) - - #Digest data - ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), digested_data, byref(digest_length)) - - #Convert Digested data into a python string - ck_char_array = digested_data._objects.values()[0] - digested_python_string = convert_ck_char_array_to_string(ck_char_array) - - return ret, digested_python_string -c_digest_ex = make_error_handle_function(c_digest) - -def c_digestkey(h_session, h_key, digest_flavor, mech = None): -#Get mechanism if none provided - if mech == None: - mech = _get_mechanism(digest_flavor) - - #Initialize Digestion - ret = C_DigestInit(h_session, mech) - if ret != CKR_OK: return ret - - ret = C_DigestKey(h_session, h_key) - - return ret -c_digestkey_ex = make_error_handle_function(c_digestkey) - - - -def c_create_object(h_session, template): - ''' - Creates an object based on a given python template - - @param h_session: The session handle to use - @param template: The python template which the object will be based on - - @return: The result code, the handle of the object - ''' - c_template = Attributes(template).get_c_struct() - new_object_handle = CK_ULONG() - ret = C_CreateObject(h_session, c_template, CK_ULONG(len(template)), byref(new_object_handle)) - - return ret, new_object_handle.value -c_create_object_ex = make_error_handle_function(c_create_object) - -def c_set_ped_id(slot, id): - ''' - Set the PED ID for the given slot. - @param slot : slot number - @parm id : PED ID to use - - @return: The result code - ''' - ret = CA_SetPedId(CK_SLOT_ID(slot), CK_ULONG(id)) - return ret; -c_set_ped_id_ex = make_error_handle_function(c_set_ped_id) - -def c_get_ped_id(slot): - ''' - Get the PED ID for the given slot. - @param slot : slot number - - @return: The result code and ID - ''' - pedId = CK_ULONG() - ret = CA_GetPedId(CK_SLOT_ID(slot), byref(pedId)) - return ret, pedId.value -c_get_ped_id_ex = make_error_handle_function(c_get_ped_id) +from ctypes import create_string_buffer, cast, byref +from pycryptoki.attributes import convert_ck_char_array_to_string, \ + convert_string_to_CK_CHAR, Attributes +from pycryptoki.cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ + C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ + CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey +from pycryptoki.defines import CKR_OK +from pycryptoki.encryption import get_c_data_to_sign_or_encrypt +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.sign_verify import do_multipart_sign_or_digest +from pycryptoki.test_functions import make_error_handle_function + +def c_generate_random(h_session, length): + ''' + Generates a sequence of random numbers + + @param h_session: The current session + @param length: The length in bytes of the random number sequence + + @return: The result code, A string of random data + ''' + random_data = cast(create_string_buffer("", length), CK_BYTE_PTR) + ret = C_GenerateRandom(h_session, random_data, CK_ULONG(length)) + + random_string = convert_ck_char_array_to_string(random_data._objects.values()[0]) + return ret, random_string +c_generate_random_ex = make_error_handle_function(c_generate_random) + +def c_seed_random(h_session, seed): + ''' + Seeds the random number generator + + @param h_session: The current session + @param seed: A python string of some seed + + @return: The result code + ''' + seed_bytes = cast(convert_string_to_CK_CHAR(seed), CK_BYTE_PTR) + seed_length = CK_ULONG(len(seed)) + ret = C_SeedRandom(h_session, seed_bytes, seed_length) + return ret; +c_seed_random_ex = make_error_handle_function(c_seed_random) + +def c_digest(h_session, data_to_digest, digest_flavor, mech = None): + ''' + Digests some data + + @param h_session: Current session + @param data_to_digest: The data to digest, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, + SHA224, SHA256, SHA384, SHA512) + @param mech: The mechanism to be used. If None a blank one with the digest_flavour will be used + + @return: The result code, a python string of the digested data + ''' + + #Get mechanism if none provided + if mech == None: + mech = _get_mechanism(digest_flavor) + + #Initialize Digestion + ret = C_DigestInit(h_session, mech) + if ret != CKR_OK: return ret + + #if a list is passed out do an digest operation on each string in the list, otherwise just do one digest operation + is_multi_part_operation = isinstance(data_to_digest, list) or isinstance(data_to_digest, tuple) + + if is_multi_part_operation: + ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, C_DigestFinal, data_to_digest) + else: + #Get arguments + digest_data_length = len(data_to_digest) + c_data_to_digest = get_c_data_to_sign_or_encrypt(data_to_digest) + + #Get the length of the digested data + digest_length = CK_ULONG() + ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), None, byref(digest_length)) + if ret != CKR_OK: return ret, None + + output = create_string_buffer("", digest_length.value) + digested_data = cast(output, CK_BYTE_PTR) + + #Digest data + ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), digested_data, byref(digest_length)) + + #Convert Digested data into a python string + ck_char_array = digested_data._objects.values()[0] + digested_python_string = convert_ck_char_array_to_string(ck_char_array) + + return ret, digested_python_string +c_digest_ex = make_error_handle_function(c_digest) + +def c_digestkey(h_session, h_key, digest_flavor, mech = None): +#Get mechanism if none provided + if mech == None: + mech = _get_mechanism(digest_flavor) + + #Initialize Digestion + ret = C_DigestInit(h_session, mech) + if ret != CKR_OK: return ret + + ret = C_DigestKey(h_session, h_key) + + return ret +c_digestkey_ex = make_error_handle_function(c_digestkey) + + + +def c_create_object(h_session, template): + ''' + Creates an object based on a given python template + + @param h_session: The session handle to use + @param template: The python template which the object will be based on + + @return: The result code, the handle of the object + ''' + c_template = Attributes(template).get_c_struct() + new_object_handle = CK_ULONG() + ret = C_CreateObject(h_session, c_template, CK_ULONG(len(template)), byref(new_object_handle)) + + return ret, new_object_handle.value +c_create_object_ex = make_error_handle_function(c_create_object) + +def c_set_ped_id(slot, id): + ''' + Set the PED ID for the given slot. + @param slot : slot number + @parm id : PED ID to use + + @return: The result code + ''' + ret = CA_SetPedId(CK_SLOT_ID(slot), CK_ULONG(id)) + return ret; +c_set_ped_id_ex = make_error_handle_function(c_set_ped_id) + +def c_get_ped_id(slot): + ''' + Get the PED ID for the given slot. + @param slot : slot number + + @return: The result code and ID + ''' + pedId = CK_ULONG() + ret = CA_GetPedId(CK_SLOT_ID(slot), byref(pedId)) + return ret, pedId.value +c_get_ped_id_ex = make_error_handle_function(c_get_ped_id) diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index bce309c..0ed0071 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -1,71 +1,71 @@ -from ctypes import byref, sizeof -from pycryptoki.attributes import Attributes, c_struct_to_python -from pycryptoki.cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ - C_FindObjects, C_FindObjectsFinal, C_GetAttributeValue, C_SetAttributeValue -from pycryptoki.defines import CKR_OK, CKA_CLASS, CKA_LABEL, CKA_VALUE -from pycryptoki.test_functions import LunaException, make_error_handle_function - -def c_find_objects(h_session, objects_find, template_attributes, num_entries): - ''' - Calls c_find_objects and c_find_objects_init to get a python dictionary - of the objects found. - - @param h_session: The current session - @param objects_find: A python dictionary of the object template to look for - @param template_attributes: A python dictionary of the attributes to look for - @param num_entries: The number of entries to return - - @return: Returns a python dictionary of the templates of the objects found - ''' - attributes = [] - struct = Attributes(objects_find).get_c_struct() - ret = C_FindObjectsInit(h_session, struct, CK_ULONG(len(objects_find))) - if ret != CKR_OK: return ret, -1, None; - - h_ary = (CK_OBJECT_HANDLE * num_entries)() - us_total = CK_ULONG(num_entries) - ret = C_FindObjects(h_session, h_ary, CK_ULONG(num_entries), byref(us_total)) - if ret != CKR_OK: return ret, -1, None; - - #todo get attribute value for all of them - for i in range(0, us_total.value): - attribute = c_get_attribute_value_ex(h_session, h_ary[i], template_attributes) - attributes.append(attribute) - - - ret = C_FindObjectsFinal(h_session) - - return ret, h_ary[0], attributes -c_find_objects_ex = make_error_handle_function(c_find_objects) - -def c_get_attribute_value(h_session, h_object, template): - ''' - Calls C_GetAttrributeValue to get an attribute value based on a python template - @param h_session: The current session - @param h_object: The handle of the object to get attributes for - @param template: A python dictionary representing the template of the attributes to be retrieved - - @return: A python dictionary representing the attributes returned from the HSM/library - ''' - c_struct = Attributes(template).get_c_struct() - ret = C_GetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) - if ret != CKR_OK: return ret; - - return ret, c_struct_to_python(c_struct) -c_get_attribute_value_ex = make_error_handle_function(c_get_attribute_value) - -def c_set_attribute_value(h_session, h_object, template): - ''' - Calls C_SetAttributeValue to set an attribute value based on a python template - @param h_session: The current session - @param h_object: The handle of the object to get attributes for - @param template: A python dictionary representing the template of the attributes to be written - - @return: A python dictionary representing the attributes returned from the HSM/library - ''' - c_struct = Attributes(template).get_c_struct() - ret = C_SetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) - if ret != CKR_OK: return ret; - - return ret, c_struct_to_python(c_struct) -c_set_attribute_value_ex = make_error_handle_function(c_set_attribute_value) +from ctypes import byref, sizeof +from pycryptoki.attributes import Attributes, c_struct_to_python +from pycryptoki.cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ + C_FindObjects, C_FindObjectsFinal, C_GetAttributeValue, C_SetAttributeValue +from pycryptoki.defines import CKR_OK, CKA_CLASS, CKA_LABEL, CKA_VALUE +from pycryptoki.test_functions import LunaException, make_error_handle_function + +def c_find_objects(h_session, objects_find, template_attributes, num_entries): + ''' + Calls c_find_objects and c_find_objects_init to get a python dictionary + of the objects found. + + @param h_session: The current session + @param objects_find: A python dictionary of the object template to look for + @param template_attributes: A python dictionary of the attributes to look for + @param num_entries: The number of entries to return + + @return: Returns a python dictionary of the templates of the objects found + ''' + attributes = [] + struct = Attributes(objects_find).get_c_struct() + ret = C_FindObjectsInit(h_session, struct, CK_ULONG(len(objects_find))) + if ret != CKR_OK: return ret, -1, None; + + h_ary = (CK_OBJECT_HANDLE * num_entries)() + us_total = CK_ULONG(num_entries) + ret = C_FindObjects(h_session, h_ary, CK_ULONG(num_entries), byref(us_total)) + if ret != CKR_OK: return ret, -1, None; + + #todo get attribute value for all of them + for i in range(0, us_total.value): + attribute = c_get_attribute_value_ex(h_session, h_ary[i], template_attributes) + attributes.append(attribute) + + + ret = C_FindObjectsFinal(h_session) + + return ret, h_ary[0], attributes +c_find_objects_ex = make_error_handle_function(c_find_objects) + +def c_get_attribute_value(h_session, h_object, template): + ''' + Calls C_GetAttrributeValue to get an attribute value based on a python template + @param h_session: The current session + @param h_object: The handle of the object to get attributes for + @param template: A python dictionary representing the template of the attributes to be retrieved + + @return: A python dictionary representing the attributes returned from the HSM/library + ''' + c_struct = Attributes(template).get_c_struct() + ret = C_GetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) + if ret != CKR_OK: return ret; + + return ret, c_struct_to_python(c_struct) +c_get_attribute_value_ex = make_error_handle_function(c_get_attribute_value) + +def c_set_attribute_value(h_session, h_object, template): + ''' + Calls C_SetAttributeValue to set an attribute value based on a python template + @param h_session: The current session + @param h_object: The handle of the object to get attributes for + @param template: A python dictionary representing the template of the attributes to be written + + @return: A python dictionary representing the attributes returned from the HSM/library + ''' + c_struct = Attributes(template).get_c_struct() + ret = C_SetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) + if ret != CKR_OK: return ret; + + return ret, c_struct_to_python(c_struct) +c_set_attribute_value_ex = make_error_handle_function(c_set_attribute_value) \ No newline at end of file diff --git a/pycryptoki/policy_management.py b/pycryptoki/policy_management.py index 7bb8f12..c319856 100755 --- a/pycryptoki/policy_management.py +++ b/pycryptoki/policy_management.py @@ -1,50 +1,50 @@ -from pycryptoki.cryptoki import CA_SetHSMPolicy, CA_SetContainerPolicy, CK_ULONG, \ - CA_SetDestructiveHSMPolicy -from pycryptoki.test_functions import make_error_handle_function - -def ca_set_hsm_policy(h_session, policy_id, policy_val): - ''' - Sets the HSM policies by calling CA_SetHSMPolicy - - @param h_session: The session handle of the administrator setting the HSM policy - @param policy_id: The ID of the policy being set - @param policy_val: The value of the policy being set - - @return: The result code - ''' - ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret -ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) - -def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): - ''' - Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy - - @param h_session: The session handle of the administrator setting the HSM policy - @param policy_id: The ID of the policy being set - @param policy_val: The value of the policy being set - - @return: The result code - ''' - ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret -ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) - -def ca_set_container_policy(h_session, container_number, policy_id, policy_val): - ''' - Sets a policy on the container. - - NOTE: With per partition SO this method should generally not be used. Instead - ca_set_partition_policies should be used - - @param h_session: The session handle of the entity with permission to change the policy - @param container_number: The container number to set the policy on. - @param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) - @param policy_val: The value to set the policy to - - @return: The result code - ''' - ret = CA_SetContainerPolicy(h_session, CK_ULONG(container_number), CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret -ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) - +from pycryptoki.cryptoki import CA_SetHSMPolicy, CA_SetContainerPolicy, CK_ULONG, \ + CA_SetDestructiveHSMPolicy +from pycryptoki.test_functions import make_error_handle_function + +def ca_set_hsm_policy(h_session, policy_id, policy_val): + ''' + Sets the HSM policies by calling CA_SetHSMPolicy + + @param h_session: The session handle of the administrator setting the HSM policy + @param policy_id: The ID of the policy being set + @param policy_val: The value of the policy being set + + @return: The result code + ''' + ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret +ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) + +def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): + ''' + Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy + + @param h_session: The session handle of the administrator setting the HSM policy + @param policy_id: The ID of the policy being set + @param policy_val: The value of the policy being set + + @return: The result code + ''' + ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret +ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) + +def ca_set_container_policy(h_session, container_number, policy_id, policy_val): + ''' + Sets a policy on the container. + + NOTE: With per partition SO this method should generally not be used. Instead + ca_set_partition_policies should be used + + @param h_session: The session handle of the entity with permission to change the policy + @param container_number: The container number to set the policy on. + @param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) + @param policy_val: The value to set the policy to + + @return: The result code + ''' + ret = CA_SetContainerPolicy(h_session, CK_ULONG(container_number), CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret +ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) + diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index 57280f3..bd5860e 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -1,113 +1,111 @@ -''' -Contains both a local and remote pycryptoki client -''' -import xmlrpclib -from pycryptoki.daemon.pycryptoki_daemon import pycryptoki_functions,\ - functions_needing_serialization -from pycryptoki.session_management import c_finalize, c_initialize_ex, c_initialize - -from LunaTAP.util.UtilityMethods import get_logger -import rpyc - -log = get_logger(__name__) - - -class RemotePycryptokiClient(): - ''' - Class forwards pycryptoki calls over xmlrpc. Some functions need more serialization - so they are directly handled, others are handled automagically by __get_attr__ - ''' - - def __init__(self, ip=None, port=None): - self.ip = ip - self.port = port - self.started = False - self.start() - - def kill(self): - #maybe we should be reloading cryptoki dll? - if self.started and not self.connection.closed: - log.info("Stopping remote pycryptoki connection.") - self.connection.close() - self.started = False - - def start(self): - if not self.started: - log.info("Starting remote pycryptoki connection") - self.connection = rpyc.classic.connect(self.ip, port=self.port) - self.server = self.connection.root - self.started = True - - def cleanup(self): - pass - - - def __getattr__(self, name): - ''' - This is the python default attribute handler, if an attribute - is not found it's probably a pycryptoki call that we forward - automagically to the server - ''' - if not self.started: - self.start() - if hasattr(self.server, name): - def wrapper(*args, **kwargs): - log.info("Running remote pycryptoki command: " - "{0}(args={1}, kwargs={2})".format(name, args, kwargs)) - return getattr(self.server, name)(*args, **kwargs) - return wrapper - else: - raise AttributeError(name) - - -class LocalPycryptokiClient(object): - ''' - Class forwards calls to pycryptoki to local client but looks identical to remote - client - ''' - - def __init__(self): - '''Nothing really to do''' - pass - - def __getattr__(self, name): - ''' - Function that overrides python attribute lookup; automagically calls - functions in pycryptoki if they're listed in the daemon - ''' - log.info("Running local pycryptoki command: {0}".format(name)) - if pycryptoki_functions.has_key(name): - if 'c_initialize' in name: - return object.__getattribute__(self, name) - return pycryptoki_functions[name] - elif functions_needing_serialization.has_key(name): - return functions_needing_serialization[name] - else: - return object.__getattribute__(self, name) - - def c_initialize_ex(self): - c_finalize() - return c_initialize_ex() - - def c_initialize(self): - c_finalize() - return c_initialize() - - def kill(self): - #nothing to do here, maybe we should unload and reload the dll - pass - - def cleanup(self): - #nothing to do here - pass - - -def deserialize_dict(dictionary): - ''' - Helper function to convert a dictionary with to - for xmlrpc - ''' - deserialized_dictionary = {} - for key, value in dictionary.iteritems(): - deserialized_dictionary[int(key)] = value - return deserialized_dictionary \ No newline at end of file +''' +Contains both a local and remote pycryptoki client +''' +from pycryptoki.daemon.pycryptoki_daemon import pycryptoki_functions,\ + functions_needing_serialization +from pycryptoki.session_management import c_finalize, c_initialize_ex, c_initialize +import logging +import rpyc + +log = logging.getLogger(__name__) + + +class RemotePycryptokiClient(): + ''' + Class forwards pycryptoki calls over xmlrpc. Some functions need more serialization + so they are directly handled, others are handled automagically by __get_attr__ + ''' + + def __init__(self, ip=None, port=None): + self.ip = ip + self.port = port + self.started = False + self.start() + + def kill(self): + #maybe we should be reloading cryptoki dll? + if self.started and not self.connection.closed: + log.info("Stopping remote pycryptoki connection.") + self.connection.close() + self.started = False + + def start(self): + if not self.started: + log.info("Starting remote pycryptoki connection") + self.connection = rpyc.classic.connect(self.ip, port=self.port) + self.server = self.connection.root + self.started = True + + def cleanup(self): + pass + + + def __getattr__(self, name): + ''' + This is the python default attribute handler, if an attribute + is not found it's probably a pycryptoki call that we forward + automagically to the server + ''' + if not self.started: + self.start() + if hasattr(self.server, name): + def wrapper(*args, **kwargs): + log.info("Running remote pycryptoki command: " + "{0}(args={1}, kwargs={2})".format(name, args, kwargs)) + return getattr(self.server, name)(*args, **kwargs) + return wrapper + else: + raise AttributeError(name) + + +class LocalPycryptokiClient(object): + ''' + Class forwards calls to pycryptoki to local client but looks identical to remote + client + ''' + + def __init__(self): + '''Nothing really to do''' + pass + + def __getattr__(self, name): + ''' + Function that overrides python attribute lookup; automagically calls + functions in pycryptoki if they're listed in the daemon + ''' + log.info("Running local pycryptoki command: {0}".format(name)) + if pycryptoki_functions.has_key(name): + if 'c_initialize' in name: + return object.__getattribute__(self, name) + return pycryptoki_functions[name] + elif functions_needing_serialization.has_key(name): + return functions_needing_serialization[name] + else: + return object.__getattribute__(self, name) + + def c_initialize_ex(self): + c_finalize() + return c_initialize_ex() + + def c_initialize(self): + c_finalize() + return c_initialize() + + def kill(self): + #nothing to do here, maybe we should unload and reload the dll + pass + + def cleanup(self): + #nothing to do here + pass + + +def deserialize_dict(dictionary): + ''' + Helper function to convert a dictionary with to + for xmlrpc + ''' + deserialized_dictionary = {} + for key, value in dictionary.iteritems(): + deserialized_dictionary[int(key)] = value + return deserialized_dictionary diff --git a/pycryptoki/return_values.py b/pycryptoki/return_values.py new file mode 100644 index 0000000..f3d8afe --- /dev/null +++ b/pycryptoki/return_values.py @@ -0,0 +1,174 @@ +''' +THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE +This file should NOT be checked into MKS or modified in any way, this file was +created by setup/initialize.py. Any changes to this file will be wiped out when +it is regenerated. + +This file contains a dictionary lookup for the readable string values +of defines whose variable name starts with CKR_. This convention means they are +a return value for the cryptoki C API. + +''' + +from defines import * + +ret_vals_dictionary = { + CKR_OK : 'CKR_OK', + CKR_CANCEL : 'CKR_CANCEL', + CKR_HOST_MEMORY : 'CKR_HOST_MEMORY', + CKR_SLOT_ID_INVALID : 'CKR_SLOT_ID_INVALID', + CKR_GENERAL_ERROR : 'CKR_GENERAL_ERROR', + CKR_FUNCTION_FAILED : 'CKR_FUNCTION_FAILED', + CKR_ARGUMENTS_BAD : 'CKR_ARGUMENTS_BAD', + CKR_NO_EVENT : 'CKR_NO_EVENT', + CKR_NEED_TO_CREATE_THREADS : 'CKR_NEED_TO_CREATE_THREADS', + CKR_CANT_LOCK : 'CKR_CANT_LOCK', + CKR_ATTRIBUTE_READ_ONLY : 'CKR_ATTRIBUTE_READ_ONLY', + CKR_ATTRIBUTE_SENSITIVE : 'CKR_ATTRIBUTE_SENSITIVE', + CKR_ATTRIBUTE_TYPE_INVALID : 'CKR_ATTRIBUTE_TYPE_INVALID', + CKR_ATTRIBUTE_VALUE_INVALID : 'CKR_ATTRIBUTE_VALUE_INVALID', + CKR_DATA_INVALID : 'CKR_DATA_INVALID', + CKR_DATA_LEN_RANGE : 'CKR_DATA_LEN_RANGE', + CKR_DEVICE_ERROR : 'CKR_DEVICE_ERROR', + CKR_DEVICE_MEMORY : 'CKR_DEVICE_MEMORY', + CKR_DEVICE_REMOVED : 'CKR_DEVICE_REMOVED', + CKR_ENCRYPTED_DATA_INVALID : 'CKR_ENCRYPTED_DATA_INVALID', + CKR_ENCRYPTED_DATA_LEN_RANGE : 'CKR_ENCRYPTED_DATA_LEN_RANGE', + CKR_FUNCTION_CANCELED : 'CKR_FUNCTION_CANCELED', + CKR_FUNCTION_NOT_PARALLEL : 'CKR_FUNCTION_NOT_PARALLEL', + CKR_FUNCTION_NOT_SUPPORTED : 'CKR_FUNCTION_NOT_SUPPORTED', + CKR_KEY_HANDLE_INVALID : 'CKR_KEY_HANDLE_INVALID', + CKR_KEY_SIZE_RANGE : 'CKR_KEY_SIZE_RANGE', + CKR_KEY_TYPE_INCONSISTENT : 'CKR_KEY_TYPE_INCONSISTENT', + CKR_KEY_NOT_NEEDED : 'CKR_KEY_NOT_NEEDED', + CKR_KEY_CHANGED : 'CKR_KEY_CHANGED', + CKR_KEY_NEEDED : 'CKR_KEY_NEEDED', + CKR_KEY_INDIGESTIBLE : 'CKR_KEY_INDIGESTIBLE', + CKR_KEY_FUNCTION_NOT_PERMITTED : 'CKR_KEY_FUNCTION_NOT_PERMITTED', + CKR_KEY_NOT_WRAPPABLE : 'CKR_KEY_NOT_WRAPPABLE', + CKR_KEY_UNEXTRACTABLE : 'CKR_KEY_UNEXTRACTABLE', + CKR_MECHANISM_INVALID : 'CKR_MECHANISM_INVALID', + CKR_MECHANISM_PARAM_INVALID : 'CKR_MECHANISM_PARAM_INVALID', + CKR_OBJECT_HANDLE_INVALID : 'CKR_OBJECT_HANDLE_INVALID', + CKR_OPERATION_ACTIVE : 'CKR_OPERATION_ACTIVE', + CKR_OPERATION_NOT_INITIALIZED : 'CKR_OPERATION_NOT_INITIALIZED', + CKR_PIN_INCORRECT : 'CKR_PIN_INCORRECT', + CKR_PIN_INVALID : 'CKR_PIN_INVALID', + CKR_PIN_LEN_RANGE : 'CKR_PIN_LEN_RANGE', + CKR_PIN_EXPIRED : 'CKR_PIN_EXPIRED', + CKR_PIN_LOCKED : 'CKR_PIN_LOCKED', + CKR_SESSION_CLOSED : 'CKR_SESSION_CLOSED', + CKR_SESSION_COUNT : 'CKR_SESSION_COUNT', + CKR_SESSION_HANDLE_INVALID : 'CKR_SESSION_HANDLE_INVALID', + CKR_SESSION_PARALLEL_NOT_SUPPORTED : 'CKR_SESSION_PARALLEL_NOT_SUPPORTED', + CKR_SESSION_READ_ONLY : 'CKR_SESSION_READ_ONLY', + CKR_SESSION_EXISTS : 'CKR_SESSION_EXISTS', + CKR_SESSION_READ_ONLY_EXISTS : 'CKR_SESSION_READ_ONLY_EXISTS', + CKR_SESSION_READ_WRITE_SO_EXISTS : 'CKR_SESSION_READ_WRITE_SO_EXISTS', + CKR_SIGNATURE_INVALID : 'CKR_SIGNATURE_INVALID', + CKR_SIGNATURE_LEN_RANGE : 'CKR_SIGNATURE_LEN_RANGE', + CKR_TEMPLATE_INCOMPLETE : 'CKR_TEMPLATE_INCOMPLETE', + CKR_TEMPLATE_INCONSISTENT : 'CKR_TEMPLATE_INCONSISTENT', + CKR_TOKEN_NOT_PRESENT : 'CKR_TOKEN_NOT_PRESENT', + CKR_TOKEN_NOT_RECOGNIZED : 'CKR_TOKEN_NOT_RECOGNIZED', + CKR_TOKEN_WRITE_PROTECTED : 'CKR_TOKEN_WRITE_PROTECTED', + CKR_UNWRAPPING_KEY_HANDLE_INVALID : 'CKR_UNWRAPPING_KEY_HANDLE_INVALID', + CKR_UNWRAPPING_KEY_SIZE_RANGE : 'CKR_UNWRAPPING_KEY_SIZE_RANGE', + CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT : 'CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT', + CKR_USER_ALREADY_LOGGED_IN : 'CKR_USER_ALREADY_LOGGED_IN', + CKR_USER_NOT_LOGGED_IN : 'CKR_USER_NOT_LOGGED_IN', + CKR_USER_PIN_NOT_INITIALIZED : 'CKR_USER_PIN_NOT_INITIALIZED', + CKR_USER_TYPE_INVALID : 'CKR_USER_TYPE_INVALID', + CKR_USER_ANOTHER_ALREADY_LOGGED_IN : 'CKR_USER_ANOTHER_ALREADY_LOGGED_IN', + CKR_USER_TOO_MANY_TYPES : 'CKR_USER_TOO_MANY_TYPES', + CKR_WRAPPED_KEY_INVALID : 'CKR_WRAPPED_KEY_INVALID', + CKR_WRAPPED_KEY_LEN_RANGE : 'CKR_WRAPPED_KEY_LEN_RANGE', + CKR_WRAPPING_KEY_HANDLE_INVALID : 'CKR_WRAPPING_KEY_HANDLE_INVALID', + CKR_WRAPPING_KEY_SIZE_RANGE : 'CKR_WRAPPING_KEY_SIZE_RANGE', + CKR_WRAPPING_KEY_TYPE_INCONSISTENT : 'CKR_WRAPPING_KEY_TYPE_INCONSISTENT', + CKR_RANDOM_SEED_NOT_SUPPORTED : 'CKR_RANDOM_SEED_NOT_SUPPORTED', + CKR_RANDOM_NO_RNG : 'CKR_RANDOM_NO_RNG', + CKR_DOMAIN_PARAMS_INVALID : 'CKR_DOMAIN_PARAMS_INVALID', + CKR_BUFFER_TOO_SMALL : 'CKR_BUFFER_TOO_SMALL', + CKR_SAVED_STATE_INVALID : 'CKR_SAVED_STATE_INVALID', + CKR_INFORMATION_SENSITIVE : 'CKR_INFORMATION_SENSITIVE', + CKR_STATE_UNSAVEABLE : 'CKR_STATE_UNSAVEABLE', + CKR_CRYPTOKI_NOT_INITIALIZED : 'CKR_CRYPTOKI_NOT_INITIALIZED', + CKR_CRYPTOKI_ALREADY_INITIALIZED : 'CKR_CRYPTOKI_ALREADY_INITIALIZED', + CKR_MUTEX_BAD : 'CKR_MUTEX_BAD', + CKR_MUTEX_NOT_LOCKED : 'CKR_MUTEX_NOT_LOCKED', + CKR_NEW_PIN_MODE : 'CKR_NEW_PIN_MODE', + CKR_NEXT_OTP : 'CKR_NEXT_OTP', + CKR_FUNCTION_REJECTED : 'CKR_FUNCTION_REJECTED', + CKR_VENDOR_DEFINED : 'CKR_VENDOR_DEFINED', + CKR_INSERTION_CALLBACK_NOT_SUPPORTED : 'CKR_INSERTION_CALLBACK_NOT_SUPPORTED', + CKR_FUNCTION_PARALLEL : 'CKR_FUNCTION_PARALLEL', + CKR_SESSION_EXCLUSIVE_EXISTS : 'CKR_SESSION_EXCLUSIVE_EXISTS', + CKR_RC_ERROR : 'CKR_RC_ERROR', + CKR_CONTAINER_HANDLE_INVALID : 'CKR_CONTAINER_HANDLE_INVALID', + CKR_TOO_MANY_CONTAINERS : 'CKR_TOO_MANY_CONTAINERS', + CKR_USER_LOCKED_OUT : 'CKR_USER_LOCKED_OUT', + CKR_CLONING_PARAMETER_ALREADY_EXISTS : 'CKR_CLONING_PARAMETER_ALREADY_EXISTS', + CKR_CLONING_PARAMETER_MISSING : 'CKR_CLONING_PARAMETER_MISSING', + CKR_CERTIFICATE_DATA_MISSING : 'CKR_CERTIFICATE_DATA_MISSING', + CKR_CERTIFICATE_DATA_INVALID : 'CKR_CERTIFICATE_DATA_INVALID', + CKR_ACCEL_DEVICE_ERROR : 'CKR_ACCEL_DEVICE_ERROR', + CKR_WRAPPING_ERROR : 'CKR_WRAPPING_ERROR', + CKR_UNWRAPPING_ERROR : 'CKR_UNWRAPPING_ERROR', + CKR_MAC_MISSING : 'CKR_MAC_MISSING', + CKR_DAC_POLICY_PID_MISMATCH : 'CKR_DAC_POLICY_PID_MISMATCH', + CKR_DAC_MISSING : 'CKR_DAC_MISSING', + CKR_BAD_DAC : 'CKR_BAD_DAC', + CKR_SSK_MISSING : 'CKR_SSK_MISSING', + CKR_BAD_MAC : 'CKR_BAD_MAC', + CKR_DAK_MISSING : 'CKR_DAK_MISSING', + CKR_BAD_DAK : 'CKR_BAD_DAK', + CKR_SIM_AUTHORIZATION_FAILED : 'CKR_SIM_AUTHORIZATION_FAILED', + CKR_SIM_VERSION_UNSUPPORTED : 'CKR_SIM_VERSION_UNSUPPORTED', + CKR_SIM_CORRUPT_DATA : 'CKR_SIM_CORRUPT_DATA', + CKR_USER_NOT_AUTHORIZED : 'CKR_USER_NOT_AUTHORIZED', + CKR_MAX_OBJECT_COUNT_EXCEEDED : 'CKR_MAX_OBJECT_COUNT_EXCEEDED', + CKR_SO_LOGIN_FAILURE_THRESHOLD : 'CKR_SO_LOGIN_FAILURE_THRESHOLD', + CKR_SIM_AUTHFORM_INVALID : 'CKR_SIM_AUTHFORM_INVALID', + CKR_CITS_DAK_MISSING : 'CKR_CITS_DAK_MISSING', + CKR_UNABLE_TO_CONNECT : 'CKR_UNABLE_TO_CONNECT', + CKR_PARTITION_DISABLED : 'CKR_PARTITION_DISABLED', + CKR_CALLBACK_ERROR : 'CKR_CALLBACK_ERROR', + CKR_SECURITY_PARAMETER_MISSING : 'CKR_SECURITY_PARAMETER_MISSING', + CKR_SP_TIMEOUT : 'CKR_SP_TIMEOUT', + CKR_TIMEOUT : 'CKR_TIMEOUT', + CKR_ECC_UNKNOWN_CURVE : 'CKR_ECC_UNKNOWN_CURVE', + CKR_MTK_ZEROIZED : 'CKR_MTK_ZEROIZED', + CKR_MTK_STATE_INVALID : 'CKR_MTK_STATE_INVALID', + CKR_INVALID_ENTRY_TYPE : 'CKR_INVALID_ENTRY_TYPE', + CKR_MTK_SPLIT_INVALID : 'CKR_MTK_SPLIT_INVALID', + CKR_HSM_STORAGE_FULL : 'CKR_HSM_STORAGE_FULL', + CKR_DEVICE_TIMEOUT : 'CKR_DEVICE_TIMEOUT', + CKR_CONTAINER_OBJECT_STORAGE_FULL : 'CKR_CONTAINER_OBJECT_STORAGE_FULL', + CKR_PED_CLIENT_NOT_RUNNING : 'CKR_PED_CLIENT_NOT_RUNNING', + CKR_PED_UNPLUGGED : 'CKR_PED_UNPLUGGED', + CKR_ECC_POINT_INVALID : 'CKR_ECC_POINT_INVALID', + CKR_OPERATION_NOT_ALLOWED : 'CKR_OPERATION_NOT_ALLOWED', + CKR_LICENSE_CAPACITY_EXCEEDED : 'CKR_LICENSE_CAPACITY_EXCEEDED', + CKR_LOG_FILE_NOT_OPEN : 'CKR_LOG_FILE_NOT_OPEN', + CKR_LOG_FILE_WRITE_ERROR : 'CKR_LOG_FILE_WRITE_ERROR', + CKR_LOG_BAD_FILE_NAME : 'CKR_LOG_BAD_FILE_NAME', + CKR_LOG_FULL : 'CKR_LOG_FULL', + CKR_LOG_NO_KCV : 'CKR_LOG_NO_KCV', + CKR_LOG_BAD_RECORD_HMAC : 'CKR_LOG_BAD_RECORD_HMAC', + CKR_LOG_BAD_TIME : 'CKR_LOG_BAD_TIME', + CKR_LOG_AUDIT_NOT_INITIALIZED : 'CKR_LOG_AUDIT_NOT_INITIALIZED', + CKR_LOG_RESYNC_NEEDED : 'CKR_LOG_RESYNC_NEEDED', + CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS : 'CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', + CKR_AUDIT_LOGIN_FAILURE_THRESHOLD : 'CKR_AUDIT_LOGIN_FAILURE_THRESHOLD', + CKR_INVALID_FUF_TARGET : 'CKR_INVALID_FUF_TARGET', + CKR_INVALID_FUF_HEADER : 'CKR_INVALID_FUF_HEADER', + CKR_INVALID_FUF_VERSION : 'CKR_INVALID_FUF_VERSION', + CKR_ECC_ECC_RESULT_AT_INF : 'CKR_ECC_ECC_RESULT_AT_INF', + CKR_AGAIN : 'CKR_AGAIN', + CKR_TOKEN_COPIED : 'CKR_TOKEN_COPIED', + CKR_SLOT_NOT_EMPTY : 'CKR_SLOT_NOT_EMPTY', + CKR_USER_ALREADY_ACTIVATED : 'CKR_USER_ALREADY_ACTIVATED', + CKR_OBJECT_READ_ONLY : 'CKR_OBJECT_READ_ONLY', + CKR_KEY_NOT_ACTIVE : 'CKR_KEY_NOT_ACTIVE' +} \ No newline at end of file diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index c43b36f..1e90006 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -1,358 +1,358 @@ -""" -Methods responsible for managing a user's session and login/c_logout -""" -from cryptoki import C_Initialize, CK_ULONG, C_GetSlotList, CK_BBOOL, CK_SLOT_ID, \ - CK_SLOT_INFO, C_GetSlotInfo, C_CloseAllSessions, C_GetSessionInfo, CK_SESSION_HANDLE, \ - CK_SESSION_INFO, C_OpenSession, CK_FLAGS, CK_NOTIFY, C_Login, CK_USER_TYPE, C_Logout, \ - C_CloseSession, C_InitPIN, CA_FactoryReset, \ - C_GetTokenInfo, CK_TOKEN_INFO, C_Finalize, C_SetPIN, CA_DeleteContainerWithHandle, CA_OpenApplicationID, \ - CA_CloseApplicationID, CA_Restart, CA_SetApplicationID -from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ - byref, pointer -from defines import CKR_OK -from pycryptoki.cryptoki import CA_CreateContainer, CK_VOID_PTR, \ - CK_BYTE_PTR -from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION -from pycryptoki.test_functions import make_error_handle_function -import logging -import re - -logger = logging.getLogger(__name__) - - -def c_initialize(): - ''' - Calls C_Initialize to c_initialize the board - - @return: The result code - ''' - # INITIALIZE - logger.info("C_Initialize: Initializing HSM") - ret = C_Initialize(0) - return ret; -c_initialize_ex = make_error_handle_function(c_initialize) - - -def c_finalize(): - ''' - Calls C_Finalize - - @return: The result code - ''' - logger.info("C_Finalize: Finalizing HSM") - ret = C_Finalize(0) - return ret; -c_finalize_ex = make_error_handle_function(c_finalize) - -def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): - ''' - Opens a session on a given slot - - @param slot_num: The slot to get a session on - @param flags: The flags to open the session with - @return: The result code, the session handle - ''' - #OPEN SESSION - arg3 = create_string_buffer("Application") - h_session = CK_SESSION_HANDLE() - arg3 = cast(arg3, c_void_p) #CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) - ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), pointer(h_session)) - logger.info("C_OpenSession: Opening Session. slot=" + str(slot_num)) - - return ret, h_session.value -c_open_session_ex = make_error_handle_function(c_open_session) - -def login(h_session, slot_num=1, password="userpin", user_type=1): - ''' - Login to the HSM - @param h_session: Current session - @param slot_num: Slot index to login on - @param password: Password to login with - @param user_type: User type to login as - - @return: The result code - ''' - # LOGIN - user_type = long(user_type) - pb_password = c_char_p(password) - logger.info("C_Login: Logging In. user_type=" + str(user_type) + ", slot=" + str(slot_num) + ", password=" + password) - ret = C_Login(h_session, CK_USER_TYPE(user_type), cast(pb_password, CK_BYTE_PTR), CK_ULONG(len(password))) - return ret; -login_ex = make_error_handle_function(login) - -def get_slot_info(description): - ''' - Returns a slot with a certain descriptor - - Limitation: Only returns the first slot it finds that fits the description - @param description: The name of the slot to find - - @return: THe result code, a Python dictionary representing the slots - ''' - ret, slot_dict = get_slot_dict() - - return_dict = {} - - for key in slot_dict: - if re.match(description, slot_dict[key]): - return_dict[key] = slot_dict[key] - - return ret, return_dict -get_slot_info_ex = make_error_handle_function(get_slot_info) - -def c_get_session_info(session): - ''' - :param session: - :return: - ''' - session_info = {} - c_session_info = CK_SESSION_INFO() - ret = C_GetSessionInfo(CK_SESSION_HANDLE(session), byref(c_session_info)) - - if (ret == CKR_OK): - session_info['state'] = c_session_info.state - session_info['flags'] = c_session_info.flags - session_info['slotID'] = c_session_info.slotID - session_info['usDeviceError'] = c_session_info.usDeviceError - - return ret, session_info -c_get_session_info_ex = make_error_handle_function(c_get_session_info) - -def c_get_token_info(slot_id): - ''' - Gets the token info for a given slot id - @param slot_id: Slot index to get the token info for - - @return: The result code, A python dictionary representing the token info - ''' - token_info = {} - c_token_info = CK_TOKEN_INFO() - logger.info("Getting token info. slot=" + str(slot_id)) - ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) - - if (ret == CKR_OK): - token_info['label'] = str(cast(c_token_info.label, c_char_p).value)[0:32].strip() - token_info['manufacturerID'] = str(cast(c_token_info.manufacturerID, c_char_p).value)[0:32].strip() - token_info['model'] = str(cast(c_token_info.model, c_char_p).value)[0:16].strip() - token_info['serialNumber'] = int(str(cast(c_token_info.serialNumber, c_char_p).value)[0:16].strip()) - token_info['flags'] = c_token_info.flags - token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory - token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory - token_info['ulMaxSessionCount'] = c_token_info.usMaxSessionCount - token_info['ulSessionCount'] = c_token_info.usSessionCount - token_info['ulMaxRwSessionCount'] = c_token_info.usMaxRwSessionCount - token_info['ulRwSessionCount'] = c_token_info.usRwSessionCount - token_info['ulMaxPinLen'] = c_token_info.usMaxPinLen - token_info['ulMinPinLen'] = c_token_info.usMinPinLen - token_info['ulTotalPublicMemory'] = c_token_info.ulTotalPublicMemory - token_info['ulFreePublicMemory'] = c_token_info.ulFreePublicMemory - token_info['hardwareVersion'] = c_token_info.hardwareVersion - token_info['firmwareVersion'] = c_token_info.firmwareVersion - token_info['utcTime'] = str(cast(c_token_info.utcTime, c_char_p).value)[0:16].strip() - - return ret, token_info -c_get_token_info_ex = make_error_handle_function(c_get_token_info) - -def get_slot_dict(): - ''' - Compiles a dictionary of the available slots - - @return: A python dictionary of the available slots - ''' - us_count = CK_ULONG(0) - ret = C_GetSlotList(CK_BBOOL(0), None, byref(us_count)) - if ret != CKR_OK: return ret - num_slots = (us_count.value + 1) - slot_list = (CK_SLOT_ID * num_slots)() - ret = C_GetSlotList(CK_BBOOL(0), slot_list, byref(us_count)) - if ret != CKR_OK: return ret - slot_info = CK_SLOT_INFO() - slot_dict = {} - for slot in slot_list: - C_GetSlotInfo(slot, byref(slot_info)) - slot_description = str(cast(slot_info.slotDescription, c_char_p).value)[0:63].strip() - slot_dict[slot] = slot_description - - return ret, slot_dict -get_slot_dict_ex = make_error_handle_function(get_slot_dict) - -def c_close_session(h_session): - ''' - Closes a session - @param h_session: The session to close - - @return: The result code - ''' - # CLOSE SESSION - logger.info("C_CloseSession: Closing session " + str(h_session)) - ret = C_CloseSession(h_session) - return ret -c_close_session_ex = make_error_handle_function(c_close_session) - -def c_logout(h_session): - ''' - Logs out of a given session - @param h_session: The session to log out from - - @return: The result code - ''' - logger.info("C_Logout: Logging out of session " + str(h_session)) - ret = C_Logout(h_session) - return ret -c_logout_ex = make_error_handle_function(c_logout) - -def c_init_pin(h_session, pin): - ''' - Initializes the PIN - @param h_session: Current session - @param pin: pin to c_initialize - - @return: THe result code - ''' - - logger.info("C_InitPIN: Initializing PIN to " + str(pin)) - if pin == '': - ret = C_InitPIN(h_session, None, CK_ULONG(0)) - else: - ret = C_InitPIN(h_session, cast(create_string_buffer(pin), CK_BYTE_PTR), CK_ULONG(len(pin))) - return ret -c_init_pin_ex = make_error_handle_function(c_init_pin) - -def ca_factory_reset(slot): - ''' - Does a factory reset on a given slot - @param slot: The slot to do a factory reset on - - @return: The result code - ''' - logger.info("CA_FactoryReset: Factory Reset. slot=" + str(slot)) - ret = CA_FactoryReset(CK_SLOT_ID(slot), CK_ULONG(0)) - return ret -ca_factory_reset_ex = make_error_handle_function(ca_factory_reset) - -def c_set_pin(h_session, old_pass, new_pass): - ''' - Allows a user to change their PIN - @param h_session: Session of the user - @param old_pass: The user's old password - @param new_pass: The user's desired new password - - @return: The result code - ''' - logger.info("C_SetPIN: Changing password. old_pass=" + str(old_pass) + ", new_pass=" + str(new_pass)) - if old_pass == '' and new_pass == '': - ret = C_SetPIN(h_session, None, CK_ULONG(0), - None, CK_ULONG(0)) - return ret - else: - ret = C_SetPIN(h_session, cast(create_string_buffer(old_pass), CK_BYTE_PTR), CK_ULONG(len(old_pass)), - cast(create_string_buffer(new_pass), CK_BYTE_PTR), CK_ULONG(len(new_pass))) - return ret -c_set_pin_ex = make_error_handle_function(c_set_pin) - -def c_close_all_sessions(slot): - ''' - Closes all the sessions on a given slot - @param slot: The slot to close all sessions on - - @return The result code - ''' - - logger.info("C_CloseAllSessions: Closing all sessions. slot=" + str(slot)) - ret = C_CloseAllSessions(CK_ULONG(slot)) - return ret -c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) - -def ca_create_container(h_session, storage_size, password='userpin', label='Inserted Token'): - ''' - Inserts a token into a slot without a Security Officer on the token - @param h_session: Current session - @param storage_size: The storage size of the token (0 for undefined/unlimited) - @param password: The password associated with the token - @param label: The label associated with the token - - @return: The result code, The container number - ''' - - if password == '': - container_number = CK_ULONG() - logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) - ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), None, - CK_ULONG(0), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) - logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) - return ret, container_number.value - else: - container_number = CK_ULONG() - logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) - ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), cast(create_string_buffer(password), CK_BYTE_PTR), - CK_ULONG(len(password)), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) - logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) - return ret, container_number.value -ca_create_container_ex = make_error_handle_function(ca_create_container) - -def ca_delete_container_with_handle(h_session, container_handle): - container_number = CK_ULONG(container_handle) - logger.info("CA_DeleteContainerWithHandle: Attempting to delete container with handle: {0}".format(container_handle)) - - ret = CA_DeleteContainerWithHandle(h_session, container_number) - - logger.info("CA_DeleteContainerWithHandle: Ret Value: {0}".format(ret)) - - return ret -ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) - - -def ca_openapplicationID(slot, id_high, id_low): - uid_high = CK_ULONG(id_high) - uid_low = CK_ULONG(id_low) - - logger.info("CA_OpenApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) - - ret = CA_OpenApplicationID(CK_ULONG(slot), uid_high, uid_low) - - logger.info("CA_OpenApplicationID: Ret Value: {0}".format(ret)) - - return ret -ca_openapplicationID_ex= make_error_handle_function(ca_openapplicationID) - - -def ca_closeapplicationID(slot, id_high, id_low): - uid_high = CK_ULONG(id_high) - uid_low = CK_ULONG(id_low) - - logger.info("CA_CloseApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) - - ret = CA_CloseApplicationID(CK_ULONG(slot), uid_high, uid_low) - - logger.info("CA_CloseApplicationID: Ret Value: {0}".format(ret)) - - return ret -ca_closeapplicationID_ex= make_error_handle_function(ca_closeapplicationID) - - -def ca_setapplicationID(id_high, id_low): - """ - Set the App ID for the current application. - """ - uid_high = CK_ULONG(id_high) - uid_low = CK_ULONG(id_low) - - logger.info("CA_SetApplicationID: Attempting to set App ID {0}:{1}".format(id_high, id_low)) - - ret = CA_SetApplicationID(uid_high, uid_low) - - logger.info("CA_SetApplicationID: Ret Value: {0}".format(ret)) - - return ret -ca_setapplicationID_ex= make_error_handle_function(ca_setapplicationID) - - -def ca_restart(slot): - logger.info("CA_Restart: attempting to restart") - - ret = CA_Restart(CK_ULONG(slot)) - - logger.info("CA_Restart: Ret Value: {0}".format(ret)) - - return ret -ca_restart_ex = make_error_handle_function(ca_restart) +""" +Methods responsible for managing a user's session and login/c_logout +""" +from cryptoki import C_Initialize, CK_ULONG, C_GetSlotList, CK_BBOOL, CK_SLOT_ID, \ + CK_SLOT_INFO, C_GetSlotInfo, C_CloseAllSessions, C_GetSessionInfo, CK_SESSION_HANDLE, \ + CK_SESSION_INFO, C_OpenSession, CK_FLAGS, CK_NOTIFY, C_Login, CK_USER_TYPE, C_Logout, \ + C_CloseSession, C_InitPIN, CA_FactoryReset, \ + C_GetTokenInfo, CK_TOKEN_INFO, C_Finalize, C_SetPIN, CA_DeleteContainerWithHandle, CA_OpenApplicationID, \ + CA_CloseApplicationID, CA_Restart, CA_SetApplicationID +from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ + byref, pointer +from defines import CKR_OK +from pycryptoki.cryptoki import CA_CreateContainer, CK_VOID_PTR, \ + CK_BYTE_PTR +from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION +from pycryptoki.test_functions import make_error_handle_function +import logging +import re + +logger = logging.getLogger(__name__) + + +def c_initialize(): + ''' + Calls C_Initialize to c_initialize the board + + @return: The result code + ''' + # INITIALIZE + logger.info("C_Initialize: Initializing HSM") + ret = C_Initialize(0) + return ret; +c_initialize_ex = make_error_handle_function(c_initialize) + + +def c_finalize(): + ''' + Calls C_Finalize + + @return: The result code + ''' + logger.info("C_Finalize: Finalizing HSM") + ret = C_Finalize(0) + return ret; +c_finalize_ex = make_error_handle_function(c_finalize) + +def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): + ''' + Opens a session on a given slot + + @param slot_num: The slot to get a session on + @param flags: The flags to open the session with + @return: The result code, the session handle + ''' + #OPEN SESSION + arg3 = create_string_buffer("Application") + h_session = CK_SESSION_HANDLE() + arg3 = cast(arg3, c_void_p) #CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) + ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), pointer(h_session)) + logger.info("C_OpenSession: Opening Session. slot=" + str(slot_num)) + + return ret, h_session.value +c_open_session_ex = make_error_handle_function(c_open_session) + +def login(h_session, slot_num=1, password="userpin", user_type=1): + ''' + Login to the HSM + @param h_session: Current session + @param slot_num: Slot index to login on + @param password: Password to login with + @param user_type: User type to login as + + @return: The result code + ''' + # LOGIN + user_type = long(user_type) + pb_password = c_char_p(password) + logger.info("C_Login: Logging In. user_type=" + str(user_type) + ", slot=" + str(slot_num) + ", password=" + password) + ret = C_Login(h_session, CK_USER_TYPE(user_type), cast(pb_password, CK_BYTE_PTR), CK_ULONG(len(password))) + return ret; +login_ex = make_error_handle_function(login) + +def get_slot_info(description): + ''' + Returns a slot with a certain descriptor + + Limitation: Only returns the first slot it finds that fits the description + @param description: The name of the slot to find + + @return: THe result code, a Python dictionary representing the slots + ''' + ret, slot_dict = get_slot_dict() + + return_dict = {} + + for key in slot_dict: + if re.match(description, slot_dict[key]): + return_dict[key] = slot_dict[key] + + return ret, return_dict +get_slot_info_ex = make_error_handle_function(get_slot_info) + +def c_get_session_info(session): + ''' + :param session: + :return: + ''' + session_info = {} + c_session_info = CK_SESSION_INFO() + ret = C_GetSessionInfo(CK_SESSION_HANDLE(session), byref(c_session_info)) + + if (ret == CKR_OK): + session_info['state'] = c_session_info.state + session_info['flags'] = c_session_info.flags + session_info['slotID'] = c_session_info.slotID + session_info['usDeviceError'] = c_session_info.usDeviceError + + return ret, session_info +c_get_session_info_ex = make_error_handle_function(c_get_session_info) + +def c_get_token_info(slot_id): + ''' + Gets the token info for a given slot id + @param slot_id: Slot index to get the token info for + + @return: The result code, A python dictionary representing the token info + ''' + token_info = {} + c_token_info = CK_TOKEN_INFO() + logger.info("Getting token info. slot=" + str(slot_id)) + ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) + + if (ret == CKR_OK): + token_info['label'] = str(cast(c_token_info.label, c_char_p).value)[0:32].strip() + token_info['manufacturerID'] = str(cast(c_token_info.manufacturerID, c_char_p).value)[0:32].strip() + token_info['model'] = str(cast(c_token_info.model, c_char_p).value)[0:16].strip() + token_info['serialNumber'] = int(str(cast(c_token_info.serialNumber, c_char_p).value)[0:16].strip()) + token_info['flags'] = c_token_info.flags + token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory + token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory + token_info['ulMaxSessionCount'] = c_token_info.usMaxSessionCount + token_info['ulSessionCount'] = c_token_info.usSessionCount + token_info['ulMaxRwSessionCount'] = c_token_info.usMaxRwSessionCount + token_info['ulRwSessionCount'] = c_token_info.usRwSessionCount + token_info['ulMaxPinLen'] = c_token_info.usMaxPinLen + token_info['ulMinPinLen'] = c_token_info.usMinPinLen + token_info['ulTotalPublicMemory'] = c_token_info.ulTotalPublicMemory + token_info['ulFreePublicMemory'] = c_token_info.ulFreePublicMemory + token_info['hardwareVersion'] = c_token_info.hardwareVersion + token_info['firmwareVersion'] = c_token_info.firmwareVersion + token_info['utcTime'] = str(cast(c_token_info.utcTime, c_char_p).value)[0:16].strip() + + return ret, token_info +c_get_token_info_ex = make_error_handle_function(c_get_token_info) + +def get_slot_dict(): + ''' + Compiles a dictionary of the available slots + + @return: A python dictionary of the available slots + ''' + us_count = CK_ULONG(0) + ret = C_GetSlotList(CK_BBOOL(0), None, byref(us_count)) + if ret != CKR_OK: return ret + num_slots = (us_count.value + 1) + slot_list = (CK_SLOT_ID * num_slots)() + ret = C_GetSlotList(CK_BBOOL(0), slot_list, byref(us_count)) + if ret != CKR_OK: return ret + slot_info = CK_SLOT_INFO() + slot_dict = {} + for slot in slot_list: + C_GetSlotInfo(slot, byref(slot_info)) + slot_description = str(cast(slot_info.slotDescription, c_char_p).value)[0:63].strip() + slot_dict[slot] = slot_description + + return ret, slot_dict +get_slot_dict_ex = make_error_handle_function(get_slot_dict) + +def c_close_session(h_session): + ''' + Closes a session + @param h_session: The session to close + + @return: The result code + ''' + # CLOSE SESSION + logger.info("C_CloseSession: Closing session " + str(h_session)) + ret = C_CloseSession(h_session) + return ret +c_close_session_ex = make_error_handle_function(c_close_session) + +def c_logout(h_session): + ''' + Logs out of a given session + @param h_session: The session to log out from + + @return: The result code + ''' + logger.info("C_Logout: Logging out of session " + str(h_session)) + ret = C_Logout(h_session) + return ret +c_logout_ex = make_error_handle_function(c_logout) + +def c_init_pin(h_session, pin): + ''' + Initializes the PIN + @param h_session: Current session + @param pin: pin to c_initialize + + @return: THe result code + ''' + + logger.info("C_InitPIN: Initializing PIN to " + str(pin)) + if pin == '': + ret = C_InitPIN(h_session, None, CK_ULONG(0)) + else: + ret = C_InitPIN(h_session, cast(create_string_buffer(pin), CK_BYTE_PTR), CK_ULONG(len(pin))) + return ret +c_init_pin_ex = make_error_handle_function(c_init_pin) + +def ca_factory_reset(slot): + ''' + Does a factory reset on a given slot + @param slot: The slot to do a factory reset on + + @return: The result code + ''' + logger.info("CA_FactoryReset: Factory Reset. slot=" + str(slot)) + ret = CA_FactoryReset(CK_SLOT_ID(slot), CK_ULONG(0)) + return ret +ca_factory_reset_ex = make_error_handle_function(ca_factory_reset) + +def c_set_pin(h_session, old_pass, new_pass): + ''' + Allows a user to change their PIN + @param h_session: Session of the user + @param old_pass: The user's old password + @param new_pass: The user's desired new password + + @return: The result code + ''' + logger.info("C_SetPIN: Changing password. old_pass=" + str(old_pass) + ", new_pass=" + str(new_pass)) + if old_pass == '' and new_pass == '': + ret = C_SetPIN(h_session, None, CK_ULONG(0), + None, CK_ULONG(0)) + return ret + else: + ret = C_SetPIN(h_session, cast(create_string_buffer(old_pass), CK_BYTE_PTR), CK_ULONG(len(old_pass)), + cast(create_string_buffer(new_pass), CK_BYTE_PTR), CK_ULONG(len(new_pass))) + return ret +c_set_pin_ex = make_error_handle_function(c_set_pin) + +def c_close_all_sessions(slot): + ''' + Closes all the sessions on a given slot + @param slot: The slot to close all sessions on + + @return The result code + ''' + + logger.info("C_CloseAllSessions: Closing all sessions. slot=" + str(slot)) + ret = C_CloseAllSessions(CK_ULONG(slot)) + return ret +c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) + +def ca_create_container(h_session, storage_size, password='userpin', label='Inserted Token'): + ''' + Inserts a token into a slot without a Security Officer on the token + @param h_session: Current session + @param storage_size: The storage size of the token (0 for undefined/unlimited) + @param password: The password associated with the token + @param label: The label associated with the token + + @return: The result code, The container number + ''' + + if password == '': + container_number = CK_ULONG() + logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) + ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), None, + CK_ULONG(0), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) + logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) + return ret, container_number.value + else: + container_number = CK_ULONG() + logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) + ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), cast(create_string_buffer(password), CK_BYTE_PTR), + CK_ULONG(len(password)), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) + logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) + return ret, container_number.value +ca_create_container_ex = make_error_handle_function(ca_create_container) + +def ca_delete_container_with_handle(h_session, container_handle): + container_number = CK_ULONG(container_handle) + logger.info("CA_DeleteContainerWithHandle: Attempting to delete container with handle: {0}".format(container_handle)) + + ret = CA_DeleteContainerWithHandle(h_session, container_number) + + logger.info("CA_DeleteContainerWithHandle: Ret Value: {0}".format(ret)) + + return ret +ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) + + +def ca_openapplicationID(slot, id_high, id_low): + uid_high = CK_ULONG(id_high) + uid_low = CK_ULONG(id_low) + + logger.info("CA_OpenApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) + + ret = CA_OpenApplicationID(CK_ULONG(slot), uid_high, uid_low) + + logger.info("CA_OpenApplicationID: Ret Value: {0}".format(ret)) + + return ret +ca_openapplicationID_ex= make_error_handle_function(ca_openapplicationID) + + +def ca_closeapplicationID(slot, id_high, id_low): + uid_high = CK_ULONG(id_high) + uid_low = CK_ULONG(id_low) + + logger.info("CA_CloseApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) + + ret = CA_CloseApplicationID(CK_ULONG(slot), uid_high, uid_low) + + logger.info("CA_CloseApplicationID: Ret Value: {0}".format(ret)) + + return ret +ca_closeapplicationID_ex= make_error_handle_function(ca_closeapplicationID) + + +def ca_setapplicationID(id_high, id_low): + """ + Set the App ID for the current application. + """ + uid_high = CK_ULONG(id_high) + uid_low = CK_ULONG(id_low) + + logger.info("CA_SetApplicationID: Attempting to set App ID {0}:{1}".format(id_high, id_low)) + + ret = CA_SetApplicationID(uid_high, uid_low) + + logger.info("CA_SetApplicationID: Ret Value: {0}".format(ret)) + + return ret +ca_setapplicationID_ex= make_error_handle_function(ca_setapplicationID) + + +def ca_restart(slot): + logger.info("CA_Restart: attempting to restart") + + ret = CA_Restart(CK_ULONG(slot)) + + logger.info("CA_Restart: Ret Value: {0}".format(ret)) + + return ret +ca_restart_ex = make_error_handle_function(ca_restart) diff --git a/pycryptoki/setup/distribute.py b/pycryptoki/setup/distribute.py index 6dcda37..cecaf49 100755 --- a/pycryptoki/setup/distribute.py +++ b/pycryptoki/setup/distribute.py @@ -1,37 +1,37 @@ -import argparse -import os -import sys -import initialize - -print "PyCryptoki Source Code Distribution" -print "Use -h for argument information." - -parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and creates a source tarball in pycryptoki/dist..") -parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") -parser.add_argument('-dll', metavar='', required=True, help="The path to the libCryptoki2.so which will be opened and parsed, this must be the dll corresponding to Luna's components sandbox.") - -print "-------------------------------------------------------" -print " Autogenerating Python Bindings to Cryptoki" -print "-------------------------------------------------------" - -args = parser.parse_args() -options = vars(args) - -#Create all of the necessary automatically generated source -xml_output = 'h2xmlout_tmp.xml' - -if not (options['dll'] == None): - dll_path = options['dll'] -else: - if "linux" in sys.platform: - dll_path = '/usr/lib/libCryptoki2.so' - else: - raise Exception("Platform not yet supported.") - -initialize.initialize(options['lib'], dll_path) - -print "-------------------------------------------------------" -print " Packaging Source Distribution" -print "-------------------------------------------------------" -os.chdir("../../") +import argparse +import os +import sys +import initialize + +print "PyCryptoki Source Code Distribution" +print "Use -h for argument information." + +parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and creates a source tarball in pycryptoki/dist..") +parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") +parser.add_argument('-dll', metavar='', required=True, help="The path to the libCryptoki2.so which will be opened and parsed, this must be the dll corresponding to Luna's components sandbox.") + +print "-------------------------------------------------------" +print " Autogenerating Python Bindings to Cryptoki" +print "-------------------------------------------------------" + +args = parser.parse_args() +options = vars(args) + +#Create all of the necessary automatically generated source +xml_output = 'h2xmlout_tmp.xml' + +if not (options['dll'] == None): + dll_path = options['dll'] +else: + if "linux" in sys.platform: + dll_path = '/usr/lib/libCryptoki2.so' + else: + raise Exception("Platform not yet supported.") + +initialize.initialize(options['lib'], dll_path) + +print "-------------------------------------------------------" +print " Packaging Source Distribution" +print "-------------------------------------------------------" +os.chdir("../../") os.system('python setup.py sdist') \ No newline at end of file diff --git a/pycryptoki/setup/initialize.py b/pycryptoki/setup/initialize.py index f8b9d28..e0d175f 100755 --- a/pycryptoki/setup/initialize.py +++ b/pycryptoki/setup/initialize.py @@ -1,403 +1,403 @@ -""" -Setup script that will automatically generate the cryptoki.py and defines.py files. -This will get your library from your LUNA_LIBRARY environment variable and generate these -files. These files contains the defines that are in the C code and in addition contain the -CTypes formatted structs contained in the C code. - -Cryptoki.py contains the CTypes templates for the C Structs that are in the cryptoki C code. -Defines.py is a crude wrapper around a number of header files that uses a bad regular expression to -harvest the defines. - -Download gccxml from CVS (note: CVS seems to be blocked on the CVS network, you can get this from smb://172.20.11.83/ftp/forMike) -Compile gccxml -1) Recursively run dos2unix on gccxml source tree (find . -name *.* -exec dos2unix {} \;) -2) Create a folder in the same directory as gccxml is in called gccxml-build (ex /home/mhughes/gccxml and /home/mhughes/gccxml-build) -3) cd gccxml-build -4) cmake ../gccxml -DCMAKE_INSTALL_PREFIX:PATH=/home/mhughes/gccxml-build -5) make -6) make install -7) Add gccxml folder to your path - -Install python -Install python packages needed for ctypes -1) sudo pip install ctypes -2) sudo easy_install ctypeslib==dev - -Make sure pycryptoki and pycryptoki/utils are in your PYTHONPATH. In eclipse: -1) Right click on your project -2) Select Properties -3) Select PyDev - PYTHONPATH -4) Add source folder -5) Add pycryptoki and pycryptoki/utils - -Set you LUNA_LIBRARY environment variable to the path to your library. It is assumed that your -dll is in the proper path in the library -""" -from ctypeslib import h2xml, xml2py -import argparse -import os -import platform -import re -import stat -import sys - -ret_list = [] -header_files = [os.path.join("interfaces", "Include", "firmware", "luna2if.h")] -dll_path_var_name = 'DLL_PATH' -cryptoki_filename = os.path.join("..", "cryptoki.py") - -def is_nextgen_check(library_path): - ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') - return os.path.exists(ctlib_path) - -def initialize(library_path=None, dll_path=None): - ''' - Creates the cryptoki.py, defines.py and return_values.py files. - :param library_path: The path to the MKS Components sandbox - ''' - xml_output = 'h2xmlout_tmp.xml' - - library_path = parse_library(library_path, xml_output) - cryptoki_dll_path = dll_path - convert_to_python_binding(cryptoki_dll_path, xml_output, cryptoki_filename) - print "Finished!" - -def change_cryptoki_dll_path(new_dll_path): - if not os.path.exists(cryptoki_filename): - raise Exception("Error... cryptoki.py not found.") - - print "Removing references to DLL in cryptoki.py to achieve late binding to DLL" - - #Read in the current file - cryptoki_file = open(cryptoki_filename, "r") - file_contents = cryptoki_file.read() - cryptoki_file.close() - - #Create a backup - try: - os.remove(cryptoki_filename + ".bak") - except: - #Don't care this was only removing the old backup if one existed - pass - - print "Creating backup: cryptoki.py.bak" - os.rename(cryptoki_filename, cryptoki_filename + ".bak") - - #Find the previous path - print re.findall("CDLL\((.*)\)", file_contents)[0] - current_path = re.findall("CDLL\((.*)\)", file_contents)[0] - - if "win" in platform.system(): - current_path = current_path.replace("\\", '~').replace('~', '\\\\\\\\') - - new_contents = file_contents.replace(current_path, new_dll_path) - - #Remove all references to DLL to load it later - new_contents = re.sub("_libraries\s*=\s*{}\s*", "", new_contents) - new_contents = re.sub("_libraries\[DLL_PATH\]\s*=\s*CDLL\(DLL_PATH\)\s*", "", new_contents) - - #Windows needs to have _pack_ = 1 for every single struct, has to be declared before _fields_ is set - struct_names = re.findall("(\S+)\._fields_\s=\s", new_contents) - fields = re.compile("\S+\._fields_\s=\s[^\]]*]", re.MULTILINE | re.DOTALL) - field_declaration = re.findall(fields, new_contents) - - assert len(field_declaration) == len(struct_names) - for i in range(0, len(field_declaration)): - add_pack_string = "if 'win' in sys.platform:\n " + struct_names[i] + "._pack_ = 1\n" + field_declaration[i] - - new_contents = new_contents.replace(field_declaration[i], add_pack_string) - - with open(cryptoki_filename, 'w') as new_file: - new_file.write(new_contents) - - -def change_cryptoki_dll_binding(): - - print "Replacing ctypes cryptoki function definitions, in " + cryptoki_filename + ", with factory functions for later binding to the DLL" - - #Read in the current file - cryptoki_file = open(cryptoki_filename, "r") - file_contents = cryptoki_file.read() - cryptoki_file.close() - - #Find all of the lines declaring functions on the DLL - found = re.findall("_libraries\[DLL_PATH\]\.(\S*)", file_contents) - - #Replace all of the functions to have a late binding - new_contents = file_contents - for function_name in found: - new_contents = re.sub("_libraries\[DLL_PATH\]\." + function_name + "\s", "make_late_binding_function('" + function_name + "')\n", new_contents) - - #Write the final contents out - with open(cryptoki_filename, 'w') as new_file: - new_file.write(new_contents) - -def parse_library(library_path, xml_output): - defines_filename = os.path.join("..", "defines.py") - return_vals_filename = os.path.join("..", "return_values.py") - - if library_path == None: - if not os.environ.has_key('LUNA_LIBRARY'): - raise Exception("LUNA_LIBRARY environment variable is not set, it needs to be set to the path of your luna source code.") - - library_path = os.environ['LUNA_LIBRARY'] - print "Using LUNA_LIBRARY Environment variable as location of Luna's Library: " + library_path - else: - print "Using argument 1 as location of Luna's Library: " + library_path - - - #If we are on a next gen branch then throw an error if the library is not compiled because - #we will be missing an automatically generated header file - if os.path.exists(os.path.join(library_path, 'CoreLibrary', 'ctToken_lib', 'source')): - if os.path.exists(os.path.join(library_path, 'interfaces', 'include', 'cryptoki', 'sfnt_ext_list_members.h')): - raise Exception("Error: sfnt_ext_list_members.h not found. You need to compile the Components library before being able to generate the Python to C Ctypes binding.") - - _parse_headers(xml_output, library_path) - - #Add all of the header files that you would like the script to parse, - #it should be noted that the script just does simple regular expression matching - #and is very simple and could break on previously unencountered syntaxes. It is - #just a hack to make life easier - token_path = os.path.join("tools", "ekmtest", "token.h") - if os.path.exists(os.path.join(library_path, token_path)): - header_files.append(token_path) - - #if it has this library it is next gen - if is_nextgen_check(library_path): - header_files.append(os.path.join("interfaces", "Include", "RSA", "pkcs11t.h")) - header_files.append(os.path.join("CoreLibrary", "includes", "cryptoki_v2.h")) - else: - header_files.append(os.path.join("interfaces", "Include", "cryptoki", "RSA", "pkcs11t.h")) - header_files.append(os.path.join("interfaces", "Include", "cryptoki", "cryptoki_v2.h")) - - _get_defines(library_path, defines_filename, header_files) - _output_return_values(return_vals_filename, ret_list) - return library_path - -def _parse_headers(xml_output, library_path=None): - ''' - Using h2xml this function parses the cryptoki header file and generates xml - output which describes the library - :param xml_output:The filename to output the xml to - :param library_path:The path to the root of the cryptoki library - ''' - - print "Parsing luna source with GCC-XML to generate XML representation of C source" - - if os.path.exists(xml_output): - os.remove(xml_output) - - #Create a file to pull everything in - temp_include_filename = 'master_header_file.h' - if os.path.exists(temp_include_filename): - os.remove(temp_include_filename) - - ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') - is_nextgen = is_nextgen_check(library_path) - - master_include_file = open(temp_include_filename, 'w'); - if is_nextgen: - master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'pkcs11Utils', 'Utils.h"') + '\n') - else: - master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source', 'Utils.h"') + '\n') - master_include_file.write('#include "cryptoki.h"\n') - master_include_file.close() - - args = ['h2xml.py', os.path.join(os.getcwd(), temp_include_filename), '-o', xml_output, - '-I', os.path.join(library_path, 'interfaces', 'Include'), - '-I', os.path.join(library_path, 'interfaces', 'Include', 'cryptoki'), - '-I', os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source')] - - if is_nextgen: - args.append('-I') - args.append(ctlib_path) - args.append('-I') - args.append(os.path.join(library_path, 'CoreLibrary', 'util_vob', 'Include')) - - if "linux" in sys.platform: - print "Detected linux OS" - args.append('-D') - args.append('OS_LINUX') - else: - #Your operating system probably just needs to be added, might not need any special parameters - raise Exception("Error: Could not generate python to c ctypes library. Unsupported Operating System, a build on linux should work everywhere so just use it.") - - if (which("gccxml") == None and which("gccxml.exe") == None): - raise Exception("No gccxml executable found in path.") - - h2xml.compile_to_xml(args) - - if os.path.exists(temp_include_filename): - os.remove(temp_include_filename) - -def convert_to_python_binding(cryptoki_dll_path, temp_file, output_filename): - ''' - Using xml2py.py in ctypeslib this function generates the python file based - upon the xml output of h2xml. This python file is the binding between python - and C. - :param cryptoki_dll_path: The path to libCryptoki.so - :param temp_file: The xml output of h2xml.py - :param output_filename: The filename to output the binding to - ''' - print "Parsing GCC-XML output to generate python code for binding to C, writing to " + output_filename - - if os.path.exists(output_filename): - os.chmod(output_filename, stat.S_IWRITE) - os.remove(output_filename) - - args = ['xml2py.py', temp_file, '-l', cryptoki_dll_path, '-o', output_filename] - xml2py.main(args) - - change_cryptoki_dll_path(dll_path_var_name) - initial_function = '\nfrom pycryptoki.cryptoki_helpers import make_late_binding_function\nimport sys\n' - - change_cryptoki_dll_binding() - - _prepend_to_file(output_filename, initial_function) - - comment = "This file contains all of the ctypes definitions for the cryptoki library.\n" - comment = comment + "The ctypes definitions outline the structures for the cryptoki C API.\n" - _prepend_auto_file_warning(output_filename, comment) - -def _store_defines(head_filename, output_filename): - ''' - Converts all of the simple defines (defines to numbers) in a c header file to a - variable declaration in python and appends these declarations to an output file. - - This is a really hackish way of getting the defines which actually hard codes out - defines that are formatted wrong and cause errors. Done this way to get it done real - quick and imports 99% of what is needed. - - :param head_filename: The filename of the header to get the defines from - :param output_filename: The .py file to append the python style defines in - ''' - print "Getting defines from: " + str(head_filename) - - #Read in file - head_file = open(head_filename, "r") - text = head_file.read(); - - #Find all the simple defines (defines to numbers) - regex_list = re.findall(r"#define[ \t\r\f\v]+([A-Z]+[A-Za-z_0-9]+[ \t\r\f\v]+[^~\n]*)[\n]", text) - #regex_list = re.findall(r"#define[ \t\r\f\v]([\S]+[ \t\r\f\v]*[0-9]+[0-9A-Za-z]*)[\n]", text) - - #Put an equals sign in them so they are properly formatted and append them to the file - out_file = open(output_filename, "a") - out_file.write("'''" + head_filename + "'''\n") - - for entry in regex_list: - if not (entry.find("CK_POINTER") > -1 or entry.find("CK_PTR") > -1 - or entry.find("CK_ENTRY") > -1 or entry.find("C_VERSION") > -1 - or entry.find("LUNA_PARTITION_HDR_HMAC_SIZE") > -1 - or entry.find("FW_VERSION_CONF_ROLES") > -1): #XXX This is to account for function calls, should be accounted for in the regex above - entry = entry.replace('\t', ' ') #clean up tabs - entry = entry.replace(' ', '=', 1) - entry = entry.replace('//', '#') - entry = entry.replace('/*', '#') - out_file.write(entry + "\n") - - dict_entry = entry.split('=') - if 'CKR' in dict_entry[0][0:3]: - ret_list.append(dict_entry[0]) - - #Cleanup - out_file.close() - head_file.close() - -def _output_return_values(output_filename, ret_list): - ''' - Creates a file which contains a dictionary for looking up - the String values of the various defines in cryptoki. - - :param output_filename: The filename to output the dictionary to - :param ret_list: The list of return values generated when getting the - defines - ''' - - print "Creating dictionary of return value strings by scraping Luna's source, writing to: " + output_filename - - if os.path.exists(output_filename): - os.remove(output_filename) - - ret_vals_file = open(output_filename, "a") - ret_vals_file.write("from defines import *\n\n") - - ret_vals_file.write("ret_vals_dictionary = { \n") - for entry in ret_list: - ret_vals_file.write("\t" + entry + " : '" + entry + "'") - if not ret_list[len(ret_list) - 1] == entry: - ret_vals_file.write(',') - ret_vals_file.write('\n') - ret_vals_file.write("}") - ret_vals_file.close() - - comment = "This file contains a dictionary lookup for the readable string values\n" - comment = comment + "of defines whose variable name starts with CKR_. This convention means they are\n" - comment = comment + "a return value for the cryptoki C API.\n\n" - _prepend_auto_file_warning(output_filename, comment) - -def _get_defines(path_to_library, out_filename, header_files): - ''' - Gets all of the defines in a set of c files specified in the header_files variable as a list - of strings. That list is relative to the path_to_library variable. Everything is stored in - out_filename in python format. - :param path_to_library: The path to the MKS Components sandbox - :param out_filename: The .py filename to save the python style defines to - :param header_files: The header files to harvest the defines from - ''' - - print "Scraping Luna's source to convert C defines to python, writing to: " + str(out_filename) - if (os.path.exists(out_filename)): - os.remove(out_filename) - - for header_file in header_files: - head_filename = os.path.join(path_to_library, header_file) - _store_defines(head_filename=head_filename, output_filename=out_filename) - - comment = "This file contains defines which have been automatically scraped from the\n" - comment = comment + "cryptoki API header files. The defines are stored as variables in python.\n" - comment = comment + "If you add any new defines you can rerun initialize.py to regenerate this file.\n" - comment = comment + "If you need to scrape another header file add the desired file to the header_files\n" - comment = comment + "array in initialize.py and rerun initialize.py.\n" - _prepend_auto_file_warning(out_filename, comment) - -def _prepend_auto_file_warning(filename, comment): - beginning_comment = "'''\n" - beginning_comment = beginning_comment + "THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE\n" - beginning_comment = beginning_comment + "This file should NOT be checked into MKS or modified in any way, this file was\n" - beginning_comment = beginning_comment + "created by setup/initialize.py. Any changes to this file will be wiped out when\n" - beginning_comment = beginning_comment + "it is regenerated.\n\n" - beginning_comment = beginning_comment + comment - beginning_comment = beginning_comment + "'''\n\n" - - _prepend_to_file(filename, beginning_comment) - -def _prepend_to_file(filename, text_to_prepend): - with file(filename, 'r') as original: data = original.read() - with file(filename, 'w') as modified: modified.write(text_to_prepend + data) - -def which(program): - def is_exe(fpath): - return os.path.isfile(fpath) and os.access(fpath, os.X_OK) - - fpath, fname = os.path.split(program) - if fpath: - if is_exe(program): - return program - else: - for path in os.environ["PATH"].split(os.pathsep): - exe_file = os.path.join(path, program) - if is_exe(exe_file): - return exe_file - - return None - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding.") - parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") - parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") - args = parser.parse_args() - options = vars(args) - - initialize(options['lib'], options['dll']) - +""" +Setup script that will automatically generate the cryptoki.py and defines.py files. +This will get your library from your LUNA_LIBRARY environment variable and generate these +files. These files contains the defines that are in the C code and in addition contain the +CTypes formatted structs contained in the C code. + +Cryptoki.py contains the CTypes templates for the C Structs that are in the cryptoki C code. +Defines.py is a crude wrapper around a number of header files that uses a bad regular expression to +harvest the defines. + +Download gccxml from CVS (note: CVS seems to be blocked on the CVS network, you can get this from smb://172.20.11.83/ftp/forMike) +Compile gccxml +1) Recursively run dos2unix on gccxml source tree (find . -name *.* -exec dos2unix {} \;) +2) Create a folder in the same directory as gccxml is in called gccxml-build (ex /home/mhughes/gccxml and /home/mhughes/gccxml-build) +3) cd gccxml-build +4) cmake ../gccxml -DCMAKE_INSTALL_PREFIX:PATH=/home/mhughes/gccxml-build +5) make +6) make install +7) Add gccxml folder to your path + +Install python +Install python packages needed for ctypes +1) sudo pip install ctypes +2) sudo easy_install ctypeslib==dev + +Make sure pycryptoki and pycryptoki/utils are in your PYTHONPATH. In eclipse: +1) Right click on your project +2) Select Properties +3) Select PyDev - PYTHONPATH +4) Add source folder +5) Add pycryptoki and pycryptoki/utils + +Set you LUNA_LIBRARY environment variable to the path to your library. It is assumed that your +dll is in the proper path in the library +""" +from ctypeslib import h2xml, xml2py +import argparse +import os +import platform +import re +import stat +import sys + +ret_list = [] +header_files = [os.path.join("interfaces", "Include", "firmware", "luna2if.h")] +dll_path_var_name = 'DLL_PATH' +cryptoki_filename = os.path.join("..", "cryptoki.py") + +def is_nextgen_check(library_path): + ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') + return os.path.exists(ctlib_path) + +def initialize(library_path=None, dll_path=None): + ''' + Creates the cryptoki.py, defines.py and return_values.py files. + :param library_path: The path to the MKS Components sandbox + ''' + xml_output = 'h2xmlout_tmp.xml' + + library_path = parse_library(library_path, xml_output) + cryptoki_dll_path = dll_path + convert_to_python_binding(cryptoki_dll_path, xml_output, cryptoki_filename) + print "Finished!" + +def change_cryptoki_dll_path(new_dll_path): + if not os.path.exists(cryptoki_filename): + raise Exception("Error... cryptoki.py not found.") + + print "Removing references to DLL in cryptoki.py to achieve late binding to DLL" + + #Read in the current file + cryptoki_file = open(cryptoki_filename, "r") + file_contents = cryptoki_file.read() + cryptoki_file.close() + + #Create a backup + try: + os.remove(cryptoki_filename + ".bak") + except: + #Don't care this was only removing the old backup if one existed + pass + + print "Creating backup: cryptoki.py.bak" + os.rename(cryptoki_filename, cryptoki_filename + ".bak") + + #Find the previous path + print re.findall("CDLL\((.*)\)", file_contents)[0] + current_path = re.findall("CDLL\((.*)\)", file_contents)[0] + + if "win" in platform.system(): + current_path = current_path.replace("\\", '~').replace('~', '\\\\\\\\') + + new_contents = file_contents.replace(current_path, new_dll_path) + + #Remove all references to DLL to load it later + new_contents = re.sub("_libraries\s*=\s*{}\s*", "", new_contents) + new_contents = re.sub("_libraries\[DLL_PATH\]\s*=\s*CDLL\(DLL_PATH\)\s*", "", new_contents) + + #Windows needs to have _pack_ = 1 for every single struct, has to be declared before _fields_ is set + struct_names = re.findall("(\S+)\._fields_\s=\s", new_contents) + fields = re.compile("\S+\._fields_\s=\s[^\]]*]", re.MULTILINE | re.DOTALL) + field_declaration = re.findall(fields, new_contents) + + assert len(field_declaration) == len(struct_names) + for i in range(0, len(field_declaration)): + add_pack_string = "if 'win' in sys.platform:\n " + struct_names[i] + "._pack_ = 1\n" + field_declaration[i] + + new_contents = new_contents.replace(field_declaration[i], add_pack_string) + + with open(cryptoki_filename, 'w') as new_file: + new_file.write(new_contents) + + +def change_cryptoki_dll_binding(): + + print "Replacing ctypes cryptoki function definitions, in " + cryptoki_filename + ", with factory functions for later binding to the DLL" + + #Read in the current file + cryptoki_file = open(cryptoki_filename, "r") + file_contents = cryptoki_file.read() + cryptoki_file.close() + + #Find all of the lines declaring functions on the DLL + found = re.findall("_libraries\[DLL_PATH\]\.(\S*)", file_contents) + + #Replace all of the functions to have a late binding + new_contents = file_contents + for function_name in found: + new_contents = re.sub("_libraries\[DLL_PATH\]\." + function_name + "\s", "make_late_binding_function('" + function_name + "')\n", new_contents) + + #Write the final contents out + with open(cryptoki_filename, 'w') as new_file: + new_file.write(new_contents) + +def parse_library(library_path, xml_output): + defines_filename = os.path.join("..", "defines.py") + return_vals_filename = os.path.join("..", "return_values.py") + + if library_path == None: + if not os.environ.has_key('LUNA_LIBRARY'): + raise Exception("LUNA_LIBRARY environment variable is not set, it needs to be set to the path of your luna source code.") + + library_path = os.environ['LUNA_LIBRARY'] + print "Using LUNA_LIBRARY Environment variable as location of Luna's Library: " + library_path + else: + print "Using argument 1 as location of Luna's Library: " + library_path + + + #If we are on a next gen branch then throw an error if the library is not compiled because + #we will be missing an automatically generated header file + if os.path.exists(os.path.join(library_path, 'CoreLibrary', 'ctToken_lib', 'source')): + if os.path.exists(os.path.join(library_path, 'interfaces', 'include', 'cryptoki', 'sfnt_ext_list_members.h')): + raise Exception("Error: sfnt_ext_list_members.h not found. You need to compile the Components library before being able to generate the Python to C Ctypes binding.") + + _parse_headers(xml_output, library_path) + + #Add all of the header files that you would like the script to parse, + #it should be noted that the script just does simple regular expression matching + #and is very simple and could break on previously unencountered syntaxes. It is + #just a hack to make life easier + token_path = os.path.join("tools", "ekmtest", "token.h") + if os.path.exists(os.path.join(library_path, token_path)): + header_files.append(token_path) + + #if it has this library it is next gen + if is_nextgen_check(library_path): + header_files.append(os.path.join("interfaces", "Include", "RSA", "pkcs11t.h")) + header_files.append(os.path.join("CoreLibrary", "includes", "cryptoki_v2.h")) + else: + header_files.append(os.path.join("interfaces", "Include", "cryptoki", "RSA", "pkcs11t.h")) + header_files.append(os.path.join("interfaces", "Include", "cryptoki", "cryptoki_v2.h")) + + _get_defines(library_path, defines_filename, header_files) + _output_return_values(return_vals_filename, ret_list) + return library_path + +def _parse_headers(xml_output, library_path=None): + ''' + Using h2xml this function parses the cryptoki header file and generates xml + output which describes the library + :param xml_output:The filename to output the xml to + :param library_path:The path to the root of the cryptoki library + ''' + + print "Parsing luna source with GCC-XML to generate XML representation of C source" + + if os.path.exists(xml_output): + os.remove(xml_output) + + #Create a file to pull everything in + temp_include_filename = 'master_header_file.h' + if os.path.exists(temp_include_filename): + os.remove(temp_include_filename) + + ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') + is_nextgen = is_nextgen_check(library_path) + + master_include_file = open(temp_include_filename, 'w'); + if is_nextgen: + master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'pkcs11Utils', 'Utils.h"') + '\n') + else: + master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source', 'Utils.h"') + '\n') + master_include_file.write('#include "cryptoki.h"\n') + master_include_file.close() + + args = ['h2xml.py', os.path.join(os.getcwd(), temp_include_filename), '-o', xml_output, + '-I', os.path.join(library_path, 'interfaces', 'Include'), + '-I', os.path.join(library_path, 'interfaces', 'Include', 'cryptoki'), + '-I', os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source')] + + if is_nextgen: + args.append('-I') + args.append(ctlib_path) + args.append('-I') + args.append(os.path.join(library_path, 'CoreLibrary', 'util_vob', 'Include')) + + if "linux" in sys.platform: + print "Detected linux OS" + args.append('-D') + args.append('OS_LINUX') + else: + #Your operating system probably just needs to be added, might not need any special parameters + raise Exception("Error: Could not generate python to c ctypes library. Unsupported Operating System, a build on linux should work everywhere so just use it.") + + if (which("gccxml") == None and which("gccxml.exe") == None): + raise Exception("No gccxml executable found in path.") + + h2xml.compile_to_xml(args) + + if os.path.exists(temp_include_filename): + os.remove(temp_include_filename) + +def convert_to_python_binding(cryptoki_dll_path, temp_file, output_filename): + ''' + Using xml2py.py in ctypeslib this function generates the python file based + upon the xml output of h2xml. This python file is the binding between python + and C. + :param cryptoki_dll_path: The path to libCryptoki.so + :param temp_file: The xml output of h2xml.py + :param output_filename: The filename to output the binding to + ''' + print "Parsing GCC-XML output to generate python code for binding to C, writing to " + output_filename + + if os.path.exists(output_filename): + os.chmod(output_filename, stat.S_IWRITE) + os.remove(output_filename) + + args = ['xml2py.py', temp_file, '-l', cryptoki_dll_path, '-o', output_filename] + xml2py.main(args) + + change_cryptoki_dll_path(dll_path_var_name) + initial_function = '\nfrom pycryptoki.cryptoki_helpers import make_late_binding_function\nimport sys\n' + + change_cryptoki_dll_binding() + + _prepend_to_file(output_filename, initial_function) + + comment = "This file contains all of the ctypes definitions for the cryptoki library.\n" + comment = comment + "The ctypes definitions outline the structures for the cryptoki C API.\n" + _prepend_auto_file_warning(output_filename, comment) + +def _store_defines(head_filename, output_filename): + ''' + Converts all of the simple defines (defines to numbers) in a c header file to a + variable declaration in python and appends these declarations to an output file. + + This is a really hackish way of getting the defines which actually hard codes out + defines that are formatted wrong and cause errors. Done this way to get it done real + quick and imports 99% of what is needed. + + :param head_filename: The filename of the header to get the defines from + :param output_filename: The .py file to append the python style defines in + ''' + print "Getting defines from: " + str(head_filename) + + #Read in file + head_file = open(head_filename, "r") + text = head_file.read(); + + #Find all the simple defines (defines to numbers) + regex_list = re.findall(r"#define[ \t\r\f\v]+([A-Z]+[A-Za-z_0-9]+[ \t\r\f\v]+[^~\n]*)[\n]", text) + #regex_list = re.findall(r"#define[ \t\r\f\v]([\S]+[ \t\r\f\v]*[0-9]+[0-9A-Za-z]*)[\n]", text) + + #Put an equals sign in them so they are properly formatted and append them to the file + out_file = open(output_filename, "a") + out_file.write("'''" + head_filename + "'''\n") + + for entry in regex_list: + if not (entry.find("CK_POINTER") > -1 or entry.find("CK_PTR") > -1 + or entry.find("CK_ENTRY") > -1 or entry.find("C_VERSION") > -1 + or entry.find("LUNA_PARTITION_HDR_HMAC_SIZE") > -1 + or entry.find("FW_VERSION_CONF_ROLES") > -1): #XXX This is to account for function calls, should be accounted for in the regex above + entry = entry.replace('\t', ' ') #clean up tabs + entry = entry.replace(' ', '=', 1) + entry = entry.replace('//', '#') + entry = entry.replace('/*', '#') + out_file.write(entry + "\n") + + dict_entry = entry.split('=') + if 'CKR' in dict_entry[0][0:3]: + ret_list.append(dict_entry[0]) + + #Cleanup + out_file.close() + head_file.close() + +def _output_return_values(output_filename, ret_list): + ''' + Creates a file which contains a dictionary for looking up + the String values of the various defines in cryptoki. + + :param output_filename: The filename to output the dictionary to + :param ret_list: The list of return values generated when getting the + defines + ''' + + print "Creating dictionary of return value strings by scraping Luna's source, writing to: " + output_filename + + if os.path.exists(output_filename): + os.remove(output_filename) + + ret_vals_file = open(output_filename, "a") + ret_vals_file.write("from defines import *\n\n") + + ret_vals_file.write("ret_vals_dictionary = { \n") + for entry in ret_list: + ret_vals_file.write("\t" + entry + " : '" + entry + "'") + if not ret_list[len(ret_list) - 1] == entry: + ret_vals_file.write(',') + ret_vals_file.write('\n') + ret_vals_file.write("}") + ret_vals_file.close() + + comment = "This file contains a dictionary lookup for the readable string values\n" + comment = comment + "of defines whose variable name starts with CKR_. This convention means they are\n" + comment = comment + "a return value for the cryptoki C API.\n\n" + _prepend_auto_file_warning(output_filename, comment) + +def _get_defines(path_to_library, out_filename, header_files): + ''' + Gets all of the defines in a set of c files specified in the header_files variable as a list + of strings. That list is relative to the path_to_library variable. Everything is stored in + out_filename in python format. + :param path_to_library: The path to the MKS Components sandbox + :param out_filename: The .py filename to save the python style defines to + :param header_files: The header files to harvest the defines from + ''' + + print "Scraping Luna's source to convert C defines to python, writing to: " + str(out_filename) + if (os.path.exists(out_filename)): + os.remove(out_filename) + + for header_file in header_files: + head_filename = os.path.join(path_to_library, header_file) + _store_defines(head_filename=head_filename, output_filename=out_filename) + + comment = "This file contains defines which have been automatically scraped from the\n" + comment = comment + "cryptoki API header files. The defines are stored as variables in python.\n" + comment = comment + "If you add any new defines you can rerun initialize.py to regenerate this file.\n" + comment = comment + "If you need to scrape another header file add the desired file to the header_files\n" + comment = comment + "array in initialize.py and rerun initialize.py.\n" + _prepend_auto_file_warning(out_filename, comment) + +def _prepend_auto_file_warning(filename, comment): + beginning_comment = "'''\n" + beginning_comment = beginning_comment + "THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE\n" + beginning_comment = beginning_comment + "This file should NOT be checked into MKS or modified in any way, this file was\n" + beginning_comment = beginning_comment + "created by setup/initialize.py. Any changes to this file will be wiped out when\n" + beginning_comment = beginning_comment + "it is regenerated.\n\n" + beginning_comment = beginning_comment + comment + beginning_comment = beginning_comment + "'''\n\n" + + _prepend_to_file(filename, beginning_comment) + +def _prepend_to_file(filename, text_to_prepend): + with file(filename, 'r') as original: data = original.read() + with file(filename, 'w') as modified: modified.write(text_to_prepend + data) + +def which(program): + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + + return None + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding.") + parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") + parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") + args = parser.parse_args() + options = vars(args) + + initialize(options['lib'], options['dll']) + diff --git a/pycryptoki/setup/make_and_install.py b/pycryptoki/setup/make_and_install.py index a59c105..d5ce7aa 100755 --- a/pycryptoki/setup/make_and_install.py +++ b/pycryptoki/setup/make_and_install.py @@ -1,29 +1,29 @@ -''' -Script used to automatically generate python code bindings to the cryptoki library -and install the pycryptoki module in the system. -''' -import argparse -from pycryptoki.setup.initialize import initialize -import os -import sys - -parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and installs pycryptoki package.") -parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") -parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") - -print "-------------------------------------------------------" -print " Autogenerating Python Bindings to Cryptoki" -print "-------------------------------------------------------" - -options = vars(parser.parse_args()) -initialize(options['lib'], options['dll']) - -print "" -print "-------------------------------------------------------" -print " Installing PyCryptoki Python Module" -print "-------------------------------------------------------" -if "linux" in sys.platform: - os.chdir(os.path.join("..", "..")) - os.system('sudo python setup.py install') -else: +''' +Script used to automatically generate python code bindings to the cryptoki library +and install the pycryptoki module in the system. +''' +import argparse +from pycryptoki.setup.initialize import initialize +import os +import sys + +parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and installs pycryptoki package.") +parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") +parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") + +print "-------------------------------------------------------" +print " Autogenerating Python Bindings to Cryptoki" +print "-------------------------------------------------------" + +options = vars(parser.parse_args()) +initialize(options['lib'], options['dll']) + +print "" +print "-------------------------------------------------------" +print " Installing PyCryptoki Python Module" +print "-------------------------------------------------------" +if "linux" in sys.platform: + os.chdir(os.path.join("..", "..")) + os.system('sudo python setup.py install') +else: raise Exception("Unsupported operating system, you'll have to add support for it.") \ No newline at end of file diff --git a/pycryptoki/setup/verify_version.py b/pycryptoki/setup/verify_version.py index 3d55cd7..29d30aa 100755 --- a/pycryptoki/setup/verify_version.py +++ b/pycryptoki/setup/verify_version.py @@ -1,36 +1,36 @@ -''' -This function just goes through and imports every file and reports back which files have errors -in them for the purpose of compatibility between python versions. - -''' -import os, os.path - -def verify_import(): - failed_files = "" - for root, dirs, files in os.walk("../."): - for f in files: - fullpath = os.path.join(root, f) - if (fullpath.endswith("py")): - split_path = fullpath.split('/') - folder_names = "" - verify = True - if (len(split_path) > 3): - - for folder in split_path[2:len(split_path) - 1]: - if folder == "setup": - verify = False - folder_names = folder_names + str(folder) + "." - if verify: - print fullpath - cmd = "from pycryptoki." + folder_names + str(f).split(".")[0] + " import *" - print "\t" + cmd - try: - exec cmd - except Exception as e: - print "\tERROR:" - print "\t" + str(e) - failed_files = failed_files + str(f) + "\n\t" - print "\n------SUMMARY------" - print "Failed:\n\t" + failed_files -if __name__ == '__main__': +''' +This function just goes through and imports every file and reports back which files have errors +in them for the purpose of compatibility between python versions. + +''' +import os, os.path + +def verify_import(): + failed_files = "" + for root, dirs, files in os.walk("../."): + for f in files: + fullpath = os.path.join(root, f) + if (fullpath.endswith("py")): + split_path = fullpath.split('/') + folder_names = "" + verify = True + if (len(split_path) > 3): + + for folder in split_path[2:len(split_path) - 1]: + if folder == "setup": + verify = False + folder_names = folder_names + str(folder) + "." + if verify: + print fullpath + cmd = "from pycryptoki." + folder_names + str(f).split(".")[0] + " import *" + print "\t" + cmd + try: + exec cmd + except Exception as e: + print "\tERROR:" + print "\t" + str(e) + failed_files = failed_files + str(f) + "\n\t" + print "\n------SUMMARY------" + print "Failed:\n\t" + failed_files +if __name__ == '__main__': verify_import() \ No newline at end of file diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 48a3e55..d9db118 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -1,249 +1,249 @@ -from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ - CK_BYTE_PTR, C_SignInit, C_Sign -from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p -from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ - CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ - CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ - CKM_SHA512, CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, \ - CKG_MGF1_SHA512 -from pycryptoki.attributes import convert_ck_char_array_to_string -from pycryptoki.cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ - C_SignFinal, C_VerifyUpdate, C_VerifyFinal, CK_RSA_PKCS_PSS_PARAMS -from pycryptoki.encryption import _get_string_from_list, \ - get_c_data_to_sign_or_encrypt -from pycryptoki.test_functions import make_error_handle_function -import logging - -logger = logging.getLogger(__name__) - -def get_mechanism_for_sigver(flavour): - """ - Tries to build a default mechanism if none is provided, - most mechanisms just need the .pParameter field to be null. - If they don't the mechanism can be instantiated here. - """ - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(flavour) - - default_salt_len = 8 - if flavour == CKM_RSA_PKCS_PSS or \ - flavour == CKM_SHA1_RSA_PKCS_PSS: - - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA_1) - p.mgf = CK_ULONG(CKG_MGF1_SHA1) - p.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) - elif flavour == CKM_SHA224_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA224) - p.mgf = CK_ULONG(CKG_MGF1_SHA224) - p.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) - elif flavour == CKM_SHA256_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA256) - p.mgf = CK_ULONG(CKG_MGF1_SHA256) - p.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) - elif flavour == CKM_SHA384_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA384) - p.mgf = CK_ULONG(CKG_MGF1_SHA384) - p.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) - elif flavour == CKM_SHA512_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA512) - p.mgf = CK_ULONG(CKG_MGF1_SHA512) - p.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) - else: - mech.pParameter = CK_VOID_PTR(0) - mech.usParameterLen = CK_ULONG(0) - return mech - -def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech = None): - ''' - Performs a C_SignInit and C_Sign operation on some data - - @param h_session: The current session - @param sign_flavor: The flavour of signing to do - @param data_to_sign: The data to sign, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param h_key: The key to sign the data with - @param mech: The mechanism to use, if None a blank mechanism will be created based on the sign_flavor - - @return The result code, A python string represeting the signature - ''' - - #Get the mechanism - if (mech == None): - mech = get_mechanism_for_sigver(sign_flavor) - - #Initialize the sign operation - ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) - if ret != CKR_OK: return ret, None - - #if a list is passed out do a sign operation on each string in the list, otherwise just do one sign operation - is_multi_part_operation = isinstance(data_to_sign, list) or isinstance(data_to_sign, tuple) - - if is_multi_part_operation: - ret, signature_string = do_multipart_sign_or_digest(h_session, C_SignUpdate, C_SignFinal, data_to_sign) - else: - #Prepare the data to sign - c_data_to_sign = get_c_data_to_sign_or_encrypt(data_to_sign) - plain_date_len = CK_ULONG(len(data_to_sign)) - - #Get the length of the output - sign_len = CK_ULONG() - ret = C_Sign(h_session, c_data_to_sign, plain_date_len, None, byref(sign_len)) - if ret != CKR_OK: return ret, None - - #Actually get the signature - signature_buffer = create_string_buffer("", sign_len.value) - signature = cast(signature_buffer, CK_BYTE_PTR) - ret = C_Sign(h_session, c_data_to_sign, plain_date_len, signature, byref(sign_len)) - - ck_char_array = signature._objects.values()[0] - signature_string = '' - if sign_len.value > 0: - signature_string = convert_ck_char_array_to_string(ck_char_array)[0:(sign_len.value)] - - return ret, signature_string -c_sign_ex = make_error_handle_function(c_sign) - -def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, input_data_list): - ''' - Does a multipart sign or digest operation - ''' - max_data_chunk_size = 0xfff0 - plain_data_len = len(_get_string_from_list(input_data_list)) - - remaining_length = plain_data_len - python_string = '' - i = 0 - while remaining_length > 0: - current_chunk = input_data_list[i] - - #Prepare arguments for decrypt update operation - current_chunk_len = min(len(current_chunk), remaining_length) - - if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - - data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) - - ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len)) - if ret != CKR_OK: return ret, None - - remaining_length -= current_chunk_len - - i += 1 - - #Finalizing multipart decrypt operation - out_data_len = CK_ULONG(max_data_chunk_size) - output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) - ret = c_final_function(h_session, output, byref(out_data_len)) - - #Get output - ck_char_array = output._objects.values()[0] - if (out_data_len.value > 0): - python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] - - return ret, python_string - -def do_multipart_verify(h_session, input_data_list, signature): - ''' - Does a multipart verify operation - ''' - max_data_chunk_size = 0xfff0 - plain_data_len = len(_get_string_from_list(input_data_list)) - - remaining_length = plain_data_len - i = 0 - while remaining_length > 0: - current_chunk = input_data_list[i] - - #Prepare arguments for decrypt update operation - current_chunk_len = min(len(current_chunk), remaining_length) - - if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - - data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) - - ret = C_VerifyUpdate(h_session, data_chunk, CK_ULONG(current_chunk_len)) - if ret != CKR_OK: return ret - - remaining_length -= current_chunk_len - - i += 1 - - #Finalizing multipart decrypt operation - out_data_len = CK_ULONG(len(signature)) - output = cast(get_c_data_to_sign_or_encrypt(signature), CK_BYTE_PTR) - ret = C_VerifyFinal(h_session, output, out_data_len) - - return ret - -def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - ''' - Returns the result code of C_Verify which indicates whether or not the signature is - valid. - - @param h_session: The current session - @param h_key: The key handle to verify the signature against - @param verify_flavor: The flavour of the mechanism to verify against - @param data_to_verify: The data to verify, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param signature: The signature of the data - @param mech: The mechanism to use, if None is specified the mechanism will - try to be automatically obtained - - @returns The result code - ''' - - #Get the mechanism - if mech == None: - mech = get_mechanism_for_sigver(verify_flavor) - - #Initialize the verify operation - ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) - if ret != CKR_OK: return ret - - #if a list is passed out do a verify operation on each string in the list, otherwise just do one verify operation - is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(data_to_verify, tuple) - - if is_multi_part_operation: - ret = do_multipart_verify(h_session, data_to_verify, signature) - else: - #Prepare the data to verify - c_data_to_verify = get_c_data_to_sign_or_encrypt(data_to_verify) - plain_date_len = CK_ULONG(len(data_to_verify)) - - c_signature = get_c_data_to_sign_or_encrypt(signature) - - #Actually verify the data - ret = C_Verify(h_session, c_data_to_verify, plain_date_len, c_signature, CK_ULONG(len(signature))) - - return ret - -c_verify_ex = make_error_handle_function(c_verify) - +from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ + CK_BYTE_PTR, C_SignInit, C_Sign +from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p +from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ + CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ + CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ + CKM_SHA512, CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, \ + CKG_MGF1_SHA512 +from pycryptoki.attributes import convert_ck_char_array_to_string +from pycryptoki.cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ + C_SignFinal, C_VerifyUpdate, C_VerifyFinal, CK_RSA_PKCS_PSS_PARAMS +from pycryptoki.encryption import _get_string_from_list, \ + get_c_data_to_sign_or_encrypt +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def get_mechanism_for_sigver(flavour): + """ + Tries to build a default mechanism if none is provided, + most mechanisms just need the .pParameter field to be null. + If they don't the mechanism can be instantiated here. + """ + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(flavour) + + default_salt_len = 8 + if flavour == CKM_RSA_PKCS_PSS or \ + flavour == CKM_SHA1_RSA_PKCS_PSS: + + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA_1) + p.mgf = CK_ULONG(CKG_MGF1_SHA1) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA224_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA224) + p.mgf = CK_ULONG(CKG_MGF1_SHA224) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA256_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA256) + p.mgf = CK_ULONG(CKG_MGF1_SHA256) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA384_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA384) + p.mgf = CK_ULONG(CKG_MGF1_SHA384) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + elif flavour == CKM_SHA512_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() + p.hashAlg = CK_ULONG(CKM_SHA512) + p.mgf = CK_ULONG(CKG_MGF1_SHA512) + p.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(p), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(p)) + else: + mech.pParameter = CK_VOID_PTR(0) + mech.usParameterLen = CK_ULONG(0) + return mech + +def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech = None): + ''' + Performs a C_SignInit and C_Sign operation on some data + + @param h_session: The current session + @param sign_flavor: The flavour of signing to do + @param data_to_sign: The data to sign, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param h_key: The key to sign the data with + @param mech: The mechanism to use, if None a blank mechanism will be created based on the sign_flavor + + @return The result code, A python string represeting the signature + ''' + + #Get the mechanism + if (mech == None): + mech = get_mechanism_for_sigver(sign_flavor) + + #Initialize the sign operation + ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) + if ret != CKR_OK: return ret, None + + #if a list is passed out do a sign operation on each string in the list, otherwise just do one sign operation + is_multi_part_operation = isinstance(data_to_sign, list) or isinstance(data_to_sign, tuple) + + if is_multi_part_operation: + ret, signature_string = do_multipart_sign_or_digest(h_session, C_SignUpdate, C_SignFinal, data_to_sign) + else: + #Prepare the data to sign + c_data_to_sign = get_c_data_to_sign_or_encrypt(data_to_sign) + plain_date_len = CK_ULONG(len(data_to_sign)) + + #Get the length of the output + sign_len = CK_ULONG() + ret = C_Sign(h_session, c_data_to_sign, plain_date_len, None, byref(sign_len)) + if ret != CKR_OK: return ret, None + + #Actually get the signature + signature_buffer = create_string_buffer("", sign_len.value) + signature = cast(signature_buffer, CK_BYTE_PTR) + ret = C_Sign(h_session, c_data_to_sign, plain_date_len, signature, byref(sign_len)) + + ck_char_array = signature._objects.values()[0] + signature_string = '' + if sign_len.value > 0: + signature_string = convert_ck_char_array_to_string(ck_char_array)[0:(sign_len.value)] + + return ret, signature_string +c_sign_ex = make_error_handle_function(c_sign) + +def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, input_data_list): + ''' + Does a multipart sign or digest operation + ''' + max_data_chunk_size = 0xfff0 + plain_data_len = len(_get_string_from_list(input_data_list)) + + remaining_length = plain_data_len + python_string = '' + i = 0 + while remaining_length > 0: + current_chunk = input_data_list[i] + + #Prepare arguments for decrypt update operation + current_chunk_len = min(len(current_chunk), remaining_length) + + if current_chunk_len > max_data_chunk_size: + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + + ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len)) + if ret != CKR_OK: return ret, None + + remaining_length -= current_chunk_len + + i += 1 + + #Finalizing multipart decrypt operation + out_data_len = CK_ULONG(max_data_chunk_size) + output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) + ret = c_final_function(h_session, output, byref(out_data_len)) + + #Get output + ck_char_array = output._objects.values()[0] + if (out_data_len.value > 0): + python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + + return ret, python_string + +def do_multipart_verify(h_session, input_data_list, signature): + ''' + Does a multipart verify operation + ''' + max_data_chunk_size = 0xfff0 + plain_data_len = len(_get_string_from_list(input_data_list)) + + remaining_length = plain_data_len + i = 0 + while remaining_length > 0: + current_chunk = input_data_list[i] + + #Prepare arguments for decrypt update operation + current_chunk_len = min(len(current_chunk), remaining_length) + + if current_chunk_len > max_data_chunk_size: + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + + ret = C_VerifyUpdate(h_session, data_chunk, CK_ULONG(current_chunk_len)) + if ret != CKR_OK: return ret + + remaining_length -= current_chunk_len + + i += 1 + + #Finalizing multipart decrypt operation + out_data_len = CK_ULONG(len(signature)) + output = cast(get_c_data_to_sign_or_encrypt(signature), CK_BYTE_PTR) + ret = C_VerifyFinal(h_session, output, out_data_len) + + return ret + +def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + ''' + Returns the result code of C_Verify which indicates whether or not the signature is + valid. + + @param h_session: The current session + @param h_key: The key handle to verify the signature against + @param verify_flavor: The flavour of the mechanism to verify against + @param data_to_verify: The data to verify, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) + ex: + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] + @param signature: The signature of the data + @param mech: The mechanism to use, if None is specified the mechanism will + try to be automatically obtained + + @returns The result code + ''' + + #Get the mechanism + if mech == None: + mech = get_mechanism_for_sigver(verify_flavor) + + #Initialize the verify operation + ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) + if ret != CKR_OK: return ret + + #if a list is passed out do a verify operation on each string in the list, otherwise just do one verify operation + is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(data_to_verify, tuple) + + if is_multi_part_operation: + ret = do_multipart_verify(h_session, data_to_verify, signature) + else: + #Prepare the data to verify + c_data_to_verify = get_c_data_to_sign_or_encrypt(data_to_verify) + plain_date_len = CK_ULONG(len(data_to_verify)) + + c_signature = get_c_data_to_sign_or_encrypt(signature) + + #Actually verify the data + ret = C_Verify(h_session, c_data_to_verify, plain_date_len, c_signature, CK_ULONG(len(signature))) + + return ret + +c_verify_ex = make_error_handle_function(c_verify) + diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 91d28af..454f913 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -1,206 +1,206 @@ -from ctypes import byref -from defines import CKR_OK -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize -from pycryptoki.defines import CKR_OBJECT_HANDLE_INVALID -from return_values import ret_vals_dictionary -import inspect -import logging - -logger = logging.getLogger(__name__) - -def assert_test_return_value(value, expected_value, message, print_on_success=True): - ''' - Asserts a pass or fail based on whether the value parameter is equal to the expected_value parameter. - Used to test the results of pkcs11 functions and looks up human readable strings for the various error codes. - Prints out results in a consistent format. - @param value: The return value of the pkcs11 function - @param expected_value: The expected return value to be tested against - @param message: Message to print on success/failure - @param print_on_success: Whether or not to print if the test case passes - ''' - if value in ret_vals_dictionary: - code = ret_vals_dictionary[value] - else: - code = "Unknown Code=" + str(hex(value)) - - if expected_value in ret_vals_dictionary: - exp_code = ret_vals_dictionary[expected_value] - else: - exp_code = "Unknown Code=" + str(hex(value)) - - assert value==expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + "\n\tFound: " + code - - if print_on_success: - logger.info(exp_code + ": " + message) - - -def assert_test_case(result, message, print_on_success=False): - ''' - Simple wrapper around assert that allows for a consistent way to report successes/failures - @param result: A boolean representing the result of the test - @param message: The message to print on test failure - ''' - assert result, "\nERROR: " + message - if print_on_success: - logger.info("PASSED: " + message) - -class LunaException(Exception): - ''' - A class representing an exception in luna, it's in place because - it has some nice functionailty to print out the contents of the error - ''' - def __init__(self, error_code, function_name, arguments): - ''' - @param error_code: The error code of the error - @param function_name: The name of the function - @param arguments: The arguments passed into the function - ''' - self.error_code = error_code - self.function_name = function_name - self.arguments = arguments - - if self.error_code in ret_vals_dictionary: - self.error_string = ret_vals_dictionary[self.error_code] - else: - self.error_string = "Unknown Code=" + str(hex(self.error_code)) - - def __str__(self): - return "\n\tFunction: " + str(self.function_name) + "\n\tError: " + str(self.error_string) \ - + "\n\tError Code: " + str(hex(self.error_code)) + "\n\tArguments: " + str(self.arguments) - -class LunaReturn(): - def __init__(self, return_code, return_data): - self.return_code = return_code - self.return_data = return_data - -def verify_object_attributes(h_session, h_object, expected_template): - ''' - Verifies that an object generated has the correct attributes on the board. - The expected attributes are passed in alongside the handle of the object. - - @param h_session: Current session - @param h_object: Handle of the object to verify the attributes against - @param expected_template: The expected template to compare against - ''' - - # VERIFY OBJECT EXISTS - h_object = CK_OBJECT_HANDLE(h_object) - us_size = CK_ULONG() - ret = C_GetObjectSize(h_session, h_object, byref(us_size)) - assert_test_case(ret == CKR_OK, "Object " + str(h_object) + " exists") - assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.") - - # VERIFY ATTRIBUTES are the same as the ones passed in - attr = Attributes() - attr.retrieve_key_attributes(h_session, h_object.value) - expected_attributes = Attributes(expected_template) - assert_test_case(attr == expected_attributes, "Object " + str(h_object.value) + " attributes match expected attributes") - -def verify_object_exists(h_session, h_object, should_exist=True): - ''' - Queries the HSM to determine if an object exists. Asserts whether or not - it exists. - - @param h_session: The current session - @param h_object: The object to verify if it exists - @param should_exist: Whether or not the parameter should exist (Use to determine how this function asserts) - ''' - # VERIFY OBJECT EXISTS - h_object = CK_OBJECT_HANDLE(h_object) - us_size = CK_ULONG() - - if should_exist: - expected_ret = CKR_OK - out = "Verifying object " + str(h_object) + " exists." - else: - expected_ret = CKR_OBJECT_HANDLE_INVALID - out = "Verifying object " + str(h_object) + " doesn't exist." - - try: - ret = C_GetObjectSize(h_session, h_object, byref(us_size)) - except LunaException as e: - assert_test_case(e.error_code == expected_ret, out) - else: - assert_test_case(ret == expected_ret, out) - - if should_exist: - assert_test_return_value(ret, CKR_OK, "Getting object " + str(h_object.value) + "'s size", True) - assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.", False) - else: - assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, "Getting object " + str(h_object.value) + "'s size", True) - assert_test_case(us_size.value <= 0, "Object " + str(h_object.value) + " size is greater than zero.", False) - -def check_luna_exception(ret, luna_function, *args): - ''' - - ''' - arg_spec = inspect.getargspec(luna_function).args - arg_string = "(" - i = 0 - if (len(arg_spec) > 0): - for argument in args: - arg_string = arg_string + arg_spec[i] + "=" + str(argument) - - if i != (len(args) - 1): - arg_string = arg_string + ", " - i = i + 1 - - arg_string = arg_string + ")" - if ret != CKR_OK: raise LunaException(ret, luna_function.__name__, arg_string) - -def make_error_handle_function(luna_function): - ''' - This function is a helper function that creates a new function which checks the - result code returned from a function in luna. It is called by calling: - - c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) - - This code will create a c_generate_key_pair_ex which will call c_generate_key_pair and check the - first argument. The first argument is the return code of c_generate_key_pair. If the return - code != CKR_OK then c_generate_key_pair_ex will raise a LunaException. You can call c_generate_key_pair_ex - as if it is c_generate_key_pair: - - c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - - The return values of c_generate_pair are (ret, public_key_handle, private_key_handle) - - The return values of c_generate_pair_ex are (public_key_handle, private_key_handle) - - This lets you create two versions of a function. One version is for setup and - the other version is for testing the result. - - Directly testing the result: - ret = c_initialize() - assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" - - Expecting the call to go through without error. The test case should have an error (not a failure): - c_initialize_ex() - - This should therefore make for shorter test cases - ''' - - def luna_function_exception_handle(*args, **kwargs): - return_tuple = luna_function(*args, **kwargs); - if isinstance(return_tuple, tuple): - if (len(return_tuple) > 2): - return_data = return_tuple[1:] - ret = return_tuple[0] - elif (len(return_tuple) == 2): - return_data = return_tuple[1] - ret = return_tuple[0] - else: - return_data = return_tuple[0] - ret = return_tuple[0] - elif isinstance(return_tuple, long): - ret = return_tuple - return_data = return_tuple - else: - raise Exception("Functions wrapped by the exception handler should return a tuple or just the long representing Luna's return code.") - - check_luna_exception(ret, luna_function, args) - return return_data - return luna_function_exception_handle - - +from ctypes import byref +from defines import CKR_OK +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize +from pycryptoki.defines import CKR_OBJECT_HANDLE_INVALID +from return_values import ret_vals_dictionary +import inspect +import logging + +logger = logging.getLogger(__name__) + +def assert_test_return_value(value, expected_value, message, print_on_success=True): + ''' + Asserts a pass or fail based on whether the value parameter is equal to the expected_value parameter. + Used to test the results of pkcs11 functions and looks up human readable strings for the various error codes. + Prints out results in a consistent format. + @param value: The return value of the pkcs11 function + @param expected_value: The expected return value to be tested against + @param message: Message to print on success/failure + @param print_on_success: Whether or not to print if the test case passes + ''' + if value in ret_vals_dictionary: + code = ret_vals_dictionary[value] + else: + code = "Unknown Code=" + str(hex(value)) + + if expected_value in ret_vals_dictionary: + exp_code = ret_vals_dictionary[expected_value] + else: + exp_code = "Unknown Code=" + str(hex(value)) + + assert value==expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + "\n\tFound: " + code + + if print_on_success: + logger.info(exp_code + ": " + message) + + +def assert_test_case(result, message, print_on_success=False): + ''' + Simple wrapper around assert that allows for a consistent way to report successes/failures + @param result: A boolean representing the result of the test + @param message: The message to print on test failure + ''' + assert result, "\nERROR: " + message + if print_on_success: + logger.info("PASSED: " + message) + +class LunaException(Exception): + ''' + A class representing an exception in luna, it's in place because + it has some nice functionailty to print out the contents of the error + ''' + def __init__(self, error_code, function_name, arguments): + ''' + @param error_code: The error code of the error + @param function_name: The name of the function + @param arguments: The arguments passed into the function + ''' + self.error_code = error_code + self.function_name = function_name + self.arguments = arguments + + if self.error_code in ret_vals_dictionary: + self.error_string = ret_vals_dictionary[self.error_code] + else: + self.error_string = "Unknown Code=" + str(hex(self.error_code)) + + def __str__(self): + return "\n\tFunction: " + str(self.function_name) + "\n\tError: " + str(self.error_string) \ + + "\n\tError Code: " + str(hex(self.error_code)) + "\n\tArguments: " + str(self.arguments) + +class LunaReturn(): + def __init__(self, return_code, return_data): + self.return_code = return_code + self.return_data = return_data + +def verify_object_attributes(h_session, h_object, expected_template): + ''' + Verifies that an object generated has the correct attributes on the board. + The expected attributes are passed in alongside the handle of the object. + + @param h_session: Current session + @param h_object: Handle of the object to verify the attributes against + @param expected_template: The expected template to compare against + ''' + + # VERIFY OBJECT EXISTS + h_object = CK_OBJECT_HANDLE(h_object) + us_size = CK_ULONG() + ret = C_GetObjectSize(h_session, h_object, byref(us_size)) + assert_test_case(ret == CKR_OK, "Object " + str(h_object) + " exists") + assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.") + + # VERIFY ATTRIBUTES are the same as the ones passed in + attr = Attributes() + attr.retrieve_key_attributes(h_session, h_object.value) + expected_attributes = Attributes(expected_template) + assert_test_case(attr == expected_attributes, "Object " + str(h_object.value) + " attributes match expected attributes") + +def verify_object_exists(h_session, h_object, should_exist=True): + ''' + Queries the HSM to determine if an object exists. Asserts whether or not + it exists. + + @param h_session: The current session + @param h_object: The object to verify if it exists + @param should_exist: Whether or not the parameter should exist (Use to determine how this function asserts) + ''' + # VERIFY OBJECT EXISTS + h_object = CK_OBJECT_HANDLE(h_object) + us_size = CK_ULONG() + + if should_exist: + expected_ret = CKR_OK + out = "Verifying object " + str(h_object) + " exists." + else: + expected_ret = CKR_OBJECT_HANDLE_INVALID + out = "Verifying object " + str(h_object) + " doesn't exist." + + try: + ret = C_GetObjectSize(h_session, h_object, byref(us_size)) + except LunaException as e: + assert_test_case(e.error_code == expected_ret, out) + else: + assert_test_case(ret == expected_ret, out) + + if should_exist: + assert_test_return_value(ret, CKR_OK, "Getting object " + str(h_object.value) + "'s size", True) + assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.", False) + else: + assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, "Getting object " + str(h_object.value) + "'s size", True) + assert_test_case(us_size.value <= 0, "Object " + str(h_object.value) + " size is greater than zero.", False) + +def check_luna_exception(ret, luna_function, *args): + ''' + + ''' + arg_spec = inspect.getargspec(luna_function).args + arg_string = "(" + i = 0 + if (len(arg_spec) > 0): + for argument in args: + arg_string = arg_string + arg_spec[i] + "=" + str(argument) + + if i != (len(args) - 1): + arg_string = arg_string + ", " + i = i + 1 + + arg_string = arg_string + ")" + if ret != CKR_OK: raise LunaException(ret, luna_function.__name__, arg_string) + +def make_error_handle_function(luna_function): + ''' + This function is a helper function that creates a new function which checks the + result code returned from a function in luna. It is called by calling: + + c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) + + This code will create a c_generate_key_pair_ex which will call c_generate_key_pair and check the + first argument. The first argument is the return code of c_generate_key_pair. If the return + code != CKR_OK then c_generate_key_pair_ex will raise a LunaException. You can call c_generate_key_pair_ex + as if it is c_generate_key_pair: + + c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + + The return values of c_generate_pair are (ret, public_key_handle, private_key_handle) + + The return values of c_generate_pair_ex are (public_key_handle, private_key_handle) + + This lets you create two versions of a function. One version is for setup and + the other version is for testing the result. + + Directly testing the result: + ret = c_initialize() + assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" + + Expecting the call to go through without error. The test case should have an error (not a failure): + c_initialize_ex() + + This should therefore make for shorter test cases + ''' + + def luna_function_exception_handle(*args, **kwargs): + return_tuple = luna_function(*args, **kwargs); + if isinstance(return_tuple, tuple): + if (len(return_tuple) > 2): + return_data = return_tuple[1:] + ret = return_tuple[0] + elif (len(return_tuple) == 2): + return_data = return_tuple[1] + ret = return_tuple[0] + else: + return_data = return_tuple[0] + ret = return_tuple[0] + elif isinstance(return_tuple, long): + ret = return_tuple + return_data = return_tuple + else: + raise Exception("Functions wrapped by the exception handler should return a tuple or just the long representing Luna's return code.") + + check_luna_exception(ret, luna_function, args) + return return_data + return luna_function_exception_handle + + diff --git a/pycryptoki/tests/run_tests_in_folder.py b/pycryptoki/tests/run_tests_in_folder.py index 88b751a..d3d852b 100755 --- a/pycryptoki/tests/run_tests_in_folder.py +++ b/pycryptoki/tests/run_tests_in_folder.py @@ -1,9 +1,9 @@ -''' -Created on Aug 30, 2012 - -@author: mhughes -''' -import pytest - -if __name__ == '__main__': - pytest.cmdline.main(args=[]) +''' +Created on Aug 30, 2012 + +@author: mhughes +''' +import pytest + +if __name__ == '__main__': + pytest.cmdline.main(args=[]) diff --git a/pycryptoki/tests/setup_for_tests.py b/pycryptoki/tests/setup_for_tests.py index ffd04e6..6d20753 100755 --- a/pycryptoki/tests/setup_for_tests.py +++ b/pycryptoki/tests/setup_for_tests.py @@ -1,43 +1,43 @@ -''' -Created on Sep 18, 2012 - -@author: mhughes -''' -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD, \ - CO_PASSWORD -from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ - CKF_SO_SESSION -from pycryptoki.session_management import ca_factory_reset_ex, c_open_session_ex, \ - c_close_all_sessions_ex, login_ex, c_init_pin_ex, c_logout_ex, c_initialize_ex, \ - c_finalize_ex -from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex -import logging - -logger = logging.getLogger(__name__) - -def setup_for_tests(should_factory_reset, initialize_admin_token, initialize_users): - c_initialize_ex() - - #Factory Reset - slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - if should_factory_reset: - c_close_all_sessions_ex(slot) - ca_factory_reset_ex(slot) - - #Initialize the Admin Token - session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) - if initialize_admin_token: - h_session = c_open_session_ex(slot, session_flags) - c_init_token_ex(slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) - - - if initialize_users and initialize_admin_token: - slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - c_close_all_sessions_ex(slot) - h_session = c_open_session_ex(slot, session_flags) - login_ex(h_session, slot, ADMINISTRATOR_PASSWORD, 0) - c_init_pin_ex(h_session, CO_PASSWORD) - c_logout_ex(h_session) - c_close_all_sessions_ex(slot) - +''' +Created on Sep 18, 2012 + +@author: mhughes +''' +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD, \ + CO_PASSWORD +from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ + CKF_SO_SESSION +from pycryptoki.session_management import ca_factory_reset_ex, c_open_session_ex, \ + c_close_all_sessions_ex, login_ex, c_init_pin_ex, c_logout_ex, c_initialize_ex, \ + c_finalize_ex +from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex +import logging + +logger = logging.getLogger(__name__) + +def setup_for_tests(should_factory_reset, initialize_admin_token, initialize_users): + c_initialize_ex() + + #Factory Reset + slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + if should_factory_reset: + c_close_all_sessions_ex(slot) + ca_factory_reset_ex(slot) + + #Initialize the Admin Token + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + if initialize_admin_token: + h_session = c_open_session_ex(slot, session_flags) + c_init_token_ex(slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) + + + if initialize_users and initialize_admin_token: + slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + c_close_all_sessions_ex(slot) + h_session = c_open_session_ex(slot, session_flags) + login_ex(h_session, slot, ADMINISTRATOR_PASSWORD, 0) + c_init_pin_ex(h_session, CO_PASSWORD) + c_logout_ex(h_session) + c_close_all_sessions_ex(slot) + c_finalize_ex() \ No newline at end of file diff --git a/pycryptoki/tests/test_cka_start_and_end.py b/pycryptoki/tests/test_cka_start_and_end.py index dcb4600..8561981 100755 --- a/pycryptoki/tests/test_cka_start_and_end.py +++ b/pycryptoki/tests/test_cka_start_and_end.py @@ -1,358 +1,358 @@ -from ctypes import * -from datetime import datetime -import math -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL -from pycryptoki.defines import CKF_SERIAL_SESSION,CKM_DES_KEY_GEN, CKU_USER, \ - CKA_END_DATE, CKU_AUDIT, CKF_AUDIT_SESSION -from pycryptoki.defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ - CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ - CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ - CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ - CKK_AES, CKM_DES_ECB, CKU_SO, CKR_KEY_NOT_ACTIVE, CKM_RSA_PKCS_KEY_PAIR_GEN, \ - CKM_RSA_PKCS, CKM_AES_ECB, CKM_AES_KEY_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA_SHA1 -from pycryptoki.default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex -from pycryptoki.session_management import c_initialize_ex, login, c_finalize, c_open_session_ex, login_ex, \ - c_logout_ex, c_close_session_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -from pycryptoki.attributes import date_attrb -from pycryptoki.dictionary_handling import CDict -from pycryptoki.encryption import c_encrypt, c_encrypt_ex -from pycryptoki.audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex -from pycryptoki.sign_verify import c_sign_ex, c_sign -import logging -import os -import pytest - -logger = logging.getLogger(__name__) -class TestCKAStartEndDate(): - - h_session = 0 - admin_slot = 0 - - def setup(self): - setup_for_tests(True, True, True) - c_initialize_ex() - self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - c_finalize() - - - def test_symmetric_key_expiry_des(self): - """ - Test: Verify that user is not able to use the symmetric object after date specified in - CKA_END_DATE attribute - Procedure: - Generate a DES Key des1 - Use des1 in encrypt operation. Should work fine - Using audit role, change the date of HSM to 12/31/2013 - Use des1 in encrypt operation - """ - - logger.info("Test: Verify that user is not able to use the symmetric object after date specified in \ - CKA_END_DATE attribute") - - end_d = date_attrb - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" - - CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 8, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES Key", - CKA_END_DATE : CDict(end_d)} - - - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - - - - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, "a" * 512) - - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) - login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - - dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) - delta = dt - epoch - hsm_dt = delta.total_seconds() - hsm_new_date = int(hsm_dt) - - ca_time_sync_ex(h_session2, hsm_new_date) - - hsm_time = ca_get_time_ex(h_session2) - - c_logout_ex(h_session2) - c_close_session_ex(h_session2) - - h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - return_val = c_encrypt(h_session, CKM_DES_ECB, h_key, "This is some data to sign .. ") - - assert return_val == CKR_KEY_NOT_ACTIVE, "return value should be CKR_KEY_NOT_ACTIVE" - c_logout_ex(h_session) - c_close_session_ex(h_session) - - - def test_symmetric_key_expiry_aes(self): - """ - Test: Verify that user is not able to use the symmetric aes object after date specified in - CKA_END_DATE attribute - Procedure: - Generate a AES key aes1 - Use aes1 in encrypt operation. Should work fine - Using audit role, change the date of HSM to 12/31/2013 - Use aes1 in encrypt operation - """ - - logger.info("Test: Verify that user is not able to use the symmetric aes object after date specified in \ - CKA_END_DATE attribute") - end_d = date_attrb - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" - - CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_AES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "AES Key", - CKA_END_DATE : CDict(end_d)} - - - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - - - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") - - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) - login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - - dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) - delta = dt - epoch - hsm_dt = delta.total_seconds() - hsm_new_date = int(hsm_dt) - ca_time_sync_ex(h_session2, hsm_new_date) - - hsm_time = ca_get_time_ex(h_session2) - - c_logout_ex(h_session2) - c_close_session_ex(h_session2) - - h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - return_val = c_encrypt(h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") - logger.info("Called C_Encrypt, return code: " + str(return_val)) - assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - - - def test_asymmetric_key_expiry_rsa(self): - """ - Test: Verify that user is not able to use the rsa asymmetric object after date specified in - CKA_END_DATE attribute - Procedure: - Generate a rsa Key rsa1 - Use des1 in encrypt operation. Should work fine - Using audit role, change the date of HSM to 12/31/2013 - Use rsa1 in encrypt operation - """ - - logger.info("Test: Verify that user is not able to use the rsa asymmetric object after date specified in \ - CKA_END_DATE attribute") - end_d = date_attrb - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" - - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_MODIFIABLE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS - CKA_PUBLIC_EXPONENT : 3, #byte - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "RSA Public Key"} - - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_MODIFIABLE : True, - CKA_EXTRACTABLE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "RSA Private Key"} - - - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") - - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) - login(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - - dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) - delta = dt - epoch - hsm_dt = delta.total_seconds() - hsm_new_date = int(hsm_dt) - ca_time_sync_ex(h_session2, hsm_new_date) - - hsm_time = ca_get_time_ex(h_session2) -# print datetime.fromtimestamp(float(hsm_time.value)) - c_logout_ex(h_session2) - c_close_session_ex(h_session2) - - h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - return_val = c_encrypt(h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") - logger.info("Called C_Encrypt, return code: " + str(return_val)) - assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - - - def test_asymmetric_key_expiry_dsa(self): - """ - Test: Verify that user is not able to use the dsa asymmetric object after date specified in - CKA_END_DATE attribute - Procedure: - Generate a DSA Key dsa1 - Use dsa11 in encrypt operation. Should work fine - Using audit role, change the date of HSM to 12/31/2013 - Use dsa1 in encrypt operation - """ - - logger.info("Test: Verify that user is not able to use the dsa asymmetric object after date specified in \ - CKA_END_DATE attribute") - end_d = date_attrb - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" - - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_1024_160, - CKA_SUBPRIME : dsa_sub_prime_1024_160, - CKA_BASE : dsa_base_1024_160, - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "DSA 1024_160 Public Key"} - - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_EXTRACTABLE : True, - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "DSA Public Key"} - - - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_DSA_KEY_PAIR_GEN, - pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, - prkey_template=CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - - c_sign_ex(self.h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) - - - - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) - login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - - dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) - delta = dt - epoch - hsm_dt = delta.total_seconds() - hsm_new_date = int(hsm_dt) - ca_time_sync_ex(h_session2, hsm_new_date) - - hsm_time = ca_get_time_ex(self.h_session) -# print datetime.fromtimestamp(float(hsm_time.value)) - c_logout_ex(h_session2) - c_close_session_ex(h_session2) - - h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - return_val, sig = c_sign(h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) - logger.info("Called C_Sign, return code: " + str(return_val)) - assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - - - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) - +from ctypes import * +from datetime import datetime +import math +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL +from pycryptoki.defines import CKF_SERIAL_SESSION,CKM_DES_KEY_GEN, CKU_USER, \ + CKA_END_DATE, CKU_AUDIT, CKF_AUDIT_SESSION +from pycryptoki.defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ + CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ + CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ + CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ + CKK_AES, CKM_DES_ECB, CKU_SO, CKR_KEY_NOT_ACTIVE, CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKM_RSA_PKCS, CKM_AES_ECB, CKM_AES_KEY_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA_SHA1 +from pycryptoki.default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.session_management import c_initialize_ex, login, c_finalize, c_open_session_ex, login_ex, \ + c_logout_ex, c_close_session_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +from pycryptoki.attributes import date_attrb +from pycryptoki.dictionary_handling import CDict +from pycryptoki.encryption import c_encrypt, c_encrypt_ex +from pycryptoki.audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex +from pycryptoki.sign_verify import c_sign_ex, c_sign +import logging +import os +import pytest + +logger = logging.getLogger(__name__) +class TestCKAStartEndDate(): + + h_session = 0 + admin_slot = 0 + + def setup(self): + setup_for_tests(True, True, True) + c_initialize_ex() + self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + c_finalize() + + + def test_symmetric_key_expiry_des(self): + """ + Test: Verify that user is not able to use the symmetric object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a DES Key des1 + Use des1 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use des1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the symmetric object after date specified in \ + CKA_END_DATE attribute") + + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_DES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 8, + CKA_EXTRACTABLE :True, + CKA_LABEL : "DES Key", + CKA_END_DATE : CDict(end_d)} + + + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + + + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, "a" * 512) + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(h_session2) + + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val = c_encrypt(h_session, CKM_DES_ECB, h_key, "This is some data to sign .. ") + + assert return_val == CKR_KEY_NOT_ACTIVE, "return value should be CKR_KEY_NOT_ACTIVE" + c_logout_ex(h_session) + c_close_session_ex(h_session) + + + def test_symmetric_key_expiry_aes(self): + """ + Test: Verify that user is not able to use the symmetric aes object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a AES key aes1 + Use aes1 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use aes1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the symmetric aes object after date specified in \ + CKA_END_DATE attribute") + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKA_KEY_TYPE : CKK_AES, + CKA_TOKEN : True, + CKA_SENSITIVE : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_UNWRAP : True, + CKA_DERIVE : True, + CKA_VALUE_LEN : 16, + CKA_EXTRACTABLE :True, + CKA_LABEL : "AES Key", + CKA_END_DATE : CDict(end_d)} + + + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + + + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(h_session2) + + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val = c_encrypt(h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") + logger.info("Called C_Encrypt, return code: " + str(return_val)) + assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" + + + def test_asymmetric_key_expiry_rsa(self): + """ + Test: Verify that user is not able to use the rsa asymmetric object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a rsa Key rsa1 + Use des1 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use rsa1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the rsa asymmetric object after date specified in \ + CKA_END_DATE attribute") + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_MODIFIABLE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT : 3, #byte + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "RSA Public Key"} + + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_MODIFIABLE : True, + CKA_EXTRACTABLE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "RSA Private Key"} + + + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(h_session2) +# print datetime.fromtimestamp(float(hsm_time.value)) + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val = c_encrypt(h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") + logger.info("Called C_Encrypt, return code: " + str(return_val)) + assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" + + + def test_asymmetric_key_expiry_dsa(self): + """ + Test: Verify that user is not able to use the dsa asymmetric object after date specified in + CKA_END_DATE attribute + Procedure: + Generate a DSA Key dsa1 + Use dsa11 in encrypt operation. Should work fine + Using audit role, change the date of HSM to 12/31/2013 + Use dsa1 in encrypt operation + """ + + logger.info("Test: Verify that user is not able to use the dsa asymmetric object after date specified in \ + CKA_END_DATE attribute") + end_d = date_attrb + end_d['year'] = "2013" + end_d['month'] = "12" + end_d['day'] = "31" + + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_ENCRYPT : True, + CKA_VERIFY : True, + CKA_WRAP : True, + CKA_PRIME : dsa_prime_1024_160, + CKA_SUBPRIME : dsa_sub_prime_1024_160, + CKA_BASE : dsa_base_1024_160, + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "DSA 1024_160 Public Key"} + + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, + CKA_PRIVATE : True, + CKA_SENSITIVE : True, + CKA_DECRYPT : True, + CKA_SIGN : True, + CKA_UNWRAP : True, + CKA_EXTRACTABLE : True, + CKA_END_DATE : CDict(end_d), + CKA_LABEL : "DSA Public Key"} + + + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_DSA_KEY_PAIR_GEN, + pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + prkey_template=CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + c_sign_ex(self.h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) + + + + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) + + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) + + dt = datetime(2014, 1 , 31) + epoch = datetime.utcfromtimestamp(0) + delta = dt - epoch + hsm_dt = delta.total_seconds() + hsm_new_date = int(hsm_dt) + ca_time_sync_ex(h_session2, hsm_new_date) + + hsm_time = ca_get_time_ex(self.h_session) +# print datetime.fromtimestamp(float(hsm_time.value)) + c_logout_ex(h_session2) + c_close_session_ex(h_session2) + + h_session = c_open_session_ex(slot_num=self.admin_slot) + login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) + + return_val, sig = c_sign(h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) + logger.info("Called C_Sign, return code: " + str(return_val)) + assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" + + + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) + \ No newline at end of file diff --git a/pycryptoki/tests/test_digest_data.py b/pycryptoki/tests/test_digest_data.py index 9234c26..23406c0 100755 --- a/pycryptoki/tests/test_digest_data.py +++ b/pycryptoki/tests/test_digest_data.py @@ -1,53 +1,53 @@ -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_MD2, CKR_OK -from pycryptoki.encryption import _get_string_from_list -from pycryptoki.misc import c_digest -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestDigestData(): - @classmethod - def setup_class(self): - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(self): - c_finalize_ex() - - def setup(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_digest_data(self): - ''' - Calls C_Digest on some data and makes sure there is no failure - ''' - data_to_digest = "Some arbitrary string" - ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) - assert ret == CKR_OK, "Digesting should occur with no errors" - assert len(digested_data) > 0, "The digested data should have a length" - assert data_to_digest != digested_data, "The digested data should not be the same as the original string" - - def test_multipart_digest_data(self): - data_to_digest = ["Some arbitrary string", "Some second arbitrary string"] - ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) - assert ret == CKR_OK, "Digesting should occur with no errors" - assert len(digested_data) > 0, "The digested data should have a length" - assert _get_string_from_list(data_to_digest) != digested_data, "The digested data should not be the same as the original string" - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_MD2, CKR_OK +from pycryptoki.encryption import _get_string_from_list +from pycryptoki.misc import c_digest +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestDigestData(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_digest_data(self): + ''' + Calls C_Digest on some data and makes sure there is no failure + ''' + data_to_digest = "Some arbitrary string" + ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) + assert ret == CKR_OK, "Digesting should occur with no errors" + assert len(digested_data) > 0, "The digested data should have a length" + assert data_to_digest != digested_data, "The digested data should not be the same as the original string" + + def test_multipart_digest_data(self): + data_to_digest = ["Some arbitrary string", "Some second arbitrary string"] + ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) + assert ret == CKR_OK, "Digesting should occur with no errors" + assert len(digested_data) > 0, "The digested data should have a length" + assert _get_string_from_list(data_to_digest) != digested_data, "The digested data should not be the same as the original string" + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_encrypt_decrypt.py b/pycryptoki/tests/test_encrypt_decrypt.py index 061da03..e56ed79 100755 --- a/pycryptoki/tests/test_encrypt_decrypt.py +++ b/pycryptoki/tests/test_encrypt_decrypt.py @@ -1,72 +1,72 @@ -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ - CKM_DES_CBC_PAD, CKM_DES_CBC_ENCRYPT_DATA -from pycryptoki.encryption import c_encrypt, c_decrypt, _split_string_into_list, \ - _get_string_from_list -from pycryptoki.key_generator import c_generate_key_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestEncryptData(): - @classmethod - def setup_class(self): - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(self): - c_finalize_ex() - - def setup(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_encrypt_decrypt_string(self): - ''' - Tests encrypting and decrypting a string with a key - ''' - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - data_to_encrypt = "a" * (0xfff0) - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - - ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data) - assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] - assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) - - def test_multipart_encrypt_decrypt(self): - ''' - Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore doing it in multiple - parts - ''' - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - data_to_encrypt = ['a' * 512, 'b' * 512, 'c' * 512, 'd' * 512] - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - assert len(encrypted_data) == len(_get_string_from_list(data_to_encrypt)) - - encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) - - ret, decrypted_data = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data_chunks) - assert ret == CKR_OK, "Decryption should succeed, instead it returned " + ret_vals_dictionary[ret] - assert _get_string_from_list(data_to_encrypt) == decrypted_data, "The data before encryption should match the data after encryption" - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ + CKM_DES_CBC_PAD, CKM_DES_CBC_ENCRYPT_DATA +from pycryptoki.encryption import c_encrypt, c_decrypt, _split_string_into_list, \ + _get_string_from_list +from pycryptoki.key_generator import c_generate_key_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestEncryptData(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_encrypt_decrypt_string(self): + ''' + Tests encrypting and decrypting a string with a key + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + data_to_encrypt = "a" * (0xfff0) + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] + + ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data) + assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] + assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) + + def test_multipart_encrypt_decrypt(self): + ''' + Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore doing it in multiple + parts + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + data_to_encrypt = ['a' * 512, 'b' * 512, 'c' * 512, 'd' * 512] + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] + assert len(encrypted_data) == len(_get_string_from_list(data_to_encrypt)) + + encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) + + ret, decrypted_data = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data_chunks) + assert ret == CKR_OK, "Decryption should succeed, instead it returned " + ret_vals_dictionary[ret] + assert _get_string_from_list(data_to_encrypt) == decrypted_data, "The data before encryption should match the data after encryption" + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_get_token_info.py b/pycryptoki/tests/test_get_token_info.py index 1019a4c..2c1e726 100755 --- a/pycryptoki/tests/test_get_token_info.py +++ b/pycryptoki/tests/test_get_token_info.py @@ -1,47 +1,47 @@ -from ctypes import byref -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD -from pycryptoki.defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ - CKF_RESTORE_KEY_NOT_NEEDED, CKF_TOKEN_INITIALIZED -from pycryptoki.session_management import c_finalize, ca_factory_reset_ex, \ - c_get_token_info_ex, c_close_all_sessions, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestGetTokenInfo(): - - def setup(self): - setup_for_tests(True, False, False) - c_initialize_ex() - - def teardown(self): - c_finalize() - - def test_initial_flags(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL); - - #Get to clean state - c_close_all_sessions(admin_slot) - ca_factory_reset_ex(admin_slot) - - #Look at flags before initialization - flags = c_get_token_info_ex(admin_slot)['flags'] - expected_flags = CKF_TOKEN_PRESENT | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED - assert flags == expected_flags, "After factory reset found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) - - c_init_token_ex(admin_slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL); - - #Test flags after initialization - flags = c_get_token_info_ex(admin_slot)['flags'] - expected_flags = expected_flags | CKF_TOKEN_INITIALIZED - assert flags == expected_flags, "After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) - logger.info("After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags))) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) +from ctypes import byref +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD +from pycryptoki.defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ + CKF_RESTORE_KEY_NOT_NEEDED, CKF_TOKEN_INITIALIZED +from pycryptoki.session_management import c_finalize, ca_factory_reset_ex, \ + c_get_token_info_ex, c_close_all_sessions, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestGetTokenInfo(): + + def setup(self): + setup_for_tests(True, False, False) + c_initialize_ex() + + def teardown(self): + c_finalize() + + def test_initial_flags(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL); + + #Get to clean state + c_close_all_sessions(admin_slot) + ca_factory_reset_ex(admin_slot) + + #Look at flags before initialization + flags = c_get_token_info_ex(admin_slot)['flags'] + expected_flags = CKF_TOKEN_PRESENT | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED + assert flags == expected_flags, "After factory reset found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) + + c_init_token_ex(admin_slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL); + + #Test flags after initialization + flags = c_get_token_info_ex(admin_slot)['flags'] + expected_flags = expected_flags | CKF_TOKEN_INITIALIZED + assert flags == expected_flags, "After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) + logger.info("After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags))) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_keys.py b/pycryptoki/tests/test_keys.py index b07c1d2..dc2735b 100755 --- a/pycryptoki/tests/test_keys.py +++ b/pycryptoki/tests/test_keys.py @@ -1,167 +1,167 @@ -from ctypes import cast, pointer -from pycryptoki.cryptoki import CK_VOID_PTR, CK_ULONG -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ - CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ - CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP, \ - CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, CKM_DSA_PARAMETER_GEN_TEMP, \ - CKM_KCDSA_PARAMETER_GEN_TEMP, CKM_ARIA_KEY_GEN_TEMP, \ - CKM_DH_PKCS_PARAMETER_GEN_TEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, \ - CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, \ - CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP, curve_list -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKR_OK, \ - CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ - CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ - CKM_RC5_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ - CKM_DSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN, CKM_ARIA_KEY_GEN, \ - CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ - CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ - CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN, \ - CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS -from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, \ - c_derive_key, c_generate_key_ex, _get_mechanism -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import ctypes -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestKeys(): - @classmethod - def setup_class(self): - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(self): - c_finalize_ex() - - def setup(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), - (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), - (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), - (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), - (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), - (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), -# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), -# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX -# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) -# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX - ]) - def test_generate_key(self, key_type, key_template): - ''' - Tests generating a key, asserts that the operation returns correctly with key handles - greater than 0 - - @param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) - @param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) - ''' - ret, key_handle = c_generate_key(self.h_session, key_type, key_template) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] - assert key_handle > 0, "The key handle returned should be non zero" - - - @pytest.mark.parametrize(("key_type", "public_key_template", "private_key_template"), [ - (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), - (CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP), -# (CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP) #XXX - ]) - def test_generate_key_pair(self, key_type, public_key_template, private_key_template): - ''' - Tests generating a key pair, asserts that the operation returns correctly with key handles - greater than 0. - - @param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) - @param public_key_template: The template to use for public key generation (ex. CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 - @param private_key_template: The template to use for private key generation (ex. CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 - ''' - ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, key_type, public_key_template, private_key_template) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] - assert public_key_handle > 0, "The public key handle returned should be non zero" - assert private_key_handle > 0, "The private key handle returned should be non zero" - - @pytest.mark.parametrize(("curve_type"), curve_list.keys()) - def test_generate_ecdsa_key_pairs(self, curve_type): - print curve_list.keys() - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] - ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] - assert public_key_handle > 0, "The public key handle returned should be non zero" - assert private_key_handle > 0, "The private key handle returned should be non zero" - - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), - (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), - (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), - (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), - (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), - (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), -# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), -# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX -# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) -# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX - ]) - def test_derive_key(self, key_type, key_template): - ''' - Tests deriving a key - ''' - h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) - h_second_key = c_generate_key_ex(self.h_session, key_type, key_template) - - mech = _get_mechanism(CKM_CONCATENATE_BASE_AND_KEY) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - ret, h_derived_key = c_derive_key(self.h_session, h_base_key, key_template, None, mech) - assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_derived_key, key_template) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) +from ctypes import cast, pointer +from pycryptoki.cryptoki import CK_VOID_PTR, CK_ULONG +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ + CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ + CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP, \ + CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, CKM_DSA_PARAMETER_GEN_TEMP, \ + CKM_KCDSA_PARAMETER_GEN_TEMP, CKM_ARIA_KEY_GEN_TEMP, \ + CKM_DH_PKCS_PARAMETER_GEN_TEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, \ + CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, \ + CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP, curve_list +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKR_OK, \ + CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ + CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ + CKM_RC5_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ + CKM_DSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN, CKM_ARIA_KEY_GEN, \ + CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ + CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ + CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN, \ + CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS +from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, \ + c_derive_key, c_generate_key_ex, _get_mechanism +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import ctypes +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestKeys(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), + (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), + (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), + (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), + (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), + (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), + (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), +# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), +# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX +# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) +# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX + ]) + def test_generate_key(self, key_type, key_template): + ''' + Tests generating a key, asserts that the operation returns correctly with key handles + greater than 0 + + @param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) + @param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) + ''' + ret, key_handle = c_generate_key(self.h_session, key_type, key_template) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + assert key_handle > 0, "The key handle returned should be non zero" + + + @pytest.mark.parametrize(("key_type", "public_key_template", "private_key_template"), [ + (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), + (CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP), +# (CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP) #XXX + ]) + def test_generate_key_pair(self, key_type, public_key_template, private_key_template): + ''' + Tests generating a key pair, asserts that the operation returns correctly with key handles + greater than 0. + + @param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) + @param public_key_template: The template to use for public key generation (ex. CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 + @param private_key_template: The template to use for private key generation (ex. CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 + ''' + ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, key_type, public_key_template, private_key_template) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + assert public_key_handle > 0, "The public key handle returned should be non zero" + assert private_key_handle > 0, "The private key handle returned should be non zero" + + @pytest.mark.parametrize(("curve_type"), curve_list.keys()) + def test_generate_ecdsa_key_pairs(self, curve_type): + print curve_list.keys() + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] + ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + assert public_key_handle > 0, "The public key handle returned should be non zero" + assert private_key_handle > 0, "The private key handle returned should be non zero" + + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), + (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), + (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), + (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), + (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), + (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), + (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), +# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), +# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX +# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) +# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX + ]) + def test_derive_key(self, key_type, key_template): + ''' + Tests deriving a key + ''' + h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) + h_second_key = c_generate_key_ex(self.h_session, key_type, key_template) + + mech = _get_mechanism(CKM_CONCATENATE_BASE_AND_KEY) + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + ret, h_derived_key = c_derive_key(self.h_session, h_base_key, key_template, None, mech) + assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_derived_key, key_template) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_object_create.py b/pycryptoki/tests/test_object_create.py index 5e6a432..7810f7d 100755 --- a/pycryptoki/tests/test_object_create.py +++ b/pycryptoki/tests/test_object_create.py @@ -1,59 +1,59 @@ -from pycryptoki.default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_OK -from pycryptoki.misc import c_create_object -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestObjectCloning(): - @classmethod - def setup_class(self): - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(self): - c_finalize_ex() - - def setup(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_certificate_create(self): - ''' - Tests C_CreateObject with a certificate template and verifies the object's - attributes - ''' - - ret, h_object = c_create_object(self.h_session, CERTIFICATE_TEMPLATE) - assert ret == CKR_OK, "The result code of creating a certificate should be CKR_OK, not " + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_object, CERTIFICATE_TEMPLATE) - - def test_data_create(self): - ''' - Tests C_CreateObject with a data template and verifies the object's - attributes - ''' - ret, h_object = c_create_object(self.h_session, DATA_TEMPLATE) - assert ret == CKR_OK, "The result of creating a data object should be CKR_OK, not" + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) +from pycryptoki.default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_OK +from pycryptoki.misc import c_create_object +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestObjectCloning(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_certificate_create(self): + ''' + Tests C_CreateObject with a certificate template and verifies the object's + attributes + ''' + + ret, h_object = c_create_object(self.h_session, CERTIFICATE_TEMPLATE) + assert ret == CKR_OK, "The result code of creating a certificate should be CKR_OK, not " + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_object, CERTIFICATE_TEMPLATE) + + def test_data_create(self): + ''' + Tests C_CreateObject with a data template and verifies the object's + attributes + ''' + ret, h_object = c_create_object(self.h_session, DATA_TEMPLATE) + assert ret == CKR_OK, "The result of creating a data object should be CKR_OK, not" + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_sign_verify.py b/pycryptoki/tests/test_sign_verify.py index b01f81c..78f9f70 100755 --- a/pycryptoki/tests/test_sign_verify.py +++ b/pycryptoki/tests/test_sign_verify.py @@ -1,95 +1,95 @@ -from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_OK, CKM_RSA_PKCS, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKR_SIGNATURE_INVALID, CKM_DSA_KEY_PAIR_GEN, CKM_DSA -from pycryptoki.key_generator import c_generate_key_pair_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.sign_verify import c_sign, c_verify -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest -logger = logging.getLogger(__name__) - -class TestSignVerify(): - @classmethod - def setup_class(self): - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(self): - c_finalize_ex() - - def setup(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ - (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_RSA_PKCS), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) - ]) - def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): - ''' - Verifies that signing a string and verifying that string works - - @param key_type: The handle of the key to sign the data with - @param pub_key_template: The template for the public key to be generated - @param priv_key_template: The template for the private key to be generated - @param sign_flavor: The flavor of the signature - ''' - - #Generate a key for the test - h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - - data_to_sign = "This is some test string to sign." - ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) - assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] - - ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) - assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] - - @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) - ]) - def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): - ''' - Verifies that signing a string and verifying that string works doing the operation - in multiple parts with c_sign_update and c_verify_update - - @param key_type: The handle of the key to sign the data with - @param pub_key_template: The template for the public key to be generated - @param priv_key_template: The template for the private key to be generated - @param sign_flavor: The flavor of the signature - ''' - - #Generate a key for the test - h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - - data_to_sign = ["a" * 1024, "b" * 1024] - ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) - assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] - - ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) - assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) +from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_OK, CKM_RSA_PKCS, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKR_SIGNATURE_INVALID, CKM_DSA_KEY_PAIR_GEN, CKM_DSA +from pycryptoki.key_generator import c_generate_key_pair_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.sign_verify import c_sign, c_verify +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest +logger = logging.getLogger(__name__) + +class TestSignVerify(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ + (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_RSA_PKCS), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) + ]) + def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): + ''' + Verifies that signing a string and verifying that string works + + @param key_type: The handle of the key to sign the data with + @param pub_key_template: The template for the public key to be generated + @param priv_key_template: The template for the private key to be generated + @param sign_flavor: The flavor of the signature + ''' + + #Generate a key for the test + h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) + + data_to_sign = "This is some test string to sign." + ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) + assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] + + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) + assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] + + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) + ]) + def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): + ''' + Verifies that signing a string and verifying that string works doing the operation + in multiple parts with c_sign_update and c_verify_update + + @param key_type: The handle of the key to sign the data with + @param pub_key_template: The template for the public key to be generated + @param priv_key_template: The template for the private key to be generated + @param sign_flavor: The flavor of the signature + ''' + + #Generate a key for the test + h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) + + data_to_sign = ["a" * 1024, "b" * 1024] + ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) + assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] + + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) + assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_supporting_operations.py b/pycryptoki/tests/test_supporting_operations.py index bd2da55..274a66c 100755 --- a/pycryptoki/tests/test_supporting_operations.py +++ b/pycryptoki/tests/test_supporting_operations.py @@ -1,62 +1,62 @@ -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_OK -from pycryptoki.misc import c_generate_random_ex, c_seed_random, \ - c_generate_random -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestSupportingOperations(): - @classmethod - def setup_class(self): - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(self): - c_finalize_ex() - - def setup(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_rng(self): - ''' - Tests generating a random number - ''' - length = 15 - ret, random_string = c_generate_random(self.h_session, length) - assert ret == CKR_OK, "C_GenerateRandom should return CKR_OK, instead it returned " + ret_vals_dictionary[ret] - assert len(random_string) == length, "The length of the random string should be the same as the length of the requested data." - - def test_seeded_rng(self): - ''' - Tests that seeding the random number generator with the same data will - generate the same random number - ''' - seed = "k" * 1024 - ret = c_seed_random(self.h_session, seed) - assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, it returned " + ret_vals_dictionary[ret] - - random_string_one = c_generate_random_ex(self.h_session, 10) - - ret = c_seed_random(self.h_session, seed) - assert ret == CKR_OK, "Seeding the random number generator a second time shouldn't return an error, it returned " + ret_vals_dictionary[ret] - - random_string_two = c_generate_random_ex(self.h_session, 10) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKR_OK +from pycryptoki.misc import c_generate_random_ex, c_seed_random, \ + c_generate_random +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestSupportingOperations(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_rng(self): + ''' + Tests generating a random number + ''' + length = 15 + ret, random_string = c_generate_random(self.h_session, length) + assert ret == CKR_OK, "C_GenerateRandom should return CKR_OK, instead it returned " + ret_vals_dictionary[ret] + assert len(random_string) == length, "The length of the random string should be the same as the length of the requested data." + + def test_seeded_rng(self): + ''' + Tests that seeding the random number generator with the same data will + generate the same random number + ''' + seed = "k" * 1024 + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, it returned " + ret_vals_dictionary[ret] + + random_string_one = c_generate_random_ex(self.h_session, 10) + + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator a second time shouldn't return an error, it returned " + ret_vals_dictionary[ret] + + random_string_two = c_generate_random_ex(self.h_session, 10) + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/tests/test_usage_limit_and_count.py b/pycryptoki/tests/test_usage_limit_and_count.py index a1cb586..74e5470 100755 --- a/pycryptoki/tests/test_usage_limit_and_count.py +++ b/pycryptoki/tests/test_usage_limit_and_count.py @@ -1,326 +1,326 @@ -''' -Created on Aug 15, 2012 - -@author: root -''' - -from ctypes import * -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CK_ULONG, C_SetAttributeValue -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP -from pycryptoki.defaults import CO_PASSWORD, ADMIN_PARTITION_LABEL -from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ - CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ - CKM_DES_ECB, CKM_RSA_PKCS, CKR_OK, CKR_KEY_NOT_ACTIVE, CKU_USER, CKM_AES_ECB -from pycryptoki.encryption import c_encrypt, c_encrypt_ex -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex -from pycryptoki.session_management import login_ex -from pycryptoki.object_attr_lookup import c_get_attribute_value_ex -from pycryptoki.session_management import c_initialize_ex, c_open_session_ex, c_logout_ex, \ - c_close_session_ex, c_finalize -from pycryptoki.test_functions import LunaException -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - - -logger = logging.getLogger(__name__) - -class TestUsageLimitAndCount(): - - h_session = 0 - - def setup(self): - setup_for_tests(True, True, True) - c_initialize_ex() - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - c_finalize() - - def test_set_attribute_usage_limit_sym(self): - """ Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on - an symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 5 - Use C_getAttributeValue to verify """ - - logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an symmetric crypto object") - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 5} - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - usage_limit = 5 - - - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) -# print c_struct[CKA_USAGE_LIMIT] - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value - logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(int(usage_val_out))) - assert usage_limit== usage_val_out, "reported USAGE LIMIT does not match" - - - - - def test_usage_limit_attribute_check_sym_des(self): - """ - Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use des key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 - """ - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - usage_count = 2 - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) - - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) - - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - - - - - def test_usage_limit_attribute_check_sym_aes(self): - - """ - Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use aes key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 - """ - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - usage_count = 2 - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_AES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) - - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) - - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - - - - def test_set_attribute_usage_limit_Assym(self): - """ - Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on - an assymetric crypto object - Procedure: - Generate a RSA key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 on RSA public key - Use C_getAttributeValue to verify - """ - - logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an assymetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - usage_limit = 2 - - return_val = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) - if return_val != CKR_OK: raise LunaException(return_val, 'C_SetAttributeValue', "Setting up attribute") - - c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value - logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) - assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" - - - - - - def test_usage_limit_attribute_check_Assym(self): - """ - Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the assymetric crypto object - Procedure: - Generate a RSA Key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 - """ - - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the assymetric crypto object") - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - usage_count = 2 - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) - - - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - - return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - - c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - - - def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): - - """ - Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT - Procedure: - Generate a 3DES key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key 3 times for encryption - """ - - logger.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - return_val = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_val != CKR_OK: raise LunaException(return_val, 'C_setAttributeValue', "Setting up limit attribute") - - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - - return_val = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - logger.info("Called C_Encrypt, return code: " + str(return_val)) - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - - - - - def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): - - """ - Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT - Procedure: - Generate a RSA Key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key 3 times for encryption - """ - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - - return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - return_val = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - logger.info("Called C_Encrypt, return code: " + str(return_val)) - c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - - - -if __name__ == "__main__": - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) - +''' +Created on Aug 15, 2012 + +@author: root +''' + +from ctypes import * +from pycryptoki.attributes import Attributes +from pycryptoki.cryptoki import CK_ULONG, C_SetAttributeValue +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP +from pycryptoki.defaults import CO_PASSWORD, ADMIN_PARTITION_LABEL +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ + CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ + CKM_DES_ECB, CKM_RSA_PKCS, CKR_OK, CKR_KEY_NOT_ACTIVE, CKU_USER, CKM_AES_ECB +from pycryptoki.encryption import c_encrypt, c_encrypt_ex +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.session_management import login_ex +from pycryptoki.object_attr_lookup import c_get_attribute_value_ex +from pycryptoki.session_management import c_initialize_ex, c_open_session_ex, c_logout_ex, \ + c_close_session_ex, c_finalize +from pycryptoki.test_functions import LunaException +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + + +logger = logging.getLogger(__name__) + +class TestUsageLimitAndCount(): + + h_session = 0 + + def setup(self): + setup_for_tests(True, True, True) + c_initialize_ex() + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + c_finalize() + + def test_set_attribute_usage_limit_sym(self): + """ Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + an symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 5 + Use C_getAttributeValue to verify """ + + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + an symmetric crypto object") + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 5} + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + usage_limit = 5 + + + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) +# print c_struct[CKA_USAGE_LIMIT] + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value + logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(int(usage_val_out))) + assert usage_limit== usage_val_out, "reported USAGE LIMIT does not match" + + + + + def test_usage_limit_attribute_check_sym_des(self): + """ + Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use des key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + """ + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + usage_count = 2 + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) + + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + + + + def test_usage_limit_attribute_check_sym_aes(self): + + """ + Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use aes key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + """ + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + usage_count = 2 + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_AES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) + + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + + + def test_set_attribute_usage_limit_Assym(self): + """ + Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + an assymetric crypto object + Procedure: + Generate a RSA key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 on RSA public key + Use C_getAttributeValue to verify + """ + + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + an assymetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + usage_limit = 2 + + return_val = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) + if return_val != CKR_OK: raise LunaException(return_val, 'C_SetAttributeValue', "Setting up attribute") + + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value + logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + + + + + + def test_usage_limit_attribute_check_Assym(self): + """ + Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the assymetric crypto object + Procedure: + Generate a RSA Key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + """ + + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the assymetric crypto object") + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + usage_count = 2 + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) + + + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): + + """ + Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT + Procedure: + Generate a 3DES key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key 3 times for encryption + """ + + logger.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + return_val = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) + if return_val != CKR_OK: raise LunaException(return_val, 'C_setAttributeValue', "Setting up limit attribute") + + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + + return_val = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + logger.info("Called C_Encrypt, return code: " + str(return_val)) + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) + + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + + + + + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): + + """ + Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT + Procedure: + Generate a RSA Key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key 3 times for encryption + """ + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} + + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + + return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) + if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + return_val = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + logger.info("Called C_Encrypt, return code: " + str(return_val)) + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + + + +if __name__ == "__main__": + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) + diff --git a/pycryptoki/tests/test_wrap_unwrap.py b/pycryptoki/tests/test_wrap_unwrap.py index cca4c8a..b101790 100755 --- a/pycryptoki/tests/test_wrap_unwrap.py +++ b/pycryptoki/tests/test_wrap_unwrap.py @@ -1,87 +1,87 @@ -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_DES_UNWRAP_TEMP -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ - CKA_LABEL, CKM_DES_ECB -from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt -from pycryptoki.key_generator import c_generate_key, c_generate_key_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestWrappingKeys(): - @classmethod - def setup_class(self): - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(self): - c_finalize_ex() - - def setup(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_wrap_unwrap_key(self): - ''' - Tests the attributes of an unwrapped key are idential to the original key - ''' - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - #Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) - assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) - assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Verify all of the attributes against the originally generated attributes - verify_object_attributes(self.h_session, h_unwrapped_key, CKM_DES_KEY_GEN_TEMP) - - def test_encrypt_wrap_unwrap_decrypt_key(self): - ''' - Tests encrypting some data with a key. Then wrapping and unwrapping the key - and using the unwrapped key to decrypt the data. It then compares the data to the - original data. - ''' - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - #Encrypt some data - data_to_encrypt = "a" * 512 - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - - #Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) - assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) - assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Decrypt the data - ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_unwrapped_key, encrypted_data) - assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] - assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_DES_UNWRAP_TEMP +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ + CKA_LABEL, CKM_DES_ECB +from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt +from pycryptoki.key_generator import c_generate_key, c_generate_key_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ + login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex +from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.tests.setup_for_tests import setup_for_tests +from pycryptoki.token_management import get_token_by_label_ex +import logging +import os +import pytest + +logger = logging.getLogger(__name__) + +class TestWrappingKeys(): + @classmethod + def setup_class(self): + setup_for_tests(True, True, True) + c_initialize_ex() + + @classmethod + def teardown_class(self): + c_finalize_ex() + + def setup(self): + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + self.h_session = c_open_session_ex(slot_num=admin_slot) + login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) + + def teardown(self): + c_logout_ex(self.h_session) + c_close_session_ex(self.h_session) + + def test_wrap_unwrap_key(self): + ''' + Tests the attributes of an unwrapped key are idential to the original key + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + #Wrap the key + ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) + assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) + assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Verify all of the attributes against the originally generated attributes + verify_object_attributes(self.h_session, h_unwrapped_key, CKM_DES_KEY_GEN_TEMP) + + def test_encrypt_wrap_unwrap_decrypt_key(self): + ''' + Tests encrypting some data with a key. Then wrapping and unwrapping the key + and using the unwrapped key to decrypt the data. It then compares the data to the + original data. + ''' + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + #Encrypt some data + data_to_encrypt = "a" * 512 + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] + + #Wrap the key + ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) + assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) + assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + #Decrypt the data + ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_unwrapped_key, encrypted_data) + assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] + assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index 42de99a..fd3dd0e 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -1,103 +1,103 @@ -''' -Created on Aug 24, 2012 - -@author: mhughes -''' -from ctypes import byref, cast, create_string_buffer -from pycryptoki.cryptoki import C_InitToken, CK_ULONG, CK_CHAR_PTR, \ - C_GetSlotList, CK_BBOOL, CK_SLOT_ID, C_GetMechanismList, CK_MECHANISM_TYPE, \ - CK_MECHANISM_TYPE_PTR, CK_MECHANISM_INFO, C_GetMechanismInfo -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT -from pycryptoki.defines import CKR_OK -from pycryptoki.session_management import c_get_token_info, get_slot_info -from pycryptoki.test_functions import make_error_handle_function -import logging - -logger = logging.getLogger(__name__) - -def c_init_token(slot_num, password, token_label='Main Token'): - ''' - Initializes at token at a given slot with the proper password and label - @param slot_num: The index of the slot to c_initialize a token in - @param password: The password to c_initialize the slot with - @param token_label: The label to c_initialize the slot with - - @return: The result code - ''' - if password == '': - logger.info("C_InitToken: Initializing token. slot=" + str( - slot_num) + ", label='" + token_label + "', password='" + password + "'") - ret = C_InitToken(CK_ULONG(slot_num), None, - CK_ULONG(0), cast(create_string_buffer(token_label), CK_CHAR_PTR)) - return ret - else: - logger.info("C_InitToken: Initializing token. slot="+ str(slot_num) + ", label='" + token_label + "', password='" + password + "'") - ret = C_InitToken(CK_ULONG(slot_num), cast(create_string_buffer(password), CK_CHAR_PTR), CK_ULONG(len(password)), cast(create_string_buffer(token_label), CK_CHAR_PTR)) - return ret -c_init_token_ex = make_error_handle_function(c_init_token) - -def get_token_by_label(label): - ''' - Iterates through all the tokens and returns the first token that - has a label that is identical to the one that is passed in - - @param label:The label of the token to search for - @return: The result code, The slot of the token - ''' - - if label == ADMIN_PARTITION_LABEL: #XXX the admin partition's label changes depending on the boards state -# ret, slot_info = get_slot_info("Viper") -# return ret, slot_info.keys()[1] - return CKR_OK, ADMIN_SLOT - - us_count = CK_ULONG(0) - ret = C_GetSlotList(CK_BBOOL(1), None, byref(us_count)) - if ret != CKR_OK: return ret, None - num_slots = us_count.value - slot_list = (CK_SLOT_ID * num_slots)() - ret = C_GetSlotList(CK_BBOOL(1), slot_list, byref(us_count)) - if ret != CKR_OK: return ret, None - - for slot in slot_list: - ret, token_info = c_get_token_info(slot) - if token_info['label'] == label: - return ret, slot - - raise Exception("Slot with label " + str(label) + " not found.") -get_token_by_label_ex = make_error_handle_function(get_token_by_label) - -def c_get_mechanism_list(slot): - ''' - Gets the list of mechanisms from the HSM - - @param slot: The slot number to get the mechanism list on - @return: The result code, A python dictionary representing the mechanism list - ''' - count = CK_ULONG() - ret = C_GetMechanismList(CK_SLOT_ID(slot), None, byref(count)) - last_count = count - if ret != CKR_OK: return ret, None - mech_list = (CK_MECHANISM_TYPE * count.value)() - ret = C_GetMechanismList(CK_SLOT_ID(slot), CK_MECHANISM_TYPE_PTR(mech_list), byref(count)) - if ret != CKR_OK: return ret, None - if last_count != count: raise Exception("Mechanism list count was not consistent between function calls") - - ret_list = [] - for i in range(0, count.value): - ret_list.append(mech_list[i]) - return ret, ret_list -c_get_mechanism_list_ex = make_error_handle_function(c_get_mechanism_list) - -def c_get_mechanism_info(slot, mechanism_type): - ''' - Gets a mechanism's info - - @param slot: The slot to query - @param mechanism_type: The type of the mechanism to get the information for - - @return: The result code, The mechanism info - ''' - mech_info = CK_MECHANISM_INFO() - ret = C_GetMechanismInfo(CK_ULONG(slot), CK_MECHANISM_TYPE(mechanism_type), byref(mech_info)) - return ret, mech_info +''' +Created on Aug 24, 2012 + +@author: mhughes +''' +from ctypes import byref, cast, create_string_buffer +from pycryptoki.cryptoki import C_InitToken, CK_ULONG, CK_CHAR_PTR, \ + C_GetSlotList, CK_BBOOL, CK_SLOT_ID, C_GetMechanismList, CK_MECHANISM_TYPE, \ + CK_MECHANISM_TYPE_PTR, CK_MECHANISM_INFO, C_GetMechanismInfo +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT +from pycryptoki.defines import CKR_OK +from pycryptoki.session_management import c_get_token_info, get_slot_info +from pycryptoki.test_functions import make_error_handle_function +import logging + +logger = logging.getLogger(__name__) + +def c_init_token(slot_num, password, token_label='Main Token'): + ''' + Initializes at token at a given slot with the proper password and label + @param slot_num: The index of the slot to c_initialize a token in + @param password: The password to c_initialize the slot with + @param token_label: The label to c_initialize the slot with + + @return: The result code + ''' + if password == '': + logger.info("C_InitToken: Initializing token. slot=" + str( + slot_num) + ", label='" + token_label + "', password='" + password + "'") + ret = C_InitToken(CK_ULONG(slot_num), None, + CK_ULONG(0), cast(create_string_buffer(token_label), CK_CHAR_PTR)) + return ret + else: + logger.info("C_InitToken: Initializing token. slot="+ str(slot_num) + ", label='" + token_label + "', password='" + password + "'") + ret = C_InitToken(CK_ULONG(slot_num), cast(create_string_buffer(password), CK_CHAR_PTR), CK_ULONG(len(password)), cast(create_string_buffer(token_label), CK_CHAR_PTR)) + return ret +c_init_token_ex = make_error_handle_function(c_init_token) + +def get_token_by_label(label): + ''' + Iterates through all the tokens and returns the first token that + has a label that is identical to the one that is passed in + + @param label:The label of the token to search for + @return: The result code, The slot of the token + ''' + + if label == ADMIN_PARTITION_LABEL: #XXX the admin partition's label changes depending on the boards state +# ret, slot_info = get_slot_info("Viper") +# return ret, slot_info.keys()[1] + return CKR_OK, ADMIN_SLOT + + us_count = CK_ULONG(0) + ret = C_GetSlotList(CK_BBOOL(1), None, byref(us_count)) + if ret != CKR_OK: return ret, None + num_slots = us_count.value + slot_list = (CK_SLOT_ID * num_slots)() + ret = C_GetSlotList(CK_BBOOL(1), slot_list, byref(us_count)) + if ret != CKR_OK: return ret, None + + for slot in slot_list: + ret, token_info = c_get_token_info(slot) + if token_info['label'] == label: + return ret, slot + + raise Exception("Slot with label " + str(label) + " not found.") +get_token_by_label_ex = make_error_handle_function(get_token_by_label) + +def c_get_mechanism_list(slot): + ''' + Gets the list of mechanisms from the HSM + + @param slot: The slot number to get the mechanism list on + @return: The result code, A python dictionary representing the mechanism list + ''' + count = CK_ULONG() + ret = C_GetMechanismList(CK_SLOT_ID(slot), None, byref(count)) + last_count = count + if ret != CKR_OK: return ret, None + mech_list = (CK_MECHANISM_TYPE * count.value)() + ret = C_GetMechanismList(CK_SLOT_ID(slot), CK_MECHANISM_TYPE_PTR(mech_list), byref(count)) + if ret != CKR_OK: return ret, None + if last_count != count: raise Exception("Mechanism list count was not consistent between function calls") + + ret_list = [] + for i in range(0, count.value): + ret_list.append(mech_list[i]) + return ret, ret_list +c_get_mechanism_list_ex = make_error_handle_function(c_get_mechanism_list) + +def c_get_mechanism_info(slot, mechanism_type): + ''' + Gets a mechanism's info + + @param slot: The slot to query + @param mechanism_type: The type of the mechanism to get the information for + + @return: The result code, The mechanism info + ''' + mech_info = CK_MECHANISM_INFO() + ret = C_GetMechanismInfo(CK_ULONG(slot), CK_MECHANISM_TYPE(mechanism_type), byref(mech_info)) + return ret, mech_info c_get_mechanism_info_ex = make_error_handle_function(c_get_mechanism_info) \ No newline at end of file diff --git a/setup.py b/setup.py index bd830f2..b0840ba 100755 --- a/setup.py +++ b/setup.py @@ -12,6 +12,11 @@ author='Michael Hughes', author_email='michael.hughes@safenet-inc.com', url='http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Pages/pycryptoki.aspx', - version='1.0', - packages=['pycryptoki', 'pycryptoki.setup', 'pycryptoki.tests', 'pycryptoki.daemon'] - ) \ No newline at end of file + version='1.1', + packages=['pycryptoki', + 'pycryptoki.setup', + 'pycryptoki.tests', + 'pycryptoki.daemon'], + scripts=['pycryptoki/daemon/rpyc_pycryptoki.py', + 'pycryptoki/daemon/pycryptoki_daemon.py'] + ) From 3129ce16b5df8a9e9c1f67b57bfa3e479a1b7647 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 12 May 2015 13:15:42 -0400 Subject: [PATCH 004/109] LA-1062 Fixed logging for rpyc Change-Id: I44e02ea8766c0db6ea7da10aaaf1a0cea3280044 --- __init__.py | 7 +++++++ pycryptoki/daemon/rpyc_pycryptoki.py | 17 +---------------- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/__init__.py b/__init__.py index e69de29..8151ac0 100755 --- a/__init__.py +++ b/__init__.py @@ -0,0 +1,7 @@ +import logging +import sys + +logging.basicConfig(stream=sys.stdout, + level=logging.DEBUG, + format='%(asctime)s:%(name)s:%(levelname)s: %(message)s') +logging.getLogger(__name__).addHandler(logging.NullHandler()) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index f74b84e..e945e7d 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python -u """ RPYC version of of the pycryptoki daemon """ @@ -287,7 +287,6 @@ def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_fla t = ThreadedServer(PycryptokiService, hostname=ip, port=port, - logger=logger, protocol_config={'allow_public_attrs': True, 'allow_all_attrs': True, 'allow_getattr': True, @@ -295,17 +294,3 @@ def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_fla 'allow_delattr': True}) print "Starting Server" t.start() - - - - - - - - - - - - - - From 6ccbec4825e81744ebc8c8bd86a36cadbed3840a Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 18 May 2015 08:15:52 -0400 Subject: [PATCH 005/109] LA-1057 Explicit convert to long for CKA_EXPONENT Change-Id: I27442bce17960b3c3948fc4ef55404b92cc1a8e2 --- pycryptoki/attributes.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 8f38ec7..7954fa9 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -144,7 +144,9 @@ def to_byte_array(val): :param val: Big Integer to convert. :return: c_ubyte array """ - width = val.bit_length() + # Explicitly convert to a long. Python doesn't like X.bit_length() where X is an int + # and not a variable assigned an int. + width = long(val).bit_length() width += 8 - ((width % 8) or 8) fmt = "{:0%sb}" % width From dbb9dd2341160e2477038f81fe466f66ad499574 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 19 May 2015 10:02:53 -0400 Subject: [PATCH 006/109] LA-1062 Use build from 6.0 instead of 5.4 Change-Id: I4fe5d6a0a3768d4c4a268c01daabaf470ca578dc --- pycryptoki/attributes.py | 3 +- pycryptoki/cryptoki.py | 2849 +++++++++++++++++++--------------- pycryptoki/defines.py | 112 +- pycryptoki/hsm_management.py | 41 +- pycryptoki/return_values.py | 37 + 5 files changed, 1770 insertions(+), 1272 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 7954fa9..9c18fd6 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -145,7 +145,7 @@ def to_byte_array(val): :return: c_ubyte array """ # Explicitly convert to a long. Python doesn't like X.bit_length() where X is an int - # and not a variable assigned an int. + # and not a variable assigned an int. width = long(val).bit_length() width += 8 - ((width % 8) or 8) @@ -192,6 +192,7 @@ def __init__(self, attributes_list=None): def add_attribute(self, key, value): ''' Add an attribute to the dictionary in place + @param key: The type of the attribute @param value: The value of the attribute ''' diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index 463264d..283acaa 100644 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -13,564 +13,608 @@ import sys from ctypes import * -LUNA_RET_CB_PROT_DATA_INVALID = -2147481047 -LUNA_RET_SAVED_STATE_INVALID = 23068672 -LUNA_RET_STATE_UNSAVEABLE = 25165824 -LUNA_RET_LOG_FILE_NOT_OPEN = -2147480320 -RC_OBJECT_NOT_IN_LIST = -1073740790 -LUNA_INVALID_PACKET_LAYOUT = -2147482352 -LUNA_RET_ATTRIBUTE_TYPE_INVALID = 1179648 -RC_INVALID_INDEX = -1073740789 -LUNA_HIFN_UNKNOWN_ALGORITHM = -2147482353 -LUNA_RET_LOG_NO_KCV = -2147480316 -LUNA_RET_MM_ITERATOR_PAST_END = 3211269 -LUNA_RET_HIFN_DMA_ERROR = -2147482357 -LUNA_RET_DEVICE_TIMEOUT = -2147483636 -RC_PARTITION_LOCKED = -1073737728 -LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES = 68103 -RC_PARTITION_NOT_ACTIVATED = -1073737727 -RC_FAILED_TO_CREATE_THREAD = -1073733632 -RC_CALLBACK_ERROR = -1073733631 -RC_UNKNOWN_CALLBACK_COMMAND = -1073733630 -RC_SHUTTING_DOWN = -1073733629 -RC_REMOTE_SIDE_DISCONNECTED = -1073733628 -RC_SOCKET_CLOSED = -1073733627 -LUNA_RET_SFNT3120_CRC = 3147811 -RC_INVALID_COMMAND = -1073733626 -RC_UNKNOWN_COMMAND = -1073733625 -RC_UNKNOWN_COMMAND_VERSION = -1073733624 -RC_FILE_LOCK_FAILED = -1073733623 -RC_FILE_LOCK_ERROR = -1073733616 -RC_FAILED_TO_CREATE_PROCESS = -1073733615 -RC_USB_PED_NOT_FOUND = -1073733614 -RC_USB_PED_NOT_RESPONDING = -1073733613 -RC_USB_PED_OPERATION_CANCELLED = -1073733612 -RC_USB_PED_TOO_MANY_CONNECTED = -1073733611 -MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED = 32 -RC_USB_PED_OUT_OF_SYNC = -1073733610 -RC_UNABLE_TO_CONNECT = -1073737472 -LUNA_RET_SM_ACCESS_REALLOC_ERROR = 3211521 -LUNA_RET_CCM_UPDATE_DENIED = -2147482875 -LUNA_RET_UNWRAPPING_ERROR = -2147483384 -LUNA_RET_CHALLENGE_TYPE_INVALID = 2099968 -LUNA_RET_INVALID_PRIVATE_KEY_TYPE = -2147483383 -RC_SOCKET_WOULDBLOCK = -1073740538 -LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST = 3145993 -LUNA_RET_KCV_PARAMETER_MISSING = -2147483381 -LUNA_RET_CB_RETRY = -2147481083 -LUNA_RET_CB_ABORTED = -2147481082 -LUNA_RET_CB_NO_MEMORY = -2147481085 -LUNA_RET_CB_SYS_ERROR = -2147481081 -LUNA_RET_CB_HIOS_HANDLE_INVALID = -2147481072 -LUNA_RET_CB_PARAM_INVALID = -2147481086 -LUNA_RET_CB_HIOS_ID_INVALID = -2147481071 -LUNA_RET_CB_HIOS_CLOSED = -2147481070 -LUNA_RET_CB_NOT_SUPPORTED = -2147481087 -LUNA_RET_CB_HIOS_CANCELED = -2147481069 -LUNA_RET_CB_HIOS_IO_ERROR = -2147481068 -LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS = 2100229 -LUNA_RET_CB_HIOS_SEND_TIMEOUT = -2147481067 -LUNA_RET_CB_HIOS_RECV_TIMEOUT = -2147481066 -LUNA_RET_STORAGE_TYPE_INCONSISTENT = 2100228 -LUNA_RET_CB_HIOS_STATE_INVALID = -2147481065 -LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL = -2147481064 -LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST = 2100227 -LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL = -2147481063 -LUNA_RET_CB_HANDLE_INVALID = -2147481056 -LUNA_RET_OH_OBJECT_ALREADY_EXISTS = 68610 -LUNA_RET_OH_OBJECT_TYPE_INVALID = 3148801 -LUNA_RET_CB_REMOTE_CLOSED = -2147481053 -LUNA_RET_OH_OBJECT_VERSION_INVALID = 3148800 -LUNA_RET_CB_MUST_READ = -2147481051 -LUNA_RET_CHALLENGE_INVALID = 2099972 -LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE = -2147481049 -LUNA_RET_CB_SYNC_ERROR = -2147481048 -LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT = 68355 -LUNA_RET_CHALLENGE_RESPONSE_INCORRECT = 10488579 +LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 +LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 +LUNA_RET_VECTOR_TOO_SMALL = -2147483115 +LUNA_RET_VECTOR_VERSION_INVALID = -2147483111 +MSG_LAST = 54 +LUNA_RET_VECTOR_TOO_LARGE = -2147483116 +LUNA_RET_VECTOR_DUPLICATE = -2147483109 +LUNA_RET_VECTOR_TYPE_INVALID = -2147483108 +LUNA_RET_CANCEL = 65536 +LUNA_RET_MISSING_VECTOR = -2147483117 +LUNA_RET_MISSING_COMMAND_PARAMETER = -2147483107 +LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED = -2147483106 +LUNA_RET_MISSING_NUMBER_OF_VECTORS = -2147483118 +LUNA_RET_M_OF_N_IS_NOT_REQUIRED = -2147483105 +LUNA_RET_M_OF_N_IS_NOT_INITIALZED = -2147483104 +LUNA_RET_M_OF_N_PARAMETER_EXIST = -2147483112 +LUNA_RET_MISSING_VALUE_FOR_N = -2147483119 +LUNA_RET_M_OF_N_SECRET_INVALID = -2147483103 +LUNA_RET_CCM_NOT_PRESENT = -2147482880 +LUNA_RET_MISSING_VALUE_FOR_M = -2147483120 +LUNA_RET_CCM_NOT_SUPPORTED = -2147482879 +LUNA_RET_CCM_UNREMOVABLE = -2147482878 +LUNA_RET_MISSING_WEIGHT_VALUE = -2147483121 +LUNA_RET_CCM_CERT_INVALID = -2147482877 +LUNA_RET_CCM_SIGN_INVALID = -2147482876 +LUNA_RET_TOO_MANY_WEIGHTS = -2147483122 +RC_SSL_CREATE_SSL_ERROR = -1073740025 +LUNA_RET_M_OF_N_ACTIVATION_REQUIRED = -2147483125 +LUNA_RET_CCM_FWUPDATE_DENIED = -2147482874 +LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE = -2147483126 +LUNA_RET_VECTOR_OF_DIFFERENT_SET = -2147483110 +LUNA_RET_SPLIT_ID_INVALID = -2147483127 +LUNA_RET_CCM_TOO_LARGE = 2162689 +LUNA_RET_SPLIT_DATA_INVALID = -2147483128 +LUNA_RET_SM_ACCESS_ID_INVALID = -2147482624 +LUNA_RET_MISSING_SPLITS = -2147483129 +LUNA_RET_OBJECT_DELETED = -2147483635 +LUNA_RET_TOTAL_WEIGHT_INVALID = -2147483130 +LUNA_RET_SM_ACCESS_ALREADY_EXISTS = -2147482623 +LUNA_RET_WEIGHT_TOO_SMALL = -2147483131 +LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED = -2147482622 +LUNA_RET_WEIGHT_TOO_LARGE = -2147483132 +LUNA_RET_M_TOO_SMALL = -2147483133 LUNA_RET_SM_UNKNOWN_ACCESS_TYPE = -2147482621 -LUNA_RET_CHALLENGE_NOT_REQUIRED = 68354 -LUNA_RET_CHALLENGE_REQUIRES_PED = 68353 -LUNA_RET_LOG_BAD_FILE_NAME = -2147480318 -LUNA_RET_POLICY_NOT_FOUND = 2099730 -LUNA_RET_LOG_FULL = -2147480317 -LUNA_RET_BAD_SN = 2099729 -LUNA_RET_RM_CONFIG_ILLEGAL = 2099728 -LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE = 2099727 -LUNA_RET_LOG_BAD_RECORD_HMAC = -2147480315 -LUNA_RET_BAD_FW_VERSION = 2099726 -LUNA_RET_BAD_PPID = 2099725 -LUNA_RET_LOG_BAD_TIME = -2147480314 -LUNA_RET_LOG_AUDIT_NOT_INITIALIZED = -2147480313 -LUNA_RET_OPERATION_RESTRICTED = 68107 -LUNA_RET_RM_POLICY_WRITE_RESTRICTED = 68106 -LUNA_RET_LOG_RESYNC_NEEDED = -2147480312 -LUNA_RET_LICENSE_CAPACITY_EXCEEDED = 68105 -LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS = -2147480311 -LUNA_RET_LICENSE_ID_UNKNOWN = 2099720 -RC_SOCKET_ADDRESS_IN_USE = -1073740537 -LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD = -2147480310 -LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL = 68102 -LUNA_RET_USER_ALREADY_ACTIVATED = -2147480309 -LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE = 2099717 -LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE = 2099716 -LUNA_RET_RM_BAD_HSM_PARAMS = 3148291 -LUNA_RET_TOKEN_LOCKED_OUT_CL = 3145984 -LUNA_RET_RETRY = 3145761 -RC_SSL_WANT_WRITE_ERROR = -1073740018 -LUNA_RET_RM_NO_MEMORY = 3213826 -LUNA_RET_RM_ELEMENT_ID_INVALID = 2099713 -LUNA_RET_RM_ELEMENT_VALUE_INVALID = 2099712 -RC_RC_ERROR = -1073741824 +RC_SERVER_DISCONNECTED = -1073740540 +LUNA_RET_M_TOO_LARGE = -2147483134 +LUNA_RET_SM_BAD_ACCESS_HANDLE = -2147482620 +LUNA_RET_N_TOO_LARGE = -2147483136 +LUNA_RET_SM_BAD_CONTEXT_NUMBER = -2147482619 LUNA_RET_KEY_NOT_ACTIVE = -2147481340 -MSG_NVRAM_WRITE_FAILED = 26 -RC_MEMORY_ALLOCATION = -1073741823 -LUNA_RET_HSM_STORAGE_FULL = -2147481342 -RC_GENERAL_ERROR = -1073741822 -LUNA_RET_HA_NOT_SUPPORTED = -2147481344 -LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE = 68108 -RC_POINTER_INVALID = -1073741821 -MSG_FACTORY_RESET = 53 -LUNA_RET_ECC_UNKNOWN_CURVE = -2147482107 +LUNA_RET_SIM_AUTHFORM_INVALID = 2097438 +RC_SOCKET_WOULDBLOCK = -1073740538 +LUNA_RET_CONTAINER_LOCKED = -2147483639 +RC_HOST_RESOLUTION_ERROR = -1073740535 +LUNA_RET_SM_UNKNOWN_SESSION_TYPE = -2147482618 +LUNA_RET_INVALID_CERTIFICATE_FUNCTION = -2147483355 +LUNA_RET_UNKNOWN_COMMAND = 3145729 +LUNA_RET_HOC_MISSING = -2147483356 +LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED = -2147482617 +LUNA_RET_ROOT_CERT_MISSING = -2147483357 +LUNA_RET_SM_CONTEXT_NOT_ALLOCATED = -2147482616 +LUNA_RET_ECC_DAC_MISSING = -2147483358 +LUNA_RET_ECC_DAK_MISSING = -2147483359 +LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW = -2147482615 +LUNA_RET_ECC_HOC_MISSING = -2147483360 +LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE = -2147482614 +LUNA_RET_ECC_HOK_MISSING = -2147483361 +LUNA_RET_ECC_MIC_MISSING = -2147483362 +LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE = -2147482613 +LUNA_RET_SIM_CORRUPT_DATA = -2147483363 +LUNA_RET_HIFN_NOT_PRESENT = -2147482368 +LUNA_RET_SIM_VERSION_UNSUPPORTED = -2147483364 +LUNA_RET_SIM_AUTHORIZATION_FAILED = -2147483365 +LUNA_RET_HIFN_SOURCE_COUNT_INVALID = -2147482367 +LUNA_RET_CITS_DAK_MISSING = -2147483366 +LUNA_RET_HIFN_DESTINATION_COUNT_INVALID = -2147482366 +LUNA_RET_HOK_MISSING = -2147483367 +LUNA_RET_BAD_DAK = -2147483368 +LUNA_RET_HIFN_INVALID_MAC_ALGORITHM = -2147482365 LUNA_RET_DAK_MISSING = -2147483369 -RC_SLOT_ID_INVALID = -1073741567 -RC_UNEXPECTED = -1073741820 -MSG_BAD_HMAC = 51 -LUNA_RET_ECC_SELF_TEST_FAILURE = -2147482108 -MSG_LOG_WAS_TRUNCATED = 50 -RC_OPERATION_WOULD_BLOCK = -1073741819 -MSG_ZEROIZING_AFTER_DECOMMISSION = 48 -RC_BUFFER_TOO_SMALL = -1073741818 +RC_DATA_CORRUPTED = -1073740799 +LUNA_RET_HIFN_INVALID_MAC_MODE = -2147482364 +LUNA_RET_BAD_MAC = -2147483370 +LUNA_RET_SSK_MISSING = -2147483371 +LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID = -2147482363 +LUNA_RET_BAD_DAC = -2147483372 +LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID = -2147482362 +LUNA_RET_DAC_MISSING = -2147483373 +LUNA_RET_DAC_POLICY_PID_MISMATCH = -2147483374 +LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM = -2147482361 +LUNA_RET_MAC_MISSING = -2147483375 +RC_TOKEN_STATE_INVALID = -1073740800 +LUNA_RET_HIFN_INVALID_ENCRYPT_MODE = -2147482360 +LUNA_RET_INVALID_ACCESS_LEVEL = -2147483376 +LUNA_RET_MASKING_NOT_SUPPORTED = -2147483377 +LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID = -2147482359 +LUNA_RET_CPK_PARAMETER_MISSING = -2147483378 +LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID = -2147482358 +LUNA_RET_TUK_PARAMETER_MISSING = -2147483379 +LUNA_RET_TWC_PARAMETER_MISSING = -2147483380 +LUNA_RET_HIFN_DMA_ERROR = -2147482357 +LUNA_RET_KCV_PARAMETER_MISSING = -2147483381 +LUNA_RET_WRAPPING_KEY_SIZE_RANGE = 18087936 +RC_OPERATION_TIMED_OUT = -1073741053 +RC_SSL_GET_CERTIFICATE_ERROR = -1073740023 +LUNA_RET_TOKEN_NOT_PRESENT = 14680064 +LUNA_RET_SP_RX_ERROR = 3146034 +LUNA_RET_PED_UNSUPPORTED_PROTOCOL = 3146049 +MSG_RESYNC = 46 MSG_RESTART = 47 -LUNA_RET_PE1746_ERROR = 3147911 -RC_CANCEL = -1073741568 +MSG_ZEROIZING_AFTER_DECOMMISSION = 48 MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED = 45 -LUNA_RET_ISES_TEST_VS_BSAFE_FAILED = 3147910 +MSG_ZEROIZING_AFTER_NO_SECURE_DATA = 49 +MSG_LOG_WAS_TRUNCATED = 50 MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED = 44 +MSG_BAD_HMAC = 51 +MSG_ZEROIZING = 52 MSG_GENERATING_NEW_TVK_FAILED = 43 -LUNA_RET_ISES_CMD_FAILED = 3147908 -RC_DATA_INVALID = -1073741566 -LUNA_RET_ISES_RNG_TEST_FAILED = 3147907 -RC_PIN_INVALID = -1073741565 -LUNA_RET_ISES_LNAU_TEST_FAILED = 3147906 +MSG_FACTORY_RESET = 53 +MSG_GENERATING_NEW_TVK_PASSED = 42 +MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK = 40 MSG_TVK_WAS_CORRUPTED = 39 -LUNA_RET_ISES_INIT_FAILED = 3147905 -MSG_RTC_ROLLED_BACK = 37 -LUNA_RET_ISES_ERROR = 3147904 +MSG_TVK_TIMESTAMP_UPDATE_FAILED = 38 MSG_TVK_TIMESTAMP_IS_TOO_OLD = 36 -LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT = 3147812 -MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK = 35 +RC_STC_RSA_DECRYPT_ERROR = -1073700840 MSG_TVK_TIMESTAMP_CORRUPTED = 34 -RC_NON_CRYPTOKI_ELEMENT_CLONE = -1073741562 -MSG_TVK_TIMESTAMP_RECOVERY_FAILED = 33 -LUNA_RET_SFNT3120_SELFTEST_FAILED = 3147810 -LUNA_RET_SFNT3120_ERROR = 3147809 -MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER = 31 -MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET = 30 -RC_PIN_LOCKED = -1073741560 +MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED = 32 MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY = 29 -LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT = 3147790 -MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING = 28 -LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS = 3147789 MSG_TVK_WAS_LOST_DUE_TO_TAMPER = 27 -RC_KEY_NEEDED = -1073741558 +MSG_NVRAM_WRITE_FAILED = 26 MSG_NVRAM_READ_FAILED = 25 -LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH = 3147787 -RC_USER_NAME_IN_USE = -1073741557 -LUNA_RET_HIFN6500_INVALID_PARAMETERS = 3147786 -LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS = 3147788 +MSG_RTC_MSG_NVRAM_READ_FAILED = 24 MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED = 23 -LUNA_RET_HIFN_DESTINATION_COUNT_INVALID = -2147482366 -LUNA_RET_HIFN6500_ALU_TIMEOUT = 3147785 -RC_DER_CLASS_INVALID = -1073741312 -MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF = 21 -LUNA_RET_HIFN6500_RNG_UNDERFLOW = 3147784 -RC_MANUFACTURING_NO_CONFIG_AVAILABLE = -1073741056 +MSG_RTC_CONFIGURATION_CORRUPTED = 22 MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF = 19 -LUNA_RET_HIFN6500_RNG_FAILED = 3147782 -RC_MANUFACTURING_TOKEN_NOT_PRESENT = -1073741055 +MSG_RTC_BATTERY_LOW = 18 MSG_RTC_LOST_ALL_POWER = 17 -LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED = 3147781 +MSG_RTC_TAMPER_CIRCUITS_RE_ARMED = 16 MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT = 15 MSG_RTC_TAMPER_2_SIGNAL = 14 -RC_OPERATION_TIMED_OUT = -1073741053 MSG_RTC_EXTERNAL_TAMPER_LATCHED = 13 MSG_RTC_RECONFIGURING_FAILED = 12 -LUNA_RET_HIFN6500_NOT_PRESENT = 3147777 -LUNA_RET_INVALID_BOARD_TYPE = -2147481856 MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS = 10 -LUNA_RET_INVALID_IP_PACKET = -2147482112 -MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS = 8 -LUNA_RET_MTK_SPLIT_INVALID = -2147482317 +MSG_RTC_CANT_CLEAN_TAMPER_2 = 9 MSG_RTC_CANT_CLEAN_TAMPER_1 = 7 -LUNA_RET_MTK_STATE_INVALID = -2147482318 -RC_FILE_NAME_INVALID = -1073740798 +MSG_RTC_CANT_ACCESS = 6 MSG_RTC_CANT_INITIALIZE_I2C = 5 -MSG_RTC_CANT_CLEAN_TAMPER_2 = 9 +LUNA2_RET_HIFN_RESET_ERROR = -2147482356 +LUNA_RET_TSN_MISMATCH = -2147483382 MSG_RTC_MSG_NVRAM_WRITE_FAILED = 4 -LUNA_RET_HIFN_DMA_INVALID_REVISION = -2147482320 -LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO = -2147482342 -RC_FILE_ERROR = -1073740796 -LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO = -2147482343 -RC_OBJECT_ID_INVALID = -1073740795 -LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO = -2147482344 -LUNA_RET_HIFN_DESTINATION_OVERRUN = -2147482345 -RC_SOCKET_ADDRESS_INVALID = -1073740794 -LUNA_RET_HIFN_END_MARKER_NOT_PRESENT = -2147482346 -RC_LISTEN_SOCKET_INVALID = -1073740793 -LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID = -2147482347 -LUNA_RET_HIFN_INVALID_PAD_ALGORITHM = -2147482348 -RC_CACHE_DIRTY = -1073740792 -LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID = -2147482349 -RC_CACHE_NOT_MAPPED = -1073740791 -LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID = -2147482350 +LUNA_RET_HIFN_DMA_NOT_IDLE = -2147482355 +MSG_RTC_CANT_GET_TAMPER_TIMER = 2 +LUNA_RET_UNWRAPPING_ERROR = -2147483384 +LUNA_RET_HIFN_DMA_TIMED_OUT = -2147482354 +MSG_RTC_EXTERNAL_TAMPER_DETECTED = 1 +LUNA_RET_WRAPPING_ERROR = -2147483385 +LUNA_RET_INVALID_MODULUS_SIZE = -2147483387 +LUNA_HIFN_UNKNOWN_ALGORITHM = -2147482353 +LUNA_RET_INVALID_CERTIFICATE_VERSION = -2147483388 +LUNA_INVALID_PACKET_LAYOUT = -2147482352 MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC = 0 +LUNA_RET_INVALID_CERTIFICATE_TYPE = -2147483389 +LUNA_RET_INVALID_CERTIFICATE_DATA = -2147483390 LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM = -2147482351 -LUNA_RET_HIFN_DMA_TIMED_OUT = -2147482354 -RC_OBJECT_ALREADY_EXISTS = -1073740788 -LUNA_RET_HIFN_DMA_NOT_IDLE = -2147482355 -RC_SEMAPHORE_ERROR = -1073740787 -LUNA2_RET_HIFN_RESET_ERROR = -2147482356 -RC_ENDOFLIST = -1073740786 -RC_NOT_PARTITION_BACKUP_TOKEN = -1073740782 -MSG_RTC_BATTERY_LOW = 18 -LUNA_RET_HIFN6500_RNG_TIMEOUT = 3147783 -LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED = -2147482622 -RC_SOCKET_BAD_FD = -1073740536 -LUNA_RET_MM_FATAL_ERROR = 3211270 -RC_MANUFACTURING_SERIAL_NUMBER_INVALID = -1073741054 -LUNA_RET_RNG_SELF_TEST_FAILURE = 3145744 -LUNA_RET_HIFN6500_DATA_LINES_BROKEN = 3147779 -MSG_TVK_TIMESTAMP_UPDATE_FAILED = 38 -LUNA_RET_INVALID_ACCESS_LEVEL = -2147483376 -MSG_RTC_CANT_CLEAN_POWER_LOSS = 11 -LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID = -2147482358 -RC_ASSIGNING_SAME_VALUE = -1073740785 -LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID = -2147482359 -LUNA_RET_HIFN_INVALID_ENCRYPT_MODE = -2147482360 -RC_GROUP_NAME_INVALID = -1073740784 -LUNA_RET_SM_UNKNOWN_SESSION_TYPE = -2147482618 -RC_CLIENT_DISCONNECTED = -1073740539 -LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED = -2147482617 -LUNA_RET_HA_USER_NOT_INITIALIZED = -2147481343 -RC_SERVER_DISCONNECTED = -1073740540 -LUNA_RET_SM_CONTEXT_NOT_ALLOCATED = -2147482616 -LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW = -2147482615 -RC_CLIENT_MESSAGE_ERROR = -1073740541 -LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE = -2147482614 -RC_SOCKET_READ_ERROR = -1073740542 -LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE = -2147482613 -LUNA_RET_HIFN_NOT_PRESENT = -2147482368 -RC_SOCKET_WRITE_ERROR = -1073740543 -LUNA_RET_HIFN_SOURCE_COUNT_INVALID = -2147482367 -LUNA_RET_ECC_RESULT_AT_INF = -2147482106 -RC_SOCKET_ERROR = -1073740544 -LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL = -2147481341 -LUNA_RET_HIFN_INVALID_MAC_ALGORITHM = -2147482365 -RC_SIM_NOT_SUPPORTED = -1073740781 -LUNA_RET_HIFN_INVALID_MAC_MODE = -2147482364 -LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID = -2147482363 -LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID = -2147482362 -RC_NOT_HSM_BACKUP_TOKEN = -1073740783 -LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM = -2147482361 -LUNA_RET_RC4_SELF_TEST_FAILURE = 3145741 -MSG_ZEROIZING_AFTER_NO_SECURE_DATA = 49 -LUNA_RET_ECC_BUFFER_OVERFLOW = -2147482110 -LUNA_RET_ECC_NOT_SUPPORTED = -2147482111 -MSG_RESYNC = 46 -LastFirmwareCode = -1073741825 -LUNA_RET_ISES_CMD_PARAMETER_INVALID = 3147909 -MSG_GENERATING_NEW_TVK_PASSED = 42 -LUNA_RET_LOG_FILE_WRITE_ERROR = -2147480319 -RC_SSL_GET_CERTIFICATE_ERROR = -1073740023 -RC_TOKEN_NOT_PRESENT = -1073741564 -MSG_LAST = 54 +LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED = -2147483391 +LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS = -2147483392 +LUNA_RET_INVALID_FUF_VERSION = -2147483632 +LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID = -2147482349 +LUNA_RET_INVALID_FUF_HEADER = -2147483633 +LUNA_RET_N_TOO_SMALL = -2147483135 +LUNA_RET_HIFN_INVALID_PAD_ALGORITHM = -2147482348 +LUNA_RET_INVALID_FUF_TARGET = -2147483634 +LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID = -2147482347 +LUNA_RET_DEVICE_TIMEOUT = -2147483636 +LUNA_RET_HIFN_END_MARKER_NOT_PRESENT = -2147482346 +LUNA_RET_SECURITY_PARAMETER_MISSING = -2147483637 +LUNA_RET_CONTAINER_IS_DISABLED = -2147483638 +LUNA_RET_HIFN_DESTINATION_OVERRUN = -2147482345 +LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO = -2147482344 +LUNA_RET_TOO_MANY_CONTAINERS = -2147483640 +LUNA_RET_NOT_FOUND = -2147483641 +LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO = -2147482343 +LUNA_RET_AGAIN = -2147483642 +LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO = -2147482342 +LUNA_RET_INVALID_PADDING_TYPE = -2147483646 +LUNA_RET_CONTAINER_HANDLE_INVALID = -2147483647 +LUNA_RET_HIFN_DMA_INVALID_REVISION = -2147482320 +LUNA_RET_ERROR = -2147483648 +LUNA_RET_MTK_ZEROIZED = -2147482319 +LUNA_RET_CERT_VERSION_NOT_SUPPORTED = 3146496 +LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT = 18153472 +LUNA_RET_MTK_STATE_INVALID = -2147482318 +LUNA_RET_MTK_SPLIT_INVALID = -2147482317 +LUNA_RET_WRAPPING_KEY_HANDLE_INVALID = 18022400 +LUNA_RET_WRAPPED_KEY_LEN_RANGE = 17956864 +LUNA_RET_INVALID_IP_PACKET = -2147482112 +LUNA_RET_WRAPPED_KEY_INVALID = 17825792 +LUNA_RET_INVALID_BOARD_TYPE = -2147481856 +LUNA_RET_USER_TYPE_INVALID = 16973824 +LUNA_RET_HIFN6500_NOT_PRESENT = 3147777 LUNA_RET_SM_NOT_LOGGED_IN = 16842753 -LUNA_RET_USER_PIN_NOT_INITIALIZED = 16908288 +LUNA_RET_HIFN6500_RESET_TIMEOUT = 3147778 LUNA_RET_USER_NOT_LOGGED_IN = 16842752 -LUNA_RET_USER_TYPE_INVALID = 16973824 -LUNA_RET_RSA_SELF_TEST_FAILURE = 3145739 -LUNA_RET_WRAPPED_KEY_INVALID = 17825792 -RC_DATA_CORRUPTED = -1073740799 LUNA_RET_SM_SESSION_READ_ONLY_EXISTS = 11993088 -LUNA_RET_WRAPPED_KEY_LEN_RANGE = 17956864 -LUNA_RET_WRAPPING_KEY_HANDLE_INVALID = 18022400 +LUNA_RET_HIFN6500_DATA_LINES_BROKEN = 3147779 LUNA_RET_SM_OTHER_USER_LOGGED_IN = 16777217 -LUNA_RET_WRAPPING_KEY_SIZE_RANGE = 18087936 -RC_FUNCTION_NOT_SUPPORTED = -1073741563 -LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT = 18153472 +LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN = 3147780 LUNA_RET_USER_ALREADY_LOGGED_IN = 16777216 -LUNA_RET_CERT_VERSION_NOT_SUPPORTED = 3146496 -LUNA_RET_ERROR = -2147483648 LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT = 15859712 -LUNA_RET_CONTAINER_HANDLE_INVALID = -2147483647 -LUNA_RET_INVALID_PADDING_TYPE = -2147483646 LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE = 15794176 -LUNA_RET_AGAIN = -2147483642 -LUNA_RET_NOT_FOUND = -2147483641 +LUNA_RET_HIFN6500_RNG_FAILED = 3147782 LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID = 15728640 -LUNA_RET_TOO_MANY_CONTAINERS = -2147483640 -LUNA_RET_CONTAINER_LOCKED = -2147483639 LUNA_RET_SIGNATURE_LEN_RANGE = 12648448 -LUNA_RET_CONTAINER_IS_DISABLED = -2147483638 -LUNA_RET_SECURITY_PARAMETER_MISSING = -2147483637 LUNA_RET_SIGNATURE_INVALID = 12582912 -RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR = -1073740026 -LUNA_RET_NO_OFFBOARD_STORAGE = 5505025 +LUNA_RET_HIFN6500_RNG_UNDERFLOW = 3147784 LUNA_RET_SM_SESSION_HANDLE_INVALID = 11730944 -LUNA_RET_OBJECT_DELETED = -2147483635 LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS = 11665408 -RC_SESSION_SCRIPT_EXISTS = -1073739519 +LUNA_RET_HIFN6500_ALU_TIMEOUT = 3147785 LUNA_RET_SM_PIN_EXPIRED = 10682368 -LUNA_RET_INVALID_FUF_TARGET = -2147483634 +LUNA_RET_HIFN6500_INVALID_PARAMETERS = 3147786 LUNA_RET_UM_PIN_LEN_RANGE = 10616832 -LUNA_RET_INVALID_FUF_HEADER = -2147483633 LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED = 10485762 +LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH = 3147787 LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED = 10485761 -LUNA_RET_FUNCTION_NOT_SUPPORTED = 5505024 -LUNA_RET_INVALID_FUF_VERSION = -2147483632 +LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS = 3147788 LUNA_RET_UM_PIN_INCORRECT = 10485760 -LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS = -2147483392 LUNA_RET_OPERATION_NOT_INITIALIZED = 9502720 -RC_PORT_INVALID = -1073739520 +LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS = 3147789 LUNA_RET_OPERATION_ACTIVE = 9437184 -RC_CHALLENGE_BUFFER_SIZE = -1073741561 -LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED = -2147483391 +LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT = 3147790 LUNA_RET_MECHANISM_PARAM_INVALID = 7405568 -LUNA_RET_INVALID_CERTIFICATE_DATA = -2147483390 LUNA_RET_MECHANISM_INVALID = 7340032 +LUNA_RET_TEST_VS_BSAFE_FAILED = 3147808 LUNA_RET_KEY_HANDLE_INVALID = 6291456 -LUNA_RET_INVALID_CERTIFICATE_TYPE = -2147483389 +LUNA_RET_SFNT3120_ERROR = 3147809 LUNA_RET_FUNCTION_CANCELED = 5242880 -LUNA_RET_INVALID_CERTIFICATE_VERSION = -2147483388 LUNA_RET_ENCRYPTED_DATA_LEN_RANGE = 4259840 -RC_CERT_TYPE_INVALID = -1073739776 +LUNA_RET_SFNT3120_SELFTEST_FAILED = 3147810 LUNA_RET_ENCRYPTED_DATA_INVALID = 4194304 -LUNA_RET_INVALID_MODULUS_SIZE = -2147483387 +LUNA_RET_SFNT3120_CRC = 3147811 LUNA_RET_SM_MEMORY_ALLOCATION_ERROR = 3211523 -LUNA_RET_WRAPPING_ERROR = -2147483385 LUNA_RET_SM_SESSION_REALLOC_ERROR = 3211522 -LUNA_RET_TEST_VS_BSAFE_FAILED = 3147808 -LUNA_RET_SPLIT_DATA_INVALID = -2147483128 -RC_VERSION_INVALID = -1073741559 -MSG_ZEROIZING = 52 -MSG_RTC_MSG_NVRAM_READ_FAILED = 24 +LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT = 3147812 +LUNA_RET_SM_ACCESS_REALLOC_ERROR = 3211521 LUNA_RET_TOKEN_LOCKED_OUT_STC = 3145994 -RC_SSL_FAILED_HANDSHAKE = -1073740015 +LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST = 3145993 +LUNA_RET_ISES_INIT_FAILED = 3147905 LUNA_RET_TOKEN_LOCKED_OUT_CCM = 3145992 -LUNA_RET_TSN_MISMATCH = -2147483382 +LUNA_RET_ISES_LNAU_TEST_FAILED = 3147906 LUNA_RET_TOKEN_LOCKED_OUT_OH = 3145991 +LUNA_RET_USER_PIN_NOT_INITIALIZED = 16908288 LUNA_RET_TOKEN_LOCKED_OUT_PM = 3145990 +LUNA_RET_ISES_RNG_TEST_FAILED = 3147907 LUNA_RET_TOKEN_LOCKED_OUT_CA = 3145989 -LUNA_RET_TWC_PARAMETER_MISSING = -2147483380 -LUNA_RET_TOKEN_LOCKED_OUT_RN = 3145988 -LUNA_RET_TUK_PARAMETER_MISSING = -2147483379 +LUNA_RET_ISES_CMD_FAILED = 3147908 LUNA_RET_TOKEN_LOCKED_OUT_SM = 3145987 -RC_SSL_SYSCALL_ERROR = -1073740016 +LUNA_RET_ISES_CMD_PARAMETER_INVALID = 3147909 LUNA_RET_TOKEN_LOCKED_OUT_UM = 3145986 -LUNA_RET_CPK_PARAMETER_MISSING = -2147483378 -LUNA_RET_TOKEN_LOCKED_OUT_MM = 3145985 -LUNA_RET_MASKING_NOT_SUPPORTED = -2147483377 +LUNA_RET_ISES_TEST_VS_BSAFE_FAILED = 3147910 +LUNA_RET_TOKEN_LOCKED_OUT_CL = 3145984 LUNA_RET_RIPEMD160_SELF_TEST_FAILURE = 3145780 LUNA_RET_INCOMPATIBLE = 3145764 -LUNA_RET_MAC_MISSING = -2147483375 LUNA_RET_SELF_TEST_FAILURE = 3145763 -RC_SSL_WANT_X509_LOOKUP_ERROR = -1073740017 +LUNA_RET_ECC_BUFFER_OVERFLOW = -2147482110 +RC_SEMAPHORE_ERROR = -1073740787 LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE = 3145762 -LUNA_RET_DAC_POLICY_PID_MISMATCH = -2147483374 -LUNA_RET_DAC_MISSING = -2147483373 +LUNA_RET_ECC_POINT_INVALID = -2147482109 +LUNA_RET_RETRY = 3145761 +LUNA_RET_FLAGS_INVALID = 262144 LUNA_RET_NOT_READY = 3145760 +LUNA_RET_ECC_SELF_TEST_FAILURE = -2147482108 LUNA_RET_TIMEOUT = 3145759 -LUNA_RET_BAD_DAC = -2147483372 +LUNA_RET_ECC_UNKNOWN_CURVE = -2147482107 LUNA_RET_COUNTER_WRAPAROUND = 3145758 -LUNA_RET_SSK_MISSING = -2147483371 LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL = 3145757 LUNA_RET_KCDSA_SELF_TEST_FAILURE = 3145756 -LUNA_RET_BAD_MAC = -2147483370 LUNA_RET_KCDSA_PARAM_GEN_FAILURE = 3145755 +LUNA_RET_HA_NOT_SUPPORTED = -2147481344 LUNA_RET_HAS160_SELF_TEST_FAILURE = 3145754 LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE = 3145753 -LUNA_RET_BAD_DAK = -2147483368 +LUNA_RET_HA_USER_NOT_INITIALIZED = -2147481343 LUNA_RET_AES_SELF_TEST_FAILURE = 3145752 -LUNA_RET_HOK_MISSING = -2147483367 LUNA_RET_SEED_SELF_TEST_FAILURE = 3145751 -MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK = 41 -MSG_RTC_MSG_NVRAM_ZAPPING_FAILED = 3 -RC_SSL_WANT_READ_ERROR = -1073740019 +LUNA_RET_HSM_STORAGE_FULL = -2147481342 LUNA_RET_DSA_SELF_TEST_FAILURE = 3145750 -LUNA_RET_CITS_DAK_MISSING = -2147483366 LUNA_RET_DSA_PARAM_GEN_FAILURE = 3145749 -LUNA_RET_SIM_AUTHORIZATION_FAILED = -2147483365 -LUNA_RET_SM_UNKNOWN_TOSM_STATE = 3145748 +LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL = -2147481341 LUNA_RET_SM_TSV_MISSING = 3145747 -LUNA_RET_SIM_VERSION_UNSUPPORTED = -2147483364 LUNA_RET_UM_TSN_MISSING = 3145746 -LUNA_RET_SIM_CORRUPT_DATA = -2147483363 LUNA_RET_SM_UNKNOWN_COMMAND = 3145745 -RC_SSL_GET_PEER_CERT_ERROR = -1073740020 -LUNA_RET_ECC_MIC_MISSING = -2147483362 +LUNA_RET_RNG_SELF_TEST_FAILURE = 3145744 LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD = 3145743 -LUNA_RET_ECC_HOK_MISSING = -2147483361 +LUNA_RET_RM_ELEMENT_VALUE_INVALID = 2099712 LUNA_RET_RC5_SELF_TEST_FAILURE = 3145742 -LUNA_RET_ECC_HOC_MISSING = -2147483360 +LUNA_RET_RC4_SELF_TEST_FAILURE = 3145741 LUNA_RET_RC2_SELF_TEST_FAILURE = 3145740 -LUNA_RET_ECC_DAK_MISSING = -2147483359 -RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR = -1073740021 +LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED = 3147781 +RC_STC_RSA_SIGN_ERROR = -1073700841 +LUNA_RET_LOG_FILE_NOT_OPEN = -2147480320 +LUNA_RET_HIFN6500_RNG_TIMEOUT = 3147783 +RC_CLIENT_MESSAGE_ERROR = -1073740541 +LUNA_RET_CB_NO_MEMORY = -2147481085 +LUNA_RET_CCM_UPDATE_DENIED = -2147482875 +LUNA_RET_RSA_SELF_TEST_FAILURE = 3145739 +LUNA_RET_RM_ELEMENT_ID_INVALID = 2099713 LUNA_RET_SHA_SELF_TEST_FAILURE = 3145738 -MSG_RTC_EXTERNAL_TAMPER_DETECTED = 1 -LUNA_RET_ECC_DAC_MISSING = -2147483358 -LUNA_RET_ECC_POINT_INVALID = -2147482109 -LUNA_RET_MD5_SELF_TEST_FAILURE = 3145737 -LUNA_RET_ROOT_CERT_MISSING = -2147483357 LUNA_RET_MD2_SELF_TEST_FAILURE = 3145736 -LUNA_RET_CAST5_SELF_TEST_FAILURE = 3145735 -LUNA_RET_HOC_MISSING = -2147483356 +LUNA_RET_RM_NO_MEMORY = 3213826 LUNA_RET_CAST3_SELF_TEST_FAILURE = 3145734 -LUNA_RET_INVALID_CERTIFICATE_FUNCTION = -2147483355 LUNA_RET_CAST_SELF_TEST_FAILURE = 3145733 -RC_SSL_INVALID_CERT_STRUCTURE = -1073740022 LUNA_RET_DES_SELF_TEST_FAILURE = 3145732 -LUNA_RET_SIM_AUTHFORM_INVALID = 2097438 LUNA_RET_RNG_ERROR = 3145731 -LUNA_RET_N_TOO_LARGE = -2147483136 -LUNA_RET_TOKEN_LOCKED_OUT = 3145730 -LUNA_RET_UNKNOWN_COMMAND = 3145729 -LUNA_RET_N_TOO_SMALL = -2147483135 LUNA_RET_DEVICE_ERROR = 3145728 -LUNA_RET_M_TOO_LARGE = -2147483134 -LUNA_RET_GENERAL_ERROR = 327680 +LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE = 2099716 LUNA_RET_DATA_LEN_RANGE = 2162688 -LUNA_RET_M_TOO_SMALL = -2147483133 LUNA_RET_410_BUFFER_TOO_SMALL = 2097174 -LUNA_RET_WEIGHT_TOO_LARGE = -2147483132 LUNA_RET_BUFFER_TOO_SMALL = 22020096 +LUNA_RET_ISES_ERROR = 3147904 LUNA_RET_CL_COMMAND_NON_BACKUP = 5505026 -LUNA_RET_WEIGHT_TOO_SMALL = -2147483131 -LUNA_RET_TOTAL_WEIGHT_INVALID = -2147483130 -RC_SSL_LOAD_CLIENT_CERT_ERROR = -1073740024 +LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE = 2099717 +LUNA_RET_NO_OFFBOARD_STORAGE = 5505025 +LUNA_RET_FUNCTION_NOT_SUPPORTED = 5505024 LUNA_RET_NO_RNG_SEED = 2097173 -LUNA_RET_MISSING_SPLITS = -2147483129 LUNA_RET_SM_DATA_INVALID = 2097154 +LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL = 68102 LUNA_RET_TPV_INVALID = 2097153 LUNA_RET_DATA_INVALID = 2097152 -LUNA_RET_SPLIT_ID_INVALID = -2147483127 LUNA_RET_INVALID_ENTRY_TYPE = 458753 -LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE = -2147483126 LUNA_RET_ARGUMENTS_BAD = 458752 -RC_SSL_CREATE_SSL_ERROR = -1073740025 LUNA_RET_KEY_NOT_UNWRAPPABLE = 6881281 -LUNA_RET_M_OF_N_ACTIVATION_REQUIRED = -2147483125 LUNA_RET_KEY_NOT_WRAPPABLE = 6881280 -LUNA_RET_TOO_MANY_WEIGHTS = -2147483122 -LUNA_RET_KEY_EXTRACTABLE = 6946817 -LUNA_RET_MISSING_WEIGHT_VALUE = -2147483121 -LUNA_RET_KEY_UNEXTRACTABLE = 6946816 -LUNA_RET_MISSING_VALUE_FOR_M = -2147483120 -LUNA_RET_KEY_PARITY = 6488066 -LUNA_RET_KEY_INVALID_FOR_OPERATION = 6488065 -LUNA_RET_MISSING_VALUE_FOR_N = -2147483119 -LUNA_RET_MISSING_NUMBER_OF_VECTORS = -2147483118 -LUNA_RET_SM_KEY_SIZE_ERROR = 6422529 -LUNA_RET_KEY_SIZE_RANGE = 6422528 LUNA_RET_KEY_SENSITIVE = 6356992 -RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR = -1073740027 -LUNA_RET_VECTOR_TOO_LARGE = -2147483116 -LUNA_RET_SM_BAD_CONTEXT_NUMBER = -2147482619 -MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK = 40 -LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED = 13697048 -LUNA_RET_VECTOR_TOO_SMALL = -2147483115 -LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL = 6815745 -LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 -LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631510 -RC_SSL_LOAD_SERVER_CERT_ERROR = -1073740028 -LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE = 1245205 -LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 -LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631508 -LUNA_RET_M_OF_N_PARAMETER_EXIST = -2147483112 -LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY = 13697042 -LUNA_RET_ATTRIBUTE_NOT_FOUND = 1179664 -LUNA_RET_VECTOR_OF_DIFFERENT_SET = -2147483110 -LUNA_RET_MAX_OBJECT_COUNT = 8519681 -LUNA_RET_OBJECT_HANDLE_INVALID = 8519680 -LUNA_RET_ATTRIBUTE_SENSITIVE = 1114112 -LUNA_RET_VECTOR_DUPLICATE = -2147483109 -LUNA_RET_ATTRIBUTE_READ_ONLY = 1048576 -LUNA_RET_ATTRIBUTE_VALUE_INVALID = 1245184 -LUNA_RET_VECTOR_TYPE_INVALID = -2147483108 -LUNA_RET_TEMPLATE_INCONSISTENT = 13697024 -LUNA_RET_TEMPLATE_INCOMPLETE = 13631488 -RC_SSL_CIPHER_LIST_ERROR = -1073740030 -LUNA_RET_VECTOR_VERSION_INVALID = -2147483111 -LUNA_RET_MISSING_COMMAND_PARAMETER = -2147483107 -LUNA_RET_MM_INVALID_USAGE = 3211268 -LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE = 3211267 -LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED = -2147483106 -LUNA_RET_MM_USAGE_ALREADY_SET = 3211266 -LUNA_RET_MM_INVALID_HANDLE = 3211265 -LUNA_RET_MM_NOT_ENOUGH_MEMORY = 3211264 -LUNA_RET_M_OF_N_IS_NOT_REQUIRED = -2147483105 -LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE = 3146246 -LUNA_RET_CL_COMMAND_MALFORMED = 3146245 +LUNA_RET_SM_KEY_SIZE_ERROR = 6422529 +LUNA_RET_KEY_TYPE_INCONSISTENT = 6488064 +LUNA_RET_KEY_INVALID_FOR_OPERATION = 6488065 +LUNA_RET_KEY_UNEXTRACTABLE = 6946816 +LUNA_RET_LICENSE_ID_UNKNOWN = 2099720 +LUNA_RET_KEY_EXTRACTABLE = 6946817 +LUNA_RET_KEY_INDIGESTIBLE = 6750208 +RC_ASSIGNING_SAME_VALUE = -1073740785 +RC_GROUP_NAME_INVALID = -1073740784 +RC_ENDOFLIST = -1073740786 +RC_NOT_HSM_BACKUP_TOKEN = -1073740783 +RC_NOT_PARTITION_BACKUP_TOKEN = -1073740782 +RC_SIM_NOT_SUPPORTED = -1073740781 +RC_SOCKET_ERROR = -1073740544 +RC_OBJECT_ALREADY_EXISTS = -1073740788 +RC_SOCKET_WRITE_ERROR = -1073740543 +RC_SOCKET_READ_ERROR = -1073740542 +RC_INVALID_INDEX = -1073740789 +RC_OBJECT_NOT_IN_LIST = -1073740790 +RC_CLIENT_DISCONNECTED = -1073740539 +RC_CACHE_NOT_MAPPED = -1073740791 +RC_CACHE_DIRTY = -1073740792 +RC_SOCKET_BAD_FD = -1073740536 +RC_LISTEN_SOCKET_INVALID = -1073740793 +RC_SOCKET_ADDRESS_INVALID = -1073740794 +RC_OBJECT_ID_INVALID = -1073740795 +RC_INVALID_CERT_HOST = -1073740534 +RC_FILE_ERROR = -1073740796 +RC_FILE_READ_ONLY = -1073740797 +RC_FILE_NAME_INVALID = -1073740798 +RC_INVALID_ENUM_OPTION = -1073740287 +RC_SSL_ERROR = -1073740032 +RC_RESET_FAILED = -1073741052 RC_SSL_CTX_ERROR = -1073740031 +LUNA_RET_OK = 0 +RC_MANUFACTURING_SERIAL_NUMBER_INVALID = -1073741054 +RC_SSL_CIPHER_LIST_ERROR = -1073740030 +LUNA_RET_FORMER_INVALID_ENTRY_TYPE = 3146032 +LUNA_RET_SP_TX_ERROR = 3146033 +RC_MANUFACTURING_TOKEN_NOT_PRESENT = -1073741055 +RC_SSL_CERT_VERIFICATION_LOCATION_ERROR = -1073740029 +LUNA_RET_PED_ID_INVALID = 3146048 +RC_MANUFACTURING_NO_CONFIG_AVAILABLE = -1073741056 +LUNA_RET_PED_UNPLUGGED = 3146050 +RC_DER_CLASS_INVALID = -1073741312 +RC_SSL_LOAD_SERVER_CERT_ERROR = -1073740028 +LUNA_RET_ECC_RESULT_AT_INF = -2147482106 +RC_USER_NAME_IN_USE = -1073741557 +RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR = -1073740027 +RC_KEY_NEEDED = -1073741558 +LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL = 3146053 +RC_VERSION_INVALID = -1073741559 +RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR = -1073740026 +RC_PIN_LOCKED = -1073741560 +RC_CHALLENGE_BUFFER_SIZE = -1073741561 +LUNA_RET_PED_DEK_INVALID = 3146054 +RC_NON_CRYPTOKI_ELEMENT_CLONE = -1073741562 +RC_SSL_LOAD_CLIENT_CERT_ERROR = -1073740024 +RC_FUNCTION_NOT_SUPPORTED = -1073741563 +RC_TOKEN_NOT_PRESENT = -1073741564 +LUNA_RET_POLICY_NOT_FOUND = 2099730 +RC_STC_UNEXPECTED_DH_DATA_SIZE = -1073700837 +RC_PIN_INVALID = -1073741565 +RC_SSL_INVALID_CERT_STRUCTURE = -1073740022 +LUNA_RET_PED_CLIENT_NOT_RUNNING = 3146055 +RC_DATA_INVALID = -1073741566 +RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR = -1073740021 +LUNA_RET_CL_QUEUE_LOCATION_ERROR = 3146241 +LUNA_RET_CL_ALIGNMENT_ERROR = 3146240 +RC_STC_RESPONSE_UNEXPECTED_KEY = -1073700839 LUNA_RET_CL_NO_TRANSMISSION = 3146244 -LUNA_RET_M_OF_N_IS_NOT_INITIALZED = -2147483104 +LUNA_RET_CL_COMMAND_MALFORMED = 3146245 +LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE = 3146246 +LUNA_RET_RM_CONFIG_ILLEGAL = 2099728 +LUNA_RET_MM_NOT_ENOUGH_MEMORY = 3211264 +LUNA_RET_BAD_SN = 2099729 LUNA_RET_CL_TRANSMISSION_ERROR = 3146243 LUNA_RET_CL_QUEUE_OVERLAP_ERROR = 3146242 -LUNA_RET_CL_QUEUE_LOCATION_ERROR = 3146241 -LUNA_RET_M_OF_N_SECRET_INVALID = -2147483103 -LUNA_RET_CL_ALIGNMENT_ERROR = 3146240 -LUNA_RET_PED_CLIENT_NOT_RUNNING = 3146055 -LUNA_RET_PED_DEK_INVALID = 3146054 -LUNA_RET_CCM_NOT_PRESENT = -2147482880 -LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL = 3146053 -LUNA_RET_PED_ERROR = 3146052 -RC_SSL_ERROR = -1073740032 -LUNA_RET_CCM_NOT_SUPPORTED = -2147482879 -LUNA_RET_PED_UNSUPPORTED_PROTOCOL = 3146049 -LUNA_RET_PED_ID_INVALID = 3146048 -LUNA_RET_SP_RX_ERROR = 3146034 -LUNA_RET_CCM_UNREMOVABLE = -2147482878 -LUNA_RET_SP_TX_ERROR = 3146033 -LUNA_RET_PED_UNPLUGGED = 3146050 -LUNA_RET_FORMER_INVALID_ENTRY_TYPE = 3146032 -LUNA_RET_TOKEN_NOT_PRESENT = 14680064 -LUNA_RET_CCM_CERT_INVALID = -2147482877 -LUNA_RET_FLAGS_INVALID = 262144 -LUNA_RET_CANCEL = 65536 -RC_INVALID_ENUM_OPTION = -1073740287 -RC_OK = 0 -MSG_RTC_CONFIGURATION_CORRUPTED = 22 -LUNA_RET_KEY_INDIGESTIBLE = 6750208 -MSG_RTC_ZEROIZED_ON_POWER_LOSS = 20 -MSG_RTC_TAMPER_CIRCUITS_RE_ARMED = 16 -LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN = 3147780 -LUNA_RET_KEY_TYPE_INCONSISTENT = 6488064 -LUNA_RET_HIFN6500_RESET_TIMEOUT = 3147778 -RC_RESET_FAILED = -1073741052 -LUNA_RET_MISSING_VECTOR = -2147483117 -RC_TOKEN_STATE_INVALID = -1073740800 -LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION = 1048601 -LUNA_RET_CB_TIMEOUT = -2147481084 -MSG_RTC_CANT_ACCESS = 6 -LUNA_RET_MTK_ZEROIZED = -2147482319 -RC_FILE_READ_ONLY = -1073740797 -LUNA_RET_SM_BAD_ACCESS_HANDLE = -2147482620 -MSG_RTC_CANT_GET_TAMPER_TIMER = 2 -LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE = 1245203 -LUNA_RET_OK = 0 -LUNA_RET_CCM_SIGN_INVALID = -2147482876 -LUNA_RET_CB_ID_INVALID = -2147481055 +RC_SSL_WANT_READ_ERROR = -1073740019 +LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE = 3211267 +LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE = 2099727 +LUNA_RET_MM_INVALID_USAGE = 3211268 +LUNA_RET_MM_ITERATOR_PAST_END = 3211269 +LUNA_RET_MM_FATAL_ERROR = 3211270 +LUNA_RET_TEMPLATE_INCOMPLETE = 13631488 +LUNA_RET_BAD_FW_VERSION = 2099726 +LUNA_RET_TEMPLATE_INCONSISTENT = 13697024 +LUNA_RET_ATTRIBUTE_TYPE_INVALID = 1179648 +RC_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE = -1073700838 +LUNA_RET_MM_USAGE_ALREADY_SET = 3211266 +LUNA_RET_MM_INVALID_HANDLE = 3211265 +LUNA_RET_ATTRIBUTE_VALUE_INVALID = 1245184 +RC_SLOT_ID_INVALID = -1073741567 +RC_CANCEL = -1073741568 +RC_ARGUMENTS_BAD = -1073741817 +RC_BUFFER_TOO_SMALL = -1073741818 +RC_OPERATION_WOULD_BLOCK = -1073741819 +RC_SSL_WANT_WRITE_ERROR = -1073740018 +RC_UNEXPECTED = -1073741820 +RC_SSL_GET_PEER_CERT_ERROR = -1073740020 +RC_SSL_WANT_X509_LOOKUP_ERROR = -1073740017 +RC_POINTER_INVALID = -1073741821 +RC_GENERAL_ERROR = -1073741822 +RC_SSL_SYSCALL_ERROR = -1073740016 +RC_MEMORY_ALLOCATION = -1073741823 +RC_SSL_FAILED_HANDSHAKE = -1073740015 +RC_RC_ERROR = -1073741824 +RC_OK = 0 +RC_CERT_TYPE_INVALID = -1073739776 +LUNA_RET_STC_ACTIVATE_RESP_GEN_FAIL = -2147480052 +LUNA_RET_STC_ACTIVATE_MACTAG_V_GEN_FAIL = -2147480053 +RC_PORT_INVALID = -1073739520 +LUNA_RET_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL = -2147480054 +RC_SESSION_SCRIPT_EXISTS = -1073739519 +LUNA_RET_STC_OPEN_RESP_GEN_FAIL = -2147480055 +LUNA_RET_STC_OPEN_KEY_MATERIAL_GEN_FAIL = -2147480056 +RC_PARTITION_LOCKED = -1073737728 +LUNA_RET_STC_OPEN_DHNIST_PUBKEY_ERROR = -2147480057 +RC_PARTITION_NOT_ACTIVATED = -1073737727 +LUNA_RET_STC_OPEN_CIPHER_MISMATCH = -2147480058 +LUNA_RET_STC_NO_CHANNEL = -2147480059 +RC_FAILED_TO_CREATE_THREAD = -1073733632 +LUNA_RET_STC_SEQUENCE_NUM_INVALID = -2147480060 +RC_CALLBACK_ERROR = -1073733631 +LUNA_RET_STC_CONTAINER_INVALID = -2147480061 +LUNA_RET_STC_SESSION_INVALID = -2147480062 +RC_UNKNOWN_CALLBACK_COMMAND = -1073733630 +LUNA_RET_STC_CLIENT_HANDLE_INVALID = -2147480063 +RC_SHUTTING_DOWN = -1073733629 +LUNA_RET_STC_NOT_ENABLED = -2147480064 +LUNA_RET_STC_CHANNEL_REALLOC_ERROR = 3211264 +RC_REMOTE_SIDE_DISCONNECTED = -1073733628 +LUNA_RET_TIME_NOT_INITIALIZED = -2147480308 +RC_SOCKET_CLOSED = -1073733627 +LUNA_RET_USER_ALREADY_ACTIVATED = -2147480309 +LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD = -2147480310 +RC_INVALID_COMMAND = -1073733626 +LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS = -2147480311 RC_NO_BUFFER = -1073740288 -LUNA_RET_CB_REMOTE_ABORT = -2147481054 -LUNA_RET_CCM_FWUPDATE_DENIED = -2147482874 -RC_INVALID_CERT_HOST = -1073740534 -LUNA_RET_CCM_TOO_LARGE = 2162689 +RC_UNKNOWN_COMMAND = -1073733625 +LUNA_RET_BAD_PPID = 2099725 +LUNA_RET_ATTRIBUTE_SENSITIVE = 1114112 +LUNA_RET_ATTRIBUTE_READ_ONLY = 1048576 +MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET = 30 +LUNA_RET_MAX_OBJECT_COUNT = 8519681 +LUNA_RET_ATTRIBUTE_NOT_FOUND = 1179664 +LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE = 68108 LUNA_RET_CAN_NOT_CREATE_SECRET_KEY = 13697041 -RC_SSL_CERT_VERIFICATION_LOCATION_ERROR = -1073740029 -LUNA_RET_CB_REMOTE_ABANDONED = -2147481052 -LUNA_RET_SM_ACCESS_ID_INVALID = -2147482624 -RC_HOST_RESOLUTION_ERROR = -1073740535 +LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY = 13697042 +LUNA_RET_OBJECT_HANDLE_INVALID = 8519680 +LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE = 1245203 +LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631508 +LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE = 1245205 +LUNA_RET_OPERATION_RESTRICTED = 68107 +LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631510 +LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL = 6815745 +LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED = 13697048 +LUNA_RET_RM_POLICY_WRITE_RESTRICTED = 68106 +LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION = 1048601 +RC_SOCKET_ADDRESS_IN_USE = -1073740537 +LUNA_RET_LOG_RESYNC_NEEDED = -2147480312 +LUNA_RET_LOG_AUDIT_NOT_INITIALIZED = -2147480313 +RC_UNKNOWN_COMMAND_VERSION = -1073733624 +LUNA_RET_LOG_BAD_TIME = -2147480314 +RC_FILE_LOCK_FAILED = -1073733623 +LUNA_RET_LOG_BAD_RECORD_HMAC = -2147480315 +LUNA_RET_LOG_NO_KCV = -2147480316 +RC_CMD_BLOCKED_REMOTE_PED_TUNNEL = -1073733622 +LUNA_RET_LOG_FULL = -2147480317 +RC_FILE_LOCK_ERROR = -1073733616 +LUNA_RET_LOG_BAD_FILE_NAME = -2147480318 +LUNA_RET_LOG_FILE_WRITE_ERROR = -2147480319 +RC_FAILED_TO_CREATE_PROCESS = -1073733615 +RC_USB_PED_NOT_FOUND = -1073733614 +LUNA_RET_STATE_UNSAVEABLE = 25165824 +LUNA_RET_SAVED_STATE_INVALID = 23068672 +RC_USB_PED_NOT_RESPONDING = -1073733613 +LUNA_RET_CB_PROT_DATA_INVALID = -2147481047 +RC_USB_PED_OPERATION_CANCELLED = -1073733612 +LUNA_RET_CB_SYNC_ERROR = -2147481048 +LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE = -2147481049 +RC_USB_PED_TOO_MANY_CONNECTED = -1073733611 LUNA_RET_CB_MUST_WRITE = -2147481050 -LUNA_RET_SM_ACCESS_ALREADY_EXISTS = -2147482623 +RC_USB_PED_OUT_OF_SYNC = -1073733610 +LUNA_RET_CB_MUST_READ = -2147481051 +LUNA_RET_CB_REMOTE_ABANDONED = -2147481052 +RC_UNABLE_TO_CONNECT = -1073737472 +LUNA_RET_CB_REMOTE_CLOSED = -2147481053 +RC_STC_NO_CONTEXT = -1073700863 +LUNA_RET_CB_REMOTE_ABORT = -2147481054 +LUNA_RET_CB_ID_INVALID = -2147481055 +RC_STC_CLIENT_IDENTITY_NOT_CONFIGURED = -1073700862 +LUNA_RET_CB_HANDLE_INVALID = -2147481056 +RC_STC_PARTITION_IDENTITY_NOT_CONFIGURED = -1073700861 +LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL = -2147481063 +LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL = -2147481064 +RC_STC_DH_KEYGEN_ERROR = -1073700860 +LUNA_RET_CB_HIOS_STATE_INVALID = -2147481065 +RC_STC_CIPHER_SUITE_REJECTED = -1073700859 +LUNA_RET_CB_HIOS_RECV_TIMEOUT = -2147481066 +LUNA_RET_CB_HIOS_SEND_TIMEOUT = -2147481067 +RC_STC_DH_KEY_NOT_FROM_SAME_GROUP = -1073700858 +LUNA_RET_CB_HIOS_IO_ERROR = -2147481068 +RC_STC_COMPUTE_DH_KEY_ERROR = -1073700857 +LUNA_RET_CB_HIOS_CANCELED = -2147481069 +LUNA_RET_CB_HIOS_CLOSED = -2147481070 +RC_STC_FIRST_PHASE_KDF_ERROR = -1073700856 +LUNA_RET_CB_HIOS_ID_INVALID = -2147481071 +RC_STC_SECOND_PHASE_KDF_ERROR = -1073700855 +LUNA_RET_CB_HIOS_HANDLE_INVALID = -2147481072 +LUNA_RET_CB_SYS_ERROR = -2147481081 +RC_STC_KEY_CONFIRMATION_FAILED = -1073700854 +MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK = 41 +MSG_RTC_ROLLED_BACK = 37 +MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK = 35 +MSG_TVK_TIMESTAMP_RECOVERY_FAILED = 33 +LUNA_RET_MD5_SELF_TEST_FAILURE = 3145737 +MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER = 31 +LUNA_RET_CAST5_SELF_TEST_FAILURE = 3145735 +MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING = 28 +LastFirmwareCode = -1073741825 +LUNA_RET_RM_BAD_HSM_PARAMS = 3148291 +LUNA_RET_TOKEN_LOCKED_OUT = 3145730 +LUNA_RET_GENERAL_ERROR = 327680 +MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF = 21 +MSG_RTC_ZEROIZED_ON_POWER_LOSS = 20 +MSG_RTC_MSG_NVRAM_ZAPPING_FAILED = 3 +LUNA_RET_SM_UNKNOWN_TOSM_STATE = 3145748 +LUNA_RET_TOKEN_LOCKED_OUT_RN = 3145988 +MSG_RTC_CANT_CLEAN_POWER_LOSS = 11 +LUNA_RET_TOKEN_LOCKED_OUT_MM = 3145985 +LUNA_RET_PE1746_ERROR = 3147911 +LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES = 68103 +MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS = 8 +LUNA_RET_ECC_NOT_SUPPORTED = -2147482111 +LUNA_RET_INVALID_PRIVATE_KEY_TYPE = -2147483383 +LUNA_RET_KEY_SIZE_RANGE = 6422528 +LUNA_RET_LICENSE_CAPACITY_EXCEEDED = 68105 +LUNA_RET_CB_ABORTED = -2147481082 +LUNA_RET_CB_RETRY = -2147481083 +RC_STC_RESPONSE_BAD_MAC = -1073700852 +LUNA_RET_CB_TIMEOUT = -2147481084 +RC_STC_NOT_ENABLED = -1073700851 +LUNA_RET_CB_PARAM_INVALID = -2147481086 +RC_STC_CLIENT_HANDLE_INVALID = -1073700850 +LUNA_RET_CB_NOT_SUPPORTED = -2147481087 +LUNA_RET_PED_ERROR = 3146052 +RC_STC_NO_SESSION_KEY = -1073700853 +LUNA_RET_CHALLENGE_TYPE_INVALID = 2099968 +RC_STC_RSA_ENCRYPT_ERROR = -1073700842 +LUNA_RET_CHALLENGE_REQUIRES_PED = 68353 +LUNA_RET_CHALLENGE_NOT_REQUIRED = 68354 +LUNA_RET_KEY_PARITY = 6488066 +RC_STC_REKEY_CHANNEL_MISMATCH = -1073700843 +LUNA_RET_CHALLENGE_RESPONSE_INCORRECT = 10488579 +RC_STC_RESPONSE_REPLAYED = -1073700844 +LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT = 68355 +LUNA_RET_CHALLENGE_INVALID = 2099972 +RC_STC_RESPONSE_DECRYPT_ERROR = -1073700845 +LUNA_RET_OH_OBJECT_VERSION_INVALID = 3148800 +RC_STC_NO_CHANNEL = -1073700846 +LUNA_RET_OH_OBJECT_TYPE_INVALID = 3148801 +LUNA_RET_OH_OBJECT_ALREADY_EXISTS = 68610 +RC_STC_SEQUENCE_NUM_INVALID = -1073700847 +LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID = -2147482350 +LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST = 2100227 +RC_STC_CONTAINER_INVALID = -1073700848 +LUNA_RET_STORAGE_TYPE_INCONSISTENT = 2100228 +LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS = 2100229 +RC_STC_SESSION_INVALID = -1073700849 # values for enumeration 'ResultCodeValue' ResultCodeValue = c_int # enum @@ -660,6 +704,15 @@ class CK_DES_CTR_PARAMS(Structure): CK_DES_CTR_PARAMS_PTR = POINTER(CK_DES_CTR_PARAMS) CK_AES_GMAC_PARAMS = CK_AES_GCM_PARAMS CK_AES_GMAC_PARAMS_PTR = POINTER(CK_AES_GMAC_PARAMS) +class HSM_STATS_PARAMS(Structure): + pass +if 'win' in sys.platform: + HSM_STATS_PARAMS._pack_ = 1 +HSM_STATS_PARAMS._fields_ = [ + ('ulId', CK_ULONG), + ('ulHighValue', CK_ULONG), + ('ulLowValue', CK_ULONG), +] class CA_ROLE_STATE(Structure): pass if 'win' in sys.platform: @@ -808,10 +861,9 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): pass CK_SFNT_CA_FUNCTION_LIST_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST) CK_SFNT_CA_FUNCTION_LIST_PTR_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST_PTR) -CK_SLOT_ID = CK_ULONG -CK_C_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_GetFunctionList = CFUNCTYPE(CK_RV, CK_SFNT_CA_FUNCTION_LIST_PTR_PTR) CK_FLAGS = CK_ULONG +CK_SLOT_ID = CK_ULONG CK_SLOT_ID_PTR = POINTER(CK_SLOT_ID) CK_VOID_PTR = c_void_p CK_CA_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, POINTER(CK_ULONG), CK_SLOT_ID_PTR, CK_VOID_PTR) @@ -825,6 +877,7 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_CA_InitSlotRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG) CK_CA_RoleStateGet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE, POINTER(CA_ROLE_STATE)) CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_CreateContainerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) CK_CA_Deactivate = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE) CK_CA_FindAdminSlotForSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_SLOT_ID), POINTER(CK_SLOT_ID)) CK_CA_TokenInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CT_TokenHndle, CK_SLOT_ID) @@ -835,6 +888,7 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_NOTIFY = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) CK_SESSION_HANDLE_PTR = POINTER(CK_SESSION_HANDLE) CK_CA_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) +CK_CA_OpenSessionWithAppID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) CK_CA_IndirectLogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE) CK_CA_InitializeRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_CA_DeleteRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) @@ -942,9 +996,10 @@ class CK_ATTRIBUTE(Structure): CK_CA_SpRawWrite = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_CheckOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)) CK_CA_DestroyMultipleObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR) -CK_CA_OpenSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_OpenSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR) CK_CA_CloseSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_ListSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_ListSecureTokenInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_ListSecureTokenUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG) class CK_MECHANISM(Structure): pass CK_MECHANISM_PTR = POINTER(CK_MECHANISM) @@ -985,8 +1040,6 @@ class CK_MECHANISM(Structure): CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) CK_CA_EncodeECParamsFromFile = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR) -class HSM_STATS_PARAMS(Structure): - pass CK_CA_GetHSMStats = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, POINTER(HSM_STATS_PARAMS)) CK_CA_GetHSMStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetTokenStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) @@ -1003,7 +1056,6 @@ class HSM_STATS_PARAMS(Structure): CK_CA_GetTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR) CK_CA_LogSetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR) CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR) -CK_CA_LogEraseAll = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)) CK_CA_DeleteContainerWithHandle = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_GetContainerList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) @@ -1028,11 +1080,39 @@ class HSM_STATS_PARAMS(Structure): CK_CA_STCGetClientInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) CK_CA_STCGetPartPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) CK_CA_STCGetAdminPubKey = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCSetCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCGetCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_STCClearCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCSetDigestAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCGetDigestAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_STCClearDigestAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCSetKeyLifeTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCGetKeyLifeTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) +CK_CA_STCSetKeyActivationTimeOut = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCGetKeyActivationTimeOut = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) +CK_CA_STCSetMaxSessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCGetMaxSessions = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) +CK_CA_STCSetSequenceWindowSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) +CK_CA_STCGetSequenceWindowSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) +CK_CA_STCIsEnabled = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR) +CK_CA_STCGetState = CFUNCTYPE(CK_RV, CK_ULONG, POINTER(CK_CHAR), CK_BYTE) +CK_CA_STCGetCurrentKeyLife = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) +CK_CA_GetSlotIdForPhysicalSlot = CFUNCTYPE(CK_RV, CK_ULONG, CK_SLOT_ID_PTR) +CK_CA_GetSlotIdForContainer = CFUNCTYPE(CK_RV, CK_ULONG, CK_ULONG, CK_SLOT_ID_PTR) +CK_CA_STCGetChannelID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_STCGetCipherID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_STCGetDigestID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_STCGetCipherIDs = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_STCGetCipherNameByID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_CHAR_PTR, CK_BYTE) +CK_CA_STCGetDigestIDs = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_STCGetDigestNameByID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_CHAR_PTR, CK_BYTE) +CK_CA_GetServerInstanceBySlotID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_GetSlotListFromServerInstance = CFUNCTYPE(CK_RV, CK_ULONG, CK_SLOT_ID_PTR, CK_ULONG_PTR) +CK_CA_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) if 'win' in sys.platform: CK_SFNT_CA_FUNCTION_LIST._pack_ = 1 CK_SFNT_CA_FUNCTION_LIST._fields_ = [ ('version', CK_VERSION), - ('C_PerformSelfTest', CK_C_PerformSelfTest), ('CA_GetFunctionList', CK_CA_GetFunctionList), ('CA_WaitForSlotEvent', CK_CA_WaitForSlotEvent), ('CA_InitIndirectToken', CK_CA_InitIndirectToken), @@ -1042,6 +1122,7 @@ class HSM_STATS_PARAMS(Structure): ('CA_InitSlotRolePIN', CK_CA_InitSlotRolePIN), ('CA_RoleStateGet', CK_CA_RoleStateGet), ('CA_CreateLoginChallenge', CK_CA_CreateLoginChallenge), + ('CA_CreateContainerLoginChallenge', CK_CA_CreateContainerLoginChallenge), ('CA_Deactivate', CK_CA_Deactivate), ('CA_FindAdminSlotForSlot', CK_CA_FindAdminSlotForSlot), ('CA_TokenInsert', CK_CA_TokenInsert), @@ -1049,6 +1130,7 @@ class HSM_STATS_PARAMS(Structure): ('CA_TokenZeroize', CK_CA_TokenZeroize), ('CA_TokenDelete', CK_CA_TokenDelete), ('CA_OpenSession', CK_CA_OpenSession), + ('CA_OpenSessionWithAppID', CK_CA_OpenSessionWithAppID), ('CA_IndirectLogin', CK_CA_IndirectLogin), ('CA_InitializeRemotePEDVector', CK_CA_InitializeRemotePEDVector), ('CA_DeleteRemotePEDVector', CK_CA_DeleteRemotePEDVector), @@ -1152,7 +1234,8 @@ class HSM_STATS_PARAMS(Structure): ('CA_DestroyMultipleObjects', CK_CA_DestroyMultipleObjects), ('CA_OpenSecureToken', CK_CA_OpenSecureToken), ('CA_CloseSecureToken', CK_CA_CloseSecureToken), - ('CA_ListSecureToken', CK_CA_ListSecureToken), + ('CA_ListSecureTokenInit', CK_CA_ListSecureTokenInit), + ('CA_ListSecureTokenUpdate', CK_CA_ListSecureTokenUpdate), ('CA_GetSecureElementMeta', CK_CA_GetSecureElementMeta), ('CA_HAInit', CK_CA_HAInit), ('CA_HAGetMasterPublic', CK_CA_HAGetMasterPublic), @@ -1206,7 +1289,6 @@ class HSM_STATS_PARAMS(Structure): ('CA_GetTime', CK_CA_GetTime), ('CA_LogSetConfig', CK_CA_LogSetConfig), ('CA_LogGetConfig', CK_CA_LogGetConfig), - ('CA_LogEraseAll', CK_CA_LogEraseAll), ('CA_LogGetStatus', CK_CA_LogGetStatus), ('CA_DeleteContainerWithHandle', CK_CA_DeleteContainerWithHandle), ('CA_GetContainerList', CK_CA_GetContainerList), @@ -1231,6 +1313,35 @@ class HSM_STATS_PARAMS(Structure): ('CA_STCGetClientInfo', CK_CA_STCGetClientInfo), ('CA_STCGetPartPubKey', CK_CA_STCGetPartPubKey), ('CA_STCGetAdminPubKey', CK_CA_STCGetAdminPubKey), + ('CA_STCSetCipherAlgorithm', CK_CA_STCSetCipherAlgorithm), + ('CA_STCGetCipherAlgorithm', CK_CA_STCGetCipherAlgorithm), + ('CA_STCClearCipherAlgorithm', CK_CA_STCClearCipherAlgorithm), + ('CA_STCSetDigestAlgorithm', CK_CA_STCSetDigestAlgorithm), + ('CA_STCGetDigestAlgorithm', CK_CA_STCGetDigestAlgorithm), + ('CA_STCClearDigestAlgorithm', CK_CA_STCClearDigestAlgorithm), + ('CA_STCSetKeyLifeTime', CK_CA_STCSetKeyLifeTime), + ('CA_STCGetKeyLifeTime', CK_CA_STCGetKeyLifeTime), + ('CA_STCSetKeyActivationTimeOut', CK_CA_STCSetKeyActivationTimeOut), + ('CA_STCGetKeyActivationTimeOut', CK_CA_STCGetKeyActivationTimeOut), + ('CA_STCSetMaxSessions', CK_CA_STCSetMaxSessions), + ('CA_STCGetMaxSessions', CK_CA_STCGetMaxSessions), + ('CA_STCSetSequenceWindowSize', CK_CA_STCSetSequenceWindowSize), + ('CA_STCGetSequenceWindowSize', CK_CA_STCGetSequenceWindowSize), + ('CA_STCIsEnabled', CK_CA_STCIsEnabled), + ('CA_STCGetState', CK_CA_STCGetState), + ('CA_STCGetCurrentKeyLife', CK_CA_STCGetCurrentKeyLife), + ('CA_GetSlotIdForPhysicalSlot', CK_CA_GetSlotIdForPhysicalSlot), + ('CA_GetSlotIdForContainer', CK_CA_GetSlotIdForContainer), + ('CA_STCGetChannelID', CK_CA_STCGetChannelID), + ('CA_STCGetCipherID', CK_CA_STCGetCipherID), + ('CA_STCGetDigestID', CK_CA_STCGetDigestID), + ('CA_STCGetCipherIDs', CK_CA_STCGetCipherIDs), + ('CA_STCGetCipherNameByID', CK_CA_STCGetCipherNameByID), + ('CA_STCGetDigestIDs', CK_CA_STCGetDigestIDs), + ('CA_STCGetDigestNameByID', CK_CA_STCGetDigestNameByID), + ('CA_GetServerInstanceBySlotID', CK_CA_GetServerInstanceBySlotID), + ('CA_GetSlotListFromServerInstance', CK_CA_GetSlotListFromServerInstance), + ('CA_PerformSelfTest', CK_CA_PerformSelfTest), ] CA_GetFunctionList = make_late_binding_function('CA_GetFunctionList') CA_GetFunctionList.restype = CK_RV @@ -1247,15 +1358,45 @@ class HSM_STATS_PARAMS(Structure): CA_ResetPIN = make_late_binding_function('CA_ResetPIN') CA_ResetPIN.restype = CK_RV CA_ResetPIN.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG] +CA_InitRolePIN = make_late_binding_function('CA_InitRolePIN') +CA_InitRolePIN.restype = CK_RV +CA_InitRolePIN.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG] +CA_InitSlotRolePIN = make_late_binding_function('CA_InitSlotRolePIN') +CA_InitSlotRolePIN.restype = CK_RV +CA_InitSlotRolePIN.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG] +CA_RoleStateGet = make_late_binding_function('CA_RoleStateGet') +CA_RoleStateGet.restype = CK_RV +CA_RoleStateGet.argtypes = [CK_SLOT_ID, CK_USER_TYPE, POINTER(CA_ROLE_STATE)] CA_CreateLoginChallenge = make_late_binding_function('CA_CreateLoginChallenge') CA_CreateLoginChallenge.restype = CK_RV CA_CreateLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR] +CA_CreateContainerLoginChallenge = make_late_binding_function('CA_CreateContainerLoginChallenge') +CA_CreateContainerLoginChallenge.restype = CK_RV +CA_CreateContainerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR] CA_Deactivate = make_late_binding_function('CA_Deactivate') CA_Deactivate.restype = CK_RV CA_Deactivate.argtypes = [CK_SLOT_ID, CK_USER_TYPE] +CA_FindAdminSlotForSlot = make_late_binding_function('CA_FindAdminSlotForSlot') +CA_FindAdminSlotForSlot.restype = CK_RV +CA_FindAdminSlotForSlot.argtypes = [CK_SLOT_ID, POINTER(CK_SLOT_ID), POINTER(CK_SLOT_ID)] +CA_TokenInsert = make_late_binding_function('CA_TokenInsert') +CA_TokenInsert.restype = CK_RV +CA_TokenInsert.argtypes = [CK_SESSION_HANDLE, CT_TokenHndle, CK_SLOT_ID] +CA_TokenInsertNoAuth = make_late_binding_function('CA_TokenInsertNoAuth') +CA_TokenInsertNoAuth.restype = CK_RV +CA_TokenInsertNoAuth.argtypes = [CT_TokenHndle, CK_SLOT_ID] +CA_TokenZeroize = make_late_binding_function('CA_TokenZeroize') +CA_TokenZeroize.restype = CK_RV +CA_TokenZeroize.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_FLAGS] +CA_TokenDelete = make_late_binding_function('CA_TokenDelete') +CA_TokenDelete.restype = CK_RV +CA_TokenDelete.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID] CA_OpenSession = make_late_binding_function('CA_OpenSession') CA_OpenSession.restype = CK_RV CA_OpenSession.argtypes = [CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] +CA_OpenSessionWithAppID = make_late_binding_function('CA_OpenSessionWithAppID') +CA_OpenSessionWithAppID.restype = CK_RV +CA_OpenSessionWithAppID.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] CA_IndirectLogin = make_late_binding_function('CA_IndirectLogin') CA_IndirectLogin.restype = CK_RV CA_IndirectLogin.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE] @@ -1304,6 +1445,9 @@ class HSM_STATS_PARAMS(Structure): CA_SetKCV = make_late_binding_function('CA_SetKCV') CA_SetKCV.restype = CK_RV CA_SetKCV.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] +CA_SetRDK = make_late_binding_function('CA_SetRDK') +CA_SetRDK.restype = CK_RV +CA_SetRDK.argtypes = [CK_SESSION_HANDLE, POINTER(CK_BYTE), CK_ULONG] CA_SetCloningDomain = make_late_binding_function('CA_SetCloningDomain') CA_SetCloningDomain.restype = CK_RV CA_SetCloningDomain.argtypes = [CK_BYTE_PTR, CK_ULONG] @@ -1472,6 +1616,15 @@ class HSM_STATS_PARAMS(Structure): CA_SetContainerPolicies = make_late_binding_function('CA_SetContainerPolicies') CA_SetContainerPolicies.restype = CK_RV CA_SetContainerPolicies.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetTokenCapabilities = make_late_binding_function('CA_GetTokenCapabilities') +CA_GetTokenCapabilities.restype = CK_RV +CA_GetTokenCapabilities.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_SetTokenPolicies = make_late_binding_function('CA_SetTokenPolicies') +CA_SetTokenPolicies.restype = CK_RV +CA_SetTokenPolicies.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetTokenPolicies = make_late_binding_function('CA_GetTokenPolicies') +CA_GetTokenPolicies.restype = CK_RV +CA_GetTokenPolicies.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] CA_RetrieveLicenseList = make_late_binding_function('CA_RetrieveLicenseList') CA_RetrieveLicenseList.restype = CK_RV CA_RetrieveLicenseList.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] @@ -1481,6 +1634,9 @@ class HSM_STATS_PARAMS(Structure): CA_GetContainerStatus = make_late_binding_function('CA_GetContainerStatus') CA_GetContainerStatus.restype = CK_RV CA_GetContainerStatus.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetTokenStatus = make_late_binding_function('CA_GetTokenStatus') +CA_GetTokenStatus.restype = CK_RV +CA_GetTokenStatus.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] CA_GetSessionInfo = make_late_binding_function('CA_GetSessionInfo') CA_GetSessionInfo.restype = CK_RV CA_GetSessionInfo.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] @@ -1520,6 +1676,9 @@ class HSM_STATS_PARAMS(Structure): CA_ResetDevice = make_late_binding_function('CA_ResetDevice') CA_ResetDevice.restype = CK_RV CA_ResetDevice.argtypes = [CK_SLOT_ID, CK_FLAGS] +CA_Zeroize = make_late_binding_function('CA_Zeroize') +CA_Zeroize.restype = CK_RV +CA_Zeroize.argtypes = [CK_SLOT_ID, CK_FLAGS] CA_FactoryReset = make_late_binding_function('CA_FactoryReset') CA_FactoryReset.restype = CK_RV CA_FactoryReset.argtypes = [CK_SLOT_ID, CK_FLAGS] @@ -1543,13 +1702,16 @@ class HSM_STATS_PARAMS(Structure): CA_DestroyMultipleObjects.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR] CA_OpenSecureToken = make_late_binding_function('CA_OpenSecureToken') CA_OpenSecureToken.restype = CK_RV -CA_OpenSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_OpenSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR] CA_CloseSecureToken = make_late_binding_function('CA_CloseSecureToken') CA_CloseSecureToken.restype = CK_RV CA_CloseSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG] -CA_ListSecureToken = make_late_binding_function('CA_ListSecureToken') -CA_ListSecureToken.restype = CK_RV -CA_ListSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_ListSecureTokenInit = make_late_binding_function('CA_ListSecureTokenInit') +CA_ListSecureTokenInit.restype = CK_RV +CA_ListSecureTokenInit.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR] +CA_ListSecureTokenUpdate = make_late_binding_function('CA_ListSecureTokenUpdate') +CA_ListSecureTokenUpdate.restype = CK_RV +CA_ListSecureTokenUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_GetSecureElementMeta = make_late_binding_function('CA_GetSecureElementMeta') CA_GetSecureElementMeta.restype = CK_RV CA_GetSecureElementMeta.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG] @@ -1604,6 +1766,12 @@ class HSM_STATS_PARAMS(Structure): CA_Insert = make_late_binding_function('CA_Insert') CA_Insert.restype = CK_RV CA_Insert.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] +CA_GetTokenObjectUID = make_late_binding_function('CA_GetTokenObjectUID') +CA_GetTokenObjectUID.restype = CK_RV +CA_GetTokenObjectUID.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)] +CA_GetTokenObjectHandle = make_late_binding_function('CA_GetTokenObjectHandle') +CA_GetTokenObjectHandle.restype = CK_RV +CA_GetTokenObjectHandle.argtypes = [CK_SLOT_ID, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR] CA_GetObjectUID = make_late_binding_function('CA_GetObjectUID') CA_GetObjectUID.restype = CK_RV CA_GetObjectUID.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)] @@ -1655,19 +1823,15 @@ class HSM_STATS_PARAMS(Structure): CA_EncodeECParamsFromFile = make_late_binding_function('CA_EncodeECParamsFromFile') CA_EncodeECParamsFromFile.restype = CK_RV CA_EncodeECParamsFromFile.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR] -if 'win' in sys.platform: - HSM_STATS_PARAMS._pack_ = 1 -HSM_STATS_PARAMS._fields_ = [ - ('ulId', CK_ULONG), - ('ulHighValue', CK_ULONG), - ('ulLowValue', CK_ULONG), -] CA_GetHSMStats = make_late_binding_function('CA_GetHSMStats') CA_GetHSMStats.restype = CK_RV CA_GetHSMStats.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, POINTER(HSM_STATS_PARAMS)] CA_GetHSMStorageInformation = make_late_binding_function('CA_GetHSMStorageInformation') CA_GetHSMStorageInformation.restype = CK_RV CA_GetHSMStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetTokenStorageInformation = make_late_binding_function('CA_GetTokenStorageInformation') +CA_GetTokenStorageInformation.restype = CK_RV +CA_GetTokenStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] CA_GetContainerStorageInformation = make_late_binding_function('CA_GetContainerStorageInformation') CA_GetContainerStorageInformation.restype = CK_RV CA_GetContainerStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] @@ -1707,9 +1871,6 @@ class HSM_STATS_PARAMS(Structure): CA_LogGetConfig = make_late_binding_function('CA_LogGetConfig') CA_LogGetConfig.restype = CK_RV CA_LogGetConfig.argtypes = [CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR] -CA_LogEraseAll = make_late_binding_function('CA_LogEraseAll') -CA_LogEraseAll.restype = CK_RV -CA_LogEraseAll.argtypes = [CK_SESSION_HANDLE] CA_LogGetStatus = make_late_binding_function('CA_LogGetStatus') CA_LogGetStatus.restype = CK_RV CA_LogGetStatus.argtypes = [CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)] @@ -1752,11 +1913,166 @@ class HSM_STATS_PARAMS(Structure): CA_ModifyUsageCount = make_late_binding_function('CA_ModifyUsageCount') CA_ModifyUsageCount.restype = CK_RV CA_ModifyUsageCount.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG] -C_PerformSelfTest = make_late_binding_function('C_PerformSelfTest') -C_PerformSelfTest.restype = CK_RV -C_PerformSelfTest.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_EnableUnauthTokenInsertion = make_late_binding_function('CA_EnableUnauthTokenInsertion') +CA_EnableUnauthTokenInsertion.restype = CK_RV +CA_EnableUnauthTokenInsertion.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR] +CA_GetUnauthTokenInsertionStatus = make_late_binding_function('CA_GetUnauthTokenInsertionStatus') +CA_GetUnauthTokenInsertionStatus.restype = CK_RV +CA_GetUnauthTokenInsertionStatus.argtypes = [CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_ULONG), POINTER(CK_ULONG)] +CA_DisableUnauthTokenInsertion = make_late_binding_function('CA_DisableUnauthTokenInsertion') +CA_DisableUnauthTokenInsertion.restype = CK_RV +CA_DisableUnauthTokenInsertion.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_STCRegister = make_late_binding_function('CA_STCRegister') +CA_STCRegister.restype = CK_RV +CA_STCRegister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG] +CA_STCDeregister = make_late_binding_function('CA_STCDeregister') +CA_STCDeregister.restype = CK_RV +CA_STCDeregister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR)] +CA_STCGetPubKey = make_late_binding_function('CA_STCGetPubKey') +CA_STCGetPubKey.restype = CK_RV +CA_STCGetPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetClientsList = make_late_binding_function('CA_STCGetClientsList') +CA_STCGetClientsList.restype = CK_RV +CA_STCGetClientsList.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] +CA_STCGetClientInfo = make_late_binding_function('CA_STCGetClientInfo') +CA_STCGetClientInfo.restype = CK_RV +CA_STCGetClientInfo.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetPartPubKey = make_late_binding_function('CA_STCGetPartPubKey') +CA_STCGetPartPubKey.restype = CK_RV +CA_STCGetPartPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetAdminPubKey = make_late_binding_function('CA_STCGetAdminPubKey') +CA_STCGetAdminPubKey.restype = CK_RV +CA_STCGetAdminPubKey.argtypes = [CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCSetCipherAlgorithm = make_late_binding_function('CA_STCSetCipherAlgorithm') +CA_STCSetCipherAlgorithm.restype = CK_RV +CA_STCSetCipherAlgorithm.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCGetCipherAlgorithm = make_late_binding_function('CA_STCGetCipherAlgorithm') +CA_STCGetCipherAlgorithm.restype = CK_RV +CA_STCGetCipherAlgorithm.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_STCClearCipherAlgorithm = make_late_binding_function('CA_STCClearCipherAlgorithm') +CA_STCClearCipherAlgorithm.restype = CK_RV +CA_STCClearCipherAlgorithm.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCSetDigestAlgorithm = make_late_binding_function('CA_STCSetDigestAlgorithm') +CA_STCSetDigestAlgorithm.restype = CK_RV +CA_STCSetDigestAlgorithm.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCGetDigestAlgorithm = make_late_binding_function('CA_STCGetDigestAlgorithm') +CA_STCGetDigestAlgorithm.restype = CK_RV +CA_STCGetDigestAlgorithm.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_STCClearDigestAlgorithm = make_late_binding_function('CA_STCClearDigestAlgorithm') +CA_STCClearDigestAlgorithm.restype = CK_RV +CA_STCClearDigestAlgorithm.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCSetKeyLifeTime = make_late_binding_function('CA_STCSetKeyLifeTime') +CA_STCSetKeyLifeTime.restype = CK_RV +CA_STCSetKeyLifeTime.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCGetKeyLifeTime = make_late_binding_function('CA_STCGetKeyLifeTime') +CA_STCGetKeyLifeTime.restype = CK_RV +CA_STCGetKeyLifeTime.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR] +CA_STCSetKeyActivationTimeOut = make_late_binding_function('CA_STCSetKeyActivationTimeOut') +CA_STCSetKeyActivationTimeOut.restype = CK_RV +CA_STCSetKeyActivationTimeOut.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCGetKeyActivationTimeOut = make_late_binding_function('CA_STCGetKeyActivationTimeOut') +CA_STCGetKeyActivationTimeOut.restype = CK_RV +CA_STCGetKeyActivationTimeOut.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR] +CA_STCSetMaxSessions = make_late_binding_function('CA_STCSetMaxSessions') +CA_STCSetMaxSessions.restype = CK_RV +CA_STCSetMaxSessions.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCGetMaxSessions = make_late_binding_function('CA_STCGetMaxSessions') +CA_STCGetMaxSessions.restype = CK_RV +CA_STCGetMaxSessions.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR] +CA_STCSetSequenceWindowSize = make_late_binding_function('CA_STCSetSequenceWindowSize') +CA_STCSetSequenceWindowSize.restype = CK_RV +CA_STCSetSequenceWindowSize.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_STCGetSequenceWindowSize = make_late_binding_function('CA_STCGetSequenceWindowSize') +CA_STCGetSequenceWindowSize.restype = CK_RV +CA_STCGetSequenceWindowSize.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR] +CA_STCIsEnabled = make_late_binding_function('CA_STCIsEnabled') +CA_STCIsEnabled.restype = CK_RV +CA_STCIsEnabled.argtypes = [CK_ULONG, CK_BYTE_PTR] +CA_STCGetState = make_late_binding_function('CA_STCGetState') +CA_STCGetState.restype = CK_RV +CA_STCGetState.argtypes = [CK_ULONG, POINTER(CK_CHAR), CK_BYTE] +CA_STCGetCurrentKeyLife = make_late_binding_function('CA_STCGetCurrentKeyLife') +CA_STCGetCurrentKeyLife.restype = CK_RV +CA_STCGetCurrentKeyLife.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR] +CA_GetSlotIdForPhysicalSlot = make_late_binding_function('CA_GetSlotIdForPhysicalSlot') +CA_GetSlotIdForPhysicalSlot.restype = CK_RV +CA_GetSlotIdForPhysicalSlot.argtypes = [CK_ULONG, CK_SLOT_ID_PTR] +CA_GetSlotIdForContainer = make_late_binding_function('CA_GetSlotIdForContainer') +CA_GetSlotIdForContainer.restype = CK_RV +CA_GetSlotIdForContainer.argtypes = [CK_ULONG, CK_ULONG, CK_SLOT_ID_PTR] +CA_STCGetChannelID = make_late_binding_function('CA_STCGetChannelID') +CA_STCGetChannelID.restype = CK_RV +CA_STCGetChannelID.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_STCGetCipherID = make_late_binding_function('CA_STCGetCipherID') +CA_STCGetCipherID.restype = CK_RV +CA_STCGetCipherID.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_STCGetDigestID = make_late_binding_function('CA_STCGetDigestID') +CA_STCGetDigestID.restype = CK_RV +CA_STCGetDigestID.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_STCGetCipherIDs = make_late_binding_function('CA_STCGetCipherIDs') +CA_STCGetCipherIDs.restype = CK_RV +CA_STCGetCipherIDs.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_BYTE_PTR] +CA_STCGetCipherNameByID = make_late_binding_function('CA_STCGetCipherNameByID') +CA_STCGetCipherNameByID.restype = CK_RV +CA_STCGetCipherNameByID.argtypes = [CK_SLOT_ID, CK_ULONG, CK_CHAR_PTR, CK_BYTE] +CA_STCGetDigestIDs = make_late_binding_function('CA_STCGetDigestIDs') +CA_STCGetDigestIDs.restype = CK_RV +CA_STCGetDigestIDs.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_BYTE_PTR] +CA_STCGetDigestNameByID = make_late_binding_function('CA_STCGetDigestNameByID') +CA_STCGetDigestNameByID.restype = CK_RV +CA_STCGetDigestNameByID.argtypes = [CK_SLOT_ID, CK_ULONG, CK_CHAR_PTR, CK_BYTE] +CA_GetServerInstanceBySlotID = make_late_binding_function('CA_GetServerInstanceBySlotID') +CA_GetServerInstanceBySlotID.restype = CK_RV +CA_GetServerInstanceBySlotID.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_GetSlotListFromServerInstance = make_late_binding_function('CA_GetSlotListFromServerInstance') +CA_GetSlotListFromServerInstance.restype = CK_RV +CA_GetSlotListFromServerInstance.argtypes = [CK_ULONG, CK_SLOT_ID_PTR, CK_ULONG_PTR] +CA_PerformSelfTest = make_late_binding_function('CA_PerformSelfTest') +CA_PerformSelfTest.restype = CK_RV +CA_PerformSelfTest.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CK_GetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(c_int)) CK_ResetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID) + +# values for enumeration 'fwResultCode' +fwResultCode = c_int # enum + +# values for enumeration 'eInitMsgs' +eInitMsgs = c_int # enum +SInt8 = c_byte +SInt16 = c_short +SInt32 = c_long +SInt = c_int +SInt64 = c_longlong +UInt8 = c_ubyte +UInt16 = c_ushort +UInt32 = c_ulong +UInt = c_uint +ULong = c_ulong +UInt64 = c_ulonglong +Int8 = c_char +Int16 = c_short +Int32 = c_long +Int = c_int +Int64 = c_longlong +Float32 = c_float +Float64 = c_double +Float = Float64 +Byte = UInt8 +BYTE = UInt8 +HalfWord = UInt16 +Word = UInt32 +PointerDifference = SInt32 +SizeType = UInt +Boolean = UInt8 +class swapper(Union): + pass +if 'win' in sys.platform: + swapper._pack_ = 1 +swapper._fields_ = [ + ('bytes', c_char * 4), + ('words', c_int), +] +HANDLE = c_int class CK_FUNCTION_LIST(Structure): pass CK_C_Initialize = CFUNCTYPE(CK_RV, CK_VOID_PTR) @@ -2734,818 +3050,865 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): ('iv', CK_BYTE * 16), ('pData', CK_BYTE_PTR), ('length', CK_ULONG), -] -CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_ARIA_CBC_ENCRYPT_DATA_PARAMS) - -# values for enumeration 'fwResultCode' -fwResultCode = c_int # enum - -# values for enumeration 'eInitMsgs' -eInitMsgs = c_int # enum -SInt8 = c_byte -SInt16 = c_short -SInt32 = c_long -SInt = c_int -SInt64 = c_longlong -UInt8 = c_ubyte -UInt16 = c_ushort -UInt32 = c_ulong -UInt = c_uint -ULong = c_ulong -UInt64 = c_ulonglong -Int8 = c_char -Int16 = c_short -Int32 = c_long -Int = c_int -Int64 = c_longlong -Float32 = c_float -Float64 = c_double -Float = Float64 -Byte = UInt8 -BYTE = UInt8 -HalfWord = UInt16 -Word = UInt32 -PointerDifference = SInt32 -SizeType = UInt -Boolean = UInt8 -class swapper(Union): - pass -if 'win' in sys.platform: - swapper._pack_ = 1 -swapper._fields_ = [ - ('bytes', c_char * 4), - ('words', c_int), -] -HANDLE = c_int -__all__ = ['RC_MANUFACTURING_NO_CONFIG_AVAILABLE', - 'CK_ECMQV_DERIVE_PARAMS_PTR', - 'LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID', - 'CA_InvokeService', 'CK_VERSION_PTR', - 'CA_GetSecondarySlot', 'LUNA_RET_TOKEN_LOCKED_OUT_CA', - 'RC_RESET_FAILED', 'HSM_STATS_PARAMS', - 'LUNA_RET_TOKEN_LOCKED_OUT_CL', - 'CK_CA_SetDestructiveHSMPolicy', - 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE', - 'CK_CA_HAAnswerMofNChallenge', 'LUNA_RET_CB_TIMEOUT', - 'CK_X9_42_DH2_DERIVE_PARAMS_PTR', 'ResultCodeValue', - 'LUNA_RET_WRAPPING_KEY_SIZE_RANGE', 'LUNA_RET_BAD_DAC', - 'CK_KEA_DERIVE_PARAMS_PTR', - 'CK_CA_DisableUnauthTokenInsertion', - 'RC_SSL_CREATE_SSL_ERROR', 'C_UnwrapKey', 'BYTE', - 'LUNA_RET_BAD_DAK', 'CK_CA_GetRemotePEDVectorStatus', +] +CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_ARIA_CBC_ENCRYPT_DATA_PARAMS) +__all__ = ['CA_InvokeService', 'LUNA_RET_PED_UNSUPPORTED_PROTOCOL', + 'CK_OTP_SIGNATURE_INFO', 'LUNA_RET_CB_TIMEOUT', + 'LUNA_RET_BAD_DAC', 'CA_GetSlotIdForContainer', + 'C_UnwrapKey', 'LUNA_RET_BAD_DAK', 'Int32', 'CA_PerformModuleCall', 'LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID', - 'LUNA_HIFN_UNKNOWN_ALGORITHM', 'LUNA_RET_HA_NOT_SUPPORTED', - 'CK_CA_STCGetAdminPubKey', 'CA_OpenSession', - 'LUNA_RET_VECTOR_OF_DIFFERENT_SET', 'CA_MTKZeroize', - 'RC_NO_BUFFER', 'CK_LKM_TOKEN_ID_PTR', - 'RC_USER_NAME_IN_USE', 'CA_SetContainerPolicy', - 'CK_WTLS_PRF_PARAMS_PTR', 'C_FindObjectsFinal', - 'CA_SetPedId', 'CK_C_CancelFunction', - 'LUNA_RET_ECC_NOT_SUPPORTED', 'CK_CA_FactoryReset', - 'MSG_GENERATING_NEW_TVK_FAILED', 'CK_C_GetSessionInfo', - 'CK_C_VerifyRecover', 'CK_C_EncryptFinal', - 'RC_UNABLE_TO_CONNECT', 'CK_CA_ModifyMofN', - 'C_SetAttributeValue', - 'RC_SSL_CERT_VERIFICATION_LOCATION_ERROR', - 'CK_RC2_CBC_PARAMS_PTR', - 'LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE', - 'CA_ManualKCV', 'LUNA_RET_SM_ACCESS_ID_INVALID', - 'LUNA_RET_CL_QUEUE_LOCATION_ERROR', - 'RC_SSL_INVALID_CERT_STRUCTURE', 'CK_RSA_PKCS_OAEP_PARAMS', + 'LUNA_HIFN_UNKNOWN_ALGORITHM', 'CA_SetApplicationID', + 'CA_LoadEncryptedModule', 'CA_MTKZeroize', + 'LUNA_RET_ECC_NOT_SUPPORTED', 'CK_CA_Restart', + 'C_SetAttributeValue', 'CA_STCSetDigestAlgorithm', 'LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE', - 'LUNA_RET_HA_USER_NOT_INITIALIZED', - 'LUNA_RET_MD5_SELF_TEST_FAILURE', - 'LUNA_RET_OPERATION_NOT_INITIALIZED', 'CA_Deactivate', - 'LUNA_RET_LOG_BAD_TIME', 'CA_GetHSMCapabilitySetting', - 'LUNA_RET_SM_CONTEXT_NOT_ALLOCATED', 'LUNA_RET_CB_ABORTED', - 'MSG_NVRAM_READ_FAILED', - 'CK_CA_CloseApplicationIDForContainer', - 'CA_EncodeECPrimeParams', 'RC_FILE_READ_ONLY', - 'LUNA_RET_HOK_MISSING', 'RC_USB_PED_OUT_OF_SYNC', - 'CK_CA_GetContainerCapabilitySet', - 'LUNA_RET_WEIGHT_TOO_SMALL', - 'LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO', - 'CK_SSL3_KEY_MAT_PARAMS_PTR', 'CK_DATE', 'C_CloseSession', + 'LUNA_RET_MD5_SELF_TEST_FAILURE', 'LUNA_RET_LOG_BAD_TIME', + 'LUNA_RET_SM_CONTEXT_NOT_ALLOCATED', + 'CK_C_SetOperationState', 'MSG_NVRAM_READ_FAILED', + 'C_VerifyFinal', 'CK_DATE', 'LUNA_RET_TEMPLATE_INCONSISTENT', - 'RC_NON_CRYPTOKI_ELEMENT_CLONE', - 'CA_GetConfigurationElementDescription', - 'LUNA_RET_PED_UNPLUGGED', 'CK_WTLS_PRF_PARAMS', - 'CK_RC2_MAC_GENERAL_PARAMS', - 'LUNA_RET_HIFN6500_RNG_TIMEOUT', - 'LUNA_RET_VECTOR_TOO_LARGE', - 'MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED', - 'LUNA_RET_KCV_PARAMETER_MISSING', 'CA_GetMofNStatus', - 'LUNA_RET_KEY_INDIGESTIBLE', 'LUNA_RET_HSM_STORAGE_FULL', - 'CK_SLOT_INFO', 'CA_ConfigureRemotePED', 'CA_GetTPV', - 'LUNA_RET_PED_ID_INVALID', 'CK_C_EncryptInit', - 'CK_CA_LogImportSecret', - 'MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK', - 'LUNA_RET_CAN_NOT_CREATE_SECRET_KEY', - 'CK_CA_GetHSMPolicySetting', - 'CK_CA_GetUnauthTokenInsertionStatus', - 'LUNA_RET_KCDSA_SELF_TEST_FAILURE', - 'LUNA_RET_TOKEN_LOCKED_OUT_STC', 'CK_C_SetPIN', - 'CA_QueryLicense', 'CK_C_INITIALIZE_ARGS', - 'LUNA_RET_M_OF_N_ACTIVATION_REQUIRED', 'C_Logout', - 'LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE', - 'LUNA_RET_KEY_TYPE_INCONSISTENT', - 'LUNA_RET_SPLIT_ID_INVALID', - 'CK_AES_CBC_PAD_EXTRACT_PARAMS', - 'LUNA_RET_MECHANISM_INVALID', + 'RC_NON_CRYPTOKI_ELEMENT_CLONE', 'CK_WTLS_PRF_PARAMS', + 'MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED', 'C_GetInfo', + 'CA_TokenZeroize', + 'CK_CA_GetConfigurationElementDescription', 'CK_C_SetPIN', + 'RC_STC_KEY_CONFIRMATION_FAILED', 'CA_GetContainerList', 'MSG_TVK_WAS_LOST_DUE_TO_TAMPER', 'LUNA_RET_DEVICE_ERROR', - 'RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR', 'CK_ATTRIBUTE_PTR', - 'CK_VERSION', 'CK_C_GetOperationState', 'fwResultCode', - 'RC_DATA_CORRUPTED', 'LUNA_RET_KEY_UNEXTRACTABLE', + 'CK_CA_STCGetDigestID', 'CK_ATTRIBUTE_PTR', 'CK_VERSION', 'RC_USB_PED_NOT_FOUND', 'CK_CA_GetFPV', - 'CK_SESSION_HANDLE_PTR', 'Int32', - 'LUNA_RET_CL_QUEUE_OVERLAP_ERROR', 'LUNA_RET_BAD_SN', - 'CA_GetTokenInsertionCount', 'CK_CA_InitRolePIN', - 'CK_MECHANISM_PTR', 'LUNA_RET_CB_HIOS_RECV_TIMEOUT', - 'CK_ECDH2_DERIVE_PARAMS_PTR', 'CK_RC5_CBC_PARAMS', - 'C_WaitForSlotEvent', 'CK_C_CloseSession', - 'CA_LKMInitiatorComplete', 'CA_CloneAsTargetInit', - 'CK_WTLS_KEY_MAT_OUT', 'CA_GetContainerList', - 'LUNA_RET_TOKEN_LOCKED_OUT_CCM', 'MSG_NVRAM_WRITE_FAILED', - 'LUNA_RET_M_OF_N_PARAMETER_EXIST', - 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS', 'UInt64', - 'LUNA_RET_TOKEN_LOCKED_OUT_MM', - 'LUNA_RET_RC2_SELF_TEST_FAILURE', 'CK_VOID_PTR', - 'CK_C_Sign', 'CK_CA_GetTunnelSlotNumber', - 'CA_HAGetLoginChallenge', 'CA_EncodeECChar2Params', - 'LUNA_RET_MTK_ZEROIZED', 'CK_CA_ReadCommonStore', - 'LUNA_RET_ECC_UNKNOWN_CURVE', 'RC_SSL_WANT_READ_ERROR', - 'LUNA_RET_CCM_UPDATE_DENIED', - 'LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT', - 'LUNA_RET_GENERAL_ERROR', 'SInt32', - 'MSG_TVK_TIMESTAMP_RECOVERY_FAILED', 'CKCA_MODULE_ID_PTR', - 'LUNA_RET_SM_ACCESS_ALREADY_EXISTS', 'CK_LONG', - 'CA_Extract', 'CA_MOFN_GENERATION', 'RC_FILE_LOCK_ERROR', - 'CA_GetTokenCertificateInfo', - 'LUNA_RET_LICENSE_CAPACITY_EXCEEDED', - 'LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE', 'C_Decrypt', + 'LUNA_RET_CL_QUEUE_OVERLAP_ERROR', + 'LUNA_RET_POLICY_NOT_FOUND', 'CK_CA_InitRolePIN', + 'CA_LockClusteredSlot', 'C_WaitForSlotEvent', + 'LUNA_RET_TOKEN_LOCKED_OUT_CCM', 'CK_VOID_PTR', + 'CK_CA_GetSlotIdForContainer', 'CA_EncodeECParamsFromFile', + 'RC_SSL_WANT_READ_ERROR', 'CK_MECHANISM_INFO', + 'CK_CA_CloneAsTargetInit', 'RC_FILE_LOCK_ERROR', 'MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER', - 'LUNA_RET_INVALID_PADDING_TYPE', 'CK_C_VerifyInit', - 'CK_CA_ResetPIN', 'CK_C_SignEncryptUpdate', - 'CK_C_Initialize', 'MSG_RTC_LOST_ALL_POWER', + 'LUNA_RET_N_TOO_SMALL', 'MSG_RTC_LOST_ALL_POWER', 'LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT', - 'CK_SFNT_CA_FUNCTION_LIST_PTR', 'RC_SSL_SYSCALL_ERROR', - 'RC_CACHE_DIRTY', 'CK_SKIPJACK_PRIVATE_WRAP_PTR', - 'LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH', - 'CK_MAC_GENERAL_PARAMS_PTR', 'CK_EXTRACT_PARAMS_PTR', - 'LUNA_RET_RM_CONFIG_ILLEGAL', 'CA_LoadModule', - 'LUNA_RET_ECC_DAK_MISSING', 'LUNA_RET_BAD_MAC', - 'LUNA_RET_RM_NO_MEMORY', 'RC_GROUP_NAME_INVALID', - 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR', 'CA_LogGetConfig', - 'LUNA_RET_CB_RETRY', 'LUNA_RET_MM_INVALID_USAGE', - 'CK_CA_GetObjectUID', 'MSG_RESTART', - 'CK_OBJECT_HANDLE_PTR', 'LUNA_RET_ISES_RNG_TEST_FAILED', - 'CK_ECDH1_DERIVE_PARAMS', - 'MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC', - 'RC_FILE_NAME_INVALID', 'LUNA_RET_BUFFER_TOO_SMALL', - 'CK_CA_SIMExtract', 'C_DecryptDigestUpdate', - 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS', 'C_EncryptUpdate', - 'CK_CA_LogExportSecret', 'C_SetOperationState', + 'CK_CA_STCSetMaxSessions', 'CA_LoadModule', + 'CA_FirmwareRollback', 'CK_CA_GetSecureElementMeta', + 'LUNA_RET_MM_INVALID_USAGE', 'CA_Deactivate', + 'LUNA_RET_BUFFER_TOO_SMALL', 'Float64', 'LUNA_RET_MISSING_VALUE_FOR_M', - 'LUNA_RET_MISSING_VALUE_FOR_N', 'CK_CA_InvokeServiceFinal', - 'CK_AES_GCM_PARAMS', 'CK_CA_ConfigureRemotePED', - 'LUNA_RET_CL_TRANSMISSION_ERROR', - 'LUNA_RET_OBJECT_HANDLE_INVALID', - 'CA_HAAnswerLoginChallenge', 'CK_FLAGS', - 'CK_CA_MultisignValue', 'CA_SetHSMPolicies', - 'RC_FAILED_TO_CREATE_THREAD', 'LUNA_RET_KEY_NOT_ACTIVE', - 'HANDLE', 'CK_CA_STCDeregister', 'CA_UnloadModule', - 'LUNA_RET_DATA_INVALID', 'CK_XOR_BASE_DATA_KDF_PARAMS_PTR', - 'Float64', 'CK_CA_GetContainerStatus', 'CA_HAActivateMofN', - 'LUNA_RET_PED_DEK_INVALID', 'CK_CA_HAInit', 'Int', - 'CA_LKMReceiverResponse', 'LUNA_RET_LOG_RESYNC_NEEDED', - 'CK_CA_SpRawWrite', 'CK_XOR_BASE_DATA_KDF_PARAMS', - 'LUNA_RET_TUK_PARAMETER_MISSING', 'CK_OTP_PARAM_PTR', - 'CK_C_InitPIN', 'RC_SOCKET_ERROR', 'CK_RC2_PARAMS_PTR', - 'LUNA_RET_HIFN6500_RESET_TIMEOUT', - 'CA_GetNumberOfAllowedContainers', 'LUNA_RET_N_TOO_LARGE', - 'RC_SSL_WANT_WRITE_ERROR', 'CK_CA_GetHAState', - 'CK_CA_InitAudit', 'C_CloseAllSessions', - 'LUNA_RET_KEY_PARITY', 'RC_SSL_GET_CERTIFICATE_ERROR', - 'CA_InitAudit', 'CK_OTP_PARAMS_PTR', 'CA_M_OF_N_STATUS', - 'C_SignUpdate', 'CK_SKIPJACK_RELAYX_PARAMS_PTR', - 'LUNA_RET_STATE_UNSAVEABLE', 'CK_C_VerifyRecoverInit', - 'LUNA_RET_MAC_MISSING', 'C_VerifyRecover', - 'CA_GetModuleInfo', - 'LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID', - 'CK_TLS_PRF_PARAMS', 'LUNA_RET_OPERATION_RESTRICTED', - 'PointerDifference', 'LUNA_RET_SM_UNKNOWN_ACCESS_TYPE', - 'MSG_RTC_CANT_INITIALIZE_I2C', - 'LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL', - 'CK_SSL3_RANDOM_DATA', - 'LUNA_RET_STORAGE_TYPE_INCONSISTENT', 'CK_C_GetInfo', - 'C_InitPIN', 'CK_C_Login', 'CK_WTLS_KEY_MAT_PARAMS', - 'CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR', - 'CK_CA_GetExtendedTPV', 'CA_GetObjectHandle', - 'CK_C_Decrypt', 'CA_GetRemotePEDVectorStatus', - 'CK_C_GetFunctionList', - 'LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE', - 'LUNA_RET_TOKEN_LOCKED_OUT_PM', 'LUNA_RET_HIFN_DMA_ERROR', - 'LUNA_RET_CANCEL', 'LUNA_RET_RNG_SELF_TEST_FAILURE', - 'CK_CA_TokenDelete', 'CK_SLOT_ID', 'CK_CA_LogGetStatus', - 'CK_CA_FindAdminSlotForSlot', 'CA_CapabilityUpdate', - 'CA_GetExtendedTPV', 'CK_C_DigestEncryptUpdate', - 'CK_CA_IsMofNRequired', 'CA_FirmwareUpdate', - 'RC_CERT_TYPE_INVALID', 'C_VerifyRecoverInit', - 'LUNA_RET_PED_CLIENT_NOT_RUNNING', - 'LUNA_RET_HIFN6500_RNG_UNDERFLOW', 'RC_OBJECT_NOT_IN_LIST', - 'CK_HA_MEMBER_PTR', 'CA_SetApplicationID', - 'LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE', 'CT_Token', - 'C_DigestKey', 'CK_C_OpenSession', - 'LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT', - 'MSG_TVK_TIMESTAMP_CORRUPTED', - 'LUNA_RET_MM_INVALID_HANDLE', 'CK_CA_LogExternal', - 'SInt16', 'CA_IndirectLogin', - 'LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT', - 'LUNA_RET_INVALID_PRIVATE_KEY_TYPE', 'CA_SIMExtract', - 'CK_CA_CloseSecureToken', 'CK_SKIPJACK_RELAYX_PARAMS', - 'CA_SetDestructiveHSMPolicy', 'CK_C_FindObjectsInit', - 'CA_OpenSecureToken', - 'LUNA_RET_WRAPPING_KEY_HANDLE_INVALID', - 'LUNA_RET_SM_UNKNOWN_COMMAND', - 'CK_RSA_PKCS_OAEP_SOURCE_TYPE', 'CK_UNLOCKMUTEX', - 'CK_CA_GetNumberOfAllowedContainers', 'CK_OTP_PARAM', - 'LUNA_RET_INVALID_FUF_TARGET', 'LUNA_RET_ARGUMENTS_BAD', - 'C_DigestEncryptUpdate', - 'RC_MANUFACTURING_TOKEN_NOT_PRESENT', 'RC_SLOT_ID_INVALID', - 'CK_CA_MTKResplit', 'LUNA_INVALID_PACKET_LAYOUT', - 'CK_OTP_PARAMS', 'SInt8', 'CK_CA_GetFunctionList', - 'LastFirmwareCode', 'LUNA_RET_MD2_SELF_TEST_FAILURE', - 'RC_PARTITION_LOCKED', 'CA_GetSecureElementMeta', - 'CK_CA_CloneAsTarget', 'CK_CA_RetrieveLicenseList', - 'CK_CA_HALogin', 'LUNA_RET_NOT_FOUND', - 'CK_C_SetOperationState', - 'MSG_RTC_CONFIGURATION_CORRUPTED', - 'CK_CA_InvokeServiceInit', 'LUNA_RET_SAVED_STATE_INVALID', - 'CA_CloneAsSource', 'CK_ECMQV_DERIVE_PARAMS', - 'CK_CA_LKMReceiverComplete', 'CA_InvokeServiceSinglePart', - 'CK_KDF_PRF_ENCODING_SCHEME', 'LUNA_RET_MAX_OBJECT_COUNT', + 'LUNA_RET_MISSING_VALUE_FOR_N', 'CK_X9_42_DH_KDF_TYPE', + 'CK_INFO', 'CA_HAActivateMofN', 'CK_CA_MultisignValue', + 'CA_GetHSMCapabilitySet', 'LUNA_RET_KEY_NOT_ACTIVE', + 'LUNA_RET_SM_DATA_INVALID', 'CK_KIP_PARAMS', + 'LUNA_RET_LOG_RESYNC_NEEDED', 'CK_CA_SpRawWrite', + 'CK_OTP_PARAM_PTR', 'CK_X9_42_MQV_DERIVE_PARAMS', + 'LUNA_RET_N_TOO_LARGE', 'CK_CA_GetHAState', + 'C_CloseAllSessions', 'CK_CA_STCSetKeyActivationTimeOut', + 'C_SignInit', 'LUNA_RET_MISSING_NUMBER_OF_VECTORS', + 'CK_CMS_SIG_PARAMS', 'CA_GetRemotePEDVectorStatus', + 'CK_C_GetFunctionList', 'LUNA_RET_CANCEL', + 'LUNA_RET_RNG_SELF_TEST_FAILURE', 'CK_CA_LogGetStatus', + 'LUNA_RET_HIFN6500_RNG_UNDERFLOW', 'CK_C_OpenSession', + 'LUNA_RET_TOO_MANY_WEIGHTS', 'CA_IndirectLogin', + 'CA_OpenSecureToken', 'LUNA_RET_INVALID_FUF_TARGET', + 'CA_GenerateMofN', 'CK_CA_MTKResplit', + 'LUNA_RET_MD2_SELF_TEST_FAILURE', 'CA_HALogin', + 'CK_CA_RetrieveLicenseList', + 'LUNA_RET_SAVED_STATE_INVALID', 'CK_ECMQV_DERIVE_PARAMS', + 'CK_CA_LKMReceiverComplete', 'CA_InitSlotRolePIN', 'CA_MOFN_ACTIVATION_PTR', - 'MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS', - 'LUNA_RET_M_TOO_LARGE', 'UInt16', - 'LUNA_RET_CB_HIOS_HANDLE_INVALID', 'RC_PIN_INVALID', - 'CK_CA_SetHSMPolicy', 'RC_SOCKET_CLOSED', - 'CK_CA_LockClusteredSlot', 'RC_ENDOFLIST', 'UInt32', - 'LUNA_RET_LOG_NO_KCV', 'CK_C_DecryptInit', - 'LUNA_RET_DAC_POLICY_PID_MISMATCH', 'CK_CA_GetTokenStatus', - 'LUNA2_RET_HIFN_RESET_ERROR', 'RC_UNEXPECTED', - 'LUNA_RET_HIFN6500_ALU_TIMEOUT', 'CK_C_InitToken', - 'CA_InvokeServiceFinal', 'CK_CA_EncodeECParamsFromFile', - 'CA_LockClusteredSlot', 'LUNA_RET_SM_NOT_LOGGED_IN', - 'CK_CA_SIMInsert', 'CK_CA_RestartForContainer', - 'LUNA_RET_MISSING_COMMAND_PARAMETER', - 'LUNA_RET_KEY_EXTRACTABLE', - 'LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE', 'CA_FactoryReset', - 'CA_LoadEncryptedModule', 'CA_SetUserContainerName', - 'CK_TLS_PRF_PARAMS_PTR', - 'MSG_RTC_MSG_NVRAM_ZAPPING_FAILED', - 'CK_CA_InsertMaskedObject', 'RC_MEMORY_ALLOCATION', - 'CK_CA_OpenSecureToken', 'LUNA_RET_SM_PIN_EXPIRED', - 'C_VerifyFinal', 'C_DeriveKey', 'C_OpenSession', - 'CK_CA_SetUserContainerName', 'RC_OBJECT_ALREADY_EXISTS', - 'LUNA_RET_SM_SESSION_REALLOC_ERROR', - 'MSG_ZEROIZING_AFTER_DECOMMISSION', 'CA_MOFN_ACTIVATION', - 'MSG_GENERATING_NEW_TVK_PASSED', 'C_Sign', - 'LUNA_RET_HIFN_INVALID_MAC_ALGORITHM', - 'CA_WaitForSlotEvent', 'CA_ChoosePrimarySlot', - 'CK_TOKEN_INFO', 'RC_BUFFER_TOO_SMALL', - 'RC_CLIENT_DISCONNECTED', 'CK_ECDH1_DERIVE_PARAMS_PTR', - 'LUNA_RET_INVALID_BOARD_TYPE', 'LUNA_RET_UNWRAPPING_ERROR', - 'RC_SERVER_DISCONNECTED', 'LUNA_RET_CB_PROT_DATA_INVALID', - 'LUNA_RET_LICENSE_ID_UNKNOWN', - 'LUNA_RET_KCDSA_PARAM_GEN_FAILURE', - 'CK_C_CloseAllSessions', 'LUNA_RET_CL_ALIGNMENT_ERROR', + 'LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED', + 'CA_GetFunctionList', 'LUNA_RET_HIFN6500_ALU_TIMEOUT', + 'LUNA_RET_SM_NOT_LOGGED_IN', 'CK_TLS_PRF_PARAMS_PTR', + 'MSG_RTC_MSG_NVRAM_ZAPPING_FAILED', 'RC_MEMORY_ALLOCATION', + 'CA_GetHSMStorageInformation', + 'LUNA_RET_HIFN_DESTINATION_OVERRUN', + 'LUNA_RET_ISES_LNAU_TEST_FAILED', + 'LUNA_RET_SM_SESSION_REALLOC_ERROR', 'CA_MOFN_ACTIVATION', + 'MSG_GENERATING_NEW_TVK_PASSED', + 'LUNA_RET_DES_SELF_TEST_FAILURE', + 'LUNA_RET_UNWRAPPING_ERROR', + 'LUNA_RET_TIME_NOT_INITIALIZED', 'LUNA_RET_HIFN_DMA_INVALID_REVISION', - 'LUNA_RET_TOKEN_NOT_PRESENT', 'CK_VOID_PTR_PTR', - 'CK_RSA_PKCS_PSS_PARAMS_PTR', 'CK_USER_TYPE', - 'C_DigestUpdate', 'C_GetMechanismList', 'CA_ResetDevice', - 'CK_C_DigestFinal', 'LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO', - 'LUNA_RET_SM_BAD_CONTEXT_NUMBER', 'RC_OPERATION_TIMED_OUT', - 'LUNA_RET_CL_COMMAND_MALFORMED', 'LUNA_RET_SFNT3120_ERROR', - 'LUNA_RET_LOG_BAD_RECORD_HMAC', 'CKCA_MODULE_ID', - 'LUNA_RET_MECHANISM_PARAM_INVALID', - 'LUNA_RET_SIM_VERSION_UNSUPPORTED', 'CK_CA_LoadModule', - 'LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION', - 'RC_UNKNOWN_COMMAND_VERSION', 'RC_CLIENT_MESSAGE_ERROR', - 'LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE', - 'CK_ARIA_CTR_PARAMS', 'C_GetAttributeValue', - 'CK_CA_GetTime', 'MSG_ZEROIZING_AFTER_NO_SECURE_DATA', - 'CA_OpenApplicationID', 'LUNA_RET_TEMPLATE_INCOMPLETE', - 'LUNA_RET_CB_MUST_READ', 'LUNA_RET_WRAPPING_ERROR', - 'LUNA_RET_CCM_NOT_PRESENT', 'CA_ReadCommonStore', - 'CK_CA_GenerateCloningKEV', 'MSG_RTC_CANT_ACCESS', - 'CA_SwitchSecondarySlot', 'CK_CAMELLIA_CTR_PARAMS', - 'eInitMsgs', 'LUNA_RET_RETRY', - 'LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', - 'CA_LogVerifyFile', - 'RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR', 'CA_Restart', - 'CK_HA_MEMBER', 'CK_EC_ENC_SCHEME', - 'CK_C_INITIALIZE_ARGS_PTR', 'CK_CA_SetLKCV', - 'LUNA_RET_CB_HIOS_CANCELED', 'CK_MECHANISM_INFO_PTR', - 'CA_DuplicateMofN', 'CK_CA_GetModuleList', - 'LUNA_RET_CB_REMOTE_ABORT', 'CK_MAC_GENERAL_PARAMS', - 'LUNA_RET_TOKEN_LOCKED_OUT_SM', 'LUNA_RET_OK', - 'CK_AES_CBC_PAD_INSERT_PARAMS_PTR', 'C_GetFunctionStatus', - 'CK_CA_PerformModuleCall', 'CA_GetClusterState', - 'LUNA_RET_SIGNATURE_LEN_RANGE', 'CK_C_SignRecoverInit', - 'MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF', - 'C_GenerateKey', 'RC_DER_CLASS_INVALID', - 'CK_CA_SetExtendedTPV', 'CA_RetrieveLicenseList', - 'CK_CA_CloseSecondarySession', 'CK_CA_ResetDevice', - 'CA_DismantleRemotePED', 'CK_CA_FirmwareUpdate', - 'LUNA_RET_CB_HANDLE_INVALID', 'CA_ResetPIN', - 'CK_CA_GetHSMPolicySet', 'CK_CA_MTKRestore', - 'CK_OBJECT_CLASS', 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS', - 'CK_UTF8CHAR_PTR', 'CK_WTLS_KEY_MAT_OUT_PTR', - 'LUNA_RET_CONTAINER_LOCKED', - 'MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING', - 'CK_AES_GMAC_PARAMS', 'CK_OBJECT_HANDLE', - 'LUNA_RET_NOT_READY', 'CK_PBE_PARAMS_PTR', - 'LUNA_RET_ISES_TEST_VS_BSAFE_FAILED', 'C_SeedRandom', - 'swapper', 'CK_X9_42_DH_KDF_TYPE', 'Word', - 'LUNA_RET_SM_TSV_MISSING', 'C_WrapKey', - 'LUNA_RET_TOKEN_LOCKED_OUT', 'CK_CA_FirmwareRollback', - 'RC_GENERAL_ERROR', 'CA_RestartForContainer', 'Boolean', - 'LUNA_RET_KEY_HANDLE_INVALID', 'LUNA_RET_RNG_ERROR', - 'RC_OPERATION_WOULD_BLOCK', 'CK_DES_CTR_PARAMS', - 'C_PerformSelfTest', 'CK_CA_GetTokenCertificates', - 'RC_PARTITION_NOT_ACTIVATED', 'CK_CA_CapabilityUpdate', - 'LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE', - 'CK_ATTRIBUTE_TYPE', 'LUNA_RET_CB_HIOS_ID_INVALID', - 'CA_CloneMofN', 'CA_MTKGetState', 'CK_C_Verify', - 'CK_SESSION_HANDLE', 'CK_CA_GetMofNStatus', - 'CK_CA_GetRollbackFirmwareVersion', - 'CK_CA_WriteCommonStore', 'CA_GetPedId', - 'CK_OTP_PARAM_TYPE', 'LUNA_RET_VECTOR_DUPLICATE', - 'LUNA_RET_PE1746_ERROR', 'CA_InitIndirectToken', - 'CK_CA_GetContainerCapabilitySetting', 'CK_C_GetSlotInfo', - 'CK_CA_TokenInsert', 'CK_CA_GenerateMofN', - 'RC_SESSION_SCRIPT_EXISTS', 'CK_CA_GetPrimarySlot', - 'LUNA_RET_CITS_DAK_MISSING', - 'CA_SetDestructiveHSMPolicies', + 'RC_OPERATION_TIMED_OUT', + 'LUNA_RET_SIM_VERSION_UNSUPPORTED', + 'RC_UNKNOWN_COMMAND_VERSION', + 'LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE', 'CK_CA_GetTime', + 'LUNA_RET_CCM_NOT_PRESENT', 'Word', 'CA_LogVerifyFile', + 'CK_DES_CTR_PARAMS', 'CA_GetClusterState', 'CK_C_Verify', + 'CK_CA_STCGetCipherAlgorithm', 'CA_STCGetMaxSessions', + 'CK_OBJECT_HANDLE', 'LUNA_RET_TOKEN_LOCKED_OUT', + 'CK_MAC_GENERAL_PARAMS', 'CK_C_VerifyUpdate', + 'CK_CA_WriteCommonStore', 'CA_GetPedId', 'CA_Insert', 'LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE', - 'LUNA_RET_UNKNOWN_COMMAND', 'CA_LogExternal', - 'CA_ClonePrivateKey', 'CK_AES_CBC_PAD_INSERT_PARAMS', - 'CK_EC_MAC_SCHEME', 'CK_C_GetMechanismInfo', - 'CK_MECHANISM_TYPE_PTR', 'CK_CA_GetTokenCertificateInfo', - 'LUNA_RET_TSN_MISMATCH', 'RC_FILE_LOCK_FAILED', - 'LUNA_RET_SP_RX_ERROR', 'RC_UNKNOWN_COMMAND', - 'C_CancelFunction', 'CK_HA_STATUS', - 'CK_CA_STCGetClientInfo', 'MSG_RTC_ZEROIZED_ON_POWER_LOSS', - 'LUNA_RET_CONTAINER_IS_DISABLED', - 'RC_LISTEN_SOCKET_INVALID', 'LUNA_RET_ECC_DAC_MISSING', - 'CK_C_DigestKey', 'C_GetInfo', 'C_Initialize', - 'RC_INVALID_COMMAND', 'C_DestroyObject', - 'C_GetOperationState', 'LUNA_RET_TOO_MANY_CONTAINERS', - 'LUNA_RET_ROOT_CERT_MISSING', - 'LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED', - 'LUNA_RET_WRAPPED_KEY_INVALID', 'CA_DeleteContainer', - 'CA_GetContainerPolicySetting', 'C_InitToken', - 'CK_C_WrapKey', 'LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL', - 'LUNA_RET_RM_ELEMENT_VALUE_INVALID', - 'LUNA_RET_VECTOR_TOO_SMALL', - 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR', - 'RC_SOCKET_WRITE_ERROR', + 'CK_EC_MAC_SCHEME', 'LUNA_RET_TSN_MISMATCH', + 'RC_FILE_LOCK_FAILED', 'RC_UNKNOWN_COMMAND', + 'CK_CA_STCGetClientInfo', 'LUNA_RET_ECC_DAC_MISSING', + 'CA_ConfigureRemotePED', 'CA_STCGetPubKey', + 'LUNA_RET_WRAPPED_KEY_INVALID', 'CK_C_WrapKey', 'MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY', 'CA_SpRawWrite', - 'LUNA_RET_CCM_SIGN_INVALID', 'C_Login', 'C_GetSlotInfo', - 'CK_CA_InitIndirectPIN', 'CA_DeleteRemotePEDVector', - 'CK_CA_CloneAllObjectsToSession', - 'CK_CA_UnlockClusteredSlot', 'CK_CA_GetTokenCapabilities', - 'MSG_TVK_TIMESTAMP_UPDATE_FAILED', - 'LUNA_RET_ISES_CMD_PARAMETER_INVALID', - 'CK_CA_CloneModifyMofN', 'CK_KDF_PRF_PARAMS', - 'LUNA_RET_UM_PIN_INCORRECT', 'C_GetSlotList', - 'LUNA_RET_INVALID_CERTIFICATE_VERSION', 'CK_ULONG', - 'CK_SSL3_KEY_MAT_OUT_PTR', 'C_GetMechanismInfo', - 'CK_C_GenerateRandom', 'CK_CA_ActivateMofN', - 'CK_WTLS_RANDOM_DATA', 'CA_MTKResplit', 'CK_CHAR', - 'CA_HALogin', 'CA_GetHSMStats', 'LUNA_RET_BAD_PPID', - 'CK_STATE', 'UInt8', 'CK_CA_GetHSMCapabilitySetting', - 'CK_KEY_WRAP_SET_OAEP_PARAMS', - 'LUNA_RET_USER_TYPE_INVALID', - 'LUNA_RET_VECTOR_VERSION_INVALID', 'CA_GetPrimarySlot', - 'CK_CA_GetConfigurationElementDescription', - 'LUNA_RET_MM_FATAL_ERROR', 'LUNA_RET_ATTRIBUTE_SENSITIVE', + 'CK_KDF_PRF_PARAMS', 'CK_ULONG', + 'RC_STC_RESPONSE_DECRYPT_ERROR', 'CA_GetPrimarySlot', + 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR', + 'CK_X9_42_DH1_DERIVE_PARAMS', 'LUNA_RET_HIFN_DMA_TIMED_OUT', - 'CK_CA_CloneObjectToAllSessions', 'RC_VERSION_INVALID', - 'LUNA_RET_SHA_SELF_TEST_FAILURE', - 'LUNA_RET_MISSING_WEIGHT_VALUE', 'CA_MultisignValue', - 'LUNA_RET_SIGNATURE_INVALID', - 'LUNA_RET_M_OF_N_IS_NOT_REQUIRED', - 'LUNA_RET_CONTAINER_HANDLE_INVALID', - 'LUNA_RET_HIFN_NOT_PRESENT', - 'LUNA_RET_TOO_MANY_VECTORS_PROVIDED', - 'CK_CMS_SIG_PARAMS_PTR', 'CK_CA_CheckOperationState', - 'CK_CA_Zeroize', 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS', - 'LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID', - 'LUNA_RET_LOG_FILE_NOT_OPEN', 'CK_CA_GetContainerList', - 'CK_WTLS_KEY_MAT_PARAMS_PTR', 'LUNA_RET_ECC_HOC_MISSING', - 'LUNA_RET_KEY_NOT_UNWRAPPABLE', 'LUNA_RET_CCM_UNREMOVABLE', - 'CK_CA_InitIndirectToken', 'CA_GetTSV', - 'CA_InitIndirectPIN', - 'LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS', - 'LUNA_RET_SIM_AUTHORIZATION_FAILED', 'CK_CA_SetPedId', - 'CA_GenerateMofN', 'CK_CA_DeactivateMofN', 'C_EncryptInit', - 'C_Verify', 'CK_CA_Extract', 'LUNA_RET_SFNT3120_CRC', - 'CA_CloseApplicationIDForContainer', - 'CK_CA_GetHSMStorageInformation', 'CK_C_GenerateKeyPair', + 'LUNA_RET_MISSING_WEIGHT_VALUE', 'Float', + 'CK_DESTROYMUTEX', 'LUNA_RET_HIFN_NOT_PRESENT', + 'LUNA_RET_TOO_MANY_VECTORS_PROVIDED', 'CK_C_DigestFinal', + 'CA_InitIndirectPIN', 'LUNA_RET_PED_DEK_INVALID', + 'CK_CA_DeactivateMofN', 'CK_CA_STCGetPubKey', 'RC_USB_PED_TOO_MANY_CONNECTED', 'CA_SpRawRead', - 'RC_SOCKET_READ_ERROR', 'MSG_BAD_HMAC', 'CA_DestroyMultipleObjects', 'LUNA_RET_CCM_TOO_LARGE', - 'SInt64', 'CK_CA_GetHSMCapabilitySet', 'CK_C_SignFinal', - 'CK_CA_GetContainerPolicySet', 'RC_INVALID_CERT_HOST', - 'C_SignFinal', 'LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE', - 'CA_SIMMultiSign', 'LUNA_RET_INVALID_CERTIFICATE_DATA', - 'LUNA_RET_LOG_FILE_WRITE_ERROR', 'CK_C_FindObjectsFinal', - 'CK_C_GenerateKey', 'SizeType', 'LUNA_RET_M_TOO_SMALL', - 'Byte', 'CA_UnlockClusteredSlot', 'CK_CA_CloneAsSource', - 'CK_C_GetSlotList', 'CK_FUNCTION_LIST_PTR', - 'LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD', - 'LUNA_RET_FORMER_INVALID_ENTRY_TYPE', 'SInt', - 'LUNA_RET_KEY_NOT_WRAPPABLE', 'RC_FILE_ERROR', - 'CK_AES_CTR_PARAMS_PTR', - 'LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST', - 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE', 'CK_USHORT_PTR', - 'LUNA_RET_HIFN_INVALID_PAD_ALGORITHM', - 'CK_C_DecryptVerifyUpdate', 'CK_PKCS5_PBKD2_PARAMS_PTR', - 'C_CreateObject', 'RC_RC_ERROR', - 'LUNA_RET_OH_OBJECT_TYPE_INVALID', 'CA_ActivateMofN', - 'CK_RSA_PKCS_MGF_TYPE', 'LUNA_RET_TWC_PARAMETER_MISSING', - 'LUNA_RET_AES_SELF_TEST_FAILURE', 'CK_EXTRACT_PARAMS', - 'CKCA_MODULE_INFO', 'RC_OK', - 'LUNA_RET_OH_OBJECT_VERSION_INVALID', 'C_GetSessionInfo', + 'CK_C_GetSlotList', 'RC_OBJECT_ID_INVALID', + 'CA_GetTokenStorageInformation', 'SInt8', + 'RC_STC_CIPHER_SUITE_REJECTED', 'CK_DES_CTR_PARAMS_PTR', + 'LUNA_RET_TWC_PARAMETER_MISSING', 'CK_CA_STCGetState', 'LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST', - 'CK_SFNT_CA_FUNCTION_LIST', 'LUNA_RET_CB_REMOTE_CLOSED', - 'CK_RC5_PARAMS', 'CA_LogVerify', - 'LUNA_RET_MM_ITERATOR_PAST_END', 'CK_RC5_CBC_PARAMS_PTR', - 'CK_CA_OpenApplicationID', 'CK_AES_GMAC_PARAMS_PTR', + 'LUNA_RET_MM_ITERATOR_PAST_END', 'CK_RC5_MAC_GENERAL_PARAMS', 'CK_CA_InvokeService', - 'CK_CAMELLIA_CTR_PARAMS_PTR', - 'CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR', - 'MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF', - 'LUNA_RET_SM_SESSION_HANDLE_INVALID', 'CA_MTKSetStorage', - 'RC_FAILED_TO_CREATE_PROCESS', 'CA_GetHSMCapabilitySet', - 'LUNA_RET_HOC_MISSING', 'CA_GetHSMPolicySetting', - 'LUNA_RET_LOG_BAD_FILE_NAME', 'CK_OTP_SIGNATURE_INFO_PTR', - 'LUNA_RET_CAST3_SELF_TEST_FAILURE', 'CK_SEED_CTR_PARAMS', - 'CK_CA_TokenZeroize', 'CK_ResetTotalOperations', - 'LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS', - 'MSG_TVK_TIMESTAMP_IS_TOO_OLD', 'CA_MOFN_GENERATION_PTR', - 'CK_CA_InitSlotRolePIN', 'CK_AES_GCM_PARAMS_PTR', + 'LUNA_RET_SM_SESSION_HANDLE_INVALID', 'CK_SEED_CTR_PARAMS', + 'MSG_TVK_TIMESTAMP_IS_TOO_OLD', 'RC_FUNCTION_NOT_SUPPORTED', 'LUNA_RET_SPLIT_DATA_INVALID', - 'LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL', - 'CK_LKM_TOKEN_ID', 'LUNA_RET_ECC_RESULT_AT_INF', - 'LUNA_RET_CB_HIOS_STATE_INVALID', - 'CK_CA_TokenInsertNoAuth', 'MSG_TVK_WAS_CORRUPTED', - 'CA_CloneObjectToAllSessions', 'CA_Insert', - 'CK_CA_SIMMultiSign', 'CK_CA_ChoosePrimarySlot', - 'CK_CA_OpenApplicationIDForContainer', - 'CK_KEY_DERIVATION_STRING_DATA_PTR', - 'LUNA_RET_CB_NOT_SUPPORTED', - 'CK_CA_EnableUnauthTokenInsertion', + 'CK_LKM_TOKEN_ID', 'CA_CloneObjectToAllSessions', + 'LUNA_RET_CB_NOT_SUPPORTED', 'CA_ListSecureTokenUpdate', 'LUNA_RET_HIFN6500_DATA_LINES_BROKEN', 'MSG_RESYNC', - 'LUNA_RET_CHALLENGE_RESPONSE_INCORRECT', - 'CK_CA_LogSetConfig', 'CK_CA_IndirectLogin', - 'CK_CA_InvokeServiceAsynch', - 'RC_MANUFACTURING_SERIAL_NUMBER_INVALID', - 'LUNA_RET_TEST_VS_BSAFE_FAILED', 'CK_CA_GetTokenPolicies', - 'LUNA_RET_CERT_VERSION_NOT_SUPPORTED', + 'CA_MTKSetStorage', 'MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET', - 'CK_KIP_PARAMS', 'LUNA_RET_POLICY_NOT_FOUND', - 'LUNA_RET_INCOMPATIBLE', 'RC_SOCKET_BAD_FD', - 'LUNA_RET_SM_UNKNOWN_SESSION_TYPE', - 'LUNA_RET_SM_SESSION_READ_ONLY_EXISTS', - 'LUNA_RET_DEVICE_TIMEOUT', - 'LUNA_RET_SECURITY_PARAMETER_MISSING', 'MSG_LAST', - 'LUNA_RET_ENCRYPTED_DATA_INVALID', 'CK_PKCS5_PBKD2_PARAMS', - 'CK_C_Logout', 'CK_MECHANISM_TYPE', - 'CK_DES_CBC_ENCRYPT_DATA_PARAMS', 'CK_USHORT', - 'LUNA_RET_SEED_SELF_TEST_FAILURE', 'CA_SetMofN', + 'LUNA_RET_INCOMPATIBLE', 'RC_STC_UNEXPECTED_DH_DATA_SIZE', + 'LUNA_RET_SECURITY_PARAMETER_MISSING', + 'LUNA_RET_ENCRYPTED_DATA_INVALID', 'CA_SetMofN', 'LUNA_RET_INVALID_CERTIFICATE_TYPE', 'CK_CA_SetContainerPolicies', 'LUNA_RET_LOG_FULL', - 'CK_CLUSTER_STATE', 'LUNA_RET_MISSING_SPLITS', - 'LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL', - 'LUNA_RET_KEY_SENSITIVE', - 'MSG_RTC_EXTERNAL_TAMPER_DETECTED', - 'CA_CloseApplicationID', 'C_DecryptFinal', - 'CA_CloneModifyMofN', 'CK_CA_LoadEncryptedModule', - 'CK_LOCKMUTEX', 'LUNA_RET_HIFN6500_RNG_FAILED', - 'LUNA_RET_FLAGS_INVALID', - 'MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED', - 'LUNA_RET_TOO_MANY_WEIGHTS', 'CK_CA_SetContainerPolicy', - 'CK_ECIES_PARAMS', 'LUNA_RET_USER_ALREADY_ACTIVATED', - 'RC_INVALID_ENUM_OPTION', 'LUNA_RET_USER_NOT_LOGGED_IN', - 'LUNA_RET_INVALID_IP_PACKET', 'CA_SetTPV', 'CK_C_Finalize', - 'LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS', - 'CK_CA_RoleStateGet', 'CK_SFNT_CA_FUNCTION_LIST_PTR_PTR', - 'CK_CA_MTKSetStorage', 'CKA_SIM_AUTH_FORM', - 'CK_CA_LKMInitiatorChallenge', 'CK_CA_HAActivateMofN', - 'CK_KEY_DERIVATION_STRING_DATA', - 'LUNA_RET_COUNTER_WRAPAROUND', - 'LUNA_RET_INVALID_ENTRY_TYPE', 'CK_C_SignRecover', - 'LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE', - 'MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED', - 'CK_HW_FEATURE_TYPE', 'CA_SetTokenCertificateSignature', - 'CA_GetUserContainerName', 'RC_POINTER_INVALID', - 'RC_NOT_HSM_BACKUP_TOKEN', 'CK_C_CreateObject', - 'CK_CA_ExtractMaskedObject', 'CK_C_GetFunctionStatus', - 'CA_ROLE_STATE', 'CK_CA_UnloadModule', - 'LUNA_RET_SM_BAD_ACCESS_HANDLE', - 'MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS', - 'CK_CA_HAGetMasterPublic', 'CK_PRF_KDF_PARAMS', - 'CK_CA_Deactivate', 'CA_GetTokenCertificates', - 'LUNA_RET_ECC_POINT_INVALID', 'RC_SOCKET_ADDRESS_INVALID', - 'LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN', 'CA_MTKRestore', - 'CK_CLUSTER_STATE_PTR', 'CK_C_GetTokenInfo', - 'LUNA_RET_CB_HIOS_IO_ERROR', - 'CA_CloseAllSecondarySessions', 'CA_CheckOperationState', - 'LUNA_RET_M_OF_N_SECRET_INVALID', 'CK_RSA_PKCS_PSS_PARAMS', - 'LUNA_RET_SP_TX_ERROR', 'C_GetTokenInfo', - 'LUNA_RET_SM_UNKNOWN_TOSM_STATE', 'CK_CA_SetTokenPolicies', - 'RC_SOCKET_ADDRESS_IN_USE', - 'LUNA_RET_CL_COMMAND_NON_BACKUP', 'CK_CA_SetRDK', - 'CA_ListSecureToken', 'CK_SSL3_KEY_MAT_PARAMS', - 'RC_NOT_PARTITION_BACKUP_TOKEN', + 'CK_CLUSTER_STATE', 'CK_C_CreateObject', + 'CK_CA_STCIsEnabled', 'CA_CloneModifyMofN', + 'CK_C_DecryptFinal', 'LUNA_RET_FLAGS_INVALID', + 'CK_CA_SetContainerPolicy', 'RC_STC_SESSION_INVALID', + 'eInitMsgs', 'LUNA_RET_COUNTER_WRAPAROUND', + 'MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED', 'CA_GetFPV', + 'CK_HA_MEMBER_PTR', 'LUNA_RET_VECTOR_TYPE_INVALID', + 'C_Digest', 'CK_CA_SetRDK', 'LUNA_RET_RC4_SELF_TEST_FAILURE', - 'LUNA_RET_HIFN_INVALID_ENCRYPT_MODE', 'CK_CA_GetHSMStats', - 'CK_OTP_SIGNATURE_INFO', - 'LUNA_RET_M_OF_N_IS_NOT_INITIALZED', - 'LUNA_RET_CB_REMOTE_ABANDONED', 'CA_ChooseSecondarySlot', - 'LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID', - 'RC_SEMAPHORE_ERROR', 'LUNA_RET_CB_PARAM_INVALID', - 'CA_GetFunctionList', 'CK_C_DeriveKey', - 'CA_OpenApplicationIDForContainer', - 'LUNA_RET_DSA_PARAM_GEN_FAILURE', 'CK_KEY_TYPE', - 'CK_C_DecryptFinal', 'UInt', 'CA_GetObjectUID', - 'LUNA_RET_PED_UNSUPPORTED_PROTOCOL', 'CK_CA_ManualKCV', - 'LUNA_RET_TIMEOUT', 'CK_RC2_MAC_GENERAL_PARAMS_PTR', - 'CK_CA_GetSessionInfo', 'RC_CACHE_NOT_MAPPED', - 'CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR', - 'LUNA_RET_SFNT3120_SELFTEST_FAILED', - 'LUNA_RET_TOKEN_LOCKED_OUT_OH', 'C_SignEncryptUpdate', - 'RC_SHUTTING_DOWN', 'CA_DeleteContainerWithHandle', - 'CK_CA_GetSecondarySlot', 'CK_CA_DuplicateMofN', - 'RC_UNKNOWN_CALLBACK_COMMAND', - 'CK_CA_GetTokenObjectHandle', - 'LUNA_RET_CPK_PARAMETER_MISSING', - 'LUNA_RET_INVALID_MODULUS_SIZE', 'CK_RC5_PARAMS_PTR', - 'CK_KEA_DERIVE_PARAMS', 'CK_C_DigestInit', - 'LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID', - 'CA_ModifyMofN', 'CA_CloneObject', - 'CK_CA_STCGetClientsList', 'C_DecryptUpdate', - 'CK_CA_STCGetPubKey', 'LUNA_RET_CHALLENGE_NOT_REQUIRED', - 'MSG_RTC_CANT_GET_TAMPER_TIMER', - 'LUNA_RET_KEY_INVALID_FOR_OPERATION', 'CK_CA_CloneObject', + 'CA_HAAnswerLoginChallenge', 'BYTE', + 'CK_CA_GetSessionInfo', + 'RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR', + 'C_SignEncryptUpdate', 'RC_SHUTTING_DOWN', + 'CK_MECHANISM_TYPE_PTR', 'MSG_RTC_CANT_GET_TAMPER_TIMER', 'LUNA_RET_RM_BAD_HSM_PARAMS', - 'LUNA_RET_INVALID_CERTIFICATE_FUNCTION', - 'CK_CA_GetContainerPolicySetting', - 'CK_CA_LKMReceiverResponse', 'Int64', - 'CA_InvokeServiceInit', 'LUNA_RET_SM_DATA_INVALID', - 'CA_GetTime', 'CK_TOKEN_INFO_PTR', - 'LUNA_RET_VECTOR_TYPE_INVALID', 'CK_SESSION_INFO', + 'CK_XOR_BASE_DATA_KDF_PARAMS_PTR', 'CK_SESSION_INFO', 'LUNA_RET_SM_MEMORY_ALLOCATION_ERROR', - 'RC_ASSIGNING_SAME_VALUE', - 'LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED', - 'LUNA_RET_ISES_CMD_FAILED', - 'CK_CA_SetTokenCertificateSignature', - 'LUNA_RET_CCM_NOT_SUPPORTED', 'CA_SetKCV', - 'CK_CA_CreateContainer', - 'LUNA_RET_ENCRYPTED_DATA_LEN_RANGE', - 'CA_ExtractMaskedObject', 'LUNA_RET_OPERATION_ACTIVE', - 'C_GenerateKeyPair', 'LUNA_RET_DAC_MISSING', - 'CK_ULONG_PTR', 'CK_C_Encrypt', - 'LUNA_RET_SIM_AUTHFORM_INVALID', 'CK_SEED_CTR_PARAMS_PTR', - 'LUNA_RET_INVALID_FUF_HEADER', 'RC_USB_PED_NOT_RESPONDING', - 'CK_KDF_PRF_PARAMS_PTR', - 'LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED', + 'CK_CA_CloneObjectToAllSessions', 'CK_CA_FirmwareRollback', + 'CK_WTLS_KEY_MAT_OUT', 'CK_WTLS_KEY_MAT_PARAMS', + 'CA_ExtractMaskedObject', + 'CK_CA_GetNumberOfAllowedContainers', + 'C_DigestEncryptUpdate', 'UInt16', 'LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES', - 'CA_GetHSMStorageInformation', 'C_DigestFinal', - 'LUNA_RET_CB_MUST_WRITE', 'CK_CA_HAAnswerLoginChallenge', - 'CA_SIMInsert', 'CK_INFO', - 'LUNA_RET_SM_OTHER_USER_LOGGED_IN', + 'CK_CA_HAAnswerLoginChallenge', + 'LUNA_RET_STC_ACTIVATE_RESP_GEN_FAIL', 'LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS', - 'LUNA_RET_ATTRIBUTE_VALUE_INVALID', 'Float32', 'RC_TOKEN_NOT_PRESENT', - 'CK_CA_GetContainerStorageInformation', - 'CK_CA_QueryLicense', 'LUNA_RET_HIFN_END_MARKER_NOT_PRESENT', - 'LUNA_RET_CB_HIOS_CLOSED', 'CK_ATTRIBUTE', - 'CK_CA_SetDestructiveHSMPolicies', - 'CK_RSA_PKCS_MGF_TYPE_PTR', 'CK_UTF8CHAR', - 'CK_C_DecryptDigestUpdate', 'CA_LogSetConfig', - 'CK_CA_SwitchSecondarySlot', 'RC_CANCEL', 'CK_MECHANISM', - 'CK_WTLS_RANDOM_DATA_PTR', 'LUNA_RET_UM_TSN_MISSING', - 'CA_GetContainerCapabilitySetting', 'CK_MECHANISM_INFO', - 'CK_FUNCTION_LIST', - 'LUNA_RET_HIFN_DESTINATION_COUNT_INVALID', 'C_FindObjects', - 'C_VerifyInit', 'Int16', 'CA_GetContainerStatus', - 'RC_SSL_WANT_X509_LOOKUP_ERROR', 'LUNA_RET_NO_RNG_SEED', - 'RC_SOCKET_WOULDBLOCK', 'CA_InvokeServiceAsynch', - 'CK_CA_CloneAsTargetInit', - 'LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL', + 'CK_RSA_PKCS_MGF_TYPE_PTR', 'CA_STCSetSequenceWindowSize', + 'CK_SKIPJACK_RELAYX_PARAMS', 'LUNA_RET_UM_TSN_MISSING', + 'LUNA_RET_STC_OPEN_DHNIST_PUBKEY_ERROR', + 'CK_CA_InitIndirectPIN', 'LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED', - 'MSG_LOG_WAS_TRUNCATED', 'CK_C_WaitForSlotEvent', - 'CK_KEY_WRAP_SET_OAEP_PARAMS_PTR', 'RC_SSL_CTX_ERROR', - 'CK_C_SignUpdate', 'CK_CREATEMUTEX', 'CK_CA_LogVerify', - 'CK_CA_SetApplicationID', 'CK_CA_STCRegister', - 'CK_CA_GetTSV', 'CK_AES_CBC_ENCRYPT_DATA_PARAMS', - 'CK_ARIA_CTR_PARAMS_PTR', 'CA_IsMofNEnabled', - 'C_EncryptFinal', 'CK_KIP_PARAMS_PTR', - 'RC_OBJECT_ID_INVALID', 'C_FindObjectsInit', - 'CA_LKMReceiverComplete', - 'LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM', - 'CK_CA_GetUserContainerNumber', 'CK_C_SeedRandom', - 'LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED', - 'LUNA_RET_CCM_FWUPDATE_DENIED', 'CK_EC_KDF_TYPE', - 'CK_CA_OpenSession', 'CA_GetSessionInfo', - 'MSG_FACTORY_RESET', - 'LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM', - 'LUNA_RET_HAS160_SELF_TEST_FAILURE', - 'RC_HOST_RESOLUTION_ERROR', - 'RC_USB_PED_OPERATION_CANCELLED', 'CA_GetFPV', - 'LUNA_RET_MM_USAGE_ALREADY_SET', 'CA_HAInit', - 'LUNA_RET_CCM_CERT_INVALID', 'LUNA_RET_MISSING_VECTOR', - 'CA_GetHAState', 'CK_CA_SetKCV', 'C_SignRecoverInit', - 'C_DigestInit', 'LUNA_RET_ATTRIBUTE_TYPE_INVALID', - 'LUNA_RET_CB_SYS_ERROR', 'CK_EC_DH_PRIMITIVE', - 'RC_SSL_LOAD_CLIENT_CERT_ERROR', - 'LUNA_RET_INVALID_VECTOR_SIZE', 'MSG_RTC_BATTERY_LOW', - 'CK_CA_LogGetConfig', 'LUNA_RET_TOKEN_LOCKED_OUT_RN', - 'CK_PBE_PARAMS', 'C_SignInit', - 'CK_CA_InvokeServiceSinglePart', - 'LUNA_RET_HIFN6500_NOT_PRESENT', 'ULong', - 'CK_CA_WaitForSlotEvent', 'CA_LogGetStatus', + 'MSG_LOG_WAS_TRUNCATED', 'RC_SSL_CTX_ERROR', + 'CA_GetTokenObjectHandle', 'C_EncryptFinal', + 'CK_CA_TokenZeroize', 'CK_EC_KDF_TYPE', 'CKCA_MODULE_ID', + 'CA_LogVerify', 'LUNA_RET_CCM_CERT_INVALID', + 'CA_SetDestructiveHSMPolicies', 'CK_CA_ManualKCV', + 'LUNA_RET_HIFN6500_NOT_PRESENT', 'CA_LogGetStatus', 'LUNA_RET_CB_HIOS_SEND_TIMEOUT', - 'LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED', - 'CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR', 'LUNA_RET_HIFN_DMA_NOT_IDLE', 'LUNA_RET_TOTAL_WEIGHT_INVALID', - 'CK_RSA_PKCS_OAEP_PARAMS_PTR', 'CA_HAGetMasterPublic', + 'RC_STC_SEQUENCE_NUM_INVALID', + 'LUNA_RET_FUNCTION_NOT_SUPPORTED', 'CK_CREATEMUTEX', + 'LUNA_RET_INVALID_PADDING_TYPE', + 'CK_CA_LKMInitiatorComplete', + 'LUNA_RET_MM_NOT_ENOUGH_MEMORY', + 'RC_SSL_GET_PEER_CERT_ERROR', + 'LUNA_RET_ATTRIBUTE_READ_ONLY', 'RC_NO_BUFFER', + 'CA_SetPedId', 'CK_CA_ModifyMofN', + 'LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS', + 'LUNA_RET_TOKEN_LOCKED_OUT_UM', 'CK_C_GetAttributeValue', + 'CA_CreateContainer', 'CK_KEY_WRAP_SET_OAEP_PARAMS', + 'CK_C_SignInit', 'CK_SESSION_INFO_PTR', + 'CK_CA_STCSetCipherAlgorithm', 'CK_CA_SIMInsert', + 'CK_CA_SIMExtract', 'CA_GenerateCloneableMofN', + 'CK_CHAR_PTR', 'CA_ResetDevice', 'RC_STC_RESPONSE_BAD_MAC', + 'CA_STCSetCipherAlgorithm', 'LUNA_RET_CHALLENGE_INVALID', + 'LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT', + 'CA_GetModuleList', 'CK_CA_GetModuleInfo', 'CK_CA_SetTPV', + 'RC_TOKEN_STATE_INVALID', 'LUNA_RET_ATTRIBUTE_NOT_FOUND', + 'LUNA_RET_CAST_SELF_TEST_FAILURE', + 'LUNA_RET_MTK_SPLIT_INVALID', + 'MSG_RTC_CANT_CLEAN_TAMPER_1', + 'MSG_RTC_CANT_CLEAN_TAMPER_2', + 'LUNA_RET_HIFN_SOURCE_COUNT_INVALID', 'CA_GetTime', + 'CA_GetTokenPolicies', 'RC_STC_RSA_ENCRYPT_ERROR', + 'CA_InsertMaskedObject', 'CA_CloneAllObjectsToSession', + 'LUNA_RET_LOG_AUDIT_NOT_INITIALIZED', + 'LUNA_RET_SM_ACCESS_REALLOC_ERROR', 'CA_WriteCommonStore', + 'CA_CloseSecureToken', + 'LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN', + 'CK_RC5_MAC_GENERAL_PARAMS_PTR', 'CK_CA_ClonePrivateKey', + 'LUNA_RET_RM_ELEMENT_ID_INVALID', + 'LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE', + 'RC_CMD_BLOCKED_REMOTE_PED_TUNNEL', 'CK_C_EncryptFinal', + 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE', + 'RC_STC_NO_CONTEXT', + 'LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS', 'CK_C_VerifyInit', + 'CK_LKM_TOKEN_ID_PTR', 'RC_USER_NAME_IN_USE', + 'CA_SetContainerPolicy', 'CK_CA_FactoryReset', + 'MSG_GENERATING_NEW_TVK_FAILED', 'PointerDifference', + 'CA_CloseAllSecondarySessions', + 'MSG_RTC_CONFIGURATION_CORRUPTED', + 'LUNA_RET_OPERATION_NOT_INITIALIZED', + 'LUNA_RET_CB_ABORTED', + 'CK_CA_CloseApplicationIDForContainer', + 'LUNA_RET_SIM_AUTHFORM_INVALID', + 'LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO', + 'CA_STCGetKeyLifeTime', 'CK_RC2_MAC_GENERAL_PARAMS', + 'CK_SESSION_HANDLE', 'LUNA_RET_KEY_INDIGESTIBLE', + 'CK_SLOT_INFO', 'CA_STCGetDigestID', + 'LUNA_RET_PED_ID_INVALID', + 'MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK', + 'LUNA_RET_CAN_NOT_CREATE_SECRET_KEY', + 'CK_CA_GetHSMPolicySetting', + 'CK_CA_CreateContainerLoginChallenge', 'CA_QueryLicense', + 'CA_STCGetCipherAlgorithm', 'RC_DATA_CORRUPTED', + 'CK_SESSION_HANDLE_PTR', 'CK_RC2_MAC_GENERAL_PARAMS_PTR', + 'CA_CloseApplicationID', 'LUNA_RET_CB_HIOS_RECV_TIMEOUT', + 'CK_C_Logout', 'CA_HAGetLoginChallenge', 'CA_SetRDK', + 'LUNA_RET_CCM_UPDATE_DENIED', + 'LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT', + 'LUNA_RET_GENERAL_ERROR', + 'MSG_TVK_TIMESTAMP_RECOVERY_FAILED', + 'CK_C_WaitForSlotEvent', + 'LUNA_RET_LICENSE_CAPACITY_EXCEEDED', + 'LUNA_RET_UM_PIN_LEN_RANGE', + 'CK_SFNT_CA_FUNCTION_LIST_PTR', + 'CK_SKIPJACK_PRIVATE_WRAP_PTR', 'LUNA_RET_ECC_DAK_MISSING', + 'LUNA_RET_HIFN6500_RESET_TIMEOUT', 'CK_CA_GetObjectUID', + 'LUNA_RET_ISES_RNG_TEST_FAILED', + 'MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC', + 'C_SetOperationState', 'CK_CA_ConfigureRemotePED', + 'CK_C_SignRecoverInit', 'CK_CA_STCGetDigestAlgorithm', + 'LUNA_RET_DATA_INVALID', 'CK_CERTIFICATE_TYPE', + 'LUNA_RET_M_OF_N_PARAMETER_EXIST', + 'RC_SSL_WANT_WRITE_ERROR', 'CA_Extract', 'CK_OBJECT_CLASS', + 'CA_STCGetAdminPubKey', 'C_VerifyRecover', 'CK_FLAGS', + 'LUNA_RET_OPERATION_RESTRICTED', + 'LUNA_RET_SM_UNKNOWN_ACCESS_TYPE', 'LUNA_RET_MAC_MISSING', + 'CA_STCGetCipherNameByID', 'CA_GetObjectHandle', + 'LUNA_RET_HIFN_DMA_ERROR', 'CK_CA_TokenDelete', + 'CA_CloneObject', 'CK_C_DigestEncryptUpdate', + 'LUNA_RET_ERROR', 'RC_CERT_TYPE_INVALID', + 'C_VerifyRecoverInit', 'RC_OBJECT_NOT_IN_LIST', + 'LUNA_RET_ECC_SELF_TEST_FAILURE', 'C_DigestKey', + 'RC_OPERATION_WOULD_BLOCK', 'LUNA_RET_MM_INVALID_HANDLE', + 'LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL', + 'CA_LogExternal', + 'LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT', + 'LUNA_RET_WRAPPING_KEY_HANDLE_INVALID', + 'RC_MANUFACTURING_TOKEN_NOT_PRESENT', + 'CK_CA_GetFunctionList', 'CK_CA_CloneAsTarget', + 'CK_CA_HALogin', 'CA_CloneAsSource', + 'LUNA_RET_MAX_OBJECT_COUNT', 'CK_KEY_TYPE', + 'CK_RSA_PKCS_PSS_PARAMS', 'LUNA_RET_OBJECT_DELETED', + 'CK_CA_GetSecondarySlot', 'UInt32', + 'CA_OpenSessionWithAppID', 'LUNA2_RET_HIFN_RESET_ERROR', + 'RC_UNEXPECTED', 'CA_InvokeServiceFinal', + 'RC_STC_CLIENT_IDENTITY_NOT_CONFIGURED', 'C_OpenSession', + 'CK_CA_SetUserContainerName', + 'LUNA_RET_STC_CLIENT_HANDLE_INVALID', + 'CA_WaitForSlotEvent', 'LUNA_RET_INVALID_BOARD_TYPE', + 'CK_WTLS_RANDOM_DATA_PTR', 'CK_C_CloseAllSessions', + 'CK_RSA_PKCS_PSS_PARAMS_PTR', 'CK_RC2_CBC_PARAMS', + 'CK_CA_GetServerInstanceBySlotID', + 'LUNA_RET_CL_COMMAND_MALFORMED', + 'LUNA_RET_LOG_BAD_RECORD_HMAC', + 'LUNA_RET_MECHANISM_PARAM_INVALID', 'CK_CA_LoadModule', + 'LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION', + 'CK_CA_HAAnswerMofNChallenge', + 'CK_CA_GetRemotePEDVectorStatus', 'CK_ARIA_CTR_PARAMS', + 'LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW', + 'CK_CAMELLIA_CTR_PARAMS', + 'RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR', + 'CK_C_INITIALIZE_ARGS_PTR', 'CK_CA_SetLKCV', + 'LUNA_RET_CB_REMOTE_ABORT', 'RC_BUFFER_TOO_SMALL', + 'CK_AES_CBC_PAD_INSERT_PARAMS_PTR', + 'LUNA_RET_SIGNATURE_LEN_RANGE', + 'MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF', + 'CK_CA_CloseSecondarySession', 'CA_DismantleRemotePED', + 'CA_ResetPIN', 'CK_CA_MTKRestore', + 'CK_WTLS_KEY_MAT_OUT_PTR', + 'MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING', + 'LUNA_RET_LOG_BAD_FILE_NAME', 'CK_PKCS5_PBKD2_PARAMS', + 'RC_STC_COMPUTE_DH_KEY_ERROR', + 'LUNA_RET_CB_HIOS_ID_INVALID', 'CA_CloneMofN', + 'RC_STC_CLIENT_HANDLE_INVALID', 'LUNA_RET_PE1746_ERROR', + 'CK_CA_GenerateMofN', 'CK_CA_GetPrimarySlot', 'Int64', + 'CK_X9_42_DH2_DERIVE_PARAMS', 'CA_ClonePrivateKey', + 'CA_CloseSecondarySession', + 'LUNA_RET_CONTAINER_IS_DISABLED', + 'CK_CA_OpenApplicationIDForContainer', + 'LUNA_RET_STC_NOT_ENABLED', 'LUNA_RET_ROOT_CERT_MISSING', + 'CA_DeleteContainer', 'LUNA_RET_CHALLENGE_NOT_REQUIRED', + 'CA_DeleteRemotePEDVector', 'CK_CA_UnlockClusteredSlot', + 'CK_CA_GetTokenCapabilities', 'CK_CA_CloneModifyMofN', + 'LUNA_RET_STC_OPEN_KEY_MATERIAL_GEN_FAIL', 'CK_STATE', + 'CK_CA_GetHSMCapabilitySetting', + 'LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM', + 'RC_VERSION_INVALID', 'LUNA_RET_SIGNATURE_INVALID', + 'LUNA_RET_CONTAINER_HANDLE_INVALID', 'CK_C_UnwrapKey', + 'CK_CA_GetContainerList', 'CA_MultisignValue', + 'LUNA_RET_KEY_NOT_UNWRAPPABLE', + 'CK_CA_DisableUnauthTokenInsertion', 'CK_CA_SetPedId', + 'C_Verify', 'CK_CA_Extract', 'LUNA_RET_SFNT3120_CRC', + 'CK_C_SetAttributeValue', 'CK_CA_GetHSMCapabilitySet', + 'CA_SIMMultiSign', 'LUNA_RET_LOG_FILE_WRITE_ERROR', + 'C_DecryptFinal', 'Byte', 'CK_CA_CloneAsSource', + 'CK_FUNCTION_LIST_PTR', + 'LUNA_RET_FORMER_INVALID_ENTRY_TYPE', 'CA_ActivateMofN', + 'CK_CA_HAGetMasterPublic', 'CK_SFNT_CA_FUNCTION_LIST', + 'RC_STC_NO_CHANNEL', 'CK_CA_OpenApplicationID', + 'CK_AES_GMAC_PARAMS_PTR', 'CK_CAMELLIA_CTR_PARAMS_PTR', + 'RC_FAILED_TO_CREATE_PROCESS', 'CA_RetrieveLicenseList', + 'LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS', + 'CK_SSL3_RANDOM_DATA', 'CK_CA_SetContainerSize', + 'LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL', + 'LUNA_RET_CB_HIOS_STATE_INVALID', 'MSG_TVK_WAS_CORRUPTED', + 'RC_STC_REKEY_CHANNEL_MISMATCH', 'CK_SSL3_KEY_MAT_PARAMS', + 'CK_KIP_PARAMS_PTR', 'CK_CA_WaitForSlotEvent', + 'CK_OTP_SIGNATURE_INFO_PTR', + 'LUNA_RET_SM_UNKNOWN_SESSION_TYPE', 'CA_GetSessionInfo', + 'CK_WTLS_RANDOM_DATA', 'CK_USHORT', + 'LUNA_RET_MISSING_SPLITS', + 'LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL', + 'CK_CA_LoadEncryptedModule', + 'MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED', + 'RC_INVALID_ENUM_OPTION', + 'LUNA_RET_INVALID_CERTIFICATE_FUNCTION', 'CA_SetTPV', + 'CK_SFNT_CA_FUNCTION_LIST_PTR_PTR', + 'LUNA_RET_INVALID_ENTRY_TYPE', 'CA_GetUserContainerName', + 'RC_NOT_HSM_BACKUP_TOKEN', 'CK_C_GetFunctionStatus', + 'CK_CA_STCGetCipherNameByID', 'RC_SSL_FAILED_HANDSHAKE', + 'CK_PRF_KDF_PARAMS', 'CK_CA_Deactivate', + 'LUNA_RET_KEY_SENSITIVE', 'RC_SOCKET_ADDRESS_INVALID', + 'CK_X9_42_DH1_DERIVE_PARAMS_PTR', 'CK_C_VerifyFinal', + 'RC_SOCKET_ADDRESS_IN_USE', + 'LUNA_RET_CL_COMMAND_NON_BACKUP', 'CA_ChooseSecondarySlot', + 'CA_GetUserContainerNumber', + 'LUNA_RET_DSA_PARAM_GEN_FAILURE', 'UInt', + 'LUNA_RET_TIMEOUT', 'RC_CACHE_NOT_MAPPED', + 'CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR', + 'CA_GetHSMCapabilitySetting', + 'RC_UNKNOWN_CALLBACK_COMMAND', + 'CK_CA_GetTokenObjectHandle', + 'CK_CA_GetUnauthTokenInsertionStatus', 'fwResultCode', + 'CA_MTKGetState', 'LUNA_RET_KEY_INVALID_FOR_OPERATION', + 'CK_CA_CloneObject', 'RC_ASSIGNING_SAME_VALUE', + 'LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED', + 'CK_MECHANISM_TYPE', 'CA_SetKCV', + 'RC_USB_PED_NOT_RESPONDING', + 'MSG_ZEROIZING_AFTER_DECOMMISSION', + 'CK_CA_GetContainerStorageInformation', 'CK_ATTRIBUTE', + 'CK_CA_SetDestructiveHSMPolicies', + 'CK_CA_SwitchSecondarySlot', 'CK_MECHANISM', + 'CA_RoleStateGet', + 'LUNA_RET_HIFN_DESTINATION_COUNT_INVALID', + 'LUNA_RET_NO_RNG_SEED', 'C_Encrypt', 'CK_C_SignUpdate', + 'CK_INFO_PTR', 'CK_ARIA_CTR_PARAMS_PTR', + 'LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM', + 'CK_C_SeedRandom', 'LUNA_RET_HAS160_SELF_TEST_FAILURE', + 'LUNA_RET_MM_USAGE_ALREADY_SET', 'CA_GetHAState', + 'C_SignRecoverInit', 'CK_CA_STCGetClientsList', + 'RC_STC_RESPONSE_REPLAYED', 'LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED', - 'LUNA_RET_CAST5_SELF_TEST_FAILURE', 'CK_SLOT_ID_PTR', - 'LUNA_RET_410_BUFFER_TOO_SMALL', 'CK_C_Digest', - 'LUNA_RET_HIFN_DESTINATION_OVERRUN', + 'CK_CA_GetContainerPolicySetting', + 'CK_CA_STCSetKeyLifeTime', 'CK_BYTE', + 'CK_SSL3_KEY_MAT_OUT', 'LUNA_RET_ISES_ERROR', + 'LUNA_RET_ECC_MIC_MISSING', 'CK_GetTotalOperations', + 'CK_SLOT_INFO_PTR', 'CK_CA_GetObjectHandle', + 'CK_CA_GetSlotListFromServerInstance', + 'LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE', + 'CKCA_MODULE_INFO_PTR', 'CK_KEA_DERIVE_PARAMS_PTR', + 'CK_BYTE_PTR', 'CA_GetServerInstanceBySlotID', + 'CA_SetContainerSize', 'LUNA_RET_SM_ACCESS_ID_INVALID', + 'CA_GetContainerPolicySetting', + 'CK_CA_CloseAllSecondarySessions', 'CA_GenerateTokenKeys', + 'CK_CA_SetMofN', 'CA_TimeSync', 'CA_LKMInitiatorChallenge', + 'CA_InitializeRemotePEDVector', 'HalfWord', + 'CK_C_GetMechanismList', 'RC_SSL_LOAD_SERVER_CERT_ERROR', + 'CK_CA_EncodeECPrimeParams', 'CK_VOID_PTR_PTR', + 'CA_MOFN_STATUS', 'CK_CA_FindAdminSlotForSlot', + 'CK_C_CopyObject', 'CK_CA_CreateLoginChallenge', + 'CK_CA_STCGetMaxSessions', 'CT_TokenHndle', + 'MSG_RTC_MSG_NVRAM_READ_FAILED', 'C_SetPIN', + 'LUNA_RET_ECC_HOK_MISSING', 'CA_InitIndirectToken', + 'C_GenerateKey', 'RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR', + 'CK_CA_STCGetCipherIDs', 'C_InitPIN', + 'RC_STC_CONTAINER_INVALID', 'LUNA_RET_DAK_MISSING', + 'CK_C_GetSlotInfo', 'RC_INVALID_INDEX', 'CK_ECIES_PARAMS', + 'MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED', + 'LUNA_RET_STC_OPEN_RESP_GEN_FAIL', + 'MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK', + 'MSG_RTC_RECONFIGURING_FAILED', 'RC_CHALLENGE_BUFFER_SIZE', + 'MSG_RTC_MSG_NVRAM_WRITE_FAILED', 'LUNA_RET_CB_ID_INVALID', + 'LUNA_RET_CB_SYNC_ERROR', 'CK_AES_CTR_PARAMS', + 'CK_LKM_TOKEN_ID_S', 'CA_SetExtendedTPV', + 'CK_CA_STCRegister', 'CA_HAInit', + 'CK_X9_42_DH2_DERIVE_PARAMS_PTR', 'CA_InitRolePIN', + 'CK_CA_TimeSync', 'LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE', + 'CK_CA_DeleteRemotePEDVector', 'CA_LogImportSecret', + 'CK_KEY_WRAP_SET_OAEP_PARAMS_PTR', + 'CA_STCGetDigestNameByID', 'LUNA_RET_FUNCTION_CANCELED', + 'LUNA_RET_INVALID_ACCESS_LEVEL', + 'CK_CA_GetTokenInsertionCount', + 'LUNA_RET_ISES_INIT_FAILED', + 'LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO', 'CK_PARAM_TYPE', + 'CA_GetContainerName', 'CK_CA_ChooseSecondarySlot', + 'CA_MOFN_STATUS_PTR', 'CA_FindAdminSlotForSlot', + 'LUNA_RET_VECTOR_OF_DIFFERENT_SET', 'ResultCodeValue', + 'LUNA_RET_WRAPPING_KEY_SIZE_RANGE', + 'CK_ECDH1_DERIVE_PARAMS', 'RC_SSL_CREATE_SSL_ERROR', + 'CK_RC2_PARAMS_PTR', 'CK_WTLS_PRF_PARAMS_PTR', + 'C_FindObjectsFinal', 'CK_C_CancelFunction', + 'CK_CA_GetContainerStatus', 'CK_C_VerifyRecover', + 'CK_RC2_CBC_PARAMS_PTR', + 'LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE', + 'CA_STCSetMaxSessions', 'CA_GetContainerStatus', + 'CA_PerformSelfTest', 'CA_STCGetCipherID', + 'CA_EncodeECPrimeParams', 'RC_USB_PED_OUT_OF_SYNC', + 'CK_CA_GetContainerCapabilitySet', + 'LUNA_RET_WEIGHT_TOO_SMALL', + 'CA_GetConfigurationElementDescription', + 'LUNA_RET_PED_UNPLUGGED', 'LUNA_RET_HSM_STORAGE_FULL', + 'C_Login', 'CK_CA_CloneAllObjectsToSession', + 'CA_STCGetClientInfo', 'LUNA_RET_KCDSA_SELF_TEST_FAILURE', + 'LUNA_RET_M_OF_N_ACTIVATION_REQUIRED', + 'LUNA_RET_MECHANISM_INVALID', 'C_CreateObject', + 'CK_KEA_DERIVE_PARAMS', 'CK_CA_FirmwareUpdate', + 'CK_CA_OpenSession', + 'LUNA_RET_STC_ACTIVATE_MACTAG_V_GEN_FAIL', + 'CK_CA_STCSetDigestAlgorithm', 'CA_Restart', 'UInt64', + 'CK_C_Sign', 'CK_CA_ReadCommonStore', + 'LUNA_RET_ATTRIBUTE_VALUE_INVALID', 'CKCA_MODULE_ID_PTR', + 'LUNA_RET_SM_ACCESS_ALREADY_EXISTS', 'CK_LONG', + 'CA_MOFN_GENERATION', + 'LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE', + 'LUNA_RET_CAST5_SELF_TEST_FAILURE', + 'CK_CA_ListSecureTokenUpdate', 'RC_CACHE_DIRTY', + 'LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH', + 'RC_STC_SECOND_PHASE_KDF_ERROR', 'LUNA_RET_RM_NO_MEMORY', + 'CK_CA_SetKCV', 'CK_OBJECT_HANDLE_PTR', + 'CA_LogExportSecret', 'CK_CA_InvokeServiceFinal', + 'LUNA_RET_CL_TRANSMISSION_ERROR', + 'RC_FAILED_TO_CREATE_THREAD', + 'RC_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE', 'CK_CA_HAInit', + 'Int', 'CA_LKMReceiverResponse', + 'CK_CA_STCClearDigestAlgorithm', + 'LUNA_RET_TUK_PARAMETER_MISSING', 'CK_C_InitPIN', + 'CK_AES_CBC_PAD_EXTRACT_PARAMS', 'LUNA_RET_RNG_ERROR', + 'RC_SSL_GET_CERTIFICATE_ERROR', + 'CK_SKIPJACK_RELAYX_PARAMS_PTR', 'CA_GetModuleInfo', + 'CK_TLS_PRF_PARAMS', 'LUNA_RET_STC_OPEN_CIPHER_MISMATCH', + 'CA_GetSecureElementMeta', + 'LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE', + 'LUNA_RET_TOKEN_LOCKED_OUT_PM', 'CK_SLOT_ID', + 'LUNA_RET_PED_CLIENT_NOT_RUNNING', + 'LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE', 'CT_Token', + 'LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT', + 'MSG_TVK_TIMESTAMP_CORRUPTED', 'CK_CA_LogExternal', + 'LUNA_RET_SP_RX_ERROR', + 'LUNA_RET_INVALID_PRIVATE_KEY_TYPE', + 'CK_CA_CloseSecureToken', 'LUNA_RET_SM_UNKNOWN_COMMAND', + 'RC_SLOT_ID_INVALID', 'CK_CA_ListSecureTokenInit', + 'LUNA_INVALID_PACKET_LAYOUT', 'LastFirmwareCode', + 'CK_C_Digest', 'LUNA_RET_NOT_FOUND', 'CK_C_Finalize', + 'RC_STC_PARTITION_IDENTITY_NOT_CONFIGURED', + 'LUNA_RET_CB_HIOS_HANDLE_INVALID', 'RC_PIN_INVALID', + 'RC_SOCKET_CLOSED', 'LUNA_RET_DAC_POLICY_PID_MISMATCH', + 'CA_GetTPV', 'CK_CA_EncodeECParamsFromFile', + 'CK_CA_RestartForContainer', + 'LUNA_RET_MISSING_COMMAND_PARAMETER', + 'LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE', + 'LUNA_RET_SM_PIN_EXPIRED', + 'CA_GetNumberOfAllowedContainers', 'CA_ChoosePrimarySlot', + 'RC_CLIENT_DISCONNECTED', 'LUNA_RET_CB_PROT_DATA_INVALID', + 'C_VerifyInit', 'LUNA_RET_CL_ALIGNMENT_ERROR', + 'CK_SKIPJACK_PRIVATE_WRAP_PARAMS', 'CA_SetTokenPolicies', + 'LUNA_RET_HIFN6500_INVALID_PARAMETERS', + 'CK_CA_DeleteContainerWithHandle', 'CK_LOCKMUTEX', + 'LUNA_RET_WRAPPING_ERROR', 'CK_CA_GenerateCloningKEV', + 'MSG_RTC_CANT_ACCESS', 'CK_C_DecryptUpdate', + 'LUNA_RET_RETRY', 'CA_M_OF_N_STATUS', 'CK_C_CloseSession', + 'CK_EC_ENC_SCHEME', 'CK_MECHANISM_INFO_PTR', + 'CK_OTP_PARAM_TYPE', 'LUNA_RET_OK', 'CA_UnloadModule', + 'CK_CA_PerformModuleCall', 'CA_GetTokenInsertionCount', + 'CK_CA_ResetDevice', 'LUNA_RET_CB_HANDLE_INVALID', + 'CK_CA_GetHSMPolicySet', 'CA_TokenDelete', + 'LUNA_RET_CONTAINER_LOCKED', 'CK_AES_GMAC_PARAMS', + 'LUNA_RET_NOT_READY', 'CK_PBE_PARAMS_PTR', + 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS', 'C_SeedRandom', + 'RC_GENERAL_ERROR', 'CA_RestartForContainer', + 'CA_STCClearDigestAlgorithm', 'CK_CA_STCDeregister', + 'CK_CA_STCGetDigestIDs', + 'LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE', + 'CK_CA_GetTokenCertificates', 'LUNA_RET_VECTOR_DUPLICATE', + 'HANDLE', 'CK_CA_TokenInsert', 'RC_SESSION_SCRIPT_EXISTS', + 'LUNA_RET_UNKNOWN_COMMAND', 'CA_ManualKCV', + 'C_CancelFunction', 'CK_HA_STATUS', + 'LUNA_RET_ECC_RESULT_AT_INF', 'RC_LISTEN_SOCKET_INVALID', + 'CK_C_DigestKey', 'C_Initialize', 'RC_INVALID_COMMAND', + 'CK_RSA_PKCS_OAEP_PARAMS_PTR', + 'LUNA_RET_SHA_SELF_TEST_FAILURE', 'C_InitToken', + 'CK_CA_ActivateMofN', 'RC_SOCKET_WRITE_ERROR', + 'MSG_TVK_TIMESTAMP_UPDATE_FAILED', 'RC_ARGUMENTS_BAD', + 'LUNA_RET_UM_PIN_INCORRECT', 'C_GetSlotList', + 'C_GetMechanismInfo', 'LUNA_RET_BAD_PPID', + 'LUNA_RET_USER_TYPE_INVALID', + 'LUNA_RET_ATTRIBUTE_SENSITIVE', 'CA_STCGetChannelID', + 'CK_C_EncryptUpdate', 'LUNA_RET_M_OF_N_IS_NOT_REQUIRED', + 'Boolean', 'CK_CA_Zeroize', + 'LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID', + 'CK_WTLS_KEY_MAT_PARAMS_PTR', 'LUNA_RET_CCM_UNREMOVABLE', + 'CK_CA_InitIndirectToken', 'CA_GetTSV', 'CK_RC5_PARAMS', + 'MSG_BAD_HMAC', 'C_SignFinal', + 'LUNA_RET_INVALID_CERTIFICATE_DATA', 'CK_C_GenerateKey', + 'LUNA_RET_M_TOO_SMALL', 'CA_UnlockClusteredSlot', + 'RC_FILE_ERROR', 'CK_AES_CTR_PARAMS_PTR', + 'CA_FirmwareUpdate', 'CK_USHORT_PTR', + 'CK_PKCS5_PBKD2_PARAMS_PTR', + 'LUNA_RET_OH_OBJECT_TYPE_INVALID', + 'LUNA_RET_AES_SELF_TEST_FAILURE', 'CK_C_DeriveKey', + 'RC_OK', 'CK_CA_GetContainerPolicySet', 'CA_SIMInsert', + 'RC_SERVER_DISCONNECTED', 'CK_CA_SetHSMPolicies', + 'CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR', + 'LUNA_RET_CB_HIOS_CANCELED', + 'LUNA_RET_TOKEN_LOCKED_OUT_SM', + 'LUNA_RET_CAST3_SELF_TEST_FAILURE', 'CK_CA_RoleStateGet', + 'CK_C_VerifyRecoverInit', 'CK_CA_TokenInsertNoAuth', + 'CA_TokenInsertNoAuth', 'CK_ECDH2_DERIVE_PARAMS_PTR', + 'CK_CA_ChoosePrimarySlot', 'LUNA_RET_ECC_HOC_MISSING', + 'CK_CA_IndirectLogin', 'CK_CA_InvokeServiceAsynch', + 'LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE', + 'CK_CA_GetTokenPolicies', + 'LUNA_RET_CERT_VERSION_NOT_SUPPORTED', 'CK_CA_InitAudit', + 'LUNA_RET_SM_SESSION_READ_ONLY_EXISTS', + 'LUNA_RET_DEVICE_TIMEOUT', 'MSG_LAST', + 'CK_CA_SIMMultiSign', 'CK_DES_CBC_ENCRYPT_DATA_PARAMS', + 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS', + 'MSG_RTC_EXTERNAL_TAMPER_DETECTED', 'CK_CA_GetHSMStats', + 'LUNA_RET_INVALID_IP_PACKET', 'C_GenerateKeyPair', + 'CK_CA_MTKSetStorage', 'CKA_SIM_AUTH_FORM', + 'CK_C_SignRecover', + 'LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE', + 'CK_HW_FEATURE_TYPE', 'RC_POINTER_INVALID', + 'CK_CA_ExtractMaskedObject', 'CA_ROLE_STATE', + 'MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS', + 'CA_GetTokenCertificates', 'CK_CLUSTER_STATE_PTR', + 'CA_CheckOperationState', 'LUNA_RET_SP_TX_ERROR', + 'C_GetTokenInfo', 'CK_CA_SetTokenPolicies', + 'CA_CloneAsTarget', 'RC_NOT_PARTITION_BACKUP_TOKEN', + 'CA_SetCloningDomain', 'LUNA_RET_M_OF_N_IS_NOT_INITIALZED', + 'RC_SEMAPHORE_ERROR', 'CA_GetObjectUID', 'CK_VERSION_PTR', + 'CK_CA_OpenSessionWithAppID', 'C_DecryptInit', + 'LUNA_RET_CPK_PARAMETER_MISSING', 'CA_STCDeregister', + 'SInt32', 'CK_CA_STCGetCipherID', + 'CA_STCSetKeyActivationTimeOut', 'CK_CA_CreateContainer', + 'LUNA_RET_ENCRYPTED_DATA_LEN_RANGE', + 'LUNA_RET_DAC_MISSING', 'CK_ULONG_PTR', + 'CK_KDF_PRF_PARAMS_PTR', 'CA_STCGetDigestAlgorithm', + 'LUNA_RET_CB_MUST_WRITE', + 'LUNA_RET_SM_OTHER_USER_LOGGED_IN', 'CK_CA_GetTokenStatus', + 'CA_GetContainerCapabilitySetting', + 'RC_SSL_WANT_X509_LOOKUP_ERROR', 'RC_SOCKET_WOULDBLOCK', + 'CA_InvokeServiceAsynch', 'CK_C_GetInfo', + 'CK_C_FindObjectsFinal', 'CK_CA_SetApplicationID', + 'CK_AES_CBC_ENCRYPT_DATA_PARAMS', + 'CK_C_DecryptVerifyUpdate', 'CK_CA_DestroyMultipleObjects', + 'CK_KEY_DERIVATION_STRING_DATA_PTR', + 'LUNA_RET_INVALID_VECTOR_SIZE', 'MSG_RTC_BATTERY_LOW', + 'LUNA_RET_TOKEN_LOCKED_OUT_RN', + 'CK_CA_InvokeServiceSinglePart', 'ULong', + 'CK_CA_QueryLicense', 'CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CK_SLOT_ID_PTR', 'CA_TokenInsert', 'MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK', - 'CK_CA_GetPedId', 'LUNA_RET_USER_ALREADY_LOGGED_IN', - 'CK_FUNCTION_LIST_PTR_PTR', - 'LUNA_RET_FUNCTION_NOT_SUPPORTED', - 'CK_CA_LKMInitiatorComplete', 'MSG_RTC_ROLLED_BACK', - 'CK_CA_DeleteRemotePEDVector', + 'CA_IsMofNRequired', 'CA_HAGetMasterPublic', + 'MSG_RTC_ROLLED_BACK', 'RC_USB_PED_OPERATION_CANCELLED', + 'LUNA_RET_STC_NO_CHANNEL', 'CK_CA_LogVerifyFile', + 'CA_SetContainerPolicies', 'CK_CA_HAGetLoginChallenge', + 'CA_GenerateCloningKEV', 'CA_SetHSMPolicy', 'CK_CA_GetTPV', + 'MSG_RTC_CANT_CLEAN_POWER_LOSS', 'MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT', - 'RC_SSL_FAILED_HANDSHAKE', 'CK_BYTE', - 'CK_SSL3_KEY_MAT_OUT', 'CK_C_DecryptUpdate', - 'CK_CA_LogVerifyFile', 'CK_CA_DeleteContainer', - 'CK_CA_HAGetLoginChallenge', 'CA_GenerateCloningKEV', - 'LUNA_RET_ISES_ERROR', 'LUNA_RET_ISES_LNAU_TEST_FAILED', - 'LUNA_RET_ECC_MIC_MISSING', 'CK_CA_GetTPV', - 'MSG_RTC_CANT_CLEAN_POWER_LOSS', 'CK_GetTotalOperations', - 'CK_CA_LogEraseAll', 'CK_SLOT_INFO_PTR', - 'CK_CA_GetObjectHandle', 'RC_CALLBACK_ERROR', - 'LUNA_RET_ATTRIBUTE_NOT_FOUND', 'CA_CloseSecondarySession', - 'C_Encrypt', 'CK_RV', 'RC_PORT_INVALID', 'CK_NOTIFY', - 'CK_CA_InitializeRemotePEDVector', - 'LUNA_RET_MM_NOT_ENOUGH_MEMORY', 'C_Finalize', - 'CK_C_FindObjects', 'CK_CA_SetContainerSize', - 'RC_SSL_GET_PEER_CERT_ERROR', - 'LUNA_RET_ATTRIBUTE_READ_ONLY', - 'CA_GetContainerStorageInformation', - 'CA_GetContainerPolicySet', - 'LUNA_RET_HIFN_INVALID_MAC_MODE', 'RC_SSL_ERROR', - 'LUNA_RET_DSA_SELF_TEST_FAILURE', 'CK_BYTE_PTR', - 'CA_ModifyUsageCount', 'CK_CA_TimeSync', - 'LUNA_RET_N_TOO_SMALL', 'CK_CA_GenerateTokenKeys', - 'CK_DES_CTR_PARAMS_PTR', 'CA_GetHSMPolicySet', - 'LUNA_RET_SM_KEY_SIZE_ERROR', - 'LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE', 'C_CopyObject', - 'CK_CA_CloseApplicationID', 'LUNA_RET_ECC_BUFFER_OVERFLOW', - 'LUNA_RET_OH_OBJECT_ALREADY_EXISTS', 'CK_CA_Insert', - 'CK_CA_CloseAllSecondarySessions', 'RC_DATA_INVALID', - 'C_VerifyUpdate', 'CK_NOTIFICATION', - 'LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS', - 'LUNA_RET_TOKEN_LOCKED_OUT_UM', 'C_SignRecover', - 'LUNA_RET_SSK_MISSING', 'CK_C_VerifyUpdate', - 'RC_REMOTE_SIDE_DISCONNECTED', 'CK_C_GetAttributeValue', - 'CA_CreateContainer', 'CA_LogImportSecret', 'CA_TimeSync', - 'CA_LKMInitiatorChallenge', 'LUNA_RET_UM_PIN_LEN_RANGE', - 'CK_C_VerifyFinal', 'HalfWord', 'CK_C_GetMechanismList', - 'CA_CreateLoginChallenge', 'RC_PIN_LOCKED', - 'RC_SSL_LOAD_SERVER_CERT_ERROR', 'LUNA_RET_PED_ERROR', - 'LUNA_RET_MISSING_NUMBER_OF_VECTORS', - 'CA_SetContainerPolicies', 'CK_X9_42_DH_KDF_TYPE_PTR', + 'CK_CA_SetTokenCertificateSignature', + 'LUNA_RET_STC_SEQUENCE_NUM_INVALID', 'CK_RV', 'CK_NOTIFY', + 'CK_C_FindObjects', 'LUNA_RET_HIFN_INVALID_MAC_MODE', + 'CA_ModifyUsageCount', 'LUNA_RET_SM_KEY_SIZE_ERROR', + 'LUNA_RET_OH_OBJECT_ALREADY_EXISTS', 'RC_DATA_INVALID', + 'C_VerifyUpdate', 'CK_CA_LogImportSecret', + 'CK_X9_42_MQV_DERIVE_PARAMS_PTR', 'CK_CA_ResetPIN', + 'RC_STC_RESPONSE_UNEXPECTED_KEY', 'RC_PIN_LOCKED', + 'LUNA_RET_PED_ERROR', 'CK_X9_42_DH_KDF_TYPE_PTR', 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR', - 'CK_CA_EncodeECPrimeParams', 'C_DecryptVerifyUpdate', - 'CK_C_UnwrapKey', 'LUNA_RET_USER_PIN_NOT_INITIALIZED', - 'CA_MOFN_STATUS', 'CK_C_SignInit', - 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR', - 'CK_CA_GetContainerName', 'CK_CA_CloneMofN', - 'LUNA_RET_DES_SELF_TEST_FAILURE', 'CK_SESSION_INFO_PTR', - 'LUNA_RET_ERROR', 'CA_GenerateTokenKeys', - 'LUNA_RET_ECC_SELF_TEST_FAILURE', - 'LUNA_RET_CHALLENGE_REQUIRES_PED', 'CK_C_CopyObject', - 'CK_CA_CreateLoginChallenge', 'CK_CERTIFICATE_TYPE', - 'MSG_ZEROIZING', 'CA_FirmwareRollback', 'Float', - 'CK_KDF_PRF_TYPE', 'LUNA_RET_CL_NO_TRANSMISSION', - 'CK_CA_DestroyMultipleObjects', 'LUNA_RET_OBJECT_DELETED', - 'CK_CA_GenerateCloneableMofN', 'RC_SIM_NOT_SUPPORTED', - 'CA_GenerateCloneableMofN', 'CK_CMS_SIG_PARAMS', - 'CK_X9_42_DH1_DERIVE_PARAMS_PTR', 'CK_CHAR_PTR', - 'CT_TokenHndle', 'LUNA_RET_MASKING_NOT_SUPPORTED', - 'C_Digest', 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR', - 'MSG_RTC_MSG_NVRAM_READ_FAILED', - 'CA_HAAnswerMofNChallenge', 'C_SetPIN', - 'CK_C_GetObjectSize', 'LUNA_RET_WEIGHT_TOO_LARGE', - 'LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW', + 'LUNA_RET_USER_PIN_NOT_INITIALIZED', 'CK_C_Decrypt', + 'CK_CA_CloneMofN', 'CK_CA_IsMofNRequired', + 'LUNA_RET_CHALLENGE_REQUIRES_PED', 'RC_GROUP_NAME_INVALID', + 'C_Sign', 'CA_STCClearCipherAlgorithm', + 'LUNA_RET_WEIGHT_TOO_LARGE', 'LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE', - 'CK_RC5_MAC_GENERAL_PARAMS_PTR', 'CK_C_DigestUpdate', - 'LUNA_RET_KEY_SIZE_RANGE', - 'LUNA_RET_RSA_SELF_TEST_FAILURE', - 'CK_X9_42_DH1_DERIVE_PARAMS', 'C_GetFunctionList', - 'CK_CA_SetCloningDomain', 'CA_EncodeECParamsFromFile', - 'LUNA_RET_TPV_INVALID', 'LUNA_RET_ECC_HOK_MISSING', - 'CA_LogEraseAll', 'CA_DeactivateMofN', - 'LUNA_RET_RM_POLICY_WRITE_RESTRICTED', - 'CK_C_PerformSelfTest', 'LUNA_RET_CHALLENGE_INVALID', - 'CA_CloneAsTarget', 'CK_CA_Restart', - 'LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT', 'CK_INFO_PTR', - 'CA_GetModuleList', 'CK_CA_ModifyUsageCount', - 'CA_LogExportSecret', 'CK_BBOOL', - 'CK_CA_EncodeECChar2Params', 'CA_IsMofNRequired', - 'MSG_RTC_TAMPER_2_SIGNAL', 'CK_CA_GetModuleInfo', - 'LUNA_RET_RIPEMD160_SELF_TEST_FAILURE', 'CK_CA_SetTPV', - 'RC_TOKEN_STATE_INVALID', 'RC_KEY_NEEDED', 'C_DecryptInit', + 'CK_C_DigestUpdate', 'LUNA_RET_KEY_SIZE_RANGE', + 'LUNA_RET_MM_FATAL_ERROR', 'C_GetFunctionList', + 'CK_CA_SetCloningDomain', 'CK_C_Initialize', + 'CA_GetTokenObjectUID', 'C_GetOperationState', + 'CK_C_GetSessionInfo', 'CK_BBOOL', + 'CK_CA_EncodeECChar2Params', 'CK_CA_STCGetChannelID', + 'RC_KEY_NEEDED', 'LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID', - 'LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE', 'LUNA_RET_BAD_FW_VERSION', 'LUNA_RET_DATA_LEN_RANGE', - 'CK_C_DestroyObject', 'LUNA_RET_CB_NO_MEMORY', - 'LUNA_RET_CAST_SELF_TEST_FAILURE', - 'CK_X9_42_DH2_DERIVE_PARAMS', - 'CK_SKIPJACK_PRIVATE_WRAP_PARAMS', - 'CK_X9_42_MQV_DERIVE_PARAMS_PTR', 'Int8', - 'LUNA_RET_DAK_MISSING', 'CK_RC2_CBC_PARAMS', + 'LUNA_RET_CB_NO_MEMORY', 'CK_CA_LogSetConfig', 'LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY', - 'CK_X9_42_MQV_DERIVE_PARAMS', - 'CA_GetRollbackFirmwareVersion', 'RC_INVALID_INDEX', + 'CA_GetRollbackFirmwareVersion', 'LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED', - 'LUNA_RET_RC5_SELF_TEST_FAILURE', - 'MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED', - 'LUNA_RET_MTK_SPLIT_INVALID', - 'CK_CA_GetTokenStorageInformation', 'CK_C_EncryptUpdate', - 'MSG_RTC_CANT_CLEAN_TAMPER_1', - 'MSG_RTC_CANT_CLEAN_TAMPER_2', - 'LUNA_RET_MTK_STATE_INVALID', - 'MSG_RTC_TAMPER_CIRCUITS_RE_ARMED', - 'MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK', - 'MSG_RTC_RECONFIGURING_FAILED', 'CK_DESTROYMUTEX', - 'RC_CHALLENGE_BUFFER_SIZE', - 'LUNA_RET_HIFN_SOURCE_COUNT_INVALID', - 'LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID', - 'LUNA_RET_SIM_CORRUPT_DATA', - 'MSG_RTC_MSG_NVRAM_WRITE_FAILED', - 'CK_CA_GetTokenObjectUID', 'LUNA_RET_CB_ID_INVALID', - 'LUNA_RET_CB_SYNC_ERROR', 'CK_CA_GetUserContainerName', - 'CK_CA_MTKZeroize', 'CK_CA_GetClusterState', - 'CA_GetContainerName', 'CK_AES_CTR_PARAMS', - 'CA_SetContainerSize', 'CK_LKM_TOKEN_ID_S', - 'CA_SetExtendedTPV', 'CK_CA_GetSecureElementMeta', - 'CA_GetUserContainerNumber', 'CK_ECDH2_DERIVE_PARAMS', - 'LUNA_RET_AGAIN', 'CA_InsertMaskedObject', + 'CK_C_GenerateKeyPair', 'CK_CA_STCGetCurrentKeyLife', + 'LUNA_RET_MTK_STATE_INVALID', 'CK_CA_GetTokenObjectUID', + 'CK_CA_PerformSelfTest', 'CK_ECDH2_DERIVE_PARAMS', 'LUNA_RET_NO_OFFBOARD_STORAGE', - 'CA_CloneAllObjectsToSession', - 'LUNA_RET_LOG_AUDIT_NOT_INITIALIZED', - 'CK_CA_STCGetPartPubKey', - 'LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL', - 'RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR', - 'CK_ECIES_PARAMS_PTR', + 'CK_CA_CheckOperationState', + 'RC_SSL_LOAD_CLIENT_CERT_ERROR', 'LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE', - 'LUNA_RET_SM_ACCESS_REALLOC_ERROR', 'CKCA_MODULE_INFO_PTR', - 'CA_WriteCommonStore', 'CA_InitializeRemotePEDVector', - 'MSG_RTC_EXTERNAL_TAMPER_LATCHED', 'CK_CA_MTKGetState', - 'LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD', 'CK_CA_SetMofN', + 'LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD', 'LUNA_RET_SELF_TEST_FAILURE', 'LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL', - 'LUNA_RET_HIFN6500_INVALID_PARAMETERS', - 'CA_CloseSecureToken', 'CK_CA_SpRawRead', - 'CK_CA_IsMofNEnabled', 'CK_C_SetAttributeValue', - 'C_GetObjectSize', 'RC_SSL_CIPHER_LIST_ERROR', - 'CK_CA_DismantleRemotePED', 'LUNA_RET_FUNCTION_CANCELED', - 'LUNA_RET_INVALID_ACCESS_LEVEL', - 'CK_CA_GetTokenInsertionCount', - 'LUNA_RET_INVALID_FUF_VERSION', - 'LUNA_RET_ISES_INIT_FAILED', - 'LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO', 'CK_PARAM_TYPE', - 'CK_CA_ListSecureToken', 'LUNA_RET_CHALLENGE_TYPE_INVALID', - 'C_GenerateRandom', 'CA_GetContainerCapabilitySet', - 'CK_CA_ClonePrivateKey', 'CK_CA_DeleteContainerWithHandle', - 'CK_HA_STATE_PTR', 'CA_GetTunnelSlotNumber', - 'LUNA_RET_RM_ELEMENT_ID_INVALID', 'CA_SetHSMPolicy', + 'RC_REMOTE_SIDE_DISCONNECTED', 'RC_SSL_CIPHER_LIST_ERROR', + 'CK_CA_DismantleRemotePED', 'LUNA_RET_INVALID_FUF_VERSION', + 'LUNA_RET_RIPEMD160_SELF_TEST_FAILURE', + 'CA_GetTokenCapabilities', 'CK_OBJECT_CLASS_PTR', + 'CK_RC2_PARAMS', 'RC_MANUFACTURING_NO_CONFIG_AVAILABLE', + 'LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID', + 'CA_GetSecondarySlot', 'LUNA_RET_TOKEN_LOCKED_OUT_CA', + 'RC_RESET_FAILED', 'HSM_STATS_PARAMS', + 'LUNA_RET_TOKEN_LOCKED_OUT_CL', + 'CK_CA_SetDestructiveHSMPolicy', 'CK_CA_InvokeServiceInit', + 'CA_GetMofNStatus', 'LUNA_RET_SIM_AUTHORIZATION_FAILED', + 'LUNA_RET_HA_NOT_SUPPORTED', 'CK_OTP_PARAM', + 'CA_STCRegister', 'RC_UNABLE_TO_CONNECT', + 'CK_CA_SpRawRead', + 'RC_SSL_CERT_VERIFICATION_LOCATION_ERROR', + 'LUNA_RET_CL_QUEUE_LOCATION_ERROR', + 'RC_SSL_INVALID_CERT_STRUCTURE', 'CK_C_GetOperationState', + 'LUNA_RET_HA_USER_NOT_INITIALIZED', 'RC_FILE_READ_ONLY', + 'LUNA_RET_HOK_MISSING', + 'LUNA_RET_HIFN_INVALID_MAC_ALGORITHM', 'CK_TOKEN_INFO', + 'CK_RSA_PKCS_OAEP_PARAMS', 'CK_SSL3_KEY_MAT_PARAMS_PTR', + 'CA_ReadCommonStore', 'LUNA_RET_HIFN6500_RNG_TIMEOUT', + 'LUNA_RET_VECTOR_TOO_LARGE', 'CK_CA_CapabilityUpdate', + 'CK_C_EncryptInit', 'LUNA_RET_TOKEN_LOCKED_OUT_STC', + 'C_Logout', + 'LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE', + 'LUNA_RET_KEY_TYPE_INCONSISTENT', + 'LUNA_RET_SPLIT_ID_INVALID', 'LUNA_RET_KEY_UNEXTRACTABLE', + 'LUNA_RET_BAD_SN', 'CA_MTKRestore', + 'CA_LKMInitiatorComplete', 'CA_CloneAsTargetInit', + 'MSG_NVRAM_WRITE_FAILED', 'LUNA_RET_TOKEN_LOCKED_OUT_MM', + 'CA_OpenApplicationIDForContainer', + 'CK_CA_GetTunnelSlotNumber', + 'RC_STC_DH_KEY_NOT_FROM_SAME_GROUP', + 'LUNA_RET_MTK_ZEROIZED', 'LUNA_RET_ECC_UNKNOWN_CURVE', + 'CA_LogSetConfig', 'SizeType', 'CK_CA_LogExportSecret', + 'CA_STCGetCipherIDs', 'CK_C_INITIALIZE_ARGS', + 'CA_GetTokenCertificateInfo', 'C_Decrypt', + 'CK_C_SignEncryptUpdate', 'CA_GetExtendedTPV', + 'RC_SSL_SYSCALL_ERROR', 'CA_GetContainerPolicySet', + 'CK_EXTRACT_PARAMS_PTR', 'LUNA_RET_RM_CONFIG_ILLEGAL', + 'LUNA_RET_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL', + 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'LUNA_RET_BAD_MAC', 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR', + 'LUNA_RET_CB_RETRY', 'MSG_RESTART', 'RC_FILE_NAME_INVALID', + 'C_DecryptDigestUpdate', 'CK_AES_GCM_PARAMS', + 'CK_HA_STATE_PTR', 'CA_LogGetConfig', + 'LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID', + 'CA_SetHSMPolicies', 'LUNA_RET_KCV_PARAMETER_MISSING', + 'CK_XOR_BASE_DATA_KDF_PARAMS', 'C_Finalize', + 'RC_SOCKET_ERROR', 'CA_InitAudit', 'LUNA_RET_KEY_PARITY', + 'MSG_RTC_CANT_INITIALIZE_I2C', + 'LUNA_RET_STORAGE_TYPE_INCONSISTENT', + 'CK_CA_GetExtendedTPV', 'CK_CA_SetHSMPolicy', + 'CK_CA_OpenSecureToken', 'CA_CapabilityUpdate', + 'C_GetSlotInfo', 'CK_HA_MEMBER', + 'LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST', + 'CA_STCGetDigestIDs', 'C_FindObjectsInit', 'CA_SIMExtract', + 'CA_DisableUnauthTokenInsertion', 'CK_C_FindObjectsInit', + 'CK_CA_STCGetSequenceWindowSize', + 'LUNA_RET_RC2_SELF_TEST_FAILURE', + 'CK_RSA_PKCS_OAEP_SOURCE_TYPE', 'CK_UNLOCKMUTEX', + 'LUNA_RET_ARGUMENTS_BAD', 'CKCA_MODULE_INFO', + 'MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF', + 'CK_RC5_CBC_PARAMS', 'CA_InvokeServiceSinglePart', + 'CK_KDF_PRF_ENCODING_SCHEME', + 'MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS', + 'LUNA_RET_M_TOO_LARGE', 'RC_STC_NO_SESSION_KEY', + 'RC_ENDOFLIST', 'LUNA_RET_LOG_NO_KCV', 'CK_C_DecryptInit', + 'CK_CA_UnloadModule', 'CA_OpenSession', + 'LUNA_RET_KEY_EXTRACTABLE', 'CA_DeleteContainerWithHandle', + 'CA_FactoryReset', 'CA_SetUserContainerName', + 'CK_PBE_PARAMS', 'CK_CA_InsertMaskedObject', + 'CA_STCGetState', 'RC_OBJECT_ALREADY_EXISTS', + 'LUNA_RET_SSK_MISSING', 'CK_CA_STCSetSequenceWindowSize', + 'LUNA_RET_LICENSE_ID_UNKNOWN', + 'LUNA_RET_KCDSA_PARAM_GEN_FAILURE', + 'LUNA_RET_TOKEN_NOT_PRESENT', 'CK_USER_TYPE', + 'C_GetMechanismList', 'LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO', + 'LUNA_RET_SFNT3120_ERROR', 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR', - 'CA_SetCloningDomain', 'CK_OBJECT_CLASS_PTR', - 'CK_CA_ChooseSecondarySlot', 'CK_CA_SetHSMPolicies', - 'LUNA_RET_WRAPPED_KEY_LEN_RANGE', 'CA_MOFN_STATUS_PTR', - 'CA_SetLKCV', 'CK_RC2_PARAMS', - 'LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE'] + 'RC_CLIENT_MESSAGE_ERROR', 'C_GetAttributeValue', + 'CA_ListSecureTokenInit', + 'MSG_ZEROIZING_AFTER_NO_SECURE_DATA', + 'CA_OpenApplicationID', 'LUNA_RET_CB_MUST_READ', + 'LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', + 'CA_STCGetKeyActivationTimeOut', 'CA_DuplicateMofN', + 'CK_CA_GetModuleList', + 'LUNA_RET_STC_CHANNEL_REALLOC_ERROR', + 'LUNA_RET_OBJECT_HANDLE_INVALID', 'C_GetFunctionStatus', + 'CK_OTP_PARAMS_PTR', 'LUNA_RET_RSA_SELF_TEST_FAILURE', + 'CK_CA_SetExtendedTPV', 'CA_STCGetCurrentKeyLife', + 'CK_C_SignFinal', 'CA_SetDestructiveHSMPolicy', + 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS', 'CK_UTF8CHAR_PTR', + 'LUNA_RET_ISES_TEST_VS_BSAFE_FAILED', 'swapper', + 'LUNA_RET_SM_TSV_MISSING', 'C_WrapKey', + 'LUNA_RET_KEY_HANDLE_INVALID', + 'CA_GetSlotListFromServerInstance', + 'RC_PARTITION_NOT_ACTIVATED', 'CK_ATTRIBUTE_TYPE', + 'CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR', + 'CK_CA_GetMofNStatus', 'CK_CA_GetRollbackFirmwareVersion', + 'LUNA_RET_RM_POLICY_WRITE_RESTRICTED', + 'CK_CA_GetContainerCapabilitySetting', 'SInt16', + 'CK_C_GetMechanismInfo', 'LUNA_RET_CITS_DAK_MISSING', + 'CK_ECMQV_DERIVE_PARAMS_PTR', + 'CK_CA_GetTokenCertificateInfo', 'CK_CA_DeleteContainer', + 'MSG_RTC_ZEROIZED_ON_POWER_LOSS', 'CA_STCGetPartPubKey', + 'C_DestroyObject', 'LUNA_RET_TOO_MANY_CONTAINERS', + 'LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED', + 'CA_EncodeECChar2Params', + 'LUNA_RET_RM_ELEMENT_VALUE_INVALID', + 'CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR', + 'LUNA_RET_CCM_SIGN_INVALID', 'C_GetSessionInfo', 'Int16', + 'LUNA_RET_ISES_CMD_PARAMETER_INVALID', + 'CK_CA_GetUserContainerNumber', + 'LUNA_RET_INVALID_CERTIFICATE_VERSION', + 'CK_SSL3_KEY_MAT_OUT_PTR', 'CK_C_GenerateRandom', + 'CK_CA_ModifyUsageCount', 'CA_MTKResplit', 'CK_CHAR', + 'CA_GetHSMStats', 'UInt8', + 'CA_GetUnauthTokenInsertionStatus', + 'LUNA_RET_VECTOR_VERSION_INVALID', + 'LUNA_RET_SIM_CORRUPT_DATA', 'CK_CMS_SIG_PARAMS_PTR', + 'LUNA_RET_LOG_FILE_NOT_OPEN', 'C_DeriveKey', + 'C_DigestUpdate', 'CK_CA_GetHSMStorageInformation', + 'RC_SOCKET_READ_ERROR', 'C_FindObjects', 'SInt64', + 'RC_INVALID_CERT_HOST', + 'LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD', 'SInt', + 'LUNA_RET_KEY_NOT_WRAPPABLE', + 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE', + 'LUNA_RET_HIFN_INVALID_PAD_ALGORITHM', 'RC_RC_ERROR', + 'CK_RSA_PKCS_MGF_TYPE', 'CK_EXTRACT_PARAMS', + 'LUNA_RET_OH_OBJECT_VERSION_INVALID', 'RC_SOCKET_BAD_FD', + 'LUNA_RET_CB_REMOTE_CLOSED', 'CK_RC5_CBC_PARAMS_PTR', + 'RC_PARTITION_LOCKED', 'CA_STCSetKeyLifeTime', + 'LUNA_RET_STC_SESSION_INVALID', 'LUNA_RET_HOC_MISSING', + 'CA_GetHSMPolicySetting', + 'CA_CreateContainerLoginChallenge', + 'CK_ResetTotalOperations', 'CA_MOFN_GENERATION_PTR', + 'CK_CA_InitSlotRolePIN', 'CK_AES_GCM_PARAMS_PTR', + 'CK_CA_EnableUnauthTokenInsertion', + 'CK_C_DecryptDigestUpdate', + 'LUNA_RET_CHALLENGE_RESPONSE_INCORRECT', + 'RC_MANUFACTURING_SERIAL_NUMBER_INVALID', + 'LUNA_RET_TEST_VS_BSAFE_FAILED', 'CA_Zeroize', + 'CA_HAAnswerMofNChallenge', 'RC_STC_DH_KEYGEN_ERROR', + 'CK_MAC_GENERAL_PARAMS_PTR', + 'LUNA_RET_SEED_SELF_TEST_FAILURE', 'CK_TOKEN_INFO_PTR', + 'CK_CA_STCGetDigestNameByID', + 'CK_AES_CBC_PAD_INSERT_PARAMS', + 'LUNA_RET_RC5_SELF_TEST_FAILURE', + 'LUNA_RET_USER_ALREADY_ACTIVATED', + 'LUNA_RET_CCM_NOT_SUPPORTED', + 'CK_CA_GetSlotIdForPhysicalSlot', + 'LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS', + 'CK_CA_LKMInitiatorChallenge', 'CK_CA_HAActivateMofN', + 'CK_KEY_DERIVATION_STRING_DATA', 'CK_MECHANISM_PTR', + 'CA_SetTokenCertificateSignature', + 'LUNA_RET_SM_BAD_ACCESS_HANDLE', + 'LUNA_RET_ECC_POINT_INVALID', 'CK_C_GetTokenInfo', + 'LUNA_RET_CB_HIOS_IO_ERROR', + 'LUNA_RET_M_OF_N_SECRET_INVALID', + 'LUNA_RET_SM_UNKNOWN_TOSM_STATE', + 'LUNA_RET_TEMPLATE_INCOMPLETE', + 'LUNA_RET_STC_CONTAINER_INVALID', + 'LUNA_RET_CB_REMOTE_ABANDONED', + 'LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID', + 'LUNA_RET_CB_PARAM_INVALID', 'CA_SwitchSecondarySlot', + 'LUNA_RET_HIFN6500_RNG_FAILED', 'CK_CA_STCGetAdminPubKey', + 'LUNA_RET_SFNT3120_SELFTEST_FAILED', + 'LUNA_RET_TOKEN_LOCKED_OUT_OH', 'CK_FUNCTION_LIST', + 'CK_CA_DuplicateMofN', 'LUNA_RET_INVALID_MODULUS_SIZE', + 'CK_RC5_PARAMS_PTR', 'CK_C_DigestInit', + 'LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID', + 'CA_ModifyMofN', 'LUNA_RET_USER_NOT_LOGGED_IN', + 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS', 'CA_InvokeServiceInit', + 'CK_CA_STCGetKeyActivationTimeOut', 'CA_GetTokenStatus', + 'C_SignUpdate', 'LUNA_RET_OPERATION_ACTIVE', + 'C_EncryptInit', 'CK_OTP_PARAMS', 'CK_SEED_CTR_PARAMS_PTR', + 'LUNA_RET_INVALID_FUF_HEADER', + 'CA_GetContainerCapabilitySet', 'C_DigestFinal', + 'RC_STC_FIRST_PHASE_KDF_ERROR', 'CK_CA_LockClusteredSlot', + 'LUNA_RET_SM_BAD_CONTEXT_NUMBER', + 'LUNA_RET_CB_HIOS_CLOSED', 'RC_CANCEL', + 'LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL', + 'LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL', + 'CA_EnableUnauthTokenInsertion', 'CK_CA_LogVerify', + 'CK_CA_GetTSV', 'CA_LKMReceiverComplete', + 'LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED', + 'LUNA_RET_CCM_FWUPDATE_DENIED', 'MSG_FACTORY_RESET', + 'RC_HOST_RESOLUTION_ERROR', 'CA_STCIsEnabled', + 'RC_STC_RSA_DECRYPT_ERROR', 'C_CloseSession', + 'LUNA_RET_MISSING_VECTOR', + 'LUNA_RET_ATTRIBUTE_TYPE_INVALID', 'LUNA_RET_CB_SYS_ERROR', + 'CK_EC_DH_PRIMITIVE', 'CK_C_Login', 'CA_IsMofNEnabled', + 'CK_CA_LogGetConfig', 'LUNA_RET_ISES_CMD_FAILED', + 'LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED', + 'LUNA_RET_410_BUFFER_TOO_SMALL', + 'LUNA_RET_USER_ALREADY_LOGGED_IN', + 'CK_FUNCTION_LIST_PTR_PTR', 'RC_STC_NOT_ENABLED', + 'CK_CA_GenerateTokenKeys', 'C_DecryptVerifyUpdate', + 'CK_UTF8CHAR', 'RC_CALLBACK_ERROR', 'RC_PORT_INVALID', + 'CK_CA_InitializeRemotePEDVector', 'C_DigestInit', + 'CA_GetContainerStorageInformation', 'RC_SSL_ERROR', + 'LUNA_RET_DSA_SELF_TEST_FAILURE', 'CA_GetHSMPolicySet', + 'C_CopyObject', 'CK_CA_CloseApplicationID', + 'LUNA_RET_ECC_BUFFER_OVERFLOW', 'CK_CA_Insert', + 'CK_NOTIFICATION', 'C_SignRecover', + 'CA_CreateLoginChallenge', 'C_EncryptUpdate', + 'LUNA_RET_STATE_UNSAVEABLE', 'CK_CA_GetContainerName', + 'MSG_ZEROIZING', 'CK_KDF_PRF_TYPE', + 'LUNA_RET_CL_NO_TRANSMISSION', 'RC_SIM_NOT_SUPPORTED', + 'LUNA_RET_MASKING_NOT_SUPPORTED', 'CK_C_GetObjectSize', + 'CK_CA_STCGetPartPubKey', 'RC_DER_CLASS_INVALID', + 'LUNA_RET_TPV_INVALID', 'CA_DeactivateMofN', + 'CK_ECDH1_DERIVE_PARAMS_PTR', 'LUNA_RET_VECTOR_TOO_SMALL', + 'CK_C_Encrypt', 'MSG_RTC_TAMPER_2_SIGNAL', + 'CA_CloseApplicationIDForContainer', 'C_DecryptUpdate', + 'Int8', 'LUNA_RET_HIFN_INVALID_ENCRYPT_MODE', + 'CK_C_DestroyObject', 'CK_CA_STCGetKeyLifeTime', + 'CK_CA_GetTokenStorageInformation', + 'CA_GetSlotIdForPhysicalSlot', 'RC_STC_RSA_SIGN_ERROR', + 'MSG_RTC_TAMPER_CIRCUITS_RE_ARMED', 'CK_C_InitToken', + 'LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID', + 'CK_CA_LKMReceiverResponse', 'CK_CA_GetUserContainerName', + 'CK_CA_MTKZeroize', 'CK_CA_GetClusterState', + 'LUNA_RET_AGAIN', 'CK_CA_STCClearCipherAlgorithm', + 'LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL', 'Float32', + 'CK_ECIES_PARAMS_PTR', 'CK_CA_GetPedId', + 'MSG_RTC_EXTERNAL_TAMPER_LATCHED', 'CK_CA_MTKGetState', + 'LUNA_RET_WRAPPED_KEY_LEN_RANGE', 'C_GetObjectSize', + 'CK_CA_GenerateCloneableMofN', 'CA_STCGetClientsList', + 'CA_STCGetSequenceWindowSize', + 'LUNA_RET_CHALLENGE_TYPE_INVALID', 'C_GenerateRandom', + 'CA_GetTunnelSlotNumber', 'CK_CA_IsMofNEnabled', + 'CA_SetLKCV'] diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index 27a0ec8..7b40fab 100644 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -11,7 +11,7 @@ array in initialize.py and rerun initialize.py. ''' -'''/home/new_builds/689/101/interfaces/Include/firmware/luna2if.h''' +'''/home/new_builds/1175/101/interfaces/Include/firmware/luna2if.h''' LUNA_MAX_UPDATE_DATA_SIZE= (64 * 1024) LUNA_GEN_KCV_FLAG_NONE= 0x0000 LUNA_GEN_KCV_FLAG_CONSOLIDATE= 0x0001 @@ -31,6 +31,9 @@ LUNA_MECH_SHA1_DSA= 0x00000012 LUNA_MECH_DH_PKCS_KEY_PAIR_GEN= 0x00000020 LUNA_MECH_DH_PKCS_DERIVE= 0x00000021 +LUNA_MECH_X9_42_DH_KEY_PAIR_GEN= 0x00000030 +LUNA_MECH_X9_42_DH_DERIVE= 0x00000031 +LUNA_MECH_X9_42_DH_HYBRID_DERIVE= 0x00000032 LUNA_MECH_SHA256_RSA_PKCS= 0x00000040 LUNA_MECH_SHA384_RSA_PKCS= 0x00000041 LUNA_MECH_SHA512_RSA_PKCS= 0x00000042 @@ -191,6 +194,12 @@ LUNA_MECH_SHA512_KCDSA= 0x0000870D LUNA_MECH_HMAC_HAS160= 0x0000870E LUNA_MECH_KCDSA_PARAMETER_GEN= 0x0000870F +LUNA_MECH_HAS160_KCDSA_NO_PAD= 0x00008710 +LUNA_MECH_SHA1_KCDSA_NO_PAD= 0x00008711 +LUNA_MECH_SHA224_KCDSA_NO_PAD= 0x00008712 +LUNA_MECH_SHA256_KCDSA_NO_PAD= 0x00008713 +LUNA_MECH_SHA384_KCDSA_NO_PAD= 0x00008714 +LUNA_MECH_SHA512_KCDSA_NO_PAD= 0x00008715 LUNA_MECH_AES_CBC_PAD_EXTRACT= 0x00009000 LUNA_MECH_AES_CBC_PAD_INSERT= 0x00009001 LUNA_MECH_AES_CBC_PAD_EXTRACT_FLATTENED= 0x00009002 @@ -239,6 +248,14 @@ LUNA_MECH_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN= 0x80000142 LUNA_MECH_AES_GMAC= 0x80000143 LUNA_MECH_SEED_CTR= 0x80008144 +LUNA_MECH_DES3_X919_MAC= 0x80000150 +LUNA_MECH_EC_KEY_PAIR_GEN_W_EXTRA_BITS= 0x80000160 +LUNA_MECH_SHA256_ECDSA_GBCS= 0x80000161 +LUNA_MECH_DES2_DUKPT_PIN= 0x80000611 +LUNA_MECH_DES2_DUKPT_MAC= 0x80000612 +LUNA_MECH_DES2_DUKPT_MAC_RESP= 0x80000613 +LUNA_MECH_DES2_DUKPT_DATA= 0x80000614 +LUNA_MECH_DES2_DUKPT_DATA_RESP= 0x80000615 LUNA_MECH_ECIES= 0x80000A00 LUNA_MECH_NIST_PRF_KDF= 0x80000A02 LUNA_MECH_PRF_KDF= 0x80000A03 @@ -363,6 +380,7 @@ LUNA_KEY_CDMF= 0x00000014 LUNA_KEY_AES= 0x0000001F LUNA_KEY_ARIA= 0x00000020 +LUNA_KEY_X9_42_DH= 0x00000021 LUNA_KEY_VENDOR_DEFINED= 0x80000000 LUNA_KEY_KCDSA= (LUNA_KEY_VENDOR_DEFINED + 0x10) LUNA_KEY_SEED= (LUNA_KEY_VENDOR_DEFINED + 0x11) @@ -444,6 +462,7 @@ LUNA_CF_HA_INITIALIZED= 0x08000000 LUNA_CF_PARTITION_INITIALIZED= 0x00000400 LUNA_CF_CONTAINER_ACTIVATED= 0x00000001 +LUNA_CF_CONTAINER_LUSR_ACTIVATED= 0x00000002 LUNA_CF_USER_PIN_INITIALIZED= 0x00008000 LUNA_CF_SO_PIN_LOCKED= 0x00010000 LUNA_CF_SO_PIN_TO_BE_CHANGED= 0x00020000 @@ -459,15 +478,17 @@ LUNA_ISAKMP_DECRYPT= 0x00000500 LUNA_ISAKMP_ENCRYPT_FIXED_IV= 0x00000501 LUNA_ISAKMP_ENCRYPT_GEN_IV= 0x00000502 -LUNA_ENTRY_DATA_AREA= 0x00000000 +LUNA_ENTRY_DATA_AREA= 0x00000000 # obsolete in NextGen/PerPartitionSO firmware LUNA_ENTRY_SECURE_PORT= 0x00000001 LUNA_ENTRY_INDIRECT= 0x00000002 # Obsolete as of f/w 5.0 LUNA_ENTRY_RANDOM= 0x00000003 # only used for pin creation LUNA_ENTRY_CHALLENGE_RESPONSE= 0x00000004 # only used for login LUNA_ENTRY_REMOTE_AUTHENTICATION= 0x00000005 +LUNA_ENTRY_DATA_AREA_MASKED= 0x00000006 LUNA_ENTRY_NONE= 0x000000FF # to indicate that nothing yet set. LUNA_PED_ID_SCP= 0x0000 LUNA_PED_ID_MAX= 0xFFFE +LUNA_MAX_PIN_LEN= 256 LUNA_UTYPE_NONE= 0xFFFFFFFF LUNA_UTYPE_USER= 0x00000000 LUNA_UTYPE_SO= 0x00000001 @@ -505,8 +526,9 @@ LUNA_TTYPE_ARIA_OFB= 0x00000010 LUNA_TTYPE_COMMUNICATION_PERFORMANCE_TEST= 0x00000011 LUNA_DSS2_G_GEN_TEST= 0x00000012 -LUNA_TTYPE_RSA_1863_AUX_PRIME_KEY_GEN_TEST= 0x00000013 -LUNA_TTYPE_RSA_1863_ONLY_PRIME_KEY_GEN_TEST=0x00000014 +LUNA_TTYPE_RSA_1863_AUX_PRIME_KEY_GEN_TEST= 0x00000013 +LUNA_TTYPE_RSA_1863_ONLY_PRIME_KEY_GEN_TEST= 0x00000014 +LUNA_TTYPE_X9_42_DOMAIN_PARAMETER_GENERATION_TEST= 0x00000015 LUNA_CTYPE_KCV= 0x00000000 LUNA_CTYPE_MOFN=0x00000001 HA_CMD_GET_LOGIN_CHALLENGE= 0x01 @@ -588,6 +610,9 @@ CONTAINER_CONFIG_SECRET_KEY_UNMASKING= 32 CONTAINER_CONFIG_RSA_PKCS_MECHANISM= 33 CONTAINER_CONFIG_CBC_PAD_WRAP_UNWRAP_KEYS_OF_ANY_SIZE= 34 +CONTAINER_CONFIG_PRIVATE_KEY_SMALL_FORM_FACTOR= 35 +CONTAINER_CONFIG_SECRET_KEY_SMALL_FORM_FACTOR= 36 +CONTAINER_CONFIG_SECURE_TRUSTED_CHANNEL= 37 HSM_CONFIG_ENABLE_PIN_AUTHENTICATION= 0 HSM_CONFIG_ENABLE_PED_AUTHENTICATION= 1 HSM_CONFIG_PERFORMANCE_LEVEL= 2 @@ -616,7 +641,7 @@ HSM_CONFIG_ENABLE_REMOTE_PED_USAGE= 25 HSM_CONFIG_STORE_MTK_SPLIT_EXTERNALLY= 26 HSM_CONFIG_STORAGE_SIZE= 27 -HSM_CONFIG_HA_MODE_CGX= 28 +HSM_CONFIG_OBSOLETE_28= 28 HSM_CONFIG_ENABLE_ACCELERATION= 29 HSM_CONFIG_UNMASKING= 30 HSM_CONFIG_ENABLE_FW5_COMPATIBILITY= 31 @@ -626,6 +651,11 @@ HSM_CONFIG_ENABLE_SINGLE_DOMAIN= 35 HSM_CONFIG_ALLOW_UNIFIED_PED_KEY= 36 HSM_CONFIG_ALLOW_MOFN= 37 +HSM_CONFIG_ENABLE_SMALL_FORM_FACTOR_BACKUP= 38 +HSM_CONFIG_ENABLE_SECURE_TRUSTED_CHANNEL= 39 +HSM_CONFIG_DECOMMISSION_ON_TAMPER= 40 +HSM_CONFIG_PER_PARTITION_SO= 41 +HSM_CONFIG_ENABLE_PARTITION_REINIT= 42 LUNA_CLONING_PART2_OVERHEAD= 76 LUNA_FLATTENED_OBJECT_OVERHEAD= 3264 LEGACY_TWC_ACCESS_LEVEL= 1 @@ -645,6 +675,7 @@ LUNA_CONTAINER_ACTIVATION_ELEMENT= 0x00000003 LUNA_MOFN_ACTIVATION_ELEMENT= 0x00000004 LUNA_CONTAINER_ELEMENT= 0x00000005 +LUNA_USER_PARTITION_ELEMENT= 0x00000006 LUNA_UNKNOWN_ELEMENT= (-1) LUNA_FW4_CRYPTOKI_ELEMENT= 0x00000000 LUNA_FW4_PARAM_ELEMENT= 0x00000001 @@ -785,6 +816,7 @@ LUNA_CKMS_SHA512= 0x0000000a LUNA_CKMS_HMAC_RIPEMD160= 0x0000000b LUNA_CKMS_RIPEMD160= 0x0000000c +LUNA_DUKPT_PARAM_LEN= 10 # KSN parameter is 10 bytes */ LUNA_LOG_WRITE= 0x000000c1 LUNA_LOG_POLL_HOST= 0x000000c2 # This one is both internal and external, between the host & f/w, so it's defined above LUNA_LOG_SET_CONFIG= 0x000000c5 # This one is both internal and external, between the host & f/w, so it's defined above @@ -795,11 +827,8 @@ LUNA_STATS_CPU_IDLE_TIME= 3 LUNA_STATS_ICD_COMMANDS_COUNT= 4 LUNA_STATS_UNKNOWN= 0xffffffff -LUNA_STC_CLIENT_NOT_SUPPORTED= 0x00000000 -LUNA_STC_CLIENT_FULL= 0x00000001 # lunapci functionality -LUNA_STC_CLIENT_LIMITED= 0x00000002 # lunaSA client functionality -LUNA_STC_CLIENT_RBS= 0x00000003 # Remote backup server functionality -'''/home/new_builds/689/101/tools/ekmtest/token.h''' +PED_PASSWORD_LENGTH=8 +'''/home/new_builds/1175/101/tools/ekmtest/token.h''' MAX_BUF_SIZE= 32000 MAX_SLOT_COUNT= 20 MAX_SESSION_COUNT= 20 @@ -810,7 +839,7 @@ LAST_MENU_ITEM= 204 MAX_FILE_NAME_SIZE= 512 # bytes */ XOR_KDF_MAX_SHARED_DATALEN= 512 # max. amount of shared data allowed -'''/home/new_builds/689/101/interfaces/Include/RSA/pkcs11t.h''' +'''/home/new_builds/1175/101/interfaces/Include/RSA/pkcs11t.h''' CRYPTOKI_VERSION_MAJOR=2 CRYPTOKI_VERSION_MINOR=20 CRYPTOKI_VERSION_AMENDMENT=3 @@ -851,7 +880,6 @@ CKS_RW_PUBLIC_SESSION= 2 CKS_RW_USER_FUNCTIONS= 3 CKS_RW_SO_FUNCTIONS= 4 -CKS_RW_AUDIT_FUNCTIONS= CKS_RW_SO_FUNCTIONS CKF_RW_SESSION= 0x00000002 # session is r/w */ CKF_SERIAL_SESSION= 0x00000004 # no parallel */ CKO_DATA= 0x00000000 @@ -1410,7 +1438,7 @@ CKF_EXCLUDE_CHALLENGE=0x00000008 CKF_EXCLUDE_PIN= 0x00000010 CKF_USER_FRIENDLY_OTP=0x00000020 -'''/home/new_builds/689/101/CoreLibrary/includes/cryptoki_v2.h''' +'''/home/new_builds/1175/101/CoreLibrary/includes/cryptoki_v2.h''' NULL_PTR= 0 C_LIBRARY_VERSION= 0x510 # v5.10 decimal */ CK_TOKEN_SERIAL_NUMBER_SIZE= 16 @@ -1426,6 +1454,9 @@ CKF_EXCLUSIVE_EXISTS= 0x0010 CKF_SO_SESSION= 0x8000 CKF_AUDIT_SESSION= 0x10000 +CKF_VENDER_DEFINED= 0x10000000 +CKF_IGNORE_HAONLY= (CKF_VENDER_DEFINED <<3) +CKF_USE_APPID= (CKF_VENDER_DEFINED <<2) CKF_ADMIN_TOKEN= 0x10000000 CKF_ENTRUST_READY= 0x00000001 CKF_NO_CLEAR_PINS= 0x00000002 @@ -1623,6 +1654,15 @@ CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x142) CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x143) CKM_SEED_CTR= (CKM_VENDOR_DEFINED + 0x144) +CKM_KCDSA_HAS160_NO_PAD= (CKM_VENDOR_DEFINED + 0x145) +CKM_KCDSA_SHA1_NO_PAD= (CKM_VENDOR_DEFINED + 0x146) +CKM_KCDSA_SHA224_NO_PAD= (CKM_VENDOR_DEFINED + 0x147) +CKM_KCDSA_SHA256_NO_PAD= (CKM_VENDOR_DEFINED + 0x148) +CKM_KCDSA_SHA384_NO_PAD= (CKM_VENDOR_DEFINED + 0x149) +CKM_KCDSA_SHA512_NO_PAD= (CKM_VENDOR_DEFINED + 0x151) +CKM_DES3_X919_MAC= (CKM_VENDOR_DEFINED + 0x150) +CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS= (CKM_VENDOR_DEFINED + 0x160) +CKM_ECDSA_GBCS_SHA256= (CKM_VENDOR_DEFINED + 0x161) CKM_AES_CBC_PAD_EXTRACT= (CKM_VENDOR_DEFINED + 0x200) CKM_AES_CBC_PAD_INSERT= (CKM_VENDOR_DEFINED + 0x201) CKM_AES_CBC_PAD_EXTRACT_FLATTENED= (CKM_VENDOR_DEFINED + 0x202) @@ -1630,6 +1670,11 @@ CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL= (CKM_VENDOR_DEFINED + 0x204) CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL= (CKM_VENDOR_DEFINED + 0x205) CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM=(CKM_VENDOR_DEFINED + 0x502) +CKM_DES2_DUKPT_PIN= (CKM_VENDOR_DEFINED + 0x611) +CKM_DES2_DUKPT_MAC= (CKM_VENDOR_DEFINED + 0x612) +CKM_DES2_DUKPT_MAC_RESP= (CKM_VENDOR_DEFINED + 0x613) +CKM_DES2_DUKPT_DATA= (CKM_VENDOR_DEFINED + 0x614) +CKM_DES2_DUKPT_DATA_RESP= (CKM_VENDOR_DEFINED + 0x615) CKM_ECIES= (CKM_VENDOR_DEFINED + 0xA00) CKM_XOR_BASE_AND_DATA_W_KDF= (CKM_VENDOR_DEFINED + 0xA01) CKM_NIST_PRF_KDF= (CKM_VENDOR_DEFINED + 0xA02) @@ -1729,6 +1774,43 @@ CKR_TOKEN_COPIED= (CKR_VENDOR_DEFINED + 0x42) CKR_SLOT_NOT_EMPTY= (CKR_VENDOR_DEFINED + 0x43) CKR_USER_ALREADY_ACTIVATED= (CKR_VENDOR_DEFINED + 0x44) +CKR_STC_NO_CONTEXT= (CKR_VENDOR_DEFINED + 0x45) +CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED= (CKR_VENDOR_DEFINED + 0x46) +CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED=(CKR_VENDOR_DEFINED + 0x47) +CKR_STC_DH_KEYGEN_ERROR= (CKR_VENDOR_DEFINED + 0x48) +CKR_STC_CIPHER_SUITE_REJECTED= (CKR_VENDOR_DEFINED + 0x49) +CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP= (CKR_VENDOR_DEFINED + 0x4a) +CKR_STC_COMPUTE_DH_KEY_ERROR= (CKR_VENDOR_DEFINED + 0x4b) +CKR_STC_FIRST_PHASE_KDF_ERROR= (CKR_VENDOR_DEFINED + 0x4c) +CKR_STC_SECOND_PHASE_KDF_ERROR= (CKR_VENDOR_DEFINED + 0x4d) +CKR_STC_KEY_CONFIRMATION_FAILED= (CKR_VENDOR_DEFINED + 0x4e) +CKR_STC_NO_SESSION_KEY= (CKR_VENDOR_DEFINED + 0x4f) +CKR_STC_RESPONSE_BAD_MAC= (CKR_VENDOR_DEFINED + 0x50) +CKR_STC_NOT_ENABLED= (CKR_VENDOR_DEFINED + 0x51) +CKR_STC_CLIENT_HANDLE_INVALID= (CKR_VENDOR_DEFINED + 0x52) +CKR_STC_SESSION_INVALID= (CKR_VENDOR_DEFINED + 0x53) +CKR_STC_CONTAINER_INVALID= (CKR_VENDOR_DEFINED + 0x54) +CKR_STC_SEQUENCE_NUM_INVALID= (CKR_VENDOR_DEFINED + 0x55) +CKR_STC_NO_CHANNEL= (CKR_VENDOR_DEFINED + 0x56) +CKR_STC_RESPONSE_DECRYPT_ERROR= (CKR_VENDOR_DEFINED + 0x57) +CKR_STC_RESPONSE_REPLAYED= (CKR_VENDOR_DEFINED + 0X58) +CKR_STC_REKEY_CHANNEL_MISMATCH= (CKR_VENDOR_DEFINED + 0X59) +CKR_STC_RSA_ENCRYPT_ERROR= (CKR_VENDOR_DEFINED + 0X5a) +CKR_STC_RSA_SIGN_ERROR= (CKR_VENDOR_DEFINED + 0X5b) +CKR_STC_RSA_DECRYPT_ERROR= (CKR_VENDOR_DEFINED + 0X5c) +CKR_STC_RESPONSE_UNEXPECTED_KEY= (CKR_VENDOR_DEFINED + 0X5d) +CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE= (CKR_VENDOR_DEFINED + 0X5e) +CKR_STC_UNEXPECTED_DH_DATA_SIZE= (CKR_VENDOR_DEFINED + 0X5f) +CKR_STC_OPEN_CIPHER_MISMATCH= (CKR_VENDOR_DEFINED + 0X60) +CKR_STC_OPEN_DHNIST_PUBKEY_ERROR= (CKR_VENDOR_DEFINED + 0X61) +CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X62) +CKR_STC_OPEN_RESP_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X63) +CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL= (CKR_VENDOR_DEFINED + 0X64) +CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X65) +CKR_STC_ACTIVATE_RESP_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X66) +CKR_CHALLENGE_INCORRECT= (CKR_VENDOR_DEFINED + 0X67) +CKR_ACCESS_ID_INVALID= (CKR_VENDOR_DEFINED + 0X68) +CKR_ACCESS_ID_ALREADY_EXISTS= (CKR_VENDOR_DEFINED + 0X69) CKR_OBJECT_READ_ONLY= (CKR_VENDOR_DEFINED + 0x114) CKR_KEY_NOT_ACTIVE= (CKR_VENDOR_DEFINED + 0x136) CKO_TOKEN_ROLE_POLICY_SET= (CKO_VENDOR_DEFINED + 0x0001) @@ -1742,12 +1824,14 @@ CKO_FM= (CKO_VENDOR_DEFINED + 0x020C) CKS_RO_SO_FUNCTIONS= 5 # still in PKCS #11 space */ CKS_RO_VENDOR_DEFINED= 0x80000000 -CKS_RW_AUDIT_FUNCTIONS= CKS_RW_SO_FUNCTIONS +CKS_RW_VENDOR_DEFINED= 0x90000000 +CKS_RW_AUDIT_FUNCTIONS= (CKS_RW_VENDOR_DEFINED + 0x001) CAF_ROLE_STATE_INITIALIZED= 0x01 CAF_ROLE_STATE_LOCKED_OUT= 0x02 CAF_ROLE_STATE_ACTIVATED= 0x04 CAF_ROLE_STATE_HAS_RDK= 0x08 CAF_ROLE_STATE_PIN_CHANGE= 0x10 +CAF_ROLE_STATE_CHALLENGE_CHANGE=0x20 CKA_ROLE_AUTH_NONE= 0x00 CKA_ROLE_AUTH_PASSWORD= 0x01 CKA_ROLE_AUTH_PED= 0x02 diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index c47f991..a794ec4 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -2,10 +2,21 @@ Methods responsible for pycryptoki 'hsm management' set of commands. """ from ctypes import byref, create_string_buffer, cast -from pycryptoki.cryptoki import CK_SLOT_ID, CK_USER_TYPE, \ - C_PerformSelfTest, CA_SetTokenCertificateSignature, CA_HAInit, \ - CA_CreateLoginChallenge, CA_InitializeRemotePEDVector, \ - CA_DeleteRemotePEDVector, CA_MTKRestore, CA_MTKResplit, CA_MTKZeroize, CK_ULONG, CK_BYTE_PTR, CK_BYTE, CK_CHAR_PTR, CK_CHAR +from pycryptoki.cryptoki import (CK_SLOT_ID, + CK_USER_TYPE, + CA_SetTokenCertificateSignature, + CA_HAInit, + CA_CreateLoginChallenge, + CA_InitializeRemotePEDVector, + CA_DeleteRemotePEDVector, + CA_MTKRestore, + CA_MTKResplit, + CA_MTKZeroize, + CK_ULONG, + CK_BYTE_PTR, + CK_BYTE, + CK_CHAR_PTR, + CK_CHAR) from pycryptoki.attributes import Attributes from pycryptoki.test_functions import make_error_handle_function @@ -20,9 +31,7 @@ def c_performselftest(slot, @param slot: slot number @param test_type: type of test CK_ULONG @param input_data: pointer to input data CK_BYTE_PTR - @param input_length: input data length CK_ULONG - @param output_data: pointer to output data CK_BYTE_PTR - @param output_length: output data length CK_ULONG_PTR + @param input_data_len: input data length CK_ULONG @return: the result code [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] @@ -33,13 +42,17 @@ def c_performselftest(slot, input_data = (CK_BYTE * input_data)() output_data = cast(create_string_buffer('', input_data_len), CK_BYTE_PTR) output_data_len = CK_ULONG() - - ret = C_PerformSelfTest(slot, - test_type, - input_data, - input_length, - output_data, - byref(output_data_len)) + try: + from pycryptoki.cryptoki import CA_PerformSelfTest as selftest + except ImportError: + from pycryptoki.cryptoki import C_PerformSelftest as selftest + + ret = selftest(slot, + test_type, + input_data, + input_length, + output_data, + byref(output_data_len)) return ret, output_data c_performselftest_ex = make_error_handle_function(c_performselftest) diff --git a/pycryptoki/return_values.py b/pycryptoki/return_values.py index f3d8afe..b79e0ec 100644 --- a/pycryptoki/return_values.py +++ b/pycryptoki/return_values.py @@ -169,6 +169,43 @@ CKR_TOKEN_COPIED : 'CKR_TOKEN_COPIED', CKR_SLOT_NOT_EMPTY : 'CKR_SLOT_NOT_EMPTY', CKR_USER_ALREADY_ACTIVATED : 'CKR_USER_ALREADY_ACTIVATED', + CKR_STC_NO_CONTEXT : 'CKR_STC_NO_CONTEXT', + CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED : 'CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED', + CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED : 'CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED', + CKR_STC_DH_KEYGEN_ERROR : 'CKR_STC_DH_KEYGEN_ERROR', + CKR_STC_CIPHER_SUITE_REJECTED : 'CKR_STC_CIPHER_SUITE_REJECTED', + CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP : 'CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP', + CKR_STC_COMPUTE_DH_KEY_ERROR : 'CKR_STC_COMPUTE_DH_KEY_ERROR', + CKR_STC_FIRST_PHASE_KDF_ERROR : 'CKR_STC_FIRST_PHASE_KDF_ERROR', + CKR_STC_SECOND_PHASE_KDF_ERROR : 'CKR_STC_SECOND_PHASE_KDF_ERROR', + CKR_STC_KEY_CONFIRMATION_FAILED : 'CKR_STC_KEY_CONFIRMATION_FAILED', + CKR_STC_NO_SESSION_KEY : 'CKR_STC_NO_SESSION_KEY', + CKR_STC_RESPONSE_BAD_MAC : 'CKR_STC_RESPONSE_BAD_MAC', + CKR_STC_NOT_ENABLED : 'CKR_STC_NOT_ENABLED', + CKR_STC_CLIENT_HANDLE_INVALID : 'CKR_STC_CLIENT_HANDLE_INVALID', + CKR_STC_SESSION_INVALID : 'CKR_STC_SESSION_INVALID', + CKR_STC_CONTAINER_INVALID : 'CKR_STC_CONTAINER_INVALID', + CKR_STC_SEQUENCE_NUM_INVALID : 'CKR_STC_SEQUENCE_NUM_INVALID', + CKR_STC_NO_CHANNEL : 'CKR_STC_NO_CHANNEL', + CKR_STC_RESPONSE_DECRYPT_ERROR : 'CKR_STC_RESPONSE_DECRYPT_ERROR', + CKR_STC_RESPONSE_REPLAYED : 'CKR_STC_RESPONSE_REPLAYED', + CKR_STC_REKEY_CHANNEL_MISMATCH : 'CKR_STC_REKEY_CHANNEL_MISMATCH', + CKR_STC_RSA_ENCRYPT_ERROR : 'CKR_STC_RSA_ENCRYPT_ERROR', + CKR_STC_RSA_SIGN_ERROR : 'CKR_STC_RSA_SIGN_ERROR', + CKR_STC_RSA_DECRYPT_ERROR : 'CKR_STC_RSA_DECRYPT_ERROR', + CKR_STC_RESPONSE_UNEXPECTED_KEY : 'CKR_STC_RESPONSE_UNEXPECTED_KEY', + CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE : 'CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE', + CKR_STC_UNEXPECTED_DH_DATA_SIZE : 'CKR_STC_UNEXPECTED_DH_DATA_SIZE', + CKR_STC_OPEN_CIPHER_MISMATCH : 'CKR_STC_OPEN_CIPHER_MISMATCH', + CKR_STC_OPEN_DHNIST_PUBKEY_ERROR : 'CKR_STC_OPEN_DHNIST_PUBKEY_ERROR', + CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL : 'CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL', + CKR_STC_OPEN_RESP_GEN_FAIL : 'CKR_STC_OPEN_RESP_GEN_FAIL', + CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL : 'CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL', + CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL : 'CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL', + CKR_STC_ACTIVATE_RESP_GEN_FAIL : 'CKR_STC_ACTIVATE_RESP_GEN_FAIL', + CKR_CHALLENGE_INCORRECT : 'CKR_CHALLENGE_INCORRECT', + CKR_ACCESS_ID_INVALID : 'CKR_ACCESS_ID_INVALID', + CKR_ACCESS_ID_ALREADY_EXISTS : 'CKR_ACCESS_ID_ALREADY_EXISTS', CKR_OBJECT_READ_ONLY : 'CKR_OBJECT_READ_ONLY', CKR_KEY_NOT_ACTIVE : 'CKR_KEY_NOT_ACTIVE' } \ No newline at end of file From b4fcfba418c4f368038f6c92c18ba87318303db6 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 20 May 2015 11:05:39 -0400 Subject: [PATCH 007/109] LA-1071 Pyment changes & PEP8 changes Fixed up a lot of classes so that docstrings appear properly in sphinx. Fixed most files so that they abide by PEP8 at least a little bit. Fixed some other docstring issues. Change-Id: I3d9cbbdd55a5980bf739ffbee716c77a4e53aec9 --- docs/conf.py | 268 ++ docs/index.rst | 22 + docs/modules.rst | 7 + docs/pycryptoki.daemon.rst | 11 + docs/pycryptoki.rst | 232 + docs/pycryptoki.setup.rst | 46 + docs/pycryptoki.tests.rst | 141 + docs/pycryptoki.tests.stress.rst | 38 + docs/pycryptoki.utils.rst | 22 + pycryptoki/attributes.py | 182 +- pycryptoki/audit_handling.py | 45 +- pycryptoki/backup.py | 59 +- pycryptoki/cryptoki.py | 652 ++- pycryptoki/cryptoki_helpers.py | 95 +- pycryptoki/daemon/pycryptoki_daemon.py | 161 +- pycryptoki/daemon/rpyc_pycryptoki.py | 197 +- pycryptoki/default_templates.py | 1407 ++++--- pycryptoki/defaults.py | 22 +- pycryptoki/defines.py | 3752 ++++++++--------- pycryptoki/dictionary_handling.py | 12 +- pycryptoki/encryption.py | 335 +- pycryptoki/hsm_management.py | 140 +- pycryptoki/key_generator.py | 166 +- pycryptoki/key_management.py | 43 +- pycryptoki/key_usage.py | 27 +- pycryptoki/logging_filters.py | 16 +- pycryptoki/luna_threading.py | 99 +- pycryptoki/mechanism.py | 124 +- pycryptoki/misc.py | 178 +- pycryptoki/object_attr_lookup.py | 82 +- pycryptoki/policy_management.py | 67 +- pycryptoki/pycryptoki_client.py | 77 +- pycryptoki/return_values.py | 398 +- pycryptoki/session_management.py | 314 +- pycryptoki/setup/distribute.py | 4 +- pycryptoki/setup/initialize.py | 208 +- pycryptoki/setup/make_and_install.py | 6 +- pycryptoki/setup/verify_version.py | 15 +- pycryptoki/sign_verify.py | 238 +- pycryptoki/test_functions.py | 199 +- pycryptoki/tests/run_tests_in_folder.py | 6 +- pycryptoki/tests/setup_for_tests.py | 21 +- pycryptoki/tests/stress/conftest.py | 12 +- pycryptoki/tests/stress/test_multi_reset.py | 187 +- pycryptoki/tests/stress/vreset_thread.py | 27 +- pycryptoki/tests/test_cka_start_and_end.py | 193 +- pycryptoki/tests/test_digest_data.py | 28 +- pycryptoki/tests/test_encrypt_decrypt.py | 57 +- pycryptoki/tests/test_get_token_info.py | 37 +- pycryptoki/tests/test_hsm_management.py | 80 +- pycryptoki/tests/test_key_management.py | 28 +- pycryptoki/tests/test_key_usage.py | 24 +- pycryptoki/tests/test_keys.py | 103 +- pycryptoki/tests/test_object_create.py | 43 +- pycryptoki/tests/test_sign_verify.py | 80 +- .../tests/test_supporting_operations.py | 40 +- .../tests/test_usage_limit_and_count.py | 234 +- pycryptoki/tests/test_wrap_unwrap.py | 60 +- pycryptoki/token_management.py | 100 +- pycryptoki/utils/__init__.py | 0 pycryptoki/utils/common_utils.py | 1 + 61 files changed, 6694 insertions(+), 4774 deletions(-) create mode 100644 docs/conf.py create mode 100644 docs/index.rst create mode 100644 docs/modules.rst create mode 100644 docs/pycryptoki.daemon.rst create mode 100644 docs/pycryptoki.rst create mode 100644 docs/pycryptoki.setup.rst create mode 100644 docs/pycryptoki.tests.rst create mode 100644 docs/pycryptoki.tests.stress.rst create mode 100644 docs/pycryptoki.utils.rst mode change 100644 => 100755 pycryptoki/cryptoki.py mode change 100644 => 100755 pycryptoki/defines.py mode change 100644 => 100755 pycryptoki/return_values.py mode change 100755 => 100644 pycryptoki/utils/__init__.py mode change 100755 => 100644 pycryptoki/utils/common_utils.py diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..739d229 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- +# +# Pycryptoki documentation build configuration file, created by +# sphinx-quickstart on Wed May 20 08:09:23 2015. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.doctest', + 'sphinx.ext.intersphinx', + 'sphinx.ext.todo', + 'sphinx.ext.viewcode', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Pycryptoki' +copyright = u'2015, Gemalto (Michael Hughes/Ashley Straw)' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '1.0' +# The full version, including alpha/beta/rc tags. +release = '1.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Pycryptokidoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ('index', 'Pycryptoki.tex', u'Pycryptoki Documentation', + u'Gemalto (Michael Hughes/Ashley Straw)', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'pycryptoki', u'Pycryptoki Documentation', + [u'Gemalto (Michael Hughes/Ashley Straw)'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'Pycryptoki', u'Pycryptoki Documentation', + u'Gemalto (Michael Hughes/Ashley Straw)', 'Pycryptoki', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'http://docs.python.org/': None} diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..0440ef7 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,22 @@ +.. Pycryptoki documentation master file, created by + sphinx-quickstart on Wed May 20 08:09:23 2015. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Pycryptoki's documentation! +====================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/modules.rst b/docs/modules.rst new file mode 100644 index 0000000..dec241b --- /dev/null +++ b/docs/modules.rst @@ -0,0 +1,7 @@ +pycryptoki +========== + +.. toctree:: + :maxdepth: 4 + + pycryptoki diff --git a/docs/pycryptoki.daemon.rst b/docs/pycryptoki.daemon.rst new file mode 100644 index 0000000..7aa3627 --- /dev/null +++ b/docs/pycryptoki.daemon.rst @@ -0,0 +1,11 @@ +Pycryptoki Daemon Package +========================= + +rpyc_pycryptoki +--------------- + +.. automodule:: pycryptoki.daemon.rpyc_pycryptoki + :members: + :undoc-members: + :show-inheritance: + diff --git a/docs/pycryptoki.rst b/docs/pycryptoki.rst new file mode 100644 index 0000000..0c2e5fc --- /dev/null +++ b/docs/pycryptoki.rst @@ -0,0 +1,232 @@ +pycryptoki package +================== + +Subpackages +----------- + +.. toctree:: + + pycryptoki.daemon + pycryptoki.setup + pycryptoki.tests + pycryptoki.utils + +Submodules +---------- + +pycryptoki.attributes module +---------------------------- + +.. automodule:: pycryptoki.attributes + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.audit_handling module +-------------------------------- + +.. automodule:: pycryptoki.audit_handling + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.backup module +------------------------ + +.. automodule:: pycryptoki.backup + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.cryptoki module +-------------------------- + +.. automodule:: pycryptoki.cryptoki + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.cryptoki_helpers module +---------------------------------- + +.. automodule:: pycryptoki.cryptoki_helpers + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.default_templates module +----------------------------------- + +.. automodule:: pycryptoki.default_templates + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.defaults module +-------------------------- + +.. automodule:: pycryptoki.defaults + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.defines module +------------------------- + +.. automodule:: pycryptoki.defines + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.dictionary_handling module +------------------------------------- + +.. automodule:: pycryptoki.dictionary_handling + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.encryption module +---------------------------- + +.. automodule:: pycryptoki.encryption + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.hsm_management module +-------------------------------- + +.. automodule:: pycryptoki.hsm_management + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.key_generator module +------------------------------- + +.. automodule:: pycryptoki.key_generator + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.key_management module +-------------------------------- + +.. automodule:: pycryptoki.key_management + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.key_usage module +--------------------------- + +.. automodule:: pycryptoki.key_usage + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.logging_filters module +--------------------------------- + +.. automodule:: pycryptoki.logging_filters + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.luna_threading module +-------------------------------- + +.. automodule:: pycryptoki.luna_threading + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.mechanism module +--------------------------- + +.. automodule:: pycryptoki.mechanism + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.misc module +---------------------- + +.. automodule:: pycryptoki.misc + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.object_attr_lookup module +------------------------------------ + +.. automodule:: pycryptoki.object_attr_lookup + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.policy_management module +----------------------------------- + +.. automodule:: pycryptoki.policy_management + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.pycryptoki_client module +----------------------------------- + +.. automodule:: pycryptoki.pycryptoki_client + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.return_values module +------------------------------- + +.. automodule:: pycryptoki.return_values + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.session_management module +------------------------------------ + +.. automodule:: pycryptoki.session_management + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.sign_verify module +----------------------------- + +.. automodule:: pycryptoki.sign_verify + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.test_functions module +-------------------------------- + +.. automodule:: pycryptoki.test_functions + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.token_management module +---------------------------------- + +.. automodule:: pycryptoki.token_management + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pycryptoki + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/pycryptoki.setup.rst b/docs/pycryptoki.setup.rst new file mode 100644 index 0000000..57e3f22 --- /dev/null +++ b/docs/pycryptoki.setup.rst @@ -0,0 +1,46 @@ +pycryptoki.setup package +======================== + +Submodules +---------- + +pycryptoki.setup.distribute module +---------------------------------- + +.. automodule:: pycryptoki.setup.distribute + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.setup.initialize module +---------------------------------- + +.. automodule:: pycryptoki.setup.initialize + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.setup.make_and_install module +---------------------------------------- + +.. automodule:: pycryptoki.setup.make_and_install + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.setup.verify_version module +-------------------------------------- + +.. automodule:: pycryptoki.setup.verify_version + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pycryptoki.setup + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/pycryptoki.tests.rst b/docs/pycryptoki.tests.rst new file mode 100644 index 0000000..af1c37f --- /dev/null +++ b/docs/pycryptoki.tests.rst @@ -0,0 +1,141 @@ +pycryptoki.tests package +======================== + +Subpackages +----------- + +.. toctree:: + + pycryptoki.tests.stress + +Submodules +---------- + +pycryptoki.tests.run_tests_in_folder module +------------------------------------------- + +.. automodule:: pycryptoki.tests.run_tests_in_folder + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.setup_for_tests module +--------------------------------------- + +.. automodule:: pycryptoki.tests.setup_for_tests + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_cka_start_and_end module +---------------------------------------------- + +.. automodule:: pycryptoki.tests.test_cka_start_and_end + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_digest_data module +---------------------------------------- + +.. automodule:: pycryptoki.tests.test_digest_data + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_encrypt_decrypt module +-------------------------------------------- + +.. automodule:: pycryptoki.tests.test_encrypt_decrypt + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_get_token_info module +------------------------------------------- + +.. automodule:: pycryptoki.tests.test_get_token_info + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_hsm_management module +------------------------------------------- + +.. automodule:: pycryptoki.tests.test_hsm_management + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_key_management module +------------------------------------------- + +.. automodule:: pycryptoki.tests.test_key_management + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_key_usage module +-------------------------------------- + +.. automodule:: pycryptoki.tests.test_key_usage + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_keys module +--------------------------------- + +.. automodule:: pycryptoki.tests.test_keys + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_object_create module +------------------------------------------ + +.. automodule:: pycryptoki.tests.test_object_create + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_sign_verify module +---------------------------------------- + +.. automodule:: pycryptoki.tests.test_sign_verify + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_supporting_operations module +-------------------------------------------------- + +.. automodule:: pycryptoki.tests.test_supporting_operations + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_usage_limit_and_count module +-------------------------------------------------- + +.. automodule:: pycryptoki.tests.test_usage_limit_and_count + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.test_wrap_unwrap module +---------------------------------------- + +.. automodule:: pycryptoki.tests.test_wrap_unwrap + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pycryptoki.tests + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/pycryptoki.tests.stress.rst b/docs/pycryptoki.tests.stress.rst new file mode 100644 index 0000000..132720e --- /dev/null +++ b/docs/pycryptoki.tests.stress.rst @@ -0,0 +1,38 @@ +pycryptoki.tests.stress package +=============================== + +Submodules +---------- + +pycryptoki.tests.stress.conftest module +--------------------------------------- + +.. automodule:: pycryptoki.tests.stress.conftest + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.stress.test_multi_reset module +----------------------------------------------- + +.. automodule:: pycryptoki.tests.stress.test_multi_reset + :members: + :undoc-members: + :show-inheritance: + +pycryptoki.tests.stress.vreset_thread module +-------------------------------------------- + +.. automodule:: pycryptoki.tests.stress.vreset_thread + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pycryptoki.tests.stress + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/pycryptoki.utils.rst b/docs/pycryptoki.utils.rst new file mode 100644 index 0000000..1530033 --- /dev/null +++ b/docs/pycryptoki.utils.rst @@ -0,0 +1,22 @@ +pycryptoki.utils package +======================== + +Submodules +---------- + +pycryptoki.utils.common_utils module +------------------------------------ + +.. automodule:: pycryptoki.utils.common_utils + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pycryptoki.utils + :members: + :undoc-members: + :show-inheritance: diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 9c18fd6..5e25b54 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -3,10 +3,11 @@ generation to make it possible to create templates in python and easily convert them into templates in C. """ -from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ - CK_BYTE, C_GetAttributeValue, CK_OBJECT_HANDLE, CK_DATE, CK_CHAR, CK_CHAR_PTR from ctypes import cast, c_void_p, create_string_buffer, c_bool, c_char_p, \ c_ulong, pointer, POINTER, byref, sizeof, c_int, c_ubyte + +from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ + CK_BYTE, C_GetAttributeValue, CK_OBJECT_HANDLE, CK_DATE, CK_CHAR, CK_CHAR_PTR from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_VALUE, CKA_CERTIFICATE_TYPE, \ CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ @@ -20,11 +21,10 @@ CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_PKC_TCTRUST, CKA_PKC_CITS, \ CKA_OUID, \ CKA_X9_31_GENERATED, CKA_PKC_ECC, CKR_OK -from pycryptoki.cryptoki import CK_ULONG_PTR, CK_ATTRIBUTE_PTR, CK_BYTE_PTR +from pycryptoki.cryptoki import CK_ULONG_PTR from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ CKA_GENERIC_3 from pycryptoki.dictionary_handling import CDict -import logging ''' List class for handling attributes with lists of a certain type @@ -32,6 +32,7 @@ class CList: + """ """ list_type = None def __init__(self, list_type): @@ -39,6 +40,7 @@ def __init__(self, list_type): class NonAsciiString: + """ """ data = None def __init__(self, data): @@ -46,12 +48,13 @@ def __init__(self, data): def get_byte_list_from_python_list(python_byte_list): - ''' - Helper method to create a C style byte list from a python + """Helper method to create a C style byte list from a python style list of integers. - @param python_byte_list: A list of integers to convert to a C style list of integers - @return: The pointer to the C representation of the python byte list - ''' + + :param python_byte_list: A list of integers to convert to a C style list of integers + :returns: The pointer to the C representation of the python byte list + + """ list_val = create_string_buffer("", len(python_byte_list)) ptr = cast(pointer(list_val), c_void_p) for j in range(0, len(python_byte_list)): @@ -133,8 +136,7 @@ def get_byte_list_from_python_list(python_byte_list): def to_byte_array(val): - """ - Converts an arbitrarily sized integer into a byte array. + """Converts an arbitrarily sized integer into a byte array. It'll zero-pad the bit length so it's a multiple of 8, then convert the int to binary, split the binary string into sections of 8, then @@ -143,6 +145,7 @@ def to_byte_array(val): :param val: Big Integer to convert. :return: c_ubyte array + """ # Explicitly convert to a long. Python doesn't like X.bit_length() where X is an int # and not a variable assigned an int. @@ -158,20 +161,21 @@ def to_byte_array(val): class Attributes: - ''' - A wrapper around all of the attributes necessary to create a key. + """A wrapper around all of the attributes necessary to create a key. Has a python dictionary object containing python types, the corresponding C struct can then be generated with a simple method call. - ''' + + + """ attributes = {} def __init__(self, attributes_list=None): - ''' + """ Initializes a Attributes object, the attributes_list argument is optional since the attributes object can be populated from the board later @param attributes_list: The list of python style attributes to create the class with. - ''' + """ if attributes_list is not None: # take either strings or ints as the key to the dictionary (used mainly to accomodate @@ -190,12 +194,12 @@ def __init__(self, attributes_list=None): self.attributes = attributes_list def add_attribute(self, key, value): - ''' - Add an attribute to the dictionary in place + """Add an attribute to the dictionary in place + + :param key: The type of the attribute + :param value: The value of the attribute - @param key: The type of the attribute - @param value: The value of the attribute - ''' + """ if isinstance(key, str): # take either strings or ints for the key (used mainly to accomodate xmlrpc easily) key = int(key) @@ -204,29 +208,30 @@ def add_attribute(self, key, value): self.attributes[key] = value def _input_check(self, key, value): - ''' - Checks to see if the type is supported (yet) + """Checks to see if the type is supported (yet) - @param key: They key of the attribute to check - @param value: The actual value of the input to check - @return: Returns true if the variable is a of a type that has been accounted for in the + :param key: They key of the attribute to check + :param value: The actual value of the input to check + :returns: Returns true if the variable is a of a type that has been accounted for in the key_attributes dictionary - ''' + + """ if isinstance(value, bool) or isinstance(value, int) or isinstance(value, CDict) or isinstance( - value, long) or isinstance(value, str) or isinstance(value, list) or isinstance( - value, CList) or isinstance(value, NonAsciiString): + value, long) or isinstance(value, str) or isinstance(value, list) or isinstance( + value, CList) or isinstance(value, NonAsciiString): return True else: raise Exception( "Argument type not supported. ") def get_c_struct(self): - ''' - Assembles and returns a proper C struct from the dictionary of python attributes + """Assembles and returns a proper C struct from the dictionary of python attributes - @return: Returns a Ctypes struct representing the python attributes stored in this class - ''' + + :returns: Returns a Ctypes struct representing the python attributes stored in this class + + """ c_struct = (CK_ATTRIBUTE * len(self.attributes))() i = 0 @@ -235,8 +240,8 @@ def get_c_struct(self): self._input_check(key, value) # Get the proper type for what your data is, originally I had - #this automatically detected from the python type but passing in - #int's vs longs was problematic + # this automatically detected from the python type but passing in + # int's vs longs was problematic item_type = lookup_attributes(key) if item_type == bool: @@ -294,18 +299,18 @@ def get_c_struct(self): else: raise Exception("Argument type " + str(item_type) + " not supported. ") - i = i + 1 + i += 1 return c_struct def retrieve_key_attributes(self, h_session, h_object): - ''' - Gets all of the key's attributes from the board given the key's handle, + """Gets all of the key's attributes from the board given the key's handle, and populates the KeyAttribute object with all of those attributes. - @param h_session: Current session - @param h_object: The handle of the object to fetch the attributes for - ''' + :param h_session: Current session + :param h_object: The handle of the object to fetch the attributes for + + """ # Clean before starting self.attributes = {} @@ -338,7 +343,7 @@ def retrieve_key_attributes(self, h_session, h_object): self.add_attribute(attribute.type, attr_type(string)) elif attr_type == long: self.add_attribute(attribute.type, ( - attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value))) + attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value))) elif attr_type == int: self.add_attribute(attribute.type, attr_type( cast(attribute.pValue, POINTER(c_int)).contents.value)) @@ -347,7 +352,7 @@ def retrieve_key_attributes(self, h_session, h_object): i = 0 while i < attribute.usValueLen: value.append(pb_value[i]) - i = i + 1 + i += 1 self.add_attribute(attribute.type, value) elif attr_type == NonAsciiString: @@ -355,27 +360,30 @@ def retrieve_key_attributes(self, h_session, h_object): i = 0 while i < attribute.usValueLen: value += '%02x' % cast(pb_value, CK_CHAR_PTR)[i] - i = i + 1 + i += 1 self.add_attribute(attribute.type, value) - elif attr_type == None: - #raise Exception("Attribute of type " + str(attribute.type) + "'s value + elif attr_type is None: + # raise Exception("Attribute of type " + str(attribute.type) + "'s value # type not yet determined") # Add type to all_attributes pass def get_attributes(self): - ''' - Returns the python dictionary of attributes - @return: The python dictionary of attributes - ''' + """Returns the python dictionary of attributes + + + :returns: The python dictionary of attributes + + """ return self.attributes def __eq__(self, other): - ''' + """ Overriding the == sign to properly compare equality in KeyAttribute objects - @param other: Another KeyAttribute to compare against - @return: True if the attributes are equal - ''' + + :param other: Another KeyAttribute to compare against + :return: True if the attributes are equal + """ other_attribs = other.get_attributes() self_attribs = self.get_attributes() for key in self.attributes: @@ -386,21 +394,19 @@ def __eq__(self, other): return True def debug_print(self): - ''' - Simple method to print out all the keys and values in a KeyAttribute object - ''' + """Simple method to print out all the keys and values in a KeyAttribute object""" for key in self.attributes: print "key: " + str(key) + ", value: " + str(self.attributes[key]) def get_attribute_py_value(attribute): - ''' - Gets the python version of the value of a attribute from the + """Gets the python version of the value of a attribute from the C format - @param attribute: The ctypes style variable representing the value of an attribute - @return: Returns the python version of the ctypes style variable - ''' + :param attribute: The ctypes style variable representing the value of an attribute + :returns: Returns the python version of the ctypes style variable + + """ key = attribute.type attr_type = lookup_attributes(key) if attr_type == bool: @@ -442,19 +448,19 @@ def get_attribute_py_value(attribute): for i in range(0, attribute.usValueLen / sizeof(CK_CHAR(0))): value += '%02x' % cast(attribute.pValue, CK_CHAR_PTR)[i] return value - elif attr_type == None: + elif attr_type is None: # raise Exception("Attribute of type " + str(attribute.type) + "'s value type not yet # determined") # Add type to all_attributes pass def c_struct_to_python(c_struct): - ''' - Converts a struct in C to a dictionary in python. + """Converts a struct in C to a dictionary in python. + + :param c_struct: The c struct to convert into a dictionary in python + :returns: Returns a python dictionary which represents the C struct passed in - @param c_struct: The c struct to convert into a dictionary in python - @return: Returns a python dictionary which represents the C struct passed in - ''' + """ py_struct = {} for i in range(0, len(c_struct)): obj_type = c_struct[i].type @@ -467,13 +473,13 @@ def c_struct_to_python(c_struct): def lookup_attributes(key): - ''' - Utility function to look through the lists of attributes and figure out + """Utility function to look through the lists of attributes and figure out the type of variable for a given attribute represented by a key - @param key: The key representing the attribute - @return: The python type that can represent the attribute - ''' + :param key: The key representing the attribute + :returns: The python type that can represent the attribute + + """ ret_val = None if key in key_attributes: @@ -485,24 +491,39 @@ def lookup_attributes(key): def convert_string_to_CK_CHAR(string): - byte_array = (c_ubyte * len (string))() + """ + + :param string: + + """ + byte_array = (c_ubyte * len(string))() i = 0 for char in string: byte_array[i] = ord(char) - i = i + 1 + i += 1 return byte_array def convert_CK_CHAR_to_string(byte_array): + """ + + :param byte_array: + + """ string = "" for b in byte_array: - string = string + chr(b) + string += chr(b) return string def convert_ck_char_array_to_string(ck_char_array): + """ + + :param ck_char_array: + + """ string = "" for b in ck_char_array: @@ -511,10 +532,13 @@ def convert_ck_char_array_to_string(ck_char_array): def convert_CK_BYTE_array_to_string(byte_array): + """ + + :param byte_array: + + """ string = "" for b in byte_array: - string = string + "%02x" % (b) + string += "%02x" % b return string - - diff --git a/pycryptoki/audit_handling.py b/pycryptoki/audit_handling.py index dd0517b..160b233 100755 --- a/pycryptoki/audit_handling.py +++ b/pycryptoki/audit_handling.py @@ -1,35 +1,60 @@ """ Methods responsible for managing a user's session and login/c_logout """ -from cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR from ctypes import cast, c_ulong, byref -from pycryptoki.test_functions import LunaException, check_luna_exception, \ - make_error_handle_function import logging +from cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR +from pycryptoki.test_functions import make_error_handle_function + logger = logging.getLogger(__name__) + def ca_init_audit(slot, audit_pin, audit_label): + """ + + :param slot: + :param audit_pin: + :param audit_label: + + """ if audit_pin == '': ret = CA_InitAudit(CK_SLOT_ID(slot), None, CK_ULONG(0), cast(audit_label, CK_CHAR_PTR)) else: - ret = CA_InitAudit(CK_SLOT_ID(slot), cast(audit_pin, CK_CHAR_PTR), CK_ULONG(len(audit_pin)), cast(audit_label, CK_CHAR_PTR)) + ret = CA_InitAudit(CK_SLOT_ID(slot), cast(audit_pin, CK_CHAR_PTR), CK_ULONG(len(audit_pin)), + cast(audit_label, CK_CHAR_PTR)) return ret -ca_init_audit_ex = make_error_handle_function(ca_init_audit) + + +ca_init_audit_ex = make_error_handle_function(ca_init_audit) + def ca_time_sync(h_session, ultime): - + """ + + :param h_session: + :param ultime: + + """ + ret = CA_TimeSync(h_session, CK_ULONG(ultime)) return ret + + ca_time_sync_ex = make_error_handle_function(ca_time_sync) + def ca_get_time(h_session): - + """ + + :param h_session: + + """ + hsm_time = c_ulong() - + ret = CA_GetTime(h_session, byref(hsm_time)) return ret, hsm_time -ca_get_time_ex = make_error_handle_function(ca_get_time) - +ca_get_time_ex = make_error_handle_function(ca_get_time) diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index f6cb024..57321f0 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -1,11 +1,10 @@ from ctypes import byref -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CA_OpenSecureToken, CK_ULONG_PTR, \ - CA_CloseSecureToken, CA_Extract, CA_Insert, CK_MECHANISM, CK_ULONG +import logging + +from pycryptoki.cryptoki import CA_OpenSecureToken, CA_CloseSecureToken, CA_Extract, CA_Insert, CK_ULONG from pycryptoki.mechanism import get_c_struct_from_mechanism, \ get_python_dict_from_c_mechanism from pycryptoki.test_functions import make_error_handle_function -import logging logger = logging.getLogger(__name__) @@ -17,41 +16,81 @@ CK_ULONG_PTR numberOfElems, CK_ULONG_PTR phID ''' + + def ca_open_secure_token(h_session, storage_path, dev_ID, mode): + """ + + :param h_session: + :param storage_path: + :param dev_ID: + :param mode: + + """ number_of_elems = CK_ULONG(0) ph_ID = CK_ULONG(0) ret = CA_OpenSecureToken(h_session, storage_path, dev_ID, mode, byref(number_of_elems), byref(ph_ID)) - + return ret, number_of_elems.value, ph_ID.value + + ca_open_secure_token_ex = make_error_handle_function(ca_open_secure_token) ''' CK_SESSION_HANDLE hSession, CK_ULONG hID ''' + + def ca_close_secure_token(h_session, h_ID): - + """ + + :param h_session: + :param h_ID: + + """ + ret = CA_CloseSecureToken(h_session, h_ID) return ret + + ca_close_secure_token_ex = make_error_handle_function(ca_close_secure_token) def ca_extract(h_session, py_mechanism_dict, params_type_string): - + """ + + :param h_session: + :param py_mechanism_dict: + :param params_type_string: + + """ + c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) - + ret = CA_Extract(h_session, c_mechanism) - + py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) return ret, py_dictionary + + ca_extract_ex = make_error_handle_function(ca_extract) # CA_Insert( CK_SESSION_HANDLE hSession, # CK_MECHANISM_PTR pMechanism ) def ca_insert(h_session, py_mechanism_dict, params_type_string): - + """ + + :param h_session: + :param py_mechanism_dict: + :param params_type_string: + + """ + c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) ret = CA_Insert(h_session, c_mechanism) py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) return ret, py_dictionary + + ca_insert_ex = make_error_handle_function(ca_insert) diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py old mode 100644 new mode 100755 index 283acaa..824939a --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -1,4 +1,4 @@ -''' +""" THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE This file should NOT be checked into MKS or modified in any way, this file was created by setup/initialize.py. Any changes to this file will be wiped out when @@ -6,13 +6,13 @@ This file contains all of the ctypes definitions for the cryptoki library. The ctypes definitions outline the structures for the cryptoki C API. -''' +""" - -from pycryptoki.cryptoki_helpers import make_late_binding_function import sys from ctypes import * +from pycryptoki.cryptoki_helpers import make_late_binding_function + LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 LUNA_RET_VECTOR_TOO_SMALL = -2147483115 @@ -617,13 +617,18 @@ RC_STC_SESSION_INVALID = -1073700849 # values for enumeration 'ResultCodeValue' -ResultCodeValue = c_int # enum +ResultCodeValue = c_int # enum # values for unnamed enumeration CK_USHORT = c_ulong CK_USHORT_PTR = POINTER(CK_USHORT) + + class CK_AES_GCM_PARAMS(Structure): + """ """ pass + + CK_BYTE = c_ubyte CK_BYTE_PTR = POINTER(CK_BYTE) CK_ULONG = c_ulong @@ -638,8 +643,13 @@ class CK_AES_GCM_PARAMS(Structure): ('ulTagBits', CK_ULONG), ] CK_AES_GCM_PARAMS_PTR = CK_AES_GCM_PARAMS + + class CK_XOR_BASE_DATA_KDF_PARAMS(Structure): + """ """ pass + + CK_EC_KDF_TYPE = CK_ULONG if 'win' in sys.platform: CK_XOR_BASE_DATA_KDF_PARAMS._pack_ = 1 @@ -652,8 +662,13 @@ class CK_XOR_BASE_DATA_KDF_PARAMS(Structure): CK_EC_DH_PRIMITIVE = CK_ULONG CK_EC_ENC_SCHEME = CK_ULONG CK_EC_MAC_SCHEME = CK_ULONG + + class CK_ECIES_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_ECIES_PARAMS._pack_ = 1 CK_ECIES_PARAMS._fields_ = [ @@ -672,8 +687,13 @@ class CK_ECIES_PARAMS(Structure): CK_ECIES_PARAMS_PTR = POINTER(CK_ECIES_PARAMS) CK_KDF_PRF_TYPE = CK_ULONG CK_KDF_PRF_ENCODING_SCHEME = CK_ULONG + + class CK_KDF_PRF_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_KDF_PRF_PARAMS._pack_ = 1 CK_KDF_PRF_PARAMS._fields_ = [ @@ -687,14 +707,24 @@ class CK_KDF_PRF_PARAMS(Structure): ] CK_PRF_KDF_PARAMS = CK_KDF_PRF_PARAMS CK_KDF_PRF_PARAMS_PTR = POINTER(CK_PRF_KDF_PARAMS) + + class CK_AES_CTR_PARAMS(Structure): + """ """ pass + + CK_SEED_CTR_PARAMS = CK_AES_CTR_PARAMS CK_SEED_CTR_PARAMS_PTR = POINTER(CK_SEED_CTR_PARAMS) CK_ARIA_CTR_PARAMS = CK_AES_CTR_PARAMS CK_ARIA_CTR_PARAMS_PTR = POINTER(CK_ARIA_CTR_PARAMS) + + class CK_DES_CTR_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_DES_CTR_PARAMS._pack_ = 1 CK_DES_CTR_PARAMS._fields_ = [ @@ -704,8 +734,13 @@ class CK_DES_CTR_PARAMS(Structure): CK_DES_CTR_PARAMS_PTR = POINTER(CK_DES_CTR_PARAMS) CK_AES_GMAC_PARAMS = CK_AES_GCM_PARAMS CK_AES_GMAC_PARAMS_PTR = POINTER(CK_AES_GMAC_PARAMS) + + class HSM_STATS_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: HSM_STATS_PARAMS._pack_ = 1 HSM_STATS_PARAMS._fields_ = [ @@ -713,8 +748,13 @@ class HSM_STATS_PARAMS(Structure): ('ulHighValue', CK_ULONG), ('ulLowValue', CK_ULONG), ] + + class CA_ROLE_STATE(Structure): + """ """ pass + + if 'win' in sys.platform: CA_ROLE_STATE._pack_ = 1 CA_ROLE_STATE._fields_ = [ @@ -723,8 +763,13 @@ class CA_ROLE_STATE(Structure): ('primaryAuthMech', CK_BYTE), ('secondaryAuthMech', CK_BYTE), ] + + class CA_MOFN_GENERATION(Structure): + """ """ pass + + if 'win' in sys.platform: CA_MOFN_GENERATION._pack_ = 1 CA_MOFN_GENERATION._fields_ = [ @@ -733,8 +778,13 @@ class CA_MOFN_GENERATION(Structure): ('ulVectorLen', CK_ULONG), ] CA_MOFN_GENERATION_PTR = POINTER(CA_MOFN_GENERATION) + + class CA_MOFN_ACTIVATION(Structure): + """ """ pass + + if 'win' in sys.platform: CA_MOFN_ACTIVATION._pack_ = 1 CA_MOFN_ACTIVATION._fields_ = [ @@ -742,8 +792,13 @@ class CA_MOFN_ACTIVATION(Structure): ('ulVectorLen', CK_ULONG), ] CA_MOFN_ACTIVATION_PTR = POINTER(CA_MOFN_ACTIVATION) + + class CA_M_OF_N_STATUS(Structure): + """ """ pass + + if 'win' in sys.platform: CA_M_OF_N_STATUS._pack_ = 1 CA_M_OF_N_STATUS._fields_ = [ @@ -757,11 +812,21 @@ class CA_M_OF_N_STATUS(Structure): CA_MOFN_STATUS_PTR = POINTER(CA_MOFN_STATUS) CKCA_MODULE_ID = CK_ULONG CKCA_MODULE_ID_PTR = POINTER(CKCA_MODULE_ID) + + class CKCA_MODULE_INFO(Structure): + """ """ pass + + CK_CHAR = CK_BYTE + + class CK_VERSION(Structure): + """ """ pass + + if 'win' in sys.platform: CK_VERSION._pack_ = 1 CK_VERSION._fields_ = [ @@ -777,8 +842,13 @@ class CK_VERSION(Structure): ('moduleVersion', CK_VERSION), ] CKCA_MODULE_INFO_PTR = POINTER(CKCA_MODULE_INFO) + + class CK_HA_MEMBER(Structure): + """ """ pass + + CK_RV = CK_ULONG if 'win' in sys.platform: CK_HA_MEMBER._pack_ = 1 @@ -786,8 +856,13 @@ class CK_HA_MEMBER(Structure): ('memberSerial', CK_CHAR * 20), ('memberStatus', CK_RV), ] + + class CK_HA_STATUS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_HA_STATUS._pack_ = 1 CK_HA_STATUS._fields_ = [ @@ -798,15 +873,25 @@ class CK_HA_STATUS(Structure): CK_HA_MEMBER_PTR = POINTER(CK_HA_MEMBER) CK_HA_STATE_PTR = POINTER(CK_HA_STATUS) CKA_SIM_AUTH_FORM = CK_ULONG + + class CT_Token(Structure): + """ """ pass + + if 'win' in sys.platform: CT_Token._pack_ = 1 CT_Token._fields_ = [ ] CT_TokenHndle = POINTER(CT_Token) + + class CK_AES_CBC_PAD_EXTRACT_PARAMS(Structure): + """ """ pass + + CK_ULONG_PTR = POINTER(CK_ULONG) if 'win' in sys.platform: CK_AES_CBC_PAD_EXTRACT_PARAMS._pack_ = 1 @@ -822,8 +907,13 @@ class CK_AES_CBC_PAD_EXTRACT_PARAMS(Structure): ('ctxID', CK_ULONG), ] CK_AES_CBC_PAD_EXTRACT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_EXTRACT_PARAMS) + + class CK_AES_CBC_PAD_INSERT_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_AES_CBC_PAD_INSERT_PARAMS._pack_ = 1 CK_AES_CBC_PAD_INSERT_PARAMS._fields_ = [ @@ -839,8 +929,13 @@ class CK_AES_CBC_PAD_INSERT_PARAMS(Structure): ('ctxID', CK_ULONG), ] CK_AES_CBC_PAD_INSERT_PARAMS_PTR = POINTER(CK_AES_CBC_PAD_INSERT_PARAMS) + + class CK_CLUSTER_STATE(Structure): + """ """ pass + + if 'win' in sys.platform: CK_CLUSTER_STATE._pack_ = 1 CK_CLUSTER_STATE._fields_ = [ @@ -848,8 +943,13 @@ class CK_CLUSTER_STATE(Structure): ('ulMemberStatus', CK_ULONG * 8), ] CK_CLUSTER_STATE_PTR = POINTER(CK_CLUSTER_STATE) + + class CK_LKM_TOKEN_ID_S(Structure): + """ """ pass + + if 'win' in sys.platform: CK_LKM_TOKEN_ID_S._pack_ = 1 CK_LKM_TOKEN_ID_S._fields_ = [ @@ -857,8 +957,13 @@ class CK_LKM_TOKEN_ID_S(Structure): ] CK_LKM_TOKEN_ID = CK_LKM_TOKEN_ID_S CK_LKM_TOKEN_ID_PTR = POINTER(CK_LKM_TOKEN_ID) + + class CK_SFNT_CA_FUNCTION_LIST(Structure): + """ """ pass + + CK_SFNT_CA_FUNCTION_LIST_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST) CK_SFNT_CA_FUNCTION_LIST_PTR_PTR = POINTER(CK_SFNT_CA_FUNCTION_LIST_PTR) CK_CA_GetFunctionList = CFUNCTYPE(CK_RV, CK_SFNT_CA_FUNCTION_LIST_PTR_PTR) @@ -876,8 +981,10 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_CA_InitRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG) CK_CA_InitSlotRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG) CK_CA_RoleStateGet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE, POINTER(CA_ROLE_STATE)) -CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) -CK_CA_CreateContainerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, + CK_CHAR_PTR) +CK_CA_CreateContainerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, + CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) CK_CA_Deactivate = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE) CK_CA_FindAdminSlotForSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_SLOT_ID), POINTER(CK_SLOT_ID)) CK_CA_TokenInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CT_TokenHndle, CK_SLOT_ID) @@ -888,7 +995,8 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_NOTIFY = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) CK_SESSION_HANDLE_PTR = POINTER(CK_SESSION_HANDLE) CK_CA_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) -CK_CA_OpenSessionWithAppID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) +CK_CA_OpenSessionWithAppID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, + CK_SESSION_HANDLE_PTR) CK_CA_IndirectLogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE) CK_CA_InitializeRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_CA_DeleteRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) @@ -910,16 +1018,23 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_OBJECT_HANDLE = CK_ULONG CK_OBJECT_HANDLE_PTR = POINTER(CK_OBJECT_HANDLE) CK_CA_ClonePrivateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) -CK_CA_CloneObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) +CK_CA_CloneObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE_PTR) CK_CA_GenerateCloningKEV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_BBOOL = CK_BYTE -CK_CA_CloneAsTargetInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_CloneAsSource = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_CloneAsTarget = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR) +CK_CA_CloneAsTargetInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, + CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsSource = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, + CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsTarget = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, + CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR) CK_CA_SetMofN = CFUNCTYPE(CK_RV, CK_BBOOL) -CK_CA_GenerateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) -CK_CA_GenerateCloneableMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) -CK_CA_ModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_GenerateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, + CK_VOID_PTR) +CK_CA_GenerateCloneableMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, + CK_VOID_PTR) +CK_CA_ModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, + CK_VOID_PTR) CK_CA_CloneMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) CK_CA_CloneModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) CK_CA_ActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CA_MOFN_ACTIVATION_PTR, CK_ULONG) @@ -928,19 +1043,29 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_CA_DuplicateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_CA_IsMofNEnabled = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_IsMofNRequired = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) + + class CK_ATTRIBUTE(Structure): + """ """ pass + + CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) CK_CA_GenerateTokenKeys = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) CK_CA_GetTokenCertificateInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG) CK_CA_GetModuleList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR) CK_CA_GetModuleInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR) -CK_CA_LoadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) -CK_CA_LoadEncryptedModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_LoadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_LoadEncryptedModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) CK_CA_UnloadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID) -CK_CA_PerformModuleCall = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) -CK_CA_FirmwareUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) +CK_CA_PerformModuleCall = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_ULONG_PTR) +CK_CA_FirmwareUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR) CK_CA_FirmwareRollback = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_CA_CapabilityUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) CK_CA_GetUserContainerNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) @@ -951,14 +1076,17 @@ class CK_ATTRIBUTE(Structure): CK_CA_GetFPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetExtendedTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetConfigurationElementDescription = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_GetConfigurationElementDescription = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR) CK_CA_GetHSMCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetHSMCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) CK_CA_GetHSMPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetHSMPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetContainerCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_GetContainerCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetContainerPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_GetContainerPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) CK_CA_SetTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_SetExtendedTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) @@ -972,8 +1100,10 @@ class CK_ATTRIBUTE(Structure): CK_CA_SetTokenPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetTokenPolicies = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_RetrieveLicenseList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_QueryLicense = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR) -CK_CA_GetContainerStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_QueryLicense = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_BYTE_PTR) +CK_CA_GetContainerStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_GetTokenStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_ReadCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) @@ -996,18 +1126,28 @@ class CK_ATTRIBUTE(Structure): CK_CA_SpRawWrite = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_CheckOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)) CK_CA_DestroyMultipleObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR) -CK_CA_OpenSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR) +CK_CA_OpenSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR) CK_CA_CloseSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_ListSecureTokenInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_ListSecureTokenInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_BYTE_PTR) CK_CA_ListSecureTokenUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG) + + class CK_MECHANISM(Structure): + """ """ pass + + CK_MECHANISM_PTR = POINTER(CK_MECHANISM) -CK_CA_GetSecureElementMeta = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) +CK_CA_GetSecureElementMeta = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_BYTE_PTR, CK_ULONG) CK_CA_HAInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) CK_CA_HAGetMasterPublic = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAGetLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAAnswerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAGetLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_CA_HAAnswerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) CK_CA_HALogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_HAAnswerMofNChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_HAActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) @@ -1015,10 +1155,15 @@ class CK_MECHANISM(Structure): CK_CA_GetTokenCertificates = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_ExtractMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_InsertMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) -CK_CA_MultisignValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) -CK_CA_SIMExtract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR) -CK_CA_SIMInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR) -CK_CA_SIMMultiSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) +CK_CA_MultisignValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) +CK_CA_SIMExtract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, + CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_SIMInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), + CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_SIMMultiSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, + POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, + POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) CK_CA_Extract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) CK_CA_Insert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) CK_CA_GetTokenObjectUID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)) @@ -1036,16 +1181,24 @@ class CK_MECHANISM(Structure): CK_CA_InvokeService = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) CK_CA_InvokeServiceFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_InvokeServiceAsynch = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_InvokeServiceSinglePart = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_InvokeServiceSinglePart = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) CK_CA_EncodeECParamsFromFile = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR) CK_CA_GetHSMStats = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, POINTER(HSM_STATS_PARAMS)) CK_CA_GetHSMStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetTokenStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetContainerStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetTokenStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) +CK_CA_GetContainerStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_SetContainerSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_CreateContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_CreateContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, + CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR) CK_CA_InitAudit = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR) CK_CA_LogVerify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG_PTR) CK_CA_LogVerifyFile = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG_PTR) @@ -1055,8 +1208,10 @@ class CK_MECHANISM(Structure): CK_CA_TimeSync = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_GetTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR) CK_CA_LogSetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR) -CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR) -CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)) +CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG), CK_BYTE_PTR) +CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG), POINTER(CK_ULONG)) CK_CA_DeleteContainerWithHandle = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_GetContainerList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) @@ -1065,20 +1220,30 @@ class CK_MECHANISM(Structure): CK_CA_GetClusterState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CLUSTER_STATE_PTR) CK_CA_LockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) CK_CA_UnlockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_LKMInitiatorChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR) -CK_CA_LKMReceiverResponse = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR) -CK_CA_LKMInitiatorComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) -CK_CA_LKMReceiverComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_LKMInitiatorChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, + CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMReceiverResponse = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, + CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMInitiatorComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, + CK_OBJECT_HANDLE_PTR) +CK_CA_LKMReceiverComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) CK_CA_ModifyUsageCount = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG) CK_CA_EnableUnauthTokenInsertion = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetUnauthTokenInsertionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_ULONG), POINTER(CK_ULONG)) +CK_CA_GetUnauthTokenInsertionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_ULONG), + POINTER(CK_ULONG)) CK_CA_DisableUnauthTokenInsertion = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_STCRegister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG) +CK_CA_STCRegister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), + CK_ULONG, POINTER(CK_CHAR), CK_ULONG) CK_CA_STCDeregister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR)) -CK_CA_STCGetPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, + POINTER(CK_CHAR), CK_ULONG_PTR) CK_CA_STCGetClientsList = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_STCGetClientInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) -CK_CA_STCGetPartPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetClientInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, + CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetPartPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, + POINTER(CK_CHAR), CK_ULONG_PTR) CK_CA_STCGetAdminPubKey = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) CK_CA_STCSetCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) CK_CA_STCGetCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) @@ -1372,7 +1537,8 @@ class CK_MECHANISM(Structure): CA_CreateLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR] CA_CreateContainerLoginChallenge = make_late_binding_function('CA_CreateContainerLoginChallenge') CA_CreateContainerLoginChallenge.restype = CK_RV -CA_CreateContainerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR] +CA_CreateContainerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, + CK_ULONG_PTR, CK_CHAR_PTR] CA_Deactivate = make_late_binding_function('CA_Deactivate') CA_Deactivate.restype = CK_RV CA_Deactivate.argtypes = [CK_SLOT_ID, CK_USER_TYPE] @@ -1396,7 +1562,8 @@ class CK_MECHANISM(Structure): CA_OpenSession.argtypes = [CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] CA_OpenSessionWithAppID = make_late_binding_function('CA_OpenSessionWithAppID') CA_OpenSessionWithAppID.restype = CK_RV -CA_OpenSessionWithAppID.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] +CA_OpenSessionWithAppID.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, + CK_SESSION_HANDLE_PTR] CA_IndirectLogin = make_late_binding_function('CA_IndirectLogin') CA_IndirectLogin.restype = CK_RV CA_IndirectLogin.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE] @@ -1462,13 +1629,16 @@ class CK_MECHANISM(Structure): CA_GenerateCloningKEV.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] CA_CloneAsTargetInit = make_late_binding_function('CA_CloneAsTargetInit') CA_CloneAsTargetInit.restype = CK_RV -CA_CloneAsTargetInit.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR] +CA_CloneAsTargetInit.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, + CK_ULONG_PTR] CA_CloneAsSource = make_late_binding_function('CA_CloneAsSource') CA_CloneAsSource.restype = CK_RV -CA_CloneAsSource.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR] +CA_CloneAsSource.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, + CK_ULONG_PTR] CA_CloneAsTarget = make_late_binding_function('CA_CloneAsTarget') CA_CloneAsTarget.restype = CK_RV -CA_CloneAsTarget.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR] +CA_CloneAsTarget.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, + CK_BBOOL, CK_OBJECT_HANDLE_PTR] CA_SetMofN = make_late_binding_function('CA_SetMofN') CA_SetMofN.restype = CK_RV CA_SetMofN.argtypes = [CK_BBOOL] @@ -1477,7 +1647,8 @@ class CK_MECHANISM(Structure): CA_GenerateMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] CA_GenerateCloneableMofN = make_late_binding_function('CA_GenerateCloneableMofN') CA_GenerateCloneableMofN.restype = CK_RV -CA_GenerateCloneableMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] +CA_GenerateCloneableMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, + CK_VOID_PTR] CA_ModifyMofN = make_late_binding_function('CA_ModifyMofN') CA_ModifyMofN.restype = CK_RV CA_ModifyMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] @@ -1513,7 +1684,8 @@ class CK_MECHANISM(Structure): CA_GetTokenCertificateInfo.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CA_SetTokenCertificateSignature = make_late_binding_function('CA_SetTokenCertificateSignature') CA_SetTokenCertificateSignature.restype = CK_RV -CA_SetTokenCertificateSignature.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_SetTokenCertificateSignature.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG] CA_GetModuleList = make_late_binding_function('CA_GetModuleList') CA_GetModuleList.restype = CK_RV CA_GetModuleList.argtypes = [CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR] @@ -1522,19 +1694,23 @@ class CK_MECHANISM(Structure): CA_GetModuleInfo.argtypes = [CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR] CA_LoadModule = make_late_binding_function('CA_LoadModule') CA_LoadModule.restype = CK_RV -CA_LoadModule.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] +CA_LoadModule.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] CA_LoadEncryptedModule = make_late_binding_function('CA_LoadEncryptedModule') CA_LoadEncryptedModule.restype = CK_RV -CA_LoadEncryptedModule.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] +CA_LoadEncryptedModule.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] CA_UnloadModule = make_late_binding_function('CA_UnloadModule') CA_UnloadModule.restype = CK_RV CA_UnloadModule.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID] CA_PerformModuleCall = make_late_binding_function('CA_PerformModuleCall') CA_PerformModuleCall.restype = CK_RV -CA_PerformModuleCall.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR] +CA_PerformModuleCall.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_ULONG_PTR] CA_FirmwareUpdate = make_late_binding_function('CA_FirmwareUpdate') CA_FirmwareUpdate.restype = CK_RV -CA_FirmwareUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR] +CA_FirmwareUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR] CA_FirmwareRollback = make_late_binding_function('CA_FirmwareRollback') CA_FirmwareRollback.restype = CK_RV CA_FirmwareRollback.argtypes = [CK_SESSION_HANDLE] @@ -1567,7 +1743,8 @@ class CK_MECHANISM(Structure): CA_GetExtendedTPV.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] CA_GetConfigurationElementDescription = make_late_binding_function('CA_GetConfigurationElementDescription') CA_GetConfigurationElementDescription.restype = CK_RV -CA_GetConfigurationElementDescription.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR] +CA_GetConfigurationElementDescription.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_CHAR_PTR] CA_GetHSMCapabilitySet = make_late_binding_function('CA_GetHSMCapabilitySet') CA_GetHSMCapabilitySet.restype = CK_RV CA_GetHSMCapabilitySet.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] @@ -1702,7 +1879,8 @@ class CK_MECHANISM(Structure): CA_DestroyMultipleObjects.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR] CA_OpenSecureToken = make_late_binding_function('CA_OpenSecureToken') CA_OpenSecureToken.restype = CK_RV -CA_OpenSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR] +CA_OpenSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG, CK_CHAR_PTR] CA_CloseSecureToken = make_late_binding_function('CA_CloseSecureToken') CA_CloseSecureToken.restype = CK_RV CA_CloseSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG] @@ -1714,7 +1892,8 @@ class CK_MECHANISM(Structure): CA_ListSecureTokenUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_GetSecureElementMeta = make_late_binding_function('CA_GetSecureElementMeta') CA_GetSecureElementMeta.restype = CK_RV -CA_GetSecureElementMeta.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG] +CA_GetSecureElementMeta.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_BYTE_PTR, CK_ULONG] CA_HAInit = make_late_binding_function('CA_HAInit') CA_HAInit.restype = CK_RV CA_HAInit.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] @@ -1726,7 +1905,8 @@ class CK_MECHANISM(Structure): CA_HAGetLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CA_HAAnswerLoginChallenge = make_late_binding_function('CA_HAAnswerLoginChallenge') CA_HAAnswerLoginChallenge.restype = CK_RV -CA_HAAnswerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HAAnswerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR] CA_HALogin = make_late_binding_function('CA_HALogin') CA_HALogin.restype = CK_RV CA_HALogin.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] @@ -1750,16 +1930,21 @@ class CK_MECHANISM(Structure): CA_InsertMaskedObject.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG] CA_MultisignValue = make_late_binding_function('CA_MultisignValue') CA_MultisignValue.restype = CK_RV -CA_MultisignValue.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] +CA_MultisignValue.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] CA_SIMExtract = make_late_binding_function('CA_SIMExtract') CA_SIMExtract.restype = CK_RV -CA_SIMExtract.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR] +CA_SIMExtract.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, + CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR] CA_SIMInsert = make_late_binding_function('CA_SIMInsert') CA_SIMInsert.restype = CK_RV -CA_SIMInsert.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR] +CA_SIMInsert.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, + CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR] CA_SIMMultiSign = make_late_binding_function('CA_SIMMultiSign') CA_SIMMultiSign.restype = CK_RV -CA_SIMMultiSign.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] +CA_SIMMultiSign.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, + POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), + CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] CA_Extract = make_late_binding_function('CA_Extract') CA_Extract.restype = CK_RV CA_Extract.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] @@ -1816,10 +2001,14 @@ class CK_MECHANISM(Structure): CA_InvokeServiceSinglePart.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CA_EncodeECPrimeParams = make_late_binding_function('CA_EncodeECPrimeParams') CA_EncodeECPrimeParams.restype = CK_RV -CA_EncodeECPrimeParams.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_EncodeECPrimeParams.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_EncodeECChar2Params = make_late_binding_function('CA_EncodeECChar2Params') CA_EncodeECChar2Params.restype = CK_RV -CA_EncodeECChar2Params.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_EncodeECChar2Params.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_EncodeECParamsFromFile = make_late_binding_function('CA_EncodeECParamsFromFile') CA_EncodeECParamsFromFile.restype = CK_RV CA_EncodeECParamsFromFile.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR] @@ -1831,16 +2020,19 @@ class CK_MECHANISM(Structure): CA_GetHSMStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] CA_GetTokenStorageInformation = make_late_binding_function('CA_GetTokenStorageInformation') CA_GetTokenStorageInformation.restype = CK_RV -CA_GetTokenStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetTokenStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR] CA_GetContainerStorageInformation = make_late_binding_function('CA_GetContainerStorageInformation') CA_GetContainerStorageInformation.restype = CK_RV -CA_GetContainerStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR] CA_SetContainerSize = make_late_binding_function('CA_SetContainerSize') CA_SetContainerSize.restype = CK_RV CA_SetContainerSize.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] CA_CreateContainer = make_late_binding_function('CA_CreateContainer') CA_CreateContainer.restype = CK_RV -CA_CreateContainer.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR] +CA_CreateContainer.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, + CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR] CA_InitAudit = make_late_binding_function('CA_InitAudit') CA_InitAudit.restype = CK_RV CA_InitAudit.argtypes = [CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR] @@ -1870,10 +2062,12 @@ class CK_MECHANISM(Structure): CA_LogSetConfig.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR] CA_LogGetConfig = make_late_binding_function('CA_LogGetConfig') CA_LogGetConfig.restype = CK_RV -CA_LogGetConfig.argtypes = [CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR] +CA_LogGetConfig.argtypes = [CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG), CK_BYTE_PTR] CA_LogGetStatus = make_late_binding_function('CA_LogGetStatus') CA_LogGetStatus.restype = CK_RV -CA_LogGetStatus.argtypes = [CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)] +CA_LogGetStatus.argtypes = [CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG)] CA_DeleteContainerWithHandle = make_late_binding_function('CA_DeleteContainerWithHandle') CA_DeleteContainerWithHandle.restype = CK_RV CA_DeleteContainerWithHandle.argtypes = [CK_SESSION_HANDLE, CK_ULONG] @@ -1900,16 +2094,21 @@ class CK_MECHANISM(Structure): CA_UnlockClusteredSlot.argtypes = [CK_SLOT_ID] CA_LKMInitiatorChallenge = make_late_binding_function('CA_LKMInitiatorChallenge') CA_LKMInitiatorChallenge.restype = CK_RV -CA_LKMInitiatorChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR] +CA_LKMInitiatorChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, + CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR] CA_LKMReceiverResponse = make_late_binding_function('CA_LKMReceiverResponse') CA_LKMReceiverResponse.restype = CK_RV -CA_LKMReceiverResponse.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR] +CA_LKMReceiverResponse.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, + CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR] CA_LKMInitiatorComplete = make_late_binding_function('CA_LKMInitiatorComplete') CA_LKMInitiatorComplete.restype = CK_RV -CA_LKMInitiatorComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +CA_LKMInitiatorComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, + CK_OBJECT_HANDLE_PTR] CA_LKMReceiverComplete = make_late_binding_function('CA_LKMReceiverComplete') CA_LKMReceiverComplete.restype = CK_RV -CA_LKMReceiverComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +CA_LKMReceiverComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] CA_ModifyUsageCount = make_late_binding_function('CA_ModifyUsageCount') CA_ModifyUsageCount.restype = CK_RV CA_ModifyUsageCount.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG] @@ -1924,22 +2123,26 @@ class CK_MECHANISM(Structure): CA_DisableUnauthTokenInsertion.argtypes = [CK_SESSION_HANDLE, CK_ULONG] CA_STCRegister = make_late_binding_function('CA_STCRegister') CA_STCRegister.restype = CK_RV -CA_STCRegister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG] +CA_STCRegister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG, + POINTER(CK_CHAR), CK_ULONG] CA_STCDeregister = make_late_binding_function('CA_STCDeregister') CA_STCDeregister.restype = CK_RV CA_STCDeregister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR)] CA_STCGetPubKey = make_late_binding_function('CA_STCGetPubKey') CA_STCGetPubKey.restype = CK_RV -CA_STCGetPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, + POINTER(CK_CHAR), CK_ULONG_PTR] CA_STCGetClientsList = make_late_binding_function('CA_STCGetClientsList') CA_STCGetClientsList.restype = CK_RV CA_STCGetClientsList.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] CA_STCGetClientInfo = make_late_binding_function('CA_STCGetClientInfo') CA_STCGetClientInfo.restype = CK_RV -CA_STCGetClientInfo.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetClientInfo.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, CK_ULONG_PTR, + POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] CA_STCGetPartPubKey = make_late_binding_function('CA_STCGetPartPubKey') CA_STCGetPartPubKey.restype = CK_RV -CA_STCGetPartPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetPartPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), + CK_ULONG_PTR] CA_STCGetAdminPubKey = make_late_binding_function('CA_STCGetAdminPubKey') CA_STCGetAdminPubKey.restype = CK_RV CA_STCGetAdminPubKey.argtypes = [CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] @@ -2034,10 +2237,10 @@ class CK_MECHANISM(Structure): CK_ResetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID) # values for enumeration 'fwResultCode' -fwResultCode = c_int # enum +fwResultCode = c_int # enum # values for enumeration 'eInitMsgs' -eInitMsgs = c_int # enum +eInitMsgs = c_int # enum SInt8 = c_byte SInt16 = c_short SInt32 = c_long @@ -2064,8 +2267,13 @@ class CK_MECHANISM(Structure): PointerDifference = SInt32 SizeType = UInt Boolean = UInt8 + + class swapper(Union): + """ """ pass + + if 'win' in sys.platform: swapper._pack_ = 1 swapper._fields_ = [ @@ -2073,31 +2281,56 @@ class swapper(Union): ('words', c_int), ] HANDLE = c_int + + class CK_FUNCTION_LIST(Structure): + """ """ pass + + CK_C_Initialize = CFUNCTYPE(CK_RV, CK_VOID_PTR) CK_C_Finalize = CFUNCTYPE(CK_RV, CK_VOID_PTR) + + class CK_INFO(Structure): + """ """ pass + + CK_INFO_PTR = POINTER(CK_INFO) CK_C_GetInfo = CFUNCTYPE(CK_RV, CK_INFO_PTR) CK_FUNCTION_LIST_PTR = POINTER(CK_FUNCTION_LIST) CK_FUNCTION_LIST_PTR_PTR = POINTER(CK_FUNCTION_LIST_PTR) CK_C_GetFunctionList = CFUNCTYPE(CK_RV, CK_FUNCTION_LIST_PTR_PTR) CK_C_GetSlotList = CFUNCTYPE(CK_RV, CK_BBOOL, CK_SLOT_ID_PTR, CK_ULONG_PTR) + + class CK_SLOT_INFO(Structure): + """ """ pass + + CK_SLOT_INFO_PTR = POINTER(CK_SLOT_INFO) CK_C_GetSlotInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_INFO_PTR) + + class CK_TOKEN_INFO(Structure): + """ """ pass + + CK_TOKEN_INFO_PTR = POINTER(CK_TOKEN_INFO) CK_C_GetTokenInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_TOKEN_INFO_PTR) CK_MECHANISM_TYPE = CK_ULONG CK_MECHANISM_TYPE_PTR = POINTER(CK_MECHANISM_TYPE) CK_C_GetMechanismList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE_PTR, CK_ULONG_PTR) + + class CK_MECHANISM_INFO(Structure): + """ """ pass + + CK_MECHANISM_INFO_PTR = POINTER(CK_MECHANISM_INFO) CK_C_GetMechanismInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_MECHANISM_TYPE, CK_MECHANISM_INFO_PTR) CK_UTF8CHAR = CK_BYTE @@ -2108,8 +2341,13 @@ class CK_MECHANISM_INFO(Structure): CK_C_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) CK_C_CloseSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_C_CloseAllSessions = CFUNCTYPE(CK_RV, CK_SLOT_ID) + + class CK_SESSION_INFO(Structure): + """ """ pass + + CK_SESSION_INFO_PTR = POINTER(CK_SESSION_INFO) CK_C_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_INFO_PTR) CK_C_GetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) @@ -2117,7 +2355,8 @@ class CK_SESSION_INFO(Structure): CK_C_Login = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG) CK_C_Logout = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_C_CreateObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_CopyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_CopyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR) CK_C_DestroyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) CK_C_GetObjectSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR) CK_C_GetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) @@ -2154,11 +2393,16 @@ class CK_SESSION_INFO(Structure): CK_C_DecryptDigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_C_SignEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_C_DecryptVerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_GenerateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_GenerateKeyPair = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) -CK_C_WrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_UnwrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_DeriveKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_GenerateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR) +CK_C_GenerateKeyPair = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_C_WrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_C_UnwrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_DeriveKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR) CK_C_SeedRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_C_GenerateRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_C_GetFunctionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) @@ -2416,16 +2660,20 @@ class CK_SESSION_INFO(Structure): C_GenerateKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] C_GenerateKeyPair = make_late_binding_function('C_GenerateKeyPair') C_GenerateKeyPair.restype = CK_RV -C_GenerateKeyPair.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +C_GenerateKeyPair.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, + CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] C_WrapKey = make_late_binding_function('C_WrapKey') C_WrapKey.restype = CK_RV -C_WrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] +C_WrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, + CK_ULONG_PTR] C_UnwrapKey = make_late_binding_function('C_UnwrapKey') C_UnwrapKey.restype = CK_RV -C_UnwrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_UnwrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, + CK_ULONG, CK_OBJECT_HANDLE_PTR] C_DeriveKey = make_late_binding_function('C_DeriveKey') C_DeriveKey.restype = CK_RV -C_DeriveKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_DeriveKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR] C_SeedRandom = make_late_binding_function('C_SeedRandom') C_SeedRandom.restype = CK_RV C_SeedRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] @@ -2506,8 +2754,13 @@ class CK_SESSION_INFO(Structure): ('pValue', CK_VOID_PTR), ('usValueLen', CK_ULONG), ] + + class CK_DATE(Structure): + """ """ pass + + if 'win' in sys.platform: CK_DATE._pack_ = 1 CK_DATE._fields_ = [ @@ -2533,8 +2786,13 @@ class CK_DATE(Structure): CK_DESTROYMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) CK_LOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) CK_UNLOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR) + + class CK_C_INITIALIZE_ARGS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_C_INITIALIZE_ARGS._pack_ = 1 CK_C_INITIALIZE_ARGS._fields_ = [ @@ -2550,8 +2808,13 @@ class CK_C_INITIALIZE_ARGS(Structure): CK_RSA_PKCS_MGF_TYPE_PTR = POINTER(CK_RSA_PKCS_MGF_TYPE) CK_RSA_PKCS_OAEP_SOURCE_TYPE = CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR = POINTER(CK_RSA_PKCS_OAEP_SOURCE_TYPE) + + class CK_RSA_PKCS_OAEP_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_RSA_PKCS_OAEP_PARAMS._pack_ = 1 CK_RSA_PKCS_OAEP_PARAMS._fields_ = [ @@ -2562,8 +2825,13 @@ class CK_RSA_PKCS_OAEP_PARAMS(Structure): ('ulSourceDataLen', CK_ULONG), ] CK_RSA_PKCS_OAEP_PARAMS_PTR = POINTER(CK_RSA_PKCS_OAEP_PARAMS) + + class CK_RSA_PKCS_PSS_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_RSA_PKCS_PSS_PARAMS._pack_ = 1 CK_RSA_PKCS_PSS_PARAMS._fields_ = [ @@ -2572,8 +2840,13 @@ class CK_RSA_PKCS_PSS_PARAMS(Structure): ('usSaltLen', CK_ULONG), ] CK_RSA_PKCS_PSS_PARAMS_PTR = POINTER(CK_RSA_PKCS_PSS_PARAMS) + + class CK_ECDH1_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_ECDH1_DERIVE_PARAMS._pack_ = 1 CK_ECDH1_DERIVE_PARAMS._fields_ = [ @@ -2584,8 +2857,13 @@ class CK_ECDH1_DERIVE_PARAMS(Structure): ('pPublicData', CK_BYTE_PTR), ] CK_ECDH1_DERIVE_PARAMS_PTR = POINTER(CK_ECDH1_DERIVE_PARAMS) + + class CK_ECDH2_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_ECDH2_DERIVE_PARAMS._pack_ = 1 CK_ECDH2_DERIVE_PARAMS._fields_ = [ @@ -2600,8 +2878,13 @@ class CK_ECDH2_DERIVE_PARAMS(Structure): ('pPublicData2', CK_BYTE_PTR), ] CK_ECDH2_DERIVE_PARAMS_PTR = POINTER(CK_ECDH2_DERIVE_PARAMS) + + class CK_ECMQV_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_ECMQV_DERIVE_PARAMS._pack_ = 1 CK_ECMQV_DERIVE_PARAMS._fields_ = [ @@ -2619,8 +2902,13 @@ class CK_ECMQV_DERIVE_PARAMS(Structure): CK_ECMQV_DERIVE_PARAMS_PTR = POINTER(CK_ECMQV_DERIVE_PARAMS) CK_X9_42_DH_KDF_TYPE = CK_ULONG CK_X9_42_DH_KDF_TYPE_PTR = POINTER(CK_X9_42_DH_KDF_TYPE) + + class CK_X9_42_DH1_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_X9_42_DH1_DERIVE_PARAMS._pack_ = 1 CK_X9_42_DH1_DERIVE_PARAMS._fields_ = [ @@ -2631,8 +2919,13 @@ class CK_X9_42_DH1_DERIVE_PARAMS(Structure): ('pPublicData', CK_BYTE_PTR), ] CK_X9_42_DH1_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH1_DERIVE_PARAMS) + + class CK_X9_42_DH2_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_X9_42_DH2_DERIVE_PARAMS._pack_ = 1 CK_X9_42_DH2_DERIVE_PARAMS._fields_ = [ @@ -2647,8 +2940,13 @@ class CK_X9_42_DH2_DERIVE_PARAMS(Structure): ('pPublicData2', CK_BYTE_PTR), ] CK_X9_42_DH2_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_DH2_DERIVE_PARAMS) + + class CK_X9_42_MQV_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_X9_42_MQV_DERIVE_PARAMS._pack_ = 1 CK_X9_42_MQV_DERIVE_PARAMS._fields_ = [ @@ -2664,8 +2962,13 @@ class CK_X9_42_MQV_DERIVE_PARAMS(Structure): ('publicKey', CK_OBJECT_HANDLE), ] CK_X9_42_MQV_DERIVE_PARAMS_PTR = POINTER(CK_X9_42_MQV_DERIVE_PARAMS) + + class CK_KEA_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_KEA_DERIVE_PARAMS._pack_ = 1 CK_KEA_DERIVE_PARAMS._fields_ = [ @@ -2679,8 +2982,13 @@ class CK_KEA_DERIVE_PARAMS(Structure): CK_KEA_DERIVE_PARAMS_PTR = POINTER(CK_KEA_DERIVE_PARAMS) CK_RC2_PARAMS = CK_ULONG CK_RC2_PARAMS_PTR = POINTER(CK_RC2_PARAMS) + + class CK_RC2_CBC_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_RC2_CBC_PARAMS._pack_ = 1 CK_RC2_CBC_PARAMS._fields_ = [ @@ -2688,8 +2996,13 @@ class CK_RC2_CBC_PARAMS(Structure): ('iv', CK_BYTE * 8), ] CK_RC2_CBC_PARAMS_PTR = POINTER(CK_RC2_CBC_PARAMS) + + class CK_RC2_MAC_GENERAL_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_RC2_MAC_GENERAL_PARAMS._pack_ = 1 CK_RC2_MAC_GENERAL_PARAMS._fields_ = [ @@ -2697,8 +3010,13 @@ class CK_RC2_MAC_GENERAL_PARAMS(Structure): ('ulMacLength', CK_ULONG), ] CK_RC2_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC2_MAC_GENERAL_PARAMS) + + class CK_RC5_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_RC5_PARAMS._pack_ = 1 CK_RC5_PARAMS._fields_ = [ @@ -2706,8 +3024,13 @@ class CK_RC5_PARAMS(Structure): ('ulRounds', CK_ULONG), ] CK_RC5_PARAMS_PTR = POINTER(CK_RC5_PARAMS) + + class CK_RC5_CBC_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_RC5_CBC_PARAMS._pack_ = 1 CK_RC5_CBC_PARAMS._fields_ = [ @@ -2717,8 +3040,13 @@ class CK_RC5_CBC_PARAMS(Structure): ('ulIvLen', CK_ULONG), ] CK_RC5_CBC_PARAMS_PTR = POINTER(CK_RC5_CBC_PARAMS) + + class CK_RC5_MAC_GENERAL_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_RC5_MAC_GENERAL_PARAMS._pack_ = 1 CK_RC5_MAC_GENERAL_PARAMS._fields_ = [ @@ -2729,8 +3057,13 @@ class CK_RC5_MAC_GENERAL_PARAMS(Structure): CK_RC5_MAC_GENERAL_PARAMS_PTR = POINTER(CK_RC5_MAC_GENERAL_PARAMS) CK_MAC_GENERAL_PARAMS = CK_ULONG CK_MAC_GENERAL_PARAMS_PTR = POINTER(CK_MAC_GENERAL_PARAMS) + + class CK_DES_CBC_ENCRYPT_DATA_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_DES_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 CK_DES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ @@ -2739,8 +3072,13 @@ class CK_DES_CBC_ENCRYPT_DATA_PARAMS(Structure): ('length', CK_ULONG), ] CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_DES_CBC_ENCRYPT_DATA_PARAMS) + + class CK_AES_CBC_ENCRYPT_DATA_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_AES_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 CK_AES_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ @@ -2749,8 +3087,13 @@ class CK_AES_CBC_ENCRYPT_DATA_PARAMS(Structure): ('length', CK_ULONG), ] CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_AES_CBC_ENCRYPT_DATA_PARAMS) + + class CK_SKIPJACK_PRIVATE_WRAP_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_SKIPJACK_PRIVATE_WRAP_PARAMS._pack_ = 1 CK_SKIPJACK_PRIVATE_WRAP_PARAMS._fields_ = [ @@ -2767,8 +3110,13 @@ class CK_SKIPJACK_PRIVATE_WRAP_PARAMS(Structure): ('pSubprimeQ', CK_BYTE_PTR), ] CK_SKIPJACK_PRIVATE_WRAP_PTR = POINTER(CK_SKIPJACK_PRIVATE_WRAP_PARAMS) + + class CK_SKIPJACK_RELAYX_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_SKIPJACK_RELAYX_PARAMS._pack_ = 1 CK_SKIPJACK_RELAYX_PARAMS._fields_ = [ @@ -2788,8 +3136,13 @@ class CK_SKIPJACK_RELAYX_PARAMS(Structure): ('pNewRandomA', CK_BYTE_PTR), ] CK_SKIPJACK_RELAYX_PARAMS_PTR = POINTER(CK_SKIPJACK_RELAYX_PARAMS) + + class CK_PBE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_PBE_PARAMS._pack_ = 1 CK_PBE_PARAMS._fields_ = [ @@ -2801,8 +3154,13 @@ class CK_PBE_PARAMS(Structure): ('usIteration', CK_ULONG), ] CK_PBE_PARAMS_PTR = POINTER(CK_PBE_PARAMS) + + class CK_KEY_WRAP_SET_OAEP_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_KEY_WRAP_SET_OAEP_PARAMS._pack_ = 1 CK_KEY_WRAP_SET_OAEP_PARAMS._fields_ = [ @@ -2811,8 +3169,13 @@ class CK_KEY_WRAP_SET_OAEP_PARAMS(Structure): ('ulXLen', CK_ULONG), ] CK_KEY_WRAP_SET_OAEP_PARAMS_PTR = POINTER(CK_KEY_WRAP_SET_OAEP_PARAMS) + + class CK_SSL3_RANDOM_DATA(Structure): + """ """ pass + + if 'win' in sys.platform: CK_SSL3_RANDOM_DATA._pack_ = 1 CK_SSL3_RANDOM_DATA._fields_ = [ @@ -2821,8 +3184,13 @@ class CK_SSL3_RANDOM_DATA(Structure): ('pServerRandom', CK_BYTE_PTR), ('ulServerRandomLen', CK_ULONG), ] + + class CK_SSL3_MASTER_KEY_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_SSL3_MASTER_KEY_DERIVE_PARAMS._pack_ = 1 CK_SSL3_MASTER_KEY_DERIVE_PARAMS._fields_ = [ @@ -2830,8 +3198,13 @@ class CK_SSL3_MASTER_KEY_DERIVE_PARAMS(Structure): ('pVersion', CK_VERSION_PTR), ] CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_SSL3_MASTER_KEY_DERIVE_PARAMS) + + class CK_SSL3_KEY_MAT_OUT(Structure): + """ """ pass + + if 'win' in sys.platform: CK_SSL3_KEY_MAT_OUT._pack_ = 1 CK_SSL3_KEY_MAT_OUT._fields_ = [ @@ -2843,8 +3216,13 @@ class CK_SSL3_KEY_MAT_OUT(Structure): ('pIVServer', CK_BYTE_PTR), ] CK_SSL3_KEY_MAT_OUT_PTR = POINTER(CK_SSL3_KEY_MAT_OUT) + + class CK_SSL3_KEY_MAT_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_SSL3_KEY_MAT_PARAMS._pack_ = 1 CK_SSL3_KEY_MAT_PARAMS._fields_ = [ @@ -2856,8 +3234,13 @@ class CK_SSL3_KEY_MAT_PARAMS(Structure): ('pReturnedKeyMaterial', CK_SSL3_KEY_MAT_OUT_PTR), ] CK_SSL3_KEY_MAT_PARAMS_PTR = POINTER(CK_SSL3_KEY_MAT_PARAMS) + + class CK_TLS_PRF_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_TLS_PRF_PARAMS._pack_ = 1 CK_TLS_PRF_PARAMS._fields_ = [ @@ -2869,8 +3252,13 @@ class CK_TLS_PRF_PARAMS(Structure): ('pulOutputLen', CK_ULONG_PTR), ] CK_TLS_PRF_PARAMS_PTR = POINTER(CK_TLS_PRF_PARAMS) + + class CK_WTLS_RANDOM_DATA(Structure): + """ """ pass + + if 'win' in sys.platform: CK_WTLS_RANDOM_DATA._pack_ = 1 CK_WTLS_RANDOM_DATA._fields_ = [ @@ -2880,8 +3268,13 @@ class CK_WTLS_RANDOM_DATA(Structure): ('ulServerRandomLen', CK_ULONG), ] CK_WTLS_RANDOM_DATA_PTR = POINTER(CK_WTLS_RANDOM_DATA) + + class CK_WTLS_MASTER_KEY_DERIVE_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_WTLS_MASTER_KEY_DERIVE_PARAMS._pack_ = 1 CK_WTLS_MASTER_KEY_DERIVE_PARAMS._fields_ = [ @@ -2890,8 +3283,13 @@ class CK_WTLS_MASTER_KEY_DERIVE_PARAMS(Structure): ('pVersion', CK_BYTE_PTR), ] CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR = POINTER(CK_WTLS_MASTER_KEY_DERIVE_PARAMS) + + class CK_WTLS_PRF_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_WTLS_PRF_PARAMS._pack_ = 1 CK_WTLS_PRF_PARAMS._fields_ = [ @@ -2904,8 +3302,13 @@ class CK_WTLS_PRF_PARAMS(Structure): ('pulOutputLen', CK_ULONG_PTR), ] CK_WTLS_PRF_PARAMS_PTR = POINTER(CK_WTLS_PRF_PARAMS) + + class CK_WTLS_KEY_MAT_OUT(Structure): + """ """ pass + + if 'win' in sys.platform: CK_WTLS_KEY_MAT_OUT._pack_ = 1 CK_WTLS_KEY_MAT_OUT._fields_ = [ @@ -2914,8 +3317,13 @@ class CK_WTLS_KEY_MAT_OUT(Structure): ('pIV', CK_BYTE_PTR), ] CK_WTLS_KEY_MAT_OUT_PTR = POINTER(CK_WTLS_KEY_MAT_OUT) + + class CK_WTLS_KEY_MAT_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_WTLS_KEY_MAT_PARAMS._pack_ = 1 CK_WTLS_KEY_MAT_PARAMS._fields_ = [ @@ -2929,8 +3337,13 @@ class CK_WTLS_KEY_MAT_PARAMS(Structure): ('pReturnedKeyMaterial', CK_WTLS_KEY_MAT_OUT_PTR), ] CK_WTLS_KEY_MAT_PARAMS_PTR = POINTER(CK_WTLS_KEY_MAT_PARAMS) + + class CK_CMS_SIG_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_CMS_SIG_PARAMS._pack_ = 1 CK_CMS_SIG_PARAMS._fields_ = [ @@ -2944,8 +3357,13 @@ class CK_CMS_SIG_PARAMS(Structure): ('ulRequiredAttributesLen', CK_ULONG), ] CK_CMS_SIG_PARAMS_PTR = POINTER(CK_CMS_SIG_PARAMS) + + class CK_KEY_DERIVATION_STRING_DATA(Structure): + """ """ pass + + if 'win' in sys.platform: CK_KEY_DERIVATION_STRING_DATA._pack_ = 1 CK_KEY_DERIVATION_STRING_DATA._fields_ = [ @@ -2959,8 +3377,13 @@ class CK_KEY_DERIVATION_STRING_DATA(Structure): CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR = POINTER(CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE) CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE = CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR = POINTER(CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE) + + class CK_PKCS5_PBKD2_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_PKCS5_PBKD2_PARAMS._pack_ = 1 CK_PKCS5_PBKD2_PARAMS._fields_ = [ @@ -2977,8 +3400,13 @@ class CK_PKCS5_PBKD2_PARAMS(Structure): CK_PKCS5_PBKD2_PARAMS_PTR = POINTER(CK_PKCS5_PBKD2_PARAMS) CK_OTP_PARAM_TYPE = CK_ULONG CK_PARAM_TYPE = CK_OTP_PARAM_TYPE + + class CK_OTP_PARAM(Structure): + """ """ pass + + if 'win' in sys.platform: CK_OTP_PARAM._pack_ = 1 CK_OTP_PARAM._fields_ = [ @@ -2987,8 +3415,13 @@ class CK_OTP_PARAM(Structure): ('usValueLen', CK_ULONG), ] CK_OTP_PARAM_PTR = POINTER(CK_OTP_PARAM) + + class CK_OTP_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_OTP_PARAMS._pack_ = 1 CK_OTP_PARAMS._fields_ = [ @@ -2996,8 +3429,13 @@ class CK_OTP_PARAMS(Structure): ('ulCount', CK_ULONG), ] CK_OTP_PARAMS_PTR = POINTER(CK_OTP_PARAMS) + + class CK_OTP_SIGNATURE_INFO(Structure): + """ """ pass + + if 'win' in sys.platform: CK_OTP_SIGNATURE_INFO._pack_ = 1 CK_OTP_SIGNATURE_INFO._fields_ = [ @@ -3005,8 +3443,13 @@ class CK_OTP_SIGNATURE_INFO(Structure): ('ulCount', CK_ULONG), ] CK_OTP_SIGNATURE_INFO_PTR = POINTER(CK_OTP_SIGNATURE_INFO) + + class CK_KIP_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_KIP_PARAMS._pack_ = 1 CK_KIP_PARAMS._fields_ = [ @@ -3023,8 +3466,13 @@ class CK_KIP_PARAMS(Structure): ('cb', CK_BYTE * 16), ] CK_AES_CTR_PARAMS_PTR = POINTER(CK_AES_CTR_PARAMS) + + class CK_CAMELLIA_CTR_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_CAMELLIA_CTR_PARAMS._pack_ = 1 CK_CAMELLIA_CTR_PARAMS._fields_ = [ @@ -3032,8 +3480,13 @@ class CK_CAMELLIA_CTR_PARAMS(Structure): ('cb', CK_BYTE * 16), ] CK_CAMELLIA_CTR_PARAMS_PTR = POINTER(CK_CAMELLIA_CTR_PARAMS) + + class CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ @@ -3042,8 +3495,13 @@ class CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS(Structure): ('length', CK_ULONG), ] CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR = POINTER(CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS) + + class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): + """ """ pass + + if 'win' in sys.platform: CK_ARIA_CBC_ENCRYPT_DATA_PARAMS._pack_ = 1 CK_ARIA_CBC_ENCRYPT_DATA_PARAMS._fields_ = [ diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index 15b2eaa..6f8a756 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -1,12 +1,13 @@ from ctypes import CDLL -from pycryptoki.defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE import os import re import sys +from pycryptoki.defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE + + def parse_chrystoki_conf(): - ''' - The autogeneration of cryptoki.py now prepends a method which sets the DLL's path to + """The autogeneration of cryptoki.py now prepends a method which sets the DLL's path to be called every time cryptoki.py is imported. This method parses Cryptoki's configuration file in python for the DLL's location. While originally it was desired to reuse the C code which parses Cryptoki.conf this was not possible because Pycryptoki can only call functions @@ -39,19 +40,21 @@ def parse_chrystoki_conf(): It is also the simplest approach. The disadvantage to this is the configuration file may be parsed differently in C than in python. Therefore lot of error checking was added to the parsing process as well as printing of which DLL was found in each run of the Cryptoki library.. - ''' + + + """ env_conf_path = os.environ.get("ChrystokiConfigurationPath") conf_path = None - if CHRYSTOKI_DLL_FILE != None: - #Use this value for the location of the DLL - dll_path = CHRYSTOKI_DLL_FILE + if CHRYSTOKI_DLL_FILE is not None: + # Use this value for the location of the DLL + dll_path = CHRYSTOKI_DLL_FILE print "Using DLL Path from defaults.py:" + dll_path return dll_path - elif CHRYSTOKI_CONFIG_FILE != None: + elif CHRYSTOKI_CONFIG_FILE is not None: conf_path = CHRYSTOKI_CONFIG_FILE print "Using Chrystoki.conf location from defaults.py: " + conf_path - elif env_conf_path != None: + elif env_conf_path is not None: if 'win' in sys.platform: env_conf_path = env_conf_path.replace('\\\\', '~').replace('~', '\\') + 'crystoki.ini' else: @@ -60,7 +63,7 @@ def parse_chrystoki_conf(): print "Using Chrystoki.conf location from environment variable ChrystokiConfigurationPath: " + conf_path - if conf_path == None: + if conf_path is None: conf_path = '/etc/Chrystoki.conf' print "No DLL Path or Chyrstoki.conf path set in defaults.py looking up DLL path in " + str(conf_path) @@ -74,21 +77,23 @@ def parse_chrystoki_conf(): return dll_path + def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): - ''' - Parses the chrystoki configuration file for the section that specifies the location + """Parses the chrystoki configuration file for the section that specifies the location of the DLL and returns the DLL location. - @param conf_path: The path to the configuration file - @param chrystoki_conf_text: The output of the read in chrystoki configuration file - @return: The path to the chrystoki DLL - ''' + :param conf_path: The path to the configuration file + :param chrystoki_conf_text: The output of the read in chrystoki configuration file + :returns: The path to the chrystoki DLL + + """ if 'win' in sys.platform: chrystoki2_segments = re.findall("\s*\[Chrystoki2\]\s*([^\r\n]*)", chrystoki_conf_text) if len(chrystoki2_segments) > 1: print chrystoki2_segments - raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + raise Exception( + "Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) elif len(chrystoki2_segments) < 1: print chrystoki2_segments raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) @@ -101,7 +106,7 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): if len(lib_nt_line) > 1: raise Exception("Found more than one LibNT pattern on the same line") elif len(lib_nt_line) == 1: - if (dll_path != ""): + if dll_path != "": raise Exception("Found more than one instance of LibNT in the file.") dll_path = lib_nt_line[0].strip().strip(';').strip().strip("'").strip('"') @@ -112,7 +117,8 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): if len(chrystoki2_segments) > 1: print chrystoki2_segments - raise Exception("Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + raise Exception( + "Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) elif len(chrystoki2_segments) < 1: print chrystoki2_segments raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) @@ -120,7 +126,7 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): chrystoki2 = chrystoki2_segments[0].split('\n') dll_path = "" for line in chrystoki2: - is_64bits = sys.maxsize > 2**32 + is_64bits = sys.maxsize > 2 ** 32 if is_64bits: lib_unix_line = re.findall("^\s*LibUNIX64\s*=\s*([^\n]+)", line) else: @@ -129,7 +135,7 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): if len(lib_unix_line) > 1: raise Exception("Found more than one LibUNIX pattern on the same line") elif len(lib_unix_line) == 1: - if (dll_path != ""): + if dll_path != "": raise Exception("Found more than one instance of LibUNIX in the file.") dll_path = lib_unix_line[0].strip().strip(';').strip().strip("'").strip('"') @@ -138,26 +144,31 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): return dll_path + def _get_chrystoki_conf_file_text(conf_path): - ''' - Reads in the chrystoki configuration and returns the text in the file - ''' + """Reads in the chrystoki configuration and returns the text in the file + + :param conf_path: + + """ try: chrystoki_conf_file = open(conf_path, "r") - chrystoki_conf_text = chrystoki_conf_file.read(); + chrystoki_conf_text = chrystoki_conf_file.read() except IOError: raise Exception("Could not find/read Chrystoki configuration file at path " + str(conf_path)) return chrystoki_conf_text + class CryptokiDLLException(Exception): - ''' - Custom exception class used to print an error when a call to the Cryptoki DLL failed. + """Custom exception class used to print an error when a call to the Cryptoki DLL failed. The late binding makes debugging a little bit more difficult because function calls have to pass through an additional layer of abstraction. This custom exception prints out a quick message detailing exactly what function failed. - ''' + + """ + def __init__(self, additional_info, orig_error): self.msg = additional_info self.original_error = orig_error @@ -165,13 +176,13 @@ def __init__(self, additional_info, orig_error): def __str__(self): return self.msg + "\n" + str(self.original_error) + class CryptokiDLLSingleton(object): - ''' - A singleton class which holds an instance of the loaded cryptoki DLL object. - ''' + """A singleton class which holds an instance of the loaded cryptoki DLL object.""" _instance = None loaded_dll_library = None + def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(CryptokiDLLSingleton, cls).__new__(cls, *args, **kwargs) @@ -180,23 +191,35 @@ def __new__(cls, *args, **kwargs): cls._instance.dll_path = dll_path if 'win' in sys.platform: import ctypes + cls._instance.loaded_dll_library = ctypes.WinDLL(dll_path) else: cls._instance.loaded_dll_library = CDLL(dll_path) return cls._instance def get_dll(self): - if self.loaded_dll_library == None or self.loaded_dll_library == "": - raise Exception("DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read /etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") + """ """ + if self.loaded_dll_library is None or self.loaded_dll_library == "": + raise Exception( + "DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read /etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") return self.loaded_dll_library + def make_late_binding_function(function_name): - ''' - A function factory for creating a function that will bind to the cryptoki + """A function factory for creating a function that will bind to the cryptoki DLL only when the function is called. - ''' + + :param function_name: + + """ def luna_function(*args, **kwargs): + """ + + :param *args: + :param **kwargs: + + """ late_binded_function = eval("CryptokiDLLSingleton().get_dll()." + function_name) late_binded_function.restype = luna_function.restype late_binded_function.argtypes = luna_function.argtypes diff --git a/pycryptoki/daemon/pycryptoki_daemon.py b/pycryptoki/daemon/pycryptoki_daemon.py index f53cd91..e1f06cc 100755 --- a/pycryptoki/daemon/pycryptoki_daemon.py +++ b/pycryptoki/daemon/pycryptoki_daemon.py @@ -1,13 +1,16 @@ #!/usr/bin/env python -''' +""" xmlrpc server daemon that wraps pycryptoki so pycryptoki can be used over the network -''' +""" from ConfigParser import ConfigParser from SimpleXMLRPCServer import SimpleXMLRPCServer -from StringIO import StringIO from optparse import OptionParser import xmlrpclib +from _ctypes import pointer +from ctypes import cast +import ctypes + from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ ca_insert, ca_insert_ex @@ -37,13 +40,9 @@ c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ ca_init_audit_ex, ca_time_sync, ca_time_sync_ex -from _ctypes import pointer -from ctypes import cast -import ctypes from pycryptoki.key_generator import _get_mechanism from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR - ''' All the functions the server supports ''' @@ -102,7 +101,7 @@ "get_token_by_label" : get_token_by_label, "get_token_by_label_ex" : get_token_by_label_ex, "ca_close_secure_token" : ca_close_secure_token, - "ca_close_secure_token" : ca_close_secure_token_ex, + "ca_close_secure_token_ex" : ca_close_secure_token_ex, "ca_open_secure_token" : ca_open_secure_token, "ca_open_secure_token_ex" : ca_open_secure_token_ex, "ca_extract" : ca_extract, @@ -148,6 +147,12 @@ def initialize_server(ip, port): + """ + + :param ip: + :param port: + + """ print "Initializing Server" server = SimpleXMLRPCServer((ip, port)) server.logRequests = 0 @@ -164,36 +169,72 @@ def initialize_server(ip, port): def serialize_dict(dictionary): - ''' - Helper function to convert a dictionary with to + """Helper function to convert a dictionary with to for xmlrpc - ''' + + :param dictionary: + + """ serialized_dictionary = {} for key, value in dictionary.iteritems(): serialized_dictionary[str(key)] = value return serialized_dictionary def c_get_attribute_value_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' + """returns dictionary with k,v pairs of for xmlrpc + + :param h_session: + :param h_object: + :param template: + + """ ret, dictionary = c_get_attribute_value(h_session, h_object, template) return ret, serialize_dict(dictionary) def c_get_attribute_value_ex_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' + """returns dictionary with k,v pairs of for xmlrpc + + :param h_session: + :param h_object: + :param template: + + """ dictionary = c_get_attribute_value_ex(h_session, h_object, template) return serialize_dict(dictionary) def c_find_objects_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' + """returns dictionary with k,v pairs of for xmlrpc + + :param h_session: + :param h_object: + :param template: + + """ ret, dictionary = c_find_objects(h_session, h_object, template) return ret, serialize_dict(dictionary) def c_find_objects_ex_serialize(h_session, h_object, template): - ''' returns dictionary with k,v pairs of for xmlrpc''' + """returns dictionary with k,v pairs of for xmlrpc + + :param h_session: + :param h_object: + :param template: + + """ dictionary = c_find_objects_ex(h_session, h_object, template) return serialize_dict(dictionary) def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + """ + + :param h_session: + :param h_base_key: + :param h_second_key: + :param template: + :param mech_flavor: + :param mech: (Default value = None) + + """ if mech: mech = _get_mechanism(mech) c_second_key = CK_ULONG(h_second_key) @@ -203,6 +244,16 @@ def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_f return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): + """ + + :param h_session: + :param h_base_key: + :param h_second_key: + :param template: + :param mech_flavor: + :param mech: (Default value = None) + + """ if mech: mech = _get_mechanism(mech) c_second_key = CK_ULONG(h_second_key) @@ -212,36 +263,110 @@ def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mec return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) def c_sign_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + """ + + :param h_session: + :param sign_flavor: + :param data_to_sign: + :param h_key: + :param mech: (Default value = None) + + """ ret, signature = c_sign(h_session, sign_flavor, data_to_sign, h_key, mech) return ret, xmlrpclib.Binary(signature) def c_sign_ex_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): + """ + + :param h_session: + :param sign_flavor: + :param data_to_sign: + :param h_key: + :param mech: (Default value = None) + + """ signature = c_sign_ex(h_session, sign_flavor, data_to_sign, h_key, mech) return xmlrpclib.Binary(signature) def c_encrypt_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + """ + + :param h_session: + :param encryption_flavor: + :param h_key: + :param data_to_encrypt: + :param mech: (Default value = None) + + """ ret, enc_data = c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech) return ret, xmlrpclib.Binary(enc_data) def c_encrypt_ex_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): + """ + + :param h_session: + :param encryption_flavor: + :param h_key: + :param data_to_encrypt: + :param mech: (Default value = None) + + """ enc_data = c_encrypt_ex(h_session, encryption_flavor, h_key, data_to_encrypt, mech) return xmlrpclib.Binary(enc_data) def c_verify_serialize( h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + """ + + :param h_session: + :param h_key: + :param verify_flavor: + :param data_to_verify: + :param signature: + :param mech: (Default value = None) + + """ return c_verify(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) def c_verify_ex_serialize(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): + """ + + :param h_session: + :param h_key: + :param verify_flavor: + :param data_to_verify: + :param signature: + :param mech: (Default value = None) + + """ return c_verify_ex(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) def c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + """ + + :param h_session: + :param decrypt_flavor: + :param h_key: + :param encrypted_data: + :param mech: (Default value = None) + + """ return c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): + """ + + :param h_session: + :param decrypt_flavor: + :param h_key: + :param encrypted_data: + :param mech: (Default value = None) + + """ return c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) if __name__ == '__main__': #Setup argument parser - resources_config_parser = ConfigParser(); + resources_config_parser = ConfigParser() parser = OptionParser() parser.add_option("-i", "--ip_address", dest="i", help="pycryptoki daemon IP address", metavar="") @@ -250,8 +375,8 @@ def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): (options, args) = parser.parse_args() #Default arguments - ip = options.i if options.i != None else 'localhost' - port = int( options.p if options.p != None else '8001') + ip = options.i if options.i is not None else 'localhost' + port = int( options.p if options.p is not None else '8001') print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) server = initialize_server(ip, port) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index e945e7d..9980060 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -1,6 +1,21 @@ #!/usr/bin/env python -u """ -RPYC version of of the pycryptoki daemon +RPYC-based daemon that allows for remote execution +of pycryptoki commands. + +Start via "./rpyc\_pycryptoki.py -i -p " +or "python rpyc\_pycryptoki.py -i -p " + +All methods starting with 'exposed\_' are useable via just +rpyc\_conn. instead of rpyc\_conn.exposed_ + +All methods ending with '\_ex' will automatically check the return code from +cryptoki & raise an exception if it is not CKR_OK. It will *NOT* give you the return code, instead +just returning the second part of the regular return tuple:: + + c_open_session() # Returns: (ret_code, session_handle) + c_open_session_ex() # Returns: session_handle, raises exception if ret_code != CKR_OK + """ from optparse import OptionParser from _ctypes import pointer @@ -10,51 +25,74 @@ import rpyc import pycryptoki -from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token,\ - ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex,\ - ca_insert, ca_insert_ex -from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt,\ - c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex -from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex,\ - c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex,\ - c_derive_key, c_derive_key_ex, c_copy_object_ex, c_copy_object -from pycryptoki.misc import c_generate_random, c_generate_random_ex,\ - c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id,\ - c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object,\ - c_create_object_ex, c_digestkey, c_digestkey_ex -from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex,\ - c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex -from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex,\ - ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex,\ - ca_set_container_policy, ca_set_container_policy_ex -from pycryptoki.session_management import c_initialize, c_initialize_ex,\ - c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, \ - c_get_session_info, c_get_session_info_ex, c_get_token_info, \ - c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex,\ - c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin,\ - c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container,\ - ca_create_container_ex, login, login_ex, ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID_ex,\ - ca_closeapplicationID, ca_restart, ca_restart_ex, ca_delete_container_with_handle_ex, \ - ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex -from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex -from pycryptoki.token_management import c_init_token, c_init_token_ex,\ - c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info,\ - c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex -from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit,\ - ca_init_audit_ex, ca_time_sync, ca_time_sync_ex -from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR +from pycryptoki.backup import (ca_open_secure_token, ca_open_secure_token_ex, + ca_close_secure_token, ca_close_secure_token_ex, + ca_extract, ca_extract_ex, + ca_insert, ca_insert_ex) +from pycryptoki.encryption import (c_encrypt, c_encrypt_ex, + c_decrypt, c_decrypt_ex, + c_wrap_key, c_wrap_key_ex, + c_unwrap_key, c_unwrap_key_ex) +from pycryptoki.key_generator import (c_destroy_object, c_destroy_object_ex, + c_generate_key_pair, c_generate_key_pair_ex, + c_generate_key, c_generate_key_ex, + c_derive_key, c_derive_key_ex, + c_copy_object_ex, c_copy_object) +from pycryptoki.misc import (c_generate_random, c_generate_random_ex, + c_seed_random, c_seed_random_ex, + c_digest, c_digest_ex, + c_set_ped_id, c_set_ped_id_ex, + c_get_ped_id, c_get_ped_id_ex, + c_create_object, c_create_object_ex, + c_digestkey, c_digestkey_ex) +from pycryptoki.object_attr_lookup import (c_find_objects, c_find_objects_ex, + c_get_attribute_value, c_get_attribute_value_ex, + c_set_attribute_value, c_set_attribute_value_ex) +from pycryptoki.policy_management import (ca_set_hsm_policy, ca_set_hsm_policy_ex, + ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, + ca_set_container_policy, ca_set_container_policy_ex) +from pycryptoki.session_management import (c_initialize, c_initialize_ex, + c_finalize, c_finalize_ex, + c_open_session, c_open_session_ex, + c_get_session_info, c_get_session_info_ex, + c_get_token_info, c_get_token_info_ex, + c_close_session, c_close_session_ex, + c_logout, c_logout_ex, + c_init_pin, c_init_pin_ex, + ca_factory_reset, ca_factory_reset_ex, + c_set_pin, c_set_pin_ex, + c_close_all_sessions, c_close_all_sessions_ex, + ca_create_container, ca_create_container_ex, + login, login_ex, + ca_openapplicationID_ex, ca_openapplicationID, + ca_closeapplicationID, ca_closeapplicationID_ex, + ca_restart, ca_restart_ex, + ca_delete_container_with_handle_ex, ca_delete_container_with_handle, + ca_setapplicationID, ca_setapplicationID_ex) +from pycryptoki.sign_verify import (c_sign, c_sign_ex, + c_verify, c_verify_ex) +from pycryptoki.token_management import (c_init_token, c_init_token_ex, + c_get_mechanism_list, c_get_mechanism_list_ex, + c_get_mechanism_info, c_get_mechanism_info_ex, + get_token_by_label, get_token_by_label_ex) +from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, + ca_init_audit, ca_init_audit_ex, + ca_time_sync, ca_time_sync_ex) +from pycryptoki.cryptoki import CK_VOID_PTR from pycryptoki.key_generator import _get_mechanism -from pycryptoki.hsm_management import c_performselftest, c_performselftest_ex, \ - ca_settokencertificatesignature, ca_settokencertificatesignature_ex, \ - ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, \ - ca_initializeremotepedvector, ca_initializeremotepedvector_ex, \ - ca_deleteremotepedvector, ca_deleteremotepedvector_ex, ca_mtkrestore, \ - ca_mtkrestore_ex, ca_mtkresplit, ca_mtkresplit_ex, ca_mtkzeroize, ca_mtkzeroize_ex -from pycryptoki.key_management import ca_generatemofn, ca_generatemofn_ex, \ - ca_modifyusagecount, ca_modifyusagecount_ex -from pycryptoki.key_usage import ca_clonemofn, ca_clonemofn_ex, \ - ca_duplicatemofn, ca_duplicatemofn_ex - +from pycryptoki.hsm_management import (c_performselftest, c_performselftest_ex, + ca_settokencertificatesignature, ca_settokencertificatesignature_ex, + ca_hainit, ca_hainit_ex, + ca_createloginchallenge, ca_createloginchallenge_ex, + ca_initializeremotepedvector, ca_initializeremotepedvector_ex, + ca_deleteremotepedvector, ca_deleteremotepedvector_ex, + ca_mtkrestore, ca_mtkrestore_ex, + ca_mtkresplit, ca_mtkresplit_ex, + ca_mtkzeroize, ca_mtkzeroize_ex) +from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, + ca_modifyusagecount, ca_modifyusagecount_ex) +from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, + ca_duplicatemofn, ca_duplicatemofn_ex) from pycryptoki.cryptoki import * import logging @@ -62,16 +100,23 @@ class PycryptokiService(rpyc.SlaveService): - """ - This is the core service to expose to the daemon. - Add in a static method preceded by 'exposed_' and it'll be visible to anything + """This is the core service to expose to the daemon. + Add in a static method preceded by 'exposed\_' and it'll be visible to anything connecting to the daemon. If you're working with pointers, you'll need to create the pointer in a function here rather than passing in a pointer from the client (pointers getting pickled makes no sense). - """ + def _rpyc_getattr(self, name): + """Override RPYC's default getattr. + + The startswith exposed is rpyc's default. + The pycryptoki.cryptoki.__all__ is an extension, + as is the _ex bit. + + :param name: + """ if name.startswith("exposed_"): name = name elif name in pycryptoki.cryptoki.__all__: @@ -80,7 +125,7 @@ def _rpyc_getattr(self, name): name = "exposed_" + name return getattr(self, name) - #encryption.py + # encryption.py exposed_c_wrap_key = staticmethod(c_wrap_key) exposed_c_wrap_key_ex = staticmethod(c_wrap_key_ex) exposed_c_unwrap_key = staticmethod(c_unwrap_key) @@ -90,13 +135,13 @@ def _rpyc_getattr(self, name): exposed_c_decrypt = staticmethod(c_decrypt) exposed_c_decrypt_ex = staticmethod(c_decrypt_ex) - #sign_verify.py + # sign_verify.py exposed_c_sign = staticmethod(c_sign) exposed_c_sign_ex = staticmethod(c_sign_ex) exposed_c_verify = staticmethod(c_verify) exposed_c_verify_ex = staticmethod(c_verify_ex) - #token_management.py + # token_management.py exposed_c_init_token = staticmethod(c_init_token) exposed_c_init_token_ex = staticmethod(c_init_token_ex) exposed_c_get_mechanism_list = staticmethod(c_get_mechanism_list) @@ -104,7 +149,7 @@ def _rpyc_getattr(self, name): exposed_c_get_mechanism_info = staticmethod(c_get_mechanism_info) exposed_c_get_mechanism_info_ex = staticmethod(c_get_mechanism_info_ex) - #session_management.py + # session_management.py exposed_c_initialize = staticmethod(c_initialize) exposed_c_initialize_ex = staticmethod(c_initialize_ex) exposed_c_finalize = staticmethod(c_finalize) @@ -148,7 +193,7 @@ def _rpyc_getattr(self, name): exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) - #policy_management.py + # policy_management.py exposed_ca_set_hsm_policy = staticmethod(ca_set_hsm_policy) exposed_ca_set_hsm_policy_ex = staticmethod(ca_set_hsm_policy_ex) exposed_ca_set_destructive_hsm_policy = staticmethod(ca_set_destructive_hsm_policy) @@ -156,7 +201,7 @@ def _rpyc_getattr(self, name): exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) - #object_attr_lookup.py + # object_attr_lookup.py exposed_c_find_objects = staticmethod(c_find_objects) exposed_c_find_objects_ex = staticmethod(c_find_objects_ex) exposed_c_get_attribute_value = staticmethod(c_get_attribute_value) @@ -164,7 +209,7 @@ def _rpyc_getattr(self, name): exposed_c_set_attribute_value = staticmethod(c_set_attribute_value) exposed_c_set_attribute_value_ex = staticmethod(c_set_attribute_value_ex) - #misc.py + # misc.py exposed_c_generate_random = staticmethod(c_generate_random) exposed_c_generate_random_ex = staticmethod(c_generate_random_ex) exposed_c_seed_random = staticmethod(c_seed_random) @@ -180,7 +225,7 @@ def _rpyc_getattr(self, name): exposed_c_digest_key = staticmethod(c_digestkey) exposed_c_digest_key_ex = staticmethod(c_digestkey_ex) - #key_generator.py + # key_generator.py exposed_c_generate_key = staticmethod(c_generate_key) exposed_c_generate_key_ex = staticmethod(c_generate_key_ex) exposed_c_generate_key_pair = staticmethod(c_generate_key_pair) @@ -190,13 +235,13 @@ def _rpyc_getattr(self, name): exposed_c_copy_object = staticmethod(c_copy_object) exposed_c_copy_object_ex = staticmethod(c_copy_object_ex) - #backup.py + # backup.py exposed_ca_extract = staticmethod(ca_extract) exposed_ca_extract_ex = staticmethod(ca_extract_ex) exposed_ca_insert = staticmethod(ca_insert) exposed_ca_insert_ex = staticmethod(ca_insert_ex) - #audit_handling.py + # audit_handling.py exposed_ca_get_time = staticmethod(ca_get_time) exposed_ca_get_time_ex = staticmethod(ca_get_time_ex) exposed_ca_init_audit = staticmethod(ca_init_audit) @@ -204,7 +249,7 @@ def _rpyc_getattr(self, name): exposed_ca_time_sync = staticmethod(ca_time_sync) exposed_ca_time_sync_ex = staticmethod(ca_time_sync_ex) - #hsm_management.py + # hsm_management.py exposed_c_performselftest = staticmethod(c_performselftest) exposed_c_performselftest_ex = staticmethod(c_performselftest_ex) exposed_ca_settokencertificatesignature = staticmethod(ca_settokencertificatesignature) @@ -224,13 +269,13 @@ def _rpyc_getattr(self, name): exposed_ca_mtkzeroize = staticmethod(ca_mtkzeroize) exposed_ca_mtkzeroize_ex = staticmethod(ca_mtkzeroize_ex) - #key_management.py + # key_management.py exposed_ca_generatemofn = staticmethod(ca_generatemofn) exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) exposed_ca_modifyusagecount = staticmethod(ca_modifyusagecount) exposed_ca_modifyusagecount_ex = staticmethod(ca_modifyusagecount_ex) - #key_usage.py + # key_usage.py exposed_ca_clonemofn = staticmethod(ca_clonemofn) exposed_ca_clonemofn_ex = staticmethod(ca_clonemofn_ex) exposed_ca_duplicatemofn = staticmethod(ca_duplicatemofn) @@ -238,11 +283,18 @@ def _rpyc_getattr(self, name): @staticmethod def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): - """ - #key_generator.py + """#key_generator.py Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side because it involves pointers. + + :param h_session: + :param h_base_key: + :param h_second_key: + :param template: + :param mech_flavor: + :param mech: (Default value = None) + """ if mech: mech = _get_mechanism(mech) @@ -254,11 +306,18 @@ def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_ @staticmethod def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): - """ - #key_generator.py + """#key_generator.py Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side because it involves pointers. + + :param h_session: + :param h_base_key: + :param h_second_key: + :param template: + :param mech_flavor: + :param mech: (Default value = None) + """ if mech: mech = _get_mechanism(mech) @@ -279,9 +338,9 @@ def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_fla help="pycryptoki daemon IP port", metavar="") (options, args) = parser.parse_args() - #Default arguments - ip = options.i if options.i != None else 'localhost' - port = int(options.p if options.p != None else '8001') + # Default arguments + ip = options.i if options.i is not None else 'localhost' + port = int(options.p if options.p is not None else '8001') print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) t = ThreadedServer(PycryptokiService, diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py index 5fd143b..e4aa7c0 100755 --- a/pycryptoki/default_templates.py +++ b/pycryptoki/default_templates.py @@ -3,19 +3,18 @@ See the attributes.py file for methods to convert them into the proper C format. """ -from defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ - CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ +import copy + +from defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ CKK_DES2, CKK_DES3, CKK_CAST3, CKK_GENERIC_SECRET, CKA_MODIFIABLE, \ CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ CKA_VALUE_BITS, CKK_CAST5, CKK_RC2, CKK_RC4, CKK_RC5, CKA_ECDSA_PARAMS, CKK_AES, \ - CKK_SEED, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, CKK_ARIA, CKM_RSA_PKCS_KEY_PAIR_GEN, \ - CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ + CKK_SEED, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, CKK_ARIA, CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, CKM_ARIA_KEY_GEN, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN, \ - CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN, \ - CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN, \ + CKM_KCDSA_KEY_PAIR_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, \ CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, \ CKM_SHA1_RSA_PKCS, CKM_SHA224_RSA_PKCS, \ CKM_SHA256_RSA_PKCS, CKM_SHA384_RSA_PKCS, CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS_PSS, \ @@ -30,117 +29,115 @@ CKM_ECDSA from pycryptoki.defines import CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE, CKC_X_509, \ CKA_SUBJECT, CKA_VALUE, CKO_DATA, CKA_TOKEN -import copy -CKM_DES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 8, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES Key"} - -CKM_DES_UNWRAP_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_SIGN : True, - CKA_WRAP : True, - CKA_DERIVE : True, - CKA_LABEL : "DES Key"} - - -CKM_DES2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES2, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES2 Key"} -CKM_DES3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES3, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 24, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES3 Key"} - -CKM_CAST3_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_CAST3, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 8, #1-8 - CKA_EXTRACTABLE :True, - CKA_LABEL : "CAST3 Key"} - -CKM_GENERIC_SECRET_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_GENERIC_SECRET, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "GENERIC SECRET Key"} - -CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_MODIFIABLE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS - CKA_PUBLIC_EXPONENT : 3, #byte - CKA_LABEL : "RSA Public Key"} -CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_MODIFIABLE : True, - CKA_EXTRACTABLE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_LABEL : "RSA Private Key"} +CKM_DES_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_DES, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 8, + CKA_EXTRACTABLE: True, + CKA_LABEL: "DES Key"} + +CKM_DES_UNWRAP_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_DES, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_SIGN: True, + CKA_WRAP: True, + CKA_DERIVE: True, + CKA_LABEL: "DES Key"} + +CKM_DES2_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_DES2, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 16, + CKA_EXTRACTABLE: True, + CKA_LABEL: "DES2 Key"} +CKM_DES3_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_DES3, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 24, + CKA_EXTRACTABLE: True, + CKA_LABEL: "DES3 Key"} + +CKM_CAST3_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_CAST3, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 8, # 1-8 + CKA_EXTRACTABLE: True, + CKA_LABEL: "CAST3 Key"} + +CKM_GENERIC_SECRET_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_GENERIC_SECRET, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 16, + CKA_EXTRACTABLE: True, + CKA_LABEL: "GENERIC SECRET Key"} + +CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_MODIFIABLE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_MODULUS_BITS: 1024, # long 0 - MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT: 3, # byte + CKA_LABEL: "RSA Public Key"} +CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_MODIFIABLE: True, + CKA_EXTRACTABLE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_UNWRAP: True, + CKA_LABEL: "RSA Private Key"} dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, 0x6d, 0x1f, 0xf2, @@ -150,7 +147,8 @@ 0x5f, 0x39, 0x66, 0x21, 0x13, 0x65, 0xf5, 0x1b, 0x83, 0xe9, 0xff, 0xcc, 0xcb, 0x3d, 0x88, 0xcd, 0xf2, 0x38, 0xf7, 0xc2, 0x73, 0x91, 0x31, 0xca, 0x7a, 0xad, 0xff, 0x66, 0x2f, 0xec, 0x1f, 0xb0, 0xe1, 0xd3, 0x11, 0xa4, 0x04, 0x26, 0x03, 0x76, 0xfd, 0x01, 0x1f, 0xe0, 0x0d, 0x02, 0x04, 0xc3] -dsa_sub_prime_1024_160 = [0xd3, 0x80, 0x73, 0x53, 0xb5, 0x1c, 0x5f, 0x71, 0xb2, 0x2a, 0xc3, 0xd0, 0xc7, 0xe3, 0x94, 0x14, +dsa_sub_prime_1024_160 = [0xd3, 0x80, 0x73, 0x53, 0xb5, 0x1c, 0x5f, 0x71, 0xb2, 0x2a, 0xc3, 0xd0, 0xc7, 0xe3, 0x94, + 0x14, 0x8f, 0xce, 0xdc, 0x61] dsa_base_1024_160 = [0x42, 0xe3, 0x77, 0x8e, 0x6e, 0xc3, 0x1b, 0x0d, 0xb0, 0x7a, 0x6b, 0x37, 0x0d, 0x7f, 0xb6, 0xfb, 0x4a, 0x0b, 0xca, 0x6d, 0xea, 0xac, 0x37, 0x1f, 0x6a, 0xdb, 0xcb, 0xeb, 0xa3, 0x8d, 0xdf, 0x76, @@ -162,433 +160,440 @@ 0x57, 0x8f, 0xc3, 0x25, 0x54, 0x8d, 0xc1, 0xc0, 0x8e, 0x5f, 0x93, 0x22, 0xc3, 0xb1, 0x20, 0x5e] dsa_prime_2048_224 = [0xa2, 0x15, 0xdc, 0xa3, 0xf7, 0x87, 0x34, 0x2c, 0x91, 0x90, 0x87, 0x83, 0x70, 0x79, 0x73, 0x38, - 0x9f, 0x3e, 0x02, 0xf2, 0xc9, 0x68, 0xfe, 0x67, 0xca, 0xb9, 0x4f, 0x5d, 0x6f, 0x92, 0x8c, 0xe8, - 0x6c, 0x8d, 0x62, 0x25, 0x37, 0x4c, 0xa1, 0xbf, 0x7f, 0x27, 0x77, 0x44, 0x8c, 0xc7, 0xc0, 0xc5, - 0xed, 0x66, 0xd1, 0x20, 0x11, 0x7f, 0xec, 0x10, 0xed, 0x81, 0x55, 0x51, 0x45, 0x36, 0xe1, 0xaa, - 0x31, 0x6b, 0x8d, 0xd4, 0x58, 0x27, 0xa0, 0xf0, 0x0e, 0x5d, 0x91, 0x8c, 0x0f, 0xdd, 0x21, 0x8a, - 0xcd, 0x6c, 0x26, 0x3c, 0x1c, 0x2e, 0x55, 0xf6, 0xd0, 0xa7, 0x0f, 0x1b, 0xc9, 0x7f, 0x4b, 0xb0, - 0x4f, 0xff, 0xee, 0x4b, 0x78, 0xb4, 0xdf, 0x34, 0x90, 0xad, 0x98, 0xab, 0xad, 0x0a, 0x4b, 0xfe, - 0x1d, 0xaf, 0xaf, 0x6c, 0x09, 0xdd, 0xda, 0xdf, 0xb8, 0x88, 0x96, 0x94, 0x51, 0x3b, 0x86, 0x5c, - 0x07, 0xa4, 0xf5, 0xf9, 0x27, 0xbe, 0x72, 0x39, 0xe8, 0xd7, 0x67, 0x14, 0xe0, 0x3b, 0x7b, 0xfa, - 0xfb, 0x92, 0x94, 0x00, 0x0f, 0xbb, 0x3f, 0x7a, 0x75, 0x0b, 0x39, 0xca, 0x50, 0x63, 0x0e, 0xe7, - 0xd0, 0xbc, 0x45, 0xa9, 0xc9, 0x87, 0xae, 0x38, 0xae, 0x03, 0x7a, 0x11, 0xb1, 0xd1, 0x3d, 0xf5, - 0x51, 0x76, 0xd9, 0xd8, 0xab, 0x9e, 0xc0, 0xa4, 0x1b, 0x78, 0xa6, 0x36, 0x9e, 0xb5, 0x19, 0x88, - 0xfe, 0x9f, 0xbd, 0x97, 0xa1, 0x0d, 0x48, 0xe2, 0xeb, 0x21, 0x8e, 0xc6, 0x92, 0xb3, 0x1c, 0xfc, - 0xc9, 0x58, 0x3c, 0x7a, 0x41, 0x1d, 0x7d, 0xfa, 0x0a, 0xb3, 0x15, 0xfb, 0x0c, 0x75, 0xe2, 0x10, - 0x9e, 0xb1, 0xe2, 0xee, 0x75, 0xf4, 0x1d, 0x0a, 0x01, 0x65, 0x46, 0xda, 0x70, 0xa6, 0x31, 0xac, - 0x77, 0x8a, 0x2a, 0xe3, 0x25, 0x1f, 0x11, 0x39, 0xe5, 0x74, 0xe2, 0x6d, 0x2c, 0xc6, 0x5c, 0x47] -dsa_sub_prime_2048_224 = [0xd3, 0x76, 0x83, 0x74, 0x55, 0x3d, 0x49, 0x17, 0x19, 0x92, 0x74, 0xba, 0x05, 0x63, 0xbe, 0xff, + 0x9f, 0x3e, 0x02, 0xf2, 0xc9, 0x68, 0xfe, 0x67, 0xca, 0xb9, 0x4f, 0x5d, 0x6f, 0x92, 0x8c, 0xe8, + 0x6c, 0x8d, 0x62, 0x25, 0x37, 0x4c, 0xa1, 0xbf, 0x7f, 0x27, 0x77, 0x44, 0x8c, 0xc7, 0xc0, 0xc5, + 0xed, 0x66, 0xd1, 0x20, 0x11, 0x7f, 0xec, 0x10, 0xed, 0x81, 0x55, 0x51, 0x45, 0x36, 0xe1, 0xaa, + 0x31, 0x6b, 0x8d, 0xd4, 0x58, 0x27, 0xa0, 0xf0, 0x0e, 0x5d, 0x91, 0x8c, 0x0f, 0xdd, 0x21, 0x8a, + 0xcd, 0x6c, 0x26, 0x3c, 0x1c, 0x2e, 0x55, 0xf6, 0xd0, 0xa7, 0x0f, 0x1b, 0xc9, 0x7f, 0x4b, 0xb0, + 0x4f, 0xff, 0xee, 0x4b, 0x78, 0xb4, 0xdf, 0x34, 0x90, 0xad, 0x98, 0xab, 0xad, 0x0a, 0x4b, 0xfe, + 0x1d, 0xaf, 0xaf, 0x6c, 0x09, 0xdd, 0xda, 0xdf, 0xb8, 0x88, 0x96, 0x94, 0x51, 0x3b, 0x86, 0x5c, + 0x07, 0xa4, 0xf5, 0xf9, 0x27, 0xbe, 0x72, 0x39, 0xe8, 0xd7, 0x67, 0x14, 0xe0, 0x3b, 0x7b, 0xfa, + 0xfb, 0x92, 0x94, 0x00, 0x0f, 0xbb, 0x3f, 0x7a, 0x75, 0x0b, 0x39, 0xca, 0x50, 0x63, 0x0e, 0xe7, + 0xd0, 0xbc, 0x45, 0xa9, 0xc9, 0x87, 0xae, 0x38, 0xae, 0x03, 0x7a, 0x11, 0xb1, 0xd1, 0x3d, 0xf5, + 0x51, 0x76, 0xd9, 0xd8, 0xab, 0x9e, 0xc0, 0xa4, 0x1b, 0x78, 0xa6, 0x36, 0x9e, 0xb5, 0x19, 0x88, + 0xfe, 0x9f, 0xbd, 0x97, 0xa1, 0x0d, 0x48, 0xe2, 0xeb, 0x21, 0x8e, 0xc6, 0x92, 0xb3, 0x1c, 0xfc, + 0xc9, 0x58, 0x3c, 0x7a, 0x41, 0x1d, 0x7d, 0xfa, 0x0a, 0xb3, 0x15, 0xfb, 0x0c, 0x75, 0xe2, 0x10, + 0x9e, 0xb1, 0xe2, 0xee, 0x75, 0xf4, 0x1d, 0x0a, 0x01, 0x65, 0x46, 0xda, 0x70, 0xa6, 0x31, 0xac, + 0x77, 0x8a, 0x2a, 0xe3, 0x25, 0x1f, 0x11, 0x39, 0xe5, 0x74, 0xe2, 0x6d, 0x2c, 0xc6, 0x5c, 0x47] +dsa_sub_prime_2048_224 = [0xd3, 0x76, 0x83, 0x74, 0x55, 0x3d, 0x49, 0x17, 0x19, 0x92, 0x74, 0xba, 0x05, 0x63, 0xbe, + 0xff, 0xa2, 0xa4, 0x5f, 0x05, 0xae, 0x83, 0xdf, 0x9b, 0x34, 0x81, 0x55, 0xbf] dsa_base_2048_224 = [0x4e, 0x1f, 0x73, 0x4e, 0x08, 0x92, 0xd0, 0x4d, 0x80, 0x89, 0x93, 0xe6, 0x3d, 0xad, 0xef, 0xb3, - 0xfa, 0xa2, 0x48, 0x4c, 0x88, 0x83, 0x8d, 0x38, 0xd8, 0xea, 0x64, 0xca, 0x28, 0xd6, 0xc0, 0x89, - 0xbe, 0x4b, 0x88, 0x14, 0x66, 0x83, 0xec, 0xbd, 0x8b, 0x8d, 0xc6, 0xfb, 0x17, 0x81, 0xca, 0x1d, - 0x83, 0xf3, 0x7f, 0x38, 0xd2, 0x36, 0x03, 0x2b, 0x17, 0x51, 0x16, 0x6a, 0xe4, 0x3f, 0x22, 0xb5, - 0x2d, 0xd6, 0x03, 0x40, 0x1e, 0x89, 0xfe, 0xf6, 0xc9, 0xd0, 0x21, 0x5f, 0x49, 0xa2, 0xcf, 0x97, - 0x33, 0x7b, 0xe2, 0x61, 0x28, 0x8f, 0xd9, 0xac, 0xfb, 0xb6, 0xc2, 0xc0, 0xc5, 0xea, 0x70, 0x9d, - 0x14, 0x76, 0x02, 0x74, 0x41, 0x75, 0x4c, 0xcd, 0x71, 0x00, 0x79, 0x05, 0x52, 0x55, 0x97, 0xd7, - 0xae, 0xc7, 0x71, 0xeb, 0x01, 0x2b, 0x0b, 0xfc, 0xd3, 0x4f, 0x87, 0x16, 0xc7, 0xcc, 0xb1, 0x91, - 0x3d, 0x4f, 0xa6, 0x10, 0x50, 0x4b, 0x67, 0x79, 0x01, 0xdb, 0x37, 0x80, 0x01, 0x9a, 0xa6, 0x92, - 0x23, 0xfb, 0xcd, 0x94, 0x33, 0x6f, 0x2b, 0xf0, 0x2b, 0x44, 0x09, 0x39, 0x39, 0xcc, 0x0d, 0x96, - 0x11, 0xe8, 0xf5, 0xc6, 0x28, 0x50, 0x2e, 0x2b, 0x81, 0x08, 0x3f, 0xc1, 0x28, 0x2f, 0x65, 0x2e, - 0x16, 0x48, 0xc4, 0xe2, 0xb0, 0x29, 0x54, 0x99, 0x19, 0xc5, 0x78, 0xbf, 0x3b, 0xf3, 0x84, 0x70, - 0xc7, 0x8b, 0x5a, 0xcb, 0x10, 0x55, 0xfe, 0x4b, 0x71, 0xef, 0xf5, 0xdb, 0x85, 0xa6, 0xf5, 0xe8, - 0x00, 0xf5, 0xc2, 0xb4, 0xa6, 0x48, 0x39, 0x83, 0x6e, 0xd1, 0xb0, 0xad, 0xea, 0x2d, 0x7e, 0x2e, - 0x22, 0x98, 0xaa, 0x10, 0x7f, 0xa0, 0xec, 0x23, 0x70, 0x87, 0xf5, 0xda, 0x6b, 0x5e, 0x0d, 0x8b, - 0x46, 0xc8, 0x88, 0x61, 0xc3, 0xc1, 0xf5, 0xdb, 0x02, 0x2a, 0x62, 0x7a, 0xd5, 0x95, 0xe5, 0xe2] - -dsa_prime_2048_256 = [ 0xad, 0x78, 0xd1, 0x93, 0x08, 0x76, 0x4f, 0x04, 0xeb, 0x6a, 0xa3, 0x82, 0x09, 0x38, 0x0f, 0xf6, - 0xc9, 0x87, 0x5e, 0x27, 0xb2, 0x7c, 0xc1, 0x4b, 0x78, 0x29, 0xbe, 0x2e, 0xcd, 0xae, 0x26, 0x88, - 0xf4, 0x5d, 0xe8, 0x09, 0xd1, 0x16, 0x06, 0x61, 0xd4, 0x81, 0x65, 0x00, 0x5d, 0x76, 0x7e, 0xf1, - 0x24, 0x73, 0x01, 0x8f, 0x92, 0xd4, 0x07, 0xe7, 0xf3, 0xf7, 0x3a, 0xb9, 0x8b, 0x8e, 0xc8, 0xf4, - 0x13, 0x2b, 0x52, 0xb8, 0x2a, 0x08, 0x57, 0xbc, 0x15, 0xe5, 0x8e, 0x2a, 0x16, 0xda, 0x5e, 0xff, - 0xd2, 0x4e, 0xc7, 0x24, 0xa9, 0x70, 0x74, 0xd2, 0xb4, 0xc1, 0xc0, 0xec, 0x81, 0xcb, 0x83, 0xe9, - 0x29, 0x2a, 0xfd, 0x3b, 0xb9, 0x83, 0xec, 0x23, 0xd1, 0xf9, 0x13, 0xec, 0x1a, 0x68, 0x3f, 0x44, - 0x9b, 0x85, 0x7a, 0x5e, 0x6a, 0x38, 0x91, 0xe0, 0xc6, 0xc8, 0x15, 0x23, 0xf3, 0x98, 0xf7, 0x29, - 0x7f, 0x7b, 0x07, 0x14, 0x3f, 0x6f, 0xfa, 0x11, 0x71, 0x65, 0xff, 0xd9, 0xdc, 0x71, 0x23, 0xd3, - 0x40, 0xec, 0x3b, 0x5f, 0x47, 0x9c, 0x4d, 0x53, 0x4c, 0x4f, 0x61, 0x31, 0xae, 0xda, 0x2e, 0xb6, - 0xd3, 0xd2, 0x01, 0x2c, 0x63, 0x9b, 0xaa, 0x61, 0x79, 0x13, 0xe9, 0xcc, 0xef, 0x57, 0xb1, 0x7a, - 0xd1, 0xd2, 0xe3, 0xfd, 0x92, 0x29, 0x43, 0x4a, 0xc4, 0x50, 0x8c, 0x36, 0xe8, 0xa5, 0xca, 0x9a, - 0xf6, 0x43, 0x3e, 0x75, 0x32, 0x16, 0x8b, 0xe8, 0x98, 0x9c, 0x60, 0x00, 0x83, 0xb6, 0xf4, 0xc9, - 0xa2, 0x36, 0xe8, 0xf6, 0xe3, 0x8a, 0x68, 0x64, 0x61, 0x1d, 0x7b, 0xe2, 0x3c, 0xf2, 0x48, 0x77, - 0x7d, 0xe5, 0xd1, 0xd0, 0x7a, 0x8d, 0x34, 0xdd, 0x1c, 0xc2, 0xbe, 0x99, 0xa4, 0xda, 0xbf, 0xd1, - 0x30, 0x4b, 0xc1, 0xc9, 0x73, 0xc1, 0x07, 0x78, 0x04, 0x0f, 0xdd, 0x7f, 0xa2, 0xfa, 0xc1, 0x0f] -dsa_sub_prime_2048_256 = [ 0xac, 0x66, 0x19, 0x0a, 0x7f, 0x8d, 0x6b, 0x5f, 0xc3, 0x77, 0x06, 0x35, 0x58, 0x2f, 0x9b, 0xc1, - 0x4a, 0x56, 0x91, 0x55, 0xf9, 0x79, 0x3b, 0x79, 0x8e, 0x2e, 0xdb, 0xfc, 0x69, 0x4e, 0x6a, 0xfd] + 0xfa, 0xa2, 0x48, 0x4c, 0x88, 0x83, 0x8d, 0x38, 0xd8, 0xea, 0x64, 0xca, 0x28, 0xd6, 0xc0, 0x89, + 0xbe, 0x4b, 0x88, 0x14, 0x66, 0x83, 0xec, 0xbd, 0x8b, 0x8d, 0xc6, 0xfb, 0x17, 0x81, 0xca, 0x1d, + 0x83, 0xf3, 0x7f, 0x38, 0xd2, 0x36, 0x03, 0x2b, 0x17, 0x51, 0x16, 0x6a, 0xe4, 0x3f, 0x22, 0xb5, + 0x2d, 0xd6, 0x03, 0x40, 0x1e, 0x89, 0xfe, 0xf6, 0xc9, 0xd0, 0x21, 0x5f, 0x49, 0xa2, 0xcf, 0x97, + 0x33, 0x7b, 0xe2, 0x61, 0x28, 0x8f, 0xd9, 0xac, 0xfb, 0xb6, 0xc2, 0xc0, 0xc5, 0xea, 0x70, 0x9d, + 0x14, 0x76, 0x02, 0x74, 0x41, 0x75, 0x4c, 0xcd, 0x71, 0x00, 0x79, 0x05, 0x52, 0x55, 0x97, 0xd7, + 0xae, 0xc7, 0x71, 0xeb, 0x01, 0x2b, 0x0b, 0xfc, 0xd3, 0x4f, 0x87, 0x16, 0xc7, 0xcc, 0xb1, 0x91, + 0x3d, 0x4f, 0xa6, 0x10, 0x50, 0x4b, 0x67, 0x79, 0x01, 0xdb, 0x37, 0x80, 0x01, 0x9a, 0xa6, 0x92, + 0x23, 0xfb, 0xcd, 0x94, 0x33, 0x6f, 0x2b, 0xf0, 0x2b, 0x44, 0x09, 0x39, 0x39, 0xcc, 0x0d, 0x96, + 0x11, 0xe8, 0xf5, 0xc6, 0x28, 0x50, 0x2e, 0x2b, 0x81, 0x08, 0x3f, 0xc1, 0x28, 0x2f, 0x65, 0x2e, + 0x16, 0x48, 0xc4, 0xe2, 0xb0, 0x29, 0x54, 0x99, 0x19, 0xc5, 0x78, 0xbf, 0x3b, 0xf3, 0x84, 0x70, + 0xc7, 0x8b, 0x5a, 0xcb, 0x10, 0x55, 0xfe, 0x4b, 0x71, 0xef, 0xf5, 0xdb, 0x85, 0xa6, 0xf5, 0xe8, + 0x00, 0xf5, 0xc2, 0xb4, 0xa6, 0x48, 0x39, 0x83, 0x6e, 0xd1, 0xb0, 0xad, 0xea, 0x2d, 0x7e, 0x2e, + 0x22, 0x98, 0xaa, 0x10, 0x7f, 0xa0, 0xec, 0x23, 0x70, 0x87, 0xf5, 0xda, 0x6b, 0x5e, 0x0d, 0x8b, + 0x46, 0xc8, 0x88, 0x61, 0xc3, 0xc1, 0xf5, 0xdb, 0x02, 0x2a, 0x62, 0x7a, 0xd5, 0x95, 0xe5, 0xe2] + +dsa_prime_2048_256 = [0xad, 0x78, 0xd1, 0x93, 0x08, 0x76, 0x4f, 0x04, 0xeb, 0x6a, 0xa3, 0x82, 0x09, 0x38, 0x0f, 0xf6, + 0xc9, 0x87, 0x5e, 0x27, 0xb2, 0x7c, 0xc1, 0x4b, 0x78, 0x29, 0xbe, 0x2e, 0xcd, 0xae, 0x26, 0x88, + 0xf4, 0x5d, 0xe8, 0x09, 0xd1, 0x16, 0x06, 0x61, 0xd4, 0x81, 0x65, 0x00, 0x5d, 0x76, 0x7e, 0xf1, + 0x24, 0x73, 0x01, 0x8f, 0x92, 0xd4, 0x07, 0xe7, 0xf3, 0xf7, 0x3a, 0xb9, 0x8b, 0x8e, 0xc8, 0xf4, + 0x13, 0x2b, 0x52, 0xb8, 0x2a, 0x08, 0x57, 0xbc, 0x15, 0xe5, 0x8e, 0x2a, 0x16, 0xda, 0x5e, 0xff, + 0xd2, 0x4e, 0xc7, 0x24, 0xa9, 0x70, 0x74, 0xd2, 0xb4, 0xc1, 0xc0, 0xec, 0x81, 0xcb, 0x83, 0xe9, + 0x29, 0x2a, 0xfd, 0x3b, 0xb9, 0x83, 0xec, 0x23, 0xd1, 0xf9, 0x13, 0xec, 0x1a, 0x68, 0x3f, 0x44, + 0x9b, 0x85, 0x7a, 0x5e, 0x6a, 0x38, 0x91, 0xe0, 0xc6, 0xc8, 0x15, 0x23, 0xf3, 0x98, 0xf7, 0x29, + 0x7f, 0x7b, 0x07, 0x14, 0x3f, 0x6f, 0xfa, 0x11, 0x71, 0x65, 0xff, 0xd9, 0xdc, 0x71, 0x23, 0xd3, + 0x40, 0xec, 0x3b, 0x5f, 0x47, 0x9c, 0x4d, 0x53, 0x4c, 0x4f, 0x61, 0x31, 0xae, 0xda, 0x2e, 0xb6, + 0xd3, 0xd2, 0x01, 0x2c, 0x63, 0x9b, 0xaa, 0x61, 0x79, 0x13, 0xe9, 0xcc, 0xef, 0x57, 0xb1, 0x7a, + 0xd1, 0xd2, 0xe3, 0xfd, 0x92, 0x29, 0x43, 0x4a, 0xc4, 0x50, 0x8c, 0x36, 0xe8, 0xa5, 0xca, 0x9a, + 0xf6, 0x43, 0x3e, 0x75, 0x32, 0x16, 0x8b, 0xe8, 0x98, 0x9c, 0x60, 0x00, 0x83, 0xb6, 0xf4, 0xc9, + 0xa2, 0x36, 0xe8, 0xf6, 0xe3, 0x8a, 0x68, 0x64, 0x61, 0x1d, 0x7b, 0xe2, 0x3c, 0xf2, 0x48, 0x77, + 0x7d, 0xe5, 0xd1, 0xd0, 0x7a, 0x8d, 0x34, 0xdd, 0x1c, 0xc2, 0xbe, 0x99, 0xa4, 0xda, 0xbf, 0xd1, + 0x30, 0x4b, 0xc1, 0xc9, 0x73, 0xc1, 0x07, 0x78, 0x04, 0x0f, 0xdd, 0x7f, 0xa2, 0xfa, 0xc1, 0x0f] +dsa_sub_prime_2048_256 = [0xac, 0x66, 0x19, 0x0a, 0x7f, 0x8d, 0x6b, 0x5f, 0xc3, 0x77, 0x06, 0x35, 0x58, 0x2f, 0x9b, + 0xc1, + 0x4a, 0x56, 0x91, 0x55, 0xf9, 0x79, 0x3b, 0x79, 0x8e, 0x2e, 0xdb, 0xfc, 0x69, 0x4e, 0x6a, + 0xfd] dsa_base_2048_256 = [0xa6, 0x37, 0x45, 0x31, 0xe5, 0x54, 0x8a, 0x58, 0xa6, 0xd0, 0x20, 0x33, 0xdf, 0x60, 0xbf, 0xf8, - 0xa3, 0x5c, 0xa4, 0x1b, 0x37, 0xe4, 0xc9, 0xea, 0xb0, 0xf2, 0x53, 0x22, 0x19, 0x60, 0xaa, 0x6f, - 0xb2, 0x6b, 0xad, 0x24, 0x04, 0xad, 0x38, 0x57, 0x70, 0x3c, 0x4e, 0x71, 0x6e, 0x35, 0x0d, 0x4b, - 0xcc, 0xbc, 0x4d, 0xad, 0xd9, 0x1d, 0x30, 0x5e, 0xc4, 0x3a, 0x62, 0xfe, 0x2e, 0x82, 0x52, 0xcb, - 0x97, 0x37, 0xb6, 0x0a, 0xf4, 0xc5, 0x5d, 0xf7, 0xfa, 0xe4, 0x95, 0x18, 0xeb, 0x0d, 0x1b, 0xcc, - 0x0e, 0xda, 0x06, 0x50, 0x28, 0xa5, 0x1a, 0x87, 0x51, 0x21, 0xcd, 0xd5, 0xea, 0x60, 0xa1, 0x39, - 0x39, 0x82, 0x33, 0xa5, 0xd1, 0x9b, 0x0d, 0xb3, 0x5c, 0xc3, 0xeb, 0x7d, 0xa3, 0x23, 0xa8, 0xf3, - 0xb2, 0x95, 0xd3, 0x5c, 0x31, 0xb6, 0xaa, 0x55, 0xd4, 0x22, 0xaa, 0xb5, 0x5f, 0x47, 0x0f, 0xd2, - 0x79, 0xa3, 0xd3, 0x55, 0xb2, 0xa5, 0xd7, 0x5b, 0xd0, 0x37, 0x1d, 0x92, 0x58, 0xf6, 0xda, 0x07, - 0x48, 0x9e, 0x02, 0x9d, 0xfb, 0xd6, 0x71, 0x10, 0x7e, 0x0b, 0x2c, 0x94, 0xff, 0xc3, 0xdc, 0xa7, - 0x40, 0x4b, 0x81, 0x34, 0x19, 0xdb, 0x55, 0xc3, 0x46, 0xf8, 0xc3, 0x4d, 0xe7, 0x8a, 0x0d, 0x1c, - 0x69, 0xd2, 0x6f, 0x91, 0xb2, 0xd3, 0xcf, 0xc5, 0x20, 0xfe, 0x0a, 0xc0, 0x6d, 0x95, 0x5b, 0xd2, - 0x50, 0xa6, 0xb8, 0x6f, 0xe1, 0x32, 0xc0, 0x57, 0x13, 0x0b, 0x26, 0xd8, 0x22, 0x9d, 0xe3, 0xad, - 0x06, 0x79, 0xb4, 0xfc, 0xf5, 0x00, 0xb5, 0x5c, 0x76, 0x5d, 0xf9, 0x86, 0xb6, 0x69, 0x4f, 0x6c, - 0x02, 0x2d, 0x92, 0x7d, 0x9c, 0x48, 0x58, 0x7b, 0x17, 0x95, 0x7c, 0xe3, 0x97, 0x4d, 0x93, 0x7a, - 0x4c, 0x26, 0xc1, 0xa1, 0xe0, 0x6c, 0xbb, 0xc3, 0x01, 0x70, 0x9f, 0x14, 0x29, 0x3f, 0xe0, 0x5e] + 0xa3, 0x5c, 0xa4, 0x1b, 0x37, 0xe4, 0xc9, 0xea, 0xb0, 0xf2, 0x53, 0x22, 0x19, 0x60, 0xaa, 0x6f, + 0xb2, 0x6b, 0xad, 0x24, 0x04, 0xad, 0x38, 0x57, 0x70, 0x3c, 0x4e, 0x71, 0x6e, 0x35, 0x0d, 0x4b, + 0xcc, 0xbc, 0x4d, 0xad, 0xd9, 0x1d, 0x30, 0x5e, 0xc4, 0x3a, 0x62, 0xfe, 0x2e, 0x82, 0x52, 0xcb, + 0x97, 0x37, 0xb6, 0x0a, 0xf4, 0xc5, 0x5d, 0xf7, 0xfa, 0xe4, 0x95, 0x18, 0xeb, 0x0d, 0x1b, 0xcc, + 0x0e, 0xda, 0x06, 0x50, 0x28, 0xa5, 0x1a, 0x87, 0x51, 0x21, 0xcd, 0xd5, 0xea, 0x60, 0xa1, 0x39, + 0x39, 0x82, 0x33, 0xa5, 0xd1, 0x9b, 0x0d, 0xb3, 0x5c, 0xc3, 0xeb, 0x7d, 0xa3, 0x23, 0xa8, 0xf3, + 0xb2, 0x95, 0xd3, 0x5c, 0x31, 0xb6, 0xaa, 0x55, 0xd4, 0x22, 0xaa, 0xb5, 0x5f, 0x47, 0x0f, 0xd2, + 0x79, 0xa3, 0xd3, 0x55, 0xb2, 0xa5, 0xd7, 0x5b, 0xd0, 0x37, 0x1d, 0x92, 0x58, 0xf6, 0xda, 0x07, + 0x48, 0x9e, 0x02, 0x9d, 0xfb, 0xd6, 0x71, 0x10, 0x7e, 0x0b, 0x2c, 0x94, 0xff, 0xc3, 0xdc, 0xa7, + 0x40, 0x4b, 0x81, 0x34, 0x19, 0xdb, 0x55, 0xc3, 0x46, 0xf8, 0xc3, 0x4d, 0xe7, 0x8a, 0x0d, 0x1c, + 0x69, 0xd2, 0x6f, 0x91, 0xb2, 0xd3, 0xcf, 0xc5, 0x20, 0xfe, 0x0a, 0xc0, 0x6d, 0x95, 0x5b, 0xd2, + 0x50, 0xa6, 0xb8, 0x6f, 0xe1, 0x32, 0xc0, 0x57, 0x13, 0x0b, 0x26, 0xd8, 0x22, 0x9d, 0xe3, 0xad, + 0x06, 0x79, 0xb4, 0xfc, 0xf5, 0x00, 0xb5, 0x5c, 0x76, 0x5d, 0xf9, 0x86, 0xb6, 0x69, 0x4f, 0x6c, + 0x02, 0x2d, 0x92, 0x7d, 0x9c, 0x48, 0x58, 0x7b, 0x17, 0x95, 0x7c, 0xe3, 0x97, 0x4d, 0x93, 0x7a, + 0x4c, 0x26, 0xc1, 0xa1, 0xe0, 0x6c, 0xbb, 0xc3, 0x01, 0x70, 0x9f, 0x14, 0x29, 0x3f, 0xe0, 0x5e] dsa_prime_3072_256 = [0xa0, 0x38, 0x3e, 0xe6, 0x92, 0xf8, 0xf5, 0xba, 0xdd, 0xf9, 0x31, 0x7b, 0x16, 0xed, 0xd2, 0x84, - 0xa3, 0x63, 0x19, 0xb0, 0x53, 0xf7, 0x3a, 0xd4, 0x31, 0xae, 0x4b, 0x5d, 0xb2, 0xc6, 0x63, 0x0b, - 0x5a, 0xbf, 0xe8, 0xc5, 0xcb, 0x9d, 0x23, 0x06, 0x50, 0xdc, 0x72, 0xee, 0xfb, 0xe6, 0xf2, 0x61, - 0xdb, 0x2f, 0x43, 0xe6, 0x83, 0x81, 0x58, 0x8c, 0xfd, 0x4a, 0x74, 0x51, 0xbb, 0xbb, 0x30, 0xc5, - 0x95, 0x21, 0xd7, 0x8e, 0xa7, 0x6d, 0xc0, 0x70, 0xcf, 0x81, 0x78, 0x33, 0x19, 0x9f, 0xf7, 0x15, - 0xcb, 0xd1, 0x12, 0xa2, 0x58, 0x50, 0x69, 0x35, 0x44, 0x66, 0x2e, 0x12, 0xbb, 0x27, 0x93, 0xa8, - 0x14, 0x84, 0x77, 0x64, 0xac, 0x27, 0x7c, 0x5c, 0xf0, 0x6b, 0x3e, 0x04, 0x4a, 0x45, 0x91, 0x3e, - 0xdd, 0x61, 0x92, 0x29, 0xdd, 0xd7, 0x28, 0x93, 0x14, 0xd0, 0x0b, 0xb6, 0xa7, 0xda, 0xf1, 0x7e, - 0xb8, 0x63, 0xf3, 0x1d, 0xc2, 0x2c, 0xcc, 0x05, 0xf6, 0x14, 0xc1, 0xbb, 0x0c, 0xea, 0x4c, 0x45, - 0x4f, 0xc6, 0xa0, 0x29, 0xc0, 0xd2, 0x56, 0x8d, 0x1c, 0x5e, 0xef, 0x7f, 0x7c, 0x41, 0xf1, 0xb6, - 0x59, 0xce, 0xd9, 0x24, 0xdd, 0x0e, 0xab, 0xc7, 0xc9, 0xbc, 0x3a, 0x55, 0x90, 0xd4, 0x03, 0x12, - 0xe3, 0xec, 0x13, 0xa2, 0xca, 0xa1, 0x80, 0xed, 0x6b, 0x0c, 0x7d, 0x54, 0xd1, 0x63, 0xca, 0x1f, - 0x32, 0xcd, 0x89, 0x27, 0xa0, 0xfd, 0x39, 0x4e, 0x51, 0xde, 0xf2, 0xa3, 0x1e, 0x83, 0xfc, 0x53, - 0x73, 0xbe, 0xf8, 0xd2, 0x5f, 0x65, 0x32, 0xef, 0x51, 0x5f, 0x86, 0x7b, 0x0b, 0x31, 0x73, 0x8f, - 0xf2, 0x7f, 0xac, 0xad, 0x0d, 0xfb, 0x40, 0xe7, 0x6b, 0x68, 0x3a, 0x3b, 0x11, 0xc9, 0x9f, 0x59, - 0xc8, 0xa4, 0x98, 0xba, 0x2b, 0x88, 0x08, 0x70, 0x0f, 0x20, 0x15, 0x14, 0x5c, 0x77, 0xdb, 0xa4, - 0x20, 0xc5, 0xf0, 0xdb, 0x95, 0xac, 0x88, 0x03, 0x6a, 0x40, 0x90, 0x4a, 0x53, 0xb3, 0x80, 0xaa, - 0x0c, 0x75, 0x80, 0x5a, 0x0d, 0xfd, 0xad, 0x4c, 0xbe, 0xaa, 0x48, 0x91, 0xab, 0xd8, 0x4d, 0x24, - 0xbb, 0x64, 0x4d, 0x96, 0xc5, 0x9f, 0x33, 0x9e, 0x01, 0x6b, 0xb4, 0x32, 0x1f, 0xf4, 0xee, 0x33, - 0xe4, 0x03, 0xce, 0xa0, 0xde, 0x9e, 0xd9, 0x59, 0xcc, 0x6c, 0x1b, 0xba, 0x2c, 0x7d, 0xc7, 0x44, - 0xde, 0x7a, 0x22, 0x5f, 0x65, 0xfb, 0x0a, 0x78, 0xee, 0x57, 0xba, 0x7d, 0x2a, 0x92, 0xf2, 0x47, - 0x50, 0xda, 0xa6, 0x8c, 0x8a, 0x6a, 0x83, 0x06, 0xc3, 0x5c, 0x49, 0x0d, 0x2d, 0x2f, 0x58, 0x92, - 0xbe, 0x12, 0x41, 0x86, 0x0a, 0xd5, 0x45, 0x3b, 0x1b, 0xe3, 0x2b, 0x0e, 0xc7, 0x29, 0x98, 0x3e, - 0x3c, 0x97, 0xd3, 0x28, 0x73, 0xfc, 0x82, 0xc7, 0xb4, 0xf4, 0x6b, 0xfd, 0xa5, 0x14, 0x9e, 0x8f] -dsa_sub_prime_3072_256 = [0xf3, 0x96, 0x52, 0xd0, 0x0e, 0xf7, 0x96, 0x2d, 0xae, 0x7d, 0x8a, 0x13, 0xa8, 0x09, 0xa8, 0x14, - 0xc5, 0xe4, 0xf9, 0xba, 0x8e, 0x6d, 0xea, 0x3d, 0x18, 0xf3, 0x51, 0x48, 0x04, 0xfc, 0xe1, 0x37] -dsa_base_3072_256 = [ 0x07, 0x1f, 0x94, 0x97, 0xf8, 0x58, 0x85, 0x5e, 0xa6, 0x1f, 0xa8, 0x05, 0x97, 0x34, 0xc0, 0x12, - 0x2a, 0xc9, 0x1c, 0xb9, 0xf8, 0x1d, 0xfd, 0x8f, 0xa6, 0xec, 0xc0, 0x83, 0xf6, 0x0c, 0xb3, 0x0e, - 0xa8, 0x0b, 0x15, 0x56, 0xe5, 0xc3, 0x90, 0xd0, 0x06, 0x73, 0x24, 0x68, 0x28, 0xd4, 0xbc, 0xed, - 0xa1, 0x84, 0x89, 0x15, 0xab, 0x86, 0xff, 0x24, 0x56, 0x8e, 0x40, 0x02, 0x03, 0x99, 0xbd, 0xb9, - 0xf6, 0x75, 0x12, 0x59, 0x51, 0xad, 0x1e, 0x57, 0x1d, 0xd4, 0xf2, 0x23, 0x46, 0x14, 0x89, 0xab, - 0x65, 0x45, 0x04, 0x40, 0xe2, 0x2b, 0x01, 0xb8, 0xf5, 0x9b, 0x9b, 0x38, 0x69, 0x2f, 0x12, 0x0b, - 0x98, 0x34, 0xdd, 0x28, 0xeb, 0x9f, 0xf0, 0x8a, 0xfc, 0x44, 0x98, 0xe1, 0x72, 0xeb, 0x3d, 0x54, - 0xb2, 0x8a, 0x8e, 0xb1, 0x00, 0xab, 0x50, 0xa5, 0x66, 0x7b, 0x9a, 0x9e, 0x8a, 0xad, 0x3f, 0x68, - 0xf1, 0xde, 0xb1, 0x04, 0x60, 0x4a, 0x3d, 0x2e, 0x0f, 0x25, 0x0a, 0x9c, 0x18, 0x8b, 0x74, 0x61, - 0xec, 0xd7, 0xde, 0xc6, 0x56, 0xb5, 0x77, 0xe8, 0x46, 0x7e, 0x46, 0x4e, 0x11, 0xac, 0x49, 0x44, - 0x97, 0x88, 0x65, 0xcd, 0xf5, 0x63, 0xaa, 0xb6, 0xa2, 0xe6, 0x8a, 0x29, 0x53, 0x95, 0x2b, 0x0a, - 0x68, 0xe8, 0x81, 0x48, 0x6e, 0x76, 0x34, 0xd4, 0x91, 0x8d, 0xf9, 0x70, 0xa7, 0xce, 0x0d, 0x60, - 0x8a, 0x92, 0x70, 0x8e, 0x49, 0x52, 0x12, 0xfd, 0x4b, 0x26, 0x79, 0x0d, 0x5c, 0x07, 0xdd, 0x5a, - 0xb5, 0x5a, 0xe8, 0x20, 0x9b, 0x63, 0x19, 0x05, 0x55, 0xc0, 0x43, 0xb7, 0x80, 0x2f, 0xae, 0x78, - 0x79, 0x7e, 0x4f, 0x63, 0xf1, 0xcb, 0x18, 0x09, 0xaf, 0x4a, 0xfc, 0x60, 0xb2, 0xb4, 0xaf, 0x78, - 0xba, 0xb3, 0xad, 0x9c, 0xcc, 0x39, 0x10, 0x08, 0x96, 0x43, 0x8e, 0x67, 0x91, 0xae, 0xec, 0x90, - 0xe8, 0x99, 0xf9, 0x76, 0x59, 0x45, 0x4f, 0x4c, 0x75, 0x96, 0x33, 0xb0, 0xd8, 0x57, 0xb5, 0x05, - 0x12, 0x45, 0x15, 0xc7, 0x5e, 0x3a, 0x64, 0x90, 0xe7, 0x16, 0x8c, 0x73, 0xfa, 0x15, 0x68, 0xe8, - 0xc9, 0x04, 0xb0, 0x42, 0x49, 0xfa, 0x31, 0xa8, 0x3c, 0x6d, 0x83, 0x8a, 0xf7, 0xd4, 0x2d, 0x48, - 0x71, 0x09, 0x89, 0xf9, 0xfb, 0xc9, 0xc3, 0x7b, 0x2c, 0x87, 0x91, 0x57, 0xc9, 0xe9, 0x81, 0x8e, - 0xa4, 0xdd, 0xb7, 0x7a, 0x1f, 0xbc, 0x66, 0x3e, 0xd8, 0x2d, 0xe8, 0x38, 0xc3, 0xab, 0x3b, 0x82, - 0xc5, 0x7d, 0xd0, 0xff, 0xbf, 0xa4, 0x95, 0xe6, 0xea, 0xd3, 0x3e, 0x44, 0x05, 0xd0, 0x58, 0xe9, - 0xb3, 0x7b, 0x3a, 0x71, 0xce, 0xbd, 0xe4, 0x2f, 0x4d, 0x33, 0x46, 0xb4, 0xc5, 0xf9, 0xd6, 0x49, - 0x8b, 0x73, 0xbc, 0x1b, 0x9f, 0x0d, 0x3d, 0x0c, 0x49, 0x29, 0x42, 0x99, 0x70, 0xe9, 0xc5, 0xeb] - -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_1024_160, - CKA_SUBPRIME : dsa_sub_prime_1024_160, - CKA_BASE : dsa_base_1024_160, - CKA_LABEL : "DSA 1024_160 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_2048_224, - CKA_SUBPRIME : dsa_sub_prime_2048_224, - CKA_BASE : dsa_base_2048_224, - CKA_LABEL : "DSA 2048_224 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_2048_256, - CKA_SUBPRIME : dsa_sub_prime_2048_256, - CKA_BASE : dsa_base_2048_256, - CKA_LABEL : "DSA 2048_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_3072_256, - CKA_SUBPRIME : dsa_sub_prime_3072_256, - CKA_BASE : dsa_base_3072_256, - CKA_LABEL : "DSA 3072_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "DSA Public Key"} + 0xa3, 0x63, 0x19, 0xb0, 0x53, 0xf7, 0x3a, 0xd4, 0x31, 0xae, 0x4b, 0x5d, 0xb2, 0xc6, 0x63, 0x0b, + 0x5a, 0xbf, 0xe8, 0xc5, 0xcb, 0x9d, 0x23, 0x06, 0x50, 0xdc, 0x72, 0xee, 0xfb, 0xe6, 0xf2, 0x61, + 0xdb, 0x2f, 0x43, 0xe6, 0x83, 0x81, 0x58, 0x8c, 0xfd, 0x4a, 0x74, 0x51, 0xbb, 0xbb, 0x30, 0xc5, + 0x95, 0x21, 0xd7, 0x8e, 0xa7, 0x6d, 0xc0, 0x70, 0xcf, 0x81, 0x78, 0x33, 0x19, 0x9f, 0xf7, 0x15, + 0xcb, 0xd1, 0x12, 0xa2, 0x58, 0x50, 0x69, 0x35, 0x44, 0x66, 0x2e, 0x12, 0xbb, 0x27, 0x93, 0xa8, + 0x14, 0x84, 0x77, 0x64, 0xac, 0x27, 0x7c, 0x5c, 0xf0, 0x6b, 0x3e, 0x04, 0x4a, 0x45, 0x91, 0x3e, + 0xdd, 0x61, 0x92, 0x29, 0xdd, 0xd7, 0x28, 0x93, 0x14, 0xd0, 0x0b, 0xb6, 0xa7, 0xda, 0xf1, 0x7e, + 0xb8, 0x63, 0xf3, 0x1d, 0xc2, 0x2c, 0xcc, 0x05, 0xf6, 0x14, 0xc1, 0xbb, 0x0c, 0xea, 0x4c, 0x45, + 0x4f, 0xc6, 0xa0, 0x29, 0xc0, 0xd2, 0x56, 0x8d, 0x1c, 0x5e, 0xef, 0x7f, 0x7c, 0x41, 0xf1, 0xb6, + 0x59, 0xce, 0xd9, 0x24, 0xdd, 0x0e, 0xab, 0xc7, 0xc9, 0xbc, 0x3a, 0x55, 0x90, 0xd4, 0x03, 0x12, + 0xe3, 0xec, 0x13, 0xa2, 0xca, 0xa1, 0x80, 0xed, 0x6b, 0x0c, 0x7d, 0x54, 0xd1, 0x63, 0xca, 0x1f, + 0x32, 0xcd, 0x89, 0x27, 0xa0, 0xfd, 0x39, 0x4e, 0x51, 0xde, 0xf2, 0xa3, 0x1e, 0x83, 0xfc, 0x53, + 0x73, 0xbe, 0xf8, 0xd2, 0x5f, 0x65, 0x32, 0xef, 0x51, 0x5f, 0x86, 0x7b, 0x0b, 0x31, 0x73, 0x8f, + 0xf2, 0x7f, 0xac, 0xad, 0x0d, 0xfb, 0x40, 0xe7, 0x6b, 0x68, 0x3a, 0x3b, 0x11, 0xc9, 0x9f, 0x59, + 0xc8, 0xa4, 0x98, 0xba, 0x2b, 0x88, 0x08, 0x70, 0x0f, 0x20, 0x15, 0x14, 0x5c, 0x77, 0xdb, 0xa4, + 0x20, 0xc5, 0xf0, 0xdb, 0x95, 0xac, 0x88, 0x03, 0x6a, 0x40, 0x90, 0x4a, 0x53, 0xb3, 0x80, 0xaa, + 0x0c, 0x75, 0x80, 0x5a, 0x0d, 0xfd, 0xad, 0x4c, 0xbe, 0xaa, 0x48, 0x91, 0xab, 0xd8, 0x4d, 0x24, + 0xbb, 0x64, 0x4d, 0x96, 0xc5, 0x9f, 0x33, 0x9e, 0x01, 0x6b, 0xb4, 0x32, 0x1f, 0xf4, 0xee, 0x33, + 0xe4, 0x03, 0xce, 0xa0, 0xde, 0x9e, 0xd9, 0x59, 0xcc, 0x6c, 0x1b, 0xba, 0x2c, 0x7d, 0xc7, 0x44, + 0xde, 0x7a, 0x22, 0x5f, 0x65, 0xfb, 0x0a, 0x78, 0xee, 0x57, 0xba, 0x7d, 0x2a, 0x92, 0xf2, 0x47, + 0x50, 0xda, 0xa6, 0x8c, 0x8a, 0x6a, 0x83, 0x06, 0xc3, 0x5c, 0x49, 0x0d, 0x2d, 0x2f, 0x58, 0x92, + 0xbe, 0x12, 0x41, 0x86, 0x0a, 0xd5, 0x45, 0x3b, 0x1b, 0xe3, 0x2b, 0x0e, 0xc7, 0x29, 0x98, 0x3e, + 0x3c, 0x97, 0xd3, 0x28, 0x73, 0xfc, 0x82, 0xc7, 0xb4, 0xf4, 0x6b, 0xfd, 0xa5, 0x14, 0x9e, 0x8f] +dsa_sub_prime_3072_256 = [0xf3, 0x96, 0x52, 0xd0, 0x0e, 0xf7, 0x96, 0x2d, 0xae, 0x7d, 0x8a, 0x13, 0xa8, 0x09, 0xa8, + 0x14, + 0xc5, 0xe4, 0xf9, 0xba, 0x8e, 0x6d, 0xea, 0x3d, 0x18, 0xf3, 0x51, 0x48, 0x04, 0xfc, 0xe1, + 0x37] +dsa_base_3072_256 = [0x07, 0x1f, 0x94, 0x97, 0xf8, 0x58, 0x85, 0x5e, 0xa6, 0x1f, 0xa8, 0x05, 0x97, 0x34, 0xc0, 0x12, + 0x2a, 0xc9, 0x1c, 0xb9, 0xf8, 0x1d, 0xfd, 0x8f, 0xa6, 0xec, 0xc0, 0x83, 0xf6, 0x0c, 0xb3, 0x0e, + 0xa8, 0x0b, 0x15, 0x56, 0xe5, 0xc3, 0x90, 0xd0, 0x06, 0x73, 0x24, 0x68, 0x28, 0xd4, 0xbc, 0xed, + 0xa1, 0x84, 0x89, 0x15, 0xab, 0x86, 0xff, 0x24, 0x56, 0x8e, 0x40, 0x02, 0x03, 0x99, 0xbd, 0xb9, + 0xf6, 0x75, 0x12, 0x59, 0x51, 0xad, 0x1e, 0x57, 0x1d, 0xd4, 0xf2, 0x23, 0x46, 0x14, 0x89, 0xab, + 0x65, 0x45, 0x04, 0x40, 0xe2, 0x2b, 0x01, 0xb8, 0xf5, 0x9b, 0x9b, 0x38, 0x69, 0x2f, 0x12, 0x0b, + 0x98, 0x34, 0xdd, 0x28, 0xeb, 0x9f, 0xf0, 0x8a, 0xfc, 0x44, 0x98, 0xe1, 0x72, 0xeb, 0x3d, 0x54, + 0xb2, 0x8a, 0x8e, 0xb1, 0x00, 0xab, 0x50, 0xa5, 0x66, 0x7b, 0x9a, 0x9e, 0x8a, 0xad, 0x3f, 0x68, + 0xf1, 0xde, 0xb1, 0x04, 0x60, 0x4a, 0x3d, 0x2e, 0x0f, 0x25, 0x0a, 0x9c, 0x18, 0x8b, 0x74, 0x61, + 0xec, 0xd7, 0xde, 0xc6, 0x56, 0xb5, 0x77, 0xe8, 0x46, 0x7e, 0x46, 0x4e, 0x11, 0xac, 0x49, 0x44, + 0x97, 0x88, 0x65, 0xcd, 0xf5, 0x63, 0xaa, 0xb6, 0xa2, 0xe6, 0x8a, 0x29, 0x53, 0x95, 0x2b, 0x0a, + 0x68, 0xe8, 0x81, 0x48, 0x6e, 0x76, 0x34, 0xd4, 0x91, 0x8d, 0xf9, 0x70, 0xa7, 0xce, 0x0d, 0x60, + 0x8a, 0x92, 0x70, 0x8e, 0x49, 0x52, 0x12, 0xfd, 0x4b, 0x26, 0x79, 0x0d, 0x5c, 0x07, 0xdd, 0x5a, + 0xb5, 0x5a, 0xe8, 0x20, 0x9b, 0x63, 0x19, 0x05, 0x55, 0xc0, 0x43, 0xb7, 0x80, 0x2f, 0xae, 0x78, + 0x79, 0x7e, 0x4f, 0x63, 0xf1, 0xcb, 0x18, 0x09, 0xaf, 0x4a, 0xfc, 0x60, 0xb2, 0xb4, 0xaf, 0x78, + 0xba, 0xb3, 0xad, 0x9c, 0xcc, 0x39, 0x10, 0x08, 0x96, 0x43, 0x8e, 0x67, 0x91, 0xae, 0xec, 0x90, + 0xe8, 0x99, 0xf9, 0x76, 0x59, 0x45, 0x4f, 0x4c, 0x75, 0x96, 0x33, 0xb0, 0xd8, 0x57, 0xb5, 0x05, + 0x12, 0x45, 0x15, 0xc7, 0x5e, 0x3a, 0x64, 0x90, 0xe7, 0x16, 0x8c, 0x73, 0xfa, 0x15, 0x68, 0xe8, + 0xc9, 0x04, 0xb0, 0x42, 0x49, 0xfa, 0x31, 0xa8, 0x3c, 0x6d, 0x83, 0x8a, 0xf7, 0xd4, 0x2d, 0x48, + 0x71, 0x09, 0x89, 0xf9, 0xfb, 0xc9, 0xc3, 0x7b, 0x2c, 0x87, 0x91, 0x57, 0xc9, 0xe9, 0x81, 0x8e, + 0xa4, 0xdd, 0xb7, 0x7a, 0x1f, 0xbc, 0x66, 0x3e, 0xd8, 0x2d, 0xe8, 0x38, 0xc3, 0xab, 0x3b, 0x82, + 0xc5, 0x7d, 0xd0, 0xff, 0xbf, 0xa4, 0x95, 0xe6, 0xea, 0xd3, 0x3e, 0x44, 0x05, 0xd0, 0x58, 0xe9, + 0xb3, 0x7b, 0x3a, 0x71, 0xce, 0xbd, 0xe4, 0x2f, 0x4d, 0x33, 0x46, 0xb4, 0xc5, 0xf9, 0xd6, 0x49, + 0x8b, 0x73, 0xbc, 0x1b, 0x9f, 0x0d, 0x3d, 0x0c, 0x49, 0x29, 0x42, 0x99, 0x70, 0xe9, 0xc5, 0xeb] + +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_PRIME: dsa_prime_1024_160, + CKA_SUBPRIME: dsa_sub_prime_1024_160, + CKA_BASE: dsa_base_1024_160, + CKA_LABEL: "DSA 1024_160 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224 = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_PRIME: dsa_prime_2048_224, + CKA_SUBPRIME: dsa_sub_prime_2048_224, + CKA_BASE: dsa_base_2048_224, + CKA_LABEL: "DSA 2048_224 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_PRIME: dsa_prime_2048_256, + CKA_SUBPRIME: dsa_sub_prime_2048_256, + CKA_BASE: dsa_base_2048_256, + CKA_LABEL: "DSA 2048_256 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_PRIME: dsa_prime_3072_256, + CKA_SUBPRIME: dsa_sub_prime_3072_256, + CKA_BASE: dsa_base_3072_256, + CKA_LABEL: "DSA 3072_256 Public Key"} +CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_UNWRAP: True, + CKA_EXTRACTABLE: True, + CKA_LABEL: "DSA Public Key"} dh_prime = [0xF4, 0x88, 0xFD, 0x58, 0x4E, 0x49, 0xDB, 0xCD, 0x20, 0xB4, 0x9D, 0xE4, 0x91, 0x07, 0x36, 0x6B, - 0x33, 0x6C, 0x38, 0x0D, 0x45, 0x1D, 0x0F, 0x7C, 0x88, 0xB3, 0x1C, 0x7C, 0x5B, 0x2D, 0x8E, 0xF6, - 0xF3, 0xC9, 0x23, 0xC0, 0x43, 0xF0, 0xA5, 0x5B, 0x18, 0x8D, 0x8E, 0xBB, 0x55, 0x8C, 0xB8, 0x5D, - 0x38, 0xD3, 0x34, 0xFD, 0x7C, 0x17, 0x57, 0x43, 0xA3, 0x1D, 0x18, 0x6C, 0xDE, 0x33, 0x21, 0x2C, - 0xB5, 0x2A, 0xFF, 0x3C, 0xE1, 0xB1, 0x29, 0x40, 0x18, 0x11, 0x8D, 0x7C, 0x84, 0xA7, 0x0A, 0x72, - 0xD6, 0x86, 0xC4, 0x03, 0x19, 0xC8, 0x07, 0x29, 0x7A, 0xCA, 0x95, 0x0C, 0xD9, 0x96, 0x9F, 0xAB, - 0xD0, 0x0A, 0x50, 0x9B, 0x02, 0x46, 0xD3, 0x08, 0x3D, 0x66, 0xA4, 0x5D, 0x41, 0x9F, 0x9C, 0x7C, - 0xBD, 0x89, 0x4B, 0x22, 0x19, 0x26, 0xBA, 0xAB, 0xA2, 0x5E, 0xC3, 0x55, 0xE9, 0x2F, 0x78, 0xC7] -dh_prime_2048= [0xF1, 0x20, 0xB5, 0x5B, 0x3A, 0xE4, 0xD0, 0xF6, 0xEF, 0xA4, 0xF2, 0x9F, 0xC4, 0xDF, 0x86, 0x84, - 0x57, 0x54, 0x14, 0x90, 0x98, 0xBD, 0x3E, 0x57, 0x86, 0xE8, 0xC9, 0xA0, 0x30, 0xAF, 0xE6, 0xA7, - 0x6D, 0x7E, 0x4F, 0xDA, 0x20, 0x87, 0x46, 0x0C, 0xED, 0x88, 0xDC, 0xDB, 0x95, 0xDE, 0xD3, 0x4F, - 0xC7, 0x18, 0x80, 0x3A, 0x0D, 0xD2, 0xF1, 0x54, 0x5C, 0xD2, 0x29, 0x78, 0x3C, 0xE4, 0x40, 0x0C, - 0x1A, 0x6B, 0x36, 0x73, 0x42, 0xE1, 0xB3, 0xD3, 0xEB, 0x95, 0xDB, 0x7A, 0x06, 0xD6, 0x54, 0x11, - 0xDB, 0x0B, 0xB3, 0x00, 0x52, 0xA5, 0x74, 0x77, 0x5B, 0x47, 0x2A, 0x6E, 0x31, 0xCB, 0x8A, 0x5D, - 0x1C, 0x8A, 0x7D, 0x93, 0x7A, 0xC3, 0x62, 0x44, 0xC3, 0x29, 0x40, 0x6D, 0x3E, 0x47, 0x62, 0x2F, - 0x93, 0xCD, 0xF3, 0xED, 0xA6, 0x1E, 0x1D, 0x57, 0x4E, 0xFF, 0x5F, 0x46, 0x92, 0xCC, 0xFC, 0x7E, - 0x98, 0x8C, 0xE8, 0xB0, 0xAA, 0x33, 0x70, 0x96, 0x3D, 0xC1, 0x5B, 0x10, 0x2A, 0x07, 0x34, 0x84, - 0x4E, 0xCD, 0xEB, 0xD7, 0x15, 0x63, 0x8C, 0xC4, 0x67, 0xB0, 0xC1, 0xB9, 0xB8, 0x45, 0xB0, 0x3B, - 0x3A, 0x76, 0x83, 0x2C, 0xF5, 0x28, 0xB3, 0xF7, 0x10, 0x23, 0x7E, 0xAA, 0xF6, 0xE6, 0x8B, 0xE7, - 0x57, 0x35, 0x1F, 0x51, 0x34, 0x58, 0x5E, 0x0C, 0x2D, 0x36, 0xCF, 0xA3, 0x85, 0x34, 0xB0, 0x14, - 0x7D, 0xD0, 0x8C, 0x34, 0xBB, 0xC1, 0x8D, 0x49, 0x8C, 0xDA, 0x41, 0x48, 0x66, 0xDB, 0x41, 0xE1, - 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, - 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, - 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] -CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_DERIVE : True, - CKA_PRIME : dh_prime, - CKA_BASE : [0x02], - CKA_LABEL : "DH Public Key"} -CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS : len(dh_prime) * 8, #long - CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DERIVE : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "DH Private Key"} - -CKM_CAST5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_CAST5, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, # 1-16 - CKA_EXTRACTABLE :True, - CKA_LABEL : "CAST5 Key"} - -CKM_RC2_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_RC2, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 64, #1-128 - CKA_EXTRACTABLE :True, - CKA_LABEL : "RC2 Key"} - -CKM_RC4_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_RC4, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 256, #1-256 - CKA_EXTRACTABLE :True, - CKA_LABEL : "RC4 Key"} - -CKM_RC5_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_RC5, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 255, #1-255 - CKA_EXTRACTABLE :True, - CKA_LABEL : "RC5 Key"} - -CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP = {CKA_TOKEN : True, - CKA_DERIVE : True, - CKA_ENCRYPT : 0x1001, #TODO, is encrypt both a long and a boolean, uh oh - CKA_LABEL : "SSL3 Pre Master Key"} - + 0x33, 0x6C, 0x38, 0x0D, 0x45, 0x1D, 0x0F, 0x7C, 0x88, 0xB3, 0x1C, 0x7C, 0x5B, 0x2D, 0x8E, 0xF6, + 0xF3, 0xC9, 0x23, 0xC0, 0x43, 0xF0, 0xA5, 0x5B, 0x18, 0x8D, 0x8E, 0xBB, 0x55, 0x8C, 0xB8, 0x5D, + 0x38, 0xD3, 0x34, 0xFD, 0x7C, 0x17, 0x57, 0x43, 0xA3, 0x1D, 0x18, 0x6C, 0xDE, 0x33, 0x21, 0x2C, + 0xB5, 0x2A, 0xFF, 0x3C, 0xE1, 0xB1, 0x29, 0x40, 0x18, 0x11, 0x8D, 0x7C, 0x84, 0xA7, 0x0A, 0x72, + 0xD6, 0x86, 0xC4, 0x03, 0x19, 0xC8, 0x07, 0x29, 0x7A, 0xCA, 0x95, 0x0C, 0xD9, 0x96, 0x9F, 0xAB, + 0xD0, 0x0A, 0x50, 0x9B, 0x02, 0x46, 0xD3, 0x08, 0x3D, 0x66, 0xA4, 0x5D, 0x41, 0x9F, 0x9C, 0x7C, + 0xBD, 0x89, 0x4B, 0x22, 0x19, 0x26, 0xBA, 0xAB, 0xA2, 0x5E, 0xC3, 0x55, 0xE9, 0x2F, 0x78, 0xC7] +dh_prime_2048 = [0xF1, 0x20, 0xB5, 0x5B, 0x3A, 0xE4, 0xD0, 0xF6, 0xEF, 0xA4, 0xF2, 0x9F, 0xC4, 0xDF, 0x86, 0x84, + 0x57, 0x54, 0x14, 0x90, 0x98, 0xBD, 0x3E, 0x57, 0x86, 0xE8, 0xC9, 0xA0, 0x30, 0xAF, 0xE6, 0xA7, + 0x6D, 0x7E, 0x4F, 0xDA, 0x20, 0x87, 0x46, 0x0C, 0xED, 0x88, 0xDC, 0xDB, 0x95, 0xDE, 0xD3, 0x4F, + 0xC7, 0x18, 0x80, 0x3A, 0x0D, 0xD2, 0xF1, 0x54, 0x5C, 0xD2, 0x29, 0x78, 0x3C, 0xE4, 0x40, 0x0C, + 0x1A, 0x6B, 0x36, 0x73, 0x42, 0xE1, 0xB3, 0xD3, 0xEB, 0x95, 0xDB, 0x7A, 0x06, 0xD6, 0x54, 0x11, + 0xDB, 0x0B, 0xB3, 0x00, 0x52, 0xA5, 0x74, 0x77, 0x5B, 0x47, 0x2A, 0x6E, 0x31, 0xCB, 0x8A, 0x5D, + 0x1C, 0x8A, 0x7D, 0x93, 0x7A, 0xC3, 0x62, 0x44, 0xC3, 0x29, 0x40, 0x6D, 0x3E, 0x47, 0x62, 0x2F, + 0x93, 0xCD, 0xF3, 0xED, 0xA6, 0x1E, 0x1D, 0x57, 0x4E, 0xFF, 0x5F, 0x46, 0x92, 0xCC, 0xFC, 0x7E, + 0x98, 0x8C, 0xE8, 0xB0, 0xAA, 0x33, 0x70, 0x96, 0x3D, 0xC1, 0x5B, 0x10, 0x2A, 0x07, 0x34, 0x84, + 0x4E, 0xCD, 0xEB, 0xD7, 0x15, 0x63, 0x8C, 0xC4, 0x67, 0xB0, 0xC1, 0xB9, 0xB8, 0x45, 0xB0, 0x3B, + 0x3A, 0x76, 0x83, 0x2C, 0xF5, 0x28, 0xB3, 0xF7, 0x10, 0x23, 0x7E, 0xAA, 0xF6, 0xE6, 0x8B, 0xE7, + 0x57, 0x35, 0x1F, 0x51, 0x34, 0x58, 0x5E, 0x0C, 0x2D, 0x36, 0xCF, 0xA3, 0x85, 0x34, 0xB0, 0x14, + 0x7D, 0xD0, 0x8C, 0x34, 0xBB, 0xC1, 0x8D, 0x49, 0x8C, 0xDA, 0x41, 0x48, 0x66, 0xDB, 0x41, 0xE1, + 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, + 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, + 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] +CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_DERIVE: True, + CKA_PRIME: dh_prime, + CKA_BASE: [0x02], + CKA_LABEL: "DH Public Key"} +CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS: len(dh_prime) * 8, # long + CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_DERIVE: True, + CKA_EXTRACTABLE: True, + CKA_LABEL: "DH Private Key"} + +CKM_CAST5_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_CAST5, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 16, # 1-16 + CKA_EXTRACTABLE: True, + CKA_LABEL: "CAST5 Key"} + +CKM_RC2_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_RC2, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 64, # 1-128 + CKA_EXTRACTABLE: True, + CKA_LABEL: "RC2 Key"} + +CKM_RC4_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_RC4, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 256, # 1-256 + CKA_EXTRACTABLE: True, + CKA_LABEL: "RC4 Key"} + +CKM_RC5_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_RC5, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 255, # 1-255 + CKA_EXTRACTABLE: True, + CKA_LABEL: "RC5 Key"} + +CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP = {CKA_TOKEN: True, + CKA_DERIVE: True, + CKA_ENCRYPT: 0x1001, # TODO, is encrypt both a long and a boolean, uh oh + CKA_LABEL: "SSL3 Pre Master Key"} ''' Curve dictionary for ECDSA with oids as lists, taken from Components/tools/common/CommonData.cpp ''' curve_list = { - 'secp112r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x06], # [0] OID_secp112r1 - 'secp112r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x07], # [7] OID_secp112r2 - 'secp128r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1C], # [14] OID_secp128r1 - 'secp128r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1D], # [21] OID_secp128r2 - 'secp160k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x09], # [28] OID_secp160k1 - 'secp160r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x08], # [35] OID_secp160r1 - 'secp160r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1E], # [42] OID_secp160r2 - 'secp192k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1F], # [49] OID_secp192k1 - 'secp224k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x20], # [56] OID_secp224k1 - 'secp224r1(P-224)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x21], # [63] OID_secp224r1 - 'secp256k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], # [70] OID_secp256k1 - 'secp384r1(P-384)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], # [77] OID_secp384r1 - 'secp521r1(P-521)' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], # [84] OID_secp521r1 - - 'X9_62_prime192v1(P-192)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01], # [91] OID_X9_62_prime192v1 - 'X9_62_prime192v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], # [101] OID_X9_62_prime192v2 - 'X9_62_prime192v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], # [111] OID_X9_62_prime192v3 - 'X9_62_prime239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], # [121] OID_X9_62_prime239v1 - 'X9_62_prime239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], # [131] OID_X9_62_prime239v2 - 'X9_62_prime239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], # [141] OID_X9_62_prime239v3 - 'X9_62_prime256v1(P-256)' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], # [151] OID_X9_62_prime256v1 - - 'sect113r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x04], # [161] OID_sect113r1 - 'sect113r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x05], # [168] OID_sect113r2 - 'sect131r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x16], # [175] OID_sect131r1 - 'sect131r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x17], # [182] OID_sect131r2 - 'sect163k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x01], # [189] OID_sect163k1 - 'sect163r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x02], # [196] OID_sect163r1 - 'sect163r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0F], # [203] OID_sect163r2 - 'sect193r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x18], # [210] OID_sect193r1 - 'sect193r2' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x19], # [217] OID_sect193r2 - 'sect233k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1A], # [224] OID_sect233k1 - 'sect233r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1B], # [231] OID_sect233r1 - 'sect239k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x03], # [238] OID_sect239k1 - 'sect283k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x10], # [245] OID_sect283k1 - 'sect283r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x11], # [252] OID_sect283r1 - 'sect409k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x24], # [259] OID_sect409k1 - 'sect409r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x25], # [266] OID_sect409r1 - 'sect571k1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x26], # [273] OID_sect571k1 - 'sect571r1' : [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x27], # [280] OID_sect571r1 - - 'X9_62_c2pnb163v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], # [287] OID_X9_62_c2pnb163v1 - 'X9_62_c2pnb163v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], # [297] OID_X9_62_c2pnb163v2 - 'X9_62_c2pnb163v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], # [307] OID_X9_62_c2pnb163v3 - 'X9_62_c2pnb176v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], # [317] OID_X9_62_c2pnb176v1 - 'X9_62_c2tnb191v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], # [327] OID_X9_62_c2tnb191v1 - 'X9_62_c2tnb191v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], # [337] OID_X9_62_c2tnb191v2 - 'X9_62_c2tnb191v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], # [347] OID_X9_62_c2tnb191v3 - 'X9_62_c2pnb208w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], # [357] OID_X9_62_c2pnb208w1 - 'X9_62_c2tnb239v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], # [367] OID_X9_62_c2tnb239v1 - 'X9_62_c2tnb239v2' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], # [377] OID_X9_62_c2tnb239v2 - 'X9_62_c2tnb239v3' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], # [387] OID_X9_62_c2tnb239v3 - 'X9_62_c2pnb272w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], # [397] OID_X9_62_c2pnb272w1 - 'X9_62_c2pnb304w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], # [407] OID_X9_62_c2pnb304w1 - 'X9_62_c2tnb359v1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], # [417] OID_X9_62_c2tnb359v1 - 'X9_62_c2pnb368w1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], # [427] OID_X9_62_c2pnb368w1 - 'X9_62_c2tnb431r1' : [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], # [437] OID_X9_62_c2tnb431r1 - - 'brainpoolP160r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], # [447] brainpoolP160r1 - 'brainpoolP160t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], # [458] brainpoolP160t1 - 'brainpoolP192r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], # [469] brainpoolP192r1 - 'brainpoolP192t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], # [480] brainpoolP192t1 - 'brainpoolP224r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], # [491] brainpoolP224r1 - 'brainpoolP224t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], # [502] brainpoolP224t1 - 'brainpoolP256r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], # [513] brainpoolP256r1 - 'brainpoolP256t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], # [524] brainpoolP256t1 - 'brainpoolP320r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], # [535] brainpoolP320r1 - 'brainpoolP320t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], # [546] brainpoolP320t1 - 'brainpoolP384r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], # [557] brainpoolP384r1 - 'brainpoolP384t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], # [568] brainpoolP384t1 - 'brainpoolP512r1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], # [579] brainpoolP512r1 - 'brainpoolP512t1' : [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], # [590] brainpoolP512t1 - 'microsoftPlayReadP160' : [0x30, 0x81, 0x95, 0x02, 0x01, 0x01, 0x30, 0x20, - 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, - 0x01, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, - 0x01, 0x23, 0x45, 0x67, 0x27, 0x18, 0x28, 0x18, - 0x31, 0x41, 0x59, 0x26, 0x14, 0x14, 0x24, 0xf7, - 0x30, 0x2c, 0x04, 0x14, 0x37, 0xa5, 0xab, 0xcc, - 0xd2, 0x77, 0xbc, 0xe8, 0x76, 0x32, 0xff, 0x3d, - 0x47, 0x80, 0xc0, 0x09, 0xeb, 0xe4, 0x14, 0x97, - 0x04, 0x14, 0x0d, 0xd8, 0xda, 0xbf, 0x72, 0x5e, - 0x2f, 0x32, 0x28, 0xe8, 0x5f, 0x1a, 0xd7, 0x8f, - 0xde, 0xdf, 0x93, 0x28, 0x23, 0x9e, 0x04, 0x29, - 0x04, 0x87, 0x23, 0x94, 0x7f, 0xd6, 0xa3, 0xa1, - 0xe5, 0x35, 0x10, 0xc0, 0x7d, 0xba, 0x38, 0xda, - 0xf0, 0x10, 0x9f, 0xa1, 0x20, 0x44, 0x57, 0x44, - 0x91, 0x10, 0x75, 0x52, 0x2d, 0x8c, 0x3c, 0x58, - 0x56, 0xd4, 0xed, 0x7a, 0xcd, 0xa3, 0x79, 0x93, - 0x6f, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, - 0x01, 0x23, 0x45, 0x67, 0x27, 0x16, 0xb2, 0x6e, - 0xec, 0x14, 0x90, 0x44, 0x28, 0xc2, 0xa6, 0x75] - } - -CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_DERIVE : True, - CKA_ECDSA_PARAMS : curve_list['secp112r1'], - CKA_LABEL : "ECDSA Public Key"} -CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_DERIVE : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "ECDSA Private Key"} - -CKM_AES_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_AES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 24, #16, 24, 32 - CKA_EXTRACTABLE :True, - CKA_LABEL : "AES Key"} - -CKM_SEED_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_SEED, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "SEED Key"} + 'secp112r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x06], # [0] OID_secp112r1 + 'secp112r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x07], # [7] OID_secp112r2 + 'secp128r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1C], # [14] OID_secp128r1 + 'secp128r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1D], # [21] OID_secp128r2 + 'secp160k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x09], # [28] OID_secp160k1 + 'secp160r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x08], # [35] OID_secp160r1 + 'secp160r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1E], # [42] OID_secp160r2 + 'secp192k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1F], # [49] OID_secp192k1 + 'secp224k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x20], # [56] OID_secp224k1 + 'secp224r1(P-224)': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x21], # [63] OID_secp224r1 + 'secp256k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A], # [70] OID_secp256k1 + 'secp384r1(P-384)': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22], # [77] OID_secp384r1 + 'secp521r1(P-521)': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], # [84] OID_secp521r1 + + 'X9_62_prime192v1(P-192)': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01], +# [91] OID_X9_62_prime192v1 + 'X9_62_prime192v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], # [101] OID_X9_62_prime192v2 + 'X9_62_prime192v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], # [111] OID_X9_62_prime192v3 + 'X9_62_prime239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], # [121] OID_X9_62_prime239v1 + 'X9_62_prime239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], # [131] OID_X9_62_prime239v2 + 'X9_62_prime239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], # [141] OID_X9_62_prime239v3 + 'X9_62_prime256v1(P-256)': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], +# [151] OID_X9_62_prime256v1 + + 'sect113r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x04], # [161] OID_sect113r1 + 'sect113r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x05], # [168] OID_sect113r2 + 'sect131r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x16], # [175] OID_sect131r1 + 'sect131r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x17], # [182] OID_sect131r2 + 'sect163k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x01], # [189] OID_sect163k1 + 'sect163r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x02], # [196] OID_sect163r1 + 'sect163r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0F], # [203] OID_sect163r2 + 'sect193r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x18], # [210] OID_sect193r1 + 'sect193r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x19], # [217] OID_sect193r2 + 'sect233k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1A], # [224] OID_sect233k1 + 'sect233r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x1B], # [231] OID_sect233r1 + 'sect239k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x03], # [238] OID_sect239k1 + 'sect283k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x10], # [245] OID_sect283k1 + 'sect283r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x11], # [252] OID_sect283r1 + 'sect409k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x24], # [259] OID_sect409k1 + 'sect409r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x25], # [266] OID_sect409r1 + 'sect571k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x26], # [273] OID_sect571k1 + 'sect571r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x27], # [280] OID_sect571r1 + + 'X9_62_c2pnb163v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], # [287] OID_X9_62_c2pnb163v1 + 'X9_62_c2pnb163v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], # [297] OID_X9_62_c2pnb163v2 + 'X9_62_c2pnb163v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], # [307] OID_X9_62_c2pnb163v3 + 'X9_62_c2pnb176v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], # [317] OID_X9_62_c2pnb176v1 + 'X9_62_c2tnb191v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], # [327] OID_X9_62_c2tnb191v1 + 'X9_62_c2tnb191v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], # [337] OID_X9_62_c2tnb191v2 + 'X9_62_c2tnb191v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], # [347] OID_X9_62_c2tnb191v3 + 'X9_62_c2pnb208w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], # [357] OID_X9_62_c2pnb208w1 + 'X9_62_c2tnb239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], # [367] OID_X9_62_c2tnb239v1 + 'X9_62_c2tnb239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], # [377] OID_X9_62_c2tnb239v2 + 'X9_62_c2tnb239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], # [387] OID_X9_62_c2tnb239v3 + 'X9_62_c2pnb272w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], # [397] OID_X9_62_c2pnb272w1 + 'X9_62_c2pnb304w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], # [407] OID_X9_62_c2pnb304w1 + 'X9_62_c2tnb359v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], # [417] OID_X9_62_c2tnb359v1 + 'X9_62_c2pnb368w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], # [427] OID_X9_62_c2pnb368w1 + 'X9_62_c2tnb431r1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], # [437] OID_X9_62_c2tnb431r1 + + 'brainpoolP160r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], # [447] brainpoolP160r1 + 'brainpoolP160t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], # [458] brainpoolP160t1 + 'brainpoolP192r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], # [469] brainpoolP192r1 + 'brainpoolP192t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], # [480] brainpoolP192t1 + 'brainpoolP224r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], # [491] brainpoolP224r1 + 'brainpoolP224t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], # [502] brainpoolP224t1 + 'brainpoolP256r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], # [513] brainpoolP256r1 + 'brainpoolP256t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], # [524] brainpoolP256t1 + 'brainpoolP320r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], # [535] brainpoolP320r1 + 'brainpoolP320t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], # [546] brainpoolP320t1 + 'brainpoolP384r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], # [557] brainpoolP384r1 + 'brainpoolP384t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], # [568] brainpoolP384t1 + 'brainpoolP512r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], # [579] brainpoolP512r1 + 'brainpoolP512t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], # [590] brainpoolP512t1 + 'microsoftPlayReadP160': [0x30, 0x81, 0x95, 0x02, 0x01, 0x01, 0x30, 0x20, + 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, + 0x01, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x27, 0x18, 0x28, 0x18, + 0x31, 0x41, 0x59, 0x26, 0x14, 0x14, 0x24, 0xf7, + 0x30, 0x2c, 0x04, 0x14, 0x37, 0xa5, 0xab, 0xcc, + 0xd2, 0x77, 0xbc, 0xe8, 0x76, 0x32, 0xff, 0x3d, + 0x47, 0x80, 0xc0, 0x09, 0xeb, 0xe4, 0x14, 0x97, + 0x04, 0x14, 0x0d, 0xd8, 0xda, 0xbf, 0x72, 0x5e, + 0x2f, 0x32, 0x28, 0xe8, 0x5f, 0x1a, 0xd7, 0x8f, + 0xde, 0xdf, 0x93, 0x28, 0x23, 0x9e, 0x04, 0x29, + 0x04, 0x87, 0x23, 0x94, 0x7f, 0xd6, 0xa3, 0xa1, + 0xe5, 0x35, 0x10, 0xc0, 0x7d, 0xba, 0x38, 0xda, + 0xf0, 0x10, 0x9f, 0xa1, 0x20, 0x44, 0x57, 0x44, + 0x91, 0x10, 0x75, 0x52, 0x2d, 0x8c, 0x3c, 0x58, + 0x56, 0xd4, 0xed, 0x7a, 0xcd, 0xa3, 0x79, 0x93, + 0x6f, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x27, 0x16, 0xb2, 0x6e, + 0xec, 0x14, 0x90, 0x44, 0x28, 0xc2, 0xa6, 0x75] +} + +CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_DERIVE: True, + CKA_ECDSA_PARAMS: curve_list['secp112r1'], + CKA_LABEL: "ECDSA Public Key"} +CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_DERIVE: True, + CKA_EXTRACTABLE: True, + CKA_LABEL: "ECDSA Private Key"} + +CKM_AES_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_AES, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 24, # 16, 24, 32 + CKA_EXTRACTABLE: True, + CKA_LABEL: "AES Key"} + +CKM_SEED_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_SEED, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 16, + CKA_EXTRACTABLE: True, + CKA_LABEL: "SEED Key"} kcdsa_prime_1024_160 = [0xdc, 0x02, 0xf3, 0xe0, 0x51, 0x4e, 0xf4, 0x72, 0x36, 0x51, 0x09, 0x72, 0x5c, 0x12, 0x00, 0x50, - 0x69, 0x7d, 0xfc, 0x1d, 0xcb, 0xb4, 0x1f, 0xbc, 0x49, 0x63, 0xc4, 0x15, 0x45, 0x97, 0xb7, 0xae, - 0x8d, 0x4a, 0x35, 0x3c, 0xe2, 0xfb, 0x1f, 0xbf, 0x77, 0x7b, 0x89, 0xe5, 0x56, 0xc5, 0x15, 0x6b, - 0x1a, 0x4a, 0x82, 0xcc, 0xe2, 0xb8, 0xec, 0x4d, 0x61, 0x86, 0xd4, 0xa3, 0xf6, 0xc5, 0x65, 0xae, - 0x8c, 0xf6, 0x04, 0x62, 0x1d, 0x63, 0xec, 0x9f, 0x1e, 0x91, 0x31, 0x39, 0x1d, 0xc0, 0x55, 0xbc, - 0xac, 0xc5, 0x1a, 0xc8, 0x5c, 0x02, 0x93, 0xd7, 0xca, 0x74, 0x4f, 0xe9, 0xa2, 0x04, 0x5c, 0x3c, - 0xc1, 0xb6, 0xe1, 0x4d, 0xcd, 0xfa, 0xbb, 0x7d, 0xf8, 0xa7, 0xb1, 0x94, 0xd5, 0x08, 0xe1, 0x99, - 0xc1, 0x81, 0x62, 0x93, 0xd6, 0x8c, 0x7a, 0x5c, 0x0f, 0x8a, 0xc7, 0x14, 0xb5, 0xd6, 0xf5, 0xa3] -kcdsa_sub_prime_1024_160 = [0xc8, 0xf6, 0x2e, 0x10, 0xf0, 0xa4, 0xe5, 0x43, 0x1b, 0x8e, 0x1b, 0x0f, 0x53, 0xf6, 0x27, 0xec, + 0x69, 0x7d, 0xfc, 0x1d, 0xcb, 0xb4, 0x1f, 0xbc, 0x49, 0x63, 0xc4, 0x15, 0x45, 0x97, 0xb7, 0xae, + 0x8d, 0x4a, 0x35, 0x3c, 0xe2, 0xfb, 0x1f, 0xbf, 0x77, 0x7b, 0x89, 0xe5, 0x56, 0xc5, 0x15, 0x6b, + 0x1a, 0x4a, 0x82, 0xcc, 0xe2, 0xb8, 0xec, 0x4d, 0x61, 0x86, 0xd4, 0xa3, 0xf6, 0xc5, 0x65, 0xae, + 0x8c, 0xf6, 0x04, 0x62, 0x1d, 0x63, 0xec, 0x9f, 0x1e, 0x91, 0x31, 0x39, 0x1d, 0xc0, 0x55, 0xbc, + 0xac, 0xc5, 0x1a, 0xc8, 0x5c, 0x02, 0x93, 0xd7, 0xca, 0x74, 0x4f, 0xe9, 0xa2, 0x04, 0x5c, 0x3c, + 0xc1, 0xb6, 0xe1, 0x4d, 0xcd, 0xfa, 0xbb, 0x7d, 0xf8, 0xa7, 0xb1, 0x94, 0xd5, 0x08, 0xe1, 0x99, + 0xc1, 0x81, 0x62, 0x93, 0xd6, 0x8c, 0x7a, 0x5c, 0x0f, 0x8a, 0xc7, 0x14, 0xb5, 0xd6, 0xf5, 0xa3] +kcdsa_sub_prime_1024_160 = [0xc8, 0xf6, 0x2e, 0x10, 0xf0, 0xa4, 0xe5, 0x43, 0x1b, 0x8e, 0x1b, 0x0f, 0x53, 0xf6, 0x27, + 0xec, 0x6a, 0xd3, 0xa6, 0xa5] kcdsa_base_1024_160 = [0x9b, 0x8b, 0x4b, 0x16, 0x53, 0x65, 0x03, 0x18, 0x47, 0x19, 0xac, 0x4d, 0x13, 0x2d, 0x14, 0x57, 0x2d, 0xca, 0x56, 0x45, 0x3f, 0x05, 0x68, 0x68, 0x3b, 0x04, 0x17, 0x27, 0x6f, 0x93, 0x88, 0xdc, @@ -599,23 +604,25 @@ 0x1f, 0xcf, 0xb0, 0xdb, 0x83, 0x71, 0x24, 0x2c, 0x73, 0xf3, 0xa6, 0x4f, 0x56, 0xb2, 0x13, 0xfd, 0xdb, 0xbc, 0xcf, 0x77, 0x5d, 0x01, 0x1f, 0xb8, 0x35, 0x85, 0x4f, 0x88, 0xb0, 0x58, 0x92, 0x07] kcdsa_prime_2048_256 = [0xec, 0xfe, 0xa3, 0x3f, 0xa2, 0x27, 0xc3, 0xb1, 0xa7, 0xdf, 0xd7, 0xf1, 0xbb, 0x48, 0x7c, 0xd4, - 0x26, 0xab, 0x0a, 0x2b, 0x2b, 0x3a, 0xf1, 0x8f, 0xef, 0x9d, 0x61, 0xcd, 0x4f, 0x7b, 0xbb, 0x8d, - 0x7d, 0x8d, 0x4c, 0x84, 0x13, 0x7a, 0xaf, 0xe5, 0xb5, 0xba, 0x9d, 0xe4, 0xd2, 0xb5, 0x8b, 0x00, - 0x39, 0xbc, 0x66, 0x9c, 0x7c, 0x3d, 0x98, 0x7e, 0x0a, 0x74, 0x1b, 0x06, 0xcf, 0x97, 0xb5, 0x3e, - 0xcb, 0x1e, 0x1d, 0x22, 0x51, 0xe6, 0xd4, 0xe2, 0x72, 0xa7, 0x72, 0xd3, 0x4c, 0x3f, 0xfc, 0xd4, - 0xd5, 0x7c, 0x3f, 0x44, 0xa2, 0x1b, 0xfc, 0x97, 0xad, 0x34, 0xb2, 0x8f, 0xd3, 0xcf, 0x77, 0x89, - 0x7a, 0xce, 0x64, 0xc6, 0x92, 0xaa, 0x69, 0x13, 0xed, 0x22, 0xa2, 0x3b, 0x45, 0x19, 0x98, 0x88, - 0x29, 0x05, 0x7c, 0xd2, 0x33, 0xaf, 0xa1, 0xf7, 0xab, 0x66, 0x40, 0xca, 0x05, 0x7e, 0x16, 0x99, - 0x7a, 0x92, 0xaa, 0x5e, 0x07, 0xc0, 0xc7, 0x3c, 0x82, 0xb4, 0x96, 0x02, 0x23, 0x66, 0x99, 0x97, - 0xa3, 0x40, 0xf1, 0x36, 0x9b, 0x33, 0xc7, 0xbe, 0xe9, 0xac, 0xce, 0x85, 0xf8, 0xbd, 0x6a, 0x26, - 0x0f, 0x79, 0xe7, 0x9e, 0xee, 0xee, 0xd6, 0x82, 0xc8, 0x7d, 0x4b, 0xe7, 0x4c, 0x2f, 0x44, 0x9a, - 0x1b, 0x68, 0x3f, 0xba, 0xe4, 0xfd, 0x19, 0xca, 0xd0, 0x97, 0xd3, 0x71, 0x12, 0x8c, 0x86, 0xbe, - 0x93, 0x84, 0xb7, 0x35, 0x2a, 0xd1, 0x3a, 0x9a, 0x27, 0x8f, 0x36, 0x4f, 0x08, 0x9e, 0x38, 0xdf, - 0x25, 0xe8, 0x4a, 0x70, 0x4d, 0xe4, 0xfb, 0x16, 0x40, 0xa5, 0x19, 0xfc, 0x62, 0x91, 0x76, 0x1d, - 0xab, 0x11, 0xe2, 0xf7, 0x80, 0xe7, 0x1a, 0x62, 0x2e, 0x9a, 0xbf, 0x85, 0xfe, 0x19, 0x4a, 0x45, - 0x79, 0x3b, 0xfa, 0xb3, 0xa1, 0xe9, 0x8a, 0x1d, 0xfd, 0x57, 0xb5, 0xc7, 0x09, 0x79, 0xb8, 0x1b] -kcdsa_sub_prime_2048_256 = [0xe5, 0x7d, 0x48, 0xd4, 0x44, 0x3d, 0x60, 0xb2, 0x6f, 0x48, 0x82, 0x3d, 0x1d, 0xea, 0xce, 0xf2, - 0xb4, 0x4a, 0x6c, 0x47, 0x5b, 0x12, 0x43, 0x47, 0xb4, 0x81, 0x47, 0xf8, 0xa2, 0xfd, 0x33, 0xd3] + 0x26, 0xab, 0x0a, 0x2b, 0x2b, 0x3a, 0xf1, 0x8f, 0xef, 0x9d, 0x61, 0xcd, 0x4f, 0x7b, 0xbb, 0x8d, + 0x7d, 0x8d, 0x4c, 0x84, 0x13, 0x7a, 0xaf, 0xe5, 0xb5, 0xba, 0x9d, 0xe4, 0xd2, 0xb5, 0x8b, 0x00, + 0x39, 0xbc, 0x66, 0x9c, 0x7c, 0x3d, 0x98, 0x7e, 0x0a, 0x74, 0x1b, 0x06, 0xcf, 0x97, 0xb5, 0x3e, + 0xcb, 0x1e, 0x1d, 0x22, 0x51, 0xe6, 0xd4, 0xe2, 0x72, 0xa7, 0x72, 0xd3, 0x4c, 0x3f, 0xfc, 0xd4, + 0xd5, 0x7c, 0x3f, 0x44, 0xa2, 0x1b, 0xfc, 0x97, 0xad, 0x34, 0xb2, 0x8f, 0xd3, 0xcf, 0x77, 0x89, + 0x7a, 0xce, 0x64, 0xc6, 0x92, 0xaa, 0x69, 0x13, 0xed, 0x22, 0xa2, 0x3b, 0x45, 0x19, 0x98, 0x88, + 0x29, 0x05, 0x7c, 0xd2, 0x33, 0xaf, 0xa1, 0xf7, 0xab, 0x66, 0x40, 0xca, 0x05, 0x7e, 0x16, 0x99, + 0x7a, 0x92, 0xaa, 0x5e, 0x07, 0xc0, 0xc7, 0x3c, 0x82, 0xb4, 0x96, 0x02, 0x23, 0x66, 0x99, 0x97, + 0xa3, 0x40, 0xf1, 0x36, 0x9b, 0x33, 0xc7, 0xbe, 0xe9, 0xac, 0xce, 0x85, 0xf8, 0xbd, 0x6a, 0x26, + 0x0f, 0x79, 0xe7, 0x9e, 0xee, 0xee, 0xd6, 0x82, 0xc8, 0x7d, 0x4b, 0xe7, 0x4c, 0x2f, 0x44, 0x9a, + 0x1b, 0x68, 0x3f, 0xba, 0xe4, 0xfd, 0x19, 0xca, 0xd0, 0x97, 0xd3, 0x71, 0x12, 0x8c, 0x86, 0xbe, + 0x93, 0x84, 0xb7, 0x35, 0x2a, 0xd1, 0x3a, 0x9a, 0x27, 0x8f, 0x36, 0x4f, 0x08, 0x9e, 0x38, 0xdf, + 0x25, 0xe8, 0x4a, 0x70, 0x4d, 0xe4, 0xfb, 0x16, 0x40, 0xa5, 0x19, 0xfc, 0x62, 0x91, 0x76, 0x1d, + 0xab, 0x11, 0xe2, 0xf7, 0x80, 0xe7, 0x1a, 0x62, 0x2e, 0x9a, 0xbf, 0x85, 0xfe, 0x19, 0x4a, 0x45, + 0x79, 0x3b, 0xfa, 0xb3, 0xa1, 0xe9, 0x8a, 0x1d, 0xfd, 0x57, 0xb5, 0xc7, 0x09, 0x79, 0xb8, 0x1b] +kcdsa_sub_prime_2048_256 = [0xe5, 0x7d, 0x48, 0xd4, 0x44, 0x3d, 0x60, 0xb2, 0x6f, 0x48, 0x82, 0x3d, 0x1d, 0xea, 0xce, + 0xf2, + 0xb4, 0x4a, 0x6c, 0x47, 0x5b, 0x12, 0x43, 0x47, 0xb4, 0x81, 0x47, 0xf8, 0xa2, 0xfd, 0x33, + 0xd3] kcdsa_base_2048_256 = [0x68, 0x90, 0xea, 0x6f, 0x5a, 0x56, 0x4f, 0xd2, 0xa1, 0xfe, 0x07, 0xd7, 0xbc, 0xa5, 0xab, 0x80, 0xf9, 0x5a, 0x5f, 0x47, 0xe9, 0x7f, 0xfc, 0x9a, 0xea, 0x67, 0x13, 0xf8, 0xad, 0x36, 0xe1, 0xfc, 0x02, 0x42, 0x17, 0xcd, 0xf9, 0xbe, 0x5c, 0xe9, 0xa6, 0xcd, 0xdb, 0x6b, 0x5c, 0x1e, 0x7e, 0x22, @@ -632,74 +639,74 @@ 0xe4, 0xb9, 0xb0, 0xba, 0xac, 0x32, 0xc2, 0x24, 0x0b, 0x2a, 0x47, 0x17, 0xda, 0x7c, 0x11, 0x6c, 0xe2, 0x09, 0x24, 0x71, 0x30, 0xac, 0x14, 0x0c, 0xd3, 0xab, 0xdc, 0xe7, 0x78, 0xa4, 0x27, 0x27, 0xf3, 0x2c, 0xfa, 0xfd, 0xae, 0x9e, 0x51, 0x68, 0x47, 0xb2, 0x6c, 0xe4, 0xcb, 0xb7, 0x66, 0x03] -CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, #1024_160 or 2048_256 - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : kcdsa_prime_1024_160, - CKA_SUBPRIME : kcdsa_sub_prime_1024_160, - CKA_BASE : kcdsa_base_1024_160, - CKA_LABEL : "KCDSA Public Key"} -CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN : True, #1024_160 or 2048_256 - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : kcdsa_prime_2048_256, - CKA_SUBPRIME : kcdsa_sub_prime_2048_256, - CKA_BASE : kcdsa_base_2048_256, - CKA_LABEL : "KCDSA Public Key"} -CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "KCDSA Private Key"} - -CKM_DSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_PRIME_BITS : 1024, # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 - CKA_SUBPRIME_BITS : 160, #0-512 - CKA_LABEL : "DSA Parameter Key"} - -CKM_KCDSA_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, #primelength 0-4096, subprimelength 0-512 - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_PRIME_BITS : 2048, #0-4096 - CKA_SUBPRIME_BITS : 256, #0-512 - CKA_LABEL : "KCDSA Parameter Key"} - -CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_MODIFIABLE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_MODULUS_BITS : 1024, #long 1-MAX_RSA_KEY_NBITS - CKA_PUBLIC_EXPONENT : 3, #byte - CKA_LABEL : "RSA Public Key"} -CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_MODIFIABLE : True, - CKA_EXTRACTABLE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_LABEL : "RSA Private Key"} +CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN: True, # 1024_160 or 2048_256 + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_PRIME: kcdsa_prime_1024_160, + CKA_SUBPRIME: kcdsa_sub_prime_1024_160, + CKA_BASE: kcdsa_base_1024_160, + CKA_LABEL: "KCDSA Public Key"} +CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN: True, # 1024_160 or 2048_256 + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_PRIME: kcdsa_prime_2048_256, + CKA_SUBPRIME: kcdsa_sub_prime_2048_256, + CKA_BASE: kcdsa_base_2048_256, + CKA_LABEL: "KCDSA Public Key"} +CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_UNWRAP: True, + CKA_EXTRACTABLE: True, + CKA_LABEL: "KCDSA Private Key"} + +CKM_DSA_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_PRIME_BITS: 1024, # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 + CKA_SUBPRIME_BITS: 160, # 0-512 + CKA_LABEL: "DSA Parameter Key"} + +CKM_KCDSA_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, # primelength 0-4096, subprimelength 0-512 + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_PRIME_BITS: 2048, # 0-4096 + CKA_SUBPRIME_BITS: 256, # 0-512 + CKA_LABEL: "KCDSA Parameter Key"} + +CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_MODIFIABLE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_MODULUS_BITS: 1024, # long 1-MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT: 3, # byte + CKA_LABEL: "RSA Public Key"} +CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_MODIFIABLE: True, + CKA_EXTRACTABLE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_UNWRAP: True, + CKA_LABEL: "RSA Private Key"} dhX9_42Prime = [0xE0, 0x01, 0xE8, 0x96, 0x7D, 0xB4, 0x93, 0x53, 0xE1, 0x6F, 0x8E, 0x89, 0x22, 0x0C, 0xCE, 0xFC, - 0x5C, 0x5F, 0x12, 0xE3, 0xDF, 0xF8, 0xF1, 0xD1, 0x49, 0x90, 0x12, 0xE6, 0xEF, 0x53, 0xE3, 0x1F, - 0x02, 0xEA, 0xCC, 0x5A, 0xDD, 0xF3, 0x37, 0x89, 0x35, 0xC9, 0x5B, 0x21, 0xEA, 0x3D, 0x6F, 0x1C, - 0xD7, 0xCE, 0x63, 0x75, 0x52, 0xEC, 0x38, 0x6C, 0x0E, 0x34, 0xF7, 0x36, 0xAD, 0x95, 0x17, 0xEF, - 0xFE, 0x5E, 0x4D, 0xA7, 0xA8, 0x6A, 0xF9, 0x0E, 0x2C, 0x22, 0x8F, 0xE4, 0xB9, 0xE6, 0xD8, 0xF8, - 0xF0, 0x2D, 0x20, 0xAF, 0x78, 0xAB, 0xB6, 0x92, 0xAC, 0xBC, 0x4B, 0x23, 0xFA, 0xF2, 0xC5, 0xCC, - 0xD4, 0x9A, 0x0C, 0x9A, 0x8B, 0xCD, 0x91, 0xAC, 0x0C, 0x55, 0x92, 0x01, 0xE6, 0xC2, 0xFD, 0x1F, - 0x47, 0xC2, 0xCB, 0x2A, 0x88, 0xA8, 0x3C, 0x21, 0x0F, 0xC0, 0x54, 0xDB, 0x29, 0x2D, 0xBC, 0x45] + 0x5C, 0x5F, 0x12, 0xE3, 0xDF, 0xF8, 0xF1, 0xD1, 0x49, 0x90, 0x12, 0xE6, 0xEF, 0x53, 0xE3, 0x1F, + 0x02, 0xEA, 0xCC, 0x5A, 0xDD, 0xF3, 0x37, 0x89, 0x35, 0xC9, 0x5B, 0x21, 0xEA, 0x3D, 0x6F, 0x1C, + 0xD7, 0xCE, 0x63, 0x75, 0x52, 0xEC, 0x38, 0x6C, 0x0E, 0x34, 0xF7, 0x36, 0xAD, 0x95, 0x17, 0xEF, + 0xFE, 0x5E, 0x4D, 0xA7, 0xA8, 0x6A, 0xF9, 0x0E, 0x2C, 0x22, 0x8F, 0xE4, 0xB9, 0xE6, 0xD8, 0xF8, + 0xF0, 0x2D, 0x20, 0xAF, 0x78, 0xAB, 0xB6, 0x92, 0xAC, 0xBC, 0x4B, 0x23, 0xFA, 0xF2, 0xC5, 0xCC, + 0xD4, 0x9A, 0x0C, 0x9A, 0x8B, 0xCD, 0x91, 0xAC, 0x0C, 0x55, 0x92, 0x01, 0xE6, 0xC2, 0xFD, 0x1F, + 0x47, 0xC2, 0xCB, 0x2A, 0x88, 0xA8, 0x3C, 0x21, 0x0F, 0xC0, 0x54, 0xDB, 0x29, 0x2D, 0xBC, 0x45] dhX9_42Base = [0x86, 0x47, 0x17, 0xA3, 0x9E, 0x6A, 0xEA, 0x7E, 0x87, 0xC4, 0x32, 0xEE, 0x77, 0x43, 0x15, 0x16, 0x96, 0x70, 0xC4, 0x99] dhX9_42SubPrime = [0x1C, 0xE0, 0xF6, 0x69, 0x26, 0x46, 0x11, 0x97, 0xEF, 0x45, 0xC4, 0x65, 0x8B, 0x83, 0xB8, 0xAB, @@ -710,87 +717,99 @@ 0xAA, 0xAE, 0x29, 0x21, 0x10, 0x19, 0x10, 0x51, 0x46, 0x47, 0x31, 0xB6, 0xCC, 0x3C, 0x93, 0xDC, 0x6E, 0x80, 0xBA, 0x16, 0x0B, 0x66, 0x64, 0xA5, 0x6C, 0xFA, 0x96, 0xEA, 0xF1, 0xB2, 0x83, 0x39, 0x8E, 0xB4, 0x61, 0x64, 0xE5, 0xE9, 0x43, 0x84, 0xEE, 0x02, 0x24, 0xE7, 0x1F, 0x03, 0x7C, 0x23] -CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, +CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, - CKA_SENSITIVE : True, - CKA_DERIVE : True, - CKA_PRIME : dhX9_42Prime, - CKA_BASE : dhX9_42Base, - CKA_SUBPRIME : dhX9_42SubPrime, - CKA_LABEL : "DH X9.42 Public Key"} -CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DERIVE : True, - CKA_EXTRACTABLE : True, - CKA_LABEL : "DH X9.42 Private Key"} - -CKM_ARIA_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_ARIA, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 24, #16, 24, 32 - CKA_EXTRACTABLE :True, - CKA_LABEL : "ARIA Key"} - -CKM_DH_PKCS_PARAMETER_GEN_TEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_PRIME_BITS : 512, #between 512 and 2048 in 256bit increments (&0xff) - CKA_LABEL : "SH PKCS Parameter Key"} + CKA_SENSITIVE: True, + CKA_DERIVE: True, + CKA_PRIME: dhX9_42Prime, + CKA_BASE: dhX9_42Base, + CKA_SUBPRIME: dhX9_42SubPrime, + CKA_LABEL: "DH X9.42 Public Key"} +CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_DERIVE: True, + CKA_EXTRACTABLE: True, + CKA_LABEL: "DH X9.42 Private Key"} + +CKM_ARIA_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_ARIA, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 24, # 16, 24, 32 + CKA_EXTRACTABLE: True, + CKA_LABEL: "ARIA Key"} + +CKM_DH_PKCS_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_PRIME_BITS: 512, # between 512 and 2048 in 256bit increments (&0xff) + CKA_LABEL: "SH PKCS Parameter Key"} ''' The simple certificate object taken from CKDemo when you select the Create Object option and choose certificate ''' -CERTIFICATE_TEMPLATE = { CKA_CLASS: CKO_CERTIFICATE, - CKA_CERTIFICATE_TYPE : CKC_X_509, - CKA_TOKEN : True, - CKA_LABEL : "Created certificate object", - CKA_SUBJECT : "", - CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} +CERTIFICATE_TEMPLATE = {CKA_CLASS: CKO_CERTIFICATE, + CKA_CERTIFICATE_TYPE: CKC_X_509, + CKA_TOKEN: True, + CKA_LABEL: "Created certificate object", + CKA_SUBJECT: "", + CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01]} ''' The simple data object template taken from CKDemo when you select the Create Object option and choose data ''' -DATA_TEMPLATE = { CKA_CLASS : CKO_DATA, - CKA_TOKEN : True, - CKA_LABEL : "Created data object", - CKA_VALUE : [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} - -KEY_GENERATOR_TEMPLATES = {CKM_DES_KEY_GEN : CKM_DES_KEY_GEN_TEMP, - CKM_DES2_KEY_GEN : CKM_DES2_KEY_GEN_TEMP, - CKM_DES3_KEY_GEN: CKM_DES3_KEY_GEN_TEMP, - CKM_CAST3_KEY_GEN: CKM_CAST3_KEY_GEN_TEMP, - CKM_GENERIC_SECRET_KEY_GEN: CKM_GENERIC_SECRET_KEY_GEN_TEMP, - CKM_CAST5_KEY_GEN: CKM_CAST5_KEY_GEN_TEMP, - CKM_RC2_KEY_GEN: CKM_RC2_KEY_GEN_TEMP, - CKM_RC4_KEY_GEN: CKM_RC4_KEY_GEN_TEMP, - CKM_RC5_KEY_GEN: CKM_RC5_KEY_GEN_TEMP, - CKM_AES_KEY_GEN: CKM_AES_KEY_GEN_TEMP, - CKM_SEED_KEY_GEN: CKM_SEED_KEY_GEN_TEMP, - CKM_ARIA_KEY_GEN: CKM_ARIA_KEY_GEN_TEMP, - CKM_DH_PKCS_PARAMETER_GEN: CKM_DH_PKCS_PARAMETER_GEN_TEMP} - -KEY_PAIR_GENERATOR_TEMPLATES = { #Note lacks multiple sizes of the same kinds of keys - CKM_RSA_PKCS_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), #pkcs template is good for x9.31 - CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN : (CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_DSA_KEY_PAIR_GEN : (CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_DH_PKCS_KEY_PAIR_GEN : (CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_ECDSA_KEY_PAIR_GEN : (CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_KCDSA_KEY_PAIR_GEN : (CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_X9_31_KEY_PAIR_GEN : (CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP)} +DATA_TEMPLATE = {CKA_CLASS: CKO_DATA, + CKA_TOKEN: True, + CKA_LABEL: "Created data object", + CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01]} + +KEY_GENERATOR_TEMPLATES = {CKM_DES_KEY_GEN: CKM_DES_KEY_GEN_TEMP, + CKM_DES2_KEY_GEN: CKM_DES2_KEY_GEN_TEMP, + CKM_DES3_KEY_GEN: CKM_DES3_KEY_GEN_TEMP, + CKM_CAST3_KEY_GEN: CKM_CAST3_KEY_GEN_TEMP, + CKM_GENERIC_SECRET_KEY_GEN: CKM_GENERIC_SECRET_KEY_GEN_TEMP, + CKM_CAST5_KEY_GEN: CKM_CAST5_KEY_GEN_TEMP, + CKM_RC2_KEY_GEN: CKM_RC2_KEY_GEN_TEMP, + CKM_RC4_KEY_GEN: CKM_RC4_KEY_GEN_TEMP, + CKM_RC5_KEY_GEN: CKM_RC5_KEY_GEN_TEMP, + CKM_AES_KEY_GEN: CKM_AES_KEY_GEN_TEMP, + CKM_SEED_KEY_GEN: CKM_SEED_KEY_GEN_TEMP, + CKM_ARIA_KEY_GEN: CKM_ARIA_KEY_GEN_TEMP, + CKM_DH_PKCS_PARAMETER_GEN: CKM_DH_PKCS_PARAMETER_GEN_TEMP} + +KEY_PAIR_GENERATOR_TEMPLATES = { # Note lacks multiple sizes of the same kinds of keys + CKM_RSA_PKCS_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + # pkcs template is good for x9.31 + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_DSA_KEY_PAIR_GEN: ( + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_DH_PKCS_KEY_PAIR_GEN: ( + CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_ECDSA_KEY_PAIR_GEN: ( + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_KCDSA_KEY_PAIR_GEN: ( + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN: ( + CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP)} ''' This list is not complete @@ -840,17 +859,21 @@ CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} + def get_default_key_template(mechanism): - ''' - Gets a default template for the given key gen mechanism, returns a deep copy - ''' + """Gets a default template for the given key gen mechanism, returns a deep copy + + :param mechanism: + + """ return copy.deepcopy(KEY_GENERATOR_TEMPLATES[mechanism]) + def get_default_key_pair_template(mechanism): - ''' - Gets the default template for the given key pair gen mechanism, returns a deep copy - ''' - pub, priv = KEY_PAIR_GENERATOR_TEMPLATES[mechanism] - return copy.deepcopy(pub), copy.deepcopy(priv) + """Gets the default template for the given key pair gen mechanism, returns a deep copy + :param mechanism: + """ + pub, priv = KEY_PAIR_GENERATOR_TEMPLATES[mechanism] + return copy.deepcopy(pub), copy.deepcopy(priv) diff --git a/pycryptoki/defaults.py b/pycryptoki/defaults.py index 457872c..1221879 100755 --- a/pycryptoki/defaults.py +++ b/pycryptoki/defaults.py @@ -1,13 +1,13 @@ -''' +""" A file containing commonly used strings or other data similar to a config file -''' +""" -#The location of the cryptoki file, if specified as None the environment variable -#ChrystokiConfigurationPath will be used or it will revert to using /etc/Chrystoki.conf +# The location of the cryptoki file, if specified as None the environment variable +# ChrystokiConfigurationPath will be used or it will revert to using /etc/Chrystoki.conf CHRYSTOKI_CONFIG_FILE = None -#The location of the DLL file, if not specified it will try to look up the file in -#the Chrystoki config file specified be the variable CHRYSTOKI_CONFIG_FILE +# The location of the DLL file, if not specified it will try to look up the file in +# the Chrystoki config file specified be the variable CHRYSTOKI_CONFIG_FILE CHRYSTOKI_DLL_FILE = None ADMIN_PARTITION_LABEL = 'no label' @@ -29,14 +29,14 @@ DEFAULT_UTILS_PATH = '/usr/safenet/lunaclient/sbin' FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" -user_credentials = {ADMINISTRATOR_USERNAME : ADMINISTRATOR_PASSWORD, - AUDITOR_USERNAME : AUDITOR_PASSWORD, - CO_USERNAME : CO_PASSWORD, - DEFAULT_USERNAME : DEFAULT_PASSWORD} +user_credentials = {ADMINISTRATOR_USERNAME: ADMINISTRATOR_PASSWORD, + AUDITOR_USERNAME: AUDITOR_PASSWORD, + CO_USERNAME: CO_PASSWORD, + DEFAULT_USERNAME: DEFAULT_PASSWORD} DES3_KEY_SIZE = 120 MANUFACTURER_ID = "SafeNet Inc." MODEL = "Luna K6" -ADMIN_SLOT = 1 \ No newline at end of file +ADMIN_SLOT = 1 diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py old mode 100644 new mode 100755 index 7b40fab..c4754eb --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1,4 +1,4 @@ -''' +""" THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE This file should NOT be checked into MKS or modified in any way, this file was created by setup/initialize.py. Any changes to this file will be wiped out when @@ -9,1883 +9,1883 @@ If you add any new defines you can rerun initialize.py to regenerate this file. If you need to scrape another header file add the desired file to the header_files array in initialize.py and rerun initialize.py. -''' +""" '''/home/new_builds/1175/101/interfaces/Include/firmware/luna2if.h''' -LUNA_MAX_UPDATE_DATA_SIZE= (64 * 1024) -LUNA_GEN_KCV_FLAG_NONE= 0x0000 -LUNA_GEN_KCV_FLAG_CONSOLIDATE= 0x0001 -LUNA_MECH_RSA_PKCS_KEY_PAIR_GEN= 0x00000000 -LUNA_MECH_RSA_PKCS= 0x00000001 -LUNA_MECH_RSA_X_509= 0x00000002 -LUNA_MECH_MD5_RSA_PKCS= 0x00000005 -LUNA_MECH_SHA1_RSA_PKCS= 0x00000006 -LUNA_MECH_RSA_PKCS_OAEP= 0x00000009 -LUNA_MECH_RSA_X9_31_KEY_PAIR_GEN= 0x0000000A -LUNA_MECH_RSA_X9_31= 0x0000000B -LUNA_MECH_SHA1_RSA_X9_31= 0x0000000C -LUNA_MECH_RSA_PKCS_PSS= 0x0000000D -LUNA_MECH_SHA1_RSA_PKCS_PSS= 0x0000000E -LUNA_MECH_DSA_KEY_PAIR_GEN= 0x00000010 -LUNA_MECH_DSA= 0x00000011 -LUNA_MECH_SHA1_DSA= 0x00000012 -LUNA_MECH_DH_PKCS_KEY_PAIR_GEN= 0x00000020 -LUNA_MECH_DH_PKCS_DERIVE= 0x00000021 -LUNA_MECH_X9_42_DH_KEY_PAIR_GEN= 0x00000030 -LUNA_MECH_X9_42_DH_DERIVE= 0x00000031 -LUNA_MECH_X9_42_DH_HYBRID_DERIVE= 0x00000032 -LUNA_MECH_SHA256_RSA_PKCS= 0x00000040 -LUNA_MECH_SHA384_RSA_PKCS= 0x00000041 -LUNA_MECH_SHA512_RSA_PKCS= 0x00000042 -LUNA_MECH_SHA256_RSA_PKCS_PSS= 0x00000043 -LUNA_MECH_SHA384_RSA_PKCS_PSS= 0x00000044 -LUNA_MECH_SHA512_RSA_PKCS_PSS= 0x00000045 -LUNA_MECH_RC2_KEY_GEN= 0x00000100 -LUNA_MECH_RC2_ECB= 0x00000101 -LUNA_MECH_RC2_CBC= 0x00000102 -LUNA_MECH_RC2_MAC= 0x00000103 -LUNA_MECH_RC2_CBC_PAD= 0x00000105 -LUNA_MECH_RC4_KEY_GEN= 0x00000110 -LUNA_MECH_RC4= 0x00000111 -LUNA_MECH_DES_KEY_GEN= 0x00000120 -LUNA_MECH_DES_ECB= 0x00000121 -LUNA_MECH_DES_CBC= 0x00000122 -LUNA_MECH_DES_MAC= 0x00000123 -LUNA_MECH_DES_CBC_PAD= 0x00000125 -LUNA_MECH_DES2_KEY_GEN= 0x00000130 -LUNA_MECH_DES3_KEY_GEN= 0x00000131 -LUNA_MECH_DES3_ECB= 0x00000132 -LUNA_MECH_DES3_CBC= 0x00000133 -LUNA_MECH_DES3_MAC= 0x00000134 -LUNA_MECH_DES3_CBC_PAD= 0x00000135 -LUNA_MECH_MD2= 0x00000200 -LUNA_MECH_MD5= 0x00000210 -LUNA_MECH_SHA_1= 0x00000220 -LUNA_MECH_SHA256= 0x00000250 -LUNA_MECH_HMAC_SHA256= 0x00000251 -LUNA_MECH_SHA384= 0x00000260 -LUNA_MECH_HMAC_SHA384= 0x00000261 -LUNA_MECH_SHA512= 0x00000270 -LUNA_MECH_HMAC_SHA512= 0x00000271 -LUNA_MECH_SHA256_KEY_DERIVATION= 0x00000393 -LUNA_MECH_SHA384_KEY_DERIVATION= 0x00000394 -LUNA_MECH_SHA512_KEY_DERIVATION= 0x00000395 -LUNA_MECH_PKCS5_PBKD2= 0x000003B0 -LUNA_MECH_KEY_WRAP_SET_OAEP= 0x00000401 -LUNA_MECH_EC_KEY_PAIR_GEN= 0x00001040 -LUNA_MECH_ECDSA= 0x00001041 -LUNA_MECH_SHA1_ECDSA= 0x00001042 -LUNA_MECH_SHA224_ECDSA= 0x00001043 -LUNA_MECH_SHA256_ECDSA= 0x00001044 -LUNA_MECH_SHA384_ECDSA= 0x00001045 -LUNA_MECH_SHA512_ECDSA= 0x00001046 -LUNA_MECH_ECDH1_DERIVE= 0x00001050 -LUNA_MECH_ECDH1_COFACTOR_DERIVE= 0x00001051 -LUNA_MECH_ECMQV_DERIVE= 0x00001052 -LUNA_MECH_AES_KEY_GEN= 0x00001080 -LUNA_MECH_AES_ECB= 0x00001081 -LUNA_MECH_AES_CBC= 0x00001082 -LUNA_MECH_AES_MAC= 0x00001083 -LUNA_MECH_AES_MAC_GENERAL= 0x00001084 -LUNA_MECH_AES_CBC_PAD= 0x00001085 -LUNA_MECH_DES_ECB_ENCRYPT_DATA= 0x00001100 -LUNA_MECH_DES_CBC_ENCRYPT_DATA= 0x00001101 -LUNA_MECH_DES3_ECB_ENCRYPT_DATA= 0x00001102 -LUNA_MECH_DES3_CBC_ENCRYPT_DATA= 0x00001103 -LUNA_MECH_AES_ECB_ENCRYPT_DATA= 0x00001104 -LUNA_MECH_AES_CBC_ENCRYPT_DATA= 0x00001105 -LUNA_MECH_ARIA_KEY_GEN= 0x00001200 -LUNA_MECH_ARIA_ECB= 0x00001201 -LUNA_MECH_ARIA_CBC= 0x00001202 -LUNA_MECH_ARIA_MAC= 0x00001203 -LUNA_MECH_ARIA_MAC_GENERAL= 0x00001204 -LUNA_MECH_ARIA_CBC_PAD= 0x00001205 -LUNA_MECH_ARIA_ECB_ENCRYPT_DATA= 0x00001206 -LUNA_MECH_ARIA_CBC_ENCRYPT_DATA= 0x00001207 -LUNA_MECH_DSA_PARAMETER_GEN= 0x00002000 -LUNA_MECH_DH_PKCS_PARAMETER_GEN= 0x00002001 -LUNA_MECH_X9_42_DH_PARAMETER_GEN= 0x00002002 -LUNA_MECH_CAST_KEY_GEN= 0x00008001 -LUNA_MECH_CAST_ECB= 0x00008002 -LUNA_MECH_CAST_CBC= 0x00008003 -LUNA_MECH_CAST_MAC= 0x00008004 -LUNA_MECH_CAST_CBC_PAD= 0x00008005 -LUNA_MECH_CAST3_KEY_GEN= 0x00008101 -LUNA_MECH_CAST3_ECB= 0x00008102 -LUNA_MECH_CAST3_CBC= 0x00008103 -LUNA_MECH_CAST3_MAC= 0x00008104 -LUNA_MECH_CAST3_CBC_PAD= 0x00008105 -LUNA_MECH_CAST5_KEY_GEN= 0x00008501 -LUNA_MECH_CAST5_ECB= 0x00008502 -LUNA_MECH_CAST5_CBC= 0x00008503 -LUNA_MECH_CAST5_MAC= 0x00008504 -LUNA_MECH_CAST5_CBC_PAD= 0x00008505 -LUNA_MECH_RC5_KEY_GEN= 0x00008600 -LUNA_MECH_RC5_ECB= 0x00008601 -LUNA_MECH_RC5_CBC= 0x00008602 -LUNA_MECH_RC5_MAC= 0x00008603 -LUNA_MECH_RC5_CBC_PAD= 0x00008605 -LUNA_MECH_MD2_DES_CBC= 0x00008201 -LUNA_MECH_MD5_DES_CBC= 0x00008202 -LUNA_MECH_SHA1_DES3_CBC= 0x00008203 -LUNA_MECH_MD5_CAST_CBC= 0x00008204 -LUNA_MECH_MD5_CAST3_CBC= 0x00008205 -LUNA_MECH_SHA1_CAST5_CBC= 0x00008206 -LUNA_MECH_SHA1_DES2_CBC= 0x00008207 -LUNA_MECH_SHA1_RC4_128= 0x00008208 -LUNA_MECH_SHA1_RC4_40= 0x00008209 -LUNA_MECH_SHA1_RC2_128_CBC= 0x0000820A -LUNA_MECH_SHA1_RC2_40_CBC= 0x0000820B -LUNA_MECH_SHA1_DES2_CBC_OLD= 0x0000820C # Added for compatibility with legacy apps -LUNA_MECH_SHA1_DES3_CBC_OLD= 0x0000820D # Added for compatibility with legacy apps -LUNA_MECH_CONCATENATE_BASE_AND_KEY= 0x00008301 # Added for SPKM & SSL Support -LUNA_MECH_CONCATENATE_KEY_AND_BASE= 0x00008302 # Added for SPKM & SSL Support -LUNA_MECH_CONCATENATE_BASE_AND_DATA= 0x00008303 # Added for SPKM & SSL Support -LUNA_MECH_CONCATENATE_DATA_AND_BASE= 0x00008304 # Added for SPKM & SSL Support -LUNA_MECH_XOR_BASE_AND_DATA= 0x00008305 # Added for SPKM & SSL Support -LUNA_MECH_XOR_BASE_AND_KEY= 0x0000860B # Added for F/W Update Support -LUNA_MECH_EXTRACT_KEY_FROM_KEY= 0x00008306 # Added for SPKM & SSL Support -LUNA_MECH_MD2_KEY_DERIVATION= 0x00008307 # Added for SPKM & SSL Support -LUNA_MECH_MD5_KEY_DERIVATION= 0x00008308 # Added for SPKM & SSL Support -LUNA_MECH_SHA1_KEY_DERIVATION= 0x00008309 # Added for SPKM & SSL Support -LUNA_MECH_GENERIC_SECRET_KEY_GEN= 0x0000830A # Added for SPKM & SSL Support -LUNA_MECH_SSL3_MASTER_KEY_DERIVE= 0x0000830B # Added for SSL Support -LUNA_MECH_SSL3_KEY_AND_MAC_DERIVE= 0x0000830C # Added for SSL Support -LUNA_MECH_SSL3_MD5_MAC= 0x0000830D # Added for SSL Support -LUNA_MECH_SSL3_SHA1_MAC= 0x0000830E # Added for SSL Support -LUNA_MECH_HMAC_SHA1= 0x0000830F # Added for SSL Support -LUNA_MECH_HMAC_SHA1_80= 0x00008310 # Added for SSL Support -LUNA_MECH_HMAC_MD5= 0x00008311 # Added for SSL Support -LUNA_MECH_HMAC_MD5_80= 0x00008312 # Added for SSL Support -LUNA_MECH_SSL3_PRE_MASTER_KEY_GEN= 0x00008313 # Added for SSL Support -LUNA_MECH_DES3_CFB8= 0x00008314 -LUNA_MECH_DES3_CFB64= 0x00008315 -LUNA_MECH_DES3_OFB= 0x00008316 -LUNA_MECH_DES3_CTR= 0x00008317 -LUNA_MECH_DES3_GCM= 0x00008318 -LUNA_MECH_AES_CFB8= 0x00008319 -LUNA_MECH_AES_CFB128= 0x0000831a -LUNA_MECH_AES_OFB= 0x0000831b -LUNA_MECH_AES_CTR= 0x0000831c -LUNA_MECH_AES_GCM= 0x0000831d -LUNA_MECH_ARIA_CFB8= 0x0000831e -LUNA_MECH_ARIA_CFB128= 0x0000831f -LUNA_MECH_ARIA_OFB= 0x00008320 -LUNA_MECH_ARIA_CTR= 0x00008321 -LUNA_MECH_ARIA_GCM= 0x00008322 -LUNA_MECH_2DES_DERIVE= 0x000083FF # Added for Gemplus -LUNA_MECH_INDIRECT_LOGIN_REENCRYPT= 0x00008400 # Added for indirect login support. Obsolete as of f/w 5.0 -LUNA_MECH_LZS= 0x00008400 # Added for Compression Support -LUNA_MECH_LOOP_BACK= 0x80000000 -LUNA_MECH_NONE= LUNA_MECH_LOOP_BACK # Added for IPSEC Support -LUNA_MECH_UNKNOWN= 0xFFFFFFFF # Added for error detection -LUNA_MECH_SEED_KEY_GEN= 0x00008701 -LUNA_MECH_SEED_ECB= 0x00008702 -LUNA_MECH_SEED_CBC= 0x00008703 -LUNA_MECH_SEED_CBC_PAD= 0x00008704 -LUNA_MECH_SEED_MAC= 0x00008705 -LUNA_MECH_HAS160= 0x00008706 -LUNA_MECH_KCDSA_KEY_PAIR_GEN= 0x00008707 -LUNA_MECH_HAS160_KCDSA= 0x00008708 -LUNA_MECH_SHA1_KCDSA= 0x00008709 -LUNA_MECH_SHA224_KCDSA= 0x0000870A -LUNA_MECH_SHA256_KCDSA= 0x0000870B -LUNA_MECH_SHA384_KCDSA= 0x0000870C -LUNA_MECH_SHA512_KCDSA= 0x0000870D -LUNA_MECH_HMAC_HAS160= 0x0000870E -LUNA_MECH_KCDSA_PARAMETER_GEN= 0x0000870F -LUNA_MECH_HAS160_KCDSA_NO_PAD= 0x00008710 -LUNA_MECH_SHA1_KCDSA_NO_PAD= 0x00008711 -LUNA_MECH_SHA224_KCDSA_NO_PAD= 0x00008712 -LUNA_MECH_SHA256_KCDSA_NO_PAD= 0x00008713 -LUNA_MECH_SHA384_KCDSA_NO_PAD= 0x00008714 -LUNA_MECH_SHA512_KCDSA_NO_PAD= 0x00008715 -LUNA_MECH_AES_CBC_PAD_EXTRACT= 0x00009000 -LUNA_MECH_AES_CBC_PAD_INSERT= 0x00009001 -LUNA_MECH_AES_CBC_PAD_EXTRACT_FLATTENED= 0x00009002 -LUNA_MECH_AES_CBC_PAD_INSERT_FLATTENED= 0x00009003 -LUNA_MECH_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL= 0x00009004 -LUNA_MECH_AES_CBC_PAD_INSERT_DOMAIN_CTRL= 0x00009005 -LUNA_MASKING_STORAGE_HOST= 0x00000000 -LUNA_MASKING_STORAGE_PED_USB_MEMORY= 0x00000001 -LUNA_MASKING_STORAGE_HSM_USB_MEMORY= 0x00000002 -LUNA_MASKING_FLAG_DELETE_AFTER_EXTRACT=0x1 # Flag "Delete After Extract" */ -LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC= 0x80009000 -LUNA_MECH_AES_CBC_PAD_INSERT_PUBLIC= 0x80009001 -LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC_FLATTENED= 0x80009002 -LUNA_MECH_AES_CBC_PAD_INSERT_PUBLIC_FLATTENED= 0x80009003 -LUNA_MECH_SHA224_RSA_PKCS= 0x80000110 -LUNA_MECH_SHA224_RSA_PKCS_PSS= 0x80000111 -LUNA_MECH_SHA224= 0x80000112 -LUNA_MECH_HMAC_SHA224= 0x80000113 -LUNA_MECH_SHA224_KEY_DERIVATION= 0x80000115 -LUNA_MECH_HMAC_RIPEMD160= 0x80000116 -LUNA_MECH_RIPEMD160= 0x80000117 -LUNA_MECH_SHA224_DSA= 0x80000122 -LUNA_MECH_SHA256_DSA= 0x80000123 -LUNA_MECH_DES3_CMAC= 0x80000126 -LUNA_MECH_ARIA_CMAC= 0x80000127 -LUNA_MECH_AES_CMAC= 0x80000128 -LUNA_MECH_SEED_CMAC= 0x80000129 -LUNA_MECH_DES3_CBC_PAD_IPSEC= 0x80000130 -LUNA_MECH_AES_CBC_PAD_IPSEC= 0x80000131 -LUNA_MECH_XOR_BASE_AND_DATA_W_KDF= 0x80000132 -LUNA_MECH_ARIA_L_ECB= 0x80000133 -LUNA_MECH_ARIA_L_CBC= 0x80000134 -LUNA_MECH_ARIA_L_CBC_PAD= 0x80000135 -LUNA_MECH_ARIA_L_MAC= 0x80000136 -LUNA_MECH_SHA224_RSA_X9_31= 0x80000137 -LUNA_MECH_SHA256_RSA_X9_31= 0x80000138 -LUNA_MECH_SHA384_RSA_X9_31= 0x80000139 -LUNA_MECH_SHA512_RSA_X9_31= 0x8000013a -LUNA_MECH_SHA1_RSA_X9_31_NON_FIPS= 0x8000013b -LUNA_MECH_SHA224_RSA_X9_31_NON_FIPS= 0x8000013c -LUNA_MECH_SHA256_RSA_X9_31_NON_FIPS= 0x8000013d -LUNA_MECH_SHA384_RSA_X9_31_NON_FIPS= 0x8000013e -LUNA_MECH_SHA512_RSA_X9_31_NON_FIPS= 0x8000013f -LUNA_MECH_RSA_X9_31_NON_FIPS= 0x80000140 -LUNA_MECH_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN= 0x80000141 -LUNA_MECH_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN= 0x80000142 -LUNA_MECH_AES_GMAC= 0x80000143 -LUNA_MECH_SEED_CTR= 0x80008144 -LUNA_MECH_DES3_X919_MAC= 0x80000150 -LUNA_MECH_EC_KEY_PAIR_GEN_W_EXTRA_BITS= 0x80000160 -LUNA_MECH_SHA256_ECDSA_GBCS= 0x80000161 -LUNA_MECH_DES2_DUKPT_PIN= 0x80000611 -LUNA_MECH_DES2_DUKPT_MAC= 0x80000612 -LUNA_MECH_DES2_DUKPT_MAC_RESP= 0x80000613 -LUNA_MECH_DES2_DUKPT_DATA= 0x80000614 -LUNA_MECH_DES2_DUKPT_DATA_RESP= 0x80000615 -LUNA_MECH_ECIES= 0x80000A00 -LUNA_MECH_NIST_PRF_KDF= 0x80000A02 -LUNA_MECH_PRF_KDF= 0x80000A03 -LUNA_MECH_FLAG_HW= 0x00000001 -LUNA_MECH_FLAG_ENCRYPT= 0x00000100 -LUNA_MECH_FLAG_DECRYPT= 0x00000200 -LUNA_MECH_FLAG_DIGEST= 0x00000400 -LUNA_MECH_FLAG_SIGN= 0x00000800 -LUNA_MECH_FLAG_SIGN_RECOVER= 0x00001000 -LUNA_MECH_FLAG_VERIFY= 0x00002000 -LUNA_MECH_FLAG_VERIFY_RECOVER= 0x00004000 -LUNA_MECH_FLAG_GENERATE= 0x00008000 -LUNA_MECH_FLAG_GENERATE_KEY_PAIR= 0x00010000 -LUNA_MECH_FLAG_WRAP= 0x00020000 -LUNA_MECH_FLAG_UNWRAP= 0x00040000 -LUNA_MECH_FLAG_DERIVE= 0x00080000 -LUNA_MECH_FLAG_EC_F_P= 0x00100000 -LUNA_MECH_FLAG_EC_F_2M= 0x00200000 -LUNA_MECH_FLAG_EC_ECPARAMETERS= 0x00400000 -LUNA_MECH_FLAG_EC_NAMEDCURVE= 0x00800000 -LUNA_MECH_FLAG_EC_UNCOMPRESS= 0x01000000 -LUNA_MECH_FLAG_EC_COMPRESS= 0x02000000 -LUNA_MECH_FLAG_EXTENSION= 0x80000000 -LUNA_MGF_MGF1_SHA1= 0x00000001 -LUNA_MGF_MGF1_SHA256= 0x00000002 -LUNA_MGF_MGF1_SHA384= 0x00000003 -LUNA_MGF_MGF1_SHA512= 0x00000004 -LUNA_MGF_MGF1_SHA224= 0x00000005 -LUNA_OAEP_SOURCES_DATA_SPECIFIED= 0x00000001 -LUNA_ATTR_UNKNOWN= 0xFFFFFFFF # Added for error detection */ -LUNA_ATTR_CLASS= 0x00000000 -LUNA_ATTR_TOKEN= 0x00000001 -LUNA_ATTR_PRIVATE= 0x00000002 -LUNA_ATTR_LABEL= 0x00000003 -LUNA_ATTR_APPLICATION= 0x00000010 -LUNA_ATTR_VALUE= 0x00000011 -LUNA_ATTR_CERTIFICATE_TYPE= 0x00000080 -LUNA_ATTR_ISSUER= 0x00000081 -LUNA_ATTR_SERIAL_NUMBER= 0x00000082 -LUNA_ATTR_KEY_TYPE= 0x00000100 -LUNA_ATTR_SUBJECT= 0x00000101 -LUNA_ATTR_ID= 0x00000102 -LUNA_ATTR_SENSITIVE= 0x00000103 -LUNA_ATTR_ENCRYPT= 0x00000104 -LUNA_ATTR_DECRYPT= 0x00000105 -LUNA_ATTR_WRAP= 0x00000106 -LUNA_ATTR_UNWRAP= 0x00000107 -LUNA_ATTR_SIGN= 0x00000108 -LUNA_ATTR_SIGN_RECOVER= 0x00000109 -LUNA_ATTR_VERIFY= 0x0000010A -LUNA_ATTR_VERIFY_RECOVER= 0x0000010B -LUNA_ATTR_DERIVE= 0x0000010C -LUNA_ATTR_START_DATE= 0x00000110 -LUNA_ATTR_END_DATE= 0x00000111 -LUNA_ATTR_MODULUS= 0x00000120 -LUNA_ATTR_MODULUS_BITS= 0x00000121 -LUNA_ATTR_PUBLIC_EXPONENT= 0x00000122 -LUNA_ATTR_PRIVATE_EXPONENT= 0x00000123 -LUNA_ATTR_PRIME_1= 0x00000124 -LUNA_ATTR_PRIME_2= 0x00000125 -LUNA_ATTR_EXPONENT_1= 0x00000126 -LUNA_ATTR_EXPONENT_2= 0x00000127 -LUNA_ATTR_COEFFICIENT= 0x00000128 -LUNA_ATTR_PRIME= 0x00000130 -LUNA_ATTR_SUBPRIME= 0x00000131 -LUNA_ATTR_BASE= 0x00000132 -LUNA_ATTR_PRIME_BITS= 0x00000133 -LUNA_ATTR_SUBPRIME_BITS= 0x00000134 -LUNA_ATTR_VALUE_BITS= 0x00000160 -LUNA_ATTR_VALUE_LEN= 0x00000161 -LUNA_ATTR_EXTRACTABLE= 0x00000162 -LUNA_ATTR_LOCAL= 0x00000163 -LUNA_ATTR_NEVER_EXTRACTABLE= 0x00000164 -LUNA_ATTR_ALWAYS_SENSITIVE= 0x00000165 -LUNA_ATTR_MODIFIABLE= 0x00000170 -LUNA_ATTR_ECDSA_PARAMS= 0x00000180 -LUNA_ATTR_EC_POINT= 0x00000181 -LUNA_ATTR_VENDOR_DEFINED= 0x80000000 -LUNA_ATTR_CCM_PRIVATE= (LUNA_ATTR_VENDOR_DEFINED | 0x00000001) -LUNA_ATTR_FINGERPRINT_SHA1= (LUNA_ATTR_VENDOR_DEFINED | 0x00000002) -LUNA_ATTR_PKC_TCTRUST= (LUNA_ATTR_VENDOR_DEFINED | 0x00000003) -LUNA_ATTR_PKC_CITS= (LUNA_ATTR_VENDOR_DEFINED | 0x00000004) -LUNA_ATTR_OUID= (LUNA_ATTR_VENDOR_DEFINED | 0x00000005) -LUNA_ATTR_X9_31_GENERATED= (LUNA_ATTR_VENDOR_DEFINED | 0x00000006) -LUNA_ATTR_PKC_ECC= (LUNA_ATTR_VENDOR_DEFINED | 0x00000007) -LUNA_ATTR_EKM_UID= (LUNA_ATTR_VENDOR_DEFINED | 0x00000008) -LUNA_ATTR_USAGE_COUNT= (LUNA_ATTR_VENDOR_DEFINED | 0x00000101) -LUNA_ATTR_USAGE_COUNT_LIMIT= (LUNA_ATTR_VENDOR_DEFINED | 0x00000200) -LUNA_ATTR_GENERIC_1= (LUNA_ATTR_VENDOR_DEFINED | 0x00001000) -LUNA_ATTR_GENERIC_2= (LUNA_ATTR_VENDOR_DEFINED | 0x00001001) -LUNA_ATTR_GENERIC_3= (LUNA_ATTR_VENDOR_DEFINED | 0x00001002) -LUNA_ATTR_FINGERPRINT_SHA256= (LUNA_ATTR_VENDOR_DEFINED | 0x00001003) -LUNA_ATTR_UNKNOWN= 0xFFFFFFFF -LUNA_OBJ_DATA= 0x00000000 -LUNA_OBJ_CERTIFICATE= 0x00000001 -LUNA_OBJ_SECRET_KEY= 0x00000002 -LUNA_OBJ_PUBLIC_KEY= 0x00000003 -LUNA_OBJ_PRIVATE_KEY= 0x00000004 -LUNA_OBJ_DOMAIN_PARAMETERS= 0x00000005 -LUNA_OBJ_VENDOR_DEFINED= 0x80000000 -LUNA_OBJ_UNKNOWN= 0xFFFFFFFF # Added for error detection */ -LUNA_KEY_RSA= 0x00000000 -LUNA_KEY_DSA= 0x00000001 -LUNA_KEY_DH= 0x00000002 -LUNA_KEY_GENERIC_SECRET= 0x00000003 -LUNA_KEY_RC2= 0x00000004 -LUNA_KEY_RC4= 0x00000005 -LUNA_KEY_DES= 0x00000006 -LUNA_KEY_DES2= 0x00000007 -LUNA_KEY_DES3= 0x00000008 -LUNA_KEY_CAST= 0x00000009 -LUNA_KEY_CAST3= 0x0000000A -LUNA_CERT_X_509= 0x0000000B -LUNA_KEY_CAST5= 0x0000000C -LUNA_KEY_RC5= 0x0000000D -LUNA_KEY_ECDSA= 0x0000000E -LUNA_KEY_KEA= 0x0000000F -LUNA_KEY_IDEA= 0x00000010 -LUNA_KEY_SKIPJACK= 0x00000011 -LUNA_KEY_BATON= 0x00000012 -LUNA_KEY_JUNIPER= 0x00000013 -LUNA_KEY_CDMF= 0x00000014 -LUNA_KEY_AES= 0x0000001F -LUNA_KEY_ARIA= 0x00000020 -LUNA_KEY_X9_42_DH= 0x00000021 -LUNA_KEY_VENDOR_DEFINED= 0x80000000 -LUNA_KEY_KCDSA= (LUNA_KEY_VENDOR_DEFINED + 0x10) -LUNA_KEY_SEED= (LUNA_KEY_VENDOR_DEFINED + 0x11) -LUNA_KEY_UNKNOWN= 0xFFFFFFFF # Added for error detection */ -LUNA_CERT_UNKNOWN= 0xFFFFFFFF # Added for error detection */ -LUNA_CVK_CERTIFICATE= 0x00000000 -LUNA_TWC_CERTIFICATE= 0x00000001 -LUNA_TUK_PRIVATE_KEY= 0x00000000 -LUNA_HOK_PRIVATE_KEY= 0x00000001 -LUNA_DAK_PRIVATE_KEY= 0x00000002 -LUNA_ECC_HOK_PRIVATE_KEY= 0x00000003 -LUNA_ECC_DAK_PRIVATE_KEY= 0x00000004 -LUNA_TUK3_PRIVATE_KEY= 0x00000005 -LUNA_VVK_PUBLIC_KEY= 0x00000001 -LUNA_GT_LABEL= 0x00000000 -LUNA_GT_MFG= 0x00000001 -LUNA_GT_MODEL= 0x00000002 -LUNA_GT_TSN= 0x00000003 -LUNA_GT_S_N= 0x00000003 #to remain backward compatible. LUNA_GT_TSN should be used. -LUNA_GT_FLAGS= 0x00000004 -LUNA_GT_SESSIONS= 0x00000005 -LUNA_GT_SRAM= 0x00000007 -LUNA_GT_FLASH= 0x00000008 -LUNA_GT_TPC= 0x00000009 -LUNA_GT_CAV= 0x0000000C -LUNA_GT_FWV= 0x0000000D -LUNA_GT_TSV= 0x0000000E -LUNA_GT_TWC= 0x0000000F -LUNA_GT_M_OF_N_INFO= 0x00000010 -LUNA_GT_M_OF_N_STATUS= 0x00000011 -LUNA_GT_TWK= 0x00000012 -LUNA_GT_USER_ILD= 0x00000014 -LUNA_GT_SO_ILD= 0x00000015 -LUNA_GT_ROOT_CERT= 0x00000017 -LUNA_GT_HW_ORIGIN_CERT= 0x00000018 # retrieves HOC+MIC -LUNA_GT_TCTRUST_DAC= 0x00000019 -LUNA_GT_TCTRUST_MAC= 0x0000001A -LUNA_GT_CITS_DAC= 0x0000001B -LUNA_GT_PPID= 0x0000001C -LUNA_GT_HARDWARE_PLATFORM= 0x0000001D -LUNA_GT_DEFAULT_MIN_MAX_PIN_LEN= 0x0000001E -LUNA_GT_TWC2= 0x0000001F -LUNA_GT_RPV_STATUS= 0x00000020 -LUNA_GT_ECC_MIC= 0x00000021 -LUNA_GT_ECC_HOC= 0x00000022 -LUNA_GT_ECC_DAC= 0x00000023 -LUNA_GT_ROLLBACK_FWV= 0x00000024 -LUNA_GT_MIC= 0x00000025 -LUNA_GT_HOC= 0x00000026 # retrieves HOC only -LUNA_GT_CITS_MAC= 0x00000027 -LUNA_GT_SP_RAWREAD= 0x00000030 -LUNA_GT_SP_RAWWRITE= 0x00000031 -LUNA_GT_PED_CALLBACK_PROTOCOL= 0x00000032 -LUNA_GT_TWK3= 0x00000033 -LUNA_GT_TWC3= 0x00000034 -LUNA_GT_HSM_STORAGE_INFO= 0x00000035 -LUNA_GT_NUMBER_OF_CONTAINERS_ALLOWED= 0x00000036 -LUNA_GT_MAX_SINGLE_PART_SIZE= 0x00000037 -LUNA_GT_PARTITION_ROLE_POLICIES= 0x00000038 -LUNA_GT_PARTITION_ROLE_DESCRIPTORS= 0x00000039 -LUNA_GT_ADMIN_PARTITION_HANDLE= 0x0000003A -LUNA_GT_TIME_OF_DAY= 0x0000003B -LUNA_GT_MONO_COUNTER= 0x0000003C -LUNA_GT_TEMP_K2= 0x0000003D -LUNA_GT_PIN= 0x00000006 -LUNA_GT_TPV= 0x0000000A -LUNA_GT_FPV= 0x0000000B -LUNA_GT_EXTENDED_TPV= 0x00000013 -LUNA_GT_EXTENDED_FPV= 0x00000016 -LUNA_TF_RNG= 0x00000001 -LUNA_TF_WRITE_PROTECTED= 0x00000002 -LUNA_TF_LOGIN_REQUIRED= 0x00000004 -LUNA_TF_USER_PIN_INITIALIZED= 0x00000008 -LUNA_TF_EXCLUSIVE_EXISTS= 0x00000010 -LUNA_TF_TOKEN_INITIALIZED= 0x00000400 -LUNA_CF_CONTAINER_ENABLED= 0x01000000 -LUNA_CF_KCV_CREATED= 0x02000000 -LUNA_CF_LKCV_CREATED= 0x04000000 -LUNA_CF_HA_INITIALIZED= 0x08000000 -LUNA_CF_PARTITION_INITIALIZED= 0x00000400 -LUNA_CF_CONTAINER_ACTIVATED= 0x00000001 -LUNA_CF_CONTAINER_LUSR_ACTIVATED= 0x00000002 -LUNA_CF_USER_PIN_INITIALIZED= 0x00008000 -LUNA_CF_SO_PIN_LOCKED= 0x00010000 -LUNA_CF_SO_PIN_TO_BE_CHANGED= 0x00020000 -LUNA_CF_USER_PIN_LOCKED= 0x00040000 -LUNA_CF_LIMITED_USER_PIN_LOCKED= 0x00080000 -LUNA_CF_LIMITED_USER_CREATED= 0x00200000 -LUNA_CF_USER_PIN_TO_BE_CHANGED= 0x00400000 -LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED= 0x00800000 -LUNA_FLAG_M_OF_N_REQUIRED= 0x00000001 -LUNA_FLAG_M_OF_N_ACTIVATED= 0x00000002 -LUNA_FLAG_M_OF_N_GENERATED= 0x00000004 -LUNA_FLAG_M_OF_N_CLONEABLE= 0x00000008 -LUNA_ISAKMP_DECRYPT= 0x00000500 -LUNA_ISAKMP_ENCRYPT_FIXED_IV= 0x00000501 -LUNA_ISAKMP_ENCRYPT_GEN_IV= 0x00000502 -LUNA_ENTRY_DATA_AREA= 0x00000000 # obsolete in NextGen/PerPartitionSO firmware -LUNA_ENTRY_SECURE_PORT= 0x00000001 -LUNA_ENTRY_INDIRECT= 0x00000002 # Obsolete as of f/w 5.0 -LUNA_ENTRY_RANDOM= 0x00000003 # only used for pin creation -LUNA_ENTRY_CHALLENGE_RESPONSE= 0x00000004 # only used for login -LUNA_ENTRY_REMOTE_AUTHENTICATION= 0x00000005 -LUNA_ENTRY_DATA_AREA_MASKED= 0x00000006 -LUNA_ENTRY_NONE= 0x000000FF # to indicate that nothing yet set. -LUNA_PED_ID_SCP= 0x0000 -LUNA_PED_ID_MAX= 0xFFFE -LUNA_MAX_PIN_LEN= 256 -LUNA_UTYPE_NONE= 0xFFFFFFFF -LUNA_UTYPE_USER= 0x00000000 -LUNA_UTYPE_SO= 0x00000001 -LUNA_UTYPE_LIMITED_USER= 0x00000005 -LUNA_UTYPE_DOMAIN= 0x00000006 -LUNA_UTYPE_MTK= 0x00000007 -LUNA_UTYPE_AUDIT= 0x00000008 -LUNA_UTYPE_CFG_BASE= 0x80000000 -LUNA_REMOTE_AUTH_LOGIN= 0x00000000 -LUNA_REMOTE_AUTH_M_OF_N= 0x00000001 -LUNA_STYPE_R_W= 0x00000000 -LUNA_STYPE_R_W_EXCLUSIVE= 0x00000001 -LUNA_STYPE_R_O= 0x00000002 -LUNA_STYPE_R_O_EXCLUSIVE= 0x00000003 -LUNA_SACCESS_PUBLIC= 0x00000001 -LUNA_SACCESS_USER= 0x00000002 -LUNA_SACCESS_SO= 0x00000003 -LUNA_PAD_RFC_1423= 0x00000000 -LUNA_TTYPE_H_W= 0x00000000 -LUNA_TTYPE_CRYPTO= 0x00000001 -LUNA_TTYPE_RNG= 0x00000002 -LUNA_DSS_PRIMALITY_TEST= 0x00000003 -LUNA_DSS_PQG_TEST= 0x00000004 -LUNA_DSS_KEY_TEST= 0x00000005 -LUNA_DSS_SIG_TEST= 0x00000006 -LUNA_DSS_SIGVERIFY_TEST= 0x00000007 -LUNA_DSS_PQGVERIFY_TEST= 0x00000008 -LUNA_HIFN6500_TEST= 0x00000009 -LUNA_TTYPE_RNG_GEN= 0x0000000a -LUNA_TTYPE_AES_OFB= 0x0000000b -LUNA_ECDSA_KEY_TEST= 0x0000000c -LUNA_ECDSA_SIG_TEST= 0x0000000d -LUNA_ECDSA_SIGVERIFY_TEST= 0x0000000e -LUNA_TTYPE_RSA_X_931_KEY_GEN_TEST= 0x0000000f -LUNA_TTYPE_ARIA_OFB= 0x00000010 -LUNA_TTYPE_COMMUNICATION_PERFORMANCE_TEST= 0x00000011 -LUNA_DSS2_G_GEN_TEST= 0x00000012 -LUNA_TTYPE_RSA_1863_AUX_PRIME_KEY_GEN_TEST= 0x00000013 -LUNA_TTYPE_RSA_1863_ONLY_PRIME_KEY_GEN_TEST= 0x00000014 -LUNA_TTYPE_X9_42_DOMAIN_PARAMETER_GENERATION_TEST= 0x00000015 -LUNA_CTYPE_KCV= 0x00000000 -LUNA_CTYPE_MOFN=0x00000001 -HA_CMD_GET_LOGIN_CHALLENGE= 0x01 -HA_CMD_ANSWER_LOGIN_CHALLENGE= 0x02 -HA_CMD_LOGIN= 0x03 -HA_CMD_GET_MOFN_CHALLENGE= 0x11 -HA_CMD_ANSWER_MOFN_CHALLENGE= 0x12 -HA_CMD_MOFN_ACTIVATE= 0x13 -LUNA_MASKING_KEY_PID= 24 -LUNA_MAC_PID= 43 # Manufacturer Authentication Certificate -LUNA_DAC_FIPS2_MEETS_PID= 44 # Device Authentication Certificate, FIPS2, "meets requirements" -LUNA_DAC_FIPS2_EVAL_PID= 45 # Device Authentication Certificate, FIPS2, "evaluated to" -LUNA_DAC_FIPS3_MEETS_PID= 46 # Device Authentication Certificate, FIPS3, "meets requirements" -LUNA_DAC_FIPS3_EVAL_PID= 47 # Device Authentication Certificate, FIPS3, "evaluated to" -LUNA_CUST_MAC_PID= 48 # Customer Manufacturer Authentication Certificate -LUNA_CUST_DAC_FIPS2_MEETS_PID=49 # Customer Device Authentication Certificate, FIPS2, "meets requirements" -LUNA_CUST_DAC_FIPS2_EVAL_PID= 50 # Customer Device Authentication Certificate, FIPS2, "evaluated to" -LUNA_CUST_DAC_FIPS3_MEETS_PID=51 # Customer Device Authentication Certificate, FIPS3, "meets requirements" -LUNA_CUST_DAC_FIPS3_EVAL_PID= 52 # Customer Device Authentication Certificate, FIPS3, "evaluated to" -LUNA_SSK_PID= 54 # Secure Signing Key -LUNA_ECC_MIC_PID= 60 # ECC Manufacturer Authentication Certificate -LUNA_ECC_HOK_PID= 61 # ECC Hardware Origin Key -LUNA_ECC_HOC_PID= 62 # ECC Hardware Origin Certificate -LUNA_ECC_DAK_PID= 63 # ECC Device Authentication Key -LUNA_ECC_DAC_PID= 64 # ECC Device Authentication Certificate -CA_MASK_DES3_RC4= 0x00000001 -CA_MASK_SHA1_AES_RC4= 0x00000002 -LUNA_MAX_CHALLENGE_SIZE=64 -LUNA_MAX_CHALLENGE_RESPONSE_SIZE=64 -LUNA_CHALLENGE_CLASS_AUTHENTICATION= 0x00000000 -LUNA_CHALLENGE_CLASS_SIM= 0x00000001 -LUNA_CHALLENGE_TYPE_NULL= 0x00000000 -LUNA_CHALLENGE_TYPE_SECRET_HASH= 0x00000001 # Obsolete -- didn't satisfy NIST -LUNA_CHALLENGE_TYPE_ENCRYPTED_SECRET_HASH= 0x00000002 -LUNA_CHALLENGE_TYPE_SO= LUNA_UTYPE_SO -LUNA_CHALLENGE_TYPE_USER= LUNA_UTYPE_USER -LUNA_CHALLENGE_TYPE_LIMITED_USER= LUNA_UTYPE_LIMITED_USER -LUNA_CHALLENGE_TYPE_AUDIT= LUNA_UTYPE_AUDIT -LUNA_SIM_NO_AUTHORIZATION=0 # no authorization needed -LUNA_SIM_PASSWORD= 1 # plain-text passwords -LUNA_SIM_CHALLENGE= 2 # challenge secrets emitted through the secure port -LUNA_SIM_SECURE_PORT= 3 # PED keys -LUNA_SIM_PORTABLE_NO_AUTHORIZATION=4 # no authorization needed -LUNA_SIM_PORTABLE_PASSWORD= 5 # plain-text passwords -LUNA_SIM_PORTABLE_CHALLENGE= 6 # challenge secrets emitted through the secure port -LUNA_SIM_PORTABLE_SECURE_PORT= 7 # PED keys -MAX_SIM_OBJECTS=2048 -CONTAINER_CONFIG_PRIVATE_KEY_CLONING= 0 -CONTAINER_CONFIG_PRIVATE_KEY_WRAPPING= 1 -CONTAINER_CONFIG_PRIVATE_KEY_UNWRAPPING= 2 -CONTAINER_CONFIG_PRIVATE_KEY_MASKING= 3 -CONTAINER_CONFIG_SECRET_KEY_CLONING= 4 -CONTAINER_CONFIG_SECRET_KEY_WRAPPING= 5 -CONTAINER_CONFIG_SECRET_KEY_UNWRAPPING= 6 -CONTAINER_CONFIG_SECRET_KEY_MASKING= 7 -CONTAINER_CONFIG_OBSOLETE_1= 8 -CONTAINER_CONFIG_OBSOLETE_2= 9 -CONTAINER_CONFIG_MULTIPURPOSE_KEYS= 10 -CONTAINER_CONFIG_CHANGE_KEY_ATTRIBUTES= 11 -CONTAINER_CONFIG_OBSOLETE_3= 12 -CONTAINER_CONFIG_OBSOLETE_4= 13 -CONTAINER_CONFIG_FAILED_CHALLENGE_COUNTER= 15 -CONTAINER_CONFIG_NO_RSA_BLINDING= 16 -CONTAINER_CONFIG_NONLOCAL_SIGNING_KEYS= 17 -CONTAINER_CONFIG_RAW_RSA_OPERATIONS= 18 -CONTAINER_CONFIG_KEY_STORAGE_SPACE= 19 # Obsolete as of f/w 6.0.2 -CONTAINER_CONFIG_MAX_FAILED_USER_LOGINS_ALLOWED=20 -CONTAINER_CONFIG_HIGH_AVAILABILITY= 21 -CONTAINER_CONFIG_ACTIVATION= 22 -CONTAINER_CONFIG_AUTO_ACTIVATION= 23 -CONTAINER_CONFIG_INDIRECT_LOGIN= 24 # Obsolete as of f/w 5.0 -CONTAINER_CONFIG_MINIMUM_PIN_LENGTH= 25 -CONTAINER_CONFIG_MAXIMUM_PIN_LENGTH= 26 -CONTAINER_CONFIG_OBSOLETE_5= 27 # CONTAINER_CONFIG_RA_TYPE_WRAPPING -CONTAINER_CONFIG_KEY_MANAGEMENT_FUNCTIONS= 28 -CONTAINER_CONFIG_RSA_SIGNATURE_CONFIRMATION= 29 -CONTAINER_CONFIG_REMOTE_AUTHENTICATION= 30 -CONTAINER_CONFIG_PRIVATE_KEY_UNMASKING= 31 -CONTAINER_CONFIG_SECRET_KEY_UNMASKING= 32 -CONTAINER_CONFIG_RSA_PKCS_MECHANISM= 33 -CONTAINER_CONFIG_CBC_PAD_WRAP_UNWRAP_KEYS_OF_ANY_SIZE= 34 -CONTAINER_CONFIG_PRIVATE_KEY_SMALL_FORM_FACTOR= 35 -CONTAINER_CONFIG_SECRET_KEY_SMALL_FORM_FACTOR= 36 -CONTAINER_CONFIG_SECURE_TRUSTED_CHANNEL= 37 -HSM_CONFIG_ENABLE_PIN_AUTHENTICATION= 0 -HSM_CONFIG_ENABLE_PED_AUTHENTICATION= 1 -HSM_CONFIG_PERFORMANCE_LEVEL= 2 -HSM_CONFIG_M_OF_N= 3 # Obsolete -HSM_CONFIG_DOMESTIC= 4 -HSM_CONFIG_CAV_USED= 5 -HSM_CONFIG_MASKING= 6 -HSM_CONFIG_CLONING= 7 -HSM_CONFIG_SPECIAL_CLONING= 8 # Obsolete -HSM_CONFIG_NONBACKUP_TOKEN= 9 -HSM_CONFIG_OBSOLETE_2= 10 -HSM_CONFIG_ECC= 11 -HSM_CONFIG_NONFIPS_ALGORITHMS= 12 -HSM_CONFIG_MOFN_AUTO_ACTIVATION= 13 # Obsolete -HSM_CONFIG_OBSOLETE_3= 14 -HSM_CONFIG_SO_CAN_RESET_PIN= 15 -HSM_CONFIG_NETWORK_REPLICATION= 16 -HSM_CONFIG_KOREAN= 17 -HSM_CONFIG_FIPS_EVALUATED= 18 -HSM_CONFIG_MANUFACT_TOKEN= 19 -HSM_CONFIG_REMOTE_AUTHENTICATION= 20 -HSM_CONFIG_FORCE_USER_PIN_CHANGE= 21 -HSM_CONFIG_OFFBOARD_STORAGE= 22 -HSM_CONFIG_ENABLE_PARTITION_GROUPS= 23 -HSM_CONFIG_ENABLE_NONFIPS_ACCELERATOR= 24 -HSM_CONFIG_ENABLE_REMOTE_PED_USAGE= 25 -HSM_CONFIG_STORE_MTK_SPLIT_EXTERNALLY= 26 -HSM_CONFIG_STORAGE_SIZE= 27 -HSM_CONFIG_OBSOLETE_28= 28 -HSM_CONFIG_ENABLE_ACCELERATION= 29 -HSM_CONFIG_UNMASKING= 30 -HSM_CONFIG_ENABLE_FW5_COMPATIBILITY= 31 -HSM_CONFIG_ALLOWS_PUBLIC_CRYPTO= 32 -HSM_CONFIG_MAX_PARTITIONS= 33 -HSM_CONFIG_ENABLE_ECIES= 34 -HSM_CONFIG_ENABLE_SINGLE_DOMAIN= 35 -HSM_CONFIG_ALLOW_UNIFIED_PED_KEY= 36 -HSM_CONFIG_ALLOW_MOFN= 37 -HSM_CONFIG_ENABLE_SMALL_FORM_FACTOR_BACKUP= 38 -HSM_CONFIG_ENABLE_SECURE_TRUSTED_CHANNEL= 39 -HSM_CONFIG_DECOMMISSION_ON_TAMPER= 40 -HSM_CONFIG_PER_PARTITION_SO= 41 -HSM_CONFIG_ENABLE_PARTITION_REINIT= 42 -LUNA_CLONING_PART2_OVERHEAD= 76 -LUNA_FLATTENED_OBJECT_OVERHEAD= 3264 -LEGACY_TWC_ACCESS_LEVEL= 1 -LUNA_LICENSE_TYPE_CONTAINER_PERSONALITY=0 -LUNA_LICENSE_TYPE_HSM_UPGRADE=1 -LUNA_LICENSE_TYPE=2 -LICENSE_DESCRIPTION_SIZE=60 -PERSONALITY_NAME_SIZE=60 -UPGRADE_DESCRIPTION_SIZE=60 -LUNA_MAX_ROLE_NAME_LEN= 24 -LUNA_MAX_PRP_LABEL_LEN= 24 -LUNA_MAX_ROLES_PER_PARTITION= 4 -LUNA_MAX_PRP_PER_SET= 3 -LUNA_NULL_ELEMENT= 0x00000000 -LUNA_CRYPTOKI_ELEMENT= 0x00000001 -LUNA_PARAM_ELEMENT= 0x00000002 -LUNA_CONTAINER_ACTIVATION_ELEMENT= 0x00000003 -LUNA_MOFN_ACTIVATION_ELEMENT= 0x00000004 -LUNA_CONTAINER_ELEMENT= 0x00000005 -LUNA_USER_PARTITION_ELEMENT= 0x00000006 -LUNA_UNKNOWN_ELEMENT= (-1) -LUNA_FW4_CRYPTOKI_ELEMENT= 0x00000000 -LUNA_FW4_PARAM_ELEMENT= 0x00000001 -LUNA_FW4_CONTAINER_ACTIVATION_ELEMENT= 0x00000002 -LUNA_FW4_MOFN_ACTIVATION_ELEMENT= 0x00000003 -LUNA_HW_UNDEFINED= 0x00000000 -LUNA_HW_K3_PCI= 0x00000001 -LUNA_HW_K4_PCI= 0x00000002 -LUNA_HW_G3_PCMCIA= 0x00000003 -LUNA_HW_G4_PCMCIA= 0x00000004 -LUNA_HW_G5_USB= 0x00000005 -LUNA_HW_K5_PCI= 0x00000006 -LUNA_HW_PS_PCI= 0x00000007 -LUNA_HW_SSM= 0x00000008 -LUNA_HW_K6_PCI= 0x00000009 -LUNA_STORAGE_SHIFT= 0 -LUNA_STORAGE_MASK= (0x03 << LUNA_STORAGE_SHIFT) -LUNA_STORAGE_DEFAULT= (0x00 << LUNA_STORAGE_SHIFT) -LUNA_STORAGE_FLASH= (0x01 << LUNA_STORAGE_SHIFT) -LUNA_STORAGE_RAM= (0x02 << LUNA_STORAGE_SHIFT) -LUNA_STORAGE_CACHE= (0x03 << LUNA_STORAGE_SHIFT) -LUNA_PARTITION_TYPE_SHIFT= 2 -LUNA_PARTITION_TYPE_MASK= (0x03 << LUNA_PARTITION_TYPE_SHIFT) -LUNA_PARTITION_TYPE_STANDALONE= (0x00 << LUNA_PARTITION_TYPE_SHIFT) -LUNA_PARTITION_TYPE_GROUP= (0x01 << LUNA_PARTITION_TYPE_SHIFT) -LUNA_PARTITION_TYPE_ADMIN= (0x03 << LUNA_PARTITION_TYPE_SHIFT) -LUNA_CONTAINER_TYPE_GROUP= LUNA_PARTITION_TYPE_GROUP -LUNA_CONTAINER_TYPE_STANDALONE= LUNA_PARTITION_TYPE_STANDALONE -LUNA_INSERTION_UNINITIALIZED= 0x10 -LUNA_ENABLE_MEMBER_CONTAINER= 0x01 -LUNA_DISABLE_MEMBER_CONTAINER= 0x02 -LUNA_UNAUTH_CMD_CONTEXT_CREATE= 0x01 -LUNA_UNAUTH_CMD_CONTEXT_DELETE= 0x02 -LUNA_UNAUTH_CMD_CONTEXT_GET= 0x03 -LUNA_PKCS5_PBKD2_HMAC_SHA1= 0x00000001 -LUNA_SALT_SOURCE_SPECIFIED= 0x00000001 -LUNA_KDF_NULL= 0x00000001 -LUNA_KDF_SHA1_KDF= 0x00000002 -LUNA_KDF_SHA1_KDF_ASN1_X9_42= 0x00000003 -LUNA_KDF_SHA1_KDF_CONCATENATE_X9_42= 0x00000004 -LUNA_KDF_SHA1_KDF_CONCATENATE_NIST= 0x80000001 -LUNA_KDF_SHA1_KDF_ASN1_NIST= 0x80000002 -LUNA_KDF_SHA224_KDF= 0x80000003 -LUNA_KDF_SHA256_KDF= 0x80000004 -LUNA_KDF_SHA384_KDF= 0x80000005 -LUNA_KDF_SHA512_KDF= 0x80000006 -LUNA_KDF_RIPEMD160_KDF= 0x80000007 -LUNA_KDF_SHA1_NIST_KDF= 0x00000012 -LUNA_KDF_SHA224_NIST_KDF= 0x80000013 -LUNA_KDF_SHA256_NIST_KDF= 0x80000014 -LUNA_KDF_SHA384_NIST_KDF= 0x80000015 -LUNA_KDF_SHA512_NIST_KDF= 0x80000016 -LUNA_KDF_RIPEMD160_NIST_KDF= 0x80000017 -LUNA_KDF_SHA1_SES_KDF= 0x82000000 -LUNA_KDF_SHA224_SES_KDF= 0x83000000 -LUNA_KDF_SHA256_SES_KDF= 0x84000000 -LUNA_KDF_SHA384_SES_KDF= 0x85000000 -LUNA_KDF_SHA512_SES_KDF= 0x86000000 -LUNA_KDF_RIPEMD160_SES_KDF= 0x87000000 -LUNA_KDF_SES_ENC_CTR= 0x00000001 -LUNA_KDF_SES_AUTH_CTR= 0x00000002 -LUNA_KDF_SES_ALT_ENC_CTR= 0x00000003 -LUNA_KDF_SES_ALT_AUTH_CTR= 0x00000004 -LUNA_KDF_SES_MAX_CTR_MASK= 0x0000FFFF -LUNA_PRF_KDF_DES3_CMAC= 0x00000001 -LUNA_PRF_KDF_AES_CMAC= 0x00000002 -LUNA_PRF_KDF_ARIA_CMAC= 0x00000003 -LUNA_PRF_KDF_SEED_CMAC= 0x00000004 -LUNA_PRF_KDF_ENCODING_SCHEME_1= 0x00000000 -LUNA_PRF_KDF_ENCODING_SCHEME_2= 0x00000001 -CB_CMD_TEST= 0x00000000 -CB_CMD_TEST_UPLOAD= 0x00000001 -CB_CMD_TEST_DOWNLOAD= 0x00000002 -CB_CMD_TEST_PING= 0x00000003 -CB_CMD_RPED_READ= 0x00000001 -CB_CMD_RPED_WRITE= 0x00000002 -CB_CMD_RPED_GET_STATUS= 0x00000003 -CB_CMD_RPED_RESET_PED= 0x00000004 -CB_CMD_LOG= 0x00000005 -LUNA_PED_CMD_GET_RAW_DATA= 0x00000000 -LUNA_PED_CMD_SET_RAW_DATA= 0x00000001 -MTK_STATE_FLAG_RESPLIT_ABORTED= 0x00000001 -MTK_STATE_FLAG_HARD_ZEROIZE= 0x00000002 -MTK_STATE_FLAG_SOFT_ZEROIZE= 0x00000004 -MTK_STATE_FLAG_LOCKED= 0x00000008 -LUNA_TSV_DOMESTIC_FLAG= 0x80 -LUNA_TSV_MISSING_MTK_FLAG= 0x40 -LUNA_TSV_CLONING_ENABLED_FLAG= 0x20 -LUNA_TSV_ERASURE_FLAG= 0x10 -LUNA_TSV_AUDIT_CONTAINER_ZEROIZED= 0x08 -LUNA_TSV_TLO_FLAG= 0x04 -LUNA_TSV_CVK_FLAG= 0x02 -LUNA_TSV_HOK_FLAG= 0x01 -LUNA_TSV_TUK_FLAG_LO= 0x80 -LUNA_TSV_TWC_FLAG_LO= 0x40 -LUNA_TSV_KCV_FLAG_LO= 0x20 -LUNA_TSV_FLAG_LO_VOLATILE_MASK= 0x1F -LUNA_TSV_MASKING_KEY_SET= 0x10 -LUNA_TSV_VOLATILE_TOKENRW_MASK= 0x0C -LUNA_TSV_VOLATILE_TOKENRW_IS_NULL= 0x00 -LUNA_TSV_VOLATILE_TOKENRW_IS_READ_ONLY= 0x04 -LUNA_TSV_VOLATILE_TOKENRW_IS_READ_WRITE=0x08 -LUNA_TSV_VOLATILE_ACCESS_MASK= 0x03 -LUNA_TSV_VOLATILE_ACCESS_IS_NULL= 0x00 -LUNA_TSV_VOLATILE_ACCESS_IS_PUBLIC= 0x01 -LUNA_TSV_VOLATILE_ACCESS_IS_USER= 0x02 -LUNA_TSV_VOLATILE_ACCESS_IS_SO= 0x03 -LUNA_TSV_VOLATILE_ACCESS_IS_AUDIT= 0x04 -LUNA_TSV_FATAL_ERROR_MASK= 0xF0 -LUNA_TSV_CRC_ERROR_FLAG= 0x80 -LUNA_TSV_RNG_ERROR_FLAG= 0x40 -LUNA_TSV_MEM_ERROR_FLAG= 0x20 -LUNA_TSV_DEV_ERROR_FLAG= 0x10 -LUNA_TSV_TOSM_MASK= 0x0F -LUNA_TSV_TOSM_BLANK= 0x00 -LUNA_TSV_TOSM_ZEROIZED= 0x01 -LUNA_TSV_TOSM_FUNCTIONAL= 0x02 -LUNA_TSV_TOSM_ERROR= 0x03 -LUNA_MODIFY_USAGE_COUNT_TYPE_INCREMENT= 0x00000001 -LUNA_MODIFY_USAGE_COUNT_TYPE_SET= 0x00000002 -LUNA_CKDHP_ECDH1_COFACTOR= 0x00000001 -LUNA_CKDHP_MODIFIED= 0x00000002 # Not implemented */ -LUNA_CKDHP_ECDH1= 0x00000003 -LUNA_CKES_XOR= 0x00000001 -LUNA_CKES_DES3_CBC_PAD= 0x00000002 -LUNA_CKES_AES_CBC_PAD= 0x00000003 -LUNA_CKES_DES3_CBC= 0x00000004 -LUNA_CKES_AES_CBC= 0x00000005 -LUNA_CKMS_HMAC_SHA1= 0x00000001 -LUNA_CKMS_SHA1= 0x00000002 -LUNA_CKMS_HMAC_SHA224= 0x00000003 -LUNA_CKMS_SHA224= 0x00000004 -LUNA_CKMS_HMAC_SHA256= 0x00000005 -LUNA_CKMS_SHA256= 0x00000006 -LUNA_CKMS_HMAC_SHA384= 0x00000007 -LUNA_CKMS_SHA384= 0x00000008 -LUNA_CKMS_HMAC_SHA512= 0x00000009 -LUNA_CKMS_SHA512= 0x0000000a -LUNA_CKMS_HMAC_RIPEMD160= 0x0000000b -LUNA_CKMS_RIPEMD160= 0x0000000c -LUNA_DUKPT_PARAM_LEN= 10 # KSN parameter is 10 bytes */ -LUNA_LOG_WRITE= 0x000000c1 -LUNA_LOG_POLL_HOST= 0x000000c2 # This one is both internal and external, between the host & f/w, so it's defined above -LUNA_LOG_SET_CONFIG= 0x000000c5 # This one is both internal and external, between the host & f/w, so it's defined above -LUNA_LOG_RESYNC= 0x000000c8 -LUNA_STATS_NONE= 0 -LUNA_STATS_BOOT_TIME= 1 -LUNA_STATS_CPU_UP_TIME= 2 -LUNA_STATS_CPU_IDLE_TIME= 3 -LUNA_STATS_ICD_COMMANDS_COUNT= 4 -LUNA_STATS_UNKNOWN= 0xffffffff -PED_PASSWORD_LENGTH=8 +LUNA_MAX_UPDATE_DATA_SIZE = (64 * 1024) +LUNA_GEN_KCV_FLAG_NONE = 0x0000 +LUNA_GEN_KCV_FLAG_CONSOLIDATE = 0x0001 +LUNA_MECH_RSA_PKCS_KEY_PAIR_GEN = 0x00000000 +LUNA_MECH_RSA_PKCS = 0x00000001 +LUNA_MECH_RSA_X_509 = 0x00000002 +LUNA_MECH_MD5_RSA_PKCS = 0x00000005 +LUNA_MECH_SHA1_RSA_PKCS = 0x00000006 +LUNA_MECH_RSA_PKCS_OAEP = 0x00000009 +LUNA_MECH_RSA_X9_31_KEY_PAIR_GEN = 0x0000000A +LUNA_MECH_RSA_X9_31 = 0x0000000B +LUNA_MECH_SHA1_RSA_X9_31 = 0x0000000C +LUNA_MECH_RSA_PKCS_PSS = 0x0000000D +LUNA_MECH_SHA1_RSA_PKCS_PSS = 0x0000000E +LUNA_MECH_DSA_KEY_PAIR_GEN = 0x00000010 +LUNA_MECH_DSA = 0x00000011 +LUNA_MECH_SHA1_DSA = 0x00000012 +LUNA_MECH_DH_PKCS_KEY_PAIR_GEN = 0x00000020 +LUNA_MECH_DH_PKCS_DERIVE = 0x00000021 +LUNA_MECH_X9_42_DH_KEY_PAIR_GEN = 0x00000030 +LUNA_MECH_X9_42_DH_DERIVE = 0x00000031 +LUNA_MECH_X9_42_DH_HYBRID_DERIVE = 0x00000032 +LUNA_MECH_SHA256_RSA_PKCS = 0x00000040 +LUNA_MECH_SHA384_RSA_PKCS = 0x00000041 +LUNA_MECH_SHA512_RSA_PKCS = 0x00000042 +LUNA_MECH_SHA256_RSA_PKCS_PSS = 0x00000043 +LUNA_MECH_SHA384_RSA_PKCS_PSS = 0x00000044 +LUNA_MECH_SHA512_RSA_PKCS_PSS = 0x00000045 +LUNA_MECH_RC2_KEY_GEN = 0x00000100 +LUNA_MECH_RC2_ECB = 0x00000101 +LUNA_MECH_RC2_CBC = 0x00000102 +LUNA_MECH_RC2_MAC = 0x00000103 +LUNA_MECH_RC2_CBC_PAD = 0x00000105 +LUNA_MECH_RC4_KEY_GEN = 0x00000110 +LUNA_MECH_RC4 = 0x00000111 +LUNA_MECH_DES_KEY_GEN = 0x00000120 +LUNA_MECH_DES_ECB = 0x00000121 +LUNA_MECH_DES_CBC = 0x00000122 +LUNA_MECH_DES_MAC = 0x00000123 +LUNA_MECH_DES_CBC_PAD = 0x00000125 +LUNA_MECH_DES2_KEY_GEN = 0x00000130 +LUNA_MECH_DES3_KEY_GEN = 0x00000131 +LUNA_MECH_DES3_ECB = 0x00000132 +LUNA_MECH_DES3_CBC = 0x00000133 +LUNA_MECH_DES3_MAC = 0x00000134 +LUNA_MECH_DES3_CBC_PAD = 0x00000135 +LUNA_MECH_MD2 = 0x00000200 +LUNA_MECH_MD5 = 0x00000210 +LUNA_MECH_SHA_1 = 0x00000220 +LUNA_MECH_SHA256 = 0x00000250 +LUNA_MECH_HMAC_SHA256 = 0x00000251 +LUNA_MECH_SHA384 = 0x00000260 +LUNA_MECH_HMAC_SHA384 = 0x00000261 +LUNA_MECH_SHA512 = 0x00000270 +LUNA_MECH_HMAC_SHA512 = 0x00000271 +LUNA_MECH_SHA256_KEY_DERIVATION = 0x00000393 +LUNA_MECH_SHA384_KEY_DERIVATION = 0x00000394 +LUNA_MECH_SHA512_KEY_DERIVATION = 0x00000395 +LUNA_MECH_PKCS5_PBKD2 = 0x000003B0 +LUNA_MECH_KEY_WRAP_SET_OAEP = 0x00000401 +LUNA_MECH_EC_KEY_PAIR_GEN = 0x00001040 +LUNA_MECH_ECDSA = 0x00001041 +LUNA_MECH_SHA1_ECDSA = 0x00001042 +LUNA_MECH_SHA224_ECDSA = 0x00001043 +LUNA_MECH_SHA256_ECDSA = 0x00001044 +LUNA_MECH_SHA384_ECDSA = 0x00001045 +LUNA_MECH_SHA512_ECDSA = 0x00001046 +LUNA_MECH_ECDH1_DERIVE = 0x00001050 +LUNA_MECH_ECDH1_COFACTOR_DERIVE = 0x00001051 +LUNA_MECH_ECMQV_DERIVE = 0x00001052 +LUNA_MECH_AES_KEY_GEN = 0x00001080 +LUNA_MECH_AES_ECB = 0x00001081 +LUNA_MECH_AES_CBC = 0x00001082 +LUNA_MECH_AES_MAC = 0x00001083 +LUNA_MECH_AES_MAC_GENERAL = 0x00001084 +LUNA_MECH_AES_CBC_PAD = 0x00001085 +LUNA_MECH_DES_ECB_ENCRYPT_DATA = 0x00001100 +LUNA_MECH_DES_CBC_ENCRYPT_DATA = 0x00001101 +LUNA_MECH_DES3_ECB_ENCRYPT_DATA = 0x00001102 +LUNA_MECH_DES3_CBC_ENCRYPT_DATA = 0x00001103 +LUNA_MECH_AES_ECB_ENCRYPT_DATA = 0x00001104 +LUNA_MECH_AES_CBC_ENCRYPT_DATA = 0x00001105 +LUNA_MECH_ARIA_KEY_GEN = 0x00001200 +LUNA_MECH_ARIA_ECB = 0x00001201 +LUNA_MECH_ARIA_CBC = 0x00001202 +LUNA_MECH_ARIA_MAC = 0x00001203 +LUNA_MECH_ARIA_MAC_GENERAL = 0x00001204 +LUNA_MECH_ARIA_CBC_PAD = 0x00001205 +LUNA_MECH_ARIA_ECB_ENCRYPT_DATA = 0x00001206 +LUNA_MECH_ARIA_CBC_ENCRYPT_DATA = 0x00001207 +LUNA_MECH_DSA_PARAMETER_GEN = 0x00002000 +LUNA_MECH_DH_PKCS_PARAMETER_GEN = 0x00002001 +LUNA_MECH_X9_42_DH_PARAMETER_GEN = 0x00002002 +LUNA_MECH_CAST_KEY_GEN = 0x00008001 +LUNA_MECH_CAST_ECB = 0x00008002 +LUNA_MECH_CAST_CBC = 0x00008003 +LUNA_MECH_CAST_MAC = 0x00008004 +LUNA_MECH_CAST_CBC_PAD = 0x00008005 +LUNA_MECH_CAST3_KEY_GEN = 0x00008101 +LUNA_MECH_CAST3_ECB = 0x00008102 +LUNA_MECH_CAST3_CBC = 0x00008103 +LUNA_MECH_CAST3_MAC = 0x00008104 +LUNA_MECH_CAST3_CBC_PAD = 0x00008105 +LUNA_MECH_CAST5_KEY_GEN = 0x00008501 +LUNA_MECH_CAST5_ECB = 0x00008502 +LUNA_MECH_CAST5_CBC = 0x00008503 +LUNA_MECH_CAST5_MAC = 0x00008504 +LUNA_MECH_CAST5_CBC_PAD = 0x00008505 +LUNA_MECH_RC5_KEY_GEN = 0x00008600 +LUNA_MECH_RC5_ECB = 0x00008601 +LUNA_MECH_RC5_CBC = 0x00008602 +LUNA_MECH_RC5_MAC = 0x00008603 +LUNA_MECH_RC5_CBC_PAD = 0x00008605 +LUNA_MECH_MD2_DES_CBC = 0x00008201 +LUNA_MECH_MD5_DES_CBC = 0x00008202 +LUNA_MECH_SHA1_DES3_CBC = 0x00008203 +LUNA_MECH_MD5_CAST_CBC = 0x00008204 +LUNA_MECH_MD5_CAST3_CBC = 0x00008205 +LUNA_MECH_SHA1_CAST5_CBC = 0x00008206 +LUNA_MECH_SHA1_DES2_CBC = 0x00008207 +LUNA_MECH_SHA1_RC4_128 = 0x00008208 +LUNA_MECH_SHA1_RC4_40 = 0x00008209 +LUNA_MECH_SHA1_RC2_128_CBC = 0x0000820A +LUNA_MECH_SHA1_RC2_40_CBC = 0x0000820B +LUNA_MECH_SHA1_DES2_CBC_OLD = 0x0000820C # Added for compatibility with legacy apps +LUNA_MECH_SHA1_DES3_CBC_OLD = 0x0000820D # Added for compatibility with legacy apps +LUNA_MECH_CONCATENATE_BASE_AND_KEY = 0x00008301 # Added for SPKM & SSL Support +LUNA_MECH_CONCATENATE_KEY_AND_BASE = 0x00008302 # Added for SPKM & SSL Support +LUNA_MECH_CONCATENATE_BASE_AND_DATA = 0x00008303 # Added for SPKM & SSL Support +LUNA_MECH_CONCATENATE_DATA_AND_BASE = 0x00008304 # Added for SPKM & SSL Support +LUNA_MECH_XOR_BASE_AND_DATA = 0x00008305 # Added for SPKM & SSL Support +LUNA_MECH_XOR_BASE_AND_KEY = 0x0000860B # Added for F/W Update Support +LUNA_MECH_EXTRACT_KEY_FROM_KEY = 0x00008306 # Added for SPKM & SSL Support +LUNA_MECH_MD2_KEY_DERIVATION = 0x00008307 # Added for SPKM & SSL Support +LUNA_MECH_MD5_KEY_DERIVATION = 0x00008308 # Added for SPKM & SSL Support +LUNA_MECH_SHA1_KEY_DERIVATION = 0x00008309 # Added for SPKM & SSL Support +LUNA_MECH_GENERIC_SECRET_KEY_GEN = 0x0000830A # Added for SPKM & SSL Support +LUNA_MECH_SSL3_MASTER_KEY_DERIVE = 0x0000830B # Added for SSL Support +LUNA_MECH_SSL3_KEY_AND_MAC_DERIVE = 0x0000830C # Added for SSL Support +LUNA_MECH_SSL3_MD5_MAC = 0x0000830D # Added for SSL Support +LUNA_MECH_SSL3_SHA1_MAC = 0x0000830E # Added for SSL Support +LUNA_MECH_HMAC_SHA1 = 0x0000830F # Added for SSL Support +LUNA_MECH_HMAC_SHA1_80 = 0x00008310 # Added for SSL Support +LUNA_MECH_HMAC_MD5 = 0x00008311 # Added for SSL Support +LUNA_MECH_HMAC_MD5_80 = 0x00008312 # Added for SSL Support +LUNA_MECH_SSL3_PRE_MASTER_KEY_GEN = 0x00008313 # Added for SSL Support +LUNA_MECH_DES3_CFB8 = 0x00008314 +LUNA_MECH_DES3_CFB64 = 0x00008315 +LUNA_MECH_DES3_OFB = 0x00008316 +LUNA_MECH_DES3_CTR = 0x00008317 +LUNA_MECH_DES3_GCM = 0x00008318 +LUNA_MECH_AES_CFB8 = 0x00008319 +LUNA_MECH_AES_CFB128 = 0x0000831a +LUNA_MECH_AES_OFB = 0x0000831b +LUNA_MECH_AES_CTR = 0x0000831c +LUNA_MECH_AES_GCM = 0x0000831d +LUNA_MECH_ARIA_CFB8 = 0x0000831e +LUNA_MECH_ARIA_CFB128 = 0x0000831f +LUNA_MECH_ARIA_OFB = 0x00008320 +LUNA_MECH_ARIA_CTR = 0x00008321 +LUNA_MECH_ARIA_GCM = 0x00008322 +LUNA_MECH_2DES_DERIVE = 0x000083FF # Added for Gemplus +LUNA_MECH_INDIRECT_LOGIN_REENCRYPT = 0x00008400 # Added for indirect login support. Obsolete as of f/w 5.0 +LUNA_MECH_LZS = 0x00008400 # Added for Compression Support +LUNA_MECH_LOOP_BACK = 0x80000000 +LUNA_MECH_NONE = LUNA_MECH_LOOP_BACK # Added for IPSEC Support +LUNA_MECH_UNKNOWN = 0xFFFFFFFF # Added for error detection +LUNA_MECH_SEED_KEY_GEN = 0x00008701 +LUNA_MECH_SEED_ECB = 0x00008702 +LUNA_MECH_SEED_CBC = 0x00008703 +LUNA_MECH_SEED_CBC_PAD = 0x00008704 +LUNA_MECH_SEED_MAC = 0x00008705 +LUNA_MECH_HAS160 = 0x00008706 +LUNA_MECH_KCDSA_KEY_PAIR_GEN = 0x00008707 +LUNA_MECH_HAS160_KCDSA = 0x00008708 +LUNA_MECH_SHA1_KCDSA = 0x00008709 +LUNA_MECH_SHA224_KCDSA = 0x0000870A +LUNA_MECH_SHA256_KCDSA = 0x0000870B +LUNA_MECH_SHA384_KCDSA = 0x0000870C +LUNA_MECH_SHA512_KCDSA = 0x0000870D +LUNA_MECH_HMAC_HAS160 = 0x0000870E +LUNA_MECH_KCDSA_PARAMETER_GEN = 0x0000870F +LUNA_MECH_HAS160_KCDSA_NO_PAD = 0x00008710 +LUNA_MECH_SHA1_KCDSA_NO_PAD = 0x00008711 +LUNA_MECH_SHA224_KCDSA_NO_PAD = 0x00008712 +LUNA_MECH_SHA256_KCDSA_NO_PAD = 0x00008713 +LUNA_MECH_SHA384_KCDSA_NO_PAD = 0x00008714 +LUNA_MECH_SHA512_KCDSA_NO_PAD = 0x00008715 +LUNA_MECH_AES_CBC_PAD_EXTRACT = 0x00009000 +LUNA_MECH_AES_CBC_PAD_INSERT = 0x00009001 +LUNA_MECH_AES_CBC_PAD_EXTRACT_FLATTENED = 0x00009002 +LUNA_MECH_AES_CBC_PAD_INSERT_FLATTENED = 0x00009003 +LUNA_MECH_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL = 0x00009004 +LUNA_MECH_AES_CBC_PAD_INSERT_DOMAIN_CTRL = 0x00009005 +LUNA_MASKING_STORAGE_HOST = 0x00000000 +LUNA_MASKING_STORAGE_PED_USB_MEMORY = 0x00000001 +LUNA_MASKING_STORAGE_HSM_USB_MEMORY = 0x00000002 +LUNA_MASKING_FLAG_DELETE_AFTER_EXTRACT = 0x1 # Flag "Delete After Extract" */ +LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC = 0x80009000 +LUNA_MECH_AES_CBC_PAD_INSERT_PUBLIC = 0x80009001 +LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC_FLATTENED = 0x80009002 +LUNA_MECH_AES_CBC_PAD_INSERT_PUBLIC_FLATTENED = 0x80009003 +LUNA_MECH_SHA224_RSA_PKCS = 0x80000110 +LUNA_MECH_SHA224_RSA_PKCS_PSS = 0x80000111 +LUNA_MECH_SHA224 = 0x80000112 +LUNA_MECH_HMAC_SHA224 = 0x80000113 +LUNA_MECH_SHA224_KEY_DERIVATION = 0x80000115 +LUNA_MECH_HMAC_RIPEMD160 = 0x80000116 +LUNA_MECH_RIPEMD160 = 0x80000117 +LUNA_MECH_SHA224_DSA = 0x80000122 +LUNA_MECH_SHA256_DSA = 0x80000123 +LUNA_MECH_DES3_CMAC = 0x80000126 +LUNA_MECH_ARIA_CMAC = 0x80000127 +LUNA_MECH_AES_CMAC = 0x80000128 +LUNA_MECH_SEED_CMAC = 0x80000129 +LUNA_MECH_DES3_CBC_PAD_IPSEC = 0x80000130 +LUNA_MECH_AES_CBC_PAD_IPSEC = 0x80000131 +LUNA_MECH_XOR_BASE_AND_DATA_W_KDF = 0x80000132 +LUNA_MECH_ARIA_L_ECB = 0x80000133 +LUNA_MECH_ARIA_L_CBC = 0x80000134 +LUNA_MECH_ARIA_L_CBC_PAD = 0x80000135 +LUNA_MECH_ARIA_L_MAC = 0x80000136 +LUNA_MECH_SHA224_RSA_X9_31 = 0x80000137 +LUNA_MECH_SHA256_RSA_X9_31 = 0x80000138 +LUNA_MECH_SHA384_RSA_X9_31 = 0x80000139 +LUNA_MECH_SHA512_RSA_X9_31 = 0x8000013a +LUNA_MECH_SHA1_RSA_X9_31_NON_FIPS = 0x8000013b +LUNA_MECH_SHA224_RSA_X9_31_NON_FIPS = 0x8000013c +LUNA_MECH_SHA256_RSA_X9_31_NON_FIPS = 0x8000013d +LUNA_MECH_SHA384_RSA_X9_31_NON_FIPS = 0x8000013e +LUNA_MECH_SHA512_RSA_X9_31_NON_FIPS = 0x8000013f +LUNA_MECH_RSA_X9_31_NON_FIPS = 0x80000140 +LUNA_MECH_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN = 0x80000141 +LUNA_MECH_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN = 0x80000142 +LUNA_MECH_AES_GMAC = 0x80000143 +LUNA_MECH_SEED_CTR = 0x80008144 +LUNA_MECH_DES3_X919_MAC = 0x80000150 +LUNA_MECH_EC_KEY_PAIR_GEN_W_EXTRA_BITS = 0x80000160 +LUNA_MECH_SHA256_ECDSA_GBCS = 0x80000161 +LUNA_MECH_DES2_DUKPT_PIN = 0x80000611 +LUNA_MECH_DES2_DUKPT_MAC = 0x80000612 +LUNA_MECH_DES2_DUKPT_MAC_RESP = 0x80000613 +LUNA_MECH_DES2_DUKPT_DATA = 0x80000614 +LUNA_MECH_DES2_DUKPT_DATA_RESP = 0x80000615 +LUNA_MECH_ECIES = 0x80000A00 +LUNA_MECH_NIST_PRF_KDF = 0x80000A02 +LUNA_MECH_PRF_KDF = 0x80000A03 +LUNA_MECH_FLAG_HW = 0x00000001 +LUNA_MECH_FLAG_ENCRYPT = 0x00000100 +LUNA_MECH_FLAG_DECRYPT = 0x00000200 +LUNA_MECH_FLAG_DIGEST = 0x00000400 +LUNA_MECH_FLAG_SIGN = 0x00000800 +LUNA_MECH_FLAG_SIGN_RECOVER = 0x00001000 +LUNA_MECH_FLAG_VERIFY = 0x00002000 +LUNA_MECH_FLAG_VERIFY_RECOVER = 0x00004000 +LUNA_MECH_FLAG_GENERATE = 0x00008000 +LUNA_MECH_FLAG_GENERATE_KEY_PAIR = 0x00010000 +LUNA_MECH_FLAG_WRAP = 0x00020000 +LUNA_MECH_FLAG_UNWRAP = 0x00040000 +LUNA_MECH_FLAG_DERIVE = 0x00080000 +LUNA_MECH_FLAG_EC_F_P = 0x00100000 +LUNA_MECH_FLAG_EC_F_2M = 0x00200000 +LUNA_MECH_FLAG_EC_ECPARAMETERS = 0x00400000 +LUNA_MECH_FLAG_EC_NAMEDCURVE = 0x00800000 +LUNA_MECH_FLAG_EC_UNCOMPRESS = 0x01000000 +LUNA_MECH_FLAG_EC_COMPRESS = 0x02000000 +LUNA_MECH_FLAG_EXTENSION = 0x80000000 +LUNA_MGF_MGF1_SHA1 = 0x00000001 +LUNA_MGF_MGF1_SHA256 = 0x00000002 +LUNA_MGF_MGF1_SHA384 = 0x00000003 +LUNA_MGF_MGF1_SHA512 = 0x00000004 +LUNA_MGF_MGF1_SHA224 = 0x00000005 +LUNA_OAEP_SOURCES_DATA_SPECIFIED = 0x00000001 +LUNA_ATTR_UNKNOWN = 0xFFFFFFFF # Added for error detection */ +LUNA_ATTR_CLASS = 0x00000000 +LUNA_ATTR_TOKEN = 0x00000001 +LUNA_ATTR_PRIVATE = 0x00000002 +LUNA_ATTR_LABEL = 0x00000003 +LUNA_ATTR_APPLICATION = 0x00000010 +LUNA_ATTR_VALUE = 0x00000011 +LUNA_ATTR_CERTIFICATE_TYPE = 0x00000080 +LUNA_ATTR_ISSUER = 0x00000081 +LUNA_ATTR_SERIAL_NUMBER = 0x00000082 +LUNA_ATTR_KEY_TYPE = 0x00000100 +LUNA_ATTR_SUBJECT = 0x00000101 +LUNA_ATTR_ID = 0x00000102 +LUNA_ATTR_SENSITIVE = 0x00000103 +LUNA_ATTR_ENCRYPT = 0x00000104 +LUNA_ATTR_DECRYPT = 0x00000105 +LUNA_ATTR_WRAP = 0x00000106 +LUNA_ATTR_UNWRAP = 0x00000107 +LUNA_ATTR_SIGN = 0x00000108 +LUNA_ATTR_SIGN_RECOVER = 0x00000109 +LUNA_ATTR_VERIFY = 0x0000010A +LUNA_ATTR_VERIFY_RECOVER = 0x0000010B +LUNA_ATTR_DERIVE = 0x0000010C +LUNA_ATTR_START_DATE = 0x00000110 +LUNA_ATTR_END_DATE = 0x00000111 +LUNA_ATTR_MODULUS = 0x00000120 +LUNA_ATTR_MODULUS_BITS = 0x00000121 +LUNA_ATTR_PUBLIC_EXPONENT = 0x00000122 +LUNA_ATTR_PRIVATE_EXPONENT = 0x00000123 +LUNA_ATTR_PRIME_1 = 0x00000124 +LUNA_ATTR_PRIME_2 = 0x00000125 +LUNA_ATTR_EXPONENT_1 = 0x00000126 +LUNA_ATTR_EXPONENT_2 = 0x00000127 +LUNA_ATTR_COEFFICIENT = 0x00000128 +LUNA_ATTR_PRIME = 0x00000130 +LUNA_ATTR_SUBPRIME = 0x00000131 +LUNA_ATTR_BASE = 0x00000132 +LUNA_ATTR_PRIME_BITS = 0x00000133 +LUNA_ATTR_SUBPRIME_BITS = 0x00000134 +LUNA_ATTR_VALUE_BITS = 0x00000160 +LUNA_ATTR_VALUE_LEN = 0x00000161 +LUNA_ATTR_EXTRACTABLE = 0x00000162 +LUNA_ATTR_LOCAL = 0x00000163 +LUNA_ATTR_NEVER_EXTRACTABLE = 0x00000164 +LUNA_ATTR_ALWAYS_SENSITIVE = 0x00000165 +LUNA_ATTR_MODIFIABLE = 0x00000170 +LUNA_ATTR_ECDSA_PARAMS = 0x00000180 +LUNA_ATTR_EC_POINT = 0x00000181 +LUNA_ATTR_VENDOR_DEFINED = 0x80000000 +LUNA_ATTR_CCM_PRIVATE = (LUNA_ATTR_VENDOR_DEFINED | 0x00000001) +LUNA_ATTR_FINGERPRINT_SHA1 = (LUNA_ATTR_VENDOR_DEFINED | 0x00000002) +LUNA_ATTR_PKC_TCTRUST = (LUNA_ATTR_VENDOR_DEFINED | 0x00000003) +LUNA_ATTR_PKC_CITS = (LUNA_ATTR_VENDOR_DEFINED | 0x00000004) +LUNA_ATTR_OUID = (LUNA_ATTR_VENDOR_DEFINED | 0x00000005) +LUNA_ATTR_X9_31_GENERATED = (LUNA_ATTR_VENDOR_DEFINED | 0x00000006) +LUNA_ATTR_PKC_ECC = (LUNA_ATTR_VENDOR_DEFINED | 0x00000007) +LUNA_ATTR_EKM_UID = (LUNA_ATTR_VENDOR_DEFINED | 0x00000008) +LUNA_ATTR_USAGE_COUNT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000101) +LUNA_ATTR_USAGE_COUNT_LIMIT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000200) +LUNA_ATTR_GENERIC_1 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001000) +LUNA_ATTR_GENERIC_2 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001001) +LUNA_ATTR_GENERIC_3 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001002) +LUNA_ATTR_FINGERPRINT_SHA256 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001003) +LUNA_ATTR_UNKNOWN = 0xFFFFFFFF +LUNA_OBJ_DATA = 0x00000000 +LUNA_OBJ_CERTIFICATE = 0x00000001 +LUNA_OBJ_SECRET_KEY = 0x00000002 +LUNA_OBJ_PUBLIC_KEY = 0x00000003 +LUNA_OBJ_PRIVATE_KEY = 0x00000004 +LUNA_OBJ_DOMAIN_PARAMETERS = 0x00000005 +LUNA_OBJ_VENDOR_DEFINED = 0x80000000 +LUNA_OBJ_UNKNOWN = 0xFFFFFFFF # Added for error detection */ +LUNA_KEY_RSA = 0x00000000 +LUNA_KEY_DSA = 0x00000001 +LUNA_KEY_DH = 0x00000002 +LUNA_KEY_GENERIC_SECRET = 0x00000003 +LUNA_KEY_RC2 = 0x00000004 +LUNA_KEY_RC4 = 0x00000005 +LUNA_KEY_DES = 0x00000006 +LUNA_KEY_DES2 = 0x00000007 +LUNA_KEY_DES3 = 0x00000008 +LUNA_KEY_CAST = 0x00000009 +LUNA_KEY_CAST3 = 0x0000000A +LUNA_CERT_X_509 = 0x0000000B +LUNA_KEY_CAST5 = 0x0000000C +LUNA_KEY_RC5 = 0x0000000D +LUNA_KEY_ECDSA = 0x0000000E +LUNA_KEY_KEA = 0x0000000F +LUNA_KEY_IDEA = 0x00000010 +LUNA_KEY_SKIPJACK = 0x00000011 +LUNA_KEY_BATON = 0x00000012 +LUNA_KEY_JUNIPER = 0x00000013 +LUNA_KEY_CDMF = 0x00000014 +LUNA_KEY_AES = 0x0000001F +LUNA_KEY_ARIA = 0x00000020 +LUNA_KEY_X9_42_DH = 0x00000021 +LUNA_KEY_VENDOR_DEFINED = 0x80000000 +LUNA_KEY_KCDSA = (LUNA_KEY_VENDOR_DEFINED + 0x10) +LUNA_KEY_SEED = (LUNA_KEY_VENDOR_DEFINED + 0x11) +LUNA_KEY_UNKNOWN = 0xFFFFFFFF # Added for error detection */ +LUNA_CERT_UNKNOWN = 0xFFFFFFFF # Added for error detection */ +LUNA_CVK_CERTIFICATE = 0x00000000 +LUNA_TWC_CERTIFICATE = 0x00000001 +LUNA_TUK_PRIVATE_KEY = 0x00000000 +LUNA_HOK_PRIVATE_KEY = 0x00000001 +LUNA_DAK_PRIVATE_KEY = 0x00000002 +LUNA_ECC_HOK_PRIVATE_KEY = 0x00000003 +LUNA_ECC_DAK_PRIVATE_KEY = 0x00000004 +LUNA_TUK3_PRIVATE_KEY = 0x00000005 +LUNA_VVK_PUBLIC_KEY = 0x00000001 +LUNA_GT_LABEL = 0x00000000 +LUNA_GT_MFG = 0x00000001 +LUNA_GT_MODEL = 0x00000002 +LUNA_GT_TSN = 0x00000003 +LUNA_GT_S_N = 0x00000003 # to remain backward compatible. LUNA_GT_TSN should be used. +LUNA_GT_FLAGS = 0x00000004 +LUNA_GT_SESSIONS = 0x00000005 +LUNA_GT_SRAM = 0x00000007 +LUNA_GT_FLASH = 0x00000008 +LUNA_GT_TPC = 0x00000009 +LUNA_GT_CAV = 0x0000000C +LUNA_GT_FWV = 0x0000000D +LUNA_GT_TSV = 0x0000000E +LUNA_GT_TWC = 0x0000000F +LUNA_GT_M_OF_N_INFO = 0x00000010 +LUNA_GT_M_OF_N_STATUS = 0x00000011 +LUNA_GT_TWK = 0x00000012 +LUNA_GT_USER_ILD = 0x00000014 +LUNA_GT_SO_ILD = 0x00000015 +LUNA_GT_ROOT_CERT = 0x00000017 +LUNA_GT_HW_ORIGIN_CERT = 0x00000018 # retrieves HOC+MIC +LUNA_GT_TCTRUST_DAC = 0x00000019 +LUNA_GT_TCTRUST_MAC = 0x0000001A +LUNA_GT_CITS_DAC = 0x0000001B +LUNA_GT_PPID = 0x0000001C +LUNA_GT_HARDWARE_PLATFORM = 0x0000001D +LUNA_GT_DEFAULT_MIN_MAX_PIN_LEN = 0x0000001E +LUNA_GT_TWC2 = 0x0000001F +LUNA_GT_RPV_STATUS = 0x00000020 +LUNA_GT_ECC_MIC = 0x00000021 +LUNA_GT_ECC_HOC = 0x00000022 +LUNA_GT_ECC_DAC = 0x00000023 +LUNA_GT_ROLLBACK_FWV = 0x00000024 +LUNA_GT_MIC = 0x00000025 +LUNA_GT_HOC = 0x00000026 # retrieves HOC only +LUNA_GT_CITS_MAC = 0x00000027 +LUNA_GT_SP_RAWREAD = 0x00000030 +LUNA_GT_SP_RAWWRITE = 0x00000031 +LUNA_GT_PED_CALLBACK_PROTOCOL = 0x00000032 +LUNA_GT_TWK3 = 0x00000033 +LUNA_GT_TWC3 = 0x00000034 +LUNA_GT_HSM_STORAGE_INFO = 0x00000035 +LUNA_GT_NUMBER_OF_CONTAINERS_ALLOWED = 0x00000036 +LUNA_GT_MAX_SINGLE_PART_SIZE = 0x00000037 +LUNA_GT_PARTITION_ROLE_POLICIES = 0x00000038 +LUNA_GT_PARTITION_ROLE_DESCRIPTORS = 0x00000039 +LUNA_GT_ADMIN_PARTITION_HANDLE = 0x0000003A +LUNA_GT_TIME_OF_DAY = 0x0000003B +LUNA_GT_MONO_COUNTER = 0x0000003C +LUNA_GT_TEMP_K2 = 0x0000003D +LUNA_GT_PIN = 0x00000006 +LUNA_GT_TPV = 0x0000000A +LUNA_GT_FPV = 0x0000000B +LUNA_GT_EXTENDED_TPV = 0x00000013 +LUNA_GT_EXTENDED_FPV = 0x00000016 +LUNA_TF_RNG = 0x00000001 +LUNA_TF_WRITE_PROTECTED = 0x00000002 +LUNA_TF_LOGIN_REQUIRED = 0x00000004 +LUNA_TF_USER_PIN_INITIALIZED = 0x00000008 +LUNA_TF_EXCLUSIVE_EXISTS = 0x00000010 +LUNA_TF_TOKEN_INITIALIZED = 0x00000400 +LUNA_CF_CONTAINER_ENABLED = 0x01000000 +LUNA_CF_KCV_CREATED = 0x02000000 +LUNA_CF_LKCV_CREATED = 0x04000000 +LUNA_CF_HA_INITIALIZED = 0x08000000 +LUNA_CF_PARTITION_INITIALIZED = 0x00000400 +LUNA_CF_CONTAINER_ACTIVATED = 0x00000001 +LUNA_CF_CONTAINER_LUSR_ACTIVATED = 0x00000002 +LUNA_CF_USER_PIN_INITIALIZED = 0x00008000 +LUNA_CF_SO_PIN_LOCKED = 0x00010000 +LUNA_CF_SO_PIN_TO_BE_CHANGED = 0x00020000 +LUNA_CF_USER_PIN_LOCKED = 0x00040000 +LUNA_CF_LIMITED_USER_PIN_LOCKED = 0x00080000 +LUNA_CF_LIMITED_USER_CREATED = 0x00200000 +LUNA_CF_USER_PIN_TO_BE_CHANGED = 0x00400000 +LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED = 0x00800000 +LUNA_FLAG_M_OF_N_REQUIRED = 0x00000001 +LUNA_FLAG_M_OF_N_ACTIVATED = 0x00000002 +LUNA_FLAG_M_OF_N_GENERATED = 0x00000004 +LUNA_FLAG_M_OF_N_CLONEABLE = 0x00000008 +LUNA_ISAKMP_DECRYPT = 0x00000500 +LUNA_ISAKMP_ENCRYPT_FIXED_IV = 0x00000501 +LUNA_ISAKMP_ENCRYPT_GEN_IV = 0x00000502 +LUNA_ENTRY_DATA_AREA = 0x00000000 # obsolete in NextGen/PerPartitionSO firmware +LUNA_ENTRY_SECURE_PORT = 0x00000001 +LUNA_ENTRY_INDIRECT = 0x00000002 # Obsolete as of f/w 5.0 +LUNA_ENTRY_RANDOM = 0x00000003 # only used for pin creation +LUNA_ENTRY_CHALLENGE_RESPONSE = 0x00000004 # only used for login +LUNA_ENTRY_REMOTE_AUTHENTICATION = 0x00000005 +LUNA_ENTRY_DATA_AREA_MASKED = 0x00000006 +LUNA_ENTRY_NONE = 0x000000FF # to indicate that nothing yet set. +LUNA_PED_ID_SCP = 0x0000 +LUNA_PED_ID_MAX = 0xFFFE +LUNA_MAX_PIN_LEN = 256 +LUNA_UTYPE_NONE = 0xFFFFFFFF +LUNA_UTYPE_USER = 0x00000000 +LUNA_UTYPE_SO = 0x00000001 +LUNA_UTYPE_LIMITED_USER = 0x00000005 +LUNA_UTYPE_DOMAIN = 0x00000006 +LUNA_UTYPE_MTK = 0x00000007 +LUNA_UTYPE_AUDIT = 0x00000008 +LUNA_UTYPE_CFG_BASE = 0x80000000 +LUNA_REMOTE_AUTH_LOGIN = 0x00000000 +LUNA_REMOTE_AUTH_M_OF_N = 0x00000001 +LUNA_STYPE_R_W = 0x00000000 +LUNA_STYPE_R_W_EXCLUSIVE = 0x00000001 +LUNA_STYPE_R_O = 0x00000002 +LUNA_STYPE_R_O_EXCLUSIVE = 0x00000003 +LUNA_SACCESS_PUBLIC = 0x00000001 +LUNA_SACCESS_USER = 0x00000002 +LUNA_SACCESS_SO = 0x00000003 +LUNA_PAD_RFC_1423 = 0x00000000 +LUNA_TTYPE_H_W = 0x00000000 +LUNA_TTYPE_CRYPTO = 0x00000001 +LUNA_TTYPE_RNG = 0x00000002 +LUNA_DSS_PRIMALITY_TEST = 0x00000003 +LUNA_DSS_PQG_TEST = 0x00000004 +LUNA_DSS_KEY_TEST = 0x00000005 +LUNA_DSS_SIG_TEST = 0x00000006 +LUNA_DSS_SIGVERIFY_TEST = 0x00000007 +LUNA_DSS_PQGVERIFY_TEST = 0x00000008 +LUNA_HIFN6500_TEST = 0x00000009 +LUNA_TTYPE_RNG_GEN = 0x0000000a +LUNA_TTYPE_AES_OFB = 0x0000000b +LUNA_ECDSA_KEY_TEST = 0x0000000c +LUNA_ECDSA_SIG_TEST = 0x0000000d +LUNA_ECDSA_SIGVERIFY_TEST = 0x0000000e +LUNA_TTYPE_RSA_X_931_KEY_GEN_TEST = 0x0000000f +LUNA_TTYPE_ARIA_OFB = 0x00000010 +LUNA_TTYPE_COMMUNICATION_PERFORMANCE_TEST = 0x00000011 +LUNA_DSS2_G_GEN_TEST = 0x00000012 +LUNA_TTYPE_RSA_1863_AUX_PRIME_KEY_GEN_TEST = 0x00000013 +LUNA_TTYPE_RSA_1863_ONLY_PRIME_KEY_GEN_TEST = 0x00000014 +LUNA_TTYPE_X9_42_DOMAIN_PARAMETER_GENERATION_TEST = 0x00000015 +LUNA_CTYPE_KCV = 0x00000000 +LUNA_CTYPE_MOFN = 0x00000001 +HA_CMD_GET_LOGIN_CHALLENGE = 0x01 +HA_CMD_ANSWER_LOGIN_CHALLENGE = 0x02 +HA_CMD_LOGIN = 0x03 +HA_CMD_GET_MOFN_CHALLENGE = 0x11 +HA_CMD_ANSWER_MOFN_CHALLENGE = 0x12 +HA_CMD_MOFN_ACTIVATE = 0x13 +LUNA_MASKING_KEY_PID = 24 +LUNA_MAC_PID = 43 # Manufacturer Authentication Certificate +LUNA_DAC_FIPS2_MEETS_PID = 44 # Device Authentication Certificate, FIPS2, "meets requirements" +LUNA_DAC_FIPS2_EVAL_PID = 45 # Device Authentication Certificate, FIPS2, "evaluated to" +LUNA_DAC_FIPS3_MEETS_PID = 46 # Device Authentication Certificate, FIPS3, "meets requirements" +LUNA_DAC_FIPS3_EVAL_PID = 47 # Device Authentication Certificate, FIPS3, "evaluated to" +LUNA_CUST_MAC_PID = 48 # Customer Manufacturer Authentication Certificate +LUNA_CUST_DAC_FIPS2_MEETS_PID = 49 # Customer Device Authentication Certificate, FIPS2, "meets requirements" +LUNA_CUST_DAC_FIPS2_EVAL_PID = 50 # Customer Device Authentication Certificate, FIPS2, "evaluated to" +LUNA_CUST_DAC_FIPS3_MEETS_PID = 51 # Customer Device Authentication Certificate, FIPS3, "meets requirements" +LUNA_CUST_DAC_FIPS3_EVAL_PID = 52 # Customer Device Authentication Certificate, FIPS3, "evaluated to" +LUNA_SSK_PID = 54 # Secure Signing Key +LUNA_ECC_MIC_PID = 60 # ECC Manufacturer Authentication Certificate +LUNA_ECC_HOK_PID = 61 # ECC Hardware Origin Key +LUNA_ECC_HOC_PID = 62 # ECC Hardware Origin Certificate +LUNA_ECC_DAK_PID = 63 # ECC Device Authentication Key +LUNA_ECC_DAC_PID = 64 # ECC Device Authentication Certificate +CA_MASK_DES3_RC4 = 0x00000001 +CA_MASK_SHA1_AES_RC4 = 0x00000002 +LUNA_MAX_CHALLENGE_SIZE = 64 +LUNA_MAX_CHALLENGE_RESPONSE_SIZE = 64 +LUNA_CHALLENGE_CLASS_AUTHENTICATION = 0x00000000 +LUNA_CHALLENGE_CLASS_SIM = 0x00000001 +LUNA_CHALLENGE_TYPE_NULL = 0x00000000 +LUNA_CHALLENGE_TYPE_SECRET_HASH = 0x00000001 # Obsolete -- didn't satisfy NIST +LUNA_CHALLENGE_TYPE_ENCRYPTED_SECRET_HASH = 0x00000002 +LUNA_CHALLENGE_TYPE_SO = LUNA_UTYPE_SO +LUNA_CHALLENGE_TYPE_USER = LUNA_UTYPE_USER +LUNA_CHALLENGE_TYPE_LIMITED_USER = LUNA_UTYPE_LIMITED_USER +LUNA_CHALLENGE_TYPE_AUDIT = LUNA_UTYPE_AUDIT +LUNA_SIM_NO_AUTHORIZATION = 0 # no authorization needed +LUNA_SIM_PASSWORD = 1 # plain-text passwords +LUNA_SIM_CHALLENGE = 2 # challenge secrets emitted through the secure port +LUNA_SIM_SECURE_PORT = 3 # PED keys +LUNA_SIM_PORTABLE_NO_AUTHORIZATION = 4 # no authorization needed +LUNA_SIM_PORTABLE_PASSWORD = 5 # plain-text passwords +LUNA_SIM_PORTABLE_CHALLENGE = 6 # challenge secrets emitted through the secure port +LUNA_SIM_PORTABLE_SECURE_PORT = 7 # PED keys +MAX_SIM_OBJECTS = 2048 +CONTAINER_CONFIG_PRIVATE_KEY_CLONING = 0 +CONTAINER_CONFIG_PRIVATE_KEY_WRAPPING = 1 +CONTAINER_CONFIG_PRIVATE_KEY_UNWRAPPING = 2 +CONTAINER_CONFIG_PRIVATE_KEY_MASKING = 3 +CONTAINER_CONFIG_SECRET_KEY_CLONING = 4 +CONTAINER_CONFIG_SECRET_KEY_WRAPPING = 5 +CONTAINER_CONFIG_SECRET_KEY_UNWRAPPING = 6 +CONTAINER_CONFIG_SECRET_KEY_MASKING = 7 +CONTAINER_CONFIG_OBSOLETE_1 = 8 +CONTAINER_CONFIG_OBSOLETE_2 = 9 +CONTAINER_CONFIG_MULTIPURPOSE_KEYS = 10 +CONTAINER_CONFIG_CHANGE_KEY_ATTRIBUTES = 11 +CONTAINER_CONFIG_OBSOLETE_3 = 12 +CONTAINER_CONFIG_OBSOLETE_4 = 13 +CONTAINER_CONFIG_FAILED_CHALLENGE_COUNTER = 15 +CONTAINER_CONFIG_NO_RSA_BLINDING = 16 +CONTAINER_CONFIG_NONLOCAL_SIGNING_KEYS = 17 +CONTAINER_CONFIG_RAW_RSA_OPERATIONS = 18 +CONTAINER_CONFIG_KEY_STORAGE_SPACE = 19 # Obsolete as of f/w 6.0.2 +CONTAINER_CONFIG_MAX_FAILED_USER_LOGINS_ALLOWED = 20 +CONTAINER_CONFIG_HIGH_AVAILABILITY = 21 +CONTAINER_CONFIG_ACTIVATION = 22 +CONTAINER_CONFIG_AUTO_ACTIVATION = 23 +CONTAINER_CONFIG_INDIRECT_LOGIN = 24 # Obsolete as of f/w 5.0 +CONTAINER_CONFIG_MINIMUM_PIN_LENGTH = 25 +CONTAINER_CONFIG_MAXIMUM_PIN_LENGTH = 26 +CONTAINER_CONFIG_OBSOLETE_5 = 27 # CONTAINER_CONFIG_RA_TYPE_WRAPPING +CONTAINER_CONFIG_KEY_MANAGEMENT_FUNCTIONS = 28 +CONTAINER_CONFIG_RSA_SIGNATURE_CONFIRMATION = 29 +CONTAINER_CONFIG_REMOTE_AUTHENTICATION = 30 +CONTAINER_CONFIG_PRIVATE_KEY_UNMASKING = 31 +CONTAINER_CONFIG_SECRET_KEY_UNMASKING = 32 +CONTAINER_CONFIG_RSA_PKCS_MECHANISM = 33 +CONTAINER_CONFIG_CBC_PAD_WRAP_UNWRAP_KEYS_OF_ANY_SIZE = 34 +CONTAINER_CONFIG_PRIVATE_KEY_SMALL_FORM_FACTOR = 35 +CONTAINER_CONFIG_SECRET_KEY_SMALL_FORM_FACTOR = 36 +CONTAINER_CONFIG_SECURE_TRUSTED_CHANNEL = 37 +HSM_CONFIG_ENABLE_PIN_AUTHENTICATION = 0 +HSM_CONFIG_ENABLE_PED_AUTHENTICATION = 1 +HSM_CONFIG_PERFORMANCE_LEVEL = 2 +HSM_CONFIG_M_OF_N = 3 # Obsolete +HSM_CONFIG_DOMESTIC = 4 +HSM_CONFIG_CAV_USED = 5 +HSM_CONFIG_MASKING = 6 +HSM_CONFIG_CLONING = 7 +HSM_CONFIG_SPECIAL_CLONING = 8 # Obsolete +HSM_CONFIG_NONBACKUP_TOKEN = 9 +HSM_CONFIG_OBSOLETE_2 = 10 +HSM_CONFIG_ECC = 11 +HSM_CONFIG_NONFIPS_ALGORITHMS = 12 +HSM_CONFIG_MOFN_AUTO_ACTIVATION = 13 # Obsolete +HSM_CONFIG_OBSOLETE_3 = 14 +HSM_CONFIG_SO_CAN_RESET_PIN = 15 +HSM_CONFIG_NETWORK_REPLICATION = 16 +HSM_CONFIG_KOREAN = 17 +HSM_CONFIG_FIPS_EVALUATED = 18 +HSM_CONFIG_MANUFACT_TOKEN = 19 +HSM_CONFIG_REMOTE_AUTHENTICATION = 20 +HSM_CONFIG_FORCE_USER_PIN_CHANGE = 21 +HSM_CONFIG_OFFBOARD_STORAGE = 22 +HSM_CONFIG_ENABLE_PARTITION_GROUPS = 23 +HSM_CONFIG_ENABLE_NONFIPS_ACCELERATOR = 24 +HSM_CONFIG_ENABLE_REMOTE_PED_USAGE = 25 +HSM_CONFIG_STORE_MTK_SPLIT_EXTERNALLY = 26 +HSM_CONFIG_STORAGE_SIZE = 27 +HSM_CONFIG_OBSOLETE_28 = 28 +HSM_CONFIG_ENABLE_ACCELERATION = 29 +HSM_CONFIG_UNMASKING = 30 +HSM_CONFIG_ENABLE_FW5_COMPATIBILITY = 31 +HSM_CONFIG_ALLOWS_PUBLIC_CRYPTO = 32 +HSM_CONFIG_MAX_PARTITIONS = 33 +HSM_CONFIG_ENABLE_ECIES = 34 +HSM_CONFIG_ENABLE_SINGLE_DOMAIN = 35 +HSM_CONFIG_ALLOW_UNIFIED_PED_KEY = 36 +HSM_CONFIG_ALLOW_MOFN = 37 +HSM_CONFIG_ENABLE_SMALL_FORM_FACTOR_BACKUP = 38 +HSM_CONFIG_ENABLE_SECURE_TRUSTED_CHANNEL = 39 +HSM_CONFIG_DECOMMISSION_ON_TAMPER = 40 +HSM_CONFIG_PER_PARTITION_SO = 41 +HSM_CONFIG_ENABLE_PARTITION_REINIT = 42 +LUNA_CLONING_PART2_OVERHEAD = 76 +LUNA_FLATTENED_OBJECT_OVERHEAD = 3264 +LEGACY_TWC_ACCESS_LEVEL = 1 +LUNA_LICENSE_TYPE_CONTAINER_PERSONALITY = 0 +LUNA_LICENSE_TYPE_HSM_UPGRADE = 1 +LUNA_LICENSE_TYPE = 2 +LICENSE_DESCRIPTION_SIZE = 60 +PERSONALITY_NAME_SIZE = 60 +UPGRADE_DESCRIPTION_SIZE = 60 +LUNA_MAX_ROLE_NAME_LEN = 24 +LUNA_MAX_PRP_LABEL_LEN = 24 +LUNA_MAX_ROLES_PER_PARTITION = 4 +LUNA_MAX_PRP_PER_SET = 3 +LUNA_NULL_ELEMENT = 0x00000000 +LUNA_CRYPTOKI_ELEMENT = 0x00000001 +LUNA_PARAM_ELEMENT = 0x00000002 +LUNA_CONTAINER_ACTIVATION_ELEMENT = 0x00000003 +LUNA_MOFN_ACTIVATION_ELEMENT = 0x00000004 +LUNA_CONTAINER_ELEMENT = 0x00000005 +LUNA_USER_PARTITION_ELEMENT = 0x00000006 +LUNA_UNKNOWN_ELEMENT = (-1) +LUNA_FW4_CRYPTOKI_ELEMENT = 0x00000000 +LUNA_FW4_PARAM_ELEMENT = 0x00000001 +LUNA_FW4_CONTAINER_ACTIVATION_ELEMENT = 0x00000002 +LUNA_FW4_MOFN_ACTIVATION_ELEMENT = 0x00000003 +LUNA_HW_UNDEFINED = 0x00000000 +LUNA_HW_K3_PCI = 0x00000001 +LUNA_HW_K4_PCI = 0x00000002 +LUNA_HW_G3_PCMCIA = 0x00000003 +LUNA_HW_G4_PCMCIA = 0x00000004 +LUNA_HW_G5_USB = 0x00000005 +LUNA_HW_K5_PCI = 0x00000006 +LUNA_HW_PS_PCI = 0x00000007 +LUNA_HW_SSM = 0x00000008 +LUNA_HW_K6_PCI = 0x00000009 +LUNA_STORAGE_SHIFT = 0 +LUNA_STORAGE_MASK = (0x03 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_DEFAULT = (0x00 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_FLASH = (0x01 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_RAM = (0x02 << LUNA_STORAGE_SHIFT) +LUNA_STORAGE_CACHE = (0x03 << LUNA_STORAGE_SHIFT) +LUNA_PARTITION_TYPE_SHIFT = 2 +LUNA_PARTITION_TYPE_MASK = (0x03 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_PARTITION_TYPE_STANDALONE = (0x00 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_PARTITION_TYPE_GROUP = (0x01 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_PARTITION_TYPE_ADMIN = (0x03 << LUNA_PARTITION_TYPE_SHIFT) +LUNA_CONTAINER_TYPE_GROUP = LUNA_PARTITION_TYPE_GROUP +LUNA_CONTAINER_TYPE_STANDALONE = LUNA_PARTITION_TYPE_STANDALONE +LUNA_INSERTION_UNINITIALIZED = 0x10 +LUNA_ENABLE_MEMBER_CONTAINER = 0x01 +LUNA_DISABLE_MEMBER_CONTAINER = 0x02 +LUNA_UNAUTH_CMD_CONTEXT_CREATE = 0x01 +LUNA_UNAUTH_CMD_CONTEXT_DELETE = 0x02 +LUNA_UNAUTH_CMD_CONTEXT_GET = 0x03 +LUNA_PKCS5_PBKD2_HMAC_SHA1 = 0x00000001 +LUNA_SALT_SOURCE_SPECIFIED = 0x00000001 +LUNA_KDF_NULL = 0x00000001 +LUNA_KDF_SHA1_KDF = 0x00000002 +LUNA_KDF_SHA1_KDF_ASN1_X9_42 = 0x00000003 +LUNA_KDF_SHA1_KDF_CONCATENATE_X9_42 = 0x00000004 +LUNA_KDF_SHA1_KDF_CONCATENATE_NIST = 0x80000001 +LUNA_KDF_SHA1_KDF_ASN1_NIST = 0x80000002 +LUNA_KDF_SHA224_KDF = 0x80000003 +LUNA_KDF_SHA256_KDF = 0x80000004 +LUNA_KDF_SHA384_KDF = 0x80000005 +LUNA_KDF_SHA512_KDF = 0x80000006 +LUNA_KDF_RIPEMD160_KDF = 0x80000007 +LUNA_KDF_SHA1_NIST_KDF = 0x00000012 +LUNA_KDF_SHA224_NIST_KDF = 0x80000013 +LUNA_KDF_SHA256_NIST_KDF = 0x80000014 +LUNA_KDF_SHA384_NIST_KDF = 0x80000015 +LUNA_KDF_SHA512_NIST_KDF = 0x80000016 +LUNA_KDF_RIPEMD160_NIST_KDF = 0x80000017 +LUNA_KDF_SHA1_SES_KDF = 0x82000000 +LUNA_KDF_SHA224_SES_KDF = 0x83000000 +LUNA_KDF_SHA256_SES_KDF = 0x84000000 +LUNA_KDF_SHA384_SES_KDF = 0x85000000 +LUNA_KDF_SHA512_SES_KDF = 0x86000000 +LUNA_KDF_RIPEMD160_SES_KDF = 0x87000000 +LUNA_KDF_SES_ENC_CTR = 0x00000001 +LUNA_KDF_SES_AUTH_CTR = 0x00000002 +LUNA_KDF_SES_ALT_ENC_CTR = 0x00000003 +LUNA_KDF_SES_ALT_AUTH_CTR = 0x00000004 +LUNA_KDF_SES_MAX_CTR_MASK = 0x0000FFFF +LUNA_PRF_KDF_DES3_CMAC = 0x00000001 +LUNA_PRF_KDF_AES_CMAC = 0x00000002 +LUNA_PRF_KDF_ARIA_CMAC = 0x00000003 +LUNA_PRF_KDF_SEED_CMAC = 0x00000004 +LUNA_PRF_KDF_ENCODING_SCHEME_1 = 0x00000000 +LUNA_PRF_KDF_ENCODING_SCHEME_2 = 0x00000001 +CB_CMD_TEST = 0x00000000 +CB_CMD_TEST_UPLOAD = 0x00000001 +CB_CMD_TEST_DOWNLOAD = 0x00000002 +CB_CMD_TEST_PING = 0x00000003 +CB_CMD_RPED_READ = 0x00000001 +CB_CMD_RPED_WRITE = 0x00000002 +CB_CMD_RPED_GET_STATUS = 0x00000003 +CB_CMD_RPED_RESET_PED = 0x00000004 +CB_CMD_LOG = 0x00000005 +LUNA_PED_CMD_GET_RAW_DATA = 0x00000000 +LUNA_PED_CMD_SET_RAW_DATA = 0x00000001 +MTK_STATE_FLAG_RESPLIT_ABORTED = 0x00000001 +MTK_STATE_FLAG_HARD_ZEROIZE = 0x00000002 +MTK_STATE_FLAG_SOFT_ZEROIZE = 0x00000004 +MTK_STATE_FLAG_LOCKED = 0x00000008 +LUNA_TSV_DOMESTIC_FLAG = 0x80 +LUNA_TSV_MISSING_MTK_FLAG = 0x40 +LUNA_TSV_CLONING_ENABLED_FLAG = 0x20 +LUNA_TSV_ERASURE_FLAG = 0x10 +LUNA_TSV_AUDIT_CONTAINER_ZEROIZED = 0x08 +LUNA_TSV_TLO_FLAG = 0x04 +LUNA_TSV_CVK_FLAG = 0x02 +LUNA_TSV_HOK_FLAG = 0x01 +LUNA_TSV_TUK_FLAG_LO = 0x80 +LUNA_TSV_TWC_FLAG_LO = 0x40 +LUNA_TSV_KCV_FLAG_LO = 0x20 +LUNA_TSV_FLAG_LO_VOLATILE_MASK = 0x1F +LUNA_TSV_MASKING_KEY_SET = 0x10 +LUNA_TSV_VOLATILE_TOKENRW_MASK = 0x0C +LUNA_TSV_VOLATILE_TOKENRW_IS_NULL = 0x00 +LUNA_TSV_VOLATILE_TOKENRW_IS_READ_ONLY = 0x04 +LUNA_TSV_VOLATILE_TOKENRW_IS_READ_WRITE = 0x08 +LUNA_TSV_VOLATILE_ACCESS_MASK = 0x03 +LUNA_TSV_VOLATILE_ACCESS_IS_NULL = 0x00 +LUNA_TSV_VOLATILE_ACCESS_IS_PUBLIC = 0x01 +LUNA_TSV_VOLATILE_ACCESS_IS_USER = 0x02 +LUNA_TSV_VOLATILE_ACCESS_IS_SO = 0x03 +LUNA_TSV_VOLATILE_ACCESS_IS_AUDIT = 0x04 +LUNA_TSV_FATAL_ERROR_MASK = 0xF0 +LUNA_TSV_CRC_ERROR_FLAG = 0x80 +LUNA_TSV_RNG_ERROR_FLAG = 0x40 +LUNA_TSV_MEM_ERROR_FLAG = 0x20 +LUNA_TSV_DEV_ERROR_FLAG = 0x10 +LUNA_TSV_TOSM_MASK = 0x0F +LUNA_TSV_TOSM_BLANK = 0x00 +LUNA_TSV_TOSM_ZEROIZED = 0x01 +LUNA_TSV_TOSM_FUNCTIONAL = 0x02 +LUNA_TSV_TOSM_ERROR = 0x03 +LUNA_MODIFY_USAGE_COUNT_TYPE_INCREMENT = 0x00000001 +LUNA_MODIFY_USAGE_COUNT_TYPE_SET = 0x00000002 +LUNA_CKDHP_ECDH1_COFACTOR = 0x00000001 +LUNA_CKDHP_MODIFIED = 0x00000002 # Not implemented */ +LUNA_CKDHP_ECDH1 = 0x00000003 +LUNA_CKES_XOR = 0x00000001 +LUNA_CKES_DES3_CBC_PAD = 0x00000002 +LUNA_CKES_AES_CBC_PAD = 0x00000003 +LUNA_CKES_DES3_CBC = 0x00000004 +LUNA_CKES_AES_CBC = 0x00000005 +LUNA_CKMS_HMAC_SHA1 = 0x00000001 +LUNA_CKMS_SHA1 = 0x00000002 +LUNA_CKMS_HMAC_SHA224 = 0x00000003 +LUNA_CKMS_SHA224 = 0x00000004 +LUNA_CKMS_HMAC_SHA256 = 0x00000005 +LUNA_CKMS_SHA256 = 0x00000006 +LUNA_CKMS_HMAC_SHA384 = 0x00000007 +LUNA_CKMS_SHA384 = 0x00000008 +LUNA_CKMS_HMAC_SHA512 = 0x00000009 +LUNA_CKMS_SHA512 = 0x0000000a +LUNA_CKMS_HMAC_RIPEMD160 = 0x0000000b +LUNA_CKMS_RIPEMD160 = 0x0000000c +LUNA_DUKPT_PARAM_LEN = 10 # KSN parameter is 10 bytes */ +LUNA_LOG_WRITE = 0x000000c1 +LUNA_LOG_POLL_HOST = 0x000000c2 # This one is both internal and external, between the host & f/w, so it's defined above +LUNA_LOG_SET_CONFIG = 0x000000c5 # This one is both internal and external, between the host & f/w, so it's defined above +LUNA_LOG_RESYNC = 0x000000c8 +LUNA_STATS_NONE = 0 +LUNA_STATS_BOOT_TIME = 1 +LUNA_STATS_CPU_UP_TIME = 2 +LUNA_STATS_CPU_IDLE_TIME = 3 +LUNA_STATS_ICD_COMMANDS_COUNT = 4 +LUNA_STATS_UNKNOWN = 0xffffffff +PED_PASSWORD_LENGTH = 8 '''/home/new_builds/1175/101/tools/ekmtest/token.h''' -MAX_BUF_SIZE= 32000 -MAX_SLOT_COUNT= 20 -MAX_SESSION_COUNT= 20 -MAX_KEY_HANDLES= 10000000 -SIGNING_PART_SIZE= 0x8000 -BENCHMARK= 1 -MAX_RSA_KEY_NBITS= 8192 -LAST_MENU_ITEM= 204 -MAX_FILE_NAME_SIZE= 512 # bytes */ -XOR_KDF_MAX_SHARED_DATALEN= 512 # max. amount of shared data allowed +MAX_BUF_SIZE = 32000 +MAX_SLOT_COUNT = 20 +MAX_SESSION_COUNT = 20 +MAX_KEY_HANDLES = 10000000 +SIGNING_PART_SIZE = 0x8000 +BENCHMARK = 1 +MAX_RSA_KEY_NBITS = 8192 +LAST_MENU_ITEM = 204 +MAX_FILE_NAME_SIZE = 512 # bytes */ +XOR_KDF_MAX_SHARED_DATALEN = 512 # max. amount of shared data allowed '''/home/new_builds/1175/101/interfaces/Include/RSA/pkcs11t.h''' -CRYPTOKI_VERSION_MAJOR=2 -CRYPTOKI_VERSION_MINOR=20 -CRYPTOKI_VERSION_AMENDMENT=3 -CK_TRUE=1 -CK_FALSE=0 -FALSE=CK_FALSE -TRUE=CK_TRUE -CK_EFFECTIVELY_INFINITE= 0 -CK_INVALID_HANDLE=0 -CKN_SURRENDER= 0 -CKN_OTP_CHANGED= 1 -CKF_TOKEN_PRESENT= 0x00000001 # a token is there */ -CKF_REMOVABLE_DEVICE= 0x00000002 # removable devices*/ -CKF_HW_SLOT= 0x00000004 # hardware slot */ -CKF_RNG= 0x00000001 # has random # -CKF_WRITE_PROTECTED= 0x00000002 # token is -CKF_LOGIN_REQUIRED= 0x00000004 # user must -CKF_USER_PIN_INITIALIZED= 0x00000008 # normal user's -CKF_RESTORE_KEY_NOT_NEEDED= 0x00000020 -CKF_CLOCK_ON_TOKEN= 0x00000040 -CKF_PROTECTED_AUTHENTICATION_PATH=0x00000100 -CKF_DUAL_CRYPTO_OPERATIONS= 0x00000200 -CKF_TOKEN_INITIALIZED= 0x00000400 -CKF_SECONDARY_AUTHENTICATION= 0x00000800 -CKF_USER_PIN_COUNT_LOW= 0x00010000 -CKF_USER_PIN_FINAL_TRY= 0x00020000 -CKF_USER_PIN_LOCKED= 0x00040000 -CKF_USER_PIN_TO_BE_CHANGED= 0x00080000 -CKF_SO_PIN_COUNT_LOW= 0x00100000 -CKF_SO_PIN_FINAL_TRY= 0x00200000 -CKF_SO_PIN_LOCKED= 0x00400000 -CKF_SO_PIN_TO_BE_CHANGED= 0x00800000 -CKU_SO= 0 -CKU_USER= 1 -CKU_CONTEXT_SPECIFIC= 2 -CKS_RO_PUBLIC_SESSION= 0 -CKS_RO_USER_FUNCTIONS= 1 -CKS_RW_PUBLIC_SESSION= 2 -CKS_RW_USER_FUNCTIONS= 3 -CKS_RW_SO_FUNCTIONS= 4 -CKF_RW_SESSION= 0x00000002 # session is r/w */ -CKF_SERIAL_SESSION= 0x00000004 # no parallel */ -CKO_DATA= 0x00000000 -CKO_CERTIFICATE= 0x00000001 -CKO_PUBLIC_KEY= 0x00000002 -CKO_PRIVATE_KEY= 0x00000003 -CKO_SECRET_KEY= 0x00000004 -CKO_HW_FEATURE= 0x00000005 -CKO_DOMAIN_PARAMETERS=0x00000006 -CKO_MECHANISM= 0x00000007 -CKO_OTP_KEY= 0x00000008 -CKO_VENDOR_DEFINED= 0x80000000 -CKH_MONOTONIC_COUNTER= 0x00000001 -CKH_CLOCK= 0x00000002 -CKH_USER_INTERFACE= 0x00000003 -CKH_VENDOR_DEFINED= 0x80000000 -CKK_RSA= 0x00000000 -CKK_DSA= 0x00000001 -CKK_DH= 0x00000002 -CKK_ECDSA= 0x00000003 -CKK_EC= 0x00000003 -CKK_X9_42_DH= 0x00000004 -CKK_KEA= 0x00000005 -CKK_GENERIC_SECRET= 0x00000010 -CKK_RC2= 0x00000011 -CKK_RC4= 0x00000012 -CKK_DES= 0x00000013 -CKK_DES2= 0x00000014 -CKK_DES3= 0x00000015 -CKK_CAST= 0x00000016 -CKK_CAST3= 0x00000017 -CKK_CAST5= 0x00000018 -CKK_CAST128= 0x00000018 -CKK_RC5= 0x00000019 -CKK_IDEA= 0x0000001A -CKK_SKIPJACK= 0x0000001B -CKK_BATON= 0x0000001C -CKK_JUNIPER= 0x0000001D -CKK_CDMF= 0x0000001E -CKK_AES= 0x0000001F -CKK_BLOWFISH= 0x00000020 -CKK_TWOFISH= 0x00000021 -CKK_SECURID= 0x00000022 -CKK_HOTP= 0x00000023 -CKK_ACTI= 0x00000024 -CKK_CAMELLIA= 0x00000025 -CKK_ARIA= 0x00000026 -CKK_VENDOR_DEFINED= 0x80000000 -CKC_X_509= 0x00000000 -CKC_X_509_ATTR_CERT=0x00000001 -CKC_WTLS= 0x00000002 -CKC_VENDOR_DEFINED= 0x80000000 -CKF_ARRAY_ATTRIBUTE= 0x40000000 -CK_OTP_FORMAT_DECIMAL= 0 -CK_OTP_FORMAT_HEXADECIMAL= 1 -CK_OTP_FORMAT_ALPHANUMERIC=2 -CK_OTP_FORMAT_BINARY= 3 -CK_OTP_PARAM_IGNORED= 0 -CK_OTP_PARAM_OPTIONAL= 1 -CK_OTP_PARAM_MANDATORY= 2 -CKA_CLASS= 0x00000000 -CKA_TOKEN= 0x00000001 -CKA_PRIVATE= 0x00000002 -CKA_LABEL= 0x00000003 -CKA_APPLICATION= 0x00000010 -CKA_VALUE= 0x00000011 -CKA_OBJECT_ID= 0x00000012 -CKA_CERTIFICATE_TYPE= 0x00000080 -CKA_ISSUER= 0x00000081 -CKA_SERIAL_NUMBER= 0x00000082 -CKA_AC_ISSUER= 0x00000083 -CKA_OWNER= 0x00000084 -CKA_ATTR_TYPES= 0x00000085 -CKA_TRUSTED= 0x00000086 -CKA_CERTIFICATE_CATEGORY= 0x00000087 -CKA_JAVA_MIDP_SECURITY_DOMAIN= 0x00000088 -CKA_URL= 0x00000089 -CKA_HASH_OF_SUBJECT_PUBLIC_KEY= 0x0000008A -CKA_HASH_OF_ISSUER_PUBLIC_KEY= 0x0000008B -CKA_CHECK_VALUE= 0x00000090 -CKA_KEY_TYPE= 0x00000100 -CKA_SUBJECT= 0x00000101 -CKA_ID= 0x00000102 -CKA_SENSITIVE= 0x00000103 -CKA_ENCRYPT= 0x00000104 -CKA_DECRYPT= 0x00000105 -CKA_WRAP= 0x00000106 -CKA_UNWRAP= 0x00000107 -CKA_SIGN= 0x00000108 -CKA_SIGN_RECOVER= 0x00000109 -CKA_VERIFY= 0x0000010A -CKA_VERIFY_RECOVER= 0x0000010B -CKA_DERIVE= 0x0000010C -CKA_START_DATE= 0x00000110 -CKA_END_DATE= 0x00000111 -CKA_MODULUS= 0x00000120 -CKA_MODULUS_BITS= 0x00000121 -CKA_PUBLIC_EXPONENT= 0x00000122 -CKA_PRIVATE_EXPONENT= 0x00000123 -CKA_PRIME_1= 0x00000124 -CKA_PRIME_2= 0x00000125 -CKA_EXPONENT_1= 0x00000126 -CKA_EXPONENT_2= 0x00000127 -CKA_COEFFICIENT= 0x00000128 -CKA_PRIME= 0x00000130 -CKA_SUBPRIME= 0x00000131 -CKA_BASE= 0x00000132 -CKA_PRIME_BITS= 0x00000133 -CKA_SUBPRIME_BITS= 0x00000134 -CKA_SUB_PRIME_BITS= CKA_SUBPRIME_BITS -CKA_VALUE_BITS= 0x00000160 -CKA_VALUE_LEN= 0x00000161 -CKA_EXTRACTABLE= 0x00000162 -CKA_LOCAL= 0x00000163 -CKA_NEVER_EXTRACTABLE= 0x00000164 -CKA_ALWAYS_SENSITIVE= 0x00000165 -CKA_KEY_GEN_MECHANISM= 0x00000166 -CKA_MODIFIABLE= 0x00000170 -CKA_ECDSA_PARAMS= 0x00000180 -CKA_EC_PARAMS= 0x00000180 -CKA_EC_POINT= 0x00000181 -CKA_SECONDARY_AUTH= 0x00000200 -CKA_AUTH_PIN_FLAGS= 0x00000201 -CKA_ALWAYS_AUTHENTICATE= 0x00000202 -CKA_WRAP_WITH_TRUSTED= 0x00000210 -CKA_WRAP_TEMPLATE= (CKF_ARRAY_ATTRIBUTE|0x00000211) -CKA_UNWRAP_TEMPLATE= (CKF_ARRAY_ATTRIBUTE|0x00000212) -CKA_OTP_FORMAT= 0x00000220 -CKA_OTP_LENGTH= 0x00000221 -CKA_OTP_TIME_INTERVAL= 0x00000222 -CKA_OTP_USER_FRIENDLY_MODE= 0x00000223 -CKA_OTP_CHALLENGE_REQUIREMENT=0x00000224 -CKA_OTP_TIME_REQUIREMENT= 0x00000225 -CKA_OTP_COUNTER_REQUIREMENT= 0x00000226 -CKA_OTP_PIN_REQUIREMENT= 0x00000227 -CKA_OTP_COUNTER= 0x0000022E -CKA_OTP_TIME= 0x0000022F -CKA_OTP_USER_IDENTIFIER= 0x0000022A -CKA_OTP_SERVICE_IDENTIFIER= 0x0000022B -CKA_OTP_SERVICE_LOGO= 0x0000022C -CKA_OTP_SERVICE_LOGO_TYPE= 0x0000022D -CKA_HW_FEATURE_TYPE= 0x00000300 -CKA_RESET_ON_INIT= 0x00000301 -CKA_HAS_RESET= 0x00000302 -CKA_PIXEL_X= 0x00000400 -CKA_PIXEL_Y= 0x00000401 -CKA_RESOLUTION= 0x00000402 -CKA_CHAR_ROWS= 0x00000403 -CKA_CHAR_COLUMNS= 0x00000404 -CKA_COLOR= 0x00000405 -CKA_BITS_PER_PIXEL= 0x00000406 -CKA_CHAR_SETS= 0x00000480 -CKA_ENCODING_METHODS= 0x00000481 -CKA_MIME_TYPES= 0x00000482 -CKA_MECHANISM_TYPE= 0x00000500 -CKA_REQUIRED_CMS_ATTRIBUTES= 0x00000501 -CKA_DEFAULT_CMS_ATTRIBUTES= 0x00000502 -CKA_SUPPORTED_CMS_ATTRIBUTES= 0x00000503 -CKA_ALLOWED_MECHANISMS= (CKF_ARRAY_ATTRIBUTE|0x00000600) -CKA_VENDOR_DEFINED= 0x80000000 -CKM_RSA_PKCS_KEY_PAIR_GEN= 0x00000000 -CKM_RSA_PKCS= 0x00000001 -CKM_RSA_9796= 0x00000002 -CKM_RSA_X_509= 0x00000003 -CKM_MD2_RSA_PKCS= 0x00000004 -CKM_MD5_RSA_PKCS= 0x00000005 -CKM_SHA1_RSA_PKCS= 0x00000006 -CKM_RIPEMD128_RSA_PKCS= 0x00000007 -CKM_RIPEMD160_RSA_PKCS= 0x00000008 -CKM_RSA_PKCS_OAEP= 0x00000009 -CKM_RSA_X9_31_KEY_PAIR_GEN= 0x0000000A -CKM_RSA_X9_31= 0x0000000B -CKM_SHA1_RSA_X9_31= 0x0000000C -CKM_RSA_PKCS_PSS= 0x0000000D -CKM_SHA1_RSA_PKCS_PSS= 0x0000000E -CKM_DSA_KEY_PAIR_GEN= 0x00000010 -CKM_DSA= 0x00000011 -CKM_DSA_SHA1= 0x00000012 -CKM_DH_PKCS_KEY_PAIR_GEN= 0x00000020 -CKM_DH_PKCS_DERIVE= 0x00000021 -CKM_X9_42_DH_KEY_PAIR_GEN= 0x00000030 -CKM_X9_42_DH_DERIVE= 0x00000031 -CKM_X9_42_DH_HYBRID_DERIVE= 0x00000032 -CKM_X9_42_MQV_DERIVE= 0x00000033 -CKM_SHA256_RSA_PKCS= 0x00000040 -CKM_SHA384_RSA_PKCS= 0x00000041 -CKM_SHA512_RSA_PKCS= 0x00000042 -CKM_SHA256_RSA_PKCS_PSS= 0x00000043 -CKM_SHA384_RSA_PKCS_PSS= 0x00000044 -CKM_SHA512_RSA_PKCS_PSS= 0x00000045 -CKM_SHA224_RSA_PKCS= 0x00000046 -CKM_SHA224_RSA_PKCS_PSS= 0x00000047 -CKM_RC2_KEY_GEN= 0x00000100 -CKM_RC2_ECB= 0x00000101 -CKM_RC2_CBC= 0x00000102 -CKM_RC2_MAC= 0x00000103 -CKM_RC2_MAC_GENERAL= 0x00000104 -CKM_RC2_CBC_PAD= 0x00000105 -CKM_RC4_KEY_GEN= 0x00000110 -CKM_RC4= 0x00000111 -CKM_DES_KEY_GEN= 0x00000120 -CKM_DES_ECB= 0x00000121 -CKM_DES_CBC= 0x00000122 -CKM_DES_MAC= 0x00000123 -CKM_DES_MAC_GENERAL= 0x00000124 -CKM_DES_CBC_PAD= 0x00000125 -CKM_DES2_KEY_GEN= 0x00000130 -CKM_DES3_KEY_GEN= 0x00000131 -CKM_DES3_ECB= 0x00000132 -CKM_DES3_CBC= 0x00000133 -CKM_DES3_MAC= 0x00000134 -CKM_DES3_MAC_GENERAL= 0x00000135 -CKM_DES3_CBC_PAD= 0x00000136 -CKM_DES3_CMAC_GENERAL= 0x00000137 -CKM_DES3_CMAC= 0x00000138 -CKM_CDMF_KEY_GEN= 0x00000140 -CKM_CDMF_ECB= 0x00000141 -CKM_CDMF_CBC= 0x00000142 -CKM_CDMF_MAC= 0x00000143 -CKM_CDMF_MAC_GENERAL= 0x00000144 -CKM_CDMF_CBC_PAD= 0x00000145 -CKM_DES_OFB64= 0x00000150 -CKM_DES_OFB8= 0x00000151 -CKM_DES_CFB64= 0x00000152 -CKM_DES_CFB8= 0x00000153 -CKM_MD2= 0x00000200 -CKM_MD2_HMAC= 0x00000201 -CKM_MD2_HMAC_GENERAL= 0x00000202 -CKM_MD5= 0x00000210 -CKM_MD5_HMAC= 0x00000211 -CKM_MD5_HMAC_GENERAL= 0x00000212 -CKM_SHA_1= 0x00000220 -CKM_SHA_1_HMAC= 0x00000221 -CKM_SHA_1_HMAC_GENERAL= 0x00000222 -CKM_RIPEMD128= 0x00000230 -CKM_RIPEMD128_HMAC= 0x00000231 -CKM_RIPEMD128_HMAC_GENERAL= 0x00000232 -CKM_RIPEMD160= 0x00000240 -CKM_RIPEMD160_HMAC= 0x00000241 -CKM_RIPEMD160_HMAC_GENERAL= 0x00000242 -CKM_SHA256= 0x00000250 -CKM_SHA256_HMAC= 0x00000251 -CKM_SHA256_HMAC_GENERAL= 0x00000252 -CKM_SHA224= 0x00000255 -CKM_SHA224_HMAC= 0x00000256 -CKM_SHA224_HMAC_GENERAL= 0x00000257 -CKM_SHA384= 0x00000260 -CKM_SHA384_HMAC= 0x00000261 -CKM_SHA384_HMAC_GENERAL= 0x00000262 -CKM_SHA512= 0x00000270 -CKM_SHA512_HMAC= 0x00000271 -CKM_SHA512_HMAC_GENERAL= 0x00000272 -CKM_SECURID_KEY_GEN= 0x00000280 -CKM_SECURID= 0x00000282 -CKM_HOTP_KEY_GEN= 0x00000290 -CKM_HOTP= 0x00000291 -CKM_ACTI= 0x000002A0 -CKM_ACTI_KEY_GEN= 0x000002A1 -CKM_CAST_KEY_GEN= 0x00000300 -CKM_CAST_ECB= 0x00000301 -CKM_CAST_CBC= 0x00000302 -CKM_CAST_MAC= 0x00000303 -CKM_CAST_MAC_GENERAL= 0x00000304 -CKM_CAST_CBC_PAD= 0x00000305 -CKM_CAST3_KEY_GEN= 0x00000310 -CKM_CAST3_ECB= 0x00000311 -CKM_CAST3_CBC= 0x00000312 -CKM_CAST3_MAC= 0x00000313 -CKM_CAST3_MAC_GENERAL= 0x00000314 -CKM_CAST3_CBC_PAD= 0x00000315 -CKM_CAST5_KEY_GEN= 0x00000320 -CKM_CAST128_KEY_GEN= 0x00000320 -CKM_CAST5_ECB= 0x00000321 -CKM_CAST128_ECB= 0x00000321 -CKM_CAST5_CBC= 0x00000322 -CKM_CAST128_CBC= 0x00000322 -CKM_CAST5_MAC= 0x00000323 -CKM_CAST128_MAC= 0x00000323 -CKM_CAST5_MAC_GENERAL= 0x00000324 -CKM_CAST128_MAC_GENERAL= 0x00000324 -CKM_CAST5_CBC_PAD= 0x00000325 -CKM_CAST128_CBC_PAD= 0x00000325 -CKM_RC5_KEY_GEN= 0x00000330 -CKM_RC5_ECB= 0x00000331 -CKM_RC5_CBC= 0x00000332 -CKM_RC5_MAC= 0x00000333 -CKM_RC5_MAC_GENERAL= 0x00000334 -CKM_RC5_CBC_PAD= 0x00000335 -CKM_IDEA_KEY_GEN= 0x00000340 -CKM_IDEA_ECB= 0x00000341 -CKM_IDEA_CBC= 0x00000342 -CKM_IDEA_MAC= 0x00000343 -CKM_IDEA_MAC_GENERAL= 0x00000344 -CKM_IDEA_CBC_PAD= 0x00000345 -CKM_GENERIC_SECRET_KEY_GEN= 0x00000350 -CKM_CONCATENATE_BASE_AND_KEY= 0x00000360 -CKM_CONCATENATE_BASE_AND_DATA= 0x00000362 -CKM_CONCATENATE_DATA_AND_BASE= 0x00000363 -CKM_XOR_BASE_AND_DATA= 0x00000364 -CKM_EXTRACT_KEY_FROM_KEY= 0x00000365 -CKM_SSL3_PRE_MASTER_KEY_GEN= 0x00000370 -CKM_SSL3_MASTER_KEY_DERIVE= 0x00000371 -CKM_SSL3_KEY_AND_MAC_DERIVE= 0x00000372 -CKM_SSL3_MASTER_KEY_DERIVE_DH= 0x00000373 -CKM_TLS_PRE_MASTER_KEY_GEN= 0x00000374 -CKM_TLS_MASTER_KEY_DERIVE= 0x00000375 -CKM_TLS_KEY_AND_MAC_DERIVE= 0x00000376 -CKM_TLS_MASTER_KEY_DERIVE_DH= 0x00000377 -CKM_TLS_PRF= 0x00000378 -CKM_SSL3_MD5_MAC= 0x00000380 -CKM_SSL3_SHA1_MAC= 0x00000381 -CKM_MD5_KEY_DERIVATION= 0x00000390 -CKM_MD2_KEY_DERIVATION= 0x00000391 -CKM_SHA1_KEY_DERIVATION= 0x00000392 -CKM_SHA256_KEY_DERIVATION= 0x00000393 -CKM_SHA384_KEY_DERIVATION= 0x00000394 -CKM_SHA512_KEY_DERIVATION= 0x00000395 -CKM_SHA224_KEY_DERIVATION= 0x00000396 -CKM_PBE_MD2_DES_CBC= 0x000003A0 -CKM_PBE_MD5_DES_CBC= 0x000003A1 -CKM_PBE_MD5_CAST_CBC= 0x000003A2 -CKM_PBE_MD5_CAST3_CBC= 0x000003A3 -CKM_PBE_MD5_CAST5_CBC= 0x000003A4 -CKM_PBE_MD5_CAST128_CBC= 0x000003A4 -CKM_PBE_SHA1_CAST5_CBC= 0x000003A5 -CKM_PBE_SHA1_CAST128_CBC= 0x000003A5 -CKM_PBE_SHA1_RC4_128= 0x000003A6 -CKM_PBE_SHA1_RC4_40= 0x000003A7 -CKM_PBE_SHA1_DES3_EDE_CBC= 0x000003A8 -CKM_PBE_SHA1_DES2_EDE_CBC= 0x000003A9 -CKM_PBE_SHA1_RC2_128_CBC= 0x000003AA -CKM_PBE_SHA1_RC2_40_CBC= 0x000003AB -CKM_PKCS5_PBKD2= 0x000003B0 -CKM_PBA_SHA1_WITH_SHA1_HMAC= 0x000003C0 -CKM_WTLS_PRE_MASTER_KEY_GEN= 0x000003D0 -CKM_WTLS_MASTER_KEY_DERIVE= 0x000003D1 -CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC= 0x000003D2 -CKM_WTLS_PRF= 0x000003D3 -CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE= 0x000003D4 -CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE= 0x000003D5 -CKM_KEY_WRAP_LYNKS= 0x00000400 -CKM_KEY_WRAP_SET_OAEP= 0x00000401 -CKM_CMS_SIG= 0x00000500 -CKM_KIP_DERIVE= 0x00000510 -CKM_KIP_WRAP= 0x00000511 -CKM_KIP_MAC= 0x00000512 -CKM_CAMELLIA_KEY_GEN= 0x00000550 -CKM_CAMELLIA_ECB= 0x00000551 -CKM_CAMELLIA_CBC= 0x00000552 -CKM_CAMELLIA_MAC= 0x00000553 -CKM_CAMELLIA_MAC_GENERAL= 0x00000554 -CKM_CAMELLIA_CBC_PAD= 0x00000555 -CKM_CAMELLIA_ECB_ENCRYPT_DATA= 0x00000556 -CKM_CAMELLIA_CBC_ENCRYPT_DATA= 0x00000557 -CKM_CAMELLIA_CTR= 0x00000558 -CKM_ARIA_KEY_GEN= 0x00000560 -CKM_ARIA_ECB= 0x00000561 -CKM_ARIA_CBC= 0x00000562 -CKM_ARIA_MAC= 0x00000563 -CKM_ARIA_MAC_GENERAL= 0x00000564 -CKM_ARIA_CBC_PAD= 0x00000565 -CKM_ARIA_ECB_ENCRYPT_DATA= 0x00000566 -CKM_ARIA_CBC_ENCRYPT_DATA= 0x00000567 -CKM_SKIPJACK_KEY_GEN= 0x00001000 -CKM_SKIPJACK_ECB64= 0x00001001 -CKM_SKIPJACK_CBC64= 0x00001002 -CKM_SKIPJACK_OFB64= 0x00001003 -CKM_SKIPJACK_CFB64= 0x00001004 -CKM_SKIPJACK_CFB32= 0x00001005 -CKM_SKIPJACK_CFB16= 0x00001006 -CKM_SKIPJACK_CFB8= 0x00001007 -CKM_SKIPJACK_WRAP= 0x00001008 -CKM_SKIPJACK_PRIVATE_WRAP= 0x00001009 -CKM_SKIPJACK_RELAYX= 0x0000100a -CKM_KEA_KEY_PAIR_GEN= 0x00001010 -CKM_KEA_KEY_DERIVE= 0x00001011 -CKM_FORTEZZA_TIMESTAMP= 0x00001020 -CKM_BATON_KEY_GEN= 0x00001030 -CKM_BATON_ECB128= 0x00001031 -CKM_BATON_ECB96= 0x00001032 -CKM_BATON_CBC128= 0x00001033 -CKM_BATON_COUNTER= 0x00001034 -CKM_BATON_SHUFFLE= 0x00001035 -CKM_BATON_WRAP= 0x00001036 -CKM_ECDSA_KEY_PAIR_GEN= 0x00001040 -CKM_EC_KEY_PAIR_GEN= 0x00001040 -CKM_ECDSA= 0x00001041 -CKM_ECDSA_SHA1= 0x00001042 -CKM_ECDH1_DERIVE= 0x00001050 -CKM_ECDH1_COFACTOR_DERIVE= 0x00001051 -CKM_ECMQV_DERIVE= 0x00001052 -CKM_JUNIPER_KEY_GEN= 0x00001060 -CKM_JUNIPER_ECB128= 0x00001061 -CKM_JUNIPER_CBC128= 0x00001062 -CKM_JUNIPER_COUNTER= 0x00001063 -CKM_JUNIPER_SHUFFLE= 0x00001064 -CKM_JUNIPER_WRAP= 0x00001065 -CKM_FASTHASH= 0x00001070 -CKM_AES_KEY_GEN= 0x00001080 -CKM_AES_ECB= 0x00001081 -CKM_AES_CBC= 0x00001082 -CKM_AES_MAC= 0x00001083 -CKM_AES_MAC_GENERAL= 0x00001084 -CKM_AES_CBC_PAD= 0x00001085 -CKM_AES_CTR= 0x00001086 -CKM_AES_CMAC_GENERAL= 0x00001089 -CKM_AES_CMAC= 0x0000108A -CKM_BLOWFISH_KEY_GEN= 0x00001090 -CKM_BLOWFISH_CBC= 0x00001091 -CKM_TWOFISH_KEY_GEN= 0x00001092 -CKM_TWOFISH_CBC= 0x00001093 -CKM_DES_ECB_ENCRYPT_DATA= 0x00001100 -CKM_DES_CBC_ENCRYPT_DATA= 0x00001101 -CKM_DES3_ECB_ENCRYPT_DATA= 0x00001102 -CKM_DES3_CBC_ENCRYPT_DATA= 0x00001103 -CKM_AES_ECB_ENCRYPT_DATA= 0x00001104 -CKM_AES_CBC_ENCRYPT_DATA= 0x00001105 -CKM_DSA_PARAMETER_GEN= 0x00002000 -CKM_DH_PKCS_PARAMETER_GEN= 0x00002001 -CKM_X9_42_DH_PARAMETER_GEN= 0x00002002 -CKM_VENDOR_DEFINED= 0x80000000 -CKF_HW= 0x00000001 # performed by HW */ -CKF_ENCRYPT= 0x00000100 -CKF_DECRYPT= 0x00000200 -CKF_DIGEST= 0x00000400 -CKF_SIGN= 0x00000800 -CKF_SIGN_RECOVER= 0x00001000 -CKF_VERIFY= 0x00002000 -CKF_VERIFY_RECOVER= 0x00004000 -CKF_GENERATE= 0x00008000 -CKF_GENERATE_KEY_PAIR= 0x00010000 -CKF_WRAP= 0x00020000 -CKF_UNWRAP= 0x00040000 -CKF_DERIVE= 0x00080000 -CKF_EC_F_P= 0x00100000 -CKF_EC_F_2M= 0x00200000 -CKF_EC_ECPARAMETERS= 0x00400000 -CKF_EC_NAMEDCURVE= 0x00800000 -CKF_EC_UNCOMPRESS= 0x01000000 -CKF_EC_COMPRESS= 0x02000000 -CKF_EXTENSION= 0x80000000 # FALSE for this version */ -CKR_OK= 0x00000000 -CKR_CANCEL= 0x00000001 -CKR_HOST_MEMORY= 0x00000002 -CKR_SLOT_ID_INVALID= 0x00000003 -CKR_GENERAL_ERROR= 0x00000005 -CKR_FUNCTION_FAILED= 0x00000006 -CKR_ARGUMENTS_BAD= 0x00000007 -CKR_NO_EVENT= 0x00000008 -CKR_NEED_TO_CREATE_THREADS= 0x00000009 -CKR_CANT_LOCK= 0x0000000A -CKR_ATTRIBUTE_READ_ONLY= 0x00000010 -CKR_ATTRIBUTE_SENSITIVE= 0x00000011 -CKR_ATTRIBUTE_TYPE_INVALID= 0x00000012 -CKR_ATTRIBUTE_VALUE_INVALID= 0x00000013 -CKR_DATA_INVALID= 0x00000020 -CKR_DATA_LEN_RANGE= 0x00000021 -CKR_DEVICE_ERROR= 0x00000030 -CKR_DEVICE_MEMORY= 0x00000031 -CKR_DEVICE_REMOVED= 0x00000032 -CKR_ENCRYPTED_DATA_INVALID= 0x00000040 -CKR_ENCRYPTED_DATA_LEN_RANGE= 0x00000041 -CKR_FUNCTION_CANCELED= 0x00000050 -CKR_FUNCTION_NOT_PARALLEL= 0x00000051 -CKR_FUNCTION_NOT_SUPPORTED= 0x00000054 -CKR_KEY_HANDLE_INVALID= 0x00000060 -CKR_KEY_SIZE_RANGE= 0x00000062 -CKR_KEY_TYPE_INCONSISTENT= 0x00000063 -CKR_KEY_NOT_NEEDED= 0x00000064 -CKR_KEY_CHANGED= 0x00000065 -CKR_KEY_NEEDED= 0x00000066 -CKR_KEY_INDIGESTIBLE= 0x00000067 -CKR_KEY_FUNCTION_NOT_PERMITTED= 0x00000068 -CKR_KEY_NOT_WRAPPABLE= 0x00000069 -CKR_KEY_UNEXTRACTABLE= 0x0000006A -CKR_MECHANISM_INVALID= 0x00000070 -CKR_MECHANISM_PARAM_INVALID= 0x00000071 -CKR_OBJECT_HANDLE_INVALID= 0x00000082 -CKR_OPERATION_ACTIVE= 0x00000090 -CKR_OPERATION_NOT_INITIALIZED= 0x00000091 -CKR_PIN_INCORRECT= 0x000000A0 -CKR_PIN_INVALID= 0x000000A1 -CKR_PIN_LEN_RANGE= 0x000000A2 -CKR_PIN_EXPIRED= 0x000000A3 -CKR_PIN_LOCKED= 0x000000A4 -CKR_SESSION_CLOSED= 0x000000B0 -CKR_SESSION_COUNT= 0x000000B1 -CKR_SESSION_HANDLE_INVALID= 0x000000B3 -CKR_SESSION_PARALLEL_NOT_SUPPORTED= 0x000000B4 -CKR_SESSION_READ_ONLY= 0x000000B5 -CKR_SESSION_EXISTS= 0x000000B6 -CKR_SESSION_READ_ONLY_EXISTS= 0x000000B7 -CKR_SESSION_READ_WRITE_SO_EXISTS= 0x000000B8 -CKR_SIGNATURE_INVALID= 0x000000C0 -CKR_SIGNATURE_LEN_RANGE= 0x000000C1 -CKR_TEMPLATE_INCOMPLETE= 0x000000D0 -CKR_TEMPLATE_INCONSISTENT= 0x000000D1 -CKR_TOKEN_NOT_PRESENT= 0x000000E0 -CKR_TOKEN_NOT_RECOGNIZED= 0x000000E1 -CKR_TOKEN_WRITE_PROTECTED= 0x000000E2 -CKR_UNWRAPPING_KEY_HANDLE_INVALID= 0x000000F0 -CKR_UNWRAPPING_KEY_SIZE_RANGE= 0x000000F1 -CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT= 0x000000F2 -CKR_USER_ALREADY_LOGGED_IN= 0x00000100 -CKR_USER_NOT_LOGGED_IN= 0x00000101 -CKR_USER_PIN_NOT_INITIALIZED= 0x00000102 -CKR_USER_TYPE_INVALID= 0x00000103 -CKR_USER_ANOTHER_ALREADY_LOGGED_IN= 0x00000104 -CKR_USER_TOO_MANY_TYPES= 0x00000105 -CKR_WRAPPED_KEY_INVALID= 0x00000110 -CKR_WRAPPED_KEY_LEN_RANGE= 0x00000112 -CKR_WRAPPING_KEY_HANDLE_INVALID= 0x00000113 -CKR_WRAPPING_KEY_SIZE_RANGE= 0x00000114 -CKR_WRAPPING_KEY_TYPE_INCONSISTENT= 0x00000115 -CKR_RANDOM_SEED_NOT_SUPPORTED= 0x00000120 -CKR_RANDOM_NO_RNG= 0x00000121 -CKR_DOMAIN_PARAMS_INVALID= 0x00000130 -CKR_BUFFER_TOO_SMALL= 0x00000150 -CKR_SAVED_STATE_INVALID= 0x00000160 -CKR_INFORMATION_SENSITIVE= 0x00000170 -CKR_STATE_UNSAVEABLE= 0x00000180 -CKR_CRYPTOKI_NOT_INITIALIZED= 0x00000190 -CKR_CRYPTOKI_ALREADY_INITIALIZED= 0x00000191 -CKR_MUTEX_BAD= 0x000001A0 -CKR_MUTEX_NOT_LOCKED= 0x000001A1 -CKR_NEW_PIN_MODE= 0x000001B0 -CKR_NEXT_OTP= 0x000001B1 -CKR_FUNCTION_REJECTED= 0x00000200 -CKR_VENDOR_DEFINED= 0x80000000 -CKF_LIBRARY_CANT_CREATE_OS_THREADS=0x00000001 -CKF_OS_LOCKING_OK= 0x00000002 -CKF_DONT_BLOCK= 1 -CKG_MGF1_SHA1= 0x00000001 -CKG_MGF1_SHA256= 0x00000002 -CKG_MGF1_SHA384= 0x00000003 -CKG_MGF1_SHA512= 0x00000004 -CKG_MGF1_SHA224= 0x00000005 -CKZ_DATA_SPECIFIED= 0x00000001 -CKD_NULL= 0x00000001 -CKD_SHA1_KDF= 0x00000002 -CKD_SHA1_KDF_ASN1= 0x00000003 -CKD_SHA1_KDF_CONCATENATE=0x00000004 -CKP_PKCS5_PBKD2_HMAC_SHA1=0x00000001 -CKZ_SALT_SPECIFIED= 0x00000001 -CK_OTP_VALUE= 0 -CK_OTP_PIN= 1 -CK_OTP_CHALLENGE= 2 -CK_OTP_TIME= 3 -CK_OTP_COUNTER= 4 -CK_OTP_FLAGS= 5 -CK_OTP_OUTPUT_LENGTH= 6 -CK_OTP_OUTPUT_FORMAT= 7 -CKF_NEXT_OTP= 0x00000001 -CKF_EXCLUDE_TIME= 0x00000002 -CKF_EXCLUDE_COUNTER= 0x00000004 -CKF_EXCLUDE_CHALLENGE=0x00000008 -CKF_EXCLUDE_PIN= 0x00000010 -CKF_USER_FRIENDLY_OTP=0x00000020 +CRYPTOKI_VERSION_MAJOR = 2 +CRYPTOKI_VERSION_MINOR = 20 +CRYPTOKI_VERSION_AMENDMENT = 3 +CK_TRUE = 1 +CK_FALSE = 0 +FALSE = CK_FALSE +TRUE = CK_TRUE +CK_EFFECTIVELY_INFINITE = 0 +CK_INVALID_HANDLE = 0 +CKN_SURRENDER = 0 +CKN_OTP_CHANGED = 1 +CKF_TOKEN_PRESENT = 0x00000001 # a token is there */ +CKF_REMOVABLE_DEVICE = 0x00000002 # removable devices*/ +CKF_HW_SLOT = 0x00000004 # hardware slot */ +CKF_RNG = 0x00000001 # has random # +CKF_WRITE_PROTECTED = 0x00000002 # token is +CKF_LOGIN_REQUIRED = 0x00000004 # user must +CKF_USER_PIN_INITIALIZED = 0x00000008 # normal user's +CKF_RESTORE_KEY_NOT_NEEDED = 0x00000020 +CKF_CLOCK_ON_TOKEN = 0x00000040 +CKF_PROTECTED_AUTHENTICATION_PATH = 0x00000100 +CKF_DUAL_CRYPTO_OPERATIONS = 0x00000200 +CKF_TOKEN_INITIALIZED = 0x00000400 +CKF_SECONDARY_AUTHENTICATION = 0x00000800 +CKF_USER_PIN_COUNT_LOW = 0x00010000 +CKF_USER_PIN_FINAL_TRY = 0x00020000 +CKF_USER_PIN_LOCKED = 0x00040000 +CKF_USER_PIN_TO_BE_CHANGED = 0x00080000 +CKF_SO_PIN_COUNT_LOW = 0x00100000 +CKF_SO_PIN_FINAL_TRY = 0x00200000 +CKF_SO_PIN_LOCKED = 0x00400000 +CKF_SO_PIN_TO_BE_CHANGED = 0x00800000 +CKU_SO = 0 +CKU_USER = 1 +CKU_CONTEXT_SPECIFIC = 2 +CKS_RO_PUBLIC_SESSION = 0 +CKS_RO_USER_FUNCTIONS = 1 +CKS_RW_PUBLIC_SESSION = 2 +CKS_RW_USER_FUNCTIONS = 3 +CKS_RW_SO_FUNCTIONS = 4 +CKF_RW_SESSION = 0x00000002 # session is r/w */ +CKF_SERIAL_SESSION = 0x00000004 # no parallel */ +CKO_DATA = 0x00000000 +CKO_CERTIFICATE = 0x00000001 +CKO_PUBLIC_KEY = 0x00000002 +CKO_PRIVATE_KEY = 0x00000003 +CKO_SECRET_KEY = 0x00000004 +CKO_HW_FEATURE = 0x00000005 +CKO_DOMAIN_PARAMETERS = 0x00000006 +CKO_MECHANISM = 0x00000007 +CKO_OTP_KEY = 0x00000008 +CKO_VENDOR_DEFINED = 0x80000000 +CKH_MONOTONIC_COUNTER = 0x00000001 +CKH_CLOCK = 0x00000002 +CKH_USER_INTERFACE = 0x00000003 +CKH_VENDOR_DEFINED = 0x80000000 +CKK_RSA = 0x00000000 +CKK_DSA = 0x00000001 +CKK_DH = 0x00000002 +CKK_ECDSA = 0x00000003 +CKK_EC = 0x00000003 +CKK_X9_42_DH = 0x00000004 +CKK_KEA = 0x00000005 +CKK_GENERIC_SECRET = 0x00000010 +CKK_RC2 = 0x00000011 +CKK_RC4 = 0x00000012 +CKK_DES = 0x00000013 +CKK_DES2 = 0x00000014 +CKK_DES3 = 0x00000015 +CKK_CAST = 0x00000016 +CKK_CAST3 = 0x00000017 +CKK_CAST5 = 0x00000018 +CKK_CAST128 = 0x00000018 +CKK_RC5 = 0x00000019 +CKK_IDEA = 0x0000001A +CKK_SKIPJACK = 0x0000001B +CKK_BATON = 0x0000001C +CKK_JUNIPER = 0x0000001D +CKK_CDMF = 0x0000001E +CKK_AES = 0x0000001F +CKK_BLOWFISH = 0x00000020 +CKK_TWOFISH = 0x00000021 +CKK_SECURID = 0x00000022 +CKK_HOTP = 0x00000023 +CKK_ACTI = 0x00000024 +CKK_CAMELLIA = 0x00000025 +CKK_ARIA = 0x00000026 +CKK_VENDOR_DEFINED = 0x80000000 +CKC_X_509 = 0x00000000 +CKC_X_509_ATTR_CERT = 0x00000001 +CKC_WTLS = 0x00000002 +CKC_VENDOR_DEFINED = 0x80000000 +CKF_ARRAY_ATTRIBUTE = 0x40000000 +CK_OTP_FORMAT_DECIMAL = 0 +CK_OTP_FORMAT_HEXADECIMAL = 1 +CK_OTP_FORMAT_ALPHANUMERIC = 2 +CK_OTP_FORMAT_BINARY = 3 +CK_OTP_PARAM_IGNORED = 0 +CK_OTP_PARAM_OPTIONAL = 1 +CK_OTP_PARAM_MANDATORY = 2 +CKA_CLASS = 0x00000000 +CKA_TOKEN = 0x00000001 +CKA_PRIVATE = 0x00000002 +CKA_LABEL = 0x00000003 +CKA_APPLICATION = 0x00000010 +CKA_VALUE = 0x00000011 +CKA_OBJECT_ID = 0x00000012 +CKA_CERTIFICATE_TYPE = 0x00000080 +CKA_ISSUER = 0x00000081 +CKA_SERIAL_NUMBER = 0x00000082 +CKA_AC_ISSUER = 0x00000083 +CKA_OWNER = 0x00000084 +CKA_ATTR_TYPES = 0x00000085 +CKA_TRUSTED = 0x00000086 +CKA_CERTIFICATE_CATEGORY = 0x00000087 +CKA_JAVA_MIDP_SECURITY_DOMAIN = 0x00000088 +CKA_URL = 0x00000089 +CKA_HASH_OF_SUBJECT_PUBLIC_KEY = 0x0000008A +CKA_HASH_OF_ISSUER_PUBLIC_KEY = 0x0000008B +CKA_CHECK_VALUE = 0x00000090 +CKA_KEY_TYPE = 0x00000100 +CKA_SUBJECT = 0x00000101 +CKA_ID = 0x00000102 +CKA_SENSITIVE = 0x00000103 +CKA_ENCRYPT = 0x00000104 +CKA_DECRYPT = 0x00000105 +CKA_WRAP = 0x00000106 +CKA_UNWRAP = 0x00000107 +CKA_SIGN = 0x00000108 +CKA_SIGN_RECOVER = 0x00000109 +CKA_VERIFY = 0x0000010A +CKA_VERIFY_RECOVER = 0x0000010B +CKA_DERIVE = 0x0000010C +CKA_START_DATE = 0x00000110 +CKA_END_DATE = 0x00000111 +CKA_MODULUS = 0x00000120 +CKA_MODULUS_BITS = 0x00000121 +CKA_PUBLIC_EXPONENT = 0x00000122 +CKA_PRIVATE_EXPONENT = 0x00000123 +CKA_PRIME_1 = 0x00000124 +CKA_PRIME_2 = 0x00000125 +CKA_EXPONENT_1 = 0x00000126 +CKA_EXPONENT_2 = 0x00000127 +CKA_COEFFICIENT = 0x00000128 +CKA_PRIME = 0x00000130 +CKA_SUBPRIME = 0x00000131 +CKA_BASE = 0x00000132 +CKA_PRIME_BITS = 0x00000133 +CKA_SUBPRIME_BITS = 0x00000134 +CKA_SUB_PRIME_BITS = CKA_SUBPRIME_BITS +CKA_VALUE_BITS = 0x00000160 +CKA_VALUE_LEN = 0x00000161 +CKA_EXTRACTABLE = 0x00000162 +CKA_LOCAL = 0x00000163 +CKA_NEVER_EXTRACTABLE = 0x00000164 +CKA_ALWAYS_SENSITIVE = 0x00000165 +CKA_KEY_GEN_MECHANISM = 0x00000166 +CKA_MODIFIABLE = 0x00000170 +CKA_ECDSA_PARAMS = 0x00000180 +CKA_EC_PARAMS = 0x00000180 +CKA_EC_POINT = 0x00000181 +CKA_SECONDARY_AUTH = 0x00000200 +CKA_AUTH_PIN_FLAGS = 0x00000201 +CKA_ALWAYS_AUTHENTICATE = 0x00000202 +CKA_WRAP_WITH_TRUSTED = 0x00000210 +CKA_WRAP_TEMPLATE = (CKF_ARRAY_ATTRIBUTE | 0x00000211) +CKA_UNWRAP_TEMPLATE = (CKF_ARRAY_ATTRIBUTE | 0x00000212) +CKA_OTP_FORMAT = 0x00000220 +CKA_OTP_LENGTH = 0x00000221 +CKA_OTP_TIME_INTERVAL = 0x00000222 +CKA_OTP_USER_FRIENDLY_MODE = 0x00000223 +CKA_OTP_CHALLENGE_REQUIREMENT = 0x00000224 +CKA_OTP_TIME_REQUIREMENT = 0x00000225 +CKA_OTP_COUNTER_REQUIREMENT = 0x00000226 +CKA_OTP_PIN_REQUIREMENT = 0x00000227 +CKA_OTP_COUNTER = 0x0000022E +CKA_OTP_TIME = 0x0000022F +CKA_OTP_USER_IDENTIFIER = 0x0000022A +CKA_OTP_SERVICE_IDENTIFIER = 0x0000022B +CKA_OTP_SERVICE_LOGO = 0x0000022C +CKA_OTP_SERVICE_LOGO_TYPE = 0x0000022D +CKA_HW_FEATURE_TYPE = 0x00000300 +CKA_RESET_ON_INIT = 0x00000301 +CKA_HAS_RESET = 0x00000302 +CKA_PIXEL_X = 0x00000400 +CKA_PIXEL_Y = 0x00000401 +CKA_RESOLUTION = 0x00000402 +CKA_CHAR_ROWS = 0x00000403 +CKA_CHAR_COLUMNS = 0x00000404 +CKA_COLOR = 0x00000405 +CKA_BITS_PER_PIXEL = 0x00000406 +CKA_CHAR_SETS = 0x00000480 +CKA_ENCODING_METHODS = 0x00000481 +CKA_MIME_TYPES = 0x00000482 +CKA_MECHANISM_TYPE = 0x00000500 +CKA_REQUIRED_CMS_ATTRIBUTES = 0x00000501 +CKA_DEFAULT_CMS_ATTRIBUTES = 0x00000502 +CKA_SUPPORTED_CMS_ATTRIBUTES = 0x00000503 +CKA_ALLOWED_MECHANISMS = (CKF_ARRAY_ATTRIBUTE | 0x00000600) +CKA_VENDOR_DEFINED = 0x80000000 +CKM_RSA_PKCS_KEY_PAIR_GEN = 0x00000000 +CKM_RSA_PKCS = 0x00000001 +CKM_RSA_9796 = 0x00000002 +CKM_RSA_X_509 = 0x00000003 +CKM_MD2_RSA_PKCS = 0x00000004 +CKM_MD5_RSA_PKCS = 0x00000005 +CKM_SHA1_RSA_PKCS = 0x00000006 +CKM_RIPEMD128_RSA_PKCS = 0x00000007 +CKM_RIPEMD160_RSA_PKCS = 0x00000008 +CKM_RSA_PKCS_OAEP = 0x00000009 +CKM_RSA_X9_31_KEY_PAIR_GEN = 0x0000000A +CKM_RSA_X9_31 = 0x0000000B +CKM_SHA1_RSA_X9_31 = 0x0000000C +CKM_RSA_PKCS_PSS = 0x0000000D +CKM_SHA1_RSA_PKCS_PSS = 0x0000000E +CKM_DSA_KEY_PAIR_GEN = 0x00000010 +CKM_DSA = 0x00000011 +CKM_DSA_SHA1 = 0x00000012 +CKM_DH_PKCS_KEY_PAIR_GEN = 0x00000020 +CKM_DH_PKCS_DERIVE = 0x00000021 +CKM_X9_42_DH_KEY_PAIR_GEN = 0x00000030 +CKM_X9_42_DH_DERIVE = 0x00000031 +CKM_X9_42_DH_HYBRID_DERIVE = 0x00000032 +CKM_X9_42_MQV_DERIVE = 0x00000033 +CKM_SHA256_RSA_PKCS = 0x00000040 +CKM_SHA384_RSA_PKCS = 0x00000041 +CKM_SHA512_RSA_PKCS = 0x00000042 +CKM_SHA256_RSA_PKCS_PSS = 0x00000043 +CKM_SHA384_RSA_PKCS_PSS = 0x00000044 +CKM_SHA512_RSA_PKCS_PSS = 0x00000045 +CKM_SHA224_RSA_PKCS = 0x00000046 +CKM_SHA224_RSA_PKCS_PSS = 0x00000047 +CKM_RC2_KEY_GEN = 0x00000100 +CKM_RC2_ECB = 0x00000101 +CKM_RC2_CBC = 0x00000102 +CKM_RC2_MAC = 0x00000103 +CKM_RC2_MAC_GENERAL = 0x00000104 +CKM_RC2_CBC_PAD = 0x00000105 +CKM_RC4_KEY_GEN = 0x00000110 +CKM_RC4 = 0x00000111 +CKM_DES_KEY_GEN = 0x00000120 +CKM_DES_ECB = 0x00000121 +CKM_DES_CBC = 0x00000122 +CKM_DES_MAC = 0x00000123 +CKM_DES_MAC_GENERAL = 0x00000124 +CKM_DES_CBC_PAD = 0x00000125 +CKM_DES2_KEY_GEN = 0x00000130 +CKM_DES3_KEY_GEN = 0x00000131 +CKM_DES3_ECB = 0x00000132 +CKM_DES3_CBC = 0x00000133 +CKM_DES3_MAC = 0x00000134 +CKM_DES3_MAC_GENERAL = 0x00000135 +CKM_DES3_CBC_PAD = 0x00000136 +CKM_DES3_CMAC_GENERAL = 0x00000137 +CKM_DES3_CMAC = 0x00000138 +CKM_CDMF_KEY_GEN = 0x00000140 +CKM_CDMF_ECB = 0x00000141 +CKM_CDMF_CBC = 0x00000142 +CKM_CDMF_MAC = 0x00000143 +CKM_CDMF_MAC_GENERAL = 0x00000144 +CKM_CDMF_CBC_PAD = 0x00000145 +CKM_DES_OFB64 = 0x00000150 +CKM_DES_OFB8 = 0x00000151 +CKM_DES_CFB64 = 0x00000152 +CKM_DES_CFB8 = 0x00000153 +CKM_MD2 = 0x00000200 +CKM_MD2_HMAC = 0x00000201 +CKM_MD2_HMAC_GENERAL = 0x00000202 +CKM_MD5 = 0x00000210 +CKM_MD5_HMAC = 0x00000211 +CKM_MD5_HMAC_GENERAL = 0x00000212 +CKM_SHA_1 = 0x00000220 +CKM_SHA_1_HMAC = 0x00000221 +CKM_SHA_1_HMAC_GENERAL = 0x00000222 +CKM_RIPEMD128 = 0x00000230 +CKM_RIPEMD128_HMAC = 0x00000231 +CKM_RIPEMD128_HMAC_GENERAL = 0x00000232 +CKM_RIPEMD160 = 0x00000240 +CKM_RIPEMD160_HMAC = 0x00000241 +CKM_RIPEMD160_HMAC_GENERAL = 0x00000242 +CKM_SHA256 = 0x00000250 +CKM_SHA256_HMAC = 0x00000251 +CKM_SHA256_HMAC_GENERAL = 0x00000252 +CKM_SHA224 = 0x00000255 +CKM_SHA224_HMAC = 0x00000256 +CKM_SHA224_HMAC_GENERAL = 0x00000257 +CKM_SHA384 = 0x00000260 +CKM_SHA384_HMAC = 0x00000261 +CKM_SHA384_HMAC_GENERAL = 0x00000262 +CKM_SHA512 = 0x00000270 +CKM_SHA512_HMAC = 0x00000271 +CKM_SHA512_HMAC_GENERAL = 0x00000272 +CKM_SECURID_KEY_GEN = 0x00000280 +CKM_SECURID = 0x00000282 +CKM_HOTP_KEY_GEN = 0x00000290 +CKM_HOTP = 0x00000291 +CKM_ACTI = 0x000002A0 +CKM_ACTI_KEY_GEN = 0x000002A1 +CKM_CAST_KEY_GEN = 0x00000300 +CKM_CAST_ECB = 0x00000301 +CKM_CAST_CBC = 0x00000302 +CKM_CAST_MAC = 0x00000303 +CKM_CAST_MAC_GENERAL = 0x00000304 +CKM_CAST_CBC_PAD = 0x00000305 +CKM_CAST3_KEY_GEN = 0x00000310 +CKM_CAST3_ECB = 0x00000311 +CKM_CAST3_CBC = 0x00000312 +CKM_CAST3_MAC = 0x00000313 +CKM_CAST3_MAC_GENERAL = 0x00000314 +CKM_CAST3_CBC_PAD = 0x00000315 +CKM_CAST5_KEY_GEN = 0x00000320 +CKM_CAST128_KEY_GEN = 0x00000320 +CKM_CAST5_ECB = 0x00000321 +CKM_CAST128_ECB = 0x00000321 +CKM_CAST5_CBC = 0x00000322 +CKM_CAST128_CBC = 0x00000322 +CKM_CAST5_MAC = 0x00000323 +CKM_CAST128_MAC = 0x00000323 +CKM_CAST5_MAC_GENERAL = 0x00000324 +CKM_CAST128_MAC_GENERAL = 0x00000324 +CKM_CAST5_CBC_PAD = 0x00000325 +CKM_CAST128_CBC_PAD = 0x00000325 +CKM_RC5_KEY_GEN = 0x00000330 +CKM_RC5_ECB = 0x00000331 +CKM_RC5_CBC = 0x00000332 +CKM_RC5_MAC = 0x00000333 +CKM_RC5_MAC_GENERAL = 0x00000334 +CKM_RC5_CBC_PAD = 0x00000335 +CKM_IDEA_KEY_GEN = 0x00000340 +CKM_IDEA_ECB = 0x00000341 +CKM_IDEA_CBC = 0x00000342 +CKM_IDEA_MAC = 0x00000343 +CKM_IDEA_MAC_GENERAL = 0x00000344 +CKM_IDEA_CBC_PAD = 0x00000345 +CKM_GENERIC_SECRET_KEY_GEN = 0x00000350 +CKM_CONCATENATE_BASE_AND_KEY = 0x00000360 +CKM_CONCATENATE_BASE_AND_DATA = 0x00000362 +CKM_CONCATENATE_DATA_AND_BASE = 0x00000363 +CKM_XOR_BASE_AND_DATA = 0x00000364 +CKM_EXTRACT_KEY_FROM_KEY = 0x00000365 +CKM_SSL3_PRE_MASTER_KEY_GEN = 0x00000370 +CKM_SSL3_MASTER_KEY_DERIVE = 0x00000371 +CKM_SSL3_KEY_AND_MAC_DERIVE = 0x00000372 +CKM_SSL3_MASTER_KEY_DERIVE_DH = 0x00000373 +CKM_TLS_PRE_MASTER_KEY_GEN = 0x00000374 +CKM_TLS_MASTER_KEY_DERIVE = 0x00000375 +CKM_TLS_KEY_AND_MAC_DERIVE = 0x00000376 +CKM_TLS_MASTER_KEY_DERIVE_DH = 0x00000377 +CKM_TLS_PRF = 0x00000378 +CKM_SSL3_MD5_MAC = 0x00000380 +CKM_SSL3_SHA1_MAC = 0x00000381 +CKM_MD5_KEY_DERIVATION = 0x00000390 +CKM_MD2_KEY_DERIVATION = 0x00000391 +CKM_SHA1_KEY_DERIVATION = 0x00000392 +CKM_SHA256_KEY_DERIVATION = 0x00000393 +CKM_SHA384_KEY_DERIVATION = 0x00000394 +CKM_SHA512_KEY_DERIVATION = 0x00000395 +CKM_SHA224_KEY_DERIVATION = 0x00000396 +CKM_PBE_MD2_DES_CBC = 0x000003A0 +CKM_PBE_MD5_DES_CBC = 0x000003A1 +CKM_PBE_MD5_CAST_CBC = 0x000003A2 +CKM_PBE_MD5_CAST3_CBC = 0x000003A3 +CKM_PBE_MD5_CAST5_CBC = 0x000003A4 +CKM_PBE_MD5_CAST128_CBC = 0x000003A4 +CKM_PBE_SHA1_CAST5_CBC = 0x000003A5 +CKM_PBE_SHA1_CAST128_CBC = 0x000003A5 +CKM_PBE_SHA1_RC4_128 = 0x000003A6 +CKM_PBE_SHA1_RC4_40 = 0x000003A7 +CKM_PBE_SHA1_DES3_EDE_CBC = 0x000003A8 +CKM_PBE_SHA1_DES2_EDE_CBC = 0x000003A9 +CKM_PBE_SHA1_RC2_128_CBC = 0x000003AA +CKM_PBE_SHA1_RC2_40_CBC = 0x000003AB +CKM_PKCS5_PBKD2 = 0x000003B0 +CKM_PBA_SHA1_WITH_SHA1_HMAC = 0x000003C0 +CKM_WTLS_PRE_MASTER_KEY_GEN = 0x000003D0 +CKM_WTLS_MASTER_KEY_DERIVE = 0x000003D1 +CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC = 0x000003D2 +CKM_WTLS_PRF = 0x000003D3 +CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE = 0x000003D4 +CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE = 0x000003D5 +CKM_KEY_WRAP_LYNKS = 0x00000400 +CKM_KEY_WRAP_SET_OAEP = 0x00000401 +CKM_CMS_SIG = 0x00000500 +CKM_KIP_DERIVE = 0x00000510 +CKM_KIP_WRAP = 0x00000511 +CKM_KIP_MAC = 0x00000512 +CKM_CAMELLIA_KEY_GEN = 0x00000550 +CKM_CAMELLIA_ECB = 0x00000551 +CKM_CAMELLIA_CBC = 0x00000552 +CKM_CAMELLIA_MAC = 0x00000553 +CKM_CAMELLIA_MAC_GENERAL = 0x00000554 +CKM_CAMELLIA_CBC_PAD = 0x00000555 +CKM_CAMELLIA_ECB_ENCRYPT_DATA = 0x00000556 +CKM_CAMELLIA_CBC_ENCRYPT_DATA = 0x00000557 +CKM_CAMELLIA_CTR = 0x00000558 +CKM_ARIA_KEY_GEN = 0x00000560 +CKM_ARIA_ECB = 0x00000561 +CKM_ARIA_CBC = 0x00000562 +CKM_ARIA_MAC = 0x00000563 +CKM_ARIA_MAC_GENERAL = 0x00000564 +CKM_ARIA_CBC_PAD = 0x00000565 +CKM_ARIA_ECB_ENCRYPT_DATA = 0x00000566 +CKM_ARIA_CBC_ENCRYPT_DATA = 0x00000567 +CKM_SKIPJACK_KEY_GEN = 0x00001000 +CKM_SKIPJACK_ECB64 = 0x00001001 +CKM_SKIPJACK_CBC64 = 0x00001002 +CKM_SKIPJACK_OFB64 = 0x00001003 +CKM_SKIPJACK_CFB64 = 0x00001004 +CKM_SKIPJACK_CFB32 = 0x00001005 +CKM_SKIPJACK_CFB16 = 0x00001006 +CKM_SKIPJACK_CFB8 = 0x00001007 +CKM_SKIPJACK_WRAP = 0x00001008 +CKM_SKIPJACK_PRIVATE_WRAP = 0x00001009 +CKM_SKIPJACK_RELAYX = 0x0000100a +CKM_KEA_KEY_PAIR_GEN = 0x00001010 +CKM_KEA_KEY_DERIVE = 0x00001011 +CKM_FORTEZZA_TIMESTAMP = 0x00001020 +CKM_BATON_KEY_GEN = 0x00001030 +CKM_BATON_ECB128 = 0x00001031 +CKM_BATON_ECB96 = 0x00001032 +CKM_BATON_CBC128 = 0x00001033 +CKM_BATON_COUNTER = 0x00001034 +CKM_BATON_SHUFFLE = 0x00001035 +CKM_BATON_WRAP = 0x00001036 +CKM_ECDSA_KEY_PAIR_GEN = 0x00001040 +CKM_EC_KEY_PAIR_GEN = 0x00001040 +CKM_ECDSA = 0x00001041 +CKM_ECDSA_SHA1 = 0x00001042 +CKM_ECDH1_DERIVE = 0x00001050 +CKM_ECDH1_COFACTOR_DERIVE = 0x00001051 +CKM_ECMQV_DERIVE = 0x00001052 +CKM_JUNIPER_KEY_GEN = 0x00001060 +CKM_JUNIPER_ECB128 = 0x00001061 +CKM_JUNIPER_CBC128 = 0x00001062 +CKM_JUNIPER_COUNTER = 0x00001063 +CKM_JUNIPER_SHUFFLE = 0x00001064 +CKM_JUNIPER_WRAP = 0x00001065 +CKM_FASTHASH = 0x00001070 +CKM_AES_KEY_GEN = 0x00001080 +CKM_AES_ECB = 0x00001081 +CKM_AES_CBC = 0x00001082 +CKM_AES_MAC = 0x00001083 +CKM_AES_MAC_GENERAL = 0x00001084 +CKM_AES_CBC_PAD = 0x00001085 +CKM_AES_CTR = 0x00001086 +CKM_AES_CMAC_GENERAL = 0x00001089 +CKM_AES_CMAC = 0x0000108A +CKM_BLOWFISH_KEY_GEN = 0x00001090 +CKM_BLOWFISH_CBC = 0x00001091 +CKM_TWOFISH_KEY_GEN = 0x00001092 +CKM_TWOFISH_CBC = 0x00001093 +CKM_DES_ECB_ENCRYPT_DATA = 0x00001100 +CKM_DES_CBC_ENCRYPT_DATA = 0x00001101 +CKM_DES3_ECB_ENCRYPT_DATA = 0x00001102 +CKM_DES3_CBC_ENCRYPT_DATA = 0x00001103 +CKM_AES_ECB_ENCRYPT_DATA = 0x00001104 +CKM_AES_CBC_ENCRYPT_DATA = 0x00001105 +CKM_DSA_PARAMETER_GEN = 0x00002000 +CKM_DH_PKCS_PARAMETER_GEN = 0x00002001 +CKM_X9_42_DH_PARAMETER_GEN = 0x00002002 +CKM_VENDOR_DEFINED = 0x80000000 +CKF_HW = 0x00000001 # performed by HW */ +CKF_ENCRYPT = 0x00000100 +CKF_DECRYPT = 0x00000200 +CKF_DIGEST = 0x00000400 +CKF_SIGN = 0x00000800 +CKF_SIGN_RECOVER = 0x00001000 +CKF_VERIFY = 0x00002000 +CKF_VERIFY_RECOVER = 0x00004000 +CKF_GENERATE = 0x00008000 +CKF_GENERATE_KEY_PAIR = 0x00010000 +CKF_WRAP = 0x00020000 +CKF_UNWRAP = 0x00040000 +CKF_DERIVE = 0x00080000 +CKF_EC_F_P = 0x00100000 +CKF_EC_F_2M = 0x00200000 +CKF_EC_ECPARAMETERS = 0x00400000 +CKF_EC_NAMEDCURVE = 0x00800000 +CKF_EC_UNCOMPRESS = 0x01000000 +CKF_EC_COMPRESS = 0x02000000 +CKF_EXTENSION = 0x80000000 # FALSE for this version */ +CKR_OK = 0x00000000 +CKR_CANCEL = 0x00000001 +CKR_HOST_MEMORY = 0x00000002 +CKR_SLOT_ID_INVALID = 0x00000003 +CKR_GENERAL_ERROR = 0x00000005 +CKR_FUNCTION_FAILED = 0x00000006 +CKR_ARGUMENTS_BAD = 0x00000007 +CKR_NO_EVENT = 0x00000008 +CKR_NEED_TO_CREATE_THREADS = 0x00000009 +CKR_CANT_LOCK = 0x0000000A +CKR_ATTRIBUTE_READ_ONLY = 0x00000010 +CKR_ATTRIBUTE_SENSITIVE = 0x00000011 +CKR_ATTRIBUTE_TYPE_INVALID = 0x00000012 +CKR_ATTRIBUTE_VALUE_INVALID = 0x00000013 +CKR_DATA_INVALID = 0x00000020 +CKR_DATA_LEN_RANGE = 0x00000021 +CKR_DEVICE_ERROR = 0x00000030 +CKR_DEVICE_MEMORY = 0x00000031 +CKR_DEVICE_REMOVED = 0x00000032 +CKR_ENCRYPTED_DATA_INVALID = 0x00000040 +CKR_ENCRYPTED_DATA_LEN_RANGE = 0x00000041 +CKR_FUNCTION_CANCELED = 0x00000050 +CKR_FUNCTION_NOT_PARALLEL = 0x00000051 +CKR_FUNCTION_NOT_SUPPORTED = 0x00000054 +CKR_KEY_HANDLE_INVALID = 0x00000060 +CKR_KEY_SIZE_RANGE = 0x00000062 +CKR_KEY_TYPE_INCONSISTENT = 0x00000063 +CKR_KEY_NOT_NEEDED = 0x00000064 +CKR_KEY_CHANGED = 0x00000065 +CKR_KEY_NEEDED = 0x00000066 +CKR_KEY_INDIGESTIBLE = 0x00000067 +CKR_KEY_FUNCTION_NOT_PERMITTED = 0x00000068 +CKR_KEY_NOT_WRAPPABLE = 0x00000069 +CKR_KEY_UNEXTRACTABLE = 0x0000006A +CKR_MECHANISM_INVALID = 0x00000070 +CKR_MECHANISM_PARAM_INVALID = 0x00000071 +CKR_OBJECT_HANDLE_INVALID = 0x00000082 +CKR_OPERATION_ACTIVE = 0x00000090 +CKR_OPERATION_NOT_INITIALIZED = 0x00000091 +CKR_PIN_INCORRECT = 0x000000A0 +CKR_PIN_INVALID = 0x000000A1 +CKR_PIN_LEN_RANGE = 0x000000A2 +CKR_PIN_EXPIRED = 0x000000A3 +CKR_PIN_LOCKED = 0x000000A4 +CKR_SESSION_CLOSED = 0x000000B0 +CKR_SESSION_COUNT = 0x000000B1 +CKR_SESSION_HANDLE_INVALID = 0x000000B3 +CKR_SESSION_PARALLEL_NOT_SUPPORTED = 0x000000B4 +CKR_SESSION_READ_ONLY = 0x000000B5 +CKR_SESSION_EXISTS = 0x000000B6 +CKR_SESSION_READ_ONLY_EXISTS = 0x000000B7 +CKR_SESSION_READ_WRITE_SO_EXISTS = 0x000000B8 +CKR_SIGNATURE_INVALID = 0x000000C0 +CKR_SIGNATURE_LEN_RANGE = 0x000000C1 +CKR_TEMPLATE_INCOMPLETE = 0x000000D0 +CKR_TEMPLATE_INCONSISTENT = 0x000000D1 +CKR_TOKEN_NOT_PRESENT = 0x000000E0 +CKR_TOKEN_NOT_RECOGNIZED = 0x000000E1 +CKR_TOKEN_WRITE_PROTECTED = 0x000000E2 +CKR_UNWRAPPING_KEY_HANDLE_INVALID = 0x000000F0 +CKR_UNWRAPPING_KEY_SIZE_RANGE = 0x000000F1 +CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT = 0x000000F2 +CKR_USER_ALREADY_LOGGED_IN = 0x00000100 +CKR_USER_NOT_LOGGED_IN = 0x00000101 +CKR_USER_PIN_NOT_INITIALIZED = 0x00000102 +CKR_USER_TYPE_INVALID = 0x00000103 +CKR_USER_ANOTHER_ALREADY_LOGGED_IN = 0x00000104 +CKR_USER_TOO_MANY_TYPES = 0x00000105 +CKR_WRAPPED_KEY_INVALID = 0x00000110 +CKR_WRAPPED_KEY_LEN_RANGE = 0x00000112 +CKR_WRAPPING_KEY_HANDLE_INVALID = 0x00000113 +CKR_WRAPPING_KEY_SIZE_RANGE = 0x00000114 +CKR_WRAPPING_KEY_TYPE_INCONSISTENT = 0x00000115 +CKR_RANDOM_SEED_NOT_SUPPORTED = 0x00000120 +CKR_RANDOM_NO_RNG = 0x00000121 +CKR_DOMAIN_PARAMS_INVALID = 0x00000130 +CKR_BUFFER_TOO_SMALL = 0x00000150 +CKR_SAVED_STATE_INVALID = 0x00000160 +CKR_INFORMATION_SENSITIVE = 0x00000170 +CKR_STATE_UNSAVEABLE = 0x00000180 +CKR_CRYPTOKI_NOT_INITIALIZED = 0x00000190 +CKR_CRYPTOKI_ALREADY_INITIALIZED = 0x00000191 +CKR_MUTEX_BAD = 0x000001A0 +CKR_MUTEX_NOT_LOCKED = 0x000001A1 +CKR_NEW_PIN_MODE = 0x000001B0 +CKR_NEXT_OTP = 0x000001B1 +CKR_FUNCTION_REJECTED = 0x00000200 +CKR_VENDOR_DEFINED = 0x80000000 +CKF_LIBRARY_CANT_CREATE_OS_THREADS = 0x00000001 +CKF_OS_LOCKING_OK = 0x00000002 +CKF_DONT_BLOCK = 1 +CKG_MGF1_SHA1 = 0x00000001 +CKG_MGF1_SHA256 = 0x00000002 +CKG_MGF1_SHA384 = 0x00000003 +CKG_MGF1_SHA512 = 0x00000004 +CKG_MGF1_SHA224 = 0x00000005 +CKZ_DATA_SPECIFIED = 0x00000001 +CKD_NULL = 0x00000001 +CKD_SHA1_KDF = 0x00000002 +CKD_SHA1_KDF_ASN1 = 0x00000003 +CKD_SHA1_KDF_CONCATENATE = 0x00000004 +CKP_PKCS5_PBKD2_HMAC_SHA1 = 0x00000001 +CKZ_SALT_SPECIFIED = 0x00000001 +CK_OTP_VALUE = 0 +CK_OTP_PIN = 1 +CK_OTP_CHALLENGE = 2 +CK_OTP_TIME = 3 +CK_OTP_COUNTER = 4 +CK_OTP_FLAGS = 5 +CK_OTP_OUTPUT_LENGTH = 6 +CK_OTP_OUTPUT_FORMAT = 7 +CKF_NEXT_OTP = 0x00000001 +CKF_EXCLUDE_TIME = 0x00000002 +CKF_EXCLUDE_COUNTER = 0x00000004 +CKF_EXCLUDE_CHALLENGE = 0x00000008 +CKF_EXCLUDE_PIN = 0x00000010 +CKF_USER_FRIENDLY_OTP = 0x00000020 '''/home/new_builds/1175/101/CoreLibrary/includes/cryptoki_v2.h''' -NULL_PTR= 0 -C_LIBRARY_VERSION= 0x510 # v5.10 decimal */ -CK_TOKEN_SERIAL_NUMBER_SIZE= 16 -CK_EFFECTIVELY_INFINITE= 0 -CKU_CRYPTO_OFFICER=CKU_USER -CKU_LIMITED_USER=0x80000001 -CKU_LIMITED_USER_OLD=0x8000001 -CKU_CRYPTO_USER=CKU_LIMITED_USER -CKU_AUDIT= 0x80000002 -CKU_INVALID_USER_TYPE=0xffffffff -CKU_VENDOR_DEFINED= 0x80000000 -CKF_EXCLUSIVE_SESSION= 0x0001 -CKF_EXCLUSIVE_EXISTS= 0x0010 -CKF_SO_SESSION= 0x8000 -CKF_AUDIT_SESSION= 0x10000 -CKF_VENDER_DEFINED= 0x10000000 -CKF_IGNORE_HAONLY= (CKF_VENDER_DEFINED <<3) -CKF_USE_APPID= (CKF_VENDER_DEFINED <<2) -CKF_ADMIN_TOKEN= 0x10000000 -CKF_ENTRUST_READY= 0x00000001 -CKF_NO_CLEAR_PINS= 0x00000002 -CKF_AUTH_PROTECTION= 0x00000004 -CKF_NO_PUBLIC_CRYPTO= 0x00000008 -CKF_TAMPER_BEFORE_UPGRADE=0x00000010 -CKF_INCREASED_SECURITY= 0x00000020 -CKF_FIPS_ALGORITHMS= 0x00000040 -CKF_FULL_SMS_ENC= 0x00000080 -CKF_FULL_SMS_SIGN= 0x00000100 -CKF_PURE_P11= 0x00000200 -CKF_DES_EVEN_PARITY_ALLOWED=0x00000400 -CKF_USER_ECC_DP_ALLOWED= 0x00000800 -CKF_MODE_LOCKED= 0x10000000 -CKA_START_DATE_OLD_XXX= 0x0083 # Kept temporarily for backward compatibility with Beta version. Use CKA_START_DATE -CKA_END_DATE_OLD_XXX= 0x0084 # Kept temporarily for backward compatibility with Beta version. Use CKA_END_DATE -CKD_SHA224_KDF= 0x00000005 -CKD_SHA224_KDF_OLD= 0x80000003 -CKD_SHA256_KDF= 0x00000006 -CKD_SHA256_KDF_OLD= 0x80000004 -CKD_SHA384_KDF= 0x00000007 -CKD_SHA384_KDF_OLD= 0x80000005 -CKD_SHA512_KDF= 0x00000008 -CKD_SHA512_KDF_OLD= 0x80000006 -CKD_RIPEMD160_KDF= 0x80000007 -CKD_SHA1_NIST_KDF= 0x00000012 -CKD_SHA224_NIST_KDF= 0x80000013 -CKD_SHA256_NIST_KDF= 0x80000014 -CKD_SHA384_NIST_KDF= 0x80000015 -CKD_SHA512_NIST_KDF= 0x80000016 -CKD_RIPEMD160_NIST_KDF= 0x80000017 -CKD_SHA1_SES_KDF= 0x82000000 -CKD_SHA224_SES_KDF= 0x83000000 -CKD_SHA256_SES_KDF= 0x84000000 -CKD_SHA384_SES_KDF= 0x85000000 -CKD_SHA512_SES_KDF= 0x86000000 -CKD_RIPEMD160_SES_KDF= 0x87000000 -CKD_SES_ENC_CTR= 0x00000001 -CKD_SES_AUTH_CTR= 0x00000002 -CKD_SES_ALT_ENC_CTR= 0x00000003 -CKD_SES_ALT_AUTH_CTR= 0x00000004 -CKD_SHA1_KDF_ASN1= 0x00000003 # not supported -CKD_SHA1_KDF_CONCATENATE= 0x00000004 -CKD_SHA1_KDF_CONCATENATE_X9_42=CKD_SHA1_KDF_CONCATENATE -CKD_SHA1_KDF_CONCATENATE_NIST= 0x80000001 -CKD_SHA1_KDF_ASN1_X9_42= CKD_SHA1_KDF_ASN1 # not supported -CKD_SHA1_KDF_ASN1_NIST= 0x80000002 # not supported -CKK_KCDSA= CKK_VENDOR_DEFINED + 0x10 -CKK_SEED= CKK_VENDOR_DEFINED + 0x11 -CKA_CCM_PRIVATE= (CKA_VENDOR_DEFINED | 0x0001) -CKA_FINGERPRINT_SHA1= (CKA_VENDOR_DEFINED | 0x0002) -CKA_PKC_TCTRUST= (CKA_VENDOR_DEFINED | 0x0003) -CKA_PKC_CITS= (CKA_VENDOR_DEFINED | 0x0004) -CKA_OUID= (CKA_VENDOR_DEFINED | 0x0005) -CKA_X9_31_GENERATED= (CKA_VENDOR_DEFINED | 0x0006) -CKA_PKC_ECC= (CKA_VENDOR_DEFINED | 0x0007) -CKA_EKM_UID= (CKA_VENDOR_DEFINED | 0x0008) -CKA_TOKEN_ROLE_POLICIES= (CKA_VENDOR_DEFINED | 0x0010) -CKA_ROLE_DESCRIPTORS= (CKA_VENDOR_DEFINED | 0x0011) -CKA_USER_VALUE= (CKA_VENDOR_DEFINED | 0x0012) -CKA_INITIALIZER= (CKA_VENDOR_DEFINED | 0x0013) -CKA_POLICY= (CKA_VENDOR_DEFINED | 0x0014) -CKA_ACTIVE= (CKA_VENDOR_DEFINED | 0x0015) -CKA_INITIALIZED= (CKA_VENDOR_DEFINED | 0x0016) -CKA_PIN_TO_BE_CHANGED= (CKA_VENDOR_DEFINED | 0x0017) -CKA_LOCKED_OUT= (CKA_VENDOR_DEFINED | 0x0018) -CKA_ACTIVATED= (CKA_VENDOR_DEFINED | 0x0019) -CKA_HAS_DOMAIN= (CKA_VENDOR_DEFINED | 0x001A) -CKA_LOGIN_ATTEMPTS_LEFT= (CKA_VENDOR_DEFINED | 0x001B) -CKA_PRIMARY_AUTH_METHOD= (CKA_VENDOR_DEFINED | 0x001C) -CKA_SECONDARY_AUTH_METHOD=(CKA_VENDOR_DEFINED | 0x001D) -CKA_USAGE_COUNT= (CKA_VENDOR_DEFINED + 0x0101) -CKA_SLOT_ID= (CKA_VENDOR_DEFINED + 0x0151) -CKA_MAX_SESSIONS= (CKA_VENDOR_DEFINED | 0x0155) -CKA_MIN_PIN_LEN= (CKA_VENDOR_DEFINED | 0x0156) -CKA_FLAGS= (CKA_VENDOR_DEFINED | 0x0159) -CKA_USAGE_LIMIT= (CKA_VENDOR_DEFINED + 0x0200) -CKA_SECURITY_MODE= (CKA_VENDOR_DEFINED + 0x0140) -CKA_TRANSPORT_MODE= (CKA_VENDOR_DEFINED + 0x0141) -CKA_BATCH= (CKA_VENDOR_DEFINED + 0x0142) -CKA_HW_STATUS= (CKA_VENDOR_DEFINED + 0x0143) -CKA_FREE_MEM= (CKA_VENDOR_DEFINED + 0x0144) -CKA_TAMPER_CMD= (CKA_VENDOR_DEFINED + 0x0145) -CKA_DATE_OF_MANUFACTURE=(CKA_VENDOR_DEFINED + 0x0146) -CKA_HALT_CMD= (CKA_VENDOR_DEFINED + 0x0147) -CKA_APPLICATION_COUNT=(CKA_VENDOR_DEFINED + 0x0148) -CKA_FW_VERSION= (CKA_VENDOR_DEFINED + 0x0149) -CKA_RESCAN_PERIPHERALS_CMD=(CKA_VENDOR_DEFINED + 0x014A) -CKA_RTC_AAC_ENABLED= (CKA_VENDOR_DEFINED + 0x014B) -CKA_RTC_AAC_GUARD_SECONDS= (CKA_VENDOR_DEFINED + 0x014C) -CKA_RTC_AAC_GUARD_COUNT= (CKA_VENDOR_DEFINED + 0x014D) -CKA_RTC_AAC_GUARD_DURATION=(CKA_VENDOR_DEFINED + 0x014E) -CKA_HW_EXT_INFO_STR= (CKA_VENDOR_DEFINED + 0x014F) -CKA_TEMPERATURE_STR= (CKA_VENDOR_DEFINED + 0x0150) -CKA_GENERIC_1= (CKA_VENDOR_DEFINED + 0x1000) -CKA_GENERIC_2= (CKA_VENDOR_DEFINED + 0x1001) -CKA_GENERIC_3= (CKA_VENDOR_DEFINED + 0x1002) -CKA_FINGERPRINT_SHA256= (CKA_VENDOR_DEFINED + 0x1003) -CKM_VENDOR_DEFINED_OLD_XXX= 0x00008000 -CKM_CAST_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 0 # Entrust added capabilities -CKM_CAST_ECB_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 1 # Entrust added capabilities -CKM_CAST_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 2 # Entrust added capabilities -CKM_CAST_MAC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 3 # Entrust added capabilities -CKM_CAST3_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 4 # Entrust added capabilities -CKM_CAST3_ECB_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 5 # Entrust added capabilities -CKM_CAST3_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 6 # Entrust added capabilities -CKM_CAST3_MAC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 7 # Entrust added capabilities -CKM_PBE_MD2_DES_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 8 # Password based encryption -CKM_PBE_MD5_DES_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 9 # Password based encryption -CKM_PBE_MD5_CAST_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 10 # Password based encryption -CKM_PBE_MD5_CAST3_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 11 # Password based encryption -CKM_CONCATENATE_BASE_AND_KEY_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 12 # SPKM & SLL added capabilities -CKM_CONCATENATE_KEY_AND_BASE_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 13 # SPKM & SLL added capabilities -CKM_CONCATENATE_BASE_AND_DATA_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 14 # SPKM & SLL added capabilities -CKM_CONCATENATE_DATA_AND_BASE_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 15 # SPKM & SLL added capabilities -CKM_XOR_BASE_AND_DATA_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 16 # SPKM & SLL added capabilities -CKM_EXTRACT_KEY_FROM_KEY_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 17 # SPKM & SLL added capabilities -CKM_MD5_KEY_DERIVATION_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 18 # SPKM & SLL added capabilities -CKM_MD2_KEY_DERIVATION_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 19 # SPKM & SLL added capabilities -CKM_SHA1_KEY_DERIVATION_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 20 # SPKM & SLL added capabilities -CKM_GENERIC_SECRET_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 21 # Generation of secret keys -CKM_CAST5_KEY_GEN_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 22 # Entrust added capabilities -CKM_CAST5_ECB_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 23 # Entrust added capabilities -CKM_CAST5_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 24 # Entrust added capabilities -CKM_CAST5_MAC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 25 # Entrust added capabilities -CKM_PBE_SHA1_CAST5_CBC_OLD_XXX= CKM_VENDOR_DEFINED_OLD_XXX + 26 # Entrust added capabilities -CKM_KEY_TRANSLATION= CKM_VENDOR_DEFINED_OLD_XXX + 27 # Entrust added capabilities -CKM_XOR_BASE_AND_KEY= CKM_VENDOR_DEFINED + 27 -CKM_2DES_KEY_DERIVATION= CKM_VENDOR_DEFINED_OLD_XXX + 28 # Custom Gemplus Capabilities -CKM_INDIRECT_LOGIN_REENCRYPT= CKM_VENDOR_DEFINED_OLD_XXX + 29 # Used for indirect login -CKM_PBE_SHA1_DES3_EDE_CBC_OLD= CKM_VENDOR_DEFINED_OLD_XXX + 30 -CKM_PBE_SHA1_DES2_EDE_CBC_OLD= CKM_VENDOR_DEFINED_OLD_XXX + 31 -CKM_HAS160= (CKM_VENDOR_DEFINED + 0x100) -CKM_KCDSA_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x101) -CKM_KCDSA_HAS160= (CKM_VENDOR_DEFINED + 0x102) -CKM_SEED_KEY_GEN= (CKM_VENDOR_DEFINED + 0x103) -CKM_SEED_ECB= (CKM_VENDOR_DEFINED + 0x104) -CKM_SEED_CBC= (CKM_VENDOR_DEFINED + 0x105) -CKM_SEED_CBC_PAD= (CKM_VENDOR_DEFINED + 0x106) -CKM_SEED_MAC= (CKM_VENDOR_DEFINED + 0x107) -CKM_SEED_MAC_GENERAL= (CKM_VENDOR_DEFINED + 0x108) -CKM_KCDSA_SHA1= (CKM_VENDOR_DEFINED + 0x109) -CKM_KCDSA_SHA224= (CKM_VENDOR_DEFINED + 0x10A) -CKM_KCDSA_SHA256= (CKM_VENDOR_DEFINED + 0x10B) -CKM_KCDSA_SHA384= (CKM_VENDOR_DEFINED + 0x10C) -CKM_KCDSA_SHA512= (CKM_VENDOR_DEFINED + 0x10D) -CKM_KCDSA_PARAMETER_GEN= (CKM_VENDOR_DEFINED + 0x10F) -CKM_SHA224_RSA_PKCS_OLD= (CKM_VENDOR_DEFINED + 0x110) -CKM_SHA224_RSA_PKCS_PSS_OLD= (CKM_VENDOR_DEFINED + 0x111) -CKM_SHA224_OLD= (CKM_VENDOR_DEFINED + 0x112) -CKM_SHA224_HMAC_OLD= (CKM_VENDOR_DEFINED + 0x113) -CKM_SHA224_HMAC_GENERAL_OLD= (CKM_VENDOR_DEFINED + 0x114) -CKM_SHA224_KEY_DERIVATION_OLD= (CKM_VENDOR_DEFINED + 0x115) -CKM_DES3_CTR= (CKM_VENDOR_DEFINED + 0x116) -CKM_AES_CFB8= (CKM_VENDOR_DEFINED + 0x118) -CKM_AES_CFB128= (CKM_VENDOR_DEFINED + 0x119) -CKM_AES_OFB= (CKM_VENDOR_DEFINED + 0x11a) -CKM_AES_CTR= (CKM_VENDOR_DEFINED + 0x11b) -CKM_AES_GCM= (CKM_VENDOR_DEFINED + 0x11c) -CKM_ARIA_CFB8= (CKM_VENDOR_DEFINED + 0x11d) -CKM_ARIA_CFB128= (CKM_VENDOR_DEFINED + 0x11e) -CKM_ARIA_OFB= (CKM_VENDOR_DEFINED + 0x11f) -CKM_ARIA_CTR= (CKM_VENDOR_DEFINED + 0x120) -CKM_ARIA_GCM= (CKM_VENDOR_DEFINED + 0x121) -CKM_ECDSA_SHA224= (CKM_VENDOR_DEFINED + 0x122) -CKM_ECDSA_SHA256= (CKM_VENDOR_DEFINED + 0x123) -CKM_ECDSA_SHA384= (CKM_VENDOR_DEFINED + 0x124) -CKM_ECDSA_SHA512= (CKM_VENDOR_DEFINED + 0x125) -CKM_AES_GMAC= (CKM_VENDOR_DEFINED + 0x126) -CKM_ARIA_CMAC= (CKM_VENDOR_DEFINED + 0x128) -CKM_ARIA_CMAC_GENERAL= (CKM_VENDOR_DEFINED + 0x129) -CKM_SEED_CMAC= (CKM_VENDOR_DEFINED + 0x12c) -CKM_SEED_CMAC_GENERAL= (CKM_VENDOR_DEFINED + 0x12d) -CKM_DES3_CBC_PAD_IPSEC_OLD= 0x00000137 -CKM_DES3_CBC_PAD_IPSEC= (CKM_VENDOR_DEFINED + 0x12e) -CKM_AES_CBC_PAD_IPSEC_OLD= 0x00001089 -CKM_AES_CBC_PAD_IPSEC= (CKM_VENDOR_DEFINED + 0x12f) -CKM_ARIA_L_ECB= (CKM_VENDOR_DEFINED + 0x130) -CKM_ARIA_L_CBC= (CKM_VENDOR_DEFINED + 0x131) -CKM_ARIA_L_CBC_PAD= (CKM_VENDOR_DEFINED + 0x132) -CKM_ARIA_L_MAC= (CKM_VENDOR_DEFINED + 0x133) -CKM_ARIA_L_MAC_GENERAL= (CKM_VENDOR_DEFINED + 0x134) -CKM_SHA224_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x135) -CKM_SHA256_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x136) -CKM_SHA384_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x137) -CKM_SHA512_RSA_X9_31= (CKM_VENDOR_DEFINED + 0x138) -CKM_SHA1_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x139) -CKM_SHA224_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13a) -CKM_SHA256_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13b) -CKM_SHA384_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13c) -CKM_SHA512_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13d) -CKM_RSA_X9_31_NON_FIPS= (CKM_VENDOR_DEFINED + 0x13e) -CKM_DSA_SHA224= (CKM_VENDOR_DEFINED + 0x140) #DH -moved here to keep ECDSA SHA 2 same as FW4 -CKM_DSA_SHA256= (CKM_VENDOR_DEFINED + 0x141) -CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x142) -CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN= (CKM_VENDOR_DEFINED + 0x143) -CKM_SEED_CTR= (CKM_VENDOR_DEFINED + 0x144) -CKM_KCDSA_HAS160_NO_PAD= (CKM_VENDOR_DEFINED + 0x145) -CKM_KCDSA_SHA1_NO_PAD= (CKM_VENDOR_DEFINED + 0x146) -CKM_KCDSA_SHA224_NO_PAD= (CKM_VENDOR_DEFINED + 0x147) -CKM_KCDSA_SHA256_NO_PAD= (CKM_VENDOR_DEFINED + 0x148) -CKM_KCDSA_SHA384_NO_PAD= (CKM_VENDOR_DEFINED + 0x149) -CKM_KCDSA_SHA512_NO_PAD= (CKM_VENDOR_DEFINED + 0x151) -CKM_DES3_X919_MAC= (CKM_VENDOR_DEFINED + 0x150) -CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS= (CKM_VENDOR_DEFINED + 0x160) -CKM_ECDSA_GBCS_SHA256= (CKM_VENDOR_DEFINED + 0x161) -CKM_AES_CBC_PAD_EXTRACT= (CKM_VENDOR_DEFINED + 0x200) -CKM_AES_CBC_PAD_INSERT= (CKM_VENDOR_DEFINED + 0x201) -CKM_AES_CBC_PAD_EXTRACT_FLATTENED= (CKM_VENDOR_DEFINED + 0x202) -CKM_AES_CBC_PAD_INSERT_FLATTENED= (CKM_VENDOR_DEFINED + 0x203) -CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL= (CKM_VENDOR_DEFINED + 0x204) -CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL= (CKM_VENDOR_DEFINED + 0x205) -CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM=(CKM_VENDOR_DEFINED + 0x502) -CKM_DES2_DUKPT_PIN= (CKM_VENDOR_DEFINED + 0x611) -CKM_DES2_DUKPT_MAC= (CKM_VENDOR_DEFINED + 0x612) -CKM_DES2_DUKPT_MAC_RESP= (CKM_VENDOR_DEFINED + 0x613) -CKM_DES2_DUKPT_DATA= (CKM_VENDOR_DEFINED + 0x614) -CKM_DES2_DUKPT_DATA_RESP= (CKM_VENDOR_DEFINED + 0x615) -CKM_ECIES= (CKM_VENDOR_DEFINED + 0xA00) -CKM_XOR_BASE_AND_DATA_W_KDF= (CKM_VENDOR_DEFINED + 0xA01) -CKM_NIST_PRF_KDF= (CKM_VENDOR_DEFINED + 0xA02) -CKM_PRF_KDF= (CKM_VENDOR_DEFINED + 0xA03) -CKDHP_STANDARD= 0x00000001 -CKDHP_ECDH1_COFACTOR= 0x00000001 -CKDHP_MODIFIED= 0x00000002 # Not implemented */ -CKDHP_ECDH1= 0x00000003 -CKES_XOR= 0x00000001 -CKES_DES3_CBC_PAD= 0x00000002 -CKES_AES_CBC_PAD= 0x00000003 -CKES_DES3_CBC= 0x00000004 -CKES_AES_CBC= 0x00000005 -CKMS_HMAC_SHA1= 0x00000001 -CKMS_SHA1= 0x00000002 -CKMS_HMAC_SHA224= 0x00000003 -CKMS_SHA224= 0x00000004 -CKMS_HMAC_SHA256= 0x00000005 -CKMS_SHA256= 0x00000006 -CKMS_HMAC_SHA384= 0x00000007 -CKMS_SHA384= 0x00000008 -CKMS_HMAC_SHA512= 0x00000009 -CKMS_SHA512= 0x0000000a -CKMS_HMAC_RIPEMD160= 0x0000000b -CKMS_RIPEMD160= 0x0000000c -CK_NIST_PRF_KDF_DES3_CMAC= 0x00000001 -CK_NIST_PRF_KDF_AES_CMAC= 0x00000002 -CK_PRF_KDF_ARIA_CMAC= 0x00000003 -CK_PRF_KDF_SEED_CMAC= 0x00000004 -LUNA_PRF_KDF_ENCODING_SCHEME_1= 0x00000000 -LUNA_PRF_KDF_ENCODING_SCHEME_2= 0x00000001 -CKR_INSERTION_CALLBACK_NOT_SUPPORTED=0x00000141 -CKR_FUNCTION_PARALLEL= 0x0052 -CKR_SESSION_EXCLUSIVE_EXISTS= 0x00B2 -CKR_RC_ERROR= (CKR_VENDOR_DEFINED + 0x04) -CKR_CONTAINER_HANDLE_INVALID= (CKR_VENDOR_DEFINED + 0x05) -CKR_TOO_MANY_CONTAINERS= (CKR_VENDOR_DEFINED + 0x06) -CKR_USER_LOCKED_OUT= (CKR_VENDOR_DEFINED + 0x07) -CKR_CLONING_PARAMETER_ALREADY_EXISTS=(CKR_VENDOR_DEFINED + 0x08) -CKR_CLONING_PARAMETER_MISSING= (CKR_VENDOR_DEFINED + 0x09) -CKR_CERTIFICATE_DATA_MISSING= (CKR_VENDOR_DEFINED + 0x0a) -CKR_CERTIFICATE_DATA_INVALID= (CKR_VENDOR_DEFINED + 0x0b) -CKR_ACCEL_DEVICE_ERROR= (CKR_VENDOR_DEFINED + 0x0c) -CKR_WRAPPING_ERROR= (CKR_VENDOR_DEFINED + 0x0d) -CKR_UNWRAPPING_ERROR= (CKR_VENDOR_DEFINED + 0x0e) -CKR_MAC_MISSING= (CKR_VENDOR_DEFINED + 0x0f) -CKR_DAC_POLICY_PID_MISMATCH= (CKR_VENDOR_DEFINED + 0x10) -CKR_DAC_MISSING= (CKR_VENDOR_DEFINED + 0x11) -CKR_BAD_DAC= (CKR_VENDOR_DEFINED + 0x12) -CKR_SSK_MISSING= (CKR_VENDOR_DEFINED + 0x13) -CKR_BAD_MAC= (CKR_VENDOR_DEFINED + 0x14) -CKR_DAK_MISSING= (CKR_VENDOR_DEFINED + 0x15) -CKR_BAD_DAK= (CKR_VENDOR_DEFINED + 0x16) -CKR_SIM_AUTHORIZATION_FAILED= (CKR_VENDOR_DEFINED + 0x17) -CKR_SIM_VERSION_UNSUPPORTED= (CKR_VENDOR_DEFINED + 0x18) -CKR_SIM_CORRUPT_DATA= (CKR_VENDOR_DEFINED + 0x19) -CKR_USER_NOT_AUTHORIZED= (CKR_VENDOR_DEFINED + 0x1a) -CKR_MAX_OBJECT_COUNT_EXCEEDED= (CKR_VENDOR_DEFINED + 0x1b) -CKR_SO_LOGIN_FAILURE_THRESHOLD= (CKR_VENDOR_DEFINED + 0x1c) -CKR_SIM_AUTHFORM_INVALID= (CKR_VENDOR_DEFINED + 0x1d) -CKR_CITS_DAK_MISSING= (CKR_VENDOR_DEFINED + 0x1e) -CKR_UNABLE_TO_CONNECT= (CKR_VENDOR_DEFINED + 0x1f) -CKR_PARTITION_DISABLED= (CKR_VENDOR_DEFINED + 0x20) -CKR_CALLBACK_ERROR= (CKR_VENDOR_DEFINED + 0x21) -CKR_SECURITY_PARAMETER_MISSING= (CKR_VENDOR_DEFINED + 0x22) -CKR_SP_TIMEOUT= (CKR_VENDOR_DEFINED + 0x23) -CKR_TIMEOUT= (CKR_VENDOR_DEFINED + 0x24) -CKR_ECC_UNKNOWN_CURVE= (CKR_VENDOR_DEFINED + 0x25) -CKR_MTK_ZEROIZED= (CKR_VENDOR_DEFINED + 0x26) -CKR_MTK_STATE_INVALID= (CKR_VENDOR_DEFINED + 0x27) -CKR_INVALID_ENTRY_TYPE= (CKR_VENDOR_DEFINED + 0x28) -CKR_MTK_SPLIT_INVALID= (CKR_VENDOR_DEFINED + 0x29) -CKR_HSM_STORAGE_FULL= (CKR_VENDOR_DEFINED + 0x2a) -CKR_DEVICE_TIMEOUT= (CKR_VENDOR_DEFINED + 0x2b) -CKR_CONTAINER_OBJECT_STORAGE_FULL= (CKR_VENDOR_DEFINED + 0x2C) -CKR_PED_CLIENT_NOT_RUNNING= (CKR_VENDOR_DEFINED + 0x2D) -CKR_PED_UNPLUGGED= (CKR_VENDOR_DEFINED + 0x2E) -CKR_ECC_POINT_INVALID= (CKR_VENDOR_DEFINED + 0x2F) -CKR_OPERATION_NOT_ALLOWED= (CKR_VENDOR_DEFINED + 0x30) -CKR_LICENSE_CAPACITY_EXCEEDED= (CKR_VENDOR_DEFINED + 0x31) -CKR_LOG_FILE_NOT_OPEN= (CKR_VENDOR_DEFINED + 0x32) -CKR_LOG_FILE_WRITE_ERROR= (CKR_VENDOR_DEFINED + 0x33) -CKR_LOG_BAD_FILE_NAME= (CKR_VENDOR_DEFINED + 0x34) -CKR_LOG_FULL= (CKR_VENDOR_DEFINED + 0x35) -CKR_LOG_NO_KCV= (CKR_VENDOR_DEFINED + 0x36) -CKR_LOG_BAD_RECORD_HMAC= (CKR_VENDOR_DEFINED + 0x37) -CKR_LOG_BAD_TIME= (CKR_VENDOR_DEFINED + 0x38) -CKR_LOG_AUDIT_NOT_INITIALIZED= (CKR_VENDOR_DEFINED + 0x39) -CKR_LOG_RESYNC_NEEDED= (CKR_VENDOR_DEFINED + 0x3A) -CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS= (CKR_VENDOR_DEFINED + 0x3B) -CKR_AUDIT_LOGIN_FAILURE_THRESHOLD= (CKR_VENDOR_DEFINED + 0x3C) -CKR_INVALID_FUF_TARGET= (CKR_VENDOR_DEFINED + 0x3D) -CKR_INVALID_FUF_HEADER= (CKR_VENDOR_DEFINED + 0x3E) -CKR_INVALID_FUF_VERSION= (CKR_VENDOR_DEFINED + 0x3F) -CKR_ECC_ECC_RESULT_AT_INF= (CKR_VENDOR_DEFINED + 0x40) -CKR_AGAIN= (CKR_VENDOR_DEFINED + 0x41) -CKR_TOKEN_COPIED= (CKR_VENDOR_DEFINED + 0x42) -CKR_SLOT_NOT_EMPTY= (CKR_VENDOR_DEFINED + 0x43) -CKR_USER_ALREADY_ACTIVATED= (CKR_VENDOR_DEFINED + 0x44) -CKR_STC_NO_CONTEXT= (CKR_VENDOR_DEFINED + 0x45) -CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED= (CKR_VENDOR_DEFINED + 0x46) -CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED=(CKR_VENDOR_DEFINED + 0x47) -CKR_STC_DH_KEYGEN_ERROR= (CKR_VENDOR_DEFINED + 0x48) -CKR_STC_CIPHER_SUITE_REJECTED= (CKR_VENDOR_DEFINED + 0x49) -CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP= (CKR_VENDOR_DEFINED + 0x4a) -CKR_STC_COMPUTE_DH_KEY_ERROR= (CKR_VENDOR_DEFINED + 0x4b) -CKR_STC_FIRST_PHASE_KDF_ERROR= (CKR_VENDOR_DEFINED + 0x4c) -CKR_STC_SECOND_PHASE_KDF_ERROR= (CKR_VENDOR_DEFINED + 0x4d) -CKR_STC_KEY_CONFIRMATION_FAILED= (CKR_VENDOR_DEFINED + 0x4e) -CKR_STC_NO_SESSION_KEY= (CKR_VENDOR_DEFINED + 0x4f) -CKR_STC_RESPONSE_BAD_MAC= (CKR_VENDOR_DEFINED + 0x50) -CKR_STC_NOT_ENABLED= (CKR_VENDOR_DEFINED + 0x51) -CKR_STC_CLIENT_HANDLE_INVALID= (CKR_VENDOR_DEFINED + 0x52) -CKR_STC_SESSION_INVALID= (CKR_VENDOR_DEFINED + 0x53) -CKR_STC_CONTAINER_INVALID= (CKR_VENDOR_DEFINED + 0x54) -CKR_STC_SEQUENCE_NUM_INVALID= (CKR_VENDOR_DEFINED + 0x55) -CKR_STC_NO_CHANNEL= (CKR_VENDOR_DEFINED + 0x56) -CKR_STC_RESPONSE_DECRYPT_ERROR= (CKR_VENDOR_DEFINED + 0x57) -CKR_STC_RESPONSE_REPLAYED= (CKR_VENDOR_DEFINED + 0X58) -CKR_STC_REKEY_CHANNEL_MISMATCH= (CKR_VENDOR_DEFINED + 0X59) -CKR_STC_RSA_ENCRYPT_ERROR= (CKR_VENDOR_DEFINED + 0X5a) -CKR_STC_RSA_SIGN_ERROR= (CKR_VENDOR_DEFINED + 0X5b) -CKR_STC_RSA_DECRYPT_ERROR= (CKR_VENDOR_DEFINED + 0X5c) -CKR_STC_RESPONSE_UNEXPECTED_KEY= (CKR_VENDOR_DEFINED + 0X5d) -CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE= (CKR_VENDOR_DEFINED + 0X5e) -CKR_STC_UNEXPECTED_DH_DATA_SIZE= (CKR_VENDOR_DEFINED + 0X5f) -CKR_STC_OPEN_CIPHER_MISMATCH= (CKR_VENDOR_DEFINED + 0X60) -CKR_STC_OPEN_DHNIST_PUBKEY_ERROR= (CKR_VENDOR_DEFINED + 0X61) -CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X62) -CKR_STC_OPEN_RESP_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X63) -CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL= (CKR_VENDOR_DEFINED + 0X64) -CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X65) -CKR_STC_ACTIVATE_RESP_GEN_FAIL= (CKR_VENDOR_DEFINED + 0X66) -CKR_CHALLENGE_INCORRECT= (CKR_VENDOR_DEFINED + 0X67) -CKR_ACCESS_ID_INVALID= (CKR_VENDOR_DEFINED + 0X68) -CKR_ACCESS_ID_ALREADY_EXISTS= (CKR_VENDOR_DEFINED + 0X69) -CKR_OBJECT_READ_ONLY= (CKR_VENDOR_DEFINED + 0x114) -CKR_KEY_NOT_ACTIVE= (CKR_VENDOR_DEFINED + 0x136) -CKO_TOKEN_ROLE_POLICY_SET= (CKO_VENDOR_DEFINED + 0x0001) -CKO_TOKEN_ROLE_POLICY= (CKO_VENDOR_DEFINED + 0x0002) -CKO_TOKEN_ROLE_DESCRIPTOR= (CKO_VENDOR_DEFINED + 0x0003) -CKO_TOKEN_ROLE_STATE= (CKO_VENDOR_DEFINED + 0x0004) -CKO_CERTIFICATE_REQUEST= (CKO_VENDOR_DEFINED + 0x0201) -CKO_CRL= (CKO_VENDOR_DEFINED + 0x0202) -CKO_ADAPTER= (CKO_VENDOR_DEFINED + 0x020A) -CKO_SLOT= (CKO_VENDOR_DEFINED + 0x020B) -CKO_FM= (CKO_VENDOR_DEFINED + 0x020C) -CKS_RO_SO_FUNCTIONS= 5 # still in PKCS #11 space */ -CKS_RO_VENDOR_DEFINED= 0x80000000 -CKS_RW_VENDOR_DEFINED= 0x90000000 -CKS_RW_AUDIT_FUNCTIONS= (CKS_RW_VENDOR_DEFINED + 0x001) -CAF_ROLE_STATE_INITIALIZED= 0x01 -CAF_ROLE_STATE_LOCKED_OUT= 0x02 -CAF_ROLE_STATE_ACTIVATED= 0x04 -CAF_ROLE_STATE_HAS_RDK= 0x08 -CAF_ROLE_STATE_PIN_CHANGE= 0x10 -CAF_ROLE_STATE_CHALLENGE_CHANGE=0x20 -CKA_ROLE_AUTH_NONE= 0x00 -CKA_ROLE_AUTH_PASSWORD= 0x01 -CKA_ROLE_AUTH_PED= 0x02 -CKA_ROLE_AUTH_INVALID= 0xFF -CAF_M_OF_N_REQUIRED= 0x00000001 -CAF_M_OF_N_ACTIVATED= 0x00000002 -CAF_M_OF_N_GENERATED= 0x00000004 -CAF_M_OF_N_CLONEABLE= 0x00000008 -CKCAO_Encrypt=0 -CKCAO_Decrypt=1 -CKCAO_Sign= 2 -CKCAO_Verify= 3 -CKCAO_Digest= 4 -CK_HA_MAX_MEMBERS= 32 -CKHSC_CERT_TYPE_TCTRUST_MAC= 0x00000001 -CKHSC_CERT_TYPE_TCTRUST_DAC= 0x00000002 -CKHSC_CERT_TYPE_CITS_ROOT= 0x00000003 -CKHSC_CERT_TYPE_CITS_MICHOC= 0x00000004 -CKHSC_CERT_TYPE_CITS_DAC= 0x00000005 -CKHSC_CERT_TYPE_ECC_MIC= 0x00000006 -CKHSC_CERT_TYPE_ECC_HOC= 0x00000007 -CKHSC_CERT_TYPE_ECC_DAC= 0x00000008 -CKHSC_CERT_TYPE_TWC= 0x00000009 -CKHSC_CERT_TYPE_TWC2= 0x0000000A -CKHSC_CERT_TYPE_TWC3= 0x0000000B -CKA_SIM_NO_AUTHORIZATION=0 # no authorization needed -CKA_SIM_PASSWORD= 1 # plain-text passwords -CKA_SIM_CHALLENGE= 2 # challenge secrets emitted through the secure port -CKA_SIM_SECURE_PORT= 3 # PED keys -CKA_SIM_PORTABLE_NO_AUTHORIZATION=4 # no authorization needed, portable -CKA_SIM_PORTABLE_PASSWORD= 5 # plain-text passwords, portable -CKA_SIM_PORTABLE_CHALLENGE= 6 # challenge secrets emitted through the secure port, portable -CKA_SIM_PORTABLE_SECURE_PORT= 7 # PED keys, portable -CK_NULL_ELEMENT= (-1) -CK_CRYPTOKI_ELEMENT= 0x00000000 -CK_PARAM_ELEMENT= 0x00000001 -CK_CONTAINER_ACTIVATION_ELEMENT=0x00000002 -CK_MOFN_ACTIVATION_ELEMENT= 0x00000003 -CK_CONTAINER_ELEMENT= 0x00000004 -CK_CLONING_PART1_OVERHEAD= 8192 -CK_CLONING_PART2_OVERHEAD= 76 -CK_FLATTENED_OBJECT_OVERHEAD= 3264 -CK_STORAGE_HOST= 0x00000000 -CK_STORAGE_PED_USB_MEMORY= 0x00000001 -CK_STORAGE_HSM_USB_MEMORY= 0x00000002 -CK_MTK_STATE_FLAG_RESPLIT_ABORTED= 0x00000001 -CK_MTK_STATE_FLAG_HARD_ZEROIZE= 0x00000002 -CK_MTK_STATE_FLAG_SOFT_ZEROIZE= 0x00000004 -CK_MTK_STATE_FLAG_LOCKED= 0x00000008 -CK_MAX_CLUSTER_MEMBERS= 8 -AKEP2_XDH_SIZE= 128 # size of LKM public key -AKEP2_MAX_DIGEST_SIZE= 32 -AKEP2_NID_SIZE= 20 -CK_PED_ID_LOCAL= 0x0000 -CK_PED_ID_MAX= 0xFFFE -CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT= 0x00000001 -CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET= 0x00000002 +NULL_PTR = 0 +C_LIBRARY_VERSION = 0x510 # v5.10 decimal */ +CK_TOKEN_SERIAL_NUMBER_SIZE = 16 +CK_EFFECTIVELY_INFINITE = 0 +CKU_CRYPTO_OFFICER = CKU_USER +CKU_LIMITED_USER = 0x80000001 +CKU_LIMITED_USER_OLD = 0x8000001 +CKU_CRYPTO_USER = CKU_LIMITED_USER +CKU_AUDIT = 0x80000002 +CKU_INVALID_USER_TYPE = 0xffffffff +CKU_VENDOR_DEFINED = 0x80000000 +CKF_EXCLUSIVE_SESSION = 0x0001 +CKF_EXCLUSIVE_EXISTS = 0x0010 +CKF_SO_SESSION = 0x8000 +CKF_AUDIT_SESSION = 0x10000 +CKF_VENDER_DEFINED = 0x10000000 +CKF_IGNORE_HAONLY = (CKF_VENDER_DEFINED << 3) +CKF_USE_APPID = (CKF_VENDER_DEFINED << 2) +CKF_ADMIN_TOKEN = 0x10000000 +CKF_ENTRUST_READY = 0x00000001 +CKF_NO_CLEAR_PINS = 0x00000002 +CKF_AUTH_PROTECTION = 0x00000004 +CKF_NO_PUBLIC_CRYPTO = 0x00000008 +CKF_TAMPER_BEFORE_UPGRADE = 0x00000010 +CKF_INCREASED_SECURITY = 0x00000020 +CKF_FIPS_ALGORITHMS = 0x00000040 +CKF_FULL_SMS_ENC = 0x00000080 +CKF_FULL_SMS_SIGN = 0x00000100 +CKF_PURE_P11 = 0x00000200 +CKF_DES_EVEN_PARITY_ALLOWED = 0x00000400 +CKF_USER_ECC_DP_ALLOWED = 0x00000800 +CKF_MODE_LOCKED = 0x10000000 +CKA_START_DATE_OLD_XXX = 0x0083 # Kept temporarily for backward compatibility with Beta version. Use CKA_START_DATE +CKA_END_DATE_OLD_XXX = 0x0084 # Kept temporarily for backward compatibility with Beta version. Use CKA_END_DATE +CKD_SHA224_KDF = 0x00000005 +CKD_SHA224_KDF_OLD = 0x80000003 +CKD_SHA256_KDF = 0x00000006 +CKD_SHA256_KDF_OLD = 0x80000004 +CKD_SHA384_KDF = 0x00000007 +CKD_SHA384_KDF_OLD = 0x80000005 +CKD_SHA512_KDF = 0x00000008 +CKD_SHA512_KDF_OLD = 0x80000006 +CKD_RIPEMD160_KDF = 0x80000007 +CKD_SHA1_NIST_KDF = 0x00000012 +CKD_SHA224_NIST_KDF = 0x80000013 +CKD_SHA256_NIST_KDF = 0x80000014 +CKD_SHA384_NIST_KDF = 0x80000015 +CKD_SHA512_NIST_KDF = 0x80000016 +CKD_RIPEMD160_NIST_KDF = 0x80000017 +CKD_SHA1_SES_KDF = 0x82000000 +CKD_SHA224_SES_KDF = 0x83000000 +CKD_SHA256_SES_KDF = 0x84000000 +CKD_SHA384_SES_KDF = 0x85000000 +CKD_SHA512_SES_KDF = 0x86000000 +CKD_RIPEMD160_SES_KDF = 0x87000000 +CKD_SES_ENC_CTR = 0x00000001 +CKD_SES_AUTH_CTR = 0x00000002 +CKD_SES_ALT_ENC_CTR = 0x00000003 +CKD_SES_ALT_AUTH_CTR = 0x00000004 +CKD_SHA1_KDF_ASN1 = 0x00000003 # not supported +CKD_SHA1_KDF_CONCATENATE = 0x00000004 +CKD_SHA1_KDF_CONCATENATE_X9_42 = CKD_SHA1_KDF_CONCATENATE +CKD_SHA1_KDF_CONCATENATE_NIST = 0x80000001 +CKD_SHA1_KDF_ASN1_X9_42 = CKD_SHA1_KDF_ASN1 # not supported +CKD_SHA1_KDF_ASN1_NIST = 0x80000002 # not supported +CKK_KCDSA = CKK_VENDOR_DEFINED + 0x10 +CKK_SEED = CKK_VENDOR_DEFINED + 0x11 +CKA_CCM_PRIVATE = (CKA_VENDOR_DEFINED | 0x0001) +CKA_FINGERPRINT_SHA1 = (CKA_VENDOR_DEFINED | 0x0002) +CKA_PKC_TCTRUST = (CKA_VENDOR_DEFINED | 0x0003) +CKA_PKC_CITS = (CKA_VENDOR_DEFINED | 0x0004) +CKA_OUID = (CKA_VENDOR_DEFINED | 0x0005) +CKA_X9_31_GENERATED = (CKA_VENDOR_DEFINED | 0x0006) +CKA_PKC_ECC = (CKA_VENDOR_DEFINED | 0x0007) +CKA_EKM_UID = (CKA_VENDOR_DEFINED | 0x0008) +CKA_TOKEN_ROLE_POLICIES = (CKA_VENDOR_DEFINED | 0x0010) +CKA_ROLE_DESCRIPTORS = (CKA_VENDOR_DEFINED | 0x0011) +CKA_USER_VALUE = (CKA_VENDOR_DEFINED | 0x0012) +CKA_INITIALIZER = (CKA_VENDOR_DEFINED | 0x0013) +CKA_POLICY = (CKA_VENDOR_DEFINED | 0x0014) +CKA_ACTIVE = (CKA_VENDOR_DEFINED | 0x0015) +CKA_INITIALIZED = (CKA_VENDOR_DEFINED | 0x0016) +CKA_PIN_TO_BE_CHANGED = (CKA_VENDOR_DEFINED | 0x0017) +CKA_LOCKED_OUT = (CKA_VENDOR_DEFINED | 0x0018) +CKA_ACTIVATED = (CKA_VENDOR_DEFINED | 0x0019) +CKA_HAS_DOMAIN = (CKA_VENDOR_DEFINED | 0x001A) +CKA_LOGIN_ATTEMPTS_LEFT = (CKA_VENDOR_DEFINED | 0x001B) +CKA_PRIMARY_AUTH_METHOD = (CKA_VENDOR_DEFINED | 0x001C) +CKA_SECONDARY_AUTH_METHOD = (CKA_VENDOR_DEFINED | 0x001D) +CKA_USAGE_COUNT = (CKA_VENDOR_DEFINED + 0x0101) +CKA_SLOT_ID = (CKA_VENDOR_DEFINED + 0x0151) +CKA_MAX_SESSIONS = (CKA_VENDOR_DEFINED | 0x0155) +CKA_MIN_PIN_LEN = (CKA_VENDOR_DEFINED | 0x0156) +CKA_FLAGS = (CKA_VENDOR_DEFINED | 0x0159) +CKA_USAGE_LIMIT = (CKA_VENDOR_DEFINED + 0x0200) +CKA_SECURITY_MODE = (CKA_VENDOR_DEFINED + 0x0140) +CKA_TRANSPORT_MODE = (CKA_VENDOR_DEFINED + 0x0141) +CKA_BATCH = (CKA_VENDOR_DEFINED + 0x0142) +CKA_HW_STATUS = (CKA_VENDOR_DEFINED + 0x0143) +CKA_FREE_MEM = (CKA_VENDOR_DEFINED + 0x0144) +CKA_TAMPER_CMD = (CKA_VENDOR_DEFINED + 0x0145) +CKA_DATE_OF_MANUFACTURE = (CKA_VENDOR_DEFINED + 0x0146) +CKA_HALT_CMD = (CKA_VENDOR_DEFINED + 0x0147) +CKA_APPLICATION_COUNT = (CKA_VENDOR_DEFINED + 0x0148) +CKA_FW_VERSION = (CKA_VENDOR_DEFINED + 0x0149) +CKA_RESCAN_PERIPHERALS_CMD = (CKA_VENDOR_DEFINED + 0x014A) +CKA_RTC_AAC_ENABLED = (CKA_VENDOR_DEFINED + 0x014B) +CKA_RTC_AAC_GUARD_SECONDS = (CKA_VENDOR_DEFINED + 0x014C) +CKA_RTC_AAC_GUARD_COUNT = (CKA_VENDOR_DEFINED + 0x014D) +CKA_RTC_AAC_GUARD_DURATION = (CKA_VENDOR_DEFINED + 0x014E) +CKA_HW_EXT_INFO_STR = (CKA_VENDOR_DEFINED + 0x014F) +CKA_TEMPERATURE_STR = (CKA_VENDOR_DEFINED + 0x0150) +CKA_GENERIC_1 = (CKA_VENDOR_DEFINED + 0x1000) +CKA_GENERIC_2 = (CKA_VENDOR_DEFINED + 0x1001) +CKA_GENERIC_3 = (CKA_VENDOR_DEFINED + 0x1002) +CKA_FINGERPRINT_SHA256 = (CKA_VENDOR_DEFINED + 0x1003) +CKM_VENDOR_DEFINED_OLD_XXX = 0x00008000 +CKM_CAST_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 0 # Entrust added capabilities +CKM_CAST_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 1 # Entrust added capabilities +CKM_CAST_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 2 # Entrust added capabilities +CKM_CAST_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 3 # Entrust added capabilities +CKM_CAST3_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 4 # Entrust added capabilities +CKM_CAST3_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 5 # Entrust added capabilities +CKM_CAST3_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 6 # Entrust added capabilities +CKM_CAST3_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 7 # Entrust added capabilities +CKM_PBE_MD2_DES_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 8 # Password based encryption +CKM_PBE_MD5_DES_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 9 # Password based encryption +CKM_PBE_MD5_CAST_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 10 # Password based encryption +CKM_PBE_MD5_CAST3_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 11 # Password based encryption +CKM_CONCATENATE_BASE_AND_KEY_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 12 # SPKM & SLL added capabilities +CKM_CONCATENATE_KEY_AND_BASE_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 13 # SPKM & SLL added capabilities +CKM_CONCATENATE_BASE_AND_DATA_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 14 # SPKM & SLL added capabilities +CKM_CONCATENATE_DATA_AND_BASE_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 15 # SPKM & SLL added capabilities +CKM_XOR_BASE_AND_DATA_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 16 # SPKM & SLL added capabilities +CKM_EXTRACT_KEY_FROM_KEY_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 17 # SPKM & SLL added capabilities +CKM_MD5_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 18 # SPKM & SLL added capabilities +CKM_MD2_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 19 # SPKM & SLL added capabilities +CKM_SHA1_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 20 # SPKM & SLL added capabilities +CKM_GENERIC_SECRET_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 21 # Generation of secret keys +CKM_CAST5_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 22 # Entrust added capabilities +CKM_CAST5_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 23 # Entrust added capabilities +CKM_CAST5_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 24 # Entrust added capabilities +CKM_CAST5_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 25 # Entrust added capabilities +CKM_PBE_SHA1_CAST5_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 26 # Entrust added capabilities +CKM_KEY_TRANSLATION = CKM_VENDOR_DEFINED_OLD_XXX + 27 # Entrust added capabilities +CKM_XOR_BASE_AND_KEY = CKM_VENDOR_DEFINED + 27 +CKM_2DES_KEY_DERIVATION = CKM_VENDOR_DEFINED_OLD_XXX + 28 # Custom Gemplus Capabilities +CKM_INDIRECT_LOGIN_REENCRYPT = CKM_VENDOR_DEFINED_OLD_XXX + 29 # Used for indirect login +CKM_PBE_SHA1_DES3_EDE_CBC_OLD = CKM_VENDOR_DEFINED_OLD_XXX + 30 +CKM_PBE_SHA1_DES2_EDE_CBC_OLD = CKM_VENDOR_DEFINED_OLD_XXX + 31 +CKM_HAS160 = (CKM_VENDOR_DEFINED + 0x100) +CKM_KCDSA_KEY_PAIR_GEN = (CKM_VENDOR_DEFINED + 0x101) +CKM_KCDSA_HAS160 = (CKM_VENDOR_DEFINED + 0x102) +CKM_SEED_KEY_GEN = (CKM_VENDOR_DEFINED + 0x103) +CKM_SEED_ECB = (CKM_VENDOR_DEFINED + 0x104) +CKM_SEED_CBC = (CKM_VENDOR_DEFINED + 0x105) +CKM_SEED_CBC_PAD = (CKM_VENDOR_DEFINED + 0x106) +CKM_SEED_MAC = (CKM_VENDOR_DEFINED + 0x107) +CKM_SEED_MAC_GENERAL = (CKM_VENDOR_DEFINED + 0x108) +CKM_KCDSA_SHA1 = (CKM_VENDOR_DEFINED + 0x109) +CKM_KCDSA_SHA224 = (CKM_VENDOR_DEFINED + 0x10A) +CKM_KCDSA_SHA256 = (CKM_VENDOR_DEFINED + 0x10B) +CKM_KCDSA_SHA384 = (CKM_VENDOR_DEFINED + 0x10C) +CKM_KCDSA_SHA512 = (CKM_VENDOR_DEFINED + 0x10D) +CKM_KCDSA_PARAMETER_GEN = (CKM_VENDOR_DEFINED + 0x10F) +CKM_SHA224_RSA_PKCS_OLD = (CKM_VENDOR_DEFINED + 0x110) +CKM_SHA224_RSA_PKCS_PSS_OLD = (CKM_VENDOR_DEFINED + 0x111) +CKM_SHA224_OLD = (CKM_VENDOR_DEFINED + 0x112) +CKM_SHA224_HMAC_OLD = (CKM_VENDOR_DEFINED + 0x113) +CKM_SHA224_HMAC_GENERAL_OLD = (CKM_VENDOR_DEFINED + 0x114) +CKM_SHA224_KEY_DERIVATION_OLD = (CKM_VENDOR_DEFINED + 0x115) +CKM_DES3_CTR = (CKM_VENDOR_DEFINED + 0x116) +CKM_AES_CFB8 = (CKM_VENDOR_DEFINED + 0x118) +CKM_AES_CFB128 = (CKM_VENDOR_DEFINED + 0x119) +CKM_AES_OFB = (CKM_VENDOR_DEFINED + 0x11a) +CKM_AES_CTR = (CKM_VENDOR_DEFINED + 0x11b) +CKM_AES_GCM = (CKM_VENDOR_DEFINED + 0x11c) +CKM_ARIA_CFB8 = (CKM_VENDOR_DEFINED + 0x11d) +CKM_ARIA_CFB128 = (CKM_VENDOR_DEFINED + 0x11e) +CKM_ARIA_OFB = (CKM_VENDOR_DEFINED + 0x11f) +CKM_ARIA_CTR = (CKM_VENDOR_DEFINED + 0x120) +CKM_ARIA_GCM = (CKM_VENDOR_DEFINED + 0x121) +CKM_ECDSA_SHA224 = (CKM_VENDOR_DEFINED + 0x122) +CKM_ECDSA_SHA256 = (CKM_VENDOR_DEFINED + 0x123) +CKM_ECDSA_SHA384 = (CKM_VENDOR_DEFINED + 0x124) +CKM_ECDSA_SHA512 = (CKM_VENDOR_DEFINED + 0x125) +CKM_AES_GMAC = (CKM_VENDOR_DEFINED + 0x126) +CKM_ARIA_CMAC = (CKM_VENDOR_DEFINED + 0x128) +CKM_ARIA_CMAC_GENERAL = (CKM_VENDOR_DEFINED + 0x129) +CKM_SEED_CMAC = (CKM_VENDOR_DEFINED + 0x12c) +CKM_SEED_CMAC_GENERAL = (CKM_VENDOR_DEFINED + 0x12d) +CKM_DES3_CBC_PAD_IPSEC_OLD = 0x00000137 +CKM_DES3_CBC_PAD_IPSEC = (CKM_VENDOR_DEFINED + 0x12e) +CKM_AES_CBC_PAD_IPSEC_OLD = 0x00001089 +CKM_AES_CBC_PAD_IPSEC = (CKM_VENDOR_DEFINED + 0x12f) +CKM_ARIA_L_ECB = (CKM_VENDOR_DEFINED + 0x130) +CKM_ARIA_L_CBC = (CKM_VENDOR_DEFINED + 0x131) +CKM_ARIA_L_CBC_PAD = (CKM_VENDOR_DEFINED + 0x132) +CKM_ARIA_L_MAC = (CKM_VENDOR_DEFINED + 0x133) +CKM_ARIA_L_MAC_GENERAL = (CKM_VENDOR_DEFINED + 0x134) +CKM_SHA224_RSA_X9_31 = (CKM_VENDOR_DEFINED + 0x135) +CKM_SHA256_RSA_X9_31 = (CKM_VENDOR_DEFINED + 0x136) +CKM_SHA384_RSA_X9_31 = (CKM_VENDOR_DEFINED + 0x137) +CKM_SHA512_RSA_X9_31 = (CKM_VENDOR_DEFINED + 0x138) +CKM_SHA1_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x139) +CKM_SHA224_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13a) +CKM_SHA256_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13b) +CKM_SHA384_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13c) +CKM_SHA512_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13d) +CKM_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13e) +CKM_DSA_SHA224 = (CKM_VENDOR_DEFINED + 0x140) # DH -moved here to keep ECDSA SHA 2 same as FW4 +CKM_DSA_SHA256 = (CKM_VENDOR_DEFINED + 0x141) +CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN = (CKM_VENDOR_DEFINED + 0x142) +CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN = (CKM_VENDOR_DEFINED + 0x143) +CKM_SEED_CTR = (CKM_VENDOR_DEFINED + 0x144) +CKM_KCDSA_HAS160_NO_PAD = (CKM_VENDOR_DEFINED + 0x145) +CKM_KCDSA_SHA1_NO_PAD = (CKM_VENDOR_DEFINED + 0x146) +CKM_KCDSA_SHA224_NO_PAD = (CKM_VENDOR_DEFINED + 0x147) +CKM_KCDSA_SHA256_NO_PAD = (CKM_VENDOR_DEFINED + 0x148) +CKM_KCDSA_SHA384_NO_PAD = (CKM_VENDOR_DEFINED + 0x149) +CKM_KCDSA_SHA512_NO_PAD = (CKM_VENDOR_DEFINED + 0x151) +CKM_DES3_X919_MAC = (CKM_VENDOR_DEFINED + 0x150) +CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS = (CKM_VENDOR_DEFINED + 0x160) +CKM_ECDSA_GBCS_SHA256 = (CKM_VENDOR_DEFINED + 0x161) +CKM_AES_CBC_PAD_EXTRACT = (CKM_VENDOR_DEFINED + 0x200) +CKM_AES_CBC_PAD_INSERT = (CKM_VENDOR_DEFINED + 0x201) +CKM_AES_CBC_PAD_EXTRACT_FLATTENED = (CKM_VENDOR_DEFINED + 0x202) +CKM_AES_CBC_PAD_INSERT_FLATTENED = (CKM_VENDOR_DEFINED + 0x203) +CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL = (CKM_VENDOR_DEFINED + 0x204) +CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL = (CKM_VENDOR_DEFINED + 0x205) +CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM = (CKM_VENDOR_DEFINED + 0x502) +CKM_DES2_DUKPT_PIN = (CKM_VENDOR_DEFINED + 0x611) +CKM_DES2_DUKPT_MAC = (CKM_VENDOR_DEFINED + 0x612) +CKM_DES2_DUKPT_MAC_RESP = (CKM_VENDOR_DEFINED + 0x613) +CKM_DES2_DUKPT_DATA = (CKM_VENDOR_DEFINED + 0x614) +CKM_DES2_DUKPT_DATA_RESP = (CKM_VENDOR_DEFINED + 0x615) +CKM_ECIES = (CKM_VENDOR_DEFINED + 0xA00) +CKM_XOR_BASE_AND_DATA_W_KDF = (CKM_VENDOR_DEFINED + 0xA01) +CKM_NIST_PRF_KDF = (CKM_VENDOR_DEFINED + 0xA02) +CKM_PRF_KDF = (CKM_VENDOR_DEFINED + 0xA03) +CKDHP_STANDARD = 0x00000001 +CKDHP_ECDH1_COFACTOR = 0x00000001 +CKDHP_MODIFIED = 0x00000002 # Not implemented */ +CKDHP_ECDH1 = 0x00000003 +CKES_XOR = 0x00000001 +CKES_DES3_CBC_PAD = 0x00000002 +CKES_AES_CBC_PAD = 0x00000003 +CKES_DES3_CBC = 0x00000004 +CKES_AES_CBC = 0x00000005 +CKMS_HMAC_SHA1 = 0x00000001 +CKMS_SHA1 = 0x00000002 +CKMS_HMAC_SHA224 = 0x00000003 +CKMS_SHA224 = 0x00000004 +CKMS_HMAC_SHA256 = 0x00000005 +CKMS_SHA256 = 0x00000006 +CKMS_HMAC_SHA384 = 0x00000007 +CKMS_SHA384 = 0x00000008 +CKMS_HMAC_SHA512 = 0x00000009 +CKMS_SHA512 = 0x0000000a +CKMS_HMAC_RIPEMD160 = 0x0000000b +CKMS_RIPEMD160 = 0x0000000c +CK_NIST_PRF_KDF_DES3_CMAC = 0x00000001 +CK_NIST_PRF_KDF_AES_CMAC = 0x00000002 +CK_PRF_KDF_ARIA_CMAC = 0x00000003 +CK_PRF_KDF_SEED_CMAC = 0x00000004 +LUNA_PRF_KDF_ENCODING_SCHEME_1 = 0x00000000 +LUNA_PRF_KDF_ENCODING_SCHEME_2 = 0x00000001 +CKR_INSERTION_CALLBACK_NOT_SUPPORTED = 0x00000141 +CKR_FUNCTION_PARALLEL = 0x0052 +CKR_SESSION_EXCLUSIVE_EXISTS = 0x00B2 +CKR_RC_ERROR = (CKR_VENDOR_DEFINED + 0x04) +CKR_CONTAINER_HANDLE_INVALID = (CKR_VENDOR_DEFINED + 0x05) +CKR_TOO_MANY_CONTAINERS = (CKR_VENDOR_DEFINED + 0x06) +CKR_USER_LOCKED_OUT = (CKR_VENDOR_DEFINED + 0x07) +CKR_CLONING_PARAMETER_ALREADY_EXISTS = (CKR_VENDOR_DEFINED + 0x08) +CKR_CLONING_PARAMETER_MISSING = (CKR_VENDOR_DEFINED + 0x09) +CKR_CERTIFICATE_DATA_MISSING = (CKR_VENDOR_DEFINED + 0x0a) +CKR_CERTIFICATE_DATA_INVALID = (CKR_VENDOR_DEFINED + 0x0b) +CKR_ACCEL_DEVICE_ERROR = (CKR_VENDOR_DEFINED + 0x0c) +CKR_WRAPPING_ERROR = (CKR_VENDOR_DEFINED + 0x0d) +CKR_UNWRAPPING_ERROR = (CKR_VENDOR_DEFINED + 0x0e) +CKR_MAC_MISSING = (CKR_VENDOR_DEFINED + 0x0f) +CKR_DAC_POLICY_PID_MISMATCH = (CKR_VENDOR_DEFINED + 0x10) +CKR_DAC_MISSING = (CKR_VENDOR_DEFINED + 0x11) +CKR_BAD_DAC = (CKR_VENDOR_DEFINED + 0x12) +CKR_SSK_MISSING = (CKR_VENDOR_DEFINED + 0x13) +CKR_BAD_MAC = (CKR_VENDOR_DEFINED + 0x14) +CKR_DAK_MISSING = (CKR_VENDOR_DEFINED + 0x15) +CKR_BAD_DAK = (CKR_VENDOR_DEFINED + 0x16) +CKR_SIM_AUTHORIZATION_FAILED = (CKR_VENDOR_DEFINED + 0x17) +CKR_SIM_VERSION_UNSUPPORTED = (CKR_VENDOR_DEFINED + 0x18) +CKR_SIM_CORRUPT_DATA = (CKR_VENDOR_DEFINED + 0x19) +CKR_USER_NOT_AUTHORIZED = (CKR_VENDOR_DEFINED + 0x1a) +CKR_MAX_OBJECT_COUNT_EXCEEDED = (CKR_VENDOR_DEFINED + 0x1b) +CKR_SO_LOGIN_FAILURE_THRESHOLD = (CKR_VENDOR_DEFINED + 0x1c) +CKR_SIM_AUTHFORM_INVALID = (CKR_VENDOR_DEFINED + 0x1d) +CKR_CITS_DAK_MISSING = (CKR_VENDOR_DEFINED + 0x1e) +CKR_UNABLE_TO_CONNECT = (CKR_VENDOR_DEFINED + 0x1f) +CKR_PARTITION_DISABLED = (CKR_VENDOR_DEFINED + 0x20) +CKR_CALLBACK_ERROR = (CKR_VENDOR_DEFINED + 0x21) +CKR_SECURITY_PARAMETER_MISSING = (CKR_VENDOR_DEFINED + 0x22) +CKR_SP_TIMEOUT = (CKR_VENDOR_DEFINED + 0x23) +CKR_TIMEOUT = (CKR_VENDOR_DEFINED + 0x24) +CKR_ECC_UNKNOWN_CURVE = (CKR_VENDOR_DEFINED + 0x25) +CKR_MTK_ZEROIZED = (CKR_VENDOR_DEFINED + 0x26) +CKR_MTK_STATE_INVALID = (CKR_VENDOR_DEFINED + 0x27) +CKR_INVALID_ENTRY_TYPE = (CKR_VENDOR_DEFINED + 0x28) +CKR_MTK_SPLIT_INVALID = (CKR_VENDOR_DEFINED + 0x29) +CKR_HSM_STORAGE_FULL = (CKR_VENDOR_DEFINED + 0x2a) +CKR_DEVICE_TIMEOUT = (CKR_VENDOR_DEFINED + 0x2b) +CKR_CONTAINER_OBJECT_STORAGE_FULL = (CKR_VENDOR_DEFINED + 0x2C) +CKR_PED_CLIENT_NOT_RUNNING = (CKR_VENDOR_DEFINED + 0x2D) +CKR_PED_UNPLUGGED = (CKR_VENDOR_DEFINED + 0x2E) +CKR_ECC_POINT_INVALID = (CKR_VENDOR_DEFINED + 0x2F) +CKR_OPERATION_NOT_ALLOWED = (CKR_VENDOR_DEFINED + 0x30) +CKR_LICENSE_CAPACITY_EXCEEDED = (CKR_VENDOR_DEFINED + 0x31) +CKR_LOG_FILE_NOT_OPEN = (CKR_VENDOR_DEFINED + 0x32) +CKR_LOG_FILE_WRITE_ERROR = (CKR_VENDOR_DEFINED + 0x33) +CKR_LOG_BAD_FILE_NAME = (CKR_VENDOR_DEFINED + 0x34) +CKR_LOG_FULL = (CKR_VENDOR_DEFINED + 0x35) +CKR_LOG_NO_KCV = (CKR_VENDOR_DEFINED + 0x36) +CKR_LOG_BAD_RECORD_HMAC = (CKR_VENDOR_DEFINED + 0x37) +CKR_LOG_BAD_TIME = (CKR_VENDOR_DEFINED + 0x38) +CKR_LOG_AUDIT_NOT_INITIALIZED = (CKR_VENDOR_DEFINED + 0x39) +CKR_LOG_RESYNC_NEEDED = (CKR_VENDOR_DEFINED + 0x3A) +CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS = (CKR_VENDOR_DEFINED + 0x3B) +CKR_AUDIT_LOGIN_FAILURE_THRESHOLD = (CKR_VENDOR_DEFINED + 0x3C) +CKR_INVALID_FUF_TARGET = (CKR_VENDOR_DEFINED + 0x3D) +CKR_INVALID_FUF_HEADER = (CKR_VENDOR_DEFINED + 0x3E) +CKR_INVALID_FUF_VERSION = (CKR_VENDOR_DEFINED + 0x3F) +CKR_ECC_ECC_RESULT_AT_INF = (CKR_VENDOR_DEFINED + 0x40) +CKR_AGAIN = (CKR_VENDOR_DEFINED + 0x41) +CKR_TOKEN_COPIED = (CKR_VENDOR_DEFINED + 0x42) +CKR_SLOT_NOT_EMPTY = (CKR_VENDOR_DEFINED + 0x43) +CKR_USER_ALREADY_ACTIVATED = (CKR_VENDOR_DEFINED + 0x44) +CKR_STC_NO_CONTEXT = (CKR_VENDOR_DEFINED + 0x45) +CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED = (CKR_VENDOR_DEFINED + 0x46) +CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED = (CKR_VENDOR_DEFINED + 0x47) +CKR_STC_DH_KEYGEN_ERROR = (CKR_VENDOR_DEFINED + 0x48) +CKR_STC_CIPHER_SUITE_REJECTED = (CKR_VENDOR_DEFINED + 0x49) +CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP = (CKR_VENDOR_DEFINED + 0x4a) +CKR_STC_COMPUTE_DH_KEY_ERROR = (CKR_VENDOR_DEFINED + 0x4b) +CKR_STC_FIRST_PHASE_KDF_ERROR = (CKR_VENDOR_DEFINED + 0x4c) +CKR_STC_SECOND_PHASE_KDF_ERROR = (CKR_VENDOR_DEFINED + 0x4d) +CKR_STC_KEY_CONFIRMATION_FAILED = (CKR_VENDOR_DEFINED + 0x4e) +CKR_STC_NO_SESSION_KEY = (CKR_VENDOR_DEFINED + 0x4f) +CKR_STC_RESPONSE_BAD_MAC = (CKR_VENDOR_DEFINED + 0x50) +CKR_STC_NOT_ENABLED = (CKR_VENDOR_DEFINED + 0x51) +CKR_STC_CLIENT_HANDLE_INVALID = (CKR_VENDOR_DEFINED + 0x52) +CKR_STC_SESSION_INVALID = (CKR_VENDOR_DEFINED + 0x53) +CKR_STC_CONTAINER_INVALID = (CKR_VENDOR_DEFINED + 0x54) +CKR_STC_SEQUENCE_NUM_INVALID = (CKR_VENDOR_DEFINED + 0x55) +CKR_STC_NO_CHANNEL = (CKR_VENDOR_DEFINED + 0x56) +CKR_STC_RESPONSE_DECRYPT_ERROR = (CKR_VENDOR_DEFINED + 0x57) +CKR_STC_RESPONSE_REPLAYED = (CKR_VENDOR_DEFINED + 0X58) +CKR_STC_REKEY_CHANNEL_MISMATCH = (CKR_VENDOR_DEFINED + 0X59) +CKR_STC_RSA_ENCRYPT_ERROR = (CKR_VENDOR_DEFINED + 0X5a) +CKR_STC_RSA_SIGN_ERROR = (CKR_VENDOR_DEFINED + 0X5b) +CKR_STC_RSA_DECRYPT_ERROR = (CKR_VENDOR_DEFINED + 0X5c) +CKR_STC_RESPONSE_UNEXPECTED_KEY = (CKR_VENDOR_DEFINED + 0X5d) +CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE = (CKR_VENDOR_DEFINED + 0X5e) +CKR_STC_UNEXPECTED_DH_DATA_SIZE = (CKR_VENDOR_DEFINED + 0X5f) +CKR_STC_OPEN_CIPHER_MISMATCH = (CKR_VENDOR_DEFINED + 0X60) +CKR_STC_OPEN_DHNIST_PUBKEY_ERROR = (CKR_VENDOR_DEFINED + 0X61) +CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL = (CKR_VENDOR_DEFINED + 0X62) +CKR_STC_OPEN_RESP_GEN_FAIL = (CKR_VENDOR_DEFINED + 0X63) +CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL = (CKR_VENDOR_DEFINED + 0X64) +CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL = (CKR_VENDOR_DEFINED + 0X65) +CKR_STC_ACTIVATE_RESP_GEN_FAIL = (CKR_VENDOR_DEFINED + 0X66) +CKR_CHALLENGE_INCORRECT = (CKR_VENDOR_DEFINED + 0X67) +CKR_ACCESS_ID_INVALID = (CKR_VENDOR_DEFINED + 0X68) +CKR_ACCESS_ID_ALREADY_EXISTS = (CKR_VENDOR_DEFINED + 0X69) +CKR_OBJECT_READ_ONLY = (CKR_VENDOR_DEFINED + 0x114) +CKR_KEY_NOT_ACTIVE = (CKR_VENDOR_DEFINED + 0x136) +CKO_TOKEN_ROLE_POLICY_SET = (CKO_VENDOR_DEFINED + 0x0001) +CKO_TOKEN_ROLE_POLICY = (CKO_VENDOR_DEFINED + 0x0002) +CKO_TOKEN_ROLE_DESCRIPTOR = (CKO_VENDOR_DEFINED + 0x0003) +CKO_TOKEN_ROLE_STATE = (CKO_VENDOR_DEFINED + 0x0004) +CKO_CERTIFICATE_REQUEST = (CKO_VENDOR_DEFINED + 0x0201) +CKO_CRL = (CKO_VENDOR_DEFINED + 0x0202) +CKO_ADAPTER = (CKO_VENDOR_DEFINED + 0x020A) +CKO_SLOT = (CKO_VENDOR_DEFINED + 0x020B) +CKO_FM = (CKO_VENDOR_DEFINED + 0x020C) +CKS_RO_SO_FUNCTIONS = 5 # still in PKCS #11 space */ +CKS_RO_VENDOR_DEFINED = 0x80000000 +CKS_RW_VENDOR_DEFINED = 0x90000000 +CKS_RW_AUDIT_FUNCTIONS = (CKS_RW_VENDOR_DEFINED + 0x001) +CAF_ROLE_STATE_INITIALIZED = 0x01 +CAF_ROLE_STATE_LOCKED_OUT = 0x02 +CAF_ROLE_STATE_ACTIVATED = 0x04 +CAF_ROLE_STATE_HAS_RDK = 0x08 +CAF_ROLE_STATE_PIN_CHANGE = 0x10 +CAF_ROLE_STATE_CHALLENGE_CHANGE = 0x20 +CKA_ROLE_AUTH_NONE = 0x00 +CKA_ROLE_AUTH_PASSWORD = 0x01 +CKA_ROLE_AUTH_PED = 0x02 +CKA_ROLE_AUTH_INVALID = 0xFF +CAF_M_OF_N_REQUIRED = 0x00000001 +CAF_M_OF_N_ACTIVATED = 0x00000002 +CAF_M_OF_N_GENERATED = 0x00000004 +CAF_M_OF_N_CLONEABLE = 0x00000008 +CKCAO_Encrypt = 0 +CKCAO_Decrypt = 1 +CKCAO_Sign = 2 +CKCAO_Verify = 3 +CKCAO_Digest = 4 +CK_HA_MAX_MEMBERS = 32 +CKHSC_CERT_TYPE_TCTRUST_MAC = 0x00000001 +CKHSC_CERT_TYPE_TCTRUST_DAC = 0x00000002 +CKHSC_CERT_TYPE_CITS_ROOT = 0x00000003 +CKHSC_CERT_TYPE_CITS_MICHOC = 0x00000004 +CKHSC_CERT_TYPE_CITS_DAC = 0x00000005 +CKHSC_CERT_TYPE_ECC_MIC = 0x00000006 +CKHSC_CERT_TYPE_ECC_HOC = 0x00000007 +CKHSC_CERT_TYPE_ECC_DAC = 0x00000008 +CKHSC_CERT_TYPE_TWC = 0x00000009 +CKHSC_CERT_TYPE_TWC2 = 0x0000000A +CKHSC_CERT_TYPE_TWC3 = 0x0000000B +CKA_SIM_NO_AUTHORIZATION = 0 # no authorization needed +CKA_SIM_PASSWORD = 1 # plain-text passwords +CKA_SIM_CHALLENGE = 2 # challenge secrets emitted through the secure port +CKA_SIM_SECURE_PORT = 3 # PED keys +CKA_SIM_PORTABLE_NO_AUTHORIZATION = 4 # no authorization needed, portable +CKA_SIM_PORTABLE_PASSWORD = 5 # plain-text passwords, portable +CKA_SIM_PORTABLE_CHALLENGE = 6 # challenge secrets emitted through the secure port, portable +CKA_SIM_PORTABLE_SECURE_PORT = 7 # PED keys, portable +CK_NULL_ELEMENT = (-1) +CK_CRYPTOKI_ELEMENT = 0x00000000 +CK_PARAM_ELEMENT = 0x00000001 +CK_CONTAINER_ACTIVATION_ELEMENT = 0x00000002 +CK_MOFN_ACTIVATION_ELEMENT = 0x00000003 +CK_CONTAINER_ELEMENT = 0x00000004 +CK_CLONING_PART1_OVERHEAD = 8192 +CK_CLONING_PART2_OVERHEAD = 76 +CK_FLATTENED_OBJECT_OVERHEAD = 3264 +CK_STORAGE_HOST = 0x00000000 +CK_STORAGE_PED_USB_MEMORY = 0x00000001 +CK_STORAGE_HSM_USB_MEMORY = 0x00000002 +CK_MTK_STATE_FLAG_RESPLIT_ABORTED = 0x00000001 +CK_MTK_STATE_FLAG_HARD_ZEROIZE = 0x00000002 +CK_MTK_STATE_FLAG_SOFT_ZEROIZE = 0x00000004 +CK_MTK_STATE_FLAG_LOCKED = 0x00000008 +CK_MAX_CLUSTER_MEMBERS = 8 +AKEP2_XDH_SIZE = 128 # size of LKM public key +AKEP2_MAX_DIGEST_SIZE = 32 +AKEP2_NID_SIZE = 20 +CK_PED_ID_LOCAL = 0x0000 +CK_PED_ID_MAX = 0xFFFE +CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT = 0x00000001 +CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET = 0x00000002 diff --git a/pycryptoki/dictionary_handling.py b/pycryptoki/dictionary_handling.py index c362fc6..55b789c 100755 --- a/pycryptoki/dictionary_handling.py +++ b/pycryptoki/dictionary_handling.py @@ -1,16 +1,14 @@ -''' +""" Created on Oct 3, 2012 @author: root -''' +""" + class CDict: - - dict_val = None - + """ """ + dict_val = None def __init__(self, dict_val): self.dict_val = dict_val - - \ No newline at end of file diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 50c26e0..0905e52 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -1,9 +1,11 @@ """ Methods related to encrypting data/files. """ -from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ - C_EncryptInit, CK_BYTE_PTR, C_Encrypt, CK_RSA_PKCS_OAEP_PARAMS from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer +import logging + +from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ + C_EncryptInit, C_Encrypt, CK_RSA_PKCS_OAEP_PARAMS from defines import CKM_DES_CBC, CKM_DES3_CBC, CKM_CAST3_CBC, CKM_DES_ECB, \ CKM_DES3_ECB, CKM_CAST3_ECB, CKM_RC2_ECB, CKM_RC2_CBC, CKM_CAST5_ECB, \ CKM_CAST5_CBC, CKM_RC4, CKM_RC5_ECB, CKM_RC5_CBC, CKM_RSA_X_509, CKM_DES_CBC_PAD, \ @@ -16,24 +18,24 @@ CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED from pycryptoki.attributes import get_byte_list_from_python_list, \ - convert_CK_CHAR_to_string, convert_ck_char_array_to_string, Attributes + convert_ck_char_array_to_string, Attributes from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ C_DecryptUpdate, C_DecryptFinal from pycryptoki.test_functions import make_error_handle_function -import logging logger = logging.getLogger(__name__) + def get_encryption_mechanism(encryption_flavor): - ''' - Returns the CK_MECHANISM() object associated with a given encryption flavor + """Returns the CK_MECHANISM() object associated with a given encryption flavor #TODO: Only works with one kind of encryption mechanism currently. - @param encryption_flavor: The flavor of the encryption that the mechanism needs + :param encryption_flavor: The flavor of the encryption that the mechanism needs to encrypt for. - @return: Returns a CTypes CK_Mechanism given the encryption flavour that you have passed in - ''' + :returns: Returns a CTypes CK_Mechanism given the encryption flavour that you have passed in + + """ mech = CK_MECHANISM() mech.mechanism = CK_MECHANISM_TYPE(encryption_flavor) mech.pParameter = 0 @@ -50,51 +52,51 @@ def get_encryption_mechanism(encryption_flavor): OAEP_params_required = 9 ECIES_params_required = 10 - encryption_flavors = {CKM_DES_CBC : iv_required, - CKM_DES3_CBC : iv_required, - CKM_CAST3_CBC : iv_required, - CKM_DES_ECB : 0, - CKM_DES3_ECB : 0, - CKM_CAST3_ECB : 0, - CKM_RC2_ECB : RC2_params_required, - CKM_RC2_CBC : RC2CBC_params_required , - CKM_CAST5_ECB : 0, - CKM_CAST5_CBC : iv_required, - CKM_RC4 : 0, - CKM_RC5_ECB : RC5_params_required, - CKM_RC5_CBC : RC5CBC_params_required, - CKM_RSA_X_509 : 0, - CKM_DES_CBC_PAD : iv_required, - CKM_DES3_CBC_PAD : iv_required, - CKM_DES3_CBC_PAD_IPSEC : iv_required, - CKM_RC2_CBC_PAD : RC2CBC_params_required, - CKM_RC5_CBC_PAD : RC5CBC_params_required, - CKM_CAST3_CBC_PAD : iv_required, - CKM_CAST5_CBC_PAD : iv_required, - CKM_SEED_ECB : 0, - CKM_SEED_CBC : IV16_required, - CKM_SEED_CBC_PAD : IV16_required, - CKM_AES_ECB : 0, - CKM_AES_CBC : IV16_required, - CKM_AES_CBC_PAD : IV16_required, - CKM_AES_CBC_PAD_IPSEC : IV16_required, - CKM_ARIA_ECB : IV16_required, - CKM_ARIA_CBC : IV16_required, - CKM_ARIA_CBC_PAD : IV16_required, - CKM_RSA_PKCS : 0, - CKM_DES_CFB8 : iv_required, - CKM_DES_CFB64 : iv_required, - CKM_DES_OFB64 : iv_required, - CKM_AES_CFB8 : iv_required, - CKM_AES_CFB128 : iv_required, - CKM_AES_OFB : iv_required, - CKM_ARIA_CFB8 : iv_required, - CKM_ARIA_CFB128 : iv_required, - CKM_ARIA_OFB : iv_required, - CKM_AES_GCM : GCM_params_required, - CKM_XOR_BASE_AND_DATA_W_KDF : xorkdf_params_required, - CKM_RSA_PKCS_OAEP : OAEP_params_required, - CKM_ECIES : ECIES_params_required} + encryption_flavors = {CKM_DES_CBC: iv_required, + CKM_DES3_CBC: iv_required, + CKM_CAST3_CBC: iv_required, + CKM_DES_ECB: 0, + CKM_DES3_ECB: 0, + CKM_CAST3_ECB: 0, + CKM_RC2_ECB: RC2_params_required, + CKM_RC2_CBC: RC2CBC_params_required, + CKM_CAST5_ECB: 0, + CKM_CAST5_CBC: iv_required, + CKM_RC4: 0, + CKM_RC5_ECB: RC5_params_required, + CKM_RC5_CBC: RC5CBC_params_required, + CKM_RSA_X_509: 0, + CKM_DES_CBC_PAD: iv_required, + CKM_DES3_CBC_PAD: iv_required, + CKM_DES3_CBC_PAD_IPSEC: iv_required, + CKM_RC2_CBC_PAD: RC2CBC_params_required, + CKM_RC5_CBC_PAD: RC5CBC_params_required, + CKM_CAST3_CBC_PAD: iv_required, + CKM_CAST5_CBC_PAD: iv_required, + CKM_SEED_ECB: 0, + CKM_SEED_CBC: IV16_required, + CKM_SEED_CBC_PAD: IV16_required, + CKM_AES_ECB: 0, + CKM_AES_CBC: IV16_required, + CKM_AES_CBC_PAD: IV16_required, + CKM_AES_CBC_PAD_IPSEC: IV16_required, + CKM_ARIA_ECB: IV16_required, + CKM_ARIA_CBC: IV16_required, + CKM_ARIA_CBC_PAD: IV16_required, + CKM_RSA_PKCS: 0, + CKM_DES_CFB8: iv_required, + CKM_DES_CFB64: iv_required, + CKM_DES_OFB64: iv_required, + CKM_AES_CFB8: iv_required, + CKM_AES_CFB128: iv_required, + CKM_AES_OFB: iv_required, + CKM_ARIA_CFB8: iv_required, + CKM_ARIA_CFB128: iv_required, + CKM_ARIA_OFB: iv_required, + CKM_AES_GCM: GCM_params_required, + CKM_XOR_BASE_AND_DATA_W_KDF: xorkdf_params_required, + CKM_RSA_PKCS_OAEP: OAEP_params_required, + CKM_ECIES: ECIES_params_required} iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] @@ -143,30 +145,30 @@ def get_encryption_mechanism(encryption_flavor): return mech -def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - ''' - Encrypts data with a given key and encryption flavor + +def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None): + """Encrypts data with a given key and encryption flavor encryption flavors - @param session: Current session - @param encryption_flavor: The flavor of encryption to use - @param h_key: The key handle to encrypt the data with - @param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param mech: The mechanism to use, if None will try to look up a - default mechanism based on the encryption flavor - @return: Returns the result code of the operation, a python string representing the encrypted data - ''' - - if mech == None: + + :param h_session: Current session + :param encryption_flavor: The flavor of encryption to use + :param h_key: The key handle to encrypt the data with + :param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is a list + a multipart operation will be used + :param mech: The mechanism to use, if None will try to look up a + default mechanism based on the encryption flavor + :param h_session: + :returns: Returns the result code of the operation, a python string representing the encrypted data + + """ + + if mech is None: mech = get_encryption_mechanism(encryption_flavor) - #if a list is passed out do an encrypt operation on each string in the list, otherwise just do one encrypt operation + # if a list is passed out do an encrypt operation on each string in the list, otherwise just do one encrypt operation is_multi_part_operation = isinstance(data_to_encrypt, list) or isinstance(data_to_encrypt, tuple) - #Initialize encryption + # Initialize encryption ret = C_EncryptInit(h_session, byref(mech), CK_ULONG(h_key)) if ret != CKR_OK: return ret, None @@ -176,7 +178,7 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None) plain_data_length = len(data_to_encrypt) plain_data = get_c_data_to_sign_or_encrypt(data_to_encrypt) - #Get the length of the encrypted data + # Get the length of the encrypted data encrypted_data_length = CK_ULONG() ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), None, byref(encrypted_data_length)) if ret != CKR_OK: return ret, None @@ -184,76 +186,82 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None) output = create_string_buffer("", encrypted_data_length.value) encrypted_data = cast(output, CK_BYTE_PTR) - #Encrypt data - ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), encrypted_data, byref(encrypted_data_length)) + # Encrypt data + ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), encrypted_data, + byref(encrypted_data_length)) - #Convert encrypted data into a python string + # Convert encrypted data into a python string ck_char_array = encrypted_data._objects.values()[0] encrypted_python_string = convert_ck_char_array_to_string(ck_char_array) return ret, encrypted_python_string + c_encrypt_ex = make_error_handle_function(c_encrypt) + def _split_string_into_list(python_string, block_size): - ''' - Splits a string into a list of equal size chunks + """Splits a string into a list of equal size chunks + + :param python_string: The string to divide + :param block_size: The size of the blocks to divide the string into + :returns: A list of strings of block_size - @param python_string: The string to divide - @param block_size: The size of the blocks to divide the string into - @return: A list of strings of block_size - ''' + """ return_list = [] total_length = len(python_string) for index in range(0, (total_length / block_size)): start_index = index * block_size end_index = min(start_index + block_size, total_length) - return_list.append(python_string[start_index : end_index]) + return_list.append(python_string[start_index: end_index]) return return_list + def _get_string_from_list(list_of_strings): - ''' - Takes a list of strings and returns a single concatenated string. + """Takes a list of strings and returns a single concatenated string. + + :param list_of_strings: A list of strings to be concatenated + :returns: Single string representing the concatenated list - @param list_of_strings: A list of strings to be concatenated - @return: Single string representing the concatenated list - ''' + """ large_string = '' for substring in list_of_strings: large_string += substring return large_string -def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech = None): - ''' - Decrypts some data - @param h_session: The session to use - @param decryption_flavor: The decryption flavor to create a new mechanism with if no mechanism - is provided - @param h_key: The handle of the key to use to decrypt - @param mech: The mechanism, if none is provided a blank one will be provided based on the decryption_flavor +def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None): + """Decrypts some data - @return: The result code, a python string of the decrypted data - ''' + :param h_session: The session to use + :param decryption_flavor: The decryption flavor to create a new mechanism with if no mechanism + is provided + :param h_key: The handle of the key to use to decrypt + :param mech: The mechanism, if none is provided a blank one will be + provided based on the decryption_flavor (Default value = None) + :param encrypted_data: + :returns: The result code, a python string of the decrypted data - #Get the mechanism - if mech == None: + """ + + # Get the mechanism + if mech is None: mech = get_encryption_mechanism(decryption_flavor) - #Initialize Decrypt + # Initialize Decrypt ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) if ret != CKR_OK: return ret, None - #if a list is passed out do a decrypt operation on each string in the list, otherwise just do one decrypt operation + # if a list is passed out do a decrypt operation on each string in the list, otherwise just do one decrypt operation is_multi_part_operation = isinstance(encrypted_data, list) or isinstance(encrypted_data, tuple) if is_multi_part_operation: python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, encrypted_data) else: - #Get the length of the final data + # Get the length of the final data # NOTE: The "Conventions for functions returning output in a variable-length buffer" # section of the PKCS#11 spec says that the length returned in this # case (no output buffer given to C_Decrypt) can exceed the precise @@ -270,11 +278,11 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech = None): output = create_string_buffer("", plain_data_len.value) plain_data = cast(output, CK_BYTE_PTR) - #Decrypt data + # Decrypt data ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), plain_data, byref(plain_data_len)) if ret != CKR_OK: return ret, None - #Convert the decrypted data to a python readable format + # Convert the decrypted data to a python readable format ck_char_array = plain_data._objects.values()[0] python_string = convert_ck_char_array_to_string(ck_char_array) # Adjust the string based on the updated plain_data_len @@ -282,13 +290,20 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech = None): return ret, python_string -c_decrypt_ex= make_error_handle_function(c_decrypt) + +c_decrypt_ex = make_error_handle_function(c_decrypt) + def do_multipart_operation(h_session, c_update_function, c_finalize_function, input_data_list): - ''' - Some code which will do a multipart encrypt or decrypt since they are the same + """Some code which will do a multipart encrypt or decrypt since they are the same with just different functions called - ''' + + :param h_session: + :param c_update_function: + :param c_finalize_function: + :param input_data_list: + + """ max_data_chunk_size = 0xfff0 plain_data_len = len(_get_string_from_list(input_data_list)) @@ -298,82 +313,92 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in while remaining_length > 0: current_chunk = input_data_list[i] - #Prepare arguments for decrypt update operation + # Prepare arguments for decrypt update operation current_chunk_len = min(len(current_chunk), remaining_length) if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + raise Exception( + "chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) out_data = create_string_buffer('', max_data_chunk_size) out_data_len = CK_ULONG(max_data_chunk_size) - if (out_data_len.value > 0): + if out_data_len.value > 0: data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) - ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len), cast(out_data, CK_BYTE_PTR), byref(out_data_len)) + ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len), cast(out_data, CK_BYTE_PTR), + byref(out_data_len)) if ret != CKR_OK: return ret, None remaining_length -= current_chunk_len - #Get the output + # Get the output ck_char_array = out_data._objects.values()[0] python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] i += 1 - #Finalizing multipart decrypt operation + # Finalizing multipart decrypt operation out_data_len = CK_ULONG(max_data_chunk_size) output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) ret = c_finalize_function(h_session, output, byref(out_data_len)) - #Get output + # Get output ck_char_array = output._objects.values()[0] - if (out_data_len.value > 0): + if out_data_len.value > 0: python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] return python_string -def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech = None): - ''' - Function which wraps a key - @param h_session: The session to use - @param h_wrapping_key: The handle of the key to use to wrap another key - @param h_key: The key to wrap - @param encryption_flavor: The encryption flavor to create a new mechanism with if no mechanism - is provided - @param mech: The mechanism, if none is provided a blank one will be provided based on the encryption flavor +def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None): + """Function which wraps a key + + :param h_session: The session to use + :param h_wrapping_key: The handle of the key to use to wrap another key + :param h_key: The key to wrap + :param encryption_flavor: The encryption flavor to create a new mechanism with if no mechanism + is provided + :param mech: The mechanism, if none is provided a blank one will be provided + based on the encryption flavor (Default value = None) + :returns: The result code, a ctypes byte array representing the new key - @return: The result code, a ctypes byte array representing the new key - ''' - if mech == None: + """ + if mech is None: mech = get_encryption_mechanism(encryption_flavor) - #Get the size of the key + # Get the size of the key wrapped_key_length = CK_ULONG() - ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), None, byref(wrapped_key_length)) + ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), None, + byref(wrapped_key_length)) if ret != CKR_OK: return ret, None - #Actually wrap the key + # Actually wrap the key output = create_string_buffer("", wrapped_key_length.value) wrapped_key_output = cast(output, CK_BYTE_PTR) - ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), wrapped_key_output, byref(wrapped_key_length)) + ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), wrapped_key_output, + byref(wrapped_key_length)) return ret, wrapped_key_output._objects.values()[0] + + c_wrap_key_ex = make_error_handle_function(c_wrap_key) -def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech = None): - ''' - Function which unwraps a key - @param h_session: The session to use - @param h_wrapping_key: The wrapping key handle - @param wapped_key: The wrapped key in a ctypes CK_CHAR_PTR array - @param key_template: The python template representing the new key's template - @param encryption_flavor: If the mechanism is not specified it will create a - default one based on the encryption flavor - @param mech: The mechanism to use, if null a default one will be created based on the encryption_flavor - - @return: The result code, the handle of the unwrapped key - ''' - if mech == None: + +def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech=None): + """Function which unwraps a key + + :param h_session: The session to use + :param h_unwrapping_key: The wrapping key handle + :param wrapped_key: The wrapped key in a ctypes CK_CHAR_PTR array + :param key_template: The python template representing the new key's template + :param encryption_flavor: If the mechanism is not specified it will create a + default one based on the encryption flavor + :param mech: The mechanism to use, if null a default one will be created based on the encryption_flavor + :param h_unwrapping_key: + :param wrapped_key: + :returns: The result code, the handle of the unwrapped key + + """ + if mech is None: mech = get_encryption_mechanism(encryption_flavor) c_template = Attributes(key_template).get_c_struct() @@ -383,17 +408,17 @@ def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encrypt c_template, CK_ULONG(len(key_template)), byref(h_output_key)) return ret, h_output_key.value + + c_unwrap_key_ex = make_error_handle_function(c_unwrap_key) -def get_c_data_to_sign_or_encrypt(python_data): - ''' - Function which gets the C data representation of some python data - @param python_data: The python data to get a c representation of +def get_c_data_to_sign_or_encrypt(python_data): + """Function which gets the C data representation of some python data - @return: A C byte pointer pointing to the C representation of the - python data - ''' + :param python_data: The python data to get a c representation of + :returns: A C byte pointer pointing to the C representation of the python data + """ c_data_to_sign = None if isinstance(python_data, str): diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index a794ec4..87c406b 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -2,6 +2,7 @@ Methods responsible for pycryptoki 'hsm management' set of commands. """ from ctypes import byref, create_string_buffer, cast + from pycryptoki.cryptoki import (CK_SLOT_ID, CK_USER_TYPE, CA_SetTokenCertificateSignature, @@ -25,17 +26,17 @@ def c_performselftest(slot, test_type, input_data, input_data_len): - ''' - Test: Performs a self test for specified test type on a given slot. + """Test: Performs a self test for specified test type on a given slot. - @param slot: slot number - @param test_type: type of test CK_ULONG - @param input_data: pointer to input data CK_BYTE_PTR - @param input_data_len: input data length CK_ULONG - @return: the result code + :param slot: slot number + :param test_type: type of test CK_ULONG + :param input_data: pointer to input data CK_BYTE_PTR + :param input_data_len: input data length CK_ULONG + :returns: the result code [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] - ''' + + """ test_type = CK_ULONG(test_type) input_length = CK_ULONG(input_data_len) @@ -54,6 +55,8 @@ def c_performselftest(slot, output_data, byref(output_data_len)) return ret, output_data + + c_performselftest_ex = make_error_handle_function(c_performselftest) @@ -63,21 +66,20 @@ def ca_settokencertificatesignature(h_session, pub_template, signature, signature_len): - ''' - Completes the installation of a certificate on a token. + """Completes the installation of a certificate on a token. The caller must supply a public key and a signature for token certificate. The public key is provided through the template; it must contain a key type, a modulus and a public exponent. - @param h_session: the current session - @param access_level: the access level - @param customer_id: the customer ID - @param pub_template: the public template - @param pub_template_length: the public template length - @param signature: the signature - @param signature_length: the length in bytes of the signature - @return: the result code - ''' + :param h_session: the current session + :param access_level: the access level + :param customer_id: the customer ID + :param pub_template: the public template + :param signature: the signature + :param signature_len: the length in bytes of the signature + :returns: the result code + + """ access_level = CK_ULONG(access_level) customer_id = CK_ULONG(customer_id) @@ -94,43 +96,44 @@ def ca_settokencertificatesignature(h_session, signature, signature_length) return ret + + ca_settokencertificatesignature_ex = \ make_error_handle_function(ca_settokencertificatesignature) def ca_hainit(h_session, h_key): - ''' - Creates a login key pair on the primary token. + """Creates a login key pair on the primary token. + + :param h_session: the current session + :param h_key: the login private key + :returns: the result code - @param h_session: the current session - @param h_key: the login private key - @return: the result code - ''' + """ ret = CA_HAInit(h_session, h_key) return ret + + ca_hainit_ex = make_error_handle_function(ca_hainit) def ca_createloginchallenge(h_session, user_type, challenge): - ''' - Creates a login challenge for the given user. - - @param h_session: the current session - @param user_type: user type - @param challenge_length: challenge length - @param challenge: challenge - @param output_data_length: PIN length - @param output_data: PIN itself - @return: the result code - ''' + """Creates a login challenge for the given user. + + :param h_session: the current session + :param user_type: user type + :param challenge: challenge + :returns: the result code + + """ challenge_length = CK_ULONG(len(challenge)) challenge = cast(create_string_buffer(challenge), CK_CHAR_PTR) output_data_length = CK_ULONG() - output_data = (CK_CHAR)() + output_data = CK_CHAR() ret = CA_CreateLoginChallenge(h_session, CK_USER_TYPE(user_type), challenge_length, @@ -138,68 +141,79 @@ def ca_createloginchallenge(h_session, output_data_length, output_data) return ret, output_data + + ca_createloginchallenge_ex = \ make_error_handle_function(ca_createloginchallenge) def ca_initializeremotepedvector(h_session): - ''' - Initializes a remote PED vector + """Initializes a remote PED vector + + :param h_session: the current session + :returns: the result code - @param h_session: the current session - @return: the result code - ''' + """ ret = CA_InitializeRemotePEDVector(h_session) return ret + + ca_initializeremotepedvector_ex = \ make_error_handle_function(ca_initializeremotepedvector) def ca_deleteremotepedvector(h_session): - ''' - Deletes a remote PED vector + """Deletes a remote PED vector - @param h_session: the current session - @return: the result code - ''' + :param h_session: the current session + :returns: the result code + + """ ret = CA_DeleteRemotePEDVector(h_session) return ret + + ca_deleteremotepedvector_ex = \ make_error_handle_function(ca_deleteremotepedvector) def ca_mtkrestore(slot): - ''' - Restore the MTK + """Restore the MTK + + :param slot: slot number + :returns: the result code - @param slot: slot number - @return: the result code - ''' + """ ret = CA_MTKRestore(CK_SLOT_ID(slot)) return ret + + ca_mtkrestore_ex = make_error_handle_function(ca_mtkrestore) def ca_mtkresplit(slot): - ''' - Resplit the MTK + """Resplit the MTK - @param slot: slot number - @return: the result code - ''' + :param slot: slot number + :returns: the result code + + """ ret = CA_MTKResplit(CK_SLOT_ID(slot)) return ret + + ca_mtkresplit_ex = make_error_handle_function(ca_mtkresplit) def ca_mtkzeroize(slot): - ''' - Zeroize the MTK + """Zeroize the MTK + + :param slot: slot number + :returns: the result code - @param slot: slot number - @return: the result code - ''' + """ ret = CA_MTKZeroize(CK_SLOT_ID(slot)) return ret -ca_mtkzeroize_ex = make_error_handle_function(ca_mtkzeroize) + +ca_mtkzeroize_ex = make_error_handle_function(ca_mtkzeroize) diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 8513eaa..32746ad 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -2,39 +2,41 @@ Methods used to generate keys. """ +from ctypes import byref + from cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, CK_MECHANISM, \ CK_MECHANISM_TYPE, CK_VOID_PTR, C_GenerateKey, C_GenerateKeyPair, C_CopyObject -from ctypes import byref, pointer, cast from default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP -from defines import CKR_OK, CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN +from defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CA_ClonePrivateKey, C_DeriveKey, \ - CK_SESSION_HANDLE +from pycryptoki.cryptoki import C_DeriveKey from pycryptoki.test_functions import make_error_handle_function + def c_destroy_object(h_session, h_object_value): - ''' - Deletes the object corresponsing to the passed in object handle - @param h_session: Current session - @param h_object_value: The handle of the object to delete - - @return: The resutl code from the C_DestroyObject operation - ''' + """Deletes the object corresponsing to the passed in object handle + + :param h_session: Current session + :param h_object_value: The handle of the object to delete + :returns: The resutl code from the C_DestroyObject operation + + """ ret = C_DestroyObject(h_session, CK_OBJECT_HANDLE(h_object_value)) return ret + + c_destroy_object_ex = make_error_handle_function(c_destroy_object) def c_copy_object(h_session, h_object, template=None): - - """ - Method to call the C_CopyObject cryptoki command. + """Method to call the C_CopyObject cryptoki command. :param h_session: Handle to the session :param h_object: Handle to the object to be cloned :param template: Template for the new object. Defaults to None :return: Handle to the new cloned object. + """ attributes = Attributes(template) if template is None: @@ -47,104 +49,116 @@ def c_copy_object(h_session, h_object, template=None): ret = C_CopyObject(h_session, h_object, attributes.get_c_struct(), template_size, h_new_object) return ret, h_new_object.value + + c_copy_object_ex = make_error_handle_function(c_copy_object) + def _get_mechanism(flavor): - ''' - Method used to get the CK_MECHANISM variable for key generation. - - @param flavor: The key flavor of the mechanism - - @return: Returns a blank mechanism of type flavor - ''' + """Method used to get the CK_MECHANISM variable for key generation. + + :param flavor: The key flavor of the mechanism + :returns: Returns a blank mechanism of type flavor + + """ mech = CK_MECHANISM() mech.mechanism = CK_MECHANISM_TYPE(flavor) mech.pParameter = CK_VOID_PTR(0) mech.usParameterLen = CK_ULONG(0) return mech -def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP): #TODO - ''' - Generates a symmetric key of a given flavor given the correct template. - - @param h_session: Current session - @param flavor: The flavour of the DES key to generate - @param template: The template to use to generate the key - - @return: Returns the result code and the key's handle - ''' + +def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP): + """ + Generates a symmetric key of a given flavor given the correct template. + + :param h_session: Current session + :param flavor: The flavour of the DES key to generate + :param template: The template to use to generate the key + + :return: Returns the result code and the key's handle + """ # INITALIZE VARIABLES mech = _get_mechanism(flavor) - + key_attributes = Attributes(template) us_public_template_size = CK_ULONG(len(template)) - + # ACTUALLY GENERATE KEY h_key = CK_OBJECT_HANDLE() - ret = C_GenerateKey(h_session, byref(mech), key_attributes.get_c_struct(), us_public_template_size, byref(h_key)); + ret = C_GenerateKey(h_session, byref(mech), key_attributes.get_c_struct(), us_public_template_size, byref(h_key)) return ret, h_key.value -c_generate_key_ex = make_error_handle_function(c_generate_key) - -def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None): - ''' - Generates a private and public key pair for a given flavor, and given public and private + + +c_generate_key_ex = make_error_handle_function(c_generate_key) + + +def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None): + """Generates a private and public key pair for a given flavor, and given public and private key templates. The return value will be the handle for the key. - - @param h_session: Current session - @param flavor: The flavor of the key to generate - @param pbkey_template: The public key template to use for key generation - @param prkey_template: The private key template to use for key generation - @param mech: The mechanism to generate the key with - - @return: Returns the result code, the public key's handle, and the private key's handle - ''' + + :param h_session: Current session + :param flavor: The flavor of the key to generate (Default value = CKM_DES_KEY_GEN) + :param pbkey_template: The public key template to use for key generation + :param prkey_template: The private key template to use for key generation + :param mech: The mechanism to generate the key with + :returns: Returns the result code, the public key's handle, and the private key's handle + + """ # INITALIZE VARIABLES if mech is None: mech = _get_mechanism(flavor) - + pbkey_template_size = len(pbkey_template) pbkey_attributes = Attributes(pbkey_template) - + prkey_template_size = len(prkey_template) prkey_attributes = Attributes(prkey_template) - - h_pbkey= CK_OBJECT_HANDLE() + + h_pbkey = CK_OBJECT_HANDLE() h_prkey = CK_OBJECT_HANDLE() - ret = C_GenerateKeyPair(h_session, byref(mech), pbkey_attributes.get_c_struct(), pbkey_template_size, + ret = C_GenerateKeyPair(h_session, byref(mech), pbkey_attributes.get_c_struct(), pbkey_template_size, prkey_attributes.get_c_struct(), prkey_template_size, byref(h_pbkey), byref(h_prkey)) - + return ret, h_pbkey.value, h_prkey.value + + c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) -def c_derive_key(h_session, h_base_key, template, mech_flavor, mech = None): - ''' - Calls C_DeriveKey - - @param h_session: The session handle to use - @param h_base_key: The base key - @param template: A python template of attributes (ex. CKM_DES_KEY_GEN_TEMP) - @param mech: The mechanism to use, if None a default mechanism will be used - - @return: The result code, The derived key's handle - ''' - - if mech == None: + +def c_derive_key(h_session, h_base_key, template, mech_flavor, mech=None): + """Calls C_DeriveKey + + :param h_session: The session handle to use + :param h_base_key: The base key + :param template: A python template of attributes (ex. CKM_DES_KEY_GEN_TEMP) + :param mech: The mechanism to use, if None a default mechanism will be used + :param mech_flavor: + :returns: The result code, The derived key's handle + + """ + + if mech is None: mech = _get_mechanism(mech_flavor) - + h_key = CK_OBJECT_HANDLE() c_template = Attributes(template).get_c_struct() ret = C_DeriveKey(h_session, mech, CK_OBJECT_HANDLE(h_base_key), c_template, CK_ULONG(len(template)), byref(h_key)) return ret, h_key.value + + c_derive_key_ex = make_error_handle_function(c_derive_key) + def clear_keys(h_session): - ''' - Quick hacked together function that can be used to clear the first 10 000 keys. - @param h_session:Current session - ''' - for i in range(1,10000): + """Quick hacked together function that can be used to clear the first 10 000 keys. + + :param h_session: Current session + + """ + for i in range(1, 10000): c_destroy_object(h_session, i) diff --git a/pycryptoki/key_management.py b/pycryptoki/key_management.py index c3d9bf5..00624b9 100755 --- a/pycryptoki/key_management.py +++ b/pycryptoki/key_management.py @@ -5,21 +5,22 @@ CK_VOID_PTR, CK_ULONG, CA_MOFN_GENERATION, CK_BYTE, CA_MOFN_GENERATION_PTR from pycryptoki.test_functions import make_error_handle_function + def ca_generatemofn(h_session, m_value, vector_value, vector_count, is_secure_port_used): - ''' - Generates MofN secret information on a token. - - @param h_session: the current session - @param m_value: m - @param vectors: vectors - @param vector_count: number of vectors - @param is_secure_port_used: is secure port used - @return: the result code - ''' + """Generates MofN secret information on a token. + + :param h_session: the current session + :param m_value: m + :param vector_count: number of vectors + :param is_secure_port_used: is secure port used + :param vector_value: + :returns: the result code + + """ reserved = CK_VOID_PTR(0) m_value = CK_ULONG(m_value) @@ -43,19 +44,23 @@ def ca_generatemofn(h_session, is_secure_port_used, reserved) return ret + + ca_generatemofn_ex = make_error_handle_function(ca_generatemofn) def ca_modifyusagecount(h_session, h_object, command_type, value): - ''' - Modifies CKA_USAGE_COUNT attribute of the object. - - @param h_session: the current session - @param h_object: object - @param command_type: command type - @param value: value - @return: the result code - ''' + """Modifies CKA_USAGE_COUNT attribute of the object. + + :param h_session: the current session + :param h_object: object + :param command_type: command type + :param value: value + :returns: the result code + + """ ret = CA_ModifyUsageCount(h_session, h_object, command_type, CK_ULONG(value)) return ret + + ca_modifyusagecount_ex = make_error_handle_function(ca_modifyusagecount) diff --git a/pycryptoki/key_usage.py b/pycryptoki/key_usage.py index 25a30c9..f590912 100755 --- a/pycryptoki/key_usage.py +++ b/pycryptoki/key_usage.py @@ -5,28 +5,33 @@ CK_VOID_PTR, CK_SESSION_HANDLE from pycryptoki.test_functions import make_error_handle_function + def ca_clonemofn(h_session): - ''' - Clones MofN secret from one token to another. + """Clones MofN secret from one token to another. + + :param h_session: the current session + :returns: the result code - @param h_session: the current session - @return: the result code - ''' + """ h_primary_session = CK_SESSION_HANDLE(0) reserved = CK_VOID_PTR(0) ret = CA_CloneMofN(h_session, h_primary_session, reserved) return ret + + ca_clonemofn_ex = make_error_handle_function(ca_clonemofn) + def ca_duplicatemofn(h_session): - ''' - Duplicates a set of M of N vectors. + """Duplicates a set of M of N vectors. - @param h_session: the current session - @return: the result code - ''' + :param h_session: the current session + :returns: the result code + + """ ret = CA_DuplicateMofN(h_session) return ret -ca_duplicatemofn_ex = make_error_handle_function(ca_duplicatemofn) + +ca_duplicatemofn_ex = make_error_handle_function(ca_duplicatemofn) diff --git a/pycryptoki/logging_filters.py b/pycryptoki/logging_filters.py index d3a8560..8a3b6f4 100755 --- a/pycryptoki/logging_filters.py +++ b/pycryptoki/logging_filters.py @@ -1,10 +1,17 @@ import logging import os + class OnlyTestsFilter(logging.Filter): + """ """ def filter(self, record): - + """ + + :param record: + + """ + file_path = os.path.realpath(__file__) dir_path = os.path.dirname(file_path) dir_members = os.listdir(dir_path) @@ -15,12 +22,9 @@ def filter(self, record): files.append(os.path.join(split_file[0])) should_show = True - + for python_file in files: if python_file in record.getMessage(): should_show = False - - return should_show - - + return should_show diff --git a/pycryptoki/luna_threading.py b/pycryptoki/luna_threading.py index 408030b..6428ea7 100755 --- a/pycryptoki/luna_threading.py +++ b/pycryptoki/luna_threading.py @@ -1,3 +1,8 @@ +import logging +import sys +import threading +import time + from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP from pycryptoki.defaults import ADMIN_PARTITION_LABEL, MANUFACTURER_ID, MODEL @@ -10,11 +15,6 @@ from pycryptoki.test_functions import verify_object_attributes from pycryptoki.token_management import get_token_by_label_ex, \ c_get_mechanism_list_ex, c_get_mechanism_info_ex -import logging -import sys -import threading -import time - logger = logging.getLogger(__name__) @@ -25,40 +25,41 @@ class TestThread(threading.Thread): - ''' - A member of the threading class which, when given the proper parameters, will + """A member of the threading class which, when given the proper parameters, will perform some functions on the HSM in it's own thread. If one of the tests fails it will be reported when all the threads finish. - ''' - def __init__(self, queue, thread_name, token_label, thread_type, max_time = 60): #60 seconds - ''' + + + """ + + def __init__(self, queue, thread_name, token_label, thread_type, max_time=60): # 60 seconds + """ @param queue: The queue that the threads will be placed into, this is required to signal to the queue that the task is done @param thread_name: The name of the thread for debug printing purposes @param token_label: The token label to perform multithreaded operations on - @param thread_type: The a numeric value specifyingoperation the thread will do, see the variables + @param thread_type: The a numeric value specifyingoperation the thread will do, see the variables described above the TestThread class declaration ex. GET_TOKEN_INFO @param max_time: The amount of time to spend doing the test in seconds - ''' - + """ + self.thread_name = thread_name self.thread_type = thread_type self.max_time = max_time self.queue = queue self.token_label = token_label threading.Thread.__init__(self) - + def run(self): - ''' - Called by the inheirited threading class to run the actual thread - ''' + """Called by the inheirited threading class to run the actual thread""" logger.debug("Starting thread " + self.thread_name + " type " + str(self.thread_type)) self._return = True - + try: - #For a given amount of time run the operations in a separate thread + # For a given amount of time run the operations in a separate thread start_time = time.time() - while ((time.time() - start_time) < self.max_time) and ((not self.starting_slot >= self.ending_slot) or (self.starting_slot == -1 and self.ending_slot == -1)): + while ((time.time() - start_time) < self.max_time) and ( + (not self.starting_slot >= self.ending_slot) or (self.starting_slot == -1 and self.ending_slot == -1)): if self.thread_type == CREATE_AND_REMOVE_KEYS: self.create_and_remove_keys() elif self.thread_type == OPEN_AND_CLOSE_SESSIONS: @@ -76,20 +77,20 @@ def run(self): self.queue.task_done() print sys.exc_info()[0] raise - return - - if (self._return == True): + + if self._return == True: self._return = True self.queue.task_done() - + def get_token_info(self): - ''' - Test that will get the token info and verify that the fields have been + """Test that will get the token info and verify that the fields have been set to something other than null - ''' + + + """ slot = get_token_by_label_ex(self.token_label) token_info = c_get_token_info_ex(slot) - + assert token_info['label'] == ADMIN_PARTITION_LABEL assert token_info['manufacturerID'] == MANUFACTURER_ID assert token_info['model'] == MODEL @@ -100,47 +101,47 @@ def get_token_info(self): assert token_info['ulRwSessionCount'] != 0 assert token_info['ulMaxPinLen'] != 0 assert token_info['ulMinPinLen'] != 0 -# token_info['hardwareVersion'] = c_token_info.hardwareVersion -# token_info['firmwareVersion'] = c_token_info.firmwareVersion - + + # token_info['hardwareVersion'] = c_token_info.hardwareVersion + # token_info['firmwareVersion'] = c_token_info.firmwareVersion + def create_and_remove_keys(self): - ''' - Test that will create a bunch of keys and verify the attributes on + """Test that will create a bunch of keys and verify the attributes on those keys - ''' + + + """ slot = get_token_by_label_ex(self.token_label) h_session = c_open_session_ex(slot) - + logger.debug(self.thread_name + " Generating keys") key_handle = c_generate_key_ex(h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - key_handle_public, key_handle_private = c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - + key_handle_public, key_handle_private = c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + logger.debug(self.thread_name + " Verifying keys") verify_object_attributes(h_session, key_handle, CKM_DES_KEY_GEN_TEMP) verify_object_attributes(h_session, key_handle_public, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP) verify_object_attributes(h_session, key_handle_private, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - + def open_and_close_sessions(self): - ''' - Test that will open and close sessions repeatedly - ''' + """Test that will open and close sessions repeatedly""" slot = get_token_by_label_ex(self.token_label) - + ret, h_session = c_open_session(slot) assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] - + ret = c_close_session(h_session) assert ret_vals_dictionary[ret] == ret_vals_dictionary[CKR_OK] - + def get_mechanism_info(self): - ''' - Test that will get the mechanism info repeatedly and verify it is non null - ''' + """Test that will get the mechanism info repeatedly and verify it is non null""" slot = get_token_by_label_ex(self.token_label) mechanism_list = c_get_mechanism_list_ex(slot) assert len(mechanism_list) > 0, "The mechanism list should have a non zero length" for mechanism in mechanism_list: mech_info = c_get_mechanism_info_ex(slot, mechanism) - assert (mech_info.ulMinKeySize > 0 or mech_info.ulMaxKeySize > 0 or mech_info.flags > 0) and mech_info.ulMinKeySize <= mech_info.ulMaxKeySize, "Verifing that all fields are not 0 should be good enough for now" - + assert ( + mech_info.ulMinKeySize > 0 or mech_info.ulMaxKeySize > 0 or mech_info.flags > 0) and mech_info.ulMinKeySize <= mech_info.ulMaxKeySize, "Verifing that all fields are not 0 should be good enough for now" diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 67e2cae..f13e7e4 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -1,136 +1,138 @@ from ctypes import c_void_p, cast, pointer, POINTER, sizeof, c_char_p, \ create_string_buffer + from pycryptoki.cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR from pycryptoki.defines import CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, \ CK_CRYPTOKI_ELEMENT, CK_STORAGE_HOST, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL - -CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, - 'ulType' : CK_CRYPTOKI_ELEMENT, - 'ulHandle' : 5, - 'ulDeleteAfterExtract' : 0, - 'pBuffer' : 0, - 'pulBufferLen' : 0, - 'ulStorage' : CK_STORAGE_HOST, - 'pedId' : 0, - 'pbFileName' : 0, - 'ctxID' : 3 +CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism': CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, + 'ulType': CK_CRYPTOKI_ELEMENT, + 'ulHandle': 5, + 'ulDeleteAfterExtract': 0, + 'pBuffer': 0, + 'pulBufferLen': 0, + 'ulStorage': CK_STORAGE_HOST, + 'pedId': 0, + 'pbFileName': 0, + 'ctxID': 3 } -CK_AES_CBC_PAD_INSERT_PARAMS_TEMP = {'mechanism' : CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, - 'ulType' : CK_CRYPTOKI_ELEMENT, - 'ulContainerState' : 0, - 'pBuffer' : 0, - 'pulBufferLen' : 0, - 'ulStorageType' : CK_STORAGE_HOST, - 'pulType' : 0, - 'pulHandle' : 0, - 'ctxID' : 3, - 'pedID' : 3, - 'pbFileName' : 0, - 'ulStorage' : CK_STORAGE_HOST, - } +CK_AES_CBC_PAD_INSERT_PARAMS_TEMP = {'mechanism': CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, + 'ulType': CK_CRYPTOKI_ELEMENT, + 'ulContainerState': 0, + 'pBuffer': 0, + 'pulBufferLen': 0, + 'ulStorageType': CK_STORAGE_HOST, + 'pulType': 0, + 'pulHandle': 0, + 'ctxID': 3, + 'pedID': 3, + 'pbFileName': 0, + 'ulStorage': CK_STORAGE_HOST, + } + +supported_parameters = {'CK_AES_CBC_PAD_EXTRACT_PARAMS': CK_AES_CBC_PAD_EXTRACT_PARAMS, + 'CK_AES_CBC_PAD_INSERT_PARAMS': CK_AES_CBC_PAD_INSERT_PARAMS} -supported_parameters = {'CK_AES_CBC_PAD_EXTRACT_PARAMS' : CK_AES_CBC_PAD_EXTRACT_PARAMS, - 'CK_AES_CBC_PAD_INSERT_PARAMS' : CK_AES_CBC_PAD_INSERT_PARAMS} def get_c_struct_from_mechanism(python_dictionary, params_type_string): - ''' - Gets a c struct from a python dictionary representing that struct - - @param python_dictionary: The python dictionary representing the C struct, + """Gets a c struct from a python dictionary representing that struct + + :param python_dictionary: The python dictionary representing the C struct, see CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP for an example - @param params_type_string: A string representing the parameter struct. + :param params_type_string: A string representing the parameter struct. ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' - @return: A C struct - ''' + :returns: A C struct + + """ params_type = supported_parameters[params_type_string] params = params_type() mech = CK_MECHANISM() mech.mechanism = python_dictionary['mechanism'] mech.pParameter = cast(pointer(params), c_void_p) mech.usParameterLen = CK_ULONG(sizeof(params_type)) - - #Automatically handle the simpler fields + + # Automatically handle the simpler fields for entry in params_type._fields_: key_name = entry[0] key_type = entry[1] - + if key_type == CK_ULONG: setattr(params, key_name, CK_ULONG(python_dictionary[key_name])) elif key_type == CK_ULONG_PTR: setattr(params, key_name, pointer(CK_ULONG(python_dictionary[key_name]))) else: continue - - #Explicitly handle the more complex fields + + # Explicitly handle the more complex fields if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: - if (len(python_dictionary['pBuffer']) == 0): + if len(python_dictionary['pBuffer']) == 0: params.pBuffer = None else: params.pBuffer = (CK_BYTE * len(python_dictionary['pBuffer']))() - #params.pbFileName = 0 #TODO convert byte pointer to serializable type + # params.pbFileName = 0 #TODO convert byte pointer to serializable type pass elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: - #params.pbFileName = TODO + # params.pbFileName = TODO params.pBuffer = cast(create_string_buffer(python_dictionary['pBuffer']), CK_BYTE_PTR) params.ulBufferLen = len(python_dictionary['pBuffer']) pass else: raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") - + return mech + def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): - ''' - Gets a python dictionary from a c mechanism's struct for serialization + """Gets a python dictionary from a c mechanism's struct for serialization and easier test case writing - - @param c_mechanism: The c mechanism to convert to a python dictionary - @param params_type_string: A string representing the parameter struct. + + :param c_mechanism: The c mechanism to convert to a python dictionary + :param params_type_string: A string representing the parameter struct. ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' - - @return: A python dictionary representing the c struct - ''' + :returns: A python dictionary representing the c struct + + """ python_dictionary = {} python_dictionary['mechanism'] = c_mechanism.mechanism params_type = supported_parameters[params_type_string] params_struct = cast(c_mechanism.pParameter, POINTER(params_type)).contents - - #Automatically handle the simpler fields + + # Automatically handle the simpler fields for entry in params_type._fields_: key_name = entry[0] key_type = entry[1] - + if key_type == CK_ULONG: python_dictionary[key_name] = getattr(params_struct, key_name) elif key_type == CK_ULONG_PTR: python_dictionary[key_name] = getattr(params_struct, key_name).contents.value else: continue - - #Explicitly handle the more complex fields + + # Explicitly handle the more complex fields if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: bufferLength = params_struct.pulBufferLen.contents.value - if params_struct.pBuffer == None: + if params_struct.pBuffer is None: bufferString = None else: char_p_string = cast(params_struct.pBuffer, c_char_p).value - if char_p_string != None: + if char_p_string is not None: bufferString = char_p_string[0:bufferLength] else: bufferString = None python_dictionary['pBuffer'] = bufferString - python_dictionary['pbFileName'] = 0 #TODO + python_dictionary['pbFileName'] = 0 # TODO elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: - python_dictionary['pbFileName'] = 0 #TODO - python_dictionary['pBuffer'] = 0 #TODO + python_dictionary['pbFileName'] = 0 # TODO + python_dictionary['pBuffer'] = 0 # TODO else: raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") return python_dictionary + if __name__ == '__main__': - pass \ No newline at end of file + pass diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 046617d..f384edd 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -1,4 +1,5 @@ from ctypes import create_string_buffer, cast, byref + from pycryptoki.attributes import convert_ck_char_array_to_string, \ convert_string_to_CK_CHAR, Attributes from pycryptoki.cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ @@ -10,142 +11,163 @@ from pycryptoki.sign_verify import do_multipart_sign_or_digest from pycryptoki.test_functions import make_error_handle_function + def c_generate_random(h_session, length): - ''' - Generates a sequence of random numbers - - @param h_session: The current session - @param length: The length in bytes of the random number sequence - - @return: The result code, A string of random data - ''' + """Generates a sequence of random numbers + + :param h_session: The current session + :param length: The length in bytes of the random number sequence + :returns: The result code, A string of random data + + """ random_data = cast(create_string_buffer("", length), CK_BYTE_PTR) ret = C_GenerateRandom(h_session, random_data, CK_ULONG(length)) - + random_string = convert_ck_char_array_to_string(random_data._objects.values()[0]) return ret, random_string + + c_generate_random_ex = make_error_handle_function(c_generate_random) + def c_seed_random(h_session, seed): - ''' - Seeds the random number generator - - @param h_session: The current session - @param seed: A python string of some seed - - @return: The result code - ''' + """Seeds the random number generator + + :param h_session: The current session + :param seed: A python string of some seed + :returns: The result code + + """ seed_bytes = cast(convert_string_to_CK_CHAR(seed), CK_BYTE_PTR) seed_length = CK_ULONG(len(seed)) ret = C_SeedRandom(h_session, seed_bytes, seed_length) - return ret; + return ret + + c_seed_random_ex = make_error_handle_function(c_seed_random) -def c_digest(h_session, data_to_digest, digest_flavor, mech = None): - ''' - Digests some data - - @param h_session: Current session - @param data_to_digest: The data to digest, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, - SHA224, SHA256, SHA384, SHA512) - @param mech: The mechanism to be used. If None a blank one with the digest_flavour will be used - - @return: The result code, a python string of the digested data - ''' - - #Get mechanism if none provided - if mech == None: + +def c_digest(h_session, data_to_digest, digest_flavor, mech=None): + """Digests some data + + :param h_session: Current session + :param data_to_digest: The data to digest, either a string or a list of strings. If this is a list + a multipart operation will be used + :param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, + SHA224, SHA256, SHA384, SHA512) + :param mech: The mechanism to be used. If None a blank one with the + digest_flavour will be used (Default value = None) + :returns: The result code, a python string of the digested data + + """ + + # Get mechanism if none provided + if mech is None: mech = _get_mechanism(digest_flavor) - #Initialize Digestion + # Initialize Digestion ret = C_DigestInit(h_session, mech) if ret != CKR_OK: return ret - #if a list is passed out do an digest operation on each string in the list, otherwise just do one digest operation + # if a list is passed out do an digest operation on each string in the list, otherwise just do one digest operation is_multi_part_operation = isinstance(data_to_digest, list) or isinstance(data_to_digest, tuple) - + if is_multi_part_operation: - ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, C_DigestFinal, data_to_digest) + ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, C_DigestFinal, + data_to_digest) else: - #Get arguments + # Get arguments digest_data_length = len(data_to_digest) c_data_to_digest = get_c_data_to_sign_or_encrypt(data_to_digest) - - #Get the length of the digested data + + # Get the length of the digested data digest_length = CK_ULONG() ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), None, byref(digest_length)) if ret != CKR_OK: return ret, None - + output = create_string_buffer("", digest_length.value) digested_data = cast(output, CK_BYTE_PTR) - - #Digest data + + # Digest data ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), digested_data, byref(digest_length)) - - #Convert Digested data into a python string + + # Convert Digested data into a python string ck_char_array = digested_data._objects.values()[0] digested_python_string = convert_ck_char_array_to_string(ck_char_array) - + return ret, digested_python_string + + c_digest_ex = make_error_handle_function(c_digest) -def c_digestkey(h_session, h_key, digest_flavor, mech = None): -#Get mechanism if none provided - if mech == None: + +def c_digestkey(h_session, h_key, digest_flavor, mech=None): + """ + + :param h_session: Logged in session handle + :param h_key: Key to digest + :param digest_flavor: Digest flavor + :param mech: Mechanism to use for digest. Defaults to using the flavor mechanism. (Default value = None) + """ + # Get mechanism if none provided + if mech is None: mech = _get_mechanism(digest_flavor) - #Initialize Digestion + # Initialize Digestion ret = C_DigestInit(h_session, mech) if ret != CKR_OK: return ret ret = C_DigestKey(h_session, h_key) return ret -c_digestkey_ex = make_error_handle_function(c_digestkey) +c_digestkey_ex = make_error_handle_function(c_digestkey) + def c_create_object(h_session, template): - ''' - Creates an object based on a given python template - - @param h_session: The session handle to use - @param template: The python template which the object will be based on - - @return: The result code, the handle of the object - ''' + """Creates an object based on a given python template + + :param h_session: The session handle to use + :param template: The python template which the object will be based on + :returns: The result code, the handle of the object + + """ c_template = Attributes(template).get_c_struct() new_object_handle = CK_ULONG() ret = C_CreateObject(h_session, c_template, CK_ULONG(len(template)), byref(new_object_handle)) - + return ret, new_object_handle.value + + c_create_object_ex = make_error_handle_function(c_create_object) + def c_set_ped_id(slot, id): - ''' - Set the PED ID for the given slot. - @param slot : slot number - @parm id : PED ID to use - - @return: The result code - ''' + """Set the PED ID for the given slot. + + :param slot: slot number + :param id: PED ID to use + :returns: The result code + + """ ret = CA_SetPedId(CK_SLOT_ID(slot), CK_ULONG(id)) - return ret; + return ret + + c_set_ped_id_ex = make_error_handle_function(c_set_ped_id) + def c_get_ped_id(slot): - ''' - Get the PED ID for the given slot. - @param slot : slot number - - @return: The result code and ID - ''' + """Get the PED ID for the given slot. + + :param slot: slot number + :returns: The result code and ID + + """ pedId = CK_ULONG() ret = CA_GetPedId(CK_SLOT_ID(slot), byref(pedId)) return ret, pedId.value + + c_get_ped_id_ex = make_error_handle_function(c_get_ped_id) diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 0ed0071..06f7887 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -1,71 +1,79 @@ -from ctypes import byref, sizeof +from ctypes import byref + from pycryptoki.attributes import Attributes, c_struct_to_python from pycryptoki.cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ C_FindObjects, C_FindObjectsFinal, C_GetAttributeValue, C_SetAttributeValue -from pycryptoki.defines import CKR_OK, CKA_CLASS, CKA_LABEL, CKA_VALUE -from pycryptoki.test_functions import LunaException, make_error_handle_function +from pycryptoki.defines import CKR_OK +from pycryptoki.test_functions import make_error_handle_function + def c_find_objects(h_session, objects_find, template_attributes, num_entries): - ''' - Calls c_find_objects and c_find_objects_init to get a python dictionary + """Calls c_find_objects and c_find_objects_init to get a python dictionary of the objects found. - - @param h_session: The current session - @param objects_find: A python dictionary of the object template to look for - @param template_attributes: A python dictionary of the attributes to look for - @param num_entries: The number of entries to return - - @return: Returns a python dictionary of the templates of the objects found - ''' + + :param h_session: The current session + :param objects_find: A python dictionary of the object template to look for + :param template_attributes: A python dictionary of the attributes to look for + :param num_entries: The number of entries to return + :returns: Returns a python dictionary of the templates of the objects found + + """ attributes = [] struct = Attributes(objects_find).get_c_struct() ret = C_FindObjectsInit(h_session, struct, CK_ULONG(len(objects_find))) if ret != CKR_OK: return ret, -1, None; - + h_ary = (CK_OBJECT_HANDLE * num_entries)() us_total = CK_ULONG(num_entries) ret = C_FindObjects(h_session, h_ary, CK_ULONG(num_entries), byref(us_total)) if ret != CKR_OK: return ret, -1, None; - #todo get attribute value for all of them + # todo get attribute value for all of them for i in range(0, us_total.value): attribute = c_get_attribute_value_ex(h_session, h_ary[i], template_attributes) attributes.append(attribute) - ret = C_FindObjectsFinal(h_session) return ret, h_ary[0], attributes -c_find_objects_ex = make_error_handle_function(c_find_objects) + + +c_find_objects_ex = make_error_handle_function(c_find_objects) + def c_get_attribute_value(h_session, h_object, template): - ''' - Calls C_GetAttrributeValue to get an attribute value based on a python template - @param h_session: The current session - @param h_object: The handle of the object to get attributes for - @param template: A python dictionary representing the template of the attributes to be retrieved - - @return: A python dictionary representing the attributes returned from the HSM/library - ''' + """Calls C_GetAttrributeValue to get an attribute value based on a python template + + :param h_session: The current session + :param h_object: The handle of the object to get attributes for + :param template: A python dictionary representing the template of the attributes to be retrieved + :returns: A python dictionary representing the attributes returned from the HSM/library + + """ c_struct = Attributes(template).get_c_struct() ret = C_GetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) if ret != CKR_OK: return ret; - + return ret, c_struct_to_python(c_struct) -c_get_attribute_value_ex = make_error_handle_function(c_get_attribute_value) + + +c_get_attribute_value_ex = make_error_handle_function(c_get_attribute_value) + def c_set_attribute_value(h_session, h_object, template): - ''' - Calls C_SetAttributeValue to set an attribute value based on a python template - @param h_session: The current session - @param h_object: The handle of the object to get attributes for - @param template: A python dictionary representing the template of the attributes to be written - - @return: A python dictionary representing the attributes returned from the HSM/library - ''' + """Calls C_SetAttributeValue to set an attribute value based on a python template + + :param h_session: The current session + :param h_object: The handle of the object to get attributes for + :param template: A python dictionary representing the template of the attributes to be written + :returns: A python dictionary representing the attributes returned from the HSM/library + + """ c_struct = Attributes(template).get_c_struct() ret = C_SetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) if ret != CKR_OK: return ret; - + return ret, c_struct_to_python(c_struct) -c_set_attribute_value_ex = make_error_handle_function(c_set_attribute_value) \ No newline at end of file + + +c_set_attribute_value_ex = make_error_handle_function(c_set_attribute_value) diff --git a/pycryptoki/policy_management.py b/pycryptoki/policy_management.py index c319856..f43cc7a 100755 --- a/pycryptoki/policy_management.py +++ b/pycryptoki/policy_management.py @@ -2,49 +2,54 @@ CA_SetDestructiveHSMPolicy from pycryptoki.test_functions import make_error_handle_function + def ca_set_hsm_policy(h_session, policy_id, policy_val): - ''' - Sets the HSM policies by calling CA_SetHSMPolicy - - @param h_session: The session handle of the administrator setting the HSM policy - @param policy_id: The ID of the policy being set - @param policy_val: The value of the policy being set - - @return: The result code - ''' + """Sets the HSM policies by calling CA_SetHSMPolicy + + :param h_session: The session handle of the administrator setting the HSM policy + :param policy_id: The ID of the policy being set + :param policy_val: The value of the policy being set + :returns: The result code + + """ ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) return ret + + ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) + def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): - ''' - Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy - - @param h_session: The session handle of the administrator setting the HSM policy - @param policy_id: The ID of the policy being set - @param policy_val: The value of the policy being set - - @return: The result code - ''' + """Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy + + :param h_session: The session handle of the administrator setting the HSM policy + :param policy_id: The ID of the policy being set + :param policy_val: The value of the policy being set + :returns: The result code + + """ ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) return ret + + ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) + def ca_set_container_policy(h_session, container_number, policy_id, policy_val): - ''' - Sets a policy on the container. - - NOTE: With per partition SO this method should generally not be used. Instead + """Sets a policy on the container. + + NOTE: With per partition SO this method should generally not be used. Instead ca_set_partition_policies should be used - - @param h_session: The session handle of the entity with permission to change the policy - @param container_number: The container number to set the policy on. - @param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) - @param policy_val: The value to set the policy to - - @return: The result code - ''' + + :param h_session: The session handle of the entity with permission to change the policy + :param container_number: The container number to set the policy on. + :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) + :param policy_val: The value to set the policy to + :returns: The result code + + """ ret = CA_SetContainerPolicy(h_session, CK_ULONG(container_number), CK_ULONG(policy_id), CK_ULONG(policy_val)) return ret -ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) + +ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index bd5860e..439563d 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -1,20 +1,27 @@ -''' +""" Contains both a local and remote pycryptoki client -''' -from pycryptoki.daemon.pycryptoki_daemon import pycryptoki_functions,\ - functions_needing_serialization -from pycryptoki.session_management import c_finalize, c_initialize_ex, c_initialize +""" import logging + import rpyc +from pycryptoki.daemon.pycryptoki_daemon import pycryptoki_functions, \ + functions_needing_serialization +from pycryptoki.session_management import c_finalize, c_initialize_ex, c_initialize + log = logging.getLogger(__name__) -class RemotePycryptokiClient(): - ''' - Class forwards pycryptoki calls over xmlrpc. Some functions need more serialization - so they are directly handled, others are handled automagically by __get_attr__ - ''' +class RemotePycryptokiClient: + """Class to handle connecting to a remote Pycryptoki RPYC daemon. + + After instantiation, you can use it directly to make calls to a remote + cryptoki library via RPYC (no need to do any imports or anything like that, just + use the direct pycryptoki call like c\_initialize_ex() ) + + :param ip: IP Address of the client the remote daemon is running on. + :param port: What Port the daemon is running on. + """ def __init__(self, ip=None, port=None): self.ip = ip @@ -23,13 +30,19 @@ def __init__(self, ip=None, port=None): self.start() def kill(self): - #maybe we should be reloading cryptoki dll? + """ + Close out the local RPYC connection. + """ + # maybe we should be reloading cryptoki dll? if self.started and not self.connection.closed: log.info("Stopping remote pycryptoki connection.") self.connection.close() self.started = False def start(self): + """ + Start the connection to the remote RPYC daemon. + """ if not self.started: log.info("Starting remote pycryptoki connection") self.connection = rpyc.classic.connect(self.ip, port=self.port) @@ -37,42 +50,50 @@ def start(self): self.started = True def cleanup(self): + """ """ pass - def __getattr__(self, name): - ''' + """ This is the python default attribute handler, if an attribute is not found it's probably a pycryptoki call that we forward automagically to the server - ''' + """ if not self.started: self.start() if hasattr(self.server, name): def wrapper(*args, **kwargs): + """ + + :param *args: + :param **kwargs: + + """ log.info("Running remote pycryptoki command: " "{0}(args={1}, kwargs={2})".format(name, args, kwargs)) return getattr(self.server, name)(*args, **kwargs) + return wrapper else: raise AttributeError(name) class LocalPycryptokiClient(object): - ''' - Class forwards calls to pycryptoki to local client but looks identical to remote + """Class forwards calls to pycryptoki to local client but looks identical to remote client - ''' + + + """ def __init__(self): - '''Nothing really to do''' + """Nothing really to do""" pass def __getattr__(self, name): - ''' + """ Function that overrides python attribute lookup; automagically calls functions in pycryptoki if they're listed in the daemon - ''' + """ log.info("Running local pycryptoki command: {0}".format(name)) if pycryptoki_functions.has_key(name): if 'c_initialize' in name: @@ -84,27 +105,33 @@ def __getattr__(self, name): return object.__getattribute__(self, name) def c_initialize_ex(self): + """ """ c_finalize() return c_initialize_ex() def c_initialize(self): + """ """ c_finalize() return c_initialize() def kill(self): - #nothing to do here, maybe we should unload and reload the dll + """ """ + # nothing to do here, maybe we should unload and reload the dll pass def cleanup(self): - #nothing to do here + """ """ + # nothing to do here pass def deserialize_dict(dictionary): - ''' - Helper function to convert a dictionary with to + """Helper function to convert a dictionary with to for xmlrpc - ''' + + :param dictionary: + + """ deserialized_dictionary = {} for key, value in dictionary.iteritems(): deserialized_dictionary[int(key)] = value diff --git a/pycryptoki/return_values.py b/pycryptoki/return_values.py old mode 100644 new mode 100755 index b79e0ec..9471eba --- a/pycryptoki/return_values.py +++ b/pycryptoki/return_values.py @@ -1,4 +1,4 @@ -''' +""" THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE This file should NOT be checked into MKS or modified in any way, this file was created by setup/initialize.py. Any changes to this file will be wiped out when @@ -8,204 +8,204 @@ of defines whose variable name starts with CKR_. This convention means they are a return value for the cryptoki C API. -''' +""" from defines import * -ret_vals_dictionary = { - CKR_OK : 'CKR_OK', - CKR_CANCEL : 'CKR_CANCEL', - CKR_HOST_MEMORY : 'CKR_HOST_MEMORY', - CKR_SLOT_ID_INVALID : 'CKR_SLOT_ID_INVALID', - CKR_GENERAL_ERROR : 'CKR_GENERAL_ERROR', - CKR_FUNCTION_FAILED : 'CKR_FUNCTION_FAILED', - CKR_ARGUMENTS_BAD : 'CKR_ARGUMENTS_BAD', - CKR_NO_EVENT : 'CKR_NO_EVENT', - CKR_NEED_TO_CREATE_THREADS : 'CKR_NEED_TO_CREATE_THREADS', - CKR_CANT_LOCK : 'CKR_CANT_LOCK', - CKR_ATTRIBUTE_READ_ONLY : 'CKR_ATTRIBUTE_READ_ONLY', - CKR_ATTRIBUTE_SENSITIVE : 'CKR_ATTRIBUTE_SENSITIVE', - CKR_ATTRIBUTE_TYPE_INVALID : 'CKR_ATTRIBUTE_TYPE_INVALID', - CKR_ATTRIBUTE_VALUE_INVALID : 'CKR_ATTRIBUTE_VALUE_INVALID', - CKR_DATA_INVALID : 'CKR_DATA_INVALID', - CKR_DATA_LEN_RANGE : 'CKR_DATA_LEN_RANGE', - CKR_DEVICE_ERROR : 'CKR_DEVICE_ERROR', - CKR_DEVICE_MEMORY : 'CKR_DEVICE_MEMORY', - CKR_DEVICE_REMOVED : 'CKR_DEVICE_REMOVED', - CKR_ENCRYPTED_DATA_INVALID : 'CKR_ENCRYPTED_DATA_INVALID', - CKR_ENCRYPTED_DATA_LEN_RANGE : 'CKR_ENCRYPTED_DATA_LEN_RANGE', - CKR_FUNCTION_CANCELED : 'CKR_FUNCTION_CANCELED', - CKR_FUNCTION_NOT_PARALLEL : 'CKR_FUNCTION_NOT_PARALLEL', - CKR_FUNCTION_NOT_SUPPORTED : 'CKR_FUNCTION_NOT_SUPPORTED', - CKR_KEY_HANDLE_INVALID : 'CKR_KEY_HANDLE_INVALID', - CKR_KEY_SIZE_RANGE : 'CKR_KEY_SIZE_RANGE', - CKR_KEY_TYPE_INCONSISTENT : 'CKR_KEY_TYPE_INCONSISTENT', - CKR_KEY_NOT_NEEDED : 'CKR_KEY_NOT_NEEDED', - CKR_KEY_CHANGED : 'CKR_KEY_CHANGED', - CKR_KEY_NEEDED : 'CKR_KEY_NEEDED', - CKR_KEY_INDIGESTIBLE : 'CKR_KEY_INDIGESTIBLE', - CKR_KEY_FUNCTION_NOT_PERMITTED : 'CKR_KEY_FUNCTION_NOT_PERMITTED', - CKR_KEY_NOT_WRAPPABLE : 'CKR_KEY_NOT_WRAPPABLE', - CKR_KEY_UNEXTRACTABLE : 'CKR_KEY_UNEXTRACTABLE', - CKR_MECHANISM_INVALID : 'CKR_MECHANISM_INVALID', - CKR_MECHANISM_PARAM_INVALID : 'CKR_MECHANISM_PARAM_INVALID', - CKR_OBJECT_HANDLE_INVALID : 'CKR_OBJECT_HANDLE_INVALID', - CKR_OPERATION_ACTIVE : 'CKR_OPERATION_ACTIVE', - CKR_OPERATION_NOT_INITIALIZED : 'CKR_OPERATION_NOT_INITIALIZED', - CKR_PIN_INCORRECT : 'CKR_PIN_INCORRECT', - CKR_PIN_INVALID : 'CKR_PIN_INVALID', - CKR_PIN_LEN_RANGE : 'CKR_PIN_LEN_RANGE', - CKR_PIN_EXPIRED : 'CKR_PIN_EXPIRED', - CKR_PIN_LOCKED : 'CKR_PIN_LOCKED', - CKR_SESSION_CLOSED : 'CKR_SESSION_CLOSED', - CKR_SESSION_COUNT : 'CKR_SESSION_COUNT', - CKR_SESSION_HANDLE_INVALID : 'CKR_SESSION_HANDLE_INVALID', - CKR_SESSION_PARALLEL_NOT_SUPPORTED : 'CKR_SESSION_PARALLEL_NOT_SUPPORTED', - CKR_SESSION_READ_ONLY : 'CKR_SESSION_READ_ONLY', - CKR_SESSION_EXISTS : 'CKR_SESSION_EXISTS', - CKR_SESSION_READ_ONLY_EXISTS : 'CKR_SESSION_READ_ONLY_EXISTS', - CKR_SESSION_READ_WRITE_SO_EXISTS : 'CKR_SESSION_READ_WRITE_SO_EXISTS', - CKR_SIGNATURE_INVALID : 'CKR_SIGNATURE_INVALID', - CKR_SIGNATURE_LEN_RANGE : 'CKR_SIGNATURE_LEN_RANGE', - CKR_TEMPLATE_INCOMPLETE : 'CKR_TEMPLATE_INCOMPLETE', - CKR_TEMPLATE_INCONSISTENT : 'CKR_TEMPLATE_INCONSISTENT', - CKR_TOKEN_NOT_PRESENT : 'CKR_TOKEN_NOT_PRESENT', - CKR_TOKEN_NOT_RECOGNIZED : 'CKR_TOKEN_NOT_RECOGNIZED', - CKR_TOKEN_WRITE_PROTECTED : 'CKR_TOKEN_WRITE_PROTECTED', - CKR_UNWRAPPING_KEY_HANDLE_INVALID : 'CKR_UNWRAPPING_KEY_HANDLE_INVALID', - CKR_UNWRAPPING_KEY_SIZE_RANGE : 'CKR_UNWRAPPING_KEY_SIZE_RANGE', - CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT : 'CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT', - CKR_USER_ALREADY_LOGGED_IN : 'CKR_USER_ALREADY_LOGGED_IN', - CKR_USER_NOT_LOGGED_IN : 'CKR_USER_NOT_LOGGED_IN', - CKR_USER_PIN_NOT_INITIALIZED : 'CKR_USER_PIN_NOT_INITIALIZED', - CKR_USER_TYPE_INVALID : 'CKR_USER_TYPE_INVALID', - CKR_USER_ANOTHER_ALREADY_LOGGED_IN : 'CKR_USER_ANOTHER_ALREADY_LOGGED_IN', - CKR_USER_TOO_MANY_TYPES : 'CKR_USER_TOO_MANY_TYPES', - CKR_WRAPPED_KEY_INVALID : 'CKR_WRAPPED_KEY_INVALID', - CKR_WRAPPED_KEY_LEN_RANGE : 'CKR_WRAPPED_KEY_LEN_RANGE', - CKR_WRAPPING_KEY_HANDLE_INVALID : 'CKR_WRAPPING_KEY_HANDLE_INVALID', - CKR_WRAPPING_KEY_SIZE_RANGE : 'CKR_WRAPPING_KEY_SIZE_RANGE', - CKR_WRAPPING_KEY_TYPE_INCONSISTENT : 'CKR_WRAPPING_KEY_TYPE_INCONSISTENT', - CKR_RANDOM_SEED_NOT_SUPPORTED : 'CKR_RANDOM_SEED_NOT_SUPPORTED', - CKR_RANDOM_NO_RNG : 'CKR_RANDOM_NO_RNG', - CKR_DOMAIN_PARAMS_INVALID : 'CKR_DOMAIN_PARAMS_INVALID', - CKR_BUFFER_TOO_SMALL : 'CKR_BUFFER_TOO_SMALL', - CKR_SAVED_STATE_INVALID : 'CKR_SAVED_STATE_INVALID', - CKR_INFORMATION_SENSITIVE : 'CKR_INFORMATION_SENSITIVE', - CKR_STATE_UNSAVEABLE : 'CKR_STATE_UNSAVEABLE', - CKR_CRYPTOKI_NOT_INITIALIZED : 'CKR_CRYPTOKI_NOT_INITIALIZED', - CKR_CRYPTOKI_ALREADY_INITIALIZED : 'CKR_CRYPTOKI_ALREADY_INITIALIZED', - CKR_MUTEX_BAD : 'CKR_MUTEX_BAD', - CKR_MUTEX_NOT_LOCKED : 'CKR_MUTEX_NOT_LOCKED', - CKR_NEW_PIN_MODE : 'CKR_NEW_PIN_MODE', - CKR_NEXT_OTP : 'CKR_NEXT_OTP', - CKR_FUNCTION_REJECTED : 'CKR_FUNCTION_REJECTED', - CKR_VENDOR_DEFINED : 'CKR_VENDOR_DEFINED', - CKR_INSERTION_CALLBACK_NOT_SUPPORTED : 'CKR_INSERTION_CALLBACK_NOT_SUPPORTED', - CKR_FUNCTION_PARALLEL : 'CKR_FUNCTION_PARALLEL', - CKR_SESSION_EXCLUSIVE_EXISTS : 'CKR_SESSION_EXCLUSIVE_EXISTS', - CKR_RC_ERROR : 'CKR_RC_ERROR', - CKR_CONTAINER_HANDLE_INVALID : 'CKR_CONTAINER_HANDLE_INVALID', - CKR_TOO_MANY_CONTAINERS : 'CKR_TOO_MANY_CONTAINERS', - CKR_USER_LOCKED_OUT : 'CKR_USER_LOCKED_OUT', - CKR_CLONING_PARAMETER_ALREADY_EXISTS : 'CKR_CLONING_PARAMETER_ALREADY_EXISTS', - CKR_CLONING_PARAMETER_MISSING : 'CKR_CLONING_PARAMETER_MISSING', - CKR_CERTIFICATE_DATA_MISSING : 'CKR_CERTIFICATE_DATA_MISSING', - CKR_CERTIFICATE_DATA_INVALID : 'CKR_CERTIFICATE_DATA_INVALID', - CKR_ACCEL_DEVICE_ERROR : 'CKR_ACCEL_DEVICE_ERROR', - CKR_WRAPPING_ERROR : 'CKR_WRAPPING_ERROR', - CKR_UNWRAPPING_ERROR : 'CKR_UNWRAPPING_ERROR', - CKR_MAC_MISSING : 'CKR_MAC_MISSING', - CKR_DAC_POLICY_PID_MISMATCH : 'CKR_DAC_POLICY_PID_MISMATCH', - CKR_DAC_MISSING : 'CKR_DAC_MISSING', - CKR_BAD_DAC : 'CKR_BAD_DAC', - CKR_SSK_MISSING : 'CKR_SSK_MISSING', - CKR_BAD_MAC : 'CKR_BAD_MAC', - CKR_DAK_MISSING : 'CKR_DAK_MISSING', - CKR_BAD_DAK : 'CKR_BAD_DAK', - CKR_SIM_AUTHORIZATION_FAILED : 'CKR_SIM_AUTHORIZATION_FAILED', - CKR_SIM_VERSION_UNSUPPORTED : 'CKR_SIM_VERSION_UNSUPPORTED', - CKR_SIM_CORRUPT_DATA : 'CKR_SIM_CORRUPT_DATA', - CKR_USER_NOT_AUTHORIZED : 'CKR_USER_NOT_AUTHORIZED', - CKR_MAX_OBJECT_COUNT_EXCEEDED : 'CKR_MAX_OBJECT_COUNT_EXCEEDED', - CKR_SO_LOGIN_FAILURE_THRESHOLD : 'CKR_SO_LOGIN_FAILURE_THRESHOLD', - CKR_SIM_AUTHFORM_INVALID : 'CKR_SIM_AUTHFORM_INVALID', - CKR_CITS_DAK_MISSING : 'CKR_CITS_DAK_MISSING', - CKR_UNABLE_TO_CONNECT : 'CKR_UNABLE_TO_CONNECT', - CKR_PARTITION_DISABLED : 'CKR_PARTITION_DISABLED', - CKR_CALLBACK_ERROR : 'CKR_CALLBACK_ERROR', - CKR_SECURITY_PARAMETER_MISSING : 'CKR_SECURITY_PARAMETER_MISSING', - CKR_SP_TIMEOUT : 'CKR_SP_TIMEOUT', - CKR_TIMEOUT : 'CKR_TIMEOUT', - CKR_ECC_UNKNOWN_CURVE : 'CKR_ECC_UNKNOWN_CURVE', - CKR_MTK_ZEROIZED : 'CKR_MTK_ZEROIZED', - CKR_MTK_STATE_INVALID : 'CKR_MTK_STATE_INVALID', - CKR_INVALID_ENTRY_TYPE : 'CKR_INVALID_ENTRY_TYPE', - CKR_MTK_SPLIT_INVALID : 'CKR_MTK_SPLIT_INVALID', - CKR_HSM_STORAGE_FULL : 'CKR_HSM_STORAGE_FULL', - CKR_DEVICE_TIMEOUT : 'CKR_DEVICE_TIMEOUT', - CKR_CONTAINER_OBJECT_STORAGE_FULL : 'CKR_CONTAINER_OBJECT_STORAGE_FULL', - CKR_PED_CLIENT_NOT_RUNNING : 'CKR_PED_CLIENT_NOT_RUNNING', - CKR_PED_UNPLUGGED : 'CKR_PED_UNPLUGGED', - CKR_ECC_POINT_INVALID : 'CKR_ECC_POINT_INVALID', - CKR_OPERATION_NOT_ALLOWED : 'CKR_OPERATION_NOT_ALLOWED', - CKR_LICENSE_CAPACITY_EXCEEDED : 'CKR_LICENSE_CAPACITY_EXCEEDED', - CKR_LOG_FILE_NOT_OPEN : 'CKR_LOG_FILE_NOT_OPEN', - CKR_LOG_FILE_WRITE_ERROR : 'CKR_LOG_FILE_WRITE_ERROR', - CKR_LOG_BAD_FILE_NAME : 'CKR_LOG_BAD_FILE_NAME', - CKR_LOG_FULL : 'CKR_LOG_FULL', - CKR_LOG_NO_KCV : 'CKR_LOG_NO_KCV', - CKR_LOG_BAD_RECORD_HMAC : 'CKR_LOG_BAD_RECORD_HMAC', - CKR_LOG_BAD_TIME : 'CKR_LOG_BAD_TIME', - CKR_LOG_AUDIT_NOT_INITIALIZED : 'CKR_LOG_AUDIT_NOT_INITIALIZED', - CKR_LOG_RESYNC_NEEDED : 'CKR_LOG_RESYNC_NEEDED', - CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS : 'CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', - CKR_AUDIT_LOGIN_FAILURE_THRESHOLD : 'CKR_AUDIT_LOGIN_FAILURE_THRESHOLD', - CKR_INVALID_FUF_TARGET : 'CKR_INVALID_FUF_TARGET', - CKR_INVALID_FUF_HEADER : 'CKR_INVALID_FUF_HEADER', - CKR_INVALID_FUF_VERSION : 'CKR_INVALID_FUF_VERSION', - CKR_ECC_ECC_RESULT_AT_INF : 'CKR_ECC_ECC_RESULT_AT_INF', - CKR_AGAIN : 'CKR_AGAIN', - CKR_TOKEN_COPIED : 'CKR_TOKEN_COPIED', - CKR_SLOT_NOT_EMPTY : 'CKR_SLOT_NOT_EMPTY', - CKR_USER_ALREADY_ACTIVATED : 'CKR_USER_ALREADY_ACTIVATED', - CKR_STC_NO_CONTEXT : 'CKR_STC_NO_CONTEXT', - CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED : 'CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED', - CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED : 'CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED', - CKR_STC_DH_KEYGEN_ERROR : 'CKR_STC_DH_KEYGEN_ERROR', - CKR_STC_CIPHER_SUITE_REJECTED : 'CKR_STC_CIPHER_SUITE_REJECTED', - CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP : 'CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP', - CKR_STC_COMPUTE_DH_KEY_ERROR : 'CKR_STC_COMPUTE_DH_KEY_ERROR', - CKR_STC_FIRST_PHASE_KDF_ERROR : 'CKR_STC_FIRST_PHASE_KDF_ERROR', - CKR_STC_SECOND_PHASE_KDF_ERROR : 'CKR_STC_SECOND_PHASE_KDF_ERROR', - CKR_STC_KEY_CONFIRMATION_FAILED : 'CKR_STC_KEY_CONFIRMATION_FAILED', - CKR_STC_NO_SESSION_KEY : 'CKR_STC_NO_SESSION_KEY', - CKR_STC_RESPONSE_BAD_MAC : 'CKR_STC_RESPONSE_BAD_MAC', - CKR_STC_NOT_ENABLED : 'CKR_STC_NOT_ENABLED', - CKR_STC_CLIENT_HANDLE_INVALID : 'CKR_STC_CLIENT_HANDLE_INVALID', - CKR_STC_SESSION_INVALID : 'CKR_STC_SESSION_INVALID', - CKR_STC_CONTAINER_INVALID : 'CKR_STC_CONTAINER_INVALID', - CKR_STC_SEQUENCE_NUM_INVALID : 'CKR_STC_SEQUENCE_NUM_INVALID', - CKR_STC_NO_CHANNEL : 'CKR_STC_NO_CHANNEL', - CKR_STC_RESPONSE_DECRYPT_ERROR : 'CKR_STC_RESPONSE_DECRYPT_ERROR', - CKR_STC_RESPONSE_REPLAYED : 'CKR_STC_RESPONSE_REPLAYED', - CKR_STC_REKEY_CHANNEL_MISMATCH : 'CKR_STC_REKEY_CHANNEL_MISMATCH', - CKR_STC_RSA_ENCRYPT_ERROR : 'CKR_STC_RSA_ENCRYPT_ERROR', - CKR_STC_RSA_SIGN_ERROR : 'CKR_STC_RSA_SIGN_ERROR', - CKR_STC_RSA_DECRYPT_ERROR : 'CKR_STC_RSA_DECRYPT_ERROR', - CKR_STC_RESPONSE_UNEXPECTED_KEY : 'CKR_STC_RESPONSE_UNEXPECTED_KEY', - CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE : 'CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE', - CKR_STC_UNEXPECTED_DH_DATA_SIZE : 'CKR_STC_UNEXPECTED_DH_DATA_SIZE', - CKR_STC_OPEN_CIPHER_MISMATCH : 'CKR_STC_OPEN_CIPHER_MISMATCH', - CKR_STC_OPEN_DHNIST_PUBKEY_ERROR : 'CKR_STC_OPEN_DHNIST_PUBKEY_ERROR', - CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL : 'CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL', - CKR_STC_OPEN_RESP_GEN_FAIL : 'CKR_STC_OPEN_RESP_GEN_FAIL', - CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL : 'CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL', - CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL : 'CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL', - CKR_STC_ACTIVATE_RESP_GEN_FAIL : 'CKR_STC_ACTIVATE_RESP_GEN_FAIL', - CKR_CHALLENGE_INCORRECT : 'CKR_CHALLENGE_INCORRECT', - CKR_ACCESS_ID_INVALID : 'CKR_ACCESS_ID_INVALID', - CKR_ACCESS_ID_ALREADY_EXISTS : 'CKR_ACCESS_ID_ALREADY_EXISTS', - CKR_OBJECT_READ_ONLY : 'CKR_OBJECT_READ_ONLY', - CKR_KEY_NOT_ACTIVE : 'CKR_KEY_NOT_ACTIVE' -} \ No newline at end of file +ret_vals_dictionary = { + CKR_OK: 'CKR_OK', + CKR_CANCEL: 'CKR_CANCEL', + CKR_HOST_MEMORY: 'CKR_HOST_MEMORY', + CKR_SLOT_ID_INVALID: 'CKR_SLOT_ID_INVALID', + CKR_GENERAL_ERROR: 'CKR_GENERAL_ERROR', + CKR_FUNCTION_FAILED: 'CKR_FUNCTION_FAILED', + CKR_ARGUMENTS_BAD: 'CKR_ARGUMENTS_BAD', + CKR_NO_EVENT: 'CKR_NO_EVENT', + CKR_NEED_TO_CREATE_THREADS: 'CKR_NEED_TO_CREATE_THREADS', + CKR_CANT_LOCK: 'CKR_CANT_LOCK', + CKR_ATTRIBUTE_READ_ONLY: 'CKR_ATTRIBUTE_READ_ONLY', + CKR_ATTRIBUTE_SENSITIVE: 'CKR_ATTRIBUTE_SENSITIVE', + CKR_ATTRIBUTE_TYPE_INVALID: 'CKR_ATTRIBUTE_TYPE_INVALID', + CKR_ATTRIBUTE_VALUE_INVALID: 'CKR_ATTRIBUTE_VALUE_INVALID', + CKR_DATA_INVALID: 'CKR_DATA_INVALID', + CKR_DATA_LEN_RANGE: 'CKR_DATA_LEN_RANGE', + CKR_DEVICE_ERROR: 'CKR_DEVICE_ERROR', + CKR_DEVICE_MEMORY: 'CKR_DEVICE_MEMORY', + CKR_DEVICE_REMOVED: 'CKR_DEVICE_REMOVED', + CKR_ENCRYPTED_DATA_INVALID: 'CKR_ENCRYPTED_DATA_INVALID', + CKR_ENCRYPTED_DATA_LEN_RANGE: 'CKR_ENCRYPTED_DATA_LEN_RANGE', + CKR_FUNCTION_CANCELED: 'CKR_FUNCTION_CANCELED', + CKR_FUNCTION_NOT_PARALLEL: 'CKR_FUNCTION_NOT_PARALLEL', + CKR_FUNCTION_NOT_SUPPORTED: 'CKR_FUNCTION_NOT_SUPPORTED', + CKR_KEY_HANDLE_INVALID: 'CKR_KEY_HANDLE_INVALID', + CKR_KEY_SIZE_RANGE: 'CKR_KEY_SIZE_RANGE', + CKR_KEY_TYPE_INCONSISTENT: 'CKR_KEY_TYPE_INCONSISTENT', + CKR_KEY_NOT_NEEDED: 'CKR_KEY_NOT_NEEDED', + CKR_KEY_CHANGED: 'CKR_KEY_CHANGED', + CKR_KEY_NEEDED: 'CKR_KEY_NEEDED', + CKR_KEY_INDIGESTIBLE: 'CKR_KEY_INDIGESTIBLE', + CKR_KEY_FUNCTION_NOT_PERMITTED: 'CKR_KEY_FUNCTION_NOT_PERMITTED', + CKR_KEY_NOT_WRAPPABLE: 'CKR_KEY_NOT_WRAPPABLE', + CKR_KEY_UNEXTRACTABLE: 'CKR_KEY_UNEXTRACTABLE', + CKR_MECHANISM_INVALID: 'CKR_MECHANISM_INVALID', + CKR_MECHANISM_PARAM_INVALID: 'CKR_MECHANISM_PARAM_INVALID', + CKR_OBJECT_HANDLE_INVALID: 'CKR_OBJECT_HANDLE_INVALID', + CKR_OPERATION_ACTIVE: 'CKR_OPERATION_ACTIVE', + CKR_OPERATION_NOT_INITIALIZED: 'CKR_OPERATION_NOT_INITIALIZED', + CKR_PIN_INCORRECT: 'CKR_PIN_INCORRECT', + CKR_PIN_INVALID: 'CKR_PIN_INVALID', + CKR_PIN_LEN_RANGE: 'CKR_PIN_LEN_RANGE', + CKR_PIN_EXPIRED: 'CKR_PIN_EXPIRED', + CKR_PIN_LOCKED: 'CKR_PIN_LOCKED', + CKR_SESSION_CLOSED: 'CKR_SESSION_CLOSED', + CKR_SESSION_COUNT: 'CKR_SESSION_COUNT', + CKR_SESSION_HANDLE_INVALID: 'CKR_SESSION_HANDLE_INVALID', + CKR_SESSION_PARALLEL_NOT_SUPPORTED: 'CKR_SESSION_PARALLEL_NOT_SUPPORTED', + CKR_SESSION_READ_ONLY: 'CKR_SESSION_READ_ONLY', + CKR_SESSION_EXISTS: 'CKR_SESSION_EXISTS', + CKR_SESSION_READ_ONLY_EXISTS: 'CKR_SESSION_READ_ONLY_EXISTS', + CKR_SESSION_READ_WRITE_SO_EXISTS: 'CKR_SESSION_READ_WRITE_SO_EXISTS', + CKR_SIGNATURE_INVALID: 'CKR_SIGNATURE_INVALID', + CKR_SIGNATURE_LEN_RANGE: 'CKR_SIGNATURE_LEN_RANGE', + CKR_TEMPLATE_INCOMPLETE: 'CKR_TEMPLATE_INCOMPLETE', + CKR_TEMPLATE_INCONSISTENT: 'CKR_TEMPLATE_INCONSISTENT', + CKR_TOKEN_NOT_PRESENT: 'CKR_TOKEN_NOT_PRESENT', + CKR_TOKEN_NOT_RECOGNIZED: 'CKR_TOKEN_NOT_RECOGNIZED', + CKR_TOKEN_WRITE_PROTECTED: 'CKR_TOKEN_WRITE_PROTECTED', + CKR_UNWRAPPING_KEY_HANDLE_INVALID: 'CKR_UNWRAPPING_KEY_HANDLE_INVALID', + CKR_UNWRAPPING_KEY_SIZE_RANGE: 'CKR_UNWRAPPING_KEY_SIZE_RANGE', + CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: 'CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT', + CKR_USER_ALREADY_LOGGED_IN: 'CKR_USER_ALREADY_LOGGED_IN', + CKR_USER_NOT_LOGGED_IN: 'CKR_USER_NOT_LOGGED_IN', + CKR_USER_PIN_NOT_INITIALIZED: 'CKR_USER_PIN_NOT_INITIALIZED', + CKR_USER_TYPE_INVALID: 'CKR_USER_TYPE_INVALID', + CKR_USER_ANOTHER_ALREADY_LOGGED_IN: 'CKR_USER_ANOTHER_ALREADY_LOGGED_IN', + CKR_USER_TOO_MANY_TYPES: 'CKR_USER_TOO_MANY_TYPES', + CKR_WRAPPED_KEY_INVALID: 'CKR_WRAPPED_KEY_INVALID', + CKR_WRAPPED_KEY_LEN_RANGE: 'CKR_WRAPPED_KEY_LEN_RANGE', + CKR_WRAPPING_KEY_HANDLE_INVALID: 'CKR_WRAPPING_KEY_HANDLE_INVALID', + CKR_WRAPPING_KEY_SIZE_RANGE: 'CKR_WRAPPING_KEY_SIZE_RANGE', + CKR_WRAPPING_KEY_TYPE_INCONSISTENT: 'CKR_WRAPPING_KEY_TYPE_INCONSISTENT', + CKR_RANDOM_SEED_NOT_SUPPORTED: 'CKR_RANDOM_SEED_NOT_SUPPORTED', + CKR_RANDOM_NO_RNG: 'CKR_RANDOM_NO_RNG', + CKR_DOMAIN_PARAMS_INVALID: 'CKR_DOMAIN_PARAMS_INVALID', + CKR_BUFFER_TOO_SMALL: 'CKR_BUFFER_TOO_SMALL', + CKR_SAVED_STATE_INVALID: 'CKR_SAVED_STATE_INVALID', + CKR_INFORMATION_SENSITIVE: 'CKR_INFORMATION_SENSITIVE', + CKR_STATE_UNSAVEABLE: 'CKR_STATE_UNSAVEABLE', + CKR_CRYPTOKI_NOT_INITIALIZED: 'CKR_CRYPTOKI_NOT_INITIALIZED', + CKR_CRYPTOKI_ALREADY_INITIALIZED: 'CKR_CRYPTOKI_ALREADY_INITIALIZED', + CKR_MUTEX_BAD: 'CKR_MUTEX_BAD', + CKR_MUTEX_NOT_LOCKED: 'CKR_MUTEX_NOT_LOCKED', + CKR_NEW_PIN_MODE: 'CKR_NEW_PIN_MODE', + CKR_NEXT_OTP: 'CKR_NEXT_OTP', + CKR_FUNCTION_REJECTED: 'CKR_FUNCTION_REJECTED', + CKR_VENDOR_DEFINED: 'CKR_VENDOR_DEFINED', + CKR_INSERTION_CALLBACK_NOT_SUPPORTED: 'CKR_INSERTION_CALLBACK_NOT_SUPPORTED', + CKR_FUNCTION_PARALLEL: 'CKR_FUNCTION_PARALLEL', + CKR_SESSION_EXCLUSIVE_EXISTS: 'CKR_SESSION_EXCLUSIVE_EXISTS', + CKR_RC_ERROR: 'CKR_RC_ERROR', + CKR_CONTAINER_HANDLE_INVALID: 'CKR_CONTAINER_HANDLE_INVALID', + CKR_TOO_MANY_CONTAINERS: 'CKR_TOO_MANY_CONTAINERS', + CKR_USER_LOCKED_OUT: 'CKR_USER_LOCKED_OUT', + CKR_CLONING_PARAMETER_ALREADY_EXISTS: 'CKR_CLONING_PARAMETER_ALREADY_EXISTS', + CKR_CLONING_PARAMETER_MISSING: 'CKR_CLONING_PARAMETER_MISSING', + CKR_CERTIFICATE_DATA_MISSING: 'CKR_CERTIFICATE_DATA_MISSING', + CKR_CERTIFICATE_DATA_INVALID: 'CKR_CERTIFICATE_DATA_INVALID', + CKR_ACCEL_DEVICE_ERROR: 'CKR_ACCEL_DEVICE_ERROR', + CKR_WRAPPING_ERROR: 'CKR_WRAPPING_ERROR', + CKR_UNWRAPPING_ERROR: 'CKR_UNWRAPPING_ERROR', + CKR_MAC_MISSING: 'CKR_MAC_MISSING', + CKR_DAC_POLICY_PID_MISMATCH: 'CKR_DAC_POLICY_PID_MISMATCH', + CKR_DAC_MISSING: 'CKR_DAC_MISSING', + CKR_BAD_DAC: 'CKR_BAD_DAC', + CKR_SSK_MISSING: 'CKR_SSK_MISSING', + CKR_BAD_MAC: 'CKR_BAD_MAC', + CKR_DAK_MISSING: 'CKR_DAK_MISSING', + CKR_BAD_DAK: 'CKR_BAD_DAK', + CKR_SIM_AUTHORIZATION_FAILED: 'CKR_SIM_AUTHORIZATION_FAILED', + CKR_SIM_VERSION_UNSUPPORTED: 'CKR_SIM_VERSION_UNSUPPORTED', + CKR_SIM_CORRUPT_DATA: 'CKR_SIM_CORRUPT_DATA', + CKR_USER_NOT_AUTHORIZED: 'CKR_USER_NOT_AUTHORIZED', + CKR_MAX_OBJECT_COUNT_EXCEEDED: 'CKR_MAX_OBJECT_COUNT_EXCEEDED', + CKR_SO_LOGIN_FAILURE_THRESHOLD: 'CKR_SO_LOGIN_FAILURE_THRESHOLD', + CKR_SIM_AUTHFORM_INVALID: 'CKR_SIM_AUTHFORM_INVALID', + CKR_CITS_DAK_MISSING: 'CKR_CITS_DAK_MISSING', + CKR_UNABLE_TO_CONNECT: 'CKR_UNABLE_TO_CONNECT', + CKR_PARTITION_DISABLED: 'CKR_PARTITION_DISABLED', + CKR_CALLBACK_ERROR: 'CKR_CALLBACK_ERROR', + CKR_SECURITY_PARAMETER_MISSING: 'CKR_SECURITY_PARAMETER_MISSING', + CKR_SP_TIMEOUT: 'CKR_SP_TIMEOUT', + CKR_TIMEOUT: 'CKR_TIMEOUT', + CKR_ECC_UNKNOWN_CURVE: 'CKR_ECC_UNKNOWN_CURVE', + CKR_MTK_ZEROIZED: 'CKR_MTK_ZEROIZED', + CKR_MTK_STATE_INVALID: 'CKR_MTK_STATE_INVALID', + CKR_INVALID_ENTRY_TYPE: 'CKR_INVALID_ENTRY_TYPE', + CKR_MTK_SPLIT_INVALID: 'CKR_MTK_SPLIT_INVALID', + CKR_HSM_STORAGE_FULL: 'CKR_HSM_STORAGE_FULL', + CKR_DEVICE_TIMEOUT: 'CKR_DEVICE_TIMEOUT', + CKR_CONTAINER_OBJECT_STORAGE_FULL: 'CKR_CONTAINER_OBJECT_STORAGE_FULL', + CKR_PED_CLIENT_NOT_RUNNING: 'CKR_PED_CLIENT_NOT_RUNNING', + CKR_PED_UNPLUGGED: 'CKR_PED_UNPLUGGED', + CKR_ECC_POINT_INVALID: 'CKR_ECC_POINT_INVALID', + CKR_OPERATION_NOT_ALLOWED: 'CKR_OPERATION_NOT_ALLOWED', + CKR_LICENSE_CAPACITY_EXCEEDED: 'CKR_LICENSE_CAPACITY_EXCEEDED', + CKR_LOG_FILE_NOT_OPEN: 'CKR_LOG_FILE_NOT_OPEN', + CKR_LOG_FILE_WRITE_ERROR: 'CKR_LOG_FILE_WRITE_ERROR', + CKR_LOG_BAD_FILE_NAME: 'CKR_LOG_BAD_FILE_NAME', + CKR_LOG_FULL: 'CKR_LOG_FULL', + CKR_LOG_NO_KCV: 'CKR_LOG_NO_KCV', + CKR_LOG_BAD_RECORD_HMAC: 'CKR_LOG_BAD_RECORD_HMAC', + CKR_LOG_BAD_TIME: 'CKR_LOG_BAD_TIME', + CKR_LOG_AUDIT_NOT_INITIALIZED: 'CKR_LOG_AUDIT_NOT_INITIALIZED', + CKR_LOG_RESYNC_NEEDED: 'CKR_LOG_RESYNC_NEEDED', + CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS: 'CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', + CKR_AUDIT_LOGIN_FAILURE_THRESHOLD: 'CKR_AUDIT_LOGIN_FAILURE_THRESHOLD', + CKR_INVALID_FUF_TARGET: 'CKR_INVALID_FUF_TARGET', + CKR_INVALID_FUF_HEADER: 'CKR_INVALID_FUF_HEADER', + CKR_INVALID_FUF_VERSION: 'CKR_INVALID_FUF_VERSION', + CKR_ECC_ECC_RESULT_AT_INF: 'CKR_ECC_ECC_RESULT_AT_INF', + CKR_AGAIN: 'CKR_AGAIN', + CKR_TOKEN_COPIED: 'CKR_TOKEN_COPIED', + CKR_SLOT_NOT_EMPTY: 'CKR_SLOT_NOT_EMPTY', + CKR_USER_ALREADY_ACTIVATED: 'CKR_USER_ALREADY_ACTIVATED', + CKR_STC_NO_CONTEXT: 'CKR_STC_NO_CONTEXT', + CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED: 'CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED', + CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED: 'CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED', + CKR_STC_DH_KEYGEN_ERROR: 'CKR_STC_DH_KEYGEN_ERROR', + CKR_STC_CIPHER_SUITE_REJECTED: 'CKR_STC_CIPHER_SUITE_REJECTED', + CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP: 'CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP', + CKR_STC_COMPUTE_DH_KEY_ERROR: 'CKR_STC_COMPUTE_DH_KEY_ERROR', + CKR_STC_FIRST_PHASE_KDF_ERROR: 'CKR_STC_FIRST_PHASE_KDF_ERROR', + CKR_STC_SECOND_PHASE_KDF_ERROR: 'CKR_STC_SECOND_PHASE_KDF_ERROR', + CKR_STC_KEY_CONFIRMATION_FAILED: 'CKR_STC_KEY_CONFIRMATION_FAILED', + CKR_STC_NO_SESSION_KEY: 'CKR_STC_NO_SESSION_KEY', + CKR_STC_RESPONSE_BAD_MAC: 'CKR_STC_RESPONSE_BAD_MAC', + CKR_STC_NOT_ENABLED: 'CKR_STC_NOT_ENABLED', + CKR_STC_CLIENT_HANDLE_INVALID: 'CKR_STC_CLIENT_HANDLE_INVALID', + CKR_STC_SESSION_INVALID: 'CKR_STC_SESSION_INVALID', + CKR_STC_CONTAINER_INVALID: 'CKR_STC_CONTAINER_INVALID', + CKR_STC_SEQUENCE_NUM_INVALID: 'CKR_STC_SEQUENCE_NUM_INVALID', + CKR_STC_NO_CHANNEL: 'CKR_STC_NO_CHANNEL', + CKR_STC_RESPONSE_DECRYPT_ERROR: 'CKR_STC_RESPONSE_DECRYPT_ERROR', + CKR_STC_RESPONSE_REPLAYED: 'CKR_STC_RESPONSE_REPLAYED', + CKR_STC_REKEY_CHANNEL_MISMATCH: 'CKR_STC_REKEY_CHANNEL_MISMATCH', + CKR_STC_RSA_ENCRYPT_ERROR: 'CKR_STC_RSA_ENCRYPT_ERROR', + CKR_STC_RSA_SIGN_ERROR: 'CKR_STC_RSA_SIGN_ERROR', + CKR_STC_RSA_DECRYPT_ERROR: 'CKR_STC_RSA_DECRYPT_ERROR', + CKR_STC_RESPONSE_UNEXPECTED_KEY: 'CKR_STC_RESPONSE_UNEXPECTED_KEY', + CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE: 'CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE', + CKR_STC_UNEXPECTED_DH_DATA_SIZE: 'CKR_STC_UNEXPECTED_DH_DATA_SIZE', + CKR_STC_OPEN_CIPHER_MISMATCH: 'CKR_STC_OPEN_CIPHER_MISMATCH', + CKR_STC_OPEN_DHNIST_PUBKEY_ERROR: 'CKR_STC_OPEN_DHNIST_PUBKEY_ERROR', + CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL: 'CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL', + CKR_STC_OPEN_RESP_GEN_FAIL: 'CKR_STC_OPEN_RESP_GEN_FAIL', + CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL: 'CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL', + CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL: 'CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL', + CKR_STC_ACTIVATE_RESP_GEN_FAIL: 'CKR_STC_ACTIVATE_RESP_GEN_FAIL', + CKR_CHALLENGE_INCORRECT: 'CKR_CHALLENGE_INCORRECT', + CKR_ACCESS_ID_INVALID: 'CKR_ACCESS_ID_INVALID', + CKR_ACCESS_ID_ALREADY_EXISTS: 'CKR_ACCESS_ID_ALREADY_EXISTS', + CKR_OBJECT_READ_ONLY: 'CKR_OBJECT_READ_ONLY', + CKR_KEY_NOT_ACTIVE: 'CKR_KEY_NOT_ACTIVE' +} diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 1e90006..821cf5e 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -1,94 +1,110 @@ """ Methods responsible for managing a user's session and login/c_logout """ +from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ + byref, pointer +import logging +import re + from cryptoki import C_Initialize, CK_ULONG, C_GetSlotList, CK_BBOOL, CK_SLOT_ID, \ CK_SLOT_INFO, C_GetSlotInfo, C_CloseAllSessions, C_GetSessionInfo, CK_SESSION_HANDLE, \ CK_SESSION_INFO, C_OpenSession, CK_FLAGS, CK_NOTIFY, C_Login, CK_USER_TYPE, C_Logout, \ C_CloseSession, C_InitPIN, CA_FactoryReset, \ C_GetTokenInfo, CK_TOKEN_INFO, C_Finalize, C_SetPIN, CA_DeleteContainerWithHandle, CA_OpenApplicationID, \ CA_CloseApplicationID, CA_Restart, CA_SetApplicationID -from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ - byref, pointer from defines import CKR_OK from pycryptoki.cryptoki import CA_CreateContainer, CK_VOID_PTR, \ CK_BYTE_PTR from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION from pycryptoki.test_functions import make_error_handle_function -import logging -import re logger = logging.getLogger(__name__) def c_initialize(): - ''' - Calls C_Initialize to c_initialize the board + """Calls C_Initialize to c_initialize the board + - @return: The result code - ''' + :returns: The result code + + """ # INITIALIZE logger.info("C_Initialize: Initializing HSM") ret = C_Initialize(0) - return ret; + return ret + + c_initialize_ex = make_error_handle_function(c_initialize) def c_finalize(): - ''' - Calls C_Finalize + """Calls C_Finalize + - @return: The result code - ''' + :returns: The result code + + """ logger.info("C_Finalize: Finalizing HSM") ret = C_Finalize(0) - return ret; + return ret + + c_finalize_ex = make_error_handle_function(c_finalize) + def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): - ''' - Opens a session on a given slot - - @param slot_num: The slot to get a session on - @param flags: The flags to open the session with - @return: The result code, the session handle - ''' - #OPEN SESSION + """Opens a session on a given slot + + :param slot_num: The slot to get a session on + :param flags: The flags to open the session with (Default value = (CKF_SERIAL_SESSION | CKF_RW_SESSION) + :returns: The result code, the session handle + + """ + # OPEN SESSION arg3 = create_string_buffer("Application") h_session = CK_SESSION_HANDLE() - arg3 = cast(arg3, c_void_p) #CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) - ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), pointer(h_session)) + arg3 = cast(arg3, c_void_p) # CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) + ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), + pointer(h_session)) logger.info("C_OpenSession: Opening Session. slot=" + str(slot_num)) return ret, h_session.value + + c_open_session_ex = make_error_handle_function(c_open_session) + def login(h_session, slot_num=1, password="userpin", user_type=1): - ''' - Login to the HSM - @param h_session: Current session - @param slot_num: Slot index to login on - @param password: Password to login with - @param user_type: User type to login as - - @return: The result code - ''' + """Login to the HSM + + :param h_session: Current session + :param slot_num: Slot index to login on (Default value = 1) + :param password: Password to login with (Default value = "userpin") + :param user_type: User type to login as (Default value = 1) + :returns: The result code + + """ # LOGIN user_type = long(user_type) pb_password = c_char_p(password) - logger.info("C_Login: Logging In. user_type=" + str(user_type) + ", slot=" + str(slot_num) + ", password=" + password) + logger.info( + "C_Login: Logging In. user_type=" + str(user_type) + ", slot=" + str(slot_num) + ", password=" + password) ret = C_Login(h_session, CK_USER_TYPE(user_type), cast(pb_password, CK_BYTE_PTR), CK_ULONG(len(password))) - return ret; + return ret + + login_ex = make_error_handle_function(login) + def get_slot_info(description): - ''' - Returns a slot with a certain descriptor + """Returns a slot with a certain descriptor Limitation: Only returns the first slot it finds that fits the description - @param description: The name of the slot to find - @return: THe result code, a Python dictionary representing the slots - ''' + :param description: The name of the slot to find + :returns: THe result code, a Python dictionary representing the slots + + """ ret, slot_dict = get_slot_dict() return_dict = {} @@ -98,39 +114,46 @@ def get_slot_info(description): return_dict[key] = slot_dict[key] return ret, return_dict + + get_slot_info_ex = make_error_handle_function(get_slot_info) + def c_get_session_info(session): - ''' - :param session: - :return: - ''' + """ + + :param session: return: + + """ session_info = {} c_session_info = CK_SESSION_INFO() ret = C_GetSessionInfo(CK_SESSION_HANDLE(session), byref(c_session_info)) - if (ret == CKR_OK): + if ret == CKR_OK: session_info['state'] = c_session_info.state session_info['flags'] = c_session_info.flags session_info['slotID'] = c_session_info.slotID session_info['usDeviceError'] = c_session_info.usDeviceError return ret, session_info + + c_get_session_info_ex = make_error_handle_function(c_get_session_info) + def c_get_token_info(slot_id): - ''' - Gets the token info for a given slot id - @param slot_id: Slot index to get the token info for + """Gets the token info for a given slot id - @return: The result code, A python dictionary representing the token info - ''' + :param slot_id: Slot index to get the token info for + :returns: The result code, A python dictionary representing the token info + + """ token_info = {} c_token_info = CK_TOKEN_INFO() logger.info("Getting token info. slot=" + str(slot_id)) ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) - if (ret == CKR_OK): + if ret == CKR_OK: token_info['label'] = str(cast(c_token_info.label, c_char_p).value)[0:32].strip() token_info['manufacturerID'] = str(cast(c_token_info.manufacturerID, c_char_p).value)[0:32].strip() token_info['model'] = str(cast(c_token_info.model, c_char_p).value)[0:16].strip() @@ -151,14 +174,18 @@ def c_get_token_info(slot_id): token_info['utcTime'] = str(cast(c_token_info.utcTime, c_char_p).value)[0:16].strip() return ret, token_info + + c_get_token_info_ex = make_error_handle_function(c_get_token_info) + def get_slot_dict(): - ''' - Compiles a dictionary of the available slots + """Compiles a dictionary of the available slots + - @return: A python dictionary of the available slots - ''' + :returns: A python dictionary of the available slots + + """ us_count = CK_ULONG(0) ret = C_GetSlotList(CK_BBOOL(0), None, byref(us_count)) if ret != CKR_OK: return ret @@ -174,41 +201,50 @@ def get_slot_dict(): slot_dict[slot] = slot_description return ret, slot_dict + + get_slot_dict_ex = make_error_handle_function(get_slot_dict) + def c_close_session(h_session): - ''' - Closes a session - @param h_session: The session to close + """Closes a session + + :param h_session: The session to close + :returns: The result code - @return: The result code - ''' + """ # CLOSE SESSION logger.info("C_CloseSession: Closing session " + str(h_session)) ret = C_CloseSession(h_session) return ret + + c_close_session_ex = make_error_handle_function(c_close_session) + def c_logout(h_session): - ''' - Logs out of a given session - @param h_session: The session to log out from + """Logs out of a given session + + :param h_session: The session to log out from + :returns: The result code - @return: The result code - ''' + """ logger.info("C_Logout: Logging out of session " + str(h_session)) ret = C_Logout(h_session) return ret + + c_logout_ex = make_error_handle_function(c_logout) + def c_init_pin(h_session, pin): - ''' - Initializes the PIN - @param h_session: Current session - @param pin: pin to c_initialize + """Initializes the PIN - @return: THe result code - ''' + :param h_session: Current session + :param pin: pin to c_initialize + :returns: THe result code + + """ logger.info("C_InitPIN: Initializing PIN to " + str(pin)) if pin == '': @@ -216,29 +252,35 @@ def c_init_pin(h_session, pin): else: ret = C_InitPIN(h_session, cast(create_string_buffer(pin), CK_BYTE_PTR), CK_ULONG(len(pin))) return ret + + c_init_pin_ex = make_error_handle_function(c_init_pin) + def ca_factory_reset(slot): - ''' - Does a factory reset on a given slot - @param slot: The slot to do a factory reset on + """Does a factory reset on a given slot + + :param slot: The slot to do a factory reset on + :returns: The result code - @return: The result code - ''' + """ logger.info("CA_FactoryReset: Factory Reset. slot=" + str(slot)) ret = CA_FactoryReset(CK_SLOT_ID(slot), CK_ULONG(0)) return ret + + ca_factory_reset_ex = make_error_handle_function(ca_factory_reset) + def c_set_pin(h_session, old_pass, new_pass): - ''' - Allows a user to change their PIN - @param h_session: Session of the user - @param old_pass: The user's old password - @param new_pass: The user's desired new password - - @return: The result code - ''' + """Allows a user to change their PIN + + :param h_session: Session of the user + :param old_pass: The user's old password + :param new_pass: The user's desired new password + :returns: The result code + + """ logger.info("C_SetPIN: Changing password. old_pass=" + str(old_pass) + ", new_pass=" + str(new_pass)) if old_pass == '' and new_pass == '': ret = C_SetPIN(h_session, None, CK_ULONG(0), @@ -248,61 +290,92 @@ def c_set_pin(h_session, old_pass, new_pass): ret = C_SetPIN(h_session, cast(create_string_buffer(old_pass), CK_BYTE_PTR), CK_ULONG(len(old_pass)), cast(create_string_buffer(new_pass), CK_BYTE_PTR), CK_ULONG(len(new_pass))) return ret + + c_set_pin_ex = make_error_handle_function(c_set_pin) + def c_close_all_sessions(slot): - ''' - Closes all the sessions on a given slot - @param slot: The slot to close all sessions on + """Closes all the sessions on a given slot - @return The result code - ''' + :param slot: The slot to close all sessions on + :returns: The result code + + """ logger.info("C_CloseAllSessions: Closing all sessions. slot=" + str(slot)) ret = C_CloseAllSessions(CK_ULONG(slot)) return ret + + c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) + def ca_create_container(h_session, storage_size, password='userpin', label='Inserted Token'): - ''' - Inserts a token into a slot without a Security Officer on the token - @param h_session: Current session - @param storage_size: The storage size of the token (0 for undefined/unlimited) - @param password: The password associated with the token - @param label: The label associated with the token + """Inserts a token into a slot without a Security Officer on the token - @return: The result code, The container number - ''' + :param h_session: Current session + :param storage_size: The storage size of the token (0 for undefined/unlimited) + :param password: The password associated with the token (Default value = 'userpin') + :param label: The label associated with the token (Default value = 'Inserted Token') + :returns: The result code, The container number + + """ if password == '': container_number = CK_ULONG() - logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) - ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), None, - CK_ULONG(0), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) + logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( + storage_size) + ", pin=" + password + ", label=" + label) + ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), + CK_ULONG(len(label)), None, + CK_ULONG(0), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), + CK_ULONG(storage_size), byref(container_number)) logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) return ret, container_number.value else: container_number = CK_ULONG() - logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str(storage_size) + ", pin=" + password + ", label=" + label) - ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), CK_ULONG(len(label)), cast(create_string_buffer(password), CK_BYTE_PTR), - CK_ULONG(len(password)), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(container_number)) + logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( + storage_size) + ", pin=" + password + ", label=" + label) + ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), + CK_ULONG(len(label)), cast(create_string_buffer(password), CK_BYTE_PTR), + CK_ULONG(len(password)), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), + CK_ULONG(storage_size), byref(container_number)) logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) return ret, container_number.value + + ca_create_container_ex = make_error_handle_function(ca_create_container) + def ca_delete_container_with_handle(h_session, container_handle): + """ + + :param h_session: + :param container_handle: + + """ container_number = CK_ULONG(container_handle) - logger.info("CA_DeleteContainerWithHandle: Attempting to delete container with handle: {0}".format(container_handle)) + logger.info( + "CA_DeleteContainerWithHandle: Attempting to delete container with handle: {0}".format(container_handle)) ret = CA_DeleteContainerWithHandle(h_session, container_number) logger.info("CA_DeleteContainerWithHandle: Ret Value: {0}".format(ret)) return ret + + ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) def ca_openapplicationID(slot, id_high, id_low): + """ + + :param slot: + :param id_high: + :param id_low: + + """ uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) @@ -313,10 +386,19 @@ def ca_openapplicationID(slot, id_high, id_low): logger.info("CA_OpenApplicationID: Ret Value: {0}".format(ret)) return ret -ca_openapplicationID_ex= make_error_handle_function(ca_openapplicationID) + + +ca_openapplicationID_ex = make_error_handle_function(ca_openapplicationID) def ca_closeapplicationID(slot, id_high, id_low): + """ + + :param slot: + :param id_high: + :param id_low: + + """ uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) @@ -327,12 +409,17 @@ def ca_closeapplicationID(slot, id_high, id_low): logger.info("CA_CloseApplicationID: Ret Value: {0}".format(ret)) return ret -ca_closeapplicationID_ex= make_error_handle_function(ca_closeapplicationID) + + +ca_closeapplicationID_ex = make_error_handle_function(ca_closeapplicationID) def ca_setapplicationID(id_high, id_low): - """ - Set the App ID for the current application. + """Set the App ID for the current application. + + :param id_high: + :param id_low: + """ uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) @@ -344,10 +431,17 @@ def ca_setapplicationID(id_high, id_low): logger.info("CA_SetApplicationID: Ret Value: {0}".format(ret)) return ret -ca_setapplicationID_ex= make_error_handle_function(ca_setapplicationID) + + +ca_setapplicationID_ex = make_error_handle_function(ca_setapplicationID) def ca_restart(slot): + """ + + :param slot: + + """ logger.info("CA_Restart: attempting to restart") ret = CA_Restart(CK_ULONG(slot)) @@ -355,4 +449,6 @@ def ca_restart(slot): logger.info("CA_Restart: Ret Value: {0}".format(ret)) return ret + + ca_restart_ex = make_error_handle_function(ca_restart) diff --git a/pycryptoki/setup/distribute.py b/pycryptoki/setup/distribute.py index cecaf49..1c2f914 100755 --- a/pycryptoki/setup/distribute.py +++ b/pycryptoki/setup/distribute.py @@ -20,7 +20,7 @@ #Create all of the necessary automatically generated source xml_output = 'h2xmlout_tmp.xml' -if not (options['dll'] == None): +if not (options['dll'] is None): dll_path = options['dll'] else: if "linux" in sys.platform: @@ -34,4 +34,4 @@ print " Packaging Source Distribution" print "-------------------------------------------------------" os.chdir("../../") -os.system('python setup.py sdist') \ No newline at end of file +os.system('python setup.py sdist') diff --git a/pycryptoki/setup/initialize.py b/pycryptoki/setup/initialize.py index e0d175f..4ba3628 100755 --- a/pycryptoki/setup/initialize.py +++ b/pycryptoki/setup/initialize.py @@ -1,17 +1,19 @@ """ Setup script that will automatically generate the cryptoki.py and defines.py files. This will get your library from your LUNA_LIBRARY environment variable and generate these -files. These files contains the defines that are in the C code and in addition contain the +files. These files contains the defines that are in the C code and in addition contain the CTypes formatted structs contained in the C code. -Cryptoki.py contains the CTypes templates for the C Structs that are in the cryptoki C code. +Cryptoki.py contains the CTypes templates for the C Structs that are in the cryptoki C code. Defines.py is a crude wrapper around a number of header files that uses a bad regular expression to harvest the defines. -Download gccxml from CVS (note: CVS seems to be blocked on the CVS network, you can get this from smb://172.20.11.83/ftp/forMike) +Download gccxml from CVS (note: CVS seems to be blocked on the CVS network, + you can get this from smb://172.20.11.83/ftp/forMike) Compile gccxml 1) Recursively run dos2unix on gccxml source tree (find . -name *.* -exec dos2unix {} \;) -2) Create a folder in the same directory as gccxml is in called gccxml-build (ex /home/mhughes/gccxml and /home/mhughes/gccxml-build) +2) Create a folder in the same directory as gccxml is + in called gccxml-build (ex /home/mhughes/gccxml and /home/mhughes/gccxml-build) 3) cd gccxml-build 4) cmake ../gccxml -DCMAKE_INSTALL_PREFIX:PATH=/home/mhughes/gccxml-build 5) make @@ -51,75 +53,75 @@ def is_nextgen_check(library_path): return os.path.exists(ctlib_path) def initialize(library_path=None, dll_path=None): - ''' - Creates the cryptoki.py, defines.py and return_values.py files. + """ + Creates the cryptoki.py, defines.py and return_values.py files. :param library_path: The path to the MKS Components sandbox - ''' + """ xml_output = 'h2xmlout_tmp.xml' - + library_path = parse_library(library_path, xml_output) cryptoki_dll_path = dll_path convert_to_python_binding(cryptoki_dll_path, xml_output, cryptoki_filename) print "Finished!" - + def change_cryptoki_dll_path(new_dll_path): if not os.path.exists(cryptoki_filename): raise Exception("Error... cryptoki.py not found.") - + print "Removing references to DLL in cryptoki.py to achieve late binding to DLL" - + #Read in the current file cryptoki_file = open(cryptoki_filename, "r") file_contents = cryptoki_file.read() cryptoki_file.close() - + #Create a backup try: os.remove(cryptoki_filename + ".bak") except: #Don't care this was only removing the old backup if one existed pass - + print "Creating backup: cryptoki.py.bak" os.rename(cryptoki_filename, cryptoki_filename + ".bak") - + #Find the previous path print re.findall("CDLL\((.*)\)", file_contents)[0] current_path = re.findall("CDLL\((.*)\)", file_contents)[0] - + if "win" in platform.system(): current_path = current_path.replace("\\", '~').replace('~', '\\\\\\\\') - - new_contents = file_contents.replace(current_path, new_dll_path) - + + new_contents = file_contents.replace(current_path, new_dll_path) + #Remove all references to DLL to load it later new_contents = re.sub("_libraries\s*=\s*{}\s*", "", new_contents) new_contents = re.sub("_libraries\[DLL_PATH\]\s*=\s*CDLL\(DLL_PATH\)\s*", "", new_contents) - + #Windows needs to have _pack_ = 1 for every single struct, has to be declared before _fields_ is set struct_names = re.findall("(\S+)\._fields_\s=\s", new_contents) fields = re.compile("\S+\._fields_\s=\s[^\]]*]", re.MULTILINE | re.DOTALL) field_declaration = re.findall(fields, new_contents) - + assert len(field_declaration) == len(struct_names) for i in range(0, len(field_declaration)): add_pack_string = "if 'win' in sys.platform:\n " + struct_names[i] + "._pack_ = 1\n" + field_declaration[i] - + new_contents = new_contents.replace(field_declaration[i], add_pack_string) - + with open(cryptoki_filename, 'w') as new_file: new_file.write(new_contents) - + def change_cryptoki_dll_binding(): - + print "Replacing ctypes cryptoki function definitions, in " + cryptoki_filename + ", with factory functions for later binding to the DLL" - + #Read in the current file cryptoki_file = open(cryptoki_filename, "r") file_contents = cryptoki_file.read() cryptoki_file.close() - + #Find all of the lines declaring functions on the DLL found = re.findall("_libraries\[DLL_PATH\]\.(\S*)", file_contents) @@ -127,7 +129,7 @@ def change_cryptoki_dll_binding(): new_contents = file_contents for function_name in found: new_contents = re.sub("_libraries\[DLL_PATH\]\." + function_name + "\s", "make_late_binding_function('" + function_name + "')\n", new_contents) - + #Write the final contents out with open(cryptoki_filename, 'w') as new_file: new_file.write(new_contents) @@ -136,10 +138,10 @@ def parse_library(library_path, xml_output): defines_filename = os.path.join("..", "defines.py") return_vals_filename = os.path.join("..", "return_values.py") - if library_path == None: + if library_path is None: if not os.environ.has_key('LUNA_LIBRARY'): raise Exception("LUNA_LIBRARY environment variable is not set, it needs to be set to the path of your luna source code.") - + library_path = os.environ['LUNA_LIBRARY'] print "Using LUNA_LIBRARY Environment variable as location of Luna's Library: " + library_path else: @@ -151,9 +153,9 @@ def parse_library(library_path, xml_output): if os.path.exists(os.path.join(library_path, 'CoreLibrary', 'ctToken_lib', 'source')): if os.path.exists(os.path.join(library_path, 'interfaces', 'include', 'cryptoki', 'sfnt_ext_list_members.h')): raise Exception("Error: sfnt_ext_list_members.h not found. You need to compile the Components library before being able to generate the Python to C Ctypes binding.") - + _parse_headers(xml_output, library_path) - + #Add all of the header files that you would like the script to parse, #it should be noted that the script just does simple regular expression matching #and is very simple and could break on previously unencountered syntaxes. It is @@ -161,7 +163,7 @@ def parse_library(library_path, xml_output): token_path = os.path.join("tools", "ekmtest", "token.h") if os.path.exists(os.path.join(library_path, token_path)): header_files.append(token_path) - + #if it has this library it is next gen if is_nextgen_check(library_path): header_files.append(os.path.join("interfaces", "Include", "RSA", "pkcs11t.h")) @@ -173,39 +175,39 @@ def parse_library(library_path, xml_output): _get_defines(library_path, defines_filename, header_files) _output_return_values(return_vals_filename, ret_list) return library_path - + def _parse_headers(xml_output, library_path=None): - ''' + """ Using h2xml this function parses the cryptoki header file and generates xml output which describes the library :param xml_output:The filename to output the xml to :param library_path:The path to the root of the cryptoki library - ''' - + """ + print "Parsing luna source with GCC-XML to generate XML representation of C source" - + if os.path.exists(xml_output): os.remove(xml_output) - + #Create a file to pull everything in temp_include_filename = 'master_header_file.h' if os.path.exists(temp_include_filename): os.remove(temp_include_filename) - + ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') is_nextgen = is_nextgen_check(library_path) - - master_include_file = open(temp_include_filename, 'w'); + + master_include_file = open(temp_include_filename, 'w') if is_nextgen: master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'pkcs11Utils', 'Utils.h"') + '\n') else: master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source', 'Utils.h"') + '\n') master_include_file.write('#include "cryptoki.h"\n') master_include_file.close() - + args = ['h2xml.py', os.path.join(os.getcwd(), temp_include_filename), '-o', xml_output, - '-I', os.path.join(library_path, 'interfaces', 'Include'), - '-I', os.path.join(library_path, 'interfaces', 'Include', 'cryptoki'), + '-I', os.path.join(library_path, 'interfaces', 'Include'), + '-I', os.path.join(library_path, 'interfaces', 'Include', 'cryptoki'), '-I', os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source')] if is_nextgen: @@ -213,7 +215,7 @@ def _parse_headers(xml_output, library_path=None): args.append(ctlib_path) args.append('-I') args.append(os.path.join(library_path, 'CoreLibrary', 'util_vob', 'Include')) - + if "linux" in sys.platform: print "Detected linux OS" args.append('-D') @@ -221,81 +223,81 @@ def _parse_headers(xml_output, library_path=None): else: #Your operating system probably just needs to be added, might not need any special parameters raise Exception("Error: Could not generate python to c ctypes library. Unsupported Operating System, a build on linux should work everywhere so just use it.") - - if (which("gccxml") == None and which("gccxml.exe") == None): + + if which("gccxml") is None and which("gccxml.exe") is None: raise Exception("No gccxml executable found in path.") - + h2xml.compile_to_xml(args) - + if os.path.exists(temp_include_filename): os.remove(temp_include_filename) def convert_to_python_binding(cryptoki_dll_path, temp_file, output_filename): - ''' + """ Using xml2py.py in ctypeslib this function generates the python file based upon the xml output of h2xml. This python file is the binding between python and C. :param cryptoki_dll_path: The path to libCryptoki.so :param temp_file: The xml output of h2xml.py :param output_filename: The filename to output the binding to - ''' + """ print "Parsing GCC-XML output to generate python code for binding to C, writing to " + output_filename - + if os.path.exists(output_filename): os.chmod(output_filename, stat.S_IWRITE) os.remove(output_filename) - + args = ['xml2py.py', temp_file, '-l', cryptoki_dll_path, '-o', output_filename] xml2py.main(args) - + change_cryptoki_dll_path(dll_path_var_name) initial_function = '\nfrom pycryptoki.cryptoki_helpers import make_late_binding_function\nimport sys\n' - + change_cryptoki_dll_binding() - + _prepend_to_file(output_filename, initial_function) - + comment = "This file contains all of the ctypes definitions for the cryptoki library.\n" - comment = comment + "The ctypes definitions outline the structures for the cryptoki C API.\n" + comment += "The ctypes definitions outline the structures for the cryptoki C API.\n" _prepend_auto_file_warning(output_filename, comment) - + def _store_defines(head_filename, output_filename): - ''' - Converts all of the simple defines (defines to numbers) in a c header file to a + """ + Converts all of the simple defines (defines to numbers) in a c header file to a variable declaration in python and appends these declarations to an output file. - + This is a really hackish way of getting the defines which actually hard codes out defines that are formatted wrong and cause errors. Done this way to get it done real quick and imports 99% of what is needed. - + :param head_filename: The filename of the header to get the defines from :param output_filename: The .py file to append the python style defines in - ''' + """ print "Getting defines from: " + str(head_filename) - + #Read in file head_file = open(head_filename, "r") - text = head_file.read(); - + text = head_file.read() + #Find all the simple defines (defines to numbers) regex_list = re.findall(r"#define[ \t\r\f\v]+([A-Z]+[A-Za-z_0-9]+[ \t\r\f\v]+[^~\n]*)[\n]", text) #regex_list = re.findall(r"#define[ \t\r\f\v]([\S]+[ \t\r\f\v]*[0-9]+[0-9A-Za-z]*)[\n]", text) - + #Put an equals sign in them so they are properly formatted and append them to the file out_file = open(output_filename, "a") out_file.write("'''" + head_filename + "'''\n") - + for entry in regex_list: - if not (entry.find("CK_POINTER") > -1 or entry.find("CK_PTR") > -1 + if not (entry.find("CK_POINTER") > -1 or entry.find("CK_PTR") > -1 or entry.find("CK_ENTRY") > -1 or entry.find("C_VERSION") > -1 - or entry.find("LUNA_PARTITION_HDR_HMAC_SIZE") > -1 + or entry.find("LUNA_PARTITION_HDR_HMAC_SIZE") > -1 or entry.find("FW_VERSION_CONF_ROLES") > -1): #XXX This is to account for function calls, should be accounted for in the regex above entry = entry.replace('\t', ' ') #clean up tabs entry = entry.replace(' ', '=', 1) entry = entry.replace('//', '#') entry = entry.replace('/*', '#') out_file.write(entry + "\n") - + dict_entry = entry.split('=') if 'CKR' in dict_entry[0][0:3]: ret_list.append(dict_entry[0]) @@ -303,25 +305,25 @@ def _store_defines(head_filename, output_filename): #Cleanup out_file.close() head_file.close() - + def _output_return_values(output_filename, ret_list): - ''' + """ Creates a file which contains a dictionary for looking up the String values of the various defines in cryptoki. - + :param output_filename: The filename to output the dictionary to :param ret_list: The list of return values generated when getting the defines - ''' - + """ + print "Creating dictionary of return value strings by scraping Luna's source, writing to: " + output_filename - + if os.path.exists(output_filename): os.remove(output_filename) - + ret_vals_file = open(output_filename, "a") ret_vals_file.write("from defines import *\n\n") - + ret_vals_file.write("ret_vals_dictionary = { \n") for entry in ret_list: ret_vals_file.write("\t" + entry + " : '" + entry + "'") @@ -330,52 +332,52 @@ def _output_return_values(output_filename, ret_list): ret_vals_file.write('\n') ret_vals_file.write("}") ret_vals_file.close() - + comment = "This file contains a dictionary lookup for the readable string values\n" - comment = comment + "of defines whose variable name starts with CKR_. This convention means they are\n" - comment = comment + "a return value for the cryptoki C API.\n\n" + comment += "of defines whose variable name starts with CKR_. This convention means they are\n" + comment += "a return value for the cryptoki C API.\n\n" _prepend_auto_file_warning(output_filename, comment) - + def _get_defines(path_to_library, out_filename, header_files): - ''' + """ Gets all of the defines in a set of c files specified in the header_files variable as a list of strings. That list is relative to the path_to_library variable. Everything is stored in out_filename in python format. :param path_to_library: The path to the MKS Components sandbox :param out_filename: The .py filename to save the python style defines to :param header_files: The header files to harvest the defines from - ''' - + """ + print "Scraping Luna's source to convert C defines to python, writing to: " + str(out_filename) - if (os.path.exists(out_filename)): + if os.path.exists(out_filename): os.remove(out_filename) - + for header_file in header_files: head_filename = os.path.join(path_to_library, header_file) _store_defines(head_filename=head_filename, output_filename=out_filename) - + comment = "This file contains defines which have been automatically scraped from the\n" - comment = comment + "cryptoki API header files. The defines are stored as variables in python.\n" - comment = comment + "If you add any new defines you can rerun initialize.py to regenerate this file.\n" - comment = comment + "If you need to scrape another header file add the desired file to the header_files\n" - comment = comment + "array in initialize.py and rerun initialize.py.\n" + comment += "cryptoki API header files. The defines are stored as variables in python.\n" + comment += "If you add any new defines you can rerun initialize.py to regenerate this file.\n" + comment += "If you need to scrape another header file add the desired file to the header_files\n" + comment += "array in initialize.py and rerun initialize.py.\n" _prepend_auto_file_warning(out_filename, comment) - + def _prepend_auto_file_warning(filename, comment): beginning_comment = "'''\n" - beginning_comment = beginning_comment + "THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE\n" - beginning_comment = beginning_comment + "This file should NOT be checked into MKS or modified in any way, this file was\n" - beginning_comment = beginning_comment + "created by setup/initialize.py. Any changes to this file will be wiped out when\n" - beginning_comment = beginning_comment + "it is regenerated.\n\n" + beginning_comment += "THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE\n" + beginning_comment += "This file should NOT be checked into MKS or modified in any way, this file was\n" + beginning_comment += "created by setup/initialize.py. Any changes to this file will be wiped out when\n" + beginning_comment += "it is regenerated.\n\n" beginning_comment = beginning_comment + comment - beginning_comment = beginning_comment + "'''\n\n" - + beginning_comment += "'''\n\n" + _prepend_to_file(filename, beginning_comment) - + def _prepend_to_file(filename, text_to_prepend): with file(filename, 'r') as original: data = original.read() with file(filename, 'w') as modified: modified.write(text_to_prepend + data) - + def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) diff --git a/pycryptoki/setup/make_and_install.py b/pycryptoki/setup/make_and_install.py index d5ce7aa..d548c35 100755 --- a/pycryptoki/setup/make_and_install.py +++ b/pycryptoki/setup/make_and_install.py @@ -1,7 +1,7 @@ -''' +""" Script used to automatically generate python code bindings to the cryptoki library and install the pycryptoki module in the system. -''' +""" import argparse from pycryptoki.setup.initialize import initialize import os @@ -26,4 +26,4 @@ os.chdir(os.path.join("..", "..")) os.system('sudo python setup.py install') else: - raise Exception("Unsupported operating system, you'll have to add support for it.") \ No newline at end of file + raise Exception("Unsupported operating system, you'll have to add support for it.") diff --git a/pycryptoki/setup/verify_version.py b/pycryptoki/setup/verify_version.py index 29d30aa..8c72a34 100755 --- a/pycryptoki/setup/verify_version.py +++ b/pycryptoki/setup/verify_version.py @@ -1,28 +1,29 @@ -''' +""" This function just goes through and imports every file and reports back which files have errors in them for the purpose of compatibility between python versions. -''' +""" import os, os.path def verify_import(): + """ """ failed_files = "" for root, dirs, files in os.walk("../."): for f in files: fullpath = os.path.join(root, f) - if (fullpath.endswith("py")): + if fullpath.endswith("py"): split_path = fullpath.split('/') folder_names = "" verify = True - if (len(split_path) > 3): - + if len(split_path) > 3: + for folder in split_path[2:len(split_path) - 1]: if folder == "setup": verify = False folder_names = folder_names + str(folder) + "." if verify: print fullpath - cmd = "from pycryptoki." + folder_names + str(f).split(".")[0] + " import *" + cmd = "from pycryptoki." + folder_names + str(f).split(".")[0] + " import *" print "\t" + cmd try: exec cmd @@ -33,4 +34,4 @@ def verify_import(): print "\n------SUMMARY------" print "Failed:\n\t" + failed_files if __name__ == '__main__': - verify_import() \ No newline at end of file + verify_import() diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index d9db118..c67db80 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -1,6 +1,8 @@ +from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p +import logging + from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign -from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ @@ -12,28 +14,30 @@ from pycryptoki.encryption import _get_string_from_list, \ get_c_data_to_sign_or_encrypt from pycryptoki.test_functions import make_error_handle_function -import logging logger = logging.getLogger(__name__) + def get_mechanism_for_sigver(flavour): - """ - Tries to build a default mechanism if none is provided, + """Tries to build a default mechanism if none is provided, most mechanisms just need the .pParameter field to be null. If they don't the mechanism can be instantiated here. + + :param flavour: + """ mech = CK_MECHANISM() mech.mechanism = CK_MECHANISM_TYPE(flavour) - + default_salt_len = 8 if flavour == CKM_RSA_PKCS_PSS or \ - flavour == CKM_SHA1_RSA_PKCS_PSS: - + flavour == CKM_SHA1_RSA_PKCS_PSS: + p = CK_RSA_PKCS_PSS_PARAMS() p.hashAlg = CK_ULONG(CKM_SHA_1) p.mgf = CK_ULONG(CKG_MGF1_SHA1) p.usSaltLen = CK_ULONG(default_salt_len) - + mech.pParameter = cast(pointer(p), c_void_p) mech.usParameterLen = CK_ULONG(sizeof(p)) elif flavour == CKM_SHA224_RSA_PKCS_PSS: @@ -41,7 +45,7 @@ def get_mechanism_for_sigver(flavour): p.hashAlg = CK_ULONG(CKM_SHA224) p.mgf = CK_ULONG(CKG_MGF1_SHA224) p.usSaltLen = CK_ULONG(default_salt_len) - + mech.pParameter = cast(pointer(p), c_void_p) mech.usParameterLen = CK_ULONG(sizeof(p)) elif flavour == CKM_SHA256_RSA_PKCS_PSS: @@ -49,7 +53,7 @@ def get_mechanism_for_sigver(flavour): p.hashAlg = CK_ULONG(CKM_SHA256) p.mgf = CK_ULONG(CKG_MGF1_SHA256) p.usSaltLen = CK_ULONG(default_salt_len) - + mech.pParameter = cast(pointer(p), c_void_p) mech.usParameterLen = CK_ULONG(sizeof(p)) elif flavour == CKM_SHA384_RSA_PKCS_PSS: @@ -57,15 +61,15 @@ def get_mechanism_for_sigver(flavour): p.hashAlg = CK_ULONG(CKM_SHA384) p.mgf = CK_ULONG(CKG_MGF1_SHA384) p.usSaltLen = CK_ULONG(default_salt_len) - + mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) + mech.usParameterLen = CK_ULONG(sizeof(p)) elif flavour == CKM_SHA512_RSA_PKCS_PSS: p = CK_RSA_PKCS_PSS_PARAMS() p.hashAlg = CK_ULONG(CKM_SHA512) p.mgf = CK_ULONG(CKG_MGF1_SHA512) p.usSaltLen = CK_ULONG(default_salt_len) - + mech.pParameter = cast(pointer(p), c_void_p) mech.usParameterLen = CK_ULONG(sizeof(p)) else: @@ -73,177 +77,185 @@ def get_mechanism_for_sigver(flavour): mech.usParameterLen = CK_ULONG(0) return mech -def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech = None): - ''' - Performs a C_SignInit and C_Sign operation on some data - - @param h_session: The current session - @param sign_flavor: The flavour of signing to do - @param data_to_sign: The data to sign, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param h_key: The key to sign the data with - @param mech: The mechanism to use, if None a blank mechanism will be created based on the sign_flavor - - @return The result code, A python string represeting the signature - ''' - - #Get the mechanism - if (mech == None): + +def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None): + """Performs a C_SignInit and C_Sign operation on some data + + :param h_session: The current session + :param sign_flavor: The flavour of signing to do + :param data_to_sign: The data to sign, either a string or a list of strings. If this is a list + a multipart operation will be used + :param h_key: The key to sign the data with + :param mech: The mechanism to use, if None a blank mechanism will be created based on the sign_flavor (Default value = None) + :returns: The result code, A python string represeting the signature + + """ + + # Get the mechanism + if mech is None: mech = get_mechanism_for_sigver(sign_flavor) - - #Initialize the sign operation + + # Initialize the sign operation ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) if ret != CKR_OK: return ret, None - - #if a list is passed out do a sign operation on each string in the list, otherwise just do one sign operation + + # if a list is passed out do a sign operation on each string in the list, otherwise just do one sign operation is_multi_part_operation = isinstance(data_to_sign, list) or isinstance(data_to_sign, tuple) - + if is_multi_part_operation: ret, signature_string = do_multipart_sign_or_digest(h_session, C_SignUpdate, C_SignFinal, data_to_sign) else: - #Prepare the data to sign + # Prepare the data to sign c_data_to_sign = get_c_data_to_sign_or_encrypt(data_to_sign) plain_date_len = CK_ULONG(len(data_to_sign)) - - #Get the length of the output + + # Get the length of the output sign_len = CK_ULONG() ret = C_Sign(h_session, c_data_to_sign, plain_date_len, None, byref(sign_len)) if ret != CKR_OK: return ret, None - - #Actually get the signature + + # Actually get the signature signature_buffer = create_string_buffer("", sign_len.value) signature = cast(signature_buffer, CK_BYTE_PTR) ret = C_Sign(h_session, c_data_to_sign, plain_date_len, signature, byref(sign_len)) - + ck_char_array = signature._objects.values()[0] signature_string = '' if sign_len.value > 0: - signature_string = convert_ck_char_array_to_string(ck_char_array)[0:(sign_len.value)] - + signature_string = convert_ck_char_array_to_string(ck_char_array)[0:sign_len.value] + return ret, signature_string + + c_sign_ex = make_error_handle_function(c_sign) + def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, input_data_list): - ''' - Does a multipart sign or digest operation - ''' + """Does a multipart sign or digest operation + + :param h_session: + :param c_update_function: + :param c_final_function: + :param input_data_list: + + """ max_data_chunk_size = 0xfff0 plain_data_len = len(_get_string_from_list(input_data_list)) - + remaining_length = plain_data_len python_string = '' i = 0 while remaining_length > 0: current_chunk = input_data_list[i] - - #Prepare arguments for decrypt update operation + + # Prepare arguments for decrypt update operation current_chunk_len = min(len(current_chunk), remaining_length) - + if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - + raise Exception( + "chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) - + ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len)) if ret != CKR_OK: return ret, None - + remaining_length -= current_chunk_len - + i += 1 - - #Finalizing multipart decrypt operation + + # Finalizing multipart decrypt operation out_data_len = CK_ULONG(max_data_chunk_size) output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) ret = c_final_function(h_session, output, byref(out_data_len)) - - #Get output + + # Get output ck_char_array = output._objects.values()[0] - if (out_data_len.value > 0): + if out_data_len.value > 0: python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] - + return ret, python_string - + + def do_multipart_verify(h_session, input_data_list, signature): - ''' - Does a multipart verify operation - ''' + """Does a multipart verify operation + + :param h_session: + :param input_data_list: + :param signature: + """ max_data_chunk_size = 0xfff0 plain_data_len = len(_get_string_from_list(input_data_list)) - + remaining_length = plain_data_len i = 0 while remaining_length > 0: current_chunk = input_data_list[i] - - #Prepare arguments for decrypt update operation + + # Prepare arguments for decrypt update operation current_chunk_len = min(len(current_chunk), remaining_length) - + if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - + raise Exception( + "chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) - + ret = C_VerifyUpdate(h_session, data_chunk, CK_ULONG(current_chunk_len)) if ret != CKR_OK: return ret - + remaining_length -= current_chunk_len - + i += 1 - - #Finalizing multipart decrypt operation + + # Finalizing multipart decrypt operation out_data_len = CK_ULONG(len(signature)) output = cast(get_c_data_to_sign_or_encrypt(signature), CK_BYTE_PTR) ret = C_VerifyFinal(h_session, output, out_data_len) - + return ret - -def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - ''' - Returns the result code of C_Verify which indicates whether or not the signature is + + +def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=None): + """Returns the result code of C_Verify which indicates whether or not the signature is valid. - - @param h_session: The current session - @param h_key: The key handle to verify the signature against - @param verify_flavor: The flavour of the mechanism to verify against - @param data_to_verify: The data to verify, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) - ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", "It will operate on these strings in parts"] - @param signature: The signature of the data - @param mech: The mechanism to use, if None is specified the mechanism will - try to be automatically obtained - - @returns The result code - ''' - - #Get the mechanism - if mech == None: + + :param h_session: The current session + :param h_key: The key handle to verify the signature against + :param verify_flavor: The flavour of the mechanism to verify against + :param data_to_verify: The data to verify, either a string or a list of strings. If this is a list + a multipart operation will be used + :param signature: The signature of the data + :param mech: The mechanism to use, if None is specified the mechanism will + try to be automatically obtained (Default value = None) + :returns: s The result code + + """ + + # Get the mechanism + if mech is None: mech = get_mechanism_for_sigver(verify_flavor) - - #Initialize the verify operation + + # Initialize the verify operation ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) if ret != CKR_OK: return ret - - #if a list is passed out do a verify operation on each string in the list, otherwise just do one verify operation + + # if a list is passed out do a verify operation on each string in the list, otherwise just do one verify operation is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(data_to_verify, tuple) - + if is_multi_part_operation: ret = do_multipart_verify(h_session, data_to_verify, signature) else: - #Prepare the data to verify + # Prepare the data to verify c_data_to_verify = get_c_data_to_sign_or_encrypt(data_to_verify) plain_date_len = CK_ULONG(len(data_to_verify)) - + c_signature = get_c_data_to_sign_or_encrypt(signature) - - #Actually verify the data + + # Actually verify the data ret = C_Verify(h_session, c_data_to_verify, plain_date_len, c_signature, CK_ULONG(len(signature))) - + return ret - + + c_verify_ex = make_error_handle_function(c_verify) - diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 454f913..05eee9b 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -1,193 +1,224 @@ from ctypes import byref +from functools import wraps +import inspect +import logging + from defines import CKR_OK from pycryptoki.attributes import Attributes from pycryptoki.cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize from pycryptoki.defines import CKR_OBJECT_HANDLE_INVALID from return_values import ret_vals_dictionary -import inspect -import logging logger = logging.getLogger(__name__) + def assert_test_return_value(value, expected_value, message, print_on_success=True): - ''' - Asserts a pass or fail based on whether the value parameter is equal to the expected_value parameter. + """Asserts a pass or fail based on whether the value parameter is equal to the expected_value parameter. Used to test the results of pkcs11 functions and looks up human readable strings for the various error codes. Prints out results in a consistent format. - @param value: The return value of the pkcs11 function - @param expected_value: The expected return value to be tested against - @param message: Message to print on success/failure - @param print_on_success: Whether or not to print if the test case passes - ''' + + :param value: The return value of the pkcs11 function + :param expected_value: The expected return value to be tested against + :param message: Message to print on success/failure + :param print_on_success: Whether or not to print if the test case passes (Default value = True) + + """ if value in ret_vals_dictionary: code = ret_vals_dictionary[value] else: code = "Unknown Code=" + str(hex(value)) - + if expected_value in ret_vals_dictionary: exp_code = ret_vals_dictionary[expected_value] else: exp_code = "Unknown Code=" + str(hex(value)) - - assert value==expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + "\n\tFound: " + code - + + assert value == expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + "\n\tFound: " + code + if print_on_success: logger.info(exp_code + ": " + message) - + def assert_test_case(result, message, print_on_success=False): - ''' - Simple wrapper around assert that allows for a consistent way to report successes/failures - @param result: A boolean representing the result of the test - @param message: The message to print on test failure - ''' + """Simple wrapper around assert that allows for a consistent way to report successes/failures + + :param result: A boolean representing the result of the test + :param message: The message to print on test failure + :param print_on_success: (Default value = False) + + """ assert result, "\nERROR: " + message if print_on_success: logger.info("PASSED: " + message) - + + class LunaException(Exception): - ''' - A class representing an exception in luna, it's in place because + """A class representing an exception in luna, it's in place because it has some nice functionailty to print out the contents of the error - ''' + + + """ + def __init__(self, error_code, function_name, arguments): - ''' - @param error_code: The error code of the error + """ + @param error_code: The error code of the error @param function_name: The name of the function @param arguments: The arguments passed into the function - ''' + """ self.error_code = error_code self.function_name = function_name self.arguments = arguments - + if self.error_code in ret_vals_dictionary: self.error_string = ret_vals_dictionary[self.error_code] else: self.error_string = "Unknown Code=" + str(hex(self.error_code)) - + def __str__(self): return "\n\tFunction: " + str(self.function_name) + "\n\tError: " + str(self.error_string) \ - + "\n\tError Code: " + str(hex(self.error_code)) + "\n\tArguments: " + str(self.arguments) - -class LunaReturn(): + + "\n\tError Code: " + str(hex(self.error_code)) + "\n\tArguments: " + str(self.arguments) + + +class LunaReturn: + """ """ + def __init__(self, return_code, return_data): self.return_code = return_code self.return_data = return_data - + + def verify_object_attributes(h_session, h_object, expected_template): - ''' - Verifies that an object generated has the correct attributes on the board. + """Verifies that an object generated has the correct attributes on the board. The expected attributes are passed in alongside the handle of the object. - - @param h_session: Current session - @param h_object: Handle of the object to verify the attributes against - @param expected_template: The expected template to compare against - ''' - + + :param h_session: Current session + :param h_object: Handle of the object to verify the attributes against + :param expected_template: The expected template to compare against + + """ + # VERIFY OBJECT EXISTS h_object = CK_OBJECT_HANDLE(h_object) us_size = CK_ULONG() ret = C_GetObjectSize(h_session, h_object, byref(us_size)) assert_test_case(ret == CKR_OK, "Object " + str(h_object) + " exists") assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.") - + # VERIFY ATTRIBUTES are the same as the ones passed in attr = Attributes() attr.retrieve_key_attributes(h_session, h_object.value) expected_attributes = Attributes(expected_template) - assert_test_case(attr == expected_attributes, "Object " + str(h_object.value) + " attributes match expected attributes") + assert_test_case(attr == expected_attributes, + "Object " + str(h_object.value) + " attributes match expected attributes") + def verify_object_exists(h_session, h_object, should_exist=True): - ''' - Queries the HSM to determine if an object exists. Asserts whether or not + """Queries the HSM to determine if an object exists. Asserts whether or not it exists. - - @param h_session: The current session - @param h_object: The object to verify if it exists - @param should_exist: Whether or not the parameter should exist (Use to determine how this function asserts) - ''' + + :param h_session: The current session + :param h_object: The object to verify if it exists + :param should_exist: Whether or not the parameter should exist (Default value = True) + + """ # VERIFY OBJECT EXISTS h_object = CK_OBJECT_HANDLE(h_object) us_size = CK_ULONG() - + if should_exist: expected_ret = CKR_OK out = "Verifying object " + str(h_object) + " exists." else: expected_ret = CKR_OBJECT_HANDLE_INVALID out = "Verifying object " + str(h_object) + " doesn't exist." - + try: ret = C_GetObjectSize(h_session, h_object, byref(us_size)) except LunaException as e: assert_test_case(e.error_code == expected_ret, out) else: assert_test_case(ret == expected_ret, out) - + if should_exist: assert_test_return_value(ret, CKR_OK, "Getting object " + str(h_object.value) + "'s size", True) assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.", False) else: - assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, "Getting object " + str(h_object.value) + "'s size", True) + assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, "Getting object " + str(h_object.value) + "'s size", + True) assert_test_case(us_size.value <= 0, "Object " + str(h_object.value) + " size is greater than zero.", False) + def check_luna_exception(ret, luna_function, *args): - ''' - - ''' + """ + + :param ret: + :param luna_function: + :param *args: + + """ arg_spec = inspect.getargspec(luna_function).args arg_string = "(" i = 0 - if (len(arg_spec) > 0): + if len(arg_spec) > 0: for argument in args: - arg_string = arg_string + arg_spec[i] + "=" + str(argument) - + arg_string = arg_string + arg_spec[i] + "=" + str(argument) + if i != (len(args) - 1): - arg_string = arg_string + ", " - i = i + 1 - - arg_string = arg_string + ")" + arg_string += ", " + i += 1 + + arg_string += ")" if ret != CKR_OK: raise LunaException(ret, luna_function.__name__, arg_string) + def make_error_handle_function(luna_function): - ''' - This function is a helper function that creates a new function which checks the + """This function is a helper function that creates a new function which checks the result code returned from a function in luna. It is called by calling: - + c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) - + This code will create a c_generate_key_pair_ex which will call c_generate_key_pair and check the - first argument. The first argument is the return code of c_generate_key_pair. If the return + first argument. The first argument is the return code of c_generate_key_pair. If the return code != CKR_OK then c_generate_key_pair_ex will raise a LunaException. You can call c_generate_key_pair_ex as if it is c_generate_key_pair: - c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - + The return values of c_generate_pair are (ret, public_key_handle, private_key_handle) - + The return values of c_generate_pair_ex are (public_key_handle, private_key_handle) - + This lets you create two versions of a function. One version is for setup and the other version is for testing the result. - + Directly testing the result: ret = c_initialize() assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" - + Expecting the call to go through without error. The test case should have an error (not a failure): c_initialize_ex() - + This should therefore make for shorter test cases - ''' - + + :param luna_function: + + """ + + @wraps(luna_function) def luna_function_exception_handle(*args, **kwargs): - return_tuple = luna_function(*args, **kwargs); + """ + + :param *args: + :param **kwargs: + + """ + return_tuple = luna_function(*args, **kwargs) if isinstance(return_tuple, tuple): - if (len(return_tuple) > 2): + if len(return_tuple) > 2: return_data = return_tuple[1:] ret = return_tuple[0] - elif (len(return_tuple) == 2): + elif len(return_tuple) == 2: return_data = return_tuple[1] ret = return_tuple[0] else: @@ -197,10 +228,10 @@ def luna_function_exception_handle(*args, **kwargs): ret = return_tuple return_data = return_tuple else: - raise Exception("Functions wrapped by the exception handler should return a tuple or just the long representing Luna's return code.") - + raise Exception( + "Functions wrapped by the exception handler should return a tuple or just the long representing Luna's return code.") + check_luna_exception(ret, luna_function, args) return return_data + return luna_function_exception_handle - - diff --git a/pycryptoki/tests/run_tests_in_folder.py b/pycryptoki/tests/run_tests_in_folder.py index d3d852b..d1527ad 100755 --- a/pycryptoki/tests/run_tests_in_folder.py +++ b/pycryptoki/tests/run_tests_in_folder.py @@ -1,9 +1,9 @@ -''' +""" Created on Aug 30, 2012 @author: mhughes -''' +""" import pytest if __name__ == '__main__': - pytest.cmdline.main(args=[]) + pytest.cmdline.main(args=[]) diff --git a/pycryptoki/tests/setup_for_tests.py b/pycryptoki/tests/setup_for_tests.py index 6d20753..31b04df 100755 --- a/pycryptoki/tests/setup_for_tests.py +++ b/pycryptoki/tests/setup_for_tests.py @@ -1,8 +1,8 @@ -''' +""" Created on Sep 18, 2012 @author: mhughes -''' +""" from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD, \ CO_PASSWORD from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ @@ -16,8 +16,15 @@ logger = logging.getLogger(__name__) def setup_for_tests(should_factory_reset, initialize_admin_token, initialize_users): + """ + + :param should_factory_reset: + :param initialize_admin_token: + :param initialize_users: + + """ c_initialize_ex() - + #Factory Reset slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) if should_factory_reset: @@ -29,8 +36,8 @@ def setup_for_tests(should_factory_reset, initialize_admin_token, initialize_use if initialize_admin_token: h_session = c_open_session_ex(slot, session_flags) c_init_token_ex(slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) - - + + if initialize_users and initialize_admin_token: slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) c_close_all_sessions_ex(slot) @@ -39,5 +46,5 @@ def setup_for_tests(should_factory_reset, initialize_admin_token, initialize_use c_init_pin_ex(h_session, CO_PASSWORD) c_logout_ex(h_session) c_close_all_sessions_ex(slot) - - c_finalize_ex() \ No newline at end of file + + c_finalize_ex() diff --git a/pycryptoki/tests/stress/conftest.py b/pycryptoki/tests/stress/conftest.py index 336ed7f..df7076f 100755 --- a/pycryptoki/tests/stress/conftest.py +++ b/pycryptoki/tests/stress/conftest.py @@ -1,21 +1,21 @@ -''' +""" This allows for configuration of the designated test/testdir - Currently this adds custom command args (see below) to py.test interface for this test/directory -''' +""" from pycryptoki.defaults import DEFAULT_UTILS_PATH from pycryptoki.utils.common_utils import setLogFile -def pytest_addoption(parser): +def pytest_addoption(parser): parser.addoption("--tslot", help="This is the token slot we wish to target ", type=int, default=1) parser.addoption("--vdevice", metavar='device', help="Target device we want to use i.e. /dev/viper0 or /dev/viper1", default="/dev/viper0") - parser.addoption("--upath", metavar='path', + parser.addoption("--upath", metavar='path', help="Path to where the utils are stored: vrest, dumpit", - default=DEFAULT_UTILS_PATH) + default=DEFAULT_UTILS_PATH) parser.addoption("--logfile", help="name of log to store output", default=setLogFile()) @@ -29,4 +29,4 @@ def pytest_funcarg__upath(request): return request.config.option.upath def pytest_funcarg__tslot(request): - return request.config.option.tslot \ No newline at end of file + return request.config.option.tslot diff --git a/pycryptoki/tests/stress/test_multi_reset.py b/pycryptoki/tests/stress/test_multi_reset.py index 966a394..c574a79 100755 --- a/pycryptoki/tests/stress/test_multi_reset.py +++ b/pycryptoki/tests/stress/test_multi_reset.py @@ -26,7 +26,7 @@ from pycryptoki.utils.common_utils import setLogFile from pycryptoki.tests.stress.vreset_thread import ResetThread from pycryptoki.defaults import DEFAULT_UTILS_PATH, FORMAT -from random import randint +from random import randint import logging import os import threading @@ -36,16 +36,17 @@ #Global Scope logger = logging.getLogger(__name__) - -class MultiResetDuringKeyGen(): + +class MultiResetDuringKeyGen: + """ """ def __init__(self, slot): self.slot = slot self.h_session = 0 - #Setup events + #Setup events self.trigger = threading.Event() self.complete = threading.Event() #Keygen options - 13 options randomly selected - self.keytype_and_template_list = [(CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + self.keytype_and_template_list = [(CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), @@ -55,36 +56,41 @@ def __init__(self, slot): (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP), (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP)] def close_off(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) c_finalize_ex() - + def getDefltLabel(self): - label = DEFAULT_LABEL+str(self.slot) + """ """ + label = DEFAULT_LABEL+str(self.slot) return label - + def gen_verify_clean(self, vdevice, upath): - ''' - This method is the core of the test case. + """This method is the core of the test case. The purpose being to continually generate keys until a random reset causes a DEVICE_ERROR to be returned at which point we capture the exception generated, and verify the objects that were created. Once a certain number of keys (currently set to 20000) are generated we delete and repeat the process - ''' + + :param vdevice: + :param upath: + + """ cntNum = CK_ULONG() generated_objects = [] logger.info("--- Starting Test ---") - rthread = ResetThread(self.trigger, self.complete,vdevice, upath, logger) + rthread = ResetThread(self.trigger, self.complete,vdevice, upath, logger) ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) logger.info("Container Number:[%s]" % str(cntNum)) - if (ret != CKR_OK): + if ret != CKR_OK: rthread.join(1) logger.info("Error: could not get container number[%s]" % str(cntNum)) - exit(-1) + exit(-1) rthread.start() self.trigger.set() self.complete.clear() @@ -97,30 +103,30 @@ def gen_verify_clean(self, vdevice, upath): type_of_keygen = randint(0,12) #Generate random key type with associated template gen_ret, hdl = c_generate_key(self.h_session, self.keytype_and_template_list[type_of_keygen][0], self.keytype_and_template_list[type_of_keygen][1]) - if (gen_ret == CKR_DEVICE_ERROR): + if gen_ret == CKR_DEVICE_ERROR: raise Exception('keygen') ouid_ret = CA_GetObjectUID(CK_SLOT_ID(self.slot),cntNum,CK_ULONG(CK_CRYPTOKI_ELEMENT),CK_ULONG(hdl),ouid) - if (ouid_ret == CKR_DEVICE_ERROR): + if ouid_ret == CKR_DEVICE_ERROR: raise Exception('ouid') - if (ouid_ret == CKR_OK and gen_ret == CKR_OK): - self.trigger.set() + if ouid_ret == CKR_OK and gen_ret == CKR_OK: + self.trigger.set() #Store off the object OUID and the template used for keygen generated_objects.append((ouid,self.keytype_and_template_list[type_of_keygen][1])) - logger.debug("Entry Info: hdl[%d]:num[%d]:ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % + logger.debug("Entry Info: hdl[%d]:num[%d]:ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % (hdl,num,ouid[0],ouid[1],ouid[2],ouid[3],ouid[4],ouid[5],ouid[6], ouid[7],ouid[8], ouid[9], ouid[10], ouid[11])) except Exception as e: self.trigger.clear() msg = e.args[0] - logger.info("Exception:[%s] on entry [%d]" % (msg,num)) - if (msg != 'keygen' and msg != 'ouid'): + logger.info("Exception:[%s] on entry [%d]" % (msg,num)) + if msg != 'keygen' and msg != 'ouid': rthread.join(1) - logger.info("Unexpected exception:[%s] - exiting!" % msg) - exit(-1); - if (msg == 'keygen'): - logger.info("Create: Keygen errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) - if (msg == 'ouid'): - logger.info("Create: OUID lookup errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) + logger.info("Unexpected exception:[%s] - exiting!" % msg) + exit(-1) + if msg == 'keygen': + logger.info("Create: Keygen errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) + if msg == 'ouid': + logger.info("Create: OUID lookup errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) logger.info("Waiting to verify %d objects" % len(generated_objects)) self.complete.wait() self.complete.clear() @@ -129,7 +135,7 @@ def gen_verify_clean(self, vdevice, upath): logger.info("Start verification of %d objects" % len(generated_objects)) ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) logger.info("Container Number:[%s]" % str(cntNum)) - if (ret != CKR_OK): + if ret != CKR_OK: rthread.join(1) logger.info("Error: could not get container number[%s]" % str(cntNum)) exit(-1) @@ -138,16 +144,16 @@ def gen_verify_clean(self, vdevice, upath): TODO: Make this set of operations more intensive. For example: Encrypt/Decrypt data blob on alternating vreset iterations. - Create EC keys, keypairs etc - ''' + Create EC keys, keypairs etc + ''' for kouid, temp in generated_objects: - + key = CK_ULONG() oType = CK_ULONG() ret = CA_GetObjectHandle(CK_SLOT_ID(self.slot), cntNum, kouid, byref(oType), byref(key)) - if (ret != CKR_OK): + if ret != CKR_OK: logger.debug("Verify: Error: could not get handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % (key.value,kouid[0],kouid[1],kouid[2],kouid[3],kouid[4],kouid[5],kouid[6], kouid[7],kouid[8], kouid[9], kouid[10], kouid[11])) @@ -156,7 +162,7 @@ def gen_verify_clean(self, vdevice, upath): exit(-1) logger.debug("Verify: handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % (key.value,kouid[0],kouid[1],kouid[2],kouid[3],kouid[4],kouid[5],kouid[6], - kouid[7],kouid[8], kouid[9], kouid[10], kouid[11])) + kouid[7],kouid[8], kouid[9], kouid[10], kouid[11])) verify_object_exists(self.h_session, key.value, True) verify_object_attributes(self.h_session, key.value, temp) logger.info("Completed verification of %d objects" % len(generated_objects)) @@ -176,68 +182,68 @@ def gen_verify_clean(self, vdevice, upath): gethdl_ret = CA_GetObjectHandle(CK_SLOT_ID(self.slot), cntNum, douid, byref(oType), byref(key)) - if (gethdl_ret == CKR_DEVICE_ERROR): - raise Exception('get_hdl') + if gethdl_ret == CKR_DEVICE_ERROR: + raise Exception('get_hdl') dest_ret = c_destroy_object(self.h_session, key.value) - if (dest_ret == CKR_DEVICE_ERROR): - raise Exception('destroy') - if (dest_ret == CKR_OK and gethdl_ret == CKR_OK): + if dest_ret == CKR_DEVICE_ERROR: + raise Exception('destroy') + if dest_ret == CKR_OK and gethdl_ret == CKR_OK: delcount+=1 except Exception as e: - self.trigger.clear() + self.trigger.clear() msg = e.args[0] - logger.info("Exception:[%s] on entry [%d]" % (msg,delcount)) - if (msg != 'get_hdl' and msg != 'destroy'): + logger.info("Exception:[%s] on entry [%d]" % (msg,delcount)) + if msg != 'get_hdl' and msg != 'destroy': rthread.join(1) - logger.info("Unexpected exception:[%s] - exiting!" % msg) - exit(-1); - if (msg == 'get_hdl'): - logger.info("Delete: Error: could not get handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" + logger.info("Unexpected exception:[%s] - exiting!" % msg) + exit(-1) + if msg == 'get_hdl': + logger.info("Delete: Error: could not get handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % (key.value, douid[0],douid[1],douid[2],douid[3],douid[4],douid[5],douid[6], - douid[7],douid[8], douid[9], douid[10], douid[11])) - if (msg == 'destroy'): - logger.info("Delete: Error: failed to delete entry [%d] with ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" + douid[7],douid[8], douid[9], douid[10], douid[11])) + if msg == 'destroy': + logger.info("Delete: Error: failed to delete entry [%d] with ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % (key.value, douid[0],douid[1],douid[2],douid[3],douid[4],douid[5],douid[6], - douid[7],douid[8], douid[9], douid[10], douid[11])) + douid[7],douid[8], douid[9], douid[10], douid[11])) self.complete.wait() - self.complete.clear() + self.complete.clear() self.h_session = c_open_session_ex(CK_SLOT_ID(self.slot), CKF_SERIAL_SESSION | CKF_RW_SESSION) - login_ex(self.h_session, self.slot, DEFAULT_PASSWORD, 1) + login_ex(self.h_session, self.slot, DEFAULT_PASSWORD, 1) ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) logger.debug("Container Number:[%s]" % str(cntNum)) - if (ret != CKR_OK): + if ret != CKR_OK: rthread.join(1) logger.info("Error: could not get container number[%s]" % str(cntNum)) exit(-1) # Clear the memory of the exception sys.exc_clear() - continue + continue logger.info("Deleted: %d of %d Objects" % (delcount,store_count)) - self.trigger.set() - rthread.join(1) - logger.info("--- Ending Test ---") - + self.trigger.set() + rthread.join(1) + logger.info("--- Ending Test ---") + def setup_for_test(self, initialize_admin_token, initialize_users, slot): - ''' - A common setup for the configurable roles tests - + """A common setup for the configurable roles tests + :param initialize_admin_token: Whether or not to initialize the admin partition :param initialize_users: Whether or not to initialize the PIN's of the users - :param slot: Token slot to target - ''' - c_initialize(); - + :param slot: Token slot to target + + """ + c_initialize() + #Factory Reset logger.info(slot) # NOTE: This is required always. c_close_all_sessions_ex(slot) ca_factory_reset_ex(slot) - + #Initialize the Token session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) if initialize_admin_token: h_session = c_open_session_ex(slot, session_flags) - c_init_token_ex(slot, DEFAULT_PASSWORD, self.getDefltLabel() ) + c_init_token_ex(slot, DEFAULT_PASSWORD, self.getDefltLabel() ) c_finalize() c_initialize() if initialize_users and initialize_admin_token: @@ -259,15 +265,16 @@ def setup_for_test(self, initialize_admin_token, initialize_users, slot): Get the command line args provided as input for test application/case ''' def get_cmd_args(): + """ """ parser = argparse.ArgumentParser() parser.add_argument("--tslot", help="This is the token slot we wish to target ", type=int, default=1) parser.add_argument("--vdevice", metavar='device', help="Target device we want to use i.e. viper0 or viper1", default="/dev/viper0") - parser.add_argument("--upath", metavar='path', + parser.add_argument("--upath", metavar='path', help="Path to where the utils are stored: vrest, dumpit", - default=DEFAULT_UTILS_PATH) + default=DEFAULT_UTILS_PATH) parser.add_argument("--logfile", help="name of log to store output", default=setLogFile()) args = parser.parse_args() @@ -283,23 +290,28 @@ def get_cmd_args(): try: os.stat(valid_vreset_path) except OSError as e: - print "Startup: Exception: Invalid utils path [%s] or vreset not present [%s]" % (args.upath, e.args) - exit(-1) + print "Startup: Exception: Invalid utils path [%s] or vreset not present [%s]" % (args.upath, e.args) + exit(-1) valid_dumpit_path = args.upath + "/dumpit" try: os.stat(valid_dumpit_path) except OSError as e: - print "Startup: Exception: Invalid utils path [%s] or dumpit not present[%s]" % (args.upath, e.args) + print "Startup: Exception: Invalid utils path [%s] or dumpit not present[%s]" % (args.upath, e.args) exit(-1) return args -''' +''' Setup logging structure ''' def config_logging(args): + """ + + :param args: + + """ print args logging.basicConfig(format=FORMAT,filename=args.logfile,level=logging.DEBUG,) - + # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.INFO) @@ -309,33 +321,34 @@ def config_logging(args): console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) - + ''' PyTest Entry Point: NOTE: In order to enable console output to the py.test when running this test provide the following in setup.cfg # content of setup.cfg [pytest] addopts = -s -''' +''' def test_gen_verify_clean(): + """ """ args = get_cmd_args() config_logging(args) - Reset = MultiResetDuringKeyGen(args.tslot) + Reset = MultiResetDuringKeyGen(args.tslot) Reset.setup_for_test(True, True, args.tslot) - Reset.gen_verify_clean(args.vdevice, args.upath) - Reset.close_off() - + Reset.gen_verify_clean(args.vdevice, args.upath) + Reset.close_off() + ''' Application Entry Point: Call directly from the command line: python -''' +''' if __name__ == '__main__': test_gen_verify_clean() - - - - - - + + + + + + diff --git a/pycryptoki/tests/stress/vreset_thread.py b/pycryptoki/tests/stress/vreset_thread.py index 364bc9e..d0686c6 100755 --- a/pycryptoki/tests/stress/vreset_thread.py +++ b/pycryptoki/tests/stress/vreset_thread.py @@ -2,17 +2,18 @@ import threading import time import subprocess -from random import randint +from random import randint -# Reset Thread class - wanted to be able to stop thread on error +# Reset Thread class - wanted to be able to stop thread on error class ResetThread(threading.Thread): - ''' - Input parameters for this class are: + """Input parameters for this class are: trigger: the event to initiate the reset operation - thread waits on this event complete: the event to tell the external world that the reset has complete device: the target device node to reset upath: the path to the driver utils i.e. vreset and dumpit - ''' + + + """ def __init__(self, trigger, complete, device, upath, logger): super(ResetThread, self).__init__() self.trigger = trigger @@ -22,8 +23,9 @@ def __init__(self, trigger, complete, device, upath, logger): self.device = device self.upath = upath self.logger = logger - + def run(self): + """ """ while not self.stoprequest.isSet(): self.count += 1 self.trigger.wait() @@ -36,19 +38,24 @@ def run(self): self.complete.set() else: self.complete.clear() - self.logger.info("-----Vreset Failed: [%d] on device [%s]-------" % (val,self.device)) + self.logger.info("-----Vreset Failed: [%d] on device [%s]-------" % (val,self.device)) proc_dump = subprocess.Popen([self.upath + str("/dumpit"), self.device], stdout=subprocess.PIPE, shell=True) (dump_out, dump_err) = proc_dump.communicate() self.logger.debug("DUMPIT OUTPUT: stdout") - self.logger.debug(dump_out) + self.logger.debug(dump_out) self.logger.debug("DUMPIT ERROR: stderr") self.logger.debug(dump_err) tail_proc = subprocess.Popen([str("tail -n 100 "), str("/var/log/messages")], stdout=subprocess.PIPE, shell=True) (tail_out, tail_err) = tail_proc.communicate() self.logger.debug("TAIL OUTPUT: stdout") - self.logger.debug(tail_out) + self.logger.debug(tail_out) self.logger.debug("TAIL ERROR: stderr") self.logger.debug(tail_err) def join(self, timeout=None): + """ + + :param timeout: (Default value = None) + + """ self.stoprequest.set() - super(ResetThread, self).join(timeout) \ No newline at end of file + super(ResetThread, self).join(timeout) diff --git a/pycryptoki/tests/test_cka_start_and_end.py b/pycryptoki/tests/test_cka_start_and_end.py index 8561981..e6777bd 100755 --- a/pycryptoki/tests/test_cka_start_and_end.py +++ b/pycryptoki/tests/test_cka_start_and_end.py @@ -1,6 +1,9 @@ -from ctypes import * from datetime import datetime -import math +import logging +import os + +import pytest + from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL from pycryptoki.defines import CKF_SERIAL_SESSION,CKM_DES_KEY_GEN, CKU_USER, \ CKA_END_DATE, CKU_AUDIT, CKF_AUDIT_SESSION @@ -8,7 +11,7 @@ CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ - CKK_AES, CKM_DES_ECB, CKU_SO, CKR_KEY_NOT_ACTIVE, CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKK_AES, CKM_DES_ECB, CKR_KEY_NOT_ACTIVE, CKM_RSA_PKCS_KEY_PAIR_GEN, \ CKM_RSA_PKCS, CKM_AES_ECB, CKM_AES_KEY_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA_SHA1 from pycryptoki.default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex @@ -19,19 +22,18 @@ from pycryptoki.attributes import date_attrb from pycryptoki.dictionary_handling import CDict from pycryptoki.encryption import c_encrypt, c_encrypt_ex -from pycryptoki.audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex -from pycryptoki.sign_verify import c_sign_ex, c_sign -import logging -import os -import pytest +from pycryptoki.audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex +from pycryptoki.sign_verify import c_sign_ex, c_sign logger = logging.getLogger(__name__) -class TestCKAStartEndDate(): +class TestCKAStartEndDate: + """ """ h_session = 0 admin_slot = 0 - + def setup(self): + """ """ setup_for_tests(True, True, True) c_initialize_ex() self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) @@ -40,31 +42,33 @@ def setup(self): def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) c_finalize() - + def test_symmetric_key_expiry_des(self): - """ - Test: Verify that user is not able to use the symmetric object after date specified in + """Test: Verify that user is not able to use the symmetric object after date specified in CKA_END_DATE attribute Procedure: Generate a DES Key des1 Use des1 in encrypt operation. Should work fine Using audit role, change the date of HSM to 12/31/2013 - Use des1 in encrypt operation - """ - + Use des1 in encrypt operation + + + """ + logger.info("Test: Verify that user is not able to use the symmetric object after date specified in \ - CKA_END_DATE attribute") - + CKA_END_DATE attribute") + end_d = date_attrb end_d['year'] = "2013" end_d['month'] = "12" end_d['day'] = "31" - CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, CKA_KEY_TYPE : CKK_DES, CKA_TOKEN : True, CKA_SENSITIVE : True, @@ -74,7 +78,7 @@ def test_symmetric_key_expiry_des(self): CKA_SIGN : True, CKA_VERIFY : True, CKA_WRAP : True, - CKA_UNWRAP : True, + CKA_UNWRAP : True, CKA_DERIVE : True, CKA_VALUE_LEN : 8, CKA_EXTRACTABLE :True, @@ -82,64 +86,65 @@ def test_symmetric_key_expiry_des(self): CKA_END_DATE : CDict(end_d)} - + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) - + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, "a" * 512) c_logout_ex(self.h_session) c_close_session_ex(self.h_session) - + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - + dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) + epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() hsm_new_date = int(hsm_dt) - + ca_time_sync_ex(h_session2, hsm_new_date) - + hsm_time = ca_get_time_ex(h_session2) c_logout_ex(h_session2) c_close_session_ex(h_session2) - + h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - + return_val = c_encrypt(h_session, CKM_DES_ECB, h_key, "This is some data to sign .. ") - + assert return_val == CKR_KEY_NOT_ACTIVE, "return value should be CKR_KEY_NOT_ACTIVE" c_logout_ex(h_session) c_close_session_ex(h_session) def test_symmetric_key_expiry_aes(self): - """ - Test: Verify that user is not able to use the symmetric aes object after date specified in + """Test: Verify that user is not able to use the symmetric aes object after date specified in CKA_END_DATE attribute Procedure: Generate a AES key aes1 Use aes1 in encrypt operation. Should work fine Using audit role, change the date of HSM to 12/31/2013 - Use aes1 in encrypt operation - """ - + Use aes1 in encrypt operation + + + """ + logger.info("Test: Verify that user is not able to use the symmetric aes object after date specified in \ - CKA_END_DATE attribute") + CKA_END_DATE attribute") end_d = date_attrb end_d['year'] = "2013" end_d['month'] = "12" end_d['day'] = "31" - CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, + CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, CKA_KEY_TYPE : CKK_AES, CKA_TOKEN : True, CKA_SENSITIVE : True, @@ -149,7 +154,7 @@ def test_symmetric_key_expiry_aes(self): CKA_SIGN : True, CKA_VERIFY : True, CKA_WRAP : True, - CKA_UNWRAP : True, + CKA_UNWRAP : True, CKA_DERIVE : True, CKA_VALUE_LEN : 16, CKA_EXTRACTABLE :True, @@ -157,23 +162,23 @@ def test_symmetric_key_expiry_aes(self): CKA_END_DATE : CDict(end_d)} - + h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) - + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") - + c_logout_ex(self.h_session) c_close_session_ex(self.h_session) - + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - + dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) + epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() hsm_new_date = int(hsm_dt) @@ -183,28 +188,29 @@ def test_symmetric_key_expiry_aes(self): c_logout_ex(h_session2) c_close_session_ex(h_session2) - + h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - + return_val = c_encrypt(h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") - logger.info("Called C_Encrypt, return code: " + str(return_val)) + logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" def test_asymmetric_key_expiry_rsa(self): - """ - Test: Verify that user is not able to use the rsa asymmetric object after date specified in + """Test: Verify that user is not able to use the rsa asymmetric object after date specified in CKA_END_DATE attribute Procedure: Generate a rsa Key rsa1 Use des1 in encrypt operation. Should work fine Using audit role, change the date of HSM to 12/31/2013 - Use rsa1 in encrypt operation - """ - + Use rsa1 in encrypt operation + + + """ + logger.info("Test: Verify that user is not able to use the rsa asymmetric object after date specified in \ - CKA_END_DATE attribute") + CKA_END_DATE attribute") end_d = date_attrb end_d['year'] = "2013" end_d['month'] = "12" @@ -233,56 +239,57 @@ def test_asymmetric_key_expiry_rsa(self): CKA_LABEL : "RSA Private Key"} - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") - + c_logout_ex(self.h_session) c_close_session_ex(self.h_session) - + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - + dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) + epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() hsm_new_date = int(hsm_dt) ca_time_sync_ex(h_session2, hsm_new_date) - + hsm_time = ca_get_time_ex(h_session2) # print datetime.fromtimestamp(float(hsm_time.value)) c_logout_ex(h_session2) c_close_session_ex(h_session2) - + h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - + return_val = c_encrypt(h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") - logger.info("Called C_Encrypt, return code: " + str(return_val)) + logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" def test_asymmetric_key_expiry_dsa(self): - """ - Test: Verify that user is not able to use the dsa asymmetric object after date specified in + """Test: Verify that user is not able to use the dsa asymmetric object after date specified in CKA_END_DATE attribute Procedure: Generate a DSA Key dsa1 Use dsa11 in encrypt operation. Should work fine Using audit role, change the date of HSM to 12/31/2013 - Use dsa1 in encrypt operation - """ - + Use dsa1 in encrypt operation + + + """ + logger.info("Test: Verify that user is not able to use the dsa asymmetric object after date specified in \ - CKA_END_DATE attribute") + CKA_END_DATE attribute") end_d = date_attrb end_d['year'] = "2013" end_d['month'] = "12" @@ -310,49 +317,49 @@ def test_asymmetric_key_expiry_dsa(self): CKA_LABEL : "DSA Public Key"} - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_DSA_KEY_PAIR_GEN, - pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_DSA_KEY_PAIR_GEN, + pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, prkey_template=CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, mech=None) logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - + c_sign_ex(self.h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) - - - + + + c_logout_ex(self.h_session) c_close_session_ex(self.h_session) - + ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - + h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - + dt = datetime(2014, 1 , 31) - epoch = datetime.utcfromtimestamp(0) + epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() hsm_new_date = int(hsm_dt) ca_time_sync_ex(h_session2, hsm_new_date) - + hsm_time = ca_get_time_ex(self.h_session) # print datetime.fromtimestamp(float(hsm_time.value)) c_logout_ex(h_session2) c_close_session_ex(h_session2) - + h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - + return_val, sig = c_sign(h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) - logger.info("Called C_Sign, return code: " + str(return_val)) + logger.info("Called C_Sign, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - - + + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) - - \ No newline at end of file + + diff --git a/pycryptoki/tests/test_digest_data.py b/pycryptoki/tests/test_digest_data.py index 23406c0..50136ed 100755 --- a/pycryptoki/tests/test_digest_data.py +++ b/pycryptoki/tests/test_digest_data.py @@ -12,42 +12,46 @@ logger = logging.getLogger(__name__) -class TestDigestData(): +class TestDigestData: + """ """ @classmethod - def setup_class(self): + def setup_class(cls): + """ """ setup_for_tests(True, True, True) c_initialize_ex() - + @classmethod - def teardown_class(self): + def teardown_class(cls): + """ """ c_finalize_ex() - + def setup(self): + """ """ admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=admin_slot) login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - + def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) def test_digest_data(self): - ''' - Calls C_Digest on some data and makes sure there is no failure - ''' + """Calls C_Digest on some data and makes sure there is no failure""" data_to_digest = "Some arbitrary string" ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) assert ret == CKR_OK, "Digesting should occur with no errors" assert len(digested_data) > 0, "The digested data should have a length" assert data_to_digest != digested_data, "The digested data should not be the same as the original string" - + def test_multipart_digest_data(self): + """ """ data_to_digest = ["Some arbitrary string", "Some second arbitrary string"] ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) assert ret == CKR_OK, "Digesting should occur with no errors" assert len(digested_data) > 0, "The digested data should have a length" assert _get_string_from_list(data_to_digest) != digested_data, "The digested data should not be the same as the original string" - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_encrypt_decrypt.py b/pycryptoki/tests/test_encrypt_decrypt.py index e56ed79..6c97f40 100755 --- a/pycryptoki/tests/test_encrypt_decrypt.py +++ b/pycryptoki/tests/test_encrypt_decrypt.py @@ -1,7 +1,11 @@ +import logging +import os + +import pytest + from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ - CKM_DES_CBC_PAD, CKM_DES_CBC_ENCRYPT_DATA +from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK from pycryptoki.encryption import c_encrypt, c_decrypt, _split_string_into_list, \ _get_string_from_list from pycryptoki.key_generator import c_generate_key_ex @@ -10,63 +14,64 @@ login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex from pycryptoki.tests.setup_for_tests import setup_for_tests from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest logger = logging.getLogger(__name__) -class TestEncryptData(): +class TestEncryptData: + """ """ @classmethod - def setup_class(self): + def setup_class(cls): + """ """ setup_for_tests(True, True, True) c_initialize_ex() - + @classmethod - def teardown_class(self): + def teardown_class(cls): + """ """ c_finalize_ex() - + def setup(self): + """ """ admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=admin_slot) login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - + def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) def test_encrypt_decrypt_string(self): - ''' - Tests encrypting and decrypting a string with a key - ''' + """Tests encrypting and decrypting a string with a key""" h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - data_to_encrypt = "a" * (0xfff0) + + data_to_encrypt = "a" * 0xfff0 ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - + ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data) assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) - + def test_multipart_encrypt_decrypt(self): - ''' - Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore doing it in multiple + """Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore doing it in multiple parts - ''' + + + """ h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - + data_to_encrypt = ['a' * 512, 'b' * 512, 'c' * 512, 'd' * 512] ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] assert len(encrypted_data) == len(_get_string_from_list(data_to_encrypt)) - + encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) - + ret, decrypted_data = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data_chunks) assert ret == CKR_OK, "Decryption should succeed, instead it returned " + ret_vals_dictionary[ret] assert _get_string_from_list(data_to_encrypt) == decrypted_data, "The data before encryption should match the data after encryption" - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_get_token_info.py b/pycryptoki/tests/test_get_token_info.py index 2c1e726..7070be8 100755 --- a/pycryptoki/tests/test_get_token_info.py +++ b/pycryptoki/tests/test_get_token_info.py @@ -1,4 +1,8 @@ -from ctypes import byref +import logging +import os + +import pytest + from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD from pycryptoki.defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ CKF_RESTORE_KEY_NOT_NEEDED, CKF_TOKEN_INITIALIZED @@ -6,42 +10,43 @@ c_get_token_info_ex, c_close_all_sessions, c_initialize_ex from pycryptoki.tests.setup_for_tests import setup_for_tests from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex -import logging -import os -import pytest logger = logging.getLogger(__name__) -class TestGetTokenInfo(): - +class TestGetTokenInfo: + """ """ + def setup(self): + """ """ setup_for_tests(True, False, False) c_initialize_ex() - + def teardown(self): + """ """ c_finalize() def test_initial_flags(self): - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL); - + """ """ + admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + #Get to clean state c_close_all_sessions(admin_slot) ca_factory_reset_ex(admin_slot) - + #Look at flags before initialization flags = c_get_token_info_ex(admin_slot)['flags'] expected_flags = CKF_TOKEN_PRESENT | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED assert flags == expected_flags, "After factory reset found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) - - c_init_token_ex(admin_slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL); - + + c_init_token_ex(admin_slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) + #Test flags after initialization flags = c_get_token_info_ex(admin_slot)['flags'] expected_flags = expected_flags | CKF_TOKEN_INITIALIZED assert flags == expected_flags, "After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) logger.info("After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags))) - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) - \ No newline at end of file + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) + diff --git a/pycryptoki/tests/test_hsm_management.py b/pycryptoki/tests/test_hsm_management.py index 6282f1b..2bd0d2d 100755 --- a/pycryptoki/tests/test_hsm_management.py +++ b/pycryptoki/tests/test_hsm_management.py @@ -28,65 +28,62 @@ import pytest -class TestAlgorithm(): - """ Test algorithm class """ +class TestAlgorithm: + """Test algorithm class""" h_session = 0 admin_slot = 0 @classmethod - def setup_class(self): - """ Setup class """ + def setup_class(cls): + """Setup class""" setup_for_tests(True, True, True) c_initialize_ex() @classmethod - def teardown_class(self): - """ Finalize tests """ + def teardown_class(cls): + """Finalize tests""" c_finalize_ex() def setup(self): - """ Setup test """ + """Setup test""" self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) def teardown(self): - """ Teardown test """ + """Teardown test""" c_logout_ex(self.h_session) c_close_session_ex(self.h_session) - @pytest.mark.parametrize(("test_type"), + @pytest.mark.parametrize("test_type", [LUNA_TTYPE_CRYPTO, LUNA_TTYPE_RNG, LUNA_DSS_SIGVERIFY_TEST]) def test_performselftest(self, test_type): - ''' - Tests performs self test + """Tests performs self test - @param test_type: test type - ''' + :param test_type: test type + + """ input_data = (CK_BYTE*1000)() input_length = CK_ULONG(1000) - output_data = (CK_BYTE*1000)() - output_length = CK_ULONG(0) ret = c_performselftest(self.admin_slot, test_type, input_data, - input_length, - output_data, - output_length) + input_length) assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] def test_settokencertsignature(self): - ''' - Tests set token certificate signature + """Tests set token certificate signature To do: fix attribute value - ''' + + + """ gen_temp = {CKA_CLASS : CKO_SECRET_KEY, CKA_KEY_TYPE : CKK_AES, CKA_TOKEN : True, @@ -106,7 +103,6 @@ def test_settokencertsignature(self): access_level = CK_ULONG(1) customer_id = CK_ULONG(1) pub_template = gen_temp - pub_template_length = CK_ULONG(len(pub_template)) signature = (CK_BYTE*4000)() signature_length = CK_ULONG(4000) @@ -114,7 +110,6 @@ def test_settokencertsignature(self): access_level, customer_id, pub_template, - pub_template_length, signature, signature_length) assert ret == CKR_ATTRIBUTE_VALUE_INVALID, \ @@ -124,9 +119,7 @@ def test_settokencertsignature(self): def test_hainit(self): - ''' - Tests performs HA init - ''' + """Tests performs HA init""" ret, pubkey_h, prikey_h = c_generate_key_pair(self.h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, @@ -147,32 +140,25 @@ def test_hainit(self): def test_createloginchallenge(self): - ''' - Test create login challenge. + """Test create login challenge. This test requires PED based HSM. If performing this test on PWD based HSM return value is CKR_CANCEL. - ''' + + + """ user_type = CKU_CRYPTO_USER - challenge_length = CK_ULONG(12) challenge = cast(create_string_buffer("password1234", 12), CK_BYTE_PTR) - output_data_length = CK_ULONG(0) - output_data = (CK_BYTE*1)() ret = ca_createloginchallenge(self.h_session, user_type, - challenge_length, - challenge, - output_data_length, - output_data) + challenge) assert (ret == CKR_OK or ret == CKR_CANCEL), \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] def test_initializeremotepedvector(self): - ''' - Tests to initialize remote ped vector - ''' + """Tests to initialize remote ped vector""" ret = ca_initializeremotepedvector(self.h_session) # since not SO return value must be CKR_USER_NOT_AUTHORIZED assert ret == CKR_USER_NOT_AUTHORIZED, \ @@ -181,9 +167,7 @@ def test_initializeremotepedvector(self): def test_deleteremotepedvector(self): - ''' - Tests to delete remote ped vector - ''' + """Tests to delete remote ped vector""" ret = ca_deleteremotepedvector(self.h_session) # since not SO return value must be CKR_USER_NOT_AUTHORIZED assert ret == CKR_USER_NOT_AUTHORIZED, \ @@ -192,9 +176,7 @@ def test_deleteremotepedvector(self): def test_mtkrestore(self): - ''' - Tests MTK restore - ''' + """Tests MTK restore""" ret = ca_mtkrestore(self.admin_slot) assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ @@ -202,9 +184,7 @@ def test_mtkrestore(self): def test_mtkresplit(self): - ''' - Tests MTK resplit - ''' + """Tests MTK resplit""" ret = ca_mtkresplit(self.admin_slot) assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ @@ -212,9 +192,7 @@ def test_mtkresplit(self): def test_mtkzeroize(self): - ''' - Tests MTK zeroize - ''' + """Tests MTK zeroize""" ret = ca_mtkzeroize(self.admin_slot) assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ diff --git a/pycryptoki/tests/test_key_management.py b/pycryptoki/tests/test_key_management.py index a94692f..cd55d1a 100755 --- a/pycryptoki/tests/test_key_management.py +++ b/pycryptoki/tests/test_key_management.py @@ -20,38 +20,36 @@ import pytest -class TestAlgorithm(): - """ Test algorithm class """ +class TestAlgorithm: + """Test algorithm class""" h_session = 0 admin_slot = 0 @classmethod - def setup_class(self): - """ Setup class """ + def setup_class(cls): + """Setup class""" setup_for_tests(True, True, True) c_initialize_ex() @classmethod - def teardown_class(self): - """ Finalize tests """ + def teardown_class(cls): + """Finalize tests""" c_finalize_ex() def setup(self): - """ Setup test """ + """Setup test""" self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) def teardown(self): - """ Teardown test """ + """Teardown test""" c_logout_ex(self.h_session) c_close_session_ex(self.h_session) def test_generatemofn(self): - ''' - Test generate M of N - ''' + """Test generate M of N""" m_value = CK_ULONG(1) value = (CK_BYTE*16)() vector_count = CK_ULONG(2) @@ -80,9 +78,11 @@ def test_generatemofn(self): [CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET]) def test_modifyusagecount(self, command_type): - ''' - Test modify usage count - ''' + """Test modify usage count + + :param command_type: + + """ ret, key_handle = c_generate_key(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) diff --git a/pycryptoki/tests/test_key_usage.py b/pycryptoki/tests/test_key_usage.py index 9f54034..a62e6c0 100755 --- a/pycryptoki/tests/test_key_usage.py +++ b/pycryptoki/tests/test_key_usage.py @@ -14,38 +14,36 @@ import os import pytest -class TestAlgorithm(): - """ Test algorithm class """ +class TestAlgorithm: + """Test algorithm class""" h_session = 0 admin_slot = 0 @classmethod - def setup_class(self): - """ Setup class """ + def setup_class(cls): + """Setup class""" setup_for_tests(True, True, True) c_initialize_ex() @classmethod - def teardown_class(self): - """ Finalize tests """ + def teardown_class(cls): + """Finalize tests""" c_finalize_ex() def setup(self): - """ Setup test """ + """Setup test""" self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) def teardown(self): - """ Teardown test """ + """Teardown test""" c_logout_ex(self.h_session) c_close_session_ex(self.h_session) def test_clonemofn(self): - ''' - Test clone M of N - ''' + """Test clone M of N""" ret = ca_clonemofn(self.h_session) assert ret == CKR_SESSION_HANDLE_INVALID, \ "Return code should be " + \ @@ -54,9 +52,7 @@ def test_clonemofn(self): def test_duplicatemofn(self): - ''' - Test duplicate M of N - ''' + """Test duplicate M of N""" ret = ca_duplicatemofn(self.h_session) assert ret == CKR_USER_NOT_AUTHORIZED, \ "Return code should be " + \ diff --git a/pycryptoki/tests/test_keys.py b/pycryptoki/tests/test_keys.py index dc2735b..cbea7d8 100755 --- a/pycryptoki/tests/test_keys.py +++ b/pycryptoki/tests/test_keys.py @@ -1,12 +1,16 @@ from ctypes import cast, pointer +import ctypes +import logging +import os + +import pytest + from pycryptoki.cryptoki import CK_VOID_PTR, CK_ULONG from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ - CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP, \ - CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, CKM_DSA_PARAMETER_GEN_TEMP, \ - CKM_KCDSA_PARAMETER_GEN_TEMP, CKM_ARIA_KEY_GEN_TEMP, \ - CKM_DH_PKCS_PARAMETER_GEN_TEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, CKM_ARIA_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, \ @@ -14,18 +18,16 @@ CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, \ CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, \ - CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP, curve_list + CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, curve_list from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKR_OK, \ CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ - CKM_RC5_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ - CKM_DSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN, CKM_ARIA_KEY_GEN, \ - CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ + CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ + CKM_ARIA_KEY_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ - CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN, \ - CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS + CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, \ c_derive_key, c_generate_key_ex, _get_mechanism from pycryptoki.return_values import ret_vals_dictionary @@ -34,29 +36,30 @@ from pycryptoki.test_functions import verify_object_attributes from pycryptoki.tests.setup_for_tests import setup_for_tests from pycryptoki.token_management import get_token_by_label_ex -import ctypes -import logging -import os -import pytest logger = logging.getLogger(__name__) -class TestKeys(): +class TestKeys: + """ """ @classmethod - def setup_class(self): + def setup_class(cls): + """ """ setup_for_tests(True, True, True) c_initialize_ex() - + @classmethod - def teardown_class(self): + def teardown_class(cls): + """ """ c_finalize_ex() - + def setup(self): + """ """ admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=admin_slot) login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - + def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) @@ -79,18 +82,18 @@ def teardown(self): # (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX ]) def test_generate_key(self, key_type, key_template): - ''' - Tests generating a key, asserts that the operation returns correctly with key handles + """Tests generating a key, asserts that the operation returns correctly with key handles greater than 0 - - @param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) - @param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) - ''' + + :param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) + :param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) + + """ ret, key_handle = c_generate_key(self.h_session, key_type, key_template) assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] assert key_handle > 0, "The key handle returned should be non zero" - - + + @pytest.mark.parametrize(("key_type", "public_key_template", "private_key_template"), [ (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), @@ -105,21 +108,26 @@ def test_generate_key(self, key_type, key_template): # (CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP) #XXX ]) def test_generate_key_pair(self, key_type, public_key_template, private_key_template): - ''' - Tests generating a key pair, asserts that the operation returns correctly with key handles + """Tests generating a key pair, asserts that the operation returns correctly with key handles greater than 0. - - @param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) - @param public_key_template: The template to use for public key generation (ex. CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 - @param private_key_template: The template to use for private key generation (ex. CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 - ''' + + :param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) + :param public_key_template: The template to use for public key generation (ex. CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 + :param private_key_template: The template to use for private key generation (ex. CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 + + """ ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, key_type, public_key_template, private_key_template) assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] assert public_key_handle > 0, "The public key handle returned should be non zero" assert private_key_handle > 0, "The private key handle returned should be non zero" - - @pytest.mark.parametrize(("curve_type"), curve_list.keys()) + + @pytest.mark.parametrize("curve_type", curve_list.keys()) def test_generate_ecdsa_key_pairs(self, curve_type): + """ + + :param curve_type: + + """ print curve_list.keys() CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) @@ -146,22 +154,25 @@ def test_generate_ecdsa_key_pairs(self, curve_type): # (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX ]) def test_derive_key(self, key_type, key_template): - ''' - Tests deriving a key - ''' + """Tests deriving a key + + :param key_type: + :param key_template: + + """ h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) h_second_key = c_generate_key_ex(self.h_session, key_type, key_template) - + mech = _get_mechanism(CKM_CONCATENATE_BASE_AND_KEY) c_second_key = CK_ULONG(h_second_key) mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) mech.usParameterLen = ctypes.sizeof(c_second_key) - + ret, h_derived_key = c_derive_key(self.h_session, h_base_key, key_template, None, mech) assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + ret_vals_dictionary[ret] - + verify_object_attributes(self.h_session, h_derived_key, key_template) - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_object_create.py b/pycryptoki/tests/test_object_create.py index 7810f7d..2259041 100755 --- a/pycryptoki/tests/test_object_create.py +++ b/pycryptoki/tests/test_object_create.py @@ -14,46 +14,53 @@ logger = logging.getLogger(__name__) -class TestObjectCloning(): +class TestObjectCloning: + """ """ @classmethod - def setup_class(self): + def setup_class(cls): + """ """ setup_for_tests(True, True, True) c_initialize_ex() - + @classmethod - def teardown_class(self): + def teardown_class(cls): + """ """ c_finalize_ex() - + def setup(self): + """ """ admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=admin_slot) login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - + def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) def test_certificate_create(self): - ''' - Tests C_CreateObject with a certificate template and verifies the object's + """Tests C_CreateObject with a certificate template and verifies the object's attributes - ''' - + + + """ + ret, h_object = c_create_object(self.h_session, CERTIFICATE_TEMPLATE) assert ret == CKR_OK, "The result code of creating a certificate should be CKR_OK, not " + ret_vals_dictionary[ret] - + verify_object_attributes(self.h_session, h_object, CERTIFICATE_TEMPLATE) - + def test_data_create(self): - ''' - Tests C_CreateObject with a data template and verifies the object's + """Tests C_CreateObject with a data template and verifies the object's attributes - ''' + + + """ ret, h_object = c_create_object(self.h_session, DATA_TEMPLATE) assert ret == CKR_OK, "The result of creating a data object should be CKR_OK, not" + ret_vals_dictionary[ret] - + verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_sign_verify.py b/pycryptoki/tests/test_sign_verify.py index 78f9f70..d0917b5 100755 --- a/pycryptoki/tests/test_sign_verify.py +++ b/pycryptoki/tests/test_sign_verify.py @@ -1,10 +1,15 @@ +import logging +import os + +import pytest + from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD from pycryptoki.defines import CKU_USER, CKR_OK, CKM_RSA_PKCS, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKR_SIGNATURE_INVALID, CKM_DSA_KEY_PAIR_GEN, CKM_DSA + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA from pycryptoki.key_generator import c_generate_key_pair_ex from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ @@ -12,30 +17,33 @@ from pycryptoki.sign_verify import c_sign, c_verify from pycryptoki.tests.setup_for_tests import setup_for_tests from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest + logger = logging.getLogger(__name__) -class TestSignVerify(): +class TestSignVerify: + """ """ @classmethod - def setup_class(self): + def setup_class(cls): + """ """ setup_for_tests(True, True, True) c_initialize_ex() - + @classmethod - def teardown_class(self): + def teardown_class(cls): + """ """ c_finalize_ex() - + def setup(self): + """ """ admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=admin_slot) login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - + def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) - + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_RSA_PKCS), (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), @@ -44,25 +52,25 @@ def teardown(self): (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) ]) def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): - ''' - Verifies that signing a string and verifying that string works - - @param key_type: The handle of the key to sign the data with - @param pub_key_template: The template for the public key to be generated - @param priv_key_template: The template for the private key to be generated - @param sign_flavor: The flavor of the signature - ''' - + """Verifies that signing a string and verifying that string works + + :param key_type: The handle of the key to sign the data with + :param pub_key_template: The template for the public key to be generated + :param priv_key_template: The template for the private key to be generated + :param sign_flavor: The flavor of the signature + + """ + #Generate a key for the test h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - + data_to_sign = "This is some test string to sign." ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] - + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] - + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), @@ -70,26 +78,26 @@ def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_f (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) ]) def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): - ''' - Verifies that signing a string and verifying that string works doing the operation + """Verifies that signing a string and verifying that string works doing the operation in multiple parts with c_sign_update and c_verify_update - - @param key_type: The handle of the key to sign the data with - @param pub_key_template: The template for the public key to be generated - @param priv_key_template: The template for the private key to be generated - @param sign_flavor: The flavor of the signature - ''' - + + :param key_type: The handle of the key to sign the data with + :param pub_key_template: The template for the public key to be generated + :param priv_key_template: The template for the private key to be generated + :param sign_flavor: The flavor of the signature + + """ + #Generate a key for the test h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - + data_to_sign = ["a" * 1024, "b" * 1024] ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] - + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_supporting_operations.py b/pycryptoki/tests/test_supporting_operations.py index 274a66c..a7f852c 100755 --- a/pycryptoki/tests/test_supporting_operations.py +++ b/pycryptoki/tests/test_supporting_operations.py @@ -13,50 +13,54 @@ logger = logging.getLogger(__name__) -class TestSupportingOperations(): +class TestSupportingOperations: + """ """ @classmethod - def setup_class(self): + def setup_class(cls): + """ """ setup_for_tests(True, True, True) c_initialize_ex() - + @classmethod - def teardown_class(self): + def teardown_class(cls): + """ """ c_finalize_ex() - + def setup(self): + """ """ admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=admin_slot) login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - + def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) def test_rng(self): - ''' - Tests generating a random number - ''' + """Tests generating a random number""" length = 15 ret, random_string = c_generate_random(self.h_session, length) assert ret == CKR_OK, "C_GenerateRandom should return CKR_OK, instead it returned " + ret_vals_dictionary[ret] assert len(random_string) == length, "The length of the random string should be the same as the length of the requested data." - + def test_seeded_rng(self): - ''' - Tests that seeding the random number generator with the same data will + """Tests that seeding the random number generator with the same data will generate the same random number - ''' + + + """ seed = "k" * 1024 ret = c_seed_random(self.h_session, seed) assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, it returned " + ret_vals_dictionary[ret] - + random_string_one = c_generate_random_ex(self.h_session, 10) - + ret = c_seed_random(self.h_session, seed) assert ret == CKR_OK, "Seeding the random number generator a second time shouldn't return an error, it returned " + ret_vals_dictionary[ret] - + random_string_two = c_generate_random_ex(self.h_session, 10) - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) \ No newline at end of file + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_usage_limit_and_count.py b/pycryptoki/tests/test_usage_limit_and_count.py index 74e5470..34c5d90 100755 --- a/pycryptoki/tests/test_usage_limit_and_count.py +++ b/pycryptoki/tests/test_usage_limit_and_count.py @@ -1,15 +1,19 @@ -''' +""" Created on Aug 15, 2012 @author: root -''' +""" + +import logging +import os + +import pytest -from ctypes import * from pycryptoki.attributes import Attributes from pycryptoki.cryptoki import CK_ULONG, C_SetAttributeValue from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP -from pycryptoki.defaults import CO_PASSWORD, ADMIN_PARTITION_LABEL +from pycryptoki.defaults import CO_PASSWORD, ADMIN_PARTITION_LABEL from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ CKM_DES_ECB, CKM_RSA_PKCS, CKR_OK, CKR_KEY_NOT_ACTIVE, CKU_USER, CKM_AES_ECB @@ -22,18 +26,16 @@ from pycryptoki.test_functions import LunaException from pycryptoki.tests.setup_for_tests import setup_for_tests from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - logger = logging.getLogger(__name__) -class TestUsageLimitAndCount(): - +class TestUsageLimitAndCount: + """ """ + h_session = 0 - + def setup(self): + """ """ setup_for_tests(True, True, True) c_initialize_ex() admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) @@ -42,60 +44,65 @@ def setup(self): def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) c_finalize() - + def test_set_attribute_usage_limit_sym(self): - """ Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on an symmetric crypto object Procedure: Generate a DES Key Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 5 - Use C_getAttributeValue to verify """ - + Use C_getAttributeValue to verify + + + """ + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an symmetric crypto object") + an symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, CKA_USAGE_LIMIT : 5} h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) usage_limit = 5 - + key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) # print c_struct[CKA_USAGE_LIMIT] usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(int(usage_val_out))) - assert usage_limit== usage_val_out, "reported USAGE LIMIT does not match" + assert usage_limit== usage_val_out, "reported USAGE LIMIT does not match" + - def test_usage_limit_attribute_check_sym_des(self): - """ - Test: Verify that CKA_USAGE_COUNT attribute increments as user + """Test: Verify that CKA_USAGE_COUNT attribute increments as user use the symmetric crypto object Procedure: Generate a DES Key Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 Use des key twice for encryption Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + + """ logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) usage_count = 2 @@ -103,40 +110,41 @@ def test_usage_limit_attribute_check_sym_des(self): logger.info("Called c-generate: Key handle -" + str(h_key)) return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) - + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - - - - + + + + def test_usage_limit_attribute_check_sym_aes(self): - """ - Test: Verify that CKA_USAGE_COUNT attribute increments as user + """Test: Verify that CKA_USAGE_COUNT attribute increments as user use the symmetric crypto object Procedure: Generate a DES Key Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 Use aes key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + + """ logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) usage_count = 2 @@ -145,39 +153,40 @@ def test_usage_limit_attribute_check_sym_aes(self): return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) - + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) - - + + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - + def test_set_attribute_usage_limit_Assym(self): - """ - Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on an assymetric crypto object Procedure: Generate a RSA key pair Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 on RSA public key - Use C_getAttributeValue to verify + Use C_getAttributeValue to verify + + """ - + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an assymetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + an assymetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, CKA_USAGE_LIMIT : 2} key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) @@ -185,142 +194,145 @@ def test_set_attribute_usage_limit_Assym(self): return_val = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) if return_val != CKR_OK: raise LunaException(return_val, 'C_SetAttributeValue', "Setting up attribute") - + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) - assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" - - + assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + + + - def test_usage_limit_attribute_check_Assym(self): - """ - Test: Verify that CKA_USAGE_COUNT attribute increments as user + """Test: Verify that CKA_USAGE_COUNT attribute increments as user use the assymetric crypto object Procedure: Generate a RSA Key pair Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 Use RSA public key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + + """ - + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ use the assymetric crypto object") - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, CKA_USAGE_LIMIT : 2} usage_count = 2 key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) - - + + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - + + c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): - """ - Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE if user try to use crypto object more than limit set on CKA_USAGE_LIMIT Procedure: Generate a 3DES key Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 Use RSA public key 3 times for encryption + + """ - + logger.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + CKA_USAGE_LIMIT : 2} key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) + us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) return_val = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) if return_val != CKR_OK: raise LunaException(return_val, 'C_setAttributeValue', "Setting up limit attribute") - + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) return_val = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) logger.info("Called C_Encrypt, return code: " + str(return_val)) - + c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - + + usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - - - + + + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): - """ - Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE if user try to use crypto object more than limit set on CKA_USAGE_LIMIT Procedure: Generate a RSA Key pair Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 Use RSA public key 3 times for encryption + + """ - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, CKA_USAGE_LIMIT : 2} key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) - + logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - + return_val = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - logger.info("Called C_Encrypt, return code: " + str(return_val)) + logger.info("Called C_Encrypt, return code: " + str(return_val)) c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + - if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) - + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) + diff --git a/pycryptoki/tests/test_wrap_unwrap.py b/pycryptoki/tests/test_wrap_unwrap.py index b101790..373c7e3 100755 --- a/pycryptoki/tests/test_wrap_unwrap.py +++ b/pycryptoki/tests/test_wrap_unwrap.py @@ -1,87 +1,93 @@ +import logging +import os + +import pytest + from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_DES_UNWRAP_TEMP from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ - CKA_LABEL, CKM_DES_ECB + CKM_DES_ECB from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt -from pycryptoki.key_generator import c_generate_key, c_generate_key_ex +from pycryptoki.key_generator import c_generate_key_ex from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex from pycryptoki.test_functions import verify_object_attributes from pycryptoki.tests.setup_for_tests import setup_for_tests from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest logger = logging.getLogger(__name__) -class TestWrappingKeys(): +class TestWrappingKeys: + """ """ @classmethod - def setup_class(self): + def setup_class(cls): + """ """ setup_for_tests(True, True, True) c_initialize_ex() - + @classmethod - def teardown_class(self): + def teardown_class(cls): + """ """ c_finalize_ex() - + def setup(self): + """ """ admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) self.h_session = c_open_session_ex(slot_num=admin_slot) login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - + def teardown(self): + """ """ c_logout_ex(self.h_session) c_close_session_ex(self.h_session) def test_wrap_unwrap_key(self): - ''' - Tests the attributes of an unwrapped key are idential to the original key - ''' + """Tests the attributes of an unwrapped key are idential to the original key""" h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - + #Wrap the key ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - + #Unwrap the Key ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - + #Verify all of the attributes against the originally generated attributes verify_object_attributes(self.h_session, h_unwrapped_key, CKM_DES_KEY_GEN_TEMP) - + def test_encrypt_wrap_unwrap_decrypt_key(self): - ''' - Tests encrypting some data with a key. Then wrapping and unwrapping the key + """Tests encrypting some data with a key. Then wrapping and unwrapping the key and using the unwrapped key to decrypt the data. It then compares the data to the original data. - ''' + + + """ h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - + #Encrypt some data data_to_encrypt = "a" * 512 ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - + #Wrap the key ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - + #Unwrap the Key ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - + #Decrypt the data ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_unwrapped_key, encrypted_data) assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) - + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) \ No newline at end of file + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index fd3dd0e..518786f 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -1,29 +1,31 @@ -''' +""" Created on Aug 24, 2012 @author: mhughes -''' +""" from ctypes import byref, cast, create_string_buffer +import logging + from pycryptoki.cryptoki import C_InitToken, CK_ULONG, CK_CHAR_PTR, \ C_GetSlotList, CK_BBOOL, CK_SLOT_ID, C_GetMechanismList, CK_MECHANISM_TYPE, \ CK_MECHANISM_TYPE_PTR, CK_MECHANISM_INFO, C_GetMechanismInfo from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT from pycryptoki.defines import CKR_OK -from pycryptoki.session_management import c_get_token_info, get_slot_info +from pycryptoki.session_management import c_get_token_info from pycryptoki.test_functions import make_error_handle_function -import logging logger = logging.getLogger(__name__) + def c_init_token(slot_num, password, token_label='Main Token'): - ''' - Initializes at token at a given slot with the proper password and label - @param slot_num: The index of the slot to c_initialize a token in - @param password: The password to c_initialize the slot with - @param token_label: The label to c_initialize the slot with - - @return: The result code - ''' + """Initializes at token at a given slot with the proper password and label + + :param slot_num: The index of the slot to c_initialize a token in + :param password: The password to c_initialize the slot with + :param token_label: The label to c_initialize the slot with (Default value = 'Main Token') + :returns: The result code + + """ if password == '': logger.info("C_InitToken: Initializing token. slot=" + str( slot_num) + ", label='" + token_label + "', password='" + password + "'") @@ -31,25 +33,30 @@ def c_init_token(slot_num, password, token_label='Main Token'): CK_ULONG(0), cast(create_string_buffer(token_label), CK_CHAR_PTR)) return ret else: - logger.info("C_InitToken: Initializing token. slot="+ str(slot_num) + ", label='" + token_label + "', password='" + password + "'") - ret = C_InitToken(CK_ULONG(slot_num), cast(create_string_buffer(password), CK_CHAR_PTR), CK_ULONG(len(password)), cast(create_string_buffer(token_label), CK_CHAR_PTR)) + logger.info("C_InitToken: Initializing token. slot=" + str( + slot_num) + ", label='" + token_label + "', password='" + password + "'") + ret = C_InitToken(CK_ULONG(slot_num), cast(create_string_buffer(password), CK_CHAR_PTR), + CK_ULONG(len(password)), cast(create_string_buffer(token_label), CK_CHAR_PTR)) return ret + + c_init_token_ex = make_error_handle_function(c_init_token) + def get_token_by_label(label): - ''' - Iterates through all the tokens and returns the first token that + """Iterates through all the tokens and returns the first token that has a label that is identical to the one that is passed in - - @param label:The label of the token to search for - @return: The result code, The slot of the token - ''' - - if label == ADMIN_PARTITION_LABEL: #XXX the admin partition's label changes depending on the boards state -# ret, slot_info = get_slot_info("Viper") -# return ret, slot_info.keys()[1] + + :param label: The label of the token to search for + :returns: The result code, The slot of the token + + """ + + if label == ADMIN_PARTITION_LABEL: # XXX the admin partition's label changes depending on the boards state + # ret, slot_info = get_slot_info("Viper") + # return ret, slot_info.keys()[1] return CKR_OK, ADMIN_SLOT - + us_count = CK_ULONG(0) ret = C_GetSlotList(CK_BBOOL(1), None, byref(us_count)) if ret != CKR_OK: return ret, None @@ -62,17 +69,20 @@ def get_token_by_label(label): ret, token_info = c_get_token_info(slot) if token_info['label'] == label: return ret, slot - + raise Exception("Slot with label " + str(label) + " not found.") -get_token_by_label_ex = make_error_handle_function(get_token_by_label) + + +get_token_by_label_ex = make_error_handle_function(get_token_by_label) + def c_get_mechanism_list(slot): - ''' - Gets the list of mechanisms from the HSM - - @param slot: The slot number to get the mechanism list on - @return: The result code, A python dictionary representing the mechanism list - ''' + """Gets the list of mechanisms from the HSM + + :param slot: The slot number to get the mechanism list on + :returns: The result code, A python dictionary representing the mechanism list + + """ count = CK_ULONG() ret = C_GetMechanismList(CK_SLOT_ID(slot), None, byref(count)) last_count = count @@ -81,23 +91,27 @@ def c_get_mechanism_list(slot): ret = C_GetMechanismList(CK_SLOT_ID(slot), CK_MECHANISM_TYPE_PTR(mech_list), byref(count)) if ret != CKR_OK: return ret, None if last_count != count: raise Exception("Mechanism list count was not consistent between function calls") - + ret_list = [] for i in range(0, count.value): ret_list.append(mech_list[i]) return ret, ret_list + + c_get_mechanism_list_ex = make_error_handle_function(c_get_mechanism_list) + def c_get_mechanism_info(slot, mechanism_type): - ''' - Gets a mechanism's info - - @param slot: The slot to query - @param mechanism_type: The type of the mechanism to get the information for - - @return: The result code, The mechanism info - ''' + """Gets a mechanism's info + + :param slot: The slot to query + :param mechanism_type: The type of the mechanism to get the information for + :returns: The result code, The mechanism info + + """ mech_info = CK_MECHANISM_INFO() ret = C_GetMechanismInfo(CK_ULONG(slot), CK_MECHANISM_TYPE(mechanism_type), byref(mech_info)) return ret, mech_info -c_get_mechanism_info_ex = make_error_handle_function(c_get_mechanism_info) \ No newline at end of file + + +c_get_mechanism_info_ex = make_error_handle_function(c_get_mechanism_info) diff --git a/pycryptoki/utils/__init__.py b/pycryptoki/utils/__init__.py old mode 100755 new mode 100644 diff --git a/pycryptoki/utils/common_utils.py b/pycryptoki/utils/common_utils.py old mode 100755 new mode 100644 index 3913fa7..17c1fa2 --- a/pycryptoki/utils/common_utils.py +++ b/pycryptoki/utils/common_utils.py @@ -1,6 +1,7 @@ import datetime #Utility to set a default logfile name def setLogFile(): + """ """ dt = str(datetime.datetime.now()).strip() logname = "./test_" + dt + ".log" return logname From 316773150dd65e77f49ada619dd0768ca1312530 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 17 Jun 2015 13:46:59 -0400 Subject: [PATCH 008/109] LA-1127 Default to empty string instead of userpin Change-Id: I793fc4bbb0633265c75de1d0b09b76a8f9f2d544 --- pycryptoki/session_management.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 821cf5e..789e4fa 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -74,7 +74,7 @@ def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): c_open_session_ex = make_error_handle_function(c_open_session) -def login(h_session, slot_num=1, password="userpin", user_type=1): +def login(h_session, slot_num=1, password="", user_type=1): """Login to the HSM :param h_session: Current session @@ -311,7 +311,7 @@ def c_close_all_sessions(slot): c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) -def ca_create_container(h_session, storage_size, password='userpin', label='Inserted Token'): +def ca_create_container(h_session, storage_size, password='', label='Inserted Token'): """Inserts a token into a slot without a Security Officer on the token :param h_session: Current session From 1b89d76302f07819b89f8ae0658019779d02cc77 Mon Sep 17 00:00:00 2001 From: Kevin Safford Date: Thu, 18 Jun 2015 15:26:11 -0400 Subject: [PATCH 009/109] LA-1128 Add custom mech functionality to sigver Add a function to make it possible to specify different hash algorithms for a given signing/verifying mechanism. Change-Id: I0a878106774e7b00980255fc628bd1ce0b603962 --- pycryptoki/sign_verify.py | 263 ++++++++++++++++++++++++-------------- 1 file changed, 168 insertions(+), 95 deletions(-) diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index c67db80..6446a56 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -1,8 +1,6 @@ -from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p -import logging - from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign +from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ @@ -14,107 +12,166 @@ from pycryptoki.encryption import _get_string_from_list, \ get_c_data_to_sign_or_encrypt from pycryptoki.test_functions import make_error_handle_function +import logging + +LOG = logging.getLogger(__name__) + +def get_custom_mech_for_sigver(sigver_mech, algorithm, mask=None, salt_len=8): + """ + Generate a mechanism for signing/verifying operations with RSA PKCS PSS + variants. Use the specified algorithm in the returned CK_MECHANISM object. + + Note: + + PKCS #1 recommends using a mask generation algorithm based on the hash + algorithm used for hashing. I.e., if CKM_SHA224 is used to hash, + CKG_MGF1_SHA224 _should_ be used for mask generation. + + Algorithm must be one of: + CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, CKM_SHA512 + + Mask must be one of: + CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, CKG_MGF1_SHA512 -logger = logging.getLogger(__name__) + :param sigver_mech: signing/verifying mechanism + :param algorithm: hashing algorithm + :param mask: mask generation function; if None, use matching + :param salt_len: length of salt + :return: CK_MECHANISM with PSS parameters configured + """ + if mask is None: + masks = {CKM_SHA_1: CKG_MGF1_SHA1, + CKM_SHA224: CKG_MGF1_SHA224, + CKM_SHA256: CKG_MGF1_SHA256, + CKM_SHA384: CKG_MGF1_SHA384, + CKM_SHA512: CKG_MGF1_SHA512} + mask = masks[algorithm] + + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(sigver_mech) + params = CK_RSA_PKCS_PSS_PARAMS() + params.hashAlg = CK_ULONG(algorithm) + params.mgf = CK_ULONG(mask) + params.usSaltLen = CK_ULONG(salt_len) + + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params)) + return mech def get_mechanism_for_sigver(flavour): - """Tries to build a default mechanism if none is provided, + """ + Try to build a default mechanism if none is provided, most mechanisms just need the .pParameter field to be null. If they don't the mechanism can be instantiated here. - :param flavour: - + :param flavour: signing/verifying mechanism + :return: CK_MECHANISM with PSS parameters configured """ mech = CK_MECHANISM() mech.mechanism = CK_MECHANISM_TYPE(flavour) default_salt_len = 8 - if flavour == CKM_RSA_PKCS_PSS or \ - flavour == CKM_SHA1_RSA_PKCS_PSS: - - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA_1) - p.mgf = CK_ULONG(CKG_MGF1_SHA1) - p.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) + if flavour == CKM_RSA_PKCS_PSS or flavour == CKM_SHA1_RSA_PKCS_PSS: + params = CK_RSA_PKCS_PSS_PARAMS() + params.hashAlg = CK_ULONG(CKM_SHA_1) + params.mgf = CK_ULONG(CKG_MGF1_SHA1) + params.usSaltLen = CK_ULONG(default_salt_len) + + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params)) elif flavour == CKM_SHA224_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA224) - p.mgf = CK_ULONG(CKG_MGF1_SHA224) - p.usSaltLen = CK_ULONG(default_salt_len) + params = CK_RSA_PKCS_PSS_PARAMS() + params.hashAlg = CK_ULONG(CKM_SHA224) + params.mgf = CK_ULONG(CKG_MGF1_SHA224) + params.usSaltLen = CK_ULONG(default_salt_len) - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params)) elif flavour == CKM_SHA256_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA256) - p.mgf = CK_ULONG(CKG_MGF1_SHA256) - p.usSaltLen = CK_ULONG(default_salt_len) + params = CK_RSA_PKCS_PSS_PARAMS() + params.hashAlg = CK_ULONG(CKM_SHA256) + params.mgf = CK_ULONG(CKG_MGF1_SHA256) + params.usSaltLen = CK_ULONG(default_salt_len) - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params)) elif flavour == CKM_SHA384_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA384) - p.mgf = CK_ULONG(CKG_MGF1_SHA384) - p.usSaltLen = CK_ULONG(default_salt_len) + params = CK_RSA_PKCS_PSS_PARAMS() + params.hashAlg = CK_ULONG(CKM_SHA384) + params.mgf = CK_ULONG(CKG_MGF1_SHA384) + params.usSaltLen = CK_ULONG(default_salt_len) - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params)) elif flavour == CKM_SHA512_RSA_PKCS_PSS: - p = CK_RSA_PKCS_PSS_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA512) - p.mgf = CK_ULONG(CKG_MGF1_SHA512) - p.usSaltLen = CK_ULONG(default_salt_len) + params = CK_RSA_PKCS_PSS_PARAMS() + params.hashAlg = CK_ULONG(CKM_SHA512) + params.mgf = CK_ULONG(CKG_MGF1_SHA512) + params.usSaltLen = CK_ULONG(default_salt_len) - mech.pParameter = cast(pointer(p), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(p)) + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params)) else: mech.pParameter = CK_VOID_PTR(0) mech.usParameterLen = CK_ULONG(0) return mech - -def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None): - """Performs a C_SignInit and C_Sign operation on some data +def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=None): + """ + Performs a C_SignInit and C_Sign operation on some data :param h_session: The current session :param sign_flavor: The flavour of signing to do :param data_to_sign: The data to sign, either a string or a list of strings. If this is a list - a multipart operation will be used - :param h_key: The key to sign the data with - :param mech: The mechanism to use, if None a blank mechanism will be created based on the sign_flavor (Default value = None) - :returns: The result code, A python string represeting the signature + a multipart operation will be used (using C_...Update and C_...Final) + ex: + + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", + "It will operate on these strings in parts"] + + :param h_key: The key to sign the data with + :param mech: The mechanism to use, if None a blank mechanism will be created based on the + sign_flavor + :param algorithm: The hash algorithm used on data_to_sign; only necessary for RSA PKCS PSS + :return: The result code, A python string representing the signature """ - # Get the mechanism + #Get the mechanism if mech is None: mech = get_mechanism_for_sigver(sign_flavor) - # Initialize the sign operation + if algorithm is not None: + mech = get_custom_mech_for_sigver(sign_flavor, algorithm) + + #Initialize the sign operation ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) - if ret != CKR_OK: return ret, None + if ret != CKR_OK: + return ret, None - # if a list is passed out do a sign operation on each string in the list, otherwise just do one sign operation + #if a list is passed out do a sign operation on each string in the list, + #otherwise just do one sign operation is_multi_part_operation = isinstance(data_to_sign, list) or isinstance(data_to_sign, tuple) if is_multi_part_operation: - ret, signature_string = do_multipart_sign_or_digest(h_session, C_SignUpdate, C_SignFinal, data_to_sign) + ret, signature_string = do_multipart_sign_or_digest(h_session, + C_SignUpdate, + C_SignFinal, + data_to_sign) else: - # Prepare the data to sign + #Prepare the data to sign c_data_to_sign = get_c_data_to_sign_or_encrypt(data_to_sign) plain_date_len = CK_ULONG(len(data_to_sign)) - # Get the length of the output + #Get the length of the output sign_len = CK_ULONG() ret = C_Sign(h_session, c_data_to_sign, plain_date_len, None, byref(sign_len)) - if ret != CKR_OK: return ret, None + if ret != CKR_OK: + return ret, None - # Actually get the signature + #Actually get the signature signature_buffer = create_string_buffer("", sign_len.value) signature = cast(signature_buffer, CK_BYTE_PTR) ret = C_Sign(h_session, c_data_to_sign, plain_date_len, signature, byref(sign_len)) @@ -125,19 +182,17 @@ def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None): signature_string = convert_ck_char_array_to_string(ck_char_array)[0:sign_len.value] return ret, signature_string - - c_sign_ex = make_error_handle_function(c_sign) - def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, input_data_list): - """Does a multipart sign or digest operation + """ + Do a multipart sign or digest operation - :param h_session: - :param c_update_function: - :param c_final_function: + :param h_session: The current session + :param c_update_function: signing update function + :param c_final_function: signing finalization function :param input_data_list: - + :return: The result code, A python string representing the signature """ max_data_chunk_size = 0xfff0 plain_data_len = len(_get_string_from_list(input_data_list)) @@ -148,12 +203,12 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, while remaining_length > 0: current_chunk = input_data_list[i] - # Prepare arguments for decrypt update operation + #Prepare arguments for decrypt update operation current_chunk_len = min(len(current_chunk), remaining_length) if current_chunk_len > max_data_chunk_size: - raise Exception( - "chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + + str(max_data_chunk_size)) data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) @@ -164,25 +219,26 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, i += 1 - # Finalizing multipart decrypt operation + #Finalizing multipart decrypt operation out_data_len = CK_ULONG(max_data_chunk_size) output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) ret = c_final_function(h_session, output, byref(out_data_len)) - # Get output + #Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] return ret, python_string - def do_multipart_verify(h_session, input_data_list, signature): - """Does a multipart verify operation + """ + Do a multipart verify operation - :param h_session: - :param input_data_list: - :param signature: + :param h_session: The current session + :param input_data_list: list of data to verify with + :param signature: signature to verify + :return: The result code """ max_data_chunk_size = 0xfff0 plain_data_len = len(_get_string_from_list(input_data_list)) @@ -192,12 +248,12 @@ def do_multipart_verify(h_session, input_data_list, signature): while remaining_length > 0: current_chunk = input_data_list[i] - # Prepare arguments for decrypt update operation + #Prepare arguments for decrypt update operation current_chunk_len = min(len(current_chunk), remaining_length) if current_chunk_len > max_data_chunk_size: - raise Exception( - "chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + + str(max_data_chunk_size)) data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) @@ -208,54 +264,71 @@ def do_multipart_verify(h_session, input_data_list, signature): i += 1 - # Finalizing multipart decrypt operation + #Finalizing multipart decrypt operation out_data_len = CK_ULONG(len(signature)) output = cast(get_c_data_to_sign_or_encrypt(signature), CK_BYTE_PTR) ret = C_VerifyFinal(h_session, output, out_data_len) return ret - -def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=None): - """Returns the result code of C_Verify which indicates whether or not the signature is +def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=None, algorithm=None): + """ + Return the result code of C_Verify which indicates whether or not the signature is valid. :param h_session: The current session :param h_key: The key handle to verify the signature against :param verify_flavor: The flavour of the mechanism to verify against - :param data_to_verify: The data to verify, either a string or a list of strings. If this is a list - a multipart operation will be used + :param data_to_verify: The data to verify, either a string or a list of strings. If this is a + list, a multipart operation will be used (using C_...Update and + C_...Final) + + ex: + + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", + "It will operate on these strings in parts"] + :param signature: The signature of the data :param mech: The mechanism to use, if None is specified the mechanism will - try to be automatically obtained (Default value = None) - :returns: s The result code - + try to be automatically obtained + :param algorithm: The hash algorithm used on data_to_sign; only necessary for RSA PKCS PSS + :return: The result code """ - # Get the mechanism + #Get the mechanism if mech is None: mech = get_mechanism_for_sigver(verify_flavor) - # Initialize the verify operation + if algorithm is not None: + mech = get_custom_mech_for_sigver(verify_flavor, algorithm) + + #Initialize the verify operation ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) - if ret != CKR_OK: return ret + if ret != CKR_OK: + return ret - # if a list is passed out do a verify operation on each string in the list, otherwise just do one verify operation + #if a list is passed out do a verify operation on each string in the list, + #otherwise just do one verify operation is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(data_to_verify, tuple) if is_multi_part_operation: ret = do_multipart_verify(h_session, data_to_verify, signature) else: - # Prepare the data to verify + #Prepare the data to verify c_data_to_verify = get_c_data_to_sign_or_encrypt(data_to_verify) plain_date_len = CK_ULONG(len(data_to_verify)) c_signature = get_c_data_to_sign_or_encrypt(signature) - # Actually verify the data - ret = C_Verify(h_session, c_data_to_verify, plain_date_len, c_signature, CK_ULONG(len(signature))) + #Actually verify the data + ret = C_Verify(h_session, + c_data_to_verify, + plain_date_len, + c_signature, + CK_ULONG(len(signature))) return ret - c_verify_ex = make_error_handle_function(c_verify) + From cdcaff188ae4110ff1ecc044051c73625bdbf08d Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 15 Jul 2015 08:35:46 -0400 Subject: [PATCH 010/109] LA-1184 Added Capability/Policy getters Change-Id: I33ea13ee1690af888b465ba30c65bb74b9059443 --- pycryptoki/daemon/rpyc_pycryptoki.py | 33 +++++++---- pycryptoki/token_management.py | 87 ++++++++++++++++++++++++++-- 2 files changed, 104 insertions(+), 16 deletions(-) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 9980060..9941745 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -21,10 +21,11 @@ from _ctypes import pointer from ctypes import cast import ctypes +import logging import rpyc -import pycryptoki +import pycryptoki from pycryptoki.backup import (ca_open_secure_token, ca_open_secure_token_ex, ca_close_secure_token, ca_close_secure_token_ex, ca_extract, ca_extract_ex, @@ -49,7 +50,8 @@ c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex) from pycryptoki.policy_management import (ca_set_hsm_policy, ca_set_hsm_policy_ex, - ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, + ca_set_destructive_hsm_policy, + ca_set_destructive_hsm_policy_ex, ca_set_container_policy, ca_set_container_policy_ex) from pycryptoki.session_management import (c_initialize, c_initialize_ex, c_finalize, c_finalize_ex, @@ -67,24 +69,29 @@ ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID, ca_closeapplicationID_ex, ca_restart, ca_restart_ex, - ca_delete_container_with_handle_ex, ca_delete_container_with_handle, + ca_delete_container_with_handle_ex, + ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex) from pycryptoki.sign_verify import (c_sign, c_sign_ex, c_verify, c_verify_ex) from pycryptoki.token_management import (c_init_token, c_init_token_ex, c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, c_get_mechanism_info_ex, - get_token_by_label, get_token_by_label_ex) + get_token_by_label, get_token_by_label_ex, + ca_get_hsm_policy_set_ex, ca_get_hsm_policy_set, + ca_get_hsm_capability_set_ex, ca_get_hsm_capability_set) from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, ca_init_audit, ca_init_audit_ex, ca_time_sync, ca_time_sync_ex) from pycryptoki.cryptoki import CK_VOID_PTR from pycryptoki.key_generator import _get_mechanism from pycryptoki.hsm_management import (c_performselftest, c_performselftest_ex, - ca_settokencertificatesignature, ca_settokencertificatesignature_ex, + ca_settokencertificatesignature, + ca_settokencertificatesignature_ex, ca_hainit, ca_hainit_ex, ca_createloginchallenge, ca_createloginchallenge_ex, - ca_initializeremotepedvector, ca_initializeremotepedvector_ex, + ca_initializeremotepedvector, + ca_initializeremotepedvector_ex, ca_deleteremotepedvector, ca_deleteremotepedvector_ex, ca_mtkrestore, ca_mtkrestore_ex, ca_mtkresplit, ca_mtkresplit_ex, @@ -94,7 +101,6 @@ from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, ca_duplicatemofn_ex) from pycryptoki.cryptoki import * -import logging logger = logging.getLogger(__name__) @@ -148,6 +154,10 @@ def _rpyc_getattr(self, name): exposed_c_get_mechanism_list_ex = staticmethod(c_get_mechanism_list_ex) exposed_c_get_mechanism_info = staticmethod(c_get_mechanism_info) exposed_c_get_mechanism_info_ex = staticmethod(c_get_mechanism_info_ex) + exposed_ca_get_hsm_policy_set = staticmethod(ca_get_hsm_policy_set) + exposed_ca_get_hsm_policy_set_ex = staticmethod(ca_get_hsm_policy_set_ex) + exposed_ca_get_hsm_capability_set = staticmethod(ca_get_hsm_capability_set) + exposed_ca_get_hsm_capability_set_ex = staticmethod(ca_get_hsm_capability_set_ex) # session_management.py exposed_c_initialize = staticmethod(c_initialize) @@ -282,10 +292,12 @@ def _rpyc_getattr(self, name): exposed_ca_duplicatemofn_ex = staticmethod(ca_duplicatemofn_ex) @staticmethod - def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): + def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_flavor, + mech=None): """#key_generator.py - Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side + Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the + daemon side because it involves pointers. :param h_session: @@ -308,7 +320,8 @@ def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_ def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): """#key_generator.py - Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the daemon side + Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the + daemon side because it involves pointers. :param h_session: diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index 518786f..e6ef4a5 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -6,11 +6,25 @@ from ctypes import byref, cast, create_string_buffer import logging -from pycryptoki.cryptoki import C_InitToken, CK_ULONG, CK_CHAR_PTR, \ - C_GetSlotList, CK_BBOOL, CK_SLOT_ID, C_GetMechanismList, CK_MECHANISM_TYPE, \ - CK_MECHANISM_TYPE_PTR, CK_MECHANISM_INFO, C_GetMechanismInfo +# Cryptoki Constants +from pycryptoki.cryptoki import (CK_ULONG, + CK_CHAR_PTR, + CK_BBOOL, + CK_SLOT_ID, + CK_MECHANISM_TYPE, + CK_MECHANISM_TYPE_PTR, + CK_MECHANISM_INFO) from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT from pycryptoki.defines import CKR_OK + + +# Cryptoki functions. +from pycryptoki.cryptoki import (C_InitToken, + C_GetSlotList, + C_GetMechanismList, + C_GetMechanismInfo, + CA_GetHSMCapabilitySet, + CA_GetHSMPolicySet) from pycryptoki.session_management import c_get_token_info from pycryptoki.test_functions import make_error_handle_function @@ -36,7 +50,8 @@ def c_init_token(slot_num, password, token_label='Main Token'): logger.info("C_InitToken: Initializing token. slot=" + str( slot_num) + ", label='" + token_label + "', password='" + password + "'") ret = C_InitToken(CK_ULONG(slot_num), cast(create_string_buffer(password), CK_CHAR_PTR), - CK_ULONG(len(password)), cast(create_string_buffer(token_label), CK_CHAR_PTR)) + CK_ULONG(len(password)), + cast(create_string_buffer(token_label), CK_CHAR_PTR)) return ret @@ -52,7 +67,8 @@ def get_token_by_label(label): """ - if label == ADMIN_PARTITION_LABEL: # XXX the admin partition's label changes depending on the boards state + if label == ADMIN_PARTITION_LABEL: # XXX the admin partition's label changes depending on + # the boards state # ret, slot_info = get_slot_info("Viper") # return ret, slot_info.keys()[1] return CKR_OK, ADMIN_SLOT @@ -90,7 +106,8 @@ def c_get_mechanism_list(slot): mech_list = (CK_MECHANISM_TYPE * count.value)() ret = C_GetMechanismList(CK_SLOT_ID(slot), CK_MECHANISM_TYPE_PTR(mech_list), byref(count)) if ret != CKR_OK: return ret, None - if last_count != count: raise Exception("Mechanism list count was not consistent between function calls") + if last_count != count: raise Exception( + "Mechanism list count was not consistent between function calls") ret_list = [] for i in range(0, count.value): @@ -115,3 +132,61 @@ def c_get_mechanism_info(slot, mechanism_type): c_get_mechanism_info_ex = make_error_handle_function(c_get_mechanism_info) + + +def ca_get_hsm_capability_set(slot): + """ + Get the capabilities of the given slot. + + :param int slot: Target slot number + :return: retcode, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_ULONG(slot) + cap_id_count = CK_ULONG() + cap_val_count = CK_ULONG() + ret = CA_GetHSMCapabilitySet(slot_id, None, byref(cap_id_count), + None, byref(cap_val_count)) + if ret != CKR_OK: + return ret, None + + c_cap_ids = (CK_ULONG * cap_id_count.value)() + c_cap_vals = (CK_ULONG * cap_val_count.value)() + ret = CA_GetHSMCapabilitySet(slot_id, c_cap_ids, byref(cap_id_count), + c_cap_vals, byref(cap_val_count)) + + if ret != CKR_OK: + return ret, None + + return ret, dict(zip(c_cap_ids, c_cap_vals)) + + +ca_get_hsm_capability_set_ex = make_error_handle_function(ca_get_hsm_capability_set) + + +def ca_get_hsm_policy_set(slot): + """ + Get the policies of the given slot. + + :param int slot: Target slot number + :return: retcode, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_ULONG(slot) + cap_id_count = CK_ULONG() + cap_val_count = CK_ULONG() + ret = CA_GetHSMPolicySet(slot_id, None, byref(cap_id_count), + None, byref(cap_val_count)) + if ret != CKR_OK: + return ret, None + + c_cap_ids = (CK_ULONG * cap_id_count.value)() + c_cap_vals = (CK_ULONG * cap_val_count.value)() + ret = CA_GetHSMPolicySet(slot_id, c_cap_ids, byref(cap_id_count), + c_cap_vals, byref(cap_val_count)) + + if ret != CKR_OK: + return ret, None + + return ret, dict(zip(c_cap_ids, c_cap_vals)) + + +ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) From 7323aea8ab744cce447211bbd9501400346fe8b1 Mon Sep 17 00:00:00 2001 From: sliao Date: Thu, 16 Jul 2015 16:11:30 -0400 Subject: [PATCH 011/109] create pycryptoki function for par showp Change-Id: I3ac276ae69d3ce3417047cd32aa2e2671a3bf287 issue-id: LA-1187 --- pycryptoki/daemon/rpyc_pycryptoki.py | 10 ++++++--- pycryptoki/token_management.py | 32 +++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 9941745..81a4f63 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -79,7 +79,8 @@ c_get_mechanism_info, c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex, ca_get_hsm_policy_set_ex, ca_get_hsm_policy_set, - ca_get_hsm_capability_set_ex, ca_get_hsm_capability_set) + ca_get_hsm_capability_set_ex, ca_get_hsm_capability_set, + ca_get_token_policies_ex, ca_get_token_policies) from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, ca_init_audit, ca_init_audit_ex, ca_time_sync, ca_time_sync_ex) @@ -100,7 +101,8 @@ ca_modifyusagecount, ca_modifyusagecount_ex) from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, ca_duplicatemofn_ex) -from pycryptoki.cryptoki import * +from pycryptoki.cryptoki import CK_ULONG +CRYPTO_OPS = pycryptoki.cryptoki.__all__.copy() logger = logging.getLogger(__name__) @@ -125,7 +127,7 @@ def _rpyc_getattr(self, name): """ if name.startswith("exposed_"): name = name - elif name in pycryptoki.cryptoki.__all__: + elif name in CRYPTO_OPS: return getattr(pycryptoki.cryptoki, name) else: name = "exposed_" + name @@ -158,6 +160,8 @@ def _rpyc_getattr(self, name): exposed_ca_get_hsm_policy_set_ex = staticmethod(ca_get_hsm_policy_set_ex) exposed_ca_get_hsm_capability_set = staticmethod(ca_get_hsm_capability_set) exposed_ca_get_hsm_capability_set_ex = staticmethod(ca_get_hsm_capability_set_ex) + exposed_ca_get_token_policies = staticmethod(ca_get_token_policies) + exposed_ca_get_token_policies_ex = staticmethod(ca_get_token_policies_ex) # session_management.py exposed_c_initialize = staticmethod(c_initialize) diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index e6ef4a5..5b6c923 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -24,7 +24,8 @@ C_GetMechanismList, C_GetMechanismInfo, CA_GetHSMCapabilitySet, - CA_GetHSMPolicySet) + CA_GetHSMPolicySet, + CA_GetTokenPolicies) from pycryptoki.session_management import c_get_token_info from pycryptoki.test_functions import make_error_handle_function @@ -190,3 +191,32 @@ def ca_get_hsm_policy_set(slot): ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) + +def ca_get_token_policies(slot): + """ + Get the policies of the given slot. + + :param int slot: Target slot number + :return: retcode, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_ULONG(slot) + cap_id_count = CK_ULONG() + cap_val_count = CK_ULONG() + ret = CA_GetTokenPolicies(slot_id, None, byref(cap_id_count), + None, byref(cap_val_count)); + + if ret != CKR_OK: + return ret, None + + c_cap_ids = (CK_ULONG * cap_id_count.value)() + c_cap_vals = (CK_ULONG * cap_val_count.value)() + ret = CA_GetTokenPolicies(slot_id, c_cap_ids, byref(cap_id_count), + c_cap_vals, byref(cap_val_count)) + + if ret != CKR_OK: + return ret, None + + return ret, dict(zip(c_cap_ids, c_cap_vals)) + + +ca_get_token_policies_ex = make_error_handle_function(ca_get_token_policies) From a6ef7ebdec1ddfbb0466c4692d587b9e0fc6dea6 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 17 Jul 2015 09:10:36 -0400 Subject: [PATCH 012/109] LA-543 Minor bugfix-use [:] slice instead of copy Change-Id: I63079398e952c5b4f7a5ce03011b0cb67ded0ed5 --- pycryptoki/daemon/rpyc_pycryptoki.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 81a4f63..1fe843a 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -102,7 +102,7 @@ from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, ca_duplicatemofn_ex) from pycryptoki.cryptoki import CK_ULONG -CRYPTO_OPS = pycryptoki.cryptoki.__all__.copy() +CRYPTO_OPS = pycryptoki.cryptoki.__all__[:] logger = logging.getLogger(__name__) From 6db1500f3c6cd84a5f15620a12a474f8741b06ec Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 22 Jul 2015 14:46:05 -0400 Subject: [PATCH 013/109] LA-543 Pycryptoki improvements Change-Id: I93a04526d0d9a6ee62db345c8e6a5e1adc579311 --- pycryptoki/common_utils.py | 155 +++++++++++++++ pycryptoki/pylintrc | 314 +++++++++++++++++++++++++++++++ pycryptoki/session_management.py | 209 ++++++++++++-------- pycryptoki/token_management.py | 151 +++++++-------- pycryptoki/utils/common_utils.py | 7 - setup.py | 3 +- 6 files changed, 668 insertions(+), 171 deletions(-) create mode 100644 pycryptoki/common_utils.py create mode 100644 pycryptoki/pylintrc delete mode 100644 pycryptoki/utils/common_utils.py diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py new file mode 100644 index 0000000..2b93c41 --- /dev/null +++ b/pycryptoki/common_utils.py @@ -0,0 +1,155 @@ +""" +Utilities for pycryptoki +""" +from _ctypes import pointer, POINTER +from ctypes import c_ulong, cast +from pycryptoki.defines import CKR_OK + + +class CException(Exception): + """ + Raised from attempts at parsing ctypes! + """ + pass + + +class AutoCArray(object): + """ + An attempt to provide automatic resolution of C-style arrays. + + """ + def __init__(self, data=None, ctype=c_ulong, size=None): + """ + Initialize the Array. + + If it's to be a target for Crypto operation output, you only need + to specify the ctype (defaults to ULONG) + + Otherwise, you'll want to specify data and the ctype. Data can be a list-type + object (this includes strings!). If it is a list, all objects in the list need to + be compatible with your specified ctype. + + Size *always* needs to be a ctype in (c_ulong, c_uint)! + + You can specify a size at initialization time, if you know what the size will be. + Otherwise, it will be set either by the crypto-op, defaulted to 0L, or set to the size + of the given array. + + :param data: Data array should be initialized with. Needs to be string/list. + :param ctype: Type of data the array should store (Default: CK_ULONG) + :param size: Size of the array. PKCS#11 calls will init this for us, but you can also + specify it manually. + """ + self._array = None + self._size = size + self.ctype = ctype + + # name was just for logging. + if data is not None: + # Parse out any given data. + if isinstance(data, basestring) or isinstance(data, list): + self._array = (ctype * len(data))(*data) + self._size = c_ulong(len(data)) + else: + raise NotImplementedError("AutoCArray does not support given data type.") + + @property + def array(self): + """ + Allows for dynamic returning of data. + + If size is None, return None. + If size is not None and internal array is None, return a pointer to a + allocated memory of size self.ctype * self.size + If size is not None, and internal array is not None, returna pointer to the + allocated memory of the internal array. + + + :return: pointer to the internal array. + :rtype: POINTER + """ + if self._size is None: + # Return None, because this is the first time we've used this array. + # We need to set the size first w/ a call. + return None + if self._array is None: + # If we get to this point, we have a specified size, a ctype, + # And our array is still none, but we're trying to access it. + # Therefore, we go ahead & allocate the memory for + self._array = (self.ctype * self._size.value)() + return cast(self._array, POINTER(self.ctype)) + + @property + def size(self): + """ + Return a pointer to a c_ulong + + :return: Pointer to a CK_ULONG + :rtype: pointer + """ + if self._size is None: + # Default size to a ulong. + self._size = c_ulong() + return pointer(self._size) + + def __len__(self): + if self._array is not None: + return len(self._array) + else: + return 0 + + def __iter__(self): + """ + Allow for iteration over contained data (you can't iterate over AutoCArray.array, + as it is a pointer). + """ + if self._array: + for i in self._array: + yield i + + +def refresh_c_arrays(retries=1): + """ + Will re-run any Cryptoki function with an AutoCArray instance to automatically place the data + into the array. + + This is so that it's easier to do cryptoki transforms:: + + @refresh_c_arrays(retries=1) + def closure_func(): + return C_PkcsFunction(slot, autoarray.array, autoarray.size) + + # Set up the closure, then run the PKCS11 function inside the closure. + # This is so that the properties will work properly for both calls (rather + # than being evaluated only once) + + :param func: Function to decorate. + :return: closure. + """ + def wrap(func): + """ + Inner decorator. + + :param func: Original function decorated. + :return: + """ + def wrapped_func(*args, **kwargs): + """ + Runs the wrapped function the given number of times, + checking for failure. + + :param args: + :param kwargs: + :return: + """ + tries = 0 + ret = None + while tries <= retries: + ret = func(*args, **kwargs) + if ret != CKR_OK: + # Break early if one command failed. + return ret + tries += 1 + return ret + return wrapped_func + return wrap diff --git a/pycryptoki/pylintrc b/pycryptoki/pylintrc new file mode 100644 index 0000000..59909cf --- /dev/null +++ b/pycryptoki/pylintrc @@ -0,0 +1,314 @@ +# lint Python modules using external checkers. +# +# This is the main checker controling the other ones and the reports +# generation. It is itself both a raw checker and an astng checker in order +# to: +# * handle message activation / deactivation at the module level +# * handle some basic but necessary stats'data (number of classes, methods...) +# +[MASTER] + +# Specify a configuration file. +#rcfile= + +# Profiled execution. +profile=no + +# Add to the black list. It should be a base name, not a +# path. You may set this option multiple times. +ignore=.svn + +# Pickle collected data for later comparisons. +persistent=yes + +# Set the cache size for astng objects. +cache-size=500 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + + +[MESSAGES CONTROL] + +# Enable only checker(s) with the given id(s). This option conflict with the +# disable-checker option +#enable-checker= + +# Enable all checker(s) except those with the given id(s). This option conflict +# with the disable-checker option +#disable-checker= + +# Enable all messages in the listed categories. +#enable-msg-cat= + +# Disable all messages in the listed categories. +#disable-msg-cat= + +# Enable the message(s) with the given id(s). +#enable-msg= + +# Disable the message(s) with the given id(s). +disable-msg=W0142,W0703,R0201 +#Ignoring: +#W0142 - Used * or ** for args/kwargs +#W0201 - Instance attribute defined outside of __init__ +#W0232 - class has no __init__ defined + + +[REPORTS] + +# set the output format. Available formats are text, parseable, colorized and +# html +output-format=colorized + +# Include message's id in output +include-ids=yes + +# Put messages in a separate file for each module / package specified on the +# command line instead of printing them on stdout. Reports (if any) will be +# written in a file name "pylint_global.[txt|html]". +files-output=no + +# Tells wether to display a full report or only the messages +reports=yes + +# Python expression which should return a note less than 10 (10 is the highest +# note).You have access to the variables errors warning, statement which +# respectivly contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (R0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Add a comment according to your evaluation note. This is used by the global +# evaluation report (R0004). +comment=yes + +# Enable the report(s) with the given id(s). +#enable-report= + +# Disable the report(s) with the given id(s). +#disable-report= + + +# checks for +# * unused variables / imports +# * undefined variables +# * redefinition of variable from builtins or from an outer scope +# * use of variable before assigment +# +[VARIABLES] + +# Tells wether we should check for unused import in __init__ files. +init-import=yes + +# A regular expression matching names used for dummy variables (i.e. not used). +dummy-variables-rgx=_|dummy + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + + +# try to find bugs in the code using type inference +# +[TYPECHECK] + +# Tells wether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + + +# List of classes names for which member attributes should not be checked +# (useful for classes with attributes dynamically set). +ignored-classes=SQLObject,pytest + +# When zope mode is activated, add a predefined set of Zope acquired attributes +# to generated-members. +zope=no + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E0201 when accessed. Python regular +# expressions are accepted. +generated-members=REQUEST,acl_users,aq_parent,[a-zA-Z_]+_ex +#,.*_ex +#*._ex ignores the automatic exception creation with Lush/Lunacm Parsers. + + +# checks for : +# * doc strings +# * modules / classes / functions / methods / arguments / variables name +# * number of arguments, local variables, branchs, returns and statements in +# functions, methods +# * required module attributes +# * dangerous default values as arguments +# * redefinition of function / method / class +# * uses of the global statement +# +[BASIC] + +# Required attributes for module, separated by a comma +required-attributes= + +# Regular expression which should only match functions or classes name which do +# not require a docstring +no-docstring-rgx=__.*__ + +# Regular expression which should only match correct module names +module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Regular expression which should only match correct module level names +const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__)|([a-zA-Z0-9_]*_ex))$ + +# Regular expression which should only match correct class names +class-rgx=[A-Z_][a-zA-Z0-9]+$ + +# Regular expression which should only match correct function names +function-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct method names +method-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct instance attribute names +attr-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct argument names +argument-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct variable names +variable-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match correct list comprehension / +# generator expression variable names +inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ + +# Good variable names which should always be accepted, separated by a comma +good-names=i,j,k,ex,Run,_ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# List of builtins function names that should not be used, separated by a comma +bad-functions=apply,input + + +# checks for sign of poor/misdesign: +# * number of methods, attributes, local variables... +# * size, complexity of functions, methods +# +[DESIGN] + +# Maximum number of arguments for function / method +max-args=12 + +# Maximum number of locals for function / method body +max-locals=30 + +# Maximum number of return / yield for function / method body +max-returns=12 + +# Maximum number of branch for function / method body +max-branchs=30 + +# Maximum number of statements in function / method body +max-statements=60 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of attributes for a class (see R0902). +max-attributes=20 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=0 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + + +# checks for +# * external modules dependencies +# * relative / wildcard imports +# * cyclic imports +# * uses of deprecated modules +# +[IMPORTS] + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=regsub,string,TERMIOS,Bastion,rexec + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report R0402 must not be disabled) +import-graph= + +# Create a graph of external dependencies in the given file (report R0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of internal dependencies in the given file (report R0402 must +# not be disabled) +int-import-graph= + + +# checks for : +# * methods without self as first argument +# * overridden methods signature +# * access only to existant members via self +# * attributes not defined in the __init__ method +# * supported interfaces implementation +# * unreachable code +# +[CLASSES] + +# List of interface methods to ignore, separated by a comma. This is used for +# instance to not check methods defines in Zope's Interface base class. +ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__,__new__,setUp + +#ignore pytest + +# checks for similarities and duplicated code. This computation may be +# memory / CPU intensive, so you should disable it if you experiments some +# problems. +# +[SIMILARITIES] + +# Minimum lines number of a similarity. +min-similarity-lines=10 + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + + +# checks for: +# * warning notes in the code like FIXME, XXX +# * PEP 263: source code with non ascii character but no encoding declaration +# +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME,XXX,TODO + + +# checks for : +# * unauthorized constructions +# * strict indentation +# * line length +# * use of <> instead of != +# +[FORMAT] + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module +max-module-lines=1000 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 789e4fa..f80eec7 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -6,19 +6,47 @@ import logging import re -from cryptoki import C_Initialize, CK_ULONG, C_GetSlotList, CK_BBOOL, CK_SLOT_ID, \ - CK_SLOT_INFO, C_GetSlotInfo, C_CloseAllSessions, C_GetSessionInfo, CK_SESSION_HANDLE, \ - CK_SESSION_INFO, C_OpenSession, CK_FLAGS, CK_NOTIFY, C_Login, CK_USER_TYPE, C_Logout, \ - C_CloseSession, C_InitPIN, CA_FactoryReset, \ - C_GetTokenInfo, CK_TOKEN_INFO, C_Finalize, C_SetPIN, CA_DeleteContainerWithHandle, CA_OpenApplicationID, \ - CA_CloseApplicationID, CA_Restart, CA_SetApplicationID -from defines import CKR_OK -from pycryptoki.cryptoki import CA_CreateContainer, CK_VOID_PTR, \ - CK_BYTE_PTR -from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION +# cryptoki constants +from pycryptoki.cryptoki import (CK_ULONG, + CK_BBOOL, + CK_SLOT_ID, + CK_SLOT_INFO, + CK_SESSION_HANDLE, + CK_FLAGS, + CK_NOTIFY, + CK_SESSION_INFO, + CK_USER_TYPE, + CK_TOKEN_INFO, + CK_VOID_PTR, + CK_BYTE) + +# Cryptoki Functions +from pycryptoki.cryptoki import (C_Initialize, + C_GetSlotList, + C_GetSlotInfo, + C_CloseAllSessions, + C_GetSessionInfo, + C_OpenSession, + C_Login, + C_Logout, + C_CloseSession, + C_InitPIN, + CA_FactoryReset, + C_GetTokenInfo, + C_Finalize, + C_SetPIN, + CA_DeleteContainerWithHandle, + CA_OpenApplicationID, + CA_CloseApplicationID, + CA_Restart, + CA_CreateContainer, + CA_SetApplicationID) + +from pycryptoki.common_utils import AutoCArray, refresh_c_arrays +from pycryptoki.defines import CKR_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION from pycryptoki.test_functions import make_error_handle_function -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) def c_initialize(): @@ -29,7 +57,7 @@ def c_initialize(): """ # INITIALIZE - logger.info("C_Initialize: Initializing HSM") + LOG.info("C_Initialize: Initializing HSM") ret = C_Initialize(0) return ret @@ -44,7 +72,7 @@ def c_finalize(): :returns: The result code """ - logger.info("C_Finalize: Finalizing HSM") + LOG.info("C_Finalize: Finalizing HSM") ret = C_Finalize(0) return ret @@ -56,17 +84,20 @@ def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): """Opens a session on a given slot :param slot_num: The slot to get a session on - :param flags: The flags to open the session with (Default value = (CKF_SERIAL_SESSION | CKF_RW_SESSION) + :param flags: The flags to open the session with + (Default value = (CKF_SERIAL_SESSION | CKF_RW_SESSION) :returns: The result code, the session handle """ # OPEN SESSION arg3 = create_string_buffer("Application") h_session = CK_SESSION_HANDLE() - arg3 = cast(arg3, c_void_p) # CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) - ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), + arg3 = cast(arg3, c_void_p) + # CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) + ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), + cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), pointer(h_session)) - logger.info("C_OpenSession: Opening Session. slot=" + str(slot_num)) + LOG.info("C_OpenSession: Opening Session. slot=" + str(slot_num)) return ret, h_session.value @@ -74,7 +105,7 @@ def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): c_open_session_ex = make_error_handle_function(c_open_session) -def login(h_session, slot_num=1, password="", user_type=1): +def login(h_session, slot_num=1, password=None, user_type=1): """Login to the HSM :param h_session: Current session @@ -85,11 +116,18 @@ def login(h_session, slot_num=1, password="", user_type=1): """ # LOGIN - user_type = long(user_type) - pb_password = c_char_p(password) - logger.info( - "C_Login: Logging In. user_type=" + str(user_type) + ", slot=" + str(slot_num) + ", password=" + password) - ret = C_Login(h_session, CK_USER_TYPE(user_type), cast(pb_password, CK_BYTE_PTR), CK_ULONG(len(password))) + LOG.info("C_Login: " + "user_type=%s, " + "slot=%s, " + "password=%s", user_type, slot_num, password) + if password == '': + password = None + + user_type = CK_USER_TYPE(long(user_type)) + password = AutoCArray(data=password, ctype=CK_BYTE) + + ret = C_Login(h_session, user_type, password.array, password.size.contents) + return ret @@ -150,14 +188,17 @@ def c_get_token_info(slot_id): """ token_info = {} c_token_info = CK_TOKEN_INFO() - logger.info("Getting token info. slot=" + str(slot_id)) + LOG.info("Getting token info. slot=" + str(slot_id)) ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) if ret == CKR_OK: token_info['label'] = str(cast(c_token_info.label, c_char_p).value)[0:32].strip() - token_info['manufacturerID'] = str(cast(c_token_info.manufacturerID, c_char_p).value)[0:32].strip() - token_info['model'] = str(cast(c_token_info.model, c_char_p).value)[0:16].strip() - token_info['serialNumber'] = int(str(cast(c_token_info.serialNumber, c_char_p).value)[0:16].strip()) + token_info['manufacturerID'] = str(cast(c_token_info.manufacturerID, + c_char_p).value)[0:32].strip() + token_info['model'] = str(cast(c_token_info.model, + c_char_p).value)[0:16].strip() + token_info['serialNumber'] = int(str(cast(c_token_info.serialNumber, + c_char_p).value)[0:16].strip()) token_info['flags'] = c_token_info.flags token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory @@ -186,13 +227,19 @@ def get_slot_dict(): :returns: A python dictionary of the available slots """ - us_count = CK_ULONG(0) - ret = C_GetSlotList(CK_BBOOL(0), None, byref(us_count)) - if ret != CKR_OK: return ret - num_slots = (us_count.value + 1) - slot_list = (CK_SLOT_ID * num_slots)() - ret = C_GetSlotList(CK_BBOOL(0), slot_list, byref(us_count)) - if ret != CKR_OK: return ret + slot_list = AutoCArray() + + @refresh_c_arrays(1) + def _get_slot_list(): + """ + Closure to refresh properties. + """ + return C_GetSlotList(CK_BBOOL(0), slot_list.array, slot_list.size) + + ret = _get_slot_list() + if ret != CKR_OK: + return ret, None + slot_info = CK_SLOT_INFO() slot_dict = {} for slot in slot_list: @@ -214,7 +261,7 @@ def c_close_session(h_session): """ # CLOSE SESSION - logger.info("C_CloseSession: Closing session " + str(h_session)) + LOG.info("C_CloseSession: Closing session " + str(h_session)) ret = C_CloseSession(h_session) return ret @@ -229,7 +276,7 @@ def c_logout(h_session): :returns: The result code """ - logger.info("C_Logout: Logging out of session " + str(h_session)) + LOG.info("C_Logout: Logging out of session " + str(h_session)) ret = C_Logout(h_session) return ret @@ -246,11 +293,9 @@ def c_init_pin(h_session, pin): """ - logger.info("C_InitPIN: Initializing PIN to " + str(pin)) - if pin == '': - ret = C_InitPIN(h_session, None, CK_ULONG(0)) - else: - ret = C_InitPIN(h_session, cast(create_string_buffer(pin), CK_BYTE_PTR), CK_ULONG(len(pin))) + LOG.info("C_InitPIN: Initializing PIN to " + str(pin)) + pin = AutoCArray(data=pin) + ret = C_InitPIN(h_session, pin.array, pin.size.contents) return ret @@ -264,7 +309,7 @@ def ca_factory_reset(slot): :returns: The result code """ - logger.info("CA_FactoryReset: Factory Reset. slot=" + str(slot)) + LOG.info("CA_FactoryReset: Factory Reset. slot=" + str(slot)) ret = CA_FactoryReset(CK_SLOT_ID(slot), CK_ULONG(0)) return ret @@ -281,15 +326,16 @@ def c_set_pin(h_session, old_pass, new_pass): :returns: The result code """ - logger.info("C_SetPIN: Changing password. old_pass=" + str(old_pass) + ", new_pass=" + str(new_pass)) - if old_pass == '' and new_pass == '': - ret = C_SetPIN(h_session, None, CK_ULONG(0), - None, CK_ULONG(0)) - return ret - else: - ret = C_SetPIN(h_session, cast(create_string_buffer(old_pass), CK_BYTE_PTR), CK_ULONG(len(old_pass)), - cast(create_string_buffer(new_pass), CK_BYTE_PTR), CK_ULONG(len(new_pass))) - return ret + LOG.info("C_SetPIN: Changing password. " + "old_pass=" + str(old_pass) + ", new_pass=" + str(new_pass)) + + old_pass = AutoCArray(data=old_pass) + new_pass = AutoCArray(data=new_pass) + + ret = C_SetPIN(h_session, + old_pass.array, old_pass.size.contents, + new_pass.array, new_pass.size.contents) + return ret c_set_pin_ex = make_error_handle_function(c_set_pin) @@ -303,7 +349,7 @@ def c_close_all_sessions(slot): """ - logger.info("C_CloseAllSessions: Closing all sessions. slot=" + str(slot)) + LOG.info("C_CloseAllSessions: Closing all sessions. slot=" + str(slot)) ret = C_CloseAllSessions(CK_ULONG(slot)) return ret @@ -311,7 +357,7 @@ def c_close_all_sessions(slot): c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) -def ca_create_container(h_session, storage_size, password='', label='Inserted Token'): +def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): """Inserts a token into a slot without a Security Officer on the token :param h_session: Current session @@ -321,27 +367,23 @@ def ca_create_container(h_session, storage_size, password='', label='Inserted To :returns: The result code, The container number """ + container_number = CK_ULONG() + LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( + storage_size) + ", pin=" + str(password) + ", label=" + label) if password == '': - container_number = CK_ULONG() - logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( - storage_size) + ", pin=" + password + ", label=" + label) - ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), - CK_ULONG(len(label)), None, - CK_ULONG(0), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), - CK_ULONG(storage_size), byref(container_number)) - logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) - return ret, container_number.value - else: - container_number = CK_ULONG() - logger.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( - storage_size) + ", pin=" + password + ", label=" + label) - ret = CA_CreateContainer(h_session, CK_ULONG(0), cast(create_string_buffer(label), CK_BYTE_PTR), - CK_ULONG(len(label)), cast(create_string_buffer(password), CK_BYTE_PTR), - CK_ULONG(len(password)), CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), - CK_ULONG(storage_size), byref(container_number)) - logger.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) - return ret, container_number.value + password = None + + password = AutoCArray(data=password) + label = AutoCArray(data=label) + + ret = CA_CreateContainer(h_session, CK_ULONG(0), + label.array, label.size.contents, + password.array, password.size.contents, + CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), + CK_ULONG(storage_size), byref(container_number)) + LOG.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) + return ret, container_number.value ca_create_container_ex = make_error_handle_function(ca_create_container) @@ -355,12 +397,13 @@ def ca_delete_container_with_handle(h_session, container_handle): """ container_number = CK_ULONG(container_handle) - logger.info( - "CA_DeleteContainerWithHandle: Attempting to delete container with handle: {0}".format(container_handle)) + LOG.info( + "CA_DeleteContainerWithHandle: " + "Attempting to delete container with handle: %s", container_handle) ret = CA_DeleteContainerWithHandle(h_session, container_number) - logger.info("CA_DeleteContainerWithHandle: Ret Value: {0}".format(ret)) + LOG.info("CA_DeleteContainerWithHandle: Ret Value: %s", ret) return ret @@ -379,11 +422,11 @@ def ca_openapplicationID(slot, id_high, id_low): uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) - logger.info("CA_OpenApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) + LOG.info("CA_OpenApplicationID: Attempting to open App ID %s:%s", id_high, id_low) ret = CA_OpenApplicationID(CK_ULONG(slot), uid_high, uid_low) - logger.info("CA_OpenApplicationID: Ret Value: {0}".format(ret)) + LOG.info("CA_OpenApplicationID: Ret Value: %s", ret) return ret @@ -402,11 +445,11 @@ def ca_closeapplicationID(slot, id_high, id_low): uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) - logger.info("CA_CloseApplicationID: Attempting to open App ID {0}:{1}".format(id_high, id_low)) + LOG.info("CA_CloseApplicationID: Attempting to close App ID %s:%s", id_high, id_low) ret = CA_CloseApplicationID(CK_ULONG(slot), uid_high, uid_low) - logger.info("CA_CloseApplicationID: Ret Value: {0}".format(ret)) + LOG.info("CA_CloseApplicationID: Ret Value: %s", ret) return ret @@ -424,11 +467,11 @@ def ca_setapplicationID(id_high, id_low): uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) - logger.info("CA_SetApplicationID: Attempting to set App ID {0}:{1}".format(id_high, id_low)) + LOG.info("CA_SetApplicationID: Attempting to set App ID %s:%s", id_high, id_low) ret = CA_SetApplicationID(uid_high, uid_low) - logger.info("CA_SetApplicationID: Ret Value: {0}".format(ret)) + LOG.info("CA_SetApplicationID: Ret Value: %s", ret) return ret @@ -442,11 +485,11 @@ def ca_restart(slot): :param slot: """ - logger.info("CA_Restart: attempting to restart") + LOG.info("CA_Restart: attempting to restart") ret = CA_Restart(CK_ULONG(slot)) - logger.info("CA_Restart: Ret Value: {0}".format(ret)) + LOG.info("CA_Restart: Ret Value: %s", ret) return ret diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index 5b6c923..0556242 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -3,16 +3,13 @@ @author: mhughes """ -from ctypes import byref, cast, create_string_buffer +from ctypes import byref import logging # Cryptoki Constants from pycryptoki.cryptoki import (CK_ULONG, - CK_CHAR_PTR, CK_BBOOL, - CK_SLOT_ID, CK_MECHANISM_TYPE, - CK_MECHANISM_TYPE_PTR, CK_MECHANISM_INFO) from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT from pycryptoki.defines import CKR_OK @@ -28,8 +25,10 @@ CA_GetTokenPolicies) from pycryptoki.session_management import c_get_token_info from pycryptoki.test_functions import make_error_handle_function +from pycryptoki.common_utils import AutoCArray +from pycryptoki.common_utils import refresh_c_arrays -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) def c_init_token(slot_num, password, token_label='Main Token'): @@ -41,19 +40,18 @@ def c_init_token(slot_num, password, token_label='Main Token'): :returns: The result code """ + LOG.info("C_InitToken: Initializing token. slot=" + str( + slot_num) + ", label='" + token_label + "', password='" + str(password) + "'") + if password == '': - logger.info("C_InitToken: Initializing token. slot=" + str( - slot_num) + ", label='" + token_label + "', password='" + password + "'") - ret = C_InitToken(CK_ULONG(slot_num), None, - CK_ULONG(0), cast(create_string_buffer(token_label), CK_CHAR_PTR)) - return ret - else: - logger.info("C_InitToken: Initializing token. slot=" + str( - slot_num) + ", label='" + token_label + "', password='" + password + "'") - ret = C_InitToken(CK_ULONG(slot_num), cast(create_string_buffer(password), CK_CHAR_PTR), - CK_ULONG(len(password)), - cast(create_string_buffer(token_label), CK_CHAR_PTR)) - return ret + password = None + password = AutoCArray(data=password) + slot_id = CK_ULONG(slot_num) + label = AutoCArray(data=token_label) + + return C_InitToken(slot_id, + password.array, password.size.contents, + label.array) c_init_token_ex = make_error_handle_function(c_init_token) @@ -68,19 +66,24 @@ def get_token_by_label(label): """ - if label == ADMIN_PARTITION_LABEL: # XXX the admin partition's label changes depending on - # the boards state + if label == ADMIN_PARTITION_LABEL: + # XXX the admin partition's label changes depending on + # the boards state # ret, slot_info = get_slot_info("Viper") # return ret, slot_info.keys()[1] return CKR_OK, ADMIN_SLOT - us_count = CK_ULONG(0) - ret = C_GetSlotList(CK_BBOOL(1), None, byref(us_count)) - if ret != CKR_OK: return ret, None - num_slots = us_count.value - slot_list = (CK_SLOT_ID * num_slots)() - ret = C_GetSlotList(CK_BBOOL(1), slot_list, byref(us_count)) - if ret != CKR_OK: return ret, None + slot_list = AutoCArray() + + @refresh_c_arrays(1) + def _get_slot_list(): + """Closure + """ + return C_GetSlotList(CK_BBOOL(1), slot_list.array, slot_list.size) + + ret = _get_slot_list() + if ret != CKR_OK: + return ret, None for slot in slot_list: ret, token_info = c_get_token_info(slot) @@ -100,20 +103,17 @@ def c_get_mechanism_list(slot): :returns: The result code, A python dictionary representing the mechanism list """ - count = CK_ULONG() - ret = C_GetMechanismList(CK_SLOT_ID(slot), None, byref(count)) - last_count = count - if ret != CKR_OK: return ret, None - mech_list = (CK_MECHANISM_TYPE * count.value)() - ret = C_GetMechanismList(CK_SLOT_ID(slot), CK_MECHANISM_TYPE_PTR(mech_list), byref(count)) - if ret != CKR_OK: return ret, None - if last_count != count: raise Exception( - "Mechanism list count was not consistent between function calls") - - ret_list = [] - for i in range(0, count.value): - ret_list.append(mech_list[i]) - return ret, ret_list + slot_id = CK_ULONG(slot) + mech = AutoCArray(ctype=CK_MECHANISM_TYPE) + + @refresh_c_arrays(1) + def _c_get_mech_list(): + """Closure for retry to work w/ properties. + """ + return C_GetMechanismList(slot_id, mech.array, mech.size) + + ret = _c_get_mech_list() + return ret, [x for x in mech] c_get_mechanism_list_ex = make_error_handle_function(c_get_mechanism_list) @@ -143,22 +143,19 @@ def ca_get_hsm_capability_set(slot): :return: retcode, {id: val} dict of policies (None if command failed) """ slot_id = CK_ULONG(slot) - cap_id_count = CK_ULONG() - cap_val_count = CK_ULONG() - ret = CA_GetHSMCapabilitySet(slot_id, None, byref(cap_id_count), - None, byref(cap_val_count)) - if ret != CKR_OK: - return ret, None + cap_ids = AutoCArray() + cap_vals = AutoCArray() - c_cap_ids = (CK_ULONG * cap_id_count.value)() - c_cap_vals = (CK_ULONG * cap_val_count.value)() - ret = CA_GetHSMCapabilitySet(slot_id, c_cap_ids, byref(cap_id_count), - c_cap_vals, byref(cap_val_count)) + @refresh_c_arrays(1) + def _get_hsm_caps(): + """Closer for retries to work w/ properties + """ + return CA_GetHSMCapabilitySet(slot_id, cap_ids.array, cap_ids.size, + cap_vals.array, cap_vals.size) - if ret != CKR_OK: - return ret, None + ret = _get_hsm_caps() - return ret, dict(zip(c_cap_ids, c_cap_vals)) + return ret, dict(zip(cap_ids, cap_vals)) ca_get_hsm_capability_set_ex = make_error_handle_function(ca_get_hsm_capability_set) @@ -172,26 +169,24 @@ def ca_get_hsm_policy_set(slot): :return: retcode, {id: val} dict of policies (None if command failed) """ slot_id = CK_ULONG(slot) - cap_id_count = CK_ULONG() - cap_val_count = CK_ULONG() - ret = CA_GetHSMPolicySet(slot_id, None, byref(cap_id_count), - None, byref(cap_val_count)) - if ret != CKR_OK: - return ret, None + cap_ids = AutoCArray() + cap_vals = AutoCArray() - c_cap_ids = (CK_ULONG * cap_id_count.value)() - c_cap_vals = (CK_ULONG * cap_val_count.value)() - ret = CA_GetHSMPolicySet(slot_id, c_cap_ids, byref(cap_id_count), - c_cap_vals, byref(cap_val_count)) + @refresh_c_arrays(1) + def _ca_get_hsm_policy_set(): + """Closure for retries. + """ + return CA_GetHSMPolicySet(slot_id, cap_ids.array, cap_ids.size, + cap_vals.array, cap_vals.size) - if ret != CKR_OK: - return ret, None + ret = _ca_get_hsm_policy_set() - return ret, dict(zip(c_cap_ids, c_cap_vals)) + return ret, dict(zip(cap_ids, cap_vals)) ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) + def ca_get_token_policies(slot): """ Get the policies of the given slot. @@ -200,23 +195,19 @@ def ca_get_token_policies(slot): :return: retcode, {id: val} dict of policies (None if command failed) """ slot_id = CK_ULONG(slot) - cap_id_count = CK_ULONG() - cap_val_count = CK_ULONG() - ret = CA_GetTokenPolicies(slot_id, None, byref(cap_id_count), - None, byref(cap_val_count)); + pol_ids = AutoCArray() + pol_vals = AutoCArray() - if ret != CKR_OK: - return ret, None - - c_cap_ids = (CK_ULONG * cap_id_count.value)() - c_cap_vals = (CK_ULONG * cap_val_count.value)() - ret = CA_GetTokenPolicies(slot_id, c_cap_ids, byref(cap_id_count), - c_cap_vals, byref(cap_val_count)) + @refresh_c_arrays(1) + def _get_token_policies(): + """Closure for retries to work w/ properties. + """ + return CA_GetTokenPolicies(slot_id, pol_ids.array, pol_ids.size, + pol_vals.array, pol_vals.size) - if ret != CKR_OK: - return ret, None + ret = _get_token_policies() - return ret, dict(zip(c_cap_ids, c_cap_vals)) + return ret, dict(zip(pol_ids, pol_vals)) ca_get_token_policies_ex = make_error_handle_function(ca_get_token_policies) diff --git a/pycryptoki/utils/common_utils.py b/pycryptoki/utils/common_utils.py deleted file mode 100644 index 17c1fa2..0000000 --- a/pycryptoki/utils/common_utils.py +++ /dev/null @@ -1,7 +0,0 @@ -import datetime -#Utility to set a default logfile name -def setLogFile(): - """ """ - dt = str(datetime.datetime.now()).strip() - logname = "./test_" + dt + ".log" - return logname diff --git a/setup.py b/setup.py index b0840ba..44d40bb 100755 --- a/setup.py +++ b/setup.py @@ -16,7 +16,8 @@ packages=['pycryptoki', 'pycryptoki.setup', 'pycryptoki.tests', - 'pycryptoki.daemon'], + 'pycryptoki.daemon', + 'pycryptoki.utils'], scripts=['pycryptoki/daemon/rpyc_pycryptoki.py', 'pycryptoki/daemon/pycryptoki_daemon.py'] ) From 2e78495df7c76c0c2dbc58d40938bd3937784f3a Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 31 Jul 2015 10:03:34 -0400 Subject: [PATCH 014/109] LA-543 Fix for password login Change-Id: Ibd0cfefefb6de400e0f841a3c9714e6f46cf6fac --- pycryptoki/common_utils.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index 2b93c41..aa9f8dd 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -2,7 +2,8 @@ Utilities for pycryptoki """ from _ctypes import pointer, POINTER -from ctypes import c_ulong, cast +from ctypes import c_ulong, cast, create_string_buffer +from pycryptoki.cryptoki import CK_CHAR from pycryptoki.defines import CKR_OK @@ -47,7 +48,11 @@ def __init__(self, data=None, ctype=c_ulong, size=None): # name was just for logging. if data is not None: # Parse out any given data. - if isinstance(data, basestring) or isinstance(data, list): + if isinstance(data, basestring): + self._array = create_string_buffer(data) + self._size = c_ulong(len(data)) + self.ctype = CK_CHAR + elif isinstance(data, list): self._array = (ctype * len(data))(*data) self._size = c_ulong(len(data)) else: From f3e6fc34d7a65b5944aed3ffd1a61491e0574df7 Mon Sep 17 00:00:00 2001 From: Joseph Dobie Date: Thu, 15 Oct 2015 12:20:03 -0400 Subject: [PATCH 015/109] LA-1358: Update pycryptoki to handle template attributes. Change-Id: I96a5acf98757a1ce20adeb093cc132887fb01fac --- pycryptoki/attributes.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 5e25b54..fe097a8 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -19,7 +19,7 @@ CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_ECDSA_PARAMS, CKA_EC_POINT, CKA_LOCAL, \ CKA_MODIFIABLE, CKA_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_NEVER_EXTRACTABLE, \ CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_PKC_TCTRUST, CKA_PKC_CITS, \ - CKA_OUID, \ + CKA_OUID, CKA_UNWRAP_TEMPLATE, \ CKA_X9_31_GENERATED, CKA_PKC_ECC, CKR_OK from pycryptoki.cryptoki import CK_ULONG_PTR from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ @@ -130,7 +130,8 @@ def get_byte_list_from_python_list(python_byte_list): CKA_EKM_UID: None, CKA_GENERIC_1: None, CKA_GENERIC_2: None, - CKA_GENERIC_3: None} + CKA_GENERIC_3: None, + CKA_UNWRAP_TEMPLATE: {}} role_attributes = {} @@ -219,7 +220,7 @@ def _input_check(self, key, value): if isinstance(value, bool) or isinstance(value, int) or isinstance(value, CDict) or isinstance( value, long) or isinstance(value, str) or isinstance(value, list) or isinstance( - value, CList) or isinstance(value, NonAsciiString): + value, CList) or isinstance(value, NonAsciiString) or isinstance(value, dict): return True else: raise Exception( @@ -296,6 +297,11 @@ def get_c_struct(self): list_val[j] = CK_CHAR(ord(value[j]) - 0x30) c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(sizeof(CK_CHAR(0)) * len(value))) + elif isinstance(item_type, dict): + template = Attributes(attributes_list=value).get_c_struct() + c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), + cast(template, c_void_p), + CK_ULONG(len(template))) else: raise Exception("Argument type " + str(item_type) + " not supported. ") From dfb471ad0f0f2e8d8751189d97a5da794d2e2836 Mon Sep 17 00:00:00 2001 From: Joseph Dobie Date: Mon, 19 Oct 2015 12:46:24 -0400 Subject: [PATCH 016/109] LA-1358: Add CKA_DERIVE_TEMPLATE to the attribute handler. Change-Id: I15431349485763e0e97a3282297f88d2fbf841c1 --- pycryptoki/attributes.py | 5 +++-- pycryptoki/defines.py | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index fe097a8..0905a74 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -19,7 +19,7 @@ CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_ECDSA_PARAMS, CKA_EC_POINT, CKA_LOCAL, \ CKA_MODIFIABLE, CKA_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_NEVER_EXTRACTABLE, \ CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_PKC_TCTRUST, CKA_PKC_CITS, \ - CKA_OUID, CKA_UNWRAP_TEMPLATE, \ + CKA_OUID, CKA_UNWRAP_TEMPLATE, CKA_DERIVE_TEMPLATE, \ CKA_X9_31_GENERATED, CKA_PKC_ECC, CKR_OK from pycryptoki.cryptoki import CK_ULONG_PTR from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ @@ -131,7 +131,8 @@ def get_byte_list_from_python_list(python_byte_list): CKA_GENERIC_1: None, CKA_GENERIC_2: None, CKA_GENERIC_3: None, - CKA_UNWRAP_TEMPLATE: {}} + CKA_UNWRAP_TEMPLATE: {}, + CKA_DERIVE_TEMPLATE: {}} role_attributes = {} diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index c4754eb..f9098f4 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1007,6 +1007,7 @@ CKA_WRAP_WITH_TRUSTED = 0x00000210 CKA_WRAP_TEMPLATE = (CKF_ARRAY_ATTRIBUTE | 0x00000211) CKA_UNWRAP_TEMPLATE = (CKF_ARRAY_ATTRIBUTE | 0x00000212) +CKA_DERIVE_TEMPLATE = (CKF_ARRAY_ATTRIBUTE | 0x00000213) CKA_OTP_FORMAT = 0x00000220 CKA_OTP_LENGTH = 0x00000221 CKA_OTP_TIME_INTERVAL = 0x00000222 From be169ea1320922d4e072dbe9d9a02d1d5ef0dca1 Mon Sep 17 00:00:00 2001 From: Joseph Dobie Date: Thu, 22 Oct 2015 16:47:18 -0400 Subject: [PATCH 017/109] LA-1358: Update Currently Used Asym templates in addition to RC4 and RC5 Change-Id: I4ab8d277d166f15c894ba3d1a068483e2a5d8519 --- pycryptoki/default_templates.py | 47 +++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py index e4aa7c0..58b6f7e 100755 --- a/pycryptoki/default_templates.py +++ b/pycryptoki/default_templates.py @@ -26,7 +26,7 @@ CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, CKM_ECDSA_SHA256, \ CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, \ CKM_SHA_1_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, \ - CKM_ECDSA + CKM_ECDSA, CKO_PUBLIC_KEY, CKO_PRIVATE_KEY, CKK_RSA, CKK_DH, CKK_DSA, CKK_ECDSA from pycryptoki.defines import CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE, CKC_X_509, \ CKA_SUBJECT, CKA_VALUE, CKO_DATA, CKA_TOKEN @@ -120,7 +120,9 @@ CKA_EXTRACTABLE: True, CKA_LABEL: "GENERIC SECRET Key"} -CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, +CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, + CKA_KEY_TYPE: CKK_RSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_MODIFIABLE: True, CKA_ENCRYPT: True, @@ -129,7 +131,9 @@ CKA_MODULUS_BITS: 1024, # long 0 - MAX_RSA_KEY_NBITS CKA_PUBLIC_EXPONENT: 3, # byte CKA_LABEL: "RSA Public Key"} -CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, +CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, + CKA_KEY_TYPE: CKK_RSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_MODIFIABLE: True, @@ -138,7 +142,6 @@ CKA_SIGN: True, CKA_UNWRAP: True, CKA_LABEL: "RSA Private Key"} - dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, 0x6d, 0x1f, 0xf2, 0x70, 0xf1, 0x59, 0x78, 0x5d, 0x75, 0x69, 0x21, 0xdb, 0xff, 0x97, 0x73, 0xae, 0x08, 0x48, 0x3b, @@ -312,7 +315,9 @@ CKA_SUBPRIME: dsa_sub_prime_2048_256, CKA_BASE: dsa_base_2048_256, CKA_LABEL: "DSA 2048_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN: True, +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_CLASS: CKO_PUBLIC_KEY, + CKA_KEY_TYPE: CKK_DSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_ENCRYPT: True, CKA_VERIFY: True, @@ -321,7 +326,9 @@ CKA_SUBPRIME: dsa_sub_prime_3072_256, CKA_BASE: dsa_base_3072_256, CKA_LABEL: "DSA 3072_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, +CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, + CKA_KEY_TYPE: CKK_DSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_DECRYPT: True, @@ -354,13 +361,17 @@ 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] -CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, +CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, + CKA_KEY_TYPE: CKK_DH, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_DERIVE: True, CKA_PRIME: dh_prime, CKA_BASE: [0x02], CKA_LABEL: "DH Public Key"} -CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS: len(dh_prime) * 8, # long +CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, + CKA_KEY_TYPE: CKK_DH, + CKA_VALUE_BITS: len(dh_prime) * 8, # long CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -412,7 +423,7 @@ CKA_WRAP: True, CKA_UNWRAP: True, CKA_DERIVE: True, - CKA_VALUE_LEN: 256, # 1-256 + CKA_VALUE_LEN: 8, # 1-256 CKA_EXTRACTABLE: True, CKA_LABEL: "RC4 Key"} @@ -428,7 +439,7 @@ CKA_WRAP: True, CKA_UNWRAP: True, CKA_DERIVE: True, - CKA_VALUE_LEN: 255, # 1-255 + CKA_VALUE_LEN: 16, # 1-255 CKA_EXTRACTABLE: True, CKA_LABEL: "RC5 Key"} @@ -536,14 +547,18 @@ 0xec, 0x14, 0x90, 0x44, 0x28, 0xc2, 0xa6, 0x75] } -CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, +CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, + CKA_KEY_TYPE: CKK_ECDSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_ENCRYPT: True, CKA_VERIFY: True, CKA_DERIVE: True, CKA_ECDSA_PARAMS: curve_list['secp112r1'], CKA_LABEL: "ECDSA Public Key"} -CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, +CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, + CKA_KEY_TYPE: CKK_ECDSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_DECRYPT: True, @@ -680,7 +695,9 @@ CKA_SUBPRIME_BITS: 256, # 0-512 CKA_LABEL: "KCDSA Parameter Key"} -CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, +CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, + CKA_KEY_TYPE: CKK_RSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_MODIFIABLE: True, CKA_ENCRYPT: True, @@ -689,7 +706,9 @@ CKA_MODULUS_BITS: 1024, # long 1-MAX_RSA_KEY_NBITS CKA_PUBLIC_EXPONENT: 3, # byte CKA_LABEL: "RSA Public Key"} -CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, +CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, + CKA_KEY_TYPE: CKK_RSA, + CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_MODIFIABLE: True, From 15d3d564255158fda723b56ffee8c1b9cbb9cef2 Mon Sep 17 00:00:00 2001 From: Joseph Dobie Date: Tue, 27 Oct 2015 10:47:10 -0400 Subject: [PATCH 018/109] LA-1358: Add CKA_ID to the attribute lookup table. Change-Id: Id061907a0cc93b31e7a8d2748da09128fa9d968a --- pycryptoki/attributes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 0905a74..1ec5972 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -83,7 +83,7 @@ def get_byte_list_from_python_list(python_byte_list): CKA_SERIAL_NUMBER: None, CKA_KEY_TYPE: long, CKA_SUBJECT: str, - CKA_ID: None, + CKA_ID: str, CKA_SENSITIVE: bool, CKA_ENCRYPT: bool, CKA_DECRYPT: bool, From 081fac8167d29616e41235314a6368c2a5a0c8cf Mon Sep 17 00:00:00 2001 From: Joseph Dobie Date: Mon, 2 Nov 2015 09:00:49 -0500 Subject: [PATCH 019/109] LA-1358: Revert asym template change to default templates. Cloning tests are currently failing, recently after default template change. Reverting file to remove failures. Change-Id: I1ab0febbac620ca315f2d0c884702f42f5428c27 --- pycryptoki/default_templates.py | 47 ++++++++++----------------------- 1 file changed, 14 insertions(+), 33 deletions(-) diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py index 58b6f7e..e4aa7c0 100755 --- a/pycryptoki/default_templates.py +++ b/pycryptoki/default_templates.py @@ -26,7 +26,7 @@ CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, CKM_ECDSA_SHA256, \ CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, \ CKM_SHA_1_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, \ - CKM_ECDSA, CKO_PUBLIC_KEY, CKO_PRIVATE_KEY, CKK_RSA, CKK_DH, CKK_DSA, CKK_ECDSA + CKM_ECDSA from pycryptoki.defines import CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE, CKC_X_509, \ CKA_SUBJECT, CKA_VALUE, CKO_DATA, CKA_TOKEN @@ -120,9 +120,7 @@ CKA_EXTRACTABLE: True, CKA_LABEL: "GENERIC SECRET Key"} -CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, - CKA_KEY_TYPE: CKK_RSA, - CKA_TOKEN: True, +CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_MODIFIABLE: True, CKA_ENCRYPT: True, @@ -131,9 +129,7 @@ CKA_MODULUS_BITS: 1024, # long 0 - MAX_RSA_KEY_NBITS CKA_PUBLIC_EXPONENT: 3, # byte CKA_LABEL: "RSA Public Key"} -CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, - CKA_KEY_TYPE: CKK_RSA, - CKA_TOKEN: True, +CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_MODIFIABLE: True, @@ -142,6 +138,7 @@ CKA_SIGN: True, CKA_UNWRAP: True, CKA_LABEL: "RSA Private Key"} + dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, 0x6d, 0x1f, 0xf2, 0x70, 0xf1, 0x59, 0x78, 0x5d, 0x75, 0x69, 0x21, 0xdb, 0xff, 0x97, 0x73, 0xae, 0x08, 0x48, 0x3b, @@ -315,9 +312,7 @@ CKA_SUBPRIME: dsa_sub_prime_2048_256, CKA_BASE: dsa_base_2048_256, CKA_LABEL: "DSA 2048_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_CLASS: CKO_PUBLIC_KEY, - CKA_KEY_TYPE: CKK_DSA, - CKA_TOKEN: True, +CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_ENCRYPT: True, CKA_VERIFY: True, @@ -326,9 +321,7 @@ CKA_SUBPRIME: dsa_sub_prime_3072_256, CKA_BASE: dsa_base_3072_256, CKA_LABEL: "DSA 3072_256 Public Key"} -CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, - CKA_KEY_TYPE: CKK_DSA, - CKA_TOKEN: True, +CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_DECRYPT: True, @@ -361,17 +354,13 @@ 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] -CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, - CKA_KEY_TYPE: CKK_DH, - CKA_TOKEN: True, +CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_DERIVE: True, CKA_PRIME: dh_prime, CKA_BASE: [0x02], CKA_LABEL: "DH Public Key"} -CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, - CKA_KEY_TYPE: CKK_DH, - CKA_VALUE_BITS: len(dh_prime) * 8, # long +CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS: len(dh_prime) * 8, # long CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -423,7 +412,7 @@ CKA_WRAP: True, CKA_UNWRAP: True, CKA_DERIVE: True, - CKA_VALUE_LEN: 8, # 1-256 + CKA_VALUE_LEN: 256, # 1-256 CKA_EXTRACTABLE: True, CKA_LABEL: "RC4 Key"} @@ -439,7 +428,7 @@ CKA_WRAP: True, CKA_UNWRAP: True, CKA_DERIVE: True, - CKA_VALUE_LEN: 16, # 1-255 + CKA_VALUE_LEN: 255, # 1-255 CKA_EXTRACTABLE: True, CKA_LABEL: "RC5 Key"} @@ -547,18 +536,14 @@ 0xec, 0x14, 0x90, 0x44, 0x28, 0xc2, 0xa6, 0x75] } -CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, - CKA_KEY_TYPE: CKK_ECDSA, - CKA_TOKEN: True, +CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_ENCRYPT: True, CKA_VERIFY: True, CKA_DERIVE: True, CKA_ECDSA_PARAMS: curve_list['secp112r1'], CKA_LABEL: "ECDSA Public Key"} -CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, - CKA_KEY_TYPE: CKK_ECDSA, - CKA_TOKEN: True, +CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_DECRYPT: True, @@ -695,9 +680,7 @@ CKA_SUBPRIME_BITS: 256, # 0-512 CKA_LABEL: "KCDSA Parameter Key"} -CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_CLASS: CKO_PUBLIC_KEY, - CKA_KEY_TYPE: CKK_RSA, - CKA_TOKEN: True, +CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_MODIFIABLE: True, CKA_ENCRYPT: True, @@ -706,9 +689,7 @@ CKA_MODULUS_BITS: 1024, # long 1-MAX_RSA_KEY_NBITS CKA_PUBLIC_EXPONENT: 3, # byte CKA_LABEL: "RSA Public Key"} -CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_CLASS: CKO_PRIVATE_KEY, - CKA_KEY_TYPE: CKK_RSA, - CKA_TOKEN: True, +CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_MODIFIABLE: True, From f04708a7efb3d806464f589736742bf97ae4feb9 Mon Sep 17 00:00:00 2001 From: Kevin Safford Date: Thu, 22 Oct 2015 15:52:44 -0400 Subject: [PATCH 020/109] LA-1362 Add native Python HSM functions Add native Python functions for: - CA_GetHSMPolicySetting - CA_GetHSMCapabilitySetting - CA_SetHSMPolicies - CA_SetDestructiveHSMPolicies Change-Id: Ib58f75a33f8408686b9e3dce58e79082dadf2235 --- pycryptoki/daemon/pycryptoki_daemon.py | 6 +- pycryptoki/daemon/rpyc_pycryptoki.py | 42 +++--- pycryptoki/hsm_management.py | 169 ++++++++++++++++++++++++- pycryptoki/policy_management.py | 35 +---- pycryptoki/token_management.py | 54 -------- 5 files changed, 199 insertions(+), 107 deletions(-) diff --git a/pycryptoki/daemon/pycryptoki_daemon.py b/pycryptoki/daemon/pycryptoki_daemon.py index e1f06cc..145531b 100755 --- a/pycryptoki/daemon/pycryptoki_daemon.py +++ b/pycryptoki/daemon/pycryptoki_daemon.py @@ -25,9 +25,9 @@ c_create_object_ex from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex -from pycryptoki.policy_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ - ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex, \ - ca_set_container_policy, ca_set_container_policy_ex +from pycryptoki.policy_management import ca_set_container_policy, ca_set_container_policy_ex +from pycryptoki.hsm_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ + ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex from pycryptoki.session_management import c_initialize, c_initialize_ex, \ c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, c_get_token_info, \ c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 1fe843a..903e6b4 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -49,10 +49,7 @@ from pycryptoki.object_attr_lookup import (c_find_objects, c_find_objects_ex, c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex) -from pycryptoki.policy_management import (ca_set_hsm_policy, ca_set_hsm_policy_ex, - ca_set_destructive_hsm_policy, - ca_set_destructive_hsm_policy_ex, - ca_set_container_policy, ca_set_container_policy_ex) +from pycryptoki.policy_management import (ca_set_container_policy, ca_set_container_policy_ex) from pycryptoki.session_management import (c_initialize, c_initialize_ex, c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, @@ -78,8 +75,6 @@ c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex, - ca_get_hsm_policy_set_ex, ca_get_hsm_policy_set, - ca_get_hsm_capability_set_ex, ca_get_hsm_capability_set, ca_get_token_policies_ex, ca_get_token_policies) from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, ca_init_audit, ca_init_audit_ex, @@ -96,12 +91,21 @@ ca_deleteremotepedvector, ca_deleteremotepedvector_ex, ca_mtkrestore, ca_mtkrestore_ex, ca_mtkresplit, ca_mtkresplit_ex, - ca_mtkzeroize, ca_mtkzeroize_ex) + ca_mtkzeroize, ca_mtkzeroize_ex, ca_set_hsm_policy, + ca_set_hsm_policy_ex, ca_set_destructive_hsm_policy, + ca_set_destructive_hsm_policy_ex, ca_get_hsm_capability_set, + ca_get_hsm_capability_set_ex, ca_get_hsm_policy_set, + ca_get_hsm_policy_set_ex, ca_get_hsm_policy_setting, + ca_get_hsm_policy_setting_ex, ca_get_hsm_capability_setting, + ca_get_hsm_capability_setting_ex, ca_set_hsm_policies, + ca_set_hsm_policies_ex, ca_set_destructive_hsm_policies, + ca_set_destructive_hsm_policies_ex) from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, ca_modifyusagecount, ca_modifyusagecount_ex) from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, ca_duplicatemofn, ca_duplicatemofn_ex) from pycryptoki.cryptoki import CK_ULONG + CRYPTO_OPS = pycryptoki.cryptoki.__all__[:] logger = logging.getLogger(__name__) @@ -156,10 +160,6 @@ def _rpyc_getattr(self, name): exposed_c_get_mechanism_list_ex = staticmethod(c_get_mechanism_list_ex) exposed_c_get_mechanism_info = staticmethod(c_get_mechanism_info) exposed_c_get_mechanism_info_ex = staticmethod(c_get_mechanism_info_ex) - exposed_ca_get_hsm_policy_set = staticmethod(ca_get_hsm_policy_set) - exposed_ca_get_hsm_policy_set_ex = staticmethod(ca_get_hsm_policy_set_ex) - exposed_ca_get_hsm_capability_set = staticmethod(ca_get_hsm_capability_set) - exposed_ca_get_hsm_capability_set_ex = staticmethod(ca_get_hsm_capability_set_ex) exposed_ca_get_token_policies = staticmethod(ca_get_token_policies) exposed_ca_get_token_policies_ex = staticmethod(ca_get_token_policies_ex) @@ -208,10 +208,6 @@ def _rpyc_getattr(self, name): exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) # policy_management.py - exposed_ca_set_hsm_policy = staticmethod(ca_set_hsm_policy) - exposed_ca_set_hsm_policy_ex = staticmethod(ca_set_hsm_policy_ex) - exposed_ca_set_destructive_hsm_policy = staticmethod(ca_set_destructive_hsm_policy) - exposed_ca_set_destructive_hsm_policy_ex = staticmethod(ca_set_destructive_hsm_policy_ex) exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) @@ -282,6 +278,22 @@ def _rpyc_getattr(self, name): exposed_ca_mtkresplit_ex = staticmethod(ca_mtkresplit_ex) exposed_ca_mtkzeroize = staticmethod(ca_mtkzeroize) exposed_ca_mtkzeroize_ex = staticmethod(ca_mtkzeroize_ex) + exposed_ca_get_hsm_policy_set = staticmethod(ca_get_hsm_policy_set) + exposed_ca_get_hsm_policy_set_ex = staticmethod(ca_get_hsm_policy_set_ex) + exposed_ca_get_hsm_capability_set = staticmethod(ca_get_hsm_capability_set) + exposed_ca_get_hsm_capability_set_ex = staticmethod(ca_get_hsm_capability_set_ex) + exposed_ca_get_hsm_policy_setting = staticmethod(ca_get_hsm_policy_setting) + exposed_ca_get_hsm_policy_setting_ex = staticmethod(ca_get_hsm_policy_setting_ex) + exposed_ca_get_hsm_capability_setting = staticmethod(ca_get_hsm_capability_setting) + exposed_ca_get_hsm_capability_setting_ex = staticmethod(ca_get_hsm_capability_setting_ex) + exposed_ca_set_hsm_policy = staticmethod(ca_set_hsm_policy) + exposed_ca_set_hsm_policy_ex = staticmethod(ca_set_hsm_policy_ex) + exposed_ca_set_destructive_hsm_policy = staticmethod(ca_set_destructive_hsm_policy) + exposed_ca_set_destructive_hsm_policy_ex = staticmethod(ca_set_destructive_hsm_policy_ex) + exposed_ca_set_hsm_policies = staticmethod(ca_set_hsm_policies) + exposed_ca_set_hsm_policies_ex = staticmethod(ca_set_hsm_policies_ex) + exposed_ca_set_destructive_hsm_policies = staticmethod(ca_set_destructive_hsm_policies) + exposed_ca_set_destructive_hsm_policies_ex = staticmethod(ca_set_destructive_hsm_policies_ex) # key_management.py exposed_ca_generatemofn = staticmethod(ca_generatemofn) diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 87c406b..1db86eb 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -1,7 +1,9 @@ """ Methods responsible for pycryptoki 'hsm management' set of commands. """ +from _ctypes import pointer from ctypes import byref, create_string_buffer, cast +from pycryptoki.common_utils import AutoCArray, refresh_c_arrays from pycryptoki.cryptoki import (CK_SLOT_ID, CK_USER_TYPE, @@ -17,7 +19,10 @@ CK_BYTE_PTR, CK_BYTE, CK_CHAR_PTR, - CK_CHAR) + CK_CHAR, CA_SetHSMPolicy, CK_SESSION_HANDLE, CA_SetHSMPolicies, + CA_SetDestructiveHSMPolicy, CA_SetDestructiveHSMPolicies, + CA_GetHSMCapabilitySet, CA_GetHSMCapabilitySetting, + CA_GetHSMPolicySet, CA_GetHSMPolicySetting) from pycryptoki.attributes import Attributes from pycryptoki.test_functions import make_error_handle_function @@ -217,3 +222,165 @@ def ca_mtkzeroize(slot): ca_mtkzeroize_ex = make_error_handle_function(ca_mtkzeroize) + + +def ca_set_hsm_policy(h_session, policy_id, policy_val): + """Sets the HSM policies by calling CA_SetHSMPolicy + + :param h_session: The session handle of the administrator setting the HSM policy + :param policy_id: The ID of the policy being set + :param policy_val: The value of the policy being set + :returns: The result code + + """ + ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret + + +ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) + + +def ca_set_hsm_policies(h_session, policies): + """ + Set multiple HSM policies. + + :param h_session: session handle + :param policies: dict of policy ID ints and value ints + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + pol_id_list = policies.keys() + pol_val_list = policies.values() + pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) + pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) + + ret = CA_SetHSMPolicies(h_sess, pol_ids.size.contents, + pol_ids.array, pol_vals.array) + + return ret + + +ca_set_hsm_policies_ex = make_error_handle_function(ca_set_hsm_policies) + + +def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): + """Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy + + :param h_session: The session handle of the administrator setting the HSM policy + :param policy_id: The ID of the policy being set + :param policy_val: The value of the policy being set + :returns: The result code + + """ + ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret + + +ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) + + +def ca_set_destructive_hsm_policies(h_session, policies): + """ + Set multiple HSM policies. + + :param h_session: session handle + :param policies: dict of policy ID ints and value ints + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + pol_id_list = policies.keys() + pol_val_list = policies.values() + pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) + pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) + + ret = CA_SetDestructiveHSMPolicies(h_sess, pol_ids.size.contents, + pol_ids.array, pol_vals.array) + + return ret + + +ca_set_destructive_hsm_policies_ex = make_error_handle_function(ca_set_destructive_hsm_policies) + + +def ca_get_hsm_capability_set(slot): + """ + Get the capabilities of the given slot. + + :param int slot: Target slot number + :return: retcode, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_ULONG(slot) + cap_ids = AutoCArray() + cap_vals = AutoCArray() + + @refresh_c_arrays(1) + def _get_hsm_caps(): + """Closer for retries to work w/ properties + """ + return CA_GetHSMCapabilitySet(slot_id, cap_ids.array, cap_ids.size, + cap_vals.array, cap_vals.size) + + ret = _get_hsm_caps() + + return ret, dict(zip(cap_ids, cap_vals)) + + +ca_get_hsm_capability_set_ex = make_error_handle_function(ca_get_hsm_capability_set) + + +def ca_get_hsm_capability_setting(slot, capability_id): + """ + Get the value of a single capability + + :param slot: slot ID of slot to query + :param capability_id: capability ID + :return: result code, CK_ULONG representing capability active or not + """ + capability_val = CK_ULONG() + ret = CA_GetHSMCapabilitySetting(CK_ULONG(slot), CK_ULONG(capability_id), pointer(capability_val)) + return ret, capability_val.value + + +ca_get_hsm_capability_setting_ex = make_error_handle_function(ca_get_hsm_capability_setting) + + +def ca_get_hsm_policy_set(slot): + """ + Get the policies of the given slot. + + :param int slot: Target slot number + :return: retcode, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_ULONG(slot) + cap_ids = AutoCArray() + cap_vals = AutoCArray() + + @refresh_c_arrays(1) + def _ca_get_hsm_policy_set(): + """Closure for retries. + """ + return CA_GetHSMPolicySet(slot_id, cap_ids.array, cap_ids.size, + cap_vals.array, cap_vals.size) + + ret = _ca_get_hsm_policy_set() + + return ret, dict(zip(cap_ids, cap_vals)) + + +ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) + + +def ca_get_hsm_policy_setting(slot, policy_id): + """ + Get the value of a single policy + + :param slot: slot ID of slot to query + :param policy_id: policy ID + :return: result code, CK_ULONG representing policy active or not + """ + policy_val = CK_ULONG() + ret = CA_GetHSMPolicySetting(CK_ULONG(slot), CK_ULONG(policy_id), pointer(policy_val)) + return ret, policy_val.value + + +ca_get_hsm_policy_setting_ex = make_error_handle_function(ca_get_hsm_policy_setting) diff --git a/pycryptoki/policy_management.py b/pycryptoki/policy_management.py index f43cc7a..e1b960a 100755 --- a/pycryptoki/policy_management.py +++ b/pycryptoki/policy_management.py @@ -1,40 +1,7 @@ -from pycryptoki.cryptoki import CA_SetHSMPolicy, CA_SetContainerPolicy, CK_ULONG, \ - CA_SetDestructiveHSMPolicy +from pycryptoki.cryptoki import CA_SetContainerPolicy, CK_ULONG from pycryptoki.test_functions import make_error_handle_function -def ca_set_hsm_policy(h_session, policy_id, policy_val): - """Sets the HSM policies by calling CA_SetHSMPolicy - - :param h_session: The session handle of the administrator setting the HSM policy - :param policy_id: The ID of the policy being set - :param policy_val: The value of the policy being set - :returns: The result code - - """ - ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret - - -ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) - - -def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): - """Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy - - :param h_session: The session handle of the administrator setting the HSM policy - :param policy_id: The ID of the policy being set - :param policy_val: The value of the policy being set - :returns: The result code - - """ - ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret - - -ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) - - def ca_set_container_policy(h_session, container_number, policy_id, policy_val): """Sets a policy on the container. diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index 0556242..5cff5a7 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -20,8 +20,6 @@ C_GetSlotList, C_GetMechanismList, C_GetMechanismInfo, - CA_GetHSMCapabilitySet, - CA_GetHSMPolicySet, CA_GetTokenPolicies) from pycryptoki.session_management import c_get_token_info from pycryptoki.test_functions import make_error_handle_function @@ -135,58 +133,6 @@ def c_get_mechanism_info(slot, mechanism_type): c_get_mechanism_info_ex = make_error_handle_function(c_get_mechanism_info) -def ca_get_hsm_capability_set(slot): - """ - Get the capabilities of the given slot. - - :param int slot: Target slot number - :return: retcode, {id: val} dict of policies (None if command failed) - """ - slot_id = CK_ULONG(slot) - cap_ids = AutoCArray() - cap_vals = AutoCArray() - - @refresh_c_arrays(1) - def _get_hsm_caps(): - """Closer for retries to work w/ properties - """ - return CA_GetHSMCapabilitySet(slot_id, cap_ids.array, cap_ids.size, - cap_vals.array, cap_vals.size) - - ret = _get_hsm_caps() - - return ret, dict(zip(cap_ids, cap_vals)) - - -ca_get_hsm_capability_set_ex = make_error_handle_function(ca_get_hsm_capability_set) - - -def ca_get_hsm_policy_set(slot): - """ - Get the policies of the given slot. - - :param int slot: Target slot number - :return: retcode, {id: val} dict of policies (None if command failed) - """ - slot_id = CK_ULONG(slot) - cap_ids = AutoCArray() - cap_vals = AutoCArray() - - @refresh_c_arrays(1) - def _ca_get_hsm_policy_set(): - """Closure for retries. - """ - return CA_GetHSMPolicySet(slot_id, cap_ids.array, cap_ids.size, - cap_vals.array, cap_vals.size) - - ret = _ca_get_hsm_policy_set() - - return ret, dict(zip(cap_ids, cap_vals)) - - -ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) - - def ca_get_token_policies(slot): """ Get the policies of the given slot. From 6bcc2ea52a2f0a50ac60ad7cea18300022c1097c Mon Sep 17 00:00:00 2001 From: ksafford Date: Thu, 12 Nov 2015 15:39:02 -0500 Subject: [PATCH 021/109] LA-1424 Add native Python "Container" functions Add native Python functions for: - CA_GetContainerCapabilitySet - CA_GetContainerCapabilitySetting - CA_GetContainerList - CA_GetContainerName - CA_GetContainerPolicySet - CA_GetContainerPolicySetting - CA_GetContainerStatus - CA_GetContainerStorageInformation - CA_SetContainerPolicies - CA_SetContainerSize Change-Id: Ida4ef6ec5fa4a7ec5ad55b9c832e77760250afec --- pycryptoki/daemon/rpyc_pycryptoki.py | 66 ++++- pycryptoki/hsm_management.py | 32 ++- pycryptoki/partition_management.py | 412 +++++++++++++++++++++++++++ pycryptoki/policy_management.py | 22 -- pycryptoki/session_management.py | 54 ---- 5 files changed, 484 insertions(+), 102 deletions(-) create mode 100644 pycryptoki/partition_management.py delete mode 100755 pycryptoki/policy_management.py diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 903e6b4..4a35169 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -49,7 +49,6 @@ from pycryptoki.object_attr_lookup import (c_find_objects, c_find_objects_ex, c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex) -from pycryptoki.policy_management import (ca_set_container_policy, ca_set_container_policy_ex) from pycryptoki.session_management import (c_initialize, c_initialize_ex, c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, @@ -61,13 +60,10 @@ ca_factory_reset, ca_factory_reset_ex, c_set_pin, c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, - ca_create_container, ca_create_container_ex, login, login_ex, ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID, ca_closeapplicationID_ex, ca_restart, ca_restart_ex, - ca_delete_container_with_handle_ex, - ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex) from pycryptoki.sign_verify import (c_sign, c_sign_ex, c_verify, c_verify_ex) @@ -100,6 +96,32 @@ ca_get_hsm_capability_setting_ex, ca_set_hsm_policies, ca_set_hsm_policies_ex, ca_set_destructive_hsm_policies, ca_set_destructive_hsm_policies_ex) +from pycryptoki.partition_management import (ca_create_container, + ca_create_container_ex, + ca_delete_container_with_handle_ex, + ca_delete_container_with_handle, + ca_set_container_policy, + ca_set_container_policy_ex, + ca_get_container_capability_set, + ca_get_container_capability_set_ex, + ca_get_container_capability_setting, + ca_get_container_capability_setting_ex, + ca_get_container_list, + ca_get_container_list_ex, + ca_get_container_name, + ca_get_container_name_ex, + ca_get_container_policy_set, + ca_get_container_policy_set_ex, + ca_get_container_policy_setting, + ca_get_container_policy_setting_ex, + ca_get_container_status, + ca_get_container_status_ex, + ca_get_container_storage_information, + ca_get_container_storage_information_ex, + ca_set_container_policies, + ca_set_container_policies_ex, + ca_set_container_size, + ca_set_container_size_ex) from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, ca_modifyusagecount, ca_modifyusagecount_ex) from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, @@ -194,8 +216,6 @@ def _rpyc_getattr(self, name): exposed_ca_open_secure_token_ex = staticmethod(ca_open_secure_token_ex) exposed_c_close_all_sessions = staticmethod(c_close_all_sessions) exposed_c_close_all_sessions_ex = staticmethod(c_close_all_sessions_ex) - exposed_ca_create_container = staticmethod(ca_create_container) - exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) exposed_ca_openapplicationID_ex = staticmethod(ca_openapplicationID_ex) exposed_ca_openapplicationID = staticmethod(ca_openapplicationID) exposed_ca_closeapplicationID_ex = staticmethod(ca_closeapplicationID_ex) @@ -204,12 +224,6 @@ def _rpyc_getattr(self, name): exposed_ca_setapplicationID = staticmethod(ca_setapplicationID) exposed_ca_restart_ex = staticmethod(ca_restart_ex) exposed_ca_restart = staticmethod(ca_restart) - exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) - exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) - - # policy_management.py - exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) - exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) # object_attr_lookup.py exposed_c_find_objects = staticmethod(c_find_objects) @@ -295,6 +309,34 @@ def _rpyc_getattr(self, name): exposed_ca_set_destructive_hsm_policies = staticmethod(ca_set_destructive_hsm_policies) exposed_ca_set_destructive_hsm_policies_ex = staticmethod(ca_set_destructive_hsm_policies_ex) + # partition_management.py + exposed_ca_create_container = staticmethod(ca_create_container) + exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) + exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) + exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) + exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) + exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) + exposed_ca_get_container_capability_set = staticmethod(ca_get_container_capability_set) + exposed_ca_get_container_capability_set_ex = staticmethod(ca_get_container_capability_set_ex) + exposed_ca_get_container_capability_setting = staticmethod(ca_get_container_capability_setting) + exposed_ca_get_container_capability_setting_ex = staticmethod(ca_get_container_capability_setting_ex) + exposed_ca_get_container_list = staticmethod(ca_get_container_list) + exposed_ca_get_container_list_ex = staticmethod(ca_get_container_list_ex) + exposed_ca_get_container_name = staticmethod(ca_get_container_name) + exposed_ca_get_container_name_ex = staticmethod(ca_get_container_name_ex) + exposed_ca_get_container_policy_set = staticmethod(ca_get_container_policy_set) + exposed_ca_get_container_policy_set_ex = staticmethod(ca_get_container_policy_set_ex) + exposed_ca_get_container_policy_setting = staticmethod(ca_get_container_policy_setting) + exposed_ca_get_container_policy_setting_ex = staticmethod(ca_get_container_policy_setting_ex) + exposed_ca_get_container_status = staticmethod(ca_get_container_status) + exposed_ca_get_container_status_ex = staticmethod(ca_get_container_status_ex) + exposed_ca_get_container_storage_information = staticmethod(ca_get_container_storage_information) + exposed_ca_get_container_storage_information_ex = staticmethod(ca_get_container_storage_information_ex) + exposed_ca_set_container_policies = staticmethod(ca_set_container_policies) + exposed_ca_set_container_policies_ex = staticmethod(ca_set_container_policies_ex) + exposed_ca_set_container_size = staticmethod(ca_set_container_size) + exposed_ca_set_container_size_ex = staticmethod(ca_set_container_size_ex) + # key_management.py exposed_ca_generatemofn = staticmethod(ca_generatemofn) exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 1db86eb..243bfa3 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -307,9 +307,9 @@ def ca_get_hsm_capability_set(slot): Get the capabilities of the given slot. :param int slot: Target slot number - :return: retcode, {id: val} dict of policies (None if command failed) + :return: retcode, {id: val} dict of capabilities (None if command failed) """ - slot_id = CK_ULONG(slot) + slot_id = CK_SLOT_ID(slot) cap_ids = AutoCArray() cap_vals = AutoCArray() @@ -336,9 +336,11 @@ def ca_get_hsm_capability_setting(slot, capability_id): :param capability_id: capability ID :return: result code, CK_ULONG representing capability active or not """ - capability_val = CK_ULONG() - ret = CA_GetHSMCapabilitySetting(CK_ULONG(slot), CK_ULONG(capability_id), pointer(capability_val)) - return ret, capability_val.value + slot_id = CK_SLOT_ID(slot) + cap_id = CK_ULONG(capability_id) + cap_val = CK_ULONG() + ret = CA_GetHSMCapabilitySetting(slot_id, cap_id, pointer(cap_val)) + return ret, cap_val.value ca_get_hsm_capability_setting_ex = make_error_handle_function(ca_get_hsm_capability_setting) @@ -351,20 +353,20 @@ def ca_get_hsm_policy_set(slot): :param int slot: Target slot number :return: retcode, {id: val} dict of policies (None if command failed) """ - slot_id = CK_ULONG(slot) - cap_ids = AutoCArray() - cap_vals = AutoCArray() + slot_id = CK_SLOT_ID(slot) + pol_ids = AutoCArray() + pol_vals = AutoCArray() @refresh_c_arrays(1) def _ca_get_hsm_policy_set(): """Closure for retries. """ - return CA_GetHSMPolicySet(slot_id, cap_ids.array, cap_ids.size, - cap_vals.array, cap_vals.size) + return CA_GetHSMPolicySet(slot_id, pol_ids.array, pol_ids.size, + pol_vals.array, pol_vals.size) ret = _ca_get_hsm_policy_set() - return ret, dict(zip(cap_ids, cap_vals)) + return ret, dict(zip(pol_ids, pol_vals)) ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) @@ -378,9 +380,11 @@ def ca_get_hsm_policy_setting(slot, policy_id): :param policy_id: policy ID :return: result code, CK_ULONG representing policy active or not """ - policy_val = CK_ULONG() - ret = CA_GetHSMPolicySetting(CK_ULONG(slot), CK_ULONG(policy_id), pointer(policy_val)) - return ret, policy_val.value + slot_id = CK_SLOT_ID(slot) + pol_id = CK_ULONG(policy_id) + pol_val = CK_ULONG() + ret = CA_GetHSMPolicySetting(slot_id, pol_id, pointer(pol_val)) + return ret, pol_val.value ca_get_hsm_policy_setting_ex = make_error_handle_function(ca_get_hsm_policy_setting) diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py new file mode 100644 index 0000000..bb0aec2 --- /dev/null +++ b/pycryptoki/partition_management.py @@ -0,0 +1,412 @@ +""" +Functions for managing partitions +""" +from _ctypes import pointer +from ctypes import byref, c_ubyte +import logging +from pycryptoki.cryptoki import (CK_SLOT_ID, + CK_ULONG, + CK_SESSION_HANDLE, + CA_CreateContainer, + CA_DeleteContainerWithHandle, + CA_GetContainerList, + CA_GetContainerCapabilitySet, + CA_GetContainerCapabilitySetting, + CA_GetContainerPolicySet, + CA_GetContainerPolicySetting, + CA_GetContainerName, + CA_GetContainerStorageInformation, + CA_GetContainerStatus, + CA_SetContainerPolicy, + CA_SetContainerPolicies, + CA_SetContainerSize) +from pycryptoki.defines import (LUNA_PARTITION_TYPE_STANDALONE, + LUNA_CF_CONTAINER_ENABLED, + LUNA_CF_KCV_CREATED, + LUNA_CF_LKCV_CREATED, + LUNA_CF_HA_INITIALIZED, + LUNA_CF_PARTITION_INITIALIZED, + LUNA_CF_CONTAINER_ACTIVATED, + LUNA_CF_CONTAINER_LUSR_ACTIVATED, + LUNA_CF_USER_PIN_INITIALIZED, + LUNA_CF_SO_PIN_LOCKED, + LUNA_CF_SO_PIN_TO_BE_CHANGED, + LUNA_CF_USER_PIN_LOCKED, + LUNA_CF_LIMITED_USER_PIN_LOCKED, + LUNA_CF_LIMITED_USER_CREATED, + LUNA_CF_USER_PIN_TO_BE_CHANGED, + LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED) +from pycryptoki.common_utils import AutoCArray, refresh_c_arrays +from pycryptoki.test_functions import make_error_handle_function + + +LOG = logging.getLogger(__name__) + + +def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): + """Inserts a token into a slot without a Security Officer on the token + + :param h_session: Current session + :param storage_size: The storage size of the token (0 for undefined/unlimited) + :param password: The password associated with the token (Default value = 'userpin') + :param label: The label associated with the token (Default value = 'Inserted Token') + :returns: The result code, The container number + + """ + h_sess = CK_SESSION_HANDLE(h_session) + h_container = CK_ULONG() + LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( + storage_size) + ", pin=" + str(password) + ", label=" + label) + + if password == '': + password = None + + password = AutoCArray(data=password) + label = AutoCArray(data=label) + + ret = CA_CreateContainer(h_sess, CK_ULONG(0), + label.array, label.size.contents, + password.array, password.size.contents, + CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), + CK_ULONG(storage_size), byref(h_container)) + LOG.info("CA_CreateContainer: Inserted token into slot " + str(h_container.value)) + return ret, h_container.value + + +ca_create_container_ex = make_error_handle_function(ca_create_container) + + +def ca_delete_container_with_handle(h_session, h_container): + """ + Delete a container by handle + + :param h_session: session + :param h_container: target container handle + """ + h_sess = CK_SESSION_HANDLE(h_session) + container_id = CK_ULONG(h_container) + LOG.info( + "CA_DeleteContainerWithHandle: " + "Attempting to delete container with handle: %s", h_container) + + ret = CA_DeleteContainerWithHandle(h_sess, container_id) + + LOG.info("CA_DeleteContainerWithHandle: Ret Value: %s", ret) + + return ret + + +ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) + + +def ca_get_container_list(slot, group_handle=0, container_type=LUNA_PARTITION_TYPE_STANDALONE): + """ + """ + slot_id = CK_SLOT_ID(slot) + group = CK_ULONG(group_handle) + cont_type = CK_ULONG(container_type) + cont_handles = AutoCArray() + + @refresh_c_arrays(1) + def _get_cont_list(): + """Closer for retries to work w/ properties + """ + return CA_GetContainerList(slot_id, group, cont_type, + cont_handles.array, cont_handles.size) + + ret = _get_cont_list() + + return ret, list(cont_handles.array) + + +ca_get_container_list_ex = make_error_handle_function(ca_get_container_list) + + +def ca_get_container_capability_set(slot, h_container): + """ + Get the container capabilities of the given slot. + + :param int slot: target slot number + :param int h_container: target container handle + :return: retcode, {id: val} dict of capabilities (None if command failed) + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + cap_ids = AutoCArray() + cap_vals = AutoCArray() + + @refresh_c_arrays(1) + def _get_container_caps(): + """Closer for retries to work w/ properties + """ + return CA_GetContainerCapabilitySet(slot_id, + cont_id, + cap_ids.array, + cap_ids.size, + cap_vals.array, + cap_vals.size) + + ret = _get_container_caps() + + return ret, dict(zip(cap_ids, cap_vals)) + + +ca_get_container_capability_set_ex = make_error_handle_function(ca_get_container_capability_set) + + +def ca_get_container_capability_setting(slot, h_container, capability_id): + """ + Get the value of a container's single capability + + :param slot: slot ID of slot to query + :param h_container: target container handle + :param capability_id: capability ID + :return: result code, CK_ULONG representing capability active or not + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + cap_id = CK_ULONG(capability_id) + cap_val = CK_ULONG() + ret = CA_GetContainerCapabilitySetting(slot_id, + cont_id, + cap_id, + pointer(cap_val)) + return ret, cap_val.value + + +ca_get_container_capability_setting_ex = make_error_handle_function(ca_get_container_capability_setting) + + +def ca_get_container_policy_set(slot, h_container): + """ + Get the policies of the given slot and container. + + :param int slot: target slot number + :param int h_container: target container handle + :return: retcode, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + pol_ids = AutoCArray() + pol_vals = AutoCArray() + + @refresh_c_arrays(1) + def _ca_get_container_policy_set(): + """Closure for retries. + """ + return CA_GetContainerPolicySet(slot_id, + cont_id, + pol_ids.array, + pol_ids.size, + pol_vals.array, + pol_vals.size) + + ret = _ca_get_container_policy_set() + + return ret, dict(zip(pol_ids, pol_vals)) + + +ca_get_container_policy_set_ex = make_error_handle_function(ca_get_container_policy_set) + + +def ca_get_container_policy_setting(slot, h_container, policy_id): + """ + Get the value of a container's single policy + + :param slot: slot ID of slot to query + :param h_container: target container handle + :param policy_id: policy ID + :return: result code, CK_ULONG representing policy active or not + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + pol_id = CK_ULONG(policy_id) + pol_val = CK_ULONG() + ret = CA_GetContainerPolicySetting(slot_id, cont_id, pol_id, pointer(pol_val)) + return ret, pol_val.value + + +ca_get_container_policy_setting_ex = make_error_handle_function(ca_get_container_policy_setting) + + +def ca_get_container_name(slot, h_container): + """ + Get a container's name + + :param slot: target slot + :param h_container: target container handle + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + name_arr = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _ca_get_container_name(): + """ + Closure for retries + """ + return CA_GetContainerName(slot_id, + cont_id, + name_arr.array, + name_arr.size) + ret = _ca_get_container_name() + + return ret, ''.join(map(chr, name_arr.array)) + + +ca_get_container_name_ex = make_error_handle_function(ca_get_container_name) + + +def ca_get_container_storage_information(slot, h_container): + """ + Get a container's storage information + + :param slot: target slot + :param h_container: target container handle + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + overhead = CK_ULONG() + total = CK_ULONG() + used = CK_ULONG() + free = CK_ULONG() + obj_count = CK_ULONG() + + ret = CA_GetContainerStorageInformation(slot_id, + cont_id, + pointer(overhead), + pointer(total), + pointer(used), + pointer(free), + pointer(obj_count)) + return ret, {'overhead': overhead.value, + 'total': total.value, + 'used': used.value, + 'free': free.value, + 'object_count': obj_count.value} + + +ca_get_container_storage_information_ex = make_error_handle_function(ca_get_container_storage_information) + + +def ca_get_container_status(slot, h_container): + """ + Get a container's Status + + :param slot: target slot + :param h_container: target container handle + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + status_flags = CK_ULONG() + failed_so_logins = CK_ULONG() + failed_user_logins = CK_ULONG() + failed_limited_user_logins = CK_ULONG() + + ret = CA_GetContainerStatus(slot_id, + cont_id, + pointer(status_flags), + pointer(failed_so_logins), + pointer(failed_user_logins), + pointer(failed_limited_user_logins)) + flags_dict = { + 'container_enabled': LUNA_CF_CONTAINER_ENABLED, + 'kcv_created': LUNA_CF_KCV_CREATED, + 'lkcv_created': LUNA_CF_LKCV_CREATED, + 'ha_initialized': LUNA_CF_HA_INITIALIZED, + 'partition_initialized': LUNA_CF_PARTITION_INITIALIZED, + 'container_activated': LUNA_CF_CONTAINER_ACTIVATED, + 'container_lusr_activated': LUNA_CF_CONTAINER_LUSR_ACTIVATED, + 'user_pin_initialized': LUNA_CF_USER_PIN_INITIALIZED, + 'so_pin_locked': LUNA_CF_SO_PIN_LOCKED, + 'so_pin_to_be_changed': LUNA_CF_SO_PIN_TO_BE_CHANGED, + 'user_pin_locked': LUNA_CF_USER_PIN_LOCKED, + 'limited_user_pin_locked': LUNA_CF_LIMITED_USER_PIN_LOCKED, + 'limited_user_created': LUNA_CF_LIMITED_USER_CREATED, + 'user_pin_to_be_changed': LUNA_CF_USER_PIN_TO_BE_CHANGED, + 'limited_user_pin_to_be_changed': LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED + } + for key, flag in flags_dict.iteritems(): + flags_dict[key] = 1 if flag & status_flags.value else 0 + + failed_logins_dict = { + 'failed_so_logins': failed_so_logins.value, + 'failed_user_logins': failed_user_logins.value, + 'failed_limited_user_logins': failed_limited_user_logins.value + } + return ret, flags_dict, failed_logins_dict + + +ca_get_container_status_ex = make_error_handle_function(ca_get_container_status) + + +def ca_set_container_policy(h_session, h_containerber, policy_id, policy_val): + """Sets a policy on the container. + + NOTE: With per partition SO this method should generally not be used. Instead + ca_set_partition_policies should be used + + :param h_session: The session handle of the entity with permission to change the policy + :param h_containerber: The container number to set the policy on. + :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) + :param policy_val: The value to set the policy to + :returns: The result code + + """ + ret = CA_SetContainerPolicy(CK_SESSION_HANDLE(h_session), + CK_ULONG(h_containerber), + CK_ULONG(policy_id), + CK_ULONG(policy_val)) + return ret + + +ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) + + +def ca_set_container_policies(h_session, h_container, policies): + """ + Set multiple container policies. + + :param h_session: session handle + :param h_container: target container handle + :param policies: dict of policy ID ints and value ints + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + container_id = CK_ULONG(h_container) + pol_id_list = policies.keys() + pol_val_list = policies.values() + pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) + pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) + + ret = CA_SetContainerPolicies(h_sess, + container_id, + pol_ids.size.contents, + pol_ids.array, + pol_vals.array) + + return ret + + +ca_set_container_policies_ex = make_error_handle_function(ca_set_container_policies) + + +def ca_set_container_size(h_session, h_container, size): + """ + Set a container's size + + :param h_session: session handle + :param h_container: target container handle + :param size: size + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + container_id = CK_ULONG(h_container) + size = CK_ULONG(size) + ret = CA_SetContainerSize(h_sess, + container_id, + size) + return ret + + +ca_set_container_size_ex = make_error_handle_function(ca_set_container_size) diff --git a/pycryptoki/policy_management.py b/pycryptoki/policy_management.py deleted file mode 100755 index e1b960a..0000000 --- a/pycryptoki/policy_management.py +++ /dev/null @@ -1,22 +0,0 @@ -from pycryptoki.cryptoki import CA_SetContainerPolicy, CK_ULONG -from pycryptoki.test_functions import make_error_handle_function - - -def ca_set_container_policy(h_session, container_number, policy_id, policy_val): - """Sets a policy on the container. - - NOTE: With per partition SO this method should generally not be used. Instead - ca_set_partition_policies should be used - - :param h_session: The session handle of the entity with permission to change the policy - :param container_number: The container number to set the policy on. - :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) - :param policy_val: The value to set the policy to - :returns: The result code - - """ - ret = CA_SetContainerPolicy(h_session, CK_ULONG(container_number), CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret - - -ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index f80eec7..f47f545 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -357,60 +357,6 @@ def c_close_all_sessions(slot): c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) -def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): - """Inserts a token into a slot without a Security Officer on the token - - :param h_session: Current session - :param storage_size: The storage size of the token (0 for undefined/unlimited) - :param password: The password associated with the token (Default value = 'userpin') - :param label: The label associated with the token (Default value = 'Inserted Token') - :returns: The result code, The container number - - """ - container_number = CK_ULONG() - LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( - storage_size) + ", pin=" + str(password) + ", label=" + label) - - if password == '': - password = None - - password = AutoCArray(data=password) - label = AutoCArray(data=label) - - ret = CA_CreateContainer(h_session, CK_ULONG(0), - label.array, label.size.contents, - password.array, password.size.contents, - CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), - CK_ULONG(storage_size), byref(container_number)) - LOG.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) - return ret, container_number.value - - -ca_create_container_ex = make_error_handle_function(ca_create_container) - - -def ca_delete_container_with_handle(h_session, container_handle): - """ - - :param h_session: - :param container_handle: - - """ - container_number = CK_ULONG(container_handle) - LOG.info( - "CA_DeleteContainerWithHandle: " - "Attempting to delete container with handle: %s", container_handle) - - ret = CA_DeleteContainerWithHandle(h_session, container_number) - - LOG.info("CA_DeleteContainerWithHandle: Ret Value: %s", ret) - - return ret - - -ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) - - def ca_openapplicationID(slot, id_high, id_low): """ From e318c81e91e7e3f7bb4635dd9950eecd606eadd9 Mon Sep 17 00:00:00 2001 From: "Straw, Ashley" Date: Thu, 3 Dec 2015 09:38:54 -0500 Subject: [PATCH 022/109] LA-1424 Revert -- Add native Python "Container" functions Broken import in pycryptoki_daemon. This reverts commit 6bcc2ea52a2f0a50ac60ad7cea18300022c1097c. Change-Id: I0ef5899c7597def2ea23ad7d005fbc7e679ab819 --- pycryptoki/daemon/rpyc_pycryptoki.py | 66 +---- pycryptoki/hsm_management.py | 32 +-- pycryptoki/partition_management.py | 412 --------------------------- pycryptoki/policy_management.py | 22 ++ pycryptoki/session_management.py | 54 ++++ 5 files changed, 102 insertions(+), 484 deletions(-) delete mode 100644 pycryptoki/partition_management.py create mode 100755 pycryptoki/policy_management.py diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 4a35169..903e6b4 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -49,6 +49,7 @@ from pycryptoki.object_attr_lookup import (c_find_objects, c_find_objects_ex, c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex) +from pycryptoki.policy_management import (ca_set_container_policy, ca_set_container_policy_ex) from pycryptoki.session_management import (c_initialize, c_initialize_ex, c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, @@ -60,10 +61,13 @@ ca_factory_reset, ca_factory_reset_ex, c_set_pin, c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, + ca_create_container, ca_create_container_ex, login, login_ex, ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID, ca_closeapplicationID_ex, ca_restart, ca_restart_ex, + ca_delete_container_with_handle_ex, + ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex) from pycryptoki.sign_verify import (c_sign, c_sign_ex, c_verify, c_verify_ex) @@ -96,32 +100,6 @@ ca_get_hsm_capability_setting_ex, ca_set_hsm_policies, ca_set_hsm_policies_ex, ca_set_destructive_hsm_policies, ca_set_destructive_hsm_policies_ex) -from pycryptoki.partition_management import (ca_create_container, - ca_create_container_ex, - ca_delete_container_with_handle_ex, - ca_delete_container_with_handle, - ca_set_container_policy, - ca_set_container_policy_ex, - ca_get_container_capability_set, - ca_get_container_capability_set_ex, - ca_get_container_capability_setting, - ca_get_container_capability_setting_ex, - ca_get_container_list, - ca_get_container_list_ex, - ca_get_container_name, - ca_get_container_name_ex, - ca_get_container_policy_set, - ca_get_container_policy_set_ex, - ca_get_container_policy_setting, - ca_get_container_policy_setting_ex, - ca_get_container_status, - ca_get_container_status_ex, - ca_get_container_storage_information, - ca_get_container_storage_information_ex, - ca_set_container_policies, - ca_set_container_policies_ex, - ca_set_container_size, - ca_set_container_size_ex) from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, ca_modifyusagecount, ca_modifyusagecount_ex) from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, @@ -216,6 +194,8 @@ def _rpyc_getattr(self, name): exposed_ca_open_secure_token_ex = staticmethod(ca_open_secure_token_ex) exposed_c_close_all_sessions = staticmethod(c_close_all_sessions) exposed_c_close_all_sessions_ex = staticmethod(c_close_all_sessions_ex) + exposed_ca_create_container = staticmethod(ca_create_container) + exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) exposed_ca_openapplicationID_ex = staticmethod(ca_openapplicationID_ex) exposed_ca_openapplicationID = staticmethod(ca_openapplicationID) exposed_ca_closeapplicationID_ex = staticmethod(ca_closeapplicationID_ex) @@ -224,6 +204,12 @@ def _rpyc_getattr(self, name): exposed_ca_setapplicationID = staticmethod(ca_setapplicationID) exposed_ca_restart_ex = staticmethod(ca_restart_ex) exposed_ca_restart = staticmethod(ca_restart) + exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) + exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) + + # policy_management.py + exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) + exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) # object_attr_lookup.py exposed_c_find_objects = staticmethod(c_find_objects) @@ -309,34 +295,6 @@ def _rpyc_getattr(self, name): exposed_ca_set_destructive_hsm_policies = staticmethod(ca_set_destructive_hsm_policies) exposed_ca_set_destructive_hsm_policies_ex = staticmethod(ca_set_destructive_hsm_policies_ex) - # partition_management.py - exposed_ca_create_container = staticmethod(ca_create_container) - exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) - exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) - exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) - exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) - exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) - exposed_ca_get_container_capability_set = staticmethod(ca_get_container_capability_set) - exposed_ca_get_container_capability_set_ex = staticmethod(ca_get_container_capability_set_ex) - exposed_ca_get_container_capability_setting = staticmethod(ca_get_container_capability_setting) - exposed_ca_get_container_capability_setting_ex = staticmethod(ca_get_container_capability_setting_ex) - exposed_ca_get_container_list = staticmethod(ca_get_container_list) - exposed_ca_get_container_list_ex = staticmethod(ca_get_container_list_ex) - exposed_ca_get_container_name = staticmethod(ca_get_container_name) - exposed_ca_get_container_name_ex = staticmethod(ca_get_container_name_ex) - exposed_ca_get_container_policy_set = staticmethod(ca_get_container_policy_set) - exposed_ca_get_container_policy_set_ex = staticmethod(ca_get_container_policy_set_ex) - exposed_ca_get_container_policy_setting = staticmethod(ca_get_container_policy_setting) - exposed_ca_get_container_policy_setting_ex = staticmethod(ca_get_container_policy_setting_ex) - exposed_ca_get_container_status = staticmethod(ca_get_container_status) - exposed_ca_get_container_status_ex = staticmethod(ca_get_container_status_ex) - exposed_ca_get_container_storage_information = staticmethod(ca_get_container_storage_information) - exposed_ca_get_container_storage_information_ex = staticmethod(ca_get_container_storage_information_ex) - exposed_ca_set_container_policies = staticmethod(ca_set_container_policies) - exposed_ca_set_container_policies_ex = staticmethod(ca_set_container_policies_ex) - exposed_ca_set_container_size = staticmethod(ca_set_container_size) - exposed_ca_set_container_size_ex = staticmethod(ca_set_container_size_ex) - # key_management.py exposed_ca_generatemofn = staticmethod(ca_generatemofn) exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 243bfa3..1db86eb 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -307,9 +307,9 @@ def ca_get_hsm_capability_set(slot): Get the capabilities of the given slot. :param int slot: Target slot number - :return: retcode, {id: val} dict of capabilities (None if command failed) + :return: retcode, {id: val} dict of policies (None if command failed) """ - slot_id = CK_SLOT_ID(slot) + slot_id = CK_ULONG(slot) cap_ids = AutoCArray() cap_vals = AutoCArray() @@ -336,11 +336,9 @@ def ca_get_hsm_capability_setting(slot, capability_id): :param capability_id: capability ID :return: result code, CK_ULONG representing capability active or not """ - slot_id = CK_SLOT_ID(slot) - cap_id = CK_ULONG(capability_id) - cap_val = CK_ULONG() - ret = CA_GetHSMCapabilitySetting(slot_id, cap_id, pointer(cap_val)) - return ret, cap_val.value + capability_val = CK_ULONG() + ret = CA_GetHSMCapabilitySetting(CK_ULONG(slot), CK_ULONG(capability_id), pointer(capability_val)) + return ret, capability_val.value ca_get_hsm_capability_setting_ex = make_error_handle_function(ca_get_hsm_capability_setting) @@ -353,20 +351,20 @@ def ca_get_hsm_policy_set(slot): :param int slot: Target slot number :return: retcode, {id: val} dict of policies (None if command failed) """ - slot_id = CK_SLOT_ID(slot) - pol_ids = AutoCArray() - pol_vals = AutoCArray() + slot_id = CK_ULONG(slot) + cap_ids = AutoCArray() + cap_vals = AutoCArray() @refresh_c_arrays(1) def _ca_get_hsm_policy_set(): """Closure for retries. """ - return CA_GetHSMPolicySet(slot_id, pol_ids.array, pol_ids.size, - pol_vals.array, pol_vals.size) + return CA_GetHSMPolicySet(slot_id, cap_ids.array, cap_ids.size, + cap_vals.array, cap_vals.size) ret = _ca_get_hsm_policy_set() - return ret, dict(zip(pol_ids, pol_vals)) + return ret, dict(zip(cap_ids, cap_vals)) ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) @@ -380,11 +378,9 @@ def ca_get_hsm_policy_setting(slot, policy_id): :param policy_id: policy ID :return: result code, CK_ULONG representing policy active or not """ - slot_id = CK_SLOT_ID(slot) - pol_id = CK_ULONG(policy_id) - pol_val = CK_ULONG() - ret = CA_GetHSMPolicySetting(slot_id, pol_id, pointer(pol_val)) - return ret, pol_val.value + policy_val = CK_ULONG() + ret = CA_GetHSMPolicySetting(CK_ULONG(slot), CK_ULONG(policy_id), pointer(policy_val)) + return ret, policy_val.value ca_get_hsm_policy_setting_ex = make_error_handle_function(ca_get_hsm_policy_setting) diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py deleted file mode 100644 index bb0aec2..0000000 --- a/pycryptoki/partition_management.py +++ /dev/null @@ -1,412 +0,0 @@ -""" -Functions for managing partitions -""" -from _ctypes import pointer -from ctypes import byref, c_ubyte -import logging -from pycryptoki.cryptoki import (CK_SLOT_ID, - CK_ULONG, - CK_SESSION_HANDLE, - CA_CreateContainer, - CA_DeleteContainerWithHandle, - CA_GetContainerList, - CA_GetContainerCapabilitySet, - CA_GetContainerCapabilitySetting, - CA_GetContainerPolicySet, - CA_GetContainerPolicySetting, - CA_GetContainerName, - CA_GetContainerStorageInformation, - CA_GetContainerStatus, - CA_SetContainerPolicy, - CA_SetContainerPolicies, - CA_SetContainerSize) -from pycryptoki.defines import (LUNA_PARTITION_TYPE_STANDALONE, - LUNA_CF_CONTAINER_ENABLED, - LUNA_CF_KCV_CREATED, - LUNA_CF_LKCV_CREATED, - LUNA_CF_HA_INITIALIZED, - LUNA_CF_PARTITION_INITIALIZED, - LUNA_CF_CONTAINER_ACTIVATED, - LUNA_CF_CONTAINER_LUSR_ACTIVATED, - LUNA_CF_USER_PIN_INITIALIZED, - LUNA_CF_SO_PIN_LOCKED, - LUNA_CF_SO_PIN_TO_BE_CHANGED, - LUNA_CF_USER_PIN_LOCKED, - LUNA_CF_LIMITED_USER_PIN_LOCKED, - LUNA_CF_LIMITED_USER_CREATED, - LUNA_CF_USER_PIN_TO_BE_CHANGED, - LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED) -from pycryptoki.common_utils import AutoCArray, refresh_c_arrays -from pycryptoki.test_functions import make_error_handle_function - - -LOG = logging.getLogger(__name__) - - -def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): - """Inserts a token into a slot without a Security Officer on the token - - :param h_session: Current session - :param storage_size: The storage size of the token (0 for undefined/unlimited) - :param password: The password associated with the token (Default value = 'userpin') - :param label: The label associated with the token (Default value = 'Inserted Token') - :returns: The result code, The container number - - """ - h_sess = CK_SESSION_HANDLE(h_session) - h_container = CK_ULONG() - LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( - storage_size) + ", pin=" + str(password) + ", label=" + label) - - if password == '': - password = None - - password = AutoCArray(data=password) - label = AutoCArray(data=label) - - ret = CA_CreateContainer(h_sess, CK_ULONG(0), - label.array, label.size.contents, - password.array, password.size.contents, - CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), - CK_ULONG(storage_size), byref(h_container)) - LOG.info("CA_CreateContainer: Inserted token into slot " + str(h_container.value)) - return ret, h_container.value - - -ca_create_container_ex = make_error_handle_function(ca_create_container) - - -def ca_delete_container_with_handle(h_session, h_container): - """ - Delete a container by handle - - :param h_session: session - :param h_container: target container handle - """ - h_sess = CK_SESSION_HANDLE(h_session) - container_id = CK_ULONG(h_container) - LOG.info( - "CA_DeleteContainerWithHandle: " - "Attempting to delete container with handle: %s", h_container) - - ret = CA_DeleteContainerWithHandle(h_sess, container_id) - - LOG.info("CA_DeleteContainerWithHandle: Ret Value: %s", ret) - - return ret - - -ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) - - -def ca_get_container_list(slot, group_handle=0, container_type=LUNA_PARTITION_TYPE_STANDALONE): - """ - """ - slot_id = CK_SLOT_ID(slot) - group = CK_ULONG(group_handle) - cont_type = CK_ULONG(container_type) - cont_handles = AutoCArray() - - @refresh_c_arrays(1) - def _get_cont_list(): - """Closer for retries to work w/ properties - """ - return CA_GetContainerList(slot_id, group, cont_type, - cont_handles.array, cont_handles.size) - - ret = _get_cont_list() - - return ret, list(cont_handles.array) - - -ca_get_container_list_ex = make_error_handle_function(ca_get_container_list) - - -def ca_get_container_capability_set(slot, h_container): - """ - Get the container capabilities of the given slot. - - :param int slot: target slot number - :param int h_container: target container handle - :return: retcode, {id: val} dict of capabilities (None if command failed) - """ - slot_id = CK_SLOT_ID(slot) - cont_id = CK_ULONG(h_container) - cap_ids = AutoCArray() - cap_vals = AutoCArray() - - @refresh_c_arrays(1) - def _get_container_caps(): - """Closer for retries to work w/ properties - """ - return CA_GetContainerCapabilitySet(slot_id, - cont_id, - cap_ids.array, - cap_ids.size, - cap_vals.array, - cap_vals.size) - - ret = _get_container_caps() - - return ret, dict(zip(cap_ids, cap_vals)) - - -ca_get_container_capability_set_ex = make_error_handle_function(ca_get_container_capability_set) - - -def ca_get_container_capability_setting(slot, h_container, capability_id): - """ - Get the value of a container's single capability - - :param slot: slot ID of slot to query - :param h_container: target container handle - :param capability_id: capability ID - :return: result code, CK_ULONG representing capability active or not - """ - slot_id = CK_SLOT_ID(slot) - cont_id = CK_ULONG(h_container) - cap_id = CK_ULONG(capability_id) - cap_val = CK_ULONG() - ret = CA_GetContainerCapabilitySetting(slot_id, - cont_id, - cap_id, - pointer(cap_val)) - return ret, cap_val.value - - -ca_get_container_capability_setting_ex = make_error_handle_function(ca_get_container_capability_setting) - - -def ca_get_container_policy_set(slot, h_container): - """ - Get the policies of the given slot and container. - - :param int slot: target slot number - :param int h_container: target container handle - :return: retcode, {id: val} dict of policies (None if command failed) - """ - slot_id = CK_SLOT_ID(slot) - cont_id = CK_ULONG(h_container) - pol_ids = AutoCArray() - pol_vals = AutoCArray() - - @refresh_c_arrays(1) - def _ca_get_container_policy_set(): - """Closure for retries. - """ - return CA_GetContainerPolicySet(slot_id, - cont_id, - pol_ids.array, - pol_ids.size, - pol_vals.array, - pol_vals.size) - - ret = _ca_get_container_policy_set() - - return ret, dict(zip(pol_ids, pol_vals)) - - -ca_get_container_policy_set_ex = make_error_handle_function(ca_get_container_policy_set) - - -def ca_get_container_policy_setting(slot, h_container, policy_id): - """ - Get the value of a container's single policy - - :param slot: slot ID of slot to query - :param h_container: target container handle - :param policy_id: policy ID - :return: result code, CK_ULONG representing policy active or not - """ - slot_id = CK_SLOT_ID(slot) - cont_id = CK_ULONG(h_container) - pol_id = CK_ULONG(policy_id) - pol_val = CK_ULONG() - ret = CA_GetContainerPolicySetting(slot_id, cont_id, pol_id, pointer(pol_val)) - return ret, pol_val.value - - -ca_get_container_policy_setting_ex = make_error_handle_function(ca_get_container_policy_setting) - - -def ca_get_container_name(slot, h_container): - """ - Get a container's name - - :param slot: target slot - :param h_container: target container handle - """ - slot_id = CK_SLOT_ID(slot) - cont_id = CK_ULONG(h_container) - name_arr = AutoCArray(ctype=c_ubyte) - - @refresh_c_arrays(1) - def _ca_get_container_name(): - """ - Closure for retries - """ - return CA_GetContainerName(slot_id, - cont_id, - name_arr.array, - name_arr.size) - ret = _ca_get_container_name() - - return ret, ''.join(map(chr, name_arr.array)) - - -ca_get_container_name_ex = make_error_handle_function(ca_get_container_name) - - -def ca_get_container_storage_information(slot, h_container): - """ - Get a container's storage information - - :param slot: target slot - :param h_container: target container handle - """ - slot_id = CK_SLOT_ID(slot) - cont_id = CK_ULONG(h_container) - overhead = CK_ULONG() - total = CK_ULONG() - used = CK_ULONG() - free = CK_ULONG() - obj_count = CK_ULONG() - - ret = CA_GetContainerStorageInformation(slot_id, - cont_id, - pointer(overhead), - pointer(total), - pointer(used), - pointer(free), - pointer(obj_count)) - return ret, {'overhead': overhead.value, - 'total': total.value, - 'used': used.value, - 'free': free.value, - 'object_count': obj_count.value} - - -ca_get_container_storage_information_ex = make_error_handle_function(ca_get_container_storage_information) - - -def ca_get_container_status(slot, h_container): - """ - Get a container's Status - - :param slot: target slot - :param h_container: target container handle - """ - slot_id = CK_SLOT_ID(slot) - cont_id = CK_ULONG(h_container) - status_flags = CK_ULONG() - failed_so_logins = CK_ULONG() - failed_user_logins = CK_ULONG() - failed_limited_user_logins = CK_ULONG() - - ret = CA_GetContainerStatus(slot_id, - cont_id, - pointer(status_flags), - pointer(failed_so_logins), - pointer(failed_user_logins), - pointer(failed_limited_user_logins)) - flags_dict = { - 'container_enabled': LUNA_CF_CONTAINER_ENABLED, - 'kcv_created': LUNA_CF_KCV_CREATED, - 'lkcv_created': LUNA_CF_LKCV_CREATED, - 'ha_initialized': LUNA_CF_HA_INITIALIZED, - 'partition_initialized': LUNA_CF_PARTITION_INITIALIZED, - 'container_activated': LUNA_CF_CONTAINER_ACTIVATED, - 'container_lusr_activated': LUNA_CF_CONTAINER_LUSR_ACTIVATED, - 'user_pin_initialized': LUNA_CF_USER_PIN_INITIALIZED, - 'so_pin_locked': LUNA_CF_SO_PIN_LOCKED, - 'so_pin_to_be_changed': LUNA_CF_SO_PIN_TO_BE_CHANGED, - 'user_pin_locked': LUNA_CF_USER_PIN_LOCKED, - 'limited_user_pin_locked': LUNA_CF_LIMITED_USER_PIN_LOCKED, - 'limited_user_created': LUNA_CF_LIMITED_USER_CREATED, - 'user_pin_to_be_changed': LUNA_CF_USER_PIN_TO_BE_CHANGED, - 'limited_user_pin_to_be_changed': LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED - } - for key, flag in flags_dict.iteritems(): - flags_dict[key] = 1 if flag & status_flags.value else 0 - - failed_logins_dict = { - 'failed_so_logins': failed_so_logins.value, - 'failed_user_logins': failed_user_logins.value, - 'failed_limited_user_logins': failed_limited_user_logins.value - } - return ret, flags_dict, failed_logins_dict - - -ca_get_container_status_ex = make_error_handle_function(ca_get_container_status) - - -def ca_set_container_policy(h_session, h_containerber, policy_id, policy_val): - """Sets a policy on the container. - - NOTE: With per partition SO this method should generally not be used. Instead - ca_set_partition_policies should be used - - :param h_session: The session handle of the entity with permission to change the policy - :param h_containerber: The container number to set the policy on. - :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) - :param policy_val: The value to set the policy to - :returns: The result code - - """ - ret = CA_SetContainerPolicy(CK_SESSION_HANDLE(h_session), - CK_ULONG(h_containerber), - CK_ULONG(policy_id), - CK_ULONG(policy_val)) - return ret - - -ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) - - -def ca_set_container_policies(h_session, h_container, policies): - """ - Set multiple container policies. - - :param h_session: session handle - :param h_container: target container handle - :param policies: dict of policy ID ints and value ints - :return: result code - """ - h_sess = CK_SESSION_HANDLE(h_session) - container_id = CK_ULONG(h_container) - pol_id_list = policies.keys() - pol_val_list = policies.values() - pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) - pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) - - ret = CA_SetContainerPolicies(h_sess, - container_id, - pol_ids.size.contents, - pol_ids.array, - pol_vals.array) - - return ret - - -ca_set_container_policies_ex = make_error_handle_function(ca_set_container_policies) - - -def ca_set_container_size(h_session, h_container, size): - """ - Set a container's size - - :param h_session: session handle - :param h_container: target container handle - :param size: size - :return: result code - """ - h_sess = CK_SESSION_HANDLE(h_session) - container_id = CK_ULONG(h_container) - size = CK_ULONG(size) - ret = CA_SetContainerSize(h_sess, - container_id, - size) - return ret - - -ca_set_container_size_ex = make_error_handle_function(ca_set_container_size) diff --git a/pycryptoki/policy_management.py b/pycryptoki/policy_management.py new file mode 100755 index 0000000..e1b960a --- /dev/null +++ b/pycryptoki/policy_management.py @@ -0,0 +1,22 @@ +from pycryptoki.cryptoki import CA_SetContainerPolicy, CK_ULONG +from pycryptoki.test_functions import make_error_handle_function + + +def ca_set_container_policy(h_session, container_number, policy_id, policy_val): + """Sets a policy on the container. + + NOTE: With per partition SO this method should generally not be used. Instead + ca_set_partition_policies should be used + + :param h_session: The session handle of the entity with permission to change the policy + :param container_number: The container number to set the policy on. + :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) + :param policy_val: The value to set the policy to + :returns: The result code + + """ + ret = CA_SetContainerPolicy(h_session, CK_ULONG(container_number), CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret + + +ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index f47f545..f80eec7 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -357,6 +357,60 @@ def c_close_all_sessions(slot): c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) +def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): + """Inserts a token into a slot without a Security Officer on the token + + :param h_session: Current session + :param storage_size: The storage size of the token (0 for undefined/unlimited) + :param password: The password associated with the token (Default value = 'userpin') + :param label: The label associated with the token (Default value = 'Inserted Token') + :returns: The result code, The container number + + """ + container_number = CK_ULONG() + LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( + storage_size) + ", pin=" + str(password) + ", label=" + label) + + if password == '': + password = None + + password = AutoCArray(data=password) + label = AutoCArray(data=label) + + ret = CA_CreateContainer(h_session, CK_ULONG(0), + label.array, label.size.contents, + password.array, password.size.contents, + CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), + CK_ULONG(storage_size), byref(container_number)) + LOG.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) + return ret, container_number.value + + +ca_create_container_ex = make_error_handle_function(ca_create_container) + + +def ca_delete_container_with_handle(h_session, container_handle): + """ + + :param h_session: + :param container_handle: + + """ + container_number = CK_ULONG(container_handle) + LOG.info( + "CA_DeleteContainerWithHandle: " + "Attempting to delete container with handle: %s", container_handle) + + ret = CA_DeleteContainerWithHandle(h_session, container_number) + + LOG.info("CA_DeleteContainerWithHandle: Ret Value: %s", ret) + + return ret + + +ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) + + def ca_openapplicationID(slot, id_high, id_low): """ From a9705ea76242c1c0738250ca7f027dfde5a1cc61 Mon Sep 17 00:00:00 2001 From: Alex Mihailescu Date: Mon, 14 Dec 2015 13:20:40 -0500 Subject: [PATCH 023/109] LA-1348: Christoki LibHPUX regex support Change-Id: Ia8165c2511ea363e3bd19c42363b1b3ccb1d8456 --- pycryptoki/cryptoki_helpers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index 6f8a756..49de0db 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -128,9 +128,9 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): for line in chrystoki2: is_64bits = sys.maxsize > 2 ** 32 if is_64bits: - lib_unix_line = re.findall("^\s*LibUNIX64\s*=\s*([^\n]+)", line) + lib_unix_line = re.findall("^\s*Lib(?:UNIX64|HPUX)\s*=\s*([^\n]+)", line) else: - lib_unix_line = re.findall("^\s*LibUNIX\s*=\s*([^\n]+)", line) + lib_unix_line = re.findall("^\s*Lib(?:UNIX|HPUX)\s*=\s*([^\n]+)", line) if len(lib_unix_line) > 1: raise Exception("Found more than one LibUNIX pattern on the same line") From 7f696bc91b111abef620ac3d1899e449f11cd0d2 Mon Sep 17 00:00:00 2001 From: ksafford Date: Thu, 12 Nov 2015 15:39:02 -0500 Subject: [PATCH 024/109] LA-1424 Add native Python "Container" functions Add native Python functions for: - CA_GetContainerCapabilitySet - CA_GetContainerCapabilitySetting - CA_GetContainerList - CA_GetContainerName - CA_GetContainerPolicySet - CA_GetContainerPolicySetting - CA_GetContainerStatus - CA_GetContainerStorageInformation - CA_SetContainerPolicies - CA_SetContainerSize Also remove the old pycryptoki daemon, pycryptoki_daemon.py Change-Id: I8a4bd822e0e492225b3b97ba96b6c145311995c8 --- pycryptoki/daemon/pycryptoki_daemon.py | 386 ---------------------- pycryptoki/daemon/rpyc_pycryptoki.py | 66 +++- pycryptoki/hsm_management.py | 32 +- pycryptoki/partition_management.py | 434 +++++++++++++++++++++++++ pycryptoki/policy_management.py | 22 -- pycryptoki/pycryptoki_client.py | 22 +- pycryptoki/session_management.py | 54 --- setup.py | 3 +- 8 files changed, 509 insertions(+), 510 deletions(-) delete mode 100755 pycryptoki/daemon/pycryptoki_daemon.py create mode 100644 pycryptoki/partition_management.py delete mode 100755 pycryptoki/policy_management.py diff --git a/pycryptoki/daemon/pycryptoki_daemon.py b/pycryptoki/daemon/pycryptoki_daemon.py deleted file mode 100755 index 145531b..0000000 --- a/pycryptoki/daemon/pycryptoki_daemon.py +++ /dev/null @@ -1,386 +0,0 @@ -#!/usr/bin/env python -""" -xmlrpc server daemon that wraps pycryptoki so pycryptoki can be used over -the network -""" -from ConfigParser import ConfigParser -from SimpleXMLRPCServer import SimpleXMLRPCServer -from optparse import OptionParser -import xmlrpclib -from _ctypes import pointer -from ctypes import cast -import ctypes - -from pycryptoki.backup import ca_open_secure_token, ca_close_secure_token, \ - ca_open_secure_token_ex, ca_close_secure_token_ex, ca_extract, ca_extract_ex, \ - ca_insert, ca_insert_ex -from pycryptoki.encryption import c_encrypt, c_encrypt_ex, c_decrypt, \ - c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex -from pycryptoki.key_generator import c_destroy_object, c_destroy_object_ex, \ - c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, \ - c_derive_key, c_derive_key_ex -from pycryptoki.misc import c_generate_random, c_generate_random_ex, \ - c_seed_random, c_seed_random_ex, c_digest, c_digest_ex, c_set_ped_id, \ - c_set_ped_id_ex, c_get_ped_id, c_get_ped_id_ex, c_create_object, \ - c_create_object_ex -from pycryptoki.object_attr_lookup import c_find_objects, c_find_objects_ex, \ - c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex -from pycryptoki.policy_management import ca_set_container_policy, ca_set_container_policy_ex -from pycryptoki.hsm_management import ca_set_hsm_policy, ca_set_hsm_policy_ex, \ - ca_set_destructive_hsm_policy, ca_set_destructive_hsm_policy_ex -from pycryptoki.session_management import c_initialize, c_initialize_ex, \ - c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, c_get_token_info, \ - c_get_token_info_ex, c_close_session, c_close_session_ex, c_logout, c_logout_ex, \ - c_init_pin, c_init_pin_ex, ca_factory_reset, ca_factory_reset_ex, c_set_pin, \ - c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, ca_create_container, \ - ca_create_container_ex, login, login_ex -from pycryptoki.sign_verify import c_sign, c_sign_ex, c_verify, c_verify_ex -from pycryptoki.token_management import c_init_token, c_init_token_ex, \ - c_get_mechanism_list, c_get_mechanism_list_ex, c_get_mechanism_info, \ - c_get_mechanism_info_ex, get_token_by_label, get_token_by_label_ex -from pycryptoki.audit_handling import ca_get_time, ca_get_time_ex, ca_init_audit, \ - ca_init_audit_ex, ca_time_sync, ca_time_sync_ex -from pycryptoki.key_generator import _get_mechanism -from pycryptoki.cryptoki import CK_ULONG, CK_VOID_PTR - -''' -All the functions the server supports -''' -pycryptoki_functions = {"c_wrap_key" : c_wrap_key, - "c_wrap_key_ex" : c_wrap_key_ex, - "c_unwrap_key" : c_unwrap_key, - "c_unwrap_key_ex" : c_unwrap_key_ex, - "c_destroy_object" : c_destroy_object, - "c_destroy_object_ex" : c_destroy_object_ex, - "c_generate_random" : c_generate_random, - "c_generate_random_ex" : c_generate_random_ex, - "c_seed_random" : c_seed_random, - "c_seed_random_ex" : c_seed_random_ex, - "c_digest" : c_digest, - "c_digest_ex" : c_digest_ex, - "c_set_ped_id" : c_set_ped_id, - "c_set_ped_id_ex" : c_set_ped_id_ex, - "c_get_ped_id" : c_get_ped_id, - "c_get_ped_id_ex" : c_get_ped_id_ex, - "ca_set_hsm_policy" : ca_set_hsm_policy, - "ca_set_hsm_policy_ex" : ca_set_hsm_policy_ex, - "ca_set_destructive_hsm_policy" : ca_set_destructive_hsm_policy, - "ca_set_destructive_hsm_policy_ex" : ca_set_destructive_hsm_policy_ex, - "ca_set_container_policy" : ca_set_container_policy, - "ca_set_container_policy_ex" : ca_set_container_policy_ex, - "c_initialize" : c_initialize, - "c_initialize_ex" : c_initialize_ex, - "c_finalize" : c_finalize, - "c_finalize_ex" : c_finalize_ex, - "c_open_session" : c_open_session, - "c_open_session_ex" : c_open_session_ex, - "login" : login, - "login_ex" : login_ex, - "c_get_token_info" : c_get_token_info, - "c_get_token_info_ex" : c_get_token_info_ex, - "c_close_session" : c_close_session, - "c_close_session_ex" : c_close_session_ex, - "c_logout" : c_logout, - "c_logout_ex" : c_logout_ex, - "c_init_pin" : c_init_pin, - "c_init_pin_ex" : c_init_pin_ex, - "ca_factory_reset" : ca_factory_reset, - "ca_factory_reset_ex" : ca_factory_reset_ex, - "c_set_pin" : c_set_pin, - "c_set_pin_ex" : c_set_pin_ex, - "c_close_all_sessions" : c_close_all_sessions, - "c_close_all_sessions_ex" : c_close_all_sessions_ex, - "ca_create_container" : ca_create_container, - "ca_create_container_ex" : ca_create_container_ex, - "c_init_token" : c_init_token, - "c_init_token_ex" : c_init_token_ex, - "c_get_mechanism_list" : c_get_mechanism_list, - "c_get_mechanism_list_ex" : c_get_mechanism_list_ex, - "c_get_mechanism_info" : c_get_mechanism_info, - "c_get_mechanism_info_ex" : c_get_mechanism_info_ex, - "get_token_by_label" : get_token_by_label, - "get_token_by_label_ex" : get_token_by_label_ex, - "ca_close_secure_token" : ca_close_secure_token, - "ca_close_secure_token_ex" : ca_close_secure_token_ex, - "ca_open_secure_token" : ca_open_secure_token, - "ca_open_secure_token_ex" : ca_open_secure_token_ex, - "ca_extract" : ca_extract, - "ca_extract_ex" : ca_extract_ex, - "ca_insert" : ca_insert, - "ca_insert_ex" : ca_insert_ex, - "c_set_attribute_value" : c_set_attribute_value, - "c_set_attribute_value_ex" : c_set_attribute_value_ex, - "c_generate_key" : c_generate_key, - "c_generate_key_ex" : c_generate_key_ex, - "c_generate_key_pair" : c_generate_key_pair, - "c_generate_key_pair_ex" : c_generate_key_pair_ex, - "c_create_object" : c_create_object, - "c_create_object_ex" : c_create_object_ex, - "ca_get_time": ca_get_time, - "ca_get_time_ex": ca_get_time_ex, - "ca_init_audit": ca_init_audit, - "ca_init_audit_ex": ca_init_audit_ex, - "ca_time_sync": ca_time_sync, - "ca_time_sync_ex": ca_time_sync_ex - } - -''' -Functions with arguments/return values that need specialized -serialization/deserialization -''' -functions_needing_serialization = { - "c_find_objects" : c_find_objects, - "c_find_objects_ex" : c_find_objects_ex, - "c_get_attribute_value" : c_get_attribute_value, - "c_get_attribute_value_ex" : c_get_attribute_value_ex, - "c_sign": c_sign, - "c_sign_ex": c_sign_ex, - "c_encrypt": c_encrypt, - "c_encrypt_ex": c_encrypt_ex, - "c_verify" : c_verify, - "c_verify_ex" : c_verify_ex, - "c_derive_key" : c_derive_key, - "c_derive_key_ex" : c_derive_key_ex, - "c_decrypt_ex" : c_decrypt_ex, - "c_decrypt" : c_decrypt - } - - -def initialize_server(ip, port): - """ - - :param ip: - :param port: - - """ - print "Initializing Server" - server = SimpleXMLRPCServer((ip, port)) - server.logRequests = 0 - - #Dynamically add functions to server - for key, value in pycryptoki_functions.iteritems(): - server.register_function(value, key) - - #For functions that need better serialization, do it - for key, value in functions_needing_serialization.iteritems(): - server.register_function(eval(key + "_serialize"), key) - - return server - - -def serialize_dict(dictionary): - """Helper function to convert a dictionary with to - for xmlrpc - - :param dictionary: - - """ - serialized_dictionary = {} - for key, value in dictionary.iteritems(): - serialized_dictionary[str(key)] = value - return serialized_dictionary - -def c_get_attribute_value_serialize(h_session, h_object, template): - """returns dictionary with k,v pairs of for xmlrpc - - :param h_session: - :param h_object: - :param template: - - """ - ret, dictionary = c_get_attribute_value(h_session, h_object, template) - return ret, serialize_dict(dictionary) - -def c_get_attribute_value_ex_serialize(h_session, h_object, template): - """returns dictionary with k,v pairs of for xmlrpc - - :param h_session: - :param h_object: - :param template: - - """ - dictionary = c_get_attribute_value_ex(h_session, h_object, template) - return serialize_dict(dictionary) - -def c_find_objects_serialize(h_session, h_object, template): - """returns dictionary with k,v pairs of for xmlrpc - - :param h_session: - :param h_object: - :param template: - - """ - ret, dictionary = c_find_objects(h_session, h_object, template) - return ret, serialize_dict(dictionary) - -def c_find_objects_ex_serialize(h_session, h_object, template): - """returns dictionary with k,v pairs of for xmlrpc - - :param h_session: - :param h_object: - :param template: - - """ - dictionary = c_find_objects_ex(h_session, h_object, template) - return serialize_dict(dictionary) - -def c_derive_key_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): - """ - - :param h_session: - :param h_base_key: - :param h_second_key: - :param template: - :param mech_flavor: - :param mech: (Default value = None) - - """ - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) - -def c_derive_key_ex_serialize(h_session, h_base_key, h_second_key, template, mech_flavor, mech = None): - """ - - :param h_session: - :param h_base_key: - :param h_second_key: - :param template: - :param mech_flavor: - :param mech: (Default value = None) - - """ - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) - -def c_sign_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): - """ - - :param h_session: - :param sign_flavor: - :param data_to_sign: - :param h_key: - :param mech: (Default value = None) - - """ - ret, signature = c_sign(h_session, sign_flavor, data_to_sign, h_key, mech) - return ret, xmlrpclib.Binary(signature) - -def c_sign_ex_serialize(h_session, sign_flavor, data_to_sign, h_key, mech = None): - """ - - :param h_session: - :param sign_flavor: - :param data_to_sign: - :param h_key: - :param mech: (Default value = None) - - """ - signature = c_sign_ex(h_session, sign_flavor, data_to_sign, h_key, mech) - return xmlrpclib.Binary(signature) - -def c_encrypt_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - """ - - :param h_session: - :param encryption_flavor: - :param h_key: - :param data_to_encrypt: - :param mech: (Default value = None) - - """ - ret, enc_data = c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech) - return ret, xmlrpclib.Binary(enc_data) - -def c_encrypt_ex_serialize(h_session, encryption_flavor, h_key, data_to_encrypt, mech = None): - """ - - :param h_session: - :param encryption_flavor: - :param h_key: - :param data_to_encrypt: - :param mech: (Default value = None) - - """ - enc_data = c_encrypt_ex(h_session, encryption_flavor, h_key, data_to_encrypt, mech) - return xmlrpclib.Binary(enc_data) - -def c_verify_serialize( h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - """ - - :param h_session: - :param h_key: - :param verify_flavor: - :param data_to_verify: - :param signature: - :param mech: (Default value = None) - - """ - return c_verify(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) - -def c_verify_ex_serialize(h_session, h_key, verify_flavor, data_to_verify, signature, mech = None): - """ - - :param h_session: - :param h_key: - :param verify_flavor: - :param data_to_verify: - :param signature: - :param mech: (Default value = None) - - """ - return c_verify_ex(h_session, h_key, verify_flavor, data_to_verify, signature.data, mech) - -def c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): - """ - - :param h_session: - :param decrypt_flavor: - :param h_key: - :param encrypted_data: - :param mech: (Default value = None) - - """ - return c_decrypt(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) - -def c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data, mech = None): - """ - - :param h_session: - :param decrypt_flavor: - :param h_key: - :param encrypted_data: - :param mech: (Default value = None) - - """ - return c_decrypt_ex(h_session, decrypt_flavor, h_key, encrypted_data.data, mech) - -if __name__ == '__main__': - #Setup argument parser - resources_config_parser = ConfigParser() - parser = OptionParser() - parser.add_option("-i", "--ip_address", dest="i", - help="pycryptoki daemon IP address", metavar="") - parser.add_option("-p", "--port", dest="p", - help="pycryptoki daemon IP port", metavar="") - (options, args) = parser.parse_args() - - #Default arguments - ip = options.i if options.i is not None else 'localhost' - port = int( options.p if options.p is not None else '8001') - print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) - - server = initialize_server(ip, port) - - # run until we die - print "Starting Server" - server.serve_forever() diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 903e6b4..4a35169 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -49,7 +49,6 @@ from pycryptoki.object_attr_lookup import (c_find_objects, c_find_objects_ex, c_get_attribute_value, c_get_attribute_value_ex, c_set_attribute_value, c_set_attribute_value_ex) -from pycryptoki.policy_management import (ca_set_container_policy, ca_set_container_policy_ex) from pycryptoki.session_management import (c_initialize, c_initialize_ex, c_finalize, c_finalize_ex, c_open_session, c_open_session_ex, @@ -61,13 +60,10 @@ ca_factory_reset, ca_factory_reset_ex, c_set_pin, c_set_pin_ex, c_close_all_sessions, c_close_all_sessions_ex, - ca_create_container, ca_create_container_ex, login, login_ex, ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID, ca_closeapplicationID_ex, ca_restart, ca_restart_ex, - ca_delete_container_with_handle_ex, - ca_delete_container_with_handle, ca_setapplicationID, ca_setapplicationID_ex) from pycryptoki.sign_verify import (c_sign, c_sign_ex, c_verify, c_verify_ex) @@ -100,6 +96,32 @@ ca_get_hsm_capability_setting_ex, ca_set_hsm_policies, ca_set_hsm_policies_ex, ca_set_destructive_hsm_policies, ca_set_destructive_hsm_policies_ex) +from pycryptoki.partition_management import (ca_create_container, + ca_create_container_ex, + ca_delete_container_with_handle_ex, + ca_delete_container_with_handle, + ca_set_container_policy, + ca_set_container_policy_ex, + ca_get_container_capability_set, + ca_get_container_capability_set_ex, + ca_get_container_capability_setting, + ca_get_container_capability_setting_ex, + ca_get_container_list, + ca_get_container_list_ex, + ca_get_container_name, + ca_get_container_name_ex, + ca_get_container_policy_set, + ca_get_container_policy_set_ex, + ca_get_container_policy_setting, + ca_get_container_policy_setting_ex, + ca_get_container_status, + ca_get_container_status_ex, + ca_get_container_storage_information, + ca_get_container_storage_information_ex, + ca_set_container_policies, + ca_set_container_policies_ex, + ca_set_container_size, + ca_set_container_size_ex) from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, ca_modifyusagecount, ca_modifyusagecount_ex) from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, @@ -194,8 +216,6 @@ def _rpyc_getattr(self, name): exposed_ca_open_secure_token_ex = staticmethod(ca_open_secure_token_ex) exposed_c_close_all_sessions = staticmethod(c_close_all_sessions) exposed_c_close_all_sessions_ex = staticmethod(c_close_all_sessions_ex) - exposed_ca_create_container = staticmethod(ca_create_container) - exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) exposed_ca_openapplicationID_ex = staticmethod(ca_openapplicationID_ex) exposed_ca_openapplicationID = staticmethod(ca_openapplicationID) exposed_ca_closeapplicationID_ex = staticmethod(ca_closeapplicationID_ex) @@ -204,12 +224,6 @@ def _rpyc_getattr(self, name): exposed_ca_setapplicationID = staticmethod(ca_setapplicationID) exposed_ca_restart_ex = staticmethod(ca_restart_ex) exposed_ca_restart = staticmethod(ca_restart) - exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) - exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) - - # policy_management.py - exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) - exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) # object_attr_lookup.py exposed_c_find_objects = staticmethod(c_find_objects) @@ -295,6 +309,34 @@ def _rpyc_getattr(self, name): exposed_ca_set_destructive_hsm_policies = staticmethod(ca_set_destructive_hsm_policies) exposed_ca_set_destructive_hsm_policies_ex = staticmethod(ca_set_destructive_hsm_policies_ex) + # partition_management.py + exposed_ca_create_container = staticmethod(ca_create_container) + exposed_ca_create_container_ex = staticmethod(ca_create_container_ex) + exposed_ca_delete_container_with_handle = staticmethod(ca_delete_container_with_handle) + exposed_ca_delete_container_with_handle_ex = staticmethod(ca_delete_container_with_handle_ex) + exposed_ca_set_container_policy = staticmethod(ca_set_container_policy) + exposed_ca_set_container_policy_ex = staticmethod(ca_set_container_policy_ex) + exposed_ca_get_container_capability_set = staticmethod(ca_get_container_capability_set) + exposed_ca_get_container_capability_set_ex = staticmethod(ca_get_container_capability_set_ex) + exposed_ca_get_container_capability_setting = staticmethod(ca_get_container_capability_setting) + exposed_ca_get_container_capability_setting_ex = staticmethod(ca_get_container_capability_setting_ex) + exposed_ca_get_container_list = staticmethod(ca_get_container_list) + exposed_ca_get_container_list_ex = staticmethod(ca_get_container_list_ex) + exposed_ca_get_container_name = staticmethod(ca_get_container_name) + exposed_ca_get_container_name_ex = staticmethod(ca_get_container_name_ex) + exposed_ca_get_container_policy_set = staticmethod(ca_get_container_policy_set) + exposed_ca_get_container_policy_set_ex = staticmethod(ca_get_container_policy_set_ex) + exposed_ca_get_container_policy_setting = staticmethod(ca_get_container_policy_setting) + exposed_ca_get_container_policy_setting_ex = staticmethod(ca_get_container_policy_setting_ex) + exposed_ca_get_container_status = staticmethod(ca_get_container_status) + exposed_ca_get_container_status_ex = staticmethod(ca_get_container_status_ex) + exposed_ca_get_container_storage_information = staticmethod(ca_get_container_storage_information) + exposed_ca_get_container_storage_information_ex = staticmethod(ca_get_container_storage_information_ex) + exposed_ca_set_container_policies = staticmethod(ca_set_container_policies) + exposed_ca_set_container_policies_ex = staticmethod(ca_set_container_policies_ex) + exposed_ca_set_container_size = staticmethod(ca_set_container_size) + exposed_ca_set_container_size_ex = staticmethod(ca_set_container_size_ex) + # key_management.py exposed_ca_generatemofn = staticmethod(ca_generatemofn) exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 1db86eb..243bfa3 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -307,9 +307,9 @@ def ca_get_hsm_capability_set(slot): Get the capabilities of the given slot. :param int slot: Target slot number - :return: retcode, {id: val} dict of policies (None if command failed) + :return: retcode, {id: val} dict of capabilities (None if command failed) """ - slot_id = CK_ULONG(slot) + slot_id = CK_SLOT_ID(slot) cap_ids = AutoCArray() cap_vals = AutoCArray() @@ -336,9 +336,11 @@ def ca_get_hsm_capability_setting(slot, capability_id): :param capability_id: capability ID :return: result code, CK_ULONG representing capability active or not """ - capability_val = CK_ULONG() - ret = CA_GetHSMCapabilitySetting(CK_ULONG(slot), CK_ULONG(capability_id), pointer(capability_val)) - return ret, capability_val.value + slot_id = CK_SLOT_ID(slot) + cap_id = CK_ULONG(capability_id) + cap_val = CK_ULONG() + ret = CA_GetHSMCapabilitySetting(slot_id, cap_id, pointer(cap_val)) + return ret, cap_val.value ca_get_hsm_capability_setting_ex = make_error_handle_function(ca_get_hsm_capability_setting) @@ -351,20 +353,20 @@ def ca_get_hsm_policy_set(slot): :param int slot: Target slot number :return: retcode, {id: val} dict of policies (None if command failed) """ - slot_id = CK_ULONG(slot) - cap_ids = AutoCArray() - cap_vals = AutoCArray() + slot_id = CK_SLOT_ID(slot) + pol_ids = AutoCArray() + pol_vals = AutoCArray() @refresh_c_arrays(1) def _ca_get_hsm_policy_set(): """Closure for retries. """ - return CA_GetHSMPolicySet(slot_id, cap_ids.array, cap_ids.size, - cap_vals.array, cap_vals.size) + return CA_GetHSMPolicySet(slot_id, pol_ids.array, pol_ids.size, + pol_vals.array, pol_vals.size) ret = _ca_get_hsm_policy_set() - return ret, dict(zip(cap_ids, cap_vals)) + return ret, dict(zip(pol_ids, pol_vals)) ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) @@ -378,9 +380,11 @@ def ca_get_hsm_policy_setting(slot, policy_id): :param policy_id: policy ID :return: result code, CK_ULONG representing policy active or not """ - policy_val = CK_ULONG() - ret = CA_GetHSMPolicySetting(CK_ULONG(slot), CK_ULONG(policy_id), pointer(policy_val)) - return ret, policy_val.value + slot_id = CK_SLOT_ID(slot) + pol_id = CK_ULONG(policy_id) + pol_val = CK_ULONG() + ret = CA_GetHSMPolicySetting(slot_id, pol_id, pointer(pol_val)) + return ret, pol_val.value ca_get_hsm_policy_setting_ex = make_error_handle_function(ca_get_hsm_policy_setting) diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py new file mode 100644 index 0000000..a6e3cea --- /dev/null +++ b/pycryptoki/partition_management.py @@ -0,0 +1,434 @@ +""" +Functions for managing partitions +""" +from _ctypes import pointer +from ctypes import byref, c_ubyte +import logging +from pycryptoki.cryptoki import (CK_SLOT_ID, + CK_ULONG, + CK_SESSION_HANDLE, + CA_CreateContainer, + CA_DeleteContainerWithHandle, + CA_GetContainerList, + CA_GetContainerCapabilitySet, + CA_GetContainerCapabilitySetting, + CA_GetContainerPolicySet, + CA_GetContainerPolicySetting, + CA_GetContainerName, + CA_GetContainerStorageInformation, + CA_GetContainerStatus, + CA_SetContainerPolicy, + CA_SetContainerPolicies, + CA_SetContainerSize) +from pycryptoki.defines import (LUNA_PARTITION_TYPE_STANDALONE, + LUNA_CF_CONTAINER_ENABLED, + LUNA_CF_KCV_CREATED, + LUNA_CF_LKCV_CREATED, + LUNA_CF_HA_INITIALIZED, + LUNA_CF_PARTITION_INITIALIZED, + LUNA_CF_CONTAINER_ACTIVATED, + LUNA_CF_CONTAINER_LUSR_ACTIVATED, + LUNA_CF_USER_PIN_INITIALIZED, + LUNA_CF_SO_PIN_LOCKED, + LUNA_CF_SO_PIN_TO_BE_CHANGED, + LUNA_CF_USER_PIN_LOCKED, + LUNA_CF_LIMITED_USER_PIN_LOCKED, + LUNA_CF_LIMITED_USER_CREATED, + LUNA_CF_USER_PIN_TO_BE_CHANGED, + LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED) +from pycryptoki.common_utils import AutoCArray, refresh_c_arrays +from pycryptoki.test_functions import make_error_handle_function + + +LOG = logging.getLogger(__name__) + + +def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): + """Inserts a token into a slot without a Security Officer on the token + + :param h_session: Current session + :param storage_size: The storage size of the token (0 for undefined/unlimited) + :param password: The password associated with the token (Default value = 'userpin') + :param label: The label associated with the token (Default value = 'Inserted Token') + :returns: The result code, The container number + + """ + h_sess = CK_SESSION_HANDLE(h_session) + h_container = CK_ULONG() + LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( + storage_size) + ", pin=" + str(password) + ", label=" + label) + + if password == '': + password = None + + password = AutoCArray(data=password) + label = AutoCArray(data=label) + + ret = CA_CreateContainer(h_sess, CK_ULONG(0), + label.array, label.size.contents, + password.array, password.size.contents, + CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), + CK_ULONG(storage_size), byref(h_container)) + LOG.info("CA_CreateContainer: Inserted token into slot " + str(h_container.value)) + return ret, h_container.value + + +ca_create_container_ex = make_error_handle_function(ca_create_container) + + +def ca_delete_container_with_handle(h_session, h_container): + """ + Delete a container by handle + + :param h_session: session + :param h_container: target container handle + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + container_id = CK_ULONG(h_container) + LOG.info( + "CA_DeleteContainerWithHandle: " + "Attempting to delete container with handle: %s", h_container) + + ret = CA_DeleteContainerWithHandle(h_sess, container_id) + + LOG.info("CA_DeleteContainerWithHandle: Ret Value: %s", ret) + + return ret + + +ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) + + +def ca_get_container_list(slot, group_handle=0, container_type=LUNA_PARTITION_TYPE_STANDALONE): + """ + Get list of containers. + + :param slot: slot ID of the slot to query + :param group_handle: group ID + :param container_type: type of container + :return: result code, list of container handles + """ + slot_id = CK_SLOT_ID(slot) + group = CK_ULONG(group_handle) + cont_type = CK_ULONG(container_type) + cont_handles = AutoCArray() + + @refresh_c_arrays(1) + def _get_cont_list(): + """Closer for retries to work w/ properties + """ + return CA_GetContainerList(slot_id, group, cont_type, + cont_handles.array, cont_handles.size) + + ret = _get_cont_list() + + return ret, list(cont_handles.array) + + +ca_get_container_list_ex = make_error_handle_function(ca_get_container_list) + + +def ca_get_container_capability_set(slot, h_container): + """ + Get the container capabilities of the given slot. + + :param int slot: target slot number + :param int h_container: target container handle + :return: result code, {id: val} dict of capabilities (None if command failed) + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + cap_ids = AutoCArray() + cap_vals = AutoCArray() + + @refresh_c_arrays(1) + def _get_container_caps(): + """Closer for retries to work w/ properties + """ + return CA_GetContainerCapabilitySet(slot_id, + cont_id, + cap_ids.array, + cap_ids.size, + cap_vals.array, + cap_vals.size) + + ret = _get_container_caps() + + return ret, dict(zip(cap_ids, cap_vals)) + + +ca_get_container_capability_set_ex = make_error_handle_function(ca_get_container_capability_set) + + +def ca_get_container_capability_setting(slot, h_container, capability_id): + """ + Get the value of a container's single capability + + :param slot: slot ID of slot to query + :param h_container: target container handle + :param capability_id: capability ID + :return: result code, CK_ULONG representing capability active or not + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + cap_id = CK_ULONG(capability_id) + cap_val = CK_ULONG() + ret = CA_GetContainerCapabilitySetting(slot_id, + cont_id, + cap_id, + pointer(cap_val)) + return ret, cap_val.value + + +ca_get_container_capability_setting_ex = make_error_handle_function(ca_get_container_capability_setting) + + +def ca_get_container_policy_set(slot, h_container): + """ + Get the policies of the given slot and container. + + :param int slot: target slot number + :param int h_container: target container handle + :return: result code, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + pol_ids = AutoCArray() + pol_vals = AutoCArray() + + @refresh_c_arrays(1) + def _ca_get_container_policy_set(): + """Closure for retries. + """ + return CA_GetContainerPolicySet(slot_id, + cont_id, + pol_ids.array, + pol_ids.size, + pol_vals.array, + pol_vals.size) + + ret = _ca_get_container_policy_set() + + return ret, dict(zip(pol_ids, pol_vals)) + + +ca_get_container_policy_set_ex = make_error_handle_function(ca_get_container_policy_set) + + +def ca_get_container_policy_setting(slot, h_container, policy_id): + """ + Get the value of a container's single policy + + :param slot: slot ID of slot to query + :param h_container: target container handle + :param policy_id: policy ID + :return: result code, CK_ULONG representing policy active or not + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + pol_id = CK_ULONG(policy_id) + pol_val = CK_ULONG() + ret = CA_GetContainerPolicySetting(slot_id, cont_id, pol_id, pointer(pol_val)) + return ret, pol_val.value + + +ca_get_container_policy_setting_ex = make_error_handle_function(ca_get_container_policy_setting) + + +def ca_get_container_name(slot, h_container): + """ + Get a container's name + + :param slot: target slot + :param h_container: target container handle + :return: result code, container name string + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + name_arr = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _ca_get_container_name(): + """ + Closure for retries + """ + return CA_GetContainerName(slot_id, + cont_id, + name_arr.array, + name_arr.size) + ret = _ca_get_container_name() + + return ret, ''.join(map(chr, name_arr.array)) + + +ca_get_container_name_ex = make_error_handle_function(ca_get_container_name) + + +def ca_get_container_storage_information(slot, h_container): + """ + Get a container's storage information + + :param slot: target slot + :param h_container: target container handle + :return: result code, dict of storage values + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + overhead = CK_ULONG() + total = CK_ULONG() + used = CK_ULONG() + free = CK_ULONG() + obj_count = CK_ULONG() + + ret = CA_GetContainerStorageInformation(slot_id, + cont_id, + pointer(overhead), + pointer(total), + pointer(used), + pointer(free), + pointer(obj_count)) + return ret, {'overhead': overhead.value, + 'total': total.value, + 'used': used.value, + 'free': free.value, + 'object_count': obj_count.value} + + +ca_get_container_storage_information_ex = make_error_handle_function(ca_get_container_storage_information) + + +def ca_get_container_status(slot, h_container): + """ + Get a container's Status + + :param slot: target slot + :param h_container: target container handle + :return: result code, dict of flags, dict of failed logins + """ + slot_id = CK_SLOT_ID(slot) + cont_id = CK_ULONG(h_container) + status_flags = CK_ULONG() + failed_so_logins = CK_ULONG() + failed_user_logins = CK_ULONG() + failed_limited_user_logins = CK_ULONG() + + ret = CA_GetContainerStatus(slot_id, + cont_id, + pointer(status_flags), + pointer(failed_so_logins), + pointer(failed_user_logins), + pointer(failed_limited_user_logins)) + + flags_dict = { + LUNA_CF_CONTAINER_ENABLED: None, + LUNA_CF_KCV_CREATED: None, + LUNA_CF_LKCV_CREATED: None, + LUNA_CF_HA_INITIALIZED: None, + LUNA_CF_PARTITION_INITIALIZED: None, + LUNA_CF_CONTAINER_ACTIVATED: None, + LUNA_CF_CONTAINER_LUSR_ACTIVATED: None, + LUNA_CF_USER_PIN_INITIALIZED: None, + LUNA_CF_SO_PIN_LOCKED: None, + LUNA_CF_SO_PIN_TO_BE_CHANGED: None, + LUNA_CF_USER_PIN_LOCKED: None, + LUNA_CF_LIMITED_USER_PIN_LOCKED: None, + LUNA_CF_LIMITED_USER_CREATED: None, + LUNA_CF_USER_PIN_TO_BE_CHANGED: None, + LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED: None + } + flags_or = reduce(lambda x, y: x | y, flags_dict.keys()) + mask = status_flags.value & flags_or + if status_flags.value ^ mask != 0: + unknown_flags = [] + for i in range(status_flags.value.bit_length()): + if((status_flags.value ^ mask) >> i) & 1: + unknown_flags.append(2 ** i) + raise Exception("Found unknown flags! {}".format(' '.join(unknown_flags))) + for key, flag in flags_dict.iteritems(): + flags_dict[key] = 1 if key & status_flags.value else 0 + + failed_logins_dict = { + 'failed_so_logins': failed_so_logins.value, + 'failed_user_logins': failed_user_logins.value, + 'failed_limited_user_logins': failed_limited_user_logins.value + } + for key, val in failed_logins_dict.iteritems(): + if not val ^ int('1' * 64, 2) or not val ^ int('1' * 32, 2): + failed_logins_dict[key] = -1L + return ret, flags_dict, failed_logins_dict + + +ca_get_container_status_ex = make_error_handle_function(ca_get_container_status) + + +def ca_set_container_policy(h_session, h_containerber, policy_id, policy_val): + """Sets a policy on the container. + + NOTE: With per partition SO this method should generally not be used. Instead + ca_set_partition_policies should be used + + :param h_session: The session handle of the entity with permission to change the policy + :param h_containerber: The container number to set the policy on. + :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) + :param policy_val: The value to set the policy to + :returns: The result code + + """ + ret = CA_SetContainerPolicy(CK_SESSION_HANDLE(h_session), + CK_ULONG(h_containerber), + CK_ULONG(policy_id), + CK_ULONG(policy_val)) + return ret + + +ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) + + +def ca_set_container_policies(h_session, h_container, policies): + """ + Set multiple container policies. + + :param h_session: session handle + :param h_container: target container handle + :param policies: dict of policy ID ints and value ints + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + container_id = CK_ULONG(h_container) + pol_id_list = policies.keys() + pol_val_list = policies.values() + pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) + pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) + + ret = CA_SetContainerPolicies(h_sess, + container_id, + pol_ids.size.contents, + pol_ids.array, + pol_vals.array) + + return ret + + +ca_set_container_policies_ex = make_error_handle_function(ca_set_container_policies) + + +def ca_set_container_size(h_session, h_container, size): + """ + Set a container's size + + :param h_session: session handle + :param h_container: target container handle + :param size: size + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + container_id = CK_ULONG(h_container) + size = CK_ULONG(size) + ret = CA_SetContainerSize(h_sess, + container_id, + size) + return ret + + +ca_set_container_size_ex = make_error_handle_function(ca_set_container_size) diff --git a/pycryptoki/policy_management.py b/pycryptoki/policy_management.py deleted file mode 100755 index e1b960a..0000000 --- a/pycryptoki/policy_management.py +++ /dev/null @@ -1,22 +0,0 @@ -from pycryptoki.cryptoki import CA_SetContainerPolicy, CK_ULONG -from pycryptoki.test_functions import make_error_handle_function - - -def ca_set_container_policy(h_session, container_number, policy_id, policy_val): - """Sets a policy on the container. - - NOTE: With per partition SO this method should generally not be used. Instead - ca_set_partition_policies should be used - - :param h_session: The session handle of the entity with permission to change the policy - :param container_number: The container number to set the policy on. - :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) - :param policy_val: The value to set the policy to - :returns: The result code - - """ - ret = CA_SetContainerPolicy(h_session, CK_ULONG(container_number), CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret - - -ca_set_container_policy_ex = make_error_handle_function(ca_set_container_policy) diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index 439563d..0b2f7d2 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -5,8 +5,7 @@ import rpyc -from pycryptoki.daemon.pycryptoki_daemon import pycryptoki_functions, \ - functions_needing_serialization +from pycryptoki.daemon import rpyc_pycryptoki from pycryptoki.session_management import c_finalize, c_initialize_ex, c_initialize log = logging.getLogger(__name__) @@ -95,24 +94,7 @@ def __getattr__(self, name): functions in pycryptoki if they're listed in the daemon """ log.info("Running local pycryptoki command: {0}".format(name)) - if pycryptoki_functions.has_key(name): - if 'c_initialize' in name: - return object.__getattribute__(self, name) - return pycryptoki_functions[name] - elif functions_needing_serialization.has_key(name): - return functions_needing_serialization[name] - else: - return object.__getattribute__(self, name) - - def c_initialize_ex(self): - """ """ - c_finalize() - return c_initialize_ex() - - def c_initialize(self): - """ """ - c_finalize() - return c_initialize() + return getattr(rpyc_pycryptoki, name) def kill(self): """ """ diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index f80eec7..f47f545 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -357,60 +357,6 @@ def c_close_all_sessions(slot): c_close_all_sessions_ex = make_error_handle_function(c_close_all_sessions) -def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): - """Inserts a token into a slot without a Security Officer on the token - - :param h_session: Current session - :param storage_size: The storage size of the token (0 for undefined/unlimited) - :param password: The password associated with the token (Default value = 'userpin') - :param label: The label associated with the token (Default value = 'Inserted Token') - :returns: The result code, The container number - - """ - container_number = CK_ULONG() - LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( - storage_size) + ", pin=" + str(password) + ", label=" + label) - - if password == '': - password = None - - password = AutoCArray(data=password) - label = AutoCArray(data=label) - - ret = CA_CreateContainer(h_session, CK_ULONG(0), - label.array, label.size.contents, - password.array, password.size.contents, - CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), - CK_ULONG(storage_size), byref(container_number)) - LOG.info("CA_CreateContainer: Inserted token into slot " + str(container_number.value)) - return ret, container_number.value - - -ca_create_container_ex = make_error_handle_function(ca_create_container) - - -def ca_delete_container_with_handle(h_session, container_handle): - """ - - :param h_session: - :param container_handle: - - """ - container_number = CK_ULONG(container_handle) - LOG.info( - "CA_DeleteContainerWithHandle: " - "Attempting to delete container with handle: %s", container_handle) - - ret = CA_DeleteContainerWithHandle(h_session, container_number) - - LOG.info("CA_DeleteContainerWithHandle: Ret Value: %s", ret) - - return ret - - -ca_delete_container_with_handle_ex = make_error_handle_function(ca_delete_container_with_handle) - - def ca_openapplicationID(slot, id_high, id_low): """ diff --git a/setup.py b/setup.py index 44d40bb..36fd07b 100755 --- a/setup.py +++ b/setup.py @@ -18,6 +18,5 @@ 'pycryptoki.tests', 'pycryptoki.daemon', 'pycryptoki.utils'], - scripts=['pycryptoki/daemon/rpyc_pycryptoki.py', - 'pycryptoki/daemon/pycryptoki_daemon.py'] + scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'] ) From 71dc2eb3ba072c8c56fb81c8d1ff0e4090a36ae0 Mon Sep 17 00:00:00 2001 From: Ian Bent Date: Wed, 20 Jan 2016 15:40:04 -0500 Subject: [PATCH 025/109] LHSM-24928: Add External Integrity Value parameter to encryption.py Change-Id: I24c0c6492bde30594d4893c437ac5304aa6b0a6b --- pycryptoki/encryption.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 0905e52..d404ebe 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -27,7 +27,7 @@ logger = logging.getLogger(__name__) -def get_encryption_mechanism(encryption_flavor): +def get_encryption_mechanism(encryption_flavor, external_iv=None): """Returns the CK_MECHANISM() object associated with a given encryption flavor #TODO: Only works with one kind of encryption mechanism currently. @@ -98,8 +98,12 @@ def get_encryption_mechanism(encryption_flavor): CKM_RSA_PKCS_OAEP: OAEP_params_required, CKM_ECIES: ECIES_params_required} - iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] - iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + if external_iv: + iv = external_iv + iv16 = external_iv + else: + iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] + iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] params = encryption_flavors.get(encryption_flavor) if params == iv_required: @@ -146,7 +150,7 @@ def get_encryption_mechanism(encryption_flavor): return mech -def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None): +def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, external_iv=None): """Encrypts data with a given key and encryption flavor encryption flavors @@ -157,13 +161,12 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None): a multipart operation will be used :param mech: The mechanism to use, if None will try to look up a default mechanism based on the encryption flavor - :param h_session: + :param external_iv: The new Integrity Value to be used. :returns: Returns the result code of the operation, a python string representing the encrypted data """ - if mech is None: - mech = get_encryption_mechanism(encryption_flavor) + mech = get_encryption_mechanism(encryption_flavor, external_iv) # if a list is passed out do an encrypt operation on each string in the list, otherwise just do one encrypt operation is_multi_part_operation = isinstance(data_to_encrypt, list) or isinstance(data_to_encrypt, tuple) @@ -232,7 +235,7 @@ def _get_string_from_list(list_of_strings): return large_string -def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None): +def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, external_iv=None): """Decrypts some data :param h_session: The session to use @@ -248,7 +251,7 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None): # Get the mechanism if mech is None: - mech = get_encryption_mechanism(decryption_flavor) + mech = get_encryption_mechanism(decryption_flavor, external_iv) # Initialize Decrypt ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) From 0ef6122c12dac99b10401112d101760e8bd7fc7b Mon Sep 17 00:00:00 2001 From: Ian Bent Date: Wed, 3 Feb 2016 15:07:59 -0500 Subject: [PATCH 026/109] LHSM-24928: Added CKM_AES_KW mechanisms to defines and encryption. Change-Id: Ic30207824dc8d7ebcd3975464b9cc280a212b8fe --- pycryptoki/defines.py | 6 ++++++ pycryptoki/encryption.py | 12 +++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index f9098f4..d776aee 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1301,6 +1301,8 @@ CKM_DSA_PARAMETER_GEN = 0x00002000 CKM_DH_PKCS_PARAMETER_GEN = 0x00002001 CKM_X9_42_DH_PARAMETER_GEN = 0x00002002 +CKM_AES_KEY_WRAP = 0x00002109 +CKM_AES_KEY_WRAP_PAD = 0x0000210A CKM_VENDOR_DEFINED = 0x80000000 CKF_HW = 0x00000001 # performed by HW */ CKF_ENCRYPT = 0x00000100 @@ -1664,6 +1666,10 @@ CKM_DES3_X919_MAC = (CKM_VENDOR_DEFINED + 0x150) CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS = (CKM_VENDOR_DEFINED + 0x160) CKM_ECDSA_GBCS_SHA256 = (CKM_VENDOR_DEFINED + 0x161) +CKM_AES_KW = (CKM_VENDOR_DEFINED + 0x170) +CKM_AES_KWP = (CKM_VENDOR_DEFINED + 0x171) +CKM_TDEA_KW = (CKM_VENDOR_DEFINED + 0x172) +CKM_TDEA_KWP = (CKM_VENDOR_DEFINED + 0x173) CKM_AES_CBC_PAD_EXTRACT = (CKM_VENDOR_DEFINED + 0x200) CKM_AES_CBC_PAD_INSERT = (CKM_VENDOR_DEFINED + 0x201) CKM_AES_CBC_PAD_EXTRACT_FLATTENED = (CKM_VENDOR_DEFINED + 0x202) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index d404ebe..8cc1232 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -16,7 +16,7 @@ CKM_RSA_PKCS, CKM_DES_CFB8, CKM_DES_CFB64, CKM_DES_OFB64, CKM_AES_CFB8, \ CKM_AES_CFB128, CKM_AES_OFB, CKM_ARIA_CFB8, CKM_ARIA_CFB128, CKM_ARIA_OFB, \ CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ - CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED + CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED, CKM_AES_KW, CKM_AES_KWP from pycryptoki.attributes import get_byte_list_from_python_list, \ convert_ck_char_array_to_string, Attributes from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ @@ -77,6 +77,8 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): CKM_SEED_CBC: IV16_required, CKM_SEED_CBC_PAD: IV16_required, CKM_AES_ECB: 0, + CKM_AES_KW: iv_required, + CKM_AES_KWP: iv_required, CKM_AES_CBC: IV16_required, CKM_AES_CBC_PAD: IV16_required, CKM_AES_CBC_PAD_IPSEC: IV16_required, @@ -352,7 +354,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in return python_string -def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None): +def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, external_iv=None): """Function which wraps a key :param h_session: The session to use @@ -366,7 +368,7 @@ def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None): """ if mech is None: - mech = get_encryption_mechanism(encryption_flavor) + mech = get_encryption_mechanism(encryption_flavor, external_iv) # Get the size of the key wrapped_key_length = CK_ULONG() @@ -386,7 +388,7 @@ def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None): c_wrap_key_ex = make_error_handle_function(c_wrap_key) -def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech=None): +def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech=None, external_iv=None): """Function which unwraps a key :param h_session: The session to use @@ -402,7 +404,7 @@ def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encrypt """ if mech is None: - mech = get_encryption_mechanism(encryption_flavor) + mech = get_encryption_mechanism(encryption_flavor, external_iv) c_template = Attributes(key_template).get_c_struct() byte_wrapped_key = cast(wrapped_key, CK_BYTE_PTR) From 71286a8d07a8e5a7e1d0b6663e4a2b98fd26221c Mon Sep 17 00:00:00 2001 From: ksafford Date: Wed, 24 Feb 2016 15:03:22 -0500 Subject: [PATCH 027/109] LA-1634 Revise and fix c_find_objects Make c_find_objects return only a list of found objects' handles. Change-Id: I0539223dc5f4e7e31f9b6ca949b036c860e8dc9f --- pycryptoki/object_attr_lookup.py | 36 ++++++++++++++++---------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 06f7887..2c49097 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -1,3 +1,6 @@ +""" +Functions for dealing with object attributes +""" from ctypes import byref from pycryptoki.attributes import Attributes, c_struct_to_python @@ -7,35 +10,30 @@ from pycryptoki.test_functions import make_error_handle_function -def c_find_objects(h_session, objects_find, template_attributes, num_entries): +def c_find_objects(h_session, template, num_entries): """Calls c_find_objects and c_find_objects_init to get a python dictionary of the objects found. :param h_session: The current session - :param objects_find: A python dictionary of the object template to look for - :param template_attributes: A python dictionary of the attributes to look for - :param num_entries: The number of entries to return - :returns: Returns a python dictionary of the templates of the objects found + :param template: A python dictionary of the object template to look for + :param num_entries: The max number of entries to return + :returns: Returns a list of handles of objects found """ - attributes = [] - struct = Attributes(objects_find).get_c_struct() - ret = C_FindObjectsInit(h_session, struct, CK_ULONG(len(objects_find))) - if ret != CKR_OK: return ret, -1, None; + struct = Attributes(template).get_c_struct() + ret = C_FindObjectsInit(h_session, struct, CK_ULONG(len(template))) + if ret != CKR_OK: + return ret, None h_ary = (CK_OBJECT_HANDLE * num_entries)() us_total = CK_ULONG(num_entries) ret = C_FindObjects(h_session, h_ary, CK_ULONG(num_entries), byref(us_total)) - if ret != CKR_OK: return ret, -1, None; - - # todo get attribute value for all of them - for i in range(0, us_total.value): - attribute = c_get_attribute_value_ex(h_session, h_ary[i], template_attributes) - attributes.append(attribute) + if ret != CKR_OK: + return ret, None ret = C_FindObjectsFinal(h_session) - return ret, h_ary[0], attributes + return ret, [h_ary[i] for i in range(us_total.value)] c_find_objects_ex = make_error_handle_function(c_find_objects) @@ -52,7 +50,8 @@ def c_get_attribute_value(h_session, h_object, template): """ c_struct = Attributes(template).get_c_struct() ret = C_GetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) - if ret != CKR_OK: return ret; + if ret != CKR_OK: + return ret, None return ret, c_struct_to_python(c_struct) @@ -71,7 +70,8 @@ def c_set_attribute_value(h_session, h_object, template): """ c_struct = Attributes(template).get_c_struct() ret = C_SetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) - if ret != CKR_OK: return ret; + if ret != CKR_OK: + return ret, None return ret, c_struct_to_python(c_struct) From e6acabe6a567d0653ae2af251605e214ad5e6242 Mon Sep 17 00:00:00 2001 From: ksafford Date: Thu, 3 Mar 2016 13:00:35 -0500 Subject: [PATCH 028/109] LA-1653 Remove old CKM_AES_CTR definition CKM_AES_CTR used to be a vendor defined mechanism. It is now defined in PKCS #11. Remove the old definition. Change-Id: I40dc1ecaf076ef3392cb2b44195c87d343f7c8b7 --- pycryptoki/defines.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index d776aee..bc724e6 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1617,7 +1617,6 @@ CKM_AES_CFB8 = (CKM_VENDOR_DEFINED + 0x118) CKM_AES_CFB128 = (CKM_VENDOR_DEFINED + 0x119) CKM_AES_OFB = (CKM_VENDOR_DEFINED + 0x11a) -CKM_AES_CTR = (CKM_VENDOR_DEFINED + 0x11b) CKM_AES_GCM = (CKM_VENDOR_DEFINED + 0x11c) CKM_ARIA_CFB8 = (CKM_VENDOR_DEFINED + 0x11d) CKM_ARIA_CFB128 = (CKM_VENDOR_DEFINED + 0x11e) From 3b40351d88e9cd4c0501ad9f440a2b68e4573109 Mon Sep 17 00:00:00 2001 From: ksafford Date: Thu, 3 Mar 2016 15:55:32 -0500 Subject: [PATCH 029/109] LA-1652 Extend mechanism mapping Add a dictionary mapping mechanisms to tuples of all matching strings. Some mechanisms are aliases to the same int value; e.g. CAST5 and CAST128. Change-Id: If6b337c84050a518dc82c43e953085ed2ac9f879 --- pycryptoki/default_templates.py | 455 ++++++++++++++++++++++++++++++-- 1 file changed, 431 insertions(+), 24 deletions(-) diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py index e4aa7c0..77a8be7 100755 --- a/pycryptoki/default_templates.py +++ b/pycryptoki/default_templates.py @@ -5,30 +5,91 @@ import copy -from defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ - CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ - CKK_DES2, CKK_DES3, CKK_CAST3, CKK_GENERIC_SECRET, CKA_MODIFIABLE, \ - CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ - CKA_VALUE_BITS, CKK_CAST5, CKK_RC2, CKK_RC4, CKK_RC5, CKA_ECDSA_PARAMS, CKK_AES, \ - CKK_SEED, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, CKK_ARIA, CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ - CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ - CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, CKM_ARIA_KEY_GEN, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN, \ - CKM_KCDSA_KEY_PAIR_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, \ - CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, \ - CKM_SHA1_RSA_PKCS, CKM_SHA224_RSA_PKCS, \ - CKM_SHA256_RSA_PKCS, CKM_SHA384_RSA_PKCS, CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS_PSS, \ - CKM_SHA1_RSA_PKCS_PSS, CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, \ - CKM_SHA384_RSA_PKCS_PSS, CKM_SHA512_RSA_PKCS_PSS, CKM_RSA_X9_31_KEY_PAIR_GEN, \ - CKM_RSA_X9_31, CKM_SHA1_RSA_X9_31, CKM_SHA224_RSA_X9_31, CKM_SHA256_RSA_X9_31, \ - CKM_SHA384_RSA_X9_31, CKM_SHA512_RSA_X9_31, CKM_RSA_PKCS_OAEP, CKM_DSA_KEY_PAIR_GEN, \ - CKM_DSA, CKM_DSA_SHA1, CKM_DSA_SHA224, CKM_DSA_SHA256, CKM_DSA_PARAMETER_GEN, \ - CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, CKM_ECDSA_SHA256, \ - CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, \ - CKM_SHA_1_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, \ - CKM_ECDSA -from pycryptoki.defines import CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE, CKC_X_509, \ - CKA_SUBJECT, CKA_VALUE, CKO_DATA, CKA_TOKEN +from defines import (CKA_BASE, CKA_CERTIFICATE_TYPE, CKA_CLASS, CKA_DECRYPT, CKA_DERIVE, +CKA_ECDSA_PARAMS, CKA_ENCRYPT, +CKA_EXTRACTABLE, CKA_KEY_TYPE, CKA_LABEL, CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PRIME, +CKA_PRIME_BITS, CKA_PRIVATE, CKA_PUBLIC_EXPONENT, CKA_SENSITIVE, CKA_SIGN, CKA_SUBJECT, +CKA_SUBPRIME, CKA_SUBPRIME_BITS, CKA_TOKEN, CKA_UNWRAP, CKA_VALUE, CKA_VALUE_BITS, CKA_VALUE_LEN, +CKA_VERIFY, CKA_WRAP, CKC_X_509, CKK_AES, CKK_ARIA, CKK_CAST3, CKK_CAST5, CKK_DES, CKK_DES2, +CKK_DES3, CKK_GENERIC_SECRET, CKK_RC2, CKK_RC4, CKK_RC5, CKK_SEED, CKM_2DES_KEY_DERIVATION, +CKM_ACTI, CKM_ACTI_KEY_GEN, CKM_AES_CBC, CKM_AES_CBC_ENCRYPT_DATA, CKM_AES_CBC_PAD, +CKM_AES_CBC_PAD_EXTRACT, CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, CKM_AES_CBC_PAD_EXTRACT_FLATTENED, +CKM_AES_CBC_PAD_INSERT, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, CKM_AES_CBC_PAD_INSERT_FLATTENED, +CKM_AES_CBC_PAD_IPSEC, CKM_AES_CFB128, CKM_AES_CFB8, CKM_AES_CMAC, CKM_AES_CMAC_GENERAL, +CKM_AES_CTR, CKM_AES_ECB, CKM_AES_ECB_ENCRYPT_DATA, CKM_AES_GCM, CKM_AES_GMAC, CKM_AES_KEY_GEN, +CKM_AES_KEY_WRAP, CKM_AES_KEY_WRAP_PAD, CKM_AES_KW, CKM_AES_KWP, CKM_AES_MAC, CKM_AES_MAC_GENERAL, +CKM_AES_OFB, CKM_ARIA_CBC, CKM_ARIA_CBC_ENCRYPT_DATA, CKM_ARIA_CBC_PAD, CKM_ARIA_CFB128, +CKM_ARIA_CFB8, CKM_ARIA_CMAC, CKM_ARIA_CMAC_GENERAL, CKM_ARIA_CTR, CKM_ARIA_ECB, +CKM_ARIA_ECB_ENCRYPT_DATA, CKM_ARIA_GCM, CKM_ARIA_KEY_GEN, CKM_ARIA_L_CBC, CKM_ARIA_L_CBC_PAD, +CKM_ARIA_L_ECB, CKM_ARIA_L_MAC, CKM_ARIA_L_MAC_GENERAL, CKM_ARIA_MAC, CKM_ARIA_MAC_GENERAL, +CKM_ARIA_OFB, CKM_BATON_CBC128, CKM_BATON_COUNTER, CKM_BATON_ECB128, CKM_BATON_ECB96, +CKM_BATON_KEY_GEN, CKM_BATON_SHUFFLE, CKM_BATON_WRAP, CKM_BLOWFISH_CBC, CKM_BLOWFISH_KEY_GEN, +CKM_CAMELLIA_CBC, CKM_CAMELLIA_CBC_ENCRYPT_DATA, CKM_CAMELLIA_CBC_PAD, CKM_CAMELLIA_CTR, +CKM_CAMELLIA_ECB, CKM_CAMELLIA_ECB_ENCRYPT_DATA, CKM_CAMELLIA_KEY_GEN, CKM_CAMELLIA_MAC, +CKM_CAMELLIA_MAC_GENERAL, CKM_CAST3_CBC, CKM_CAST3_CBC_PAD, CKM_CAST3_ECB, CKM_CAST3_KEY_GEN, +CKM_CAST3_MAC, CKM_CAST3_MAC_GENERAL, CKM_CAST5_CBC, CKM_CAST5_CBC_PAD, CKM_CAST5_ECB, +CKM_CAST5_KEY_GEN, CKM_CAST5_MAC, CKM_CAST5_MAC_GENERAL, CKM_CAST_CBC, CKM_CAST_CBC_PAD, +CKM_CAST_ECB, CKM_CAST_KEY_GEN, CKM_CAST_MAC, CKM_CAST_MAC_GENERAL, CKM_CDMF_CBC, CKM_CDMF_CBC_PAD, +CKM_CDMF_ECB, CKM_CDMF_KEY_GEN, CKM_CDMF_MAC, CKM_CDMF_MAC_GENERAL, CKM_CMS_SIG, +CKM_CONCATENATE_BASE_AND_DATA, CKM_CONCATENATE_BASE_AND_KEY, CKM_CONCATENATE_DATA_AND_BASE, +CKM_DES2_DUKPT_DATA, CKM_DES2_DUKPT_DATA_RESP, CKM_DES2_DUKPT_MAC, CKM_DES2_DUKPT_MAC_RESP, +CKM_DES2_DUKPT_PIN, CKM_DES2_KEY_GEN, CKM_DES3_CBC, CKM_DES3_CBC_ENCRYPT_DATA, CKM_DES3_CBC_PAD, +CKM_DES3_CBC_PAD_IPSEC, CKM_DES3_CMAC, CKM_DES3_CMAC_GENERAL, CKM_DES3_CTR, CKM_DES3_ECB, +CKM_DES3_ECB_ENCRYPT_DATA, CKM_DES3_KEY_GEN, CKM_DES3_MAC, CKM_DES3_MAC_GENERAL, CKM_DES3_X919_MAC, +CKM_DES_CBC, CKM_DES_CBC_ENCRYPT_DATA, CKM_DES_CBC_PAD, CKM_DES_CFB64, CKM_DES_CFB8, CKM_DES_ECB, +CKM_DES_ECB_ENCRYPT_DATA, CKM_DES_KEY_GEN, CKM_DES_MAC, CKM_DES_MAC_GENERAL, CKM_DES_OFB64, +CKM_DES_OFB8, CKM_DH_PKCS_DERIVE, CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKM_DSA, +CKM_DSA_KEY_PAIR_GEN, CKM_DSA_PARAMETER_GEN, CKM_DSA_SHA1, CKM_DSA_SHA224, CKM_DSA_SHA256, +CKM_ECDH1_COFACTOR_DERIVE, CKM_ECDH1_DERIVE, CKM_ECDSA, CKM_ECDSA_GBCS_SHA256, +CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, +CKM_ECDSA_SHA256, CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECIES, CKM_ECMQV_DERIVE, +CKM_EXTRACT_KEY_FROM_KEY, CKM_FASTHASH, CKM_FORTEZZA_TIMESTAMP, CKM_GENERIC_SECRET_KEY_GEN, +CKM_HAS160, CKM_HOTP, CKM_HOTP_KEY_GEN, CKM_IDEA_CBC, CKM_IDEA_CBC_PAD, CKM_IDEA_ECB, +CKM_IDEA_KEY_GEN, CKM_IDEA_MAC, CKM_IDEA_MAC_GENERAL, CKM_INDIRECT_LOGIN_REENCRYPT, +CKM_JUNIPER_CBC128, CKM_JUNIPER_COUNTER, CKM_JUNIPER_ECB128, CKM_JUNIPER_KEY_GEN, +CKM_JUNIPER_SHUFFLE, CKM_JUNIPER_WRAP, CKM_KCDSA_HAS160, CKM_KCDSA_HAS160_NO_PAD, +CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_SHA1, CKM_KCDSA_SHA1_NO_PAD, +CKM_KCDSA_SHA224, CKM_KCDSA_SHA224_NO_PAD, CKM_KCDSA_SHA256, CKM_KCDSA_SHA256_NO_PAD, +CKM_KCDSA_SHA384, CKM_KCDSA_SHA384_NO_PAD, CKM_KCDSA_SHA512, CKM_KCDSA_SHA512_NO_PAD, +CKM_KEA_KEY_DERIVE, CKM_KEA_KEY_PAIR_GEN, CKM_KEY_TRANSLATION, CKM_KEY_WRAP_LYNKS, +CKM_KEY_WRAP_SET_OAEP, CKM_KIP_DERIVE, CKM_KIP_MAC, CKM_KIP_WRAP, CKM_MD2, CKM_MD2_HMAC, +CKM_MD2_HMAC_GENERAL, CKM_MD2_KEY_DERIVATION, CKM_MD2_RSA_PKCS, CKM_MD5, CKM_MD5_HMAC, +CKM_MD5_HMAC_GENERAL, CKM_MD5_KEY_DERIVATION, CKM_MD5_RSA_PKCS, CKM_NIST_PRF_KDF, +CKM_PBA_SHA1_WITH_SHA1_HMAC, CKM_PBE_MD2_DES_CBC, CKM_PBE_MD5_CAST3_CBC, CKM_PBE_MD5_CAST5_CBC, +CKM_PBE_MD5_CAST_CBC, CKM_PBE_MD5_DES_CBC, CKM_PBE_SHA1_CAST5_CBC, CKM_PBE_SHA1_DES2_EDE_CBC, +CKM_PBE_SHA1_DES3_EDE_CBC, CKM_PBE_SHA1_RC2_128_CBC, CKM_PBE_SHA1_RC2_40_CBC, CKM_PBE_SHA1_RC4_128, +CKM_PBE_SHA1_RC4_40, CKM_PKCS5_PBKD2, CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM, CKM_PRF_KDF, +CKM_RC2_CBC, CKM_RC2_CBC_PAD, CKM_RC2_ECB, CKM_RC2_KEY_GEN, CKM_RC2_MAC, CKM_RC2_MAC_GENERAL, +CKM_RC4, CKM_RC4_KEY_GEN, CKM_RC5_CBC, CKM_RC5_CBC_PAD, CKM_RC5_ECB, CKM_RC5_KEY_GEN, CKM_RC5_MAC, +CKM_RC5_MAC_GENERAL, CKM_RIPEMD128, CKM_RIPEMD128_HMAC, CKM_RIPEMD128_HMAC_GENERAL, +CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160, CKM_RIPEMD160_HMAC, CKM_RIPEMD160_HMAC_GENERAL, +CKM_RIPEMD160_RSA_PKCS, CKM_RSA_9796, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, +CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_OAEP, +CKM_RSA_PKCS_PSS, CKM_RSA_X9_31, CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31_NON_FIPS, CKM_RSA_X_509, +CKM_SECURID, CKM_SECURID_KEY_GEN, CKM_SEED_CBC, CKM_SEED_CBC_PAD, CKM_SEED_CMAC, +CKM_SEED_CMAC_GENERAL, CKM_SEED_CTR, CKM_SEED_ECB, CKM_SEED_KEY_GEN, CKM_SEED_MAC, +CKM_SEED_MAC_GENERAL, CKM_SHA1_KEY_DERIVATION, CKM_SHA1_RSA_PKCS, CKM_SHA1_RSA_PKCS_PSS, +CKM_SHA1_RSA_X9_31, CKM_SHA1_RSA_X9_31_NON_FIPS, CKM_SHA224, CKM_SHA224_HMAC, +CKM_SHA224_HMAC_GENERAL, CKM_SHA224_KEY_DERIVATION, CKM_SHA224_RSA_PKCS, CKM_SHA224_RSA_PKCS_PSS, +CKM_SHA224_RSA_X9_31, CKM_SHA224_RSA_X9_31_NON_FIPS, CKM_SHA256, CKM_SHA256_HMAC, +CKM_SHA256_HMAC_GENERAL, CKM_SHA256_KEY_DERIVATION, CKM_SHA256_RSA_PKCS, CKM_SHA256_RSA_PKCS_PSS, +CKM_SHA256_RSA_X9_31, CKM_SHA256_RSA_X9_31_NON_FIPS, CKM_SHA384, CKM_SHA384_HMAC, +CKM_SHA384_HMAC_GENERAL, CKM_SHA384_KEY_DERIVATION, CKM_SHA384_RSA_PKCS, CKM_SHA384_RSA_PKCS_PSS, +CKM_SHA384_RSA_X9_31, CKM_SHA384_RSA_X9_31_NON_FIPS, CKM_SHA512, CKM_SHA512_HMAC, +CKM_SHA512_HMAC_GENERAL, CKM_SHA512_KEY_DERIVATION, CKM_SHA512_RSA_PKCS, CKM_SHA512_RSA_PKCS_PSS, +CKM_SHA512_RSA_X9_31, CKM_SHA512_RSA_X9_31_NON_FIPS, CKM_SHA_1, CKM_SHA_1_HMAC, +CKM_SHA_1_HMAC_GENERAL, CKM_SKIPJACK_CBC64, CKM_SKIPJACK_CFB16, CKM_SKIPJACK_CFB32, +CKM_SKIPJACK_CFB64, CKM_SKIPJACK_CFB8, CKM_SKIPJACK_ECB64, CKM_SKIPJACK_KEY_GEN, CKM_SKIPJACK_OFB64, +CKM_SKIPJACK_PRIVATE_WRAP, CKM_SKIPJACK_RELAYX, CKM_SKIPJACK_WRAP, CKM_SSL3_KEY_AND_MAC_DERIVE, +CKM_SSL3_MASTER_KEY_DERIVE, CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_SSL3_MD5_MAC, +CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_SHA1_MAC, CKM_TDEA_KW, CKM_TDEA_KWP, +CKM_TLS_KEY_AND_MAC_DERIVE, CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_MASTER_KEY_DERIVE_DH, +CKM_TLS_PRE_MASTER_KEY_GEN, CKM_TLS_PRF, CKM_TWOFISH_CBC, CKM_TWOFISH_KEY_GEN, CKM_VENDOR_DEFINED, +CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE, CKM_WTLS_MASTER_KEY_DERIVE, CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC, +CKM_WTLS_PRE_MASTER_KEY_GEN, CKM_WTLS_PRF, CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE, CKM_X9_42_DH_DERIVE, +CKM_X9_42_DH_HYBRID_DERIVE, CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_PARAMETER_GEN, +CKM_X9_42_MQV_DERIVE, CKM_XOR_BASE_AND_DATA, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_XOR_BASE_AND_KEY, +CKO_CERTIFICATE, CKO_DATA, CKO_SECRET_KEY) CKM_DES_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_DES, @@ -859,6 +920,352 @@ CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} +MECHANISM_LOOKUP_EXT = { + CKM_RSA_PKCS_KEY_PAIR_GEN: ('CKM_RSA_PKCS_KEY_PAIR_GEN',), + CKM_RSA_PKCS: ('CKM_RSA_PKCS',), + CKM_RSA_9796: ('CKM_RSA_9796',), + CKM_RSA_X_509: ('CKM_RSA_X_509',), + CKM_MD2_RSA_PKCS: ('CKM_MD2_RSA_PKCS',), + CKM_MD5_RSA_PKCS: ('CKM_MD5_RSA_PKCS',), + CKM_SHA1_RSA_PKCS: ('CKM_SHA1_RSA_PKCS',), + CKM_RIPEMD128_RSA_PKCS: ('CKM_RIPEMD128_RSA_PKCS',), + CKM_RIPEMD160_RSA_PKCS: ('CKM_RIPEMD160_RSA_PKCS',), + CKM_RSA_PKCS_OAEP: ('CKM_RSA_PKCS_OAEP',), + CKM_RSA_X9_31_KEY_PAIR_GEN: ('CKM_RSA_X9_31_KEY_PAIR_GEN',), + CKM_RSA_X9_31: ('CKM_RSA_X9_31',), + CKM_SHA1_RSA_X9_31: ('CKM_SHA1_RSA_X9_31',), + CKM_RSA_PKCS_PSS: ('CKM_RSA_PKCS_PSS',), + CKM_SHA1_RSA_PKCS_PSS: ('CKM_SHA1_RSA_PKCS_PSS',), + CKM_DSA_KEY_PAIR_GEN: ('CKM_DSA_KEY_PAIR_GEN',), + CKM_DSA: ('CKM_DSA',), + CKM_DSA_SHA1: ('CKM_DSA_SHA1',), + CKM_DH_PKCS_KEY_PAIR_GEN: ('CKM_DH_PKCS_KEY_PAIR_GEN',), + CKM_DH_PKCS_DERIVE: ('CKM_DH_PKCS_DERIVE',), + CKM_X9_42_DH_KEY_PAIR_GEN: ('CKM_X9_42_DH_KEY_PAIR_GEN',), + CKM_X9_42_DH_DERIVE: ('CKM_X9_42_DH_DERIVE',), + CKM_X9_42_DH_HYBRID_DERIVE: ('CKM_X9_42_DH_HYBRID_DERIVE',), + CKM_X9_42_MQV_DERIVE: ('CKM_X9_42_MQV_DERIVE',), + CKM_SHA256_RSA_PKCS: ('CKM_SHA256_RSA_PKCS',), + CKM_SHA384_RSA_PKCS: ('CKM_SHA384_RSA_PKCS',), + CKM_SHA512_RSA_PKCS: ('CKM_SHA512_RSA_PKCS',), + CKM_SHA256_RSA_PKCS_PSS: ('CKM_SHA256_RSA_PKCS_PSS',), + CKM_SHA384_RSA_PKCS_PSS: ('CKM_SHA384_RSA_PKCS_PSS',), + CKM_SHA512_RSA_PKCS_PSS: ('CKM_SHA512_RSA_PKCS_PSS',), + CKM_SHA224_RSA_PKCS: ('CKM_SHA224_RSA_PKCS',), + CKM_SHA224_RSA_PKCS_PSS: ('CKM_SHA224_RSA_PKCS_PSS',), + CKM_RC2_KEY_GEN: ('CKM_RC2_KEY_GEN',), + CKM_RC2_ECB: ('CKM_RC2_ECB',), + CKM_RC2_CBC: ('CKM_RC2_CBC',), + CKM_RC2_MAC: ('CKM_RC2_MAC',), + CKM_RC2_MAC_GENERAL: ('CKM_RC2_MAC_GENERAL',), + CKM_RC2_CBC_PAD: ('CKM_RC2_CBC_PAD',), + CKM_RC4_KEY_GEN: ('CKM_RC4_KEY_GEN',), + CKM_RC4: ('CKM_RC4',), + CKM_DES_KEY_GEN: ('CKM_DES_KEY_GEN',), + CKM_DES_ECB: ('CKM_DES_ECB',), + CKM_DES_CBC: ('CKM_DES_CBC',), + CKM_DES_MAC: ('CKM_DES_MAC',), + CKM_DES_MAC_GENERAL: ('CKM_DES_MAC_GENERAL',), + CKM_DES_CBC_PAD: ('CKM_DES_CBC_PAD',), + CKM_DES2_KEY_GEN: ('CKM_DES2_KEY_GEN',), + CKM_DES3_KEY_GEN: ('CKM_DES3_KEY_GEN',), + CKM_DES3_ECB: ('CKM_DES3_ECB',), + CKM_DES3_CBC: ('CKM_DES3_CBC',), + CKM_DES3_MAC: ('CKM_DES3_MAC',), + CKM_DES3_MAC_GENERAL: ('CKM_DES3_MAC_GENERAL',), + CKM_DES3_CBC_PAD: ('CKM_DES3_CBC_PAD',), + CKM_DES3_CMAC_GENERAL: ('CKM_DES3_CMAC_GENERAL',), + CKM_DES3_CMAC: ('CKM_DES3_CMAC',), + CKM_CDMF_KEY_GEN: ('CKM_CDMF_KEY_GEN',), + CKM_CDMF_ECB: ('CKM_CDMF_ECB',), + CKM_CDMF_CBC: ('CKM_CDMF_CBC',), + CKM_CDMF_MAC: ('CKM_CDMF_MAC',), + CKM_CDMF_MAC_GENERAL: ('CKM_CDMF_MAC_GENERAL',), + CKM_CDMF_CBC_PAD: ('CKM_CDMF_CBC_PAD',), + CKM_DES_OFB64: ('CKM_DES_OFB64',), + CKM_DES_OFB8: ('CKM_DES_OFB8',), + CKM_DES_CFB64: ('CKM_DES_CFB64',), + CKM_DES_CFB8: ('CKM_DES_CFB8',), + CKM_MD2: ('CKM_MD2',), + CKM_MD2_HMAC: ('CKM_MD2_HMAC',), + CKM_MD2_HMAC_GENERAL: ('CKM_MD2_HMAC_GENERAL',), + CKM_MD5: ('CKM_MD5',), + CKM_MD5_HMAC: ('CKM_MD5_HMAC',), + CKM_MD5_HMAC_GENERAL: ('CKM_MD5_HMAC_GENERAL',), + CKM_SHA_1: ('CKM_SHA_1',), + CKM_SHA_1_HMAC: ('CKM_SHA_1_HMAC',), + CKM_SHA_1_HMAC_GENERAL: ('CKM_SHA_1_HMAC_GENERAL',), + CKM_RIPEMD128: ('CKM_RIPEMD128',), + CKM_RIPEMD128_HMAC: ('CKM_RIPEMD128_HMAC',), + CKM_RIPEMD128_HMAC_GENERAL: ('CKM_RIPEMD128_HMAC_GENERAL',), + CKM_RIPEMD160: ('CKM_RIPEMD160',), + CKM_RIPEMD160_HMAC: ('CKM_RIPEMD160_HMAC',), + CKM_RIPEMD160_HMAC_GENERAL: ('CKM_RIPEMD160_HMAC_GENERAL',), + CKM_SHA256: ('CKM_SHA256',), + CKM_SHA256_HMAC: ('CKM_SHA256_HMAC',), + CKM_SHA256_HMAC_GENERAL: ('CKM_SHA256_HMAC_GENERAL',), + CKM_SHA224: ('CKM_SHA224',), + CKM_SHA224_HMAC: ('CKM_SHA224_HMAC',), + CKM_SHA224_HMAC_GENERAL: ('CKM_SHA224_HMAC_GENERAL',), + CKM_SHA384: ('CKM_SHA384',), + CKM_SHA384_HMAC: ('CKM_SHA384_HMAC',), + CKM_SHA384_HMAC_GENERAL: ('CKM_SHA384_HMAC_GENERAL',), + CKM_SHA512: ('CKM_SHA512',), + CKM_SHA512_HMAC: ('CKM_SHA512_HMAC',), + CKM_SHA512_HMAC_GENERAL: ('CKM_SHA512_HMAC_GENERAL',), + CKM_SECURID_KEY_GEN: ('CKM_SECURID_KEY_GEN',), + CKM_SECURID: ('CKM_SECURID',), + CKM_HOTP_KEY_GEN: ('CKM_HOTP_KEY_GEN',), + CKM_HOTP: ('CKM_HOTP',), + CKM_ACTI: ('CKM_ACTI',), + CKM_ACTI_KEY_GEN: ('CKM_ACTI_KEY_GEN',), + CKM_CAST_KEY_GEN: ('CKM_CAST_KEY_GEN',), + CKM_CAST_ECB: ('CKM_CAST_ECB',), + CKM_CAST_CBC: ('CKM_CAST_CBC',), + CKM_CAST_MAC: ('CKM_CAST_MAC',), + CKM_CAST_MAC_GENERAL: ('CKM_CAST_MAC_GENERAL',), + CKM_CAST_CBC_PAD: ('CKM_CAST_CBC_PAD',), + CKM_CAST3_KEY_GEN: ('CKM_CAST3_KEY_GEN',), + CKM_CAST3_ECB: ('CKM_CAST3_ECB',), + CKM_CAST3_CBC: ('CKM_CAST3_CBC',), + CKM_CAST3_MAC: ('CKM_CAST3_MAC',), + CKM_CAST3_MAC_GENERAL: ('CKM_CAST3_MAC_GENERAL',), + CKM_CAST3_CBC_PAD: ('CKM_CAST3_CBC_PAD',), + CKM_CAST5_KEY_GEN: ('CKM_CAST5_KEY_GEN', 'CKM_CAST128_KEY_GEN'), + CKM_CAST5_ECB: ('CKM_CAST5_ECB', 'CKM_CAST128_ECB'), + CKM_CAST5_CBC: ('CKM_CAST5_CBC', 'CKM_CAST128_CBC'), + CKM_CAST5_MAC: ('CKM_CAST5_MAC', 'CKM_CAST128_MAC'), + CKM_CAST5_MAC_GENERAL: ('CKM_CAST5_MAC_GENERAL', 'CKM_CAST128_MAC_GENERAL'), + CKM_CAST5_CBC_PAD: ('CKM_CAST5_CBC_PAD', 'CKM_CAST128_CBC_PAD'), + CKM_RC5_KEY_GEN: ('CKM_RC5_KEY_GEN',), + CKM_RC5_ECB: ('CKM_RC5_ECB',), + CKM_RC5_CBC: ('CKM_RC5_CBC',), + CKM_RC5_MAC: ('CKM_RC5_MAC',), + CKM_RC5_MAC_GENERAL: ('CKM_RC5_MAC_GENERAL',), + CKM_RC5_CBC_PAD: ('CKM_RC5_CBC_PAD',), + CKM_IDEA_KEY_GEN: ('CKM_IDEA_KEY_GEN',), + CKM_IDEA_ECB: ('CKM_IDEA_ECB',), + CKM_IDEA_CBC: ('CKM_IDEA_CBC',), + CKM_IDEA_MAC: ('CKM_IDEA_MAC',), + CKM_IDEA_MAC_GENERAL: ('CKM_IDEA_MAC_GENERAL',), + CKM_IDEA_CBC_PAD: ('CKM_IDEA_CBC_PAD',), + CKM_GENERIC_SECRET_KEY_GEN: ('CKM_GENERIC_SECRET_KEY_GEN',), + CKM_CONCATENATE_BASE_AND_KEY: ('CKM_CONCATENATE_BASE_AND_KEY',), + CKM_CONCATENATE_BASE_AND_DATA: ('CKM_CONCATENATE_BASE_AND_DATA',), + CKM_CONCATENATE_DATA_AND_BASE: ('CKM_CONCATENATE_DATA_AND_BASE',), + CKM_XOR_BASE_AND_DATA: ('CKM_XOR_BASE_AND_DATA',), + CKM_EXTRACT_KEY_FROM_KEY: ('CKM_EXTRACT_KEY_FROM_KEY',), + CKM_SSL3_PRE_MASTER_KEY_GEN: ('CKM_SSL3_PRE_MASTER_KEY_GEN',), + CKM_SSL3_MASTER_KEY_DERIVE: ('CKM_SSL3_MASTER_KEY_DERIVE',), + CKM_SSL3_KEY_AND_MAC_DERIVE: ('CKM_SSL3_KEY_AND_MAC_DERIVE',), + CKM_SSL3_MASTER_KEY_DERIVE_DH: ('CKM_SSL3_MASTER_KEY_DERIVE_DH',), + CKM_TLS_PRE_MASTER_KEY_GEN: ('CKM_TLS_PRE_MASTER_KEY_GEN',), + CKM_TLS_MASTER_KEY_DERIVE: ('CKM_TLS_MASTER_KEY_DERIVE',), + CKM_TLS_KEY_AND_MAC_DERIVE: ('CKM_TLS_KEY_AND_MAC_DERIVE',), + CKM_TLS_MASTER_KEY_DERIVE_DH: ('CKM_TLS_MASTER_KEY_DERIVE_DH',), + CKM_TLS_PRF: ('CKM_TLS_PRF',), + CKM_SSL3_MD5_MAC: ('CKM_SSL3_MD5_MAC',), + CKM_SSL3_SHA1_MAC: ('CKM_SSL3_SHA1_MAC',), + CKM_MD5_KEY_DERIVATION: ('CKM_MD5_KEY_DERIVATION',), + CKM_MD2_KEY_DERIVATION: ('CKM_MD2_KEY_DERIVATION',), + CKM_SHA1_KEY_DERIVATION: ('CKM_SHA1_KEY_DERIVATION',), + CKM_SHA256_KEY_DERIVATION: ('CKM_SHA256_KEY_DERIVATION',), + CKM_SHA384_KEY_DERIVATION: ('CKM_SHA384_KEY_DERIVATION',), + CKM_SHA512_KEY_DERIVATION: ('CKM_SHA512_KEY_DERIVATION',), + CKM_SHA224_KEY_DERIVATION: ('CKM_SHA224_KEY_DERIVATION',), + CKM_PBE_MD2_DES_CBC: ('CKM_PBE_MD2_DES_CBC',), + CKM_PBE_MD5_DES_CBC: ('CKM_PBE_MD5_DES_CBC',), + CKM_PBE_MD5_CAST_CBC: ('CKM_PBE_MD5_CAST_CBC',), + CKM_PBE_MD5_CAST3_CBC: ('CKM_PBE_MD5_CAST3_CBC',), + CKM_PBE_MD5_CAST5_CBC: ('CKM_PBE_MD5_CAST5_CBC', 'CKM_PBE_MD5_CAST128_CBC'), + CKM_PBE_SHA1_CAST5_CBC: ('CKM_PBE_SHA1_CAST5_CBC', 'CKM_PBE_SHA1_CAST128_CBC'), + CKM_PBE_SHA1_RC4_128: ('CKM_PBE_SHA1_RC4_128',), + CKM_PBE_SHA1_RC4_40: ('CKM_PBE_SHA1_RC4_40',), + CKM_PBE_SHA1_DES3_EDE_CBC: ('CKM_PBE_SHA1_DES3_EDE_CBC',), + CKM_PBE_SHA1_DES2_EDE_CBC: ('CKM_PBE_SHA1_DES2_EDE_CBC',), + CKM_PBE_SHA1_RC2_128_CBC: ('CKM_PBE_SHA1_RC2_128_CBC',), + CKM_PBE_SHA1_RC2_40_CBC: ('CKM_PBE_SHA1_RC2_40_CBC',), + CKM_PKCS5_PBKD2: ('CKM_PKCS5_PBKD2',), + CKM_PBA_SHA1_WITH_SHA1_HMAC: ('CKM_PBA_SHA1_WITH_SHA1_HMAC',), + CKM_WTLS_PRE_MASTER_KEY_GEN: ('CKM_WTLS_PRE_MASTER_KEY_GEN',), + CKM_WTLS_MASTER_KEY_DERIVE: ('CKM_WTLS_MASTER_KEY_DERIVE',), + CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC: ('CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC',), + CKM_WTLS_PRF: ('CKM_WTLS_PRF',), + CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE: ('CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE',), + CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE: ('CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE',), + CKM_KEY_WRAP_LYNKS: ('CKM_KEY_WRAP_LYNKS',), + CKM_KEY_WRAP_SET_OAEP: ('CKM_KEY_WRAP_SET_OAEP',), + CKM_CMS_SIG: ('CKM_CMS_SIG',), + CKM_KIP_DERIVE: ('CKM_KIP_DERIVE',), + CKM_KIP_WRAP: ('CKM_KIP_WRAP',), + CKM_KIP_MAC: ('CKM_KIP_MAC',), + CKM_CAMELLIA_KEY_GEN: ('CKM_CAMELLIA_KEY_GEN',), + CKM_CAMELLIA_ECB: ('CKM_CAMELLIA_ECB',), + CKM_CAMELLIA_CBC: ('CKM_CAMELLIA_CBC',), + CKM_CAMELLIA_MAC: ('CKM_CAMELLIA_MAC',), + CKM_CAMELLIA_MAC_GENERAL: ('CKM_CAMELLIA_MAC_GENERAL',), + CKM_CAMELLIA_CBC_PAD: ('CKM_CAMELLIA_CBC_PAD',), + CKM_CAMELLIA_ECB_ENCRYPT_DATA: ('CKM_CAMELLIA_ECB_ENCRYPT_DATA',), + CKM_CAMELLIA_CBC_ENCRYPT_DATA: ('CKM_CAMELLIA_CBC_ENCRYPT_DATA',), + CKM_CAMELLIA_CTR: ('CKM_CAMELLIA_CTR',), + CKM_ARIA_KEY_GEN: ('CKM_ARIA_KEY_GEN',), + CKM_ARIA_ECB: ('CKM_ARIA_ECB',), + CKM_ARIA_CBC: ('CKM_ARIA_CBC',), + CKM_ARIA_MAC: ('CKM_ARIA_MAC',), + CKM_ARIA_MAC_GENERAL: ('CKM_ARIA_MAC_GENERAL',), + CKM_ARIA_CBC_PAD: ('CKM_ARIA_CBC_PAD',), + CKM_ARIA_ECB_ENCRYPT_DATA: ('CKM_ARIA_ECB_ENCRYPT_DATA',), + CKM_ARIA_CBC_ENCRYPT_DATA: ('CKM_ARIA_CBC_ENCRYPT_DATA',), + CKM_SKIPJACK_KEY_GEN: ('CKM_SKIPJACK_KEY_GEN',), + CKM_SKIPJACK_ECB64: ('CKM_SKIPJACK_ECB64',), + CKM_SKIPJACK_CBC64: ('CKM_SKIPJACK_CBC64',), + CKM_SKIPJACK_OFB64: ('CKM_SKIPJACK_OFB64',), + CKM_SKIPJACK_CFB64: ('CKM_SKIPJACK_CFB64',), + CKM_SKIPJACK_CFB32: ('CKM_SKIPJACK_CFB32',), + CKM_SKIPJACK_CFB16: ('CKM_SKIPJACK_CFB16',), + CKM_SKIPJACK_CFB8: ('CKM_SKIPJACK_CFB8',), + CKM_SKIPJACK_WRAP: ('CKM_SKIPJACK_WRAP',), + CKM_SKIPJACK_PRIVATE_WRAP: ('CKM_SKIPJACK_PRIVATE_WRAP',), + CKM_SKIPJACK_RELAYX: ('CKM_SKIPJACK_RELAYX',), + CKM_KEA_KEY_PAIR_GEN: ('CKM_KEA_KEY_PAIR_GEN',), + CKM_KEA_KEY_DERIVE: ('CKM_KEA_KEY_DERIVE',), + CKM_FORTEZZA_TIMESTAMP: ('CKM_FORTEZZA_TIMESTAMP',), + CKM_BATON_KEY_GEN: ('CKM_BATON_KEY_GEN',), + CKM_BATON_ECB128: ('CKM_BATON_ECB128',), + CKM_BATON_ECB96: ('CKM_BATON_ECB96',), + CKM_BATON_CBC128: ('CKM_BATON_CBC128',), + CKM_BATON_COUNTER: ('CKM_BATON_COUNTER',), + CKM_BATON_SHUFFLE: ('CKM_BATON_SHUFFLE',), + CKM_BATON_WRAP: ('CKM_BATON_WRAP',), + CKM_ECDSA_KEY_PAIR_GEN: ('CKM_ECDSA_KEY_PAIR_GEN', 'CKM_EC_KEY_PAIR_GEN'), + CKM_ECDSA: ('CKM_ECDSA',), + CKM_ECDSA_SHA1: ('CKM_ECDSA_SHA1',), + CKM_ECDH1_DERIVE: ('CKM_ECDH1_DERIVE',), + CKM_ECDH1_COFACTOR_DERIVE: ('CKM_ECDH1_COFACTOR_DERIVE',), + CKM_ECMQV_DERIVE: ('CKM_ECMQV_DERIVE',), + CKM_JUNIPER_KEY_GEN: ('CKM_JUNIPER_KEY_GEN',), + CKM_JUNIPER_ECB128: ('CKM_JUNIPER_ECB128',), + CKM_JUNIPER_CBC128: ('CKM_JUNIPER_CBC128',), + CKM_JUNIPER_COUNTER: ('CKM_JUNIPER_COUNTER',), + CKM_JUNIPER_SHUFFLE: ('CKM_JUNIPER_SHUFFLE',), + CKM_JUNIPER_WRAP: ('CKM_JUNIPER_WRAP',), + CKM_FASTHASH: ('CKM_FASTHASH',), + CKM_AES_KEY_GEN: ('CKM_AES_KEY_GEN',), + CKM_AES_ECB: ('CKM_AES_ECB',), + CKM_AES_CBC: ('CKM_AES_CBC',), + CKM_AES_MAC: ('CKM_AES_MAC',), + CKM_AES_MAC_GENERAL: ('CKM_AES_MAC_GENERAL',), + CKM_AES_CBC_PAD: ('CKM_AES_CBC_PAD',), + CKM_AES_CTR: ('CKM_AES_CTR',), + CKM_AES_CMAC_GENERAL: ('CKM_AES_CMAC_GENERAL',), + CKM_AES_CMAC: ('CKM_AES_CMAC',), + CKM_BLOWFISH_KEY_GEN: ('CKM_BLOWFISH_KEY_GEN',), + CKM_BLOWFISH_CBC: ('CKM_BLOWFISH_CBC',), + CKM_TWOFISH_KEY_GEN: ('CKM_TWOFISH_KEY_GEN',), + CKM_TWOFISH_CBC: ('CKM_TWOFISH_CBC',), + CKM_DES_ECB_ENCRYPT_DATA: ('CKM_DES_ECB_ENCRYPT_DATA',), + CKM_DES_CBC_ENCRYPT_DATA: ('CKM_DES_CBC_ENCRYPT_DATA',), + CKM_DES3_ECB_ENCRYPT_DATA: ('CKM_DES3_ECB_ENCRYPT_DATA',), + CKM_DES3_CBC_ENCRYPT_DATA: ('CKM_DES3_CBC_ENCRYPT_DATA',), + CKM_AES_ECB_ENCRYPT_DATA: ('CKM_AES_ECB_ENCRYPT_DATA',), + CKM_AES_CBC_ENCRYPT_DATA: ('CKM_AES_CBC_ENCRYPT_DATA',), + CKM_DSA_PARAMETER_GEN: ('CKM_DSA_PARAMETER_GEN',), + CKM_DH_PKCS_PARAMETER_GEN: ('CKM_DH_PKCS_PARAMETER_GEN',), + CKM_X9_42_DH_PARAMETER_GEN: ('CKM_X9_42_DH_PARAMETER_GEN',), + CKM_AES_KEY_WRAP: ('CKM_AES_KEY_WRAP',), + CKM_AES_KEY_WRAP_PAD: ('CKM_AES_KEY_WRAP_PAD',), + CKM_VENDOR_DEFINED: ('CKM_VENDOR_DEFINED',), + CKM_KEY_TRANSLATION: ('CKM_KEY_TRANSLATION',), + CKM_XOR_BASE_AND_KEY: ('CKM_XOR_BASE_AND_KEY',), + CKM_2DES_KEY_DERIVATION: ('CKM_2DES_KEY_DERIVATION',), + CKM_INDIRECT_LOGIN_REENCRYPT: ('CKM_INDIRECT_LOGIN_REENCRYPT',), + CKM_HAS160: ('CKM_HAS160',), + CKM_KCDSA_KEY_PAIR_GEN: ('CKM_KCDSA_KEY_PAIR_GEN',), + CKM_KCDSA_HAS160: ('CKM_KCDSA_HAS160',), + CKM_SEED_KEY_GEN: ('CKM_SEED_KEY_GEN',), + CKM_SEED_ECB: ('CKM_SEED_ECB',), + CKM_SEED_CBC: ('CKM_SEED_CBC',), + CKM_SEED_CBC_PAD: ('CKM_SEED_CBC_PAD',), + CKM_SEED_MAC: ('CKM_SEED_MAC',), + CKM_SEED_MAC_GENERAL: ('CKM_SEED_MAC_GENERAL',), + CKM_KCDSA_SHA1: ('CKM_KCDSA_SHA1',), + CKM_KCDSA_SHA224: ('CKM_KCDSA_SHA224',), + CKM_KCDSA_SHA256: ('CKM_KCDSA_SHA256',), + CKM_KCDSA_SHA384: ('CKM_KCDSA_SHA384',), + CKM_KCDSA_SHA512: ('CKM_KCDSA_SHA512',), + CKM_KCDSA_PARAMETER_GEN: ('CKM_KCDSA_PARAMETER_GEN',), + CKM_DES3_CTR: ('CKM_DES3_CTR',), + CKM_AES_CFB8: ('CKM_AES_CFB8',), + CKM_AES_CFB128: ('CKM_AES_CFB128',), + CKM_AES_OFB: ('CKM_AES_OFB',), + CKM_AES_GCM: ('CKM_AES_GCM',), + CKM_ARIA_CFB8: ('CKM_ARIA_CFB8',), + CKM_ARIA_CFB128: ('CKM_ARIA_CFB128',), + CKM_ARIA_OFB: ('CKM_ARIA_OFB',), + CKM_ARIA_CTR: ('CKM_ARIA_CTR',), + CKM_ARIA_GCM: ('CKM_ARIA_GCM',), + CKM_ECDSA_SHA224: ('CKM_ECDSA_SHA224',), + CKM_ECDSA_SHA256: ('CKM_ECDSA_SHA256',), + CKM_ECDSA_SHA384: ('CKM_ECDSA_SHA384',), + CKM_ECDSA_SHA512: ('CKM_ECDSA_SHA512',), + CKM_AES_GMAC: ('CKM_AES_GMAC',), + CKM_ARIA_CMAC: ('CKM_ARIA_CMAC',), + CKM_ARIA_CMAC_GENERAL: ('CKM_ARIA_CMAC_GENERAL',), + CKM_SEED_CMAC: ('CKM_SEED_CMAC',), + CKM_SEED_CMAC_GENERAL: ('CKM_SEED_CMAC_GENERAL',), + CKM_DES3_CBC_PAD_IPSEC: ('CKM_DES3_CBC_PAD_IPSEC',), + CKM_AES_CBC_PAD_IPSEC: ('CKM_AES_CBC_PAD_IPSEC',), + CKM_ARIA_L_ECB: ('CKM_ARIA_L_ECB',), + CKM_ARIA_L_CBC: ('CKM_ARIA_L_CBC',), + CKM_ARIA_L_CBC_PAD: ('CKM_ARIA_L_CBC_PAD',), + CKM_ARIA_L_MAC: ('CKM_ARIA_L_MAC',), + CKM_ARIA_L_MAC_GENERAL: ('CKM_ARIA_L_MAC_GENERAL',), + CKM_SHA224_RSA_X9_31: ('CKM_SHA224_RSA_X9_31',), + CKM_SHA256_RSA_X9_31: ('CKM_SHA256_RSA_X9_31',), + CKM_SHA384_RSA_X9_31: ('CKM_SHA384_RSA_X9_31',), + CKM_SHA512_RSA_X9_31: ('CKM_SHA512_RSA_X9_31',), + CKM_SHA1_RSA_X9_31_NON_FIPS: ('CKM_SHA1_RSA_X9_31_NON_FIPS',), + CKM_SHA224_RSA_X9_31_NON_FIPS: ('CKM_SHA224_RSA_X9_31_NON_FIPS',), + CKM_SHA256_RSA_X9_31_NON_FIPS: ('CKM_SHA256_RSA_X9_31_NON_FIPS',), + CKM_SHA384_RSA_X9_31_NON_FIPS: ('CKM_SHA384_RSA_X9_31_NON_FIPS',), + CKM_SHA512_RSA_X9_31_NON_FIPS: ('CKM_SHA512_RSA_X9_31_NON_FIPS',), + CKM_RSA_X9_31_NON_FIPS: ('CKM_RSA_X9_31_NON_FIPS',), + CKM_DSA_SHA224: ('CKM_DSA_SHA224',), + CKM_DSA_SHA256: ('CKM_DSA_SHA256',), + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: ('CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN',), + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: ('CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN',), + CKM_SEED_CTR: ('CKM_SEED_CTR',), + CKM_KCDSA_HAS160_NO_PAD: ('CKM_KCDSA_HAS160_NO_PAD',), + CKM_KCDSA_SHA1_NO_PAD: ('CKM_KCDSA_SHA1_NO_PAD',), + CKM_KCDSA_SHA224_NO_PAD: ('CKM_KCDSA_SHA224_NO_PAD',), + CKM_KCDSA_SHA256_NO_PAD: ('CKM_KCDSA_SHA256_NO_PAD',), + CKM_KCDSA_SHA384_NO_PAD: ('CKM_KCDSA_SHA384_NO_PAD',), + CKM_KCDSA_SHA512_NO_PAD: ('CKM_KCDSA_SHA512_NO_PAD',), + CKM_DES3_X919_MAC: ('CKM_DES3_X919_MAC',), + CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS: ('CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS',), + CKM_ECDSA_GBCS_SHA256: ('CKM_ECDSA_GBCS_SHA256',), + CKM_AES_KW: ('CKM_AES_KW',), + CKM_AES_KWP: ('CKM_AES_KWP',), + CKM_TDEA_KW: ('CKM_TDEA_KW',), + CKM_TDEA_KWP: ('CKM_TDEA_KWP',), + CKM_AES_CBC_PAD_EXTRACT: ('CKM_AES_CBC_PAD_EXTRACT',), + CKM_AES_CBC_PAD_INSERT: ('CKM_AES_CBC_PAD_INSERT',), + CKM_AES_CBC_PAD_EXTRACT_FLATTENED: ('CKM_AES_CBC_PAD_EXTRACT_FLATTENED',), + CKM_AES_CBC_PAD_INSERT_FLATTENED: ('CKM_AES_CBC_PAD_INSERT_FLATTENED',), + CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL: ('CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL',), + CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL: ('CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL',), + CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM: ('CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM',), + CKM_DES2_DUKPT_PIN: ('CKM_DES2_DUKPT_PIN',), + CKM_DES2_DUKPT_MAC: ('CKM_DES2_DUKPT_MAC',), + CKM_DES2_DUKPT_MAC_RESP: ('CKM_DES2_DUKPT_MAC_RESP',), + CKM_DES2_DUKPT_DATA: ('CKM_DES2_DUKPT_DATA',), + CKM_DES2_DUKPT_DATA_RESP: ('CKM_DES2_DUKPT_DATA_RESP',), + CKM_ECIES: ('CKM_ECIES',), + CKM_XOR_BASE_AND_DATA_W_KDF: ('CKM_XOR_BASE_AND_DATA_W_KDF',), + CKM_NIST_PRF_KDF: ('CKM_NIST_PRF_KDF',), + CKM_PRF_KDF: ('CKM_PRF_KDF',) +} + def get_default_key_template(mechanism): """Gets a default template for the given key gen mechanism, returns a deep copy From af2211487aff8638e61fc7f9857debf2b920d119 Mon Sep 17 00:00:00 2001 From: Ian Bent Date: Tue, 8 Mar 2016 15:08:16 -0500 Subject: [PATCH 030/109] LA-1663: Added fix for multipart wrong data size. Change-Id: I707b6e05d710c3e1cae3a2e12d66e3efdc81df66 --- pycryptoki/encryption.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 8cc1232..67b5a2a 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -178,7 +178,7 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e if ret != CKR_OK: return ret, None if is_multi_part_operation: - encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, C_EncryptFinal, data_to_encrypt) + ret, encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, C_EncryptFinal, data_to_encrypt) else: plain_data_length = len(data_to_encrypt) plain_data = get_c_data_to_sign_or_encrypt(data_to_encrypt) @@ -263,7 +263,7 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, ex is_multi_part_operation = isinstance(encrypted_data, list) or isinstance(encrypted_data, tuple) if is_multi_part_operation: - python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, encrypted_data) + ret, python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, encrypted_data) else: # Get the length of the final data @@ -345,13 +345,13 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in out_data_len = CK_ULONG(max_data_chunk_size) output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) ret = c_finalize_function(h_session, output, byref(out_data_len)) - + if ret != CKR_OK: return ret, None # Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] - return python_string + return ret, python_string def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, external_iv=None): From 4301a766f02e8e87d4268399059fb66a63a83a90 Mon Sep 17 00:00:00 2001 From: ksafford Date: Fri, 11 Mar 2016 13:39:59 -0500 Subject: [PATCH 031/109] LA-1675 Fix broken exception string Fix concatenation of strings in Exception string. Change-Id: Ied10ff16d401d025dd3d15f58ba41bce77375c48 --- pycryptoki/encryption.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 67b5a2a..c3083b0 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -430,6 +430,7 @@ def get_c_data_to_sign_or_encrypt(python_data): c_data_to_sign = create_string_buffer(python_data) c_data_to_sign = cast(c_data_to_sign, CK_BYTE_PTR) else: - raise Exception("Please extend this function to support the type of data " + type(python_data)) + raise Exception("Please extend this function to support the type of data " + + str(type(python_data))) return c_data_to_sign From aa7aa0bc23bc448208bc68d81ac83b81d02cee8d Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 9 Mar 2016 14:33:01 -0500 Subject: [PATCH 032/109] LA-1667 Subprocess the RPYC Daemon This will allow us to restart the daemon automatically if it dies from a segfault or something similar. Change-Id: I485e7e990ca650a6e09fa27d4a30413a99af1653 --- pycryptoki/daemon/rpyc_pycryptoki.py | 211 ++++++++++++++++++--------- pycryptoki/pycryptoki_client.py | 113 ++++++++++++-- 2 files changed, 246 insertions(+), 78 deletions(-) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 4a35169..35f88b9 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -17,66 +17,34 @@ c_open_session_ex() # Returns: session_handle, raises exception if ret_code != CKR_OK """ -from optparse import OptionParser -from _ctypes import pointer -from ctypes import cast +import os +import signal import ctypes import logging +import multiprocessing +from _ctypes import pointer +from ctypes import cast +from optparse import OptionParser import rpyc +import time + +import sys import pycryptoki +from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, + ca_init_audit, ca_init_audit_ex, + ca_time_sync, ca_time_sync_ex) from pycryptoki.backup import (ca_open_secure_token, ca_open_secure_token_ex, ca_close_secure_token, ca_close_secure_token_ex, ca_extract, ca_extract_ex, ca_insert, ca_insert_ex) +from pycryptoki.cryptoki import CK_ULONG +from pycryptoki.cryptoki import CK_VOID_PTR from pycryptoki.encryption import (c_encrypt, c_encrypt_ex, c_decrypt, c_decrypt_ex, c_wrap_key, c_wrap_key_ex, c_unwrap_key, c_unwrap_key_ex) -from pycryptoki.key_generator import (c_destroy_object, c_destroy_object_ex, - c_generate_key_pair, c_generate_key_pair_ex, - c_generate_key, c_generate_key_ex, - c_derive_key, c_derive_key_ex, - c_copy_object_ex, c_copy_object) -from pycryptoki.misc import (c_generate_random, c_generate_random_ex, - c_seed_random, c_seed_random_ex, - c_digest, c_digest_ex, - c_set_ped_id, c_set_ped_id_ex, - c_get_ped_id, c_get_ped_id_ex, - c_create_object, c_create_object_ex, - c_digestkey, c_digestkey_ex) -from pycryptoki.object_attr_lookup import (c_find_objects, c_find_objects_ex, - c_get_attribute_value, c_get_attribute_value_ex, - c_set_attribute_value, c_set_attribute_value_ex) -from pycryptoki.session_management import (c_initialize, c_initialize_ex, - c_finalize, c_finalize_ex, - c_open_session, c_open_session_ex, - c_get_session_info, c_get_session_info_ex, - c_get_token_info, c_get_token_info_ex, - c_close_session, c_close_session_ex, - c_logout, c_logout_ex, - c_init_pin, c_init_pin_ex, - ca_factory_reset, ca_factory_reset_ex, - c_set_pin, c_set_pin_ex, - c_close_all_sessions, c_close_all_sessions_ex, - login, login_ex, - ca_openapplicationID_ex, ca_openapplicationID, - ca_closeapplicationID, ca_closeapplicationID_ex, - ca_restart, ca_restart_ex, - ca_setapplicationID, ca_setapplicationID_ex) -from pycryptoki.sign_verify import (c_sign, c_sign_ex, - c_verify, c_verify_ex) -from pycryptoki.token_management import (c_init_token, c_init_token_ex, - c_get_mechanism_list, c_get_mechanism_list_ex, - c_get_mechanism_info, c_get_mechanism_info_ex, - get_token_by_label, get_token_by_label_ex, - ca_get_token_policies_ex, ca_get_token_policies) -from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, - ca_init_audit, ca_init_audit_ex, - ca_time_sync, ca_time_sync_ex) -from pycryptoki.cryptoki import CK_VOID_PTR -from pycryptoki.key_generator import _get_mechanism from pycryptoki.hsm_management import (c_performselftest, c_performselftest_ex, ca_settokencertificatesignature, ca_settokencertificatesignature_ex, @@ -96,6 +64,26 @@ ca_get_hsm_capability_setting_ex, ca_set_hsm_policies, ca_set_hsm_policies_ex, ca_set_destructive_hsm_policies, ca_set_destructive_hsm_policies_ex) +from pycryptoki.key_generator import _get_mechanism +from pycryptoki.key_generator import (c_destroy_object, c_destroy_object_ex, + c_generate_key_pair, c_generate_key_pair_ex, + c_generate_key, c_generate_key_ex, + c_derive_key, c_derive_key_ex, + c_copy_object_ex, c_copy_object) +from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, + ca_modifyusagecount, ca_modifyusagecount_ex) +from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, + ca_duplicatemofn, ca_duplicatemofn_ex) +from pycryptoki.misc import (c_generate_random, c_generate_random_ex, + c_seed_random, c_seed_random_ex, + c_digest, c_digest_ex, + c_set_ped_id, c_set_ped_id_ex, + c_get_ped_id, c_get_ped_id_ex, + c_create_object, c_create_object_ex, + c_digestkey, c_digestkey_ex) +from pycryptoki.object_attr_lookup import (c_find_objects, c_find_objects_ex, + c_get_attribute_value, c_get_attribute_value_ex, + c_set_attribute_value, c_set_attribute_value_ex) from pycryptoki.partition_management import (ca_create_container, ca_create_container_ex, ca_delete_container_with_handle_ex, @@ -122,11 +110,29 @@ ca_set_container_policies_ex, ca_set_container_size, ca_set_container_size_ex) -from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, - ca_modifyusagecount, ca_modifyusagecount_ex) -from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, - ca_duplicatemofn, ca_duplicatemofn_ex) -from pycryptoki.cryptoki import CK_ULONG +from pycryptoki.session_management import (c_initialize, c_initialize_ex, + c_finalize, c_finalize_ex, + c_open_session, c_open_session_ex, + c_get_session_info, c_get_session_info_ex, + c_get_token_info, c_get_token_info_ex, + c_close_session, c_close_session_ex, + c_logout, c_logout_ex, + c_init_pin, c_init_pin_ex, + ca_factory_reset, ca_factory_reset_ex, + c_set_pin, c_set_pin_ex, + c_close_all_sessions, c_close_all_sessions_ex, + login, login_ex, + ca_openapplicationID_ex, ca_openapplicationID, + ca_closeapplicationID, ca_closeapplicationID_ex, + ca_restart, ca_restart_ex, + ca_setapplicationID, ca_setapplicationID_ex) +from pycryptoki.sign_verify import (c_sign, c_sign_ex, + c_verify, c_verify_ex) +from pycryptoki.token_management import (c_init_token, c_init_token_ex, + c_get_mechanism_list, c_get_mechanism_list_ex, + c_get_mechanism_info, c_get_mechanism_info_ex, + get_token_by_label, get_token_by_label_ex, + ca_get_token_policies_ex, ca_get_token_policies) CRYPTO_OPS = pycryptoki.cryptoki.__all__[:] @@ -319,7 +325,8 @@ def _rpyc_getattr(self, name): exposed_ca_get_container_capability_set = staticmethod(ca_get_container_capability_set) exposed_ca_get_container_capability_set_ex = staticmethod(ca_get_container_capability_set_ex) exposed_ca_get_container_capability_setting = staticmethod(ca_get_container_capability_setting) - exposed_ca_get_container_capability_setting_ex = staticmethod(ca_get_container_capability_setting_ex) + exposed_ca_get_container_capability_setting_ex = staticmethod( + ca_get_container_capability_setting_ex) exposed_ca_get_container_list = staticmethod(ca_get_container_list) exposed_ca_get_container_list_ex = staticmethod(ca_get_container_list_ex) exposed_ca_get_container_name = staticmethod(ca_get_container_name) @@ -330,8 +337,10 @@ def _rpyc_getattr(self, name): exposed_ca_get_container_policy_setting_ex = staticmethod(ca_get_container_policy_setting_ex) exposed_ca_get_container_status = staticmethod(ca_get_container_status) exposed_ca_get_container_status_ex = staticmethod(ca_get_container_status_ex) - exposed_ca_get_container_storage_information = staticmethod(ca_get_container_storage_information) - exposed_ca_get_container_storage_information_ex = staticmethod(ca_get_container_storage_information_ex) + exposed_ca_get_container_storage_information = staticmethod( + ca_get_container_storage_information) + exposed_ca_get_container_storage_information_ex = staticmethod( + ca_get_container_storage_information_ex) exposed_ca_set_container_policies = staticmethod(ca_set_container_policies) exposed_ca_set_container_policies_ex = staticmethod(ca_set_container_policies_ex) exposed_ca_set_container_size = staticmethod(ca_set_container_size) @@ -399,28 +408,98 @@ def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_fla return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) +def server_launch(service, ip, port, config): + """ + Target for the multiprocessing Pycryptoki service. + + :param service: + :param ip: + :param port: + :param config: + :return: + """ + t = ThreadedServer(service, + hostname=ip, + port=port, + protocol_config=config) + t.start() + + +def create_server_subprocess(target, args): + """ + Create the subprocess, set it as a daemon, setup a signal handler + in case the parent process is killed, the child process should also be killed, then return + the subprocess. + + :param target: Target function to run in a subprocess + :param args: Args to pass to the function + :return: `multiprocessing.Process` + """ + server = multiprocessing.Process(target=target, + args=args) + server.daemon = True + server.start() + + logger.info("Created subprocess w/ PID %s", server.pid) + + def sighandler(): + print "Caught SIGTERM, closing subprocess" + server.terminate() + signal.signal(signal.SIGTERM, sighandler) + return server + + if __name__ == '__main__': from rpyc.utils.server import ThreadedServer + logging.basicConfig(stream=sys.stdout, + level=logging.DEBUG, + format='%(asctime)s:%(name)s:%(levelname)s: %(message)s') + logger = logging.getLogger(__name__) + parser = OptionParser() parser.add_option("-i", "--ip_address", dest="i", help="pycryptoki daemon IP address", metavar="") parser.add_option("-p", "--port", dest="p", help="pycryptoki daemon IP port", metavar="") + parser.add_option("-f", "--forked", dest="forked", + help="Fork the daemon from the parent process so we can recover from " + "segfaults", default=False, action="store_true") (options, args) = parser.parse_args() # Default arguments ip = options.i if options.i is not None else 'localhost' port = int(options.p if options.p is not None else '8001') - print "Pycryptoki Daemon ip=" + str(ip) + ", port=" + str(port) - - t = ThreadedServer(PycryptokiService, - hostname=ip, - port=port, - protocol_config={'allow_public_attrs': True, - 'allow_all_attrs': True, - 'allow_getattr': True, - 'allow_setattr': True, - 'allow_delattr': True}) - print "Starting Server" - t.start() + logger.info("Pycryptoki Daemon ip=" + str(ip) + ", port=" + + str(port) + ", PID=" + str(os.getpid())) + + server_config = {'allow_public_attrs': True, + 'allow_all_attrs': True, + 'allow_getattr': True, + 'allow_setattr': True, + 'allow_delattr': True} + + server_kwargs = dict(target=server_launch, + args=(PycryptokiService, + ip, port, + server_config)) + + if options.forked: + logger.info("Starting PycryptokiServer in a separate process...") + server = create_server_subprocess(**server_kwargs) + if server.exitcode is not None and not server.is_alive(): + logger.error("Failed to start PycryptokiServer!") + exit(-1) + + while True: + if server.exitcode not in (1, None) and not server.is_alive(): + logger.error("PycryptokiServer died w/ exit code %s! Possible segfault", + server.exitcode) + logger.info("Restarting Pycryptoki server") + server.terminate() + server = create_server_subprocess(**server_kwargs) + + time.sleep(0.5) + + else: + server_launch(PycryptokiService, ip, port, server_config) diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index 0b2f7d2..c2e39b6 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -2,15 +2,85 @@ Contains both a local and remote pycryptoki client """ import logging +import socket +from functools import wraps import rpyc +import time + +from rpyc.core.protocol import PingError from pycryptoki.daemon import rpyc_pycryptoki -from pycryptoki.session_management import c_finalize, c_initialize_ex, c_initialize log = logging.getLogger(__name__) +# from https://github.com/saltycrane/retry-decorator/blob/master/decorators.py +def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None): + """Retry calling the decorated function using an exponential backoff. + + http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ + original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry + + :param ExceptionToCheck: the exception to check. may be a tuple of + exceptions to check + :type ExceptionToCheck: Exception or tuple + :param tries: number of times to try (not retry) before giving up + :type tries: int + :param delay: initial delay between retries in seconds + :type delay: int + :param backoff: backoff multiplier e.g. value of 2 will double the delay + each retry + :type backoff: int + :param logger: logger to use. If None, print + :type logger: logging.Logger instance + """ + + def deco_retry(f): + + @wraps(f) + def f_retry(*args, **kwargs): + mtries, mdelay = tries, delay + while mtries > 1: + try: + return f(*args, **kwargs) + except ExceptionToCheck, e: + msg = "%s, Retrying in %d seconds..." % (str(e), mdelay) + if logger: + logger.warning(msg) + else: + print msg + time.sleep(mdelay) + mtries -= 1 + mdelay *= backoff + return f(*args, **kwargs) + + return f_retry # true decorator + + return deco_retry + + +def connection_test(func): + """ + Decorator to check that the underlying rpyc connection is alive before + sending commands across it. + + :param func: + :return: + """ + @wraps(func) + def wrapper(self, *args, **kwargs): + """ + Inner closure. + """ + if not self.started: + self.start() + + return func(self, *args, **kwargs) + + return wrapper + + class RemotePycryptokiClient: """Class to handle connecting to a remote Pycryptoki RPYC daemon. @@ -25,8 +95,8 @@ class RemotePycryptokiClient: def __init__(self, ip=None, port=None): self.ip = ip self.port = port - self.started = False - self.start() + self.connection = None + self.server = None def kill(self): """ @@ -36,8 +106,8 @@ def kill(self): if self.started and not self.connection.closed: log.info("Stopping remote pycryptoki connection.") self.connection.close() - self.started = False + @retry((socket.error, EOFError, PingError), logger=log) def start(self): """ Start the connection to the remote RPYC daemon. @@ -45,31 +115,50 @@ def start(self): if not self.started: log.info("Starting remote pycryptoki connection") self.connection = rpyc.classic.connect(self.ip, port=self.port) + self.connection.ping() self.server = self.connection.root - self.started = True def cleanup(self): """ """ pass + @property + def started(self): + """ + Check if the RPYC connection is alive. + + :return: boolean + """ + try: + return (self.connection is not None and + self.server is not None and + self.connection.ping() is None) + except (PingError, EOFError): + self.connection = None + self.server = None + return False + + @connection_test def __getattr__(self, name): """ This is the python default attribute handler, if an attribute is not found it's probably a pycryptoki call that we forward automagically to the server """ - if not self.started: - self.start() if hasattr(self.server, name): def wrapper(*args, **kwargs): """ - - :param *args: - :param **kwargs: - + Closer to allow us to log the full args & keyword argument list + of all calls. """ + masked_args = args + masked_kwargs = kwargs + if any(x in name for x in ("login", "create_container")): + masked_args = tuple("*" for _ in args) + masked_kwargs = {key: "*" for key, _ in kwargs.items()} + log.info("Running remote pycryptoki command: " - "{0}(args={1}, kwargs={2})".format(name, args, kwargs)) + "{0}(args={1}, kwargs={2})".format(name, masked_args, masked_kwargs)) return getattr(self.server, name)(*args, **kwargs) return wrapper From 6ae1c524d58cffacd9629a619fb991ba6fb39f08 Mon Sep 17 00:00:00 2001 From: ksafford Date: Tue, 15 Mar 2016 11:34:57 -0400 Subject: [PATCH 033/109] LA-1680 Make c_set_attribute_value match PKCS #11 Change c_set_attribute_value to return only the return code. PKCS #11 does not modify the template passed in, and returns only the return code. Change-Id: I22bcdac898a9644581072999a4116a455e94dd7a --- pycryptoki/object_attr_lookup.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 2c49097..7cac41d 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -70,10 +70,7 @@ def c_set_attribute_value(h_session, h_object, template): """ c_struct = Attributes(template).get_c_struct() ret = C_SetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) - if ret != CKR_OK: - return ret, None - - return ret, c_struct_to_python(c_struct) + return ret c_set_attribute_value_ex = make_error_handle_function(c_set_attribute_value) From d265ab769aba5e2a09b7e1c518a256737f969c9b Mon Sep 17 00:00:00 2001 From: ksafford Date: Wed, 16 Mar 2016 14:25:58 -0400 Subject: [PATCH 034/109] LA-1682 Fix CKA_OUID Change the "attribute type" of CKA_OUID to int so that CKA_OUID can be used in templates. Especially useful for use in c_find_objects. Change-Id: I5153b9e9a8a5d3f1ec402f99e64a740d0f253495 --- pycryptoki/attributes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 1ec5972..81bd098 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -124,7 +124,7 @@ def get_byte_list_from_python_list(python_byte_list): CKA_FINGERPRINT_SHA256: NonAsciiString, CKA_PKC_TCTRUST: None, CKA_PKC_CITS: None, - CKA_OUID: NonAsciiString, + CKA_OUID: int, CKA_X9_31_GENERATED: None, CKA_PKC_ECC: None, CKA_EKM_UID: None, From e4ed2939baba1eae072acdfd8452fea3a471501a Mon Sep 17 00:00:00 2001 From: "Straw, Ashley" Date: Thu, 17 Mar 2016 07:08:39 -0500 Subject: [PATCH 035/109] LA-1682 Revert "LA-1682 Fix CKA_OUID" Needs more testing (specifically with templates that expected a nonascii string conversion). This reverts commit d265ab769aba5e2a09b7e1c518a256737f969c9b. Change-Id: Id6d8fac52c9ef95e23621f158d0be0712ef1a757 --- pycryptoki/attributes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 81bd098..1ec5972 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -124,7 +124,7 @@ def get_byte_list_from_python_list(python_byte_list): CKA_FINGERPRINT_SHA256: NonAsciiString, CKA_PKC_TCTRUST: None, CKA_PKC_CITS: None, - CKA_OUID: int, + CKA_OUID: NonAsciiString, CKA_X9_31_GENERATED: None, CKA_PKC_ECC: None, CKA_EKM_UID: None, From 2a406935c2ee8dd6e83b41735512fc32ed3eb8f4 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 17 Mar 2016 10:31:42 -0400 Subject: [PATCH 036/109] LA-1682 Attributes class rework Changed to use transforms Removed a lot of unneeded code (todo) Change-Id: I7858e202416e798e534b2ec83531af1823532dda --- pycryptoki/attributes.py | 786 +++++++++++---------------- pycryptoki/cryptoki.py | 5 - pycryptoki/daemon/rpyc_pycryptoki.py | 17 +- pycryptoki/encryption.py | 13 +- pycryptoki/misc.py | 11 +- pycryptoki/object_attr_lookup.py | 27 +- pycryptoki/sign_verify.py | 7 +- setup.py | 2 +- 8 files changed, 377 insertions(+), 491 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 1ec5972..8a1fdc3 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -3,48 +3,32 @@ generation to make it possible to create templates in python and easily convert them into templates in C. """ +import datetime +import logging +from collections import defaultdict from ctypes import cast, c_void_p, create_string_buffer, c_bool, c_char_p, \ - c_ulong, pointer, POINTER, byref, sizeof, c_int, c_ubyte + c_ulong, pointer, POINTER, sizeof, c_char +from functools import wraps from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ - CK_BYTE, C_GetAttributeValue, CK_OBJECT_HANDLE, CK_DATE, CK_CHAR, CK_CHAR_PTR + CK_BYTE from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ - CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_VALUE, CKA_CERTIFICATE_TYPE, \ + CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_CERTIFICATE_TYPE, \ CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER, \ CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE, \ CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, \ CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT, \ CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, CKA_SUBPRIME_BITS, \ - CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_ECDSA_PARAMS, CKA_EC_POINT, CKA_LOCAL, \ + CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_LOCAL, \ CKA_MODIFIABLE, CKA_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_NEVER_EXTRACTABLE, \ - CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_PKC_TCTRUST, CKA_PKC_CITS, \ - CKA_OUID, CKA_UNWRAP_TEMPLATE, CKA_DERIVE_TEMPLATE, \ - CKA_X9_31_GENERATED, CKA_PKC_ECC, CKR_OK -from pycryptoki.cryptoki import CK_ULONG_PTR + CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_OUID, CKA_UNWRAP_TEMPLATE, \ + CKA_DERIVE_TEMPLATE, \ + CKA_X9_31_GENERATED, CKA_VALUE from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ CKA_GENERIC_3 -from pycryptoki.dictionary_handling import CDict -''' -List class for handling attributes with lists of a certain type -''' - - -class CList: - """ """ - list_type = None - - def __init__(self, list_type): - self.list_type = list_type - - -class NonAsciiString: - """ """ - data = None - - def __init__(self, data): - self.data = data +LOG = logging.getLogger(__name__) def get_byte_list_from_python_list(python_byte_list): @@ -62,490 +46,376 @@ def get_byte_list_from_python_list(python_byte_list): return ptr -date_attrb = {'year': str, - 'month': str, - 'day': str} - -''' -A mapping of attributes to what type they have. This is used when converting -a python dictionary to a C struct or vice versa -''' -key_attributes = {CKA_USAGE_LIMIT: long, - CKA_USAGE_COUNT: long, - CKA_CLASS: long, - CKA_TOKEN: bool, - CKA_PRIVATE: bool, - CKA_LABEL: str, - CKA_APPLICATION: None, - CKA_VALUE: CList(str), - CKA_CERTIFICATE_TYPE: long, # TODO guessing - CKA_ISSUER: None, - CKA_SERIAL_NUMBER: None, - CKA_KEY_TYPE: long, - CKA_SUBJECT: str, - CKA_ID: str, - CKA_SENSITIVE: bool, - CKA_ENCRYPT: bool, - CKA_DECRYPT: bool, - CKA_WRAP: bool, - CKA_UNWRAP: bool, - CKA_SIGN: bool, - CKA_SIGN_RECOVER: None, - CKA_VERIFY: bool, - CKA_VERIFY_RECOVER: None, - CKA_DERIVE: bool, - CKA_START_DATE: CDict(date_attrb), - CKA_END_DATE: CDict(date_attrb), - CKA_MODULUS: None, - CKA_MODULUS_BITS: long, - CKA_PUBLIC_EXPONENT: int, # Python has no concept of byte - CKA_PRIVATE_EXPONENT: None, - CKA_PRIME_1: None, - CKA_PRIME_2: None, - CKA_EXPONENT_1: None, - CKA_EXPONENT_2: None, - CKA_COEFFICIENT: None, - CKA_PRIME: CList(str), - CKA_SUBPRIME: CList(str), - CKA_BASE: CList(str), - CKA_PRIME_BITS: long, - CKA_SUBPRIME_BITS: long, - CKA_VALUE_BITS: long, - CKA_VALUE_LEN: long, - CKA_ECDSA_PARAMS: CList(str), - CKA_EC_POINT: None, - CKA_LOCAL: None, - CKA_MODIFIABLE: bool, - CKA_EXTRACTABLE: bool, - CKA_ALWAYS_SENSITIVE: bool, - CKA_NEVER_EXTRACTABLE: bool, - CKA_CCM_PRIVATE: None, - CKA_FINGERPRINT_SHA1: NonAsciiString, - CKA_FINGERPRINT_SHA256: NonAsciiString, - CKA_PKC_TCTRUST: None, - CKA_PKC_CITS: None, - CKA_OUID: NonAsciiString, - CKA_X9_31_GENERATED: None, - CKA_PKC_ECC: None, - CKA_EKM_UID: None, - CKA_GENERIC_1: None, - CKA_GENERIC_2: None, - CKA_GENERIC_3: None, - CKA_UNWRAP_TEMPLATE: {}, - CKA_DERIVE_TEMPLATE: {}} - -role_attributes = {} - - -def to_byte_array(val): - """Converts an arbitrarily sized integer into a byte array. - - It'll zero-pad the bit length so it's a multiple of 8, then convert - the int to binary, split the binary string into sections of 8, then - place each section into a slot in a c_ubyte array (converting to small - int). - - :param val: Big Integer to convert. - :return: c_ubyte array - +def ret_type(c_type): """ - # Explicitly convert to a long. Python doesn't like X.bit_length() where X is an int - # and not a variable assigned an int. - width = long(val).bit_length() - width += 8 - ((width % 8) or 8) - - fmt = "{:0%sb}" % width - str_val = fmt.format(val) - n = 8 - str_array = [str_val[i:i + n] for i in range(0, len(str_val), n)] - - return (CK_BYTE * len(str_array))(*[int(x, 2) for x in str_array]) - - -class Attributes: - """A wrapper around all of the attributes necessary to create a key. - Has a python dictionary object containing python types, the corresponding - C struct can then be generated with a simple method call. - + Decorator to set a returned C Type so we can determine what type to use + for an AutoCArray + :param c_type: Default return-type of the transform function. """ - attributes = {} - def __init__(self, attributes_list=None): + def func_wrapper(func): """ - Initializes a Attributes object, the attributes_list argument is optional - since the attributes object can be populated from the board later + Set the ctype on the function. - @param attributes_list: The list of python style attributes to create the class with. + :param func: + :return: """ + func.ctype = c_type - if attributes_list is not None: - # take either strings or ints as the key to the dictionary (used mainly to accomodate - # xmlrpc easily) - attributes_list_new = {} - for key, value in attributes_list.iteritems(): - if isinstance(key, str): - attributes_list_new[int(key)] = value - else: - break - if len(attributes_list_new) > 0: - attributes_list = attributes_list_new + @wraps(func) + def wrapped(*args, **kwargs): + """ + Run the actual function. - for key in attributes_list: - self._input_check(key, attributes_list[key]) - self.attributes = attributes_list + :param args: + :param kwargs: + :return: + """ + return func(*args, **kwargs) - def add_attribute(self, key, value): - """Add an attribute to the dictionary in place + return wrapped - :param key: The type of the attribute - :param value: The value of the attribute - - """ - if isinstance(key, str): - # take either strings or ints for the key (used mainly to accomodate xmlrpc easily) - key = int(key) + return func_wrapper - self._input_check(key, value) - self.attributes[key] = value - def _input_check(self, key, value): - """Checks to see if the type is supported (yet) +@ret_type(CK_ULONG) +def to_long(val, reverse=False): + """Convert a integer/long value to a pValue, ulValueLen tuple - :param key: They key of the attribute to check - :param value: The actual value of the input to check - :returns: Returns true if the variable is a of a type that has been accounted for in the - key_attributes dictionary + :param val: Value to convert + :param reverse: Whether to convert from C -> Python + :return: (:class:`ctypes.c_void_p` ptr to :class:`ctypes.c_ulong`, :class:`ctypes.c_ulong` + size of long value) + """ + if reverse: + return long(cast(val.pValue, POINTER(c_ulong)).contents.value) + if not isinstance(val, (int, long)): + raise TypeError("Invalid conversion {} to CK_ULONG!".format(type(val))) + long_val = CK_ULONG(val) + return cast(pointer(long_val), c_void_p), CK_ULONG(sizeof(long_val)) + + +@ret_type(CK_BBOOL) +def to_bool(val, reverse=False): + """Convert a boolean-ish value to a pValue, ulValueLen tuple. + + :param val: Value to convert + :param reverse: Whether to convert from C -> Python + :return: (:class:`ctypes.c_void_p` ptr to :class:`pycryptoki.cryptoki.CK_BBOOL`, + :class:`ctypes.c_ulong` size of bool value) + """ + if reverse: + return bool(cast(val.pValue, POINTER(c_bool)).contents.value) - """ - if isinstance(value, bool) or isinstance(value, int) or isinstance(value, - CDict) or isinstance( - value, long) or isinstance(value, str) or isinstance(value, list) or isinstance( - value, CList) or isinstance(value, NonAsciiString) or isinstance(value, dict): - return True - else: - raise Exception( - "Argument type not supported. ") + if not isinstance(val, (int, bool)): + raise TypeError("Invalid conversion {} to CK_BBOOL!".format(type(val))) + # Convert to 0 | 1 + byte_val = CK_BBOOL(int(bool(val))) + return cast(pointer(byte_val), c_void_p), CK_ULONG(sizeof(byte_val)) - def get_c_struct(self): - """Assembles and returns a proper C struct from the dictionary of python attributes +@ret_type(c_char) +def to_char_array(val, reverse=False): + """Convert the given string or list of string values into a char array. - :returns: Returns a Ctypes struct representing the python attributes stored in this class + This is slightly different than to_byte_array, which has different assumptions as + to the format of the input. - """ - c_struct = (CK_ATTRIBUTE * len(self.attributes))() - - i = 0 - for key in self.attributes: - value = self.attributes[key] - self._input_check(key, value) - - # Get the proper type for what your data is, originally I had - # this automatically detected from the python type but passing in - # int's vs longs was problematic - item_type = lookup_attributes(key) - - if item_type == bool: - byte_val = CK_BBOOL(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), - cast(pointer(byte_val), c_void_p), - CK_ULONG(sizeof(byte_val))) - elif item_type == long: - long_val = CK_ULONG(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), - cast(pointer(long_val), c_void_p), - CK_ULONG(sizeof(long_val))) - elif item_type == int: - ck_byte_array = to_byte_array(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), - cast(pointer(ck_byte_array), c_void_p), - CK_ULONG(sizeof(ck_byte_array))) - elif item_type == str: - string_val = create_string_buffer(value) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(string_val, c_void_p), - CK_ULONG(len(string_val))) - elif isinstance(item_type, CDict): - date = CK_DATE() - - date.year = convert_string_to_CK_CHAR(value.dict_val['year']) - date.month = convert_string_to_CK_CHAR(value.dict_val['month']) - date.day = convert_string_to_CK_CHAR(value.dict_val['day']) - - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), cast(pointer(date), c_void_p), - CK_ULONG(sizeof(date))) - elif isinstance(item_type, CList): - if item_type.list_type == str: - list_val = create_string_buffer("", len(value)) - - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(value)): - list_val[j] = chr(value[j]) - - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, CK_ULONG(len(value))) - elif item_type.list_type == long: - list_val = (CK_ULONG * len(value))() - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(value)): - list_val[j] = CK_ULONG(value[j]) - - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, - CK_ULONG(sizeof(CK_ULONG(0)) * len(value))) - elif item_type == NonAsciiString: - list_val = (CK_CHAR * len(value))() - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(value)): - list_val[j] = CK_CHAR(ord(value[j]) - 0x30) - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), ptr, - CK_ULONG(sizeof(CK_CHAR(0)) * len(value))) - elif isinstance(item_type, dict): - template = Attributes(attributes_list=value).get_c_struct() - c_struct[i] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), - cast(template, c_void_p), - CK_ULONG(len(template))) - else: - raise Exception("Argument type " + str(item_type) + " not supported. ") - i += 1 - - return c_struct + :param val: Value to convert + :param reverse: Whether to convert from C -> Python + :return: (:class:`ctypes.c_void_p` ptr to :class:`pycryptoki.cryptoki.CK_CHAR` array, + :class:`ctypes.c_ulong` size of array) + """ + if reverse: + return str(cast(val.pValue, c_char_p).value[0:val.usValueLen]) - def retrieve_key_attributes(self, h_session, h_object): - """Gets all of the key's attributes from the board given the key's handle, - and populates the KeyAttribute object with all of those attributes. + if not isinstance(val, (str, list)): + raise TypeError("Invalid conversion {} to CK_CHAR*!".format(type(val))) - :param h_session: Current session - :param h_object: The handle of the object to fetch the attributes for + if isinstance(val, str): + string_val = create_string_buffer(val) + else: + # TODO: Figure out what, if anything we want to do with a list. + string_val = bytearray(val) + return cast(pointer(string_val), c_void_p), CK_ULONG(sizeof(string_val)) - """ - # Clean before starting - self.attributes = {} - - for key in key_attributes: - attribute = CK_ATTRIBUTE() - attribute.type = CK_ULONG(key) - attribute.pValue = c_void_p(0) - retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), byref(attribute), - CK_ULONG(1)) - if retCode == CKR_OK: - attr_type = lookup_attributes(key) - - if isinstance(attr_type, CList): - if attr_type.list_type == str: - pb_value = (CK_BYTE * attribute.usValueLen)() - elif attr_type.list_type == long: - pb_value = (CK_ULONG * attribute.usValueLen)() - else: - pb_value = create_string_buffer(attribute.usValueLen) - - attribute.pValue = cast(pb_value, c_void_p) - retCode = C_GetAttributeValue(h_session, CK_OBJECT_HANDLE(h_object), - byref(attribute), CK_ULONG(1)) - if retCode == CKR_OK: - if attr_type == bool: - self.add_attribute(attribute.type, attr_type( - cast(attribute.pValue, POINTER(c_bool)).contents.value)) - elif attr_type == str: - string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] - self.add_attribute(attribute.type, attr_type(string)) - elif attr_type == long: - self.add_attribute(attribute.type, ( - attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value))) - elif attr_type == int: - self.add_attribute(attribute.type, attr_type( - cast(attribute.pValue, POINTER(c_int)).contents.value)) - elif isinstance(attr_type, CList): - value = [] - i = 0 - while i < attribute.usValueLen: - value.append(pb_value[i]) - i += 1 - - self.add_attribute(attribute.type, value) - elif attr_type == NonAsciiString: - value = '' - i = 0 - while i < attribute.usValueLen: - value += '%02x' % cast(pb_value, CK_CHAR_PTR)[i] - i += 1 - - self.add_attribute(attribute.type, value) - elif attr_type is None: - # raise Exception("Attribute of type " + str(attribute.type) + "'s value - # type not yet determined") # Add type to all_attributes - pass - - def get_attributes(self): - """Returns the python dictionary of attributes - - - :returns: The python dictionary of attributes - """ - return self.attributes +@ret_type(c_char) +def to_ck_date(val, reverse=False): + """Transform a date string, date dictionary, or date object into + a PKCS11 readable form (YYYYMMDD) - def __eq__(self, other): - """ - Overriding the == sign to properly compare equality in KeyAttribute objects + :param val: Value to convert + :param reverse: Whether to convert from C -> Python + :return: (:class:`ctypes.c_void_p` ptr to :class:`pycryptoki.cryptoki.CK_CHAR` array, + :class:`ctypes.c_ulong` size of array) + """ + if reverse: + return str(cast(val.pValue, c_char_p).value[0:val.usValueLen]) - :param other: Another KeyAttribute to compare against - :return: True if the attributes are equal - """ - other_attribs = other.get_attributes() - self_attribs = self.get_attributes() - for key in self.attributes: - if key in self_attribs and key in other_attribs: # TODO we are only checking if the - # key exists in both, maybe this is a bad idea - if self_attribs[key] != other_attribs[key]: - return False - return True + if isinstance(val, str): + if len(val) != 8: + raise TypeError("Invalid date string passed! Should be of type YYYYMMDD") + date_val = create_string_buffer(val) + elif isinstance(val, dict): + date_str = val['year'] + val['month'] + val['day'] + date_val = create_string_buffer(date_str) + elif isinstance(val, datetime.date): + date_val = create_string_buffer(val.strftime("%Y%m%d")) + else: + raise TypeError("Invalid conversion {} to CK_DATE!".format(type(val))) - def debug_print(self): - """Simple method to print out all the keys and values in a KeyAttribute object""" - for key in self.attributes: - print "key: " + str(key) + ", value: " + str(self.attributes[key]) + return cast(pointer(date_val), c_void_p), CK_ULONG(sizeof(date_val)) -def get_attribute_py_value(attribute): - """Gets the python version of the value of a attribute from the - C format +@ret_type(CK_BYTE) +def to_byte_array(val, reverse=False): + """Converts an arbitrarily sized integer, list, or hex string + into a byte array. - :param attribute: The ctypes style variable representing the value of an attribute - :returns: Returns the python version of the ctypes style variable + It'll zero-pad the bit length so it's a multiple of 8, then convert + the int to binary, split the binary string into sections of 8, then + place each section into a slot in a :class:`ctypes.c_ubyte` array (converting to small + int). + :param val: Value to convert + :param reverse: Whether to convert from C -> Python + :return: (:class:`ctypes.c_void_p` ptr to :class:`pycryptoki.cryptoki.CK_BYTE` array, + :class:`ctypes.c_ulong` size of array) """ - key = attribute.type - attr_type = lookup_attributes(key) - if attr_type == bool: - return attr_type(cast(attribute.pValue, POINTER(c_bool)).contents.value) - elif attr_type == str: - string = cast(attribute.pValue, c_char_p).value[0:attribute.usValueLen] - return attr_type(string) - elif attr_type == long: - return attr_type(cast(attribute.pValue, POINTER(c_ulong)).contents.value) - elif attr_type == int: - return attr_type(cast(attribute.pValue, POINTER(c_int)).contents.value) - elif isinstance(attr_type, CDict): - py_date = {} - - c_date = cast(attribute.pValue, POINTER(CK_DATE)) - - py_date['year'] = convert_CK_CHAR_to_string(cast(c_date.year, CK_CHAR_PTR)) - py_date['month'] = convert_CK_CHAR_to_string(cast(c_date.month, CK_CHAR_PTR)) - py_date['day'] = convert_CK_CHAR_to_string(cast(c_date.day, CK_CHAR_PTR)) - return py_date - - elif isinstance(attr_type, CList): - if attr_type.list_type == str: - value = [] - try: - for i in range(0, attribute.usValueLen): - value.append(attribute.pValue[i]) - return value - except OverflowError: - return value - - elif attr_type.list_type == long: - value = [] - for i in range(0, attribute.usValueLen / sizeof(CK_ULONG(0))): - value.append(cast(attribute.pValue, CK_ULONG_PTR)[i]) - return value - elif attr_type == NonAsciiString: - value = '' - for i in range(0, attribute.usValueLen / sizeof(CK_CHAR(0))): - value += '%02x' % cast(attribute.pValue, CK_CHAR_PTR)[i] - return value - elif attr_type is None: - # raise Exception("Attribute of type " + str(attribute.type) + "'s value type not yet - # determined") # Add type to all_attributes - pass - - -def c_struct_to_python(c_struct): - """Converts a struct in C to a dictionary in python. - - :param c_struct: The c struct to convert into a dictionary in python - :returns: Returns a python dictionary which represents the C struct passed in - + if reverse: + return cast(val.pValue, c_char_p).value[0:val.usValueLen] + + if isinstance(val, list): + py_bytes = bytearray(val) + byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) + elif isinstance(val, (int, long)): + # Explicitly convert to a long. Python doesn't like X.bit_length() where X is an int + # and not a variable assigned an int. + width = long(val).bit_length() + width += 8 - ((width % 8) or 8) + + fmt = "{:0%sb}" % width + str_val = fmt.format(val) + n = 8 + str_array = [str_val[i:i + n] for i in range(0, len(str_val), n)] + byte_array = (CK_BYTE * len(str_array))(*[int(x, 2) for x in str_array]) + + elif isinstance(val, str): + # Can be Hex string ('01e4') or a bytestring (ex '\x8p\xb26\x12'G\xa3T\x84\x17\x89') + try: + # Would prefer to use bytearray.fromhex(), but a few testcases use ' ' * 80 or the like, + # which is converted into a zero-length bytearray. + hex_array = [val[i:i + 2] for i in range(0, len(val), 2)] + byte_array = (CK_BYTE * len(val))(*[int(x, 16) for x in hex_array]) + except ValueError: + # Assume a byte array? + py_bytes = bytearray(val) + byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) + else: + raise TypeError("Invalid conversion {} to byte array!".format(type(val))) + + return cast(pointer(byte_array), c_void_p), CK_ULONG(sizeof(byte_array)) + + +def to_sub_attributes(val, reverse=False): """ - py_struct = {} - for i in range(0, len(c_struct)): - obj_type = c_struct[i].type - - value = get_attribute_py_value(c_struct[i]) - - py_struct[obj_type] = value - - return py_struct - - -def lookup_attributes(key): - """Utility function to look through the lists of attributes and figure out - the type of variable for a given attribute represented by a key - - :param key: The key representing the attribute - :returns: The python type that can represent the attribute + Convert to another Attributes class & return the struct. + :param val: Value to convert + :param reverse: Whether to convert from C -> Python + :return: (:class:`ctypes.c_void_p` ptr to :class:`pycryptoki.cryptoki.CK_ATTRIBUTE` array, + :class:`ctypes.c_ulong` size of array) """ + if reverse: + return c_struct_to_python(cast(val.pValue, POINTER(CK_ATTRIBUTE))) + if not isinstance(val, dict): + raise TypeError("Invalid conversion {} to Template!".format(type(val))) + + attrs = Attributes(**val).get_c_struct() + + return cast(pointer(attrs), c_void_p), CK_ULONG(len(attrs)) + + +# Default any unset transform to :func:`to_byte_array` +KEY_TRANSFORMS = defaultdict(lambda: to_byte_array) + +KEY_TRANSFORMS.update({ + # int, long + CKA_CLASS: to_long, + CKA_CERTIFICATE_TYPE: to_long, + CKA_KEY_TYPE: to_long, + CKA_VALUE_LEN: to_long, + CKA_MODULUS_BITS: to_long, + CKA_PRIME_BITS: to_long, + CKA_SUBPRIME_BITS: to_long, + CKA_VALUE_BITS: to_long, + + # int, bool + CKA_TOKEN: to_bool, + CKA_PRIVATE: to_bool, + CKA_SENSITIVE: to_bool, + CKA_ENCRYPT: to_bool, + CKA_DECRYPT: to_bool, + CKA_WRAP: to_bool, + CKA_UNWRAP: to_bool, + CKA_SIGN: to_bool, + CKA_SIGN_RECOVER: to_bool, + CKA_VERIFY: to_bool, + CKA_VERIFY_RECOVER: to_bool, + CKA_DERIVE: to_bool, + CKA_CCM_PRIVATE: to_bool, + CKA_LOCAL: to_bool, + CKA_MODIFIABLE: to_bool, + CKA_EXTRACTABLE: to_bool, + CKA_ALWAYS_SENSITIVE: to_bool, + CKA_NEVER_EXTRACTABLE: to_bool, + CKA_X9_31_GENERATED: to_bool, + + # str, list(?) + CKA_LABEL: to_char_array, + CKA_APPLICATION: to_char_array, + CKA_ISSUER: to_char_array, + CKA_SUBJECT: to_char_array, + CKA_ID: to_char_array, + CKA_EKM_UID: to_char_array, + CKA_GENERIC_1: to_char_array, + CKA_GENERIC_2: to_char_array, + CKA_GENERIC_3: to_char_array, + + # str, dict, datetime + CKA_START_DATE: to_ck_date, + CKA_END_DATE: to_ck_date, + + # Generic data. + CKA_VALUE: to_byte_array, + CKA_SERIAL_NUMBER: to_byte_array, + CKA_MODULUS: to_byte_array, + CKA_PUBLIC_EXPONENT: to_byte_array, + CKA_PRIVATE_EXPONENT: to_byte_array, + CKA_PRIME_1: to_byte_array, + CKA_PRIME_2: to_byte_array, + CKA_EXPONENT_1: to_byte_array, + CKA_EXPONENT_2: to_byte_array, + CKA_COEFFICIENT: to_byte_array, + CKA_PRIME: to_byte_array, + CKA_SUBPRIME: to_byte_array, + CKA_BASE: to_byte_array, + CKA_FINGERPRINT_SHA1: to_byte_array, + CKA_FINGERPRINT_SHA256: to_byte_array, + CKA_USAGE_COUNT: to_byte_array, + CKA_USAGE_LIMIT: to_byte_array, + CKA_OUID: to_byte_array, + + # Dict + CKA_UNWRAP_TEMPLATE: to_sub_attributes, + CKA_DERIVE_TEMPLATE: to_sub_attributes, +}) + + +class Attributes(dict): + """ + Python container for handling PKCS11 Attributes. - ret_val = None - if key in key_attributes: - ret_val = key_attributes[key] - elif key in role_attributes: - ret_val = role_attributes[key] - - return ret_val + Provides :func:`get_c_struct`, that would returns a list of C Structs, each with + the following structure:: + class CK_ATTRIBUTE(Structure): + ''' + Defines type, value and length of an attribute: -def convert_string_to_CK_CHAR(string): - """ + c_ulong type; + c_void_p pValue; + c_ulong ulValueLen; + ''' + pass - :param string: - """ - byte_array = (c_ubyte * len(string))() - i = 0 - for char in string: - byte_array[i] = ord(char) - i += 1 + This list of structs can be used with :func:`~pycryptoki.cryptoki.C_GetAttributeValue` to get + the length of the value that will be placed + in ``pValue`` (will be set to ``ulValueLen``), or if you already know the + length required you can 'blank fill' ``pValue`` for direct use. - return byte_array + You can also provide new transformations in the form of a dictionary that will be preferred + to the :const:`~pycryptoki.attributes.KEY_TRANSFORMS` dictionary. This is passed in only as a + keyword argument:: + transform = {1L: lambda x: return x**2}` + attrs = Attributes({...}, new_transforms=transform) + # attrs.get_c_struct will use the lambda expression in the transform dictionary + # for key 1L -def convert_CK_CHAR_to_string(byte_array): """ - :param byte_array: + def __init__(self, *args, **kwargs): + if 'new_transforms' in kwargs: + self.new_transforms = kwargs.pop('new_transforms') + else: + self.new_transforms = {} + super(Attributes, self).__init__(*args, **kwargs) - """ - string = "" + def get_c_struct(self): + """ + Build an array of :class:`~pycryptoki.cryptoki.CK_ATTRIBUTE` Structs & return it. - for b in byte_array: - string += chr(b) - return string + :return: :class:`~pycryptoki.cryptoki.CK_ATTRIBUTE` array + """ + ret_struct = (CK_ATTRIBUTE * len(self.keys()))() + + for index, key in enumerate(self.iterkeys()): + value = self[key] + if value is None: + # Create an empty CK_ATTRIBUTE struct so it can be overwritten with length + # data by the C_GetAttributeValue call. + blank_attr = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), None, CK_ULONG(0)) + ret_struct[index] = blank_attr + elif key in self.new_transforms: + p_value, ul_length = self.new_transforms[key](value) + ret_struct[index] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), + p_value, + ul_length) + else: + if key not in KEY_TRANSFORMS: + LOG.warning("Using default `to_byte_array` transformation for key %s " + "and data %s", key, value) + p_value, ul_length = KEY_TRANSFORMS[key](value) + ret_struct[index] = CK_ATTRIBUTE(CK_ATTRIBUTE_TYPE(key), + p_value, + ul_length) + return ret_struct + + @staticmethod + def from_c_struct(c_struct): + """ + Build out a dictionary from a c_struct. + :param c_struct: Pointer to an array of :class:`~pycryptoki.cryptoki.CK_ATTRIBUTE` structs + :return: dict + """ + return c_struct_to_python(c_struct) -def convert_ck_char_array_to_string(ck_char_array): - """ - :param ck_char_array: +def c_struct_to_python(c_struct): + """Converts a C struct to a python dictionary. + :param c_struct: The c struct to convert into a dictionary in python + :returns: Returns a python dictionary which represents the C struct passed in """ - string = "" + py_data = {} + for i in range(0, len(c_struct)): + obj_type = c_struct[i].type + if c_struct[i].pValue is None: + py_data[obj_type] = None + else: + py_data[obj_type] = KEY_TRANSFORMS[obj_type](c_struct[i], reverse=True) - for b in ck_char_array: - string = string + b - return string + return py_data -def convert_CK_BYTE_array_to_string(byte_array): - """ +def convert_c_ubyte_array_to_string(byte_array): + """Converts a ctypes unsigned byte array into a string. :param byte_array: - """ - string = "" - - for b in byte_array: - string += "%02x" % b - return string + return "".join("%02x" % b for b in byte_array) diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index 824939a..a2c7d7a 100755 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -1,9 +1,4 @@ """ -THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE -This file should NOT be checked into MKS or modified in any way, this file was -created by setup/initialize.py. Any changes to this file will be wiped out when -it is regenerated. - This file contains all of the ctypes definitions for the cryptoki library. The ctypes definitions outline the structures for the cryptoki C API. """ diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 35f88b9..316cd32 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -17,19 +17,19 @@ c_open_session_ex() # Returns: session_handle, raises exception if ret_code != CKR_OK """ -import os -import signal import ctypes import logging import multiprocessing +import os +import signal +import sys +import time from _ctypes import pointer from ctypes import cast from optparse import OptionParser import rpyc -import time - -import sys +from rpyc.utils.server import ThreadedServer import pycryptoki from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, @@ -442,15 +442,16 @@ def create_server_subprocess(target, args): logger.info("Created subprocess w/ PID %s", server.pid) - def sighandler(): + def sighandler(signum, frame): print "Caught SIGTERM, closing subprocess" server.terminate() + exit(0) + signal.signal(signal.SIGTERM, sighandler) return server if __name__ == '__main__': - from rpyc.utils.server import ThreadedServer logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, @@ -492,7 +493,7 @@ def sighandler(): exit(-1) while True: - if server.exitcode not in (1, None) and not server.is_alive(): + if server.exitcode not in (1, None, -15) and not server.is_alive(): logger.error("PycryptokiServer died w/ exit code %s! Possible segfault", server.exitcode) logger.info("Restarting Pycryptoki server") diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index c3083b0..4b0e3a6 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -1,7 +1,7 @@ """ Methods related to encrypting data/files. """ -from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer +from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer, string_at import logging from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ @@ -17,8 +17,7 @@ CKM_AES_CFB128, CKM_AES_OFB, CKM_ARIA_CFB8, CKM_ARIA_CFB128, CKM_ARIA_OFB, \ CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED, CKM_AES_KW, CKM_AES_KWP -from pycryptoki.attributes import get_byte_list_from_python_list, \ - convert_ck_char_array_to_string, Attributes +from pycryptoki.attributes import get_byte_list_from_python_list, Attributes from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ C_DecryptUpdate, C_DecryptFinal @@ -197,7 +196,7 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e # Convert encrypted data into a python string ck_char_array = encrypted_data._objects.values()[0] - encrypted_python_string = convert_ck_char_array_to_string(ck_char_array) + encrypted_python_string = string_at(ck_char_array) return ret, encrypted_python_string @@ -289,7 +288,7 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, ex # Convert the decrypted data to a python readable format ck_char_array = plain_data._objects.values()[0] - python_string = convert_ck_char_array_to_string(ck_char_array) + python_string = string_at(ck_char_array) # Adjust the string based on the updated plain_data_len python_string = python_string[:plain_data_len.value] @@ -338,7 +337,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in # Get the output ck_char_array = out_data._objects.values()[0] - python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + python_string += string_at(ck_char_array)[0:out_data_len.value] i += 1 # Finalizing multipart decrypt operation @@ -349,7 +348,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in # Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: - python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + python_string += string_at(ck_char_array)[0:out_data_len.value] return ret, python_string diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index f384edd..e053250 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -1,7 +1,6 @@ -from ctypes import create_string_buffer, cast, byref +from ctypes import create_string_buffer, cast, byref, string_at -from pycryptoki.attributes import convert_ck_char_array_to_string, \ - convert_string_to_CK_CHAR, Attributes +from pycryptoki.attributes import Attributes from pycryptoki.cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey @@ -23,7 +22,7 @@ def c_generate_random(h_session, length): random_data = cast(create_string_buffer("", length), CK_BYTE_PTR) ret = C_GenerateRandom(h_session, random_data, CK_ULONG(length)) - random_string = convert_ck_char_array_to_string(random_data._objects.values()[0]) + random_string = string_at(random_data._objects.values()[0]) return ret, random_string @@ -38,7 +37,7 @@ def c_seed_random(h_session, seed): :returns: The result code """ - seed_bytes = cast(convert_string_to_CK_CHAR(seed), CK_BYTE_PTR) + seed_bytes = cast(create_string_buffer(seed), CK_BYTE_PTR) seed_length = CK_ULONG(len(seed)) ret = C_SeedRandom(h_session, seed_bytes, seed_length) return ret @@ -93,7 +92,7 @@ def c_digest(h_session, data_to_digest, digest_flavor, mech=None): # Convert Digested data into a python string ck_char_array = digested_data._objects.values()[0] - digested_python_string = convert_ck_char_array_to_string(ck_char_array) + digested_python_string = string_at(ck_char_array) return ret, digested_python_string diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 7cac41d..342a88f 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -1,14 +1,17 @@ """ Functions for dealing with object attributes """ -from ctypes import byref +import logging +from ctypes import byref, cast, c_void_p -from pycryptoki.attributes import Attributes, c_struct_to_python +from pycryptoki.attributes import Attributes, c_struct_to_python, KEY_TRANSFORMS from pycryptoki.cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ C_FindObjects, C_FindObjectsFinal, C_GetAttributeValue, C_SetAttributeValue from pycryptoki.defines import CKR_OK from pycryptoki.test_functions import make_error_handle_function +LOG = logging.getLogger(__name__) + def c_find_objects(h_session, template, num_entries): """Calls c_find_objects and c_find_objects_init to get a python dictionary @@ -49,6 +52,26 @@ def c_get_attribute_value(h_session, h_object, template): """ c_struct = Attributes(template).get_c_struct() + unknown_key_vals = [key for key, value in template.iteritems() if value is None] + if unknown_key_vals: + LOG.debug("Retrieving Attribute Length for keys %s", unknown_key_vals) + # We need to get the size of the target memory area first, then + # we can allocate the mem size. + ret = C_GetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) + if ret != CKR_OK: + return ret, None + + for index in range(0, len(c_struct)): + key_type = c_struct[index].type + if any(key_type == unknown_key_type for unknown_key_type in unknown_key_vals): + LOG.debug("Allocating memory len(%s) for key %s", + c_struct[index].usValueLen, + key_type) + # Allocate memory for the type. + c_obj_type = KEY_TRANSFORMS[key_type].ctype + mem = (c_obj_type * c_struct[index].usValueLen)() + c_struct[index].pValue = cast(mem, c_void_p) + ret = C_GetAttributeValue(h_session, h_object, c_struct, CK_ULONG(len(template))) if ret != CKR_OK: return ret, None diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 6446a56..9457807 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -1,12 +1,11 @@ from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign -from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p +from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p, string_at from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ CKM_SHA512, CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, \ CKG_MGF1_SHA512 -from pycryptoki.attributes import convert_ck_char_array_to_string from pycryptoki.cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ C_SignFinal, C_VerifyUpdate, C_VerifyFinal, CK_RSA_PKCS_PSS_PARAMS from pycryptoki.encryption import _get_string_from_list, \ @@ -179,7 +178,7 @@ def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=Non ck_char_array = signature._objects.values()[0] signature_string = '' if sign_len.value > 0: - signature_string = convert_ck_char_array_to_string(ck_char_array)[0:sign_len.value] + signature_string = string_at(ck_char_array)[0:sign_len.value] return ret, signature_string c_sign_ex = make_error_handle_function(c_sign) @@ -227,7 +226,7 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, #Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: - python_string += convert_ck_char_array_to_string(ck_char_array)[0:out_data_len.value] + python_string += string_at(ck_char_array)[0:out_data_len.value] return ret, python_string diff --git a/setup.py b/setup.py index 36fd07b..02ae9b3 100755 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ author='Michael Hughes', author_email='michael.hughes@safenet-inc.com', url='http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Pages/pycryptoki.aspx', - version='1.1', + version='1.2', packages=['pycryptoki', 'pycryptoki.setup', 'pycryptoki.tests', From 38df1f30e12280e8caec1200c4617e35ab893e98 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 30 Mar 2016 15:04:02 -0400 Subject: [PATCH 037/109] LA-1682 Fix for non-null terminated strings Also allow for initializing Attributes with None. Change-Id: Ia45754c49fe91ecaf88cf4e2b10cc47df694bbf2 --- pycryptoki/attributes.py | 4 ++++ pycryptoki/encryption.py | 8 ++++---- pycryptoki/key_generator.py | 7 +++---- pycryptoki/misc.py | 5 +++-- pycryptoki/sign_verify.py | 4 ++-- 5 files changed, 16 insertions(+), 12 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 8a1fdc3..80af054 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -349,6 +349,10 @@ class CK_ATTRIBUTE(Structure): """ def __init__(self, *args, **kwargs): + if args is None: + args = [] + if kwargs is None: + kwargs = {} if 'new_transforms' in kwargs: self.new_transforms = kwargs.pop('new_transforms') else: diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 4b0e3a6..e4e5ae7 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -196,7 +196,7 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e # Convert encrypted data into a python string ck_char_array = encrypted_data._objects.values()[0] - encrypted_python_string = string_at(ck_char_array) + encrypted_python_string = string_at(ck_char_array, len(ck_char_array)) return ret, encrypted_python_string @@ -288,7 +288,7 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, ex # Convert the decrypted data to a python readable format ck_char_array = plain_data._objects.values()[0] - python_string = string_at(ck_char_array) + python_string = string_at(ck_char_array, len(ck_char_array)) # Adjust the string based on the updated plain_data_len python_string = python_string[:plain_data_len.value] @@ -337,7 +337,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in # Get the output ck_char_array = out_data._objects.values()[0] - python_string += string_at(ck_char_array)[0:out_data_len.value] + python_string += string_at(ck_char_array, len(ck_char_array))[0:out_data_len.value] i += 1 # Finalizing multipart decrypt operation @@ -348,7 +348,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in # Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: - python_string += string_at(ck_char_array)[0:out_data_len.value] + python_string += string_at(ck_char_array, len(ck_char_array))[0:out_data_len.value] return ret, python_string diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 32746ad..480efea 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -38,11 +38,10 @@ def c_copy_object(h_session, h_object, template=None): :return: Handle to the new cloned object. """ - attributes = Attributes(template) if template is None: - template_size = CK_ULONG(0) - else: - template_size = CK_ULONG(len(template)) + template = {} + attributes = Attributes(template) + template_size = CK_ULONG(len(template)) h_new_object = CK_OBJECT_HANDLE() diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index e053250..4c04c9c 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -22,7 +22,8 @@ def c_generate_random(h_session, length): random_data = cast(create_string_buffer("", length), CK_BYTE_PTR) ret = C_GenerateRandom(h_session, random_data, CK_ULONG(length)) - random_string = string_at(random_data._objects.values()[0]) + char_array = random_data._objects.values()[0] + random_string = string_at(char_array, len(char_array)) return ret, random_string @@ -92,7 +93,7 @@ def c_digest(h_session, data_to_digest, digest_flavor, mech=None): # Convert Digested data into a python string ck_char_array = digested_data._objects.values()[0] - digested_python_string = string_at(ck_char_array) + digested_python_string = string_at(ck_char_array, len(ck_char_array)) return ret, digested_python_string diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 9457807..d693dac 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -178,7 +178,7 @@ def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=Non ck_char_array = signature._objects.values()[0] signature_string = '' if sign_len.value > 0: - signature_string = string_at(ck_char_array)[0:sign_len.value] + signature_string = string_at(ck_char_array, len(ck_char_array))[0:sign_len.value] return ret, signature_string c_sign_ex = make_error_handle_function(c_sign) @@ -226,7 +226,7 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, #Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: - python_string += string_at(ck_char_array)[0:out_data_len.value] + python_string += string_at(ck_char_array, len(ck_char_array))[0:out_data_len.value] return ret, python_string From c7dd9e74136e2f34b3d02531117669199bdd1d68 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 31 Mar 2016 12:09:16 -0400 Subject: [PATCH 038/109] LA-1682 Change c_char_p to LP_c_ubyte c_char_p will terminate on first null, which will lead to errors when converting a byte array back to hex. Needed to change it to an explicit POINTER. Change-Id: If288e83f50ccf24adea25bd5ddd9fc8d6701ffc9 --- pycryptoki/attributes.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 80af054..557e79a 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -7,11 +7,13 @@ import logging from collections import defaultdict from ctypes import cast, c_void_p, create_string_buffer, c_bool, c_char_p, \ - c_ulong, pointer, POINTER, sizeof, c_char + c_ulong, pointer, POINTER, sizeof, c_char, string_at, c_ubyte from functools import wraps +import binascii + from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ - CK_BYTE + CK_BYTE, CK_CHAR_PTR, CK_CHAR from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_CERTIFICATE_TYPE, \ CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ @@ -128,7 +130,14 @@ def to_char_array(val, reverse=False): :class:`ctypes.c_ulong` size of array) """ if reverse: - return str(cast(val.pValue, c_char_p).value[0:val.usValueLen]) + LOG.debug("Attempting to convert CK_ATTRIBUTE(len:%s, data:%s, type:%s) " + "back to ascii string", + val.usValueLen, val.pValue, val.type) + + data = cast(val.pValue, c_char_p).value + ret_data = string_at(data, val.usValueLen) + LOG.debug("Converted to : %s", ret_data) + return ret_data if not isinstance(val, (str, list)): raise TypeError("Invalid conversion {} to CK_CHAR*!".format(type(val))) @@ -185,7 +194,12 @@ def to_byte_array(val, reverse=False): :class:`ctypes.c_ulong` size of array) """ if reverse: - return cast(val.pValue, c_char_p).value[0:val.usValueLen] + LOG.debug("Attempting to convert CK_ATTRIBUTE(len:%s, data:%s, type:%s) back to hex", + val.usValueLen, val.pValue, val.type) + data_list = list(cast(val.pValue, POINTER(c_ubyte))[0:val.usValueLen]) + fin = binascii.hexlify(bytearray(data_list)) + LOG.debug("Final hex data: %s", fin) + return fin if isinstance(val, list): py_bytes = bytearray(val) From 5a2ae0318d9948a84e9551829d7e13af7d38aa56 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 31 Mar 2016 14:01:26 -0400 Subject: [PATCH 039/109] LA-1682 Fix for sub-templates Change-Id: I86e04d8483b80944161253a36d92de83c2ef4d1b --- pycryptoki/attributes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 557e79a..2bd4a82 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -247,7 +247,7 @@ def to_sub_attributes(val, reverse=False): if not isinstance(val, dict): raise TypeError("Invalid conversion {} to Template!".format(type(val))) - attrs = Attributes(**val).get_c_struct() + attrs = Attributes(val).get_c_struct() return cast(pointer(attrs), c_void_p), CK_ULONG(len(attrs)) From daadb763a4e85ad41c1ece86b0433aeb939e521f Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 31 Mar 2016 14:33:53 -0400 Subject: [PATCH 040/109] LA-1682 Removed null termination added to strings create_string_buffer by default adds null termination, unless you specify a length of the string. Change-Id: Ie8439eff94984fcf8ee2f8a002803793015c5bcc --- pycryptoki/attributes.py | 17 +++++++++-------- pycryptoki/mechanism.py | 4 ++-- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 2bd4a82..19092e1 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -6,14 +6,14 @@ import datetime import logging from collections import defaultdict -from ctypes import cast, c_void_p, create_string_buffer, c_bool, c_char_p, \ +from ctypes import cast, c_void_p, create_string_buffer, c_bool, \ c_ulong, pointer, POINTER, sizeof, c_char, string_at, c_ubyte from functools import wraps import binascii from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ - CK_BYTE, CK_CHAR_PTR, CK_CHAR + CK_BYTE, CK_CHAR from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_CERTIFICATE_TYPE, \ CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ @@ -134,7 +134,7 @@ def to_char_array(val, reverse=False): "back to ascii string", val.usValueLen, val.pValue, val.type) - data = cast(val.pValue, c_char_p).value + data = cast(val.pValue, POINTER(CK_CHAR)) ret_data = string_at(data, val.usValueLen) LOG.debug("Converted to : %s", ret_data) return ret_data @@ -143,7 +143,7 @@ def to_char_array(val, reverse=False): raise TypeError("Invalid conversion {} to CK_CHAR*!".format(type(val))) if isinstance(val, str): - string_val = create_string_buffer(val) + string_val = create_string_buffer(val, len(val)) else: # TODO: Figure out what, if anything we want to do with a list. string_val = bytearray(val) @@ -161,17 +161,18 @@ def to_ck_date(val, reverse=False): :class:`ctypes.c_ulong` size of array) """ if reverse: - return str(cast(val.pValue, c_char_p).value[0:val.usValueLen]) + return string_at(cast(val.pValue, POINTER(c_char)), val.usValueLen) if isinstance(val, str): if len(val) != 8: raise TypeError("Invalid date string passed! Should be of type YYYYMMDD") - date_val = create_string_buffer(val) + date_val = create_string_buffer(val, len(val)) elif isinstance(val, dict): date_str = val['year'] + val['month'] + val['day'] - date_val = create_string_buffer(date_str) + date_val = create_string_buffer(date_str, len(date_str)) elif isinstance(val, datetime.date): - date_val = create_string_buffer(val.strftime("%Y%m%d")) + data = val.strftime("%Y%m%d") + date_val = create_string_buffer(data, len(data)) else: raise TypeError("Invalid conversion {} to CK_DATE!".format(type(val))) diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index f13e7e4..db49962 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -1,5 +1,5 @@ from ctypes import c_void_p, cast, pointer, POINTER, sizeof, c_char_p, \ - create_string_buffer + create_string_buffer, c_char from pycryptoki.cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR @@ -118,7 +118,7 @@ def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): if params_struct.pBuffer is None: bufferString = None else: - char_p_string = cast(params_struct.pBuffer, c_char_p).value + char_p_string = cast(params_struct.pBuffer, POINTER(c_char)) if char_p_string is not None: bufferString = char_p_string[0:bufferLength] else: From ca87ca55348c2caffacbe542563d48a6c86a1527 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 7 Apr 2016 15:45:46 -0400 Subject: [PATCH 041/109] LA-1718 Removed 'get_byte_list...' * Now use 'to_char_array' * Modified some functions to use AutoCArray Change-Id: I5de0ebef209c692b721f77687ed08ffa7155b0e6 --- pycryptoki/attributes.py | 15 --- pycryptoki/common_utils.py | 2 +- pycryptoki/encryption.py | 187 ++++++++++++++++++------------------ pycryptoki/key_generator.py | 15 ++- pycryptoki/misc.py | 67 ++++++++----- pycryptoki/sign_verify.py | 120 +++++++++++++---------- 6 files changed, 215 insertions(+), 191 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 19092e1..a208c01 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -33,21 +33,6 @@ LOG = logging.getLogger(__name__) -def get_byte_list_from_python_list(python_byte_list): - """Helper method to create a C style byte list from a python - style list of integers. - - :param python_byte_list: A list of integers to convert to a C style list of integers - :returns: The pointer to the C representation of the python byte list - - """ - list_val = create_string_buffer("", len(python_byte_list)) - ptr = cast(pointer(list_val), c_void_p) - for j in range(0, len(python_byte_list)): - list_val[j] = chr(python_byte_list[j]) - return ptr - - def ret_type(c_type): """ Decorator to set a returned C Type so we can determine what type to use diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index aa9f8dd..de25910 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -80,7 +80,7 @@ def array(self): if self._array is None: # If we get to this point, we have a specified size, a ctype, # And our array is still none, but we're trying to access it. - # Therefore, we go ahead & allocate the memory for + # Therefore, we go ahead & allocate the memory self._array = (self.ctype * self._size.value)() return cast(self._array, POINTER(self.ctype)) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index e4e5ae7..6fefd41 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -1,8 +1,10 @@ """ Methods related to encrypting data/files. """ -from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer, string_at import logging +from _ctypes import POINTER +from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer, \ + string_at, c_ubyte from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ C_EncryptInit, C_Encrypt, CK_RSA_PKCS_OAEP_PARAMS @@ -17,13 +19,14 @@ CKM_AES_CFB128, CKM_AES_OFB, CKM_ARIA_CFB8, CKM_ARIA_CFB128, CKM_ARIA_OFB, \ CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED, CKM_AES_KW, CKM_AES_KWP -from pycryptoki.attributes import get_byte_list_from_python_list, Attributes +from pycryptoki.attributes import Attributes, to_byte_array, to_char_array +from pycryptoki.common_utils import AutoCArray, refresh_c_arrays from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ C_DecryptUpdate, C_DecryptFinal from pycryptoki.test_functions import make_error_handle_function -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) def get_encryption_mechanism(encryption_flavor, external_iv=None): @@ -103,13 +106,15 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): iv = external_iv iv16 = external_iv else: + LOG.warning("Using static IVs can be insecure! ") iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] params = encryption_flavors.get(encryption_flavor) if params == iv_required: - mech.pParameter = get_byte_list_from_python_list(iv) - mech.usParameterLen = CK_ULONG(len(iv)) + iv_ba, iv_len = to_byte_array(iv) + mech.pParameter = iv_ba + mech.usParameterLen = iv_len elif params == RC2_params_required: num_of_effective_bits = 0 rc2_params = (c_char * 2)() @@ -118,33 +123,30 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): rc2_params = create_string_buffer("", 2) mech.pParameter = cast(rc2_params, c_void_p) mech.usParameterLen = CK_ULONG(len(rc2_params)) - pass elif params == RC2CBC_params_required: num_of_effective_bits = 0 - pass elif params == RC5_params_required: num_rounds = 0 - pass elif params == RC5CBC_params_required: num_rounds = 0 - pass elif params == IV16_required: - mech.pParameter = get_byte_list_from_python_list(iv16) - mech.usParameterLen = CK_ULONG(len(iv16)) + iv_ba, iv_len = to_byte_array(iv16) + mech.pParameter = iv_ba + mech.usParameterLen = iv_len elif params == GCM_params_required: pass elif params == xorkdf_params_required: pass elif params == OAEP_params_required: - p = CK_RSA_PKCS_OAEP_PARAMS() - p.hashAlg = CK_ULONG(CKM_SHA_1) - p.mgf = CK_ULONG(CKG_MGF1_SHA1) - p.source = CK_ULONG(CKZ_DATA_SPECIFIED) - p.pSourceData = 0 - p.ulSourceDataLen = 0 - - mech.pParameter = cast(pointer(p), CK_VOID_PTR) - mech.usParameterLen = CK_ULONG(sizeof(p)) + oaep_params = CK_RSA_PKCS_OAEP_PARAMS() + oaep_params.hashAlg = CK_ULONG(CKM_SHA_1) + oaep_params.mgf = CK_ULONG(CKG_MGF1_SHA1) + oaep_params.source = CK_ULONG(CKZ_DATA_SPECIFIED) + oaep_params.pSourceData = 0 + oaep_params.ulSourceDataLen = 0 + + mech.pParameter = cast(pointer(oaep_params), CK_VOID_PTR) + mech.usParameterLen = CK_ULONG(sizeof(oaep_params)) elif params == ECIES_params_required: pass @@ -158,45 +160,49 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e :param h_session: Current session :param encryption_flavor: The flavor of encryption to use :param h_key: The key handle to encrypt the data with - :param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is a list + :param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is + a list a multipart operation will be used :param mech: The mechanism to use, if None will try to look up a default mechanism based on the encryption flavor :param external_iv: The new Integrity Value to be used. - :returns: Returns the result code of the operation, a python string representing the encrypted data + :returns: Returns the result code of the operation, a python string representing the + encrypted data """ if mech is None: mech = get_encryption_mechanism(encryption_flavor, external_iv) - # if a list is passed out do an encrypt operation on each string in the list, otherwise just do one encrypt operation - is_multi_part_operation = isinstance(data_to_encrypt, list) or isinstance(data_to_encrypt, tuple) + # if a list is passed out do an encrypt operation on each string in the list, otherwise just + # do one encrypt operation + is_multi_part_operation = isinstance(data_to_encrypt, (list, tuple)) # Initialize encryption ret = C_EncryptInit(h_session, byref(mech), CK_ULONG(h_key)) - if ret != CKR_OK: return ret, None + if ret != CKR_OK: + return ret, None if is_multi_part_operation: - ret, encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, C_EncryptFinal, data_to_encrypt) + ret, encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, + C_EncryptFinal, data_to_encrypt) else: - plain_data_length = len(data_to_encrypt) - plain_data = get_c_data_to_sign_or_encrypt(data_to_encrypt) + plain_data, plain_data_length = to_char_array(data_to_encrypt) + plain_data = cast(plain_data, POINTER(c_ubyte)) - # Get the length of the encrypted data - encrypted_data_length = CK_ULONG() - ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), None, byref(encrypted_data_length)) - if ret != CKR_OK: return ret, None + enc_data = AutoCArray(ctype=c_ubyte) - output = create_string_buffer("", encrypted_data_length.value) - encrypted_data = cast(output, CK_BYTE_PTR) + @refresh_c_arrays(1) + def _encrypt(): + return C_Encrypt(h_session, + plain_data, plain_data_length, + enc_data.array, enc_data.size) - # Encrypt data - ret = C_Encrypt(h_session, plain_data, CK_ULONG(plain_data_length), encrypted_data, - byref(encrypted_data_length)) + ret = _encrypt() + if ret != CKR_OK: + return ret, None # Convert encrypted data into a python string - ck_char_array = encrypted_data._objects.values()[0] - encrypted_python_string = string_at(ck_char_array, len(ck_char_array)) + encrypted_python_string = string_at(enc_data.array, len(enc_data)) return ret, encrypted_python_string @@ -256,13 +262,16 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, ex # Initialize Decrypt ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) - if ret != CKR_OK: return ret, None + if ret != CKR_OK: + return ret, None - # if a list is passed out do a decrypt operation on each string in the list, otherwise just do one decrypt operation - is_multi_part_operation = isinstance(encrypted_data, list) or isinstance(encrypted_data, tuple) + # if a list is passed out do a decrypt operation on each string in the list, otherwise just + # do one decrypt operation + is_multi_part_operation = isinstance(encrypted_data, (list, tuple)) if is_multi_part_operation: - ret, python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, encrypted_data) + ret, python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, + encrypted_data) else: # Get the length of the final data @@ -272,25 +281,24 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, ex # number of bytes needed. So the python string that's returned in the # end needs to be adjusted based on the second called to C_Decrypt # which will have the right length - plain_data_len = CK_ULONG() - c_encrypted_data = get_c_data_to_sign_or_encrypt(encrypted_data) - encrypted_data_len = len(encrypted_data) - ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), None, byref(plain_data_len)) + c_enc_data, c_enc_data_len = to_char_array(encrypted_data) + c_enc_data = cast(c_enc_data, POINTER(c_ubyte)) - if ret != CKR_OK: return ret, None + decrypted_data = AutoCArray(ctype=c_ubyte) - output = create_string_buffer("", plain_data_len.value) - plain_data = cast(output, CK_BYTE_PTR) + @refresh_c_arrays(1) + def _decrypt(): + """ Perform the decryption ops""" + return C_Decrypt(h_session, + c_enc_data, c_enc_data_len, + decrypted_data.array, decrypted_data.size) - # Decrypt data - ret = C_Decrypt(h_session, c_encrypted_data, CK_ULONG(encrypted_data_len), plain_data, byref(plain_data_len)) - if ret != CKR_OK: return ret, None + ret = _decrypt() + if ret != CKR_OK: + return ret, None # Convert the decrypted data to a python readable format - ck_char_array = plain_data._objects.values()[0] - python_string = string_at(ck_char_array, len(ck_char_array)) - # Adjust the string based on the updated plain_data_len - python_string = python_string[:plain_data_len.value] + python_string = string_at(decrypted_data.array, len(decrypted_data)) return ret, python_string @@ -322,16 +330,18 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in if current_chunk_len > max_data_chunk_size: raise Exception( - "chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) + "chunk_sizes variable too large, the maximum size of a chunk is " + str( + max_data_chunk_size)) out_data = create_string_buffer('', max_data_chunk_size) out_data_len = CK_ULONG(max_data_chunk_size) - if out_data_len.value > 0: - data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + data_chunk, data_chunk_len = to_char_array(data_chunk) - ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len), cast(out_data, CK_BYTE_PTR), + ret = c_update_function(h_session, data_chunk, data_chunk_len, + cast(out_data, CK_BYTE_PTR), byref(out_data_len)) - if ret != CKR_OK: return ret, None + if ret != CKR_OK: + return ret, None remaining_length -= current_chunk_len @@ -344,7 +354,8 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in out_data_len = CK_ULONG(max_data_chunk_size) output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) ret = c_finalize_function(h_session, output, byref(out_data_len)) - if ret != CKR_OK: return ret, None + if ret != CKR_OK: + return ret, None # Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: @@ -369,25 +380,27 @@ def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, e if mech is None: mech = get_encryption_mechanism(encryption_flavor, external_iv) - # Get the size of the key - wrapped_key_length = CK_ULONG() - ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), None, - byref(wrapped_key_length)) - if ret != CKR_OK: return ret, None + wrapped_key = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _wrap(): + """ Perform the Wrapping operation""" + return C_WrapKey(h_session, mech, + CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), + wrapped_key.array, wrapped_key.size) - # Actually wrap the key - output = create_string_buffer("", wrapped_key_length.value) - wrapped_key_output = cast(output, CK_BYTE_PTR) - ret = C_WrapKey(h_session, mech, CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), wrapped_key_output, - byref(wrapped_key_length)) + ret = _wrap() + if ret != CKR_OK: + return ret, None - return ret, wrapped_key_output._objects.values()[0] + return ret, string_at(wrapped_key.array, len(wrapped_key)) c_wrap_key_ex = make_error_handle_function(c_wrap_key) -def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, mech=None, external_iv=None): +def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, + mech=None, external_iv=None): """Function which unwraps a key :param h_session: The session to use @@ -396,7 +409,8 @@ def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encrypt :param key_template: The python template representing the new key's template :param encryption_flavor: If the mechanism is not specified it will create a default one based on the encryption flavor - :param mech: The mechanism to use, if null a default one will be created based on the encryption_flavor + :param mech: The mechanism to use, if null a default one will be created based on the + encryption_flavor :param h_unwrapping_key: :param wrapped_key: :returns: The result code, the handle of the unwrapped key @@ -408,28 +422,11 @@ def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encrypt c_template = Attributes(key_template).get_c_struct() byte_wrapped_key = cast(wrapped_key, CK_BYTE_PTR) h_output_key = CK_ULONG() - ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), byte_wrapped_key, CK_ULONG(len(wrapped_key)), + ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), byte_wrapped_key, + CK_ULONG(len(wrapped_key)), c_template, CK_ULONG(len(key_template)), byref(h_output_key)) return ret, h_output_key.value c_unwrap_key_ex = make_error_handle_function(c_unwrap_key) - - -def get_c_data_to_sign_or_encrypt(python_data): - """Function which gets the C data representation of some python data - - :param python_data: The python data to get a c representation of - :returns: A C byte pointer pointing to the C representation of the python data - """ - - c_data_to_sign = None - if isinstance(python_data, str): - c_data_to_sign = create_string_buffer(python_data) - c_data_to_sign = cast(c_data_to_sign, CK_BYTE_PTR) - else: - raise Exception("Please extend this function to support the type of data " + - str(type(python_data))) - - return c_data_to_sign diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 480efea..003ecdf 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -85,7 +85,9 @@ def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_T # ACTUALLY GENERATE KEY h_key = CK_OBJECT_HANDLE() - ret = C_GenerateKey(h_session, byref(mech), key_attributes.get_c_struct(), us_public_template_size, byref(h_key)) + ret = C_GenerateKey(h_session, + byref(mech), key_attributes.get_c_struct(), + us_public_template_size, byref(h_key)) return ret, h_key.value @@ -120,8 +122,10 @@ def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, h_pbkey = CK_OBJECT_HANDLE() h_prkey = CK_OBJECT_HANDLE() - ret = C_GenerateKeyPair(h_session, byref(mech), pbkey_attributes.get_c_struct(), pbkey_template_size, - prkey_attributes.get_c_struct(), prkey_template_size, byref(h_pbkey), byref(h_prkey)) + ret = C_GenerateKeyPair(h_session, byref(mech), + pbkey_attributes.get_c_struct(), pbkey_template_size, + prkey_attributes.get_c_struct(), prkey_template_size, + byref(h_pbkey), byref(h_prkey)) return ret, h_pbkey.value, h_prkey.value @@ -146,7 +150,10 @@ def c_derive_key(h_session, h_base_key, template, mech_flavor, mech=None): h_key = CK_OBJECT_HANDLE() c_template = Attributes(template).get_c_struct() - ret = C_DeriveKey(h_session, mech, CK_OBJECT_HANDLE(h_base_key), c_template, CK_ULONG(len(template)), byref(h_key)) + ret = C_DeriveKey(h_session, mech, + CK_OBJECT_HANDLE(h_base_key), + c_template, CK_ULONG(len(template)), + byref(h_key)) return ret, h_key.value diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 4c04c9c..834a027 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -1,11 +1,23 @@ -from ctypes import create_string_buffer, cast, byref, string_at - -from pycryptoki.attributes import Attributes +""" +PKCS11 Interface to the following functions: + +* c_generate_random +* c_seed_random +* c_digest +* c_digestkey +* c_create_object +* c_set_ped_id (CA_ function) +* c_get_ped_id (CA_ function) +""" +from _ctypes import POINTER +from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte + +from pycryptoki.attributes import Attributes, to_char_array +from pycryptoki.common_utils import refresh_c_arrays, AutoCArray from pycryptoki.cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey from pycryptoki.defines import CKR_OK -from pycryptoki.encryption import get_c_data_to_sign_or_encrypt from pycryptoki.key_generator import _get_mechanism from pycryptoki.sign_verify import do_multipart_sign_or_digest from pycryptoki.test_functions import make_error_handle_function @@ -51,8 +63,8 @@ def c_digest(h_session, data_to_digest, digest_flavor, mech=None): """Digests some data :param h_session: Current session - :param data_to_digest: The data to digest, either a string or a list of strings. If this is a list - a multipart operation will be used + :param data_to_digest: The data to digest, either a string or a list of strings. If this is a + list a multipart operation will be used :param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, SHA224, SHA256, SHA384, SHA512) :param mech: The mechanism to be used. If None a blank one with the @@ -67,33 +79,38 @@ def c_digest(h_session, data_to_digest, digest_flavor, mech=None): # Initialize Digestion ret = C_DigestInit(h_session, mech) - if ret != CKR_OK: return ret + if ret != CKR_OK: + return ret - # if a list is passed out do an digest operation on each string in the list, otherwise just do one digest operation - is_multi_part_operation = isinstance(data_to_digest, list) or isinstance(data_to_digest, tuple) + # if a list is passed out do an digest operation on each string in the list, otherwise just + # do one digest operation + is_multi_part_operation = isinstance(data_to_digest, (list, tuple)) if is_multi_part_operation: - ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, C_DigestFinal, + ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, + C_DigestFinal, data_to_digest) else: # Get arguments - digest_data_length = len(data_to_digest) - c_data_to_digest = get_c_data_to_sign_or_encrypt(data_to_digest) + c_data_to_digest, c_digest_data_len = to_char_array(data_to_digest) + c_data_to_digest = cast(c_data_to_digest, POINTER(c_ubyte)) - # Get the length of the digested data - digest_length = CK_ULONG() - ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), None, byref(digest_length)) - if ret != CKR_OK: return ret, None + digested_data = AutoCArray(ctype=c_ubyte) - output = create_string_buffer("", digest_length.value) - digested_data = cast(output, CK_BYTE_PTR) + @refresh_c_arrays(1) + def _digest(): + """ Perform the digest operations + """ + return C_Digest(h_session, + c_data_to_digest, c_digest_data_len, + digested_data.array, digested_data.size) - # Digest data - ret = C_Digest(h_session, c_data_to_digest, CK_ULONG(digest_data_length), digested_data, byref(digest_length)) + ret = _digest() + if ret != CKR_OK: + return ret, None # Convert Digested data into a python string - ck_char_array = digested_data._objects.values()[0] - digested_python_string = string_at(ck_char_array, len(ck_char_array)) + digested_python_string = string_at(digested_data.array, len(digested_data)) return ret, digested_python_string @@ -107,7 +124,8 @@ def c_digestkey(h_session, h_key, digest_flavor, mech=None): :param h_session: Logged in session handle :param h_key: Key to digest :param digest_flavor: Digest flavor - :param mech: Mechanism to use for digest. Defaults to using the flavor mechanism. (Default value = None) + :param mech: Mechanism to use for digest. Defaults to using the flavor mechanism. (Default + value = None) """ # Get mechanism if none provided if mech is None: @@ -115,7 +133,8 @@ def c_digestkey(h_session, h_key, digest_flavor, mech=None): # Initialize Digestion ret = C_DigestInit(h_session, mech) - if ret != CKR_OK: return ret + if ret != CKR_OK: + return ret ret = C_DigestKey(h_session, h_key) diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index d693dac..35eea9f 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -1,20 +1,27 @@ +""" +PKCS11 Operations related to Signing and Verifying data +""" +import logging +from _ctypes import POINTER +from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p, string_at, c_ubyte + from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign -from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p, string_at from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ CKM_SHA512, CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, \ CKG_MGF1_SHA512 +from pycryptoki.attributes import to_char_array +from pycryptoki.common_utils import refresh_c_arrays, AutoCArray from pycryptoki.cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ C_SignFinal, C_VerifyUpdate, C_VerifyFinal, CK_RSA_PKCS_PSS_PARAMS -from pycryptoki.encryption import _get_string_from_list, \ - get_c_data_to_sign_or_encrypt +from pycryptoki.encryption import _get_string_from_list from pycryptoki.test_functions import make_error_handle_function -import logging LOG = logging.getLogger(__name__) + def get_custom_mech_for_sigver(sigver_mech, algorithm, mask=None, salt_len=8): """ Generate a mechanism for signing/verifying operations with RSA PKCS PSS @@ -58,6 +65,7 @@ def get_custom_mech_for_sigver(sigver_mech, algorithm, mask=None, salt_len=8): mech.usParameterLen = CK_ULONG(sizeof(params)) return mech + def get_mechanism_for_sigver(flavour): """ Try to build a default mechanism if none is provided, @@ -116,6 +124,7 @@ def get_mechanism_for_sigver(flavour): mech.usParameterLen = CK_ULONG(0) return mech + def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=None): """ Performs a C_SignInit and C_Sign operation on some data @@ -138,21 +147,21 @@ def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=Non :return: The result code, A python string representing the signature """ - #Get the mechanism + # Get the mechanism if mech is None: mech = get_mechanism_for_sigver(sign_flavor) if algorithm is not None: mech = get_custom_mech_for_sigver(sign_flavor, algorithm) - #Initialize the sign operation + # Initialize the sign operation ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) if ret != CKR_OK: return ret, None - #if a list is passed out do a sign operation on each string in the list, - #otherwise just do one sign operation - is_multi_part_operation = isinstance(data_to_sign, list) or isinstance(data_to_sign, tuple) + # if a list is passed out do a sign operation on each string in the list, + # otherwise just do one sign operation + is_multi_part_operation = isinstance(data_to_sign, (list, tuple)) if is_multi_part_operation: ret, signature_string = do_multipart_sign_or_digest(h_session, @@ -160,29 +169,31 @@ def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=Non C_SignFinal, data_to_sign) else: - #Prepare the data to sign - c_data_to_sign = get_c_data_to_sign_or_encrypt(data_to_sign) - plain_date_len = CK_ULONG(len(data_to_sign)) + # Prepare the data to sign + c_data_to_sign, plain_date_len = to_char_array(data_to_sign) + c_data_to_sign = cast(c_data_to_sign, POINTER(c_ubyte)) + + signed_data = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _sign(): + """Perform the signing operation""" + return C_Sign(h_session, + c_data_to_sign, plain_date_len, + signed_data.array, signed_data.size) - #Get the length of the output - sign_len = CK_ULONG() - ret = C_Sign(h_session, c_data_to_sign, plain_date_len, None, byref(sign_len)) + ret = _sign() if ret != CKR_OK: return ret, None - #Actually get the signature - signature_buffer = create_string_buffer("", sign_len.value) - signature = cast(signature_buffer, CK_BYTE_PTR) - ret = C_Sign(h_session, c_data_to_sign, plain_date_len, signature, byref(sign_len)) - - ck_char_array = signature._objects.values()[0] - signature_string = '' - if sign_len.value > 0: - signature_string = string_at(ck_char_array, len(ck_char_array))[0:sign_len.value] + signature_string = string_at(signed_data.array, len(signed_data)) return ret, signature_string + + c_sign_ex = make_error_handle_function(c_sign) + def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, input_data_list): """ Do a multipart sign or digest operation @@ -202,34 +213,37 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, while remaining_length > 0: current_chunk = input_data_list[i] - #Prepare arguments for decrypt update operation + # Prepare arguments for decrypt update operation current_chunk_len = min(len(current_chunk), remaining_length) if current_chunk_len > max_data_chunk_size: raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + data_chunk, data_chunk_len = to_char_array(current_chunk) + data_chunk = cast(data_chunk, POINTER(c_ubyte)) - ret = c_update_function(h_session, data_chunk, CK_ULONG(current_chunk_len)) - if ret != CKR_OK: return ret, None + ret = c_update_function(h_session, data_chunk, data_chunk_len) + if ret != CKR_OK: + return ret, None remaining_length -= current_chunk_len i += 1 - #Finalizing multipart decrypt operation + # Finalizing multipart decrypt operation out_data_len = CK_ULONG(max_data_chunk_size) output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) ret = c_final_function(h_session, output, byref(out_data_len)) - #Get output + # Get output ck_char_array = output._objects.values()[0] if out_data_len.value > 0: python_string += string_at(ck_char_array, len(ck_char_array))[0:out_data_len.value] return ret, python_string + def do_multipart_verify(h_session, input_data_list, signature): """ Do a multipart verify operation @@ -247,29 +261,32 @@ def do_multipart_verify(h_session, input_data_list, signature): while remaining_length > 0: current_chunk = input_data_list[i] - #Prepare arguments for decrypt update operation + # Prepare arguments for decrypt update operation current_chunk_len = min(len(current_chunk), remaining_length) if current_chunk_len > max_data_chunk_size: raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - data_chunk = get_c_data_to_sign_or_encrypt(current_chunk) + data_chunk, data_chunk_len = to_char_array(current_chunk) + data_chunk = cast(data_chunk, POINTER(c_ubyte)) - ret = C_VerifyUpdate(h_session, data_chunk, CK_ULONG(current_chunk_len)) - if ret != CKR_OK: return ret + ret = C_VerifyUpdate(h_session, data_chunk, data_chunk_len) + if ret != CKR_OK: + return ret remaining_length -= current_chunk_len i += 1 - #Finalizing multipart decrypt operation - out_data_len = CK_ULONG(len(signature)) - output = cast(get_c_data_to_sign_or_encrypt(signature), CK_BYTE_PTR) - ret = C_VerifyFinal(h_session, output, out_data_len) + # Finalizing multipart decrypt operation + c_sig_data, c_sig_data_len = to_char_array(signature) + output = cast(c_sig_data, CK_BYTE_PTR) + ret = C_VerifyFinal(h_session, output, c_sig_data_len) return ret + def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=None, algorithm=None): """ Return the result code of C_Verify which indicates whether or not the signature is @@ -295,39 +312,38 @@ def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=No :return: The result code """ - #Get the mechanism + # Get the mechanism if mech is None: mech = get_mechanism_for_sigver(verify_flavor) if algorithm is not None: mech = get_custom_mech_for_sigver(verify_flavor, algorithm) - #Initialize the verify operation + # Initialize the verify operation ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) if ret != CKR_OK: return ret - #if a list is passed out do a verify operation on each string in the list, - #otherwise just do one verify operation + # if a list is passed out do a verify operation on each string in the list, + # otherwise just do one verify operation is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(data_to_verify, tuple) if is_multi_part_operation: ret = do_multipart_verify(h_session, data_to_verify, signature) else: - #Prepare the data to verify - c_data_to_verify = get_c_data_to_sign_or_encrypt(data_to_verify) - plain_date_len = CK_ULONG(len(data_to_verify)) + # Prepare the data to verify + c_data_to_verify, plain_date_len = to_char_array(data_to_verify) + c_data_to_verify = cast(c_data_to_verify, POINTER(c_ubyte)) - c_signature = get_c_data_to_sign_or_encrypt(signature) + c_signature, c_sig_length = to_char_array(signature) + c_signature = cast(c_signature, POINTER(c_ubyte)) - #Actually verify the data + # Actually verify the data ret = C_Verify(h_session, - c_data_to_verify, - plain_date_len, - c_signature, - CK_ULONG(len(signature))) + c_data_to_verify, plain_date_len, + c_signature, c_sig_length) return ret -c_verify_ex = make_error_handle_function(c_verify) +c_verify_ex = make_error_handle_function(c_verify) From 730ff91997a5e0f9afdf1bd058535e994a60f0f9 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 19 Apr 2016 13:08:45 -0400 Subject: [PATCH 042/109] LA-1718 Fix invalid attribute error Change-Id: I82445185a421ba9f6653f16344e8291cb2453993 --- pycryptoki/encryption.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 6fefd41..59d847d 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -335,7 +335,8 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in out_data = create_string_buffer('', max_data_chunk_size) out_data_len = CK_ULONG(max_data_chunk_size) - data_chunk, data_chunk_len = to_char_array(data_chunk) + data_chunk, data_chunk_len = to_char_array(current_chunk) + data_chunk = cast(data_chunk, POINTER(c_ubyte)) ret = c_update_function(h_session, data_chunk, data_chunk_len, cast(out_data, CK_BYTE_PTR), From 32e57596de42807e113d894f533a1c4f2ab9c495 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 22 Apr 2016 10:04:00 -0400 Subject: [PATCH 043/109] LA-1696 Shortened logging output of exceptions Truncates long input strings when raising an exception. Change-Id: Ib2446610cf7a29292a4076672cf14722d7b091b7 --- pycryptoki/common_utils.py | 14 +++++ pycryptoki/encryption.py | 49 +++++++-------- pycryptoki/pycryptoki_client.py | 2 + pycryptoki/test_functions.py | 105 ++++++++++++++++++-------------- 4 files changed, 99 insertions(+), 71 deletions(-) diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index de25910..990b78b 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -3,6 +3,7 @@ """ from _ctypes import pointer, POINTER from ctypes import c_ulong, cast, create_string_buffer + from pycryptoki.cryptoki import CK_CHAR from pycryptoki.defines import CKR_OK @@ -19,6 +20,7 @@ class AutoCArray(object): An attempt to provide automatic resolution of C-style arrays. """ + def __init__(self, data=None, ctype=c_ulong, size=None): """ Initialize the Array. @@ -112,6 +114,14 @@ def __iter__(self): for i in self._array: yield i + def __str__(self): + """ + Return a legible version of the array. + """ + return "AutoCArray = ({ctype} * {size})({data})".format(ctype=self.ctype, + size=len(self), + data=self._array) + def refresh_c_arrays(retries=1): """ @@ -131,6 +141,7 @@ def closure_func(): :param func: Function to decorate. :return: closure. """ + def wrap(func): """ Inner decorator. @@ -138,6 +149,7 @@ def wrap(func): :param func: Original function decorated. :return: """ + def wrapped_func(*args, **kwargs): """ Runs the wrapped function the given number of times, @@ -156,5 +168,7 @@ def wrapped_func(*args, **kwargs): return ret tries += 1 return ret + return wrapped_func + return wrap diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 6fefd41..c032848 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -35,6 +35,7 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): :param encryption_flavor: The flavor of the encryption that the mechanism needs to encrypt for. + :param external_iv: External IV to insert into the mechanism struct. :returns: Returns a CTypes CK_Mechanism given the encryption flavour that you have passed in """ @@ -102,15 +103,17 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): CKM_RSA_PKCS_OAEP: OAEP_params_required, CKM_ECIES: ECIES_params_required} - if external_iv: - iv = external_iv - iv16 = external_iv - else: - LOG.warning("Using static IVs can be insecure! ") - iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] - iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] - params = encryption_flavors.get(encryption_flavor) + + if params in (iv_required, IV16_required): + if external_iv: + iv = external_iv + iv16 = external_iv + else: + LOG.warning("Using static IVs can be insecure! ") + iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] + iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + if params == iv_required: iv_ba, iv_len = to_byte_array(iv) mech.pParameter = iv_ba @@ -124,19 +127,19 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): mech.pParameter = cast(rc2_params, c_void_p) mech.usParameterLen = CK_ULONG(len(rc2_params)) elif params == RC2CBC_params_required: - num_of_effective_bits = 0 + raise NotImplementedError("RC2 CBC params not yet implemented") elif params == RC5_params_required: - num_rounds = 0 + raise NotImplementedError("RC5 params not yet implemented") elif params == RC5CBC_params_required: - num_rounds = 0 + raise NotImplementedError("RC5 CBC params not yet implemented") elif params == IV16_required: iv_ba, iv_len = to_byte_array(iv16) mech.pParameter = iv_ba mech.usParameterLen = iv_len elif params == GCM_params_required: - pass + raise NotImplementedError("GCM params not yet implemented") elif params == xorkdf_params_required: - pass + raise NotImplementedError("xorkdf params not yet implemented") elif params == OAEP_params_required: oaep_params = CK_RSA_PKCS_OAEP_PARAMS() oaep_params.hashAlg = CK_ULONG(CKM_SHA_1) @@ -148,7 +151,10 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): mech.pParameter = cast(pointer(oaep_params), CK_VOID_PTR) mech.usParameterLen = CK_ULONG(sizeof(oaep_params)) elif params == ECIES_params_required: - pass + raise NotImplementedError("ECIES params not yet implemented") + else: + raise NotImplementedError("Encryption flavor {} is not " + "implemented!".format(encryption_flavor)) return mech @@ -193,6 +199,7 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e @refresh_c_arrays(1) def _encrypt(): + """Closure for getting the buffer size with encrypt.""" return C_Encrypt(h_session, plain_data, plain_data_length, enc_data.array, enc_data.size) @@ -218,14 +225,8 @@ def _split_string_into_list(python_string, block_size): :returns: A list of strings of block_size """ - return_list = [] total_length = len(python_string) - for index in range(0, (total_length / block_size)): - start_index = index * block_size - end_index = min(start_index + block_size, total_length) - return_list.append(python_string[start_index: end_index]) - - return return_list + return [python_string[x:x + block_size] for x in xrange(0, total_length, block_size)] def _get_string_from_list(list_of_strings): @@ -235,11 +236,7 @@ def _get_string_from_list(list_of_strings): :returns: Single string representing the concatenated list """ - large_string = '' - for substring in list_of_strings: - large_string += substring - - return large_string + return "".join(list_of_strings) def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, external_iv=None): diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index c2e39b6..fb676d4 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -157,6 +157,8 @@ def wrapper(*args, **kwargs): masked_args = tuple("*" for _ in args) masked_kwargs = {key: "*" for key, _ in kwargs.items()} + masked_args = ["{:.10}".format(str(arg)) for arg in masked_args] + masked_kwargs = ["{:.10}".format(str(kwarg)) for kwarg in masked_kwargs] log.info("Running remote pycryptoki command: " "{0}(args={1}, kwargs={2})".format(name, masked_args, masked_kwargs)) return getattr(self.server, name)(*args, **kwargs) diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 05eee9b..be6fb13 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -1,7 +1,7 @@ -from ctypes import byref -from functools import wraps import inspect import logging +from ctypes import byref +from functools import wraps from defines import CKR_OK from pycryptoki.attributes import Attributes @@ -9,12 +9,14 @@ from pycryptoki.defines import CKR_OBJECT_HANDLE_INVALID from return_values import ret_vals_dictionary -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) def assert_test_return_value(value, expected_value, message, print_on_success=True): - """Asserts a pass or fail based on whether the value parameter is equal to the expected_value parameter. - Used to test the results of pkcs11 functions and looks up human readable strings for the various error codes. + """Asserts a pass or fail based on whether the value parameter is equal to the expected_value + parameter. + Used to test the results of pkcs11 functions and looks up human readable strings for the + various error codes. Prints out results in a consistent format. :param value: The return value of the pkcs11 function @@ -33,10 +35,10 @@ def assert_test_return_value(value, expected_value, message, print_on_success=Tr else: exp_code = "Unknown Code=" + str(hex(value)) - assert value == expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + "\n\tFound: " + code - + assert value == expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + \ + "\n\tFound: " + code if print_on_success: - logger.info(exp_code + ": " + message) + LOG.info(exp_code + ": " + message) def assert_test_case(result, message, print_on_success=False): @@ -49,7 +51,7 @@ def assert_test_case(result, message, print_on_success=False): """ assert result, "\nERROR: " + message if print_on_success: - logger.info("PASSED: " + message) + LOG.info("PASSED: " + message) class LunaException(Exception): @@ -75,11 +77,18 @@ def __init__(self, error_code, function_name, arguments): self.error_string = "Unknown Code=" + str(hex(self.error_code)) def __str__(self): - return "\n\tFunction: " + str(self.function_name) + "\n\tError: " + str(self.error_string) \ - + "\n\tError Code: " + str(hex(self.error_code)) + "\n\tArguments: " + str(self.arguments) + data = ("\n\tFunction: {func_name}" + "\n\tError: {err_string}" + "\n\tError Code: {err_code}" + "\n\tArguments: {args}").format(func_name=self.function_name, + err_string=self.error_string, + err_code=hex(self.error_code), + args=self.arguments) + + return data -class LunaReturn: +class LunaReturn(object): """ """ def __init__(self, return_code, return_data): @@ -102,7 +111,8 @@ def verify_object_attributes(h_session, h_object, expected_template): us_size = CK_ULONG() ret = C_GetObjectSize(h_session, h_object, byref(us_size)) assert_test_case(ret == CKR_OK, "Object " + str(h_object) + " exists") - assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.") + assert_test_case(us_size.value > 0, + "Object " + str(h_object.value) + " size is greater than zero.") # VERIFY ATTRIBUTES are the same as the ones passed in attr = Attributes() @@ -140,50 +150,51 @@ def verify_object_exists(h_session, h_object, should_exist=True): assert_test_case(ret == expected_ret, out) if should_exist: - assert_test_return_value(ret, CKR_OK, "Getting object " + str(h_object.value) + "'s size", True) - assert_test_case(us_size.value > 0, "Object " + str(h_object.value) + " size is greater than zero.", False) + assert_test_return_value(ret, CKR_OK, "Getting object " + str(h_object.value) + "'s size", + True) + assert_test_case(us_size.value > 0, + "Object " + str(h_object.value) + " size is greater than zero.", False) else: - assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, "Getting object " + str(h_object.value) + "'s size", + assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, + "Getting object " + str(h_object.value) + "'s size", True) - assert_test_case(us_size.value <= 0, "Object " + str(h_object.value) + " size is greater than zero.", False) + assert_test_case(us_size.value <= 0, + "Object " + str(h_object.value) + " size is greater than zero.", False) -def check_luna_exception(ret, luna_function, *args): +def check_luna_exception(ret, luna_function, args): """ + Check the return code from cryptoki.dll, and if it's non-zero raise an + exception with the error code looked up. - :param ret: - :param luna_function: - :param *args: - + :param ret: Return code from the C call + :param luna_function: pycryptoki function that was called + :param args: Arguments passed to the pycryptoki function. """ arg_spec = inspect.getargspec(luna_function).args - arg_string = "(" - i = 0 - if len(arg_spec) > 0: - for argument in args: - arg_string = arg_string + arg_spec[i] + "=" + str(argument) + nice_args = [x if len(str(x)) < 20 else "{}...{}".format(str(x)[:10], str(x)[-10:]) + for x in args] + arg_string = ", ".join("{}={}".format(key, value) for key, value in zip(arg_spec, nice_args)) - if i != (len(args) - 1): - arg_string += ", " - i += 1 - - arg_string += ")" - if ret != CKR_OK: raise LunaException(ret, luna_function.__name__, arg_string) + arg_string = "({})".format(arg_string) + if ret != CKR_OK: + raise LunaException(ret, luna_function.__name__, arg_string) def make_error_handle_function(luna_function): """This function is a helper function that creates a new function which checks the - result code returned from a function in luna. It is called by calling: + result code returned from a function in luna. It is called by calling:: - c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) + c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) This code will create a c_generate_key_pair_ex which will call c_generate_key_pair and check the first argument. The first argument is the return code of c_generate_key_pair. If the return - code != CKR_OK then c_generate_key_pair_ex will raise a LunaException. You can call c_generate_key_pair_ex - as if it is c_generate_key_pair: + code != CKR_OK then c_generate_key_pair_ex will raise a LunaException. You can call + c_generate_key_pair_ex as if it is c_generate_key_pair:: - c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) The return values of c_generate_pair are (ret, public_key_handle, private_key_handle) @@ -192,12 +203,15 @@ def make_error_handle_function(luna_function): This lets you create two versions of a function. One version is for setup and the other version is for testing the result. - Directly testing the result: - ret = c_initialize() - assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" + Directly testing the result:: + + ret = c_initialize() + assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" + + Expecting the call to go through without error. The test case should have an error (not a + failure):: - Expecting the call to go through without error. The test case should have an error (not a failure): - c_initialize_ex() + c_initialize_ex() This should therefore make for shorter test cases @@ -229,7 +243,8 @@ def luna_function_exception_handle(*args, **kwargs): return_data = return_tuple else: raise Exception( - "Functions wrapped by the exception handler should return a tuple or just the long representing Luna's return code.") + "Functions wrapped by the exception handler should return a tuple or just the " + "long representing Luna's return code.") check_luna_exception(ret, luna_function, args) return return_data From 626047e7b0eb2721e11e206fa5b4c967b1459f82 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 25 Apr 2016 12:41:26 -0400 Subject: [PATCH 044/109] LA-1696 Removed pycryptoki mech fallthrough exception Change-Id: Id32e3df7253f42a782db3c700e3840cb8b47a1cf --- pycryptoki/encryption.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index c032848..91b801a 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -152,9 +152,6 @@ def get_encryption_mechanism(encryption_flavor, external_iv=None): mech.usParameterLen = CK_ULONG(sizeof(oaep_params)) elif params == ECIES_params_required: raise NotImplementedError("ECIES params not yet implemented") - else: - raise NotImplementedError("Encryption flavor {} is not " - "implemented!".format(encryption_flavor)) return mech From 27a16d9fff464fe7402b4b6cb5dec0ae92d3e9e0 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 18 May 2016 15:08:29 -0400 Subject: [PATCH 045/109] LA-1696 Update pycryptoki w/ K7 data Re-ran the build from our library headers to pull in added retcodes/constants/functions. Change-Id: Ica18ca2f776287157b2b45b7ddfdc6505b55ea82 --- pycryptoki/cryptoki.py | 1924 +++++++++++++++++++---------------- pycryptoki/defines.py | 175 +++- pycryptoki/return_values.py | 4 +- 3 files changed, 1180 insertions(+), 923 deletions(-) diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index a2c7d7a..1b70594 100755 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -1,615 +1,642 @@ -""" +''' +THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE +This file should NOT be checked into MKS or modified in any way, this file was +created by setup/initialize.py. Any changes to this file will be wiped out when +it is regenerated. + This file contains all of the ctypes definitions for the cryptoki library. The ctypes definitions outline the structures for the cryptoki C API. -""" +''' import sys from ctypes import * from pycryptoki.cryptoki_helpers import make_late_binding_function -LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 -LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 -LUNA_RET_VECTOR_TOO_SMALL = -2147483115 -LUNA_RET_VECTOR_VERSION_INVALID = -2147483111 -MSG_LAST = 54 -LUNA_RET_VECTOR_TOO_LARGE = -2147483116 -LUNA_RET_VECTOR_DUPLICATE = -2147483109 -LUNA_RET_VECTOR_TYPE_INVALID = -2147483108 -LUNA_RET_CANCEL = 65536 -LUNA_RET_MISSING_VECTOR = -2147483117 +LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE = -2147482613 +LUNA_RET_ARGUMENTS_BAD = 458752 +LUNA_RET_HIFN_INVALID_ENCRYPT_MODE = -2147482360 +LUNA_RET_SM_UNKNOWN_SESSION_TYPE = -2147482618 +LUNA_RET_KEY_UNEXTRACTABLE = 6946816 +MSG_RTC_CANT_CLEAN_TAMPER_1 = 7 +LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM = -2147482361 +LUNA_RET_SM_UNKNOWN_ACCESS_TYPE = -2147482621 +LUNA_RET_STC_OPEN_CIPHER_MISMATCH = -2147480058 +LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED = -2147482622 +LUNA_RET_N_TOO_SMALL = -2147483135 +RC_ARGUMENTS_BAD = -1073741817 +RC_VERSION_INVALID = -1073741559 +LUNA_RET_CCM_UNREMOVABLE = -2147482878 +LUNA_RET_CCM_NOT_PRESENT = -2147482880 LUNA_RET_MISSING_COMMAND_PARAMETER = -2147483107 -LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED = -2147483106 -LUNA_RET_MISSING_NUMBER_OF_VECTORS = -2147483118 -LUNA_RET_M_OF_N_IS_NOT_REQUIRED = -2147483105 -LUNA_RET_M_OF_N_IS_NOT_INITIALZED = -2147483104 -LUNA_RET_M_OF_N_PARAMETER_EXIST = -2147483112 +LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631508 +LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY = 13697042 +LUNA_RET_CAN_NOT_CREATE_SECRET_KEY = 13697041 +LUNA_RET_ATTRIBUTE_NOT_FOUND = 1179664 +LUNA_RET_MAX_OBJECT_COUNT = 8519681 +LUNA_RET_ATTRIBUTE_SENSITIVE = 1114112 +LUNA_RET_ATTRIBUTE_READ_ONLY = 1048576 +LUNA_RET_ATTRIBUTE_VALUE_INVALID = 1245184 +LUNA_RET_ATTRIBUTE_TYPE_INVALID = 1179648 +LUNA_RET_TEMPLATE_INCONSISTENT = 13697024 +LUNA_RET_MEMORY_ALLOCATION_FAILED = 3211271 +LUNA_RET_MM_FATAL_ERROR = 3211270 +LUNA_RET_MM_ITERATOR_PAST_END = 3211269 +LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE = 3211267 +LUNA_RET_MM_USAGE_ALREADY_SET = 3211266 +LUNA_RET_MM_INVALID_HANDLE = 3211265 +LUNA_RET_MM_NOT_ENOUGH_MEMORY = 3211264 +LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE = 3146246 +LUNA_RET_CL_COMMAND_MALFORMED = 3146245 +LUNA_RET_CL_TRANSMISSION_ERROR = 3146243 +LUNA_RET_CL_QUEUE_LOCATION_ERROR = 3146241 +LUNA_RET_CL_ALIGNMENT_ERROR = 3146240 +LUNA_RET_PED_CLIENT_NOT_RUNNING = 3146055 +LUNA_RET_PED_DEK_INVALID = 3146054 +LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL = 3146053 +LUNA_RET_PED_ERROR = 3146052 +LUNA_RET_PED_UNPLUGGED = 3146050 +LUNA_RET_PED_UNSUPPORTED_PROTOCOL = 3146049 +LUNA_RET_PED_ID_INVALID = 3146048 +LUNA_RET_FORMER_INVALID_ENTRY_TYPE = 3146032 +LUNA_RET_TOKEN_NOT_PRESENT = 14680064 +LUNA_RET_FLAGS_INVALID = 262144 +LUNA_RET_OK = 0 +RC_GENERAL_ERROR = -1073741822 +MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET = 30 +MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY = 29 +LUNA_RET_VECTOR_TOO_SMALL = -2147483115 +MSG_NVRAM_WRITE_FAILED = 26 +MSG_NVRAM_READ_FAILED = 25 LUNA_RET_MISSING_VALUE_FOR_N = -2147483119 -LUNA_RET_M_OF_N_SECRET_INVALID = -2147483103 -LUNA_RET_CCM_NOT_PRESENT = -2147482880 +LUNA_RET_SSK_MISSING = -2147483371 LUNA_RET_MISSING_VALUE_FOR_M = -2147483120 -LUNA_RET_CCM_NOT_SUPPORTED = -2147482879 -LUNA_RET_CCM_UNREMOVABLE = -2147482878 LUNA_RET_MISSING_WEIGHT_VALUE = -2147483121 -LUNA_RET_CCM_CERT_INVALID = -2147482877 -LUNA_RET_CCM_SIGN_INVALID = -2147482876 -LUNA_RET_TOO_MANY_WEIGHTS = -2147483122 -RC_SSL_CREATE_SSL_ERROR = -1073740025 -LUNA_RET_M_OF_N_ACTIVATION_REQUIRED = -2147483125 -LUNA_RET_CCM_FWUPDATE_DENIED = -2147482874 +LUNA_RET_HIFN_DESTINATION_OVERRUN = -2147482345 +LUNA_RET_HIFN_END_MARKER_NOT_PRESENT = -2147482346 +LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID = -2147482347 +LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID = -2147482349 LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE = -2147483126 -LUNA_RET_VECTOR_OF_DIFFERENT_SET = -2147483110 +LUNA_INVALID_PACKET_LAYOUT = -2147482352 +LUNA_HIFN_UNKNOWN_ALGORITHM = -2147482353 +LUNA_RET_HIFN_DMA_TIMED_OUT = -2147482354 +LUNA2_RET_HIFN_RESET_ERROR = -2147482356 LUNA_RET_SPLIT_ID_INVALID = -2147483127 -LUNA_RET_CCM_TOO_LARGE = 2162689 -LUNA_RET_SPLIT_DATA_INVALID = -2147483128 -LUNA_RET_SM_ACCESS_ID_INVALID = -2147482624 -LUNA_RET_MISSING_SPLITS = -2147483129 -LUNA_RET_OBJECT_DELETED = -2147483635 -LUNA_RET_TOTAL_WEIGHT_INVALID = -2147483130 +LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID = -2147482358 +LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID = -2147482362 +MSG_RTC_LOST_ALL_POWER = 17 +LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID = -2147482363 +LUNA_RET_HIFN_INVALID_MAC_MODE = -2147482364 +LUNA_RET_HIFN_INVALID_MAC_ALGORITHM = -2147482365 +LUNA_RET_HIFN_DESTINATION_COUNT_INVALID = -2147482366 +LUNA_RET_HIFN_SOURCE_COUNT_INVALID = -2147482367 +LUNA_RET_HIFN_NOT_PRESENT = -2147482368 +MSG_RTC_TAMPER_CIRCUITS_RE_ARMED = 16 +LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE = -2147482614 +LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW = -2147482615 +LUNA_RET_SM_CONTEXT_NOT_ALLOCATED = -2147482616 +LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED = -2147482617 +MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT = 15 +LUNA_RET_SM_BAD_CONTEXT_NUMBER = -2147482619 +LUNA_RET_SM_BAD_ACCESS_HANDLE = -2147482620 LUNA_RET_SM_ACCESS_ALREADY_EXISTS = -2147482623 -LUNA_RET_WEIGHT_TOO_SMALL = -2147483131 -LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED = -2147482622 -LUNA_RET_WEIGHT_TOO_LARGE = -2147483132 -LUNA_RET_M_TOO_SMALL = -2147483133 -LUNA_RET_SM_UNKNOWN_ACCESS_TYPE = -2147482621 -RC_SERVER_DISCONNECTED = -1073740540 +LUNA_RET_SM_ACCESS_ID_INVALID = -2147482624 +LUNA_RET_CCM_TOO_LARGE = 2162689 +LUNA_RET_CCM_FWUPDATE_DENIED = -2147482874 +LUNA_RET_CCM_UPDATE_DENIED = -2147482875 +LUNA_RET_CCM_SIGN_INVALID = -2147482876 +LUNA_RET_ECC_HOK_MISSING = -2147483361 +LUNA_RET_CCM_CERT_INVALID = -2147482877 +LUNA_RET_CCM_NOT_SUPPORTED = -2147482879 +LUNA_RET_M_OF_N_IS_NOT_REQUIRED = -2147483105 +MSG_RTC_RECONFIGURING_FAILED = 12 +LUNA_RET_VECTOR_TYPE_INVALID = -2147483108 +LUNA_RET_VECTOR_DUPLICATE = -2147483109 +LUNA_RET_VECTOR_OF_DIFFERENT_SET = -2147483110 +LUNA_RET_VECTOR_VERSION_INVALID = -2147483111 LUNA_RET_M_TOO_LARGE = -2147483134 -LUNA_RET_SM_BAD_ACCESS_HANDLE = -2147482620 -LUNA_RET_N_TOO_LARGE = -2147483136 -LUNA_RET_SM_BAD_CONTEXT_NUMBER = -2147482619 -LUNA_RET_KEY_NOT_ACTIVE = -2147481340 +LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 +MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS = 10 +MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED = 45 +RC_STC_RESPONSE_DECRYPT_ERROR = -1073700845 +LUNA_RET_ECC_MIC_MISSING = -2147483362 LUNA_RET_SIM_AUTHFORM_INVALID = 2097438 -RC_SOCKET_WOULDBLOCK = -1073740538 -LUNA_RET_CONTAINER_LOCKED = -2147483639 -RC_HOST_RESOLUTION_ERROR = -1073740535 -LUNA_RET_SM_UNKNOWN_SESSION_TYPE = -2147482618 LUNA_RET_INVALID_CERTIFICATE_FUNCTION = -2147483355 -LUNA_RET_UNKNOWN_COMMAND = 3145729 -LUNA_RET_HOC_MISSING = -2147483356 -LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED = -2147482617 +MSG_RTC_CANT_ACCESS = 6 LUNA_RET_ROOT_CERT_MISSING = -2147483357 -LUNA_RET_SM_CONTEXT_NOT_ALLOCATED = -2147482616 -LUNA_RET_ECC_DAC_MISSING = -2147483358 -LUNA_RET_ECC_DAK_MISSING = -2147483359 -LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW = -2147482615 +MSG_RTC_MSG_NVRAM_ZAPPING_FAILED = 3 LUNA_RET_ECC_HOC_MISSING = -2147483360 -LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE = -2147482614 -LUNA_RET_ECC_HOK_MISSING = -2147483361 -LUNA_RET_ECC_MIC_MISSING = -2147483362 -LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE = -2147482613 -LUNA_RET_SIM_CORRUPT_DATA = -2147483363 -LUNA_RET_HIFN_NOT_PRESENT = -2147482368 -LUNA_RET_SIM_VERSION_UNSUPPORTED = -2147483364 -LUNA_RET_SIM_AUTHORIZATION_FAILED = -2147483365 -LUNA_RET_HIFN_SOURCE_COUNT_INVALID = -2147482367 -LUNA_RET_CITS_DAK_MISSING = -2147483366 -LUNA_RET_HIFN_DESTINATION_COUNT_INVALID = -2147482366 +RC_MEMORY_ALLOCATION = -1073741823 LUNA_RET_HOK_MISSING = -2147483367 -LUNA_RET_BAD_DAK = -2147483368 -LUNA_RET_HIFN_INVALID_MAC_ALGORITHM = -2147482365 -LUNA_RET_DAK_MISSING = -2147483369 -RC_DATA_CORRUPTED = -1073740799 -LUNA_RET_HIFN_INVALID_MAC_MODE = -2147482364 -LUNA_RET_BAD_MAC = -2147483370 -LUNA_RET_SSK_MISSING = -2147483371 -LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID = -2147482363 +LUNA_RET_CHALLENGE_TYPE_INVALID = 2099968 LUNA_RET_BAD_DAC = -2147483372 -LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID = -2147482362 -LUNA_RET_DAC_MISSING = -2147483373 LUNA_RET_DAC_POLICY_PID_MISMATCH = -2147483374 -LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM = -2147482361 +LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE = 2099716 LUNA_RET_MAC_MISSING = -2147483375 -RC_TOKEN_STATE_INVALID = -1073740800 -LUNA_RET_HIFN_INVALID_ENCRYPT_MODE = -2147482360 LUNA_RET_INVALID_ACCESS_LEVEL = -2147483376 -LUNA_RET_MASKING_NOT_SUPPORTED = -2147483377 -LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID = -2147482359 +MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED = 44 LUNA_RET_CPK_PARAMETER_MISSING = -2147483378 -LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID = -2147482358 +RC_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE = -1073700838 +RC_STC_RESPONSE_UNEXPECTED_KEY = -1073700839 +RC_STC_RSA_DECRYPT_ERROR = -1073700840 +RC_STC_RSA_SIGN_ERROR = -1073700841 LUNA_RET_TUK_PARAMETER_MISSING = -2147483379 -LUNA_RET_TWC_PARAMETER_MISSING = -2147483380 -LUNA_RET_HIFN_DMA_ERROR = -2147482357 +RC_STC_RSA_ENCRYPT_ERROR = -1073700842 +RC_STC_REKEY_CHANNEL_MISMATCH = -1073700843 +RC_STC_RESPONSE_REPLAYED = -1073700844 +RC_STC_NO_CHANNEL = -1073700846 +RC_STC_SEQUENCE_NUM_INVALID = -1073700847 +RC_STC_CONTAINER_INVALID = -1073700848 +RC_STC_SESSION_INVALID = -1073700849 +RC_STC_CLIENT_HANDLE_INVALID = -1073700850 +RC_STC_NOT_ENABLED = -1073700851 +RC_STC_RESPONSE_BAD_MAC = -1073700852 +RC_STC_NO_SESSION_KEY = -1073700853 LUNA_RET_KCV_PARAMETER_MISSING = -2147483381 -LUNA_RET_WRAPPING_KEY_SIZE_RANGE = 18087936 +RC_STC_KEY_CONFIRMATION_FAILED = -1073700854 +RC_STC_SECOND_PHASE_KDF_ERROR = -1073700855 +RC_STC_FIRST_PHASE_KDF_ERROR = -1073700856 +RC_STC_COMPUTE_DH_KEY_ERROR = -1073700857 +RC_STC_DH_KEY_NOT_FROM_SAME_GROUP = -1073700858 +RC_STC_CIPHER_SUITE_REJECTED = -1073700859 +RC_STC_DH_KEYGEN_ERROR = -1073700860 +RC_STC_PARTITION_IDENTITY_NOT_CONFIGURED = -1073700861 +RC_STC_CLIENT_IDENTITY_NOT_CONFIGURED = -1073700862 +RC_STC_NO_CONTEXT = -1073700863 +LUNA_RET_KEY_NOT_KEKED = -2147481338 +RC_UNABLE_TO_CONNECT = -1073737472 +RC_USB_PED_OUT_OF_SYNC = -1073733610 +RC_USB_PED_TOO_MANY_CONNECTED = -1073733611 +RC_USB_PED_OPERATION_CANCELLED = -1073733612 +RC_USB_PED_NOT_RESPONDING = -1073733613 +RC_USB_PED_NOT_FOUND = -1073733614 +RC_FAILED_TO_CREATE_PROCESS = -1073733615 +RC_FILE_LOCK_ERROR = -1073733616 +RC_CMD_BLOCKED_REMOTE_PED_TUNNEL = -1073733622 +RC_FILE_LOCK_FAILED = -1073733623 +RC_UNKNOWN_COMMAND_VERSION = -1073733624 +LUNA_RET_WRAPPING_ERROR = -2147483385 +LUNA_RET_INVALID_MODULUS_SIZE = -2147483387 +LastFirmwareCode = -1073741825 +LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED = -2147483391 +LUNA_RET_ECC_BUFFER_OVERFLOW = -2147482110 +LUNA_RET_INVALID_FUF_TARGET = -2147483634 +LUNA_RET_ECC_NOT_SUPPORTED = -2147482111 +RC_OBJECT_ID_INVALID = -1073740795 +LUNA_RET_DEVICE_TIMEOUT = -2147483636 +RC_FILE_READ_ONLY = -1073740797 +LUNA_RET_CONTAINER_IS_DISABLED = -2147483638 +LUNA_RET_PE1746_ERROR = 3147911 +RC_DATA_CORRUPTED = -1073740799 +RC_TOKEN_STATE_INVALID = -1073740800 +LUNA_RET_NOT_FOUND = -2147483641 RC_OPERATION_TIMED_OUT = -1073741053 -RC_SSL_GET_CERTIFICATE_ERROR = -1073740023 -LUNA_RET_TOKEN_NOT_PRESENT = 14680064 -LUNA_RET_SP_RX_ERROR = 3146034 -LUNA_RET_PED_UNSUPPORTED_PROTOCOL = 3146049 -MSG_RESYNC = 46 -MSG_RESTART = 47 +RC_MANUFACTURING_SERIAL_NUMBER_INVALID = -1073741054 +LUNA_RET_CONTAINER_HANDLE_INVALID = -2147483647 +LUNA_RET_WRAPPING_KEY_SIZE_RANGE = 18087936 +LUNA_RET_SFNT3120_SELFTEST_FAILED = 3147810 +LUNA_RET_WRAPPED_KEY_LEN_RANGE = 17956864 +LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT = 3147790 +LUNA_RET_USER_PIN_NOT_INITIALIZED = 16908288 +LUNA_RET_SM_SESSION_READ_ONLY_EXISTS = 11993088 +LUNA_RET_SM_OTHER_USER_LOGGED_IN = 16777217 +LUNA_RET_M_OF_N_PARAMETER_EXIST = -2147483112 +LUNA_RET_INVALID_BOARD_TYPE = -2147481856 +RC_UNKNOWN_COMMAND = -1073733625 +RC_INVALID_COMMAND = -1073733626 +LUNA_RET_INVALID_IP_PACKET = -2147482112 +RC_SOCKET_CLOSED = -1073733627 +RC_REMOTE_SIDE_DISCONNECTED = -1073733628 +RC_UNKNOWN_CALLBACK_COMMAND = -1073733630 +RC_CALLBACK_ERROR = -1073733631 +RC_FAILED_TO_CREATE_THREAD = -1073733632 +RC_PARTITION_ROLE_POLICY_SET_VERSION_INVALID = -1073737724 +RC_PARTITION_ROLE_POLICY_VERSION_INVALID = -1073737725 +RC_PARTITION_ROLE_DESC_VERSION_INVALID = -1073737726 +RC_PARTITION_NOT_ACTIVATED = -1073737727 +RC_PARTITION_LOCKED = -1073737728 +RC_SESSION_SCRIPT_EXISTS = -1073739519 +RC_SSL_FAILED_HANDSHAKE = -1073740015 +RC_SSL_SYSCALL_ERROR = -1073740016 +RC_SSL_WANT_X509_LOOKUP_ERROR = -1073740017 +RC_SSL_WANT_WRITE_ERROR = -1073740018 +RC_SSL_WANT_READ_ERROR = -1073740019 +RC_SSL_GET_PEER_CERT_ERROR = -1073740020 +RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR = -1073740021 +RC_SSL_INVALID_CERT_STRUCTURE = -1073740022 +MSG_FACTORY_RESET = 53 +RC_SSL_CREATE_SSL_ERROR = -1073740025 +RC_SSL_LOAD_SERVER_CERT_ERROR = -1073740028 +RC_SSL_CIPHER_LIST_ERROR = -1073740030 +RC_SSL_ERROR = -1073740032 +RC_INVALID_ENUM_OPTION = -1073740287 +RC_NO_BUFFER = -1073740288 +RC_NO_PRIMARY_PEER = -1073740532 +RC_INVALID_CERT_HOST = -1073740534 +RC_HOST_RESOLUTION_ERROR = -1073740535 +RC_SOCKET_BAD_FD = -1073740536 +RC_SOCKET_ADDRESS_IN_USE = -1073740537 +RC_CLIENT_DISCONNECTED = -1073740539 +RC_SERVER_DISCONNECTED = -1073740540 +RC_CLIENT_MESSAGE_ERROR = -1073740541 +RC_SOCKET_ERROR = -1073740544 +RC_SIM_NOT_SUPPORTED = -1073740781 +RC_NOT_HSM_BACKUP_TOKEN = -1073740783 +RC_GROUP_NAME_INVALID = -1073740784 MSG_ZEROIZING_AFTER_DECOMMISSION = 48 -MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED = 45 -MSG_ZEROIZING_AFTER_NO_SECURE_DATA = 49 -MSG_LOG_WAS_TRUNCATED = 50 -MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED = 44 -MSG_BAD_HMAC = 51 +RC_ENDOFLIST = -1073740786 +RC_SEMAPHORE_ERROR = -1073740787 +RC_OBJECT_ALREADY_EXISTS = -1073740788 +RC_INVALID_INDEX = -1073740789 +RC_CACHE_NOT_MAPPED = -1073740791 +MSG_RESTART = 47 +RC_CACHE_DIRTY = -1073740792 +RC_LISTEN_SOCKET_INVALID = -1073740793 +RC_SOCKET_ADDRESS_INVALID = -1073740794 +LUNA_RET_M_OF_N_SECRET_INVALID = -2147483103 +LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD = -2147480310 +RC_SHUTTING_DOWN = -1073733629 +LUNA_RET_M_OF_N_IS_NOT_INITIALZED = -2147483104 +RC_PORT_INVALID = -1073739520 +RC_CERT_TYPE_INVALID = -1073739776 +LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED = -2147483106 +RC_SSL_GET_CERTIFICATE_ERROR = -1073740023 +MSG_RTC_TAMPER_2_SIGNAL = 14 +RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR = -1073740027 +RC_SSL_CERT_VERIFICATION_LOCATION_ERROR = -1073740029 +MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK = 40 +RC_SSL_CTX_ERROR = -1073740031 +MSG_RTC_ROLLED_BACK = 37 +RC_REMOTE_PEER_OFFLINE = -1073740533 +MSG_TVK_TIMESTAMP_RECOVERY_FAILED = 33 +RC_KEY_NEEDED = -1073741558 +RC_SOCKET_WOULDBLOCK = -1073740538 +LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE = 1245205 +RC_PIN_LOCKED = -1073741560 +MSG_LAST = 55 +MSG_PARTITION_STC_POLICY_SET = 54 MSG_ZEROIZING = 52 +LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE = 1245203 +MSG_BAD_HMAC = 51 +MSG_LOG_WAS_TRUNCATED = 50 +MSG_ZEROIZING_AFTER_NO_SECURE_DATA = 49 +RC_SOCKET_READ_ERROR = -1073740542 MSG_GENERATING_NEW_TVK_FAILED = 43 -MSG_FACTORY_RESET = 53 MSG_GENERATING_NEW_TVK_PASSED = 42 -MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK = 40 +RC_STC_UNEXPECTED_DH_DATA_SIZE = -1073700837 +MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK = 41 +RC_SOCKET_WRITE_ERROR = -1073740543 +LUNA_RET_OBJECT_HANDLE_INVALID = 8519680 +RC_NOT_PARTITION_BACKUP_TOKEN = -1073740782 MSG_TVK_WAS_CORRUPTED = 39 MSG_TVK_TIMESTAMP_UPDATE_FAILED = 38 +RC_CANCEL = -1073741568 MSG_TVK_TIMESTAMP_IS_TOO_OLD = 36 -RC_STC_RSA_DECRYPT_ERROR = -1073700840 +MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK = 35 MSG_TVK_TIMESTAMP_CORRUPTED = 34 MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED = 32 -MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY = 29 +MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER = 31 +RC_ASSIGNING_SAME_VALUE = -1073740785 +RC_BUFFER_TOO_SMALL = -1073741818 +RC_OPERATION_WOULD_BLOCK = -1073741819 +LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL = -2147481063 +LUNA_RET_TEMPLATE_INCOMPLETE = 13631488 MSG_TVK_WAS_LOST_DUE_TO_TAMPER = 27 -MSG_NVRAM_WRITE_FAILED = 26 -MSG_NVRAM_READ_FAILED = 25 +RC_OBJECT_NOT_IN_LIST = -1073740790 +LUNA_RET_MM_INVALID_USAGE = 3211268 +LUNA_RET_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL = -2147480054 +LUNA_RET_STC_OPEN_RESP_GEN_FAIL = -2147480055 +LUNA_RET_CL_NO_TRANSMISSION = 3146244 +LUNA_RET_CL_QUEUE_OVERLAP_ERROR = 3146242 +LUNA_RET_USER_ALREADY_ACTIVATED = -2147480309 +LUNA_RET_SP_RX_ERROR = 3146034 +LUNA_RET_SP_TX_ERROR = 3146033 +LUNA_RET_LOG_RESYNC_NEEDED = -2147480312 +LUNA_RET_LOG_BAD_TIME = -2147480314 +LUNA_RET_CANCEL = 65536 +MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING = 28 +LUNA_RET_LOG_BAD_RECORD_HMAC = -2147480315 +LUNA_RET_MISSING_VECTOR = -2147483117 MSG_RTC_MSG_NVRAM_READ_FAILED = 24 MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED = 23 MSG_RTC_CONFIGURATION_CORRUPTED = 22 +LUNA_RET_TOO_MANY_WEIGHTS = -2147483122 +LUNA_RET_M_OF_N_ACTIVATION_REQUIRED = -2147483125 MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF = 19 MSG_RTC_BATTERY_LOW = 18 -MSG_RTC_LOST_ALL_POWER = 17 -MSG_RTC_TAMPER_CIRCUITS_RE_ARMED = 16 -MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT = 15 -MSG_RTC_TAMPER_2_SIGNAL = 14 -MSG_RTC_EXTERNAL_TAMPER_LATCHED = 13 -MSG_RTC_RECONFIGURING_FAILED = 12 -MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS = 10 -MSG_RTC_CANT_CLEAN_TAMPER_2 = 9 -MSG_RTC_CANT_CLEAN_TAMPER_1 = 7 -MSG_RTC_CANT_ACCESS = 6 -MSG_RTC_CANT_INITIALIZE_I2C = 5 -LUNA2_RET_HIFN_RESET_ERROR = -2147482356 -LUNA_RET_TSN_MISMATCH = -2147483382 -MSG_RTC_MSG_NVRAM_WRITE_FAILED = 4 -LUNA_RET_HIFN_DMA_NOT_IDLE = -2147482355 +LUNA_RET_SPLIT_DATA_INVALID = -2147483128 +LUNA_RET_MISSING_SPLITS = -2147483129 +MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF = 21 +LUNA_RET_TOTAL_WEIGHT_INVALID = -2147483130 +LUNA_RET_WEIGHT_TOO_SMALL = -2147483131 +LUNA_RET_WEIGHT_TOO_LARGE = -2147483132 +LUNA_RET_M_TOO_SMALL = -2147483133 +MSG_RTC_CANT_CLEAN_POWER_LOSS = 11 +LUNA_RET_N_TOO_LARGE = -2147483136 +MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS = 8 +LUNA_RET_HOC_MISSING = -2147483356 +LUNA_RET_ECC_DAC_MISSING = -2147483358 +LUNA_RET_ECC_DAK_MISSING = -2147483359 MSG_RTC_CANT_GET_TAMPER_TIMER = 2 -LUNA_RET_UNWRAPPING_ERROR = -2147483384 -LUNA_RET_HIFN_DMA_TIMED_OUT = -2147482354 MSG_RTC_EXTERNAL_TAMPER_DETECTED = 1 -LUNA_RET_WRAPPING_ERROR = -2147483385 -LUNA_RET_INVALID_MODULUS_SIZE = -2147483387 -LUNA_HIFN_UNKNOWN_ALGORITHM = -2147482353 -LUNA_RET_INVALID_CERTIFICATE_VERSION = -2147483388 -LUNA_INVALID_PACKET_LAYOUT = -2147482352 MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC = 0 +LUNA_RET_SIM_CORRUPT_DATA = -2147483363 +LUNA_RET_SIM_VERSION_UNSUPPORTED = -2147483364 +LUNA_RET_SIM_AUTHORIZATION_FAILED = -2147483365 +LUNA_RET_CITS_DAK_MISSING = -2147483366 +LUNA_RET_BAD_DAK = -2147483368 +LUNA_RET_DAK_MISSING = -2147483369 +LUNA_RET_BAD_MAC = -2147483370 +LUNA_RET_DAC_MISSING = -2147483373 +MSG_RTC_ZEROIZED_ON_POWER_LOSS = 20 +LUNA_RET_MASKING_NOT_SUPPORTED = -2147483377 +LUNA_RET_TWC_PARAMETER_MISSING = -2147483380 +LUNA_RET_TSN_MISMATCH = -2147483382 +LUNA_RET_INVALID_PRIVATE_KEY_TYPE = -2147483383 +LUNA_RET_UNWRAPPING_ERROR = -2147483384 +LUNA_RET_INVALID_CERTIFICATE_VERSION = -2147483388 LUNA_RET_INVALID_CERTIFICATE_TYPE = -2147483389 LUNA_RET_INVALID_CERTIFICATE_DATA = -2147483390 -LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM = -2147482351 -LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED = -2147483391 +LUNA_RET_CB_PROT_DATA_INVALID = -2147481047 LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS = -2147483392 LUNA_RET_INVALID_FUF_VERSION = -2147483632 -LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID = -2147482349 LUNA_RET_INVALID_FUF_HEADER = -2147483633 -LUNA_RET_N_TOO_SMALL = -2147483135 -LUNA_RET_HIFN_INVALID_PAD_ALGORITHM = -2147482348 -LUNA_RET_INVALID_FUF_TARGET = -2147483634 -LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID = -2147482347 -LUNA_RET_DEVICE_TIMEOUT = -2147483636 -LUNA_RET_HIFN_END_MARKER_NOT_PRESENT = -2147482346 +LUNA_RET_OBJECT_DELETED = -2147483635 +RC_FILE_ERROR = -1073740796 LUNA_RET_SECURITY_PARAMETER_MISSING = -2147483637 -LUNA_RET_CONTAINER_IS_DISABLED = -2147483638 -LUNA_RET_HIFN_DESTINATION_OVERRUN = -2147482345 -LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO = -2147482344 +RC_FILE_NAME_INVALID = -1073740798 +LUNA_RET_CONTAINER_LOCKED = -2147483639 LUNA_RET_TOO_MANY_CONTAINERS = -2147483640 -LUNA_RET_NOT_FOUND = -2147483641 -LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO = -2147482343 +RC_RESET_FAILED = -1073741052 LUNA_RET_AGAIN = -2147483642 -LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO = -2147482342 -LUNA_RET_INVALID_PADDING_TYPE = -2147483646 -LUNA_RET_CONTAINER_HANDLE_INVALID = -2147483647 -LUNA_RET_HIFN_DMA_INVALID_REVISION = -2147482320 +LUNA_RET_INVALID_PADDING_TYPE = -2147483646 +RC_MANUFACTURING_TOKEN_NOT_PRESENT = -1073741055 LUNA_RET_ERROR = -2147483648 -LUNA_RET_MTK_ZEROIZED = -2147482319 LUNA_RET_CERT_VERSION_NOT_SUPPORTED = 3146496 LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT = 18153472 -LUNA_RET_MTK_STATE_INVALID = -2147482318 -LUNA_RET_MTK_SPLIT_INVALID = -2147482317 LUNA_RET_WRAPPING_KEY_HANDLE_INVALID = 18022400 -LUNA_RET_WRAPPED_KEY_LEN_RANGE = 17956864 -LUNA_RET_INVALID_IP_PACKET = -2147482112 LUNA_RET_WRAPPED_KEY_INVALID = 17825792 -LUNA_RET_INVALID_BOARD_TYPE = -2147481856 LUNA_RET_USER_TYPE_INVALID = 16973824 -LUNA_RET_HIFN6500_NOT_PRESENT = 3147777 LUNA_RET_SM_NOT_LOGGED_IN = 16842753 -LUNA_RET_HIFN6500_RESET_TIMEOUT = 3147778 LUNA_RET_USER_NOT_LOGGED_IN = 16842752 -LUNA_RET_SM_SESSION_READ_ONLY_EXISTS = 11993088 -LUNA_RET_HIFN6500_DATA_LINES_BROKEN = 3147779 -LUNA_RET_SM_OTHER_USER_LOGGED_IN = 16777217 -LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN = 3147780 LUNA_RET_USER_ALREADY_LOGGED_IN = 16777216 LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT = 15859712 LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE = 15794176 -LUNA_RET_HIFN6500_RNG_FAILED = 3147782 LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID = 15728640 LUNA_RET_SIGNATURE_LEN_RANGE = 12648448 LUNA_RET_SIGNATURE_INVALID = 12582912 -LUNA_RET_HIFN6500_RNG_UNDERFLOW = 3147784 LUNA_RET_SM_SESSION_HANDLE_INVALID = 11730944 +LUNA_RET_CB_REMOTE_CLOSED = -2147481053 LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS = 11665408 -LUNA_RET_HIFN6500_ALU_TIMEOUT = 3147785 LUNA_RET_SM_PIN_EXPIRED = 10682368 -LUNA_RET_HIFN6500_INVALID_PARAMETERS = 3147786 LUNA_RET_UM_PIN_LEN_RANGE = 10616832 +LUNA_RET_UM_PIN_INVALID = 10551296 LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED = 10485762 -LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH = 3147787 LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED = 10485761 -LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS = 3147788 LUNA_RET_UM_PIN_INCORRECT = 10485760 LUNA_RET_OPERATION_NOT_INITIALIZED = 9502720 -LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS = 3147789 LUNA_RET_OPERATION_ACTIVE = 9437184 -LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT = 3147790 LUNA_RET_MECHANISM_PARAM_INVALID = 7405568 LUNA_RET_MECHANISM_INVALID = 7340032 -LUNA_RET_TEST_VS_BSAFE_FAILED = 3147808 LUNA_RET_KEY_HANDLE_INVALID = 6291456 -LUNA_RET_SFNT3120_ERROR = 3147809 LUNA_RET_FUNCTION_CANCELED = 5242880 LUNA_RET_ENCRYPTED_DATA_LEN_RANGE = 4259840 -LUNA_RET_SFNT3120_SELFTEST_FAILED = 3147810 LUNA_RET_ENCRYPTED_DATA_INVALID = 4194304 -LUNA_RET_SFNT3120_CRC = 3147811 LUNA_RET_SM_MEMORY_ALLOCATION_ERROR = 3211523 LUNA_RET_SM_SESSION_REALLOC_ERROR = 3211522 -LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT = 3147812 LUNA_RET_SM_ACCESS_REALLOC_ERROR = 3211521 LUNA_RET_TOKEN_LOCKED_OUT_STC = 3145994 LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST = 3145993 -LUNA_RET_ISES_INIT_FAILED = 3147905 +MSG_RESYNC = 46 LUNA_RET_TOKEN_LOCKED_OUT_CCM = 3145992 -LUNA_RET_ISES_LNAU_TEST_FAILED = 3147906 LUNA_RET_TOKEN_LOCKED_OUT_OH = 3145991 -LUNA_RET_USER_PIN_NOT_INITIALIZED = 16908288 LUNA_RET_TOKEN_LOCKED_OUT_PM = 3145990 -LUNA_RET_ISES_RNG_TEST_FAILED = 3147907 LUNA_RET_TOKEN_LOCKED_OUT_CA = 3145989 -LUNA_RET_ISES_CMD_FAILED = 3147908 +LUNA_RET_TOKEN_LOCKED_OUT_RN = 3145988 LUNA_RET_TOKEN_LOCKED_OUT_SM = 3145987 -LUNA_RET_ISES_CMD_PARAMETER_INVALID = 3147909 LUNA_RET_TOKEN_LOCKED_OUT_UM = 3145986 -LUNA_RET_ISES_TEST_VS_BSAFE_FAILED = 3147910 +LUNA_RET_TOKEN_LOCKED_OUT_MM = 3145985 LUNA_RET_TOKEN_LOCKED_OUT_CL = 3145984 +LUNA_RET_RECALCULATE_K = 3145781 LUNA_RET_RIPEMD160_SELF_TEST_FAILURE = 3145780 LUNA_RET_INCOMPATIBLE = 3145764 LUNA_RET_SELF_TEST_FAILURE = 3145763 -LUNA_RET_ECC_BUFFER_OVERFLOW = -2147482110 -RC_SEMAPHORE_ERROR = -1073740787 -LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE = 3145762 -LUNA_RET_ECC_POINT_INVALID = -2147482109 -LUNA_RET_RETRY = 3145761 -LUNA_RET_FLAGS_INVALID = 262144 -LUNA_RET_NOT_READY = 3145760 -LUNA_RET_ECC_SELF_TEST_FAILURE = -2147482108 -LUNA_RET_TIMEOUT = 3145759 -LUNA_RET_ECC_UNKNOWN_CURVE = -2147482107 -LUNA_RET_COUNTER_WRAPAROUND = 3145758 -LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL = 3145757 -LUNA_RET_KCDSA_SELF_TEST_FAILURE = 3145756 -LUNA_RET_KCDSA_PARAM_GEN_FAILURE = 3145755 -LUNA_RET_HA_NOT_SUPPORTED = -2147481344 -LUNA_RET_HAS160_SELF_TEST_FAILURE = 3145754 -LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE = 3145753 -LUNA_RET_HA_USER_NOT_INITIALIZED = -2147481343 -LUNA_RET_AES_SELF_TEST_FAILURE = 3145752 -LUNA_RET_SEED_SELF_TEST_FAILURE = 3145751 -LUNA_RET_HSM_STORAGE_FULL = -2147481342 -LUNA_RET_DSA_SELF_TEST_FAILURE = 3145750 -LUNA_RET_DSA_PARAM_GEN_FAILURE = 3145749 -LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL = -2147481341 -LUNA_RET_SM_TSV_MISSING = 3145747 -LUNA_RET_UM_TSN_MISSING = 3145746 -LUNA_RET_SM_UNKNOWN_COMMAND = 3145745 -LUNA_RET_RNG_SELF_TEST_FAILURE = 3145744 -LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD = 3145743 -LUNA_RET_RM_ELEMENT_VALUE_INVALID = 2099712 -LUNA_RET_RC5_SELF_TEST_FAILURE = 3145742 -LUNA_RET_RC4_SELF_TEST_FAILURE = 3145741 -LUNA_RET_RC2_SELF_TEST_FAILURE = 3145740 -LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED = 3147781 -RC_STC_RSA_SIGN_ERROR = -1073700841 -LUNA_RET_LOG_FILE_NOT_OPEN = -2147480320 -LUNA_RET_HIFN6500_RNG_TIMEOUT = 3147783 -RC_CLIENT_MESSAGE_ERROR = -1073740541 -LUNA_RET_CB_NO_MEMORY = -2147481085 -LUNA_RET_CCM_UPDATE_DENIED = -2147482875 -LUNA_RET_RSA_SELF_TEST_FAILURE = 3145739 -LUNA_RET_RM_ELEMENT_ID_INVALID = 2099713 -LUNA_RET_SHA_SELF_TEST_FAILURE = 3145738 -LUNA_RET_MD2_SELF_TEST_FAILURE = 3145736 -LUNA_RET_RM_NO_MEMORY = 3213826 -LUNA_RET_CAST3_SELF_TEST_FAILURE = 3145734 -LUNA_RET_CAST_SELF_TEST_FAILURE = 3145733 -LUNA_RET_DES_SELF_TEST_FAILURE = 3145732 -LUNA_RET_RNG_ERROR = 3145731 -LUNA_RET_DEVICE_ERROR = 3145728 -LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE = 2099716 -LUNA_RET_DATA_LEN_RANGE = 2162688 -LUNA_RET_410_BUFFER_TOO_SMALL = 2097174 -LUNA_RET_BUFFER_TOO_SMALL = 22020096 -LUNA_RET_ISES_ERROR = 3147904 -LUNA_RET_CL_COMMAND_NON_BACKUP = 5505026 -LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE = 2099717 -LUNA_RET_NO_OFFBOARD_STORAGE = 5505025 -LUNA_RET_FUNCTION_NOT_SUPPORTED = 5505024 -LUNA_RET_NO_RNG_SEED = 2097173 -LUNA_RET_SM_DATA_INVALID = 2097154 -LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL = 68102 -LUNA_RET_TPV_INVALID = 2097153 -LUNA_RET_DATA_INVALID = 2097152 -LUNA_RET_INVALID_ENTRY_TYPE = 458753 -LUNA_RET_ARGUMENTS_BAD = 458752 -LUNA_RET_KEY_NOT_UNWRAPPABLE = 6881281 -LUNA_RET_KEY_NOT_WRAPPABLE = 6881280 -LUNA_RET_KEY_SENSITIVE = 6356992 -LUNA_RET_SM_KEY_SIZE_ERROR = 6422529 -LUNA_RET_KEY_TYPE_INCONSISTENT = 6488064 -LUNA_RET_KEY_INVALID_FOR_OPERATION = 6488065 -LUNA_RET_KEY_UNEXTRACTABLE = 6946816 -LUNA_RET_LICENSE_ID_UNKNOWN = 2099720 -LUNA_RET_KEY_EXTRACTABLE = 6946817 -LUNA_RET_KEY_INDIGESTIBLE = 6750208 -RC_ASSIGNING_SAME_VALUE = -1073740785 -RC_GROUP_NAME_INVALID = -1073740784 -RC_ENDOFLIST = -1073740786 -RC_NOT_HSM_BACKUP_TOKEN = -1073740783 -RC_NOT_PARTITION_BACKUP_TOKEN = -1073740782 -RC_SIM_NOT_SUPPORTED = -1073740781 -RC_SOCKET_ERROR = -1073740544 -RC_OBJECT_ALREADY_EXISTS = -1073740788 -RC_SOCKET_WRITE_ERROR = -1073740543 -RC_SOCKET_READ_ERROR = -1073740542 -RC_INVALID_INDEX = -1073740789 -RC_OBJECT_NOT_IN_LIST = -1073740790 -RC_CLIENT_DISCONNECTED = -1073740539 -RC_CACHE_NOT_MAPPED = -1073740791 -RC_CACHE_DIRTY = -1073740792 -RC_SOCKET_BAD_FD = -1073740536 -RC_LISTEN_SOCKET_INVALID = -1073740793 -RC_SOCKET_ADDRESS_INVALID = -1073740794 -RC_OBJECT_ID_INVALID = -1073740795 -RC_INVALID_CERT_HOST = -1073740534 -RC_FILE_ERROR = -1073740796 -RC_FILE_READ_ONLY = -1073740797 -RC_FILE_NAME_INVALID = -1073740798 -RC_INVALID_ENUM_OPTION = -1073740287 -RC_SSL_ERROR = -1073740032 -RC_RESET_FAILED = -1073741052 -RC_SSL_CTX_ERROR = -1073740031 -LUNA_RET_OK = 0 -RC_MANUFACTURING_SERIAL_NUMBER_INVALID = -1073741054 -RC_SSL_CIPHER_LIST_ERROR = -1073740030 -LUNA_RET_FORMER_INVALID_ENTRY_TYPE = 3146032 -LUNA_RET_SP_TX_ERROR = 3146033 -RC_MANUFACTURING_TOKEN_NOT_PRESENT = -1073741055 -RC_SSL_CERT_VERIFICATION_LOCATION_ERROR = -1073740029 -LUNA_RET_PED_ID_INVALID = 3146048 RC_MANUFACTURING_NO_CONFIG_AVAILABLE = -1073741056 -LUNA_RET_PED_UNPLUGGED = 3146050 RC_DER_CLASS_INVALID = -1073741312 -RC_SSL_LOAD_SERVER_CERT_ERROR = -1073740028 -LUNA_RET_ECC_RESULT_AT_INF = -2147482106 -RC_USER_NAME_IN_USE = -1073741557 -RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR = -1073740027 -RC_KEY_NEEDED = -1073741558 -LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL = 3146053 -RC_VERSION_INVALID = -1073741559 -RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR = -1073740026 -RC_PIN_LOCKED = -1073741560 RC_CHALLENGE_BUFFER_SIZE = -1073741561 -LUNA_RET_PED_DEK_INVALID = 3146054 RC_NON_CRYPTOKI_ELEMENT_CLONE = -1073741562 -RC_SSL_LOAD_CLIENT_CERT_ERROR = -1073740024 RC_FUNCTION_NOT_SUPPORTED = -1073741563 RC_TOKEN_NOT_PRESENT = -1073741564 -LUNA_RET_POLICY_NOT_FOUND = 2099730 -RC_STC_UNEXPECTED_DH_DATA_SIZE = -1073700837 -RC_PIN_INVALID = -1073741565 -RC_SSL_INVALID_CERT_STRUCTURE = -1073740022 -LUNA_RET_PED_CLIENT_NOT_RUNNING = 3146055 RC_DATA_INVALID = -1073741566 -RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR = -1073740021 -LUNA_RET_CL_QUEUE_LOCATION_ERROR = 3146241 -LUNA_RET_CL_ALIGNMENT_ERROR = 3146240 -RC_STC_RESPONSE_UNEXPECTED_KEY = -1073700839 -LUNA_RET_CL_NO_TRANSMISSION = 3146244 -LUNA_RET_CL_COMMAND_MALFORMED = 3146245 -LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE = 3146246 -LUNA_RET_RM_CONFIG_ILLEGAL = 2099728 -LUNA_RET_MM_NOT_ENOUGH_MEMORY = 3211264 -LUNA_RET_BAD_SN = 2099729 -LUNA_RET_CL_TRANSMISSION_ERROR = 3146243 -LUNA_RET_CL_QUEUE_OVERLAP_ERROR = 3146242 -RC_SSL_WANT_READ_ERROR = -1073740019 -LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE = 3211267 -LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE = 2099727 -LUNA_RET_MM_INVALID_USAGE = 3211268 -LUNA_RET_MM_ITERATOR_PAST_END = 3211269 -LUNA_RET_MM_FATAL_ERROR = 3211270 -LUNA_RET_TEMPLATE_INCOMPLETE = 13631488 -LUNA_RET_BAD_FW_VERSION = 2099726 -LUNA_RET_TEMPLATE_INCONSISTENT = 13697024 -LUNA_RET_ATTRIBUTE_TYPE_INVALID = 1179648 -RC_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE = -1073700838 -LUNA_RET_MM_USAGE_ALREADY_SET = 3211266 -LUNA_RET_MM_INVALID_HANDLE = 3211265 -LUNA_RET_ATTRIBUTE_VALUE_INVALID = 1245184 RC_SLOT_ID_INVALID = -1073741567 -RC_CANCEL = -1073741568 -RC_ARGUMENTS_BAD = -1073741817 -RC_BUFFER_TOO_SMALL = -1073741818 -RC_OPERATION_WOULD_BLOCK = -1073741819 -RC_SSL_WANT_WRITE_ERROR = -1073740018 +RC_SSL_LOAD_CLIENT_CERT_ERROR = -1073740024 +LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 RC_UNEXPECTED = -1073741820 -RC_SSL_GET_PEER_CERT_ERROR = -1073740020 -RC_SSL_WANT_X509_LOOKUP_ERROR = -1073740017 RC_POINTER_INVALID = -1073741821 -RC_GENERAL_ERROR = -1073741822 -RC_SSL_SYSCALL_ERROR = -1073740016 -RC_MEMORY_ALLOCATION = -1073741823 -RC_SSL_FAILED_HANDSHAKE = -1073740015 RC_RC_ERROR = -1073741824 RC_OK = 0 -RC_CERT_TYPE_INVALID = -1073739776 LUNA_RET_STC_ACTIVATE_RESP_GEN_FAIL = -2147480052 LUNA_RET_STC_ACTIVATE_MACTAG_V_GEN_FAIL = -2147480053 -RC_PORT_INVALID = -1073739520 -LUNA_RET_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL = -2147480054 -RC_SESSION_SCRIPT_EXISTS = -1073739519 -LUNA_RET_STC_OPEN_RESP_GEN_FAIL = -2147480055 LUNA_RET_STC_OPEN_KEY_MATERIAL_GEN_FAIL = -2147480056 -RC_PARTITION_LOCKED = -1073737728 LUNA_RET_STC_OPEN_DHNIST_PUBKEY_ERROR = -2147480057 -RC_PARTITION_NOT_ACTIVATED = -1073737727 -LUNA_RET_STC_OPEN_CIPHER_MISMATCH = -2147480058 LUNA_RET_STC_NO_CHANNEL = -2147480059 -RC_FAILED_TO_CREATE_THREAD = -1073733632 LUNA_RET_STC_SEQUENCE_NUM_INVALID = -2147480060 -RC_CALLBACK_ERROR = -1073733631 LUNA_RET_STC_CONTAINER_INVALID = -2147480061 LUNA_RET_STC_SESSION_INVALID = -2147480062 -RC_UNKNOWN_CALLBACK_COMMAND = -1073733630 LUNA_RET_STC_CLIENT_HANDLE_INVALID = -2147480063 -RC_SHUTTING_DOWN = -1073733629 LUNA_RET_STC_NOT_ENABLED = -2147480064 LUNA_RET_STC_CHANNEL_REALLOC_ERROR = 3211264 -RC_REMOTE_SIDE_DISCONNECTED = -1073733628 LUNA_RET_TIME_NOT_INITIALIZED = -2147480308 -RC_SOCKET_CLOSED = -1073733627 -LUNA_RET_USER_ALREADY_ACTIVATED = -2147480309 -LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD = -2147480310 -RC_INVALID_COMMAND = -1073733626 LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS = -2147480311 -RC_NO_BUFFER = -1073740288 -RC_UNKNOWN_COMMAND = -1073733625 -LUNA_RET_BAD_PPID = 2099725 -LUNA_RET_ATTRIBUTE_SENSITIVE = 1114112 -LUNA_RET_ATTRIBUTE_READ_ONLY = 1048576 -MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET = 30 -LUNA_RET_MAX_OBJECT_COUNT = 8519681 -LUNA_RET_ATTRIBUTE_NOT_FOUND = 1179664 -LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE = 68108 -LUNA_RET_CAN_NOT_CREATE_SECRET_KEY = 13697041 -LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY = 13697042 -LUNA_RET_OBJECT_HANDLE_INVALID = 8519680 -LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE = 1245203 -LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631508 -LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE = 1245205 -LUNA_RET_OPERATION_RESTRICTED = 68107 -LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631510 -LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL = 6815745 -LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED = 13697048 -LUNA_RET_RM_POLICY_WRITE_RESTRICTED = 68106 -LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION = 1048601 -RC_SOCKET_ADDRESS_IN_USE = -1073740537 -LUNA_RET_LOG_RESYNC_NEEDED = -2147480312 LUNA_RET_LOG_AUDIT_NOT_INITIALIZED = -2147480313 -RC_UNKNOWN_COMMAND_VERSION = -1073733624 -LUNA_RET_LOG_BAD_TIME = -2147480314 -RC_FILE_LOCK_FAILED = -1073733623 -LUNA_RET_LOG_BAD_RECORD_HMAC = -2147480315 +LUNA_RET_CB_RETRY = -2147481083 LUNA_RET_LOG_NO_KCV = -2147480316 -RC_CMD_BLOCKED_REMOTE_PED_TUNNEL = -1073733622 LUNA_RET_LOG_FULL = -2147480317 -RC_FILE_LOCK_ERROR = -1073733616 LUNA_RET_LOG_BAD_FILE_NAME = -2147480318 -LUNA_RET_LOG_FILE_WRITE_ERROR = -2147480319 -RC_FAILED_TO_CREATE_PROCESS = -1073733615 -RC_USB_PED_NOT_FOUND = -1073733614 +LUNA_RET_CB_TIMEOUT = -2147481084 +LUNA_RET_LOG_FILE_WRITE_ERROR = -2147480319 +LUNA_RET_LOG_FILE_NOT_OPEN = -2147480320 LUNA_RET_STATE_UNSAVEABLE = 25165824 LUNA_RET_SAVED_STATE_INVALID = 23068672 -RC_USB_PED_NOT_RESPONDING = -1073733613 -LUNA_RET_CB_PROT_DATA_INVALID = -2147481047 -RC_USB_PED_OPERATION_CANCELLED = -1073733612 +LUNA_RET_FM_ID_INVALID = -2147480832 LUNA_RET_CB_SYNC_ERROR = -2147481048 LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE = -2147481049 -RC_USB_PED_TOO_MANY_CONNECTED = -1073733611 LUNA_RET_CB_MUST_WRITE = -2147481050 -RC_USB_PED_OUT_OF_SYNC = -1073733610 LUNA_RET_CB_MUST_READ = -2147481051 LUNA_RET_CB_REMOTE_ABANDONED = -2147481052 -RC_UNABLE_TO_CONNECT = -1073737472 -LUNA_RET_CB_REMOTE_CLOSED = -2147481053 -RC_STC_NO_CONTEXT = -1073700863 LUNA_RET_CB_REMOTE_ABORT = -2147481054 LUNA_RET_CB_ID_INVALID = -2147481055 -RC_STC_CLIENT_IDENTITY_NOT_CONFIGURED = -1073700862 LUNA_RET_CB_HANDLE_INVALID = -2147481056 -RC_STC_PARTITION_IDENTITY_NOT_CONFIGURED = -1073700861 -LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL = -2147481063 LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL = -2147481064 -RC_STC_DH_KEYGEN_ERROR = -1073700860 LUNA_RET_CB_HIOS_STATE_INVALID = -2147481065 -RC_STC_CIPHER_SUITE_REJECTED = -1073700859 LUNA_RET_CB_HIOS_RECV_TIMEOUT = -2147481066 LUNA_RET_CB_HIOS_SEND_TIMEOUT = -2147481067 -RC_STC_DH_KEY_NOT_FROM_SAME_GROUP = -1073700858 LUNA_RET_CB_HIOS_IO_ERROR = -2147481068 -RC_STC_COMPUTE_DH_KEY_ERROR = -1073700857 LUNA_RET_CB_HIOS_CANCELED = -2147481069 +RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR = -1073740026 LUNA_RET_CB_HIOS_CLOSED = -2147481070 -RC_STC_FIRST_PHASE_KDF_ERROR = -1073700856 +LUNA_RET_VECTOR_TOO_LARGE = -2147483116 LUNA_RET_CB_HIOS_ID_INVALID = -2147481071 -RC_STC_SECOND_PHASE_KDF_ERROR = -1073700855 +LUNA_RET_MUTEX_BAD = 27262976 LUNA_RET_CB_HIOS_HANDLE_INVALID = -2147481072 LUNA_RET_CB_SYS_ERROR = -2147481081 -RC_STC_KEY_CONFIRMATION_FAILED = -1073700854 -MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK = 41 -MSG_RTC_ROLLED_BACK = 37 -MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK = 35 -MSG_TVK_TIMESTAMP_RECOVERY_FAILED = 33 -LUNA_RET_MD5_SELF_TEST_FAILURE = 3145737 -MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER = 31 -LUNA_RET_CAST5_SELF_TEST_FAILURE = 3145735 -MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING = 28 -LastFirmwareCode = -1073741825 -LUNA_RET_RM_BAD_HSM_PARAMS = 3148291 -LUNA_RET_TOKEN_LOCKED_OUT = 3145730 -LUNA_RET_GENERAL_ERROR = 327680 -MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF = 21 -MSG_RTC_ZEROIZED_ON_POWER_LOSS = 20 -MSG_RTC_MSG_NVRAM_ZAPPING_FAILED = 3 -LUNA_RET_SM_UNKNOWN_TOSM_STATE = 3145748 -LUNA_RET_TOKEN_LOCKED_OUT_RN = 3145988 -MSG_RTC_CANT_CLEAN_POWER_LOSS = 11 -LUNA_RET_TOKEN_LOCKED_OUT_MM = 3145985 -LUNA_RET_PE1746_ERROR = 3147911 -LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES = 68103 -MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS = 8 -LUNA_RET_ECC_NOT_SUPPORTED = -2147482111 -LUNA_RET_INVALID_PRIVATE_KEY_TYPE = -2147483383 -LUNA_RET_KEY_SIZE_RANGE = 6422528 -LUNA_RET_LICENSE_CAPACITY_EXCEEDED = 68105 LUNA_RET_CB_ABORTED = -2147481082 -LUNA_RET_CB_RETRY = -2147481083 -RC_STC_RESPONSE_BAD_MAC = -1073700852 -LUNA_RET_CB_TIMEOUT = -2147481084 -RC_STC_NOT_ENABLED = -1073700851 +LUNA_RET_CB_NO_MEMORY = -2147481085 LUNA_RET_CB_PARAM_INVALID = -2147481086 -RC_STC_CLIENT_HANDLE_INVALID = -1073700850 LUNA_RET_CB_NOT_SUPPORTED = -2147481087 -LUNA_RET_PED_ERROR = 3146052 -RC_STC_NO_SESSION_KEY = -1073700853 -LUNA_RET_CHALLENGE_TYPE_INVALID = 2099968 -RC_STC_RSA_ENCRYPT_ERROR = -1073700842 +LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS = 2100229 +LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST = 2100227 +LUNA_RET_STORAGE_TYPE_INCONSISTENT = 2100228 +LUNA_RET_OH_OBJECT_TYPE_INVALID = 3148801 +LUNA_RET_OH_OBJECT_VERSION_INVALID = 3148800 +LUNA_RET_CHALLENGE_INVALID = 2099972 +LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT = 68355 LUNA_RET_CHALLENGE_REQUIRES_PED = 68353 +LUNA_RET_BAD_SN = 2099729 +LUNA_RET_RM_CONFIG_ILLEGAL = 2099728 +LUNA_RET_OH_OBJECT_ALREADY_EXISTS = 68610 +LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE = 2099727 +LUNA_RET_BAD_FW_VERSION = 2099726 +LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE = 68108 +LUNA_RET_OPERATION_RESTRICTED = 68107 +LUNA_RET_RM_POLICY_WRITE_RESTRICTED = 68106 +LUNA_RET_LICENSE_CAPACITY_EXCEEDED = 68105 +LUNA_RET_LICENSE_ID_UNKNOWN = 2099720 +LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES = 68103 +LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL = 68102 +LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE = 2099717 +MSG_RTC_EXTERNAL_TAMPER_LATCHED = 13 +LUNA_RET_NOT_READY = 3145760 +LUNA_RET_TIMEOUT = 3145759 +LUNA_RET_COUNTER_WRAPAROUND = 3145758 +LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL = 3145757 +LUNA_RET_KCDSA_SELF_TEST_FAILURE = 3145756 +LUNA_RET_KCDSA_PARAM_GEN_FAILURE = 3145755 +LUNA_RET_HAS160_SELF_TEST_FAILURE = 3145754 +LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE = 3145753 +LUNA_RET_AES_SELF_TEST_FAILURE = 3145752 +LUNA_RET_SEED_SELF_TEST_FAILURE = 3145751 +LUNA_RET_DSA_SELF_TEST_FAILURE = 3145750 +LUNA_RET_DSA_PARAM_GEN_FAILURE = 3145749 +LUNA_RET_SM_UNKNOWN_TOSM_STATE = 3145748 +LUNA_RET_SM_TSV_MISSING = 3145747 +LUNA_RET_UM_TSN_MISSING = 3145746 +LUNA_RET_SM_UNKNOWN_COMMAND = 3145745 +LUNA_RET_CHALLENGE_RESPONSE_INCORRECT = 10488579 +LUNA_RET_RNG_SELF_TEST_FAILURE = 3145744 +LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD = 3145743 +LUNA_RET_RC5_SELF_TEST_FAILURE = 3145742 +LUNA_RET_RC2_SELF_TEST_FAILURE = 3145740 +LUNA_RET_MISSING_NUMBER_OF_VECTORS = -2147483118 +LUNA_RET_RSA_SELF_TEST_FAILURE = 3145739 LUNA_RET_CHALLENGE_NOT_REQUIRED = 68354 +LUNA_RET_SHA_SELF_TEST_FAILURE = 3145738 +LUNA_RET_CAST5_SELF_TEST_FAILURE = 3145735 +LUNA_RET_CAST_SELF_TEST_FAILURE = 3145733 +LUNA_RET_DES_SELF_TEST_FAILURE = 3145732 +LUNA_RET_RNG_ERROR = 3145731 +LUNA_RET_TOKEN_LOCKED_OUT = 3145730 +LUNA_RET_UNKNOWN_COMMAND = 3145729 +LUNA_RET_DEVICE_ERROR = 3145728 +LUNA_RET_GENERAL_ERROR = 327680 +LUNA_RET_410_BUFFER_TOO_SMALL = 2097174 +LUNA_RET_BUFFER_TOO_SMALL = 22020096 +LUNA_RET_NO_OFFBOARD_STORAGE = 5505025 +LUNA_RET_POLICY_NOT_FOUND = 2099730 +LUNA_RET_NO_RNG_SEED = 2097173 +LUNA_RET_SM_DATA_INVALID = 2097154 +LUNA_RET_TPV_INVALID = 2097153 +LUNA_RET_DATA_INVALID = 2097152 +LUNA_RET_INVALID_ENTRY_TYPE = 458753 +LUNA_RET_KEY_NOT_UNWRAPPABLE = 6881281 +LUNA_RET_KEY_NOT_WRAPPABLE = 6881280 +LUNA_RET_KEY_INDIGESTIBLE = 6750208 +LUNA_RET_KEY_EXTRACTABLE = 6946817 LUNA_RET_KEY_PARITY = 6488066 -RC_STC_REKEY_CHANNEL_MISMATCH = -1073700843 -LUNA_RET_CHALLENGE_RESPONSE_INCORRECT = 10488579 -RC_STC_RESPONSE_REPLAYED = -1073700844 -LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT = 68355 -LUNA_RET_CHALLENGE_INVALID = 2099972 -RC_STC_RESPONSE_DECRYPT_ERROR = -1073700845 -LUNA_RET_OH_OBJECT_VERSION_INVALID = 3148800 -RC_STC_NO_CHANNEL = -1073700846 -LUNA_RET_OH_OBJECT_TYPE_INVALID = 3148801 -LUNA_RET_OH_OBJECT_ALREADY_EXISTS = 68610 -RC_STC_SEQUENCE_NUM_INVALID = -1073700847 +LUNA_RET_KEY_INVALID_FOR_OPERATION = 6488065 +LUNA_RET_KEY_TYPE_INCONSISTENT = 6488064 +LUNA_RET_SM_KEY_SIZE_ERROR = 6422529 +LUNA_RET_KEY_SIZE_RANGE = 6422528 +LUNA_RET_KEY_SENSITIVE = 6356992 +LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION = 1048601 +LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED = 13697048 +LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL = 6815745 +LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631510 +LUNA_RET_BAD_PPID = 2099725 +MSG_RTC_CANT_CLEAN_TAMPER_2 = 9 +RC_USER_NAME_IN_USE = -1073741557 +LUNA_RET_RM_BAD_HSM_PARAMS = 3148291 +LUNA_RET_RM_NO_MEMORY = 3213826 +LUNA_RET_RM_ELEMENT_ID_INVALID = 2099713 +LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE = 3145762 +LUNA_RET_RM_ELEMENT_VALUE_INVALID = 2099712 +LUNA_RET_SESSION_HANDLE_INVALID_FOR_FP = -2147481335 +LUNA_RET_OPERATION_INVALID_FOR_FP = -2147481336 +LUNA_RET_MECHANISM_INVALID_FOR_FP = -2147481337 +LUNA_RET_KEY_CANNOT_BE_KEKED = -2147481339 +LUNA_RET_RETRY = 3145761 +LUNA_RET_KEY_NOT_ACTIVE = -2147481340 +LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL = -2147481341 +LUNA_RET_HSM_STORAGE_FULL = -2147481342 +LUNA_RET_HA_USER_NOT_INITIALIZED = -2147481343 +LUNA_RET_HA_NOT_SUPPORTED = -2147481344 +LUNA_RET_ECC_RESULT_AT_INF = -2147482106 +LUNA_RET_ECC_UNKNOWN_CURVE = -2147482107 +LUNA_RET_ECC_SELF_TEST_FAILURE = -2147482108 +LUNA_RET_ECC_POINT_INVALID = -2147482109 +LUNA_RET_RNG_RESEED_TOO_EARLY = 3147914 +LUNA_RET_RNG_RESEED_REQUIRED = 3147913 +LUNA_RET_NO_INVERSE = 2097155 +LUNA_RET_SENTRY_PKA_ERROR = 3147912 +LUNA_RET_ISES_TEST_VS_BSAFE_FAILED = 3147910 +LUNA_RET_ISES_CMD_PARAMETER_INVALID = 3147909 +LUNA_RET_ISES_CMD_FAILED = 3147908 +LUNA_RET_ISES_RNG_TEST_FAILED = 3147907 +LUNA_RET_ISES_LNAU_TEST_FAILED = 3147906 +LUNA_RET_ISES_INIT_FAILED = 3147905 +LUNA_RET_ISES_ERROR = 3147904 +LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT = 3147812 +LUNA_RET_SFNT3120_CRC = 3147811 +LUNA_RET_SFNT3120_ERROR = 3147809 +LUNA_RET_TEST_VS_BSAFE_FAILED = 3147808 +LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS = 3147789 +LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS = 3147788 +LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH = 3147787 +LUNA_RET_HIFN6500_INVALID_PARAMETERS = 3147786 +LUNA_RET_HIFN6500_ALU_TIMEOUT = 3147785 +LUNA_RET_HIFN6500_RNG_UNDERFLOW = 3147784 +LUNA_RET_HIFN6500_RNG_TIMEOUT = 3147783 +LUNA_RET_HIFN6500_RNG_FAILED = 3147782 +LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED = 3147781 +LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN = 3147780 +LUNA_RET_HIFN6500_DATA_LINES_BROKEN = 3147779 +LUNA_RET_HIFN6500_RESET_TIMEOUT = 3147778 +LUNA_RET_HIFN6500_NOT_PRESENT = 3147777 +LUNA_RET_HSM_TAMPERED = -2147482315 +LUNA_RET_STM_CMD_NON_TRANSPORT = -2147482316 +LUNA_RET_MTK_SPLIT_INVALID = -2147482317 +LUNA_RET_MTK_STATE_INVALID = -2147482318 +LUNA_RET_MTK_ZEROIZED = -2147482319 +LUNA_RET_HIFN_DMA_INVALID_REVISION = -2147482320 +LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO = -2147482342 +LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO = -2147482343 +LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO = -2147482344 +MSG_RTC_CANT_INITIALIZE_I2C = 5 +LUNA_RET_RC4_SELF_TEST_FAILURE = 3145741 +MSG_RTC_MSG_NVRAM_WRITE_FAILED = 4 +LUNA_RET_HIFN_INVALID_PAD_ALGORITHM = -2147482348 +LUNA_RET_MD5_SELF_TEST_FAILURE = 3145737 +LUNA_RET_MD2_SELF_TEST_FAILURE = 3145736 LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID = -2147482350 -LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST = 2100227 -RC_STC_CONTAINER_INVALID = -1073700848 -LUNA_RET_STORAGE_TYPE_INCONSISTENT = 2100228 -LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS = 2100229 -RC_STC_SESSION_INVALID = -1073700849 +LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM = -2147482351 +LUNA_RET_CAST3_SELF_TEST_FAILURE = 3145734 +LUNA_RET_HIFN_DMA_NOT_IDLE = -2147482355 +LUNA_RET_HIFN_DMA_ERROR = -2147482357 +LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID = -2147482359 +LUNA_RET_DATA_LEN_RANGE = 2162688 +LUNA_RET_CL_COMMAND_NON_BACKUP = 5505026 +RC_PIN_INVALID = -1073741565 +LUNA_RET_FUNCTION_NOT_SUPPORTED = 5505024 # values for enumeration 'ResultCodeValue' ResultCodeValue = c_int # enum @@ -620,7 +647,6 @@ class CK_AES_GCM_PARAMS(Structure): - """ """ pass @@ -641,7 +667,6 @@ class CK_AES_GCM_PARAMS(Structure): class CK_XOR_BASE_DATA_KDF_PARAMS(Structure): - """ """ pass @@ -654,13 +679,26 @@ class CK_XOR_BASE_DATA_KDF_PARAMS(Structure): ('pSharedData', CK_BYTE_PTR), ] CK_XOR_BASE_DATA_KDF_PARAMS_PTR = POINTER(CK_XOR_BASE_DATA_KDF_PARAMS) + + +class CK_AES_XTS_PARAMS(Structure): + pass + + +CK_OBJECT_HANDLE = CK_ULONG +if 'win' in sys.platform: + CK_AES_XTS_PARAMS._pack_ = 1 +CK_AES_XTS_PARAMS._fields_ = [ + ('hTweakKey', CK_OBJECT_HANDLE), + ('cb', CK_BYTE * 16), +] +CK_AES_XTS_PARAMS_PTR = POINTER(CK_AES_XTS_PARAMS) CK_EC_DH_PRIMITIVE = CK_ULONG CK_EC_ENC_SCHEME = CK_ULONG CK_EC_MAC_SCHEME = CK_ULONG class CK_ECIES_PARAMS(Structure): - """ """ pass @@ -685,7 +723,6 @@ class CK_ECIES_PARAMS(Structure): class CK_KDF_PRF_PARAMS(Structure): - """ """ pass @@ -705,7 +742,6 @@ class CK_KDF_PRF_PARAMS(Structure): class CK_AES_CTR_PARAMS(Structure): - """ """ pass @@ -716,7 +752,6 @@ class CK_AES_CTR_PARAMS(Structure): class CK_DES_CTR_PARAMS(Structure): - """ """ pass @@ -732,7 +767,6 @@ class CK_DES_CTR_PARAMS(Structure): class HSM_STATS_PARAMS(Structure): - """ """ pass @@ -746,7 +780,6 @@ class HSM_STATS_PARAMS(Structure): class CA_ROLE_STATE(Structure): - """ """ pass @@ -761,7 +794,6 @@ class CA_ROLE_STATE(Structure): class CA_MOFN_GENERATION(Structure): - """ """ pass @@ -776,7 +808,6 @@ class CA_MOFN_GENERATION(Structure): class CA_MOFN_ACTIVATION(Structure): - """ """ pass @@ -790,7 +821,6 @@ class CA_MOFN_ACTIVATION(Structure): class CA_M_OF_N_STATUS(Structure): - """ """ pass @@ -810,7 +840,6 @@ class CA_M_OF_N_STATUS(Structure): class CKCA_MODULE_INFO(Structure): - """ """ pass @@ -818,7 +847,6 @@ class CKCA_MODULE_INFO(Structure): class CK_VERSION(Structure): - """ """ pass @@ -840,7 +868,6 @@ class CK_VERSION(Structure): class CK_HA_MEMBER(Structure): - """ """ pass @@ -854,7 +881,6 @@ class CK_HA_MEMBER(Structure): class CK_HA_STATUS(Structure): - """ """ pass @@ -871,7 +897,6 @@ class CK_HA_STATUS(Structure): class CT_Token(Structure): - """ """ pass @@ -883,7 +908,6 @@ class CT_Token(Structure): class CK_AES_CBC_PAD_EXTRACT_PARAMS(Structure): - """ """ pass @@ -905,7 +929,6 @@ class CK_AES_CBC_PAD_EXTRACT_PARAMS(Structure): class CK_AES_CBC_PAD_INSERT_PARAMS(Structure): - """ """ pass @@ -927,7 +950,6 @@ class CK_AES_CBC_PAD_INSERT_PARAMS(Structure): class CK_CLUSTER_STATE(Structure): - """ """ pass @@ -941,7 +963,6 @@ class CK_CLUSTER_STATE(Structure): class CK_LKM_TOKEN_ID_S(Structure): - """ """ pass @@ -955,7 +976,6 @@ class CK_LKM_TOKEN_ID_S(Structure): class CK_SFNT_CA_FUNCTION_LIST(Structure): - """ """ pass @@ -969,17 +989,20 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_CA_WaitForSlotEvent = CFUNCTYPE(CK_RV, CK_FLAGS, POINTER(CK_ULONG), CK_SLOT_ID_PTR, CK_VOID_PTR) CK_CHAR_PTR = POINTER(CK_CHAR) CK_SESSION_HANDLE = CK_ULONG -CK_CA_InitIndirectToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_SESSION_HANDLE) -CK_CA_InitIndirectPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_SESSION_HANDLE) +CK_CA_InitIndirectToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, + CK_SESSION_HANDLE) +CK_CA_InitIndirectPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, + CK_SESSION_HANDLE) CK_CA_ResetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG) CK_USER_TYPE = CK_ULONG CK_CA_InitRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG) -CK_CA_InitSlotRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_CHAR_PTR, CK_ULONG) +CK_CA_InitSlotRolePIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_CHAR_PTR, + CK_ULONG) CK_CA_RoleStateGet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE, POINTER(CA_ROLE_STATE)) -CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, - CK_CHAR_PTR) -CK_CA_CreateContainerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, - CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_CreateLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, + CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_CreateContainerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, + CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR) CK_CA_Deactivate = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_USER_TYPE) CK_CA_FindAdminSlotForSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_SLOT_ID), POINTER(CK_SLOT_ID)) CK_CA_TokenInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CT_TokenHndle, CK_SLOT_ID) @@ -989,9 +1012,10 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_NOTIFICATION = CK_ULONG CK_NOTIFY = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) CK_SESSION_HANDLE_PTR = POINTER(CK_SESSION_HANDLE) -CK_CA_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) -CK_CA_OpenSessionWithAppID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, - CK_SESSION_HANDLE_PTR) +CK_CA_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, + CK_SESSION_HANDLE_PTR) +CK_CA_OpenSessionWithAppID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, + CK_NOTIFY, CK_SESSION_HANDLE_PTR) CK_CA_IndirectLogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE) CK_CA_InitializeRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_CA_DeleteRemotePEDVector = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) @@ -1010,26 +1034,26 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_CA_SetKCV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_CA_SetRDK = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_BYTE), CK_ULONG) CK_CA_SetCloningDomain = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG) -CK_OBJECT_HANDLE = CK_ULONG CK_OBJECT_HANDLE_PTR = POINTER(CK_OBJECT_HANDLE) -CK_CA_ClonePrivateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) -CK_CA_CloneObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, - CK_OBJECT_HANDLE_PTR) +CK_CA_ClonePrivateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE_PTR) +CK_CA_CloneObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, + CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR) CK_CA_GenerateCloningKEV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_BBOOL = CK_BYTE -CK_CA_CloneAsTargetInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, - CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_CloneAsSource = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, - CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_CloneAsTarget = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, - CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR) +CK_CA_CloneAsTargetInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsSource = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_CloneAsTarget = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR) CK_CA_SetMofN = CFUNCTYPE(CK_RV, CK_BBOOL) -CK_CA_GenerateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, - CK_VOID_PTR) -CK_CA_GenerateCloneableMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, - CK_VOID_PTR) -CK_CA_ModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, - CK_VOID_PTR) +CK_CA_GenerateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, + CK_ULONG, CK_VOID_PTR) +CK_CA_GenerateCloneableMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, + CK_ULONG, CK_ULONG, CK_VOID_PTR) +CK_CA_ModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, + CK_ULONG, CK_VOID_PTR) CK_CA_CloneMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) CK_CA_CloneModifyMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR) CK_CA_ActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CA_MOFN_ACTIVATION_PTR, CK_ULONG) @@ -1041,28 +1065,29 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): class CK_ATTRIBUTE(Structure): - """ """ pass CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) CK_CA_GenerateTokenKeys = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) CK_CA_GetTokenCertificateInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_BYTE_PTR, CK_ULONG) +CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) CK_CA_GetModuleList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR) CK_CA_GetModuleInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR) -CK_CA_LoadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) -CK_CA_LoadEncryptedModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_LoadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) +CK_CA_LoadEncryptedModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR) CK_CA_UnloadModule = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID) -CK_CA_PerformModuleCall = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_ULONG_PTR) -CK_CA_FirmwareUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_BYTE_PTR) +CK_CA_PerformModuleCall = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) +CK_CA_FirmwareUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) CK_CA_FirmwareRollback = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_CA_CapabilityUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR) +CK_CA_CapabilityUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR) CK_CA_GetUserContainerNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_SetUserContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG) @@ -1071,36 +1096,45 @@ class CK_ATTRIBUTE(Structure): CK_CA_GetFPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetExtendedTPV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetConfigurationElementDescription = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, - CK_ULONG_PTR, CK_ULONG_PTR, CK_CHAR_PTR) -CK_CA_GetHSMCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetConfigurationElementDescription = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, + CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_CHAR_PTR) +CK_CA_GetHSMCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_GetHSMCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetHSMPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetHSMPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_GetHSMPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetContainerCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR) +CK_CA_GetContainerCapabilitySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetContainerCapabilitySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetContainerPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR) +CK_CA_GetContainerPolicySet = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetContainerPolicySetting = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR) CK_CA_SetTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_SetExtendedTPV = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) CK_CA_SetHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) CK_CA_SetHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_SetDestructiveHSMPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_SetDestructiveHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetDestructiveHSMPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_SetContainerPolicy = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG) -CK_CA_SetContainerPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetTokenCapabilities = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_SetTokenPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetTokenPolicies = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_SetContainerPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR) +CK_CA_GetTokenCapabilities = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) +CK_CA_SetTokenPolicies = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR) +CK_CA_GetTokenPolicies = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_RetrieveLicenseList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_QueryLicense = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_BYTE_PTR) -CK_CA_GetContainerStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR) +CK_CA_QueryLicense = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_GetContainerStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR) CK_CA_GetTokenStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_ReadCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_WriteCommonStore = CFUNCTYPE(CK_RV, CK_ULONG, CK_BYTE_PTR, CK_ULONG) CK_CA_GetPrimarySlot = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID_PTR) @@ -1120,131 +1154,160 @@ class CK_ATTRIBUTE(Structure): CK_CA_SpRawRead = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_SpRawWrite = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_CheckOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)) -CK_CA_DestroyMultipleObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR) -CK_CA_OpenSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, - CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR) +CK_CA_DestroyMultipleObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, + CK_ULONG_PTR) +CK_CA_OpenSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, + CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR) CK_CA_CloseSecureToken = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_ListSecureTokenInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, - CK_BYTE_PTR) -CK_CA_ListSecureTokenUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_ListSecureTokenInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_ListSecureTokenUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, + CK_ULONG) class CK_MECHANISM(Structure): - """ """ pass CK_MECHANISM_PTR = POINTER(CK_MECHANISM) -CK_CA_GetSecureElementMeta = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_BYTE_PTR, CK_ULONG) +CK_CA_GetSecureElementMeta = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, + CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) CK_CA_HAInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) CK_CA_HAGetMasterPublic = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAGetLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG_PTR) -CK_CA_HAAnswerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG_PTR) -CK_CA_HALogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_CA_HAAnswerMofNChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAGetLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HAAnswerLoginChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_HALogin = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_CA_HAAnswerMofNChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_HAActivateMofN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_CA_GetHAState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_HA_STATE_PTR) CK_CA_GetTokenCertificates = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_ExtractMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_InsertMaskedObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) -CK_CA_MultisignValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, - CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) -CK_CA_SIMExtract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, - CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR) -CK_CA_SIMInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), - CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR) -CK_CA_SIMMultiSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, - POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, - POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) +CK_CA_MultisignValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, + POINTER(CK_BYTE_PTR)) +CK_CA_SIMExtract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, + CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), + CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR) +CK_CA_SIMInsert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, + POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, + CK_OBJECT_HANDLE_PTR) +CK_CA_SIMMultiSign = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, + CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), + CK_ULONG_PTR, POINTER(CK_BYTE_PTR)) CK_CA_Extract = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) CK_CA_Insert = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) CK_CA_GetTokenObjectUID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)) -CK_CA_GetTokenObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetTokenObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_BYTE), CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_GetObjectUID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, POINTER(CK_BYTE)) -CK_CA_GetObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, POINTER(CK_BYTE), CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetObjectHandle = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, POINTER(CK_BYTE), CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_DeleteContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_CA_MTKSetStorage = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_MTKRestore = CFUNCTYPE(CK_RV, CK_SLOT_ID) CK_CA_MTKResplit = CFUNCTYPE(CK_RV, CK_SLOT_ID) CK_CA_MTKZeroize = CFUNCTYPE(CK_RV, CK_SLOT_ID) CK_CA_MTKGetState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) +CK_CA_STMToggle = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) +CK_CA_STMGetState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetTSV = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_InvokeServiceInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_InvokeService = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR) CK_CA_InvokeServiceFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_InvokeServiceAsynch = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_InvokeServiceSinglePart = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG_PTR) -CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, - CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) -CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, - CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_InvokeServiceSinglePart = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_EncodeECPrimeParams = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) +CK_CA_EncodeECChar2Params = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, + CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG) CK_CA_EncodeECParamsFromFile = CFUNCTYPE(CK_RV, CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR) CK_CA_GetHSMStats = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, POINTER(HSM_STATS_PARAMS)) -CK_CA_GetHSMStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_GetTokenStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR) -CK_CA_GetContainerStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetHSMStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetTokenStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerStorageInformation = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_SetContainerSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_CreateContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, - CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR) +CK_CA_CreateContainer = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, + CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, + CK_ULONG, CK_ULONG_PTR) CK_CA_InitAudit = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR) CK_CA_LogVerify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG_PTR) CK_CA_LogVerifyFile = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG_PTR) CK_CA_LogExternal = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SESSION_HANDLE, POINTER(CK_CHAR), CK_ULONG) -CK_CA_LogImportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) -CK_CA_LogExportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR) +CK_CA_LogImportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) +CK_CA_LogExportSecret = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_TimeSync = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) CK_CA_GetTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG_PTR) -CK_CA_LogSetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR) -CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), - POINTER(CK_ULONG), CK_BYTE_PTR) -CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), - POINTER(CK_ULONG), POINTER(CK_ULONG)) +CK_CA_LogSetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, + CK_BYTE_PTR) +CK_CA_LogGetConfig = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR) +CK_CA_ReplaceFastPathKEK = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) +CK_CA_LogGetStatus = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG)) CK_CA_DeleteContainerWithHandle = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_GetContainerList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR) +CK_CA_GetContainerList = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR) CK_CA_GetContainerName = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_GetNumberOfAllowedContainers = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetTunnelSlotNumber = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_SLOT_ID_PTR) CK_CA_GetClusterState = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_CLUSTER_STATE_PTR) CK_CA_LockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) CK_CA_UnlockClusteredSlot = CFUNCTYPE(CK_RV, CK_SLOT_ID) -CK_CA_LKMInitiatorChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, - CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR) -CK_CA_LKMReceiverResponse = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, - CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR) -CK_CA_LKMInitiatorComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, +CK_CA_LKMInitiatorChallenge = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, + CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMReceiverResponse = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, + CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, + CK_CHAR_PTR, CK_ULONG_PTR) +CK_CA_LKMInitiatorComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) -CK_CA_LKMReceiverComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) +CK_CA_LKMReceiverComplete = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) CK_CA_ModifyUsageCount = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG) CK_CA_EnableUnauthTokenInsertion = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) -CK_CA_GetUnauthTokenInsertionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_ULONG), - POINTER(CK_ULONG)) +CK_CA_GetUnauthTokenInsertionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, + POINTER(CK_ULONG), POINTER(CK_ULONG)) CK_CA_DisableUnauthTokenInsertion = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG) -CK_CA_STCRegister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), - CK_ULONG, POINTER(CK_CHAR), CK_ULONG) +CK_CA_STCRegister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, + POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG) CK_CA_STCDeregister = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR)) -CK_CA_STCGetPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, - POINTER(CK_CHAR), CK_ULONG_PTR) -CK_CA_STCGetClientsList = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR) -CK_CA_STCGetClientInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, - CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) -CK_CA_STCGetPartPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, +CK_CA_STCGetPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), + POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetClientsList = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG_PTR, + CK_ULONG_PTR) +CK_CA_STCGetClientInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), + CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) -CK_CA_STCGetAdminPubKey = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetPartPubKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), + CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR) +CK_CA_STCGetAdminPubKey = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, + POINTER(CK_CHAR), CK_ULONG_PTR) CK_CA_STCSetCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_STCGetCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_STCGetCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) CK_CA_STCClearCipherAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) CK_CA_STCSetDigestAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) -CK_CA_STCGetDigestAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_STCGetDigestAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) CK_CA_STCClearDigestAlgorithm = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) CK_CA_STCSetKeyLifeTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG) CK_CA_STCGetKeyLifeTime = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR) @@ -1268,7 +1331,8 @@ class CK_MECHANISM(Structure): CK_CA_STCGetDigestNameByID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_CHAR_PTR, CK_BYTE) CK_CA_GetServerInstanceBySlotID = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_GetSlotListFromServerInstance = CFUNCTYPE(CK_RV, CK_ULONG, CK_SLOT_ID_PTR, CK_ULONG_PTR) -CK_CA_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) if 'win' in sys.platform: CK_SFNT_CA_FUNCTION_LIST._pack_ = 1 CK_SFNT_CA_FUNCTION_LIST._fields_ = [ @@ -1424,6 +1488,8 @@ class CK_MECHANISM(Structure): ('CA_MTKResplit', CK_CA_MTKResplit), ('CA_MTKZeroize', CK_CA_MTKZeroize), ('CA_MTKGetState', CK_CA_MTKGetState), + ('CA_STMToggle', CK_CA_STMToggle), + ('CA_STMGetState', CK_CA_STMGetState), ('CA_GetTSV', CK_CA_GetTSV), ('CA_InvokeServiceInit', CK_CA_InvokeServiceInit), ('CA_InvokeService', CK_CA_InvokeService), @@ -1449,6 +1515,7 @@ class CK_MECHANISM(Structure): ('CA_GetTime', CK_CA_GetTime), ('CA_LogSetConfig', CK_CA_LogSetConfig), ('CA_LogGetConfig', CK_CA_LogGetConfig), + ('CA_ReplaceFastPathKEK', CK_CA_ReplaceFastPathKEK), ('CA_LogGetStatus', CK_CA_LogGetStatus), ('CA_DeleteContainerWithHandle', CK_CA_DeleteContainerWithHandle), ('CA_GetContainerList', CK_CA_GetContainerList), @@ -1529,11 +1596,12 @@ class CK_MECHANISM(Structure): CA_RoleStateGet.argtypes = [CK_SLOT_ID, CK_USER_TYPE, POINTER(CA_ROLE_STATE)] CA_CreateLoginChallenge = make_late_binding_function('CA_CreateLoginChallenge') CA_CreateLoginChallenge.restype = CK_RV -CA_CreateLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR] +CA_CreateLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, + CK_ULONG_PTR, CK_CHAR_PTR] CA_CreateContainerLoginChallenge = make_late_binding_function('CA_CreateContainerLoginChallenge') CA_CreateContainerLoginChallenge.restype = CK_RV -CA_CreateContainerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, CK_CHAR_PTR, - CK_ULONG_PTR, CK_CHAR_PTR] +CA_CreateContainerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_USER_TYPE, CK_ULONG, + CK_CHAR_PTR, CK_ULONG_PTR, CK_CHAR_PTR] CA_Deactivate = make_late_binding_function('CA_Deactivate') CA_Deactivate.restype = CK_RV CA_Deactivate.argtypes = [CK_SLOT_ID, CK_USER_TYPE] @@ -1554,11 +1622,12 @@ class CK_MECHANISM(Structure): CA_TokenDelete.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID] CA_OpenSession = make_late_binding_function('CA_OpenSession') CA_OpenSession.restype = CK_RV -CA_OpenSession.argtypes = [CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR] +CA_OpenSession.argtypes = [CK_SLOT_ID, CK_ULONG, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, + CK_SESSION_HANDLE_PTR] CA_OpenSessionWithAppID = make_late_binding_function('CA_OpenSessionWithAppID') CA_OpenSessionWithAppID.restype = CK_RV -CA_OpenSessionWithAppID.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, CK_NOTIFY, - CK_SESSION_HANDLE_PTR] +CA_OpenSessionWithAppID.argtypes = [CK_SLOT_ID, CK_FLAGS, CK_ULONG, CK_ULONG, CK_VOID_PTR, + CK_NOTIFY, CK_SESSION_HANDLE_PTR] CA_IndirectLogin = make_late_binding_function('CA_IndirectLogin') CA_IndirectLogin.restype = CK_RV CA_IndirectLogin.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_SESSION_HANDLE] @@ -1615,38 +1684,42 @@ class CK_MECHANISM(Structure): CA_SetCloningDomain.argtypes = [CK_BYTE_PTR, CK_ULONG] CA_ClonePrivateKey = make_late_binding_function('CA_ClonePrivateKey') CA_ClonePrivateKey.restype = CK_RV -CA_ClonePrivateKey.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR] +CA_ClonePrivateKey.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE_PTR] CA_CloneObject = make_late_binding_function('CA_CloneObject') CA_CloneObject.restype = CK_RV -CA_CloneObject.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR] +CA_CloneObject.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE_PTR] CA_GenerateCloningKEV = make_late_binding_function('CA_GenerateCloningKEV') CA_GenerateCloningKEV.restype = CK_RV CA_GenerateCloningKEV.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] CA_CloneAsTargetInit = make_late_binding_function('CA_CloneAsTargetInit') CA_CloneAsTargetInit.restype = CK_RV -CA_CloneAsTargetInit.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, - CK_ULONG_PTR] +CA_CloneAsTargetInit.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BBOOL, CK_BYTE_PTR, CK_ULONG_PTR] CA_CloneAsSource = make_late_binding_function('CA_CloneAsSource') CA_CloneAsSource.restype = CK_RV -CA_CloneAsSource.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, CK_BYTE_PTR, - CK_ULONG_PTR] +CA_CloneAsSource.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BBOOL, + CK_BYTE_PTR, CK_ULONG_PTR] CA_CloneAsTarget = make_late_binding_function('CA_CloneAsTarget') CA_CloneAsTarget.restype = CK_RV -CA_CloneAsTarget.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG, CK_ULONG, - CK_BBOOL, CK_OBJECT_HANDLE_PTR] +CA_CloneAsTarget.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_ULONG, CK_ULONG, CK_BBOOL, CK_OBJECT_HANDLE_PTR] CA_SetMofN = make_late_binding_function('CA_SetMofN') CA_SetMofN.restype = CK_RV CA_SetMofN.argtypes = [CK_BBOOL] CA_GenerateMofN = make_late_binding_function('CA_GenerateMofN') CA_GenerateMofN.restype = CK_RV -CA_GenerateMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] +CA_GenerateMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, + CK_VOID_PTR] CA_GenerateCloneableMofN = make_late_binding_function('CA_GenerateCloneableMofN') CA_GenerateCloneableMofN.restype = CK_RV -CA_GenerateCloneableMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, - CK_VOID_PTR] +CA_GenerateCloneableMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, + CK_ULONG, CK_VOID_PTR] CA_ModifyMofN = make_late_binding_function('CA_ModifyMofN') CA_ModifyMofN.restype = CK_RV -CA_ModifyMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, CK_VOID_PTR] +CA_ModifyMofN.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CA_MOFN_GENERATION_PTR, CK_ULONG, CK_ULONG, + CK_VOID_PTR] CA_CloneMofN = make_late_binding_function('CA_CloneMofN') CA_CloneMofN.restype = CK_RV CA_CloneMofN.argtypes = [CK_SESSION_HANDLE, CK_SESSION_HANDLE, CK_VOID_PTR] @@ -1679,8 +1752,8 @@ class CK_MECHANISM(Structure): CA_GetTokenCertificateInfo.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CA_SetTokenCertificateSignature = make_late_binding_function('CA_SetTokenCertificateSignature') CA_SetTokenCertificateSignature.restype = CK_RV -CA_SetTokenCertificateSignature.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_BYTE_PTR, CK_ULONG] +CA_SetTokenCertificateSignature.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ATTRIBUTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_GetModuleList = make_late_binding_function('CA_GetModuleList') CA_GetModuleList.restype = CK_RV CA_GetModuleList.argtypes = [CK_SLOT_ID, CKCA_MODULE_ID_PTR, CK_ULONG, CK_ULONG_PTR] @@ -1689,23 +1762,24 @@ class CK_MECHANISM(Structure): CA_GetModuleInfo.argtypes = [CK_SLOT_ID, CKCA_MODULE_ID, CKCA_MODULE_INFO_PTR] CA_LoadModule = make_late_binding_function('CA_LoadModule') CA_LoadModule.restype = CK_RV -CA_LoadModule.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, - CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] +CA_LoadModule.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] CA_LoadEncryptedModule = make_late_binding_function('CA_LoadEncryptedModule') CA_LoadEncryptedModule.restype = CK_RV -CA_LoadEncryptedModule.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, - CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CKCA_MODULE_ID_PTR] +CA_LoadEncryptedModule.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CKCA_MODULE_ID_PTR] CA_UnloadModule = make_late_binding_function('CA_UnloadModule') CA_UnloadModule.restype = CK_RV CA_UnloadModule.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID] CA_PerformModuleCall = make_late_binding_function('CA_PerformModuleCall') CA_PerformModuleCall.restype = CK_RV -CA_PerformModuleCall.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, - CK_ULONG_PTR] +CA_PerformModuleCall.argtypes = [CK_SESSION_HANDLE, CKCA_MODULE_ID, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR] CA_FirmwareUpdate = make_late_binding_function('CA_FirmwareUpdate') CA_FirmwareUpdate.restype = CK_RV -CA_FirmwareUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, - CK_BYTE_PTR] +CA_FirmwareUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR] CA_FirmwareRollback = make_late_binding_function('CA_FirmwareRollback') CA_FirmwareRollback.restype = CK_RV CA_FirmwareRollback.argtypes = [CK_SESSION_HANDLE] @@ -1736,13 +1810,16 @@ class CK_MECHANISM(Structure): CA_GetExtendedTPV = make_late_binding_function('CA_GetExtendedTPV') CA_GetExtendedTPV.restype = CK_RV CA_GetExtendedTPV.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] -CA_GetConfigurationElementDescription = make_late_binding_function('CA_GetConfigurationElementDescription') +CA_GetConfigurationElementDescription = make_late_binding_function( + 'CA_GetConfigurationElementDescription') CA_GetConfigurationElementDescription.restype = CK_RV -CA_GetConfigurationElementDescription.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR, CK_CHAR_PTR] +CA_GetConfigurationElementDescription.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG, + CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_CHAR_PTR] CA_GetHSMCapabilitySet = make_late_binding_function('CA_GetHSMCapabilitySet') CA_GetHSMCapabilitySet.restype = CK_RV -CA_GetHSMCapabilitySet.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetHSMCapabilitySet.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR] CA_GetHSMCapabilitySetting = make_late_binding_function('CA_GetHSMCapabilitySetting') CA_GetHSMCapabilitySetting.restype = CK_RV CA_GetHSMCapabilitySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR] @@ -1754,16 +1831,21 @@ class CK_MECHANISM(Structure): CA_GetHSMPolicySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR] CA_GetContainerCapabilitySet = make_late_binding_function('CA_GetContainerCapabilitySet') CA_GetContainerCapabilitySet.restype = CK_RV -CA_GetContainerCapabilitySet.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerCapabilitySet.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR] CA_GetContainerCapabilitySetting = make_late_binding_function('CA_GetContainerCapabilitySetting') CA_GetContainerCapabilitySetting.restype = CK_RV CA_GetContainerCapabilitySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR] CA_GetContainerPolicySet = make_late_binding_function('CA_GetContainerPolicySet') CA_GetContainerPolicySet.restype = CK_RV -CA_GetContainerPolicySet.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerPolicySet.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR] CA_GetContainerPolicySetting = make_late_binding_function('CA_GetContainerPolicySetting') CA_GetContainerPolicySetting.restype = CK_RV CA_GetContainerPolicySetting.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR] +CA_GetPartitionPolicyTemplate = make_late_binding_function('CA_GetPartitionPolicyTemplate') +CA_GetPartitionPolicyTemplate.restype = CK_RV +CA_GetPartitionPolicyTemplate.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR] CA_SetTPV = make_late_binding_function('CA_SetTPV') CA_SetTPV.restype = CK_RV CA_SetTPV.argtypes = [CK_SESSION_HANDLE, CK_ULONG] @@ -1787,10 +1869,12 @@ class CK_MECHANISM(Structure): CA_SetContainerPolicy.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG] CA_SetContainerPolicies = make_late_binding_function('CA_SetContainerPolicies') CA_SetContainerPolicies.restype = CK_RV -CA_SetContainerPolicies.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] +CA_SetContainerPolicies.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR] CA_GetTokenCapabilities = make_late_binding_function('CA_GetTokenCapabilities') CA_GetTokenCapabilities.restype = CK_RV -CA_GetTokenCapabilities.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetTokenCapabilities.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR] CA_SetTokenPolicies = make_late_binding_function('CA_SetTokenPolicies') CA_SetTokenPolicies.restype = CK_RV CA_SetTokenPolicies.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR] @@ -1802,16 +1886,19 @@ class CK_MECHANISM(Structure): CA_RetrieveLicenseList.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] CA_QueryLicense = make_late_binding_function('CA_QueryLicense') CA_QueryLicense.restype = CK_RV -CA_QueryLicense.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR] +CA_QueryLicense.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_BYTE_PTR] CA_GetContainerStatus = make_late_binding_function('CA_GetContainerStatus') CA_GetContainerStatus.restype = CK_RV -CA_GetContainerStatus.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerStatus.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR] CA_GetTokenStatus = make_late_binding_function('CA_GetTokenStatus') CA_GetTokenStatus.restype = CK_RV CA_GetTokenStatus.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] CA_GetSessionInfo = make_late_binding_function('CA_GetSessionInfo') CA_GetSessionInfo.restype = CK_RV -CA_GetSessionInfo.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetSessionInfo.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR] CA_ReadCommonStore = make_late_binding_function('CA_ReadCommonStore') CA_ReadCommonStore.restype = CK_RV CA_ReadCommonStore.argtypes = [CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] @@ -1871,24 +1958,26 @@ class CK_MECHANISM(Structure): CA_CheckOperationState.argtypes = [CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_BBOOL)] CA_DestroyMultipleObjects = make_late_binding_function('CA_DestroyMultipleObjects') CA_DestroyMultipleObjects.restype = CK_RV -CA_DestroyMultipleObjects.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG_PTR] +CA_DestroyMultipleObjects.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, + CK_ULONG_PTR] CA_OpenSecureToken = make_late_binding_function('CA_OpenSecureToken') CA_OpenSecureToken.restype = CK_RV -CA_OpenSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG, CK_CHAR_PTR] +CA_OpenSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, + CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG, CK_CHAR_PTR] CA_CloseSecureToken = make_late_binding_function('CA_CloseSecureToken') CA_CloseSecureToken.restype = CK_RV CA_CloseSecureToken.argtypes = [CK_SESSION_HANDLE, CK_ULONG] CA_ListSecureTokenInit = make_late_binding_function('CA_ListSecureTokenInit') CA_ListSecureTokenInit.restype = CK_RV -CA_ListSecureTokenInit.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR] +CA_ListSecureTokenInit.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG_PTR, + CK_ULONG_PTR, CK_BYTE_PTR] CA_ListSecureTokenUpdate = make_late_binding_function('CA_ListSecureTokenUpdate') CA_ListSecureTokenUpdate.restype = CK_RV CA_ListSecureTokenUpdate.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_GetSecureElementMeta = make_late_binding_function('CA_GetSecureElementMeta') CA_GetSecureElementMeta.restype = CK_RV -CA_GetSecureElementMeta.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_BYTE_PTR, CK_ULONG] +CA_GetSecureElementMeta.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG] CA_HAInit = make_late_binding_function('CA_HAInit') CA_HAInit.restype = CK_RV CA_HAInit.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] @@ -1897,17 +1986,19 @@ class CK_MECHANISM(Structure): CA_HAGetMasterPublic.argtypes = [CK_SLOT_ID, CK_BYTE_PTR, CK_ULONG_PTR] CA_HAGetLoginChallenge = make_late_binding_function('CA_HAGetLoginChallenge') CA_HAGetLoginChallenge.restype = CK_RV -CA_HAGetLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HAGetLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG_PTR] CA_HAAnswerLoginChallenge = make_late_binding_function('CA_HAAnswerLoginChallenge') CA_HAAnswerLoginChallenge.restype = CK_RV -CA_HAAnswerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG_PTR] +CA_HAAnswerLoginChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG_PTR] CA_HALogin = make_late_binding_function('CA_HALogin') CA_HALogin.restype = CK_RV CA_HALogin.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CA_HAAnswerMofNChallenge = make_late_binding_function('CA_HAAnswerMofNChallenge') CA_HAAnswerMofNChallenge.restype = CK_RV -CA_HAAnswerMofNChallenge.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_HAAnswerMofNChallenge.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR] CA_HAActivateMofN = make_late_binding_function('CA_HAActivateMofN') CA_HAActivateMofN.restype = CK_RV CA_HAActivateMofN.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] @@ -1925,21 +2016,24 @@ class CK_MECHANISM(Structure): CA_InsertMaskedObject.argtypes = [CK_SESSION_HANDLE, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG] CA_MultisignValue = make_late_binding_function('CA_MultisignValue') CA_MultisignValue.restype = CK_RV -CA_MultisignValue.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] +CA_MultisignValue.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, + POINTER(CK_BYTE_PTR)] CA_SIMExtract = make_late_binding_function('CA_SIMExtract') CA_SIMExtract.restype = CK_RV -CA_SIMExtract.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, CKA_SIM_AUTH_FORM, - CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, CK_ULONG_PTR, CK_BYTE_PTR] +CA_SIMExtract.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG, + CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_BBOOL, + CK_ULONG_PTR, CK_BYTE_PTR] CA_SIMInsert = make_late_binding_function('CA_SIMInsert') CA_SIMInsert.restype = CK_RV -CA_SIMInsert.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, - CK_BYTE_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR] +CA_SIMInsert.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, + POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR, + CK_OBJECT_HANDLE_PTR] CA_SIMMultiSign = make_late_binding_function('CA_SIMMultiSign') CA_SIMMultiSign.restype = CK_RV -CA_SIMMultiSign.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, CK_ULONG_PTR, - POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_ULONG_PTR, POINTER(CK_BYTE_PTR), - CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] +CA_SIMMultiSign.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ULONG, CKA_SIM_AUTH_FORM, + CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_ULONG_PTR, POINTER(CK_BYTE_PTR), CK_ULONG_PTR, POINTER(CK_BYTE_PTR)] CA_Extract = make_late_binding_function('CA_Extract') CA_Extract.restype = CK_RV CA_Extract.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR] @@ -1976,6 +2070,15 @@ class CK_MECHANISM(Structure): CA_MTKGetState = make_late_binding_function('CA_MTKGetState') CA_MTKGetState.restype = CK_RV CA_MTKGetState.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] +CA_TamperClear = make_late_binding_function('CA_TamperClear') +CA_TamperClear.restype = CK_RV +CA_TamperClear.argtypes = [CK_SESSION_HANDLE] +CA_STMToggle = make_late_binding_function('CA_STMToggle') +CA_STMToggle.restype = CK_RV +CA_STMToggle.argtypes = [CK_SESSION_HANDLE, CK_ULONG] +CA_STMGetState = make_late_binding_function('CA_STMGetState') +CA_STMGetState.restype = CK_RV +CA_STMGetState.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] CA_GetTSV = make_late_binding_function('CA_GetTSV') CA_GetTSV.restype = CK_RV CA_GetTSV.argtypes = [CK_SLOT_ID, CK_ULONG_PTR] @@ -1993,17 +2096,20 @@ class CK_MECHANISM(Structure): CA_InvokeServiceAsynch.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_InvokeServiceSinglePart = make_late_binding_function('CA_InvokeServiceSinglePart') CA_InvokeServiceSinglePart.restype = CK_RV -CA_InvokeServiceSinglePart.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_InvokeServiceSinglePart.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG_PTR] CA_EncodeECPrimeParams = make_late_binding_function('CA_EncodeECPrimeParams') CA_EncodeECPrimeParams.restype = CK_RV -CA_EncodeECPrimeParams.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, - CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_EncodeECPrimeParams.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_EncodeECChar2Params = make_late_binding_function('CA_EncodeECChar2Params') CA_EncodeECChar2Params.restype = CK_RV -CA_EncodeECChar2Params.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR, - CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, - CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] +CA_EncodeECChar2Params.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_ULONG, CK_ULONG, CK_ULONG, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, + CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG] CA_EncodeECParamsFromFile = make_late_binding_function('CA_EncodeECParamsFromFile') CA_EncodeECParamsFromFile.restype = CK_RV CA_EncodeECParamsFromFile.argtypes = [CK_BYTE_PTR, CK_ULONG_PTR, CK_BYTE_PTR] @@ -2012,22 +2118,30 @@ class CK_MECHANISM(Structure): CA_GetHSMStats.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, POINTER(HSM_STATS_PARAMS)] CA_GetHSMStorageInformation = make_late_binding_function('CA_GetHSMStorageInformation') CA_GetHSMStorageInformation.restype = CK_RV -CA_GetHSMStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetHSMStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR] CA_GetTokenStorageInformation = make_late_binding_function('CA_GetTokenStorageInformation') CA_GetTokenStorageInformation.restype = CK_RV -CA_GetTokenStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR] +CA_GetTokenStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR] CA_GetContainerStorageInformation = make_late_binding_function('CA_GetContainerStorageInformation') CA_GetContainerStorageInformation.restype = CK_RV -CA_GetContainerStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR, - CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetContainerStorageInformation.argtypes = [CK_SLOT_ID, CK_ULONG, CK_ULONG_PTR, CK_ULONG_PTR, + CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] CA_SetContainerSize = make_late_binding_function('CA_SetContainerSize') CA_SetContainerSize.restype = CK_RV CA_SetContainerSize.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] +CA_CreateContainerWithPolicy = make_late_binding_function('CA_CreateContainerWithPolicy') +CA_CreateContainerWithPolicy.restype = CK_RV +CA_CreateContainerWithPolicy.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, + CK_CHAR_PTR, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, + CK_ULONG, CK_ULONG, CK_ULONG_PTR, CK_ULONG, CK_ULONG, + CK_BYTE_PTR] CA_CreateContainer = make_late_binding_function('CA_CreateContainer') CA_CreateContainer.restype = CK_RV -CA_CreateContainer.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_ULONG, - CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG_PTR] +CA_CreateContainer.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, + CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, + CK_ULONG_PTR] CA_InitAudit = make_late_binding_function('CA_InitAudit') CA_InitAudit.restype = CK_RV CA_InitAudit.argtypes = [CK_SLOT_ID, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR] @@ -2042,10 +2156,10 @@ class CK_MECHANISM(Structure): CA_LogExternal.argtypes = [CK_SLOT_ID, CK_SESSION_HANDLE, POINTER(CK_CHAR), CK_ULONG] CA_LogImportSecret = make_late_binding_function('CA_LogImportSecret') CA_LogImportSecret.restype = CK_RV -CA_LogImportSecret.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR] +CA_LogImportSecret.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] CA_LogExportSecret = make_late_binding_function('CA_LogExportSecret') CA_LogExportSecret.restype = CK_RV -CA_LogExportSecret.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR] +CA_LogExportSecret.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] CA_TimeSync = make_late_binding_function('CA_TimeSync') CA_TimeSync.restype = CK_RV CA_TimeSync.argtypes = [CK_SESSION_HANDLE, CK_ULONG] @@ -2057,12 +2171,15 @@ class CK_MECHANISM(Structure): CA_LogSetConfig.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_ULONG, CK_ULONG, CK_BYTE_PTR] CA_LogGetConfig = make_late_binding_function('CA_LogGetConfig') CA_LogGetConfig.restype = CK_RV -CA_LogGetConfig.argtypes = [CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), - POINTER(CK_ULONG), CK_BYTE_PTR] +CA_LogGetConfig.argtypes = [CK_SESSION_HANDLE, POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG), POINTER(CK_ULONG), CK_BYTE_PTR] +CA_ReplaceFastPathKEK = make_late_binding_function('CA_ReplaceFastPathKEK') +CA_ReplaceFastPathKEK.restype = CK_RV +CA_ReplaceFastPathKEK.argtypes = [CK_SESSION_HANDLE] CA_LogGetStatus = make_late_binding_function('CA_LogGetStatus') CA_LogGetStatus.restype = CK_RV -CA_LogGetStatus.argtypes = [CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), - POINTER(CK_ULONG)] +CA_LogGetStatus.argtypes = [CK_SLOT_ID, POINTER(CK_ULONG), POINTER(CK_ULONG), POINTER(CK_ULONG), + POINTER(CK_ULONG), POINTER(CK_ULONG)] CA_DeleteContainerWithHandle = make_late_binding_function('CA_DeleteContainerWithHandle') CA_DeleteContainerWithHandle.restype = CK_RV CA_DeleteContainerWithHandle.argtypes = [CK_SESSION_HANDLE, CK_ULONG] @@ -2089,21 +2206,24 @@ class CK_MECHANISM(Structure): CA_UnlockClusteredSlot.argtypes = [CK_SLOT_ID] CA_LKMInitiatorChallenge = make_late_binding_function('CA_LKMInitiatorChallenge') CA_LKMInitiatorChallenge.restype = CK_RV -CA_LKMInitiatorChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, - CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG_PTR] +CA_LKMInitiatorChallenge.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, + CK_ULONG, CK_LKM_TOKEN_ID_PTR, CK_LKM_TOKEN_ID_PTR, + CK_CHAR_PTR, CK_ULONG_PTR] CA_LKMReceiverResponse = make_late_binding_function('CA_LKMReceiverResponse') CA_LKMReceiverResponse.restype = CK_RV -CA_LKMReceiverResponse.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_LKM_TOKEN_ID_PTR, - CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR] +CA_LKMReceiverResponse.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, + CK_LKM_TOKEN_ID_PTR, CK_CHAR_PTR, CK_ULONG, CK_CHAR_PTR, + CK_ULONG_PTR] CA_LKMInitiatorComplete = make_late_binding_function('CA_LKMInitiatorComplete') CA_LKMInitiatorComplete.restype = CK_RV -CA_LKMInitiatorComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, CK_OBJECT_HANDLE_PTR, - CK_OBJECT_HANDLE_PTR] +CA_LKMInitiatorComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, + CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_CHAR_PTR, CK_ULONG_PTR, + CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] CA_LKMReceiverComplete = make_late_binding_function('CA_LKMReceiverComplete') CA_LKMReceiverComplete.restype = CK_RV -CA_LKMReceiverComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +CA_LKMReceiverComplete.argtypes = [CK_SESSION_HANDLE, CK_CHAR_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, + CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, + CK_OBJECT_HANDLE_PTR] CA_ModifyUsageCount = make_late_binding_function('CA_ModifyUsageCount') CA_ModifyUsageCount.restype = CK_RV CA_ModifyUsageCount.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG, CK_ULONG] @@ -2112,35 +2232,38 @@ class CK_MECHANISM(Structure): CA_EnableUnauthTokenInsertion.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG_PTR] CA_GetUnauthTokenInsertionStatus = make_late_binding_function('CA_GetUnauthTokenInsertionStatus') CA_GetUnauthTokenInsertionStatus.restype = CK_RV -CA_GetUnauthTokenInsertionStatus.argtypes = [CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_ULONG), POINTER(CK_ULONG)] +CA_GetUnauthTokenInsertionStatus.argtypes = [CK_SESSION_HANDLE, CK_ULONG, POINTER(CK_ULONG), + POINTER(CK_ULONG)] CA_DisableUnauthTokenInsertion = make_late_binding_function('CA_DisableUnauthTokenInsertion') CA_DisableUnauthTokenInsertion.restype = CK_RV CA_DisableUnauthTokenInsertion.argtypes = [CK_SESSION_HANDLE, CK_ULONG] CA_STCRegister = make_late_binding_function('CA_STCRegister') CA_STCRegister.restype = CK_RV -CA_STCRegister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG, - POINTER(CK_CHAR), CK_ULONG] +CA_STCRegister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG, + POINTER(CK_CHAR), CK_ULONG, POINTER(CK_CHAR), CK_ULONG] CA_STCDeregister = make_late_binding_function('CA_STCDeregister') CA_STCDeregister.restype = CK_RV CA_STCDeregister.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR)] CA_STCGetPubKey = make_late_binding_function('CA_STCGetPubKey') CA_STCGetPubKey.restype = CK_RV -CA_STCGetPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), CK_ULONG_PTR, - POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), POINTER(CK_CHAR), + CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] CA_STCGetClientsList = make_late_binding_function('CA_STCGetClientsList') CA_STCGetClientsList.restype = CK_RV CA_STCGetClientsList.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR] CA_STCGetClientInfo = make_late_binding_function('CA_STCGetClientInfo') CA_STCGetClientInfo.restype = CK_RV -CA_STCGetClientInfo.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), CK_ULONG_PTR, CK_ULONG_PTR, - POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetClientInfo.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, CK_ULONG, POINTER(CK_CHAR), + CK_ULONG_PTR, CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR, + POINTER(CK_CHAR), CK_ULONG_PTR] CA_STCGetPartPubKey = make_late_binding_function('CA_STCGetPartPubKey') CA_STCGetPartPubKey.restype = CK_RV -CA_STCGetPartPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), - CK_ULONG_PTR] +CA_STCGetPartPubKey.argtypes = [CK_SESSION_HANDLE, CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, + POINTER(CK_CHAR), CK_ULONG_PTR] CA_STCGetAdminPubKey = make_late_binding_function('CA_STCGetAdminPubKey') CA_STCGetAdminPubKey.restype = CK_RV -CA_STCGetAdminPubKey.argtypes = [CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), CK_ULONG_PTR] +CA_STCGetAdminPubKey.argtypes = [CK_SLOT_ID, POINTER(CK_CHAR), CK_ULONG_PTR, POINTER(CK_CHAR), + CK_ULONG_PTR] CA_STCSetCipherAlgorithm = make_late_binding_function('CA_STCSetCipherAlgorithm') CA_STCSetCipherAlgorithm.restype = CK_RV CA_STCSetCipherAlgorithm.argtypes = [CK_SESSION_HANDLE, CK_ULONG, CK_ULONG] @@ -2227,7 +2350,16 @@ class CK_MECHANISM(Structure): CA_GetSlotListFromServerInstance.argtypes = [CK_ULONG, CK_SLOT_ID_PTR, CK_ULONG_PTR] CA_PerformSelfTest = make_late_binding_function('CA_PerformSelfTest') CA_PerformSelfTest.restype = CK_RV -CA_PerformSelfTest.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +CA_PerformSelfTest.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR] +CA_DeriveKeyAndWrap = make_late_binding_function('CA_DeriveKeyAndWrap') +CA_DeriveKeyAndWrap.restype = CK_RV +CA_DeriveKeyAndWrap.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, + CK_BYTE_PTR, CK_ULONG_PTR] +CA_Get = make_late_binding_function('CA_Get') +CA_Get.restype = CK_RV +CA_Get.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] CK_GetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(c_int)) CK_ResetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID) @@ -2265,7 +2397,6 @@ class CK_MECHANISM(Structure): class swapper(Union): - """ """ pass @@ -2279,7 +2410,6 @@ class swapper(Union): class CK_FUNCTION_LIST(Structure): - """ """ pass @@ -2288,7 +2418,6 @@ class CK_FUNCTION_LIST(Structure): class CK_INFO(Structure): - """ """ pass @@ -2301,7 +2430,6 @@ class CK_INFO(Structure): class CK_SLOT_INFO(Structure): - """ """ pass @@ -2310,7 +2438,6 @@ class CK_SLOT_INFO(Structure): class CK_TOKEN_INFO(Structure): - """ """ pass @@ -2322,7 +2449,6 @@ class CK_TOKEN_INFO(Structure): class CK_MECHANISM_INFO(Structure): - """ """ pass @@ -2332,40 +2458,47 @@ class CK_MECHANISM_INFO(Structure): CK_UTF8CHAR_PTR = POINTER(CK_UTF8CHAR) CK_C_InitToken = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR) CK_C_InitPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG) -CK_C_SetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, CK_ULONG) -CK_C_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, CK_SESSION_HANDLE_PTR) +CK_C_SetPIN = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR, + CK_ULONG) +CK_C_OpenSession = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY, + CK_SESSION_HANDLE_PTR) CK_C_CloseSession = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_C_CloseAllSessions = CFUNCTYPE(CK_RV, CK_SLOT_ID) class CK_SESSION_INFO(Structure): - """ """ pass CK_SESSION_INFO_PTR = POINTER(CK_SESSION_INFO) CK_C_GetSessionInfo = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_SESSION_INFO_PTR) CK_C_GetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_SetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE) +CK_C_SetOperationState = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE, CK_OBJECT_HANDLE) CK_C_Login = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG) CK_C_Logout = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) -CK_C_CreateObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_CreateObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR) CK_C_CopyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) CK_C_DestroyObject = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) CK_C_GetObjectSize = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ULONG_PTR) -CK_C_GetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) -CK_C_SetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) +CK_C_GetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, + CK_ULONG) +CK_C_SetAttributeValue = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, + CK_ULONG) CK_C_FindObjectsInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) CK_C_FindObjects = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE_PTR, CK_ULONG, CK_ULONG_PTR) CK_C_FindObjectsFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) CK_C_EncryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) CK_C_Encrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_EncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_EncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) CK_C_EncryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_C_DecryptInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) CK_C_Decrypt = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_DecryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) CK_C_DecryptFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_C_DigestInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR) CK_C_Digest = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) @@ -2377,27 +2510,34 @@ class CK_SESSION_INFO(Structure): CK_C_SignUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_C_SignFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) CK_C_SignRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_SignRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_SignRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) CK_C_VerifyInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) CK_C_Verify = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG) CK_C_VerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_C_VerifyFinal = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_C_VerifyRecoverInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE) -CK_C_VerifyRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DigestEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptDigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_SignEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) -CK_C_DecryptVerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_VerifyRecover = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_C_DigestEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_C_DecryptDigestUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_C_SignEncryptUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) +CK_C_DecryptVerifyUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR) CK_C_GenerateKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_GenerateKeyPair = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR) -CK_C_WrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, - CK_ULONG_PTR) -CK_C_UnwrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, +CK_C_GenerateKeyPair = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, + CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, + CK_OBJECT_HANDLE_PTR) +CK_C_WrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR) +CK_C_UnwrapKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, + CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) +CK_C_DeriveKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR) -CK_C_DeriveKey = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_OBJECT_HANDLE_PTR) CK_C_SeedRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_C_GenerateRandom = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG) CK_C_GetFunctionStatus = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE) @@ -2529,7 +2669,8 @@ class CK_SESSION_INFO(Structure): C_GetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR] C_SetOperationState = make_late_binding_function('C_SetOperationState') C_SetOperationState.restype = CK_RV -C_SetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE] +C_SetOperationState.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_OBJECT_HANDLE, + CK_OBJECT_HANDLE] C_Login = make_late_binding_function('C_Login') C_Login.restype = CK_RV C_Login.argtypes = [CK_SESSION_HANDLE, CK_USER_TYPE, CK_UTF8CHAR_PTR, CK_ULONG] @@ -2541,7 +2682,8 @@ class CK_SESSION_INFO(Structure): C_CreateObject.argtypes = [CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] C_CopyObject = make_late_binding_function('C_CopyObject') C_CopyObject.restype = CK_RV -C_CopyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_CopyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR] C_DestroyObject = make_late_binding_function('C_DestroyObject') C_DestroyObject.restype = CK_RV C_DestroyObject.argtypes = [CK_SESSION_HANDLE, CK_OBJECT_HANDLE] @@ -2640,35 +2782,40 @@ class CK_SESSION_INFO(Structure): C_VerifyRecover.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] C_DigestEncryptUpdate = make_late_binding_function('C_DigestEncryptUpdate') C_DigestEncryptUpdate.restype = CK_RV -C_DigestEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DigestEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR] C_DecryptDigestUpdate = make_late_binding_function('C_DecryptDigestUpdate') C_DecryptDigestUpdate.restype = CK_RV -C_DecryptDigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptDigestUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR] C_SignEncryptUpdate = make_late_binding_function('C_SignEncryptUpdate') C_SignEncryptUpdate.restype = CK_RV C_SignEncryptUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] C_DecryptVerifyUpdate = make_late_binding_function('C_DecryptVerifyUpdate') C_DecryptVerifyUpdate.restype = CK_RV -C_DecryptVerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] +C_DecryptVerifyUpdate.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, + CK_ULONG_PTR] C_GenerateKey = make_late_binding_function('C_GenerateKey') C_GenerateKey.restype = CK_RV -C_GenerateKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_GenerateKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_OBJECT_HANDLE_PTR] C_GenerateKeyPair = make_late_binding_function('C_GenerateKeyPair') C_GenerateKeyPair.restype = CK_RV -C_GenerateKeyPair.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, - CK_ULONG, CK_OBJECT_HANDLE_PTR, CK_OBJECT_HANDLE_PTR] +C_GenerateKeyPair.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_ATTRIBUTE_PTR, CK_ULONG, + CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR, + CK_OBJECT_HANDLE_PTR] C_WrapKey = make_late_binding_function('C_WrapKey') C_WrapKey.restype = CK_RV -C_WrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, CK_BYTE_PTR, - CK_ULONG_PTR] +C_WrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_OBJECT_HANDLE, + CK_BYTE_PTR, CK_ULONG_PTR] C_UnwrapKey = make_late_binding_function('C_UnwrapKey') C_UnwrapKey.restype = CK_RV -C_UnwrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_ATTRIBUTE_PTR, - CK_ULONG, CK_OBJECT_HANDLE_PTR] +C_UnwrapKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_BYTE_PTR, + CK_ULONG, CK_ATTRIBUTE_PTR, CK_ULONG, CK_OBJECT_HANDLE_PTR] C_DeriveKey = make_late_binding_function('C_DeriveKey') C_DeriveKey.restype = CK_RV -C_DeriveKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG, - CK_OBJECT_HANDLE_PTR] +C_DeriveKey.argtypes = [CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE, CK_ATTRIBUTE_PTR, + CK_ULONG, CK_OBJECT_HANDLE_PTR] C_SeedRandom = make_late_binding_function('C_SeedRandom') C_SeedRandom.restype = CK_RV C_SeedRandom.argtypes = [CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG] @@ -2752,7 +2899,6 @@ class CK_SESSION_INFO(Structure): class CK_DATE(Structure): - """ """ pass @@ -2784,7 +2930,6 @@ class CK_DATE(Structure): class CK_C_INITIALIZE_ARGS(Structure): - """ """ pass @@ -2806,7 +2951,6 @@ class CK_C_INITIALIZE_ARGS(Structure): class CK_RSA_PKCS_OAEP_PARAMS(Structure): - """ """ pass @@ -2823,7 +2967,6 @@ class CK_RSA_PKCS_OAEP_PARAMS(Structure): class CK_RSA_PKCS_PSS_PARAMS(Structure): - """ """ pass @@ -2838,7 +2981,6 @@ class CK_RSA_PKCS_PSS_PARAMS(Structure): class CK_ECDH1_DERIVE_PARAMS(Structure): - """ """ pass @@ -2855,7 +2997,6 @@ class CK_ECDH1_DERIVE_PARAMS(Structure): class CK_ECDH2_DERIVE_PARAMS(Structure): - """ """ pass @@ -2876,7 +3017,6 @@ class CK_ECDH2_DERIVE_PARAMS(Structure): class CK_ECMQV_DERIVE_PARAMS(Structure): - """ """ pass @@ -2900,7 +3040,6 @@ class CK_ECMQV_DERIVE_PARAMS(Structure): class CK_X9_42_DH1_DERIVE_PARAMS(Structure): - """ """ pass @@ -2917,7 +3056,6 @@ class CK_X9_42_DH1_DERIVE_PARAMS(Structure): class CK_X9_42_DH2_DERIVE_PARAMS(Structure): - """ """ pass @@ -2938,7 +3076,6 @@ class CK_X9_42_DH2_DERIVE_PARAMS(Structure): class CK_X9_42_MQV_DERIVE_PARAMS(Structure): - """ """ pass @@ -2960,7 +3097,6 @@ class CK_X9_42_MQV_DERIVE_PARAMS(Structure): class CK_KEA_DERIVE_PARAMS(Structure): - """ """ pass @@ -2980,7 +3116,6 @@ class CK_KEA_DERIVE_PARAMS(Structure): class CK_RC2_CBC_PARAMS(Structure): - """ """ pass @@ -2994,7 +3129,6 @@ class CK_RC2_CBC_PARAMS(Structure): class CK_RC2_MAC_GENERAL_PARAMS(Structure): - """ """ pass @@ -3008,7 +3142,6 @@ class CK_RC2_MAC_GENERAL_PARAMS(Structure): class CK_RC5_PARAMS(Structure): - """ """ pass @@ -3022,7 +3155,6 @@ class CK_RC5_PARAMS(Structure): class CK_RC5_CBC_PARAMS(Structure): - """ """ pass @@ -3038,7 +3170,6 @@ class CK_RC5_CBC_PARAMS(Structure): class CK_RC5_MAC_GENERAL_PARAMS(Structure): - """ """ pass @@ -3055,7 +3186,6 @@ class CK_RC5_MAC_GENERAL_PARAMS(Structure): class CK_DES_CBC_ENCRYPT_DATA_PARAMS(Structure): - """ """ pass @@ -3070,7 +3200,6 @@ class CK_DES_CBC_ENCRYPT_DATA_PARAMS(Structure): class CK_AES_CBC_ENCRYPT_DATA_PARAMS(Structure): - """ """ pass @@ -3085,7 +3214,6 @@ class CK_AES_CBC_ENCRYPT_DATA_PARAMS(Structure): class CK_SKIPJACK_PRIVATE_WRAP_PARAMS(Structure): - """ """ pass @@ -3108,7 +3236,6 @@ class CK_SKIPJACK_PRIVATE_WRAP_PARAMS(Structure): class CK_SKIPJACK_RELAYX_PARAMS(Structure): - """ """ pass @@ -3134,7 +3261,6 @@ class CK_SKIPJACK_RELAYX_PARAMS(Structure): class CK_PBE_PARAMS(Structure): - """ """ pass @@ -3152,7 +3278,6 @@ class CK_PBE_PARAMS(Structure): class CK_KEY_WRAP_SET_OAEP_PARAMS(Structure): - """ """ pass @@ -3167,7 +3292,6 @@ class CK_KEY_WRAP_SET_OAEP_PARAMS(Structure): class CK_SSL3_RANDOM_DATA(Structure): - """ """ pass @@ -3182,7 +3306,6 @@ class CK_SSL3_RANDOM_DATA(Structure): class CK_SSL3_MASTER_KEY_DERIVE_PARAMS(Structure): - """ """ pass @@ -3196,7 +3319,6 @@ class CK_SSL3_MASTER_KEY_DERIVE_PARAMS(Structure): class CK_SSL3_KEY_MAT_OUT(Structure): - """ """ pass @@ -3214,7 +3336,6 @@ class CK_SSL3_KEY_MAT_OUT(Structure): class CK_SSL3_KEY_MAT_PARAMS(Structure): - """ """ pass @@ -3232,7 +3353,6 @@ class CK_SSL3_KEY_MAT_PARAMS(Structure): class CK_TLS_PRF_PARAMS(Structure): - """ """ pass @@ -3250,7 +3370,6 @@ class CK_TLS_PRF_PARAMS(Structure): class CK_WTLS_RANDOM_DATA(Structure): - """ """ pass @@ -3266,7 +3385,6 @@ class CK_WTLS_RANDOM_DATA(Structure): class CK_WTLS_MASTER_KEY_DERIVE_PARAMS(Structure): - """ """ pass @@ -3281,7 +3399,6 @@ class CK_WTLS_MASTER_KEY_DERIVE_PARAMS(Structure): class CK_WTLS_PRF_PARAMS(Structure): - """ """ pass @@ -3300,7 +3417,6 @@ class CK_WTLS_PRF_PARAMS(Structure): class CK_WTLS_KEY_MAT_OUT(Structure): - """ """ pass @@ -3315,7 +3431,6 @@ class CK_WTLS_KEY_MAT_OUT(Structure): class CK_WTLS_KEY_MAT_PARAMS(Structure): - """ """ pass @@ -3335,7 +3450,6 @@ class CK_WTLS_KEY_MAT_PARAMS(Structure): class CK_CMS_SIG_PARAMS(Structure): - """ """ pass @@ -3355,7 +3469,6 @@ class CK_CMS_SIG_PARAMS(Structure): class CK_KEY_DERIVATION_STRING_DATA(Structure): - """ """ pass @@ -3375,7 +3488,6 @@ class CK_KEY_DERIVATION_STRING_DATA(Structure): class CK_PKCS5_PBKD2_PARAMS(Structure): - """ """ pass @@ -3398,7 +3510,6 @@ class CK_PKCS5_PBKD2_PARAMS(Structure): class CK_OTP_PARAM(Structure): - """ """ pass @@ -3413,7 +3524,6 @@ class CK_OTP_PARAM(Structure): class CK_OTP_PARAMS(Structure): - """ """ pass @@ -3427,7 +3537,6 @@ class CK_OTP_PARAMS(Structure): class CK_OTP_SIGNATURE_INFO(Structure): - """ """ pass @@ -3441,7 +3550,6 @@ class CK_OTP_SIGNATURE_INFO(Structure): class CK_KIP_PARAMS(Structure): - """ """ pass @@ -3464,7 +3572,6 @@ class CK_KIP_PARAMS(Structure): class CK_CAMELLIA_CTR_PARAMS(Structure): - """ """ pass @@ -3478,7 +3585,6 @@ class CK_CAMELLIA_CTR_PARAMS(Structure): class CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS(Structure): - """ """ pass @@ -3493,7 +3599,6 @@ class CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS(Structure): class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): - """ """ pass @@ -3516,7 +3621,8 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_ECC_NOT_SUPPORTED', 'CK_CA_Restart', 'C_SetAttributeValue', 'CA_STCSetDigestAlgorithm', 'LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE', - 'LUNA_RET_MD5_SELF_TEST_FAILURE', 'LUNA_RET_LOG_BAD_TIME', + 'LUNA_RET_FM_ID_INVALID', 'LUNA_RET_MD5_SELF_TEST_FAILURE', + 'LUNA_RET_LOG_BAD_TIME', 'LUNA_RET_SM_CONTEXT_NOT_ALLOCATED', 'CK_C_SetOperationState', 'MSG_NVRAM_READ_FAILED', 'C_VerifyFinal', 'CK_DATE', @@ -3552,7 +3658,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_OTP_PARAM_PTR', 'CK_X9_42_MQV_DERIVE_PARAMS', 'LUNA_RET_N_TOO_LARGE', 'CK_CA_GetHAState', 'C_CloseAllSessions', 'CK_CA_STCSetKeyActivationTimeOut', - 'C_SignInit', 'LUNA_RET_MISSING_NUMBER_OF_VECTORS', + 'C_SignInit', 'LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL', 'CK_CMS_SIG_PARAMS', 'CA_GetRemotePEDVectorStatus', 'CK_C_GetFunctionList', 'LUNA_RET_CANCEL', 'LUNA_RET_RNG_SELF_TEST_FAILURE', 'CK_CA_LogGetStatus', @@ -3560,6 +3666,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_TOO_MANY_WEIGHTS', 'CA_IndirectLogin', 'CA_OpenSecureToken', 'LUNA_RET_INVALID_FUF_TARGET', 'CA_GenerateMofN', 'CK_CA_MTKResplit', + 'LUNA_RET_STM_CMD_NON_TRANSPORT', 'LUNA_RET_MD2_SELF_TEST_FAILURE', 'CA_HALogin', 'CK_CA_RetrieveLicenseList', 'LUNA_RET_SAVED_STATE_INVALID', 'CK_ECMQV_DERIVE_PARAMS', @@ -3572,9 +3679,9 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CA_GetHSMStorageInformation', 'LUNA_RET_HIFN_DESTINATION_OVERRUN', 'LUNA_RET_ISES_LNAU_TEST_FAILED', - 'LUNA_RET_SM_SESSION_REALLOC_ERROR', 'CA_MOFN_ACTIVATION', - 'MSG_GENERATING_NEW_TVK_PASSED', - 'LUNA_RET_DES_SELF_TEST_FAILURE', + 'LUNA_RET_SM_SESSION_REALLOC_ERROR', + 'LUNA_RET_KEY_NOT_KEKED', 'CA_MOFN_ACTIVATION', + 'MSG_GENERATING_NEW_TVK_PASSED', 'RC_BUFFER_TOO_SMALL', 'LUNA_RET_UNWRAPPING_ERROR', 'LUNA_RET_TIME_NOT_INITIALIZED', 'LUNA_RET_HIFN_DMA_INVALID_REVISION', @@ -3583,27 +3690,27 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'RC_UNKNOWN_COMMAND_VERSION', 'LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE', 'CK_CA_GetTime', 'LUNA_RET_CCM_NOT_PRESENT', 'Word', 'CA_LogVerifyFile', - 'CK_DES_CTR_PARAMS', 'CA_GetClusterState', 'CK_C_Verify', - 'CK_CA_STCGetCipherAlgorithm', 'CA_STCGetMaxSessions', - 'CK_OBJECT_HANDLE', 'LUNA_RET_TOKEN_LOCKED_OUT', - 'CK_MAC_GENERAL_PARAMS', 'CK_C_VerifyUpdate', - 'CK_CA_WriteCommonStore', 'CA_GetPedId', 'CA_Insert', - 'LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE', + 'CK_DES_CTR_PARAMS', 'CA_GetClusterState', + 'CA_STMGetState', 'CK_CA_STCGetCipherAlgorithm', + 'CA_STCGetMaxSessions', 'CK_OBJECT_HANDLE', + 'LUNA_RET_TOKEN_LOCKED_OUT', 'CK_MAC_GENERAL_PARAMS', + 'CK_C_VerifyUpdate', 'CK_CA_WriteCommonStore', + 'CA_GetPedId', 'CA_Insert', 'LUNA_RET_CCM_UNREMOVABLE', 'CK_EC_MAC_SCHEME', 'LUNA_RET_TSN_MISMATCH', 'RC_FILE_LOCK_FAILED', 'RC_UNKNOWN_COMMAND', 'CK_CA_STCGetClientInfo', 'LUNA_RET_ECC_DAC_MISSING', 'CA_ConfigureRemotePED', 'CA_STCGetPubKey', 'LUNA_RET_WRAPPED_KEY_INVALID', 'CK_C_WrapKey', 'MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY', 'CA_SpRawWrite', - 'CK_KDF_PRF_PARAMS', 'CK_ULONG', + 'LUNA_RET_UM_PIN_INVALID', 'CK_KDF_PRF_PARAMS', 'CK_ULONG', 'RC_STC_RESPONSE_DECRYPT_ERROR', 'CA_GetPrimarySlot', 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR', - 'CK_X9_42_DH1_DERIVE_PARAMS', - 'LUNA_RET_HIFN_DMA_TIMED_OUT', + 'LUNA_RET_MM_FATAL_ERROR', 'LUNA_RET_HIFN_DMA_TIMED_OUT', 'LUNA_RET_MISSING_WEIGHT_VALUE', 'Float', 'CK_DESTROYMUTEX', 'LUNA_RET_HIFN_NOT_PRESENT', - 'LUNA_RET_TOO_MANY_VECTORS_PROVIDED', 'CK_C_DigestFinal', - 'CA_InitIndirectPIN', 'LUNA_RET_PED_DEK_INVALID', + 'LUNA_RET_TOO_MANY_VECTORS_PROVIDED', + 'CK_ECMQV_DERIVE_PARAMS_PTR', 'CA_InitIndirectPIN', + 'LUNA_RET_SIM_AUTHORIZATION_FAILED', 'CK_CA_DeactivateMofN', 'CK_CA_STCGetPubKey', 'RC_USB_PED_TOO_MANY_CONNECTED', 'CA_SpRawRead', 'CA_DestroyMultipleObjects', 'LUNA_RET_CCM_TOO_LARGE', @@ -3631,22 +3738,22 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_CA_STCIsEnabled', 'CA_CloneModifyMofN', 'CK_C_DecryptFinal', 'LUNA_RET_FLAGS_INVALID', 'CK_CA_SetContainerPolicy', 'RC_STC_SESSION_INVALID', - 'eInitMsgs', 'LUNA_RET_COUNTER_WRAPAROUND', + 'eInitMsgs', 'CK_FLAGS', 'CK_CA_STCSetDigestAlgorithm', + 'LUNA_RET_COUNTER_WRAPAROUND', 'MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED', 'CA_GetFPV', 'CK_HA_MEMBER_PTR', 'LUNA_RET_VECTOR_TYPE_INVALID', 'C_Digest', 'CK_CA_SetRDK', 'LUNA_RET_RC4_SELF_TEST_FAILURE', 'CA_HAAnswerLoginChallenge', 'BYTE', - 'CK_CA_GetSessionInfo', - 'RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR', - 'C_SignEncryptUpdate', 'RC_SHUTTING_DOWN', - 'CK_MECHANISM_TYPE_PTR', 'MSG_RTC_CANT_GET_TAMPER_TIMER', + 'CK_CA_GetSessionInfo', 'C_SignEncryptUpdate', + 'RC_SHUTTING_DOWN', 'CK_MECHANISM_TYPE_PTR', + 'MSG_RTC_CANT_GET_TAMPER_TIMER', 'LUNA_RET_RM_BAD_HSM_PARAMS', 'CK_XOR_BASE_DATA_KDF_PARAMS_PTR', 'CK_SESSION_INFO', 'LUNA_RET_SM_MEMORY_ALLOCATION_ERROR', 'CK_CA_CloneObjectToAllSessions', 'CK_CA_FirmwareRollback', 'CK_WTLS_KEY_MAT_OUT', 'CK_WTLS_KEY_MAT_PARAMS', - 'CA_ExtractMaskedObject', + 'CA_ReplaceFastPathKEK', 'CA_ExtractMaskedObject', 'CK_CA_GetNumberOfAllowedContainers', 'C_DigestEncryptUpdate', 'UInt16', 'LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES', @@ -3662,8 +3769,9 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED', 'MSG_LOG_WAS_TRUNCATED', 'RC_SSL_CTX_ERROR', 'CA_GetTokenObjectHandle', 'C_EncryptFinal', - 'CK_CA_TokenZeroize', 'CK_EC_KDF_TYPE', 'CKCA_MODULE_ID', - 'CA_LogVerify', 'LUNA_RET_CCM_CERT_INVALID', + 'CK_CA_TokenZeroize', 'CK_EC_KDF_TYPE', + 'CA_InitializeRemotePEDVector', 'CA_LogVerify', + 'LUNA_RET_CCM_CERT_INVALID', 'CA_SetDestructiveHSMPolicies', 'CK_CA_ManualKCV', 'LUNA_RET_HIFN6500_NOT_PRESENT', 'CA_LogGetStatus', 'LUNA_RET_CB_HIOS_SEND_TIMEOUT', @@ -3673,6 +3781,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_FUNCTION_NOT_SUPPORTED', 'CK_CREATEMUTEX', 'LUNA_RET_INVALID_PADDING_TYPE', 'CK_CA_LKMInitiatorComplete', + 'LUNA_RET_RNG_RESEED_REQUIRED', 'LUNA_RET_MM_NOT_ENOUGH_MEMORY', 'RC_SSL_GET_PEER_CERT_ERROR', 'LUNA_RET_ATTRIBUTE_READ_ONLY', 'RC_NO_BUFFER', @@ -3699,7 +3808,8 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_SM_ACCESS_REALLOC_ERROR', 'CA_WriteCommonStore', 'CA_CloseSecureToken', 'LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN', - 'CK_RC5_MAC_GENERAL_PARAMS_PTR', 'CK_CA_ClonePrivateKey', + 'CK_RC5_MAC_GENERAL_PARAMS_PTR', + 'LUNA_RET_DES_SELF_TEST_FAILURE', 'CK_CA_ClonePrivateKey', 'LUNA_RET_RM_ELEMENT_ID_INVALID', 'LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE', 'RC_CMD_BLOCKED_REMOTE_PED_TUNNEL', 'CK_C_EncryptFinal', @@ -3716,10 +3826,10 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_CA_CloseApplicationIDForContainer', 'LUNA_RET_SIM_AUTHFORM_INVALID', 'LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO', - 'CA_STCGetKeyLifeTime', 'CK_RC2_MAC_GENERAL_PARAMS', - 'CK_SESSION_HANDLE', 'LUNA_RET_KEY_INDIGESTIBLE', - 'CK_SLOT_INFO', 'CA_STCGetDigestID', - 'LUNA_RET_PED_ID_INVALID', + 'LUNA_RET_KEY_CANNOT_BE_KEKED', 'CA_STCGetKeyLifeTime', + 'CK_RC2_MAC_GENERAL_PARAMS', 'CK_SESSION_HANDLE', + 'LUNA_RET_KEY_INDIGESTIBLE', 'CK_SLOT_INFO', + 'CA_STCGetDigestID', 'LUNA_RET_PED_ID_INVALID', 'MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK', 'LUNA_RET_CAN_NOT_CREATE_SECRET_KEY', 'CK_CA_GetHSMPolicySetting', @@ -3727,7 +3837,8 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CA_STCGetCipherAlgorithm', 'RC_DATA_CORRUPTED', 'CK_SESSION_HANDLE_PTR', 'CK_RC2_MAC_GENERAL_PARAMS_PTR', 'CA_CloseApplicationID', 'LUNA_RET_CB_HIOS_RECV_TIMEOUT', - 'CK_C_Logout', 'CA_HAGetLoginChallenge', 'CA_SetRDK', + 'CK_C_Logout', 'CA_HAGetLoginChallenge', + 'LUNA_RET_RECALCULATE_K', 'CA_SetRDK', 'LUNA_RET_CCM_UPDATE_DENIED', 'LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT', 'LUNA_RET_GENERAL_ERROR', @@ -3737,15 +3848,17 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_UM_PIN_LEN_RANGE', 'CK_SFNT_CA_FUNCTION_LIST_PTR', 'CK_SKIPJACK_PRIVATE_WRAP_PTR', 'LUNA_RET_ECC_DAK_MISSING', - 'LUNA_RET_HIFN6500_RESET_TIMEOUT', 'CK_CA_GetObjectUID', + 'RC_GROUP_NAME_INVALID', 'CK_CA_GetObjectUID', 'LUNA_RET_ISES_RNG_TEST_FAILED', 'MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC', 'C_SetOperationState', 'CK_CA_ConfigureRemotePED', - 'CK_C_SignRecoverInit', 'CK_CA_STCGetDigestAlgorithm', - 'LUNA_RET_DATA_INVALID', 'CK_CERTIFICATE_TYPE', + 'CK_C_SignRecoverInit', 'LUNA_RET_RNG_RESEED_TOO_EARLY', + 'CK_CA_STCGetDigestAlgorithm', 'LUNA_RET_DATA_INVALID', + 'CK_CERTIFICATE_TYPE', 'RC_REMOTE_PEER_OFFLINE', 'LUNA_RET_M_OF_N_PARAMETER_EXIST', 'RC_SSL_WANT_WRITE_ERROR', 'CA_Extract', 'CK_OBJECT_CLASS', - 'CA_STCGetAdminPubKey', 'C_VerifyRecover', 'CK_FLAGS', + 'CA_STCGetAdminPubKey', 'C_VerifyRecover', + 'LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID', 'LUNA_RET_OPERATION_RESTRICTED', 'LUNA_RET_SM_UNKNOWN_ACCESS_TYPE', 'LUNA_RET_MAC_MISSING', 'CA_STCGetCipherNameByID', 'CA_GetObjectHandle', @@ -3755,18 +3868,18 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'C_VerifyRecoverInit', 'RC_OBJECT_NOT_IN_LIST', 'LUNA_RET_ECC_SELF_TEST_FAILURE', 'C_DigestKey', 'RC_OPERATION_WOULD_BLOCK', 'LUNA_RET_MM_INVALID_HANDLE', - 'LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL', 'CA_LogExternal', 'LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT', 'LUNA_RET_WRAPPING_KEY_HANDLE_INVALID', 'RC_MANUFACTURING_TOKEN_NOT_PRESENT', - 'CK_CA_GetFunctionList', 'CK_CA_CloneAsTarget', - 'CK_CA_HALogin', 'CA_CloneAsSource', + 'CK_CA_GetFunctionList', 'CA_GetPartitionPolicyTemplate', + 'CK_CA_CloneAsTarget', 'CK_CA_HALogin', 'CA_CloneAsSource', 'LUNA_RET_MAX_OBJECT_COUNT', 'CK_KEY_TYPE', 'CK_RSA_PKCS_PSS_PARAMS', 'LUNA_RET_OBJECT_DELETED', 'CK_CA_GetSecondarySlot', 'UInt32', 'CA_OpenSessionWithAppID', 'LUNA2_RET_HIFN_RESET_ERROR', - 'RC_UNEXPECTED', 'CA_InvokeServiceFinal', + 'RC_UNEXPECTED', 'MSG_PARTITION_STC_POLICY_SET', + 'CA_InvokeServiceFinal', 'CK_AES_XTS_PARAMS_PTR', 'RC_STC_CLIENT_IDENTITY_NOT_CONFIGURED', 'C_OpenSession', 'CK_CA_SetUserContainerName', 'LUNA_RET_STC_CLIENT_HANDLE_INVALID', @@ -3784,7 +3897,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_CAMELLIA_CTR_PARAMS', 'RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR', 'CK_C_INITIALIZE_ARGS_PTR', 'CK_CA_SetLKCV', - 'LUNA_RET_CB_REMOTE_ABORT', 'RC_BUFFER_TOO_SMALL', + 'LUNA_RET_CB_REMOTE_ABORT', 'CK_AES_CBC_PAD_INSERT_PARAMS_PTR', 'LUNA_RET_SIGNATURE_LEN_RANGE', 'MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF', @@ -3793,16 +3906,17 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_WTLS_KEY_MAT_OUT_PTR', 'MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING', 'LUNA_RET_LOG_BAD_FILE_NAME', 'CK_PKCS5_PBKD2_PARAMS', - 'RC_STC_COMPUTE_DH_KEY_ERROR', - 'LUNA_RET_CB_HIOS_ID_INVALID', 'CA_CloneMofN', - 'RC_STC_CLIENT_HANDLE_INVALID', 'LUNA_RET_PE1746_ERROR', - 'CK_CA_GenerateMofN', 'CK_CA_GetPrimarySlot', 'Int64', + 'CK_C_Verify', 'LUNA_RET_CB_HIOS_ID_INVALID', + 'CA_CloneMofN', 'RC_STC_CLIENT_HANDLE_INVALID', + 'LUNA_RET_PE1746_ERROR', 'CK_CA_GenerateMofN', + 'CK_CA_GetPrimarySlot', 'Int64', 'CK_X9_42_DH2_DERIVE_PARAMS', 'CA_ClonePrivateKey', 'CA_CloseSecondarySession', 'LUNA_RET_CONTAINER_IS_DISABLED', 'CK_CA_OpenApplicationIDForContainer', - 'LUNA_RET_STC_NOT_ENABLED', 'LUNA_RET_ROOT_CERT_MISSING', - 'CA_DeleteContainer', 'LUNA_RET_CHALLENGE_NOT_REQUIRED', + 'LUNA_RET_MUTEX_BAD', 'LUNA_RET_STC_NOT_ENABLED', + 'LUNA_RET_ROOT_CERT_MISSING', 'CA_DeleteContainer', + 'LUNA_RET_CHALLENGE_NOT_REQUIRED', 'CA_DeleteRemotePEDVector', 'CK_CA_UnlockClusteredSlot', 'CK_CA_GetTokenCapabilities', 'CK_CA_CloneModifyMofN', 'LUNA_RET_STC_OPEN_KEY_MATERIAL_GEN_FAIL', 'CK_STATE', @@ -3816,8 +3930,8 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'C_Verify', 'CK_CA_Extract', 'LUNA_RET_SFNT3120_CRC', 'CK_C_SetAttributeValue', 'CK_CA_GetHSMCapabilitySet', 'CA_SIMMultiSign', 'LUNA_RET_LOG_FILE_WRITE_ERROR', - 'C_DecryptFinal', 'Byte', 'CK_CA_CloneAsSource', - 'CK_FUNCTION_LIST_PTR', + 'RC_PARTITION_ROLE_DESC_VERSION_INVALID', 'C_DecryptFinal', + 'Byte', 'CK_CA_CloneAsSource', 'CK_FUNCTION_LIST_PTR', 'LUNA_RET_FORMER_INVALID_ENTRY_TYPE', 'CA_ActivateMofN', 'CK_CA_HAGetMasterPublic', 'CK_SFNT_CA_FUNCTION_LIST', 'RC_STC_NO_CHANNEL', 'CK_CA_OpenApplicationID', @@ -3830,9 +3944,10 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'RC_STC_REKEY_CHANNEL_MISMATCH', 'CK_SSL3_KEY_MAT_PARAMS', 'CK_KIP_PARAMS_PTR', 'CK_CA_WaitForSlotEvent', 'CK_OTP_SIGNATURE_INFO_PTR', + 'LUNA_RET_CHALLENGE_TYPE_INVALID', 'LUNA_RET_SM_UNKNOWN_SESSION_TYPE', 'CA_GetSessionInfo', - 'CK_WTLS_RANDOM_DATA', 'CK_USHORT', - 'LUNA_RET_MISSING_SPLITS', + 'CK_WTLS_RANDOM_DATA', 'CK_USHORT', 'LUNA_RET_NO_INVERSE', + 'LUNA_RET_SEED_SELF_TEST_FAILURE', 'LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL', 'CK_CA_LoadEncryptedModule', 'MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED', @@ -3860,6 +3975,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED', 'CK_MECHANISM_TYPE', 'CA_SetKCV', 'RC_USB_PED_NOT_RESPONDING', + 'LUNA_RET_MEMORY_ALLOCATION_FAILED', 'MSG_ZEROIZING_AFTER_DECOMMISSION', 'CK_CA_GetContainerStorageInformation', 'CK_ATTRIBUTE', 'CK_CA_SetDestructiveHSMPolicies', @@ -3872,7 +3988,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_C_SeedRandom', 'LUNA_RET_HAS160_SELF_TEST_FAILURE', 'LUNA_RET_MM_USAGE_ALREADY_SET', 'CA_GetHAState', 'C_SignRecoverInit', 'CK_CA_STCGetClientsList', - 'RC_STC_RESPONSE_REPLAYED', + 'CK_C_FindObjectsFinal', 'LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED', 'CK_CA_GetContainerPolicySetting', 'CK_CA_STCSetKeyLifeTime', 'CK_BYTE', @@ -3886,16 +4002,17 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CA_SetContainerSize', 'LUNA_RET_SM_ACCESS_ID_INVALID', 'CA_GetContainerPolicySetting', 'CK_CA_CloseAllSecondarySessions', 'CA_GenerateTokenKeys', - 'CK_CA_SetMofN', 'CA_TimeSync', 'CA_LKMInitiatorChallenge', - 'CA_InitializeRemotePEDVector', 'HalfWord', + 'RC_REMOTE_SIDE_DISCONNECTED', 'CA_TimeSync', + 'CA_LKMInitiatorChallenge', 'HalfWord', 'CK_C_GetMechanismList', 'RC_SSL_LOAD_SERVER_CERT_ERROR', + 'LUNA_RET_MISSING_NUMBER_OF_VECTORS', 'CK_CA_EncodeECPrimeParams', 'CK_VOID_PTR_PTR', 'CA_MOFN_STATUS', 'CK_CA_FindAdminSlotForSlot', 'CK_C_CopyObject', 'CK_CA_CreateLoginChallenge', 'CK_CA_STCGetMaxSessions', 'CT_TokenHndle', 'MSG_RTC_MSG_NVRAM_READ_FAILED', 'C_SetPIN', 'LUNA_RET_ECC_HOK_MISSING', 'CA_InitIndirectToken', - 'C_GenerateKey', 'RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR', + 'C_GenerateKey', 'LUNA_RET_TEMPLATE_INCOMPLETE', 'CK_CA_STCGetCipherIDs', 'C_InitPIN', 'RC_STC_CONTAINER_INVALID', 'LUNA_RET_DAK_MISSING', 'CK_C_GetSlotInfo', 'RC_INVALID_INDEX', 'CK_ECIES_PARAMS', @@ -3907,8 +4024,8 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_CB_SYNC_ERROR', 'CK_AES_CTR_PARAMS', 'CK_LKM_TOKEN_ID_S', 'CA_SetExtendedTPV', 'CK_CA_STCRegister', 'CA_HAInit', - 'CK_X9_42_DH2_DERIVE_PARAMS_PTR', 'CA_InitRolePIN', - 'CK_CA_TimeSync', 'LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE', + 'CK_X9_42_DH2_DERIVE_PARAMS_PTR', 'CK_CA_TimeSync', + 'LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE', 'CK_CA_DeleteRemotePEDVector', 'CA_LogImportSecret', 'CK_KEY_WRAP_SET_OAEP_PARAMS_PTR', 'CA_STCGetDigestNameByID', 'LUNA_RET_FUNCTION_CANCELED', @@ -3940,18 +4057,20 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_KEA_DERIVE_PARAMS', 'CK_CA_FirmwareUpdate', 'CK_CA_OpenSession', 'LUNA_RET_STC_ACTIVATE_MACTAG_V_GEN_FAIL', - 'CK_CA_STCSetDigestAlgorithm', 'CA_Restart', 'UInt64', - 'CK_C_Sign', 'CK_CA_ReadCommonStore', + 'LUNA_RET_MECHANISM_INVALID_FOR_FP', 'CA_Restart', + 'UInt64', 'CK_C_Sign', 'CK_CA_ReadCommonStore', 'LUNA_RET_ATTRIBUTE_VALUE_INVALID', 'CKCA_MODULE_ID_PTR', 'LUNA_RET_SM_ACCESS_ALREADY_EXISTS', 'CK_LONG', - 'CA_MOFN_GENERATION', + 'CA_MOFN_GENERATION', 'LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO', 'LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE', 'LUNA_RET_CAST5_SELF_TEST_FAILURE', 'CK_CA_ListSecureTokenUpdate', 'RC_CACHE_DIRTY', 'LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH', - 'RC_STC_SECOND_PHASE_KDF_ERROR', 'LUNA_RET_RM_NO_MEMORY', - 'CK_CA_SetKCV', 'CK_OBJECT_HANDLE_PTR', - 'CA_LogExportSecret', 'CK_CA_InvokeServiceFinal', + 'RC_STC_SECOND_PHASE_KDF_ERROR', + 'LUNA_RET_SESSION_HANDLE_INVALID_FOR_FP', + 'LUNA_RET_RM_NO_MEMORY', 'CK_CA_SetKCV', + 'CK_OBJECT_HANDLE_PTR', 'CA_LogExportSecret', + 'CK_CA_InvokeServiceFinal', 'LUNA_RET_CL_TRANSMISSION_ERROR', 'RC_FAILED_TO_CREATE_THREAD', 'RC_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE', 'CK_CA_HAInit', @@ -3987,7 +4106,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'RC_CLIENT_DISCONNECTED', 'LUNA_RET_CB_PROT_DATA_INVALID', 'C_VerifyInit', 'LUNA_RET_CL_ALIGNMENT_ERROR', 'CK_SKIPJACK_PRIVATE_WRAP_PARAMS', 'CA_SetTokenPolicies', - 'LUNA_RET_HIFN6500_INVALID_PARAMETERS', + 'LUNA_RET_HIFN6500_INVALID_PARAMETERS', 'CKCA_MODULE_ID', 'CK_CA_DeleteContainerWithHandle', 'CK_LOCKMUTEX', 'LUNA_RET_WRAPPING_ERROR', 'CK_CA_GenerateCloningKEV', 'MSG_RTC_CANT_ACCESS', 'CK_C_DecryptUpdate', @@ -4021,7 +4140,8 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_C_EncryptUpdate', 'LUNA_RET_M_OF_N_IS_NOT_REQUIRED', 'Boolean', 'CK_CA_Zeroize', 'LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID', - 'CK_WTLS_KEY_MAT_PARAMS_PTR', 'LUNA_RET_CCM_UNREMOVABLE', + 'CK_WTLS_KEY_MAT_PARAMS_PTR', + 'LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE', 'CK_CA_InitIndirectToken', 'CA_GetTSV', 'CK_RC5_PARAMS', 'MSG_BAD_HMAC', 'C_SignFinal', 'LUNA_RET_INVALID_CERTIFICATE_DATA', 'CK_C_GenerateKey', @@ -4070,16 +4190,20 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_DAC_MISSING', 'CK_ULONG_PTR', 'CK_KDF_PRF_PARAMS_PTR', 'CA_STCGetDigestAlgorithm', 'LUNA_RET_CB_MUST_WRITE', - 'LUNA_RET_SM_OTHER_USER_LOGGED_IN', 'CK_CA_GetTokenStatus', - 'CA_GetContainerCapabilitySetting', + 'LUNA_RET_SM_OTHER_USER_LOGGED_IN', + 'RC_PARTITION_ROLE_POLICY_SET_VERSION_INVALID', + 'CK_CA_GetTokenStatus', 'CA_CreateContainerWithPolicy', + 'CA_GetContainerCapabilitySetting', 'CA_DeriveKeyAndWrap', 'RC_SSL_WANT_X509_LOOKUP_ERROR', 'RC_SOCKET_WOULDBLOCK', 'CA_InvokeServiceAsynch', 'CK_C_GetInfo', - 'CK_C_FindObjectsFinal', 'CK_CA_SetApplicationID', + 'RC_STC_RESPONSE_REPLAYED', 'CK_CA_SetApplicationID', 'CK_AES_CBC_ENCRYPT_DATA_PARAMS', - 'CK_C_DecryptVerifyUpdate', 'CK_CA_DestroyMultipleObjects', + 'CK_C_DecryptVerifyUpdate', 'CK_CA_STMToggle', + 'CK_CA_DestroyMultipleObjects', 'CK_KEY_DERIVATION_STRING_DATA_PTR', - 'LUNA_RET_INVALID_VECTOR_SIZE', 'MSG_RTC_BATTERY_LOW', - 'LUNA_RET_TOKEN_LOCKED_OUT_RN', + 'RC_PARTITION_ROLE_POLICY_VERSION_INVALID', + 'CK_CA_ReplaceFastPathKEK', 'LUNA_RET_INVALID_VECTOR_SIZE', + 'MSG_RTC_BATTERY_LOW', 'LUNA_RET_TOKEN_LOCKED_OUT_RN', 'CK_CA_InvokeServiceSinglePart', 'ULong', 'CK_CA_QueryLicense', 'CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR', 'CK_SLOT_ID_PTR', 'CA_TokenInsert', @@ -4103,12 +4227,12 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR', 'LUNA_RET_USER_PIN_NOT_INITIALIZED', 'CK_C_Decrypt', 'CK_CA_CloneMofN', 'CK_CA_IsMofNRequired', - 'LUNA_RET_CHALLENGE_REQUIRES_PED', 'RC_GROUP_NAME_INVALID', - 'C_Sign', 'CA_STCClearCipherAlgorithm', - 'LUNA_RET_WEIGHT_TOO_LARGE', + 'LUNA_RET_CHALLENGE_REQUIRES_PED', + 'LUNA_RET_HIFN6500_RESET_TIMEOUT', 'C_Sign', + 'CA_STCClearCipherAlgorithm', 'LUNA_RET_WEIGHT_TOO_LARGE', 'LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE', 'CK_C_DigestUpdate', 'LUNA_RET_KEY_SIZE_RANGE', - 'LUNA_RET_MM_FATAL_ERROR', 'C_GetFunctionList', + 'CK_X9_42_DH1_DERIVE_PARAMS', 'C_GetFunctionList', 'CK_CA_SetCloningDomain', 'CK_C_Initialize', 'CA_GetTokenObjectUID', 'C_GetOperationState', 'CK_C_GetSessionInfo', 'CK_BBOOL', @@ -4120,6 +4244,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY', 'CA_GetRollbackFirmwareVersion', 'LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED', + 'LUNA_RET_OPERATION_INVALID_FOR_FP', 'CK_C_GenerateKeyPair', 'CK_CA_STCGetCurrentKeyLife', 'LUNA_RET_MTK_STATE_INVALID', 'CK_CA_GetTokenObjectUID', 'CK_CA_PerformSelfTest', 'CK_ECDH2_DERIVE_PARAMS', @@ -4129,9 +4254,9 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE', 'LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD', 'LUNA_RET_SELF_TEST_FAILURE', - 'LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL', - 'RC_REMOTE_SIDE_DISCONNECTED', 'RC_SSL_CIPHER_LIST_ERROR', - 'CK_CA_DismantleRemotePED', 'LUNA_RET_INVALID_FUF_VERSION', + 'LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL', 'CK_CA_SetMofN', + 'RC_SSL_CIPHER_LIST_ERROR', 'CK_CA_DismantleRemotePED', + 'LUNA_RET_INVALID_FUF_VERSION', 'LUNA_RET_RIPEMD160_SELF_TEST_FAILURE', 'CA_GetTokenCapabilities', 'CK_OBJECT_CLASS_PTR', 'CK_RC2_PARAMS', 'RC_MANUFACTURING_NO_CONFIG_AVAILABLE', @@ -4140,7 +4265,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'RC_RESET_FAILED', 'HSM_STATS_PARAMS', 'LUNA_RET_TOKEN_LOCKED_OUT_CL', 'CK_CA_SetDestructiveHSMPolicy', 'CK_CA_InvokeServiceInit', - 'CA_GetMofNStatus', 'LUNA_RET_SIM_AUTHORIZATION_FAILED', + 'CA_GetMofNStatus', 'LUNA_RET_PED_DEK_INVALID', 'LUNA_RET_HA_NOT_SUPPORTED', 'CK_OTP_PARAM', 'CA_STCRegister', 'RC_UNABLE_TO_CONNECT', 'CK_CA_SpRawRead', @@ -4175,27 +4300,26 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR', 'LUNA_RET_BAD_MAC', 'CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR', 'LUNA_RET_CB_RETRY', 'MSG_RESTART', 'RC_FILE_NAME_INVALID', - 'C_DecryptDigestUpdate', 'CK_AES_GCM_PARAMS', - 'CK_HA_STATE_PTR', 'CA_LogGetConfig', - 'LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID', - 'CA_SetHSMPolicies', 'LUNA_RET_KCV_PARAMETER_MISSING', + 'C_DecryptDigestUpdate', 'CK_AES_XTS_PARAMS', 'CA_Get', + 'CK_AES_GCM_PARAMS', 'CK_HA_STATE_PTR', 'CA_LogGetConfig', + 'CA_STCGetCurrentKeyLife', 'CA_SetHSMPolicies', + 'CA_STMToggle', 'LUNA_RET_KCV_PARAMETER_MISSING', 'CK_XOR_BASE_DATA_KDF_PARAMS', 'C_Finalize', 'RC_SOCKET_ERROR', 'CA_InitAudit', 'LUNA_RET_KEY_PARITY', 'MSG_RTC_CANT_INITIALIZE_I2C', 'LUNA_RET_STORAGE_TYPE_INCONSISTENT', - 'CK_CA_GetExtendedTPV', 'CK_CA_SetHSMPolicy', + 'LUNA_RET_SENTRY_PKA_ERROR', 'CK_CA_SetHSMPolicy', 'CK_CA_OpenSecureToken', 'CA_CapabilityUpdate', 'C_GetSlotInfo', 'CK_HA_MEMBER', 'LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST', 'CA_STCGetDigestIDs', 'C_FindObjectsInit', 'CA_SIMExtract', - 'CA_DisableUnauthTokenInsertion', 'CK_C_FindObjectsInit', - 'CK_CA_STCGetSequenceWindowSize', + 'CK_CA_GetExtendedTPV', 'CA_DisableUnauthTokenInsertion', + 'CK_C_FindObjectsInit', 'CK_CA_STCGetSequenceWindowSize', 'LUNA_RET_RC2_SELF_TEST_FAILURE', 'CK_RSA_PKCS_OAEP_SOURCE_TYPE', 'CK_UNLOCKMUTEX', 'LUNA_RET_ARGUMENTS_BAD', 'CKCA_MODULE_INFO', - 'MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF', - 'CK_RC5_CBC_PARAMS', 'CA_InvokeServiceSinglePart', - 'CK_KDF_PRF_ENCODING_SCHEME', + 'RC_PARTITION_LOCKED', 'CK_RC5_CBC_PARAMS', + 'CA_InvokeServiceSinglePart', 'CK_KDF_PRF_ENCODING_SCHEME', 'MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS', 'LUNA_RET_M_TOO_LARGE', 'RC_STC_NO_SESSION_KEY', 'RC_ENDOFLIST', 'LUNA_RET_LOG_NO_KCV', 'CK_C_DecryptInit', @@ -4208,7 +4332,8 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_LICENSE_ID_UNKNOWN', 'LUNA_RET_KCDSA_PARAM_GEN_FAILURE', 'LUNA_RET_TOKEN_NOT_PRESENT', 'CK_USER_TYPE', - 'C_GetMechanismList', 'LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO', + 'C_GetMechanismList', + 'RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR', 'LUNA_RET_SFNT3120_ERROR', 'CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR', 'RC_CLIENT_MESSAGE_ERROR', 'C_GetAttributeValue', @@ -4220,9 +4345,9 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_CA_GetModuleList', 'LUNA_RET_STC_CHANNEL_REALLOC_ERROR', 'LUNA_RET_OBJECT_HANDLE_INVALID', 'C_GetFunctionStatus', - 'CK_OTP_PARAMS_PTR', 'LUNA_RET_RSA_SELF_TEST_FAILURE', - 'CK_CA_SetExtendedTPV', 'CA_STCGetCurrentKeyLife', - 'CK_C_SignFinal', 'CA_SetDestructiveHSMPolicy', + 'CK_OTP_PARAMS_PTR', 'RC_DER_CLASS_INVALID', + 'CK_CA_SetExtendedTPV', 'CK_C_SignFinal', + 'CA_SetDestructiveHSMPolicy', 'CK_SSL3_MASTER_KEY_DERIVE_PARAMS', 'CK_UTF8CHAR_PTR', 'LUNA_RET_ISES_TEST_VS_BSAFE_FAILED', 'swapper', 'LUNA_RET_SM_TSV_MISSING', 'C_WrapKey', @@ -4234,10 +4359,10 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_RM_POLICY_WRITE_RESTRICTED', 'CK_CA_GetContainerCapabilitySetting', 'SInt16', 'CK_C_GetMechanismInfo', 'LUNA_RET_CITS_DAK_MISSING', - 'CK_ECMQV_DERIVE_PARAMS_PTR', - 'CK_CA_GetTokenCertificateInfo', 'CK_CA_DeleteContainer', - 'MSG_RTC_ZEROIZED_ON_POWER_LOSS', 'CA_STCGetPartPubKey', - 'C_DestroyObject', 'LUNA_RET_TOO_MANY_CONTAINERS', + 'CK_C_DigestFinal', 'CK_CA_GetTokenCertificateInfo', + 'CK_CA_DeleteContainer', 'MSG_RTC_ZEROIZED_ON_POWER_LOSS', + 'CA_STCGetPartPubKey', 'C_DestroyObject', + 'LUNA_RET_TOO_MANY_CONTAINERS', 'LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED', 'CA_EncodeECChar2Params', 'LUNA_RET_RM_ELEMENT_VALUE_INVALID', @@ -4263,21 +4388,20 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'CK_RSA_PKCS_MGF_TYPE', 'CK_EXTRACT_PARAMS', 'LUNA_RET_OH_OBJECT_VERSION_INVALID', 'RC_SOCKET_BAD_FD', 'LUNA_RET_CB_REMOTE_CLOSED', 'CK_RC5_CBC_PARAMS_PTR', - 'RC_PARTITION_LOCKED', 'CA_STCSetKeyLifeTime', - 'LUNA_RET_STC_SESSION_INVALID', 'LUNA_RET_HOC_MISSING', - 'CA_GetHSMPolicySetting', + 'MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF', + 'CA_STCSetKeyLifeTime', 'LUNA_RET_STC_SESSION_INVALID', + 'LUNA_RET_HOC_MISSING', 'CA_GetHSMPolicySetting', 'CA_CreateContainerLoginChallenge', 'CK_ResetTotalOperations', 'CA_MOFN_GENERATION_PTR', 'CK_CA_InitSlotRolePIN', 'CK_AES_GCM_PARAMS_PTR', - 'CK_CA_EnableUnauthTokenInsertion', + 'CK_CA_STMGetState', 'CK_CA_EnableUnauthTokenInsertion', 'CK_C_DecryptDigestUpdate', 'LUNA_RET_CHALLENGE_RESPONSE_INCORRECT', 'RC_MANUFACTURING_SERIAL_NUMBER_INVALID', 'LUNA_RET_TEST_VS_BSAFE_FAILED', 'CA_Zeroize', 'CA_HAAnswerMofNChallenge', 'RC_STC_DH_KEYGEN_ERROR', - 'CK_MAC_GENERAL_PARAMS_PTR', - 'LUNA_RET_SEED_SELF_TEST_FAILURE', 'CK_TOKEN_INFO_PTR', - 'CK_CA_STCGetDigestNameByID', + 'CK_MAC_GENERAL_PARAMS_PTR', 'LUNA_RET_MISSING_SPLITS', + 'CK_TOKEN_INFO_PTR', 'CK_CA_STCGetDigestNameByID', 'CK_AES_CBC_PAD_INSERT_PARAMS', 'LUNA_RET_RC5_SELF_TEST_FAILURE', 'LUNA_RET_USER_ALREADY_ACTIVATED', @@ -4292,7 +4416,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'LUNA_RET_CB_HIOS_IO_ERROR', 'LUNA_RET_M_OF_N_SECRET_INVALID', 'LUNA_RET_SM_UNKNOWN_TOSM_STATE', - 'LUNA_RET_TEMPLATE_INCOMPLETE', + 'RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR', 'LUNA_RET_STC_CONTAINER_INVALID', 'LUNA_RET_CB_REMOTE_ABANDONED', 'LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID', @@ -4342,13 +4466,15 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'MSG_ZEROIZING', 'CK_KDF_PRF_TYPE', 'LUNA_RET_CL_NO_TRANSMISSION', 'RC_SIM_NOT_SUPPORTED', 'LUNA_RET_MASKING_NOT_SUPPORTED', 'CK_C_GetObjectSize', - 'CK_CA_STCGetPartPubKey', 'RC_DER_CLASS_INVALID', - 'LUNA_RET_TPV_INVALID', 'CA_DeactivateMofN', - 'CK_ECDH1_DERIVE_PARAMS_PTR', 'LUNA_RET_VECTOR_TOO_SMALL', - 'CK_C_Encrypt', 'MSG_RTC_TAMPER_2_SIGNAL', + 'CK_CA_STCGetPartPubKey', 'LUNA_RET_RSA_SELF_TEST_FAILURE', + 'LUNA_RET_HSM_TAMPERED', 'LUNA_RET_TPV_INVALID', + 'CA_DeactivateMofN', 'CK_ECDH1_DERIVE_PARAMS_PTR', + 'LUNA_RET_VECTOR_TOO_SMALL', 'CK_C_Encrypt', + 'MSG_RTC_TAMPER_2_SIGNAL', 'CA_CloseApplicationIDForContainer', 'C_DecryptUpdate', - 'Int8', 'LUNA_RET_HIFN_INVALID_ENCRYPT_MODE', - 'CK_C_DestroyObject', 'CK_CA_STCGetKeyLifeTime', + 'Int8', 'CA_TamperClear', + 'LUNA_RET_HIFN_INVALID_ENCRYPT_MODE', 'CK_C_DestroyObject', + 'CK_CA_STCGetKeyLifeTime', 'CK_CA_GetTokenStorageInformation', 'CA_GetSlotIdForPhysicalSlot', 'RC_STC_RSA_SIGN_ERROR', 'MSG_RTC_TAMPER_CIRCUITS_RE_ARMED', 'CK_C_InitToken', @@ -4361,7 +4487,7 @@ class CK_ARIA_CBC_ENCRYPT_DATA_PARAMS(Structure): 'MSG_RTC_EXTERNAL_TAMPER_LATCHED', 'CK_CA_MTKGetState', 'LUNA_RET_WRAPPED_KEY_LEN_RANGE', 'C_GetObjectSize', 'CK_CA_GenerateCloneableMofN', 'CA_STCGetClientsList', - 'CA_STCGetSequenceWindowSize', - 'LUNA_RET_CHALLENGE_TYPE_INVALID', 'C_GenerateRandom', + 'CA_STCGetSequenceWindowSize', 'RC_NO_PRIMARY_PEER', + 'CA_InitRolePIN', 'C_GenerateRandom', 'CA_GetTunnelSlotNumber', 'CK_CA_IsMofNEnabled', - 'CA_SetLKCV'] + 'RC_STC_COMPUTE_DH_KEY_ERROR', 'CA_SetLKCV'] diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index bc724e6..c97f18f 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1,4 +1,4 @@ -""" +''' THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE This file should NOT be checked into MKS or modified in any way, this file was created by setup/initialize.py. Any changes to this file will be wiped out when @@ -9,9 +9,9 @@ If you add any new defines you can rerun initialize.py to regenerate this file. If you need to scrape another header file add the desired file to the header_files array in initialize.py and rerun initialize.py. -""" +''' -'''/home/new_builds/1175/101/interfaces/Include/firmware/luna2if.h''' +'''/var/jenkins/workspace/luna-k7/crypto/interfaces/Include/firmware/luna2if.h''' LUNA_MAX_UPDATE_DATA_SIZE = (64 * 1024) LUNA_GEN_KCV_FLAG_NONE = 0x0000 LUNA_GEN_KCV_FLAG_CONSOLIDATE = 0x0001 @@ -259,6 +259,10 @@ LUNA_MECH_ECIES = 0x80000A00 LUNA_MECH_NIST_PRF_KDF = 0x80000A02 LUNA_MECH_PRF_KDF = 0x80000A03 +LUNA_MECH_AES_XTS = 0x80000A04 +LUNA_MECH_SM3 = 0x80000B01 +LUNA_MECH_HMAC_SM3 = 0x80000B02 +LUNA_MECH_SM3_KEY_DERIVATION = 0x80000B04 LUNA_MECH_FLAG_HW = 0x00000001 LUNA_MECH_FLAG_ENCRYPT = 0x00000100 LUNA_MECH_FLAG_DECRYPT = 0x00000200 @@ -333,7 +337,12 @@ LUNA_ATTR_MODIFIABLE = 0x00000170 LUNA_ATTR_ECDSA_PARAMS = 0x00000180 LUNA_ATTR_EC_POINT = 0x00000181 +LUNA_ATTR_HW_FEATURE_TYPE = 0x00000300 +LUNA_ATTR_ARRAY_ATTRIBUTE = 0x40000000 +LUNA_ATTR_UNWRAP_TEMPLATE = (LUNA_ATTR_ARRAY_ATTRIBUTE | 0x00000212) +LUNA_ATTR_DERIVE_TEMPLATE = (LUNA_ATTR_ARRAY_ATTRIBUTE | 0x00000213) LUNA_ATTR_VENDOR_DEFINED = 0x80000000 +LUNA_ATTR_PARTITION_ATTRIBUTE = (LUNA_ATTR_VENDOR_DEFINED | 0x20000000) LUNA_ATTR_CCM_PRIVATE = (LUNA_ATTR_VENDOR_DEFINED | 0x00000001) LUNA_ATTR_FINGERPRINT_SHA1 = (LUNA_ATTR_VENDOR_DEFINED | 0x00000002) LUNA_ATTR_PKC_TCTRUST = (LUNA_ATTR_VENDOR_DEFINED | 0x00000003) @@ -342,19 +351,35 @@ LUNA_ATTR_X9_31_GENERATED = (LUNA_ATTR_VENDOR_DEFINED | 0x00000006) LUNA_ATTR_PKC_ECC = (LUNA_ATTR_VENDOR_DEFINED | 0x00000007) LUNA_ATTR_EKM_UID = (LUNA_ATTR_VENDOR_DEFINED | 0x00000008) +LUNA_ATTR_PKC_LEGACY_ECC = ( +LUNA_ATTR_VENDOR_DEFINED | 0x00000009) # retired but available if needed LUNA_ATTR_USAGE_COUNT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000101) LUNA_ATTR_USAGE_COUNT_LIMIT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000200) LUNA_ATTR_GENERIC_1 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001000) LUNA_ATTR_GENERIC_2 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001001) LUNA_ATTR_GENERIC_3 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001002) LUNA_ATTR_FINGERPRINT_SHA256 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001003) +LUNA_ATTR_WARNING_THRESHOLD = (LUNA_ATTR_VENDOR_DEFINED | 0x00001004) +LUNA_ATTR_KEK_GROUP_ID = (LUNA_ATTR_PARTITION_ATTRIBUTE | 0x00000000) +LUNA_ATTR_KEK_MAX_LIFETIME = (LUNA_ATTR_PARTITION_ATTRIBUTE | 0x00000001) +LUNA_ATTR_KEK_ACTUAL_LIFETIME = (LUNA_ATTR_PARTITION_ATTRIBUTE | 0x00000002) +LUNA_ATTR_KEK_MANAGEMENT_FLAGS = (LUNA_ATTR_PARTITION_ATTRIBUTE | 0x00000003) LUNA_ATTR_UNKNOWN = 0xFFFFFFFF +LUNA_HW_FEATURE_MONOTONIC_COUNTER = 0x00000001 +LUNA_HW_FEATURE_CLOCK = 0x00000002 +LUNA_HW_FEATURE_USER_INTERFACE = 0x00000003 +LUNA_HW_FEATURE_VENDOR_DEFINED = 0x80000000 +LUNA_HW_FEATURE_TEMPERATURE = (LUNA_HW_FEATURE_VENDOR_DEFINED | 0x00000001) +LUNA_HW_FEATURE_BATTERY = (LUNA_HW_FEATURE_VENDOR_DEFINED | 0x00000002) +LUNA_HW_FEATURE_FAN = (LUNA_HW_FEATURE_VENDOR_DEFINED | 0x00000003) +LUNA_HW_FEATURE_UNKNOWN = 0xFFFFFFFF LUNA_OBJ_DATA = 0x00000000 LUNA_OBJ_CERTIFICATE = 0x00000001 LUNA_OBJ_SECRET_KEY = 0x00000002 LUNA_OBJ_PUBLIC_KEY = 0x00000003 LUNA_OBJ_PRIVATE_KEY = 0x00000004 LUNA_OBJ_DOMAIN_PARAMETERS = 0x00000005 +LUNA_OBJ_HW_FEATURE = 0x00000006 LUNA_OBJ_VENDOR_DEFINED = 0x80000000 LUNA_OBJ_UNKNOWN = 0xFFFFFFFF # Added for error detection */ LUNA_KEY_RSA = 0x00000000 @@ -391,9 +416,11 @@ LUNA_TUK_PRIVATE_KEY = 0x00000000 LUNA_HOK_PRIVATE_KEY = 0x00000001 LUNA_DAK_PRIVATE_KEY = 0x00000002 -LUNA_ECC_HOK_PRIVATE_KEY = 0x00000003 -LUNA_ECC_DAK_PRIVATE_KEY = 0x00000004 +LUNA_LEGACY_ECC_HOK_PRIVATE_KEY = 0x00000003 +LUNA_LEGACY_ECC_DAK_PRIVATE_KEY = 0x00000004 LUNA_TUK3_PRIVATE_KEY = 0x00000005 +LUNA_ECC_HOK_PRIVATE_KEY = 0x00000006 +LUNA_ECC_TUK_PRIVATE_KEY = 0x00000007 LUNA_VVK_PUBLIC_KEY = 0x00000001 LUNA_GT_LABEL = 0x00000000 LUNA_GT_MFG = 0x00000001 @@ -424,13 +451,15 @@ LUNA_GT_DEFAULT_MIN_MAX_PIN_LEN = 0x0000001E LUNA_GT_TWC2 = 0x0000001F LUNA_GT_RPV_STATUS = 0x00000020 -LUNA_GT_ECC_MIC = 0x00000021 -LUNA_GT_ECC_HOC = 0x00000022 -LUNA_GT_ECC_DAC = 0x00000023 +LUNA_GT_LEGACY_ECC_MIC = 0x00000021 +LUNA_GT_LEGACY_ECC_HOC = 0x00000022 +LUNA_GT_LEGACY_ECC_DAC = 0x00000023 LUNA_GT_ROLLBACK_FWV = 0x00000024 LUNA_GT_MIC = 0x00000025 LUNA_GT_HOC = 0x00000026 # retrieves HOC only LUNA_GT_CITS_MAC = 0x00000027 +LUNA_GT_DIAGNOSTIC_LOG = 0x00000028 +LUNA_GT_SAVED_DIAGNOSTIC_LOG = 0x00000029 LUNA_GT_SP_RAWREAD = 0x00000030 LUNA_GT_SP_RAWWRITE = 0x00000031 LUNA_GT_PED_CALLBACK_PROTOCOL = 0x00000032 @@ -445,6 +474,18 @@ LUNA_GT_TIME_OF_DAY = 0x0000003B LUNA_GT_MONO_COUNTER = 0x0000003C LUNA_GT_TEMP_K2 = 0x0000003D +LUNA_GT_ECC_ROOT_CERT = 0x0000003E +LUNA_GT_ECC_MIC = 0x0000003F +LUNA_GT_ECC_HOC = 0x00000040 +LUNA_GT_ECC_HW_ORIGIN_CERT = 0x00000041 # retrieves HOC+MIC +LUNA_GT_ECC_TWC = 0x00000042 +LUNA_GT_RTC_TEMP = 0x00000050 +LUNA_GT_DS3644_TEMP = 0x00000051 +LUNA_GT_DIE_TEMP = 0x00000052 +LUNA_GT_PKA_TEMP = 0x00000053 +LUNA_GT_TAMPER_INFO = 0x00000054 +LUNA_GT_FP_MIN_KEK_REPLACEMENT_INTERVAL = 0x00000055 +LUNA_GT_FP_MAX_KEK_REPLACEMENT_INTERVAL = 0x00000056 LUNA_GT_PIN = 0x00000006 LUNA_GT_TPV = 0x0000000A LUNA_GT_FPV = 0x0000000B @@ -529,6 +570,15 @@ LUNA_TTYPE_RSA_1863_AUX_PRIME_KEY_GEN_TEST = 0x00000013 LUNA_TTYPE_RSA_1863_ONLY_PRIME_KEY_GEN_TEST = 0x00000014 LUNA_TTYPE_X9_42_DOMAIN_PARAMETER_GENERATION_TEST = 0x00000015 +LUNA_TTYPE_ACCESS_ENTROPY_TEST = 0x00000016 +LUNA_TTYPE_ENTROPY_CRC_ERR_INJECTION_TEST = 0x00000017 +LUNA_TTYPE_ENTROPY_HW_ERR_INJECTION_TEST = 0x00000018 +LUNA_TTYPE_ENTROPY_FRO_DEGRADATION_TEST = 0x00000019 +LUNA_TTYPE_ENTROPY_CONTINUOUS_TEST = 0x0000001a +LUNA_TTYPE_DRBG_TEST = 0x0000001b +LUNA_TTYPE_AES_KEY_WRAP_TEST = 0x0000001c +LUNA_TTYPE_DRBG_CRC_ERR_INJECTION_TEST = 0x0000001d +LUNA_TTYPE_AES_KEY_WRAP_PAD_TEST = 0x0000001e LUNA_CTYPE_KCV = 0x00000000 LUNA_CTYPE_MOFN = 0x00000001 HA_CMD_GET_LOGIN_CHALLENGE = 0x01 @@ -549,11 +599,20 @@ LUNA_CUST_DAC_FIPS3_MEETS_PID = 51 # Customer Device Authentication Certificate, FIPS3, "meets requirements" LUNA_CUST_DAC_FIPS3_EVAL_PID = 52 # Customer Device Authentication Certificate, FIPS3, "evaluated to" LUNA_SSK_PID = 54 # Secure Signing Key -LUNA_ECC_MIC_PID = 60 # ECC Manufacturer Authentication Certificate -LUNA_ECC_HOK_PID = 61 # ECC Hardware Origin Key -LUNA_ECC_HOC_PID = 62 # ECC Hardware Origin Certificate -LUNA_ECC_DAK_PID = 63 # ECC Device Authentication Key -LUNA_ECC_DAC_PID = 64 # ECC Device Authentication Certificate +LUNA_LEGACY_ECC_MIC_PID = 60 # Legacy ECC Manufacturer Authentication Certificate +LUNA_LEGACY_ECC_HOK_PID = 61 # Legacy ECC Hardware Origin Key +LUNA_LEGACY_ECC_HOC_PID = 62 # Legacy ECC Hardware Origin Certificate +LUNA_LEGACY_ECC_DAK_PID = 63 # Legacy ECC Device Authentication Key +LUNA_LEGACY_ECC_DAC_PID = 64 # Legacy ECC Device Authentication Certificate +LUNA_ECC_HOK_PID = 87 # ECC Hierarchy Hardware Origin Key +LUNA_ECC_HOC_PID = 88 # ECC Hierarchy Hardware Origin Certificate +LUNA_ECC_TUK_PID = 89 # TUK for ECC Hierarchy - version 0 +LUNA_ECC_TWK_PID = 90 # TWK for ECC Hierarchy - version 0 +LUNA_ECC_TWC_PID = 91 # TWC for ECC Hierarchy - version 0 +LUNA_ECC_ROOT_PID = 92 # ECC Hierarchy Root Certificate +LUNA_ECC_MIC_PID = 93 # ECC Hierarchy Manufacturer Authentication Certificate +LUNA_ECC_EMVC_PID = 94 # ECC Hierarchy Emergency Message Verification Certificate +LUNA_U3KEY_PID = 95 # U3 Update Key used in ECC Hierarchy CA_MASK_DES3_RC4 = 0x00000001 CA_MASK_SHA1_AES_RC4 = 0x00000002 LUNA_MAX_CHALLENGE_SIZE = 64 @@ -563,6 +622,7 @@ LUNA_CHALLENGE_TYPE_NULL = 0x00000000 LUNA_CHALLENGE_TYPE_SECRET_HASH = 0x00000001 # Obsolete -- didn't satisfy NIST LUNA_CHALLENGE_TYPE_ENCRYPTED_SECRET_HASH = 0x00000002 +LUNA_CHALLENGE_FLAGS_CREATE_DEFAULT_CHALLENGE = (0x00000001) LUNA_CHALLENGE_TYPE_SO = LUNA_UTYPE_SO LUNA_CHALLENGE_TYPE_USER = LUNA_UTYPE_USER LUNA_CHALLENGE_TYPE_LIMITED_USER = LUNA_UTYPE_LIMITED_USER @@ -613,6 +673,8 @@ CONTAINER_CONFIG_PRIVATE_KEY_SMALL_FORM_FACTOR = 35 CONTAINER_CONFIG_SECRET_KEY_SMALL_FORM_FACTOR = 36 CONTAINER_CONFIG_SECURE_TRUSTED_CHANNEL = 37 +CONTAINER_CONFIG_FAST_PATH = 38 +CONTAINER_CONFIG_ENFORCE_START_AND_END_ATTRIBUTES = 39 HSM_CONFIG_ENABLE_PIN_AUTHENTICATION = 0 HSM_CONFIG_ENABLE_PED_AUTHENTICATION = 1 HSM_CONFIG_PERFORMANCE_LEVEL = 2 @@ -656,6 +718,12 @@ HSM_CONFIG_DECOMMISSION_ON_TAMPER = 40 HSM_CONFIG_PER_PARTITION_SO = 41 HSM_CONFIG_ENABLE_PARTITION_REINIT = 42 +HSM_CONFIG_ENABLE_LOW_LEVEL_MATH_ACCELERATION = 43 +HSM_CONFIG_ENABLE_FIPS_LEVEL4_SUPPORT = 44 +HSM_CONFIG_ENABLE_FAST_PATH = 45 +HSM_CONFIG_ALLOW_DISABLING_DECOMMISSION = 46 +HSM_CONFIG_ENABLE_G5_TUNNEL_SLOT = 47 +HSM_CONFIG_ENABLE_CONTROLLED_TAMPER_RECOVERY = 48 LUNA_CLONING_PART2_OVERHEAD = 76 LUNA_FLATTENED_OBJECT_OVERHEAD = 3264 LEGACY_TWC_ACCESS_LEVEL = 1 @@ -665,7 +733,9 @@ LICENSE_DESCRIPTION_SIZE = 60 PERSONALITY_NAME_SIZE = 60 UPGRADE_DESCRIPTION_SIZE = 60 +LUNA_ROLE_DESCRIPTOR_VERSION = 1 LUNA_MAX_ROLE_NAME_LEN = 24 +LUNA_MAX_ROLE_SHORT_NAME_LEN = 4 LUNA_MAX_PRP_LABEL_LEN = 24 LUNA_MAX_ROLES_PER_PARTITION = 4 LUNA_MAX_PRP_PER_SET = 3 @@ -691,6 +761,7 @@ LUNA_HW_PS_PCI = 0x00000007 LUNA_HW_SSM = 0x00000008 LUNA_HW_K6_PCI = 0x00000009 +LUNA_HW_K7_PCI = 0x0000000A LUNA_STORAGE_SHIFT = 0 LUNA_STORAGE_MASK = (0x03 << LUNA_STORAGE_SHIFT) LUNA_STORAGE_DEFAULT = (0x00 << LUNA_STORAGE_SHIFT) @@ -705,12 +776,16 @@ LUNA_CONTAINER_TYPE_GROUP = LUNA_PARTITION_TYPE_GROUP LUNA_CONTAINER_TYPE_STANDALONE = LUNA_PARTITION_TYPE_STANDALONE LUNA_INSERTION_UNINITIALIZED = 0x10 +LUNA_PARTITION_VERSION = 1 +LUNA_POLICY_TEMPLATE = 0x20 +MAX_CAPABILITY_SET_SIZE = 16 # UAV_MAX_CAPABILITY_SET_SIZE LUNA_ENABLE_MEMBER_CONTAINER = 0x01 LUNA_DISABLE_MEMBER_CONTAINER = 0x02 LUNA_UNAUTH_CMD_CONTEXT_CREATE = 0x01 LUNA_UNAUTH_CMD_CONTEXT_DELETE = 0x02 LUNA_UNAUTH_CMD_CONTEXT_GET = 0x03 LUNA_PKCS5_PBKD2_HMAC_SHA1 = 0x00000001 +LUNA_PKCS5_PBKD2_HMAC_SM3 = 0x80000B01 LUNA_SALT_SOURCE_SPECIFIED = 0x00000001 LUNA_KDF_NULL = 0x00000001 LUNA_KDF_SHA1_KDF = 0x00000002 @@ -744,8 +819,10 @@ LUNA_PRF_KDF_AES_CMAC = 0x00000002 LUNA_PRF_KDF_ARIA_CMAC = 0x00000003 LUNA_PRF_KDF_SEED_CMAC = 0x00000004 -LUNA_PRF_KDF_ENCODING_SCHEME_1 = 0x00000000 -LUNA_PRF_KDF_ENCODING_SCHEME_2 = 0x00000001 +LUNA_PRF_KDF_ENCODING_SCHEME_1 = 0x00000000 # use to get previous results because of above bug +LUNA_PRF_KDF_ENCODING_SCHEME_2 = 0x00000001 # use to get previous results because of above bug +LUNA_PRF_KDF_ENCODING_SCHEME_3 = 0x00000002 # use in FW 7 and later, equivalent to scheme 1 +LUNA_PRF_KDF_ENCODING_SCHEME_4 = 0x00000003 # use in FW 7 and later, equivalent to scheme 2 CB_CMD_TEST = 0x00000000 CB_CMD_TEST_UPLOAD = 0x00000001 CB_CMD_TEST_DOWNLOAD = 0x00000002 @@ -761,6 +838,7 @@ MTK_STATE_FLAG_HARD_ZEROIZE = 0x00000002 MTK_STATE_FLAG_SOFT_ZEROIZE = 0x00000004 MTK_STATE_FLAG_LOCKED = 0x00000008 +STM_STATE_FLAG_STM_TURNED_ON = 0x00000004 LUNA_TSV_DOMESTIC_FLAG = 0x80 LUNA_TSV_MISSING_MTK_FLAG = 0x40 LUNA_TSV_CLONING_ENABLED_FLAG = 0x20 @@ -794,6 +872,8 @@ LUNA_TSV_TOSM_ZEROIZED = 0x01 LUNA_TSV_TOSM_FUNCTIONAL = 0x02 LUNA_TSV_TOSM_ERROR = 0x03 +LUNA_TSV_ECC_TWC_FLAG_EXT1 = 0x80 +LUNA_TSV_ECC_HOC_FLAG_EXT1 = 0x40 LUNA_MODIFY_USAGE_COUNT_TYPE_INCREMENT = 0x00000001 LUNA_MODIFY_USAGE_COUNT_TYPE_SET = 0x00000002 LUNA_CKDHP_ECDH1_COFACTOR = 0x00000001 @@ -828,7 +908,7 @@ LUNA_STATS_ICD_COMMANDS_COUNT = 4 LUNA_STATS_UNKNOWN = 0xffffffff PED_PASSWORD_LENGTH = 8 -'''/home/new_builds/1175/101/tools/ekmtest/token.h''' +'''/var/jenkins/workspace/luna-k7/crypto/tools/ekmtest/token.h''' MAX_BUF_SIZE = 32000 MAX_SLOT_COUNT = 20 MAX_SESSION_COUNT = 20 @@ -839,7 +919,7 @@ LAST_MENU_ITEM = 204 MAX_FILE_NAME_SIZE = 512 # bytes */ XOR_KDF_MAX_SHARED_DATALEN = 512 # max. amount of shared data allowed -'''/home/new_builds/1175/101/interfaces/Include/RSA/pkcs11t.h''' +'''/var/jenkins/workspace/luna-k7/crypto/interfaces/Include/RSA/pkcs11t.h''' CRYPTOKI_VERSION_MAJOR = 2 CRYPTOKI_VERSION_MINOR = 20 CRYPTOKI_VERSION_AMENDMENT = 3 @@ -1441,7 +1521,7 @@ CKF_EXCLUDE_CHALLENGE = 0x00000008 CKF_EXCLUDE_PIN = 0x00000010 CKF_USER_FRIENDLY_OTP = 0x00000020 -'''/home/new_builds/1175/101/CoreLibrary/includes/cryptoki_v2.h''' +'''/var/jenkins/workspace/luna-k7/crypto/CoreLibrary/includes/cryptoki_v2.h''' NULL_PTR = 0 C_LIBRARY_VERSION = 0x510 # v5.10 decimal */ CK_TOKEN_SERIAL_NUMBER_SIZE = 16 @@ -1474,8 +1554,6 @@ CKF_DES_EVEN_PARITY_ALLOWED = 0x00000400 CKF_USER_ECC_DP_ALLOWED = 0x00000800 CKF_MODE_LOCKED = 0x10000000 -CKA_START_DATE_OLD_XXX = 0x0083 # Kept temporarily for backward compatibility with Beta version. Use CKA_START_DATE -CKA_END_DATE_OLD_XXX = 0x0084 # Kept temporarily for backward compatibility with Beta version. Use CKA_END_DATE CKD_SHA224_KDF = 0x00000005 CKD_SHA224_KDF_OLD = 0x80000003 CKD_SHA256_KDF = 0x00000006 @@ -1517,6 +1595,7 @@ CKA_X9_31_GENERATED = (CKA_VENDOR_DEFINED | 0x0006) CKA_PKC_ECC = (CKA_VENDOR_DEFINED | 0x0007) CKA_EKM_UID = (CKA_VENDOR_DEFINED | 0x0008) +CKA_PKC_LEGACY_ECC = (CKA_VENDOR_DEFINED | 0x0009) CKA_TOKEN_ROLE_POLICIES = (CKA_VENDOR_DEFINED | 0x0010) CKA_ROLE_DESCRIPTORS = (CKA_VENDOR_DEFINED | 0x0011) CKA_USER_VALUE = (CKA_VENDOR_DEFINED | 0x0012) @@ -1531,6 +1610,8 @@ CKA_LOGIN_ATTEMPTS_LEFT = (CKA_VENDOR_DEFINED | 0x001B) CKA_PRIMARY_AUTH_METHOD = (CKA_VENDOR_DEFINED | 0x001C) CKA_SECONDARY_AUTH_METHOD = (CKA_VENDOR_DEFINED | 0x001D) +CKA_ROLE_SHORT_NAME = (CKA_VENDOR_DEFINED | 0x001E) +CKA_VERSION = (CKA_VENDOR_DEFINED | 0x001F) CKA_USAGE_COUNT = (CKA_VENDOR_DEFINED + 0x0101) CKA_SLOT_ID = (CKA_VENDOR_DEFINED + 0x0151) CKA_MAX_SESSIONS = (CKA_VENDOR_DEFINED | 0x0155) @@ -1558,6 +1639,15 @@ CKA_GENERIC_2 = (CKA_VENDOR_DEFINED + 0x1001) CKA_GENERIC_3 = (CKA_VENDOR_DEFINED + 0x1002) CKA_FINGERPRINT_SHA256 = (CKA_VENDOR_DEFINED + 0x1003) +CKA_WARNING_THRESHOLD = (CKA_VENDOR_DEFINED + 0x1004) +CKA_PARTITION_ATTRIBUTE = 0x40000000 +CKA_KEK_GROUP_ID = (CKA_VENDOR_DEFINED + CKA_PARTITION_ATTRIBUTE + 0x1005) +CKA_KEK_MAX_LIFETIME = (CKA_VENDOR_DEFINED + CKA_PARTITION_ATTRIBUTE + 0x1006) +CKA_KEK_ACTUAL_LIFETIME = (CKA_VENDOR_DEFINED + CKA_PARTITION_ATTRIBUTE + 0x1007) +CKA_KEK_MANAGEMENT_FLAGS = (CKA_VENDOR_DEFINED + CKA_PARTITION_ATTRIBUTE + 0x1008) +CKH_TEMPERATURE = (CKH_VENDOR_DEFINED | 0x00000001) +CKH_BATTERY = (CKH_VENDOR_DEFINED | 0x00000002) +CKH_FAN = (CKH_VENDOR_DEFINED | 0x00000003) CKM_VENDOR_DEFINED_OLD_XXX = 0x00008000 CKM_CAST_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 0 # Entrust added capabilities CKM_CAST_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 1 # Entrust added capabilities @@ -1617,6 +1707,7 @@ CKM_AES_CFB8 = (CKM_VENDOR_DEFINED + 0x118) CKM_AES_CFB128 = (CKM_VENDOR_DEFINED + 0x119) CKM_AES_OFB = (CKM_VENDOR_DEFINED + 0x11a) +CKM_AES_CTR = (CKM_VENDOR_DEFINED + 0x11b) CKM_AES_GCM = (CKM_VENDOR_DEFINED + 0x11c) CKM_ARIA_CFB8 = (CKM_VENDOR_DEFINED + 0x11d) CKM_ARIA_CFB128 = (CKM_VENDOR_DEFINED + 0x11e) @@ -1685,6 +1776,11 @@ CKM_XOR_BASE_AND_DATA_W_KDF = (CKM_VENDOR_DEFINED + 0xA01) CKM_NIST_PRF_KDF = (CKM_VENDOR_DEFINED + 0xA02) CKM_PRF_KDF = (CKM_VENDOR_DEFINED + 0xA03) +CKM_AES_XTS = (CKM_VENDOR_DEFINED + 0xA04) +CKM_SM3 = (CKM_VENDOR_DEFINED + 0xB01) +CKM_SM3_HMAC = (CKM_VENDOR_DEFINED + 0xB02) +CKM_SM3_HMAC_GENERAL = (CKM_VENDOR_DEFINED + 0xB03) +CKM_SM3_KEY_DERIVATION = (CKM_VENDOR_DEFINED + 0xB04) CKDHP_STANDARD = 0x00000001 CKDHP_ECDH1_COFACTOR = 0x00000001 CKDHP_MODIFIED = 0x00000002 # Not implemented */ @@ -1817,6 +1913,18 @@ CKR_CHALLENGE_INCORRECT = (CKR_VENDOR_DEFINED + 0X67) CKR_ACCESS_ID_INVALID = (CKR_VENDOR_DEFINED + 0X68) CKR_ACCESS_ID_ALREADY_EXISTS = (CKR_VENDOR_DEFINED + 0X69) +CKR_KEY_NOT_KEKABLE = (CKR_VENDOR_DEFINED + 0x6a) +CKR_MECHANISM_INVALID_FOR_FP = (CKR_VENDOR_DEFINED + 0x6b) +CKR_OPERATION_INVALID_FOR_FP = (CKR_VENDOR_DEFINED + 0x6c) +CKR_SESSION_HANDLE_INVALID_FOR_FP = (CKR_VENDOR_DEFINED + 0x6d) +CKR_STM_CMD_NON_TRANSPORT = (CKR_VENDOR_DEFINED + 0x6e) +CKR_OBJECT_ALREADY_EXISTS = (CKR_VENDOR_DEFINED + 0X6f) +CKR_PARTITION_ROLE_POLICY_VERSION_INVALID = (CKR_VENDOR_DEFINED + 0X71) +CKR_PARTITION_ROLE_POLICY_SET_VERSION_INVALID = (CKR_VENDOR_DEFINED + 0X72) +CKR_REKEK_KEY = (CKR_VENDOR_DEFINED + 0X73) +CKR_KEK_RETRY_FAILURE = (CKR_VENDOR_DEFINED + 0X74) +CKR_RNG_RESEED_TOO_EARLY = (CKR_VENDOR_DEFINED + 0X75) +CKR_HSM_TAMPERED = (CKR_VENDOR_DEFINED + 0X76) CKR_OBJECT_READ_ONLY = (CKR_VENDOR_DEFINED + 0x114) CKR_KEY_NOT_ACTIVE = (CKR_VENDOR_DEFINED + 0x136) CKO_TOKEN_ROLE_POLICY_SET = (CKO_VENDOR_DEFINED + 0x0001) @@ -1832,6 +1940,13 @@ CKS_RO_VENDOR_DEFINED = 0x80000000 CKS_RW_VENDOR_DEFINED = 0x90000000 CKS_RW_AUDIT_FUNCTIONS = (CKS_RW_VENDOR_DEFINED + 0x001) +CKF_FP_NONE = 0x00 +CKF_FP_KEK_REPLACEMENT_ON_SESSION_KEY_DELETION = 0x01 +CKF_FP_KEK_REPLACEMENT_ON_TOKEN_KEY_DELETION = 0x02 +CKF_FP_KEK_REPLACEMENT_WHEN_USAGE_LIMIT_APPLIED = 0x04 +CKF_FP_KEK_REPLACEMENT_ON_ATTRIBUTE_CHANGE = 0x08 +CKF_FP_KEK_FLAG_ALLOW_MIX_MODED_KEYS = 0x10 +CKF_FP_KEK_REPLACEMENT_WHEN_START_END_DATE_APPLIED = 0x20 CAF_ROLE_STATE_INITIALIZED = 0x01 CAF_ROLE_STATE_LOCKED_OUT = 0x02 CAF_ROLE_STATE_ACTIVATED = 0x04 @@ -1842,6 +1957,11 @@ CKA_ROLE_AUTH_PASSWORD = 0x01 CKA_ROLE_AUTH_PED = 0x02 CKA_ROLE_AUTH_INVALID = 0xFF +CA_MAX_ROLE_NAME_LEN = 24 +CA_MAX_ROLE_SHORT_NAME_LEN = 4 +CA_MAX_PRP_LABEL_LEN = 24 +CA_MAX_ROLES_PER_PARTITION = 4 +CA_MAX_PRP_PER_SET = 3 CAF_M_OF_N_REQUIRED = 0x00000001 CAF_M_OF_N_ACTIVATED = 0x00000002 CAF_M_OF_N_GENERATED = 0x00000004 @@ -1857,12 +1977,16 @@ CKHSC_CERT_TYPE_CITS_ROOT = 0x00000003 CKHSC_CERT_TYPE_CITS_MICHOC = 0x00000004 CKHSC_CERT_TYPE_CITS_DAC = 0x00000005 -CKHSC_CERT_TYPE_ECC_MIC = 0x00000006 -CKHSC_CERT_TYPE_ECC_HOC = 0x00000007 -CKHSC_CERT_TYPE_ECC_DAC = 0x00000008 +CKHSC_CERT_TYPE_LEGACY_ECC_MIC = 0x00000006 +CKHSC_CERT_TYPE_LEGACY_ECC_HOC = 0x00000007 +CKHSC_CERT_TYPE_LEGACY_ECC_DAC = 0x00000008 CKHSC_CERT_TYPE_TWC = 0x00000009 CKHSC_CERT_TYPE_TWC2 = 0x0000000A CKHSC_CERT_TYPE_TWC3 = 0x0000000B +CKHSC_CERT_TYPE_ECC_ROOT = 0x0000000C +CKHSC_CERT_TYPE_ECC_MIC = 0x0000000D +CKHSC_CERT_TYPE_ECC_HOC = 0x0000000E +CKHSC_CERT_TYPE_ECC_TWC = 0x0000000F CKA_SIM_NO_AUTHORIZATION = 0 # no authorization needed CKA_SIM_PASSWORD = 1 # plain-text passwords CKA_SIM_CHALLENGE = 2 # challenge secrets emitted through the secure port @@ -1887,6 +2011,9 @@ CK_MTK_STATE_FLAG_HARD_ZEROIZE = 0x00000002 CK_MTK_STATE_FLAG_SOFT_ZEROIZE = 0x00000004 CK_MTK_STATE_FLAG_LOCKED = 0x00000008 +CK_STM_STATE_FLAG_STM_TURNED_ON = 0x00000004 +CK_GT_TAMPER_INFO = 0x00000054 +CK_GT_LIVE_TAMPER_INFO = 0x00000057 CK_MAX_CLUSTER_MEMBERS = 8 AKEP2_XDH_SIZE = 128 # size of LKM public key AKEP2_MAX_DIGEST_SIZE = 32 @@ -1895,3 +2022,5 @@ CK_PED_ID_MAX = 0xFFFE CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT = 0x00000001 CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET = 0x00000002 +CKP_PKCS5_PBKD2_HMAC_SHA1 = 0x00000001 +CKP_PKCS5_PBKD2_HMAC_SM3 = 0x80000B01 diff --git a/pycryptoki/return_values.py b/pycryptoki/return_values.py index 9471eba..8a477a7 100755 --- a/pycryptoki/return_values.py +++ b/pycryptoki/return_values.py @@ -207,5 +207,7 @@ CKR_ACCESS_ID_INVALID: 'CKR_ACCESS_ID_INVALID', CKR_ACCESS_ID_ALREADY_EXISTS: 'CKR_ACCESS_ID_ALREADY_EXISTS', CKR_OBJECT_READ_ONLY: 'CKR_OBJECT_READ_ONLY', - CKR_KEY_NOT_ACTIVE: 'CKR_KEY_NOT_ACTIVE' + CKR_KEY_NOT_ACTIVE: 'CKR_KEY_NOT_ACTIVE', + CKR_KEK_RETRY_FAILURE: 'CKR_KEK_RETRY_FAILURE', + CKR_RNG_RESEED_TOO_EARLY: 'CKR_RNG_RESEED_TOO_EARLY' } From 235dfeeac249156a0144b51d6ffe57b9c08f320a Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 9 Jun 2016 13:00:00 -0400 Subject: [PATCH 046/109] LA-1661 Fix seedrandom to allow for random-size data Change-Id: I1f2192d46d59d49c98a35a32b1fe9bb1f3003154 --- pycryptoki/misc.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 834a027..34c3762 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -51,7 +51,10 @@ def c_seed_random(h_session, seed): """ seed_bytes = cast(create_string_buffer(seed), CK_BYTE_PTR) - seed_length = CK_ULONG(len(seed)) + if isinstance(seed, (int, float, long)): + seed_length = seed + else: + seed_length = CK_ULONG(len(seed)) ret = C_SeedRandom(h_session, seed_bytes, seed_length) return ret From 5cf00b482996a96a062ade604f88baf06639307a Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 17 Jun 2016 10:37:34 -0400 Subject: [PATCH 047/109] LA-1864 Updating docs in prep for release Removed the code for building cryptoki.py/defines.py from C Header files. Updated readme Updated setup.py Updated documentation Change-Id: Ide1e881e685a07c86847e1cf2011e0d24a7acffb --- README.MD | 26 ++ README.txt | 6 - __init__.py | 4 - docs/attributes.rst | 9 + docs/conf.py | 17 +- docs/encryption.rst | 8 + docs/index.rst | 33 ++- docs/keys.rst | 27 ++ docs/mechanisms.rst | 7 + docs/misc.rst | 46 +++ docs/pycryptoki.daemon.rst | 17 ++ docs/pycryptoki.rst | 208 ++------------ docs/pycryptoki.setup.rst | 46 --- docs/pycryptoki.tests.rst | 141 ---------- docs/pycryptoki.tests.stress.rst | 38 --- docs/pycryptoki.utils.rst | 22 -- docs/sessions.rst | 21 ++ docs/sigver.rst | 7 + pycryptoki/setup/__init__.py | 0 pycryptoki/setup/distribute.py | 37 --- pycryptoki/setup/initialize.py | 405 --------------------------- pycryptoki/setup/make_and_install.py | 29 -- pycryptoki/setup/setup_tools.sh | 32 --- pycryptoki/setup/verify_version.py | 37 --- pycryptoki/utils/__init__.py | 0 setup.py | 8 +- 26 files changed, 242 insertions(+), 989 deletions(-) create mode 100755 README.MD delete mode 100755 README.txt create mode 100644 docs/attributes.rst create mode 100644 docs/encryption.rst create mode 100644 docs/keys.rst create mode 100644 docs/mechanisms.rst create mode 100644 docs/misc.rst delete mode 100644 docs/pycryptoki.setup.rst delete mode 100644 docs/pycryptoki.tests.rst delete mode 100644 docs/pycryptoki.tests.stress.rst delete mode 100644 docs/pycryptoki.utils.rst create mode 100644 docs/sessions.rst create mode 100644 docs/sigver.rst delete mode 100755 pycryptoki/setup/__init__.py delete mode 100755 pycryptoki/setup/distribute.py delete mode 100755 pycryptoki/setup/initialize.py delete mode 100755 pycryptoki/setup/make_and_install.py delete mode 100755 pycryptoki/setup/setup_tools.sh delete mode 100755 pycryptoki/setup/verify_version.py delete mode 100644 pycryptoki/utils/__init__.py diff --git a/README.MD b/README.MD new file mode 100755 index 0000000..2dbde20 --- /dev/null +++ b/README.MD @@ -0,0 +1,26 @@ +## Pycryptoki + +Pycryptoki is a python wrapper around the PKCS11 library. + + + +## Installation + +pip install git+https://github.com/gemalto/pycryptoki + + + +## Tests + +Unittests can be run on any environment using: +``` +py.test tests/unittests +``` + +Functional tests require an HSM to test against, and will actively use the libCryptoki library. +These tests *will* factory reset the HSM! We're working on making it so that we don't have to do that, +but in the meantime, don't run this on a production HSM! + +``` +py.test tests/functional --slot= +``` diff --git a/README.txt b/README.txt deleted file mode 100755 index 7bd92fe..0000000 --- a/README.txt +++ /dev/null @@ -1,6 +0,0 @@ -PyCryptoki is a module dedicated to testing the cryptoki library. In order to -achieve this goal it parses the cryptoki.h header file and creates automatically -generated python code to interface with the libCryptoki2.so DLL. - -More setup information can be found on the wiki: -http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Pages/pycryptoki.aspx \ No newline at end of file diff --git a/__init__.py b/__init__.py index 8151ac0..967b94b 100755 --- a/__init__.py +++ b/__init__.py @@ -1,7 +1,3 @@ import logging -import sys -logging.basicConfig(stream=sys.stdout, - level=logging.DEBUG, - format='%(asctime)s:%(name)s:%(levelname)s: %(message)s') logging.getLogger(__name__).addHandler(logging.NullHandler()) diff --git a/docs/attributes.rst b/docs/attributes.rst new file mode 100644 index 0000000..34309d1 --- /dev/null +++ b/docs/attributes.rst @@ -0,0 +1,9 @@ +Attributes and Conversions +========================== + + +.. automodule:: pycryptoki.attributes + :members: + + .. data:: pycryptoki.attributes.KEY_TRANSFORMS + :annotation: CK_ATTRIBUTE Types mapped to Python->C transformation functions diff --git a/docs/conf.py b/docs/conf.py index 739d229..31ae513 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,6 +14,7 @@ import sys import os +import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -34,6 +35,7 @@ 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.viewcode', + 'sphinxcontrib.napoleon', ] # Add any paths that contain templates here, relative to this directory. @@ -50,7 +52,7 @@ # General information about the project. project = u'Pycryptoki' -copyright = u'2015, Gemalto (Michael Hughes/Ashley Straw)' +copyright = u'2016, Gemalto' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -104,7 +106,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'default' +html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the @@ -203,7 +205,7 @@ # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Pycryptoki.tex', u'Pycryptoki Documentation', - u'Gemalto (Michael Hughes/Ashley Straw)', 'manual'), + u'Gemalto', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of @@ -233,7 +235,7 @@ # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pycryptoki', u'Pycryptoki Documentation', - [u'Gemalto (Michael Hughes/Ashley Straw)'], 1) + [u'Gemalto'], 1) ] # If true, show URL addresses after external links. @@ -247,8 +249,8 @@ # dir menu entry, description, category) texinfo_documents = [ ('index', 'Pycryptoki', u'Pycryptoki Documentation', - u'Gemalto (Michael Hughes/Ashley Straw)', 'Pycryptoki', 'One line description of project.', - 'Miscellaneous'), + u'Gemalto', 'Pycryptoki', 'Python wrapper for C Cryptoki library', + 'Cryptography'), ] # Documents to append as an appendix to all manuals. @@ -265,4 +267,5 @@ # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} +intersphinx_mapping = {'ctypes': ("https://docs.python.org/2", + None)} diff --git a/docs/encryption.rst b/docs/encryption.rst new file mode 100644 index 0000000..e9dedba --- /dev/null +++ b/docs/encryption.rst @@ -0,0 +1,8 @@ +Encryption/Decryption +--------------------- + + +.. automodule:: pycryptoki.encryption + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/index.rst b/docs/index.rst index 0440ef7..ed89cea 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -6,10 +6,41 @@ Welcome to Pycryptoki's documentation! ====================================== -Contents: +This package contains a python wrapper for our C PKCS11 libraries. +It provides automatic conversion to C types for the most commonly used functions. + +You can use it similarly to how you would use the C version of the PKCS11 library:: + + from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, + c_open_session_ex, c_close_session_ex, + login_ex) + + from pycryptoki.key_generator import c_generate_key_pair_ex + + c_initialize_ex() + session = c_open_session_ex(SLOT) + login_ex(session, 'userpin') + + pub_key_handle, priv_key_handle = c_generate_key_pair_ex(session) # Will default to RSA PKCS templates + + c_close_session_ex(session) + c_finalize_ex() + .. toctree:: :maxdepth: 2 + :numbered: + :includehidden: + + Session/Token Management + Key Generation/Management + Encryption/Decryption + Sign/Verify + Attributes + Mechanisms + Miscellaneous + RPYC Daemon + diff --git a/docs/keys.rst b/docs/keys.rst new file mode 100644 index 0000000..580b042 --- /dev/null +++ b/docs/keys.rst @@ -0,0 +1,27 @@ +Key Generation and Management +============================= + + +Key Generation +-------------- + +.. automodule:: pycryptoki.key_generator + :members: + :undoc-members: + :show-inheritance: + +Key Management +-------------- + +.. automodule:: pycryptoki.key_management + :members: + :undoc-members: + :show-inheritance: + +Key Usage +--------- + +.. automodule:: pycryptoki.key_usage + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/mechanisms.rst b/docs/mechanisms.rst new file mode 100644 index 0000000..4917e31 --- /dev/null +++ b/docs/mechanisms.rst @@ -0,0 +1,7 @@ +Mechanisms +---------- + +.. automodule:: pycryptoki.mechanism + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/misc.rst b/docs/misc.rst new file mode 100644 index 0000000..6190a9f --- /dev/null +++ b/docs/misc.rst @@ -0,0 +1,46 @@ +Miscellaneous +============= + + + +RNG, Digest, Creating Objects +----------------------------- + +.. automodule:: pycryptoki.misc + :members: + :undoc-members: + :show-inheritance: + + +Find Objects, Attribute Setting/Getting +--------------------------------------- + +.. automodule:: pycryptoki.object_attr_lookup + :members: + :undoc-members: + :show-inheritance: + +HSM Management +-------------- + +.. automodule:: pycryptoki.hsm_management + :members: + :undoc-members: + :show-inheritance: + + +Audit Functions +--------------- + +.. automodule:: pycryptoki.audit_handling + :members: + :undoc-members: + :show-inheritance: + +Backup Functions +---------------- + +.. automodule:: pycryptoki.backup + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/pycryptoki.daemon.rst b/docs/pycryptoki.daemon.rst index 7aa3627..316d700 100644 --- a/docs/pycryptoki.daemon.rst +++ b/docs/pycryptoki.daemon.rst @@ -1,6 +1,16 @@ Pycryptoki Daemon Package ========================= +Start the following daemon on your remote client, then connect to it +using :class:`~pycryptoki.pycryptoki_client.RemotePycryptokiClient`. You can then +use the RemotePycryptokiClient as if it were local:: + + pycryptoki = RemotePycryptokiClient('10.2.96.130', port=8001) + pycryptoki.c_initialize_ex() # Executed on the daemon! + session = pycryptoki.c_open_session_ex(SLOT) + #etc + + rpyc_pycryptoki --------------- @@ -9,3 +19,10 @@ rpyc_pycryptoki :undoc-members: :show-inheritance: +pycryptoki.pycryptoki_client +---------------------------- + +.. automodule:: pycryptoki.pycryptoki_client + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/pycryptoki.rst b/docs/pycryptoki.rst index 0c2e5fc..20e683e 100644 --- a/docs/pycryptoki.rst +++ b/docs/pycryptoki.rst @@ -1,42 +1,34 @@ -pycryptoki package +Pycryptoki Package ================== -Subpackages ------------ +This package contains a python wrapper for our C PKCS11 libraries. +It provides automatic conversion to C types for the most commonly used functions. -.. toctree:: +You can use it similarly to how you would use the C version of the PKCS11 library:: - pycryptoki.daemon - pycryptoki.setup - pycryptoki.tests - pycryptoki.utils + from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, + c_open_session_ex, c_close_session_ex, + login_ex) -Submodules ----------- + from pycryptoki.key_generator import c_generate_key_pair_ex -pycryptoki.attributes module ----------------------------- + c_initialize_ex() + session = c_open_session_ex(SLOT) + login_ex(session, 'userpin') -.. automodule:: pycryptoki.attributes - :members: - :undoc-members: - :show-inheritance: + pub_key_handle, priv_key_handle = c_generate_key_pair_ex(session) # Will default to RSA PKCS templates -pycryptoki.audit_handling module --------------------------------- + c_close_session_ex(session) + c_finalize_ex() -.. automodule:: pycryptoki.audit_handling - :members: - :undoc-members: - :show-inheritance: +To use pycryptoki in LunaTAP on a remote client, use the daemon +:mod:`pycryptoki.daemon.rpyc_pycryptoki` as well as the client :mod:`pycryptoki.pycryptoki_client`. -pycryptoki.backup module ------------------------- +.. toctree:: + :hidden: + + daemon -.. automodule:: pycryptoki.backup - :members: - :undoc-members: - :show-inheritance: pycryptoki.cryptoki module -------------------------- @@ -44,189 +36,47 @@ pycryptoki.cryptoki module .. automodule:: pycryptoki.cryptoki :members: :undoc-members: - :show-inheritance: -pycryptoki.cryptoki_helpers module ----------------------------------- + +pycryptoki.cryptoki_helpers +--------------------------- .. automodule:: pycryptoki.cryptoki_helpers :members: :undoc-members: :show-inheritance: -pycryptoki.default_templates module ------------------------------------ +pycryptoki.default_templates +---------------------------- .. automodule:: pycryptoki.default_templates :members: :undoc-members: :show-inheritance: -pycryptoki.defaults module --------------------------- +pycryptoki.defaults +------------------- .. automodule:: pycryptoki.defaults :members: :undoc-members: :show-inheritance: -pycryptoki.defines module -------------------------- -.. automodule:: pycryptoki.defines - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.dictionary_handling module -------------------------------------- +pycryptoki.dictionary_handling +------------------------------ .. automodule:: pycryptoki.dictionary_handling :members: :undoc-members: :show-inheritance: -pycryptoki.encryption module ----------------------------- - -.. automodule:: pycryptoki.encryption - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.hsm_management module --------------------------------- - -.. automodule:: pycryptoki.hsm_management - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.key_generator module -------------------------------- - -.. automodule:: pycryptoki.key_generator - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.key_management module --------------------------------- - -.. automodule:: pycryptoki.key_management - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.key_usage module ---------------------------- - -.. automodule:: pycryptoki.key_usage - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.logging_filters module ---------------------------------- - -.. automodule:: pycryptoki.logging_filters - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.luna_threading module --------------------------------- -.. automodule:: pycryptoki.luna_threading - :members: - :undoc-members: - :show-inheritance: -pycryptoki.mechanism module ---------------------------- -.. automodule:: pycryptoki.mechanism - :members: - :undoc-members: - :show-inheritance: -pycryptoki.misc module ----------------------- -.. automodule:: pycryptoki.misc - :members: - :undoc-members: - :show-inheritance: -pycryptoki.object_attr_lookup module ------------------------------------- -.. automodule:: pycryptoki.object_attr_lookup - :members: - :undoc-members: - :show-inheritance: -pycryptoki.policy_management module ------------------------------------ -.. automodule:: pycryptoki.policy_management - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.pycryptoki_client module ------------------------------------ - -.. automodule:: pycryptoki.pycryptoki_client - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.return_values module -------------------------------- - -.. automodule:: pycryptoki.return_values - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.session_management module ------------------------------------- - -.. automodule:: pycryptoki.session_management - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.sign_verify module ------------------------------ - -.. automodule:: pycryptoki.sign_verify - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.test_functions module --------------------------------- - -.. automodule:: pycryptoki.test_functions - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.token_management module ----------------------------------- - -.. automodule:: pycryptoki.token_management - :members: - :undoc-members: - :show-inheritance: - - -Module contents ---------------- - -.. automodule:: pycryptoki - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/pycryptoki.setup.rst b/docs/pycryptoki.setup.rst deleted file mode 100644 index 57e3f22..0000000 --- a/docs/pycryptoki.setup.rst +++ /dev/null @@ -1,46 +0,0 @@ -pycryptoki.setup package -======================== - -Submodules ----------- - -pycryptoki.setup.distribute module ----------------------------------- - -.. automodule:: pycryptoki.setup.distribute - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.setup.initialize module ----------------------------------- - -.. automodule:: pycryptoki.setup.initialize - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.setup.make_and_install module ----------------------------------------- - -.. automodule:: pycryptoki.setup.make_and_install - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.setup.verify_version module --------------------------------------- - -.. automodule:: pycryptoki.setup.verify_version - :members: - :undoc-members: - :show-inheritance: - - -Module contents ---------------- - -.. automodule:: pycryptoki.setup - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/pycryptoki.tests.rst b/docs/pycryptoki.tests.rst deleted file mode 100644 index af1c37f..0000000 --- a/docs/pycryptoki.tests.rst +++ /dev/null @@ -1,141 +0,0 @@ -pycryptoki.tests package -======================== - -Subpackages ------------ - -.. toctree:: - - pycryptoki.tests.stress - -Submodules ----------- - -pycryptoki.tests.run_tests_in_folder module -------------------------------------------- - -.. automodule:: pycryptoki.tests.run_tests_in_folder - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.setup_for_tests module ---------------------------------------- - -.. automodule:: pycryptoki.tests.setup_for_tests - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_cka_start_and_end module ----------------------------------------------- - -.. automodule:: pycryptoki.tests.test_cka_start_and_end - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_digest_data module ----------------------------------------- - -.. automodule:: pycryptoki.tests.test_digest_data - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_encrypt_decrypt module --------------------------------------------- - -.. automodule:: pycryptoki.tests.test_encrypt_decrypt - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_get_token_info module -------------------------------------------- - -.. automodule:: pycryptoki.tests.test_get_token_info - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_hsm_management module -------------------------------------------- - -.. automodule:: pycryptoki.tests.test_hsm_management - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_key_management module -------------------------------------------- - -.. automodule:: pycryptoki.tests.test_key_management - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_key_usage module --------------------------------------- - -.. automodule:: pycryptoki.tests.test_key_usage - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_keys module ---------------------------------- - -.. automodule:: pycryptoki.tests.test_keys - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_object_create module ------------------------------------------- - -.. automodule:: pycryptoki.tests.test_object_create - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_sign_verify module ----------------------------------------- - -.. automodule:: pycryptoki.tests.test_sign_verify - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_supporting_operations module --------------------------------------------------- - -.. automodule:: pycryptoki.tests.test_supporting_operations - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_usage_limit_and_count module --------------------------------------------------- - -.. automodule:: pycryptoki.tests.test_usage_limit_and_count - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.test_wrap_unwrap module ----------------------------------------- - -.. automodule:: pycryptoki.tests.test_wrap_unwrap - :members: - :undoc-members: - :show-inheritance: - - -Module contents ---------------- - -.. automodule:: pycryptoki.tests - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/pycryptoki.tests.stress.rst b/docs/pycryptoki.tests.stress.rst deleted file mode 100644 index 132720e..0000000 --- a/docs/pycryptoki.tests.stress.rst +++ /dev/null @@ -1,38 +0,0 @@ -pycryptoki.tests.stress package -=============================== - -Submodules ----------- - -pycryptoki.tests.stress.conftest module ---------------------------------------- - -.. automodule:: pycryptoki.tests.stress.conftest - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.stress.test_multi_reset module ------------------------------------------------ - -.. automodule:: pycryptoki.tests.stress.test_multi_reset - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.tests.stress.vreset_thread module --------------------------------------------- - -.. automodule:: pycryptoki.tests.stress.vreset_thread - :members: - :undoc-members: - :show-inheritance: - - -Module contents ---------------- - -.. automodule:: pycryptoki.tests.stress - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/pycryptoki.utils.rst b/docs/pycryptoki.utils.rst deleted file mode 100644 index 1530033..0000000 --- a/docs/pycryptoki.utils.rst +++ /dev/null @@ -1,22 +0,0 @@ -pycryptoki.utils package -======================== - -Submodules ----------- - -pycryptoki.utils.common_utils module ------------------------------------- - -.. automodule:: pycryptoki.utils.common_utils - :members: - :undoc-members: - :show-inheritance: - - -Module contents ---------------- - -.. automodule:: pycryptoki.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/sessions.rst b/docs/sessions.rst new file mode 100644 index 0000000..e5a8038 --- /dev/null +++ b/docs/sessions.rst @@ -0,0 +1,21 @@ +Session/Token Management +======================== + +Modules for Token and session creation and management. + +Session Management +------------------ + +.. automodule:: pycryptoki.session_management + :members: + :undoc-members: + :show-inheritance: + + +Token Management +---------------- + +.. automodule:: pycryptoki.token_management + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/sigver.rst b/docs/sigver.rst new file mode 100644 index 0000000..864f7ec --- /dev/null +++ b/docs/sigver.rst @@ -0,0 +1,7 @@ +Sign/Verify operations +====================== + +.. automodule:: pycryptoki.sign_verify + :members: + :undoc-members: + :show-inheritance: diff --git a/pycryptoki/setup/__init__.py b/pycryptoki/setup/__init__.py deleted file mode 100755 index e69de29..0000000 diff --git a/pycryptoki/setup/distribute.py b/pycryptoki/setup/distribute.py deleted file mode 100755 index 1c2f914..0000000 --- a/pycryptoki/setup/distribute.py +++ /dev/null @@ -1,37 +0,0 @@ -import argparse -import os -import sys -import initialize - -print "PyCryptoki Source Code Distribution" -print "Use -h for argument information." - -parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and creates a source tarball in pycryptoki/dist..") -parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") -parser.add_argument('-dll', metavar='', required=True, help="The path to the libCryptoki2.so which will be opened and parsed, this must be the dll corresponding to Luna's components sandbox.") - -print "-------------------------------------------------------" -print " Autogenerating Python Bindings to Cryptoki" -print "-------------------------------------------------------" - -args = parser.parse_args() -options = vars(args) - -#Create all of the necessary automatically generated source -xml_output = 'h2xmlout_tmp.xml' - -if not (options['dll'] is None): - dll_path = options['dll'] -else: - if "linux" in sys.platform: - dll_path = '/usr/lib/libCryptoki2.so' - else: - raise Exception("Platform not yet supported.") - -initialize.initialize(options['lib'], dll_path) - -print "-------------------------------------------------------" -print " Packaging Source Distribution" -print "-------------------------------------------------------" -os.chdir("../../") -os.system('python setup.py sdist') diff --git a/pycryptoki/setup/initialize.py b/pycryptoki/setup/initialize.py deleted file mode 100755 index 4ba3628..0000000 --- a/pycryptoki/setup/initialize.py +++ /dev/null @@ -1,405 +0,0 @@ -""" -Setup script that will automatically generate the cryptoki.py and defines.py files. -This will get your library from your LUNA_LIBRARY environment variable and generate these -files. These files contains the defines that are in the C code and in addition contain the -CTypes formatted structs contained in the C code. - -Cryptoki.py contains the CTypes templates for the C Structs that are in the cryptoki C code. -Defines.py is a crude wrapper around a number of header files that uses a bad regular expression to -harvest the defines. - -Download gccxml from CVS (note: CVS seems to be blocked on the CVS network, - you can get this from smb://172.20.11.83/ftp/forMike) -Compile gccxml -1) Recursively run dos2unix on gccxml source tree (find . -name *.* -exec dos2unix {} \;) -2) Create a folder in the same directory as gccxml is - in called gccxml-build (ex /home/mhughes/gccxml and /home/mhughes/gccxml-build) -3) cd gccxml-build -4) cmake ../gccxml -DCMAKE_INSTALL_PREFIX:PATH=/home/mhughes/gccxml-build -5) make -6) make install -7) Add gccxml folder to your path - -Install python -Install python packages needed for ctypes -1) sudo pip install ctypes -2) sudo easy_install ctypeslib==dev - -Make sure pycryptoki and pycryptoki/utils are in your PYTHONPATH. In eclipse: -1) Right click on your project -2) Select Properties -3) Select PyDev - PYTHONPATH -4) Add source folder -5) Add pycryptoki and pycryptoki/utils - -Set you LUNA_LIBRARY environment variable to the path to your library. It is assumed that your -dll is in the proper path in the library -""" -from ctypeslib import h2xml, xml2py -import argparse -import os -import platform -import re -import stat -import sys - -ret_list = [] -header_files = [os.path.join("interfaces", "Include", "firmware", "luna2if.h")] -dll_path_var_name = 'DLL_PATH' -cryptoki_filename = os.path.join("..", "cryptoki.py") - -def is_nextgen_check(library_path): - ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') - return os.path.exists(ctlib_path) - -def initialize(library_path=None, dll_path=None): - """ - Creates the cryptoki.py, defines.py and return_values.py files. - :param library_path: The path to the MKS Components sandbox - """ - xml_output = 'h2xmlout_tmp.xml' - - library_path = parse_library(library_path, xml_output) - cryptoki_dll_path = dll_path - convert_to_python_binding(cryptoki_dll_path, xml_output, cryptoki_filename) - print "Finished!" - -def change_cryptoki_dll_path(new_dll_path): - if not os.path.exists(cryptoki_filename): - raise Exception("Error... cryptoki.py not found.") - - print "Removing references to DLL in cryptoki.py to achieve late binding to DLL" - - #Read in the current file - cryptoki_file = open(cryptoki_filename, "r") - file_contents = cryptoki_file.read() - cryptoki_file.close() - - #Create a backup - try: - os.remove(cryptoki_filename + ".bak") - except: - #Don't care this was only removing the old backup if one existed - pass - - print "Creating backup: cryptoki.py.bak" - os.rename(cryptoki_filename, cryptoki_filename + ".bak") - - #Find the previous path - print re.findall("CDLL\((.*)\)", file_contents)[0] - current_path = re.findall("CDLL\((.*)\)", file_contents)[0] - - if "win" in platform.system(): - current_path = current_path.replace("\\", '~').replace('~', '\\\\\\\\') - - new_contents = file_contents.replace(current_path, new_dll_path) - - #Remove all references to DLL to load it later - new_contents = re.sub("_libraries\s*=\s*{}\s*", "", new_contents) - new_contents = re.sub("_libraries\[DLL_PATH\]\s*=\s*CDLL\(DLL_PATH\)\s*", "", new_contents) - - #Windows needs to have _pack_ = 1 for every single struct, has to be declared before _fields_ is set - struct_names = re.findall("(\S+)\._fields_\s=\s", new_contents) - fields = re.compile("\S+\._fields_\s=\s[^\]]*]", re.MULTILINE | re.DOTALL) - field_declaration = re.findall(fields, new_contents) - - assert len(field_declaration) == len(struct_names) - for i in range(0, len(field_declaration)): - add_pack_string = "if 'win' in sys.platform:\n " + struct_names[i] + "._pack_ = 1\n" + field_declaration[i] - - new_contents = new_contents.replace(field_declaration[i], add_pack_string) - - with open(cryptoki_filename, 'w') as new_file: - new_file.write(new_contents) - - -def change_cryptoki_dll_binding(): - - print "Replacing ctypes cryptoki function definitions, in " + cryptoki_filename + ", with factory functions for later binding to the DLL" - - #Read in the current file - cryptoki_file = open(cryptoki_filename, "r") - file_contents = cryptoki_file.read() - cryptoki_file.close() - - #Find all of the lines declaring functions on the DLL - found = re.findall("_libraries\[DLL_PATH\]\.(\S*)", file_contents) - - #Replace all of the functions to have a late binding - new_contents = file_contents - for function_name in found: - new_contents = re.sub("_libraries\[DLL_PATH\]\." + function_name + "\s", "make_late_binding_function('" + function_name + "')\n", new_contents) - - #Write the final contents out - with open(cryptoki_filename, 'w') as new_file: - new_file.write(new_contents) - -def parse_library(library_path, xml_output): - defines_filename = os.path.join("..", "defines.py") - return_vals_filename = os.path.join("..", "return_values.py") - - if library_path is None: - if not os.environ.has_key('LUNA_LIBRARY'): - raise Exception("LUNA_LIBRARY environment variable is not set, it needs to be set to the path of your luna source code.") - - library_path = os.environ['LUNA_LIBRARY'] - print "Using LUNA_LIBRARY Environment variable as location of Luna's Library: " + library_path - else: - print "Using argument 1 as location of Luna's Library: " + library_path - - - #If we are on a next gen branch then throw an error if the library is not compiled because - #we will be missing an automatically generated header file - if os.path.exists(os.path.join(library_path, 'CoreLibrary', 'ctToken_lib', 'source')): - if os.path.exists(os.path.join(library_path, 'interfaces', 'include', 'cryptoki', 'sfnt_ext_list_members.h')): - raise Exception("Error: sfnt_ext_list_members.h not found. You need to compile the Components library before being able to generate the Python to C Ctypes binding.") - - _parse_headers(xml_output, library_path) - - #Add all of the header files that you would like the script to parse, - #it should be noted that the script just does simple regular expression matching - #and is very simple and could break on previously unencountered syntaxes. It is - #just a hack to make life easier - token_path = os.path.join("tools", "ekmtest", "token.h") - if os.path.exists(os.path.join(library_path, token_path)): - header_files.append(token_path) - - #if it has this library it is next gen - if is_nextgen_check(library_path): - header_files.append(os.path.join("interfaces", "Include", "RSA", "pkcs11t.h")) - header_files.append(os.path.join("CoreLibrary", "includes", "cryptoki_v2.h")) - else: - header_files.append(os.path.join("interfaces", "Include", "cryptoki", "RSA", "pkcs11t.h")) - header_files.append(os.path.join("interfaces", "Include", "cryptoki", "cryptoki_v2.h")) - - _get_defines(library_path, defines_filename, header_files) - _output_return_values(return_vals_filename, ret_list) - return library_path - -def _parse_headers(xml_output, library_path=None): - """ - Using h2xml this function parses the cryptoki header file and generates xml - output which describes the library - :param xml_output:The filename to output the xml to - :param library_path:The path to the root of the cryptoki library - """ - - print "Parsing luna source with GCC-XML to generate XML representation of C source" - - if os.path.exists(xml_output): - os.remove(xml_output) - - #Create a file to pull everything in - temp_include_filename = 'master_header_file.h' - if os.path.exists(temp_include_filename): - os.remove(temp_include_filename) - - ctlib_path = os.path.join(library_path, 'CoreLibrary', 'ctTokenLib', 'source') - is_nextgen = is_nextgen_check(library_path) - - master_include_file = open(temp_include_filename, 'w') - if is_nextgen: - master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'pkcs11Utils', 'Utils.h"') + '\n') - else: - master_include_file.write('#include "' + os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source', 'Utils.h"') + '\n') - master_include_file.write('#include "cryptoki.h"\n') - master_include_file.close() - - args = ['h2xml.py', os.path.join(os.getcwd(), temp_include_filename), '-o', xml_output, - '-I', os.path.join(library_path, 'interfaces', 'Include'), - '-I', os.path.join(library_path, 'interfaces', 'Include', 'cryptoki'), - '-I', os.path.join(library_path, 'CoreLibrary', 'util_vob', 'source')] - - if is_nextgen: - args.append('-I') - args.append(ctlib_path) - args.append('-I') - args.append(os.path.join(library_path, 'CoreLibrary', 'util_vob', 'Include')) - - if "linux" in sys.platform: - print "Detected linux OS" - args.append('-D') - args.append('OS_LINUX') - else: - #Your operating system probably just needs to be added, might not need any special parameters - raise Exception("Error: Could not generate python to c ctypes library. Unsupported Operating System, a build on linux should work everywhere so just use it.") - - if which("gccxml") is None and which("gccxml.exe") is None: - raise Exception("No gccxml executable found in path.") - - h2xml.compile_to_xml(args) - - if os.path.exists(temp_include_filename): - os.remove(temp_include_filename) - -def convert_to_python_binding(cryptoki_dll_path, temp_file, output_filename): - """ - Using xml2py.py in ctypeslib this function generates the python file based - upon the xml output of h2xml. This python file is the binding between python - and C. - :param cryptoki_dll_path: The path to libCryptoki.so - :param temp_file: The xml output of h2xml.py - :param output_filename: The filename to output the binding to - """ - print "Parsing GCC-XML output to generate python code for binding to C, writing to " + output_filename - - if os.path.exists(output_filename): - os.chmod(output_filename, stat.S_IWRITE) - os.remove(output_filename) - - args = ['xml2py.py', temp_file, '-l', cryptoki_dll_path, '-o', output_filename] - xml2py.main(args) - - change_cryptoki_dll_path(dll_path_var_name) - initial_function = '\nfrom pycryptoki.cryptoki_helpers import make_late_binding_function\nimport sys\n' - - change_cryptoki_dll_binding() - - _prepend_to_file(output_filename, initial_function) - - comment = "This file contains all of the ctypes definitions for the cryptoki library.\n" - comment += "The ctypes definitions outline the structures for the cryptoki C API.\n" - _prepend_auto_file_warning(output_filename, comment) - -def _store_defines(head_filename, output_filename): - """ - Converts all of the simple defines (defines to numbers) in a c header file to a - variable declaration in python and appends these declarations to an output file. - - This is a really hackish way of getting the defines which actually hard codes out - defines that are formatted wrong and cause errors. Done this way to get it done real - quick and imports 99% of what is needed. - - :param head_filename: The filename of the header to get the defines from - :param output_filename: The .py file to append the python style defines in - """ - print "Getting defines from: " + str(head_filename) - - #Read in file - head_file = open(head_filename, "r") - text = head_file.read() - - #Find all the simple defines (defines to numbers) - regex_list = re.findall(r"#define[ \t\r\f\v]+([A-Z]+[A-Za-z_0-9]+[ \t\r\f\v]+[^~\n]*)[\n]", text) - #regex_list = re.findall(r"#define[ \t\r\f\v]([\S]+[ \t\r\f\v]*[0-9]+[0-9A-Za-z]*)[\n]", text) - - #Put an equals sign in them so they are properly formatted and append them to the file - out_file = open(output_filename, "a") - out_file.write("'''" + head_filename + "'''\n") - - for entry in regex_list: - if not (entry.find("CK_POINTER") > -1 or entry.find("CK_PTR") > -1 - or entry.find("CK_ENTRY") > -1 or entry.find("C_VERSION") > -1 - or entry.find("LUNA_PARTITION_HDR_HMAC_SIZE") > -1 - or entry.find("FW_VERSION_CONF_ROLES") > -1): #XXX This is to account for function calls, should be accounted for in the regex above - entry = entry.replace('\t', ' ') #clean up tabs - entry = entry.replace(' ', '=', 1) - entry = entry.replace('//', '#') - entry = entry.replace('/*', '#') - out_file.write(entry + "\n") - - dict_entry = entry.split('=') - if 'CKR' in dict_entry[0][0:3]: - ret_list.append(dict_entry[0]) - - #Cleanup - out_file.close() - head_file.close() - -def _output_return_values(output_filename, ret_list): - """ - Creates a file which contains a dictionary for looking up - the String values of the various defines in cryptoki. - - :param output_filename: The filename to output the dictionary to - :param ret_list: The list of return values generated when getting the - defines - """ - - print "Creating dictionary of return value strings by scraping Luna's source, writing to: " + output_filename - - if os.path.exists(output_filename): - os.remove(output_filename) - - ret_vals_file = open(output_filename, "a") - ret_vals_file.write("from defines import *\n\n") - - ret_vals_file.write("ret_vals_dictionary = { \n") - for entry in ret_list: - ret_vals_file.write("\t" + entry + " : '" + entry + "'") - if not ret_list[len(ret_list) - 1] == entry: - ret_vals_file.write(',') - ret_vals_file.write('\n') - ret_vals_file.write("}") - ret_vals_file.close() - - comment = "This file contains a dictionary lookup for the readable string values\n" - comment += "of defines whose variable name starts with CKR_. This convention means they are\n" - comment += "a return value for the cryptoki C API.\n\n" - _prepend_auto_file_warning(output_filename, comment) - -def _get_defines(path_to_library, out_filename, header_files): - """ - Gets all of the defines in a set of c files specified in the header_files variable as a list - of strings. That list is relative to the path_to_library variable. Everything is stored in - out_filename in python format. - :param path_to_library: The path to the MKS Components sandbox - :param out_filename: The .py filename to save the python style defines to - :param header_files: The header files to harvest the defines from - """ - - print "Scraping Luna's source to convert C defines to python, writing to: " + str(out_filename) - if os.path.exists(out_filename): - os.remove(out_filename) - - for header_file in header_files: - head_filename = os.path.join(path_to_library, header_file) - _store_defines(head_filename=head_filename, output_filename=out_filename) - - comment = "This file contains defines which have been automatically scraped from the\n" - comment += "cryptoki API header files. The defines are stored as variables in python.\n" - comment += "If you add any new defines you can rerun initialize.py to regenerate this file.\n" - comment += "If you need to scrape another header file add the desired file to the header_files\n" - comment += "array in initialize.py and rerun initialize.py.\n" - _prepend_auto_file_warning(out_filename, comment) - -def _prepend_auto_file_warning(filename, comment): - beginning_comment = "'''\n" - beginning_comment += "THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE\n" - beginning_comment += "This file should NOT be checked into MKS or modified in any way, this file was\n" - beginning_comment += "created by setup/initialize.py. Any changes to this file will be wiped out when\n" - beginning_comment += "it is regenerated.\n\n" - beginning_comment = beginning_comment + comment - beginning_comment += "'''\n\n" - - _prepend_to_file(filename, beginning_comment) - -def _prepend_to_file(filename, text_to_prepend): - with file(filename, 'r') as original: data = original.read() - with file(filename, 'w') as modified: modified.write(text_to_prepend + data) - -def which(program): - def is_exe(fpath): - return os.path.isfile(fpath) and os.access(fpath, os.X_OK) - - fpath, fname = os.path.split(program) - if fpath: - if is_exe(program): - return program - else: - for path in os.environ["PATH"].split(os.pathsep): - exe_file = os.path.join(path, program) - if is_exe(exe_file): - return exe_file - - return None - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding.") - parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") - parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") - args = parser.parse_args() - options = vars(args) - - initialize(options['lib'], options['dll']) - diff --git a/pycryptoki/setup/make_and_install.py b/pycryptoki/setup/make_and_install.py deleted file mode 100755 index d548c35..0000000 --- a/pycryptoki/setup/make_and_install.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -Script used to automatically generate python code bindings to the cryptoki library -and install the pycryptoki module in the system. -""" -import argparse -from pycryptoki.setup.initialize import initialize -import os -import sys - -parser = argparse.ArgumentParser(description="Automatically generates code for the python to cryptoki binding and installs pycryptoki package.") -parser.add_argument('-lib', metavar='', default=None, help="The path to Luna's Components Sandbox.") -parser.add_argument('-dll', metavar='', required=True, help="The path to libCryptoki2.so.") - -print "-------------------------------------------------------" -print " Autogenerating Python Bindings to Cryptoki" -print "-------------------------------------------------------" - -options = vars(parser.parse_args()) -initialize(options['lib'], options['dll']) - -print "" -print "-------------------------------------------------------" -print " Installing PyCryptoki Python Module" -print "-------------------------------------------------------" -if "linux" in sys.platform: - os.chdir(os.path.join("..", "..")) - os.system('sudo python setup.py install') -else: - raise Exception("Unsupported operating system, you'll have to add support for it.") diff --git a/pycryptoki/setup/setup_tools.sh b/pycryptoki/setup/setup_tools.sh deleted file mode 100755 index 6e3103f..0000000 --- a/pycryptoki/setup/setup_tools.sh +++ /dev/null @@ -1,32 +0,0 @@ - -if [ $# -ne 2 ] - then - echo "ERROR: No username and password specified to access gccxml source code from the wiki. Argument 1 must be the username to the safenet wiki, Argument 2 must be the password to the safenet wiki." - echo "Example ./setup_tools.sh mhughes mypassword" - exit -1 -fi -#Set up CMake -wget http://www.cmake.org/files/v2.8/cmake-2.8.8.tar.gz -tar -xzvf cmake-2.8.8.tar.gz -cd cmake-2.8.8 -./configure -gmake -gmake install -cd .. - -#Set up gcc-xml -wget http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Files/gccxml.tar.gz --user=$1 --password=$2 -tar -xzvf gccxml.tar.gz -cd gccxml -find . -name *.* \ tr -d '\r' -cd .. -mkdir gccxml-build -cd gccxml-build -../cmake-2.8.8/bin/cmake ../gccxml -DCMAKE_INSTALL_PREFIX:PATH=. -make -make install - -#Update the user's path -cd bin -export PATH=$PATH:$PWD -echo "export PATH=\$PATH:${PWD}" >> ~/.bashrc diff --git a/pycryptoki/setup/verify_version.py b/pycryptoki/setup/verify_version.py deleted file mode 100755 index 8c72a34..0000000 --- a/pycryptoki/setup/verify_version.py +++ /dev/null @@ -1,37 +0,0 @@ -""" -This function just goes through and imports every file and reports back which files have errors -in them for the purpose of compatibility between python versions. - -""" -import os, os.path - -def verify_import(): - """ """ - failed_files = "" - for root, dirs, files in os.walk("../."): - for f in files: - fullpath = os.path.join(root, f) - if fullpath.endswith("py"): - split_path = fullpath.split('/') - folder_names = "" - verify = True - if len(split_path) > 3: - - for folder in split_path[2:len(split_path) - 1]: - if folder == "setup": - verify = False - folder_names = folder_names + str(folder) + "." - if verify: - print fullpath - cmd = "from pycryptoki." + folder_names + str(f).split(".")[0] + " import *" - print "\t" + cmd - try: - exec cmd - except Exception as e: - print "\tERROR:" - print "\t" + str(e) - failed_files = failed_files + str(f) + "\n\t" - print "\n------SUMMARY------" - print "Failed:\n\t" + failed_files -if __name__ == '__main__': - verify_import() diff --git a/pycryptoki/utils/__init__.py b/pycryptoki/utils/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/setup.py b/setup.py index 02ae9b3..41d6efd 100755 --- a/setup.py +++ b/setup.py @@ -9,12 +9,10 @@ from distutils.core import setup setup(name='pycryptoki', description="A python wrapper around the C cryptoki library.", - author='Michael Hughes', - author_email='michael.hughes@safenet-inc.com', - url='http://mysno/Personal/amer_pohalloran/KnowledgeBaseWiki/Pages/pycryptoki.aspx', - version='1.2', + author='Ashley Straw', + url='https://github.com/gemalto/pycryptoki', + version='1.0', packages=['pycryptoki', - 'pycryptoki.setup', 'pycryptoki.tests', 'pycryptoki.daemon', 'pycryptoki.utils'], From f34b22e5cc6ad83f611cbbbacc72a64e3f6c7b54 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 9 Jun 2016 11:36:34 -0400 Subject: [PATCH 048/109] LA-1626 Mechanism rework Changed all imports to be relative. Reworked mechanism lookup completely. You can now pass in extra parameters and it should work properly. Automatic building of the c-mechanism will still need some more work though. Change-Id: Id9849029e6d484d1024f4d0053b4357ff786c22c --- pycryptoki/attributes.py | 15 +- pycryptoki/audit_handling.py | 4 +- pycryptoki/backup.py | 35 +- pycryptoki/common_utils.py | 4 +- pycryptoki/cryptoki.py | 1192 ++++++++--------- pycryptoki/cryptoki_helpers.py | 2 +- pycryptoki/default_templates.py | 1088 ++++++++++----- pycryptoki/defaults.py | 12 +- pycryptoki/defines.py | 79 +- pycryptoki/encryption.py | 188 +-- pycryptoki/hsm_management.py | 52 +- pycryptoki/key_generator.py | 18 +- pycryptoki/key_management.py | 4 +- pycryptoki/key_usage.py | 4 +- pycryptoki/luna_threading.py | 31 +- pycryptoki/mechanism.py | 402 +++++- pycryptoki/misc.py | 30 +- pycryptoki/object_attr_lookup.py | 8 +- pycryptoki/partition_management.py | 79 +- pycryptoki/pycryptoki_client.py | 2 +- pycryptoki/session_management.py | 74 +- pycryptoki/sign_verify.py | 150 +-- pycryptoki/test_functions.py | 46 +- pycryptoki/tests/functional/__init__.py | 1 + pycryptoki/tests/functional/conftest.py | 111 ++ .../test_cka_start_and_end.py | 292 ++-- .../tests/functional/test_digest_data.py | 44 + .../tests/functional/test_encrypt_decrypt.py | 70 + .../tests/functional/test_get_token_info.py | 82 ++ .../{ => functional}/test_hsm_management.py | 139 +- .../{ => functional}/test_key_management.py | 72 +- pycryptoki/tests/functional/test_key_usage.py | 46 + pycryptoki/tests/functional/test_keys.py | 198 +++ .../tests/functional/test_object_create.py | 54 + .../tests/functional/test_sign_verify.py | 111 ++ .../functional/test_supporting_operations.py | 58 + .../functional/test_usage_limit_and_count.py | 292 ++++ .../tests/functional/test_wrap_unwrap.py | 89 ++ pycryptoki/tests/run_tests_in_folder.py | 9 - pycryptoki/tests/setup_for_tests.py | 50 - pycryptoki/tests/stress/test_multi_reset.py | 28 +- pycryptoki/tests/test_digest_data.py | 57 - pycryptoki/tests/test_encrypt_decrypt.py | 77 -- pycryptoki/tests/test_get_token_info.py | 52 - pycryptoki/tests/test_key_usage.py | 65 - pycryptoki/tests/test_keys.py | 178 --- pycryptoki/tests/test_object_create.py | 66 - pycryptoki/tests/test_sign_verify.py | 103 -- .../tests/test_supporting_operations.py | 66 - .../tests/test_usage_limit_and_count.py | 338 ----- pycryptoki/tests/test_wrap_unwrap.py | 93 -- pycryptoki/tests/unittests/__init__.py | 0 pycryptoki/tests/unittests/test_attributes.py | 20 + pycryptoki/tests/unittests/test_mechanisms.py | 183 +++ pycryptoki/token_management.py | 33 +- 55 files changed, 3610 insertions(+), 2986 deletions(-) create mode 100644 pycryptoki/tests/functional/__init__.py create mode 100644 pycryptoki/tests/functional/conftest.py rename pycryptoki/tests/{ => functional}/test_cka_start_and_end.py (53%) create mode 100755 pycryptoki/tests/functional/test_digest_data.py create mode 100755 pycryptoki/tests/functional/test_encrypt_decrypt.py create mode 100755 pycryptoki/tests/functional/test_get_token_info.py rename pycryptoki/tests/{ => functional}/test_hsm_management.py (58%) rename pycryptoki/tests/{ => functional}/test_key_management.py (52%) create mode 100755 pycryptoki/tests/functional/test_key_usage.py create mode 100755 pycryptoki/tests/functional/test_keys.py create mode 100755 pycryptoki/tests/functional/test_object_create.py create mode 100755 pycryptoki/tests/functional/test_sign_verify.py create mode 100755 pycryptoki/tests/functional/test_supporting_operations.py create mode 100755 pycryptoki/tests/functional/test_usage_limit_and_count.py create mode 100755 pycryptoki/tests/functional/test_wrap_unwrap.py delete mode 100755 pycryptoki/tests/run_tests_in_folder.py delete mode 100755 pycryptoki/tests/setup_for_tests.py delete mode 100755 pycryptoki/tests/test_digest_data.py delete mode 100755 pycryptoki/tests/test_encrypt_decrypt.py delete mode 100755 pycryptoki/tests/test_get_token_info.py delete mode 100755 pycryptoki/tests/test_key_usage.py delete mode 100755 pycryptoki/tests/test_keys.py delete mode 100755 pycryptoki/tests/test_object_create.py delete mode 100755 pycryptoki/tests/test_sign_verify.py delete mode 100755 pycryptoki/tests/test_supporting_operations.py delete mode 100755 pycryptoki/tests/test_usage_limit_and_count.py delete mode 100755 pycryptoki/tests/test_wrap_unwrap.py create mode 100644 pycryptoki/tests/unittests/__init__.py create mode 100644 pycryptoki/tests/unittests/test_attributes.py create mode 100644 pycryptoki/tests/unittests/test_mechanisms.py diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index a208c01..9575db3 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -3,6 +3,7 @@ generation to make it possible to create templates in python and easily convert them into templates in C. """ +import binascii import datetime import logging from collections import defaultdict @@ -10,8 +11,6 @@ c_ulong, pointer, POINTER, sizeof, c_char, string_at, c_ubyte from functools import wraps -import binascii - from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ CK_BYTE, CK_CHAR from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ @@ -27,7 +26,7 @@ CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_OUID, CKA_UNWRAP_TEMPLATE, \ CKA_DERIVE_TEMPLATE, \ CKA_X9_31_GENERATED, CKA_VALUE -from pycryptoki.defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ +from .defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ CKA_GENERIC_3 LOG = logging.getLogger(__name__) @@ -251,6 +250,8 @@ def to_sub_attributes(val, reverse=False): CKA_PRIME_BITS: to_long, CKA_SUBPRIME_BITS: to_long, CKA_VALUE_BITS: to_long, + CKA_USAGE_COUNT: to_long, + CKA_USAGE_LIMIT: to_long, # int, bool CKA_TOKEN: to_bool, @@ -304,8 +305,6 @@ def to_sub_attributes(val, reverse=False): CKA_BASE: to_byte_array, CKA_FINGERPRINT_SHA1: to_byte_array, CKA_FINGERPRINT_SHA256: to_byte_array, - CKA_USAGE_COUNT: to_byte_array, - CKA_USAGE_LIMIT: to_byte_array, CKA_OUID: to_byte_array, # Dict @@ -313,6 +312,12 @@ def to_sub_attributes(val, reverse=False): CKA_DERIVE_TEMPLATE: to_sub_attributes, }) +CONVERSIONS = {CK_ULONG: to_long, + CK_BBOOL: to_bool, + c_char: to_char_array, + CK_BYTE: to_byte_array + } + class Attributes(dict): """ diff --git a/pycryptoki/audit_handling.py b/pycryptoki/audit_handling.py index 160b233..e7ee3a0 100755 --- a/pycryptoki/audit_handling.py +++ b/pycryptoki/audit_handling.py @@ -1,11 +1,11 @@ """ Methods responsible for managing a user's session and login/c_logout """ -from ctypes import cast, c_ulong, byref import logging +from ctypes import cast, c_ulong, byref from cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR -from pycryptoki.test_functions import make_error_handle_function +from .test_functions import make_error_handle_function logger = logging.getLogger(__name__) diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index 57321f0..ee8c53f 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -1,10 +1,10 @@ -from ctypes import byref import logging +from ctypes import byref -from pycryptoki.cryptoki import CA_OpenSecureToken, CA_CloseSecureToken, CA_Extract, CA_Insert, CK_ULONG -from pycryptoki.mechanism import get_c_struct_from_mechanism, \ - get_python_dict_from_c_mechanism -from pycryptoki.test_functions import make_error_handle_function +from .cryptoki import CA_OpenSecureToken, CA_CloseSecureToken, CA_Extract, CA_Insert, CK_ULONG +from .mechanism import get_c_struct_from_mechanism, \ + get_python_dict_from_c_mechanism, Mechanism +from .test_functions import make_error_handle_function logger = logging.getLogger(__name__) @@ -29,7 +29,8 @@ def ca_open_secure_token(h_session, storage_path, dev_ID, mode): """ number_of_elems = CK_ULONG(0) ph_ID = CK_ULONG(0) - ret = CA_OpenSecureToken(h_session, storage_path, dev_ID, mode, byref(number_of_elems), byref(ph_ID)) + ret = CA_OpenSecureToken(h_session, storage_path, dev_ID, mode, byref(number_of_elems), + byref(ph_ID)) return ret, number_of_elems.value, ph_ID.value @@ -56,29 +57,29 @@ def ca_close_secure_token(h_session, h_ID): ca_close_secure_token_ex = make_error_handle_function(ca_close_secure_token) -def ca_extract(h_session, py_mechanism_dict, params_type_string): +def ca_extract(h_session, mech_type, mech_params): """ :param h_session: :param py_mechanism_dict: :param params_type_string: - """ - c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) + mech = Mechanism(mech_type, params=mech_params) - ret = CA_Extract(h_session, c_mechanism) + cmech = mech.to_c_mech() + ret = CA_Extract(h_session, cmech) - py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) - return ret, py_dictionary + return ret ca_extract_ex = make_error_handle_function(ca_extract) + # CA_Insert( CK_SESSION_HANDLE hSession, # CK_MECHANISM_PTR pMechanism ) -def ca_insert(h_session, py_mechanism_dict, params_type_string): +def ca_insert(h_session, mech_type, mech_params): """ :param h_session: @@ -86,11 +87,11 @@ def ca_insert(h_session, py_mechanism_dict, params_type_string): :param params_type_string: """ + mech = Mechanism(mech_type, params=mech_params) - c_mechanism = get_c_struct_from_mechanism(py_mechanism_dict, params_type_string) - ret = CA_Insert(h_session, c_mechanism) - py_dictionary = get_python_dict_from_c_mechanism(c_mechanism, params_type_string) - return ret, py_dictionary + cmech = mech.to_c_mech() + ret = CA_Insert(h_session, cmech) + return ret ca_insert_ex = make_error_handle_function(ca_insert) diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index 990b78b..b8aa87e 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -4,8 +4,8 @@ from _ctypes import pointer, POINTER from ctypes import c_ulong, cast, create_string_buffer -from pycryptoki.cryptoki import CK_CHAR -from pycryptoki.defines import CKR_OK +from .cryptoki import CK_CHAR +from .defines import CKR_OK class CException(Exception): diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index 1b70594..a037942 100755 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -11,632 +11,644 @@ import sys from ctypes import * -from pycryptoki.cryptoki_helpers import make_late_binding_function +from .cryptoki_helpers import make_late_binding_function -LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE = -2147482613 + +class CK_MECHANISM(Structure): + pass + + +class CK_ATTRIBUTE(Structure): + pass + + +CK_MECHANISM_PTR = POINTER(CK_MECHANISM) +CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) + +LastFirmwareCode = -1073741825 +LUNA2_RET_HIFN_RESET_ERROR = -2147482356 +LUNA_HIFN_UNKNOWN_ALGORITHM = -2147482353 +LUNA_INVALID_PACKET_LAYOUT = -2147482352 +LUNA_RET_410_BUFFER_TOO_SMALL = 2097174 +LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT = 68355 +LUNA_RET_AES_SELF_TEST_FAILURE = 3145752 +LUNA_RET_AGAIN = -2147483642 LUNA_RET_ARGUMENTS_BAD = 458752 -LUNA_RET_HIFN_INVALID_ENCRYPT_MODE = -2147482360 -LUNA_RET_SM_UNKNOWN_SESSION_TYPE = -2147482618 -LUNA_RET_KEY_UNEXTRACTABLE = 6946816 -MSG_RTC_CANT_CLEAN_TAMPER_1 = 7 -LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM = -2147482361 -LUNA_RET_SM_UNKNOWN_ACCESS_TYPE = -2147482621 -LUNA_RET_STC_OPEN_CIPHER_MISMATCH = -2147480058 -LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED = -2147482622 -LUNA_RET_N_TOO_SMALL = -2147483135 -RC_ARGUMENTS_BAD = -1073741817 -RC_VERSION_INVALID = -1073741559 -LUNA_RET_CCM_UNREMOVABLE = -2147482878 -LUNA_RET_CCM_NOT_PRESENT = -2147482880 -LUNA_RET_MISSING_COMMAND_PARAMETER = -2147483107 -LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631508 -LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY = 13697042 -LUNA_RET_CAN_NOT_CREATE_SECRET_KEY = 13697041 LUNA_RET_ATTRIBUTE_NOT_FOUND = 1179664 -LUNA_RET_MAX_OBJECT_COUNT = 8519681 -LUNA_RET_ATTRIBUTE_SENSITIVE = 1114112 LUNA_RET_ATTRIBUTE_READ_ONLY = 1048576 -LUNA_RET_ATTRIBUTE_VALUE_INVALID = 1245184 +LUNA_RET_ATTRIBUTE_SENSITIVE = 1114112 LUNA_RET_ATTRIBUTE_TYPE_INVALID = 1179648 -LUNA_RET_TEMPLATE_INCONSISTENT = 13697024 -LUNA_RET_MEMORY_ALLOCATION_FAILED = 3211271 -LUNA_RET_MM_FATAL_ERROR = 3211270 -LUNA_RET_MM_ITERATOR_PAST_END = 3211269 -LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE = 3211267 -LUNA_RET_MM_USAGE_ALREADY_SET = 3211266 -LUNA_RET_MM_INVALID_HANDLE = 3211265 -LUNA_RET_MM_NOT_ENOUGH_MEMORY = 3211264 -LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE = 3146246 +LUNA_RET_ATTRIBUTE_VALUE_INVALID = 1245184 +LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD = -2147480310 +LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS = -2147480311 +LUNA_RET_BAD_DAC = -2147483372 +LUNA_RET_BAD_DAK = -2147483368 +LUNA_RET_BAD_FW_VERSION = 2099726 +LUNA_RET_BAD_MAC = -2147483370 +LUNA_RET_BAD_PPID = 2099725 +LUNA_RET_BAD_SN = 2099729 +LUNA_RET_BUFFER_TOO_SMALL = 22020096 +LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION = 1048601 +LUNA_RET_CAN_NOT_CREATE_PRIVATE_KEY = 13697042 +LUNA_RET_CAN_NOT_CREATE_SECRET_KEY = 13697041 +LUNA_RET_CANCEL = 65536 +LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE = 68108 +LUNA_RET_CAST3_SELF_TEST_FAILURE = 3145734 +LUNA_RET_CAST5_SELF_TEST_FAILURE = 3145735 +LUNA_RET_CAST_SELF_TEST_FAILURE = 3145733 +LUNA_RET_CB_ABORTED = -2147481082 +LUNA_RET_CB_HANDLE_INVALID = -2147481056 +LUNA_RET_CB_HIOS_CANCELED = -2147481069 +LUNA_RET_CB_HIOS_CLOSED = -2147481070 +LUNA_RET_CB_HIOS_HANDLE_INVALID = -2147481072 +LUNA_RET_CB_HIOS_ID_INVALID = -2147481071 +LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL = -2147481063 +LUNA_RET_CB_HIOS_IO_ERROR = -2147481068 +LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL = -2147481064 +LUNA_RET_CB_HIOS_RECV_TIMEOUT = -2147481066 +LUNA_RET_CB_HIOS_SEND_TIMEOUT = -2147481067 +LUNA_RET_CB_HIOS_STATE_INVALID = -2147481065 +LUNA_RET_CB_ID_INVALID = -2147481055 +LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE = -2147481049 +LUNA_RET_CB_MUST_READ = -2147481051 +LUNA_RET_CB_MUST_WRITE = -2147481050 +LUNA_RET_CB_NO_MEMORY = -2147481085 +LUNA_RET_CB_NOT_SUPPORTED = -2147481087 +LUNA_RET_CB_PARAM_INVALID = -2147481086 +LUNA_RET_CB_PROT_DATA_INVALID = -2147481047 +LUNA_RET_CB_REMOTE_ABANDONED = -2147481052 +LUNA_RET_CB_REMOTE_ABORT = -2147481054 +LUNA_RET_CB_REMOTE_CLOSED = -2147481053 +LUNA_RET_CB_RETRY = -2147481083 +LUNA_RET_CB_SYNC_ERROR = -2147481048 +LUNA_RET_CB_SYS_ERROR = -2147481081 +LUNA_RET_CB_TIMEOUT = -2147481084 +LUNA_RET_CCM_CERT_INVALID = -2147482877 +LUNA_RET_CCM_FWUPDATE_DENIED = -2147482874 +LUNA_RET_CCM_NOT_PRESENT = -2147482880 +LUNA_RET_CCM_NOT_SUPPORTED = -2147482879 +LUNA_RET_CCM_SIGN_INVALID = -2147482876 +LUNA_RET_CCM_TOO_LARGE = 2162689 +LUNA_RET_CCM_UNREMOVABLE = -2147482878 +LUNA_RET_CCM_UPDATE_DENIED = -2147482875 +LUNA_RET_CERT_VERSION_NOT_SUPPORTED = 3146496 +LUNA_RET_CHALLENGE_INVALID = 2099972 +LUNA_RET_CHALLENGE_NOT_REQUIRED = 68354 +LUNA_RET_CHALLENGE_REQUIRES_PED = 68353 +LUNA_RET_CHALLENGE_RESPONSE_INCORRECT = 10488579 +LUNA_RET_CHALLENGE_TYPE_INVALID = 2099968 +LUNA_RET_CITS_DAK_MISSING = -2147483366 +LUNA_RET_CL_ALIGNMENT_ERROR = 3146240 LUNA_RET_CL_COMMAND_MALFORMED = 3146245 -LUNA_RET_CL_TRANSMISSION_ERROR = 3146243 +LUNA_RET_CL_COMMAND_NON_BACKUP = 5505026 +LUNA_RET_CL_MAILBOXES_NOT_AVAILABLE = 3146246 +LUNA_RET_CL_NO_TRANSMISSION = 3146244 LUNA_RET_CL_QUEUE_LOCATION_ERROR = 3146241 -LUNA_RET_CL_ALIGNMENT_ERROR = 3146240 -LUNA_RET_PED_CLIENT_NOT_RUNNING = 3146055 -LUNA_RET_PED_DEK_INVALID = 3146054 -LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL = 3146053 -LUNA_RET_PED_ERROR = 3146052 -LUNA_RET_PED_UNPLUGGED = 3146050 -LUNA_RET_PED_UNSUPPORTED_PROTOCOL = 3146049 -LUNA_RET_PED_ID_INVALID = 3146048 -LUNA_RET_FORMER_INVALID_ENTRY_TYPE = 3146032 -LUNA_RET_TOKEN_NOT_PRESENT = 14680064 +LUNA_RET_CL_QUEUE_OVERLAP_ERROR = 3146242 +LUNA_RET_CL_TRANSMISSION_ERROR = 3146243 +LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS = 2100229 +LUNA_RET_CONTAINER_HANDLE_INVALID = -2147483647 +LUNA_RET_CONTAINER_IS_DISABLED = -2147483638 +LUNA_RET_CONTAINER_LOCKED = -2147483639 +LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL = -2147481341 +LUNA_RET_COUNTER_WRAPAROUND = 3145758 +LUNA_RET_CPK_PARAMETER_MISSING = -2147483378 +LUNA_RET_DAC_MISSING = -2147483373 +LUNA_RET_DAC_POLICY_PID_MISMATCH = -2147483374 +LUNA_RET_DAK_MISSING = -2147483369 +LUNA_RET_DATA_INVALID = 2097152 +LUNA_RET_DATA_LEN_RANGE = 2162688 +LUNA_RET_DES_SELF_TEST_FAILURE = 3145732 +LUNA_RET_DEVICE_ERROR = 3145728 +LUNA_RET_DEVICE_TIMEOUT = -2147483636 +LUNA_RET_DSA_PARAM_GEN_FAILURE = 3145749 +LUNA_RET_DSA_SELF_TEST_FAILURE = 3145750 +LUNA_RET_ECC_BUFFER_OVERFLOW = -2147482110 +LUNA_RET_ECC_DAC_MISSING = -2147483358 +LUNA_RET_ECC_DAK_MISSING = -2147483359 +LUNA_RET_ECC_HOC_MISSING = -2147483360 +LUNA_RET_ECC_HOK_MISSING = -2147483361 +LUNA_RET_ECC_MIC_MISSING = -2147483362 +LUNA_RET_ECC_NOT_SUPPORTED = -2147482111 +LUNA_RET_ECC_POINT_INVALID = -2147482109 +LUNA_RET_ECC_RESULT_AT_INF = -2147482106 +LUNA_RET_ECC_SELF_TEST_FAILURE = -2147482108 +LUNA_RET_ECC_UNKNOWN_CURVE = -2147482107 +LUNA_RET_ENCRYPTED_DATA_INVALID = 4194304 +LUNA_RET_ENCRYPTED_DATA_LEN_RANGE = 4259840 +LUNA_RET_ERROR = -2147483648 LUNA_RET_FLAGS_INVALID = 262144 -LUNA_RET_OK = 0 -RC_GENERAL_ERROR = -1073741822 -MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET = 30 -MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY = 29 -LUNA_RET_VECTOR_TOO_SMALL = -2147483115 -MSG_NVRAM_WRITE_FAILED = 26 -MSG_NVRAM_READ_FAILED = 25 -LUNA_RET_MISSING_VALUE_FOR_N = -2147483119 -LUNA_RET_SSK_MISSING = -2147483371 -LUNA_RET_MISSING_VALUE_FOR_M = -2147483120 -LUNA_RET_MISSING_WEIGHT_VALUE = -2147483121 -LUNA_RET_HIFN_DESTINATION_OVERRUN = -2147482345 -LUNA_RET_HIFN_END_MARKER_NOT_PRESENT = -2147482346 -LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID = -2147482347 +LUNA_RET_FM_ID_INVALID = -2147480832 +LUNA_RET_FORMER_INVALID_ENTRY_TYPE = 3146032 +LUNA_RET_FUNCTION_CANCELED = 5242880 +LUNA_RET_FUNCTION_NOT_SUPPORTED = 5505024 +LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE = 3145753 +LUNA_RET_GENERAL_ERROR = 327680 +LUNA_RET_HA_NOT_SUPPORTED = -2147481344 +LUNA_RET_HA_USER_NOT_INITIALIZED = -2147481343 +LUNA_RET_HAS160_SELF_TEST_FAILURE = 3145754 +LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN = 3147780 +LUNA_RET_HIFN6500_ALU_TIMEOUT = 3147785 +LUNA_RET_HIFN6500_DATA_LINES_BROKEN = 3147779 +LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS = 3147788 +LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH = 3147787 +LUNA_RET_HIFN6500_INVALID_PARAMETERS = 3147786 +LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS = 3147789 +LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED = 3147781 +LUNA_RET_HIFN6500_NOT_PRESENT = 3147777 +LUNA_RET_HIFN6500_RESET_TIMEOUT = 3147778 +LUNA_RET_HIFN6500_RNG_FAILED = 3147782 +LUNA_RET_HIFN6500_RNG_TIMEOUT = 3147783 +LUNA_RET_HIFN6500_RNG_UNDERFLOW = 3147784 +LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT = 3147790 +LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO = -2147482344 LUNA_RET_HIFN_COMPRESSION_HEADER_COUNT_INVALID = -2147482349 -LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE = -2147483126 -LUNA_INVALID_PACKET_LAYOUT = -2147482352 -LUNA_HIFN_UNKNOWN_ALGORITHM = -2147482353 +LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID = -2147482350 +LUNA_RET_HIFN_DESTINATION_COUNT_INVALID = -2147482366 +LUNA_RET_HIFN_DESTINATION_OVERRUN = -2147482345 +LUNA_RET_HIFN_DMA_ERROR = -2147482357 +LUNA_RET_HIFN_DMA_INVALID_REVISION = -2147482320 +LUNA_RET_HIFN_DMA_NOT_IDLE = -2147482355 LUNA_RET_HIFN_DMA_TIMED_OUT = -2147482354 -LUNA2_RET_HIFN_RESET_ERROR = -2147482356 -LUNA_RET_SPLIT_ID_INVALID = -2147483127 LUNA_RET_HIFN_ENCRYPT_HEADER_COUNT_INVALID = -2147482358 +LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID = -2147482359 +LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO = -2147482342 +LUNA_RET_HIFN_END_MARKER_NOT_PRESENT = -2147482346 +LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM = -2147482351 +LUNA_RET_HIFN_INVALID_ENCRYPT_ALGORITHM = -2147482361 +LUNA_RET_HIFN_INVALID_ENCRYPT_MODE = -2147482360 +LUNA_RET_HIFN_INVALID_MAC_ALGORITHM = -2147482365 +LUNA_RET_HIFN_INVALID_MAC_MODE = -2147482364 +LUNA_RET_HIFN_INVALID_PAD_ALGORITHM = -2147482348 LUNA_RET_HIFN_MAC_HEADER_COUNT_INVALID = -2147482362 -MSG_RTC_LOST_ALL_POWER = 17 LUNA_RET_HIFN_MAC_SOURCE_COUNT_INVALID = -2147482363 -LUNA_RET_HIFN_INVALID_MAC_MODE = -2147482364 -LUNA_RET_HIFN_INVALID_MAC_ALGORITHM = -2147482365 -LUNA_RET_HIFN_DESTINATION_COUNT_INVALID = -2147482366 -LUNA_RET_HIFN_SOURCE_COUNT_INVALID = -2147482367 +LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO = -2147482343 LUNA_RET_HIFN_NOT_PRESENT = -2147482368 -MSG_RTC_TAMPER_CIRCUITS_RE_ARMED = 16 -LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE = -2147482614 -LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW = -2147482615 -LUNA_RET_SM_CONTEXT_NOT_ALLOCATED = -2147482616 -LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED = -2147482617 -MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT = 15 -LUNA_RET_SM_BAD_CONTEXT_NUMBER = -2147482619 -LUNA_RET_SM_BAD_ACCESS_HANDLE = -2147482620 -LUNA_RET_SM_ACCESS_ALREADY_EXISTS = -2147482623 -LUNA_RET_SM_ACCESS_ID_INVALID = -2147482624 -LUNA_RET_CCM_TOO_LARGE = 2162689 -LUNA_RET_CCM_FWUPDATE_DENIED = -2147482874 -LUNA_RET_CCM_UPDATE_DENIED = -2147482875 -LUNA_RET_CCM_SIGN_INVALID = -2147482876 -LUNA_RET_ECC_HOK_MISSING = -2147483361 -LUNA_RET_CCM_CERT_INVALID = -2147482877 -LUNA_RET_CCM_NOT_SUPPORTED = -2147482879 -LUNA_RET_M_OF_N_IS_NOT_REQUIRED = -2147483105 -MSG_RTC_RECONFIGURING_FAILED = 12 -LUNA_RET_VECTOR_TYPE_INVALID = -2147483108 -LUNA_RET_VECTOR_DUPLICATE = -2147483109 -LUNA_RET_VECTOR_OF_DIFFERENT_SET = -2147483110 -LUNA_RET_VECTOR_VERSION_INVALID = -2147483111 -LUNA_RET_M_TOO_LARGE = -2147483134 -LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 -MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS = 10 -MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED = 45 -RC_STC_RESPONSE_DECRYPT_ERROR = -1073700845 -LUNA_RET_ECC_MIC_MISSING = -2147483362 -LUNA_RET_SIM_AUTHFORM_INVALID = 2097438 -LUNA_RET_INVALID_CERTIFICATE_FUNCTION = -2147483355 -MSG_RTC_CANT_ACCESS = 6 -LUNA_RET_ROOT_CERT_MISSING = -2147483357 -MSG_RTC_MSG_NVRAM_ZAPPING_FAILED = 3 -LUNA_RET_ECC_HOC_MISSING = -2147483360 -RC_MEMORY_ALLOCATION = -1073741823 +LUNA_RET_HIFN_PAD_SOURCE_COUNT_INVALID = -2147482347 +LUNA_RET_HIFN_SOURCE_COUNT_INVALID = -2147482367 +LUNA_RET_HOC_MISSING = -2147483356 LUNA_RET_HOK_MISSING = -2147483367 -LUNA_RET_CHALLENGE_TYPE_INVALID = 2099968 -LUNA_RET_BAD_DAC = -2147483372 -LUNA_RET_DAC_POLICY_PID_MISMATCH = -2147483374 -LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE = 2099716 -LUNA_RET_MAC_MISSING = -2147483375 +LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL = 3145757 +LUNA_RET_HSM_STORAGE_FULL = -2147481342 +LUNA_RET_HSM_TAMPERED = -2147482315 +LUNA_RET_INCOMPATIBLE = 3145764 LUNA_RET_INVALID_ACCESS_LEVEL = -2147483376 -MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED = 44 -LUNA_RET_CPK_PARAMETER_MISSING = -2147483378 -RC_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE = -1073700838 -RC_STC_RESPONSE_UNEXPECTED_KEY = -1073700839 -RC_STC_RSA_DECRYPT_ERROR = -1073700840 -RC_STC_RSA_SIGN_ERROR = -1073700841 -LUNA_RET_TUK_PARAMETER_MISSING = -2147483379 -RC_STC_RSA_ENCRYPT_ERROR = -1073700842 -RC_STC_REKEY_CHANNEL_MISMATCH = -1073700843 -RC_STC_RESPONSE_REPLAYED = -1073700844 -RC_STC_NO_CHANNEL = -1073700846 -RC_STC_SEQUENCE_NUM_INVALID = -1073700847 -RC_STC_CONTAINER_INVALID = -1073700848 -RC_STC_SESSION_INVALID = -1073700849 -RC_STC_CLIENT_HANDLE_INVALID = -1073700850 -RC_STC_NOT_ENABLED = -1073700851 -RC_STC_RESPONSE_BAD_MAC = -1073700852 -RC_STC_NO_SESSION_KEY = -1073700853 -LUNA_RET_KCV_PARAMETER_MISSING = -2147483381 -RC_STC_KEY_CONFIRMATION_FAILED = -1073700854 -RC_STC_SECOND_PHASE_KDF_ERROR = -1073700855 -RC_STC_FIRST_PHASE_KDF_ERROR = -1073700856 -RC_STC_COMPUTE_DH_KEY_ERROR = -1073700857 -RC_STC_DH_KEY_NOT_FROM_SAME_GROUP = -1073700858 -RC_STC_CIPHER_SUITE_REJECTED = -1073700859 -RC_STC_DH_KEYGEN_ERROR = -1073700860 -RC_STC_PARTITION_IDENTITY_NOT_CONFIGURED = -1073700861 -RC_STC_CLIENT_IDENTITY_NOT_CONFIGURED = -1073700862 -RC_STC_NO_CONTEXT = -1073700863 -LUNA_RET_KEY_NOT_KEKED = -2147481338 -RC_UNABLE_TO_CONNECT = -1073737472 -RC_USB_PED_OUT_OF_SYNC = -1073733610 -RC_USB_PED_TOO_MANY_CONNECTED = -1073733611 -RC_USB_PED_OPERATION_CANCELLED = -1073733612 -RC_USB_PED_NOT_RESPONDING = -1073733613 -RC_USB_PED_NOT_FOUND = -1073733614 -RC_FAILED_TO_CREATE_PROCESS = -1073733615 -RC_FILE_LOCK_ERROR = -1073733616 -RC_CMD_BLOCKED_REMOTE_PED_TUNNEL = -1073733622 -RC_FILE_LOCK_FAILED = -1073733623 -RC_UNKNOWN_COMMAND_VERSION = -1073733624 -LUNA_RET_WRAPPING_ERROR = -2147483385 -LUNA_RET_INVALID_MODULUS_SIZE = -2147483387 -LastFirmwareCode = -1073741825 -LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED = -2147483391 -LUNA_RET_ECC_BUFFER_OVERFLOW = -2147482110 -LUNA_RET_INVALID_FUF_TARGET = -2147483634 -LUNA_RET_ECC_NOT_SUPPORTED = -2147482111 -RC_OBJECT_ID_INVALID = -1073740795 -LUNA_RET_DEVICE_TIMEOUT = -2147483636 -RC_FILE_READ_ONLY = -1073740797 -LUNA_RET_CONTAINER_IS_DISABLED = -2147483638 -LUNA_RET_PE1746_ERROR = 3147911 -RC_DATA_CORRUPTED = -1073740799 -RC_TOKEN_STATE_INVALID = -1073740800 -LUNA_RET_NOT_FOUND = -2147483641 -RC_OPERATION_TIMED_OUT = -1073741053 -RC_MANUFACTURING_SERIAL_NUMBER_INVALID = -1073741054 -LUNA_RET_CONTAINER_HANDLE_INVALID = -2147483647 -LUNA_RET_WRAPPING_KEY_SIZE_RANGE = 18087936 -LUNA_RET_SFNT3120_SELFTEST_FAILED = 3147810 -LUNA_RET_WRAPPED_KEY_LEN_RANGE = 17956864 -LUNA_RET_HIFN6500_TOO_SMALL_USER_BUFFER_FOR_RESULT = 3147790 -LUNA_RET_USER_PIN_NOT_INITIALIZED = 16908288 -LUNA_RET_SM_SESSION_READ_ONLY_EXISTS = 11993088 -LUNA_RET_SM_OTHER_USER_LOGGED_IN = 16777217 -LUNA_RET_M_OF_N_PARAMETER_EXIST = -2147483112 LUNA_RET_INVALID_BOARD_TYPE = -2147481856 -RC_UNKNOWN_COMMAND = -1073733625 -RC_INVALID_COMMAND = -1073733626 -LUNA_RET_INVALID_IP_PACKET = -2147482112 -RC_SOCKET_CLOSED = -1073733627 -RC_REMOTE_SIDE_DISCONNECTED = -1073733628 -RC_UNKNOWN_CALLBACK_COMMAND = -1073733630 -RC_CALLBACK_ERROR = -1073733631 -RC_FAILED_TO_CREATE_THREAD = -1073733632 -RC_PARTITION_ROLE_POLICY_SET_VERSION_INVALID = -1073737724 -RC_PARTITION_ROLE_POLICY_VERSION_INVALID = -1073737725 -RC_PARTITION_ROLE_DESC_VERSION_INVALID = -1073737726 -RC_PARTITION_NOT_ACTIVATED = -1073737727 -RC_PARTITION_LOCKED = -1073737728 -RC_SESSION_SCRIPT_EXISTS = -1073739519 -RC_SSL_FAILED_HANDSHAKE = -1073740015 -RC_SSL_SYSCALL_ERROR = -1073740016 -RC_SSL_WANT_X509_LOOKUP_ERROR = -1073740017 -RC_SSL_WANT_WRITE_ERROR = -1073740018 -RC_SSL_WANT_READ_ERROR = -1073740019 -RC_SSL_GET_PEER_CERT_ERROR = -1073740020 -RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR = -1073740021 -RC_SSL_INVALID_CERT_STRUCTURE = -1073740022 -MSG_FACTORY_RESET = 53 -RC_SSL_CREATE_SSL_ERROR = -1073740025 -RC_SSL_LOAD_SERVER_CERT_ERROR = -1073740028 -RC_SSL_CIPHER_LIST_ERROR = -1073740030 -RC_SSL_ERROR = -1073740032 -RC_INVALID_ENUM_OPTION = -1073740287 -RC_NO_BUFFER = -1073740288 -RC_NO_PRIMARY_PEER = -1073740532 -RC_INVALID_CERT_HOST = -1073740534 -RC_HOST_RESOLUTION_ERROR = -1073740535 -RC_SOCKET_BAD_FD = -1073740536 -RC_SOCKET_ADDRESS_IN_USE = -1073740537 -RC_CLIENT_DISCONNECTED = -1073740539 -RC_SERVER_DISCONNECTED = -1073740540 -RC_CLIENT_MESSAGE_ERROR = -1073740541 -RC_SOCKET_ERROR = -1073740544 -RC_SIM_NOT_SUPPORTED = -1073740781 -RC_NOT_HSM_BACKUP_TOKEN = -1073740783 -RC_GROUP_NAME_INVALID = -1073740784 -MSG_ZEROIZING_AFTER_DECOMMISSION = 48 -RC_ENDOFLIST = -1073740786 -RC_SEMAPHORE_ERROR = -1073740787 -RC_OBJECT_ALREADY_EXISTS = -1073740788 -RC_INVALID_INDEX = -1073740789 -RC_CACHE_NOT_MAPPED = -1073740791 -MSG_RESTART = 47 -RC_CACHE_DIRTY = -1073740792 -RC_LISTEN_SOCKET_INVALID = -1073740793 -RC_SOCKET_ADDRESS_INVALID = -1073740794 -LUNA_RET_M_OF_N_SECRET_INVALID = -2147483103 -LUNA_RET_AUDIT_LOGIN_FAILURE_THRESHOLD = -2147480310 -RC_SHUTTING_DOWN = -1073733629 -LUNA_RET_M_OF_N_IS_NOT_INITIALZED = -2147483104 -RC_PORT_INVALID = -1073739520 -RC_CERT_TYPE_INVALID = -1073739776 -LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED = -2147483106 -RC_SSL_GET_CERTIFICATE_ERROR = -1073740023 -MSG_RTC_TAMPER_2_SIGNAL = 14 -RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR = -1073740027 -RC_SSL_CERT_VERIFICATION_LOCATION_ERROR = -1073740029 -MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK = 40 -RC_SSL_CTX_ERROR = -1073740031 -MSG_RTC_ROLLED_BACK = 37 -RC_REMOTE_PEER_OFFLINE = -1073740533 -MSG_TVK_TIMESTAMP_RECOVERY_FAILED = 33 -RC_KEY_NEEDED = -1073741558 -RC_SOCKET_WOULDBLOCK = -1073740538 -LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE = 1245205 -RC_PIN_LOCKED = -1073741560 -MSG_LAST = 55 -MSG_PARTITION_STC_POLICY_SET = 54 -MSG_ZEROIZING = 52 -LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE = 1245203 -MSG_BAD_HMAC = 51 -MSG_LOG_WAS_TRUNCATED = 50 -MSG_ZEROIZING_AFTER_NO_SECURE_DATA = 49 -RC_SOCKET_READ_ERROR = -1073740542 -MSG_GENERATING_NEW_TVK_FAILED = 43 -MSG_GENERATING_NEW_TVK_PASSED = 42 -RC_STC_UNEXPECTED_DH_DATA_SIZE = -1073700837 -MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK = 41 -RC_SOCKET_WRITE_ERROR = -1073740543 -LUNA_RET_OBJECT_HANDLE_INVALID = 8519680 -RC_NOT_PARTITION_BACKUP_TOKEN = -1073740782 -MSG_TVK_WAS_CORRUPTED = 39 -MSG_TVK_TIMESTAMP_UPDATE_FAILED = 38 -RC_CANCEL = -1073741568 -MSG_TVK_TIMESTAMP_IS_TOO_OLD = 36 -MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK = 35 -MSG_TVK_TIMESTAMP_CORRUPTED = 34 -MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED = 32 -MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER = 31 -RC_ASSIGNING_SAME_VALUE = -1073740785 -RC_BUFFER_TOO_SMALL = -1073741818 -RC_OPERATION_WOULD_BLOCK = -1073741819 -LUNA_RET_CB_HIOS_INPUT_BUFFER_TOO_SMALL = -2147481063 -LUNA_RET_TEMPLATE_INCOMPLETE = 13631488 -MSG_TVK_WAS_LOST_DUE_TO_TAMPER = 27 -RC_OBJECT_NOT_IN_LIST = -1073740790 -LUNA_RET_MM_INVALID_USAGE = 3211268 -LUNA_RET_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL = -2147480054 -LUNA_RET_STC_OPEN_RESP_GEN_FAIL = -2147480055 -LUNA_RET_CL_NO_TRANSMISSION = 3146244 -LUNA_RET_CL_QUEUE_OVERLAP_ERROR = 3146242 -LUNA_RET_USER_ALREADY_ACTIVATED = -2147480309 -LUNA_RET_SP_RX_ERROR = 3146034 -LUNA_RET_SP_TX_ERROR = 3146033 -LUNA_RET_LOG_RESYNC_NEEDED = -2147480312 -LUNA_RET_LOG_BAD_TIME = -2147480314 -LUNA_RET_CANCEL = 65536 -MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING = 28 -LUNA_RET_LOG_BAD_RECORD_HMAC = -2147480315 -LUNA_RET_MISSING_VECTOR = -2147483117 -MSG_RTC_MSG_NVRAM_READ_FAILED = 24 -MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED = 23 -MSG_RTC_CONFIGURATION_CORRUPTED = 22 -LUNA_RET_TOO_MANY_WEIGHTS = -2147483122 -LUNA_RET_M_OF_N_ACTIVATION_REQUIRED = -2147483125 -MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF = 19 -MSG_RTC_BATTERY_LOW = 18 -LUNA_RET_SPLIT_DATA_INVALID = -2147483128 -LUNA_RET_MISSING_SPLITS = -2147483129 -MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF = 21 -LUNA_RET_TOTAL_WEIGHT_INVALID = -2147483130 -LUNA_RET_WEIGHT_TOO_SMALL = -2147483131 -LUNA_RET_WEIGHT_TOO_LARGE = -2147483132 -LUNA_RET_M_TOO_SMALL = -2147483133 -MSG_RTC_CANT_CLEAN_POWER_LOSS = 11 -LUNA_RET_N_TOO_LARGE = -2147483136 -MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS = 8 -LUNA_RET_HOC_MISSING = -2147483356 -LUNA_RET_ECC_DAC_MISSING = -2147483358 -LUNA_RET_ECC_DAK_MISSING = -2147483359 -MSG_RTC_CANT_GET_TAMPER_TIMER = 2 -MSG_RTC_EXTERNAL_TAMPER_DETECTED = 1 -MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC = 0 -LUNA_RET_SIM_CORRUPT_DATA = -2147483363 -LUNA_RET_SIM_VERSION_UNSUPPORTED = -2147483364 -LUNA_RET_SIM_AUTHORIZATION_FAILED = -2147483365 -LUNA_RET_CITS_DAK_MISSING = -2147483366 -LUNA_RET_BAD_DAK = -2147483368 -LUNA_RET_DAK_MISSING = -2147483369 -LUNA_RET_BAD_MAC = -2147483370 -LUNA_RET_DAC_MISSING = -2147483373 -MSG_RTC_ZEROIZED_ON_POWER_LOSS = 20 -LUNA_RET_MASKING_NOT_SUPPORTED = -2147483377 -LUNA_RET_TWC_PARAMETER_MISSING = -2147483380 -LUNA_RET_TSN_MISMATCH = -2147483382 -LUNA_RET_INVALID_PRIVATE_KEY_TYPE = -2147483383 -LUNA_RET_UNWRAPPING_ERROR = -2147483384 -LUNA_RET_INVALID_CERTIFICATE_VERSION = -2147483388 -LUNA_RET_INVALID_CERTIFICATE_TYPE = -2147483389 LUNA_RET_INVALID_CERTIFICATE_DATA = -2147483390 -LUNA_RET_CB_PROT_DATA_INVALID = -2147481047 -LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS = -2147483392 -LUNA_RET_INVALID_FUF_VERSION = -2147483632 +LUNA_RET_INVALID_CERTIFICATE_FUNCTION = -2147483355 +LUNA_RET_INVALID_CERTIFICATE_TYPE = -2147483389 +LUNA_RET_INVALID_CERTIFICATE_VERSION = -2147483388 +LUNA_RET_INVALID_ENTRY_TYPE = 458753 LUNA_RET_INVALID_FUF_HEADER = -2147483633 -LUNA_RET_OBJECT_DELETED = -2147483635 -RC_FILE_ERROR = -1073740796 -LUNA_RET_SECURITY_PARAMETER_MISSING = -2147483637 -RC_FILE_NAME_INVALID = -1073740798 -LUNA_RET_CONTAINER_LOCKED = -2147483639 -LUNA_RET_TOO_MANY_CONTAINERS = -2147483640 -RC_RESET_FAILED = -1073741052 -LUNA_RET_AGAIN = -2147483642 +LUNA_RET_INVALID_FUF_TARGET = -2147483634 +LUNA_RET_INVALID_FUF_VERSION = -2147483632 +LUNA_RET_INVALID_IP_PACKET = -2147482112 +LUNA_RET_INVALID_MODULUS_SIZE = -2147483387 LUNA_RET_INVALID_PADDING_TYPE = -2147483646 -RC_MANUFACTURING_TOKEN_NOT_PRESENT = -1073741055 -LUNA_RET_ERROR = -2147483648 -LUNA_RET_CERT_VERSION_NOT_SUPPORTED = 3146496 -LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT = 18153472 -LUNA_RET_WRAPPING_KEY_HANDLE_INVALID = 18022400 -LUNA_RET_WRAPPED_KEY_INVALID = 17825792 -LUNA_RET_USER_TYPE_INVALID = 16973824 -LUNA_RET_SM_NOT_LOGGED_IN = 16842753 -LUNA_RET_USER_NOT_LOGGED_IN = 16842752 -LUNA_RET_USER_ALREADY_LOGGED_IN = 16777216 -LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT = 15859712 -LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE = 15794176 -LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID = 15728640 -LUNA_RET_SIGNATURE_LEN_RANGE = 12648448 -LUNA_RET_SIGNATURE_INVALID = 12582912 -LUNA_RET_SM_SESSION_HANDLE_INVALID = 11730944 -LUNA_RET_CB_REMOTE_CLOSED = -2147481053 -LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS = 11665408 -LUNA_RET_SM_PIN_EXPIRED = 10682368 -LUNA_RET_UM_PIN_LEN_RANGE = 10616832 -LUNA_RET_UM_PIN_INVALID = 10551296 -LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED = 10485762 -LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED = 10485761 -LUNA_RET_UM_PIN_INCORRECT = 10485760 -LUNA_RET_OPERATION_NOT_INITIALIZED = 9502720 -LUNA_RET_OPERATION_ACTIVE = 9437184 -LUNA_RET_MECHANISM_PARAM_INVALID = 7405568 -LUNA_RET_MECHANISM_INVALID = 7340032 +LUNA_RET_INVALID_PRIVATE_KEY_TYPE = -2147483383 +LUNA_RET_INVALID_VECTOR_SIZE = -2147483113 +LUNA_RET_ISES_CMD_FAILED = 3147908 +LUNA_RET_ISES_CMD_PARAMETER_INVALID = 3147909 +LUNA_RET_ISES_ERROR = 3147904 +LUNA_RET_ISES_INIT_FAILED = 3147905 +LUNA_RET_ISES_LNAU_TEST_FAILED = 3147906 +LUNA_RET_ISES_RNG_TEST_FAILED = 3147907 +LUNA_RET_ISES_TEST_VS_BSAFE_FAILED = 3147910 +LUNA_RET_KCDSA_PARAM_GEN_FAILURE = 3145755 +LUNA_RET_KCDSA_SELF_TEST_FAILURE = 3145756 +LUNA_RET_KCV_PARAMETER_ALREADY_EXISTS = -2147483392 +LUNA_RET_KCV_PARAMETER_COULD_NOT_BE_ADDED = -2147483391 +LUNA_RET_KCV_PARAMETER_MISSING = -2147483381 +LUNA_RET_KEY_CANNOT_BE_KEKED = -2147481339 +LUNA_RET_KEY_EXTRACTABLE = 6946817 LUNA_RET_KEY_HANDLE_INVALID = 6291456 -LUNA_RET_FUNCTION_CANCELED = 5242880 -LUNA_RET_ENCRYPTED_DATA_LEN_RANGE = 4259840 -LUNA_RET_ENCRYPTED_DATA_INVALID = 4194304 -LUNA_RET_SM_MEMORY_ALLOCATION_ERROR = 3211523 -LUNA_RET_SM_SESSION_REALLOC_ERROR = 3211522 -LUNA_RET_SM_ACCESS_REALLOC_ERROR = 3211521 -LUNA_RET_TOKEN_LOCKED_OUT_STC = 3145994 -LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST = 3145993 -MSG_RESYNC = 46 -LUNA_RET_TOKEN_LOCKED_OUT_CCM = 3145992 -LUNA_RET_TOKEN_LOCKED_OUT_OH = 3145991 -LUNA_RET_TOKEN_LOCKED_OUT_PM = 3145990 -LUNA_RET_TOKEN_LOCKED_OUT_CA = 3145989 -LUNA_RET_TOKEN_LOCKED_OUT_RN = 3145988 -LUNA_RET_TOKEN_LOCKED_OUT_SM = 3145987 -LUNA_RET_TOKEN_LOCKED_OUT_UM = 3145986 -LUNA_RET_TOKEN_LOCKED_OUT_MM = 3145985 -LUNA_RET_TOKEN_LOCKED_OUT_CL = 3145984 -LUNA_RET_RECALCULATE_K = 3145781 -LUNA_RET_RIPEMD160_SELF_TEST_FAILURE = 3145780 -LUNA_RET_INCOMPATIBLE = 3145764 -LUNA_RET_SELF_TEST_FAILURE = 3145763 -RC_MANUFACTURING_NO_CONFIG_AVAILABLE = -1073741056 -RC_DER_CLASS_INVALID = -1073741312 -RC_CHALLENGE_BUFFER_SIZE = -1073741561 -RC_NON_CRYPTOKI_ELEMENT_CLONE = -1073741562 -RC_FUNCTION_NOT_SUPPORTED = -1073741563 -RC_TOKEN_NOT_PRESENT = -1073741564 -RC_DATA_INVALID = -1073741566 -RC_SLOT_ID_INVALID = -1073741567 -RC_SSL_LOAD_CLIENT_CERT_ERROR = -1073740024 -LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 -RC_UNEXPECTED = -1073741820 -RC_POINTER_INVALID = -1073741821 -RC_RC_ERROR = -1073741824 -RC_OK = 0 -LUNA_RET_STC_ACTIVATE_RESP_GEN_FAIL = -2147480052 -LUNA_RET_STC_ACTIVATE_MACTAG_V_GEN_FAIL = -2147480053 -LUNA_RET_STC_OPEN_KEY_MATERIAL_GEN_FAIL = -2147480056 -LUNA_RET_STC_OPEN_DHNIST_PUBKEY_ERROR = -2147480057 -LUNA_RET_STC_NO_CHANNEL = -2147480059 -LUNA_RET_STC_SEQUENCE_NUM_INVALID = -2147480060 -LUNA_RET_STC_CONTAINER_INVALID = -2147480061 -LUNA_RET_STC_SESSION_INVALID = -2147480062 -LUNA_RET_STC_CLIENT_HANDLE_INVALID = -2147480063 -LUNA_RET_STC_NOT_ENABLED = -2147480064 -LUNA_RET_STC_CHANNEL_REALLOC_ERROR = 3211264 -LUNA_RET_TIME_NOT_INITIALIZED = -2147480308 -LUNA_RET_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS = -2147480311 +LUNA_RET_KEY_INDIGESTIBLE = 6750208 +LUNA_RET_KEY_INVALID_FOR_OPERATION = 6488065 +LUNA_RET_KEY_NOT_ACTIVE = -2147481340 +LUNA_RET_KEY_NOT_KEKED = -2147481338 +LUNA_RET_KEY_NOT_UNWRAPPABLE = 6881281 +LUNA_RET_KEY_NOT_WRAPPABLE = 6881280 +LUNA_RET_KEY_PARITY = 6488066 +LUNA_RET_KEY_SENSITIVE = 6356992 +LUNA_RET_KEY_SIZE_RANGE = 6422528 +LUNA_RET_KEY_TYPE_INCONSISTENT = 6488064 +LUNA_RET_KEY_UNEXTRACTABLE = 6946816 +LUNA_RET_LICENSE_CAPACITY_EXCEEDED = 68105 +LUNA_RET_LICENSE_ID_UNKNOWN = 2099720 LUNA_RET_LOG_AUDIT_NOT_INITIALIZED = -2147480313 -LUNA_RET_CB_RETRY = -2147481083 -LUNA_RET_LOG_NO_KCV = -2147480316 -LUNA_RET_LOG_FULL = -2147480317 LUNA_RET_LOG_BAD_FILE_NAME = -2147480318 -LUNA_RET_CB_TIMEOUT = -2147481084 -LUNA_RET_LOG_FILE_WRITE_ERROR = -2147480319 +LUNA_RET_LOG_BAD_RECORD_HMAC = -2147480315 +LUNA_RET_LOG_BAD_TIME = -2147480314 LUNA_RET_LOG_FILE_NOT_OPEN = -2147480320 -LUNA_RET_STATE_UNSAVEABLE = 25165824 -LUNA_RET_SAVED_STATE_INVALID = 23068672 -LUNA_RET_FM_ID_INVALID = -2147480832 -LUNA_RET_CB_SYNC_ERROR = -2147481048 -LUNA_RET_CB_INVALID_CALL_FOR_THE_STATE = -2147481049 -LUNA_RET_CB_MUST_WRITE = -2147481050 -LUNA_RET_CB_MUST_READ = -2147481051 -LUNA_RET_CB_REMOTE_ABANDONED = -2147481052 -LUNA_RET_CB_REMOTE_ABORT = -2147481054 -LUNA_RET_CB_ID_INVALID = -2147481055 -LUNA_RET_CB_HANDLE_INVALID = -2147481056 -LUNA_RET_CB_HIOS_OUTPUT_BUFFER_TOO_SMALL = -2147481064 -LUNA_RET_CB_HIOS_STATE_INVALID = -2147481065 -LUNA_RET_CB_HIOS_RECV_TIMEOUT = -2147481066 -LUNA_RET_CB_HIOS_SEND_TIMEOUT = -2147481067 -LUNA_RET_CB_HIOS_IO_ERROR = -2147481068 -LUNA_RET_CB_HIOS_CANCELED = -2147481069 -RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR = -1073740026 -LUNA_RET_CB_HIOS_CLOSED = -2147481070 -LUNA_RET_VECTOR_TOO_LARGE = -2147483116 -LUNA_RET_CB_HIOS_ID_INVALID = -2147481071 +LUNA_RET_LOG_FILE_WRITE_ERROR = -2147480319 +LUNA_RET_LOG_FULL = -2147480317 +LUNA_RET_LOG_NO_KCV = -2147480316 +LUNA_RET_LOG_RESYNC_NEEDED = -2147480312 +LUNA_RET_M_OF_N_ACTIVATION_REQUIRED = -2147483125 +LUNA_RET_M_OF_N_CLONING_IS_NOT_ALLOWED = -2147483106 +LUNA_RET_M_OF_N_IS_NOT_INITIALZED = -2147483104 +LUNA_RET_M_OF_N_IS_NOT_REQUIRED = -2147483105 +LUNA_RET_M_OF_N_PARAMETER_EXIST = -2147483112 +LUNA_RET_M_OF_N_PARAMETER_NOT_AVAILABLE = -2147483126 +LUNA_RET_M_OF_N_SECRET_INVALID = -2147483103 +LUNA_RET_M_TOO_LARGE = -2147483134 +LUNA_RET_M_TOO_SMALL = -2147483133 +LUNA_RET_MAC_MISSING = -2147483375 +LUNA_RET_MASKING_NOT_SUPPORTED = -2147483377 +LUNA_RET_MAX_OBJECT_COUNT = 8519681 +LUNA_RET_MD2_SELF_TEST_FAILURE = 3145736 +LUNA_RET_MD5_SELF_TEST_FAILURE = 3145737 +LUNA_RET_MECHANISM_INVALID = 7340032 +LUNA_RET_MECHANISM_INVALID_FOR_FP = -2147481337 +LUNA_RET_MECHANISM_PARAM_INVALID = 7405568 +LUNA_RET_MEMORY_ALLOCATION_FAILED = 3211271 +LUNA_RET_MISSING_COMMAND_PARAMETER = -2147483107 +LUNA_RET_MISSING_NUMBER_OF_VECTORS = -2147483118 +LUNA_RET_MISSING_SPLITS = -2147483129 +LUNA_RET_MISSING_VALUE_FOR_M = -2147483120 +LUNA_RET_MISSING_VALUE_FOR_N = -2147483119 +LUNA_RET_MISSING_VECTOR = -2147483117 +LUNA_RET_MISSING_WEIGHT_VALUE = -2147483121 +LUNA_RET_MM_ACCESS_OUTSIDE_ALLOCATION_RANGE = 3211267 +LUNA_RET_MM_FATAL_ERROR = 3211270 +LUNA_RET_MM_INVALID_HANDLE = 3211265 +LUNA_RET_MM_INVALID_USAGE = 3211268 +LUNA_RET_MM_ITERATOR_PAST_END = 3211269 +LUNA_RET_MM_NOT_ENOUGH_MEMORY = 3211264 +LUNA_RET_MM_USAGE_ALREADY_SET = 3211266 +LUNA_RET_MTK_SPLIT_INVALID = -2147482317 +LUNA_RET_MTK_STATE_INVALID = -2147482318 +LUNA_RET_MTK_ZEROIZED = -2147482319 +LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED = 13697048 LUNA_RET_MUTEX_BAD = 27262976 -LUNA_RET_CB_HIOS_HANDLE_INVALID = -2147481072 -LUNA_RET_CB_SYS_ERROR = -2147481081 -LUNA_RET_CB_ABORTED = -2147481082 -LUNA_RET_CB_NO_MEMORY = -2147481085 -LUNA_RET_CB_PARAM_INVALID = -2147481086 -LUNA_RET_CB_NOT_SUPPORTED = -2147481087 -LUNA_RET_CONTAINER_CAN_NOT_HAVE_MEMBERS = 2100229 +LUNA_RET_N_TOO_LARGE = -2147483136 +LUNA_RET_N_TOO_SMALL = -2147483135 +LUNA_RET_NO_INVERSE = 2097155 +LUNA_RET_NO_OFFBOARD_STORAGE = 5505025 +LUNA_RET_NO_RNG_SEED = 2097173 +LUNA_RET_NOT_FOUND = -2147483641 +LUNA_RET_NOT_READY = 3145760 +LUNA_RET_OBJECT_DELETED = -2147483635 +LUNA_RET_OBJECT_HANDLE_INVALID = 8519680 +LUNA_RET_OH_OBJECT_ALREADY_EXISTS = 68610 LUNA_RET_OH_OBJECT_OWNER_DOES_NOT_EXIST = 2100227 -LUNA_RET_STORAGE_TYPE_INCONSISTENT = 2100228 LUNA_RET_OH_OBJECT_TYPE_INVALID = 3148801 LUNA_RET_OH_OBJECT_VERSION_INVALID = 3148800 -LUNA_RET_CHALLENGE_INVALID = 2099972 -LUNA_RET_410_CHALLENGE_RESPONSE_INCORRECT = 68355 -LUNA_RET_CHALLENGE_REQUIRES_PED = 68353 -LUNA_RET_BAD_SN = 2099729 -LUNA_RET_RM_CONFIG_ILLEGAL = 2099728 -LUNA_RET_OH_OBJECT_ALREADY_EXISTS = 68610 -LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE = 2099727 -LUNA_RET_BAD_FW_VERSION = 2099726 -LUNA_RET_CANNOT_PERFORM_OPERATION_TWICE = 68108 +LUNA_RET_OK = 0 +LUNA_RET_OPERATION_ACTIVE = 9437184 +LUNA_RET_OPERATION_INVALID_FOR_FP = -2147481336 +LUNA_RET_OPERATION_NOT_INITIALIZED = 9502720 LUNA_RET_OPERATION_RESTRICTED = 68107 -LUNA_RET_RM_POLICY_WRITE_RESTRICTED = 68106 -LUNA_RET_LICENSE_CAPACITY_EXCEEDED = 68105 -LUNA_RET_LICENSE_ID_UNKNOWN = 2099720 +LUNA_RET_OPERATION_SHOULD_BE_DESTRUCTIVE = 2099727 +LUNA_RET_PE1746_ERROR = 3147911 +LUNA_RET_PED_CLIENT_NOT_RUNNING = 3146055 +LUNA_RET_PED_DEK_INVALID = 3146054 +LUNA_RET_PED_ERROR = 3146052 +LUNA_RET_PED_ID_INVALID = 3146048 +LUNA_RET_PED_UNPLUGGED = 3146050 +LUNA_RET_PED_UNSUPPORTED_CRYPTO_PROTOCOL = 3146053 +LUNA_RET_PED_UNSUPPORTED_PROTOCOL = 3146049 +LUNA_RET_POLICY_NOT_FOUND = 2099730 +LUNA_RET_PRIVATE_KEY_MUST_BE_SENSITIVE = 1245205 +LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631510 +LUNA_RET_RC2_SELF_TEST_FAILURE = 3145740 +LUNA_RET_RC4_SELF_TEST_FAILURE = 3145741 +LUNA_RET_RC5_SELF_TEST_FAILURE = 3145742 +LUNA_RET_RECALCULATE_K = 3145781 +LUNA_RET_RETRY = 3145761 +LUNA_RET_RIPEMD160_SELF_TEST_FAILURE = 3145780 +LUNA_RET_RM_BAD_HSM_PARAMS = 3148291 LUNA_RET_RM_CONFIG_CHANGE_FAILS_DEPENDENCIES = 68103 LUNA_RET_RM_CONFIG_CHANGE_ILLEGAL = 68102 +LUNA_RET_RM_CONFIG_ILLEGAL = 2099728 +LUNA_RET_RM_ELEMENT_ID_INVALID = 2099713 +LUNA_RET_RM_ELEMENT_VALUE_INVALID = 2099712 +LUNA_RET_RM_NO_MEMORY = 3213826 +LUNA_RET_RM_POLICY_ELEMENT_DESTRUCTIVE = 2099716 LUNA_RET_RM_POLICY_ELEMENT_NOT_DESTRUCTIVE = 2099717 -MSG_RTC_EXTERNAL_TAMPER_LATCHED = 13 -LUNA_RET_NOT_READY = 3145760 -LUNA_RET_TIMEOUT = 3145759 -LUNA_RET_COUNTER_WRAPAROUND = 3145758 -LUNA_RET_HSM_INTERNAL_BUFFER_TOO_SMALL = 3145757 -LUNA_RET_KCDSA_SELF_TEST_FAILURE = 3145756 -LUNA_RET_KCDSA_PARAM_GEN_FAILURE = 3145755 -LUNA_RET_HAS160_SELF_TEST_FAILURE = 3145754 -LUNA_RET_FUNCTION_NOT_SUPPORTED_BY_HARDWARE = 3145753 -LUNA_RET_AES_SELF_TEST_FAILURE = 3145752 +LUNA_RET_RM_POLICY_WRITE_RESTRICTED = 68106 +LUNA_RET_RNG_ERROR = 3145731 +LUNA_RET_RNG_RESEED_REQUIRED = 3147913 +LUNA_RET_RNG_RESEED_TOO_EARLY = 3147914 +LUNA_RET_RNG_SELF_TEST_FAILURE = 3145744 +LUNA_RET_ROOT_CERT_MISSING = -2147483357 +LUNA_RET_RSA_SELF_TEST_FAILURE = 3145739 +LUNA_RET_SAVED_STATE_INVALID = 23068672 +LUNA_RET_SECRET_KEY_MUST_BE_SENSITIVE = 1245203 +LUNA_RET_SECRET_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631508 +LUNA_RET_SECURITY_PARAMETER_MISSING = -2147483637 LUNA_RET_SEED_SELF_TEST_FAILURE = 3145751 -LUNA_RET_DSA_SELF_TEST_FAILURE = 3145750 -LUNA_RET_DSA_PARAM_GEN_FAILURE = 3145749 -LUNA_RET_SM_UNKNOWN_TOSM_STATE = 3145748 +LUNA_RET_SELF_TEST_FAILURE = 3145763 +LUNA_RET_SENTRY_PKA_ERROR = 3147912 +LUNA_RET_SESSION_HANDLE_INVALID_FOR_FP = -2147481335 +LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT = 3147812 +LUNA_RET_SFNT3120_CRC = 3147811 +LUNA_RET_SFNT3120_ERROR = 3147809 +LUNA_RET_SFNT3120_SELFTEST_FAILED = 3147810 +LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE = 3145762 +LUNA_RET_SHA_SELF_TEST_FAILURE = 3145738 +LUNA_RET_SIGNATURE_INVALID = 12582912 +LUNA_RET_SIGNATURE_LEN_RANGE = 12648448 +LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL = 6815745 +LUNA_RET_SIM_AUTHFORM_INVALID = 2097438 +LUNA_RET_SIM_AUTHORIZATION_FAILED = -2147483365 +LUNA_RET_SIM_CORRUPT_DATA = -2147483363 +LUNA_RET_SIM_VERSION_UNSUPPORTED = -2147483364 +LUNA_RET_SM_ACCESS_ALREADY_EXISTS = -2147482623 +LUNA_RET_SM_ACCESS_DOES_NOT_VALIDATE = -2147482613 +LUNA_RET_SM_ACCESS_ID_INVALID = -2147482624 +LUNA_RET_SM_ACCESS_REALLOC_ERROR = 3211521 +LUNA_RET_SM_BAD_ACCESS_HANDLE = -2147482620 +LUNA_RET_SM_BAD_CONTEXT_NUMBER = -2147482619 +LUNA_RET_SM_CONTEXT_ALREADY_ALLOCATED = -2147482617 +LUNA_RET_SM_CONTEXT_BUFFER_OVERFLOW = -2147482615 +LUNA_RET_SM_CONTEXT_NOT_ALLOCATED = -2147482616 +LUNA_RET_SM_DATA_INVALID = 2097154 +LUNA_RET_SM_EXCLUSIVE_SESSION_EXISTS = 11665408 +LUNA_RET_SM_KEY_SIZE_ERROR = 6422529 +LUNA_RET_SM_MEMORY_ALLOCATION_ERROR = 3211523 +LUNA_RET_SM_MULTIPLE_ACCESS_DISABLED = -2147482622 +LUNA_RET_SM_NOT_LOGGED_IN = 16842753 +LUNA_RET_SM_OTHER_USER_LOGGED_IN = 16777217 +LUNA_RET_SM_PIN_EXPIRED = 10682368 +LUNA_RET_SM_SESSION_HANDLE_INVALID = 11730944 +LUNA_RET_SM_SESSION_READ_ONLY_EXISTS = 11993088 +LUNA_RET_SM_SESSION_REALLOC_ERROR = 3211522 +LUNA_RET_SM_TOSM_DOES_NOT_VALIDATE = -2147482614 LUNA_RET_SM_TSV_MISSING = 3145747 -LUNA_RET_UM_TSN_MISSING = 3145746 +LUNA_RET_SM_UNKNOWN_ACCESS_TYPE = -2147482621 LUNA_RET_SM_UNKNOWN_COMMAND = 3145745 -LUNA_RET_CHALLENGE_RESPONSE_INCORRECT = 10488579 -LUNA_RET_RNG_SELF_TEST_FAILURE = 3145744 +LUNA_RET_SM_UNKNOWN_SESSION_TYPE = -2147482618 +LUNA_RET_SM_UNKNOWN_TOSM_STATE = 3145748 LUNA_RET_SO_LOGIN_FAILURE_THRESHOLD = 3145743 -LUNA_RET_RC5_SELF_TEST_FAILURE = 3145742 -LUNA_RET_RC2_SELF_TEST_FAILURE = 3145740 -LUNA_RET_MISSING_NUMBER_OF_VECTORS = -2147483118 -LUNA_RET_RSA_SELF_TEST_FAILURE = 3145739 -LUNA_RET_CHALLENGE_NOT_REQUIRED = 68354 -LUNA_RET_SHA_SELF_TEST_FAILURE = 3145738 -LUNA_RET_CAST5_SELF_TEST_FAILURE = 3145735 -LUNA_RET_CAST_SELF_TEST_FAILURE = 3145733 -LUNA_RET_DES_SELF_TEST_FAILURE = 3145732 -LUNA_RET_RNG_ERROR = 3145731 +LUNA_RET_SP_RX_ERROR = 3146034 +LUNA_RET_SP_TX_ERROR = 3146033 +LUNA_RET_SPLIT_DATA_INVALID = -2147483128 +LUNA_RET_SPLIT_ID_INVALID = -2147483127 +LUNA_RET_SSK_MISSING = -2147483371 +LUNA_RET_STATE_UNSAVEABLE = 25165824 +LUNA_RET_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL = -2147480054 +LUNA_RET_STC_ACTIVATE_MACTAG_V_GEN_FAIL = -2147480053 +LUNA_RET_STC_ACTIVATE_RESP_GEN_FAIL = -2147480052 +LUNA_RET_STC_CHANNEL_REALLOC_ERROR = 3211264 +LUNA_RET_STC_CLIENT_HANDLE_INVALID = -2147480063 +LUNA_RET_STC_CONTAINER_INVALID = -2147480061 +LUNA_RET_STC_NO_CHANNEL = -2147480059 +LUNA_RET_STC_NOT_ENABLED = -2147480064 +LUNA_RET_STC_OPEN_CIPHER_MISMATCH = -2147480058 +LUNA_RET_STC_OPEN_DHNIST_PUBKEY_ERROR = -2147480057 +LUNA_RET_STC_OPEN_KEY_MATERIAL_GEN_FAIL = -2147480056 +LUNA_RET_STC_OPEN_RESP_GEN_FAIL = -2147480055 +LUNA_RET_STC_SEQUENCE_NUM_INVALID = -2147480060 +LUNA_RET_STC_SESSION_INVALID = -2147480062 +LUNA_RET_STM_CMD_NON_TRANSPORT = -2147482316 +LUNA_RET_STORAGE_TYPE_INCONSISTENT = 2100228 +LUNA_RET_TEMPLATE_INCOMPLETE = 13631488 +LUNA_RET_TEMPLATE_INCONSISTENT = 13697024 +LUNA_RET_TEST_VS_BSAFE_FAILED = 3147808 +LUNA_RET_TIME_NOT_INITIALIZED = -2147480308 +LUNA_RET_TIMEOUT = 3145759 LUNA_RET_TOKEN_LOCKED_OUT = 3145730 -LUNA_RET_UNKNOWN_COMMAND = 3145729 -LUNA_RET_DEVICE_ERROR = 3145728 -LUNA_RET_GENERAL_ERROR = 327680 -LUNA_RET_410_BUFFER_TOO_SMALL = 2097174 -LUNA_RET_BUFFER_TOO_SMALL = 22020096 -LUNA_RET_NO_OFFBOARD_STORAGE = 5505025 -LUNA_RET_POLICY_NOT_FOUND = 2099730 -LUNA_RET_NO_RNG_SEED = 2097173 -LUNA_RET_SM_DATA_INVALID = 2097154 +LUNA_RET_TOKEN_LOCKED_OUT_CA = 3145989 +LUNA_RET_TOKEN_LOCKED_OUT_CCM = 3145992 +LUNA_RET_TOKEN_LOCKED_OUT_CL = 3145984 +LUNA_RET_TOKEN_LOCKED_OUT_MM = 3145985 +LUNA_RET_TOKEN_LOCKED_OUT_OH = 3145991 +LUNA_RET_TOKEN_LOCKED_OUT_PM = 3145990 +LUNA_RET_TOKEN_LOCKED_OUT_RN = 3145988 +LUNA_RET_TOKEN_LOCKED_OUT_SHA_DIGEST = 3145993 +LUNA_RET_TOKEN_LOCKED_OUT_SM = 3145987 +LUNA_RET_TOKEN_LOCKED_OUT_STC = 3145994 +LUNA_RET_TOKEN_LOCKED_OUT_UM = 3145986 +LUNA_RET_TOKEN_NOT_PRESENT = 14680064 +LUNA_RET_TOO_MANY_CONTAINERS = -2147483640 +LUNA_RET_TOO_MANY_VECTORS_PROVIDED = -2147483114 +LUNA_RET_TOO_MANY_WEIGHTS = -2147483122 +LUNA_RET_TOTAL_WEIGHT_INVALID = -2147483130 LUNA_RET_TPV_INVALID = 2097153 -LUNA_RET_DATA_INVALID = 2097152 -LUNA_RET_INVALID_ENTRY_TYPE = 458753 -LUNA_RET_KEY_NOT_UNWRAPPABLE = 6881281 -LUNA_RET_KEY_NOT_WRAPPABLE = 6881280 -LUNA_RET_KEY_INDIGESTIBLE = 6750208 -LUNA_RET_KEY_EXTRACTABLE = 6946817 -LUNA_RET_KEY_PARITY = 6488066 -LUNA_RET_KEY_INVALID_FOR_OPERATION = 6488065 -LUNA_RET_KEY_TYPE_INCONSISTENT = 6488064 -LUNA_RET_SM_KEY_SIZE_ERROR = 6422529 -LUNA_RET_KEY_SIZE_RANGE = 6422528 -LUNA_RET_KEY_SENSITIVE = 6356992 -LUNA_RET_CAN_NOT_CHANGE_KEY_FUNCTION = 1048601 -LUNA_RET_MULTI_FUNCTION_KEYS_NOT_ALLOWED = 13697048 -LUNA_RET_SIGNING_KEY_MUST_BE_LOCAL = 6815745 -LUNA_RET_PRIVATE_KEY_MUST_HAVE_SENSITIVE_ATTRIBUTE = 13631510 -LUNA_RET_BAD_PPID = 2099725 +LUNA_RET_TSN_MISMATCH = -2147483382 +LUNA_RET_TUK_PARAMETER_MISSING = -2147483379 +LUNA_RET_TWC_PARAMETER_MISSING = -2147483380 +LUNA_RET_UM_PIN_INCORRECT = 10485760 +LUNA_RET_UM_PIN_INCORRECT_CONTAINER_LOCKED = 10485762 +LUNA_RET_UM_PIN_INCORRECT_CONTAINER_ZEROIZED = 10485761 +LUNA_RET_UM_PIN_INVALID = 10551296 +LUNA_RET_UM_PIN_LEN_RANGE = 10616832 +LUNA_RET_UM_TSN_MISSING = 3145746 +LUNA_RET_UNKNOWN_COMMAND = 3145729 +LUNA_RET_UNWRAPPING_ERROR = -2147483384 +LUNA_RET_UNWRAPPING_KEY_HANDLE_INVALID = 15728640 +LUNA_RET_UNWRAPPING_KEY_SIZE_RANGE = 15794176 +LUNA_RET_UNWRAPPING_KEY_TYPE_INCONSISTENT = 15859712 +LUNA_RET_USER_ALREADY_ACTIVATED = -2147480309 +LUNA_RET_USER_ALREADY_LOGGED_IN = 16777216 +LUNA_RET_USER_NOT_LOGGED_IN = 16842752 +LUNA_RET_USER_PIN_NOT_INITIALIZED = 16908288 +LUNA_RET_USER_TYPE_INVALID = 16973824 +LUNA_RET_VECTOR_DUPLICATE = -2147483109 +LUNA_RET_VECTOR_OF_DIFFERENT_SET = -2147483110 +LUNA_RET_VECTOR_TOO_LARGE = -2147483116 +LUNA_RET_VECTOR_TOO_SMALL = -2147483115 +LUNA_RET_VECTOR_TYPE_INVALID = -2147483108 +LUNA_RET_VECTOR_VERSION_INVALID = -2147483111 +LUNA_RET_WEIGHT_TOO_LARGE = -2147483132 +LUNA_RET_WEIGHT_TOO_SMALL = -2147483131 +LUNA_RET_WRAPPED_KEY_INVALID = 17825792 +LUNA_RET_WRAPPED_KEY_LEN_RANGE = 17956864 +LUNA_RET_WRAPPING_ERROR = -2147483385 +LUNA_RET_WRAPPING_KEY_HANDLE_INVALID = 18022400 +LUNA_RET_WRAPPING_KEY_SIZE_RANGE = 18087936 +LUNA_RET_WRAPPING_KEY_TYPE_INCONSISTENT = 18153472 +MSG_BAD_HMAC = 51 +MSG_EXISTING_AUTO_ACTIVATION_DATA_WONT_WORK = 41 +MSG_FACTORY_RESET = 53 +MSG_GENERATING_NEW_TVK_FAILED = 43 +MSG_GENERATING_NEW_TVK_PASSED = 42 +MSG_INITIALIZING_MSG_TVK_TIMESTAMP_FAILED = 44 +MSG_LAST = 55 +MSG_LOG_NO_SECRET_PM_LOG_INIT_IS_DEFERRED = 45 +MSG_LOG_WAS_TRUNCATED = 50 +MSG_NVRAM_READ_FAILED = 25 +MSG_NVRAM_WRITE_FAILED = 26 +MSG_PARTITION_STC_POLICY_SET = 54 +MSG_RESTART = 47 +MSG_RESYNC = 46 +MSG_RTC_BATTERY_LOW = 18 +MSG_RTC_BATTERY_WAS_LOW_WHEN_MAIN_POWER_WAS_OFF = 19 +MSG_RTC_CANT_ACCESS = 6 +MSG_RTC_CANT_ARM_TAMPER_1_CIRCUITS = 8 +MSG_RTC_CANT_ARM_TAMPER_2_CIRCUITS = 10 +MSG_RTC_CANT_CLEAN_POWER_LOSS = 11 +MSG_RTC_CANT_CLEAN_TAMPER_1 = 7 MSG_RTC_CANT_CLEAN_TAMPER_2 = 9 -RC_USER_NAME_IN_USE = -1073741557 -LUNA_RET_RM_BAD_HSM_PARAMS = 3148291 -LUNA_RET_RM_NO_MEMORY = 3213826 -LUNA_RET_RM_ELEMENT_ID_INVALID = 2099713 -LUNA_RET_SHA1_RSA_SELF_TEST_FAILURE = 3145762 -LUNA_RET_RM_ELEMENT_VALUE_INVALID = 2099712 -LUNA_RET_SESSION_HANDLE_INVALID_FOR_FP = -2147481335 -LUNA_RET_OPERATION_INVALID_FOR_FP = -2147481336 -LUNA_RET_MECHANISM_INVALID_FOR_FP = -2147481337 -LUNA_RET_KEY_CANNOT_BE_KEKED = -2147481339 -LUNA_RET_RETRY = 3145761 -LUNA_RET_KEY_NOT_ACTIVE = -2147481340 -LUNA_RET_CONTAINER_OBJECT_STORAGE_FULL = -2147481341 -LUNA_RET_HSM_STORAGE_FULL = -2147481342 -LUNA_RET_HA_USER_NOT_INITIALIZED = -2147481343 -LUNA_RET_HA_NOT_SUPPORTED = -2147481344 -LUNA_RET_ECC_RESULT_AT_INF = -2147482106 -LUNA_RET_ECC_UNKNOWN_CURVE = -2147482107 -LUNA_RET_ECC_SELF_TEST_FAILURE = -2147482108 -LUNA_RET_ECC_POINT_INVALID = -2147482109 -LUNA_RET_RNG_RESEED_TOO_EARLY = 3147914 -LUNA_RET_RNG_RESEED_REQUIRED = 3147913 -LUNA_RET_NO_INVERSE = 2097155 -LUNA_RET_SENTRY_PKA_ERROR = 3147912 -LUNA_RET_ISES_TEST_VS_BSAFE_FAILED = 3147910 -LUNA_RET_ISES_CMD_PARAMETER_INVALID = 3147909 -LUNA_RET_ISES_CMD_FAILED = 3147908 -LUNA_RET_ISES_RNG_TEST_FAILED = 3147907 -LUNA_RET_ISES_LNAU_TEST_FAILED = 3147906 -LUNA_RET_ISES_INIT_FAILED = 3147905 -LUNA_RET_ISES_ERROR = 3147904 -LUNA_RET_SFNT3120_ALG_NO_SOFTWARE_SUPPORT = 3147812 -LUNA_RET_SFNT3120_CRC = 3147811 -LUNA_RET_SFNT3120_ERROR = 3147809 -LUNA_RET_TEST_VS_BSAFE_FAILED = 3147808 -LUNA_RET_HIFN6500_INVALID_RESULT_ENDIANESS = 3147789 -LUNA_RET_HIFN6500_INVALID_OPERAND_ENDIANESS = 3147788 -LUNA_RET_HIFN6500_INVALID_OPERAND_LENGTH = 3147787 -LUNA_RET_HIFN6500_INVALID_PARAMETERS = 3147786 -LUNA_RET_HIFN6500_ALU_TIMEOUT = 3147785 -LUNA_RET_HIFN6500_RNG_UNDERFLOW = 3147784 -LUNA_RET_HIFN6500_RNG_TIMEOUT = 3147783 -LUNA_RET_HIFN6500_RNG_FAILED = 3147782 -LUNA_RET_HIFN6500_KNOWN_ANSWER_TEST_FAILED = 3147781 -LUNA_RET_HIFN6500_ADDRESS_LINES_BROKEN = 3147780 -LUNA_RET_HIFN6500_DATA_LINES_BROKEN = 3147779 -LUNA_RET_HIFN6500_RESET_TIMEOUT = 3147778 -LUNA_RET_HIFN6500_NOT_PRESENT = 3147777 -LUNA_RET_HSM_TAMPERED = -2147482315 -LUNA_RET_STM_CMD_NON_TRANSPORT = -2147482316 -LUNA_RET_MTK_SPLIT_INVALID = -2147482317 -LUNA_RET_MTK_STATE_INVALID = -2147482318 -LUNA_RET_MTK_ZEROIZED = -2147482319 -LUNA_RET_HIFN_DMA_INVALID_REVISION = -2147482320 -LUNA_RET_HIFN_ENCRYPT_SOURCE_NOT_ZERO = -2147482342 -LUNA_RET_HIFN_MAC_SOURCE_NOT_ZERO = -2147482343 -LUNA_RET_HIFN_COMPRESS_SOURCE_NOT_ZERO = -2147482344 +MSG_RTC_CANT_GET_TAMPER_TIMER = 2 MSG_RTC_CANT_INITIALIZE_I2C = 5 -LUNA_RET_RC4_SELF_TEST_FAILURE = 3145741 +MSG_RTC_CONFIGURATION_CORRUPTED = 22 +MSG_RTC_EXTERNAL_TAMPER_DETECTED = 1 +MSG_RTC_EXTERNAL_TAMPER_LATCHED = 13 +MSG_RTC_HSM_WAS_REMOVED_FROM_THE_PCI_SLOT = 15 +MSG_RTC_IS_NOT_OPERATIONAL_AUTO_ACTIVATION_WILL_NO_WORK = 40 +MSG_RTC_LOST_ALL_POWER = 17 +MSG_RTC_MSG_NVRAM_READ_FAILED = 24 MSG_RTC_MSG_NVRAM_WRITE_FAILED = 4 -LUNA_RET_HIFN_INVALID_PAD_ALGORITHM = -2147482348 -LUNA_RET_MD5_SELF_TEST_FAILURE = 3145737 -LUNA_RET_MD2_SELF_TEST_FAILURE = 3145736 -LUNA_RET_HIFN_COMPRESSION_SOURCE_COUNT_INVALID = -2147482350 -LUNA_RET_HIFN_INVALID_COMPRESSION_ALGORITHM = -2147482351 -LUNA_RET_CAST3_SELF_TEST_FAILURE = 3145734 -LUNA_RET_HIFN_DMA_NOT_IDLE = -2147482355 -LUNA_RET_HIFN_DMA_ERROR = -2147482357 -LUNA_RET_HIFN_ENCRYPT_SOURCE_COUNT_INVALID = -2147482359 -LUNA_RET_DATA_LEN_RANGE = 2162688 -LUNA_RET_CL_COMMAND_NON_BACKUP = 5505026 +MSG_RTC_MSG_NVRAM_ZAPPING_FAILED = 3 +MSG_RTC_RE_CONFIGURINGPASSED_CLOCK_RESTARTED = 23 +MSG_RTC_RECONFIGURING_FAILED = 12 +MSG_RTC_ROLLED_BACK = 37 +MSG_RTC_RTC_MONITOR_CANT_COMMUNICATE_TO_RTC = 0 +MSG_RTC_TAMPER_2_SIGNAL = 14 +MSG_RTC_TAMPER_CIRCUITS_RE_ARMED = 16 +MSG_RTC_UNRELIABLE_DUE_TO_LOW_BATTERY_WHEN_MAIN_POWER_WAS_OFF = 21 +MSG_RTC_ZEROIZED_ON_POWER_LOSS = 20 +MSG_TVK_TIMESTAMP_CORRUPTED = 34 +MSG_TVK_TIMESTAMP_IS_OLDER_THAN_RTC_CLOCK = 35 +MSG_TVK_TIMESTAMP_IS_TOO_OLD = 36 +MSG_TVK_TIMESTAMP_RECOVERY_COMPLETED = 32 +MSG_TVK_TIMESTAMP_RECOVERY_FAILED = 33 +MSG_TVK_TIMESTAMP_UPDATE_FAILED = 38 +MSG_TVK_TIMESTAMP_UPDATE_WAS_LIKELY_ABORTED_TRYING_TO_RECOVER = 31 +MSG_TVK_TIMESTAMP_WAS_LOST_DUE_TO_RTC_RESET = 30 +MSG_TVK_WAS_CORRUPTED = 39 +MSG_TVK_WAS_LOST_DUE_TO_BAD_BATTERY = 29 +MSG_TVK_WAS_LOST_DUE_TO_DECOMMISSIONING = 28 +MSG_TVK_WAS_LOST_DUE_TO_TAMPER = 27 +MSG_ZEROIZING = 52 +MSG_ZEROIZING_AFTER_DECOMMISSION = 48 +MSG_ZEROIZING_AFTER_NO_SECURE_DATA = 49 +RC_ARGUMENTS_BAD = -1073741817 +RC_ASSIGNING_SAME_VALUE = -1073740785 +RC_BUFFER_TOO_SMALL = -1073741818 +RC_CACHE_DIRTY = -1073740792 +RC_CACHE_NOT_MAPPED = -1073740791 +RC_CALLBACK_ERROR = -1073733631 +RC_CANCEL = -1073741568 +RC_CERT_TYPE_INVALID = -1073739776 +RC_CHALLENGE_BUFFER_SIZE = -1073741561 +RC_CLIENT_DISCONNECTED = -1073740539 +RC_CLIENT_MESSAGE_ERROR = -1073740541 +RC_CMD_BLOCKED_REMOTE_PED_TUNNEL = -1073733622 +RC_DATA_CORRUPTED = -1073740799 +RC_DATA_INVALID = -1073741566 +RC_DER_CLASS_INVALID = -1073741312 +RC_ENDOFLIST = -1073740786 +RC_FAILED_TO_CREATE_PROCESS = -1073733615 +RC_FAILED_TO_CREATE_THREAD = -1073733632 +RC_FILE_ERROR = -1073740796 +RC_FILE_LOCK_ERROR = -1073733616 +RC_FILE_LOCK_FAILED = -1073733623 +RC_FILE_NAME_INVALID = -1073740798 +RC_FILE_READ_ONLY = -1073740797 +RC_FUNCTION_NOT_SUPPORTED = -1073741563 +RC_GENERAL_ERROR = -1073741822 +RC_GROUP_NAME_INVALID = -1073740784 +RC_HOST_RESOLUTION_ERROR = -1073740535 +RC_INVALID_CERT_HOST = -1073740534 +RC_INVALID_COMMAND = -1073733626 +RC_INVALID_ENUM_OPTION = -1073740287 +RC_INVALID_INDEX = -1073740789 +RC_KEY_NEEDED = -1073741558 +RC_LISTEN_SOCKET_INVALID = -1073740793 +RC_MANUFACTURING_NO_CONFIG_AVAILABLE = -1073741056 +RC_MANUFACTURING_SERIAL_NUMBER_INVALID = -1073741054 +RC_MANUFACTURING_TOKEN_NOT_PRESENT = -1073741055 +RC_MEMORY_ALLOCATION = -1073741823 +RC_NO_BUFFER = -1073740288 +RC_NO_PRIMARY_PEER = -1073740532 +RC_NON_CRYPTOKI_ELEMENT_CLONE = -1073741562 +RC_NOT_HSM_BACKUP_TOKEN = -1073740783 +RC_NOT_PARTITION_BACKUP_TOKEN = -1073740782 +RC_OBJECT_ALREADY_EXISTS = -1073740788 +RC_OBJECT_ID_INVALID = -1073740795 +RC_OBJECT_NOT_IN_LIST = -1073740790 +RC_OK = 0 +RC_OPERATION_TIMED_OUT = -1073741053 +RC_OPERATION_WOULD_BLOCK = -1073741819 +RC_PARTITION_LOCKED = -1073737728 +RC_PARTITION_NOT_ACTIVATED = -1073737727 +RC_PARTITION_ROLE_DESC_VERSION_INVALID = -1073737726 +RC_PARTITION_ROLE_POLICY_SET_VERSION_INVALID = -1073737724 +RC_PARTITION_ROLE_POLICY_VERSION_INVALID = -1073737725 RC_PIN_INVALID = -1073741565 -LUNA_RET_FUNCTION_NOT_SUPPORTED = 5505024 +RC_PIN_LOCKED = -1073741560 +RC_POINTER_INVALID = -1073741821 +RC_PORT_INVALID = -1073739520 +RC_RC_ERROR = -1073741824 +RC_REMOTE_PEER_OFFLINE = -1073740533 +RC_REMOTE_SIDE_DISCONNECTED = -1073733628 +RC_RESET_FAILED = -1073741052 +RC_SEMAPHORE_ERROR = -1073740787 +RC_SERVER_DISCONNECTED = -1073740540 +RC_SESSION_SCRIPT_EXISTS = -1073739519 +RC_SHUTTING_DOWN = -1073733629 +RC_SIM_NOT_SUPPORTED = -1073740781 +RC_SLOT_ID_INVALID = -1073741567 +RC_SOCKET_ADDRESS_IN_USE = -1073740537 +RC_SOCKET_ADDRESS_INVALID = -1073740794 +RC_SOCKET_BAD_FD = -1073740536 +RC_SOCKET_CLOSED = -1073733627 +RC_SOCKET_ERROR = -1073740544 +RC_SOCKET_READ_ERROR = -1073740542 +RC_SOCKET_WOULDBLOCK = -1073740538 +RC_SOCKET_WRITE_ERROR = -1073740543 +RC_SSL_CERT_VERIFICATION_LOCATION_ERROR = -1073740029 +RC_SSL_CIPHER_LIST_ERROR = -1073740030 +RC_SSL_CREATE_SSL_ERROR = -1073740025 +RC_SSL_CTX_ERROR = -1073740031 +RC_SSL_ERROR = -1073740032 +RC_SSL_FAILED_HANDSHAKE = -1073740015 +RC_SSL_GET_CERTIFICATE_ERROR = -1073740023 +RC_SSL_GET_PEER_CERT_ERROR = -1073740020 +RC_SSL_INVALID_CERT_STRUCTURE = -1073740022 +RC_SSL_LOAD_CLIENT_CERT_ERROR = -1073740024 +RC_SSL_LOAD_CLIENT_PRIVATE_KEY_ERROR = -1073740021 +RC_SSL_LOAD_SERVER_CERT_ERROR = -1073740028 +RC_SSL_LOAD_SERVER_PRIVATE_KEY_ERROR = -1073740027 +RC_SSL_SYSCALL_ERROR = -1073740016 +RC_SSL_VALIDATE_SERVER_PRIVATE_KEY_ERROR = -1073740026 +RC_SSL_WANT_READ_ERROR = -1073740019 +RC_SSL_WANT_WRITE_ERROR = -1073740018 +RC_SSL_WANT_X509_LOOKUP_ERROR = -1073740017 +RC_STC_CIPHER_SUITE_REJECTED = -1073700859 +RC_STC_CLIENT_HANDLE_INVALID = -1073700850 +RC_STC_CLIENT_IDENTITY_NOT_CONFIGURED = -1073700862 +RC_STC_COMPUTE_DH_KEY_ERROR = -1073700857 +RC_STC_CONTAINER_INVALID = -1073700848 +RC_STC_DH_KEY_NOT_FROM_SAME_GROUP = -1073700858 +RC_STC_DH_KEYGEN_ERROR = -1073700860 +RC_STC_FIRST_PHASE_KDF_ERROR = -1073700856 +RC_STC_KEY_CONFIRMATION_FAILED = -1073700854 +RC_STC_NO_CHANNEL = -1073700846 +RC_STC_NO_CONTEXT = -1073700863 +RC_STC_NO_SESSION_KEY = -1073700853 +RC_STC_NOT_ENABLED = -1073700851 +RC_STC_PARTITION_IDENTITY_NOT_CONFIGURED = -1073700861 +RC_STC_REKEY_CHANNEL_MISMATCH = -1073700843 +RC_STC_RESPONSE_BAD_MAC = -1073700852 +RC_STC_RESPONSE_DECRYPT_ERROR = -1073700845 +RC_STC_RESPONSE_REPLAYED = -1073700844 +RC_STC_RESPONSE_UNEXPECTED_KEY = -1073700839 +RC_STC_RSA_DECRYPT_ERROR = -1073700840 +RC_STC_RSA_ENCRYPT_ERROR = -1073700842 +RC_STC_RSA_SIGN_ERROR = -1073700841 +RC_STC_SECOND_PHASE_KDF_ERROR = -1073700855 +RC_STC_SEQUENCE_NUM_INVALID = -1073700847 +RC_STC_SESSION_INVALID = -1073700849 +RC_STC_UNEXPECTED_DH_DATA_SIZE = -1073700837 +RC_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE = -1073700838 +RC_TOKEN_NOT_PRESENT = -1073741564 +RC_TOKEN_STATE_INVALID = -1073740800 +RC_UNABLE_TO_CONNECT = -1073737472 +RC_UNEXPECTED = -1073741820 +RC_UNKNOWN_CALLBACK_COMMAND = -1073733630 +RC_UNKNOWN_COMMAND = -1073733625 +RC_UNKNOWN_COMMAND_VERSION = -1073733624 +RC_USB_PED_NOT_FOUND = -1073733614 +RC_USB_PED_NOT_RESPONDING = -1073733613 +RC_USB_PED_OPERATION_CANCELLED = -1073733612 +RC_USB_PED_OUT_OF_SYNC = -1073733610 +RC_USB_PED_TOO_MANY_CONNECTED = -1073733611 +RC_USER_NAME_IN_USE = -1073741557 +RC_VERSION_INVALID = -1073741559 # values for enumeration 'ResultCodeValue' ResultCodeValue = c_int # enum @@ -1063,12 +1075,6 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_CA_IsMofNEnabled = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) CK_CA_IsMofNRequired = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR) - -class CK_ATTRIBUTE(Structure): - pass - - -CK_ATTRIBUTE_PTR = POINTER(CK_ATTRIBUTE) CK_CA_GenerateTokenKeys = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ATTRIBUTE_PTR, CK_ULONG) CK_CA_GetTokenCertificateInfo = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) CK_CA_SetTokenCertificateSignature = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, @@ -1164,12 +1170,6 @@ class CK_ATTRIBUTE(Structure): CK_CA_ListSecureTokenUpdate = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_ULONG, CK_BYTE_PTR, CK_ULONG) - -class CK_MECHANISM(Structure): - pass - - -CK_MECHANISM_PTR = POINTER(CK_MECHANISM) CK_CA_GetSecureElementMeta = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_ULONG, CK_MECHANISM_PTR, CK_ULONG_PTR, CK_ULONG_PTR, CK_BYTE_PTR, CK_ULONG) CK_CA_HAInit = CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index 49de0db..dd10113 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -3,7 +3,7 @@ import re import sys -from pycryptoki.defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE +from .defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE def parse_chrystoki_conf(): diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py index 77a8be7..615b225 100755 --- a/pycryptoki/default_templates.py +++ b/pycryptoki/default_templates.py @@ -6,90 +6,167 @@ import copy from defines import (CKA_BASE, CKA_CERTIFICATE_TYPE, CKA_CLASS, CKA_DECRYPT, CKA_DERIVE, -CKA_ECDSA_PARAMS, CKA_ENCRYPT, -CKA_EXTRACTABLE, CKA_KEY_TYPE, CKA_LABEL, CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PRIME, -CKA_PRIME_BITS, CKA_PRIVATE, CKA_PUBLIC_EXPONENT, CKA_SENSITIVE, CKA_SIGN, CKA_SUBJECT, -CKA_SUBPRIME, CKA_SUBPRIME_BITS, CKA_TOKEN, CKA_UNWRAP, CKA_VALUE, CKA_VALUE_BITS, CKA_VALUE_LEN, -CKA_VERIFY, CKA_WRAP, CKC_X_509, CKK_AES, CKK_ARIA, CKK_CAST3, CKK_CAST5, CKK_DES, CKK_DES2, -CKK_DES3, CKK_GENERIC_SECRET, CKK_RC2, CKK_RC4, CKK_RC5, CKK_SEED, CKM_2DES_KEY_DERIVATION, -CKM_ACTI, CKM_ACTI_KEY_GEN, CKM_AES_CBC, CKM_AES_CBC_ENCRYPT_DATA, CKM_AES_CBC_PAD, -CKM_AES_CBC_PAD_EXTRACT, CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, CKM_AES_CBC_PAD_EXTRACT_FLATTENED, -CKM_AES_CBC_PAD_INSERT, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, CKM_AES_CBC_PAD_INSERT_FLATTENED, -CKM_AES_CBC_PAD_IPSEC, CKM_AES_CFB128, CKM_AES_CFB8, CKM_AES_CMAC, CKM_AES_CMAC_GENERAL, -CKM_AES_CTR, CKM_AES_ECB, CKM_AES_ECB_ENCRYPT_DATA, CKM_AES_GCM, CKM_AES_GMAC, CKM_AES_KEY_GEN, -CKM_AES_KEY_WRAP, CKM_AES_KEY_WRAP_PAD, CKM_AES_KW, CKM_AES_KWP, CKM_AES_MAC, CKM_AES_MAC_GENERAL, -CKM_AES_OFB, CKM_ARIA_CBC, CKM_ARIA_CBC_ENCRYPT_DATA, CKM_ARIA_CBC_PAD, CKM_ARIA_CFB128, -CKM_ARIA_CFB8, CKM_ARIA_CMAC, CKM_ARIA_CMAC_GENERAL, CKM_ARIA_CTR, CKM_ARIA_ECB, -CKM_ARIA_ECB_ENCRYPT_DATA, CKM_ARIA_GCM, CKM_ARIA_KEY_GEN, CKM_ARIA_L_CBC, CKM_ARIA_L_CBC_PAD, -CKM_ARIA_L_ECB, CKM_ARIA_L_MAC, CKM_ARIA_L_MAC_GENERAL, CKM_ARIA_MAC, CKM_ARIA_MAC_GENERAL, -CKM_ARIA_OFB, CKM_BATON_CBC128, CKM_BATON_COUNTER, CKM_BATON_ECB128, CKM_BATON_ECB96, -CKM_BATON_KEY_GEN, CKM_BATON_SHUFFLE, CKM_BATON_WRAP, CKM_BLOWFISH_CBC, CKM_BLOWFISH_KEY_GEN, -CKM_CAMELLIA_CBC, CKM_CAMELLIA_CBC_ENCRYPT_DATA, CKM_CAMELLIA_CBC_PAD, CKM_CAMELLIA_CTR, -CKM_CAMELLIA_ECB, CKM_CAMELLIA_ECB_ENCRYPT_DATA, CKM_CAMELLIA_KEY_GEN, CKM_CAMELLIA_MAC, -CKM_CAMELLIA_MAC_GENERAL, CKM_CAST3_CBC, CKM_CAST3_CBC_PAD, CKM_CAST3_ECB, CKM_CAST3_KEY_GEN, -CKM_CAST3_MAC, CKM_CAST3_MAC_GENERAL, CKM_CAST5_CBC, CKM_CAST5_CBC_PAD, CKM_CAST5_ECB, -CKM_CAST5_KEY_GEN, CKM_CAST5_MAC, CKM_CAST5_MAC_GENERAL, CKM_CAST_CBC, CKM_CAST_CBC_PAD, -CKM_CAST_ECB, CKM_CAST_KEY_GEN, CKM_CAST_MAC, CKM_CAST_MAC_GENERAL, CKM_CDMF_CBC, CKM_CDMF_CBC_PAD, -CKM_CDMF_ECB, CKM_CDMF_KEY_GEN, CKM_CDMF_MAC, CKM_CDMF_MAC_GENERAL, CKM_CMS_SIG, -CKM_CONCATENATE_BASE_AND_DATA, CKM_CONCATENATE_BASE_AND_KEY, CKM_CONCATENATE_DATA_AND_BASE, -CKM_DES2_DUKPT_DATA, CKM_DES2_DUKPT_DATA_RESP, CKM_DES2_DUKPT_MAC, CKM_DES2_DUKPT_MAC_RESP, -CKM_DES2_DUKPT_PIN, CKM_DES2_KEY_GEN, CKM_DES3_CBC, CKM_DES3_CBC_ENCRYPT_DATA, CKM_DES3_CBC_PAD, -CKM_DES3_CBC_PAD_IPSEC, CKM_DES3_CMAC, CKM_DES3_CMAC_GENERAL, CKM_DES3_CTR, CKM_DES3_ECB, -CKM_DES3_ECB_ENCRYPT_DATA, CKM_DES3_KEY_GEN, CKM_DES3_MAC, CKM_DES3_MAC_GENERAL, CKM_DES3_X919_MAC, -CKM_DES_CBC, CKM_DES_CBC_ENCRYPT_DATA, CKM_DES_CBC_PAD, CKM_DES_CFB64, CKM_DES_CFB8, CKM_DES_ECB, -CKM_DES_ECB_ENCRYPT_DATA, CKM_DES_KEY_GEN, CKM_DES_MAC, CKM_DES_MAC_GENERAL, CKM_DES_OFB64, -CKM_DES_OFB8, CKM_DH_PKCS_DERIVE, CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKM_DSA, -CKM_DSA_KEY_PAIR_GEN, CKM_DSA_PARAMETER_GEN, CKM_DSA_SHA1, CKM_DSA_SHA224, CKM_DSA_SHA256, -CKM_ECDH1_COFACTOR_DERIVE, CKM_ECDH1_DERIVE, CKM_ECDSA, CKM_ECDSA_GBCS_SHA256, -CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, -CKM_ECDSA_SHA256, CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECIES, CKM_ECMQV_DERIVE, -CKM_EXTRACT_KEY_FROM_KEY, CKM_FASTHASH, CKM_FORTEZZA_TIMESTAMP, CKM_GENERIC_SECRET_KEY_GEN, -CKM_HAS160, CKM_HOTP, CKM_HOTP_KEY_GEN, CKM_IDEA_CBC, CKM_IDEA_CBC_PAD, CKM_IDEA_ECB, -CKM_IDEA_KEY_GEN, CKM_IDEA_MAC, CKM_IDEA_MAC_GENERAL, CKM_INDIRECT_LOGIN_REENCRYPT, -CKM_JUNIPER_CBC128, CKM_JUNIPER_COUNTER, CKM_JUNIPER_ECB128, CKM_JUNIPER_KEY_GEN, -CKM_JUNIPER_SHUFFLE, CKM_JUNIPER_WRAP, CKM_KCDSA_HAS160, CKM_KCDSA_HAS160_NO_PAD, -CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_SHA1, CKM_KCDSA_SHA1_NO_PAD, -CKM_KCDSA_SHA224, CKM_KCDSA_SHA224_NO_PAD, CKM_KCDSA_SHA256, CKM_KCDSA_SHA256_NO_PAD, -CKM_KCDSA_SHA384, CKM_KCDSA_SHA384_NO_PAD, CKM_KCDSA_SHA512, CKM_KCDSA_SHA512_NO_PAD, -CKM_KEA_KEY_DERIVE, CKM_KEA_KEY_PAIR_GEN, CKM_KEY_TRANSLATION, CKM_KEY_WRAP_LYNKS, -CKM_KEY_WRAP_SET_OAEP, CKM_KIP_DERIVE, CKM_KIP_MAC, CKM_KIP_WRAP, CKM_MD2, CKM_MD2_HMAC, -CKM_MD2_HMAC_GENERAL, CKM_MD2_KEY_DERIVATION, CKM_MD2_RSA_PKCS, CKM_MD5, CKM_MD5_HMAC, -CKM_MD5_HMAC_GENERAL, CKM_MD5_KEY_DERIVATION, CKM_MD5_RSA_PKCS, CKM_NIST_PRF_KDF, -CKM_PBA_SHA1_WITH_SHA1_HMAC, CKM_PBE_MD2_DES_CBC, CKM_PBE_MD5_CAST3_CBC, CKM_PBE_MD5_CAST5_CBC, -CKM_PBE_MD5_CAST_CBC, CKM_PBE_MD5_DES_CBC, CKM_PBE_SHA1_CAST5_CBC, CKM_PBE_SHA1_DES2_EDE_CBC, -CKM_PBE_SHA1_DES3_EDE_CBC, CKM_PBE_SHA1_RC2_128_CBC, CKM_PBE_SHA1_RC2_40_CBC, CKM_PBE_SHA1_RC4_128, -CKM_PBE_SHA1_RC4_40, CKM_PKCS5_PBKD2, CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM, CKM_PRF_KDF, -CKM_RC2_CBC, CKM_RC2_CBC_PAD, CKM_RC2_ECB, CKM_RC2_KEY_GEN, CKM_RC2_MAC, CKM_RC2_MAC_GENERAL, -CKM_RC4, CKM_RC4_KEY_GEN, CKM_RC5_CBC, CKM_RC5_CBC_PAD, CKM_RC5_ECB, CKM_RC5_KEY_GEN, CKM_RC5_MAC, -CKM_RC5_MAC_GENERAL, CKM_RIPEMD128, CKM_RIPEMD128_HMAC, CKM_RIPEMD128_HMAC_GENERAL, -CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160, CKM_RIPEMD160_HMAC, CKM_RIPEMD160_HMAC_GENERAL, -CKM_RIPEMD160_RSA_PKCS, CKM_RSA_9796, CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, -CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_OAEP, -CKM_RSA_PKCS_PSS, CKM_RSA_X9_31, CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31_NON_FIPS, CKM_RSA_X_509, -CKM_SECURID, CKM_SECURID_KEY_GEN, CKM_SEED_CBC, CKM_SEED_CBC_PAD, CKM_SEED_CMAC, -CKM_SEED_CMAC_GENERAL, CKM_SEED_CTR, CKM_SEED_ECB, CKM_SEED_KEY_GEN, CKM_SEED_MAC, -CKM_SEED_MAC_GENERAL, CKM_SHA1_KEY_DERIVATION, CKM_SHA1_RSA_PKCS, CKM_SHA1_RSA_PKCS_PSS, -CKM_SHA1_RSA_X9_31, CKM_SHA1_RSA_X9_31_NON_FIPS, CKM_SHA224, CKM_SHA224_HMAC, -CKM_SHA224_HMAC_GENERAL, CKM_SHA224_KEY_DERIVATION, CKM_SHA224_RSA_PKCS, CKM_SHA224_RSA_PKCS_PSS, -CKM_SHA224_RSA_X9_31, CKM_SHA224_RSA_X9_31_NON_FIPS, CKM_SHA256, CKM_SHA256_HMAC, -CKM_SHA256_HMAC_GENERAL, CKM_SHA256_KEY_DERIVATION, CKM_SHA256_RSA_PKCS, CKM_SHA256_RSA_PKCS_PSS, -CKM_SHA256_RSA_X9_31, CKM_SHA256_RSA_X9_31_NON_FIPS, CKM_SHA384, CKM_SHA384_HMAC, -CKM_SHA384_HMAC_GENERAL, CKM_SHA384_KEY_DERIVATION, CKM_SHA384_RSA_PKCS, CKM_SHA384_RSA_PKCS_PSS, -CKM_SHA384_RSA_X9_31, CKM_SHA384_RSA_X9_31_NON_FIPS, CKM_SHA512, CKM_SHA512_HMAC, -CKM_SHA512_HMAC_GENERAL, CKM_SHA512_KEY_DERIVATION, CKM_SHA512_RSA_PKCS, CKM_SHA512_RSA_PKCS_PSS, -CKM_SHA512_RSA_X9_31, CKM_SHA512_RSA_X9_31_NON_FIPS, CKM_SHA_1, CKM_SHA_1_HMAC, -CKM_SHA_1_HMAC_GENERAL, CKM_SKIPJACK_CBC64, CKM_SKIPJACK_CFB16, CKM_SKIPJACK_CFB32, -CKM_SKIPJACK_CFB64, CKM_SKIPJACK_CFB8, CKM_SKIPJACK_ECB64, CKM_SKIPJACK_KEY_GEN, CKM_SKIPJACK_OFB64, -CKM_SKIPJACK_PRIVATE_WRAP, CKM_SKIPJACK_RELAYX, CKM_SKIPJACK_WRAP, CKM_SSL3_KEY_AND_MAC_DERIVE, -CKM_SSL3_MASTER_KEY_DERIVE, CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_SSL3_MD5_MAC, -CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_SHA1_MAC, CKM_TDEA_KW, CKM_TDEA_KWP, -CKM_TLS_KEY_AND_MAC_DERIVE, CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_MASTER_KEY_DERIVE_DH, -CKM_TLS_PRE_MASTER_KEY_GEN, CKM_TLS_PRF, CKM_TWOFISH_CBC, CKM_TWOFISH_KEY_GEN, CKM_VENDOR_DEFINED, -CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE, CKM_WTLS_MASTER_KEY_DERIVE, CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC, -CKM_WTLS_PRE_MASTER_KEY_GEN, CKM_WTLS_PRF, CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE, CKM_X9_42_DH_DERIVE, -CKM_X9_42_DH_HYBRID_DERIVE, CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_PARAMETER_GEN, -CKM_X9_42_MQV_DERIVE, CKM_XOR_BASE_AND_DATA, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_XOR_BASE_AND_KEY, -CKO_CERTIFICATE, CKO_DATA, CKO_SECRET_KEY) + CKA_ECDSA_PARAMS, CKA_ENCRYPT, + CKA_EXTRACTABLE, CKA_KEY_TYPE, CKA_LABEL, CKA_MODIFIABLE, CKA_MODULUS_BITS, + CKA_PRIME, + CKA_PRIME_BITS, CKA_PRIVATE, CKA_PUBLIC_EXPONENT, CKA_SENSITIVE, CKA_SIGN, + CKA_SUBJECT, + CKA_SUBPRIME, CKA_SUBPRIME_BITS, CKA_TOKEN, CKA_UNWRAP, CKA_VALUE, + CKA_VALUE_BITS, CKA_VALUE_LEN, + CKA_VERIFY, CKA_WRAP, CKC_X_509, CKK_AES, CKK_ARIA, CKK_CAST3, CKK_CAST5, + CKK_DES, CKK_DES2, + CKK_DES3, CKK_GENERIC_SECRET, CKK_RC2, CKK_RC4, CKK_RC5, CKK_SEED, + CKM_2DES_KEY_DERIVATION, + CKM_ACTI, CKM_ACTI_KEY_GEN, CKM_AES_CBC, CKM_AES_CBC_ENCRYPT_DATA, + CKM_AES_CBC_PAD, + CKM_AES_CBC_PAD_EXTRACT, CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, + CKM_AES_CBC_PAD_EXTRACT_FLATTENED, + CKM_AES_CBC_PAD_INSERT, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, + CKM_AES_CBC_PAD_INSERT_FLATTENED, + CKM_AES_CBC_PAD_IPSEC, CKM_AES_CFB128, CKM_AES_CFB8, CKM_AES_CMAC, + CKM_AES_CMAC_GENERAL, + CKM_AES_CTR, CKM_AES_ECB, CKM_AES_ECB_ENCRYPT_DATA, CKM_AES_GCM, CKM_AES_GMAC, + CKM_AES_KEY_GEN, + CKM_AES_KEY_WRAP, CKM_AES_KEY_WRAP_PAD, CKM_AES_KW, CKM_AES_KWP, CKM_AES_MAC, + CKM_AES_MAC_GENERAL, + CKM_AES_OFB, CKM_ARIA_CBC, CKM_ARIA_CBC_ENCRYPT_DATA, CKM_ARIA_CBC_PAD, + CKM_ARIA_CFB128, + CKM_ARIA_CFB8, CKM_ARIA_CMAC, CKM_ARIA_CMAC_GENERAL, CKM_ARIA_CTR, + CKM_ARIA_ECB, + CKM_ARIA_ECB_ENCRYPT_DATA, CKM_ARIA_GCM, CKM_ARIA_KEY_GEN, CKM_ARIA_L_CBC, + CKM_ARIA_L_CBC_PAD, + CKM_ARIA_L_ECB, CKM_ARIA_L_MAC, CKM_ARIA_L_MAC_GENERAL, CKM_ARIA_MAC, + CKM_ARIA_MAC_GENERAL, + CKM_ARIA_OFB, CKM_BATON_CBC128, CKM_BATON_COUNTER, CKM_BATON_ECB128, + CKM_BATON_ECB96, + CKM_BATON_KEY_GEN, CKM_BATON_SHUFFLE, CKM_BATON_WRAP, CKM_BLOWFISH_CBC, + CKM_BLOWFISH_KEY_GEN, + CKM_CAMELLIA_CBC, CKM_CAMELLIA_CBC_ENCRYPT_DATA, CKM_CAMELLIA_CBC_PAD, + CKM_CAMELLIA_CTR, + CKM_CAMELLIA_ECB, CKM_CAMELLIA_ECB_ENCRYPT_DATA, CKM_CAMELLIA_KEY_GEN, + CKM_CAMELLIA_MAC, + CKM_CAMELLIA_MAC_GENERAL, CKM_CAST3_CBC, CKM_CAST3_CBC_PAD, CKM_CAST3_ECB, + CKM_CAST3_KEY_GEN, + CKM_CAST3_MAC, CKM_CAST3_MAC_GENERAL, CKM_CAST5_CBC, CKM_CAST5_CBC_PAD, + CKM_CAST5_ECB, + CKM_CAST5_KEY_GEN, CKM_CAST5_MAC, CKM_CAST5_MAC_GENERAL, CKM_CAST_CBC, + CKM_CAST_CBC_PAD, + CKM_CAST_ECB, CKM_CAST_KEY_GEN, CKM_CAST_MAC, CKM_CAST_MAC_GENERAL, + CKM_CDMF_CBC, CKM_CDMF_CBC_PAD, + CKM_CDMF_ECB, CKM_CDMF_KEY_GEN, CKM_CDMF_MAC, CKM_CDMF_MAC_GENERAL, + CKM_CMS_SIG, + CKM_CONCATENATE_BASE_AND_DATA, CKM_CONCATENATE_BASE_AND_KEY, + CKM_CONCATENATE_DATA_AND_BASE, + CKM_DES2_DUKPT_DATA, CKM_DES2_DUKPT_DATA_RESP, CKM_DES2_DUKPT_MAC, + CKM_DES2_DUKPT_MAC_RESP, + CKM_DES2_DUKPT_PIN, CKM_DES2_KEY_GEN, CKM_DES3_CBC, CKM_DES3_CBC_ENCRYPT_DATA, + CKM_DES3_CBC_PAD, + CKM_DES3_CBC_PAD_IPSEC, CKM_DES3_CMAC, CKM_DES3_CMAC_GENERAL, CKM_DES3_CTR, + CKM_DES3_ECB, + CKM_DES3_ECB_ENCRYPT_DATA, CKM_DES3_KEY_GEN, CKM_DES3_MAC, + CKM_DES3_MAC_GENERAL, CKM_DES3_X919_MAC, + CKM_DES_CBC, CKM_DES_CBC_ENCRYPT_DATA, CKM_DES_CBC_PAD, CKM_DES_CFB64, + CKM_DES_CFB8, CKM_DES_ECB, + CKM_DES_ECB_ENCRYPT_DATA, CKM_DES_KEY_GEN, CKM_DES_MAC, CKM_DES_MAC_GENERAL, + CKM_DES_OFB64, + CKM_DES_OFB8, CKM_DH_PKCS_DERIVE, CKM_DH_PKCS_KEY_PAIR_GEN, + CKM_DH_PKCS_PARAMETER_GEN, CKM_DSA, + CKM_DSA_KEY_PAIR_GEN, CKM_DSA_PARAMETER_GEN, CKM_DSA_SHA1, CKM_DSA_SHA224, + CKM_DSA_SHA256, + CKM_ECDH1_COFACTOR_DERIVE, CKM_ECDH1_DERIVE, CKM_ECDSA, CKM_ECDSA_GBCS_SHA256, + CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS, CKM_ECDSA_SHA1, + CKM_ECDSA_SHA224, + CKM_ECDSA_SHA256, CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_ECIES, + CKM_ECMQV_DERIVE, + CKM_EXTRACT_KEY_FROM_KEY, CKM_FASTHASH, CKM_FORTEZZA_TIMESTAMP, + CKM_GENERIC_SECRET_KEY_GEN, + CKM_HAS160, CKM_HOTP, CKM_HOTP_KEY_GEN, CKM_IDEA_CBC, CKM_IDEA_CBC_PAD, + CKM_IDEA_ECB, + CKM_IDEA_KEY_GEN, CKM_IDEA_MAC, CKM_IDEA_MAC_GENERAL, + CKM_INDIRECT_LOGIN_REENCRYPT, + CKM_JUNIPER_CBC128, CKM_JUNIPER_COUNTER, CKM_JUNIPER_ECB128, + CKM_JUNIPER_KEY_GEN, + CKM_JUNIPER_SHUFFLE, CKM_JUNIPER_WRAP, CKM_KCDSA_HAS160, + CKM_KCDSA_HAS160_NO_PAD, + CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_SHA1, + CKM_KCDSA_SHA1_NO_PAD, + CKM_KCDSA_SHA224, CKM_KCDSA_SHA224_NO_PAD, CKM_KCDSA_SHA256, + CKM_KCDSA_SHA256_NO_PAD, + CKM_KCDSA_SHA384, CKM_KCDSA_SHA384_NO_PAD, CKM_KCDSA_SHA512, + CKM_KCDSA_SHA512_NO_PAD, + CKM_KEA_KEY_DERIVE, CKM_KEA_KEY_PAIR_GEN, CKM_KEY_TRANSLATION, + CKM_KEY_WRAP_LYNKS, + CKM_KEY_WRAP_SET_OAEP, CKM_KIP_DERIVE, CKM_KIP_MAC, CKM_KIP_WRAP, CKM_MD2, + CKM_MD2_HMAC, + CKM_MD2_HMAC_GENERAL, CKM_MD2_KEY_DERIVATION, CKM_MD2_RSA_PKCS, CKM_MD5, + CKM_MD5_HMAC, + CKM_MD5_HMAC_GENERAL, CKM_MD5_KEY_DERIVATION, CKM_MD5_RSA_PKCS, + CKM_NIST_PRF_KDF, + CKM_PBA_SHA1_WITH_SHA1_HMAC, CKM_PBE_MD2_DES_CBC, CKM_PBE_MD5_CAST3_CBC, + CKM_PBE_MD5_CAST5_CBC, + CKM_PBE_MD5_CAST_CBC, CKM_PBE_MD5_DES_CBC, CKM_PBE_SHA1_CAST5_CBC, + CKM_PBE_SHA1_DES2_EDE_CBC, + CKM_PBE_SHA1_DES3_EDE_CBC, CKM_PBE_SHA1_RC2_128_CBC, CKM_PBE_SHA1_RC2_40_CBC, + CKM_PBE_SHA1_RC4_128, + CKM_PBE_SHA1_RC4_40, CKM_PKCS5_PBKD2, CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM, + CKM_PRF_KDF, + CKM_RC2_CBC, CKM_RC2_CBC_PAD, CKM_RC2_ECB, CKM_RC2_KEY_GEN, CKM_RC2_MAC, + CKM_RC2_MAC_GENERAL, + CKM_RC4, CKM_RC4_KEY_GEN, CKM_RC5_CBC, CKM_RC5_CBC_PAD, CKM_RC5_ECB, + CKM_RC5_KEY_GEN, CKM_RC5_MAC, + CKM_RC5_MAC_GENERAL, CKM_RIPEMD128, CKM_RIPEMD128_HMAC, + CKM_RIPEMD128_HMAC_GENERAL, + CKM_RIPEMD128_RSA_PKCS, CKM_RIPEMD160, CKM_RIPEMD160_HMAC, + CKM_RIPEMD160_HMAC_GENERAL, + CKM_RIPEMD160_RSA_PKCS, CKM_RSA_9796, + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN, + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_OAEP, + CKM_RSA_PKCS_PSS, CKM_RSA_X9_31, CKM_RSA_X9_31_KEY_PAIR_GEN, + CKM_RSA_X9_31_NON_FIPS, CKM_RSA_X_509, + CKM_SECURID, CKM_SECURID_KEY_GEN, CKM_SEED_CBC, CKM_SEED_CBC_PAD, + CKM_SEED_CMAC, + CKM_SEED_CMAC_GENERAL, CKM_SEED_CTR, CKM_SEED_ECB, CKM_SEED_KEY_GEN, + CKM_SEED_MAC, + CKM_SEED_MAC_GENERAL, CKM_SHA1_KEY_DERIVATION, CKM_SHA1_RSA_PKCS, + CKM_SHA1_RSA_PKCS_PSS, + CKM_SHA1_RSA_X9_31, CKM_SHA1_RSA_X9_31_NON_FIPS, CKM_SHA224, CKM_SHA224_HMAC, + CKM_SHA224_HMAC_GENERAL, CKM_SHA224_KEY_DERIVATION, CKM_SHA224_RSA_PKCS, + CKM_SHA224_RSA_PKCS_PSS, + CKM_SHA224_RSA_X9_31, CKM_SHA224_RSA_X9_31_NON_FIPS, CKM_SHA256, + CKM_SHA256_HMAC, + CKM_SHA256_HMAC_GENERAL, CKM_SHA256_KEY_DERIVATION, CKM_SHA256_RSA_PKCS, + CKM_SHA256_RSA_PKCS_PSS, + CKM_SHA256_RSA_X9_31, CKM_SHA256_RSA_X9_31_NON_FIPS, CKM_SHA384, + CKM_SHA384_HMAC, + CKM_SHA384_HMAC_GENERAL, CKM_SHA384_KEY_DERIVATION, CKM_SHA384_RSA_PKCS, + CKM_SHA384_RSA_PKCS_PSS, + CKM_SHA384_RSA_X9_31, CKM_SHA384_RSA_X9_31_NON_FIPS, CKM_SHA512, + CKM_SHA512_HMAC, + CKM_SHA512_HMAC_GENERAL, CKM_SHA512_KEY_DERIVATION, CKM_SHA512_RSA_PKCS, + CKM_SHA512_RSA_PKCS_PSS, + CKM_SHA512_RSA_X9_31, CKM_SHA512_RSA_X9_31_NON_FIPS, CKM_SHA_1, CKM_SHA_1_HMAC, + CKM_SHA_1_HMAC_GENERAL, CKM_SKIPJACK_CBC64, CKM_SKIPJACK_CFB16, + CKM_SKIPJACK_CFB32, + CKM_SKIPJACK_CFB64, CKM_SKIPJACK_CFB8, CKM_SKIPJACK_ECB64, + CKM_SKIPJACK_KEY_GEN, CKM_SKIPJACK_OFB64, + CKM_SKIPJACK_PRIVATE_WRAP, CKM_SKIPJACK_RELAYX, CKM_SKIPJACK_WRAP, + CKM_SSL3_KEY_AND_MAC_DERIVE, + CKM_SSL3_MASTER_KEY_DERIVE, CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_SSL3_MD5_MAC, + CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_SHA1_MAC, CKM_TDEA_KW, CKM_TDEA_KWP, + CKM_TLS_KEY_AND_MAC_DERIVE, CKM_TLS_MASTER_KEY_DERIVE, + CKM_TLS_MASTER_KEY_DERIVE_DH, + CKM_TLS_PRE_MASTER_KEY_GEN, CKM_TLS_PRF, CKM_TWOFISH_CBC, CKM_TWOFISH_KEY_GEN, + CKM_VENDOR_DEFINED, + CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE, CKM_WTLS_MASTER_KEY_DERIVE, + CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC, + CKM_WTLS_PRE_MASTER_KEY_GEN, CKM_WTLS_PRF, CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE, + CKM_X9_42_DH_DERIVE, + CKM_X9_42_DH_HYBRID_DERIVE, CKM_X9_42_DH_KEY_PAIR_GEN, + CKM_X9_42_DH_PARAMETER_GEN, + CKM_X9_42_MQV_DERIVE, CKM_XOR_BASE_AND_DATA, CKM_XOR_BASE_AND_DATA_W_KDF, + CKM_XOR_BASE_AND_KEY, + CKO_CERTIFICATE, CKO_DATA, CKO_SECRET_KEY) CKM_DES_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_DES, @@ -200,151 +277,285 @@ CKA_UNWRAP: True, CKA_LABEL: "RSA Private Key"} -dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, - 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, 0x6d, 0x1f, 0xf2, - 0x70, 0xf1, 0x59, 0x78, 0x5d, 0x75, 0x69, 0x21, 0xdb, 0xff, 0x97, 0x73, 0xae, 0x08, 0x48, 0x3b, - 0x66, 0x2f, 0xc0, 0x7d, 0xf7, 0x51, 0x2f, 0xf6, 0x8b, 0x2e, 0x55, 0x65, 0xfd, 0x79, 0x82, 0xe2, - 0x0c, 0x24, 0x48, 0x32, 0xab, 0xa1, 0x21, 0xcc, 0x07, 0x99, 0xcc, 0x09, 0xf2, 0xd5, 0x41, 0x4d, - 0x5f, 0x39, 0x66, 0x21, 0x13, 0x65, 0xf5, 0x1b, 0x83, 0xe9, 0xff, 0xcc, 0xcb, 0x3d, 0x88, 0xcd, - 0xf2, 0x38, 0xf7, 0xc2, 0x73, 0x91, 0x31, 0xca, 0x7a, 0xad, 0xff, 0x66, 0x2f, 0xec, 0x1f, 0xb0, - 0xe1, 0xd3, 0x11, 0xa4, 0x04, 0x26, 0x03, 0x76, 0xfd, 0x01, 0x1f, 0xe0, 0x0d, 0x02, 0x04, 0xc3] -dsa_sub_prime_1024_160 = [0xd3, 0x80, 0x73, 0x53, 0xb5, 0x1c, 0x5f, 0x71, 0xb2, 0x2a, 0xc3, 0xd0, 0xc7, 0xe3, 0x94, +dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, + 0xda, 0xbf, 0xf5, + 0x6a, 0x0c, 0x2e, 0x79, 0xde, 0xf4, 0x4b, 0xc8, 0xf2, 0xe5, 0x36, 0x99, 0x09, + 0x6d, 0x1f, 0xf2, + 0x70, 0xf1, 0x59, 0x78, 0x5d, 0x75, 0x69, 0x21, 0xdb, 0xff, 0x97, 0x73, 0xae, + 0x08, 0x48, 0x3b, + 0x66, 0x2f, 0xc0, 0x7d, 0xf7, 0x51, 0x2f, 0xf6, 0x8b, 0x2e, 0x55, 0x65, 0xfd, + 0x79, 0x82, 0xe2, + 0x0c, 0x24, 0x48, 0x32, 0xab, 0xa1, 0x21, 0xcc, 0x07, 0x99, 0xcc, 0x09, 0xf2, + 0xd5, 0x41, 0x4d, + 0x5f, 0x39, 0x66, 0x21, 0x13, 0x65, 0xf5, 0x1b, 0x83, 0xe9, 0xff, 0xcc, 0xcb, + 0x3d, 0x88, 0xcd, + 0xf2, 0x38, 0xf7, 0xc2, 0x73, 0x91, 0x31, 0xca, 0x7a, 0xad, 0xff, 0x66, 0x2f, + 0xec, 0x1f, 0xb0, + 0xe1, 0xd3, 0x11, 0xa4, 0x04, 0x26, 0x03, 0x76, 0xfd, 0x01, 0x1f, 0xe0, 0x0d, + 0x02, 0x04, 0xc3] +dsa_sub_prime_1024_160 = [0xd3, 0x80, 0x73, 0x53, 0xb5, 0x1c, 0x5f, 0x71, 0xb2, 0x2a, 0xc3, 0xd0, + 0xc7, 0xe3, 0x94, 0x14, 0x8f, 0xce, 0xdc, 0x61] -dsa_base_1024_160 = [0x42, 0xe3, 0x77, 0x8e, 0x6e, 0xc3, 0x1b, 0x0d, 0xb0, 0x7a, 0x6b, 0x37, 0x0d, 0x7f, 0xb6, 0xfb, - 0x4a, 0x0b, 0xca, 0x6d, 0xea, 0xac, 0x37, 0x1f, 0x6a, 0xdb, 0xcb, 0xeb, 0xa3, 0x8d, 0xdf, 0x76, - 0xa4, 0x7c, 0x3c, 0x3d, 0x79, 0x27, 0x6a, 0x0e, 0x57, 0x9c, 0xe4, 0xe3, 0x47, 0x18, 0x0f, 0xd9, - 0xb4, 0xad, 0x46, 0x1d, 0x6c, 0xf0, 0xea, 0xc5, 0x1f, 0xb0, 0x8c, 0xf4, 0x52, 0xf6, 0x24, 0x57, - 0x00, 0x51, 0xe5, 0x18, 0xa7, 0x5a, 0x5b, 0xb9, 0xc3, 0x57, 0x8a, 0x14, 0xfd, 0x4f, 0x27, 0xf7, - 0x95, 0xb2, 0x2a, 0xce, 0xa6, 0x2b, 0x1f, 0xdf, 0x10, 0x32, 0xc1, 0x26, 0x6d, 0xa0, 0x81, 0xc7, - 0xfb, 0x99, 0xc4, 0x26, 0x66, 0x26, 0x58, 0x70, 0x93, 0xfd, 0x38, 0x16, 0x17, 0x23, 0x8e, 0xe1, - 0x57, 0x8f, 0xc3, 0x25, 0x54, 0x8d, 0xc1, 0xc0, 0x8e, 0x5f, 0x93, 0x22, 0xc3, 0xb1, 0x20, 0x5e] +dsa_base_1024_160 = [0x42, 0xe3, 0x77, 0x8e, 0x6e, 0xc3, 0x1b, 0x0d, 0xb0, 0x7a, 0x6b, 0x37, 0x0d, + 0x7f, 0xb6, 0xfb, + 0x4a, 0x0b, 0xca, 0x6d, 0xea, 0xac, 0x37, 0x1f, 0x6a, 0xdb, 0xcb, 0xeb, 0xa3, + 0x8d, 0xdf, 0x76, + 0xa4, 0x7c, 0x3c, 0x3d, 0x79, 0x27, 0x6a, 0x0e, 0x57, 0x9c, 0xe4, 0xe3, 0x47, + 0x18, 0x0f, 0xd9, + 0xb4, 0xad, 0x46, 0x1d, 0x6c, 0xf0, 0xea, 0xc5, 0x1f, 0xb0, 0x8c, 0xf4, 0x52, + 0xf6, 0x24, 0x57, + 0x00, 0x51, 0xe5, 0x18, 0xa7, 0x5a, 0x5b, 0xb9, 0xc3, 0x57, 0x8a, 0x14, 0xfd, + 0x4f, 0x27, 0xf7, + 0x95, 0xb2, 0x2a, 0xce, 0xa6, 0x2b, 0x1f, 0xdf, 0x10, 0x32, 0xc1, 0x26, 0x6d, + 0xa0, 0x81, 0xc7, + 0xfb, 0x99, 0xc4, 0x26, 0x66, 0x26, 0x58, 0x70, 0x93, 0xfd, 0x38, 0x16, 0x17, + 0x23, 0x8e, 0xe1, + 0x57, 0x8f, 0xc3, 0x25, 0x54, 0x8d, 0xc1, 0xc0, 0x8e, 0x5f, 0x93, 0x22, 0xc3, + 0xb1, 0x20, 0x5e] -dsa_prime_2048_224 = [0xa2, 0x15, 0xdc, 0xa3, 0xf7, 0x87, 0x34, 0x2c, 0x91, 0x90, 0x87, 0x83, 0x70, 0x79, 0x73, 0x38, - 0x9f, 0x3e, 0x02, 0xf2, 0xc9, 0x68, 0xfe, 0x67, 0xca, 0xb9, 0x4f, 0x5d, 0x6f, 0x92, 0x8c, 0xe8, - 0x6c, 0x8d, 0x62, 0x25, 0x37, 0x4c, 0xa1, 0xbf, 0x7f, 0x27, 0x77, 0x44, 0x8c, 0xc7, 0xc0, 0xc5, - 0xed, 0x66, 0xd1, 0x20, 0x11, 0x7f, 0xec, 0x10, 0xed, 0x81, 0x55, 0x51, 0x45, 0x36, 0xe1, 0xaa, - 0x31, 0x6b, 0x8d, 0xd4, 0x58, 0x27, 0xa0, 0xf0, 0x0e, 0x5d, 0x91, 0x8c, 0x0f, 0xdd, 0x21, 0x8a, - 0xcd, 0x6c, 0x26, 0x3c, 0x1c, 0x2e, 0x55, 0xf6, 0xd0, 0xa7, 0x0f, 0x1b, 0xc9, 0x7f, 0x4b, 0xb0, - 0x4f, 0xff, 0xee, 0x4b, 0x78, 0xb4, 0xdf, 0x34, 0x90, 0xad, 0x98, 0xab, 0xad, 0x0a, 0x4b, 0xfe, - 0x1d, 0xaf, 0xaf, 0x6c, 0x09, 0xdd, 0xda, 0xdf, 0xb8, 0x88, 0x96, 0x94, 0x51, 0x3b, 0x86, 0x5c, - 0x07, 0xa4, 0xf5, 0xf9, 0x27, 0xbe, 0x72, 0x39, 0xe8, 0xd7, 0x67, 0x14, 0xe0, 0x3b, 0x7b, 0xfa, - 0xfb, 0x92, 0x94, 0x00, 0x0f, 0xbb, 0x3f, 0x7a, 0x75, 0x0b, 0x39, 0xca, 0x50, 0x63, 0x0e, 0xe7, - 0xd0, 0xbc, 0x45, 0xa9, 0xc9, 0x87, 0xae, 0x38, 0xae, 0x03, 0x7a, 0x11, 0xb1, 0xd1, 0x3d, 0xf5, - 0x51, 0x76, 0xd9, 0xd8, 0xab, 0x9e, 0xc0, 0xa4, 0x1b, 0x78, 0xa6, 0x36, 0x9e, 0xb5, 0x19, 0x88, - 0xfe, 0x9f, 0xbd, 0x97, 0xa1, 0x0d, 0x48, 0xe2, 0xeb, 0x21, 0x8e, 0xc6, 0x92, 0xb3, 0x1c, 0xfc, - 0xc9, 0x58, 0x3c, 0x7a, 0x41, 0x1d, 0x7d, 0xfa, 0x0a, 0xb3, 0x15, 0xfb, 0x0c, 0x75, 0xe2, 0x10, - 0x9e, 0xb1, 0xe2, 0xee, 0x75, 0xf4, 0x1d, 0x0a, 0x01, 0x65, 0x46, 0xda, 0x70, 0xa6, 0x31, 0xac, - 0x77, 0x8a, 0x2a, 0xe3, 0x25, 0x1f, 0x11, 0x39, 0xe5, 0x74, 0xe2, 0x6d, 0x2c, 0xc6, 0x5c, 0x47] -dsa_sub_prime_2048_224 = [0xd3, 0x76, 0x83, 0x74, 0x55, 0x3d, 0x49, 0x17, 0x19, 0x92, 0x74, 0xba, 0x05, 0x63, 0xbe, +dsa_prime_2048_224 = [0xa2, 0x15, 0xdc, 0xa3, 0xf7, 0x87, 0x34, 0x2c, 0x91, 0x90, 0x87, 0x83, 0x70, + 0x79, 0x73, 0x38, + 0x9f, 0x3e, 0x02, 0xf2, 0xc9, 0x68, 0xfe, 0x67, 0xca, 0xb9, 0x4f, 0x5d, 0x6f, + 0x92, 0x8c, 0xe8, + 0x6c, 0x8d, 0x62, 0x25, 0x37, 0x4c, 0xa1, 0xbf, 0x7f, 0x27, 0x77, 0x44, 0x8c, + 0xc7, 0xc0, 0xc5, + 0xed, 0x66, 0xd1, 0x20, 0x11, 0x7f, 0xec, 0x10, 0xed, 0x81, 0x55, 0x51, 0x45, + 0x36, 0xe1, 0xaa, + 0x31, 0x6b, 0x8d, 0xd4, 0x58, 0x27, 0xa0, 0xf0, 0x0e, 0x5d, 0x91, 0x8c, 0x0f, + 0xdd, 0x21, 0x8a, + 0xcd, 0x6c, 0x26, 0x3c, 0x1c, 0x2e, 0x55, 0xf6, 0xd0, 0xa7, 0x0f, 0x1b, 0xc9, + 0x7f, 0x4b, 0xb0, + 0x4f, 0xff, 0xee, 0x4b, 0x78, 0xb4, 0xdf, 0x34, 0x90, 0xad, 0x98, 0xab, 0xad, + 0x0a, 0x4b, 0xfe, + 0x1d, 0xaf, 0xaf, 0x6c, 0x09, 0xdd, 0xda, 0xdf, 0xb8, 0x88, 0x96, 0x94, 0x51, + 0x3b, 0x86, 0x5c, + 0x07, 0xa4, 0xf5, 0xf9, 0x27, 0xbe, 0x72, 0x39, 0xe8, 0xd7, 0x67, 0x14, 0xe0, + 0x3b, 0x7b, 0xfa, + 0xfb, 0x92, 0x94, 0x00, 0x0f, 0xbb, 0x3f, 0x7a, 0x75, 0x0b, 0x39, 0xca, 0x50, + 0x63, 0x0e, 0xe7, + 0xd0, 0xbc, 0x45, 0xa9, 0xc9, 0x87, 0xae, 0x38, 0xae, 0x03, 0x7a, 0x11, 0xb1, + 0xd1, 0x3d, 0xf5, + 0x51, 0x76, 0xd9, 0xd8, 0xab, 0x9e, 0xc0, 0xa4, 0x1b, 0x78, 0xa6, 0x36, 0x9e, + 0xb5, 0x19, 0x88, + 0xfe, 0x9f, 0xbd, 0x97, 0xa1, 0x0d, 0x48, 0xe2, 0xeb, 0x21, 0x8e, 0xc6, 0x92, + 0xb3, 0x1c, 0xfc, + 0xc9, 0x58, 0x3c, 0x7a, 0x41, 0x1d, 0x7d, 0xfa, 0x0a, 0xb3, 0x15, 0xfb, 0x0c, + 0x75, 0xe2, 0x10, + 0x9e, 0xb1, 0xe2, 0xee, 0x75, 0xf4, 0x1d, 0x0a, 0x01, 0x65, 0x46, 0xda, 0x70, + 0xa6, 0x31, 0xac, + 0x77, 0x8a, 0x2a, 0xe3, 0x25, 0x1f, 0x11, 0x39, 0xe5, 0x74, 0xe2, 0x6d, 0x2c, + 0xc6, 0x5c, 0x47] +dsa_sub_prime_2048_224 = [0xd3, 0x76, 0x83, 0x74, 0x55, 0x3d, 0x49, 0x17, 0x19, 0x92, 0x74, 0xba, + 0x05, 0x63, 0xbe, 0xff, 0xa2, 0xa4, 0x5f, 0x05, 0xae, 0x83, 0xdf, 0x9b, 0x34, 0x81, 0x55, 0xbf] -dsa_base_2048_224 = [0x4e, 0x1f, 0x73, 0x4e, 0x08, 0x92, 0xd0, 0x4d, 0x80, 0x89, 0x93, 0xe6, 0x3d, 0xad, 0xef, 0xb3, - 0xfa, 0xa2, 0x48, 0x4c, 0x88, 0x83, 0x8d, 0x38, 0xd8, 0xea, 0x64, 0xca, 0x28, 0xd6, 0xc0, 0x89, - 0xbe, 0x4b, 0x88, 0x14, 0x66, 0x83, 0xec, 0xbd, 0x8b, 0x8d, 0xc6, 0xfb, 0x17, 0x81, 0xca, 0x1d, - 0x83, 0xf3, 0x7f, 0x38, 0xd2, 0x36, 0x03, 0x2b, 0x17, 0x51, 0x16, 0x6a, 0xe4, 0x3f, 0x22, 0xb5, - 0x2d, 0xd6, 0x03, 0x40, 0x1e, 0x89, 0xfe, 0xf6, 0xc9, 0xd0, 0x21, 0x5f, 0x49, 0xa2, 0xcf, 0x97, - 0x33, 0x7b, 0xe2, 0x61, 0x28, 0x8f, 0xd9, 0xac, 0xfb, 0xb6, 0xc2, 0xc0, 0xc5, 0xea, 0x70, 0x9d, - 0x14, 0x76, 0x02, 0x74, 0x41, 0x75, 0x4c, 0xcd, 0x71, 0x00, 0x79, 0x05, 0x52, 0x55, 0x97, 0xd7, - 0xae, 0xc7, 0x71, 0xeb, 0x01, 0x2b, 0x0b, 0xfc, 0xd3, 0x4f, 0x87, 0x16, 0xc7, 0xcc, 0xb1, 0x91, - 0x3d, 0x4f, 0xa6, 0x10, 0x50, 0x4b, 0x67, 0x79, 0x01, 0xdb, 0x37, 0x80, 0x01, 0x9a, 0xa6, 0x92, - 0x23, 0xfb, 0xcd, 0x94, 0x33, 0x6f, 0x2b, 0xf0, 0x2b, 0x44, 0x09, 0x39, 0x39, 0xcc, 0x0d, 0x96, - 0x11, 0xe8, 0xf5, 0xc6, 0x28, 0x50, 0x2e, 0x2b, 0x81, 0x08, 0x3f, 0xc1, 0x28, 0x2f, 0x65, 0x2e, - 0x16, 0x48, 0xc4, 0xe2, 0xb0, 0x29, 0x54, 0x99, 0x19, 0xc5, 0x78, 0xbf, 0x3b, 0xf3, 0x84, 0x70, - 0xc7, 0x8b, 0x5a, 0xcb, 0x10, 0x55, 0xfe, 0x4b, 0x71, 0xef, 0xf5, 0xdb, 0x85, 0xa6, 0xf5, 0xe8, - 0x00, 0xf5, 0xc2, 0xb4, 0xa6, 0x48, 0x39, 0x83, 0x6e, 0xd1, 0xb0, 0xad, 0xea, 0x2d, 0x7e, 0x2e, - 0x22, 0x98, 0xaa, 0x10, 0x7f, 0xa0, 0xec, 0x23, 0x70, 0x87, 0xf5, 0xda, 0x6b, 0x5e, 0x0d, 0x8b, - 0x46, 0xc8, 0x88, 0x61, 0xc3, 0xc1, 0xf5, 0xdb, 0x02, 0x2a, 0x62, 0x7a, 0xd5, 0x95, 0xe5, 0xe2] +dsa_base_2048_224 = [0x4e, 0x1f, 0x73, 0x4e, 0x08, 0x92, 0xd0, 0x4d, 0x80, 0x89, 0x93, 0xe6, 0x3d, + 0xad, 0xef, 0xb3, + 0xfa, 0xa2, 0x48, 0x4c, 0x88, 0x83, 0x8d, 0x38, 0xd8, 0xea, 0x64, 0xca, 0x28, + 0xd6, 0xc0, 0x89, + 0xbe, 0x4b, 0x88, 0x14, 0x66, 0x83, 0xec, 0xbd, 0x8b, 0x8d, 0xc6, 0xfb, 0x17, + 0x81, 0xca, 0x1d, + 0x83, 0xf3, 0x7f, 0x38, 0xd2, 0x36, 0x03, 0x2b, 0x17, 0x51, 0x16, 0x6a, 0xe4, + 0x3f, 0x22, 0xb5, + 0x2d, 0xd6, 0x03, 0x40, 0x1e, 0x89, 0xfe, 0xf6, 0xc9, 0xd0, 0x21, 0x5f, 0x49, + 0xa2, 0xcf, 0x97, + 0x33, 0x7b, 0xe2, 0x61, 0x28, 0x8f, 0xd9, 0xac, 0xfb, 0xb6, 0xc2, 0xc0, 0xc5, + 0xea, 0x70, 0x9d, + 0x14, 0x76, 0x02, 0x74, 0x41, 0x75, 0x4c, 0xcd, 0x71, 0x00, 0x79, 0x05, 0x52, + 0x55, 0x97, 0xd7, + 0xae, 0xc7, 0x71, 0xeb, 0x01, 0x2b, 0x0b, 0xfc, 0xd3, 0x4f, 0x87, 0x16, 0xc7, + 0xcc, 0xb1, 0x91, + 0x3d, 0x4f, 0xa6, 0x10, 0x50, 0x4b, 0x67, 0x79, 0x01, 0xdb, 0x37, 0x80, 0x01, + 0x9a, 0xa6, 0x92, + 0x23, 0xfb, 0xcd, 0x94, 0x33, 0x6f, 0x2b, 0xf0, 0x2b, 0x44, 0x09, 0x39, 0x39, + 0xcc, 0x0d, 0x96, + 0x11, 0xe8, 0xf5, 0xc6, 0x28, 0x50, 0x2e, 0x2b, 0x81, 0x08, 0x3f, 0xc1, 0x28, + 0x2f, 0x65, 0x2e, + 0x16, 0x48, 0xc4, 0xe2, 0xb0, 0x29, 0x54, 0x99, 0x19, 0xc5, 0x78, 0xbf, 0x3b, + 0xf3, 0x84, 0x70, + 0xc7, 0x8b, 0x5a, 0xcb, 0x10, 0x55, 0xfe, 0x4b, 0x71, 0xef, 0xf5, 0xdb, 0x85, + 0xa6, 0xf5, 0xe8, + 0x00, 0xf5, 0xc2, 0xb4, 0xa6, 0x48, 0x39, 0x83, 0x6e, 0xd1, 0xb0, 0xad, 0xea, + 0x2d, 0x7e, 0x2e, + 0x22, 0x98, 0xaa, 0x10, 0x7f, 0xa0, 0xec, 0x23, 0x70, 0x87, 0xf5, 0xda, 0x6b, + 0x5e, 0x0d, 0x8b, + 0x46, 0xc8, 0x88, 0x61, 0xc3, 0xc1, 0xf5, 0xdb, 0x02, 0x2a, 0x62, 0x7a, 0xd5, + 0x95, 0xe5, 0xe2] -dsa_prime_2048_256 = [0xad, 0x78, 0xd1, 0x93, 0x08, 0x76, 0x4f, 0x04, 0xeb, 0x6a, 0xa3, 0x82, 0x09, 0x38, 0x0f, 0xf6, - 0xc9, 0x87, 0x5e, 0x27, 0xb2, 0x7c, 0xc1, 0x4b, 0x78, 0x29, 0xbe, 0x2e, 0xcd, 0xae, 0x26, 0x88, - 0xf4, 0x5d, 0xe8, 0x09, 0xd1, 0x16, 0x06, 0x61, 0xd4, 0x81, 0x65, 0x00, 0x5d, 0x76, 0x7e, 0xf1, - 0x24, 0x73, 0x01, 0x8f, 0x92, 0xd4, 0x07, 0xe7, 0xf3, 0xf7, 0x3a, 0xb9, 0x8b, 0x8e, 0xc8, 0xf4, - 0x13, 0x2b, 0x52, 0xb8, 0x2a, 0x08, 0x57, 0xbc, 0x15, 0xe5, 0x8e, 0x2a, 0x16, 0xda, 0x5e, 0xff, - 0xd2, 0x4e, 0xc7, 0x24, 0xa9, 0x70, 0x74, 0xd2, 0xb4, 0xc1, 0xc0, 0xec, 0x81, 0xcb, 0x83, 0xe9, - 0x29, 0x2a, 0xfd, 0x3b, 0xb9, 0x83, 0xec, 0x23, 0xd1, 0xf9, 0x13, 0xec, 0x1a, 0x68, 0x3f, 0x44, - 0x9b, 0x85, 0x7a, 0x5e, 0x6a, 0x38, 0x91, 0xe0, 0xc6, 0xc8, 0x15, 0x23, 0xf3, 0x98, 0xf7, 0x29, - 0x7f, 0x7b, 0x07, 0x14, 0x3f, 0x6f, 0xfa, 0x11, 0x71, 0x65, 0xff, 0xd9, 0xdc, 0x71, 0x23, 0xd3, - 0x40, 0xec, 0x3b, 0x5f, 0x47, 0x9c, 0x4d, 0x53, 0x4c, 0x4f, 0x61, 0x31, 0xae, 0xda, 0x2e, 0xb6, - 0xd3, 0xd2, 0x01, 0x2c, 0x63, 0x9b, 0xaa, 0x61, 0x79, 0x13, 0xe9, 0xcc, 0xef, 0x57, 0xb1, 0x7a, - 0xd1, 0xd2, 0xe3, 0xfd, 0x92, 0x29, 0x43, 0x4a, 0xc4, 0x50, 0x8c, 0x36, 0xe8, 0xa5, 0xca, 0x9a, - 0xf6, 0x43, 0x3e, 0x75, 0x32, 0x16, 0x8b, 0xe8, 0x98, 0x9c, 0x60, 0x00, 0x83, 0xb6, 0xf4, 0xc9, - 0xa2, 0x36, 0xe8, 0xf6, 0xe3, 0x8a, 0x68, 0x64, 0x61, 0x1d, 0x7b, 0xe2, 0x3c, 0xf2, 0x48, 0x77, - 0x7d, 0xe5, 0xd1, 0xd0, 0x7a, 0x8d, 0x34, 0xdd, 0x1c, 0xc2, 0xbe, 0x99, 0xa4, 0xda, 0xbf, 0xd1, - 0x30, 0x4b, 0xc1, 0xc9, 0x73, 0xc1, 0x07, 0x78, 0x04, 0x0f, 0xdd, 0x7f, 0xa2, 0xfa, 0xc1, 0x0f] -dsa_sub_prime_2048_256 = [0xac, 0x66, 0x19, 0x0a, 0x7f, 0x8d, 0x6b, 0x5f, 0xc3, 0x77, 0x06, 0x35, 0x58, 0x2f, 0x9b, +dsa_prime_2048_256 = [0xad, 0x78, 0xd1, 0x93, 0x08, 0x76, 0x4f, 0x04, 0xeb, 0x6a, 0xa3, 0x82, 0x09, + 0x38, 0x0f, 0xf6, + 0xc9, 0x87, 0x5e, 0x27, 0xb2, 0x7c, 0xc1, 0x4b, 0x78, 0x29, 0xbe, 0x2e, 0xcd, + 0xae, 0x26, 0x88, + 0xf4, 0x5d, 0xe8, 0x09, 0xd1, 0x16, 0x06, 0x61, 0xd4, 0x81, 0x65, 0x00, 0x5d, + 0x76, 0x7e, 0xf1, + 0x24, 0x73, 0x01, 0x8f, 0x92, 0xd4, 0x07, 0xe7, 0xf3, 0xf7, 0x3a, 0xb9, 0x8b, + 0x8e, 0xc8, 0xf4, + 0x13, 0x2b, 0x52, 0xb8, 0x2a, 0x08, 0x57, 0xbc, 0x15, 0xe5, 0x8e, 0x2a, 0x16, + 0xda, 0x5e, 0xff, + 0xd2, 0x4e, 0xc7, 0x24, 0xa9, 0x70, 0x74, 0xd2, 0xb4, 0xc1, 0xc0, 0xec, 0x81, + 0xcb, 0x83, 0xe9, + 0x29, 0x2a, 0xfd, 0x3b, 0xb9, 0x83, 0xec, 0x23, 0xd1, 0xf9, 0x13, 0xec, 0x1a, + 0x68, 0x3f, 0x44, + 0x9b, 0x85, 0x7a, 0x5e, 0x6a, 0x38, 0x91, 0xe0, 0xc6, 0xc8, 0x15, 0x23, 0xf3, + 0x98, 0xf7, 0x29, + 0x7f, 0x7b, 0x07, 0x14, 0x3f, 0x6f, 0xfa, 0x11, 0x71, 0x65, 0xff, 0xd9, 0xdc, + 0x71, 0x23, 0xd3, + 0x40, 0xec, 0x3b, 0x5f, 0x47, 0x9c, 0x4d, 0x53, 0x4c, 0x4f, 0x61, 0x31, 0xae, + 0xda, 0x2e, 0xb6, + 0xd3, 0xd2, 0x01, 0x2c, 0x63, 0x9b, 0xaa, 0x61, 0x79, 0x13, 0xe9, 0xcc, 0xef, + 0x57, 0xb1, 0x7a, + 0xd1, 0xd2, 0xe3, 0xfd, 0x92, 0x29, 0x43, 0x4a, 0xc4, 0x50, 0x8c, 0x36, 0xe8, + 0xa5, 0xca, 0x9a, + 0xf6, 0x43, 0x3e, 0x75, 0x32, 0x16, 0x8b, 0xe8, 0x98, 0x9c, 0x60, 0x00, 0x83, + 0xb6, 0xf4, 0xc9, + 0xa2, 0x36, 0xe8, 0xf6, 0xe3, 0x8a, 0x68, 0x64, 0x61, 0x1d, 0x7b, 0xe2, 0x3c, + 0xf2, 0x48, 0x77, + 0x7d, 0xe5, 0xd1, 0xd0, 0x7a, 0x8d, 0x34, 0xdd, 0x1c, 0xc2, 0xbe, 0x99, 0xa4, + 0xda, 0xbf, 0xd1, + 0x30, 0x4b, 0xc1, 0xc9, 0x73, 0xc1, 0x07, 0x78, 0x04, 0x0f, 0xdd, 0x7f, 0xa2, + 0xfa, 0xc1, 0x0f] +dsa_sub_prime_2048_256 = [0xac, 0x66, 0x19, 0x0a, 0x7f, 0x8d, 0x6b, 0x5f, 0xc3, 0x77, 0x06, 0x35, + 0x58, 0x2f, 0x9b, 0xc1, - 0x4a, 0x56, 0x91, 0x55, 0xf9, 0x79, 0x3b, 0x79, 0x8e, 0x2e, 0xdb, 0xfc, 0x69, 0x4e, 0x6a, + 0x4a, 0x56, 0x91, 0x55, 0xf9, 0x79, 0x3b, 0x79, 0x8e, 0x2e, 0xdb, 0xfc, + 0x69, 0x4e, 0x6a, 0xfd] -dsa_base_2048_256 = [0xa6, 0x37, 0x45, 0x31, 0xe5, 0x54, 0x8a, 0x58, 0xa6, 0xd0, 0x20, 0x33, 0xdf, 0x60, 0xbf, 0xf8, - 0xa3, 0x5c, 0xa4, 0x1b, 0x37, 0xe4, 0xc9, 0xea, 0xb0, 0xf2, 0x53, 0x22, 0x19, 0x60, 0xaa, 0x6f, - 0xb2, 0x6b, 0xad, 0x24, 0x04, 0xad, 0x38, 0x57, 0x70, 0x3c, 0x4e, 0x71, 0x6e, 0x35, 0x0d, 0x4b, - 0xcc, 0xbc, 0x4d, 0xad, 0xd9, 0x1d, 0x30, 0x5e, 0xc4, 0x3a, 0x62, 0xfe, 0x2e, 0x82, 0x52, 0xcb, - 0x97, 0x37, 0xb6, 0x0a, 0xf4, 0xc5, 0x5d, 0xf7, 0xfa, 0xe4, 0x95, 0x18, 0xeb, 0x0d, 0x1b, 0xcc, - 0x0e, 0xda, 0x06, 0x50, 0x28, 0xa5, 0x1a, 0x87, 0x51, 0x21, 0xcd, 0xd5, 0xea, 0x60, 0xa1, 0x39, - 0x39, 0x82, 0x33, 0xa5, 0xd1, 0x9b, 0x0d, 0xb3, 0x5c, 0xc3, 0xeb, 0x7d, 0xa3, 0x23, 0xa8, 0xf3, - 0xb2, 0x95, 0xd3, 0x5c, 0x31, 0xb6, 0xaa, 0x55, 0xd4, 0x22, 0xaa, 0xb5, 0x5f, 0x47, 0x0f, 0xd2, - 0x79, 0xa3, 0xd3, 0x55, 0xb2, 0xa5, 0xd7, 0x5b, 0xd0, 0x37, 0x1d, 0x92, 0x58, 0xf6, 0xda, 0x07, - 0x48, 0x9e, 0x02, 0x9d, 0xfb, 0xd6, 0x71, 0x10, 0x7e, 0x0b, 0x2c, 0x94, 0xff, 0xc3, 0xdc, 0xa7, - 0x40, 0x4b, 0x81, 0x34, 0x19, 0xdb, 0x55, 0xc3, 0x46, 0xf8, 0xc3, 0x4d, 0xe7, 0x8a, 0x0d, 0x1c, - 0x69, 0xd2, 0x6f, 0x91, 0xb2, 0xd3, 0xcf, 0xc5, 0x20, 0xfe, 0x0a, 0xc0, 0x6d, 0x95, 0x5b, 0xd2, - 0x50, 0xa6, 0xb8, 0x6f, 0xe1, 0x32, 0xc0, 0x57, 0x13, 0x0b, 0x26, 0xd8, 0x22, 0x9d, 0xe3, 0xad, - 0x06, 0x79, 0xb4, 0xfc, 0xf5, 0x00, 0xb5, 0x5c, 0x76, 0x5d, 0xf9, 0x86, 0xb6, 0x69, 0x4f, 0x6c, - 0x02, 0x2d, 0x92, 0x7d, 0x9c, 0x48, 0x58, 0x7b, 0x17, 0x95, 0x7c, 0xe3, 0x97, 0x4d, 0x93, 0x7a, - 0x4c, 0x26, 0xc1, 0xa1, 0xe0, 0x6c, 0xbb, 0xc3, 0x01, 0x70, 0x9f, 0x14, 0x29, 0x3f, 0xe0, 0x5e] +dsa_base_2048_256 = [0xa6, 0x37, 0x45, 0x31, 0xe5, 0x54, 0x8a, 0x58, 0xa6, 0xd0, 0x20, 0x33, 0xdf, + 0x60, 0xbf, 0xf8, + 0xa3, 0x5c, 0xa4, 0x1b, 0x37, 0xe4, 0xc9, 0xea, 0xb0, 0xf2, 0x53, 0x22, 0x19, + 0x60, 0xaa, 0x6f, + 0xb2, 0x6b, 0xad, 0x24, 0x04, 0xad, 0x38, 0x57, 0x70, 0x3c, 0x4e, 0x71, 0x6e, + 0x35, 0x0d, 0x4b, + 0xcc, 0xbc, 0x4d, 0xad, 0xd9, 0x1d, 0x30, 0x5e, 0xc4, 0x3a, 0x62, 0xfe, 0x2e, + 0x82, 0x52, 0xcb, + 0x97, 0x37, 0xb6, 0x0a, 0xf4, 0xc5, 0x5d, 0xf7, 0xfa, 0xe4, 0x95, 0x18, 0xeb, + 0x0d, 0x1b, 0xcc, + 0x0e, 0xda, 0x06, 0x50, 0x28, 0xa5, 0x1a, 0x87, 0x51, 0x21, 0xcd, 0xd5, 0xea, + 0x60, 0xa1, 0x39, + 0x39, 0x82, 0x33, 0xa5, 0xd1, 0x9b, 0x0d, 0xb3, 0x5c, 0xc3, 0xeb, 0x7d, 0xa3, + 0x23, 0xa8, 0xf3, + 0xb2, 0x95, 0xd3, 0x5c, 0x31, 0xb6, 0xaa, 0x55, 0xd4, 0x22, 0xaa, 0xb5, 0x5f, + 0x47, 0x0f, 0xd2, + 0x79, 0xa3, 0xd3, 0x55, 0xb2, 0xa5, 0xd7, 0x5b, 0xd0, 0x37, 0x1d, 0x92, 0x58, + 0xf6, 0xda, 0x07, + 0x48, 0x9e, 0x02, 0x9d, 0xfb, 0xd6, 0x71, 0x10, 0x7e, 0x0b, 0x2c, 0x94, 0xff, + 0xc3, 0xdc, 0xa7, + 0x40, 0x4b, 0x81, 0x34, 0x19, 0xdb, 0x55, 0xc3, 0x46, 0xf8, 0xc3, 0x4d, 0xe7, + 0x8a, 0x0d, 0x1c, + 0x69, 0xd2, 0x6f, 0x91, 0xb2, 0xd3, 0xcf, 0xc5, 0x20, 0xfe, 0x0a, 0xc0, 0x6d, + 0x95, 0x5b, 0xd2, + 0x50, 0xa6, 0xb8, 0x6f, 0xe1, 0x32, 0xc0, 0x57, 0x13, 0x0b, 0x26, 0xd8, 0x22, + 0x9d, 0xe3, 0xad, + 0x06, 0x79, 0xb4, 0xfc, 0xf5, 0x00, 0xb5, 0x5c, 0x76, 0x5d, 0xf9, 0x86, 0xb6, + 0x69, 0x4f, 0x6c, + 0x02, 0x2d, 0x92, 0x7d, 0x9c, 0x48, 0x58, 0x7b, 0x17, 0x95, 0x7c, 0xe3, 0x97, + 0x4d, 0x93, 0x7a, + 0x4c, 0x26, 0xc1, 0xa1, 0xe0, 0x6c, 0xbb, 0xc3, 0x01, 0x70, 0x9f, 0x14, 0x29, + 0x3f, 0xe0, 0x5e] -dsa_prime_3072_256 = [0xa0, 0x38, 0x3e, 0xe6, 0x92, 0xf8, 0xf5, 0xba, 0xdd, 0xf9, 0x31, 0x7b, 0x16, 0xed, 0xd2, 0x84, - 0xa3, 0x63, 0x19, 0xb0, 0x53, 0xf7, 0x3a, 0xd4, 0x31, 0xae, 0x4b, 0x5d, 0xb2, 0xc6, 0x63, 0x0b, - 0x5a, 0xbf, 0xe8, 0xc5, 0xcb, 0x9d, 0x23, 0x06, 0x50, 0xdc, 0x72, 0xee, 0xfb, 0xe6, 0xf2, 0x61, - 0xdb, 0x2f, 0x43, 0xe6, 0x83, 0x81, 0x58, 0x8c, 0xfd, 0x4a, 0x74, 0x51, 0xbb, 0xbb, 0x30, 0xc5, - 0x95, 0x21, 0xd7, 0x8e, 0xa7, 0x6d, 0xc0, 0x70, 0xcf, 0x81, 0x78, 0x33, 0x19, 0x9f, 0xf7, 0x15, - 0xcb, 0xd1, 0x12, 0xa2, 0x58, 0x50, 0x69, 0x35, 0x44, 0x66, 0x2e, 0x12, 0xbb, 0x27, 0x93, 0xa8, - 0x14, 0x84, 0x77, 0x64, 0xac, 0x27, 0x7c, 0x5c, 0xf0, 0x6b, 0x3e, 0x04, 0x4a, 0x45, 0x91, 0x3e, - 0xdd, 0x61, 0x92, 0x29, 0xdd, 0xd7, 0x28, 0x93, 0x14, 0xd0, 0x0b, 0xb6, 0xa7, 0xda, 0xf1, 0x7e, - 0xb8, 0x63, 0xf3, 0x1d, 0xc2, 0x2c, 0xcc, 0x05, 0xf6, 0x14, 0xc1, 0xbb, 0x0c, 0xea, 0x4c, 0x45, - 0x4f, 0xc6, 0xa0, 0x29, 0xc0, 0xd2, 0x56, 0x8d, 0x1c, 0x5e, 0xef, 0x7f, 0x7c, 0x41, 0xf1, 0xb6, - 0x59, 0xce, 0xd9, 0x24, 0xdd, 0x0e, 0xab, 0xc7, 0xc9, 0xbc, 0x3a, 0x55, 0x90, 0xd4, 0x03, 0x12, - 0xe3, 0xec, 0x13, 0xa2, 0xca, 0xa1, 0x80, 0xed, 0x6b, 0x0c, 0x7d, 0x54, 0xd1, 0x63, 0xca, 0x1f, - 0x32, 0xcd, 0x89, 0x27, 0xa0, 0xfd, 0x39, 0x4e, 0x51, 0xde, 0xf2, 0xa3, 0x1e, 0x83, 0xfc, 0x53, - 0x73, 0xbe, 0xf8, 0xd2, 0x5f, 0x65, 0x32, 0xef, 0x51, 0x5f, 0x86, 0x7b, 0x0b, 0x31, 0x73, 0x8f, - 0xf2, 0x7f, 0xac, 0xad, 0x0d, 0xfb, 0x40, 0xe7, 0x6b, 0x68, 0x3a, 0x3b, 0x11, 0xc9, 0x9f, 0x59, - 0xc8, 0xa4, 0x98, 0xba, 0x2b, 0x88, 0x08, 0x70, 0x0f, 0x20, 0x15, 0x14, 0x5c, 0x77, 0xdb, 0xa4, - 0x20, 0xc5, 0xf0, 0xdb, 0x95, 0xac, 0x88, 0x03, 0x6a, 0x40, 0x90, 0x4a, 0x53, 0xb3, 0x80, 0xaa, - 0x0c, 0x75, 0x80, 0x5a, 0x0d, 0xfd, 0xad, 0x4c, 0xbe, 0xaa, 0x48, 0x91, 0xab, 0xd8, 0x4d, 0x24, - 0xbb, 0x64, 0x4d, 0x96, 0xc5, 0x9f, 0x33, 0x9e, 0x01, 0x6b, 0xb4, 0x32, 0x1f, 0xf4, 0xee, 0x33, - 0xe4, 0x03, 0xce, 0xa0, 0xde, 0x9e, 0xd9, 0x59, 0xcc, 0x6c, 0x1b, 0xba, 0x2c, 0x7d, 0xc7, 0x44, - 0xde, 0x7a, 0x22, 0x5f, 0x65, 0xfb, 0x0a, 0x78, 0xee, 0x57, 0xba, 0x7d, 0x2a, 0x92, 0xf2, 0x47, - 0x50, 0xda, 0xa6, 0x8c, 0x8a, 0x6a, 0x83, 0x06, 0xc3, 0x5c, 0x49, 0x0d, 0x2d, 0x2f, 0x58, 0x92, - 0xbe, 0x12, 0x41, 0x86, 0x0a, 0xd5, 0x45, 0x3b, 0x1b, 0xe3, 0x2b, 0x0e, 0xc7, 0x29, 0x98, 0x3e, - 0x3c, 0x97, 0xd3, 0x28, 0x73, 0xfc, 0x82, 0xc7, 0xb4, 0xf4, 0x6b, 0xfd, 0xa5, 0x14, 0x9e, 0x8f] -dsa_sub_prime_3072_256 = [0xf3, 0x96, 0x52, 0xd0, 0x0e, 0xf7, 0x96, 0x2d, 0xae, 0x7d, 0x8a, 0x13, 0xa8, 0x09, 0xa8, +dsa_prime_3072_256 = [0xa0, 0x38, 0x3e, 0xe6, 0x92, 0xf8, 0xf5, 0xba, 0xdd, 0xf9, 0x31, 0x7b, 0x16, + 0xed, 0xd2, 0x84, + 0xa3, 0x63, 0x19, 0xb0, 0x53, 0xf7, 0x3a, 0xd4, 0x31, 0xae, 0x4b, 0x5d, 0xb2, + 0xc6, 0x63, 0x0b, + 0x5a, 0xbf, 0xe8, 0xc5, 0xcb, 0x9d, 0x23, 0x06, 0x50, 0xdc, 0x72, 0xee, 0xfb, + 0xe6, 0xf2, 0x61, + 0xdb, 0x2f, 0x43, 0xe6, 0x83, 0x81, 0x58, 0x8c, 0xfd, 0x4a, 0x74, 0x51, 0xbb, + 0xbb, 0x30, 0xc5, + 0x95, 0x21, 0xd7, 0x8e, 0xa7, 0x6d, 0xc0, 0x70, 0xcf, 0x81, 0x78, 0x33, 0x19, + 0x9f, 0xf7, 0x15, + 0xcb, 0xd1, 0x12, 0xa2, 0x58, 0x50, 0x69, 0x35, 0x44, 0x66, 0x2e, 0x12, 0xbb, + 0x27, 0x93, 0xa8, + 0x14, 0x84, 0x77, 0x64, 0xac, 0x27, 0x7c, 0x5c, 0xf0, 0x6b, 0x3e, 0x04, 0x4a, + 0x45, 0x91, 0x3e, + 0xdd, 0x61, 0x92, 0x29, 0xdd, 0xd7, 0x28, 0x93, 0x14, 0xd0, 0x0b, 0xb6, 0xa7, + 0xda, 0xf1, 0x7e, + 0xb8, 0x63, 0xf3, 0x1d, 0xc2, 0x2c, 0xcc, 0x05, 0xf6, 0x14, 0xc1, 0xbb, 0x0c, + 0xea, 0x4c, 0x45, + 0x4f, 0xc6, 0xa0, 0x29, 0xc0, 0xd2, 0x56, 0x8d, 0x1c, 0x5e, 0xef, 0x7f, 0x7c, + 0x41, 0xf1, 0xb6, + 0x59, 0xce, 0xd9, 0x24, 0xdd, 0x0e, 0xab, 0xc7, 0xc9, 0xbc, 0x3a, 0x55, 0x90, + 0xd4, 0x03, 0x12, + 0xe3, 0xec, 0x13, 0xa2, 0xca, 0xa1, 0x80, 0xed, 0x6b, 0x0c, 0x7d, 0x54, 0xd1, + 0x63, 0xca, 0x1f, + 0x32, 0xcd, 0x89, 0x27, 0xa0, 0xfd, 0x39, 0x4e, 0x51, 0xde, 0xf2, 0xa3, 0x1e, + 0x83, 0xfc, 0x53, + 0x73, 0xbe, 0xf8, 0xd2, 0x5f, 0x65, 0x32, 0xef, 0x51, 0x5f, 0x86, 0x7b, 0x0b, + 0x31, 0x73, 0x8f, + 0xf2, 0x7f, 0xac, 0xad, 0x0d, 0xfb, 0x40, 0xe7, 0x6b, 0x68, 0x3a, 0x3b, 0x11, + 0xc9, 0x9f, 0x59, + 0xc8, 0xa4, 0x98, 0xba, 0x2b, 0x88, 0x08, 0x70, 0x0f, 0x20, 0x15, 0x14, 0x5c, + 0x77, 0xdb, 0xa4, + 0x20, 0xc5, 0xf0, 0xdb, 0x95, 0xac, 0x88, 0x03, 0x6a, 0x40, 0x90, 0x4a, 0x53, + 0xb3, 0x80, 0xaa, + 0x0c, 0x75, 0x80, 0x5a, 0x0d, 0xfd, 0xad, 0x4c, 0xbe, 0xaa, 0x48, 0x91, 0xab, + 0xd8, 0x4d, 0x24, + 0xbb, 0x64, 0x4d, 0x96, 0xc5, 0x9f, 0x33, 0x9e, 0x01, 0x6b, 0xb4, 0x32, 0x1f, + 0xf4, 0xee, 0x33, + 0xe4, 0x03, 0xce, 0xa0, 0xde, 0x9e, 0xd9, 0x59, 0xcc, 0x6c, 0x1b, 0xba, 0x2c, + 0x7d, 0xc7, 0x44, + 0xde, 0x7a, 0x22, 0x5f, 0x65, 0xfb, 0x0a, 0x78, 0xee, 0x57, 0xba, 0x7d, 0x2a, + 0x92, 0xf2, 0x47, + 0x50, 0xda, 0xa6, 0x8c, 0x8a, 0x6a, 0x83, 0x06, 0xc3, 0x5c, 0x49, 0x0d, 0x2d, + 0x2f, 0x58, 0x92, + 0xbe, 0x12, 0x41, 0x86, 0x0a, 0xd5, 0x45, 0x3b, 0x1b, 0xe3, 0x2b, 0x0e, 0xc7, + 0x29, 0x98, 0x3e, + 0x3c, 0x97, 0xd3, 0x28, 0x73, 0xfc, 0x82, 0xc7, 0xb4, 0xf4, 0x6b, 0xfd, 0xa5, + 0x14, 0x9e, 0x8f] +dsa_sub_prime_3072_256 = [0xf3, 0x96, 0x52, 0xd0, 0x0e, 0xf7, 0x96, 0x2d, 0xae, 0x7d, 0x8a, 0x13, + 0xa8, 0x09, 0xa8, 0x14, - 0xc5, 0xe4, 0xf9, 0xba, 0x8e, 0x6d, 0xea, 0x3d, 0x18, 0xf3, 0x51, 0x48, 0x04, 0xfc, 0xe1, + 0xc5, 0xe4, 0xf9, 0xba, 0x8e, 0x6d, 0xea, 0x3d, 0x18, 0xf3, 0x51, 0x48, + 0x04, 0xfc, 0xe1, 0x37] -dsa_base_3072_256 = [0x07, 0x1f, 0x94, 0x97, 0xf8, 0x58, 0x85, 0x5e, 0xa6, 0x1f, 0xa8, 0x05, 0x97, 0x34, 0xc0, 0x12, - 0x2a, 0xc9, 0x1c, 0xb9, 0xf8, 0x1d, 0xfd, 0x8f, 0xa6, 0xec, 0xc0, 0x83, 0xf6, 0x0c, 0xb3, 0x0e, - 0xa8, 0x0b, 0x15, 0x56, 0xe5, 0xc3, 0x90, 0xd0, 0x06, 0x73, 0x24, 0x68, 0x28, 0xd4, 0xbc, 0xed, - 0xa1, 0x84, 0x89, 0x15, 0xab, 0x86, 0xff, 0x24, 0x56, 0x8e, 0x40, 0x02, 0x03, 0x99, 0xbd, 0xb9, - 0xf6, 0x75, 0x12, 0x59, 0x51, 0xad, 0x1e, 0x57, 0x1d, 0xd4, 0xf2, 0x23, 0x46, 0x14, 0x89, 0xab, - 0x65, 0x45, 0x04, 0x40, 0xe2, 0x2b, 0x01, 0xb8, 0xf5, 0x9b, 0x9b, 0x38, 0x69, 0x2f, 0x12, 0x0b, - 0x98, 0x34, 0xdd, 0x28, 0xeb, 0x9f, 0xf0, 0x8a, 0xfc, 0x44, 0x98, 0xe1, 0x72, 0xeb, 0x3d, 0x54, - 0xb2, 0x8a, 0x8e, 0xb1, 0x00, 0xab, 0x50, 0xa5, 0x66, 0x7b, 0x9a, 0x9e, 0x8a, 0xad, 0x3f, 0x68, - 0xf1, 0xde, 0xb1, 0x04, 0x60, 0x4a, 0x3d, 0x2e, 0x0f, 0x25, 0x0a, 0x9c, 0x18, 0x8b, 0x74, 0x61, - 0xec, 0xd7, 0xde, 0xc6, 0x56, 0xb5, 0x77, 0xe8, 0x46, 0x7e, 0x46, 0x4e, 0x11, 0xac, 0x49, 0x44, - 0x97, 0x88, 0x65, 0xcd, 0xf5, 0x63, 0xaa, 0xb6, 0xa2, 0xe6, 0x8a, 0x29, 0x53, 0x95, 0x2b, 0x0a, - 0x68, 0xe8, 0x81, 0x48, 0x6e, 0x76, 0x34, 0xd4, 0x91, 0x8d, 0xf9, 0x70, 0xa7, 0xce, 0x0d, 0x60, - 0x8a, 0x92, 0x70, 0x8e, 0x49, 0x52, 0x12, 0xfd, 0x4b, 0x26, 0x79, 0x0d, 0x5c, 0x07, 0xdd, 0x5a, - 0xb5, 0x5a, 0xe8, 0x20, 0x9b, 0x63, 0x19, 0x05, 0x55, 0xc0, 0x43, 0xb7, 0x80, 0x2f, 0xae, 0x78, - 0x79, 0x7e, 0x4f, 0x63, 0xf1, 0xcb, 0x18, 0x09, 0xaf, 0x4a, 0xfc, 0x60, 0xb2, 0xb4, 0xaf, 0x78, - 0xba, 0xb3, 0xad, 0x9c, 0xcc, 0x39, 0x10, 0x08, 0x96, 0x43, 0x8e, 0x67, 0x91, 0xae, 0xec, 0x90, - 0xe8, 0x99, 0xf9, 0x76, 0x59, 0x45, 0x4f, 0x4c, 0x75, 0x96, 0x33, 0xb0, 0xd8, 0x57, 0xb5, 0x05, - 0x12, 0x45, 0x15, 0xc7, 0x5e, 0x3a, 0x64, 0x90, 0xe7, 0x16, 0x8c, 0x73, 0xfa, 0x15, 0x68, 0xe8, - 0xc9, 0x04, 0xb0, 0x42, 0x49, 0xfa, 0x31, 0xa8, 0x3c, 0x6d, 0x83, 0x8a, 0xf7, 0xd4, 0x2d, 0x48, - 0x71, 0x09, 0x89, 0xf9, 0xfb, 0xc9, 0xc3, 0x7b, 0x2c, 0x87, 0x91, 0x57, 0xc9, 0xe9, 0x81, 0x8e, - 0xa4, 0xdd, 0xb7, 0x7a, 0x1f, 0xbc, 0x66, 0x3e, 0xd8, 0x2d, 0xe8, 0x38, 0xc3, 0xab, 0x3b, 0x82, - 0xc5, 0x7d, 0xd0, 0xff, 0xbf, 0xa4, 0x95, 0xe6, 0xea, 0xd3, 0x3e, 0x44, 0x05, 0xd0, 0x58, 0xe9, - 0xb3, 0x7b, 0x3a, 0x71, 0xce, 0xbd, 0xe4, 0x2f, 0x4d, 0x33, 0x46, 0xb4, 0xc5, 0xf9, 0xd6, 0x49, - 0x8b, 0x73, 0xbc, 0x1b, 0x9f, 0x0d, 0x3d, 0x0c, 0x49, 0x29, 0x42, 0x99, 0x70, 0xe9, 0xc5, 0xeb] +dsa_base_3072_256 = [0x07, 0x1f, 0x94, 0x97, 0xf8, 0x58, 0x85, 0x5e, 0xa6, 0x1f, 0xa8, 0x05, 0x97, + 0x34, 0xc0, 0x12, + 0x2a, 0xc9, 0x1c, 0xb9, 0xf8, 0x1d, 0xfd, 0x8f, 0xa6, 0xec, 0xc0, 0x83, 0xf6, + 0x0c, 0xb3, 0x0e, + 0xa8, 0x0b, 0x15, 0x56, 0xe5, 0xc3, 0x90, 0xd0, 0x06, 0x73, 0x24, 0x68, 0x28, + 0xd4, 0xbc, 0xed, + 0xa1, 0x84, 0x89, 0x15, 0xab, 0x86, 0xff, 0x24, 0x56, 0x8e, 0x40, 0x02, 0x03, + 0x99, 0xbd, 0xb9, + 0xf6, 0x75, 0x12, 0x59, 0x51, 0xad, 0x1e, 0x57, 0x1d, 0xd4, 0xf2, 0x23, 0x46, + 0x14, 0x89, 0xab, + 0x65, 0x45, 0x04, 0x40, 0xe2, 0x2b, 0x01, 0xb8, 0xf5, 0x9b, 0x9b, 0x38, 0x69, + 0x2f, 0x12, 0x0b, + 0x98, 0x34, 0xdd, 0x28, 0xeb, 0x9f, 0xf0, 0x8a, 0xfc, 0x44, 0x98, 0xe1, 0x72, + 0xeb, 0x3d, 0x54, + 0xb2, 0x8a, 0x8e, 0xb1, 0x00, 0xab, 0x50, 0xa5, 0x66, 0x7b, 0x9a, 0x9e, 0x8a, + 0xad, 0x3f, 0x68, + 0xf1, 0xde, 0xb1, 0x04, 0x60, 0x4a, 0x3d, 0x2e, 0x0f, 0x25, 0x0a, 0x9c, 0x18, + 0x8b, 0x74, 0x61, + 0xec, 0xd7, 0xde, 0xc6, 0x56, 0xb5, 0x77, 0xe8, 0x46, 0x7e, 0x46, 0x4e, 0x11, + 0xac, 0x49, 0x44, + 0x97, 0x88, 0x65, 0xcd, 0xf5, 0x63, 0xaa, 0xb6, 0xa2, 0xe6, 0x8a, 0x29, 0x53, + 0x95, 0x2b, 0x0a, + 0x68, 0xe8, 0x81, 0x48, 0x6e, 0x76, 0x34, 0xd4, 0x91, 0x8d, 0xf9, 0x70, 0xa7, + 0xce, 0x0d, 0x60, + 0x8a, 0x92, 0x70, 0x8e, 0x49, 0x52, 0x12, 0xfd, 0x4b, 0x26, 0x79, 0x0d, 0x5c, + 0x07, 0xdd, 0x5a, + 0xb5, 0x5a, 0xe8, 0x20, 0x9b, 0x63, 0x19, 0x05, 0x55, 0xc0, 0x43, 0xb7, 0x80, + 0x2f, 0xae, 0x78, + 0x79, 0x7e, 0x4f, 0x63, 0xf1, 0xcb, 0x18, 0x09, 0xaf, 0x4a, 0xfc, 0x60, 0xb2, + 0xb4, 0xaf, 0x78, + 0xba, 0xb3, 0xad, 0x9c, 0xcc, 0x39, 0x10, 0x08, 0x96, 0x43, 0x8e, 0x67, 0x91, + 0xae, 0xec, 0x90, + 0xe8, 0x99, 0xf9, 0x76, 0x59, 0x45, 0x4f, 0x4c, 0x75, 0x96, 0x33, 0xb0, 0xd8, + 0x57, 0xb5, 0x05, + 0x12, 0x45, 0x15, 0xc7, 0x5e, 0x3a, 0x64, 0x90, 0xe7, 0x16, 0x8c, 0x73, 0xfa, + 0x15, 0x68, 0xe8, + 0xc9, 0x04, 0xb0, 0x42, 0x49, 0xfa, 0x31, 0xa8, 0x3c, 0x6d, 0x83, 0x8a, 0xf7, + 0xd4, 0x2d, 0x48, + 0x71, 0x09, 0x89, 0xf9, 0xfb, 0xc9, 0xc3, 0x7b, 0x2c, 0x87, 0x91, 0x57, 0xc9, + 0xe9, 0x81, 0x8e, + 0xa4, 0xdd, 0xb7, 0x7a, 0x1f, 0xbc, 0x66, 0x3e, 0xd8, 0x2d, 0xe8, 0x38, 0xc3, + 0xab, 0x3b, 0x82, + 0xc5, 0x7d, 0xd0, 0xff, 0xbf, 0xa4, 0x95, 0xe6, 0xea, 0xd3, 0x3e, 0x44, 0x05, + 0xd0, 0x58, 0xe9, + 0xb3, 0x7b, 0x3a, 0x71, 0xce, 0xbd, 0xe4, 0x2f, 0x4d, 0x33, 0x46, 0xb4, 0xc5, + 0xf9, 0xd6, 0x49, + 0x8b, 0x73, 0xbc, 0x1b, 0x9f, 0x0d, 0x3d, 0x0c, 0x49, 0x29, 0x42, 0x99, 0x70, + 0xe9, 0xc5, 0xeb] CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN: True, CKA_PRIVATE: True, @@ -391,30 +602,54 @@ CKA_EXTRACTABLE: True, CKA_LABEL: "DSA Public Key"} -dh_prime = [0xF4, 0x88, 0xFD, 0x58, 0x4E, 0x49, 0xDB, 0xCD, 0x20, 0xB4, 0x9D, 0xE4, 0x91, 0x07, 0x36, 0x6B, - 0x33, 0x6C, 0x38, 0x0D, 0x45, 0x1D, 0x0F, 0x7C, 0x88, 0xB3, 0x1C, 0x7C, 0x5B, 0x2D, 0x8E, 0xF6, - 0xF3, 0xC9, 0x23, 0xC0, 0x43, 0xF0, 0xA5, 0x5B, 0x18, 0x8D, 0x8E, 0xBB, 0x55, 0x8C, 0xB8, 0x5D, - 0x38, 0xD3, 0x34, 0xFD, 0x7C, 0x17, 0x57, 0x43, 0xA3, 0x1D, 0x18, 0x6C, 0xDE, 0x33, 0x21, 0x2C, - 0xB5, 0x2A, 0xFF, 0x3C, 0xE1, 0xB1, 0x29, 0x40, 0x18, 0x11, 0x8D, 0x7C, 0x84, 0xA7, 0x0A, 0x72, - 0xD6, 0x86, 0xC4, 0x03, 0x19, 0xC8, 0x07, 0x29, 0x7A, 0xCA, 0x95, 0x0C, 0xD9, 0x96, 0x9F, 0xAB, - 0xD0, 0x0A, 0x50, 0x9B, 0x02, 0x46, 0xD3, 0x08, 0x3D, 0x66, 0xA4, 0x5D, 0x41, 0x9F, 0x9C, 0x7C, - 0xBD, 0x89, 0x4B, 0x22, 0x19, 0x26, 0xBA, 0xAB, 0xA2, 0x5E, 0xC3, 0x55, 0xE9, 0x2F, 0x78, 0xC7] -dh_prime_2048 = [0xF1, 0x20, 0xB5, 0x5B, 0x3A, 0xE4, 0xD0, 0xF6, 0xEF, 0xA4, 0xF2, 0x9F, 0xC4, 0xDF, 0x86, 0x84, - 0x57, 0x54, 0x14, 0x90, 0x98, 0xBD, 0x3E, 0x57, 0x86, 0xE8, 0xC9, 0xA0, 0x30, 0xAF, 0xE6, 0xA7, - 0x6D, 0x7E, 0x4F, 0xDA, 0x20, 0x87, 0x46, 0x0C, 0xED, 0x88, 0xDC, 0xDB, 0x95, 0xDE, 0xD3, 0x4F, - 0xC7, 0x18, 0x80, 0x3A, 0x0D, 0xD2, 0xF1, 0x54, 0x5C, 0xD2, 0x29, 0x78, 0x3C, 0xE4, 0x40, 0x0C, - 0x1A, 0x6B, 0x36, 0x73, 0x42, 0xE1, 0xB3, 0xD3, 0xEB, 0x95, 0xDB, 0x7A, 0x06, 0xD6, 0x54, 0x11, - 0xDB, 0x0B, 0xB3, 0x00, 0x52, 0xA5, 0x74, 0x77, 0x5B, 0x47, 0x2A, 0x6E, 0x31, 0xCB, 0x8A, 0x5D, - 0x1C, 0x8A, 0x7D, 0x93, 0x7A, 0xC3, 0x62, 0x44, 0xC3, 0x29, 0x40, 0x6D, 0x3E, 0x47, 0x62, 0x2F, - 0x93, 0xCD, 0xF3, 0xED, 0xA6, 0x1E, 0x1D, 0x57, 0x4E, 0xFF, 0x5F, 0x46, 0x92, 0xCC, 0xFC, 0x7E, - 0x98, 0x8C, 0xE8, 0xB0, 0xAA, 0x33, 0x70, 0x96, 0x3D, 0xC1, 0x5B, 0x10, 0x2A, 0x07, 0x34, 0x84, - 0x4E, 0xCD, 0xEB, 0xD7, 0x15, 0x63, 0x8C, 0xC4, 0x67, 0xB0, 0xC1, 0xB9, 0xB8, 0x45, 0xB0, 0x3B, - 0x3A, 0x76, 0x83, 0x2C, 0xF5, 0x28, 0xB3, 0xF7, 0x10, 0x23, 0x7E, 0xAA, 0xF6, 0xE6, 0x8B, 0xE7, - 0x57, 0x35, 0x1F, 0x51, 0x34, 0x58, 0x5E, 0x0C, 0x2D, 0x36, 0xCF, 0xA3, 0x85, 0x34, 0xB0, 0x14, - 0x7D, 0xD0, 0x8C, 0x34, 0xBB, 0xC1, 0x8D, 0x49, 0x8C, 0xDA, 0x41, 0x48, 0x66, 0xDB, 0x41, 0xE1, - 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, 0x30, 0xD5, - 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, 0x19, 0x49, - 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, 0x05, 0x9B] +dh_prime = [0xF4, 0x88, 0xFD, 0x58, 0x4E, 0x49, 0xDB, 0xCD, 0x20, 0xB4, 0x9D, 0xE4, 0x91, 0x07, + 0x36, 0x6B, + 0x33, 0x6C, 0x38, 0x0D, 0x45, 0x1D, 0x0F, 0x7C, 0x88, 0xB3, 0x1C, 0x7C, 0x5B, 0x2D, + 0x8E, 0xF6, + 0xF3, 0xC9, 0x23, 0xC0, 0x43, 0xF0, 0xA5, 0x5B, 0x18, 0x8D, 0x8E, 0xBB, 0x55, 0x8C, + 0xB8, 0x5D, + 0x38, 0xD3, 0x34, 0xFD, 0x7C, 0x17, 0x57, 0x43, 0xA3, 0x1D, 0x18, 0x6C, 0xDE, 0x33, + 0x21, 0x2C, + 0xB5, 0x2A, 0xFF, 0x3C, 0xE1, 0xB1, 0x29, 0x40, 0x18, 0x11, 0x8D, 0x7C, 0x84, 0xA7, + 0x0A, 0x72, + 0xD6, 0x86, 0xC4, 0x03, 0x19, 0xC8, 0x07, 0x29, 0x7A, 0xCA, 0x95, 0x0C, 0xD9, 0x96, + 0x9F, 0xAB, + 0xD0, 0x0A, 0x50, 0x9B, 0x02, 0x46, 0xD3, 0x08, 0x3D, 0x66, 0xA4, 0x5D, 0x41, 0x9F, + 0x9C, 0x7C, + 0xBD, 0x89, 0x4B, 0x22, 0x19, 0x26, 0xBA, 0xAB, 0xA2, 0x5E, 0xC3, 0x55, 0xE9, 0x2F, + 0x78, 0xC7] +dh_prime_2048 = [0xF1, 0x20, 0xB5, 0x5B, 0x3A, 0xE4, 0xD0, 0xF6, 0xEF, 0xA4, 0xF2, 0x9F, 0xC4, 0xDF, + 0x86, 0x84, + 0x57, 0x54, 0x14, 0x90, 0x98, 0xBD, 0x3E, 0x57, 0x86, 0xE8, 0xC9, 0xA0, 0x30, 0xAF, + 0xE6, 0xA7, + 0x6D, 0x7E, 0x4F, 0xDA, 0x20, 0x87, 0x46, 0x0C, 0xED, 0x88, 0xDC, 0xDB, 0x95, 0xDE, + 0xD3, 0x4F, + 0xC7, 0x18, 0x80, 0x3A, 0x0D, 0xD2, 0xF1, 0x54, 0x5C, 0xD2, 0x29, 0x78, 0x3C, 0xE4, + 0x40, 0x0C, + 0x1A, 0x6B, 0x36, 0x73, 0x42, 0xE1, 0xB3, 0xD3, 0xEB, 0x95, 0xDB, 0x7A, 0x06, 0xD6, + 0x54, 0x11, + 0xDB, 0x0B, 0xB3, 0x00, 0x52, 0xA5, 0x74, 0x77, 0x5B, 0x47, 0x2A, 0x6E, 0x31, 0xCB, + 0x8A, 0x5D, + 0x1C, 0x8A, 0x7D, 0x93, 0x7A, 0xC3, 0x62, 0x44, 0xC3, 0x29, 0x40, 0x6D, 0x3E, 0x47, + 0x62, 0x2F, + 0x93, 0xCD, 0xF3, 0xED, 0xA6, 0x1E, 0x1D, 0x57, 0x4E, 0xFF, 0x5F, 0x46, 0x92, 0xCC, + 0xFC, 0x7E, + 0x98, 0x8C, 0xE8, 0xB0, 0xAA, 0x33, 0x70, 0x96, 0x3D, 0xC1, 0x5B, 0x10, 0x2A, 0x07, + 0x34, 0x84, + 0x4E, 0xCD, 0xEB, 0xD7, 0x15, 0x63, 0x8C, 0xC4, 0x67, 0xB0, 0xC1, 0xB9, 0xB8, 0x45, + 0xB0, 0x3B, + 0x3A, 0x76, 0x83, 0x2C, 0xF5, 0x28, 0xB3, 0xF7, 0x10, 0x23, 0x7E, 0xAA, 0xF6, 0xE6, + 0x8B, 0xE7, + 0x57, 0x35, 0x1F, 0x51, 0x34, 0x58, 0x5E, 0x0C, 0x2D, 0x36, 0xCF, 0xA3, 0x85, 0x34, + 0xB0, 0x14, + 0x7D, 0xD0, 0x8C, 0x34, 0xBB, 0xC1, 0x8D, 0x49, 0x8C, 0xDA, 0x41, 0x48, 0x66, 0xDB, + 0x41, 0xE1, + 0xAE, 0x41, 0x9B, 0xCB, 0x6E, 0x78, 0x92, 0x0B, 0x60, 0x17, 0x4B, 0xE8, 0x15, 0x40, + 0x30, 0xD5, + 0x06, 0xFD, 0xA3, 0x9C, 0xA1, 0xA9, 0xC2, 0xA6, 0x46, 0xF5, 0xEA, 0xE6, 0x4E, 0xF4, + 0x19, 0x49, + 0x4A, 0x5C, 0x90, 0xE4, 0x6B, 0xF8, 0x04, 0xF5, 0xB6, 0xB7, 0xF9, 0x92, 0x3D, 0x5F, + 0x05, 0x9B] CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_DERIVE: True, @@ -495,7 +730,8 @@ CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP = {CKA_TOKEN: True, CKA_DERIVE: True, - CKA_ENCRYPT: 0x1001, # TODO, is encrypt both a long and a boolean, uh oh + CKA_ENCRYPT: 0x1001, + # TODO, is encrypt both a long and a boolean, uh oh CKA_LABEL: "SSL3 Pre Master Key"} ''' @@ -517,14 +753,19 @@ 'secp521r1(P-521)': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23], # [84] OID_secp521r1 'X9_62_prime192v1(P-192)': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01], -# [91] OID_X9_62_prime192v1 - 'X9_62_prime192v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], # [101] OID_X9_62_prime192v2 - 'X9_62_prime192v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], # [111] OID_X9_62_prime192v3 - 'X9_62_prime239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], # [121] OID_X9_62_prime239v1 - 'X9_62_prime239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], # [131] OID_X9_62_prime239v2 - 'X9_62_prime239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], # [141] OID_X9_62_prime239v3 + # [91] OID_X9_62_prime192v1 + 'X9_62_prime192v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], +# [101] OID_X9_62_prime192v2 + 'X9_62_prime192v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], +# [111] OID_X9_62_prime192v3 + 'X9_62_prime239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], +# [121] OID_X9_62_prime239v1 + 'X9_62_prime239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], +# [131] OID_X9_62_prime239v2 + 'X9_62_prime239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], +# [141] OID_X9_62_prime239v3 'X9_62_prime256v1(P-256)': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], -# [151] OID_X9_62_prime256v1 + # [151] OID_X9_62_prime256v1 'sect113r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x04], # [161] OID_sect113r1 'sect113r2': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x05], # [168] OID_sect113r2 @@ -545,37 +786,67 @@ 'sect571k1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x26], # [273] OID_sect571k1 'sect571r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x27], # [280] OID_sect571r1 - 'X9_62_c2pnb163v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], # [287] OID_X9_62_c2pnb163v1 - 'X9_62_c2pnb163v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], # [297] OID_X9_62_c2pnb163v2 - 'X9_62_c2pnb163v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], # [307] OID_X9_62_c2pnb163v3 - 'X9_62_c2pnb176v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], # [317] OID_X9_62_c2pnb176v1 - 'X9_62_c2tnb191v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], # [327] OID_X9_62_c2tnb191v1 - 'X9_62_c2tnb191v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], # [337] OID_X9_62_c2tnb191v2 - 'X9_62_c2tnb191v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], # [347] OID_X9_62_c2tnb191v3 - 'X9_62_c2pnb208w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], # [357] OID_X9_62_c2pnb208w1 - 'X9_62_c2tnb239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], # [367] OID_X9_62_c2tnb239v1 - 'X9_62_c2tnb239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], # [377] OID_X9_62_c2tnb239v2 - 'X9_62_c2tnb239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], # [387] OID_X9_62_c2tnb239v3 - 'X9_62_c2pnb272w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], # [397] OID_X9_62_c2pnb272w1 - 'X9_62_c2pnb304w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], # [407] OID_X9_62_c2pnb304w1 - 'X9_62_c2tnb359v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], # [417] OID_X9_62_c2tnb359v1 - 'X9_62_c2pnb368w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], # [427] OID_X9_62_c2pnb368w1 - 'X9_62_c2tnb431r1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], # [437] OID_X9_62_c2tnb431r1 + 'X9_62_c2pnb163v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], +# [287] OID_X9_62_c2pnb163v1 + 'X9_62_c2pnb163v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], +# [297] OID_X9_62_c2pnb163v2 + 'X9_62_c2pnb163v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], +# [307] OID_X9_62_c2pnb163v3 + 'X9_62_c2pnb176v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], +# [317] OID_X9_62_c2pnb176v1 + 'X9_62_c2tnb191v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], +# [327] OID_X9_62_c2tnb191v1 + 'X9_62_c2tnb191v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], +# [337] OID_X9_62_c2tnb191v2 + 'X9_62_c2tnb191v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], +# [347] OID_X9_62_c2tnb191v3 + 'X9_62_c2pnb208w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], +# [357] OID_X9_62_c2pnb208w1 + 'X9_62_c2tnb239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], +# [367] OID_X9_62_c2tnb239v1 + 'X9_62_c2tnb239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], +# [377] OID_X9_62_c2tnb239v2 + 'X9_62_c2tnb239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], +# [387] OID_X9_62_c2tnb239v3 + 'X9_62_c2pnb272w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], +# [397] OID_X9_62_c2pnb272w1 + 'X9_62_c2pnb304w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], +# [407] OID_X9_62_c2pnb304w1 + 'X9_62_c2tnb359v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], +# [417] OID_X9_62_c2tnb359v1 + 'X9_62_c2pnb368w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], +# [427] OID_X9_62_c2pnb368w1 + 'X9_62_c2tnb431r1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], +# [437] OID_X9_62_c2tnb431r1 - 'brainpoolP160r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], # [447] brainpoolP160r1 - 'brainpoolP160t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], # [458] brainpoolP160t1 - 'brainpoolP192r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], # [469] brainpoolP192r1 - 'brainpoolP192t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], # [480] brainpoolP192t1 - 'brainpoolP224r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], # [491] brainpoolP224r1 - 'brainpoolP224t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], # [502] brainpoolP224t1 - 'brainpoolP256r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], # [513] brainpoolP256r1 - 'brainpoolP256t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], # [524] brainpoolP256t1 - 'brainpoolP320r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], # [535] brainpoolP320r1 - 'brainpoolP320t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], # [546] brainpoolP320t1 - 'brainpoolP384r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], # [557] brainpoolP384r1 - 'brainpoolP384t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], # [568] brainpoolP384t1 - 'brainpoolP512r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], # [579] brainpoolP512r1 - 'brainpoolP512t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], # [590] brainpoolP512t1 + 'brainpoolP160r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], +# [447] brainpoolP160r1 + 'brainpoolP160t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], +# [458] brainpoolP160t1 + 'brainpoolP192r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], +# [469] brainpoolP192r1 + 'brainpoolP192t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], +# [480] brainpoolP192t1 + 'brainpoolP224r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], +# [491] brainpoolP224r1 + 'brainpoolP224t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], +# [502] brainpoolP224t1 + 'brainpoolP256r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], +# [513] brainpoolP256r1 + 'brainpoolP256t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], +# [524] brainpoolP256t1 + 'brainpoolP320r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], +# [535] brainpoolP320r1 + 'brainpoolP320t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], +# [546] brainpoolP320t1 + 'brainpoolP384r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], +# [557] brainpoolP384r1 + 'brainpoolP384t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], +# [568] brainpoolP384t1 + 'brainpoolP512r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], +# [579] brainpoolP512r1 + 'brainpoolP512t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], +# [590] brainpoolP512t1 'microsoftPlayReadP160': [0x30, 0x81, 0x95, 0x02, 0x01, 0x01, 0x30, 0x20, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, @@ -645,61 +916,112 @@ CKA_EXTRACTABLE: True, CKA_LABEL: "SEED Key"} -kcdsa_prime_1024_160 = [0xdc, 0x02, 0xf3, 0xe0, 0x51, 0x4e, 0xf4, 0x72, 0x36, 0x51, 0x09, 0x72, 0x5c, 0x12, 0x00, 0x50, - 0x69, 0x7d, 0xfc, 0x1d, 0xcb, 0xb4, 0x1f, 0xbc, 0x49, 0x63, 0xc4, 0x15, 0x45, 0x97, 0xb7, 0xae, - 0x8d, 0x4a, 0x35, 0x3c, 0xe2, 0xfb, 0x1f, 0xbf, 0x77, 0x7b, 0x89, 0xe5, 0x56, 0xc5, 0x15, 0x6b, - 0x1a, 0x4a, 0x82, 0xcc, 0xe2, 0xb8, 0xec, 0x4d, 0x61, 0x86, 0xd4, 0xa3, 0xf6, 0xc5, 0x65, 0xae, - 0x8c, 0xf6, 0x04, 0x62, 0x1d, 0x63, 0xec, 0x9f, 0x1e, 0x91, 0x31, 0x39, 0x1d, 0xc0, 0x55, 0xbc, - 0xac, 0xc5, 0x1a, 0xc8, 0x5c, 0x02, 0x93, 0xd7, 0xca, 0x74, 0x4f, 0xe9, 0xa2, 0x04, 0x5c, 0x3c, - 0xc1, 0xb6, 0xe1, 0x4d, 0xcd, 0xfa, 0xbb, 0x7d, 0xf8, 0xa7, 0xb1, 0x94, 0xd5, 0x08, 0xe1, 0x99, - 0xc1, 0x81, 0x62, 0x93, 0xd6, 0x8c, 0x7a, 0x5c, 0x0f, 0x8a, 0xc7, 0x14, 0xb5, 0xd6, 0xf5, 0xa3] -kcdsa_sub_prime_1024_160 = [0xc8, 0xf6, 0x2e, 0x10, 0xf0, 0xa4, 0xe5, 0x43, 0x1b, 0x8e, 0x1b, 0x0f, 0x53, 0xf6, 0x27, +kcdsa_prime_1024_160 = [0xdc, 0x02, 0xf3, 0xe0, 0x51, 0x4e, 0xf4, 0x72, 0x36, 0x51, 0x09, 0x72, + 0x5c, 0x12, 0x00, 0x50, + 0x69, 0x7d, 0xfc, 0x1d, 0xcb, 0xb4, 0x1f, 0xbc, 0x49, 0x63, 0xc4, 0x15, + 0x45, 0x97, 0xb7, 0xae, + 0x8d, 0x4a, 0x35, 0x3c, 0xe2, 0xfb, 0x1f, 0xbf, 0x77, 0x7b, 0x89, 0xe5, + 0x56, 0xc5, 0x15, 0x6b, + 0x1a, 0x4a, 0x82, 0xcc, 0xe2, 0xb8, 0xec, 0x4d, 0x61, 0x86, 0xd4, 0xa3, + 0xf6, 0xc5, 0x65, 0xae, + 0x8c, 0xf6, 0x04, 0x62, 0x1d, 0x63, 0xec, 0x9f, 0x1e, 0x91, 0x31, 0x39, + 0x1d, 0xc0, 0x55, 0xbc, + 0xac, 0xc5, 0x1a, 0xc8, 0x5c, 0x02, 0x93, 0xd7, 0xca, 0x74, 0x4f, 0xe9, + 0xa2, 0x04, 0x5c, 0x3c, + 0xc1, 0xb6, 0xe1, 0x4d, 0xcd, 0xfa, 0xbb, 0x7d, 0xf8, 0xa7, 0xb1, 0x94, + 0xd5, 0x08, 0xe1, 0x99, + 0xc1, 0x81, 0x62, 0x93, 0xd6, 0x8c, 0x7a, 0x5c, 0x0f, 0x8a, 0xc7, 0x14, + 0xb5, 0xd6, 0xf5, 0xa3] +kcdsa_sub_prime_1024_160 = [0xc8, 0xf6, 0x2e, 0x10, 0xf0, 0xa4, 0xe5, 0x43, 0x1b, 0x8e, 0x1b, 0x0f, + 0x53, 0xf6, 0x27, 0xec, 0x6a, 0xd3, 0xa6, 0xa5] -kcdsa_base_1024_160 = [0x9b, 0x8b, 0x4b, 0x16, 0x53, 0x65, 0x03, 0x18, 0x47, 0x19, 0xac, 0x4d, 0x13, 0x2d, 0x14, 0x57, - 0x2d, 0xca, 0x56, 0x45, 0x3f, 0x05, 0x68, 0x68, 0x3b, 0x04, 0x17, 0x27, 0x6f, 0x93, 0x88, 0xdc, - 0x0a, 0x79, 0xe7, 0x76, 0x45, 0x4a, 0x97, 0x7a, 0x02, 0xc0, 0x1a, 0xc7, 0x7a, 0x07, 0x1f, 0x6b, - 0x99, 0x81, 0x67, 0xb8, 0xb9, 0x89, 0xce, 0xfd, 0x88, 0x7a, 0x26, 0x71, 0xf9, 0x44, 0x12, 0xcc, - 0x94, 0xac, 0x62, 0xe7, 0x61, 0xc9, 0x5a, 0xdb, 0x38, 0xf7, 0x8b, 0x76, 0x73, 0xcc, 0x09, 0x0a, - 0x62, 0xcf, 0xab, 0x4b, 0x03, 0x29, 0x0d, 0x34, 0x92, 0xb9, 0x09, 0x83, 0x68, 0x9b, 0x30, 0x82, - 0x1f, 0xcf, 0xb0, 0xdb, 0x83, 0x71, 0x24, 0x2c, 0x73, 0xf3, 0xa6, 0x4f, 0x56, 0xb2, 0x13, 0xfd, - 0xdb, 0xbc, 0xcf, 0x77, 0x5d, 0x01, 0x1f, 0xb8, 0x35, 0x85, 0x4f, 0x88, 0xb0, 0x58, 0x92, 0x07] -kcdsa_prime_2048_256 = [0xec, 0xfe, 0xa3, 0x3f, 0xa2, 0x27, 0xc3, 0xb1, 0xa7, 0xdf, 0xd7, 0xf1, 0xbb, 0x48, 0x7c, 0xd4, - 0x26, 0xab, 0x0a, 0x2b, 0x2b, 0x3a, 0xf1, 0x8f, 0xef, 0x9d, 0x61, 0xcd, 0x4f, 0x7b, 0xbb, 0x8d, - 0x7d, 0x8d, 0x4c, 0x84, 0x13, 0x7a, 0xaf, 0xe5, 0xb5, 0xba, 0x9d, 0xe4, 0xd2, 0xb5, 0x8b, 0x00, - 0x39, 0xbc, 0x66, 0x9c, 0x7c, 0x3d, 0x98, 0x7e, 0x0a, 0x74, 0x1b, 0x06, 0xcf, 0x97, 0xb5, 0x3e, - 0xcb, 0x1e, 0x1d, 0x22, 0x51, 0xe6, 0xd4, 0xe2, 0x72, 0xa7, 0x72, 0xd3, 0x4c, 0x3f, 0xfc, 0xd4, - 0xd5, 0x7c, 0x3f, 0x44, 0xa2, 0x1b, 0xfc, 0x97, 0xad, 0x34, 0xb2, 0x8f, 0xd3, 0xcf, 0x77, 0x89, - 0x7a, 0xce, 0x64, 0xc6, 0x92, 0xaa, 0x69, 0x13, 0xed, 0x22, 0xa2, 0x3b, 0x45, 0x19, 0x98, 0x88, - 0x29, 0x05, 0x7c, 0xd2, 0x33, 0xaf, 0xa1, 0xf7, 0xab, 0x66, 0x40, 0xca, 0x05, 0x7e, 0x16, 0x99, - 0x7a, 0x92, 0xaa, 0x5e, 0x07, 0xc0, 0xc7, 0x3c, 0x82, 0xb4, 0x96, 0x02, 0x23, 0x66, 0x99, 0x97, - 0xa3, 0x40, 0xf1, 0x36, 0x9b, 0x33, 0xc7, 0xbe, 0xe9, 0xac, 0xce, 0x85, 0xf8, 0xbd, 0x6a, 0x26, - 0x0f, 0x79, 0xe7, 0x9e, 0xee, 0xee, 0xd6, 0x82, 0xc8, 0x7d, 0x4b, 0xe7, 0x4c, 0x2f, 0x44, 0x9a, - 0x1b, 0x68, 0x3f, 0xba, 0xe4, 0xfd, 0x19, 0xca, 0xd0, 0x97, 0xd3, 0x71, 0x12, 0x8c, 0x86, 0xbe, - 0x93, 0x84, 0xb7, 0x35, 0x2a, 0xd1, 0x3a, 0x9a, 0x27, 0x8f, 0x36, 0x4f, 0x08, 0x9e, 0x38, 0xdf, - 0x25, 0xe8, 0x4a, 0x70, 0x4d, 0xe4, 0xfb, 0x16, 0x40, 0xa5, 0x19, 0xfc, 0x62, 0x91, 0x76, 0x1d, - 0xab, 0x11, 0xe2, 0xf7, 0x80, 0xe7, 0x1a, 0x62, 0x2e, 0x9a, 0xbf, 0x85, 0xfe, 0x19, 0x4a, 0x45, - 0x79, 0x3b, 0xfa, 0xb3, 0xa1, 0xe9, 0x8a, 0x1d, 0xfd, 0x57, 0xb5, 0xc7, 0x09, 0x79, 0xb8, 0x1b] -kcdsa_sub_prime_2048_256 = [0xe5, 0x7d, 0x48, 0xd4, 0x44, 0x3d, 0x60, 0xb2, 0x6f, 0x48, 0x82, 0x3d, 0x1d, 0xea, 0xce, +kcdsa_base_1024_160 = [0x9b, 0x8b, 0x4b, 0x16, 0x53, 0x65, 0x03, 0x18, 0x47, 0x19, 0xac, 0x4d, 0x13, + 0x2d, 0x14, 0x57, + 0x2d, 0xca, 0x56, 0x45, 0x3f, 0x05, 0x68, 0x68, 0x3b, 0x04, 0x17, 0x27, 0x6f, + 0x93, 0x88, 0xdc, + 0x0a, 0x79, 0xe7, 0x76, 0x45, 0x4a, 0x97, 0x7a, 0x02, 0xc0, 0x1a, 0xc7, 0x7a, + 0x07, 0x1f, 0x6b, + 0x99, 0x81, 0x67, 0xb8, 0xb9, 0x89, 0xce, 0xfd, 0x88, 0x7a, 0x26, 0x71, 0xf9, + 0x44, 0x12, 0xcc, + 0x94, 0xac, 0x62, 0xe7, 0x61, 0xc9, 0x5a, 0xdb, 0x38, 0xf7, 0x8b, 0x76, 0x73, + 0xcc, 0x09, 0x0a, + 0x62, 0xcf, 0xab, 0x4b, 0x03, 0x29, 0x0d, 0x34, 0x92, 0xb9, 0x09, 0x83, 0x68, + 0x9b, 0x30, 0x82, + 0x1f, 0xcf, 0xb0, 0xdb, 0x83, 0x71, 0x24, 0x2c, 0x73, 0xf3, 0xa6, 0x4f, 0x56, + 0xb2, 0x13, 0xfd, + 0xdb, 0xbc, 0xcf, 0x77, 0x5d, 0x01, 0x1f, 0xb8, 0x35, 0x85, 0x4f, 0x88, 0xb0, + 0x58, 0x92, 0x07] +kcdsa_prime_2048_256 = [0xec, 0xfe, 0xa3, 0x3f, 0xa2, 0x27, 0xc3, 0xb1, 0xa7, 0xdf, 0xd7, 0xf1, + 0xbb, 0x48, 0x7c, 0xd4, + 0x26, 0xab, 0x0a, 0x2b, 0x2b, 0x3a, 0xf1, 0x8f, 0xef, 0x9d, 0x61, 0xcd, + 0x4f, 0x7b, 0xbb, 0x8d, + 0x7d, 0x8d, 0x4c, 0x84, 0x13, 0x7a, 0xaf, 0xe5, 0xb5, 0xba, 0x9d, 0xe4, + 0xd2, 0xb5, 0x8b, 0x00, + 0x39, 0xbc, 0x66, 0x9c, 0x7c, 0x3d, 0x98, 0x7e, 0x0a, 0x74, 0x1b, 0x06, + 0xcf, 0x97, 0xb5, 0x3e, + 0xcb, 0x1e, 0x1d, 0x22, 0x51, 0xe6, 0xd4, 0xe2, 0x72, 0xa7, 0x72, 0xd3, + 0x4c, 0x3f, 0xfc, 0xd4, + 0xd5, 0x7c, 0x3f, 0x44, 0xa2, 0x1b, 0xfc, 0x97, 0xad, 0x34, 0xb2, 0x8f, + 0xd3, 0xcf, 0x77, 0x89, + 0x7a, 0xce, 0x64, 0xc6, 0x92, 0xaa, 0x69, 0x13, 0xed, 0x22, 0xa2, 0x3b, + 0x45, 0x19, 0x98, 0x88, + 0x29, 0x05, 0x7c, 0xd2, 0x33, 0xaf, 0xa1, 0xf7, 0xab, 0x66, 0x40, 0xca, + 0x05, 0x7e, 0x16, 0x99, + 0x7a, 0x92, 0xaa, 0x5e, 0x07, 0xc0, 0xc7, 0x3c, 0x82, 0xb4, 0x96, 0x02, + 0x23, 0x66, 0x99, 0x97, + 0xa3, 0x40, 0xf1, 0x36, 0x9b, 0x33, 0xc7, 0xbe, 0xe9, 0xac, 0xce, 0x85, + 0xf8, 0xbd, 0x6a, 0x26, + 0x0f, 0x79, 0xe7, 0x9e, 0xee, 0xee, 0xd6, 0x82, 0xc8, 0x7d, 0x4b, 0xe7, + 0x4c, 0x2f, 0x44, 0x9a, + 0x1b, 0x68, 0x3f, 0xba, 0xe4, 0xfd, 0x19, 0xca, 0xd0, 0x97, 0xd3, 0x71, + 0x12, 0x8c, 0x86, 0xbe, + 0x93, 0x84, 0xb7, 0x35, 0x2a, 0xd1, 0x3a, 0x9a, 0x27, 0x8f, 0x36, 0x4f, + 0x08, 0x9e, 0x38, 0xdf, + 0x25, 0xe8, 0x4a, 0x70, 0x4d, 0xe4, 0xfb, 0x16, 0x40, 0xa5, 0x19, 0xfc, + 0x62, 0x91, 0x76, 0x1d, + 0xab, 0x11, 0xe2, 0xf7, 0x80, 0xe7, 0x1a, 0x62, 0x2e, 0x9a, 0xbf, 0x85, + 0xfe, 0x19, 0x4a, 0x45, + 0x79, 0x3b, 0xfa, 0xb3, 0xa1, 0xe9, 0x8a, 0x1d, 0xfd, 0x57, 0xb5, 0xc7, + 0x09, 0x79, 0xb8, 0x1b] +kcdsa_sub_prime_2048_256 = [0xe5, 0x7d, 0x48, 0xd4, 0x44, 0x3d, 0x60, 0xb2, 0x6f, 0x48, 0x82, 0x3d, + 0x1d, 0xea, 0xce, 0xf2, - 0xb4, 0x4a, 0x6c, 0x47, 0x5b, 0x12, 0x43, 0x47, 0xb4, 0x81, 0x47, 0xf8, 0xa2, 0xfd, 0x33, + 0xb4, 0x4a, 0x6c, 0x47, 0x5b, 0x12, 0x43, 0x47, 0xb4, 0x81, 0x47, 0xf8, + 0xa2, 0xfd, 0x33, 0xd3] -kcdsa_base_2048_256 = [0x68, 0x90, 0xea, 0x6f, 0x5a, 0x56, 0x4f, 0xd2, 0xa1, 0xfe, 0x07, 0xd7, 0xbc, 0xa5, 0xab, 0x80, - 0xf9, 0x5a, 0x5f, 0x47, 0xe9, 0x7f, 0xfc, 0x9a, 0xea, 0x67, 0x13, 0xf8, 0xad, 0x36, 0xe1, 0xfc, - 0x02, 0x42, 0x17, 0xcd, 0xf9, 0xbe, 0x5c, 0xe9, 0xa6, 0xcd, 0xdb, 0x6b, 0x5c, 0x1e, 0x7e, 0x22, - 0x0e, 0xd5, 0x7f, 0x2b, 0x0c, 0x9b, 0xf7, 0xe2, 0xd5, 0x23, 0xc1, 0x45, 0x0b, 0x46, 0x7e, 0x64, - 0x80, 0xc9, 0x6f, 0x9b, 0x20, 0x76, 0xd0, 0x3f, 0xae, 0x8c, 0x4d, 0x99, 0x3e, 0x9c, 0xe6, 0x6b, - 0xc9, 0xb8, 0x39, 0xa5, 0x58, 0x15, 0x6c, 0x69, 0x79, 0x2a, 0xfa, 0x34, 0x76, 0x17, 0x64, 0x6a, - 0x2a, 0x29, 0x4d, 0xce, 0xe4, 0x07, 0x78, 0xa3, 0xcb, 0x93, 0x7a, 0x78, 0x2a, 0x51, 0x91, 0xbd, - 0x42, 0x97, 0x3b, 0x07, 0x31, 0xca, 0x4f, 0x62, 0x2a, 0x63, 0xe0, 0x69, 0x45, 0x31, 0xc8, 0x75, - 0x3e, 0x3a, 0xb0, 0xe8, 0x8d, 0xdc, 0x86, 0x1c, 0x75, 0x1c, 0x25, 0x2e, 0x74, 0x18, 0x89, 0xb3, - 0x3e, 0x39, 0x0e, 0x1c, 0xa5, 0xc4, 0x75, 0x1f, 0x31, 0x1e, 0x19, 0x61, 0x5b, 0xbe, 0xa7, 0x18, - 0x9b, 0x04, 0xf2, 0x29, 0xc8, 0xe7, 0x40, 0x84, 0x39, 0xd2, 0x28, 0xa5, 0x30, 0x5b, 0x22, 0x78, - 0x33, 0xab, 0xa8, 0x30, 0x98, 0x1c, 0x33, 0xec, 0xfe, 0xe7, 0x90, 0x8c, 0x6d, 0x39, 0x54, 0x42, - 0x9b, 0xef, 0x30, 0xde, 0xa1, 0x15, 0xfe, 0xe6, 0xd0, 0x3f, 0x13, 0xf0, 0xa0, 0x2e, 0xb2, 0x19, - 0xe4, 0xb9, 0xb0, 0xba, 0xac, 0x32, 0xc2, 0x24, 0x0b, 0x2a, 0x47, 0x17, 0xda, 0x7c, 0x11, 0x6c, - 0xe2, 0x09, 0x24, 0x71, 0x30, 0xac, 0x14, 0x0c, 0xd3, 0xab, 0xdc, 0xe7, 0x78, 0xa4, 0x27, 0x27, - 0xf3, 0x2c, 0xfa, 0xfd, 0xae, 0x9e, 0x51, 0x68, 0x47, 0xb2, 0x6c, 0xe4, 0xcb, 0xb7, 0x66, 0x03] +kcdsa_base_2048_256 = [0x68, 0x90, 0xea, 0x6f, 0x5a, 0x56, 0x4f, 0xd2, 0xa1, 0xfe, 0x07, 0xd7, 0xbc, + 0xa5, 0xab, 0x80, + 0xf9, 0x5a, 0x5f, 0x47, 0xe9, 0x7f, 0xfc, 0x9a, 0xea, 0x67, 0x13, 0xf8, 0xad, + 0x36, 0xe1, 0xfc, + 0x02, 0x42, 0x17, 0xcd, 0xf9, 0xbe, 0x5c, 0xe9, 0xa6, 0xcd, 0xdb, 0x6b, 0x5c, + 0x1e, 0x7e, 0x22, + 0x0e, 0xd5, 0x7f, 0x2b, 0x0c, 0x9b, 0xf7, 0xe2, 0xd5, 0x23, 0xc1, 0x45, 0x0b, + 0x46, 0x7e, 0x64, + 0x80, 0xc9, 0x6f, 0x9b, 0x20, 0x76, 0xd0, 0x3f, 0xae, 0x8c, 0x4d, 0x99, 0x3e, + 0x9c, 0xe6, 0x6b, + 0xc9, 0xb8, 0x39, 0xa5, 0x58, 0x15, 0x6c, 0x69, 0x79, 0x2a, 0xfa, 0x34, 0x76, + 0x17, 0x64, 0x6a, + 0x2a, 0x29, 0x4d, 0xce, 0xe4, 0x07, 0x78, 0xa3, 0xcb, 0x93, 0x7a, 0x78, 0x2a, + 0x51, 0x91, 0xbd, + 0x42, 0x97, 0x3b, 0x07, 0x31, 0xca, 0x4f, 0x62, 0x2a, 0x63, 0xe0, 0x69, 0x45, + 0x31, 0xc8, 0x75, + 0x3e, 0x3a, 0xb0, 0xe8, 0x8d, 0xdc, 0x86, 0x1c, 0x75, 0x1c, 0x25, 0x2e, 0x74, + 0x18, 0x89, 0xb3, + 0x3e, 0x39, 0x0e, 0x1c, 0xa5, 0xc4, 0x75, 0x1f, 0x31, 0x1e, 0x19, 0x61, 0x5b, + 0xbe, 0xa7, 0x18, + 0x9b, 0x04, 0xf2, 0x29, 0xc8, 0xe7, 0x40, 0x84, 0x39, 0xd2, 0x28, 0xa5, 0x30, + 0x5b, 0x22, 0x78, + 0x33, 0xab, 0xa8, 0x30, 0x98, 0x1c, 0x33, 0xec, 0xfe, 0xe7, 0x90, 0x8c, 0x6d, + 0x39, 0x54, 0x42, + 0x9b, 0xef, 0x30, 0xde, 0xa1, 0x15, 0xfe, 0xe6, 0xd0, 0x3f, 0x13, 0xf0, 0xa0, + 0x2e, 0xb2, 0x19, + 0xe4, 0xb9, 0xb0, 0xba, 0xac, 0x32, 0xc2, 0x24, 0x0b, 0x2a, 0x47, 0x17, 0xda, + 0x7c, 0x11, 0x6c, + 0xe2, 0x09, 0x24, 0x71, 0x30, 0xac, 0x14, 0x0c, 0xd3, 0xab, 0xdc, 0xe7, 0x78, + 0xa4, 0x27, 0x27, + 0xf3, 0x2c, 0xfa, 0xfd, 0xae, 0x9e, 0x51, 0x68, 0x47, 0xb2, 0x6c, 0xe4, 0xcb, + 0xb7, 0x66, 0x03] CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN: True, # 1024_160 or 2048_256 CKA_PRIVATE: True, CKA_ENCRYPT: True, @@ -730,7 +1052,8 @@ CKM_DSA_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, - CKA_PRIME_BITS: 1024, # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 + CKA_PRIME_BITS: 1024, + # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 CKA_SUBPRIME_BITS: 160, # 0-512 CKA_LABEL: "DSA Parameter Key"} @@ -760,24 +1083,41 @@ CKA_UNWRAP: True, CKA_LABEL: "RSA Private Key"} -dhX9_42Prime = [0xE0, 0x01, 0xE8, 0x96, 0x7D, 0xB4, 0x93, 0x53, 0xE1, 0x6F, 0x8E, 0x89, 0x22, 0x0C, 0xCE, 0xFC, - 0x5C, 0x5F, 0x12, 0xE3, 0xDF, 0xF8, 0xF1, 0xD1, 0x49, 0x90, 0x12, 0xE6, 0xEF, 0x53, 0xE3, 0x1F, - 0x02, 0xEA, 0xCC, 0x5A, 0xDD, 0xF3, 0x37, 0x89, 0x35, 0xC9, 0x5B, 0x21, 0xEA, 0x3D, 0x6F, 0x1C, - 0xD7, 0xCE, 0x63, 0x75, 0x52, 0xEC, 0x38, 0x6C, 0x0E, 0x34, 0xF7, 0x36, 0xAD, 0x95, 0x17, 0xEF, - 0xFE, 0x5E, 0x4D, 0xA7, 0xA8, 0x6A, 0xF9, 0x0E, 0x2C, 0x22, 0x8F, 0xE4, 0xB9, 0xE6, 0xD8, 0xF8, - 0xF0, 0x2D, 0x20, 0xAF, 0x78, 0xAB, 0xB6, 0x92, 0xAC, 0xBC, 0x4B, 0x23, 0xFA, 0xF2, 0xC5, 0xCC, - 0xD4, 0x9A, 0x0C, 0x9A, 0x8B, 0xCD, 0x91, 0xAC, 0x0C, 0x55, 0x92, 0x01, 0xE6, 0xC2, 0xFD, 0x1F, - 0x47, 0xC2, 0xCB, 0x2A, 0x88, 0xA8, 0x3C, 0x21, 0x0F, 0xC0, 0x54, 0xDB, 0x29, 0x2D, 0xBC, 0x45] -dhX9_42Base = [0x86, 0x47, 0x17, 0xA3, 0x9E, 0x6A, 0xEA, 0x7E, 0x87, 0xC4, 0x32, 0xEE, 0x77, 0x43, 0x15, 0x16, +dhX9_42Prime = [0xE0, 0x01, 0xE8, 0x96, 0x7D, 0xB4, 0x93, 0x53, 0xE1, 0x6F, 0x8E, 0x89, 0x22, 0x0C, + 0xCE, 0xFC, + 0x5C, 0x5F, 0x12, 0xE3, 0xDF, 0xF8, 0xF1, 0xD1, 0x49, 0x90, 0x12, 0xE6, 0xEF, 0x53, + 0xE3, 0x1F, + 0x02, 0xEA, 0xCC, 0x5A, 0xDD, 0xF3, 0x37, 0x89, 0x35, 0xC9, 0x5B, 0x21, 0xEA, 0x3D, + 0x6F, 0x1C, + 0xD7, 0xCE, 0x63, 0x75, 0x52, 0xEC, 0x38, 0x6C, 0x0E, 0x34, 0xF7, 0x36, 0xAD, 0x95, + 0x17, 0xEF, + 0xFE, 0x5E, 0x4D, 0xA7, 0xA8, 0x6A, 0xF9, 0x0E, 0x2C, 0x22, 0x8F, 0xE4, 0xB9, 0xE6, + 0xD8, 0xF8, + 0xF0, 0x2D, 0x20, 0xAF, 0x78, 0xAB, 0xB6, 0x92, 0xAC, 0xBC, 0x4B, 0x23, 0xFA, 0xF2, + 0xC5, 0xCC, + 0xD4, 0x9A, 0x0C, 0x9A, 0x8B, 0xCD, 0x91, 0xAC, 0x0C, 0x55, 0x92, 0x01, 0xE6, 0xC2, + 0xFD, 0x1F, + 0x47, 0xC2, 0xCB, 0x2A, 0x88, 0xA8, 0x3C, 0x21, 0x0F, 0xC0, 0x54, 0xDB, 0x29, 0x2D, + 0xBC, 0x45] +dhX9_42Base = [0x86, 0x47, 0x17, 0xA3, 0x9E, 0x6A, 0xEA, 0x7E, 0x87, 0xC4, 0x32, 0xEE, 0x77, 0x43, + 0x15, 0x16, 0x96, 0x70, 0xC4, 0x99] -dhX9_42SubPrime = [0x1C, 0xE0, 0xF6, 0x69, 0x26, 0x46, 0x11, 0x97, 0xEF, 0x45, 0xC4, 0x65, 0x8B, 0x83, 0xB8, 0xAB, - 0x04, 0xA9, 0x22, 0x42, 0x68, 0x50, 0x4D, 0x05, 0xB8, 0x19, 0x83, 0x99, 0xDD, 0x71, 0x37, 0x18, - 0xCC, 0x1F, 0x24, 0x5D, 0x47, 0x6C, 0xCF, 0x61, 0xA2, 0xF9, 0x34, 0x93, 0xF4, 0x1F, 0x55, 0x52, - 0x48, 0x65, 0x57, 0xE6, 0xD4, 0xCA, 0xA8, 0x00, 0xD6, 0xD0, 0xDB, 0x3C, 0xBF, 0x5A, 0x95, 0x4B, - 0x20, 0x8A, 0x4E, 0xBA, 0xF7, 0xE6, 0x49, 0xFB, 0x61, 0x24, 0xD8, 0xA2, 0x1E, 0xF2, 0xF2, 0x2B, - 0xAA, 0xAE, 0x29, 0x21, 0x10, 0x19, 0x10, 0x51, 0x46, 0x47, 0x31, 0xB6, 0xCC, 0x3C, 0x93, 0xDC, - 0x6E, 0x80, 0xBA, 0x16, 0x0B, 0x66, 0x64, 0xA5, 0x6C, 0xFA, 0x96, 0xEA, 0xF1, 0xB2, 0x83, 0x39, - 0x8E, 0xB4, 0x61, 0x64, 0xE5, 0xE9, 0x43, 0x84, 0xEE, 0x02, 0x24, 0xE7, 0x1F, 0x03, 0x7C, 0x23] +dhX9_42SubPrime = [0x1C, 0xE0, 0xF6, 0x69, 0x26, 0x46, 0x11, 0x97, 0xEF, 0x45, 0xC4, 0x65, 0x8B, + 0x83, 0xB8, 0xAB, + 0x04, 0xA9, 0x22, 0x42, 0x68, 0x50, 0x4D, 0x05, 0xB8, 0x19, 0x83, 0x99, 0xDD, + 0x71, 0x37, 0x18, + 0xCC, 0x1F, 0x24, 0x5D, 0x47, 0x6C, 0xCF, 0x61, 0xA2, 0xF9, 0x34, 0x93, 0xF4, + 0x1F, 0x55, 0x52, + 0x48, 0x65, 0x57, 0xE6, 0xD4, 0xCA, 0xA8, 0x00, 0xD6, 0xD0, 0xDB, 0x3C, 0xBF, + 0x5A, 0x95, 0x4B, + 0x20, 0x8A, 0x4E, 0xBA, 0xF7, 0xE6, 0x49, 0xFB, 0x61, 0x24, 0xD8, 0xA2, 0x1E, + 0xF2, 0xF2, 0x2B, + 0xAA, 0xAE, 0x29, 0x21, 0x10, 0x19, 0x10, 0x51, 0x46, 0x47, 0x31, 0xB6, 0xCC, + 0x3C, 0x93, 0xDC, + 0x6E, 0x80, 0xBA, 0x16, 0x0B, 0x66, 0x64, 0xA5, 0x6C, 0xFA, 0x96, 0xEA, 0xF1, + 0xB2, 0x83, 0x39, + 0x8E, 0xB4, 0x61, 0x64, 0xE5, 0xE9, 0x43, 0x84, 0xEE, 0x02, 0x24, 0xE7, 0x1F, + 0x03, 0x7C, 0x23] CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -812,7 +1152,8 @@ CKM_DH_PKCS_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, - CKA_PRIME_BITS: 512, # between 512 and 2048 in 256bit increments (&0xff) + CKA_PRIME_BITS: 512, + # between 512 and 2048 in 256bit increments (&0xff) CKA_LABEL: "SH PKCS Parameter Key"} ''' @@ -824,7 +1165,8 @@ CKA_TOKEN: True, CKA_LABEL: "Created certificate object", CKA_SUBJECT: "", - CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} ''' @@ -834,7 +1176,8 @@ DATA_TEMPLATE = {CKA_CLASS: CKO_DATA, CKA_TOKEN: True, CKA_LABEL: "Created data object", - CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01]} KEY_GENERATOR_TEMPLATES = {CKM_DES_KEY_GEN: CKM_DES_KEY_GEN_TEMP, @@ -852,25 +1195,25 @@ CKM_DH_PKCS_PARAMETER_GEN: CKM_DH_PKCS_PARAMETER_GEN_TEMP} KEY_PAIR_GENERATOR_TEMPLATES = { # Note lacks multiple sizes of the same kinds of keys - CKM_RSA_PKCS_KEY_PAIR_GEN: ( - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_X9_31_KEY_PAIR_GEN: ( - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - # pkcs template is good for x9.31 - CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: ( - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: ( - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_DSA_KEY_PAIR_GEN: ( - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_DH_PKCS_KEY_PAIR_GEN: ( - CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_ECDSA_KEY_PAIR_GEN: ( - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_KCDSA_KEY_PAIR_GEN: ( - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_X9_31_KEY_PAIR_GEN: ( - CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP)} + CKM_RSA_PKCS_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + # pkcs template is good for x9.31 + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: ( + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_DSA_KEY_PAIR_GEN: ( + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_DH_PKCS_KEY_PAIR_GEN: ( + CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), + CKM_ECDSA_KEY_PAIR_GEN: ( + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_KCDSA_KEY_PAIR_GEN: ( + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + CKM_RSA_X9_31_KEY_PAIR_GEN: ( + CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP)} ''' This list is not complete @@ -918,7 +1261,8 @@ CKM_SHA512_HMAC: "CKM_SHA512_HMAC", CKM_GENERIC_SECRET_KEY_GEN: "CKM_GENERIC_SECRET_KEY_GEN", CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", - CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} + CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: + "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} MECHANISM_LOOKUP_EXT = { CKM_RSA_PKCS_KEY_PAIR_GEN: ('CKM_RSA_PKCS_KEY_PAIR_GEN',), diff --git a/pycryptoki/defaults.py b/pycryptoki/defaults.py index 1221879..dabb185 100755 --- a/pycryptoki/defaults.py +++ b/pycryptoki/defaults.py @@ -4,6 +4,8 @@ # The location of the cryptoki file, if specified as None the environment variable # ChrystokiConfigurationPath will be used or it will revert to using /etc/Chrystoki.conf +import os + CHRYSTOKI_CONFIG_FILE = None # The location of the DLL file, if not specified it will try to look up the file in @@ -14,17 +16,17 @@ AUDITOR_LABEL = 'auditorlabel' ADMINISTRATOR_USERNAME = 'Administrator' -ADMINISTRATOR_PASSWORD = 'adminpassword' +ADMINISTRATOR_PASSWORD = '1q@W3e$R' AUDITOR_USERNAME = 'Auditor' -AUDITOR_PASSWORD = 'auditorpassword' +AUDITOR_PASSWORD = 'W3e$R' CO_USERNAME = 'Crypto Officer' -CO_PASSWORD = 'copassword' +CO_PASSWORD = 'userpin' DEFAULT_USERNAME = 'default_user' DEFAULT_LABEL = 'default_label' -DEFAULT_PASSWORD = 'default' +DEFAULT_PASSWORD = 'userpin' DEFAULT_UTILS_PATH = '/usr/safenet/lunaclient/sbin' FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" @@ -39,4 +41,4 @@ MANUFACTURER_ID = "SafeNet Inc." MODEL = "Luna K6" -ADMIN_SLOT = 1 +ADMIN_SLOT = int(os.environ.get("ADMIN_SLOT", 1)) diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index c97f18f..58195e4 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -351,8 +351,7 @@ LUNA_ATTR_X9_31_GENERATED = (LUNA_ATTR_VENDOR_DEFINED | 0x00000006) LUNA_ATTR_PKC_ECC = (LUNA_ATTR_VENDOR_DEFINED | 0x00000007) LUNA_ATTR_EKM_UID = (LUNA_ATTR_VENDOR_DEFINED | 0x00000008) -LUNA_ATTR_PKC_LEGACY_ECC = ( -LUNA_ATTR_VENDOR_DEFINED | 0x00000009) # retired but available if needed +LUNA_ATTR_PKC_LEGACY_ECC = (LUNA_ATTR_VENDOR_DEFINED | 0x00000009) # retired but available if needed LUNA_ATTR_USAGE_COUNT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000101) LUNA_ATTR_USAGE_COUNT_LIMIT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000200) LUNA_ATTR_GENERIC_1 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001000) @@ -364,7 +363,6 @@ LUNA_ATTR_KEK_MAX_LIFETIME = (LUNA_ATTR_PARTITION_ATTRIBUTE | 0x00000001) LUNA_ATTR_KEK_ACTUAL_LIFETIME = (LUNA_ATTR_PARTITION_ATTRIBUTE | 0x00000002) LUNA_ATTR_KEK_MANAGEMENT_FLAGS = (LUNA_ATTR_PARTITION_ATTRIBUTE | 0x00000003) -LUNA_ATTR_UNKNOWN = 0xFFFFFFFF LUNA_HW_FEATURE_MONOTONIC_COUNTER = 0x00000001 LUNA_HW_FEATURE_CLOCK = 0x00000002 LUNA_HW_FEATURE_USER_INTERFACE = 0x00000003 @@ -1404,60 +1402,74 @@ CKF_EC_UNCOMPRESS = 0x01000000 CKF_EC_COMPRESS = 0x02000000 CKF_EXTENSION = 0x80000000 # FALSE for this version */ -CKR_OK = 0x00000000 -CKR_CANCEL = 0x00000001 -CKR_HOST_MEMORY = 0x00000002 -CKR_SLOT_ID_INVALID = 0x00000003 -CKR_GENERAL_ERROR = 0x00000005 -CKR_FUNCTION_FAILED = 0x00000006 CKR_ARGUMENTS_BAD = 0x00000007 -CKR_NO_EVENT = 0x00000008 -CKR_NEED_TO_CREATE_THREADS = 0x00000009 -CKR_CANT_LOCK = 0x0000000A CKR_ATTRIBUTE_READ_ONLY = 0x00000010 CKR_ATTRIBUTE_SENSITIVE = 0x00000011 CKR_ATTRIBUTE_TYPE_INVALID = 0x00000012 CKR_ATTRIBUTE_VALUE_INVALID = 0x00000013 +CKR_BUFFER_TOO_SMALL = 0x00000150 +CKR_CANCEL = 0x00000001 +CKR_CANT_LOCK = 0x0000000A +CKR_CRYPTOKI_ALREADY_INITIALIZED = 0x00000191 +CKR_CRYPTOKI_NOT_INITIALIZED = 0x00000190 CKR_DATA_INVALID = 0x00000020 CKR_DATA_LEN_RANGE = 0x00000021 CKR_DEVICE_ERROR = 0x00000030 CKR_DEVICE_MEMORY = 0x00000031 CKR_DEVICE_REMOVED = 0x00000032 +CKR_DOMAIN_PARAMS_INVALID = 0x00000130 CKR_ENCRYPTED_DATA_INVALID = 0x00000040 CKR_ENCRYPTED_DATA_LEN_RANGE = 0x00000041 CKR_FUNCTION_CANCELED = 0x00000050 +CKR_FUNCTION_FAILED = 0x00000006 CKR_FUNCTION_NOT_PARALLEL = 0x00000051 CKR_FUNCTION_NOT_SUPPORTED = 0x00000054 -CKR_KEY_HANDLE_INVALID = 0x00000060 -CKR_KEY_SIZE_RANGE = 0x00000062 -CKR_KEY_TYPE_INCONSISTENT = 0x00000063 -CKR_KEY_NOT_NEEDED = 0x00000064 +CKR_FUNCTION_REJECTED = 0x00000200 +CKR_GENERAL_ERROR = 0x00000005 +CKR_HOST_MEMORY = 0x00000002 +CKR_INFORMATION_SENSITIVE = 0x00000170 CKR_KEY_CHANGED = 0x00000065 -CKR_KEY_NEEDED = 0x00000066 -CKR_KEY_INDIGESTIBLE = 0x00000067 CKR_KEY_FUNCTION_NOT_PERMITTED = 0x00000068 +CKR_KEY_HANDLE_INVALID = 0x00000060 +CKR_KEY_INDIGESTIBLE = 0x00000067 +CKR_KEY_NEEDED = 0x00000066 +CKR_KEY_NOT_NEEDED = 0x00000064 CKR_KEY_NOT_WRAPPABLE = 0x00000069 +CKR_KEY_SIZE_RANGE = 0x00000062 +CKR_KEY_TYPE_INCONSISTENT = 0x00000063 CKR_KEY_UNEXTRACTABLE = 0x0000006A CKR_MECHANISM_INVALID = 0x00000070 CKR_MECHANISM_PARAM_INVALID = 0x00000071 +CKR_MUTEX_BAD = 0x000001A0 +CKR_MUTEX_NOT_LOCKED = 0x000001A1 +CKR_NEED_TO_CREATE_THREADS = 0x00000009 +CKR_NEW_PIN_MODE = 0x000001B0 +CKR_NEXT_OTP = 0x000001B1 +CKR_NO_EVENT = 0x00000008 CKR_OBJECT_HANDLE_INVALID = 0x00000082 +CKR_OK = 0x00000000 CKR_OPERATION_ACTIVE = 0x00000090 CKR_OPERATION_NOT_INITIALIZED = 0x00000091 +CKR_PIN_EXPIRED = 0x000000A3 CKR_PIN_INCORRECT = 0x000000A0 CKR_PIN_INVALID = 0x000000A1 CKR_PIN_LEN_RANGE = 0x000000A2 -CKR_PIN_EXPIRED = 0x000000A3 CKR_PIN_LOCKED = 0x000000A4 +CKR_RANDOM_NO_RNG = 0x00000121 +CKR_RANDOM_SEED_NOT_SUPPORTED = 0x00000120 +CKR_SAVED_STATE_INVALID = 0x00000160 CKR_SESSION_CLOSED = 0x000000B0 CKR_SESSION_COUNT = 0x000000B1 +CKR_SESSION_EXISTS = 0x000000B6 CKR_SESSION_HANDLE_INVALID = 0x000000B3 CKR_SESSION_PARALLEL_NOT_SUPPORTED = 0x000000B4 CKR_SESSION_READ_ONLY = 0x000000B5 -CKR_SESSION_EXISTS = 0x000000B6 CKR_SESSION_READ_ONLY_EXISTS = 0x000000B7 CKR_SESSION_READ_WRITE_SO_EXISTS = 0x000000B8 CKR_SIGNATURE_INVALID = 0x000000C0 CKR_SIGNATURE_LEN_RANGE = 0x000000C1 +CKR_SLOT_ID_INVALID = 0x00000003 +CKR_STATE_UNSAVEABLE = 0x00000180 CKR_TEMPLATE_INCOMPLETE = 0x000000D0 CKR_TEMPLATE_INCONSISTENT = 0x000000D1 CKR_TOKEN_NOT_PRESENT = 0x000000E0 @@ -1467,31 +1479,17 @@ CKR_UNWRAPPING_KEY_SIZE_RANGE = 0x000000F1 CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT = 0x000000F2 CKR_USER_ALREADY_LOGGED_IN = 0x00000100 +CKR_USER_ANOTHER_ALREADY_LOGGED_IN = 0x00000104 CKR_USER_NOT_LOGGED_IN = 0x00000101 CKR_USER_PIN_NOT_INITIALIZED = 0x00000102 -CKR_USER_TYPE_INVALID = 0x00000103 -CKR_USER_ANOTHER_ALREADY_LOGGED_IN = 0x00000104 CKR_USER_TOO_MANY_TYPES = 0x00000105 +CKR_USER_TYPE_INVALID = 0x00000103 +CKR_VENDOR_DEFINED = 0x80000000 CKR_WRAPPED_KEY_INVALID = 0x00000110 CKR_WRAPPED_KEY_LEN_RANGE = 0x00000112 CKR_WRAPPING_KEY_HANDLE_INVALID = 0x00000113 CKR_WRAPPING_KEY_SIZE_RANGE = 0x00000114 CKR_WRAPPING_KEY_TYPE_INCONSISTENT = 0x00000115 -CKR_RANDOM_SEED_NOT_SUPPORTED = 0x00000120 -CKR_RANDOM_NO_RNG = 0x00000121 -CKR_DOMAIN_PARAMS_INVALID = 0x00000130 -CKR_BUFFER_TOO_SMALL = 0x00000150 -CKR_SAVED_STATE_INVALID = 0x00000160 -CKR_INFORMATION_SENSITIVE = 0x00000170 -CKR_STATE_UNSAVEABLE = 0x00000180 -CKR_CRYPTOKI_NOT_INITIALIZED = 0x00000190 -CKR_CRYPTOKI_ALREADY_INITIALIZED = 0x00000191 -CKR_MUTEX_BAD = 0x000001A0 -CKR_MUTEX_NOT_LOCKED = 0x000001A1 -CKR_NEW_PIN_MODE = 0x000001B0 -CKR_NEXT_OTP = 0x000001B1 -CKR_FUNCTION_REJECTED = 0x00000200 -CKR_VENDOR_DEFINED = 0x80000000 CKF_LIBRARY_CANT_CREATE_OS_THREADS = 0x00000001 CKF_OS_LOCKING_OK = 0x00000002 CKF_DONT_BLOCK = 1 @@ -1525,7 +1523,6 @@ NULL_PTR = 0 C_LIBRARY_VERSION = 0x510 # v5.10 decimal */ CK_TOKEN_SERIAL_NUMBER_SIZE = 16 -CK_EFFECTIVELY_INFINITE = 0 CKU_CRYPTO_OFFICER = CKU_USER CKU_LIMITED_USER = 0x80000001 CKU_LIMITED_USER_OLD = 0x8000001 @@ -1579,8 +1576,6 @@ CKD_SES_AUTH_CTR = 0x00000002 CKD_SES_ALT_ENC_CTR = 0x00000003 CKD_SES_ALT_AUTH_CTR = 0x00000004 -CKD_SHA1_KDF_ASN1 = 0x00000003 # not supported -CKD_SHA1_KDF_CONCATENATE = 0x00000004 CKD_SHA1_KDF_CONCATENATE_X9_42 = CKD_SHA1_KDF_CONCATENATE CKD_SHA1_KDF_CONCATENATE_NIST = 0x80000001 CKD_SHA1_KDF_ASN1_X9_42 = CKD_SHA1_KDF_ASN1 # not supported @@ -1707,7 +1702,6 @@ CKM_AES_CFB8 = (CKM_VENDOR_DEFINED + 0x118) CKM_AES_CFB128 = (CKM_VENDOR_DEFINED + 0x119) CKM_AES_OFB = (CKM_VENDOR_DEFINED + 0x11a) -CKM_AES_CTR = (CKM_VENDOR_DEFINED + 0x11b) CKM_AES_GCM = (CKM_VENDOR_DEFINED + 0x11c) CKM_ARIA_CFB8 = (CKM_VENDOR_DEFINED + 0x11d) CKM_ARIA_CFB128 = (CKM_VENDOR_DEFINED + 0x11e) @@ -1806,8 +1800,6 @@ CK_NIST_PRF_KDF_AES_CMAC = 0x00000002 CK_PRF_KDF_ARIA_CMAC = 0x00000003 CK_PRF_KDF_SEED_CMAC = 0x00000004 -LUNA_PRF_KDF_ENCODING_SCHEME_1 = 0x00000000 -LUNA_PRF_KDF_ENCODING_SCHEME_2 = 0x00000001 CKR_INSERTION_CALLBACK_NOT_SUPPORTED = 0x00000141 CKR_FUNCTION_PARALLEL = 0x0052 CKR_SESSION_EXCLUSIVE_EXISTS = 0x00B2 @@ -2022,5 +2014,4 @@ CK_PED_ID_MAX = 0xFFFE CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT = 0x00000001 CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET = 0x00000002 -CKP_PKCS5_PBKD2_HMAC_SHA1 = 0x00000001 CKP_PKCS5_PBKD2_HMAC_SM3 = 0x80000B01 diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 0b0336a..472c46c 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -3,160 +3,23 @@ """ import logging from _ctypes import POINTER -from ctypes import c_char, create_string_buffer, cast, c_void_p, byref, sizeof, pointer, \ - string_at, c_ubyte - -from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ - C_EncryptInit, C_Encrypt, CK_RSA_PKCS_OAEP_PARAMS -from defines import CKM_DES_CBC, CKM_DES3_CBC, CKM_CAST3_CBC, CKM_DES_ECB, \ - CKM_DES3_ECB, CKM_CAST3_ECB, CKM_RC2_ECB, CKM_RC2_CBC, CKM_CAST5_ECB, \ - CKM_CAST5_CBC, CKM_RC4, CKM_RC5_ECB, CKM_RC5_CBC, CKM_RSA_X_509, CKM_DES_CBC_PAD, \ - CKM_DES3_CBC_PAD, CKM_DES3_CBC_PAD_IPSEC, CKM_RC2_CBC_PAD, CKM_RC5_CBC_PAD, \ - CKM_CAST3_CBC_PAD, CKM_CAST5_CBC_PAD, CKM_SEED_ECB, CKM_SEED_CBC, \ - CKM_SEED_CBC_PAD, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, \ - CKM_AES_CBC_PAD_IPSEC, CKM_ARIA_ECB, CKM_ARIA_CBC, CKM_ARIA_CBC_PAD, \ - CKM_RSA_PKCS, CKM_DES_CFB8, CKM_DES_CFB64, CKM_DES_OFB64, CKM_AES_CFB8, \ - CKM_AES_CFB128, CKM_AES_OFB, CKM_ARIA_CFB8, CKM_ARIA_CFB128, CKM_ARIA_OFB, \ - CKM_AES_GCM, CKM_XOR_BASE_AND_DATA_W_KDF, CKM_RSA_PKCS_OAEP, CKM_ECIES, CKR_OK, \ - CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED, CKM_AES_KW, CKM_AES_KWP -from pycryptoki.attributes import Attributes, to_byte_array, to_char_array -from pycryptoki.common_utils import AutoCArray, refresh_c_arrays -from pycryptoki.cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ +from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte + +from cryptoki import CK_ULONG, \ + C_EncryptInit, C_Encrypt +from defines import CKR_OK +from .attributes import Attributes, to_char_array +from .common_utils import AutoCArray, refresh_c_arrays +from .cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ C_DecryptUpdate, C_DecryptFinal -from pycryptoki.test_functions import make_error_handle_function +from .mechanism import Mechanism +from .test_functions import make_error_handle_function LOG = logging.getLogger(__name__) -def get_encryption_mechanism(encryption_flavor, external_iv=None): - """Returns the CK_MECHANISM() object associated with a given encryption flavor - #TODO: Only works with one kind of encryption mechanism currently. - - :param encryption_flavor: The flavor of the encryption that the mechanism needs - to encrypt for. - :param external_iv: External IV to insert into the mechanism struct. - :returns: Returns a CTypes CK_Mechanism given the encryption flavour that you have passed in - - """ - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(encryption_flavor) - mech.pParameter = 0 - mech.usParameterLen = CK_ULONG(0) - - iv_required = 1 - RC2_params_required = 2 - RC2CBC_params_required = 3 - RC5_params_required = 4 - RC5CBC_params_required = 5 - IV16_required = 6 - GCM_params_required = 7 - xorkdf_params_required = 8 - OAEP_params_required = 9 - ECIES_params_required = 10 - - encryption_flavors = {CKM_DES_CBC: iv_required, - CKM_DES3_CBC: iv_required, - CKM_CAST3_CBC: iv_required, - CKM_DES_ECB: 0, - CKM_DES3_ECB: 0, - CKM_CAST3_ECB: 0, - CKM_RC2_ECB: RC2_params_required, - CKM_RC2_CBC: RC2CBC_params_required, - CKM_CAST5_ECB: 0, - CKM_CAST5_CBC: iv_required, - CKM_RC4: 0, - CKM_RC5_ECB: RC5_params_required, - CKM_RC5_CBC: RC5CBC_params_required, - CKM_RSA_X_509: 0, - CKM_DES_CBC_PAD: iv_required, - CKM_DES3_CBC_PAD: iv_required, - CKM_DES3_CBC_PAD_IPSEC: iv_required, - CKM_RC2_CBC_PAD: RC2CBC_params_required, - CKM_RC5_CBC_PAD: RC5CBC_params_required, - CKM_CAST3_CBC_PAD: iv_required, - CKM_CAST5_CBC_PAD: iv_required, - CKM_SEED_ECB: 0, - CKM_SEED_CBC: IV16_required, - CKM_SEED_CBC_PAD: IV16_required, - CKM_AES_ECB: 0, - CKM_AES_KW: iv_required, - CKM_AES_KWP: iv_required, - CKM_AES_CBC: IV16_required, - CKM_AES_CBC_PAD: IV16_required, - CKM_AES_CBC_PAD_IPSEC: IV16_required, - CKM_ARIA_ECB: IV16_required, - CKM_ARIA_CBC: IV16_required, - CKM_ARIA_CBC_PAD: IV16_required, - CKM_RSA_PKCS: 0, - CKM_DES_CFB8: iv_required, - CKM_DES_CFB64: iv_required, - CKM_DES_OFB64: iv_required, - CKM_AES_CFB8: iv_required, - CKM_AES_CFB128: iv_required, - CKM_AES_OFB: iv_required, - CKM_ARIA_CFB8: iv_required, - CKM_ARIA_CFB128: iv_required, - CKM_ARIA_OFB: iv_required, - CKM_AES_GCM: GCM_params_required, - CKM_XOR_BASE_AND_DATA_W_KDF: xorkdf_params_required, - CKM_RSA_PKCS_OAEP: OAEP_params_required, - CKM_ECIES: ECIES_params_required} - - params = encryption_flavors.get(encryption_flavor) - - if params in (iv_required, IV16_required): - if external_iv: - iv = external_iv - iv16 = external_iv - else: - LOG.warning("Using static IVs can be insecure! ") - iv = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] - iv16 = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] - - if params == iv_required: - iv_ba, iv_len = to_byte_array(iv) - mech.pParameter = iv_ba - mech.usParameterLen = iv_len - elif params == RC2_params_required: - num_of_effective_bits = 0 - rc2_params = (c_char * 2)() - rc2_params[0] = c_char(int(num_of_effective_bits, 8) & 0xff) - rc2_params[1] = c_char(int((num_of_effective_bits >> 8), 8) & 0xff) - rc2_params = create_string_buffer("", 2) - mech.pParameter = cast(rc2_params, c_void_p) - mech.usParameterLen = CK_ULONG(len(rc2_params)) - elif params == RC2CBC_params_required: - raise NotImplementedError("RC2 CBC params not yet implemented") - elif params == RC5_params_required: - raise NotImplementedError("RC5 params not yet implemented") - elif params == RC5CBC_params_required: - raise NotImplementedError("RC5 CBC params not yet implemented") - elif params == IV16_required: - iv_ba, iv_len = to_byte_array(iv16) - mech.pParameter = iv_ba - mech.usParameterLen = iv_len - elif params == GCM_params_required: - raise NotImplementedError("GCM params not yet implemented") - elif params == xorkdf_params_required: - raise NotImplementedError("xorkdf params not yet implemented") - elif params == OAEP_params_required: - oaep_params = CK_RSA_PKCS_OAEP_PARAMS() - oaep_params.hashAlg = CK_ULONG(CKM_SHA_1) - oaep_params.mgf = CK_ULONG(CKG_MGF1_SHA1) - oaep_params.source = CK_ULONG(CKZ_DATA_SPECIFIED) - oaep_params.pSourceData = 0 - oaep_params.ulSourceDataLen = 0 - - mech.pParameter = cast(pointer(oaep_params), CK_VOID_PTR) - mech.usParameterLen = CK_ULONG(sizeof(oaep_params)) - elif params == ECIES_params_required: - raise NotImplementedError("ECIES params not yet implemented") - - return mech - - -def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, external_iv=None): +def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, extra_params=None): """Encrypts data with a given key and encryption flavor encryption flavors @@ -168,13 +31,14 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e a multipart operation will be used :param mech: The mechanism to use, if None will try to look up a default mechanism based on the encryption flavor - :param external_iv: The new Integrity Value to be used. + :param extra_params: Parameters to be passed to mechanism generation. :returns: Returns the result code of the operation, a python string representing the encrypted data """ if mech is None: - mech = get_encryption_mechanism(encryption_flavor, external_iv) + py_mech = Mechanism(mech_type=encryption_flavor, params=extra_params) + mech = py_mech.to_c_mech() # if a list is passed out do an encrypt operation on each string in the list, otherwise just # do one encrypt operation @@ -236,7 +100,7 @@ def _get_string_from_list(list_of_strings): return "".join(list_of_strings) -def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, external_iv=None): +def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, extra_params=None): """Decrypts some data :param h_session: The session to use @@ -245,14 +109,16 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, ex :param h_key: The handle of the key to use to decrypt :param mech: The mechanism, if none is provided a blank one will be provided based on the decryption_flavor (Default value = None) - :param encrypted_data: + :param encrypted_data: Data to be decrypted + :param extra_params: Parameters to be passed to mechanism generation. :returns: The result code, a python string of the decrypted data """ # Get the mechanism if mech is None: - mech = get_encryption_mechanism(decryption_flavor, external_iv) + py_mech = Mechanism(mech_type=decryption_flavor, params=extra_params) + mech = py_mech.to_c_mech() # Initialize Decrypt ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) @@ -359,7 +225,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in return ret, python_string -def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, external_iv=None): +def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, extra_params=None): """Function which wraps a key :param h_session: The session to use @@ -369,11 +235,13 @@ def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, e is provided :param mech: The mechanism, if none is provided a blank one will be provided based on the encryption flavor (Default value = None) + :param extra_params: Parameters to be passed to mechanism generation. :returns: The result code, a ctypes byte array representing the new key """ if mech is None: - mech = get_encryption_mechanism(encryption_flavor, external_iv) + py_mech = Mechanism(mech_type=encryption_flavor, params=extra_params) + mech = py_mech.to_c_mech() wrapped_key = AutoCArray(ctype=c_ubyte) @@ -395,7 +263,7 @@ def _wrap(): def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, - mech=None, external_iv=None): + mech=None, extra_params=None): """Function which unwraps a key :param h_session: The session to use @@ -406,13 +274,15 @@ def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encrypt default one based on the encryption flavor :param mech: The mechanism to use, if null a default one will be created based on the encryption_flavor - :param h_unwrapping_key: - :param wrapped_key: + :param h_unwrapping_key: Key to do the unwrapping + :param wrapped_key: Key to be decrypted (unwrapped) + :param extra_params: Parameters to be passed to mechanism generation. :returns: The result code, the handle of the unwrapped key """ if mech is None: - mech = get_encryption_mechanism(encryption_flavor, external_iv) + py_mech = Mechanism(mech_type=encryption_flavor, params=extra_params) + mech = py_mech.to_c_mech() c_template = Attributes(key_template).get_c_struct() byte_wrapped_key = cast(wrapped_key, CK_BYTE_PTR) diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 243bfa3..758ebb9 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -3,28 +3,28 @@ """ from _ctypes import pointer from ctypes import byref, create_string_buffer, cast -from pycryptoki.common_utils import AutoCArray, refresh_c_arrays - -from pycryptoki.cryptoki import (CK_SLOT_ID, - CK_USER_TYPE, - CA_SetTokenCertificateSignature, - CA_HAInit, - CA_CreateLoginChallenge, - CA_InitializeRemotePEDVector, - CA_DeleteRemotePEDVector, - CA_MTKRestore, - CA_MTKResplit, - CA_MTKZeroize, - CK_ULONG, - CK_BYTE_PTR, - CK_BYTE, - CK_CHAR_PTR, - CK_CHAR, CA_SetHSMPolicy, CK_SESSION_HANDLE, CA_SetHSMPolicies, - CA_SetDestructiveHSMPolicy, CA_SetDestructiveHSMPolicies, - CA_GetHSMCapabilitySet, CA_GetHSMCapabilitySetting, - CA_GetHSMPolicySet, CA_GetHSMPolicySetting) -from pycryptoki.attributes import Attributes -from pycryptoki.test_functions import make_error_handle_function + +from .attributes import Attributes +from .common_utils import AutoCArray, refresh_c_arrays +from .cryptoki import (CK_SLOT_ID, + CK_USER_TYPE, + CA_SetTokenCertificateSignature, + CA_HAInit, + CA_CreateLoginChallenge, + CA_InitializeRemotePEDVector, + CA_DeleteRemotePEDVector, + CA_MTKRestore, + CA_MTKResplit, + CA_MTKZeroize, + CK_ULONG, + CK_BYTE_PTR, + CK_BYTE, + CK_CHAR_PTR, + CK_CHAR, CA_SetHSMPolicy, CK_SESSION_HANDLE, CA_SetHSMPolicies, + CA_SetDestructiveHSMPolicy, CA_SetDestructiveHSMPolicies, + CA_GetHSMCapabilitySet, CA_GetHSMCapabilitySetting, + CA_GetHSMPolicySet, CA_GetHSMPolicySetting) +from .test_functions import make_error_handle_function def c_performselftest(slot, @@ -45,13 +45,13 @@ def c_performselftest(slot, test_type = CK_ULONG(test_type) input_length = CK_ULONG(input_data_len) - input_data = (CK_BYTE * input_data)() + input_data = (CK_BYTE * input_data_len)(*input_data) output_data = cast(create_string_buffer('', input_data_len), CK_BYTE_PTR) output_data_len = CK_ULONG() try: - from pycryptoki.cryptoki import CA_PerformSelfTest as selftest + from .cryptoki import CA_PerformSelfTest as selftest except ImportError: - from pycryptoki.cryptoki import C_PerformSelftest as selftest + from .cryptoki import C_PerformSelftest as selftest ret = selftest(slot, test_type, @@ -91,7 +91,7 @@ def ca_settokencertificatesignature(h_session, key_attributes = Attributes(pub_template) pub_template_len = CK_ULONG(len(pub_template)) - signature = (CK_BYTE * signature)() + signature = (CK_BYTE * signature_len)(*signature) signature_length = CK_ULONG(signature_len) ret = CA_SetTokenCertificateSignature(h_session, access_level, diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 003ecdf..5fc78ba 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -4,14 +4,16 @@ from ctypes import byref -from cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, CK_MECHANISM, \ - CK_MECHANISM_TYPE, CK_VOID_PTR, C_GenerateKey, C_GenerateKeyPair, C_CopyObject +from cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, C_GenerateKey, \ + C_GenerateKeyPair, \ + C_CopyObject from default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP from defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import C_DeriveKey -from pycryptoki.test_functions import make_error_handle_function +from .attributes import Attributes +from .cryptoki import C_DeriveKey +from .mechanism import NullMech +from .test_functions import make_error_handle_function def c_destroy_object(h_session, h_object_value): @@ -60,11 +62,7 @@ def _get_mechanism(flavor): :returns: Returns a blank mechanism of type flavor """ - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(flavor) - mech.pParameter = CK_VOID_PTR(0) - mech.usParameterLen = CK_ULONG(0) - return mech + return NullMech(flavor).to_c_mech() def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP): diff --git a/pycryptoki/key_management.py b/pycryptoki/key_management.py index 00624b9..4d03436 100755 --- a/pycryptoki/key_management.py +++ b/pycryptoki/key_management.py @@ -1,9 +1,9 @@ """ Methods responsible for key management """ -from pycryptoki.cryptoki import CA_GenerateMofN, CA_ModifyUsageCount, \ +from .cryptoki import CA_GenerateMofN, CA_ModifyUsageCount, \ CK_VOID_PTR, CK_ULONG, CA_MOFN_GENERATION, CK_BYTE, CA_MOFN_GENERATION_PTR -from pycryptoki.test_functions import make_error_handle_function +from .test_functions import make_error_handle_function def ca_generatemofn(h_session, diff --git a/pycryptoki/key_usage.py b/pycryptoki/key_usage.py index f590912..bcea80e 100755 --- a/pycryptoki/key_usage.py +++ b/pycryptoki/key_usage.py @@ -1,9 +1,9 @@ """ Methods responsible for key usage """ -from pycryptoki.cryptoki import CA_CloneMofN, CA_DuplicateMofN, \ +from .cryptoki import CA_CloneMofN, CA_DuplicateMofN, \ CK_VOID_PTR, CK_SESSION_HANDLE -from pycryptoki.test_functions import make_error_handle_function +from .test_functions import make_error_handle_function def ca_clonemofn(h_session): diff --git a/pycryptoki/luna_threading.py b/pycryptoki/luna_threading.py index 6428ea7..71b89d0 100755 --- a/pycryptoki/luna_threading.py +++ b/pycryptoki/luna_threading.py @@ -3,17 +3,17 @@ import threading import time -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ +from .default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, MANUFACTURER_ID, MODEL -from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, \ +from .defaults import ADMIN_PARTITION_LABEL, MANUFACTURER_ID, MODEL +from .defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN, \ CKR_OK -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_open_session_ex, c_get_token_info_ex, \ +from .key_generator import c_generate_key_ex, c_generate_key_pair_ex +from .return_values import ret_vals_dictionary +from .session_management import c_open_session_ex, c_get_token_info_ex, \ c_open_session, c_close_session -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.token_management import get_token_by_label_ex, \ +from .test_functions import verify_object_attributes +from .token_management import get_token_by_label_ex, \ c_get_mechanism_list_ex, c_get_mechanism_info_ex logger = logging.getLogger(__name__) @@ -26,7 +26,8 @@ class TestThread(threading.Thread): """A member of the threading class which, when given the proper parameters, will - perform some functions on the HSM in it's own thread. If one of the tests fails it will be reported when all the + perform some functions on the HSM in it's own thread. If one of the tests fails it will be + reported when all the threads finish. @@ -38,7 +39,8 @@ def __init__(self, queue, thread_name, token_label, thread_type, max_time=60): to the queue that the task is done @param thread_name: The name of the thread for debug printing purposes @param token_label: The token label to perform multithreaded operations on - @param thread_type: The a numeric value specifyingoperation the thread will do, see the variables + @param thread_type: The a numeric value specifyingoperation the thread will do, + see the variables described above the TestThread class declaration ex. GET_TOKEN_INFO @param max_time: The amount of time to spend doing the test in seconds """ @@ -59,7 +61,8 @@ def run(self): # For a given amount of time run the operations in a separate thread start_time = time.time() while ((time.time() - start_time) < self.max_time) and ( - (not self.starting_slot >= self.ending_slot) or (self.starting_slot == -1 and self.ending_slot == -1)): + (not self.starting_slot >= self.ending_slot) or ( + self.starting_slot == -1 and self.ending_slot == -1)): if self.thread_type == CREATE_AND_REMOVE_KEYS: self.create_and_remove_keys() elif self.thread_type == OPEN_AND_CLOSE_SESSIONS: @@ -116,7 +119,8 @@ def create_and_remove_keys(self): logger.debug(self.thread_name + " Generating keys") key_handle = c_generate_key_ex(h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - key_handle_public, key_handle_private = c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, + key_handle_public, key_handle_private = c_generate_key_pair_ex(h_session, + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) @@ -144,4 +148,5 @@ def get_mechanism_info(self): for mechanism in mechanism_list: mech_info = c_get_mechanism_info_ex(slot, mechanism) assert ( - mech_info.ulMinKeySize > 0 or mech_info.ulMaxKeySize > 0 or mech_info.flags > 0) and mech_info.ulMinKeySize <= mech_info.ulMaxKeySize, "Verifing that all fields are not 0 should be good enough for now" + mech_info.ulMinKeySize > 0 or mech_info.ulMaxKeySize > 0 or + mech_info.flags > 0) and mech_info.ulMinKeySize <= mech_info.ulMaxKeySize, "Verifing that all fields are not 0 should be good enough for now" diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index db49962..6c48998 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -1,10 +1,21 @@ -from ctypes import c_void_p, cast, pointer, POINTER, sizeof, c_char_p, \ - create_string_buffer, c_char +""" +Mechanism-related utilities +""" -from pycryptoki.cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ - CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR -from pycryptoki.defines import CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, \ - CK_CRYPTOKI_ELEMENT, CK_STORAGE_HOST, CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL +import logging +from ctypes import c_void_p, cast, pointer, POINTER, sizeof, create_string_buffer, c_char + +from . import cryptoki +from .attributes import to_byte_array, CONVERSIONS +from .cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ + CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_RC2_CBC_PARAMS, \ + CK_RC5_PARAMS, CK_RC5_CBC_PARAMS, CK_MECHANISM_TYPE, CK_AES_XTS_PARAMS, \ + CK_RSA_PKCS_OAEP_PARAMS, \ + CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS +from .defines import * +from .test_functions import LunaException + +LOG = logging.getLogger(__name__) CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism': CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, 'ulType': CK_CRYPTOKI_ELEMENT, @@ -36,6 +47,381 @@ 'CK_AES_CBC_PAD_INSERT_PARAMS': CK_AES_CBC_PAD_INSERT_PARAMS} +class MechanismException(Exception): + """ + Mechanism-related exceptions + """ + + pass + + +class Mechanism(object): + """ + Base class for pycryptoki mechanisms. + Performs checks for missing parameters w/ created mechs, and + creates the base Mechanism Struct for conversion to ctypes. + """ + REQUIRED_PARAMS = [] + + def __new__(cls, mech_type="UNKNOWN", params=None): + """ + Factory for mechs. + """ + + if cls == Mechanism: + mech_cls = MECH_LOOKUP.get(mech_type, NullMech) + return super(Mechanism, cls).__new__(mech_cls, mech_type, params) + else: + return super(Mechanism, cls).__new__(cls, mech_type, params) + + def __init__(self, mech_type="UNKNOWN", params=None): + self.mech_type = mech_type + if params is None: + params = {} + self.params = params + + missing_params = [] + for req in self.REQUIRED_PARAMS: + if req not in params: + missing_params.append(req) + if missing_params: + raise MechanismException("Cannot create {}, " + "Missing required parameters:\n\t" + "{}".format(self.__class__, + "\n\t".join(missing_params))) + + def to_c_mech(self): + """ + Create the Mechanism structure & set the mech type to the passed-in flavor. + + :return: `CK_MECHANISM` + """ + self.mech = CK_MECHANISM() + self.mech.mechanism = CK_MECHANISM_TYPE(self.mech_type) + return self.mech + + +class IvMechanism(Mechanism): + """ + Mech class for flavors that require an IV set in the mechanism. + Will default to `[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38]` if no IV is passed in + """ + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(IvMechanism, self).to_c_mech() + if self.params is None or 'iv' not in self.params: + self.params['iv'] = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] + LOG.warning("Using static IVs can be insecure! ") + iv_ba, iv_len = to_byte_array(self.params['iv']) + self.mech.pParameter = iv_ba + self.mech.usParameterLen = iv_len + return self.mech + + +class Iv16Mechanism(Mechanism): + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(Iv16Mechanism, self).to_c_mech() + if self.params is None or 'iv' not in self.params: + self.params['iv'] = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + LOG.warning("Using static IVs can be insecure! ") + iv_ba, iv_len = to_byte_array(self.params['iv']) + self.mech.pParameter = iv_ba + self.mech.usParameterLen = iv_len + return self.mech + + +class RC2Mechanism(Mechanism): + REQUIRED_PARAMS = ['usEffectiveBits'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(RC2Mechanism, self).to_c_mech() + effective_bits = CK_ULONG(self.params['usEffectiveBits']) + self.mech.pParameter = cast(pointer(effective_bits), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(effective_bits)) + return self.mech + + +class RC2CBCMechanism(Mechanism): + REQUIRED_PARAMS = ['usEffectiveBits', 'iv'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(RC2CBCMechanism, self).to_c_mech() + effective_bits = self.params['usEffectiveBits'] + cbc_params = CK_RC2_CBC_PARAMS() + cbc_params.usEffectiveBits = CK_ULONG(effective_bits) + cbc_params.iv = (CK_BYTE * 8)(*self.params['iv']) + self.mech.pParameter = cast(pointer(cbc_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(cbc_params)) + return self.mech + + +class RC5Mechanism(Mechanism): + REQUIRED_PARAMS = ['ulWordsize', 'ulRounds'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(RC5Mechanism, self).to_c_mech() + rc5_params = CK_RC5_PARAMS() + rc5_params.ulWordsize = CK_ULONG(self.params['ulWordsize']) + rc5_params.ulRounds = CK_ULONG(self.params['ulRounds']) + self.mech.pParameter = cast(pointer(rc5_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(rc5_params)) + return self.mech + + +class RC5CBCMechanism(Mechanism): + REQUIRED_PARAMS = ['ulWordsize', 'ulRounds', 'iv'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(RC5CBCMechanism, self).to_c_mech() + rc5_params = CK_RC5_CBC_PARAMS() + rc5_params.ulWordsize = CK_ULONG(self.params['ulWordsize']) + rc5_params.ulRounds = CK_ULONG(self.params['ulRounds']) + iv, ivlen = to_byte_array(self.params['iv']) + rc5_params.pIv = cast(iv, CK_BYTE_PTR) + rc5_params.ulIvLen = ivlen + self.mech.pParameter = cast(pointer(rc5_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(rc5_params)) + return self.mech + + +class AESXTSMechanism(Mechanism): + REQUIRED_PARAMS = ['cb', 'hTweakKey'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(AESXTSMechanism, self).to_c_mech() + xts_params = CK_AES_XTS_PARAMS() + xts_params.cb = (CK_BYTE * 16)(*self.params['cb']) + xts_params.hTweakKey = CK_ULONG(self.params['hTweakKey']) + self.mech.pParameter = cast(pointer(xts_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(xts_params)) + return self.mech + + +class RSAPKCSOAEPMechanism(Mechanism): + REQUIRED_PARAMS = ['hashAlg', 'mgf', 'sourceData'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(RSAPKCSOAEPMechanism, self).to_c_mech() + oaep_params = CK_RSA_PKCS_OAEP_PARAMS() + oaep_params.hashAlg = CK_ULONG(self.params['hashAlg']) + oaep_params.mgf = CK_ULONG(self.params['mgf']) + # Note: According to + # https://www.cryptsoft.com/pkcs11doc/v220 + # /group__SEC__12__1__7__PKCS____1__RSA__OAEP__MECHANISM__PARAMETERS.html + # there is only one encoding parameter source. + oaep_params.source = CK_ULONG(CKZ_DATA_SPECIFIED) + data, data_len = to_byte_array(self.params['sourceData']) + oaep_params.pSourceData = data + oaep_params.ulSourceDataLen = data_len + + self.mech.pParameter = cast(pointer(oaep_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(oaep_params)) + return self.mech + + +class RSAPKCSPSSMechanism(Mechanism): + REQUIRED_PARAMS = ['hashAlg', 'mgf'] + + def to_c_mech(self): + """ + Uses default salt length of 8. + Can be overridden w/ a parameter though. + + :return: CK_MECHANISM + """ + super(RSAPKCSPSSMechanism, self).to_c_mech() + c_params = CK_RSA_PKCS_PSS_PARAMS() + c_params.hashAlg = CK_ULONG(self.params['hashAlg']) + c_params.mgf = CK_ULONG(self.params['mgf']) + c_params.usSaltLen = CK_ULONG(self.params.get('usSaltLen', 8)) + self.mech.pParameter = cast(pointer(c_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(c_params)) + return self.mech + + +class AESGCMMechanism(Mechanism): + REQUIRED_PARAMS = ['iv', 'AAD', 'ulTagBits'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: CK_MECHANISM + """ + super(AESGCMMechanism, self).to_c_mech() + gcm_params = CK_AES_GCM_PARAMS() + ivdata, ivlen = to_byte_array(self.params['iv']) + gcm_params.pIv = cast(ivdata, CK_BYTE_PTR) + gcm_params.ulIvLen = ivlen + # Assuming 8 bits per entry in IV. + gcm_params.ulIvBits = CK_ULONG(len(self.params['iv'] * 8)) + aad, aadlen = to_byte_array(self.params['AAD']) + gcm_params.pAAD = cast(aad, CK_BYTE_PTR) + gcm_params.ulAADLen = aadlen + gcm_params.ulTagBits = CK_ULONG(self.params['ulTagBits']) + self.mech.pParameter = cast(pointer(gcm_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(gcm_params)) + return self.mech + + +# TODO: xordf mech + +class NullMech(Mechanism): + """ + Class that creates a mechanism from a flavor with null parameters. + Used mostly for signing mechanisms that really don't need anything else. + """ + + def to_c_mech(self): + """ + Simply set the pParameter to null pointer. + :return: + """ + super(NullMech, self).to_c_mech() + self.mech.pParameter = c_void_p(0) + self.mech.usParameterLen = CK_ULONG(0) + return self.mech + + +class AutoMech(Mechanism): + """ + An attempt to examine underlying C Struct and fill in the appropriate fields, + making some assumptions about the data. This works best with parameter structs that only + have CK_ULONGs within them (though there is a best-effort attempt to handle arrays). + + .. warning : Do not use this if the mechanism is defined! + """ + + def to_c_mech(self): + """ + Attempt to handle generic mechanisms by introspection of the + structure. + :return: + """ + super(AutoMech, self).to_c_mech() + c_params_type = getattr(cryptoki, + self.params.get('params_name', "UNKNOWN"), + None) + if not c_params_type: + raise MechanismException("Failed to find a suitable " + "Ctypes Parameter Struct for type {}. " + "Make sure to set 'params_name' in the arguments!".format( + repr(self.mech_type))) + + fields = c_params_type._fields_ + c_params = c_params_type() + for name, c_type in fields: + # Check if it's an array. + if hasattr(c_type, '_length_'): + c_type = c_type._type_ + if c_type not in CONVERSIONS: + raise LunaException("Cannot convert to c_type: {}".format(c_type)) + ptr, length = CONVERSIONS[c_type](self.params[name]) + setattr(c_params, name, cast(ptr, POINTER(c_type))) + # Otherwise, do a direct conversion. + else: + # c_type = c_type._type_ + setattr(c_params, name, c_type(self.params[name])) + self.mech.pParameter = cast(pointer(c_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(c_params)) + return self.mech + + +MECH_LOOKUP = { + # Iv + CKM_DES_CBC: IvMechanism, + CKM_DES3_CBC: IvMechanism, + CKM_CAST3_CBC: IvMechanism, + CKM_CAST5_CBC: IvMechanism, + CKM_DES_CBC_PAD: IvMechanism, + CKM_DES3_CBC_PAD: IvMechanism, + CKM_DES3_CBC_PAD_IPSEC: IvMechanism, + CKM_CAST3_CBC_PAD: IvMechanism, + CKM_CAST5_CBC_PAD: IvMechanism, + CKM_AES_KW: IvMechanism, + CKM_AES_KWP: IvMechanism, + CKM_DES_CFB8: IvMechanism, + CKM_DES_CFB64: IvMechanism, + CKM_DES_OFB64: IvMechanism, + CKM_AES_CFB8: IvMechanism, + CKM_AES_CFB128: IvMechanism, + CKM_AES_OFB: IvMechanism, + CKM_ARIA_CFB8: IvMechanism, + CKM_ARIA_CFB128: IvMechanism, + CKM_ARIA_OFB: IvMechanism, + # Iv16 + CKM_SEED_CBC: Iv16Mechanism, + CKM_SEED_CBC_PAD: Iv16Mechanism, + CKM_AES_CBC: Iv16Mechanism, + CKM_AES_CBC_PAD: Iv16Mechanism, + CKM_AES_CBC_PAD_IPSEC: Iv16Mechanism, + CKM_ARIA_ECB: Iv16Mechanism, + CKM_ARIA_CBC: Iv16Mechanism, + CKM_ARIA_CBC_PAD: Iv16Mechanism, + # Others + CKM_RC2_ECB: RC2Mechanism, + CKM_RC2_MAC: RC2Mechanism, + CKM_RC2_CBC: RC2CBCMechanism, + CKM_RC2_CBC_PAD: RC2CBCMechanism, + CKM_RC5_CBC: RC5CBCMechanism, + CKM_RC5_ECB: RC5Mechanism, + + CKM_AES_XTS: AESXTSMechanism, + + CKM_RSA_PKCS_OAEP: RSAPKCSOAEPMechanism, + CKM_AES_GCM: AESGCMMechanism, + + CKM_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA1_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA224_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA256_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA384_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA512_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + + CKM_DES_ECB: NullMech, +} + + def get_c_struct_from_mechanism(python_dictionary, params_type_string): """Gets a c struct from a python dictionary representing that struct @@ -132,7 +518,3 @@ def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") return python_dictionary - - -if __name__ == '__main__': - pass diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 34c3762..4a092d5 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -12,15 +12,17 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from pycryptoki.attributes import Attributes, to_char_array -from pycryptoki.common_utils import refresh_c_arrays, AutoCArray -from pycryptoki.cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ +from .mechanism import Mechanism +from .mechanism import NullMech +from .attributes import Attributes, to_char_array +from .common_utils import refresh_c_arrays, AutoCArray +from .cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey -from pycryptoki.defines import CKR_OK -from pycryptoki.key_generator import _get_mechanism -from pycryptoki.sign_verify import do_multipart_sign_or_digest -from pycryptoki.test_functions import make_error_handle_function +from .defines import CKR_OK +from .key_generator import _get_mechanism +from .sign_verify import do_multipart_sign_or_digest +from .test_functions import make_error_handle_function def c_generate_random(h_session, length): @@ -62,7 +64,7 @@ def c_seed_random(h_session, seed): c_seed_random_ex = make_error_handle_function(c_seed_random) -def c_digest(h_session, data_to_digest, digest_flavor, mech=None): +def c_digest(h_session, data_to_digest, digest_flavor, mech=None, extra_params=None): """Digests some data :param h_session: Current session @@ -78,7 +80,10 @@ def c_digest(h_session, data_to_digest, digest_flavor, mech=None): # Get mechanism if none provided if mech is None: - mech = _get_mechanism(digest_flavor) + if extra_params is None: + mech = NullMech(digest_flavor).to_c_mech() + else: + mech = Mechanism(digest_flavor).to_c_mech() # Initialize Digestion ret = C_DigestInit(h_session, mech) @@ -121,7 +126,7 @@ def _digest(): c_digest_ex = make_error_handle_function(c_digest) -def c_digestkey(h_session, h_key, digest_flavor, mech=None): +def c_digestkey(h_session, h_key, digest_flavor, mech=None, extra_params=None): """ :param h_session: Logged in session handle @@ -132,7 +137,10 @@ def c_digestkey(h_session, h_key, digest_flavor, mech=None): """ # Get mechanism if none provided if mech is None: - mech = _get_mechanism(digest_flavor) + if extra_params is None: + mech = NullMech(digest_flavor).to_c_mech() + else: + mech = Mechanism(digest_flavor).to_c_mech() # Initialize Digestion ret = C_DigestInit(h_session, mech) diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 342a88f..0be4999 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -4,11 +4,11 @@ import logging from ctypes import byref, cast, c_void_p -from pycryptoki.attributes import Attributes, c_struct_to_python, KEY_TRANSFORMS -from pycryptoki.cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ +from .attributes import Attributes, c_struct_to_python, KEY_TRANSFORMS +from .cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ C_FindObjects, C_FindObjectsFinal, C_GetAttributeValue, C_SetAttributeValue -from pycryptoki.defines import CKR_OK -from pycryptoki.test_functions import make_error_handle_function +from .defines import CKR_OK +from .test_functions import make_error_handle_function LOG = logging.getLogger(__name__) diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py index a6e3cea..7447bfc 100644 --- a/pycryptoki/partition_management.py +++ b/pycryptoki/partition_management.py @@ -1,44 +1,44 @@ """ Functions for managing partitions """ +import logging from _ctypes import pointer from ctypes import byref, c_ubyte -import logging -from pycryptoki.cryptoki import (CK_SLOT_ID, - CK_ULONG, - CK_SESSION_HANDLE, - CA_CreateContainer, - CA_DeleteContainerWithHandle, - CA_GetContainerList, - CA_GetContainerCapabilitySet, - CA_GetContainerCapabilitySetting, - CA_GetContainerPolicySet, - CA_GetContainerPolicySetting, - CA_GetContainerName, - CA_GetContainerStorageInformation, - CA_GetContainerStatus, - CA_SetContainerPolicy, - CA_SetContainerPolicies, - CA_SetContainerSize) -from pycryptoki.defines import (LUNA_PARTITION_TYPE_STANDALONE, - LUNA_CF_CONTAINER_ENABLED, - LUNA_CF_KCV_CREATED, - LUNA_CF_LKCV_CREATED, - LUNA_CF_HA_INITIALIZED, - LUNA_CF_PARTITION_INITIALIZED, - LUNA_CF_CONTAINER_ACTIVATED, - LUNA_CF_CONTAINER_LUSR_ACTIVATED, - LUNA_CF_USER_PIN_INITIALIZED, - LUNA_CF_SO_PIN_LOCKED, - LUNA_CF_SO_PIN_TO_BE_CHANGED, - LUNA_CF_USER_PIN_LOCKED, - LUNA_CF_LIMITED_USER_PIN_LOCKED, - LUNA_CF_LIMITED_USER_CREATED, - LUNA_CF_USER_PIN_TO_BE_CHANGED, - LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED) -from pycryptoki.common_utils import AutoCArray, refresh_c_arrays -from pycryptoki.test_functions import make_error_handle_function +from .common_utils import AutoCArray, refresh_c_arrays +from .cryptoki import (CK_SLOT_ID, + CK_ULONG, + CK_SESSION_HANDLE, + CA_CreateContainer, + CA_DeleteContainerWithHandle, + CA_GetContainerList, + CA_GetContainerCapabilitySet, + CA_GetContainerCapabilitySetting, + CA_GetContainerPolicySet, + CA_GetContainerPolicySetting, + CA_GetContainerName, + CA_GetContainerStorageInformation, + CA_GetContainerStatus, + CA_SetContainerPolicy, + CA_SetContainerPolicies, + CA_SetContainerSize) +from .defines import (LUNA_PARTITION_TYPE_STANDALONE, + LUNA_CF_CONTAINER_ENABLED, + LUNA_CF_KCV_CREATED, + LUNA_CF_LKCV_CREATED, + LUNA_CF_HA_INITIALIZED, + LUNA_CF_PARTITION_INITIALIZED, + LUNA_CF_CONTAINER_ACTIVATED, + LUNA_CF_CONTAINER_LUSR_ACTIVATED, + LUNA_CF_USER_PIN_INITIALIZED, + LUNA_CF_SO_PIN_LOCKED, + LUNA_CF_SO_PIN_TO_BE_CHANGED, + LUNA_CF_USER_PIN_LOCKED, + LUNA_CF_LIMITED_USER_PIN_LOCKED, + LUNA_CF_LIMITED_USER_CREATED, + LUNA_CF_USER_PIN_TO_BE_CHANGED, + LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED) +from .test_functions import make_error_handle_function LOG = logging.getLogger(__name__) @@ -181,7 +181,8 @@ def ca_get_container_capability_setting(slot, h_container, capability_id): return ret, cap_val.value -ca_get_container_capability_setting_ex = make_error_handle_function(ca_get_container_capability_setting) +ca_get_container_capability_setting_ex = make_error_handle_function( + ca_get_container_capability_setting) def ca_get_container_policy_set(slot, h_container): @@ -257,6 +258,7 @@ def _ca_get_container_name(): cont_id, name_arr.array, name_arr.size) + ret = _ca_get_container_name() return ret, ''.join(map(chr, name_arr.array)) @@ -295,7 +297,8 @@ def ca_get_container_storage_information(slot, h_container): 'object_count': obj_count.value} -ca_get_container_storage_information_ex = make_error_handle_function(ca_get_container_storage_information) +ca_get_container_storage_information_ex = make_error_handle_function( + ca_get_container_storage_information) def ca_get_container_status(slot, h_container): @@ -342,7 +345,7 @@ def ca_get_container_status(slot, h_container): if status_flags.value ^ mask != 0: unknown_flags = [] for i in range(status_flags.value.bit_length()): - if((status_flags.value ^ mask) >> i) & 1: + if ((status_flags.value ^ mask) >> i) & 1: unknown_flags.append(2 ** i) raise Exception("Found unknown flags! {}".format(' '.join(unknown_flags))) for key, flag in flags_dict.iteritems(): diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index fb676d4..7d27b6c 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -10,7 +10,7 @@ from rpyc.core.protocol import PingError -from pycryptoki.daemon import rpyc_pycryptoki +from .daemon import rpyc_pycryptoki log = logging.getLogger(__name__) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index f47f545..f12c1c7 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -1,50 +1,48 @@ """ Methods responsible for managing a user's session and login/c_logout """ -from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ - byref, pointer import logging import re +from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ + byref, pointer # cryptoki constants -from pycryptoki.cryptoki import (CK_ULONG, - CK_BBOOL, - CK_SLOT_ID, - CK_SLOT_INFO, - CK_SESSION_HANDLE, - CK_FLAGS, - CK_NOTIFY, - CK_SESSION_INFO, - CK_USER_TYPE, - CK_TOKEN_INFO, - CK_VOID_PTR, - CK_BYTE) +from .cryptoki import (CK_ULONG, + CK_BBOOL, + CK_SLOT_ID, + CK_SLOT_INFO, + CK_SESSION_HANDLE, + CK_FLAGS, + CK_NOTIFY, + CK_SESSION_INFO, + CK_USER_TYPE, + CK_TOKEN_INFO, + CK_VOID_PTR, + CK_BYTE) # Cryptoki Functions -from pycryptoki.cryptoki import (C_Initialize, - C_GetSlotList, - C_GetSlotInfo, - C_CloseAllSessions, - C_GetSessionInfo, - C_OpenSession, - C_Login, - C_Logout, - C_CloseSession, - C_InitPIN, - CA_FactoryReset, - C_GetTokenInfo, - C_Finalize, - C_SetPIN, - CA_DeleteContainerWithHandle, - CA_OpenApplicationID, - CA_CloseApplicationID, - CA_Restart, - CA_CreateContainer, - CA_SetApplicationID) - -from pycryptoki.common_utils import AutoCArray, refresh_c_arrays -from pycryptoki.defines import CKR_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION -from pycryptoki.test_functions import make_error_handle_function +from .cryptoki import (C_Initialize, + C_GetSlotList, + C_GetSlotInfo, + C_CloseAllSessions, + C_GetSessionInfo, + C_OpenSession, + C_Login, + C_Logout, + C_CloseSession, + C_InitPIN, + CA_FactoryReset, + C_GetTokenInfo, + C_Finalize, + C_SetPIN, + CA_OpenApplicationID, + CA_CloseApplicationID, + CA_Restart, + CA_SetApplicationID) + +from .common_utils import AutoCArray, refresh_c_arrays +from .defines import CKR_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION +from .test_functions import make_error_handle_function LOG = logging.getLogger(__name__) diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 35eea9f..9397552 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -3,129 +3,23 @@ """ import logging from _ctypes import POINTER -from ctypes import create_string_buffer, cast, byref, sizeof, pointer, c_void_p, string_at, c_ubyte +from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from cryptoki import CK_MECHANISM, CK_MECHANISM_TYPE, CK_VOID_PTR, CK_ULONG, \ +from cryptoki import CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign -from defines import CKR_OK, CKM_RSA_PKCS_PSS, CKM_SHA1_RSA_PKCS_PSS, \ - CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, \ - CKM_SHA512_RSA_PKCS_PSS, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, \ - CKM_SHA512, CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, \ - CKG_MGF1_SHA512 -from pycryptoki.attributes import to_char_array -from pycryptoki.common_utils import refresh_c_arrays, AutoCArray -from pycryptoki.cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ - C_SignFinal, C_VerifyUpdate, C_VerifyFinal, CK_RSA_PKCS_PSS_PARAMS -from pycryptoki.encryption import _get_string_from_list -from pycryptoki.test_functions import make_error_handle_function +from defines import CKR_OK +from .attributes import to_char_array +from .common_utils import refresh_c_arrays, AutoCArray +from .cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ + C_SignFinal, C_VerifyUpdate, C_VerifyFinal +from .encryption import _get_string_from_list +from .mechanism import Mechanism, NullMech +from .test_functions import make_error_handle_function LOG = logging.getLogger(__name__) -def get_custom_mech_for_sigver(sigver_mech, algorithm, mask=None, salt_len=8): - """ - Generate a mechanism for signing/verifying operations with RSA PKCS PSS - variants. Use the specified algorithm in the returned CK_MECHANISM object. - - Note: - - PKCS #1 recommends using a mask generation algorithm based on the hash - algorithm used for hashing. I.e., if CKM_SHA224 is used to hash, - CKG_MGF1_SHA224 _should_ be used for mask generation. - - Algorithm must be one of: - CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, CKM_SHA512 - - Mask must be one of: - CKG_MGF1_SHA1, CKG_MGF1_SHA224, CKG_MGF1_SHA256, CKG_MGF1_SHA384, CKG_MGF1_SHA512 - - :param sigver_mech: signing/verifying mechanism - :param algorithm: hashing algorithm - :param mask: mask generation function; if None, use matching - :param salt_len: length of salt - :return: CK_MECHANISM with PSS parameters configured - """ - if mask is None: - masks = {CKM_SHA_1: CKG_MGF1_SHA1, - CKM_SHA224: CKG_MGF1_SHA224, - CKM_SHA256: CKG_MGF1_SHA256, - CKM_SHA384: CKG_MGF1_SHA384, - CKM_SHA512: CKG_MGF1_SHA512} - mask = masks[algorithm] - - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(sigver_mech) - - params = CK_RSA_PKCS_PSS_PARAMS() - params.hashAlg = CK_ULONG(algorithm) - params.mgf = CK_ULONG(mask) - params.usSaltLen = CK_ULONG(salt_len) - - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params)) - return mech - - -def get_mechanism_for_sigver(flavour): - """ - Try to build a default mechanism if none is provided, - most mechanisms just need the .pParameter field to be null. - If they don't the mechanism can be instantiated here. - - :param flavour: signing/verifying mechanism - :return: CK_MECHANISM with PSS parameters configured - """ - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(flavour) - - default_salt_len = 8 - if flavour == CKM_RSA_PKCS_PSS or flavour == CKM_SHA1_RSA_PKCS_PSS: - params = CK_RSA_PKCS_PSS_PARAMS() - params.hashAlg = CK_ULONG(CKM_SHA_1) - params.mgf = CK_ULONG(CKG_MGF1_SHA1) - params.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params)) - elif flavour == CKM_SHA224_RSA_PKCS_PSS: - params = CK_RSA_PKCS_PSS_PARAMS() - params.hashAlg = CK_ULONG(CKM_SHA224) - params.mgf = CK_ULONG(CKG_MGF1_SHA224) - params.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params)) - elif flavour == CKM_SHA256_RSA_PKCS_PSS: - params = CK_RSA_PKCS_PSS_PARAMS() - params.hashAlg = CK_ULONG(CKM_SHA256) - params.mgf = CK_ULONG(CKG_MGF1_SHA256) - params.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params)) - elif flavour == CKM_SHA384_RSA_PKCS_PSS: - params = CK_RSA_PKCS_PSS_PARAMS() - params.hashAlg = CK_ULONG(CKM_SHA384) - params.mgf = CK_ULONG(CKG_MGF1_SHA384) - params.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params)) - elif flavour == CKM_SHA512_RSA_PKCS_PSS: - params = CK_RSA_PKCS_PSS_PARAMS() - params.hashAlg = CK_ULONG(CKM_SHA512) - params.mgf = CK_ULONG(CKG_MGF1_SHA512) - params.usSaltLen = CK_ULONG(default_salt_len) - - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params)) - else: - mech.pParameter = CK_VOID_PTR(0) - mech.usParameterLen = CK_ULONG(0) - return mech - - -def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=None): +def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, extra_params=None): """ Performs a C_SignInit and C_Sign operation on some data @@ -143,16 +37,17 @@ def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, algorithm=Non :param h_key: The key to sign the data with :param mech: The mechanism to use, if None a blank mechanism will be created based on the sign_flavor - :param algorithm: The hash algorithm used on data_to_sign; only necessary for RSA PKCS PSS + :param extra_params: Parameters to be passed to the mechanism creation. If None, blank mechanism + will be used. :return: The result code, A python string representing the signature """ # Get the mechanism if mech is None: - mech = get_mechanism_for_sigver(sign_flavor) - - if algorithm is not None: - mech = get_custom_mech_for_sigver(sign_flavor, algorithm) + if extra_params is None: + mech = NullMech(sign_flavor).to_c_mech() + else: + mech = Mechanism(sign_flavor, params=extra_params).to_c_mech() # Initialize the sign operation ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) @@ -287,7 +182,8 @@ def do_multipart_verify(h_session, input_data_list, signature): return ret -def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=None, algorithm=None): +def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=None, + extra_params=None): """ Return the result code of C_Verify which indicates whether or not the signature is valid. @@ -314,10 +210,10 @@ def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=No # Get the mechanism if mech is None: - mech = get_mechanism_for_sigver(verify_flavor) - - if algorithm is not None: - mech = get_custom_mech_for_sigver(verify_flavor, algorithm) + if extra_params is None: + mech = NullMech(verify_flavor).to_c_mech() + else: + mech = Mechanism(verify_flavor, extra_params).to_c_mech() # Initialize the verify operation ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index be6fb13..8a7fc99 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -4,10 +4,10 @@ from functools import wraps from defines import CKR_OK -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize -from pycryptoki.defines import CKR_OBJECT_HANDLE_INVALID from return_values import ret_vals_dictionary +from .attributes import Attributes +from .cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize +from .defines import CKR_OBJECT_HANDLE_INVALID LOG = logging.getLogger(__name__) @@ -41,19 +41,6 @@ def assert_test_return_value(value, expected_value, message, print_on_success=Tr LOG.info(exp_code + ": " + message) -def assert_test_case(result, message, print_on_success=False): - """Simple wrapper around assert that allows for a consistent way to report successes/failures - - :param result: A boolean representing the result of the test - :param message: The message to print on test failure - :param print_on_success: (Default value = False) - - """ - assert result, "\nERROR: " + message - if print_on_success: - LOG.info("PASSED: " + message) - - class LunaException(Exception): """A class representing an exception in luna, it's in place because it has some nice functionailty to print out the contents of the error @@ -105,21 +92,20 @@ def verify_object_attributes(h_session, h_object, expected_template): :param expected_template: The expected template to compare against """ + from .object_attr_lookup import c_get_attribute_value_ex # VERIFY OBJECT EXISTS h_object = CK_OBJECT_HANDLE(h_object) us_size = CK_ULONG() ret = C_GetObjectSize(h_session, h_object, byref(us_size)) - assert_test_case(ret == CKR_OK, "Object " + str(h_object) + " exists") - assert_test_case(us_size.value > 0, - "Object " + str(h_object.value) + " size is greater than zero.") + assert ret == CKR_OK, "Object " + str(h_object) + " exists" + assert us_size.value > 0, \ + "Object " + str(h_object.value) + " size is greater than zero." # VERIFY ATTRIBUTES are the same as the ones passed in - attr = Attributes() - attr.retrieve_key_attributes(h_session, h_object.value) - expected_attributes = Attributes(expected_template) - assert_test_case(attr == expected_attributes, - "Object " + str(h_object.value) + " attributes match expected attributes") + desired_attrs = {x: None for x in expected_template.keys()} + attr = c_get_attribute_value_ex(h_session, h_object, template=desired_attrs) + assert attr == expected_template def verify_object_exists(h_session, h_object, should_exist=True): @@ -145,21 +131,21 @@ def verify_object_exists(h_session, h_object, should_exist=True): try: ret = C_GetObjectSize(h_session, h_object, byref(us_size)) except LunaException as e: - assert_test_case(e.error_code == expected_ret, out) + assert e.error_code == expected_ret, out else: - assert_test_case(ret == expected_ret, out) + assert ret == expected_ret, out if should_exist: assert_test_return_value(ret, CKR_OK, "Getting object " + str(h_object.value) + "'s size", True) - assert_test_case(us_size.value > 0, - "Object " + str(h_object.value) + " size is greater than zero.", False) + assert us_size.value > 0, \ + "Object " + str(h_object.value) + " size is greater than zero." else: assert_test_return_value(ret, CKR_OBJECT_HANDLE_INVALID, "Getting object " + str(h_object.value) + "'s size", True) - assert_test_case(us_size.value <= 0, - "Object " + str(h_object.value) + " size is greater than zero.", False) + assert us_size.value <= 0, \ + "Object " + str(h_object.value) + " size is greater than zero." def check_luna_exception(ret, luna_function, args): diff --git a/pycryptoki/tests/functional/__init__.py b/pycryptoki/tests/functional/__init__.py new file mode 100644 index 0000000..fcd8c8e --- /dev/null +++ b/pycryptoki/tests/functional/__init__.py @@ -0,0 +1 @@ +config = {} diff --git a/pycryptoki/tests/functional/conftest.py b/pycryptoki/tests/functional/conftest.py new file mode 100644 index 0000000..2257644 --- /dev/null +++ b/pycryptoki/tests/functional/conftest.py @@ -0,0 +1,111 @@ +""" +Fixtures for pycryptoki functional tests +""" +import os + +import pytest + +from . import config as hsm_config +from ...defaults import ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL, CO_PASSWORD +from ...defines import CKF_RW_SESSION, CKF_SERIAL_SESSION, CKF_PROTECTED_AUTHENTICATION_PATH +from ...defines import CKF_SO_SESSION +from ...session_management import c_initialize_ex, c_close_all_sessions_ex, \ + ca_factory_reset_ex, c_open_session_ex, login_ex, c_finalize_ex, \ + c_close_session, c_logout, c_get_token_info_ex +from ...token_management import c_init_token_ex + + +def pytest_addoption(parser): + """ + Set up some commandline options so we can specify what we want to test. + """ + optiongroup = parser.getgroup("pycryptoki", "Pycryptoki test options") + + optiongroup.addoption("--slot", + help="Specify the admin slot of the HSM you are testing on", + type=int, + default=os.environ.get("ADMIN_SLOT", 1), + dest="test_slot") + + +def pytest_configure(config): + """ + Set up the globals for this test run. + """ + hsm_config["test_slot"] = config.getoption("test_slot") + c_initialize_ex() + try: + # Factory Reset + slot = hsm_config["test_slot"] + + token_info = c_get_token_info_ex(slot) + flags = token_info['flags'] + is_ped = (flags & CKF_PROTECTED_AUTHENTICATION_PATH) != 0 + hsm_config["is_ped"] = is_ped + + if is_ped: + admin_pwd = None + co_pwd = None + else: + admin_pwd = ADMINISTRATOR_PASSWORD + co_pwd = CO_PASSWORD + hsm_config['admin_pwd'] = admin_pwd + hsm_config['co_pwd'] = co_pwd + finally: + c_finalize_ex() + + +@pytest.yield_fixture(scope='session', autouse=True) +def hsm_configured(): + """ + Factory reset & init the hsm. + """ + c_initialize_ex() + try: + slot = hsm_config["test_slot"] + c_close_all_sessions_ex(slot) + ca_factory_reset_ex(slot) + + # Initialize the Admin Token + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + + _ = c_open_session_ex(slot, session_flags) + c_init_token_ex(slot, hsm_config['admin_pwd'], ADMIN_PARTITION_LABEL) + + # TODO: This will need to change for testing on CO slots. + # In the meantime, we test on the admin slot just fine. + # slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + # c_close_all_sessions_ex(slot) + # h_session = c_open_session_ex(slot, session_flags) + # login_ex(h_session, slot, hsm_config['admin_pwd'], 0) + # c_init_pin_ex(h_session, hsm_config['co_pwd']) + # c_logout_ex(h_session) + c_close_all_sessions_ex(slot) + yield + finally: + c_finalize_ex() + + +@pytest.yield_fixture(scope="class") +def session(hsm_configured): + """ + Creates & returns a session on the Admin slot. + """ + _ = hsm_configured + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + + slot = hsm_config["test_slot"] + h_session = c_open_session_ex(slot, session_flags) + yield h_session + c_close_session(slot) + + +@pytest.yield_fixture(scope="class") +def auth_session(session): + """ + Logs into the created admin session + """ + slot = hsm_config["test_slot"] + login_ex(session, slot, hsm_config["admin_pwd"], 0) + yield session + c_logout(session) diff --git a/pycryptoki/tests/test_cka_start_and_end.py b/pycryptoki/tests/functional/test_cka_start_and_end.py similarity index 53% rename from pycryptoki/tests/test_cka_start_and_end.py rename to pycryptoki/tests/functional/test_cka_start_and_end.py index e6777bd..a28caf6 100755 --- a/pycryptoki/tests/test_cka_start_and_end.py +++ b/pycryptoki/tests/functional/test_cka_start_and_end.py @@ -1,52 +1,41 @@ -from datetime import datetime import logging import os +from datetime import datetime import pytest -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL -from pycryptoki.defines import CKF_SERIAL_SESSION,CKM_DES_KEY_GEN, CKU_USER, \ - CKA_END_DATE, CKU_AUDIT, CKF_AUDIT_SESSION -from pycryptoki.defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ +from . import config as hsm_config +from ...audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex +from ...default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 +from ...defaults import CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL +from ...defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ CKK_AES, CKM_DES_ECB, CKR_KEY_NOT_ACTIVE, CKM_RSA_PKCS_KEY_PAIR_GEN, \ CKM_RSA_PKCS, CKM_AES_ECB, CKM_AES_KEY_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA_SHA1 -from pycryptoki.default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex -from pycryptoki.session_management import c_initialize_ex, login, c_finalize, c_open_session_ex, login_ex, \ - c_logout_ex, c_close_session_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -from pycryptoki.attributes import date_attrb -from pycryptoki.dictionary_handling import CDict -from pycryptoki.encryption import c_encrypt, c_encrypt_ex -from pycryptoki.audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex -from pycryptoki.sign_verify import c_sign_ex, c_sign +from ...defines import CKF_SERIAL_SESSION, CKM_DES_KEY_GEN, CKU_USER, \ + CKA_END_DATE, CKU_AUDIT, CKF_AUDIT_SESSION +from ...encryption import c_encrypt, c_encrypt_ex +from ...key_generator import c_generate_key_ex, c_generate_key_pair_ex +from ...session_management import login, c_open_session_ex, login_ex, \ + c_logout_ex, c_close_session_ex +from ...sign_verify import c_sign_ex, c_sign logger = logging.getLogger(__name__) -class TestCKAStartEndDate: + + +@pytest.mark.xfail(run=False, reason="Changes date on HSM") +class TestCKAStartEndDate(object): """ """ h_session = 0 admin_slot = 0 - def setup(self): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - c_finalize() - + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.admin_slot = hsm_config["test_slot"] + self.h_session = auth_session def test_symmetric_key_expiry_des(self): """Test: Verify that user is not able to use the symmetric object after date specified in @@ -60,38 +49,35 @@ def test_symmetric_key_expiry_des(self): """ - logger.info("Test: Verify that user is not able to use the symmetric object after date specified in \ + logger.info("Test: Verify that user is not able to use the symmetric object after date " + "specified in \ CKA_END_DATE attribute") - end_d = date_attrb + end_d = {} end_d['year'] = "2013" end_d['month'] = "12" end_d['day'] = "31" - CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_DES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 8, - CKA_EXTRACTABLE :True, - CKA_LABEL : "DES Key", - CKA_END_DATE : CDict(end_d)} - - + CKM_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_DES, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 8, + CKA_EXTRACTABLE: True, + CKA_LABEL: "DES Key", + CKA_END_DATE: end_d} h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) - - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, "a" * 512) c_logout_ex(self.h_session) @@ -99,10 +85,11 @@ def test_symmetric_key_expiry_des(self): ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + h_session2 = c_open_session_ex(slot_num=self.admin_slot, + flags=(CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - dt = datetime(2014, 1 , 31) + dt = datetime(2014, 1, 31) epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() @@ -124,9 +111,9 @@ def test_symmetric_key_expiry_des(self): c_logout_ex(h_session) c_close_session_ex(h_session) - def test_symmetric_key_expiry_aes(self): - """Test: Verify that user is not able to use the symmetric aes object after date specified in + """Test: Verify that user is not able to use the symmetric aes object after date + specified in CKA_END_DATE attribute Procedure: Generate a AES key aes1 @@ -137,36 +124,34 @@ def test_symmetric_key_expiry_aes(self): """ - logger.info("Test: Verify that user is not able to use the symmetric aes object after date specified in \ + logger.info("Test: Verify that user is not able to use the symmetric aes object after " + "date specified in \ CKA_END_DATE attribute") - end_d = date_attrb + end_d = {} end_d['year'] = "2013" end_d['month'] = "12" end_d['day'] = "31" - CKM_KEY_GEN_TEMP = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_AES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "AES Key", - CKA_END_DATE : CDict(end_d)} - - + CKM_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_AES, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 16, + CKA_EXTRACTABLE: True, + CKA_LABEL: "AES Key", + CKA_END_DATE: end_d} h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") c_logout_ex(self.h_session) @@ -174,10 +159,11 @@ def test_symmetric_key_expiry_aes(self): ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + h_session2 = c_open_session_ex(slot_num=self.admin_slot, + flags=(CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - dt = datetime(2014, 1 , 31) + dt = datetime(2014, 1, 31) epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() @@ -196,9 +182,9 @@ def test_symmetric_key_expiry_aes(self): logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - def test_asymmetric_key_expiry_rsa(self): - """Test: Verify that user is not able to use the rsa asymmetric object after date specified in + """Test: Verify that user is not able to use the rsa asymmetric object after date + specified in CKA_END_DATE attribute Procedure: Generate a rsa Key rsa1 @@ -209,42 +195,43 @@ def test_asymmetric_key_expiry_rsa(self): """ - logger.info("Test: Verify that user is not able to use the rsa asymmetric object after date specified in \ + logger.info("Test: Verify that user is not able to use the rsa asymmetric object after " + "date specified in \ CKA_END_DATE attribute") - end_d = date_attrb + end_d = {} end_d['year'] = "2013" end_d['month'] = "12" end_d['day'] = "31" - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_MODIFIABLE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_MODULUS_BITS : 1024, #long 0 - MAX_RSA_KEY_NBITS - CKA_PUBLIC_EXPONENT : 3, #byte - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "RSA Public Key"} - - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_MODIFIABLE : True, - CKA_EXTRACTABLE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "RSA Private Key"} - - + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_MODIFIABLE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_MODULUS_BITS: 1024, # long 0 - MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT: 3, # byte + CKA_END_DATE: end_d, + CKA_LABEL: "RSA Public Key"} + + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_MODIFIABLE: True, + CKA_EXTRACTABLE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_UNWRAP: True, + CKA_END_DATE: end_d, + CKA_LABEL: "RSA Private Key"} h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info( + "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( + h_prkey)) c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") @@ -253,10 +240,11 @@ def test_asymmetric_key_expiry_rsa(self): ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + h_session2 = c_open_session_ex(slot_num=self.admin_slot, + flags=(CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - dt = datetime(2014, 1 , 31) + dt = datetime(2014, 1, 31) epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() @@ -264,7 +252,7 @@ def test_asymmetric_key_expiry_rsa(self): ca_time_sync_ex(h_session2, hsm_new_date) hsm_time = ca_get_time_ex(h_session2) -# print datetime.fromtimestamp(float(hsm_time.value)) + # print datetime.fromtimestamp(float(hsm_time.value)) c_logout_ex(h_session2) c_close_session_ex(h_session2) @@ -275,9 +263,9 @@ def test_asymmetric_key_expiry_rsa(self): logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - def test_asymmetric_key_expiry_dsa(self): - """Test: Verify that user is not able to use the dsa asymmetric object after date specified in + """Test: Verify that user is not able to use the dsa asymmetric object after date + specified in CKA_END_DATE attribute Procedure: Generate a DSA Key dsa1 @@ -288,55 +276,55 @@ def test_asymmetric_key_expiry_dsa(self): """ - logger.info("Test: Verify that user is not able to use the dsa asymmetric object after date specified in \ + logger.info("Test: Verify that user is not able to use the dsa asymmetric object after " + "date specified in \ CKA_END_DATE attribute") - end_d = date_attrb + end_d = {} end_d['year'] = "2013" end_d['month'] = "12" end_d['day'] = "31" - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_PRIME : dsa_prime_1024_160, - CKA_SUBPRIME : dsa_sub_prime_1024_160, - CKA_BASE : dsa_base_1024_160, - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "DSA 1024_160 Public Key"} - - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN : True, - CKA_PRIVATE : True, - CKA_SENSITIVE : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_UNWRAP : True, - CKA_EXTRACTABLE : True, - CKA_END_DATE : CDict(end_d), - CKA_LABEL : "DSA Public Key"} - - + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_PRIME: dsa_prime_1024_160, + CKA_SUBPRIME: dsa_sub_prime_1024_160, + CKA_BASE: dsa_base_1024_160, + CKA_END_DATE: end_d, + CKA_LABEL: "DSA 1024_160 Public Key"} + + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_UNWRAP: True, + CKA_EXTRACTABLE: True, + CKA_END_DATE: end_d, + CKA_LABEL: "DSA Public Key"} h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_DSA_KEY_PAIR_GEN, - pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, - prkey_template=CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) + pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + prkey_template=CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info( + "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( + h_prkey)) c_sign_ex(self.h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) - - c_logout_ex(self.h_session) c_close_session_ex(self.h_session) ca_init_audit_ex(self.admin_slot, AUDITOR_PASSWORD, AUDITOR_LABEL) - h_session2 = c_open_session_ex(slot_num=self.admin_slot, flags = (CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) + h_session2 = c_open_session_ex(slot_num=self.admin_slot, + flags=(CKF_SERIAL_SESSION | CKF_AUDIT_SESSION)) login_ex(h_session2, self.admin_slot, AUDITOR_PASSWORD, CKU_AUDIT) - dt = datetime(2014, 1 , 31) + dt = datetime(2014, 1, 31) epoch = datetime.utcfromtimestamp(0) delta = dt - epoch hsm_dt = delta.total_seconds() @@ -344,7 +332,7 @@ def test_asymmetric_key_expiry_dsa(self): ca_time_sync_ex(h_session2, hsm_new_date) hsm_time = ca_get_time_ex(self.h_session) -# print datetime.fromtimestamp(float(hsm_time.value)) + # print datetime.fromtimestamp(float(hsm_time.value)) c_logout_ex(h_session2) c_close_session_ex(h_session2) @@ -356,10 +344,6 @@ def test_asymmetric_key_expiry_dsa(self): assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - - if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) - - diff --git a/pycryptoki/tests/functional/test_digest_data.py b/pycryptoki/tests/functional/test_digest_data.py new file mode 100755 index 0000000..caa80ed --- /dev/null +++ b/pycryptoki/tests/functional/test_digest_data.py @@ -0,0 +1,44 @@ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...defines import CKM_MD2, CKR_OK +from ...encryption import _get_string_from_list +from ...misc import c_digest + +logger = logging.getLogger(__name__) + + +class TestDigestData(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.admin_slot = hsm_config["test_slot"] + self.h_session = auth_session + + def test_digest_data(self): + """Calls C_Digest on some data and makes sure there is no failure""" + data_to_digest = "Some arbitrary string" + ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) + assert ret == CKR_OK, "Digesting should occur with no errors" + assert len(digested_data) > 0, "The digested data should have a length" + assert data_to_digest != digested_data, "The digested data should not be the same as the " \ + "original string" + + def test_multipart_digest_data(self): + """ """ + data_to_digest = ["Some arbitrary string", "Some second arbitrary string"] + ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) + assert ret == CKR_OK, "Digesting should occur with no errors" + assert len(digested_data) > 0, "The digested data should have a length" + assert _get_string_from_list( + data_to_digest) != digested_data, "The digested data should not be the same as the " \ + "original string" + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_encrypt_decrypt.py b/pycryptoki/tests/functional/test_encrypt_decrypt.py new file mode 100755 index 0000000..35904b1 --- /dev/null +++ b/pycryptoki/tests/functional/test_encrypt_decrypt.py @@ -0,0 +1,70 @@ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...default_templates import CKM_DES_KEY_GEN_TEMP +from ...defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK +from ...encryption import c_encrypt, c_decrypt, _split_string_into_list, \ + _get_string_from_list +from ...key_generator import c_generate_key_ex +from ...return_values import ret_vals_dictionary + +logger = logging.getLogger(__name__) + + +class TestEncryptData(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.admin_slot = hsm_config["test_slot"] + self.h_session = auth_session + + def test_encrypt_decrypt_string(self): + """Tests encrypting and decrypting a string with a key""" + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + data_to_encrypt = "a" * 0xfff0 + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, \ + "Encryption should go through successfully, instead it returned " + \ + ret_vals_dictionary[ret] + + ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data) + assert ret == CKR_OK, \ + "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] + assert decrypted_string == data_to_encrypt, \ + "The decrypted data should be the same as the " \ + "data that was encrypted. Instead found " + str(decrypted_string) + + def test_multipart_encrypt_decrypt(self): + """Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore + doing it in multiple + parts + + + """ + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + data_to_encrypt = ['a' * 512, 'b' * 512, 'c' * 512, 'd' * 512] + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + \ + ret_vals_dictionary[ret] + assert len(encrypted_data) == len(_get_string_from_list(data_to_encrypt)) + + encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) + + ret, decrypted_data = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data_chunks) + assert ret == CKR_OK, "Decryption should succeed, instead it returned " + \ + ret_vals_dictionary[ret] + assert _get_string_from_list( + data_to_encrypt) == decrypted_data, "The data before encryption should match the data " \ + "" \ + "after encryption" + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_get_token_info.py b/pycryptoki/tests/functional/test_get_token_info.py new file mode 100755 index 0000000..13255d2 --- /dev/null +++ b/pycryptoki/tests/functional/test_get_token_info.py @@ -0,0 +1,82 @@ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD +from ...defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ + CKF_RESTORE_KEY_NOT_NEEDED, CKF_TOKEN_INITIALIZED, CKF_SERIAL_SESSION, CKF_SO_SESSION, \ + CKF_RW_SESSION +from ...session_management import ca_factory_reset_ex, \ + c_get_token_info_ex, c_close_all_sessions, c_close_all_sessions_ex, \ + c_open_session_ex +from ...token_management import get_token_by_label_ex, c_init_token_ex + +logger = logging.getLogger(__name__) + + +@pytest.yield_fixture(scope="class", autouse=True) +def reset_to_defaults(): + yield + # Factory Reset + slot = hsm_config['test_slot'] + + c_close_all_sessions_ex(slot) + ca_factory_reset_ex(slot) + + # Initialize the Admin Token + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + + h_session = c_open_session_ex(slot, session_flags) + c_init_token_ex(slot, hsm_config['admin_pwd'], ADMIN_PARTITION_LABEL) + + # TODO: change this for ppso hardware. + # slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + # c_close_all_sessions_ex(slot) + # h_session = c_open_session_ex(slot, session_flags) + # login_ex(h_session, slot, ADMINISTRATOR_PASSWORD, 0) + # c_init_pin_ex(h_session, CO_PASSWORD) + # c_logout_ex(h_session) + c_close_all_sessions_ex(slot) + + +class TestGetTokenInfo(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + def test_initial_flags(self): + """ """ + admin_slot = self.admin_slot + + # Get to clean state + c_close_all_sessions(admin_slot) + ca_factory_reset_ex(admin_slot) + + # Look at flags before initialization + flags = c_get_token_info_ex(admin_slot)['flags'] + expected_flags = CKF_TOKEN_PRESENT | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED + assert expected_flags & flags != 0, "After factory reset found flags " + str( + hex(flags)) + " on admin partition should match expected flags" + str( + hex(expected_flags)) + + c_init_token_ex(admin_slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) + + # Test flags after initialization + flags = c_get_token_info_ex(admin_slot)['flags'] + expected_flags = expected_flags | CKF_TOKEN_INITIALIZED + assert flags & expected_flags != 0, "After initialization found flags " + str( + hex(flags)) + " on admin partition should match expected flags" + str( + hex(expected_flags)) + logger.info("After initialization found flags " + str( + hex(flags)) + " on admin partition should match expected flags" + str( + hex(expected_flags))) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_hsm_management.py b/pycryptoki/tests/functional/test_hsm_management.py similarity index 58% rename from pycryptoki/tests/test_hsm_management.py rename to pycryptoki/tests/functional/test_hsm_management.py index 2bd0d2d..5eecab3 100755 --- a/pycryptoki/tests/test_hsm_management.py +++ b/pycryptoki/tests/functional/test_hsm_management.py @@ -1,60 +1,37 @@ """ Test methods for pycryptoki 'hsm management' set of commands. """ -from ctypes import create_string_buffer, cast -from pycryptoki.cryptoki import CK_ULONG, CK_BYTE, CK_BYTE_PTR -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKU_CRYPTO_USER, CKR_OK, \ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP +from ...defines import CKU_CRYPTO_USER, CKR_OK, \ CKR_ATTRIBUTE_VALUE_INVALID, CKR_CANCEL, CKR_USER_NOT_AUTHORIZED, \ CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_AES, CKA_TOKEN, \ CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, \ CKA_VERIFY, CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, \ CKA_EXTRACTABLE, CKA_LABEL, LUNA_TTYPE_CRYPTO, LUNA_TTYPE_RNG, \ LUNA_DSS_SIGVERIFY_TEST -from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -from pycryptoki.hsm_management import c_performselftest, \ - ca_settokencertificatesignature, ca_hainit, ca_createloginchallenge, \ +from ...hsm_management import ca_settokencertificatesignature, ca_hainit, ca_createloginchallenge, \ ca_initializeremotepedvector, ca_deleteremotepedvector, ca_mtkrestore, \ - ca_mtkresplit, ca_mtkzeroize -from pycryptoki.key_generator import c_generate_key_pair -import logging -import os -import pytest + ca_mtkresplit, ca_mtkzeroize, c_performselftest +from ...key_generator import c_generate_key_pair +from ...return_values import ret_vals_dictionary -class TestAlgorithm: +class TestAlgorithm(object): """Test algorithm class""" h_session = 0 admin_slot = 0 - @classmethod - def setup_class(cls): - """Setup class""" - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """Finalize tests""" - c_finalize_ex() - - def setup(self): - """Setup test""" - self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """Teardown test""" - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] @pytest.mark.parametrize("test_type", [LUNA_TTYPE_CRYPTO, @@ -66,45 +43,42 @@ def test_performselftest(self, test_type): :param test_type: test type """ - input_data = (CK_BYTE*1000)() - input_length = CK_ULONG(1000) + input_data = range(1000) + input_length = 1000 - ret = c_performselftest(self.admin_slot, - test_type, - input_data, - input_length) + ret, data = c_performselftest(self.admin_slot, + test_type, + input_data, + input_length) assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - def test_settokencertsignature(self): """Tests set token certificate signature To do: fix attribute value - - """ - gen_temp = {CKA_CLASS : CKO_SECRET_KEY, - CKA_KEY_TYPE : CKK_AES, - CKA_TOKEN : True, - CKA_SENSITIVE : True, - CKA_PRIVATE : True, - CKA_ENCRYPT : True, - CKA_DECRYPT : True, - CKA_SIGN : True, - CKA_VERIFY : True, - CKA_WRAP : True, - CKA_UNWRAP : True, - CKA_DERIVE : True, - CKA_VALUE_LEN : 16, - CKA_EXTRACTABLE :True, - CKA_LABEL : "AES Key"} - - access_level = CK_ULONG(1) - customer_id = CK_ULONG(1) + gen_temp = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_AES, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 16, + CKA_EXTRACTABLE: True, + CKA_LABEL: "AES Key"} + + access_level = 1 + customer_id = 1 pub_template = gen_temp - signature = (CK_BYTE*4000)() - signature_length = CK_ULONG(4000) + signature = range(4000) + signature_length = 4000 ret = ca_settokencertificatesignature(self.h_session, access_level, @@ -117,13 +91,12 @@ def test_settokencertsignature(self): ret_vals_dictionary[CKR_ATTRIBUTE_VALUE_INVALID] + \ " not " + ret_vals_dictionary[ret] - def test_hainit(self): """Tests performs HA init""" ret, pubkey_h, prikey_h = c_generate_key_pair(self.h_session, - CKM_RSA_PKCS_KEY_PAIR_GEN, - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] @@ -138,7 +111,6 @@ def test_hainit(self): "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - def test_createloginchallenge(self): """Test create login challenge. This test requires PED based HSM. @@ -147,16 +119,16 @@ def test_createloginchallenge(self): """ user_type = CKU_CRYPTO_USER - challenge = cast(create_string_buffer("password1234", 12), CK_BYTE_PTR) + challenge = "password1234" - ret = ca_createloginchallenge(self.h_session, - user_type, - challenge) + ret, data = ca_createloginchallenge(self.h_session, + user_type, + challenge) assert (ret == CKR_OK or ret == CKR_CANCEL), \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - + @pytest.mark.xfail(reason="Not valid on PWD auth") def test_initializeremotepedvector(self): """Tests to initialize remote ped vector""" ret = ca_initializeremotepedvector(self.h_session) @@ -165,16 +137,15 @@ def test_initializeremotepedvector(self): "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - + @pytest.mark.xfail(reason="Not valid on PWD auth") def test_deleteremotepedvector(self): """Tests to delete remote ped vector""" ret = ca_deleteremotepedvector(self.h_session) # since not SO return value must be CKR_USER_NOT_AUTHORIZED assert ret == CKR_USER_NOT_AUTHORIZED, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + "Return code should be " + ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ " not " + ret_vals_dictionary[ret] - def test_mtkrestore(self): """Tests MTK restore""" ret = ca_mtkrestore(self.admin_slot) @@ -182,7 +153,6 @@ def test_mtkrestore(self): "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - def test_mtkresplit(self): """Tests MTK resplit""" ret = ca_mtkresplit(self.admin_slot) @@ -190,7 +160,6 @@ def test_mtkresplit(self): "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - def test_mtkzeroize(self): """Tests MTK zeroize""" ret = ca_mtkzeroize(self.admin_slot) diff --git a/pycryptoki/tests/test_key_management.py b/pycryptoki/tests/functional/test_key_management.py similarity index 52% rename from pycryptoki/tests/test_key_management.py rename to pycryptoki/tests/functional/test_key_management.py index cd55d1a..3f3430c 100755 --- a/pycryptoki/tests/test_key_management.py +++ b/pycryptoki/tests/functional/test_key_management.py @@ -1,64 +1,45 @@ """ Test methods for pycryptoki 'key management' set of commands. """ -from pycryptoki.cryptoki import CK_ULONG, CK_BYTE, CA_MOFN_GENERATION, \ - CA_MOFN_GENERATION_PTR -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_OK, CKR_USER_NOT_AUTHORIZED, \ - CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, \ - CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET -from pycryptoki.default_templates import CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -from pycryptoki.key_management import ca_generatemofn, ca_modifyusagecount -from pycryptoki.key_generator import c_generate_key import logging import os + import pytest +from . import config as hsm_config +from ...cryptoki import CK_ULONG, CK_BYTE, CA_MOFN_GENERATION, \ + CA_MOFN_GENERATION_PTR +from ...default_templates import CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP +from ...defines import CKR_OK, CKR_USER_NOT_AUTHORIZED, \ + CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, \ + CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET +from ...key_generator import c_generate_key +from ...key_management import ca_generatemofn, ca_modifyusagecount +from ...return_values import ret_vals_dictionary + -class TestAlgorithm: +class TestAlgorithm(object): """Test algorithm class""" h_session = 0 admin_slot = 0 - @classmethod - def setup_class(cls): - """Setup class""" - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """Finalize tests""" - c_finalize_ex() - - def setup(self): - """Setup test""" - self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """Teardown test""" - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + @pytest.mark.xfail(run=False) def test_generatemofn(self): """Test generate M of N""" m_value = CK_ULONG(1) - value = (CK_BYTE*16)() + value = (CK_BYTE * 16)() vector_count = CK_ULONG(2) - vector = (CA_MOFN_GENERATION*2)() + vector = (CA_MOFN_GENERATION * 2)() vector[0].ulWeight = CK_ULONG(1) vector[0].pVector = value vector[0].ulVectorLen = CK_ULONG(16) vector[1].ulWeight = CK_ULONG(1) - vector[1].pVector = (CK_BYTE*16)() + vector[1].pVector = (CK_BYTE * 16)() vector[1].ulVectorLen = CK_ULONG(16) vectors = CA_MOFN_GENERATION_PTR(vector) is_secure_port_used = CK_ULONG(0) @@ -73,10 +54,9 @@ def test_generatemofn(self): ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ " not " + ret_vals_dictionary[ret] - @pytest.mark.parametrize("command_type", - [CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, - CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET]) + [CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, + CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET]) def test_modifyusagecount(self, command_type): """Test modify usage count @@ -87,15 +67,13 @@ def test_modifyusagecount(self, command_type): CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) assert ret == CKR_OK, "Return code should be " + \ - ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] assert key_handle > 0, "The key handle returned should be non zero" - value = CK_ULONG(0) - ret = ca_modifyusagecount(self.h_session, key_handle, command_type, - value) + 0) assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] diff --git a/pycryptoki/tests/functional/test_key_usage.py b/pycryptoki/tests/functional/test_key_usage.py new file mode 100755 index 0000000..345fd06 --- /dev/null +++ b/pycryptoki/tests/functional/test_key_usage.py @@ -0,0 +1,46 @@ +""" +Test methods for .. 'hsm usage' set of commands. +""" +import logging +import os + +import pytest + +from . import config as hsm_config +from ...defines import CKR_SESSION_HANDLE_INVALID, \ + CKR_USER_NOT_AUTHORIZED +from ...key_usage import ca_clonemofn, ca_duplicatemofn +from ...return_values import ret_vals_dictionary + + +class TestAlgorithm(object): + """Test algorithm class""" + h_session = 0 + admin_slot = 0 + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + def test_clonemofn(self): + """Test clone M of N""" + ret = ca_clonemofn(self.h_session) + assert ret == CKR_SESSION_HANDLE_INVALID, \ + "Return code should be " + \ + ret_vals_dictionary[CKR_SESSION_HANDLE_INVALID] + \ + " not " + ret_vals_dictionary[ret] + + @pytest.mark.xfail(reason="Not valid on PWD auth") + def test_duplicatemofn(self): + """Test duplicate M of N""" + ret = ca_duplicatemofn(self.h_session) + assert ret == CKR_USER_NOT_AUTHORIZED, \ + "Return code should be " + \ + ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ + " not " + ret_vals_dictionary[ret] + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_keys.py b/pycryptoki/tests/functional/test_keys.py new file mode 100755 index 0000000..11adb34 --- /dev/null +++ b/pycryptoki/tests/functional/test_keys.py @@ -0,0 +1,198 @@ +import ctypes +import logging +import os +from ctypes import cast, pointer + +import pytest + +from ...mechanism import NullMech +from . import config as hsm_config +from ...cryptoki import CK_VOID_PTR, CK_ULONG +from ...default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ + CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ + CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, \ + CKM_ARIA_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, \ + CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, curve_list +from ...defines import CKM_DES_KEY_GEN, CKR_OK, \ + CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ + CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ + CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ + CKM_ARIA_KEY_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ + CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ + CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS +from ...key_generator import c_generate_key, c_generate_key_pair, \ + c_derive_key, c_generate_key_ex, _get_mechanism +from ...return_values import ret_vals_dictionary +from ...test_functions import verify_object_attributes + +logger = logging.getLogger(__name__) + + +class TestKeys(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config['test_slot'] + + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), + (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), + (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), + (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), + (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), + (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), + (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), + # (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), + # (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX + # (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) + # (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX + ]) + def test_generate_key(self, key_type, key_template): + """Tests generating a key, asserts that the operation returns correctly with key handles + greater than 0 + + :param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) + :param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) + + """ + ret, key_handle = c_generate_key(self.h_session, key_type, key_template) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + \ + ret_vals_dictionary[ret] + assert key_handle > 0, "The key handle returned should be non zero" + + @pytest.mark.parametrize(("key_type", "public_key_template", "private_key_template"), [ + (CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_DH_PKCS_KEY_PAIR_GEN, + CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), + (CKM_ECDSA_KEY_PAIR_GEN, + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, + CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_KCDSA_KEY_PAIR_GEN, + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_KCDSA_KEY_PAIR_GEN, + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, + CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), + (CKM_RSA_X9_31_KEY_PAIR_GEN, + CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP), + # (CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, + # CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP) #XXX + ]) + def test_generate_key_pair(self, key_type, public_key_template, private_key_template): + """Tests generating a key pair, asserts that the operation returns correctly with key + handles + greater than 0. + + :param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) + :param public_key_template: The template to use for public key generation (ex. + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 + :param private_key_template: The template to use for private key generation (ex. + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 + + """ + ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, key_type, + public_key_template, + private_key_template) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + \ + ret_vals_dictionary[ret] + assert public_key_handle > 0, "The public key handle returned should be non zero" + assert private_key_handle > 0, "The private key handle returned should be non zero" + + @pytest.mark.parametrize("curve_type", curve_list.keys()) + def test_generate_ecdsa_key_pairs(self, curve_type): + """ + + :param curve_type: + + """ + print curve_list.keys() + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] + ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, + CKM_ECDSA_KEY_PAIR_GEN, + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, + CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + \ + ret_vals_dictionary[ret] + assert public_key_handle > 0, "The public key handle returned should be non zero" + assert private_key_handle > 0, "The private key handle returned should be non zero" + + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), + (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), + (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), + (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), + (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), + (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), + (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), + # (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), + # (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX + # (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) + # (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX + ]) + def test_derive_key(self, key_type, key_template): + """Tests deriving a key + + :param key_type: + :param key_template: + + """ + h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) + h_second_key = c_generate_key_ex(self.h_session, key_type, key_template) + + mech = NullMech(CKM_CONCATENATE_BASE_AND_KEY).to_c_mech() + c_second_key = CK_ULONG(h_second_key) + mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) + mech.usParameterLen = ctypes.sizeof(c_second_key) + + ret, h_derived_key = c_derive_key(self.h_session, + h_base_key, + key_template, + CKM_CONCATENATE_BASE_AND_KEY, + mech) + assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + \ + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_derived_key, key_template) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_object_create.py b/pycryptoki/tests/functional/test_object_create.py new file mode 100755 index 0000000..6631f06 --- /dev/null +++ b/pycryptoki/tests/functional/test_object_create.py @@ -0,0 +1,54 @@ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE +from ...defines import CKR_OK +from ...misc import c_create_object +from ...return_values import ret_vals_dictionary +from ...test_functions import verify_object_attributes + +logger = logging.getLogger(__name__) + + +@pytest.mark.xfail("Waiting on LA-1860") +class TestObjectCloning(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + def test_certificate_create(self): + """Tests C_CreateObject with a certificate template and verifies the object's + attributes + + + """ + + ret, h_object = c_create_object(self.h_session, CERTIFICATE_TEMPLATE) + assert ret == CKR_OK, \ + "The result code of creating a " \ + "certificate should be CKR_OK, not " + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_object, CERTIFICATE_TEMPLATE) + + def test_data_create(self): + """Tests C_CreateObject with a data template and verifies the object's + attributes + + + """ + ret, h_object = c_create_object(self.h_session, DATA_TEMPLATE) + assert ret == CKR_OK, \ + "The result of creating a data object should be CKR_OK, not" + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_sign_verify.py b/pycryptoki/tests/functional/test_sign_verify.py new file mode 100755 index 0000000..9519374 --- /dev/null +++ b/pycryptoki/tests/functional/test_sign_verify.py @@ -0,0 +1,111 @@ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 +from ...defines import CKR_OK, CKM_RSA_PKCS, \ + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA +from ...key_generator import c_generate_key_pair_ex +from ...return_values import ret_vals_dictionary +from ...sign_verify import c_sign, c_verify + +logger = logging.getLogger(__name__) + + +class TestSignVerify(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ + (CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + CKM_RSA_PKCS), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, + CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA) + ]) + def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): + """Verifies that signing a string and verifying that string works + + :param key_type: The handle of the key to sign the data with + :param pub_key_template: The template for the public key to be generated + :param priv_key_template: The template for the private key to be generated + :param sign_flavor: The flavor of the signature + + """ + + # Generate a key for the test + h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, + priv_key_template) + + data_to_sign = "This is some test string to sign." + ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) + assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + \ + ret_vals_dictionary[ret] + + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) + assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + \ + ret_vals_dictionary[ret] + + @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA), + (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA) + ]) + def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_template, + sign_flavor): + """Verifies that signing a string and verifying that string works doing the operation + in multiple parts with c_sign_update and c_verify_update + + :param key_type: The handle of the key to sign the data with + :param pub_key_template: The template for the public key to be generated + :param priv_key_template: The template for the private key to be generated + :param sign_flavor: The flavor of the signature + + """ + + # Generate a key for the test + h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, + priv_key_template) + + data_to_sign = ["a" * 1024, "b" * 1024] + ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) + assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + \ + ret_vals_dictionary[ret] + + ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) + assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + \ + ret_vals_dictionary[ret] + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_supporting_operations.py b/pycryptoki/tests/functional/test_supporting_operations.py new file mode 100755 index 0000000..270ed49 --- /dev/null +++ b/pycryptoki/tests/functional/test_supporting_operations.py @@ -0,0 +1,58 @@ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...defines import CKR_OK +from ...misc import c_generate_random_ex, c_seed_random, \ + c_generate_random +from ...return_values import ret_vals_dictionary + +logger = logging.getLogger(__name__) + + +class TestSupportingOperations(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + def test_rng(self): + """Tests generating a random number""" + length = 15 + ret, random_string = c_generate_random(self.h_session, length) + assert ret == CKR_OK, "C_GenerateRandom should return CKR_OK, instead it returned " + \ + ret_vals_dictionary[ret] + assert len( + random_string) == length, "The length of the random string should be the same as the " \ + "length of the requested data." + + def test_seeded_rng(self): + """Tests that seeding the random number generator with the same data will + generate the same random number + + + """ + seed = "k" * 1024 + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, " \ + "it returned " + \ + ret_vals_dictionary[ret] + + random_string_one = c_generate_random_ex(self.h_session, 10) + + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator a second time shouldn't return " \ + "" \ + "an error, it returned " + \ + ret_vals_dictionary[ret] + + random_string_two = c_generate_random_ex(self.h_session, 10) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_usage_limit_and_count.py b/pycryptoki/tests/functional/test_usage_limit_and_count.py new file mode 100755 index 0000000..28feb06 --- /dev/null +++ b/pycryptoki/tests/functional/test_usage_limit_and_count.py @@ -0,0 +1,292 @@ +""" +Created on Aug 15, 2012 + +@author: root +""" + +import logging +import os + +import pytest + +from . import config as hsm_config +from ...cryptoki import CK_ULONG +from ...default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP +from ...defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ + CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ + CKM_DES_ECB, CKM_RSA_PKCS, CKR_KEY_NOT_ACTIVE, CKM_AES_ECB +from ...encryption import c_encrypt, c_encrypt_ex +from ...key_generator import c_generate_key_ex, c_generate_key_pair_ex +from ...object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex + +logger = logging.getLogger(__name__) + + +class TestUsageLimitAndCount(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + def test_set_attribute_usage_limit_sym(self): + """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + an symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 5 + Use C_getAttributeValue to verify + + + """ + + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + an symmetric crypto object") + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_LIMIT: 5} + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, + template=CKM_DES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + usage_limit = 5 + + c_set_attribute_value_ex(self.h_session, + h_key, CKM_USAGE_CHECK_TEMP) + + out_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_LIMIT: None}) + + usage_val_out = out_template[CKA_USAGE_LIMIT] + logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + + def test_usage_limit_attribute_check_sym_des(self): + """Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use des key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + + + """ + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, + CKA_USAGE_LIMIT: 2} + + usage_count = 2 + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, + template=CKM_DES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + + c_set_attribute_value_ex(self.h_session, + h_key, CKM_USAGE_CHECK_TEMP) + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + + py_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_COUNT: None}) + + usage_val_out = py_template[CKA_USAGE_COUNT] + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + def test_usage_limit_attribute_check_sym_aes(self): + """Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the symmetric crypto object + Procedure: + Generate a DES Key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use aes key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + + + """ + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the symmetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, + CKA_USAGE_LIMIT: 2} + + usage_count = 2 + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, + template=CKM_AES_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + + c_set_attribute_value_ex(self.h_session, + h_key, CKM_USAGE_CHECK_TEMP) + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + + py_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_COUNT: None}) + + usage_val_out = py_template[CKA_USAGE_COUNT] + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + def test_set_attribute_usage_limit_Assym(self): + """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on + an assymetric crypto object + Procedure: + Generate a RSA key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 on RSA public key + Use C_getAttributeValue to verify + + + """ + + logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + an assymetric crypto object") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, + CKA_USAGE_LIMIT: 2} + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + logger.info( + "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( + h_prkey)) + usage_limit = 2 + + c_set_attribute_value_ex(self.h_session, + h_pbkey, CKM_USAGE_CHECK_TEMP) + + py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, + template={CKA_USAGE_LIMIT: None}) + usage_val_out = py_template[CKA_USAGE_LIMIT] + logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + + def test_usage_limit_attribute_check_Assym(self): + """Test: Verify that CKA_USAGE_COUNT attribute increments as user + use the assymetric crypto object + Procedure: + Generate a RSA Key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key twice for encryption + Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + + + """ + + logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + use the assymetric crypto object") + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, + CKA_USAGE_LIMIT: 2} + usage_count = 2 + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + + logger.info( + "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( + h_prkey)) + + c_set_attribute_value_ex(self.h_session, + h_pbkey, CKM_USAGE_CHECK_TEMP) + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, + template={CKA_USAGE_COUNT: None}) + + usage_val_out = py_template[CKA_USAGE_COUNT] + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): + """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT + Procedure: + Generate a 3DES key + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key 3 times for encryption + + + """ + + logger.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, + CKA_USAGE_LIMIT: 2} + + h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, + template=CKM_DES3_KEY_GEN_TEMP) + logger.info("Called c-generate: Key handle -" + str(h_key)) + + c_set_attribute_value_ex(self.h_session, + h_key, CKM_USAGE_CHECK_TEMP) + + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + + return_val = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + logger.info("Called C_Encrypt, return code: " + str(return_val)) + + py_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_COUNT: None}) + + usage_val_out = py_template[CKA_USAGE_COUNT] + logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + + def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): + """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE + if user try to use crypto object more than limit set on CKA_USAGE_LIMIT + Procedure: + Generate a RSA Key pair + Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 + Use RSA public key 3 times for encryption + + + """ + + CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, + CKA_USAGE_LIMIT: 2} + + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + mech=None) + + logger.info( + "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( + h_prkey)) + + c_set_attribute_value_ex(self.h_session, + h_pbkey, CKM_USAGE_CHECK_TEMP) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + + return_val = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + logger.info("Called C_Encrypt, return code: " + str(return_val)) + py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, + template={CKA_USAGE_COUNT: None}) + + usage_val_out = py_template[CKA_USAGE_COUNT] + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + + +if __name__ == "__main__": + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_wrap_unwrap.py b/pycryptoki/tests/functional/test_wrap_unwrap.py new file mode 100755 index 0000000..1f4b1eb --- /dev/null +++ b/pycryptoki/tests/functional/test_wrap_unwrap.py @@ -0,0 +1,89 @@ +import logging +import os + +import pytest + +from . import config as hsm_config +from ...default_templates import CKM_DES_KEY_GEN_TEMP, \ + CKM_DES_UNWRAP_TEMP +from ...defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ + CKM_DES_ECB +from ...encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt +from ...key_generator import c_generate_key_ex +from ...return_values import ret_vals_dictionary +from ...test_functions import verify_object_attributes + +logger = logging.getLogger(__name__) + + +class TestWrappingKeys(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + def test_wrap_unwrap_key(self): + """Tests the attributes of an unwrapped key are idential to the original key""" + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + # Wrap the key + ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) + assert ret == CKR_OK, \ + "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + # Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, + CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) + assert ret == CKR_OK, \ + "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + + # Verify all of the attributes against the originally generated attributes + verify_object_attributes(self.h_session, h_unwrapped_key, CKM_DES_KEY_GEN_TEMP) + + def test_encrypt_wrap_unwrap_decrypt_key(self): + """Tests encrypting some data with a key. Then wrapping and unwrapping the key + and using the unwrapped key to decrypt the data. It then compares the data to the + original data. + + + """ + h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + + # Encrypt some data + data_to_encrypt = "a" * 512 + ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) + assert ret == CKR_OK, \ + "Encryption should go through successfully, instead it returned " + \ + ret_vals_dictionary[ret] + + # Wrap the key + ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) + assert ret == CKR_OK, \ + "Wrapping the key should pass, instead it returns " + \ + ret_vals_dictionary[ret] + + # Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, + CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) + assert ret == CKR_OK, \ + "Unwrapping the key should pass, instead it returns " + \ + ret_vals_dictionary[ret] + + # Decrypt the data + ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_unwrapped_key, + encrypted_data) + assert ret == CKR_OK, \ + "There should be no errors when decrypting, instead found " + \ + ret_vals_dictionary[ret] + assert decrypted_string == data_to_encrypt, \ + "The decrypted data should be the same as the data that was encrypted. " \ + "Instead found " + str(decrypted_string) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.DEBUG) + pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/run_tests_in_folder.py b/pycryptoki/tests/run_tests_in_folder.py deleted file mode 100755 index d1527ad..0000000 --- a/pycryptoki/tests/run_tests_in_folder.py +++ /dev/null @@ -1,9 +0,0 @@ -""" -Created on Aug 30, 2012 - -@author: mhughes -""" -import pytest - -if __name__ == '__main__': - pytest.cmdline.main(args=[]) diff --git a/pycryptoki/tests/setup_for_tests.py b/pycryptoki/tests/setup_for_tests.py deleted file mode 100755 index 31b04df..0000000 --- a/pycryptoki/tests/setup_for_tests.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -Created on Sep 18, 2012 - -@author: mhughes -""" -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD, \ - CO_PASSWORD -from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ - CKF_SO_SESSION -from pycryptoki.session_management import ca_factory_reset_ex, c_open_session_ex, \ - c_close_all_sessions_ex, login_ex, c_init_pin_ex, c_logout_ex, c_initialize_ex, \ - c_finalize_ex -from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex -import logging - -logger = logging.getLogger(__name__) - -def setup_for_tests(should_factory_reset, initialize_admin_token, initialize_users): - """ - - :param should_factory_reset: - :param initialize_admin_token: - :param initialize_users: - - """ - c_initialize_ex() - - #Factory Reset - slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - if should_factory_reset: - c_close_all_sessions_ex(slot) - ca_factory_reset_ex(slot) - - #Initialize the Admin Token - session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) - if initialize_admin_token: - h_session = c_open_session_ex(slot, session_flags) - c_init_token_ex(slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) - - - if initialize_users and initialize_admin_token: - slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - c_close_all_sessions_ex(slot) - h_session = c_open_session_ex(slot, session_flags) - login_ex(h_session, slot, ADMINISTRATOR_PASSWORD, 0) - c_init_pin_ex(h_session, CO_PASSWORD) - c_logout_ex(h_session) - c_close_all_sessions_ex(slot) - - c_finalize_ex() diff --git a/pycryptoki/tests/stress/test_multi_reset.py b/pycryptoki/tests/stress/test_multi_reset.py index c574a79..df3e475 100755 --- a/pycryptoki/tests/stress/test_multi_reset.py +++ b/pycryptoki/tests/stress/test_multi_reset.py @@ -1,4 +1,12 @@ +import argparse +import logging +import os +import sys +import threading from ctypes import * +from pycryptoki.utils.common_utils import setLogFile +from random import randint + from pycryptoki.cryptoki import CK_SLOT_ID, CA_GetObjectUID, \ CA_GetUserContainerNumber, CA_GetObjectHandle, \ CK_ULONG, CK_BYTE @@ -8,31 +16,23 @@ CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, CKM_RC4_KEY_GEN_TEMP, \ CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, \ CKM_ARIA_KEY_GEN_TEMP, CKM_DH_PKCS_PARAMETER_GEN_TEMP +from pycryptoki.defaults import DEFAULT_PASSWORD, DEFAULT_LABEL +from pycryptoki.defaults import DEFAULT_UTILS_PATH, FORMAT +from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ + CKF_SO_SESSION from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, \ CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN, \ CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, CKM_RC5_KEY_GEN, \ CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ CKM_ARIA_KEY_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKR_OK, \ CKR_DEVICE_ERROR, CK_CRYPTOKI_ELEMENT -from pycryptoki.defaults import DEFAULT_PASSWORD, DEFAULT_LABEL -from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ - CKF_SO_SESSION from pycryptoki.key_generator import c_destroy_object, c_generate_key from pycryptoki.session_management import c_initialize, c_finalize, \ c_close_all_sessions_ex, ca_factory_reset_ex, c_open_session_ex, login_ex, \ c_get_token_info_ex, c_init_pin_ex, c_logout_ex, c_close_session_ex, c_finalize_ex -from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex from pycryptoki.test_functions import verify_object_attributes, verify_object_exists -from pycryptoki.utils.common_utils import setLogFile -from pycryptoki.tests.stress.vreset_thread import ResetThread -from pycryptoki.defaults import DEFAULT_UTILS_PATH, FORMAT -from random import randint -import logging -import os -import threading -import argparse -import sys - +from pycryptoki.tests import ResetThread +from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex #Global Scope logger = logging.getLogger(__name__) diff --git a/pycryptoki/tests/test_digest_data.py b/pycryptoki/tests/test_digest_data.py deleted file mode 100755 index 50136ed..0000000 --- a/pycryptoki/tests/test_digest_data.py +++ /dev/null @@ -1,57 +0,0 @@ -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_MD2, CKR_OK -from pycryptoki.encryption import _get_string_from_list -from pycryptoki.misc import c_digest -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestDigestData: - """ """ - @classmethod - def setup_class(cls): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """ """ - c_finalize_ex() - - def setup(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_digest_data(self): - """Calls C_Digest on some data and makes sure there is no failure""" - data_to_digest = "Some arbitrary string" - ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) - assert ret == CKR_OK, "Digesting should occur with no errors" - assert len(digested_data) > 0, "The digested data should have a length" - assert data_to_digest != digested_data, "The digested data should not be the same as the original string" - - def test_multipart_digest_data(self): - """ """ - data_to_digest = ["Some arbitrary string", "Some second arbitrary string"] - ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) - assert ret == CKR_OK, "Digesting should occur with no errors" - assert len(digested_data) > 0, "The digested data should have a length" - assert _get_string_from_list(data_to_digest) != digested_data, "The digested data should not be the same as the original string" - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_encrypt_decrypt.py b/pycryptoki/tests/test_encrypt_decrypt.py deleted file mode 100755 index 6c97f40..0000000 --- a/pycryptoki/tests/test_encrypt_decrypt.py +++ /dev/null @@ -1,77 +0,0 @@ -import logging -import os - -import pytest - -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK -from pycryptoki.encryption import c_encrypt, c_decrypt, _split_string_into_list, \ - _get_string_from_list -from pycryptoki.key_generator import c_generate_key_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex - -logger = logging.getLogger(__name__) - -class TestEncryptData: - """ """ - @classmethod - def setup_class(cls): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """ """ - c_finalize_ex() - - def setup(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_encrypt_decrypt_string(self): - """Tests encrypting and decrypting a string with a key""" - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - data_to_encrypt = "a" * 0xfff0 - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - - ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data) - assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] - assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) - - def test_multipart_encrypt_decrypt(self): - """Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore doing it in multiple - parts - - - """ - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - data_to_encrypt = ['a' * 512, 'b' * 512, 'c' * 512, 'd' * 512] - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - assert len(encrypted_data) == len(_get_string_from_list(data_to_encrypt)) - - encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) - - ret, decrypted_data = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data_chunks) - assert ret == CKR_OK, "Decryption should succeed, instead it returned " + ret_vals_dictionary[ret] - assert _get_string_from_list(data_to_encrypt) == decrypted_data, "The data before encryption should match the data after encryption" - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_get_token_info.py b/pycryptoki/tests/test_get_token_info.py deleted file mode 100755 index 7070be8..0000000 --- a/pycryptoki/tests/test_get_token_info.py +++ /dev/null @@ -1,52 +0,0 @@ -import logging -import os - -import pytest - -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD -from pycryptoki.defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ - CKF_RESTORE_KEY_NOT_NEEDED, CKF_TOKEN_INITIALIZED -from pycryptoki.session_management import c_finalize, ca_factory_reset_ex, \ - c_get_token_info_ex, c_close_all_sessions, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex - -logger = logging.getLogger(__name__) - -class TestGetTokenInfo: - """ """ - - def setup(self): - """ """ - setup_for_tests(True, False, False) - c_initialize_ex() - - def teardown(self): - """ """ - c_finalize() - - def test_initial_flags(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - - #Get to clean state - c_close_all_sessions(admin_slot) - ca_factory_reset_ex(admin_slot) - - #Look at flags before initialization - flags = c_get_token_info_ex(admin_slot)['flags'] - expected_flags = CKF_TOKEN_PRESENT | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED - assert flags == expected_flags, "After factory reset found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) - - c_init_token_ex(admin_slot, ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL) - - #Test flags after initialization - flags = c_get_token_info_ex(admin_slot)['flags'] - expected_flags = expected_flags | CKF_TOKEN_INITIALIZED - assert flags == expected_flags, "After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags)) - logger.info("After initialization found flags " + str(hex(flags)) + " on admin partition should match expected flags"+ str(hex(expected_flags))) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) - diff --git a/pycryptoki/tests/test_key_usage.py b/pycryptoki/tests/test_key_usage.py deleted file mode 100755 index a62e6c0..0000000 --- a/pycryptoki/tests/test_key_usage.py +++ /dev/null @@ -1,65 +0,0 @@ -""" -Test methods for pycryptoki 'hsm usage' set of commands. -""" -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_SESSION_HANDLE_INVALID, \ - CKR_USER_NOT_AUTHORIZED -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -from pycryptoki.key_usage import ca_clonemofn, ca_duplicatemofn -import logging -import os -import pytest - -class TestAlgorithm: - """Test algorithm class""" - h_session = 0 - admin_slot = 0 - - @classmethod - def setup_class(cls): - """Setup class""" - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """Finalize tests""" - c_finalize_ex() - - def setup(self): - """Setup test""" - self.admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=self.admin_slot) - login_ex(self.h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """Teardown test""" - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - - def test_clonemofn(self): - """Test clone M of N""" - ret = ca_clonemofn(self.h_session) - assert ret == CKR_SESSION_HANDLE_INVALID, \ - "Return code should be " + \ - ret_vals_dictionary[CKR_SESSION_HANDLE_INVALID] + \ - " not " + ret_vals_dictionary[ret] - - - def test_duplicatemofn(self): - """Test duplicate M of N""" - ret = ca_duplicatemofn(self.h_session) - assert ret == CKR_USER_NOT_AUTHORIZED, \ - "Return code should be " + \ - ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ - " not " + ret_vals_dictionary[ret] - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_keys.py b/pycryptoki/tests/test_keys.py deleted file mode 100755 index cbea7d8..0000000 --- a/pycryptoki/tests/test_keys.py +++ /dev/null @@ -1,178 +0,0 @@ -from ctypes import cast, pointer -import ctypes -import logging -import os - -import pytest - -from pycryptoki.cryptoki import CK_VOID_PTR, CK_ULONG -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ - CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ - CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, CKM_ARIA_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, \ - CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, curve_list -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKR_OK, \ - CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ - CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ - CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ - CKM_ARIA_KEY_GEN, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ - CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ - CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS -from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, \ - c_derive_key, c_generate_key_ex, _get_mechanism -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex - -logger = logging.getLogger(__name__) - -class TestKeys: - """ """ - @classmethod - def setup_class(cls): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """ """ - c_finalize_ex() - - def setup(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), - (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), - (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), - (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), - (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), - (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), -# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), -# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX -# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) -# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX - ]) - def test_generate_key(self, key_type, key_template): - """Tests generating a key, asserts that the operation returns correctly with key handles - greater than 0 - - :param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) - :param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) - - """ - ret, key_handle = c_generate_key(self.h_session, key_type, key_template) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] - assert key_handle > 0, "The key handle returned should be non zero" - - - @pytest.mark.parametrize(("key_type", "public_key_template", "private_key_template"), [ - (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), - (CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_KCDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP), -# (CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP) #XXX - ]) - def test_generate_key_pair(self, key_type, public_key_template, private_key_template): - """Tests generating a key pair, asserts that the operation returns correctly with key handles - greater than 0. - - :param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) - :param public_key_template: The template to use for public key generation (ex. CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 - :param private_key_template: The template to use for private key generation (ex. CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 - - """ - ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, key_type, public_key_template, private_key_template) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] - assert public_key_handle > 0, "The public key handle returned should be non zero" - assert private_key_handle > 0, "The private key handle returned should be non zero" - - @pytest.mark.parametrize("curve_type", curve_list.keys()) - def test_generate_ecdsa_key_pairs(self, curve_type): - """ - - :param curve_type: - - """ - print curve_list.keys() - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] - ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] - assert public_key_handle > 0, "The public key handle returned should be non zero" - assert private_key_handle > 0, "The private key handle returned should be non zero" - - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), - (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), - (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), - (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), - (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), - (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), -# (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), -# (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX -# (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) -# (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX - ]) - def test_derive_key(self, key_type, key_template): - """Tests deriving a key - - :param key_type: - :param key_template: - - """ - h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) - h_second_key = c_generate_key_ex(self.h_session, key_type, key_template) - - mech = _get_mechanism(CKM_CONCATENATE_BASE_AND_KEY) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - ret, h_derived_key = c_derive_key(self.h_session, h_base_key, key_template, None, mech) - assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_derived_key, key_template) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_object_create.py b/pycryptoki/tests/test_object_create.py deleted file mode 100755 index 2259041..0000000 --- a/pycryptoki/tests/test_object_create.py +++ /dev/null @@ -1,66 +0,0 @@ -from pycryptoki.default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_OK -from pycryptoki.misc import c_create_object -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestObjectCloning: - """ """ - @classmethod - def setup_class(cls): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """ """ - c_finalize_ex() - - def setup(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_certificate_create(self): - """Tests C_CreateObject with a certificate template and verifies the object's - attributes - - - """ - - ret, h_object = c_create_object(self.h_session, CERTIFICATE_TEMPLATE) - assert ret == CKR_OK, "The result code of creating a certificate should be CKR_OK, not " + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_object, CERTIFICATE_TEMPLATE) - - def test_data_create(self): - """Tests C_CreateObject with a data template and verifies the object's - attributes - - - """ - ret, h_object = c_create_object(self.h_session, DATA_TEMPLATE) - assert ret == CKR_OK, "The result of creating a data object should be CKR_OK, not" + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_sign_verify.py b/pycryptoki/tests/test_sign_verify.py deleted file mode 100755 index d0917b5..0000000 --- a/pycryptoki/tests/test_sign_verify.py +++ /dev/null @@ -1,103 +0,0 @@ -import logging -import os - -import pytest - -from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_OK, CKM_RSA_PKCS, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA -from pycryptoki.key_generator import c_generate_key_pair_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.sign_verify import c_sign, c_verify -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex - -logger = logging.getLogger(__name__) - -class TestSignVerify: - """ """ - @classmethod - def setup_class(cls): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """ """ - c_finalize_ex() - - def setup(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ - (CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_RSA_PKCS), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) - ]) - def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): - """Verifies that signing a string and verifying that string works - - :param key_type: The handle of the key to sign the data with - :param pub_key_template: The template for the public key to be generated - :param priv_key_template: The template for the private key to be generated - :param sign_flavor: The flavor of the signature - - """ - - #Generate a key for the test - h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - - data_to_sign = "This is some test string to sign." - ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) - assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] - - ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) - assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] - - @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) - ]) - def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): - """Verifies that signing a string and verifying that string works doing the operation - in multiple parts with c_sign_update and c_verify_update - - :param key_type: The handle of the key to sign the data with - :param pub_key_template: The template for the public key to be generated - :param priv_key_template: The template for the private key to be generated - :param sign_flavor: The flavor of the signature - - """ - - #Generate a key for the test - h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - - data_to_sign = ["a" * 1024, "b" * 1024] - ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) - assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + ret_vals_dictionary[ret] - - ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) - assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + ret_vals_dictionary[ret] - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_supporting_operations.py b/pycryptoki/tests/test_supporting_operations.py deleted file mode 100755 index a7f852c..0000000 --- a/pycryptoki/tests/test_supporting_operations.py +++ /dev/null @@ -1,66 +0,0 @@ -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKR_OK -from pycryptoki.misc import c_generate_random_ex, c_seed_random, \ - c_generate_random -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex -import logging -import os -import pytest - -logger = logging.getLogger(__name__) - -class TestSupportingOperations: - """ """ - @classmethod - def setup_class(cls): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """ """ - c_finalize_ex() - - def setup(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_rng(self): - """Tests generating a random number""" - length = 15 - ret, random_string = c_generate_random(self.h_session, length) - assert ret == CKR_OK, "C_GenerateRandom should return CKR_OK, instead it returned " + ret_vals_dictionary[ret] - assert len(random_string) == length, "The length of the random string should be the same as the length of the requested data." - - def test_seeded_rng(self): - """Tests that seeding the random number generator with the same data will - generate the same random number - - - """ - seed = "k" * 1024 - ret = c_seed_random(self.h_session, seed) - assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, it returned " + ret_vals_dictionary[ret] - - random_string_one = c_generate_random_ex(self.h_session, 10) - - ret = c_seed_random(self.h_session, seed) - assert ret == CKR_OK, "Seeding the random number generator a second time shouldn't return an error, it returned " + ret_vals_dictionary[ret] - - random_string_two = c_generate_random_ex(self.h_session, 10) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/test_usage_limit_and_count.py b/pycryptoki/tests/test_usage_limit_and_count.py deleted file mode 100755 index 34c5d90..0000000 --- a/pycryptoki/tests/test_usage_limit_and_count.py +++ /dev/null @@ -1,338 +0,0 @@ -""" -Created on Aug 15, 2012 - -@author: root -""" - -import logging -import os - -import pytest - -from pycryptoki.attributes import Attributes -from pycryptoki.cryptoki import CK_ULONG, C_SetAttributeValue -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP -from pycryptoki.defaults import CO_PASSWORD, ADMIN_PARTITION_LABEL -from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ - CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ - CKM_DES_ECB, CKM_RSA_PKCS, CKR_OK, CKR_KEY_NOT_ACTIVE, CKU_USER, CKM_AES_ECB -from pycryptoki.encryption import c_encrypt, c_encrypt_ex -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex -from pycryptoki.session_management import login_ex -from pycryptoki.object_attr_lookup import c_get_attribute_value_ex -from pycryptoki.session_management import c_initialize_ex, c_open_session_ex, c_logout_ex, \ - c_close_session_ex, c_finalize -from pycryptoki.test_functions import LunaException -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex - -logger = logging.getLogger(__name__) - -class TestUsageLimitAndCount: - """ """ - - h_session = 0 - - def setup(self): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - c_finalize() - - def test_set_attribute_usage_limit_sym(self): - """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on - an symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 5 - Use C_getAttributeValue to verify - - - """ - - logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an symmetric crypto object") - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 5} - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - usage_limit = 5 - - - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) -# print c_struct[CKA_USAGE_LIMIT] - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value - logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(int(usage_val_out))) - assert usage_limit== usage_val_out, "reported USAGE LIMIT does not match" - - - - - def test_usage_limit_attribute_check_sym_des(self): - """Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use des key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 - - - """ - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - usage_count = 2 - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) - - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) - - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - - - - - def test_usage_limit_attribute_check_sym_aes(self): - - """Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use aes key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 - - - """ - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - usage_count = 2 - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_AES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - return_value = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) - - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) - - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - - - - def test_set_attribute_usage_limit_Assym(self): - """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on - an assymetric crypto object - Procedure: - Generate a RSA key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 on RSA public key - Use C_getAttributeValue to verify - - - """ - - logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an assymetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - usage_limit = 2 - - return_val = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) - if return_val != CKR_OK: raise LunaException(return_val, 'C_SetAttributeValue', "Setting up attribute") - - c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_LIMIT]).value - logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) - assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" - - - - - - def test_usage_limit_attribute_check_Assym(self): - """Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the assymetric crypto object - Procedure: - Generate a RSA Key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 - - - """ - - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the assymetric crypto object") - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - usage_count = 2 - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) - - - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - - return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - - c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - - - def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): - - """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT - Procedure: - Generate a 3DES key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key 3 times for encryption - - - """ - - logger.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) - return_val = C_SetAttributeValue(self.h_session, h_key, key_attributes.get_c_struct(), us_public_template_size) - if return_val != CKR_OK: raise LunaException(return_val, 'C_setAttributeValue', "Setting up limit attribute") - - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - - return_val = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - logger.info("Called C_Encrypt, return code: " + str(return_val)) - - c_struct = c_get_attribute_value_ex(self.h_session, h_key, template=CKM_USAGE_CHECK_TEMP) - - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) - - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - - - - - def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): - - """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT - Procedure: - Generate a RSA Key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key 3 times for encryption - - - """ - - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT : 0, - CKA_USAGE_LIMIT : 2} - - key_attributes = Attributes(CKM_USAGE_CHECK_TEMP) - us_public_template_size = CK_ULONG(len(CKM_USAGE_CHECK_TEMP)) - - - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) - - logger.info("Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str(h_prkey)) - - return_value = C_SetAttributeValue(self.h_session, h_pbkey, key_attributes.get_c_struct(), us_public_template_size) - if return_value != CKR_OK: raise LunaException(return_value, 'C_SetAttributeValue', "Setting up limit attribute") - - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - - return_val = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - logger.info("Called C_Encrypt, return code: " + str(return_val)) - c_struct = c_get_attribute_value_ex(self.h_session, h_pbkey, template=CKM_USAGE_CHECK_TEMP) - - usage_val_out = CK_ULONG(c_struct[CKA_USAGE_COUNT]).value - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - - - -if __name__ == "__main__": - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) - diff --git a/pycryptoki/tests/test_wrap_unwrap.py b/pycryptoki/tests/test_wrap_unwrap.py deleted file mode 100755 index 373c7e3..0000000 --- a/pycryptoki/tests/test_wrap_unwrap.py +++ /dev/null @@ -1,93 +0,0 @@ -import logging -import os - -import pytest - -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_DES_UNWRAP_TEMP -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKU_USER, CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ - CKM_DES_ECB -from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt -from pycryptoki.key_generator import c_generate_key_ex -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.session_management import c_finalize_ex, c_open_session_ex, \ - login_ex, c_logout_ex, c_close_session_ex, c_initialize_ex -from pycryptoki.test_functions import verify_object_attributes -from pycryptoki.tests.setup_for_tests import setup_for_tests -from pycryptoki.token_management import get_token_by_label_ex - -logger = logging.getLogger(__name__) - -class TestWrappingKeys: - """ """ - @classmethod - def setup_class(cls): - """ """ - setup_for_tests(True, True, True) - c_initialize_ex() - - @classmethod - def teardown_class(cls): - """ """ - c_finalize_ex() - - def setup(self): - """ """ - admin_slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - self.h_session = c_open_session_ex(slot_num=admin_slot) - login_ex(self.h_session, admin_slot, CO_PASSWORD, CKU_USER) - - def teardown(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - - def test_wrap_unwrap_key(self): - """Tests the attributes of an unwrapped key are idential to the original key""" - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - #Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) - assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) - assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Verify all of the attributes against the originally generated attributes - verify_object_attributes(self.h_session, h_unwrapped_key, CKM_DES_KEY_GEN_TEMP) - - def test_encrypt_wrap_unwrap_decrypt_key(self): - """Tests encrypting some data with a key. Then wrapping and unwrapping the key - and using the unwrapped key to decrypt the data. It then compares the data to the - original data. - - - """ - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - #Encrypt some data - data_to_encrypt = "a" * 512 - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + ret_vals_dictionary[ret] - - #Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) - assert ret == CKR_OK, "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) - assert ret == CKR_OK, "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] - - #Decrypt the data - ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_unwrapped_key, encrypted_data) - assert ret == CKR_OK, "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] - assert decrypted_string == data_to_encrypt, "The decrypted data should be the same as the data that was encrypted. Instead found " + str(decrypted_string) - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/unittests/__init__.py b/pycryptoki/tests/unittests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pycryptoki/tests/unittests/test_attributes.py b/pycryptoki/tests/unittests/test_attributes.py new file mode 100644 index 0000000..772e772 --- /dev/null +++ b/pycryptoki/tests/unittests/test_attributes.py @@ -0,0 +1,20 @@ +""" + +""" +from _ctypes import POINTER +from ctypes import c_void_p, c_ulong, cast + +from hypothesis import given +from hypothesis.strategies import integers +from ...attributes import to_long + + +class TestAttributes(object): + + @given(integers()) + def test_to_long(self, testval): + pointer, len = to_long(testval) + assert isinstance(pointer, c_void_p) + assert isinstance(len, (long, int, c_ulong)) + finval = cast(pointer, POINTER(c_ulong)).contents + assert finval >= 0 diff --git a/pycryptoki/tests/unittests/test_mechanisms.py b/pycryptoki/tests/unittests/test_mechanisms.py new file mode 100644 index 0000000..797a1b6 --- /dev/null +++ b/pycryptoki/tests/unittests/test_mechanisms.py @@ -0,0 +1,183 @@ +""" +Unittests related to the mechanism module. +""" +import pytest +from ctypes import cast, c_ulong, c_ubyte +from mock import patch +from ...cryptoki import CK_RSA_PKCS_PSS_PARAMS, POINTER, CK_ULONG, CK_AES_GCM_PARAMS, CK_MECHANISM +from ...defines import * +from ...mechanism import Mechanism, MechanismException, AutoMech, MECH_LOOKUP, AESGCMMechanism, \ + NullMech + +MECH_PARAMS = {CKM_AES_XTS: {'hTweakKey': 0L, + 'cb': range(12), + 'test_id': 'AES_XTS'}, + CKM_DES3_CBC: {'iv': range(12), + 'test_id': 'DES3'}, + CKM_AES_CBC: {'iv': range(16), + 'test_id': 'AES_CBC'}, + CKM_RC2_ECB: {'usEffectiveBits': 8, + 'test_id': 'RC2_ECB'}, + CKM_RC2_CBC: {'usEffectiveBits': 8, + 'iv': range(8), + 'test_id': 'RC2_CBC'}, + CKM_RC5_ECB: {'ulWordsize': 8, + 'ulRounds': 8, + 'test_id': 'RC5_ECB'}, + CKM_RC5_CBC: {'ulWordsize': 8, + 'ulRounds': 2, + 'iv': range(12), + 'test_id': 'RC5_CBC'}, + CKM_RSA_PKCS_OAEP: {'hashAlg': CKM_SHA_1, + 'mgf': CKG_MGF1_SHA1, + 'sourceData': range(12), + 'test_id': 'RSA_OAEP'}, + CKM_AES_GCM: {'iv': range(16), + 'AAD': 'testme', + 'ulTagBits': 32, + 'test_id': 'AES_GCM'}, + CKM_RSA_PKCS_PSS: {'hashAlg': CKM_SHA_1, + 'mgf': CKG_MGF1_SHA1, + 'test_id': "RSA_PSS"}} + + +def idfn(test): + return MECH_PARAMS[test].get('test_id', 'unknown') + + +class TestMechanisms(object): + @pytest.mark.parametrize('flavor,params', + [(CKM_AES_XTS, ['hTweakKey', 'cb']), + (CKM_RC2_ECB, ['usEffectiveBits']), + (CKM_RC2_CBC, ['usEffectiveBits', 'iv']), + (CKM_RC5_ECB, ['ulWordsize', 'ulRounds']), + (CKM_RC5_CBC, ['ulWordsize', 'ulRounds', 'iv']), + (CKM_RSA_PKCS_OAEP, ['hashAlg', 'mgf', 'sourceData']) + ], + ids=["XTS", "RC2", "RC2_CBC", + "RC5", "RC5_CBC", "RSA_PKCS_OAEP"]) + def test_missing_params(self, flavor, params): + """ + Test that missing parameters for various mechs raises the appropriate exception. + + :param crypto_session: + :return: + """ + with pytest.raises(MechanismException) as excinfo: + mech = Mechanism(flavor) + + for x in params: + assert x in excinfo.value.message + + def test_auto_mechanism_simple_vals(self): + """ + Test that a mechanism created via the 'automech' creates a mechanism as expected. + + :return: + """ + # Patch the mechanism lookup so that we don't have to have an undefined + # mechanism to test the automech. + with patch.dict(MECH_LOOKUP, {}, clear=True): + pymech = AutoMech(CKM_RSA_PKCS_PSS, params={'params_name': "CK_RSA_PKCS_PSS_PARAMS", + "hashAlg": CKM_SHA_1, + "mgf": CKG_MGF1_SHA1, + "usSaltLen": 8}) + assert isinstance(pymech, AutoMech) + cmech = pymech.to_c_mech() + params = cast(cmech.pParameter, POINTER(CK_RSA_PKCS_PSS_PARAMS)).contents + assert params.hashAlg == CKM_SHA_1 + assert params.mgf == CKG_MGF1_SHA1 + assert params.usSaltLen == 8 + assert isinstance(params.usSaltLen, (long, CK_ULONG)) + assert isinstance(params.hashAlg, (long, CK_ULONG)) + assert isinstance(params.mgf, (long, CK_ULONG)) + + def test_null_mechanism_indirect_instantiation(self): + """ + Test automech by instantiating Mechanism() instead of AutoMech() + + :return: + """ + # Patch the mechanism lookup so that we don't have to have an undefined + # mechanism to test the automech. + with patch.dict(MECH_LOOKUP, {}, clear=True): + pymech = Mechanism(CKM_RSA_PKCS_PSS) + + assert isinstance(pymech, NullMech) + cmech = pymech.to_c_mech() + assert cmech.pParameter is None + assert cmech.usParameterLen == 0 + + def test_exact_mechanism_use(self): + """ + Test that directly instantiating a subclass of Mechanism works as expected. + + :return: + """ + mech = AESGCMMechanism(mech_type=CKM_AES_GCM, + params={'AAD': 'notsosecret', + 'iv': range(12), + 'ulTagBits': 32}) + cmech = mech.to_c_mech() + cparams = cast(cmech.pParameter, POINTER(CK_AES_GCM_PARAMS)).contents + assert cparams.ulTagBits == 32L + + @pytest.mark.parametrize('flavor', MECH_PARAMS.keys(), + ids=idfn) + def test_mech_conversions(self, flavor): + """ + Test that converting each mechanism works as expected w/ valid params. + """ + params = MECH_PARAMS[flavor] + mech = Mechanism(flavor, params=params) + + cmech = mech.to_c_mech() + # Would prefer to check if it's a c_void_p, but it gets transformed directly to + # an int/long depending on memory location. + assert isinstance(cmech.pParameter, (int, long, c_ulong)) + assert isinstance(cmech.usParameterLen, (int, long, c_ulong)) + assert isinstance(cmech, CK_MECHANISM) + assert cmech.mechanism == flavor + + def test_default_iv_params(self): + """ + Verify passing no IV to a mech requiring an IV will use the default value. + """ + cmech = Mechanism(CKM_DES3_CBC).to_c_mech() + + rawiv = cast(cmech.pParameter, POINTER(c_ubyte)) + iv = [rawiv[x] for x in range(cmech.usParameterLen)] + assert iv == [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] + + def test_default_iv6_params(self): + """ + Verify passing no IV to a mech requiring an IV will use the default value. + """ + cmech = Mechanism(CKM_AES_CBC).to_c_mech() + + rawiv = cast(cmech.pParameter, POINTER(c_ubyte)) + iv = [rawiv[x] for x in range(cmech.usParameterLen)] + assert iv == [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + + @pytest.mark.parametrize("flavor", [CKM_SHA256, CKM_SHA512, + CKM_DSA, CKM_RSA_PKCS], + ids=["SHA256", "SHA512", "DSA", "RSA_PKCS"]) + def test_null_mech(self, flavor): + """ + Verify creating a 'null mech' will fill out the parameter fields properly. + """ + cmech = NullMech(flavor).to_c_mech() + + assert cmech.pParameter is None + assert cmech.usParameterLen == 0 + + def test_no_params_given_automech(self): + """ + Verify that creating an automech w/o a params_name in the dictionary + will fail. + """ + with patch.dict(MECH_LOOKUP, {}, clear=True): + with pytest.raises(MechanismException) as excinfo: + cmech = AutoMech(CKM_DES3_CBC).to_c_mech() + + assert "Failed to find a suitable Ctypes Parameter" in excinfo.value.message diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index 5cff5a7..9af4904 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -3,28 +3,27 @@ @author: mhughes """ -from ctypes import byref import logging +from ctypes import byref # Cryptoki Constants -from pycryptoki.cryptoki import (CK_ULONG, - CK_BBOOL, - CK_MECHANISM_TYPE, - CK_MECHANISM_INFO) -from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT -from pycryptoki.defines import CKR_OK - +from .cryptoki import (CK_ULONG, + CK_BBOOL, + CK_MECHANISM_TYPE, + CK_MECHANISM_INFO) +from .defaults import ADMIN_PARTITION_LABEL, ADMIN_SLOT +from .defines import CKR_OK # Cryptoki functions. -from pycryptoki.cryptoki import (C_InitToken, - C_GetSlotList, - C_GetMechanismList, - C_GetMechanismInfo, - CA_GetTokenPolicies) -from pycryptoki.session_management import c_get_token_info -from pycryptoki.test_functions import make_error_handle_function -from pycryptoki.common_utils import AutoCArray -from pycryptoki.common_utils import refresh_c_arrays +from .cryptoki import (C_InitToken, + C_GetSlotList, + C_GetMechanismList, + C_GetMechanismInfo, + CA_GetTokenPolicies) +from .session_management import c_get_token_info +from .test_functions import make_error_handle_function +from .common_utils import AutoCArray +from .common_utils import refresh_c_arrays LOG = logging.getLogger(__name__) From e894c6fa751961d3a314fd873c16472285c1a032 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 20 Jun 2016 10:45:51 -0400 Subject: [PATCH 049/109] LA-1864 Fix functional derive tests * Todo: CKM_CONCATENATE_BASE_AND_KEY seems to not be working post 6.22.0 -- needs to be investigated. Change-Id: I2fdd35cf4273539e09284706f78f3ed0e13ab05d --- pycryptoki/object_attr_lookup.py | 3 - pycryptoki/tests/functional/conftest.py | 117 +++++++++---- .../functional/test_cka_start_and_end.py | 8 - .../tests/functional/test_digest_data.py | 6 - .../tests/functional/test_encrypt_decrypt.py | 5 - .../tests/functional/test_get_token_info.py | 6 +- .../tests/functional/test_hsm_management.py | 27 --- .../tests/functional/test_key_management.py | 7 - pycryptoki/tests/functional/test_key_usage.py | 9 - pycryptoki/tests/functional/test_keys.py | 162 +++++++++++++----- .../tests/functional/test_object_create.py | 6 +- .../tests/functional/test_sign_verify.py | 5 - .../functional/test_supporting_operations.py | 5 - .../functional/test_usage_limit_and_count.py | 88 ++++------ .../tests/functional/test_wrap_unwrap.py | 5 - 15 files changed, 247 insertions(+), 212 deletions(-) diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 0be4999..99307c9 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -64,9 +64,6 @@ def c_get_attribute_value(h_session, h_object, template): for index in range(0, len(c_struct)): key_type = c_struct[index].type if any(key_type == unknown_key_type for unknown_key_type in unknown_key_vals): - LOG.debug("Allocating memory len(%s) for key %s", - c_struct[index].usValueLen, - key_type) # Allocate memory for the type. c_obj_type = KEY_TRANSFORMS[key_type].ctype mem = (c_obj_type * c_struct[index].usValueLen)() diff --git a/pycryptoki/tests/functional/conftest.py b/pycryptoki/tests/functional/conftest.py index 2257644..af5f8a9 100644 --- a/pycryptoki/tests/functional/conftest.py +++ b/pycryptoki/tests/functional/conftest.py @@ -4,16 +4,21 @@ import os import pytest - +import logging +from ...attributes import Attributes +from ...key_generator import c_destroy_object +from ...object_attr_lookup import c_find_objects_ex from . import config as hsm_config from ...defaults import ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL, CO_PASSWORD -from ...defines import CKF_RW_SESSION, CKF_SERIAL_SESSION, CKF_PROTECTED_AUTHENTICATION_PATH +from ...defines import CKF_RW_SESSION, CKF_SERIAL_SESSION, CKF_PROTECTED_AUTHENTICATION_PATH, CKR_OK from ...defines import CKF_SO_SESSION from ...session_management import c_initialize_ex, c_close_all_sessions_ex, \ ca_factory_reset_ex, c_open_session_ex, login_ex, c_finalize_ex, \ c_close_session, c_logout, c_get_token_info_ex from ...token_management import c_init_token_ex +LOG = logging.getLogger(__name__) + def pytest_addoption(parser): """ @@ -22,10 +27,32 @@ def pytest_addoption(parser): optiongroup = parser.getgroup("pycryptoki", "Pycryptoki test options") optiongroup.addoption("--slot", - help="Specify the admin slot of the HSM you are testing on", + help="Specify the slot you are testing on (Can be Admin or " + "User slot)", type=int, - default=os.environ.get("ADMIN_SLOT", 1), + default=os.environ.get("SLOT", 1), dest="test_slot") + optiongroup.addoption("--reset", + help="Reset the HSM back to its default settings with a factory" + " reset.", + action="store_true", + default=False) + optiongroup.addoption("--password", + help="Password for the Admin Slot. Can be None for PED-authentication " + "devices.", + action="store", + type=str, + default=ADMINISTRATOR_PASSWORD) + optiongroup.addoption("--copassword", + help="Password for the Crypto Officer user/slot. Can be None for " + "PED-authentication.", + action="store") + optiongroup.addoption("--user", + help="User type to test with. Defaults to SO. Can also test w/ " + "Crypto Officer", + choices=["SO", "CO"], + default="SO", + action="store") def pytest_configure(config): @@ -45,54 +72,63 @@ def pytest_configure(config): if is_ped: admin_pwd = None - co_pwd = None + co_pwd = config.getoption("copassword", default=None) else: - admin_pwd = ADMINISTRATOR_PASSWORD - co_pwd = CO_PASSWORD + admin_pwd = config.getoption("password") + co_pwd = config.getoption("copassword", default=CO_PASSWORD) + hsm_config['admin_pwd'] = admin_pwd hsm_config['co_pwd'] = co_pwd + + if config.getoption("user") == "CO": + hsm_config['password'] = co_pwd + else: + hsm_config['password'] = admin_pwd finally: c_finalize_ex() @pytest.yield_fixture(scope='session', autouse=True) -def hsm_configured(): +def hsm_configured(pytestconfig): """ Factory reset & init the hsm. """ c_initialize_ex() try: - slot = hsm_config["test_slot"] - c_close_all_sessions_ex(slot) - ca_factory_reset_ex(slot) - - # Initialize the Admin Token - session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) - - _ = c_open_session_ex(slot, session_flags) - c_init_token_ex(slot, hsm_config['admin_pwd'], ADMIN_PARTITION_LABEL) - - # TODO: This will need to change for testing on CO slots. - # In the meantime, we test on the admin slot just fine. - # slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) - # c_close_all_sessions_ex(slot) - # h_session = c_open_session_ex(slot, session_flags) - # login_ex(h_session, slot, hsm_config['admin_pwd'], 0) - # c_init_pin_ex(h_session, hsm_config['co_pwd']) - # c_logout_ex(h_session) - c_close_all_sessions_ex(slot) + if pytestconfig.getoption("reset"): + slot = hsm_config["test_slot"] + c_close_all_sessions_ex(slot) + ca_factory_reset_ex(slot) + + # Initialize the Admin Token + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + + _ = c_open_session_ex(slot, session_flags) + c_init_token_ex(slot, hsm_config['admin_pwd'], ADMIN_PARTITION_LABEL) + + # TODO: This will need to change for testing on CO slots. + # In the meantime, we test on the admin slot just fine. + # slot = get_token_by_label_ex(ADMIN_PARTITION_LABEL) + # c_close_all_sessions_ex(slot) + # h_session = c_open_session_ex(slot, session_flags) + # login_ex(h_session, slot, hsm_config['admin_pwd'], 0) + # c_init_pin_ex(h_session, hsm_config['co_pwd']) + # c_logout_ex(h_session) + c_close_all_sessions_ex(slot) yield finally: c_finalize_ex() @pytest.yield_fixture(scope="class") -def session(hsm_configured): +def session(pytestconfig, hsm_configured): """ Creates & returns a session on the Admin slot. """ _ = hsm_configured - session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) + session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION) + if pytestconfig.getoption("user") == "SO": + session_flags = session_flags | CKF_SO_SESSION slot = hsm_config["test_slot"] h_session = c_open_session_ex(slot, session_flags) @@ -101,11 +137,30 @@ def session(hsm_configured): @pytest.yield_fixture(scope="class") -def auth_session(session): +def auth_session(pytestconfig, session): """ Logs into the created admin session """ slot = hsm_config["test_slot"] - login_ex(session, slot, hsm_config["admin_pwd"], 0) + usertype = 0 if pytestconfig.getoption("user") == "SO" else 1 + login_ex(session, slot, hsm_config["password"], usertype) yield session c_logout(session) + + +@pytest.yield_fixture(scope="class", autouse=True) +def partition_clearer(auth_session): + """ + Autoused fixture to make sure the active session is cleared from all created objects. + + :param auth_session: + :return: + """ + yield + # Use a blank template so we can grab everything. + template = Attributes({}).get_c_struct() + objects = c_find_objects_ex(auth_session, template, 1000) + for handle in objects: + ret = c_destroy_object(auth_session, handle) + if ret != CKR_OK: + LOG.info("Failed to destroy object w/ handle %s", handle) diff --git a/pycryptoki/tests/functional/test_cka_start_and_end.py b/pycryptoki/tests/functional/test_cka_start_and_end.py index a28caf6..d992f41 100755 --- a/pycryptoki/tests/functional/test_cka_start_and_end.py +++ b/pycryptoki/tests/functional/test_cka_start_and_end.py @@ -29,9 +29,6 @@ class TestCKAStartEndDate(object): """ """ - h_session = 0 - admin_slot = 0 - @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): self.admin_slot = hsm_config["test_slot"] @@ -342,8 +339,3 @@ def test_asymmetric_key_expiry_dsa(self): return_val, sig = c_sign(h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) logger.info("Called C_Sign, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_digest_data.py b/pycryptoki/tests/functional/test_digest_data.py index caa80ed..dfba6b8 100755 --- a/pycryptoki/tests/functional/test_digest_data.py +++ b/pycryptoki/tests/functional/test_digest_data.py @@ -1,5 +1,4 @@ import logging -import os import pytest @@ -37,8 +36,3 @@ def test_multipart_digest_data(self): assert _get_string_from_list( data_to_digest) != digested_data, "The digested data should not be the same as the " \ "original string" - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_encrypt_decrypt.py b/pycryptoki/tests/functional/test_encrypt_decrypt.py index 35904b1..ca3a937 100755 --- a/pycryptoki/tests/functional/test_encrypt_decrypt.py +++ b/pycryptoki/tests/functional/test_encrypt_decrypt.py @@ -63,8 +63,3 @@ def test_multipart_encrypt_decrypt(self): data_to_encrypt) == decrypted_data, "The data before encryption should match the data " \ "" \ "after encryption" - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_get_token_info.py b/pycryptoki/tests/functional/test_get_token_info.py index 13255d2..3c740c3 100755 --- a/pycryptoki/tests/functional/test_get_token_info.py +++ b/pycryptoki/tests/functional/test_get_token_info.py @@ -41,6 +41,7 @@ def reset_to_defaults(): c_close_all_sessions_ex(slot) +@pytest.mark.skipif("config.getoption('user') != 'SO'") class TestGetTokenInfo(object): """ """ @@ -75,8 +76,3 @@ def test_initial_flags(self): logger.info("After initialization found flags " + str( hex(flags)) + " on admin partition should match expected flags" + str( hex(expected_flags))) - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_hsm_management.py b/pycryptoki/tests/functional/test_hsm_management.py index 5eecab3..824457e 100755 --- a/pycryptoki/tests/functional/test_hsm_management.py +++ b/pycryptoki/tests/functional/test_hsm_management.py @@ -1,8 +1,6 @@ """ Test methods for pycryptoki 'hsm management' set of commands. """ -import logging -import os import pytest @@ -25,9 +23,6 @@ class TestAlgorithm(object): """Test algorithm class""" - h_session = 0 - admin_slot = 0 - @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): self.h_session = auth_session @@ -111,23 +106,6 @@ def test_hainit(self): "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - def test_createloginchallenge(self): - """Test create login challenge. - This test requires PED based HSM. - If performing this test on PWD based HSM return value is CKR_CANCEL. - - - """ - user_type = CKU_CRYPTO_USER - challenge = "password1234" - - ret, data = ca_createloginchallenge(self.h_session, - user_type, - challenge) - assert (ret == CKR_OK or ret == CKR_CANCEL), \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] - @pytest.mark.xfail(reason="Not valid on PWD auth") def test_initializeremotepedvector(self): """Tests to initialize remote ped vector""" @@ -166,8 +144,3 @@ def test_mtkzeroize(self): assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_key_management.py b/pycryptoki/tests/functional/test_key_management.py index 3f3430c..cd8a4e6 100755 --- a/pycryptoki/tests/functional/test_key_management.py +++ b/pycryptoki/tests/functional/test_key_management.py @@ -20,8 +20,6 @@ class TestAlgorithm(object): """Test algorithm class""" - h_session = 0 - admin_slot = 0 @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): @@ -77,8 +75,3 @@ def test_modifyusagecount(self, command_type): assert ret == CKR_OK, \ "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_key_usage.py b/pycryptoki/tests/functional/test_key_usage.py index 345fd06..2944f54 100755 --- a/pycryptoki/tests/functional/test_key_usage.py +++ b/pycryptoki/tests/functional/test_key_usage.py @@ -1,8 +1,6 @@ """ Test methods for .. 'hsm usage' set of commands. """ -import logging -import os import pytest @@ -15,8 +13,6 @@ class TestAlgorithm(object): """Test algorithm class""" - h_session = 0 - admin_slot = 0 @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): @@ -39,8 +35,3 @@ def test_duplicatemofn(self): "Return code should be " + \ ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ " not " + ret_vals_dictionary[ret] - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_keys.py b/pycryptoki/tests/functional/test_keys.py index 11adb34..89ac2b4 100755 --- a/pycryptoki/tests/functional/test_keys.py +++ b/pycryptoki/tests/functional/test_keys.py @@ -1,13 +1,8 @@ -import ctypes import logging -import os -from ctypes import cast, pointer import pytest -from ...mechanism import NullMech from . import config as hsm_config -from ...cryptoki import CK_VOID_PTR, CK_ULONG from ...default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ @@ -29,9 +24,13 @@ CKM_ARIA_KEY_GEN, \ CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ - CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_CONCATENATE_BASE_AND_KEY, CKA_ECDSA_PARAMS + CKM_RSA_X9_31_KEY_PAIR_GEN, CKA_ECDSA_PARAMS, \ + CKM_SHA224_KEY_DERIVATION, CKM_SHA256_KEY_DERIVATION, CKM_SHA1_KEY_DERIVATION, \ + CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_MD5_KEY_DERIVATION, \ + CKM_MD2_KEY_DERIVATION, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE from ...key_generator import c_generate_key, c_generate_key_pair, \ - c_derive_key, c_generate_key_ex, _get_mechanism + c_derive_key, c_generate_key_ex, c_destroy_object +from ...mechanism import NullMech from ...return_values import ret_vals_dictionary from ...test_functions import verify_object_attributes @@ -56,13 +55,9 @@ def setup_teardown(self, auth_session): (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), - # (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), - # (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX - # (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) - # (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX ]) def test_generate_key(self, key_type, key_template): """Tests generating a key, asserts that the operation returns correctly with key handles @@ -138,36 +133,43 @@ def test_generate_ecdsa_key_pairs(self, curve_type): :param curve_type: """ - print curve_list.keys() CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + \ - ret_vals_dictionary[ret] - assert public_key_handle > 0, "The public key handle returned should be non zero" - assert private_key_handle > 0, "The private key handle returned should be non zero" + try: + assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " \ + "" + \ + ret_vals_dictionary[ret] + assert public_key_handle > 0, "The public key handle returned should be non zero" + assert private_key_handle > 0, "The private key handle returned should be non zero" + finally: + if public_key_handle: + c_destroy_object(self.h_session, public_key_handle) + if private_key_handle: + c_destroy_object(self.h_session, private_key_handle) + @pytest.mark.parametrize("derive_type", [CKM_SHA1_KEY_DERIVATION, + CKM_SHA224_KEY_DERIVATION, + CKM_SHA256_KEY_DERIVATION, + CKM_SHA384_KEY_DERIVATION, + CKM_SHA512_KEY_DERIVATION, + CKM_MD5_KEY_DERIVATION, + CKM_MD2_KEY_DERIVATION], + ids=["SHA1", "SHA224", "SHA256", "SHA384", "SHA512", + "MD5", "MD2"]) @pytest.mark.parametrize(("key_type", "key_template"), [ (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), - (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), - (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), - # (CKM_SSL3_PRE_MASTER_KEY_GEN, CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP), XXX - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), - # (CKM_DSA_PARAMETER_GEN, CKM_DSA_PARAMETER_GEN_TEMP), XXX - # (CKM_KCDSA_PARAMETER_GEN, CKM_KCDSA_PARAMETER_GEN_TEMP), XXX - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) - # (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP) XXX - ]) - def test_derive_key(self, key_type, key_template): + ], + ids=["DES", "DES2", 'CAST3', + 'GENERIC', 'CAST5', "SEED", ]) + def test_derive_key(self, key_type, key_template, derive_type): """Tests deriving a key :param key_type: @@ -175,24 +177,102 @@ def test_derive_key(self, key_type, key_template): """ h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) - h_second_key = c_generate_key_ex(self.h_session, key_type, key_template) + mech = NullMech(derive_type).to_c_mech() - mech = NullMech(CKM_CONCATENATE_BASE_AND_KEY).to_c_mech() - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) + derived_key_template = key_template.copy() + del derived_key_template[CKA_VALUE_LEN] ret, h_derived_key = c_derive_key(self.h_session, h_base_key, key_template, - CKM_CONCATENATE_BASE_AND_KEY, - mech) - assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + \ - ret_vals_dictionary[ret] + mech_flavor=derive_type, + mech=mech) + try: + assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + \ + ret_vals_dictionary[ret] + + verify_object_attributes(self.h_session, h_derived_key, key_template) + finally: + if h_base_key: + c_destroy_object(self.h_session, h_base_key) + if h_derived_key: + c_destroy_object(self.h_session, h_derived_key) + + @pytest.mark.parametrize("derive_type", [CKM_SHA1_KEY_DERIVATION, + CKM_MD5_KEY_DERIVATION, + CKM_MD2_KEY_DERIVATION], + ids=["SHA1", "MD5", "MD2"]) + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) + ], + ids=['DES3', 'AES', 'ARIA']) + def test_too_long_length_derives(self, key_type, key_template, derive_type): + """ + Verify that trying to derive a key that is too long for the given derivation function + will return CKR_KEY_SIZE_RANGE + + :param key_type: + :param key_template: + :param derive_type: + :return: + """ + h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) + mech = NullMech(derive_type).to_c_mech() - verify_object_attributes(self.h_session, h_derived_key, key_template) + derived_key_template = key_template.copy() + del derived_key_template[CKA_VALUE_LEN] + + ret, h_derived_key = c_derive_key(self.h_session, + h_base_key, + key_template, + mech_flavor=derive_type, + mech=mech) + try: + assert ret == CKR_KEY_SIZE_RANGE + finally: + if h_base_key: + c_destroy_object(self.h_session, h_base_key) + if h_derived_key: + c_destroy_object(self.h_session, h_derived_key) + @pytest.mark.parametrize("derive_type", [CKM_SHA224_KEY_DERIVATION, + CKM_SHA256_KEY_DERIVATION, + CKM_SHA384_KEY_DERIVATION, + CKM_SHA512_KEY_DERIVATION], + ids=["SHA224", "SHA256", "SHA384", "SHA512"]) + @pytest.mark.parametrize(("key_type", "key_template"), [ + (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), + (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), + (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) + ], + ids=['DES3', 'AES', 'ARIA']) + def test_long_length_derive_key(self, key_type, key_template, derive_type): + """Tests deriving a key + + :param key_type: + :param key_template: + + """ + h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) + mech = NullMech(derive_type).to_c_mech() + + derived_key_template = key_template.copy() + del derived_key_template[CKA_VALUE_LEN] + + ret, h_derived_key = c_derive_key(self.h_session, + h_base_key, + key_template, + mech_flavor=derive_type, + mech=mech) + try: + assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + \ + ret_vals_dictionary[ret] -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) + verify_object_attributes(self.h_session, h_derived_key, key_template) + finally: + if h_base_key: + c_destroy_object(self.h_session, h_base_key) + if h_derived_key: + c_destroy_object(self.h_session, h_derived_key) diff --git a/pycryptoki/tests/functional/test_object_create.py b/pycryptoki/tests/functional/test_object_create.py index 6631f06..d4d2a71 100755 --- a/pycryptoki/tests/functional/test_object_create.py +++ b/pycryptoki/tests/functional/test_object_create.py @@ -13,7 +13,7 @@ logger = logging.getLogger(__name__) -@pytest.mark.xfail("Waiting on LA-1860") +@pytest.mark.xfail(reason="Attributes do not convert 1-to-1 back to python") class TestObjectCloning(object): """ """ @@ -48,7 +48,3 @@ def test_data_create(self): verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_sign_verify.py b/pycryptoki/tests/functional/test_sign_verify.py index 9519374..6a358d3 100755 --- a/pycryptoki/tests/functional/test_sign_verify.py +++ b/pycryptoki/tests/functional/test_sign_verify.py @@ -104,8 +104,3 @@ def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_templa ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + \ ret_vals_dictionary[ret] - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_supporting_operations.py b/pycryptoki/tests/functional/test_supporting_operations.py index 270ed49..96c5a39 100755 --- a/pycryptoki/tests/functional/test_supporting_operations.py +++ b/pycryptoki/tests/functional/test_supporting_operations.py @@ -51,8 +51,3 @@ def test_seeded_rng(self): ret_vals_dictionary[ret] random_string_two = c_generate_random_ex(self.h_session, 10) - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-vs', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_usage_limit_and_count.py b/pycryptoki/tests/functional/test_usage_limit_and_count.py index 28feb06..6f87e1d 100755 --- a/pycryptoki/tests/functional/test_usage_limit_and_count.py +++ b/pycryptoki/tests/functional/test_usage_limit_and_count.py @@ -10,7 +10,6 @@ import pytest from . import config as hsm_config -from ...cryptoki import CK_ULONG from ...default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP from ...defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ @@ -20,7 +19,7 @@ from ...key_generator import c_generate_key_ex, c_generate_key_pair_ex from ...object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) class TestUsageLimitAndCount(object): @@ -42,24 +41,24 @@ def test_set_attribute_usage_limit_sym(self): """ - logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + LOG.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ an symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_LIMIT: 5} + usage_template = {CKA_USAGE_LIMIT: 5} h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) + LOG.info("Called c-generate: Key handle -" + str(h_key)) usage_limit = 5 c_set_attribute_value_ex(self.h_session, - h_key, CKM_USAGE_CHECK_TEMP) + h_key, usage_template) out_template = c_get_attribute_value_ex(self.h_session, h_key, template={CKA_USAGE_LIMIT: None}) usage_val_out = out_template[CKA_USAGE_LIMIT] - logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" def test_usage_limit_attribute_check_sym_des(self): @@ -73,19 +72,18 @@ def test_usage_limit_attribute_check_sym_des(self): """ - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + LOG.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, - CKA_USAGE_LIMIT: 2} + usage_lim_template = {CKA_USAGE_LIMIT: 2} usage_count = 2 h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) + LOG.info("Called c-generate: Key handle -" + str(h_key)) c_set_attribute_value_ex(self.h_session, - h_key, CKM_USAGE_CHECK_TEMP) + h_key, usage_lim_template) c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) @@ -95,7 +93,7 @@ def test_usage_limit_attribute_check_sym_des(self): template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" @@ -110,19 +108,18 @@ def test_usage_limit_attribute_check_sym_aes(self): """ - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + LOG.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ use the symmetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, - CKA_USAGE_LIMIT: 2} + usage_lim_template = {CKA_USAGE_LIMIT: 2} usage_count = 2 h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_AES_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) + LOG.info("Called c-generate: Key handle -" + str(h_key)) c_set_attribute_value_ex(self.h_session, - h_key, CKM_USAGE_CHECK_TEMP) + h_key, usage_lim_template) c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) @@ -131,7 +128,7 @@ def test_usage_limit_attribute_check_sym_aes(self): template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" @@ -146,27 +143,26 @@ def test_set_attribute_usage_limit_Assym(self): """ - logger.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ + LOG.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ an assymetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, - CKA_USAGE_LIMIT: 2} + usage_lim_template = {CKA_USAGE_LIMIT: 2} h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) - logger.info( + LOG.info( "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( h_prkey)) usage_limit = 2 c_set_attribute_value_ex(self.h_session, - h_pbkey, CKM_USAGE_CHECK_TEMP) + h_pbkey, usage_lim_template) py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_LIMIT: None}) usage_val_out = py_template[CKA_USAGE_LIMIT] - logger.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" def test_usage_limit_attribute_check_Assym(self): @@ -181,11 +177,10 @@ def test_usage_limit_attribute_check_Assym(self): """ - logger.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ + LOG.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ use the assymetric crypto object") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, - CKA_USAGE_LIMIT: 2} + usage_lim_template = {CKA_USAGE_LIMIT: 2} usage_count = 2 h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, @@ -193,12 +188,12 @@ def test_usage_limit_attribute_check_Assym(self): prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) - logger.info( + LOG.info( "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( h_prkey)) c_set_attribute_value_ex(self.h_session, - h_pbkey, CKM_USAGE_CHECK_TEMP) + h_pbkey, usage_lim_template) c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) @@ -207,7 +202,7 @@ def test_usage_limit_attribute_check_Assym(self): template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): @@ -221,30 +216,29 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): """ - logger.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ + LOG.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, - CKA_USAGE_LIMIT: 2} + usage_lim_template = {CKA_USAGE_LIMIT: 2} h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) - logger.info("Called c-generate: Key handle -" + str(h_key)) + LOG.info("Called c-generate: Key handle -" + str(h_key)) c_set_attribute_value_ex(self.h_session, - h_key, CKM_USAGE_CHECK_TEMP) + h_key, usage_lim_template) c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - return_val = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) - logger.info("Called C_Encrypt, return code: " + str(return_val)) + return_val, data = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + LOG.info("Called C_Encrypt, return code: " + str(return_val)) py_template = c_get_attribute_value_ex(self.h_session, h_key, template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - logger.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" @@ -259,34 +253,28 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): """ - CKM_USAGE_CHECK_TEMP = {CKA_USAGE_COUNT: 0, - CKA_USAGE_LIMIT: 2} + usage_lim_template = {CKA_USAGE_LIMIT: 2} h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) - logger.info( + LOG.info( "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( h_prkey)) c_set_attribute_value_ex(self.h_session, - h_pbkey, CKM_USAGE_CHECK_TEMP) + h_pbkey, usage_lim_template) c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - return_val = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) - logger.info("Called C_Encrypt, return code: " + str(return_val)) + return_val, data = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + LOG.info("Called C_Encrypt, return code: " + str(return_val)) py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - - -if __name__ == "__main__": - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-s', os.path.abspath(__file__)]) diff --git a/pycryptoki/tests/functional/test_wrap_unwrap.py b/pycryptoki/tests/functional/test_wrap_unwrap.py index 1f4b1eb..638b0a9 100755 --- a/pycryptoki/tests/functional/test_wrap_unwrap.py +++ b/pycryptoki/tests/functional/test_wrap_unwrap.py @@ -82,8 +82,3 @@ def test_encrypt_wrap_unwrap_decrypt_key(self): assert decrypted_string == data_to_encrypt, \ "The decrypted data should be the same as the data that was encrypted. " \ "Instead found " + str(decrypted_string) - - -if __name__ == '__main__': - logging.basicConfig(level=logging.DEBUG) - pytest.cmdline.main(args=['-v', os.path.abspath(__file__)]) From 706826e4700227ad220c78b01e79415f64eb9fb3 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 20 Jun 2016 15:18:04 -0400 Subject: [PATCH 050/109] LA-1864 Removed references to headers Cleaned up some additional references to internal code. Change-Id: Ibafe84161c77d08dca95adf2b8335c0062d9a3b4 --- pycryptoki/backup.py | 19 +- pycryptoki/cryptoki.py | 5 - pycryptoki/cryptoki_helpers.py | 89 ++--- pycryptoki/defines.py | 313 +++++++++--------- pycryptoki/key_generator.py | 6 +- pycryptoki/logging_filters.py | 30 -- pycryptoki/misc.py | 5 +- pycryptoki/pycryptoki_client.py | 13 - pycryptoki/sign_verify.py | 4 +- pycryptoki/test_functions.py | 9 +- .../tests/functional/test_sign_verify.py | 9 +- setup.py | 1 - 12 files changed, 199 insertions(+), 304 deletions(-) delete mode 100755 pycryptoki/logging_filters.py diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index ee8c53f..4b07b34 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -2,21 +2,11 @@ from ctypes import byref from .cryptoki import CA_OpenSecureToken, CA_CloseSecureToken, CA_Extract, CA_Insert, CK_ULONG -from .mechanism import get_c_struct_from_mechanism, \ - get_python_dict_from_c_mechanism, Mechanism +from .mechanism import Mechanism from .test_functions import make_error_handle_function logger = logging.getLogger(__name__) -''' -CK_SESSION_HANDLE hSession, - CK_ULONG storagePath, - CK_ULONG devID, - CK_ULONG mode, - CK_ULONG_PTR numberOfElems, - CK_ULONG_PTR phID -''' - def ca_open_secure_token(h_session, storage_path, dev_ID, mode): """ @@ -37,10 +27,6 @@ def ca_open_secure_token(h_session, storage_path, dev_ID, mode): ca_open_secure_token_ex = make_error_handle_function(ca_open_secure_token) -''' -CK_SESSION_HANDLE hSession, CK_ULONG hID -''' - def ca_close_secure_token(h_session, h_ID): """ @@ -76,9 +62,6 @@ def ca_extract(h_session, mech_type, mech_params): ca_extract_ex = make_error_handle_function(ca_extract) -# CA_Insert( CK_SESSION_HANDLE hSession, -# CK_MECHANISM_PTR pMechanism ) - def ca_insert(h_session, mech_type, mech_params): """ diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index a037942..105d863 100755 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -1,9 +1,4 @@ ''' -THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE -This file should NOT be checked into MKS or modified in any way, this file was -created by setup/initialize.py. Any changes to this file will be wiped out when -it is regenerated. - This file contains all of the ctypes definitions for the cryptoki library. The ctypes definitions outline the structures for the cryptoki C API. ''' diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index dd10113..3a880e0 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -1,47 +1,20 @@ -from ctypes import CDLL +""" +Helper functions to get us access to the PKCS11 library. +""" +import logging import os import re import sys +from ctypes import CDLL from .defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE - -def parse_chrystoki_conf(): - """The autogeneration of cryptoki.py now prepends a method which sets the DLL's path to - be called every time cryptoki.py is imported. This method parses Cryptoki's configuration - file in python for the DLL's location. While originally it was desired to reuse the C code - which parses Cryptoki.conf this was not possible because Pycryptoki can only call functions - on the dll, you cannot do something like instantiate a class and then call a function on that class. - - ex: ckdemo does: - ChrystokiConfiguration conf; - char* libName = conf.LibraryFileName(); - - Option 1: - Create a new api function and make it visible in the DLL. It's not very good to put functions - that are customer visible in the API that are going to be used for testing tools. In addition - it would be necessary to store a copy of the DLL in the pycryptoki package and load this DLL - every time pycryptoki is run. This is therefore not a great option. - - Option 2: - Write a short program in C++ that compiles against luna's source code. Then python can call - this file to get the output. This would work however it create a dependency that portions of - pycryptoki must be compiled, in addition when distributing pycryptoki to the testing team it - would be necessary to distribute platform dependent code. - - Creating a compilation dependency between pycryptoki and the C code is not a good idea since - it will be necessary to make a C program in the setup for pycryptoki which increases the - complexity of the setup. - - Option 3: - Parse the file in python. - - This option was chosen because it was fairly easy to do and supported across all platforms. - It is also the simplest approach. The disadvantage to this is the configuration file may be - parsed differently in C than in python. Therefore lot of error checking was added to the parsing - process as well as printing of which DLL was found in each run of the Cryptoki library.. +LOG = logging.getLogger(__name__) +def parse_chrystoki_conf(): + """Parse the crystoki.ini/Chrystoki.conf file to find the library .so/.dll file so that + we can use it. """ env_conf_path = os.environ.get("ChrystokiConfigurationPath") @@ -49,11 +22,11 @@ def parse_chrystoki_conf(): if CHRYSTOKI_DLL_FILE is not None: # Use this value for the location of the DLL dll_path = CHRYSTOKI_DLL_FILE - print "Using DLL Path from defaults.py:" + dll_path + LOG.info("Using DLL Path from defaults.py: %s", dll_path) return dll_path elif CHRYSTOKI_CONFIG_FILE is not None: conf_path = CHRYSTOKI_CONFIG_FILE - print "Using Chrystoki.conf location from defaults.py: " + conf_path + LOG.info("Using Chrystoki.conf location from defaults.py: %s", conf_path) elif env_conf_path is not None: if 'win' in sys.platform: env_conf_path = env_conf_path.replace('\\\\', '~').replace('~', '\\') + 'crystoki.ini' @@ -61,19 +34,21 @@ def parse_chrystoki_conf(): env_conf_path = os.path.join(env_conf_path, 'Chrystoki.conf') conf_path = env_conf_path - print "Using Chrystoki.conf location from environment variable ChrystokiConfigurationPath: " + conf_path + LOG.info("Using Chrystoki.conf location from " + "environment variable ChrystokiConfigurationPath: %s", conf_path) if conf_path is None: conf_path = '/etc/Chrystoki.conf' - print "No DLL Path or Chyrstoki.conf path set in defaults.py looking up DLL path in " + str(conf_path) + LOG.info("No DLL Path or Chyrstoki.conf path set in defaults.py, " + "looking up DLL path in %s", conf_path) - print "Searching " + str(conf_path) + " for Chrystoki DLL path..." + LOG.info("Searching %s for Chrystoki DLL path...", conf_path) chrystoki_conf_text = _get_chrystoki_conf_file_text(conf_path) dll_path = _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text) - print "Using DLL at location: " + dll_path + LOG.info("Using DLL at location: %s", dll_path) return dll_path @@ -91,12 +66,10 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): chrystoki2_segments = re.findall("\s*\[Chrystoki2\]\s*([^\r\n]*)", chrystoki_conf_text) if len(chrystoki2_segments) > 1: - print chrystoki2_segments - raise Exception( - "Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + raise Exception("Found %s Chrystoki2 sections in the config file: %s", + chrystoki2_segments, conf_path) elif len(chrystoki2_segments) < 1: - print chrystoki2_segments - raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) + raise Exception("Found no Chrystoki2 section in the config file: %s", conf_path) chrystoki2 = chrystoki2_segments[0].split('\n') dll_path = "" @@ -111,17 +84,15 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): dll_path = lib_nt_line[0].strip().strip(';').strip().strip("'").strip('"') if dll_path == "": - raise Exception("Error finding LibNT declaration in configuration file: " + str(conf_path)) + raise Exception("Error finding LibNT declaration in configuration file: %s", conf_path) else: chrystoki2_segments = re.findall("\s*Chrystoki2\s*=\s*\{([^\}]*)", chrystoki_conf_text) if len(chrystoki2_segments) > 1: - print chrystoki2_segments - raise Exception( - "Found " + len(chrystoki2_segments) + "Chrystoki2 sections in the config file: " + str(conf_path)) + raise Exception("Found %s Chrystoki2 sections in the config file: %s", + chrystoki2_segments, conf_path) elif len(chrystoki2_segments) < 1: - print chrystoki2_segments - raise Exception("Found no Chrystoki2 section in the config file: " + str(conf_path)) + raise Exception("Found no Chrystoki2 section in the config file: %s", conf_path) chrystoki2 = chrystoki2_segments[0].split('\n') dll_path = "" @@ -140,7 +111,8 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): dll_path = lib_unix_line[0].strip().strip(';').strip().strip("'").strip('"') if dll_path == "": - raise Exception("Error finding LibUNIX declaration in configuration file: " + str(conf_path)) + raise Exception("Error finding LibUNIX declaration in configuration file: %s", + conf_path) return dll_path @@ -149,14 +121,13 @@ def _get_chrystoki_conf_file_text(conf_path): """Reads in the chrystoki configuration and returns the text in the file :param conf_path: - """ try: chrystoki_conf_file = open(conf_path, "r") chrystoki_conf_text = chrystoki_conf_file.read() except IOError: - raise Exception("Could not find/read Chrystoki configuration file at path " + str(conf_path)) + raise Exception("Could not find/read Chrystoki configuration file at path %s", conf_path) return chrystoki_conf_text @@ -201,7 +172,8 @@ def get_dll(self): """ """ if self.loaded_dll_library is None or self.loaded_dll_library == "": raise Exception( - "DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read /etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") + "DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read " + "/etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") return self.loaded_dll_library @@ -228,6 +200,7 @@ def luna_function(*args, **kwargs): return_value = late_binded_function(*args, **kwargs) return return_value except Exception as e: - raise CryptokiDLLException("Call to '" + function_name + str(args) + str(kwargs) + "' failed.", e) + raise CryptokiDLLException( + "Call to '%s(%s, %s)' failed." % (function_name, args, kwargs), e) return luna_function diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index 58195e4..6489891 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1,17 +1,7 @@ ''' -THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE -This file should NOT be checked into MKS or modified in any way, this file was -created by setup/initialize.py. Any changes to this file will be wiped out when -it is regenerated. - -This file contains defines which have been automatically scraped from the -cryptoki API header files. The defines are stored as variables in python. -If you add any new defines you can rerun initialize.py to regenerate this file. -If you need to scrape another header file add the desired file to the header_files -array in initialize.py and rerun initialize.py. +Constants & Definitions pulled from PKCS11 ''' -'''/var/jenkins/workspace/luna-k7/crypto/interfaces/Include/firmware/luna2if.h''' LUNA_MAX_UPDATE_DATA_SIZE = (64 * 1024) LUNA_GEN_KCV_FLAG_NONE = 0x0000 LUNA_GEN_KCV_FLAG_CONSOLIDATE = 0x0001 @@ -136,28 +126,28 @@ LUNA_MECH_SHA1_RC4_40 = 0x00008209 LUNA_MECH_SHA1_RC2_128_CBC = 0x0000820A LUNA_MECH_SHA1_RC2_40_CBC = 0x0000820B -LUNA_MECH_SHA1_DES2_CBC_OLD = 0x0000820C # Added for compatibility with legacy apps -LUNA_MECH_SHA1_DES3_CBC_OLD = 0x0000820D # Added for compatibility with legacy apps -LUNA_MECH_CONCATENATE_BASE_AND_KEY = 0x00008301 # Added for SPKM & SSL Support -LUNA_MECH_CONCATENATE_KEY_AND_BASE = 0x00008302 # Added for SPKM & SSL Support -LUNA_MECH_CONCATENATE_BASE_AND_DATA = 0x00008303 # Added for SPKM & SSL Support -LUNA_MECH_CONCATENATE_DATA_AND_BASE = 0x00008304 # Added for SPKM & SSL Support -LUNA_MECH_XOR_BASE_AND_DATA = 0x00008305 # Added for SPKM & SSL Support -LUNA_MECH_XOR_BASE_AND_KEY = 0x0000860B # Added for F/W Update Support -LUNA_MECH_EXTRACT_KEY_FROM_KEY = 0x00008306 # Added for SPKM & SSL Support -LUNA_MECH_MD2_KEY_DERIVATION = 0x00008307 # Added for SPKM & SSL Support -LUNA_MECH_MD5_KEY_DERIVATION = 0x00008308 # Added for SPKM & SSL Support -LUNA_MECH_SHA1_KEY_DERIVATION = 0x00008309 # Added for SPKM & SSL Support -LUNA_MECH_GENERIC_SECRET_KEY_GEN = 0x0000830A # Added for SPKM & SSL Support -LUNA_MECH_SSL3_MASTER_KEY_DERIVE = 0x0000830B # Added for SSL Support -LUNA_MECH_SSL3_KEY_AND_MAC_DERIVE = 0x0000830C # Added for SSL Support -LUNA_MECH_SSL3_MD5_MAC = 0x0000830D # Added for SSL Support -LUNA_MECH_SSL3_SHA1_MAC = 0x0000830E # Added for SSL Support -LUNA_MECH_HMAC_SHA1 = 0x0000830F # Added for SSL Support -LUNA_MECH_HMAC_SHA1_80 = 0x00008310 # Added for SSL Support -LUNA_MECH_HMAC_MD5 = 0x00008311 # Added for SSL Support -LUNA_MECH_HMAC_MD5_80 = 0x00008312 # Added for SSL Support -LUNA_MECH_SSL3_PRE_MASTER_KEY_GEN = 0x00008313 # Added for SSL Support +LUNA_MECH_SHA1_DES2_CBC_OLD = 0x0000820C +LUNA_MECH_SHA1_DES3_CBC_OLD = 0x0000820D +LUNA_MECH_CONCATENATE_BASE_AND_KEY = 0x00008301 +LUNA_MECH_CONCATENATE_KEY_AND_BASE = 0x00008302 +LUNA_MECH_CONCATENATE_BASE_AND_DATA = 0x00008303 +LUNA_MECH_CONCATENATE_DATA_AND_BASE = 0x00008304 +LUNA_MECH_XOR_BASE_AND_DATA = 0x00008305 +LUNA_MECH_XOR_BASE_AND_KEY = 0x0000860B +LUNA_MECH_EXTRACT_KEY_FROM_KEY = 0x00008306 +LUNA_MECH_MD2_KEY_DERIVATION = 0x00008307 +LUNA_MECH_MD5_KEY_DERIVATION = 0x00008308 +LUNA_MECH_SHA1_KEY_DERIVATION = 0x00008309 +LUNA_MECH_GENERIC_SECRET_KEY_GEN = 0x0000830A +LUNA_MECH_SSL3_MASTER_KEY_DERIVE = 0x0000830B +LUNA_MECH_SSL3_KEY_AND_MAC_DERIVE = 0x0000830C +LUNA_MECH_SSL3_MD5_MAC = 0x0000830D +LUNA_MECH_SSL3_SHA1_MAC = 0x0000830E +LUNA_MECH_HMAC_SHA1 = 0x0000830F +LUNA_MECH_HMAC_SHA1_80 = 0x00008310 +LUNA_MECH_HMAC_MD5 = 0x00008311 +LUNA_MECH_HMAC_MD5_80 = 0x00008312 +LUNA_MECH_SSL3_PRE_MASTER_KEY_GEN = 0x00008313 LUNA_MECH_DES3_CFB8 = 0x00008314 LUNA_MECH_DES3_CFB64 = 0x00008315 LUNA_MECH_DES3_OFB = 0x00008316 @@ -173,12 +163,12 @@ LUNA_MECH_ARIA_OFB = 0x00008320 LUNA_MECH_ARIA_CTR = 0x00008321 LUNA_MECH_ARIA_GCM = 0x00008322 -LUNA_MECH_2DES_DERIVE = 0x000083FF # Added for Gemplus -LUNA_MECH_INDIRECT_LOGIN_REENCRYPT = 0x00008400 # Added for indirect login support. Obsolete as of f/w 5.0 -LUNA_MECH_LZS = 0x00008400 # Added for Compression Support +LUNA_MECH_2DES_DERIVE = 0x000083FF +LUNA_MECH_INDIRECT_LOGIN_REENCRYPT = 0x00008400 +LUNA_MECH_LZS = 0x00008400 LUNA_MECH_LOOP_BACK = 0x80000000 -LUNA_MECH_NONE = LUNA_MECH_LOOP_BACK # Added for IPSEC Support -LUNA_MECH_UNKNOWN = 0xFFFFFFFF # Added for error detection +LUNA_MECH_NONE = LUNA_MECH_LOOP_BACK +LUNA_MECH_UNKNOWN = 0xFFFFFFFF LUNA_MECH_SEED_KEY_GEN = 0x00008701 LUNA_MECH_SEED_ECB = 0x00008702 LUNA_MECH_SEED_CBC = 0x00008703 @@ -209,7 +199,7 @@ LUNA_MASKING_STORAGE_HOST = 0x00000000 LUNA_MASKING_STORAGE_PED_USB_MEMORY = 0x00000001 LUNA_MASKING_STORAGE_HSM_USB_MEMORY = 0x00000002 -LUNA_MASKING_FLAG_DELETE_AFTER_EXTRACT = 0x1 # Flag "Delete After Extract" */ +LUNA_MASKING_FLAG_DELETE_AFTER_EXTRACT = 0x1 LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC = 0x80009000 LUNA_MECH_AES_CBC_PAD_INSERT_PUBLIC = 0x80009001 LUNA_MECH_AES_CBC_PAD_EXTRACT_PUBLIC_FLATTENED = 0x80009002 @@ -289,7 +279,7 @@ LUNA_MGF_MGF1_SHA512 = 0x00000004 LUNA_MGF_MGF1_SHA224 = 0x00000005 LUNA_OAEP_SOURCES_DATA_SPECIFIED = 0x00000001 -LUNA_ATTR_UNKNOWN = 0xFFFFFFFF # Added for error detection */ +LUNA_ATTR_UNKNOWN = 0xFFFFFFFF LUNA_ATTR_CLASS = 0x00000000 LUNA_ATTR_TOKEN = 0x00000001 LUNA_ATTR_PRIVATE = 0x00000002 @@ -351,7 +341,7 @@ LUNA_ATTR_X9_31_GENERATED = (LUNA_ATTR_VENDOR_DEFINED | 0x00000006) LUNA_ATTR_PKC_ECC = (LUNA_ATTR_VENDOR_DEFINED | 0x00000007) LUNA_ATTR_EKM_UID = (LUNA_ATTR_VENDOR_DEFINED | 0x00000008) -LUNA_ATTR_PKC_LEGACY_ECC = (LUNA_ATTR_VENDOR_DEFINED | 0x00000009) # retired but available if needed +LUNA_ATTR_PKC_LEGACY_ECC = (LUNA_ATTR_VENDOR_DEFINED | 0x00000009) LUNA_ATTR_USAGE_COUNT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000101) LUNA_ATTR_USAGE_COUNT_LIMIT = (LUNA_ATTR_VENDOR_DEFINED | 0x00000200) LUNA_ATTR_GENERIC_1 = (LUNA_ATTR_VENDOR_DEFINED | 0x00001000) @@ -379,7 +369,7 @@ LUNA_OBJ_DOMAIN_PARAMETERS = 0x00000005 LUNA_OBJ_HW_FEATURE = 0x00000006 LUNA_OBJ_VENDOR_DEFINED = 0x80000000 -LUNA_OBJ_UNKNOWN = 0xFFFFFFFF # Added for error detection */ +LUNA_OBJ_UNKNOWN = 0xFFFFFFFF LUNA_KEY_RSA = 0x00000000 LUNA_KEY_DSA = 0x00000001 LUNA_KEY_DH = 0x00000002 @@ -407,8 +397,8 @@ LUNA_KEY_VENDOR_DEFINED = 0x80000000 LUNA_KEY_KCDSA = (LUNA_KEY_VENDOR_DEFINED + 0x10) LUNA_KEY_SEED = (LUNA_KEY_VENDOR_DEFINED + 0x11) -LUNA_KEY_UNKNOWN = 0xFFFFFFFF # Added for error detection */ -LUNA_CERT_UNKNOWN = 0xFFFFFFFF # Added for error detection */ +LUNA_KEY_UNKNOWN = 0xFFFFFFFF +LUNA_CERT_UNKNOWN = 0xFFFFFFFF LUNA_CVK_CERTIFICATE = 0x00000000 LUNA_TWC_CERTIFICATE = 0x00000001 LUNA_TUK_PRIVATE_KEY = 0x00000000 @@ -424,7 +414,7 @@ LUNA_GT_MFG = 0x00000001 LUNA_GT_MODEL = 0x00000002 LUNA_GT_TSN = 0x00000003 -LUNA_GT_S_N = 0x00000003 # to remain backward compatible. LUNA_GT_TSN should be used. +LUNA_GT_S_N = 0x00000003 LUNA_GT_FLAGS = 0x00000004 LUNA_GT_SESSIONS = 0x00000005 LUNA_GT_SRAM = 0x00000007 @@ -440,7 +430,7 @@ LUNA_GT_USER_ILD = 0x00000014 LUNA_GT_SO_ILD = 0x00000015 LUNA_GT_ROOT_CERT = 0x00000017 -LUNA_GT_HW_ORIGIN_CERT = 0x00000018 # retrieves HOC+MIC +LUNA_GT_HW_ORIGIN_CERT = 0x00000018 LUNA_GT_TCTRUST_DAC = 0x00000019 LUNA_GT_TCTRUST_MAC = 0x0000001A LUNA_GT_CITS_DAC = 0x0000001B @@ -454,7 +444,7 @@ LUNA_GT_LEGACY_ECC_DAC = 0x00000023 LUNA_GT_ROLLBACK_FWV = 0x00000024 LUNA_GT_MIC = 0x00000025 -LUNA_GT_HOC = 0x00000026 # retrieves HOC only +LUNA_GT_HOC = 0x00000026 LUNA_GT_CITS_MAC = 0x00000027 LUNA_GT_DIAGNOSTIC_LOG = 0x00000028 LUNA_GT_SAVED_DIAGNOSTIC_LOG = 0x00000029 @@ -475,7 +465,7 @@ LUNA_GT_ECC_ROOT_CERT = 0x0000003E LUNA_GT_ECC_MIC = 0x0000003F LUNA_GT_ECC_HOC = 0x00000040 -LUNA_GT_ECC_HW_ORIGIN_CERT = 0x00000041 # retrieves HOC+MIC +LUNA_GT_ECC_HW_ORIGIN_CERT = 0x00000041 LUNA_GT_ECC_TWC = 0x00000042 LUNA_GT_RTC_TEMP = 0x00000050 LUNA_GT_DS3644_TEMP = 0x00000051 @@ -517,14 +507,14 @@ LUNA_ISAKMP_DECRYPT = 0x00000500 LUNA_ISAKMP_ENCRYPT_FIXED_IV = 0x00000501 LUNA_ISAKMP_ENCRYPT_GEN_IV = 0x00000502 -LUNA_ENTRY_DATA_AREA = 0x00000000 # obsolete in NextGen/PerPartitionSO firmware +LUNA_ENTRY_DATA_AREA = 0x00000000 LUNA_ENTRY_SECURE_PORT = 0x00000001 -LUNA_ENTRY_INDIRECT = 0x00000002 # Obsolete as of f/w 5.0 -LUNA_ENTRY_RANDOM = 0x00000003 # only used for pin creation -LUNA_ENTRY_CHALLENGE_RESPONSE = 0x00000004 # only used for login +LUNA_ENTRY_INDIRECT = 0x00000002 +LUNA_ENTRY_RANDOM = 0x00000003 +LUNA_ENTRY_CHALLENGE_RESPONSE = 0x00000004 LUNA_ENTRY_REMOTE_AUTHENTICATION = 0x00000005 LUNA_ENTRY_DATA_AREA_MASKED = 0x00000006 -LUNA_ENTRY_NONE = 0x000000FF # to indicate that nothing yet set. +LUNA_ENTRY_NONE = 0x000000FF LUNA_PED_ID_SCP = 0x0000 LUNA_PED_ID_MAX = 0xFFFE LUNA_MAX_PIN_LEN = 256 @@ -586,31 +576,31 @@ HA_CMD_ANSWER_MOFN_CHALLENGE = 0x12 HA_CMD_MOFN_ACTIVATE = 0x13 LUNA_MASKING_KEY_PID = 24 -LUNA_MAC_PID = 43 # Manufacturer Authentication Certificate -LUNA_DAC_FIPS2_MEETS_PID = 44 # Device Authentication Certificate, FIPS2, "meets requirements" -LUNA_DAC_FIPS2_EVAL_PID = 45 # Device Authentication Certificate, FIPS2, "evaluated to" -LUNA_DAC_FIPS3_MEETS_PID = 46 # Device Authentication Certificate, FIPS3, "meets requirements" -LUNA_DAC_FIPS3_EVAL_PID = 47 # Device Authentication Certificate, FIPS3, "evaluated to" -LUNA_CUST_MAC_PID = 48 # Customer Manufacturer Authentication Certificate -LUNA_CUST_DAC_FIPS2_MEETS_PID = 49 # Customer Device Authentication Certificate, FIPS2, "meets requirements" -LUNA_CUST_DAC_FIPS2_EVAL_PID = 50 # Customer Device Authentication Certificate, FIPS2, "evaluated to" -LUNA_CUST_DAC_FIPS3_MEETS_PID = 51 # Customer Device Authentication Certificate, FIPS3, "meets requirements" -LUNA_CUST_DAC_FIPS3_EVAL_PID = 52 # Customer Device Authentication Certificate, FIPS3, "evaluated to" -LUNA_SSK_PID = 54 # Secure Signing Key -LUNA_LEGACY_ECC_MIC_PID = 60 # Legacy ECC Manufacturer Authentication Certificate -LUNA_LEGACY_ECC_HOK_PID = 61 # Legacy ECC Hardware Origin Key -LUNA_LEGACY_ECC_HOC_PID = 62 # Legacy ECC Hardware Origin Certificate -LUNA_LEGACY_ECC_DAK_PID = 63 # Legacy ECC Device Authentication Key -LUNA_LEGACY_ECC_DAC_PID = 64 # Legacy ECC Device Authentication Certificate -LUNA_ECC_HOK_PID = 87 # ECC Hierarchy Hardware Origin Key -LUNA_ECC_HOC_PID = 88 # ECC Hierarchy Hardware Origin Certificate -LUNA_ECC_TUK_PID = 89 # TUK for ECC Hierarchy - version 0 -LUNA_ECC_TWK_PID = 90 # TWK for ECC Hierarchy - version 0 -LUNA_ECC_TWC_PID = 91 # TWC for ECC Hierarchy - version 0 -LUNA_ECC_ROOT_PID = 92 # ECC Hierarchy Root Certificate -LUNA_ECC_MIC_PID = 93 # ECC Hierarchy Manufacturer Authentication Certificate -LUNA_ECC_EMVC_PID = 94 # ECC Hierarchy Emergency Message Verification Certificate -LUNA_U3KEY_PID = 95 # U3 Update Key used in ECC Hierarchy +LUNA_MAC_PID = 43 +LUNA_DAC_FIPS2_MEETS_PID = 44 +LUNA_DAC_FIPS2_EVAL_PID = 45 +LUNA_DAC_FIPS3_MEETS_PID = 46 +LUNA_DAC_FIPS3_EVAL_PID = 47 +LUNA_CUST_MAC_PID = 48 +LUNA_CUST_DAC_FIPS2_MEETS_PID = 49 +LUNA_CUST_DAC_FIPS2_EVAL_PID = 50 +LUNA_CUST_DAC_FIPS3_MEETS_PID = 51 +LUNA_CUST_DAC_FIPS3_EVAL_PID = 52 +LUNA_SSK_PID = 54 +LUNA_LEGACY_ECC_MIC_PID = 60 +LUNA_LEGACY_ECC_HOK_PID = 61 +LUNA_LEGACY_ECC_HOC_PID = 62 +LUNA_LEGACY_ECC_DAK_PID = 63 +LUNA_LEGACY_ECC_DAC_PID = 64 +LUNA_ECC_HOK_PID = 87 +LUNA_ECC_HOC_PID = 88 +LUNA_ECC_TUK_PID = 89 +LUNA_ECC_TWK_PID = 90 +LUNA_ECC_TWC_PID = 91 +LUNA_ECC_ROOT_PID = 92 +LUNA_ECC_MIC_PID = 93 +LUNA_ECC_EMVC_PID = 94 +LUNA_U3KEY_PID = 95 CA_MASK_DES3_RC4 = 0x00000001 CA_MASK_SHA1_AES_RC4 = 0x00000002 LUNA_MAX_CHALLENGE_SIZE = 64 @@ -618,21 +608,21 @@ LUNA_CHALLENGE_CLASS_AUTHENTICATION = 0x00000000 LUNA_CHALLENGE_CLASS_SIM = 0x00000001 LUNA_CHALLENGE_TYPE_NULL = 0x00000000 -LUNA_CHALLENGE_TYPE_SECRET_HASH = 0x00000001 # Obsolete -- didn't satisfy NIST +LUNA_CHALLENGE_TYPE_SECRET_HASH = 0x00000001 LUNA_CHALLENGE_TYPE_ENCRYPTED_SECRET_HASH = 0x00000002 LUNA_CHALLENGE_FLAGS_CREATE_DEFAULT_CHALLENGE = (0x00000001) LUNA_CHALLENGE_TYPE_SO = LUNA_UTYPE_SO LUNA_CHALLENGE_TYPE_USER = LUNA_UTYPE_USER LUNA_CHALLENGE_TYPE_LIMITED_USER = LUNA_UTYPE_LIMITED_USER LUNA_CHALLENGE_TYPE_AUDIT = LUNA_UTYPE_AUDIT -LUNA_SIM_NO_AUTHORIZATION = 0 # no authorization needed -LUNA_SIM_PASSWORD = 1 # plain-text passwords -LUNA_SIM_CHALLENGE = 2 # challenge secrets emitted through the secure port -LUNA_SIM_SECURE_PORT = 3 # PED keys -LUNA_SIM_PORTABLE_NO_AUTHORIZATION = 4 # no authorization needed -LUNA_SIM_PORTABLE_PASSWORD = 5 # plain-text passwords -LUNA_SIM_PORTABLE_CHALLENGE = 6 # challenge secrets emitted through the secure port -LUNA_SIM_PORTABLE_SECURE_PORT = 7 # PED keys +LUNA_SIM_NO_AUTHORIZATION = 0 +LUNA_SIM_PASSWORD = 1 +LUNA_SIM_CHALLENGE = 2 +LUNA_SIM_SECURE_PORT = 3 +LUNA_SIM_PORTABLE_NO_AUTHORIZATION = 4 +LUNA_SIM_PORTABLE_PASSWORD = 5 +LUNA_SIM_PORTABLE_CHALLENGE = 6 +LUNA_SIM_PORTABLE_SECURE_PORT = 7 MAX_SIM_OBJECTS = 2048 CONTAINER_CONFIG_PRIVATE_KEY_CLONING = 0 CONTAINER_CONFIG_PRIVATE_KEY_WRAPPING = 1 @@ -652,15 +642,15 @@ CONTAINER_CONFIG_NO_RSA_BLINDING = 16 CONTAINER_CONFIG_NONLOCAL_SIGNING_KEYS = 17 CONTAINER_CONFIG_RAW_RSA_OPERATIONS = 18 -CONTAINER_CONFIG_KEY_STORAGE_SPACE = 19 # Obsolete as of f/w 6.0.2 +CONTAINER_CONFIG_KEY_STORAGE_SPACE = 19 CONTAINER_CONFIG_MAX_FAILED_USER_LOGINS_ALLOWED = 20 CONTAINER_CONFIG_HIGH_AVAILABILITY = 21 CONTAINER_CONFIG_ACTIVATION = 22 CONTAINER_CONFIG_AUTO_ACTIVATION = 23 -CONTAINER_CONFIG_INDIRECT_LOGIN = 24 # Obsolete as of f/w 5.0 +CONTAINER_CONFIG_INDIRECT_LOGIN = 24 CONTAINER_CONFIG_MINIMUM_PIN_LENGTH = 25 CONTAINER_CONFIG_MAXIMUM_PIN_LENGTH = 26 -CONTAINER_CONFIG_OBSOLETE_5 = 27 # CONTAINER_CONFIG_RA_TYPE_WRAPPING +CONTAINER_CONFIG_OBSOLETE_5 = 27 CONTAINER_CONFIG_KEY_MANAGEMENT_FUNCTIONS = 28 CONTAINER_CONFIG_RSA_SIGNATURE_CONFIRMATION = 29 CONTAINER_CONFIG_REMOTE_AUTHENTICATION = 30 @@ -676,17 +666,17 @@ HSM_CONFIG_ENABLE_PIN_AUTHENTICATION = 0 HSM_CONFIG_ENABLE_PED_AUTHENTICATION = 1 HSM_CONFIG_PERFORMANCE_LEVEL = 2 -HSM_CONFIG_M_OF_N = 3 # Obsolete +HSM_CONFIG_M_OF_N = 3 HSM_CONFIG_DOMESTIC = 4 HSM_CONFIG_CAV_USED = 5 HSM_CONFIG_MASKING = 6 HSM_CONFIG_CLONING = 7 -HSM_CONFIG_SPECIAL_CLONING = 8 # Obsolete +HSM_CONFIG_SPECIAL_CLONING = 8 HSM_CONFIG_NONBACKUP_TOKEN = 9 HSM_CONFIG_OBSOLETE_2 = 10 HSM_CONFIG_ECC = 11 HSM_CONFIG_NONFIPS_ALGORITHMS = 12 -HSM_CONFIG_MOFN_AUTO_ACTIVATION = 13 # Obsolete +HSM_CONFIG_MOFN_AUTO_ACTIVATION = 13 HSM_CONFIG_OBSOLETE_3 = 14 HSM_CONFIG_SO_CAN_RESET_PIN = 15 HSM_CONFIG_NETWORK_REPLICATION = 16 @@ -776,7 +766,7 @@ LUNA_INSERTION_UNINITIALIZED = 0x10 LUNA_PARTITION_VERSION = 1 LUNA_POLICY_TEMPLATE = 0x20 -MAX_CAPABILITY_SET_SIZE = 16 # UAV_MAX_CAPABILITY_SET_SIZE +MAX_CAPABILITY_SET_SIZE = 16 LUNA_ENABLE_MEMBER_CONTAINER = 0x01 LUNA_DISABLE_MEMBER_CONTAINER = 0x02 LUNA_UNAUTH_CMD_CONTEXT_CREATE = 0x01 @@ -817,10 +807,10 @@ LUNA_PRF_KDF_AES_CMAC = 0x00000002 LUNA_PRF_KDF_ARIA_CMAC = 0x00000003 LUNA_PRF_KDF_SEED_CMAC = 0x00000004 -LUNA_PRF_KDF_ENCODING_SCHEME_1 = 0x00000000 # use to get previous results because of above bug -LUNA_PRF_KDF_ENCODING_SCHEME_2 = 0x00000001 # use to get previous results because of above bug -LUNA_PRF_KDF_ENCODING_SCHEME_3 = 0x00000002 # use in FW 7 and later, equivalent to scheme 1 -LUNA_PRF_KDF_ENCODING_SCHEME_4 = 0x00000003 # use in FW 7 and later, equivalent to scheme 2 +LUNA_PRF_KDF_ENCODING_SCHEME_1 = 0x00000000 +LUNA_PRF_KDF_ENCODING_SCHEME_2 = 0x00000001 +LUNA_PRF_KDF_ENCODING_SCHEME_3 = 0x00000002 +LUNA_PRF_KDF_ENCODING_SCHEME_4 = 0x00000003 CB_CMD_TEST = 0x00000000 CB_CMD_TEST_UPLOAD = 0x00000001 CB_CMD_TEST_DOWNLOAD = 0x00000002 @@ -875,7 +865,7 @@ LUNA_MODIFY_USAGE_COUNT_TYPE_INCREMENT = 0x00000001 LUNA_MODIFY_USAGE_COUNT_TYPE_SET = 0x00000002 LUNA_CKDHP_ECDH1_COFACTOR = 0x00000001 -LUNA_CKDHP_MODIFIED = 0x00000002 # Not implemented */ +LUNA_CKDHP_MODIFIED = 0x00000002 LUNA_CKDHP_ECDH1 = 0x00000003 LUNA_CKES_XOR = 0x00000001 LUNA_CKES_DES3_CBC_PAD = 0x00000002 @@ -894,10 +884,10 @@ LUNA_CKMS_SHA512 = 0x0000000a LUNA_CKMS_HMAC_RIPEMD160 = 0x0000000b LUNA_CKMS_RIPEMD160 = 0x0000000c -LUNA_DUKPT_PARAM_LEN = 10 # KSN parameter is 10 bytes */ +LUNA_DUKPT_PARAM_LEN = 10 LUNA_LOG_WRITE = 0x000000c1 -LUNA_LOG_POLL_HOST = 0x000000c2 # This one is both internal and external, between the host & f/w, so it's defined above -LUNA_LOG_SET_CONFIG = 0x000000c5 # This one is both internal and external, between the host & f/w, so it's defined above +LUNA_LOG_POLL_HOST = 0x000000c2 +LUNA_LOG_SET_CONFIG = 0x000000c5 LUNA_LOG_RESYNC = 0x000000c8 LUNA_STATS_NONE = 0 LUNA_STATS_BOOT_TIME = 1 @@ -906,7 +896,6 @@ LUNA_STATS_ICD_COMMANDS_COUNT = 4 LUNA_STATS_UNKNOWN = 0xffffffff PED_PASSWORD_LENGTH = 8 -'''/var/jenkins/workspace/luna-k7/crypto/tools/ekmtest/token.h''' MAX_BUF_SIZE = 32000 MAX_SLOT_COUNT = 20 MAX_SESSION_COUNT = 20 @@ -915,9 +904,8 @@ BENCHMARK = 1 MAX_RSA_KEY_NBITS = 8192 LAST_MENU_ITEM = 204 -MAX_FILE_NAME_SIZE = 512 # bytes */ -XOR_KDF_MAX_SHARED_DATALEN = 512 # max. amount of shared data allowed -'''/var/jenkins/workspace/luna-k7/crypto/interfaces/Include/RSA/pkcs11t.h''' +MAX_FILE_NAME_SIZE = 512 +XOR_KDF_MAX_SHARED_DATALEN = 512 CRYPTOKI_VERSION_MAJOR = 2 CRYPTOKI_VERSION_MINOR = 20 CRYPTOKI_VERSION_AMENDMENT = 3 @@ -929,13 +917,13 @@ CK_INVALID_HANDLE = 0 CKN_SURRENDER = 0 CKN_OTP_CHANGED = 1 -CKF_TOKEN_PRESENT = 0x00000001 # a token is there */ -CKF_REMOVABLE_DEVICE = 0x00000002 # removable devices*/ -CKF_HW_SLOT = 0x00000004 # hardware slot */ -CKF_RNG = 0x00000001 # has random # -CKF_WRITE_PROTECTED = 0x00000002 # token is -CKF_LOGIN_REQUIRED = 0x00000004 # user must -CKF_USER_PIN_INITIALIZED = 0x00000008 # normal user's +CKF_TOKEN_PRESENT = 0x00000001 +CKF_REMOVABLE_DEVICE = 0x00000002 +CKF_HW_SLOT = 0x00000004 +CKF_RNG = 0x00000001 # has random +CKF_WRITE_PROTECTED = 0x00000002 +CKF_LOGIN_REQUIRED = 0x00000004 +CKF_USER_PIN_INITIALIZED = 0x00000008 CKF_RESTORE_KEY_NOT_NEEDED = 0x00000020 CKF_CLOCK_ON_TOKEN = 0x00000040 CKF_PROTECTED_AUTHENTICATION_PATH = 0x00000100 @@ -958,8 +946,8 @@ CKS_RW_PUBLIC_SESSION = 2 CKS_RW_USER_FUNCTIONS = 3 CKS_RW_SO_FUNCTIONS = 4 -CKF_RW_SESSION = 0x00000002 # session is r/w */ -CKF_SERIAL_SESSION = 0x00000004 # no parallel */ +CKF_RW_SESSION = 0x00000002 +CKF_SERIAL_SESSION = 0x00000004 CKO_DATA = 0x00000000 CKO_CERTIFICATE = 0x00000001 CKO_PUBLIC_KEY = 0x00000002 @@ -1382,7 +1370,7 @@ CKM_AES_KEY_WRAP = 0x00002109 CKM_AES_KEY_WRAP_PAD = 0x0000210A CKM_VENDOR_DEFINED = 0x80000000 -CKF_HW = 0x00000001 # performed by HW */ +CKF_HW = 0x00000001 CKF_ENCRYPT = 0x00000100 CKF_DECRYPT = 0x00000200 CKF_DIGEST = 0x00000400 @@ -1401,7 +1389,7 @@ CKF_EC_NAMEDCURVE = 0x00800000 CKF_EC_UNCOMPRESS = 0x01000000 CKF_EC_COMPRESS = 0x02000000 -CKF_EXTENSION = 0x80000000 # FALSE for this version */ +CKF_EXTENSION = 0x80000000 CKR_ARGUMENTS_BAD = 0x00000007 CKR_ATTRIBUTE_READ_ONLY = 0x00000010 CKR_ATTRIBUTE_SENSITIVE = 0x00000011 @@ -1519,9 +1507,8 @@ CKF_EXCLUDE_CHALLENGE = 0x00000008 CKF_EXCLUDE_PIN = 0x00000010 CKF_USER_FRIENDLY_OTP = 0x00000020 -'''/var/jenkins/workspace/luna-k7/crypto/CoreLibrary/includes/cryptoki_v2.h''' NULL_PTR = 0 -C_LIBRARY_VERSION = 0x510 # v5.10 decimal */ +C_LIBRARY_VERSION = 0x510 CK_TOKEN_SERIAL_NUMBER_SIZE = 16 CKU_CRYPTO_OFFICER = CKU_USER CKU_LIMITED_USER = 0x80000001 @@ -1578,8 +1565,8 @@ CKD_SES_ALT_AUTH_CTR = 0x00000004 CKD_SHA1_KDF_CONCATENATE_X9_42 = CKD_SHA1_KDF_CONCATENATE CKD_SHA1_KDF_CONCATENATE_NIST = 0x80000001 -CKD_SHA1_KDF_ASN1_X9_42 = CKD_SHA1_KDF_ASN1 # not supported -CKD_SHA1_KDF_ASN1_NIST = 0x80000002 # not supported +CKD_SHA1_KDF_ASN1_X9_42 = CKD_SHA1_KDF_ASN1 +CKD_SHA1_KDF_ASN1_NIST = 0x80000002 CKK_KCDSA = CKK_VENDOR_DEFINED + 0x10 CKK_SEED = CKK_VENDOR_DEFINED + 0x11 CKA_CCM_PRIVATE = (CKA_VENDOR_DEFINED | 0x0001) @@ -1644,37 +1631,37 @@ CKH_BATTERY = (CKH_VENDOR_DEFINED | 0x00000002) CKH_FAN = (CKH_VENDOR_DEFINED | 0x00000003) CKM_VENDOR_DEFINED_OLD_XXX = 0x00008000 -CKM_CAST_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 0 # Entrust added capabilities -CKM_CAST_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 1 # Entrust added capabilities -CKM_CAST_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 2 # Entrust added capabilities -CKM_CAST_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 3 # Entrust added capabilities -CKM_CAST3_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 4 # Entrust added capabilities -CKM_CAST3_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 5 # Entrust added capabilities -CKM_CAST3_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 6 # Entrust added capabilities -CKM_CAST3_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 7 # Entrust added capabilities -CKM_PBE_MD2_DES_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 8 # Password based encryption -CKM_PBE_MD5_DES_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 9 # Password based encryption -CKM_PBE_MD5_CAST_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 10 # Password based encryption -CKM_PBE_MD5_CAST3_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 11 # Password based encryption -CKM_CONCATENATE_BASE_AND_KEY_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 12 # SPKM & SLL added capabilities -CKM_CONCATENATE_KEY_AND_BASE_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 13 # SPKM & SLL added capabilities -CKM_CONCATENATE_BASE_AND_DATA_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 14 # SPKM & SLL added capabilities -CKM_CONCATENATE_DATA_AND_BASE_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 15 # SPKM & SLL added capabilities -CKM_XOR_BASE_AND_DATA_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 16 # SPKM & SLL added capabilities -CKM_EXTRACT_KEY_FROM_KEY_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 17 # SPKM & SLL added capabilities -CKM_MD5_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 18 # SPKM & SLL added capabilities -CKM_MD2_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 19 # SPKM & SLL added capabilities -CKM_SHA1_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 20 # SPKM & SLL added capabilities -CKM_GENERIC_SECRET_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 21 # Generation of secret keys -CKM_CAST5_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 22 # Entrust added capabilities -CKM_CAST5_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 23 # Entrust added capabilities -CKM_CAST5_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 24 # Entrust added capabilities -CKM_CAST5_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 25 # Entrust added capabilities -CKM_PBE_SHA1_CAST5_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 26 # Entrust added capabilities -CKM_KEY_TRANSLATION = CKM_VENDOR_DEFINED_OLD_XXX + 27 # Entrust added capabilities +CKM_CAST_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 0 +CKM_CAST_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 1 +CKM_CAST_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 2 +CKM_CAST_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 3 +CKM_CAST3_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 4 +CKM_CAST3_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 5 +CKM_CAST3_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 6 +CKM_CAST3_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 7 +CKM_PBE_MD2_DES_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 8 +CKM_PBE_MD5_DES_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 9 +CKM_PBE_MD5_CAST_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 10 +CKM_PBE_MD5_CAST3_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 11 +CKM_CONCATENATE_BASE_AND_KEY_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 12 +CKM_CONCATENATE_KEY_AND_BASE_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 13 +CKM_CONCATENATE_BASE_AND_DATA_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 14 +CKM_CONCATENATE_DATA_AND_BASE_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 15 +CKM_XOR_BASE_AND_DATA_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 16 +CKM_EXTRACT_KEY_FROM_KEY_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 17 +CKM_MD5_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 18 +CKM_MD2_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 19 +CKM_SHA1_KEY_DERIVATION_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 20 +CKM_GENERIC_SECRET_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 21 +CKM_CAST5_KEY_GEN_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 22 +CKM_CAST5_ECB_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 23 +CKM_CAST5_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 24 +CKM_CAST5_MAC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 25 +CKM_PBE_SHA1_CAST5_CBC_OLD_XXX = CKM_VENDOR_DEFINED_OLD_XXX + 26 +CKM_KEY_TRANSLATION = CKM_VENDOR_DEFINED_OLD_XXX + 27 CKM_XOR_BASE_AND_KEY = CKM_VENDOR_DEFINED + 27 -CKM_2DES_KEY_DERIVATION = CKM_VENDOR_DEFINED_OLD_XXX + 28 # Custom Gemplus Capabilities -CKM_INDIRECT_LOGIN_REENCRYPT = CKM_VENDOR_DEFINED_OLD_XXX + 29 # Used for indirect login +CKM_2DES_KEY_DERIVATION = CKM_VENDOR_DEFINED_OLD_XXX + 28 +CKM_INDIRECT_LOGIN_REENCRYPT = CKM_VENDOR_DEFINED_OLD_XXX + 29 CKM_PBE_SHA1_DES3_EDE_CBC_OLD = CKM_VENDOR_DEFINED_OLD_XXX + 30 CKM_PBE_SHA1_DES2_EDE_CBC_OLD = CKM_VENDOR_DEFINED_OLD_XXX + 31 CKM_HAS160 = (CKM_VENDOR_DEFINED + 0x100) @@ -1736,7 +1723,7 @@ CKM_SHA384_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13c) CKM_SHA512_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13d) CKM_RSA_X9_31_NON_FIPS = (CKM_VENDOR_DEFINED + 0x13e) -CKM_DSA_SHA224 = (CKM_VENDOR_DEFINED + 0x140) # DH -moved here to keep ECDSA SHA 2 same as FW4 +CKM_DSA_SHA224 = (CKM_VENDOR_DEFINED + 0x140) CKM_DSA_SHA256 = (CKM_VENDOR_DEFINED + 0x141) CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN = (CKM_VENDOR_DEFINED + 0x142) CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN = (CKM_VENDOR_DEFINED + 0x143) @@ -1777,7 +1764,7 @@ CKM_SM3_KEY_DERIVATION = (CKM_VENDOR_DEFINED + 0xB04) CKDHP_STANDARD = 0x00000001 CKDHP_ECDH1_COFACTOR = 0x00000001 -CKDHP_MODIFIED = 0x00000002 # Not implemented */ +CKDHP_MODIFIED = 0x00000002 CKDHP_ECDH1 = 0x00000003 CKES_XOR = 0x00000001 CKES_DES3_CBC_PAD = 0x00000002 @@ -1928,7 +1915,7 @@ CKO_ADAPTER = (CKO_VENDOR_DEFINED + 0x020A) CKO_SLOT = (CKO_VENDOR_DEFINED + 0x020B) CKO_FM = (CKO_VENDOR_DEFINED + 0x020C) -CKS_RO_SO_FUNCTIONS = 5 # still in PKCS #11 space */ +CKS_RO_SO_FUNCTIONS = 5 # still in PKCS CKS_RO_VENDOR_DEFINED = 0x80000000 CKS_RW_VENDOR_DEFINED = 0x90000000 CKS_RW_AUDIT_FUNCTIONS = (CKS_RW_VENDOR_DEFINED + 0x001) @@ -1979,14 +1966,14 @@ CKHSC_CERT_TYPE_ECC_MIC = 0x0000000D CKHSC_CERT_TYPE_ECC_HOC = 0x0000000E CKHSC_CERT_TYPE_ECC_TWC = 0x0000000F -CKA_SIM_NO_AUTHORIZATION = 0 # no authorization needed -CKA_SIM_PASSWORD = 1 # plain-text passwords -CKA_SIM_CHALLENGE = 2 # challenge secrets emitted through the secure port -CKA_SIM_SECURE_PORT = 3 # PED keys -CKA_SIM_PORTABLE_NO_AUTHORIZATION = 4 # no authorization needed, portable -CKA_SIM_PORTABLE_PASSWORD = 5 # plain-text passwords, portable -CKA_SIM_PORTABLE_CHALLENGE = 6 # challenge secrets emitted through the secure port, portable -CKA_SIM_PORTABLE_SECURE_PORT = 7 # PED keys, portable +CKA_SIM_NO_AUTHORIZATION = 0 +CKA_SIM_PASSWORD = 1 +CKA_SIM_CHALLENGE = 2 +CKA_SIM_SECURE_PORT = 3 +CKA_SIM_PORTABLE_NO_AUTHORIZATION = 4 +CKA_SIM_PORTABLE_PASSWORD = 5 +CKA_SIM_PORTABLE_CHALLENGE = 6 +CKA_SIM_PORTABLE_SECURE_PORT = 7 CK_NULL_ELEMENT = (-1) CK_CRYPTOKI_ELEMENT = 0x00000000 CK_PARAM_ELEMENT = 0x00000001 @@ -2007,7 +1994,7 @@ CK_GT_TAMPER_INFO = 0x00000054 CK_GT_LIVE_TAMPER_INFO = 0x00000057 CK_MAX_CLUSTER_MEMBERS = 8 -AKEP2_XDH_SIZE = 128 # size of LKM public key +AKEP2_XDH_SIZE = 128 AKEP2_MAX_DIGEST_SIZE = 32 AKEP2_NID_SIZE = 20 CK_PED_ID_LOCAL = 0x0000 diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 5fc78ba..5659453 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -4,12 +4,12 @@ from ctypes import byref -from cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, C_GenerateKey, \ +from .cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, C_GenerateKey, \ C_GenerateKeyPair, \ C_CopyObject -from default_templates import CKM_DES_KEY_GEN_TEMP, \ +from .default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP -from defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN +from .defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN from .attributes import Attributes from .cryptoki import C_DeriveKey from .mechanism import NullMech diff --git a/pycryptoki/logging_filters.py b/pycryptoki/logging_filters.py deleted file mode 100755 index 8a3b6f4..0000000 --- a/pycryptoki/logging_filters.py +++ /dev/null @@ -1,30 +0,0 @@ -import logging -import os - - -class OnlyTestsFilter(logging.Filter): - """ """ - - def filter(self, record): - """ - - :param record: - - """ - - file_path = os.path.realpath(__file__) - dir_path = os.path.dirname(file_path) - dir_members = os.listdir(dir_path) - files = [] - for filename in dir_members: - split_file = filename.split(".") - if len(split_file) > 1 and split_file[1] == 'py': - files.append(os.path.join(split_file[0])) - - should_show = True - - for python_file in files: - if python_file in record.getMessage(): - should_show = False - - return should_show diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 4a092d5..d33b641 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -12,15 +12,14 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from .mechanism import Mechanism -from .mechanism import NullMech from .attributes import Attributes, to_char_array from .common_utils import refresh_c_arrays, AutoCArray from .cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey from .defines import CKR_OK -from .key_generator import _get_mechanism +from .mechanism import Mechanism +from .mechanism import NullMech from .sign_verify import do_multipart_sign_or_digest from .test_functions import make_error_handle_function diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index 7d27b6c..c3f1e26 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -196,16 +196,3 @@ def cleanup(self): """ """ # nothing to do here pass - - -def deserialize_dict(dictionary): - """Helper function to convert a dictionary with to - for xmlrpc - - :param dictionary: - - """ - deserialized_dictionary = {} - for key, value in dictionary.iteritems(): - deserialized_dictionary[int(key)] = value - return deserialized_dictionary diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 9397552..2008fd0 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -5,9 +5,9 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from cryptoki import CK_ULONG, \ +from .cryptoki import CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign -from defines import CKR_OK +from .defines import CKR_OK from .attributes import to_char_array from .common_utils import refresh_c_arrays, AutoCArray from .cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 8a7fc99..41dbd7c 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -1,13 +1,16 @@ +""" +Functions used for testing, or verifying return values. +""" + import inspect import logging from ctypes import byref from functools import wraps -from defines import CKR_OK -from return_values import ret_vals_dictionary -from .attributes import Attributes from .cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize from .defines import CKR_OBJECT_HANDLE_INVALID +from .defines import CKR_OK +from .return_values import ret_vals_dictionary LOG = logging.getLogger(__name__) diff --git a/pycryptoki/tests/functional/test_sign_verify.py b/pycryptoki/tests/functional/test_sign_verify.py index 6a358d3..fe4aead 100755 --- a/pycryptoki/tests/functional/test_sign_verify.py +++ b/pycryptoki/tests/functional/test_sign_verify.py @@ -1,5 +1,4 @@ import logging -import os import pytest @@ -26,10 +25,10 @@ def setup_teardown(self, auth_session): self.admin_slot = hsm_config["test_slot"] @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ - (CKM_RSA_PKCS_KEY_PAIR_GEN, - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - CKM_RSA_PKCS), + pytest.mark.xfail(reason="Data len failure")((CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, + CKM_RSA_PKCS)), (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, diff --git a/setup.py b/setup.py index 41d6efd..50b09b0 100755 --- a/setup.py +++ b/setup.py @@ -13,7 +13,6 @@ url='https://github.com/gemalto/pycryptoki', version='1.0', packages=['pycryptoki', - 'pycryptoki.tests', 'pycryptoki.daemon', 'pycryptoki.utils'], scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'] From 4b66524f67a031de5eb63016b51cb589b5b8cfe8 Mon Sep 17 00:00:00 2001 From: ksafford Date: Thu, 23 Jun 2016 15:01:25 -0400 Subject: [PATCH 051/109] LA-1626 Change OAEP to default to empty string Change RSA PKCS OAEP's mechanism class to not have a required sourceData, and to default to empty string. This will result in a null pointer being used, which will cause cryptoki to use the default empty string for this parameter. Depends on Change 7779, ID I634e0a6fef77ac951c8da18fcb599636b062360d for that change's fixes (mainly setup.py's packages). Change-Id: I679dd0e00f913d96268eab934ccab3ed2cec880a --- pycryptoki/mechanism.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 6c48998..22444ba 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -233,7 +233,7 @@ def to_c_mech(self): class RSAPKCSOAEPMechanism(Mechanism): - REQUIRED_PARAMS = ['hashAlg', 'mgf', 'sourceData'] + REQUIRED_PARAMS = ['hashAlg', 'mgf'] def to_c_mech(self): """ @@ -250,7 +250,7 @@ def to_c_mech(self): # /group__SEC__12__1__7__PKCS____1__RSA__OAEP__MECHANISM__PARAMETERS.html # there is only one encoding parameter source. oaep_params.source = CK_ULONG(CKZ_DATA_SPECIFIED) - data, data_len = to_byte_array(self.params['sourceData']) + data, data_len = to_byte_array(self.params.get('sourceData', '')) oaep_params.pSourceData = data oaep_params.ulSourceDataLen = data_len From 403160c12bf02af02d3ca5b057e94156e1d48668 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 21 Jun 2016 09:28:18 -0400 Subject: [PATCH 052/109] LA-1864 Fix setup.py, fixing inspection warnings Added some python3 flexibility Convert all string to byte strings by default, for python3 intercompatibility. Added some imports from future to support python 3. Moved all tests up a directory, and removed __init__.py - allows for python setup.py test --addopts=unittest - properly configures coverage reports Change-Id: I634e0a6fef77ac951c8da18fcb599636b062360d --- __init__.py | 3 - pycryptoki/.coveragerc | 3 + pycryptoki/__init__.py | 3 + pycryptoki/attributes.py | 54 +- pycryptoki/audit_handling.py | 2 +- pycryptoki/backup.py | 4 +- pycryptoki/common_utils.py | 349 ++++---- pycryptoki/cryptoki.py | 4 +- pycryptoki/daemon/rpyc_pycryptoki.py | 3 +- pycryptoki/default_templates.py | 237 +++--- pycryptoki/defaults.py | 26 +- pycryptoki/defines.py | 4 +- pycryptoki/dictionary_handling.py | 14 - pycryptoki/encryption.py | 30 +- pycryptoki/hsm_management.py | 780 +++++++++--------- pycryptoki/luna_threading.py | 2 +- pycryptoki/mechanism.py | 6 +- pycryptoki/misc.py | 15 +- pycryptoki/object_attr_lookup.py | 2 +- pycryptoki/partition_management.py | 15 +- pycryptoki/pycryptoki_client.py | 10 +- pycryptoki/return_values.py | 2 +- pycryptoki/session_management.py | 10 +- pycryptoki/sign_verify.py | 7 +- pycryptoki/test_functions.py | 9 +- pycryptoki/tests/stress/__init__.py | 0 pycryptoki/tests/stress/conftest.py | 32 - pycryptoki/tests/stress/setup.cfg | 3 - pycryptoki/tests/stress/test_multi_reset.py | 354 -------- pycryptoki/tests/stress/vreset_thread.py | 61 -- pycryptoki/tests/unittests/__init__.py | 0 pycryptoki/token_management.py | 2 +- requirements.txt | 5 + setup.cfg | 2 + setup.py | 15 +- .../tests => tests}/functional/__init__.py | 0 .../tests => tests}/functional/conftest.py | 51 +- .../functional/test_cka_start_and_end.py | 65 +- .../functional/test_digest_data.py | 13 +- .../functional/test_encrypt_decrypt.py | 17 +- .../functional/test_get_token_info.py | 9 +- .../functional/test_hsm_management.py | 294 +++---- .../functional/test_key_management.py | 14 +- .../functional/test_key_usage.py | 6 +- .../tests => tests}/functional/test_keys.py | 18 +- .../functional/test_object_create.py | 11 +- .../functional/test_sign_verify.py | 14 +- .../functional/test_supporting_operations.py | 9 +- .../functional/test_usage_limit_and_count.py | 35 +- .../functional/test_wrap_unwrap.py | 15 +- .../tests => tests/unittests}/__init__.py | 0 .../unittests/test_attributes.py | 9 +- .../unittests/test_mechanisms.py | 62 +- 53 files changed, 1145 insertions(+), 1565 deletions(-) create mode 100644 pycryptoki/.coveragerc delete mode 100755 pycryptoki/dictionary_handling.py delete mode 100755 pycryptoki/tests/stress/__init__.py delete mode 100755 pycryptoki/tests/stress/conftest.py delete mode 100755 pycryptoki/tests/stress/setup.cfg delete mode 100755 pycryptoki/tests/stress/test_multi_reset.py delete mode 100755 pycryptoki/tests/stress/vreset_thread.py delete mode 100644 pycryptoki/tests/unittests/__init__.py create mode 100644 requirements.txt create mode 100644 setup.cfg rename {pycryptoki/tests => tests}/functional/__init__.py (100%) rename {pycryptoki/tests => tests}/functional/conftest.py (76%) rename {pycryptoki/tests => tests}/functional/test_cka_start_and_end.py (86%) rename {pycryptoki/tests => tests}/functional/test_digest_data.py (77%) rename {pycryptoki/tests => tests}/functional/test_encrypt_decrypt.py (82%) rename {pycryptoki/tests => tests}/functional/test_get_token_info.py (90%) rename {pycryptoki/tests => tests}/functional/test_hsm_management.py (87%) rename {pycryptoki/tests => tests}/functional/test_key_management.py (84%) rename {pycryptoki/tests => tests}/functional/test_key_usage.py (82%) rename {pycryptoki/tests => tests}/functional/test_keys.py (96%) rename {pycryptoki/tests => tests}/functional/test_object_create.py (82%) rename {pycryptoki/tests => tests}/functional/test_sign_verify.py (91%) rename {pycryptoki/tests => tests}/functional/test_supporting_operations.py (90%) rename {pycryptoki/tests => tests}/functional/test_usage_limit_and_count.py (90%) rename {pycryptoki/tests => tests}/functional/test_wrap_unwrap.py (88%) rename {pycryptoki/tests => tests/unittests}/__init__.py (100%) mode change 100755 => 100644 rename {pycryptoki/tests => tests}/unittests/test_attributes.py (67%) rename {pycryptoki/tests => tests}/unittests/test_mechanisms.py (78%) diff --git a/__init__.py b/__init__.py index 967b94b..e69de29 100755 --- a/__init__.py +++ b/__init__.py @@ -1,3 +0,0 @@ -import logging - -logging.getLogger(__name__).addHandler(logging.NullHandler()) diff --git a/pycryptoki/.coveragerc b/pycryptoki/.coveragerc new file mode 100644 index 0000000..7da4880 --- /dev/null +++ b/pycryptoki/.coveragerc @@ -0,0 +1,3 @@ +[run] +omit = tests/* +branch = True diff --git a/pycryptoki/__init__.py b/pycryptoki/__init__.py index e69de29..967b94b 100755 --- a/pycryptoki/__init__.py +++ b/pycryptoki/__init__.py @@ -0,0 +1,3 @@ +import logging + +logging.getLogger(__name__).addHandler(logging.NullHandler()) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 9575db3..fb47ebc 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -4,6 +4,7 @@ convert them into templates in C. """ import binascii +import collections import datetime import logging from collections import defaultdict @@ -11,9 +12,11 @@ c_ulong, pointer, POINTER, sizeof, c_char, string_at, c_ubyte from functools import wraps -from cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ +from .cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ CK_BYTE, CK_CHAR -from defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ +from .defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ + CKA_GENERIC_3 +from .defines import CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKA_CLASS, CKA_TOKEN, \ CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION, CKA_CERTIFICATE_TYPE, \ CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE, \ CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER, \ @@ -26,8 +29,7 @@ CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_OUID, CKA_UNWRAP_TEMPLATE, \ CKA_DERIVE_TEMPLATE, \ CKA_X9_31_GENERATED, CKA_VALUE -from .defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ - CKA_GENERIC_3 +from .test_functions import integer_types LOG = logging.getLogger(__name__) @@ -75,8 +77,8 @@ def to_long(val, reverse=False): size of long value) """ if reverse: - return long(cast(val.pValue, POINTER(c_ulong)).contents.value) - if not isinstance(val, (int, long)): + return int(cast(val.pValue, POINTER(c_ulong)).contents.value) + if not isinstance(val, integer_types): raise TypeError("Invalid conversion {} to CK_ULONG!".format(type(val))) long_val = CK_ULONG(val) return cast(pointer(long_val), c_void_p), CK_ULONG(sizeof(long_val)) @@ -123,10 +125,10 @@ def to_char_array(val, reverse=False): LOG.debug("Converted to : %s", ret_data) return ret_data - if not isinstance(val, (str, list)): + if not isinstance(val, (str, bytes, list)): raise TypeError("Invalid conversion {} to CK_CHAR*!".format(type(val))) - if isinstance(val, str): + if isinstance(val, (str, bytes)): string_val = create_string_buffer(val, len(val)) else: # TODO: Figure out what, if anything we want to do with a list. @@ -147,7 +149,7 @@ def to_ck_date(val, reverse=False): if reverse: return string_at(cast(val.pValue, POINTER(c_char)), val.usValueLen) - if isinstance(val, str): + if isinstance(val, (str, bytes)): if len(val) != 8: raise TypeError("Invalid date string passed! Should be of type YYYYMMDD") date_val = create_string_buffer(val, len(val)) @@ -186,13 +188,25 @@ def to_byte_array(val, reverse=False): LOG.debug("Final hex data: %s", fin) return fin - if isinstance(val, list): + if isinstance(val, (str, bytes)): + # Can be Hex string ('01e4') or a bytestring (ex '\x8p\xb26\x12'G\xa3T\x84\x17\x89') + try: + # Would prefer to use bytearray.fromhex(), but a few testcases use ' ' * 80 or the like, + # which is converted into a zero-length bytearray. + hex_array = [val[i:i + 2] for i in range(0, len(val), 2)] + byte_array = (CK_BYTE * len(val))(*[int(x, 16) for x in hex_array]) + except ValueError: + # Assume a byte array? + py_bytes = bytearray(val) + byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) + elif isinstance(val, collections.Iterable): py_bytes = bytearray(val) byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) - elif isinstance(val, (int, long)): + elif isinstance(val, integer_types): # Explicitly convert to a long. Python doesn't like X.bit_length() where X is an int # and not a variable assigned an int. - width = long(val).bit_length() + x = val + width = x.bit_length() width += 8 - ((width % 8) or 8) fmt = "{:0%sb}" % width @@ -200,18 +214,6 @@ def to_byte_array(val, reverse=False): n = 8 str_array = [str_val[i:i + n] for i in range(0, len(str_val), n)] byte_array = (CK_BYTE * len(str_array))(*[int(x, 2) for x in str_array]) - - elif isinstance(val, str): - # Can be Hex string ('01e4') or a bytestring (ex '\x8p\xb26\x12'G\xa3T\x84\x17\x89') - try: - # Would prefer to use bytearray.fromhex(), but a few testcases use ' ' * 80 or the like, - # which is converted into a zero-length bytearray. - hex_array = [val[i:i + 2] for i in range(0, len(val), 2)] - byte_array = (CK_BYTE * len(val))(*[int(x, 16) for x in hex_array]) - except ValueError: - # Assume a byte array? - py_bytes = bytearray(val) - byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) else: raise TypeError("Invalid conversion {} to byte array!".format(type(val))) @@ -370,9 +372,9 @@ def get_c_struct(self): :return: :class:`~pycryptoki.cryptoki.CK_ATTRIBUTE` array """ - ret_struct = (CK_ATTRIBUTE * len(self.keys()))() + ret_struct = (CK_ATTRIBUTE * len(list(self.keys())))() - for index, key in enumerate(self.iterkeys()): + for index, key in enumerate(self.keys()): value = self[key] if value is None: # Create an empty CK_ATTRIBUTE struct so it can be overwritten with length diff --git a/pycryptoki/audit_handling.py b/pycryptoki/audit_handling.py index e7ee3a0..70a8a17 100755 --- a/pycryptoki/audit_handling.py +++ b/pycryptoki/audit_handling.py @@ -4,7 +4,7 @@ import logging from ctypes import cast, c_ulong, byref -from cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR +from .cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR from .test_functions import make_error_handle_function logger = logging.getLogger(__name__) diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index 4b07b34..15e6b83 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -43,12 +43,12 @@ def ca_close_secure_token(h_session, h_ID): ca_close_secure_token_ex = make_error_handle_function(ca_close_secure_token) +# noinspection PyIncorrectDocstring def ca_extract(h_session, mech_type, mech_params): """ + :param mech_params: :param h_session: - :param py_mechanism_dict: - :param params_type_string: """ mech = Mechanism(mech_type, params=mech_params) diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index b8aa87e..bbfbbfb 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -1,174 +1,175 @@ -""" -Utilities for pycryptoki -""" -from _ctypes import pointer, POINTER -from ctypes import c_ulong, cast, create_string_buffer - -from .cryptoki import CK_CHAR -from .defines import CKR_OK - - -class CException(Exception): - """ - Raised from attempts at parsing ctypes! - """ - pass - - -class AutoCArray(object): - """ - An attempt to provide automatic resolution of C-style arrays. - - """ - - def __init__(self, data=None, ctype=c_ulong, size=None): - """ - Initialize the Array. - - If it's to be a target for Crypto operation output, you only need - to specify the ctype (defaults to ULONG) - - Otherwise, you'll want to specify data and the ctype. Data can be a list-type - object (this includes strings!). If it is a list, all objects in the list need to - be compatible with your specified ctype. - - Size *always* needs to be a ctype in (c_ulong, c_uint)! - - You can specify a size at initialization time, if you know what the size will be. - Otherwise, it will be set either by the crypto-op, defaulted to 0L, or set to the size - of the given array. - - :param data: Data array should be initialized with. Needs to be string/list. - :param ctype: Type of data the array should store (Default: CK_ULONG) - :param size: Size of the array. PKCS#11 calls will init this for us, but you can also - specify it manually. - """ - self._array = None - self._size = size - self.ctype = ctype - - # name was just for logging. - if data is not None: - # Parse out any given data. - if isinstance(data, basestring): - self._array = create_string_buffer(data) - self._size = c_ulong(len(data)) - self.ctype = CK_CHAR - elif isinstance(data, list): - self._array = (ctype * len(data))(*data) - self._size = c_ulong(len(data)) - else: - raise NotImplementedError("AutoCArray does not support given data type.") - - @property - def array(self): - """ - Allows for dynamic returning of data. - - If size is None, return None. - If size is not None and internal array is None, return a pointer to a - allocated memory of size self.ctype * self.size - If size is not None, and internal array is not None, returna pointer to the - allocated memory of the internal array. - - - :return: pointer to the internal array. - :rtype: POINTER - """ - if self._size is None: - # Return None, because this is the first time we've used this array. - # We need to set the size first w/ a call. - return None - if self._array is None: - # If we get to this point, we have a specified size, a ctype, - # And our array is still none, but we're trying to access it. - # Therefore, we go ahead & allocate the memory - self._array = (self.ctype * self._size.value)() - return cast(self._array, POINTER(self.ctype)) - - @property - def size(self): - """ - Return a pointer to a c_ulong - - :return: Pointer to a CK_ULONG - :rtype: pointer - """ - if self._size is None: - # Default size to a ulong. - self._size = c_ulong() - return pointer(self._size) - - def __len__(self): - if self._array is not None: - return len(self._array) - else: - return 0 - - def __iter__(self): - """ - Allow for iteration over contained data (you can't iterate over AutoCArray.array, - as it is a pointer). - """ - if self._array: - for i in self._array: - yield i - - def __str__(self): - """ - Return a legible version of the array. - """ - return "AutoCArray = ({ctype} * {size})({data})".format(ctype=self.ctype, - size=len(self), - data=self._array) - - -def refresh_c_arrays(retries=1): - """ - Will re-run any Cryptoki function with an AutoCArray instance to automatically place the data - into the array. - - This is so that it's easier to do cryptoki transforms:: - - @refresh_c_arrays(retries=1) - def closure_func(): - return C_PkcsFunction(slot, autoarray.array, autoarray.size) - - # Set up the closure, then run the PKCS11 function inside the closure. - # This is so that the properties will work properly for both calls (rather - # than being evaluated only once) - - :param func: Function to decorate. - :return: closure. - """ - - def wrap(func): - """ - Inner decorator. - - :param func: Original function decorated. - :return: - """ - - def wrapped_func(*args, **kwargs): - """ - Runs the wrapped function the given number of times, - checking for failure. - - :param args: - :param kwargs: - :return: - """ - tries = 0 - ret = None - while tries <= retries: - ret = func(*args, **kwargs) - if ret != CKR_OK: - # Break early if one command failed. - return ret - tries += 1 - return ret - - return wrapped_func - - return wrap +""" +Utilities for pycryptoki +""" +from past.builtins import basestring +from _ctypes import pointer, POINTER +from ctypes import c_ulong, cast, create_string_buffer + +from .cryptoki import CK_CHAR +from .defines import CKR_OK + + +class CException(Exception): + """ + Raised from attempts at parsing ctypes! + """ + pass + + +class AutoCArray(object): + """ + An attempt to provide automatic resolution of C-style arrays. + + """ + + def __init__(self, data=None, ctype=c_ulong, size=None): + """ + Initialize the Array. + + If it's to be a target for Crypto operation output, you only need + to specify the ctype (defaults to ULONG) + + Otherwise, you'll want to specify data and the ctype. Data can be a list-type + object (this includes strings!). If it is a list, all objects in the list need to + be compatible with your specified ctype. + + Size *always* needs to be a ctype in (c_ulong, c_uint)! + + You can specify a size at initialization time, if you know what the size will be. + Otherwise, it will be set either by the crypto-op, defaulted to 0L, or set to the size + of the given array. + + :param data: Data array should be initialized with. Needs to be string/list. + :param ctype: Type of data the array should store (Default: CK_ULONG) + :param size: Size of the array. PKCS#11 calls will init this for us, but you can also + specify it manually. + """ + self._array = None + self._size = size + self.ctype = ctype + + # name was just for logging. + if data is not None: + # Parse out any given data. + if isinstance(data, basestring): + self._array = create_string_buffer(data) + self._size = c_ulong(len(data)) + self.ctype = CK_CHAR + elif isinstance(data, list): + self._array = (ctype * len(data))(*data) + self._size = c_ulong(len(data)) + else: + raise NotImplementedError("AutoCArray does not support given data type.") + + @property + def array(self): + """ + Allows for dynamic returning of data. + + If size is None, return None. + If size is not None and internal array is None, return a pointer to a + allocated memory of size self.ctype * self.size + If size is not None, and internal array is not None, returna pointer to the + allocated memory of the internal array. + + + :return: pointer to the internal array. + :rtype: POINTER + """ + if self._size is None: + # Return None, because this is the first time we've used this array. + # We need to set the size first w/ a call. + return None + if self._array is None: + # If we get to this point, we have a specified size, a ctype, + # And our array is still none, but we're trying to access it. + # Therefore, we go ahead & allocate the memory + self._array = (self.ctype * self._size.value)() + return cast(self._array, POINTER(self.ctype)) + + @property + def size(self): + """ + Return a pointer to a c_ulong + + :return: Pointer to a CK_ULONG + :rtype: pointer + """ + if self._size is None: + # Default size to a ulong. + self._size = c_ulong() + return pointer(self._size) + + def __len__(self): + if self._array is not None: + return len(self._array) + else: + return 0 + + def __iter__(self): + """ + Allow for iteration over contained data (you can't iterate over AutoCArray.array, + as it is a pointer). + """ + if self._array: + for i in self._array: + yield i + + def __str__(self): + """ + Return a legible version of the array. + """ + return "AutoCArray = ({ctype} * {size})({data})".format(ctype=self.ctype, + size=len(self), + data=self._array) + + +def refresh_c_arrays(retries=1): + """ + Will re-run any Cryptoki function with an AutoCArray instance to automatically place the data + into the array. + + This is so that it's easier to do cryptoki transforms:: + + @refresh_c_arrays(retries=1) + def closure_func(): + return C_PkcsFunction(slot, autoarray.array, autoarray.size) + + # Set up the closure, then run the PKCS11 function inside the closure. + # This is so that the properties will work properly for both calls (rather + # than being evaluated only once) + + :param func: Function to decorate. + :return: closure. + """ + + def wrap(func): + """ + Inner decorator. + + :param func: Original function decorated. + :return: + """ + + def wrapped_func(*args, **kwargs): + """ + Runs the wrapped function the given number of times, + checking for failure. + + :param args: + :param kwargs: + :return: + """ + tries = 0 + ret = None + while tries <= retries: + ret = func(*args, **kwargs) + if ret != CKR_OK: + # Break early if one command failed. + return ret + tries += 1 + return ret + + return wrapped_func + + return wrap diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index 105d863..21eb47a 100755 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -1,7 +1,7 @@ -''' +""" This file contains all of the ctypes definitions for the cryptoki library. The ctypes definitions outline the structures for the cryptoki C API. -''' +""" import sys from ctypes import * diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 316cd32..6906187 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -17,6 +17,7 @@ c_open_session_ex() # Returns: session_handle, raises exception if ret_code != CKR_OK """ +from __future__ import print_function import ctypes import logging import multiprocessing @@ -443,7 +444,7 @@ def create_server_subprocess(target, args): logger.info("Created subprocess w/ PID %s", server.pid) def sighandler(signum, frame): - print "Caught SIGTERM, closing subprocess" + print("Caught SIGTERM, closing subprocess") server.terminate() exit(0) diff --git a/pycryptoki/default_templates.py b/pycryptoki/default_templates.py index 615b225..b878096 100755 --- a/pycryptoki/default_templates.py +++ b/pycryptoki/default_templates.py @@ -5,7 +5,7 @@ import copy -from defines import (CKA_BASE, CKA_CERTIFICATE_TYPE, CKA_CLASS, CKA_DECRYPT, CKA_DERIVE, +from .defines import (CKA_BASE, CKA_CERTIFICATE_TYPE, CKA_CLASS, CKA_DECRYPT, CKA_DERIVE, CKA_ECDSA_PARAMS, CKA_ENCRYPT, CKA_EXTRACTABLE, CKA_KEY_TYPE, CKA_LABEL, CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PRIME, @@ -182,7 +182,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 8, CKA_EXTRACTABLE: True, - CKA_LABEL: "DES Key"} + CKA_LABEL: b"DES Key"} CKM_DES_UNWRAP_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_DES, @@ -193,7 +193,7 @@ CKA_SIGN: True, CKA_WRAP: True, CKA_DERIVE: True, - CKA_LABEL: "DES Key"} + CKA_LABEL: b"DES Key"} CKM_DES2_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_DES2, @@ -209,7 +209,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 16, CKA_EXTRACTABLE: True, - CKA_LABEL: "DES2 Key"} + CKA_LABEL: b"DES2 Key"} CKM_DES3_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_DES3, CKA_TOKEN: True, @@ -224,7 +224,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 24, CKA_EXTRACTABLE: True, - CKA_LABEL: "DES3 Key"} + CKA_LABEL: b"DES3 Key"} CKM_CAST3_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_CAST3, @@ -240,7 +240,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 8, # 1-8 CKA_EXTRACTABLE: True, - CKA_LABEL: "CAST3 Key"} + CKA_LABEL: b"CAST3 Key"} CKM_GENERIC_SECRET_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_GENERIC_SECRET, @@ -256,7 +256,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 16, CKA_EXTRACTABLE: True, - CKA_LABEL: "GENERIC SECRET Key"} + CKA_LABEL: b"GENERIC SECRET Key"} CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, @@ -266,7 +266,7 @@ CKA_WRAP: True, CKA_MODULUS_BITS: 1024, # long 0 - MAX_RSA_KEY_NBITS CKA_PUBLIC_EXPONENT: 3, # byte - CKA_LABEL: "RSA Public Key"} + CKA_LABEL: b"RSA Public Key"} CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -275,7 +275,7 @@ CKA_DECRYPT: True, CKA_SIGN: True, CKA_UNWRAP: True, - CKA_LABEL: "RSA Private Key"} + CKA_LABEL: b"RSA Private Key"} dsa_prime_1024_160 = [0xfc, 0xec, 0x61, 0x82, 0xeb, 0x20, 0x6b, 0x43, 0xc0, 0x3e, 0x36, 0xc0, 0xea, 0xda, 0xbf, 0xf5, @@ -565,7 +565,7 @@ CKA_PRIME: dsa_prime_1024_160, CKA_SUBPRIME: dsa_sub_prime_1024_160, CKA_BASE: dsa_base_1024_160, - CKA_LABEL: "DSA 1024_160 Public Key"} + CKA_LABEL: b"DSA 1024_160 Public Key"} CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224 = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_ENCRYPT: True, @@ -574,7 +574,7 @@ CKA_PRIME: dsa_prime_2048_224, CKA_SUBPRIME: dsa_sub_prime_2048_224, CKA_BASE: dsa_base_2048_224, - CKA_LABEL: "DSA 2048_224 Public Key"} + CKA_LABEL: b"DSA 2048_224 Public Key"} CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_ENCRYPT: True, @@ -583,7 +583,7 @@ CKA_PRIME: dsa_prime_2048_256, CKA_SUBPRIME: dsa_sub_prime_2048_256, CKA_BASE: dsa_base_2048_256, - CKA_LABEL: "DSA 2048_256 Public Key"} + CKA_LABEL: b"DSA 2048_256 Public Key"} CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_ENCRYPT: True, @@ -592,7 +592,7 @@ CKA_PRIME: dsa_prime_3072_256, CKA_SUBPRIME: dsa_sub_prime_3072_256, CKA_BASE: dsa_base_3072_256, - CKA_LABEL: "DSA 3072_256 Public Key"} + CKA_LABEL: b"DSA 3072_256 Public Key"} CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -600,7 +600,7 @@ CKA_SIGN: True, CKA_UNWRAP: True, CKA_EXTRACTABLE: True, - CKA_LABEL: "DSA Public Key"} + CKA_LABEL: b"DSA Public Key"} dh_prime = [0xF4, 0x88, 0xFD, 0x58, 0x4E, 0x49, 0xDB, 0xCD, 0x20, 0xB4, 0x9D, 0xE4, 0x91, 0x07, 0x36, 0x6B, @@ -655,14 +655,14 @@ CKA_DERIVE: True, CKA_PRIME: dh_prime, CKA_BASE: [0x02], - CKA_LABEL: "DH Public Key"} + CKA_LABEL: b"DH Public Key"} CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP = {CKA_VALUE_BITS: len(dh_prime) * 8, # long CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_DERIVE: True, CKA_EXTRACTABLE: True, - CKA_LABEL: "DH Private Key"} + CKA_LABEL: b"DH Private Key"} CKM_CAST5_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_CAST5, @@ -678,7 +678,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 16, # 1-16 CKA_EXTRACTABLE: True, - CKA_LABEL: "CAST5 Key"} + CKA_LABEL: b"CAST5 Key"} CKM_RC2_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_RC2, @@ -694,7 +694,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 64, # 1-128 CKA_EXTRACTABLE: True, - CKA_LABEL: "RC2 Key"} + CKA_LABEL: b"RC2 Key"} CKM_RC4_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_RC4, @@ -710,7 +710,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 256, # 1-256 CKA_EXTRACTABLE: True, - CKA_LABEL: "RC4 Key"} + CKA_LABEL: b"RC4 Key"} CKM_RC5_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_RC5, @@ -726,13 +726,13 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 255, # 1-255 CKA_EXTRACTABLE: True, - CKA_LABEL: "RC5 Key"} + CKA_LABEL: b"RC5 Key"} CKM_SSL3_PRE_MASTER_KEY_GEN_TEMP = {CKA_TOKEN: True, CKA_DERIVE: True, CKA_ENCRYPT: 0x1001, # TODO, is encrypt both a long and a boolean, uh oh - CKA_LABEL: "SSL3 Pre Master Key"} + CKA_LABEL: b"SSL3 Pre Master Key"} ''' Curve dictionary for ECDSA with oids as lists, taken from Components/tools/common/CommonData.cpp @@ -755,15 +755,15 @@ 'X9_62_prime192v1(P-192)': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x01], # [91] OID_X9_62_prime192v1 'X9_62_prime192v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x02], -# [101] OID_X9_62_prime192v2 + # [101] OID_X9_62_prime192v2 'X9_62_prime192v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x03], -# [111] OID_X9_62_prime192v3 + # [111] OID_X9_62_prime192v3 'X9_62_prime239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x04], -# [121] OID_X9_62_prime239v1 + # [121] OID_X9_62_prime239v1 'X9_62_prime239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x05], -# [131] OID_X9_62_prime239v2 + # [131] OID_X9_62_prime239v2 'X9_62_prime239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x06], -# [141] OID_X9_62_prime239v3 + # [141] OID_X9_62_prime239v3 'X9_62_prime256v1(P-256)': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07], # [151] OID_X9_62_prime256v1 @@ -787,66 +787,66 @@ 'sect571r1': [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x27], # [280] OID_sect571r1 'X9_62_c2pnb163v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x01], -# [287] OID_X9_62_c2pnb163v1 + # [287] OID_X9_62_c2pnb163v1 'X9_62_c2pnb163v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x02], -# [297] OID_X9_62_c2pnb163v2 + # [297] OID_X9_62_c2pnb163v2 'X9_62_c2pnb163v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x03], -# [307] OID_X9_62_c2pnb163v3 + # [307] OID_X9_62_c2pnb163v3 'X9_62_c2pnb176v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x04], -# [317] OID_X9_62_c2pnb176v1 + # [317] OID_X9_62_c2pnb176v1 'X9_62_c2tnb191v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x05], -# [327] OID_X9_62_c2tnb191v1 + # [327] OID_X9_62_c2tnb191v1 'X9_62_c2tnb191v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x06], -# [337] OID_X9_62_c2tnb191v2 + # [337] OID_X9_62_c2tnb191v2 'X9_62_c2tnb191v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x07], -# [347] OID_X9_62_c2tnb191v3 + # [347] OID_X9_62_c2tnb191v3 'X9_62_c2pnb208w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0A], -# [357] OID_X9_62_c2pnb208w1 + # [357] OID_X9_62_c2pnb208w1 'X9_62_c2tnb239v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0B], -# [367] OID_X9_62_c2tnb239v1 + # [367] OID_X9_62_c2tnb239v1 'X9_62_c2tnb239v2': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0C], -# [377] OID_X9_62_c2tnb239v2 + # [377] OID_X9_62_c2tnb239v2 'X9_62_c2tnb239v3': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x0D], -# [387] OID_X9_62_c2tnb239v3 + # [387] OID_X9_62_c2tnb239v3 'X9_62_c2pnb272w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x10], -# [397] OID_X9_62_c2pnb272w1 + # [397] OID_X9_62_c2pnb272w1 'X9_62_c2pnb304w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x11], -# [407] OID_X9_62_c2pnb304w1 + # [407] OID_X9_62_c2pnb304w1 'X9_62_c2tnb359v1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x12], -# [417] OID_X9_62_c2tnb359v1 + # [417] OID_X9_62_c2tnb359v1 'X9_62_c2pnb368w1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x13], -# [427] OID_X9_62_c2pnb368w1 + # [427] OID_X9_62_c2pnb368w1 'X9_62_c2tnb431r1': [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x00, 0x14], -# [437] OID_X9_62_c2tnb431r1 + # [437] OID_X9_62_c2tnb431r1 'brainpoolP160r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x01], -# [447] brainpoolP160r1 + # [447] brainpoolP160r1 'brainpoolP160t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x02], -# [458] brainpoolP160t1 + # [458] brainpoolP160t1 'brainpoolP192r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x03], -# [469] brainpoolP192r1 + # [469] brainpoolP192r1 'brainpoolP192t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x04], -# [480] brainpoolP192t1 + # [480] brainpoolP192t1 'brainpoolP224r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x05], -# [491] brainpoolP224r1 + # [491] brainpoolP224r1 'brainpoolP224t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x06], -# [502] brainpoolP224t1 + # [502] brainpoolP224t1 'brainpoolP256r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], -# [513] brainpoolP256r1 + # [513] brainpoolP256r1 'brainpoolP256t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x08], -# [524] brainpoolP256t1 + # [524] brainpoolP256t1 'brainpoolP320r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x09], -# [535] brainpoolP320r1 + # [535] brainpoolP320r1 'brainpoolP320t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0a], -# [546] brainpoolP320t1 + # [546] brainpoolP320t1 'brainpoolP384r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0b], -# [557] brainpoolP384r1 + # [557] brainpoolP384r1 'brainpoolP384t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0c], -# [568] brainpoolP384t1 + # [568] brainpoolP384t1 'brainpoolP512r1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0d], -# [579] brainpoolP512r1 + # [579] brainpoolP512r1 'brainpoolP512t1': [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0e], -# [590] brainpoolP512t1 + # [590] brainpoolP512t1 'microsoftPlayReadP160': [0x30, 0x81, 0x95, 0x02, 0x01, 0x01, 0x30, 0x20, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01, 0x02, 0x15, 0x00, 0x89, 0xab, 0xcd, 0xef, @@ -874,7 +874,7 @@ CKA_VERIFY: True, CKA_DERIVE: True, CKA_ECDSA_PARAMS: curve_list['secp112r1'], - CKA_LABEL: "ECDSA Public Key"} + CKA_LABEL: b"ECDSA Public Key"} CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -882,7 +882,7 @@ CKA_SIGN: True, CKA_DERIVE: True, CKA_EXTRACTABLE: True, - CKA_LABEL: "ECDSA Private Key"} + CKA_LABEL: b"ECDSA Private Key"} CKM_AES_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_AES, @@ -898,7 +898,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 24, # 16, 24, 32 CKA_EXTRACTABLE: True, - CKA_LABEL: "AES Key"} + CKA_LABEL: b"AES Key"} CKM_SEED_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_SEED, @@ -914,7 +914,7 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 16, CKA_EXTRACTABLE: True, - CKA_LABEL: "SEED Key"} + CKA_LABEL: b"SEED Key"} kcdsa_prime_1024_160 = [0xdc, 0x02, 0xf3, 0xe0, 0x51, 0x4e, 0xf4, 0x72, 0x36, 0x51, 0x09, 0x72, 0x5c, 0x12, 0x00, 0x50, @@ -1030,7 +1030,7 @@ CKA_PRIME: kcdsa_prime_1024_160, CKA_SUBPRIME: kcdsa_sub_prime_1024_160, CKA_BASE: kcdsa_base_1024_160, - CKA_LABEL: "KCDSA Public Key"} + CKA_LABEL: b"KCDSA Public Key"} CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256 = {CKA_TOKEN: True, # 1024_160 or 2048_256 CKA_PRIVATE: True, CKA_ENCRYPT: True, @@ -1039,7 +1039,7 @@ CKA_PRIME: kcdsa_prime_2048_256, CKA_SUBPRIME: kcdsa_sub_prime_2048_256, CKA_BASE: kcdsa_base_2048_256, - CKA_LABEL: "KCDSA Public Key"} + CKA_LABEL: b"KCDSA Public Key"} CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -1047,7 +1047,7 @@ CKA_SIGN: True, CKA_UNWRAP: True, CKA_EXTRACTABLE: True, - CKA_LABEL: "KCDSA Private Key"} + CKA_LABEL: b"KCDSA Private Key"} CKM_DSA_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, @@ -1055,14 +1055,14 @@ CKA_PRIME_BITS: 1024, # 0-4096, ONLY SUPPORTS: 1024-160, 2048-224, 2048-256, 3072-256 CKA_SUBPRIME_BITS: 160, # 0-512 - CKA_LABEL: "DSA Parameter Key"} + CKA_LABEL: b"DSA Parameter Key"} CKM_KCDSA_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, # primelength 0-4096, subprimelength 0-512 CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_PRIME_BITS: 2048, # 0-4096 CKA_SUBPRIME_BITS: 256, # 0-512 - CKA_LABEL: "KCDSA Parameter Key"} + CKA_LABEL: b"KCDSA Parameter Key"} CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, @@ -1072,7 +1072,7 @@ CKA_WRAP: True, CKA_MODULUS_BITS: 1024, # long 1-MAX_RSA_KEY_NBITS CKA_PUBLIC_EXPONENT: 3, # byte - CKA_LABEL: "RSA Public Key"} + CKA_LABEL: b"RSA Public Key"} CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, @@ -1081,7 +1081,7 @@ CKA_DECRYPT: True, CKA_SIGN: True, CKA_UNWRAP: True, - CKA_LABEL: "RSA Private Key"} + CKA_LABEL: b"RSA Private Key"} dhX9_42Prime = [0xE0, 0x01, 0xE8, 0x96, 0x7D, 0xB4, 0x93, 0x53, 0xE1, 0x6F, 0x8E, 0x89, 0x22, 0x0C, 0xCE, 0xFC, @@ -1125,13 +1125,13 @@ CKA_PRIME: dhX9_42Prime, CKA_BASE: dhX9_42Base, CKA_SUBPRIME: dhX9_42SubPrime, - CKA_LABEL: "DH X9.42 Public Key"} + CKA_LABEL: b"DH X9.42 Public Key"} CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_DERIVE: True, CKA_EXTRACTABLE: True, - CKA_LABEL: "DH X9.42 Private Key"} + CKA_LABEL: b"DH X9.42 Private Key"} CKM_ARIA_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_ARIA, @@ -1147,14 +1147,14 @@ CKA_DERIVE: True, CKA_VALUE_LEN: 24, # 16, 24, 32 CKA_EXTRACTABLE: True, - CKA_LABEL: "ARIA Key"} + CKA_LABEL: b"ARIA Key"} CKM_DH_PKCS_PARAMETER_GEN_TEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, CKA_SENSITIVE: True, CKA_PRIME_BITS: 512, # between 512 and 2048 in 256bit increments (&0xff) - CKA_LABEL: "SH PKCS Parameter Key"} + CKA_LABEL: b"SH PKCS Parameter Key"} ''' The simple certificate object taken from CKDemo when @@ -1163,8 +1163,8 @@ CERTIFICATE_TEMPLATE = {CKA_CLASS: CKO_CERTIFICATE, CKA_CERTIFICATE_TYPE: CKC_X_509, CKA_TOKEN: True, - CKA_LABEL: "Created certificate object", - CKA_SUBJECT: "", + CKA_LABEL: b"Created certificate object", + CKA_SUBJECT: b"", CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} @@ -1175,7 +1175,7 @@ ''' DATA_TEMPLATE = {CKA_CLASS: CKO_DATA, CKA_TOKEN: True, - CKA_LABEL: "Created data object", + CKA_LABEL: b"Created data object", CKA_VALUE: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01]} @@ -1197,9 +1197,6 @@ KEY_PAIR_GENERATOR_TEMPLATES = { # Note lacks multiple sizes of the same kinds of keys CKM_RSA_PKCS_KEY_PAIR_GEN: ( CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - CKM_RSA_X9_31_KEY_PAIR_GEN: ( - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - # pkcs template is good for x9.31 CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: ( CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: ( @@ -1218,49 +1215,49 @@ ''' This list is not complete ''' -MECHANISM_LOOKUP = {CKM_RSA_PKCS_KEY_PAIR_GEN: "CKM_RSA_PKCS_KEY_PAIR_GEN", - CKM_RSA_PKCS: "CKM_RSA_PKCS", - CKM_SHA1_RSA_PKCS: "CKM_SHA1_RSA_PKCS", - CKM_SHA224_RSA_PKCS: "CKM_SHA224_RSA_PKCS", - CKM_SHA256_RSA_PKCS: "CKM_SHA256_RSA_PKCS", - CKM_SHA384_RSA_PKCS: "CKM_SHA384_RSA_PKCS", - CKM_SHA512_RSA_PKCS: "CKM_SHA512_RSA_PKCS", - CKM_RSA_PKCS_PSS: "CKM_RSA_PKCS_PSS", - CKM_SHA1_RSA_PKCS_PSS: "CKM_SHA1_RSA_PKCS_PSS", - CKM_SHA224_RSA_PKCS_PSS: "CKM_SHA224_RSA_PKCS_PSS", - CKM_SHA256_RSA_PKCS_PSS: "CKM_SHA256_RSA_PKCS_PSS", - CKM_SHA384_RSA_PKCS_PSS: "CKM_SHA384_RSA_PKCS_PSS", - CKM_SHA512_RSA_PKCS_PSS: "CKM_SHA512_RSA_PKCS_PSS", - CKM_RSA_X9_31_KEY_PAIR_GEN: "CKM_RSA_X9_31_KEY_PAIR_GEN", - CKM_RSA_X9_31: "CKM_RSA_X9_31", - CKM_SHA1_RSA_X9_31: "CKM_SHA1_RSA_X9_31", - CKM_SHA224_RSA_X9_31: "CKM_SHA224_RSA_X9_31", - CKM_SHA256_RSA_X9_31: "CKM_SHA256_RSA_X9_31", - CKM_SHA384_RSA_X9_31: "CKM_SHA384_RSA_X9_31", - CKM_SHA512_RSA_X9_31: "CKM_SHA512_RSA_X9_31", - CKM_RSA_PKCS_OAEP: "CKM_RSA_PKCS_OAEP", - CKM_DSA_KEY_PAIR_GEN: "CKM_DSA_KEY_PAIR_GEN", - CKM_DSA: "CKM_DSA", - CKM_DSA_SHA1: "CKM_DSA_SHA1", - CKM_DSA_SHA224: "CKM_DSA_SHA224", - CKM_DSA_SHA256: "CKM_DSA_SHA256", - CKM_DSA_PARAMETER_GEN: "CKM_DSA_PARAMETER_GEN", - CKM_ECDSA_KEY_PAIR_GEN: "CKM_ECDSA_KEY_PAIR_GEN", - CKM_ECDSA: "CKM_ECDSA", - CKM_ECDSA_SHA1: "CKM_ECDSA_SHA1", - CKM_ECDSA_SHA224: "CKM_ECDSA_SHA224", - CKM_ECDSA_SHA256: "CKM_ECDSA_SHA256", - CKM_ECDSA_SHA384: "CKM_ECDSA_SHA384", - CKM_ECDSA_SHA512: "CKM_ECDSA_SHA512", - CKM_ECDH1_DERIVE: "CKM_ECDH1_DERIVE", - CKM_ECDH1_COFACTOR_DERIVE: "CKM_ECDH1_DERIVE", - CKM_SHA_1_HMAC: "CKM_SHA_1_HMAC", - CKM_SHA224_HMAC: "CKM_SHA224_HMAC", - CKM_SHA256_HMAC: "CKM_SHA256_HMAC", - CKM_SHA384_HMAC: "CKM_SHA384_HMAC", - CKM_SHA512_HMAC: "CKM_SHA512_HMAC", - CKM_GENERIC_SECRET_KEY_GEN: "CKM_GENERIC_SECRET_KEY_GEN", - CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", +MECHANISM_LOOKUP = {CKM_RSA_PKCS_KEY_PAIR_GEN: b"CKM_RSA_PKCS_KEY_PAIR_GEN", + CKM_RSA_PKCS: b"CKM_RSA_PKCS", + CKM_SHA1_RSA_PKCS: b"CKM_SHA1_RSA_PKCS", + CKM_SHA224_RSA_PKCS: b"CKM_SHA224_RSA_PKCS", + CKM_SHA256_RSA_PKCS: b"CKM_SHA256_RSA_PKCS", + CKM_SHA384_RSA_PKCS: b"CKM_SHA384_RSA_PKCS", + CKM_SHA512_RSA_PKCS: b"CKM_SHA512_RSA_PKCS", + CKM_RSA_PKCS_PSS: b"CKM_RSA_PKCS_PSS", + CKM_SHA1_RSA_PKCS_PSS: b"CKM_SHA1_RSA_PKCS_PSS", + CKM_SHA224_RSA_PKCS_PSS: b"CKM_SHA224_RSA_PKCS_PSS", + CKM_SHA256_RSA_PKCS_PSS: b"CKM_SHA256_RSA_PKCS_PSS", + CKM_SHA384_RSA_PKCS_PSS: b"CKM_SHA384_RSA_PKCS_PSS", + CKM_SHA512_RSA_PKCS_PSS: b"CKM_SHA512_RSA_PKCS_PSS", + CKM_RSA_X9_31_KEY_PAIR_GEN: b"CKM_RSA_X9_31_KEY_PAIR_GEN", + CKM_RSA_X9_31: b"CKM_RSA_X9_31", + CKM_SHA1_RSA_X9_31: b"CKM_SHA1_RSA_X9_31", + CKM_SHA224_RSA_X9_31: b"CKM_SHA224_RSA_X9_31", + CKM_SHA256_RSA_X9_31: b"CKM_SHA256_RSA_X9_31", + CKM_SHA384_RSA_X9_31: b"CKM_SHA384_RSA_X9_31", + CKM_SHA512_RSA_X9_31: b"CKM_SHA512_RSA_X9_31", + CKM_RSA_PKCS_OAEP: b"CKM_RSA_PKCS_OAEP", + CKM_DSA_KEY_PAIR_GEN: b"CKM_DSA_KEY_PAIR_GEN", + CKM_DSA: b"CKM_DSA", + CKM_DSA_SHA1: b"CKM_DSA_SHA1", + CKM_DSA_SHA224: b"CKM_DSA_SHA224", + CKM_DSA_SHA256: b"CKM_DSA_SHA256", + CKM_DSA_PARAMETER_GEN: b"CKM_DSA_PARAMETER_GEN", + CKM_ECDSA_KEY_PAIR_GEN: b"CKM_ECDSA_KEY_PAIR_GEN", + CKM_ECDSA: b"CKM_ECDSA", + CKM_ECDSA_SHA1: b"CKM_ECDSA_SHA1", + CKM_ECDSA_SHA224: b"CKM_ECDSA_SHA224", + CKM_ECDSA_SHA256: b"CKM_ECDSA_SHA256", + CKM_ECDSA_SHA384: b"CKM_ECDSA_SHA384", + CKM_ECDSA_SHA512: b"CKM_ECDSA_SHA512", + CKM_ECDH1_DERIVE: b"CKM_ECDH1_DERIVE", + CKM_ECDH1_COFACTOR_DERIVE: b"CKM_ECDH1_DERIVE", + CKM_SHA_1_HMAC: b"CKM_SHA_1_HMAC", + CKM_SHA224_HMAC: b"CKM_SHA224_HMAC", + CKM_SHA256_HMAC: b"CKM_SHA256_HMAC", + CKM_SHA384_HMAC: b"CKM_SHA384_HMAC", + CKM_SHA512_HMAC: b"CKM_SHA512_HMAC", + CKM_GENERIC_SECRET_KEY_GEN: b"CKM_GENERIC_SECRET_KEY_GEN", + CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN: b"CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN: "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN"} diff --git a/pycryptoki/defaults.py b/pycryptoki/defaults.py index dabb185..a4b90d8 100755 --- a/pycryptoki/defaults.py +++ b/pycryptoki/defaults.py @@ -12,21 +12,21 @@ # the Chrystoki config file specified be the variable CHRYSTOKI_CONFIG_FILE CHRYSTOKI_DLL_FILE = None -ADMIN_PARTITION_LABEL = 'no label' -AUDITOR_LABEL = 'auditorlabel' +ADMIN_PARTITION_LABEL = b'no label' +AUDITOR_LABEL = b'auditorlabel' -ADMINISTRATOR_USERNAME = 'Administrator' -ADMINISTRATOR_PASSWORD = '1q@W3e$R' +ADMINISTRATOR_USERNAME = b'Administrator' +ADMINISTRATOR_PASSWORD = b'1q@W3e$R' -AUDITOR_USERNAME = 'Auditor' -AUDITOR_PASSWORD = 'W3e$R' +AUDITOR_USERNAME = b'Auditor' +AUDITOR_PASSWORD = b'W3e$R' -CO_USERNAME = 'Crypto Officer' -CO_PASSWORD = 'userpin' +CO_USERNAME = b'Crypto Officer' +CO_PASSWORD = b'userpin' -DEFAULT_USERNAME = 'default_user' -DEFAULT_LABEL = 'default_label' -DEFAULT_PASSWORD = 'userpin' +DEFAULT_USERNAME = b'default_user' +DEFAULT_LABEL = b'default_label' +DEFAULT_PASSWORD = b'userpin' DEFAULT_UTILS_PATH = '/usr/safenet/lunaclient/sbin' FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" @@ -38,7 +38,7 @@ DES3_KEY_SIZE = 120 -MANUFACTURER_ID = "SafeNet Inc." -MODEL = "Luna K6" +MANUFACTURER_ID = b"SafeNet Inc." +MODEL = b"Luna K6" ADMIN_SLOT = int(os.environ.get("ADMIN_SLOT", 1)) diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index 6489891..5c1ee64 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1,6 +1,6 @@ -''' +""" Constants & Definitions pulled from PKCS11 -''' +""" LUNA_MAX_UPDATE_DATA_SIZE = (64 * 1024) LUNA_GEN_KCV_FLAG_NONE = 0x0000 diff --git a/pycryptoki/dictionary_handling.py b/pycryptoki/dictionary_handling.py deleted file mode 100755 index 55b789c..0000000 --- a/pycryptoki/dictionary_handling.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -Created on Oct 3, 2012 - -@author: root -""" - - -class CDict: - """ """ - - dict_val = None - - def __init__(self, dict_val): - self.dict_val = dict_val diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 472c46c..e1d9ffc 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -5,9 +5,9 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from cryptoki import CK_ULONG, \ +from .cryptoki import CK_ULONG, \ C_EncryptInit, C_Encrypt -from defines import CKR_OK +from .defines import CKR_OK from .attributes import Attributes, to_char_array from .common_utils import AutoCArray, refresh_c_arrays from .cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ @@ -87,7 +87,7 @@ def _split_string_into_list(python_string, block_size): """ total_length = len(python_string) - return [python_string[x:x + block_size] for x in xrange(0, total_length, block_size)] + return [python_string[x:x + block_size] for x in range(0, total_length, block_size)] def _get_string_from_list(list_of_strings): @@ -97,7 +97,7 @@ def _get_string_from_list(list_of_strings): :returns: Single string representing the concatenated list """ - return "".join(list_of_strings) + return b"".join(list_of_strings) def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, extra_params=None): @@ -180,7 +180,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in plain_data_len = len(_get_string_from_list(input_data_list)) remaining_length = plain_data_len - python_string = '' + python_string = b'' i = 0 while remaining_length > 0: current_chunk = input_data_list[i] @@ -193,34 +193,32 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in "chunk_sizes variable too large, the maximum size of a chunk is " + str( max_data_chunk_size)) - out_data = create_string_buffer('', max_data_chunk_size) + out_data = create_string_buffer(b'', max_data_chunk_size) out_data_len = CK_ULONG(max_data_chunk_size) data_chunk, data_chunk_len = to_char_array(current_chunk) data_chunk = cast(data_chunk, POINTER(c_ubyte)) - ret = c_update_function(h_session, data_chunk, data_chunk_len, - cast(out_data, CK_BYTE_PTR), - byref(out_data_len)) + ret = c_update_function(h_session, + data_chunk, data_chunk_len, + cast(out_data, CK_BYTE_PTR), byref(out_data_len)) if ret != CKR_OK: return ret, None remaining_length -= current_chunk_len # Get the output - ck_char_array = out_data._objects.values()[0] - python_string += string_at(ck_char_array, len(ck_char_array))[0:out_data_len.value] + python_string += out_data.raw[0:int(out_data_len.value)] i += 1 # Finalizing multipart decrypt operation out_data_len = CK_ULONG(max_data_chunk_size) - output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) + out_data = create_string_buffer(b"", out_data_len.value) + output = cast(out_data, CK_BYTE_PTR) ret = c_finalize_function(h_session, output, byref(out_data_len)) if ret != CKR_OK: return ret, None - # Get output - ck_char_array = output._objects.values()[0] - if out_data_len.value > 0: - python_string += string_at(ck_char_array, len(ck_char_array))[0:out_data_len.value] + + python_string += out_data.value return ret, python_string diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 758ebb9..07260f7 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -1,390 +1,390 @@ -""" -Methods responsible for pycryptoki 'hsm management' set of commands. -""" -from _ctypes import pointer -from ctypes import byref, create_string_buffer, cast - -from .attributes import Attributes -from .common_utils import AutoCArray, refresh_c_arrays -from .cryptoki import (CK_SLOT_ID, - CK_USER_TYPE, - CA_SetTokenCertificateSignature, - CA_HAInit, - CA_CreateLoginChallenge, - CA_InitializeRemotePEDVector, - CA_DeleteRemotePEDVector, - CA_MTKRestore, - CA_MTKResplit, - CA_MTKZeroize, - CK_ULONG, - CK_BYTE_PTR, - CK_BYTE, - CK_CHAR_PTR, - CK_CHAR, CA_SetHSMPolicy, CK_SESSION_HANDLE, CA_SetHSMPolicies, - CA_SetDestructiveHSMPolicy, CA_SetDestructiveHSMPolicies, - CA_GetHSMCapabilitySet, CA_GetHSMCapabilitySetting, - CA_GetHSMPolicySet, CA_GetHSMPolicySetting) -from .test_functions import make_error_handle_function - - -def c_performselftest(slot, - test_type, - input_data, - input_data_len): - """Test: Performs a self test for specified test type on a given slot. - - :param slot: slot number - :param test_type: type of test CK_ULONG - :param input_data: pointer to input data CK_BYTE_PTR - :param input_data_len: input data length CK_ULONG - :returns: the result code - - [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] - - """ - - test_type = CK_ULONG(test_type) - input_length = CK_ULONG(input_data_len) - input_data = (CK_BYTE * input_data_len)(*input_data) - output_data = cast(create_string_buffer('', input_data_len), CK_BYTE_PTR) - output_data_len = CK_ULONG() - try: - from .cryptoki import CA_PerformSelfTest as selftest - except ImportError: - from .cryptoki import C_PerformSelftest as selftest - - ret = selftest(slot, - test_type, - input_data, - input_length, - output_data, - byref(output_data_len)) - return ret, output_data - - -c_performselftest_ex = make_error_handle_function(c_performselftest) - - -def ca_settokencertificatesignature(h_session, - access_level, - customer_id, - pub_template, - signature, - signature_len): - """Completes the installation of a certificate on a token. - The caller must supply a public key and a signature for token certificate. - The public key is provided through the template; it must contain a key - type, a modulus and a public exponent. - - :param h_session: the current session - :param access_level: the access level - :param customer_id: the customer ID - :param pub_template: the public template - :param signature: the signature - :param signature_len: the length in bytes of the signature - :returns: the result code - - """ - - access_level = CK_ULONG(access_level) - customer_id = CK_ULONG(customer_id) - - key_attributes = Attributes(pub_template) - pub_template_len = CK_ULONG(len(pub_template)) - signature = (CK_BYTE * signature_len)(*signature) - signature_length = CK_ULONG(signature_len) - ret = CA_SetTokenCertificateSignature(h_session, - access_level, - customer_id, - key_attributes.get_c_struct(), - pub_template_len, - signature, - signature_length) - return ret - - -ca_settokencertificatesignature_ex = \ - make_error_handle_function(ca_settokencertificatesignature) - - -def ca_hainit(h_session, h_key): - """Creates a login key pair on the primary token. - - :param h_session: the current session - :param h_key: the login private key - :returns: the result code - - """ - ret = CA_HAInit(h_session, h_key) - - return ret - - -ca_hainit_ex = make_error_handle_function(ca_hainit) - - -def ca_createloginchallenge(h_session, - user_type, - challenge): - """Creates a login challenge for the given user. - - :param h_session: the current session - :param user_type: user type - :param challenge: challenge - :returns: the result code - - """ - - challenge_length = CK_ULONG(len(challenge)) - challenge = cast(create_string_buffer(challenge), CK_CHAR_PTR) - output_data_length = CK_ULONG() - output_data = CK_CHAR() - ret = CA_CreateLoginChallenge(h_session, - CK_USER_TYPE(user_type), - challenge_length, - challenge, - output_data_length, - output_data) - return ret, output_data - - -ca_createloginchallenge_ex = \ - make_error_handle_function(ca_createloginchallenge) - - -def ca_initializeremotepedvector(h_session): - """Initializes a remote PED vector - - :param h_session: the current session - :returns: the result code - - """ - ret = CA_InitializeRemotePEDVector(h_session) - return ret - - -ca_initializeremotepedvector_ex = \ - make_error_handle_function(ca_initializeremotepedvector) - - -def ca_deleteremotepedvector(h_session): - """Deletes a remote PED vector - - :param h_session: the current session - :returns: the result code - - """ - ret = CA_DeleteRemotePEDVector(h_session) - return ret - - -ca_deleteremotepedvector_ex = \ - make_error_handle_function(ca_deleteremotepedvector) - - -def ca_mtkrestore(slot): - """Restore the MTK - - :param slot: slot number - :returns: the result code - - """ - ret = CA_MTKRestore(CK_SLOT_ID(slot)) - return ret - - -ca_mtkrestore_ex = make_error_handle_function(ca_mtkrestore) - - -def ca_mtkresplit(slot): - """Resplit the MTK - - :param slot: slot number - :returns: the result code - - """ - ret = CA_MTKResplit(CK_SLOT_ID(slot)) - return ret - - -ca_mtkresplit_ex = make_error_handle_function(ca_mtkresplit) - - -def ca_mtkzeroize(slot): - """Zeroize the MTK - - :param slot: slot number - :returns: the result code - - """ - ret = CA_MTKZeroize(CK_SLOT_ID(slot)) - return ret - - -ca_mtkzeroize_ex = make_error_handle_function(ca_mtkzeroize) - - -def ca_set_hsm_policy(h_session, policy_id, policy_val): - """Sets the HSM policies by calling CA_SetHSMPolicy - - :param h_session: The session handle of the administrator setting the HSM policy - :param policy_id: The ID of the policy being set - :param policy_val: The value of the policy being set - :returns: The result code - - """ - ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret - - -ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) - - -def ca_set_hsm_policies(h_session, policies): - """ - Set multiple HSM policies. - - :param h_session: session handle - :param policies: dict of policy ID ints and value ints - :return: result code - """ - h_sess = CK_SESSION_HANDLE(h_session) - pol_id_list = policies.keys() - pol_val_list = policies.values() - pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) - pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) - - ret = CA_SetHSMPolicies(h_sess, pol_ids.size.contents, - pol_ids.array, pol_vals.array) - - return ret - - -ca_set_hsm_policies_ex = make_error_handle_function(ca_set_hsm_policies) - - -def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): - """Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy - - :param h_session: The session handle of the administrator setting the HSM policy - :param policy_id: The ID of the policy being set - :param policy_val: The value of the policy being set - :returns: The result code - - """ - ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) - return ret - - -ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) - - -def ca_set_destructive_hsm_policies(h_session, policies): - """ - Set multiple HSM policies. - - :param h_session: session handle - :param policies: dict of policy ID ints and value ints - :return: result code - """ - h_sess = CK_SESSION_HANDLE(h_session) - pol_id_list = policies.keys() - pol_val_list = policies.values() - pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) - pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) - - ret = CA_SetDestructiveHSMPolicies(h_sess, pol_ids.size.contents, - pol_ids.array, pol_vals.array) - - return ret - - -ca_set_destructive_hsm_policies_ex = make_error_handle_function(ca_set_destructive_hsm_policies) - - -def ca_get_hsm_capability_set(slot): - """ - Get the capabilities of the given slot. - - :param int slot: Target slot number - :return: retcode, {id: val} dict of capabilities (None if command failed) - """ - slot_id = CK_SLOT_ID(slot) - cap_ids = AutoCArray() - cap_vals = AutoCArray() - - @refresh_c_arrays(1) - def _get_hsm_caps(): - """Closer for retries to work w/ properties - """ - return CA_GetHSMCapabilitySet(slot_id, cap_ids.array, cap_ids.size, - cap_vals.array, cap_vals.size) - - ret = _get_hsm_caps() - - return ret, dict(zip(cap_ids, cap_vals)) - - -ca_get_hsm_capability_set_ex = make_error_handle_function(ca_get_hsm_capability_set) - - -def ca_get_hsm_capability_setting(slot, capability_id): - """ - Get the value of a single capability - - :param slot: slot ID of slot to query - :param capability_id: capability ID - :return: result code, CK_ULONG representing capability active or not - """ - slot_id = CK_SLOT_ID(slot) - cap_id = CK_ULONG(capability_id) - cap_val = CK_ULONG() - ret = CA_GetHSMCapabilitySetting(slot_id, cap_id, pointer(cap_val)) - return ret, cap_val.value - - -ca_get_hsm_capability_setting_ex = make_error_handle_function(ca_get_hsm_capability_setting) - - -def ca_get_hsm_policy_set(slot): - """ - Get the policies of the given slot. - - :param int slot: Target slot number - :return: retcode, {id: val} dict of policies (None if command failed) - """ - slot_id = CK_SLOT_ID(slot) - pol_ids = AutoCArray() - pol_vals = AutoCArray() - - @refresh_c_arrays(1) - def _ca_get_hsm_policy_set(): - """Closure for retries. - """ - return CA_GetHSMPolicySet(slot_id, pol_ids.array, pol_ids.size, - pol_vals.array, pol_vals.size) - - ret = _ca_get_hsm_policy_set() - - return ret, dict(zip(pol_ids, pol_vals)) - - -ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) - - -def ca_get_hsm_policy_setting(slot, policy_id): - """ - Get the value of a single policy - - :param slot: slot ID of slot to query - :param policy_id: policy ID - :return: result code, CK_ULONG representing policy active or not - """ - slot_id = CK_SLOT_ID(slot) - pol_id = CK_ULONG(policy_id) - pol_val = CK_ULONG() - ret = CA_GetHSMPolicySetting(slot_id, pol_id, pointer(pol_val)) - return ret, pol_val.value - - -ca_get_hsm_policy_setting_ex = make_error_handle_function(ca_get_hsm_policy_setting) +""" +Methods responsible for pycryptoki 'hsm management' set of commands. +""" +from _ctypes import pointer +from ctypes import byref, create_string_buffer, cast + +from .attributes import Attributes +from .common_utils import AutoCArray, refresh_c_arrays +from .cryptoki import (CK_SLOT_ID, + CK_USER_TYPE, + CA_SetTokenCertificateSignature, + CA_HAInit, + CA_CreateLoginChallenge, + CA_InitializeRemotePEDVector, + CA_DeleteRemotePEDVector, + CA_MTKRestore, + CA_MTKResplit, + CA_MTKZeroize, + CK_ULONG, + CK_BYTE_PTR, + CK_BYTE, + CK_CHAR_PTR, + CK_CHAR, CA_SetHSMPolicy, CK_SESSION_HANDLE, CA_SetHSMPolicies, + CA_SetDestructiveHSMPolicy, CA_SetDestructiveHSMPolicies, + CA_GetHSMCapabilitySet, CA_GetHSMCapabilitySetting, + CA_GetHSMPolicySet, CA_GetHSMPolicySetting) +from .test_functions import make_error_handle_function + + +def c_performselftest(slot, + test_type, + input_data, + input_data_len): + """Test: Performs a self test for specified test type on a given slot. + + :param slot: slot number + :param test_type: type of test CK_ULONG + :param input_data: pointer to input data CK_BYTE_PTR + :param input_data_len: input data length CK_ULONG + :returns: the result code + + [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] + + """ + + test_type = CK_ULONG(test_type) + input_length = CK_ULONG(input_data_len) + input_data = (CK_BYTE * input_data_len)(*input_data) + output_data = cast(create_string_buffer(b'', input_data_len), CK_BYTE_PTR) + output_data_len = CK_ULONG() + try: + from .cryptoki import CA_PerformSelfTest as selftest + except ImportError: + from .cryptoki import C_PerformSelftest as selftest + + ret = selftest(slot, + test_type, + input_data, + input_length, + output_data, + byref(output_data_len)) + return ret, output_data + + +c_performselftest_ex = make_error_handle_function(c_performselftest) + + +def ca_settokencertificatesignature(h_session, + access_level, + customer_id, + pub_template, + signature, + signature_len): + """Completes the installation of a certificate on a token. + The caller must supply a public key and a signature for token certificate. + The public key is provided through the template; it must contain a key + type, a modulus and a public exponent. + + :param h_session: the current session + :param access_level: the access level + :param customer_id: the customer ID + :param pub_template: the public template + :param signature: the signature + :param signature_len: the length in bytes of the signature + :returns: the result code + + """ + + access_level = CK_ULONG(access_level) + customer_id = CK_ULONG(customer_id) + + key_attributes = Attributes(pub_template) + pub_template_len = CK_ULONG(len(pub_template)) + signature = (CK_BYTE * signature_len)(*signature) + signature_length = CK_ULONG(signature_len) + ret = CA_SetTokenCertificateSignature(h_session, + access_level, + customer_id, + key_attributes.get_c_struct(), + pub_template_len, + signature, + signature_length) + return ret + + +ca_settokencertificatesignature_ex = \ + make_error_handle_function(ca_settokencertificatesignature) + + +def ca_hainit(h_session, h_key): + """Creates a login key pair on the primary token. + + :param h_session: the current session + :param h_key: the login private key + :returns: the result code + + """ + ret = CA_HAInit(h_session, h_key) + + return ret + + +ca_hainit_ex = make_error_handle_function(ca_hainit) + + +def ca_createloginchallenge(h_session, + user_type, + challenge): + """Creates a login challenge for the given user. + + :param h_session: the current session + :param user_type: user type + :param challenge: challenge + :returns: the result code + + """ + + challenge_length = CK_ULONG(len(challenge)) + challenge = cast(create_string_buffer(challenge), CK_CHAR_PTR) + output_data_length = CK_ULONG() + output_data = CK_CHAR() + ret = CA_CreateLoginChallenge(h_session, + CK_USER_TYPE(user_type), + challenge_length, + challenge, + output_data_length, + output_data) + return ret, output_data + + +ca_createloginchallenge_ex = \ + make_error_handle_function(ca_createloginchallenge) + + +def ca_initializeremotepedvector(h_session): + """Initializes a remote PED vector + + :param h_session: the current session + :returns: the result code + + """ + ret = CA_InitializeRemotePEDVector(h_session) + return ret + + +ca_initializeremotepedvector_ex = \ + make_error_handle_function(ca_initializeremotepedvector) + + +def ca_deleteremotepedvector(h_session): + """Deletes a remote PED vector + + :param h_session: the current session + :returns: the result code + + """ + ret = CA_DeleteRemotePEDVector(h_session) + return ret + + +ca_deleteremotepedvector_ex = \ + make_error_handle_function(ca_deleteremotepedvector) + + +def ca_mtkrestore(slot): + """Restore the MTK + + :param slot: slot number + :returns: the result code + + """ + ret = CA_MTKRestore(CK_SLOT_ID(slot)) + return ret + + +ca_mtkrestore_ex = make_error_handle_function(ca_mtkrestore) + + +def ca_mtkresplit(slot): + """Resplit the MTK + + :param slot: slot number + :returns: the result code + + """ + ret = CA_MTKResplit(CK_SLOT_ID(slot)) + return ret + + +ca_mtkresplit_ex = make_error_handle_function(ca_mtkresplit) + + +def ca_mtkzeroize(slot): + """Zeroize the MTK + + :param slot: slot number + :returns: the result code + + """ + ret = CA_MTKZeroize(CK_SLOT_ID(slot)) + return ret + + +ca_mtkzeroize_ex = make_error_handle_function(ca_mtkzeroize) + + +def ca_set_hsm_policy(h_session, policy_id, policy_val): + """Sets the HSM policies by calling CA_SetHSMPolicy + + :param h_session: The session handle of the administrator setting the HSM policy + :param policy_id: The ID of the policy being set + :param policy_val: The value of the policy being set + :returns: The result code + + """ + ret = CA_SetHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret + + +ca_set_hsm_policy_ex = make_error_handle_function(ca_set_hsm_policy) + + +def ca_set_hsm_policies(h_session, policies): + """ + Set multiple HSM policies. + + :param h_session: session handle + :param policies: dict of policy ID ints and value ints + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + pol_id_list = list(policies.keys()) + pol_val_list = list(policies.values()) + pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) + pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) + + ret = CA_SetHSMPolicies(h_sess, pol_ids.size.contents, + pol_ids.array, pol_vals.array) + + return ret + + +ca_set_hsm_policies_ex = make_error_handle_function(ca_set_hsm_policies) + + +def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): + """Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy + + :param h_session: The session handle of the administrator setting the HSM policy + :param policy_id: The ID of the policy being set + :param policy_val: The value of the policy being set + :returns: The result code + + """ + ret = CA_SetDestructiveHSMPolicy(h_session, CK_ULONG(policy_id), CK_ULONG(policy_val)) + return ret + + +ca_set_destructive_hsm_policy_ex = make_error_handle_function(ca_set_destructive_hsm_policy) + + +def ca_set_destructive_hsm_policies(h_session, policies): + """ + Set multiple HSM policies. + + :param h_session: session handle + :param policies: dict of policy ID ints and value ints + :return: result code + """ + h_sess = CK_SESSION_HANDLE(h_session) + pol_id_list = list(policies.keys()) + pol_val_list = list(policies.values()) + pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) + pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) + + ret = CA_SetDestructiveHSMPolicies(h_sess, pol_ids.size.contents, + pol_ids.array, pol_vals.array) + + return ret + + +ca_set_destructive_hsm_policies_ex = make_error_handle_function(ca_set_destructive_hsm_policies) + + +def ca_get_hsm_capability_set(slot): + """ + Get the capabilities of the given slot. + + :param int slot: Target slot number + :return: retcode, {id: val} dict of capabilities (None if command failed) + """ + slot_id = CK_SLOT_ID(slot) + cap_ids = AutoCArray() + cap_vals = AutoCArray() + + @refresh_c_arrays(1) + def _get_hsm_caps(): + """Closer for retries to work w/ properties + """ + return CA_GetHSMCapabilitySet(slot_id, cap_ids.array, cap_ids.size, + cap_vals.array, cap_vals.size) + + ret = _get_hsm_caps() + + return ret, dict(list(zip(cap_ids, cap_vals))) + + +ca_get_hsm_capability_set_ex = make_error_handle_function(ca_get_hsm_capability_set) + + +def ca_get_hsm_capability_setting(slot, capability_id): + """ + Get the value of a single capability + + :param slot: slot ID of slot to query + :param capability_id: capability ID + :return: result code, CK_ULONG representing capability active or not + """ + slot_id = CK_SLOT_ID(slot) + cap_id = CK_ULONG(capability_id) + cap_val = CK_ULONG() + ret = CA_GetHSMCapabilitySetting(slot_id, cap_id, pointer(cap_val)) + return ret, cap_val.value + + +ca_get_hsm_capability_setting_ex = make_error_handle_function(ca_get_hsm_capability_setting) + + +def ca_get_hsm_policy_set(slot): + """ + Get the policies of the given slot. + + :param int slot: Target slot number + :return: retcode, {id: val} dict of policies (None if command failed) + """ + slot_id = CK_SLOT_ID(slot) + pol_ids = AutoCArray() + pol_vals = AutoCArray() + + @refresh_c_arrays(1) + def _ca_get_hsm_policy_set(): + """Closure for retries. + """ + return CA_GetHSMPolicySet(slot_id, pol_ids.array, pol_ids.size, + pol_vals.array, pol_vals.size) + + ret = _ca_get_hsm_policy_set() + + return ret, dict(list(zip(pol_ids, pol_vals))) + + +ca_get_hsm_policy_set_ex = make_error_handle_function(ca_get_hsm_policy_set) + + +def ca_get_hsm_policy_setting(slot, policy_id): + """ + Get the value of a single policy + + :param slot: slot ID of slot to query + :param policy_id: policy ID + :return: result code, CK_ULONG representing policy active or not + """ + slot_id = CK_SLOT_ID(slot) + pol_id = CK_ULONG(policy_id) + pol_val = CK_ULONG() + ret = CA_GetHSMPolicySetting(slot_id, pol_id, pointer(pol_val)) + return ret, pol_val.value + + +ca_get_hsm_policy_setting_ex = make_error_handle_function(ca_get_hsm_policy_setting) diff --git a/pycryptoki/luna_threading.py b/pycryptoki/luna_threading.py index 71b89d0..cdeddd8 100755 --- a/pycryptoki/luna_threading.py +++ b/pycryptoki/luna_threading.py @@ -78,7 +78,7 @@ def run(self): except Exception as e: self._return = e self.queue.task_done() - print sys.exc_info()[0] + print(sys.exc_info()[0]) raise if self._return == True: diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 22444ba..53ff75c 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -70,9 +70,9 @@ def __new__(cls, mech_type="UNKNOWN", params=None): if cls == Mechanism: mech_cls = MECH_LOOKUP.get(mech_type, NullMech) - return super(Mechanism, cls).__new__(mech_cls, mech_type, params) + return super(Mechanism, cls).__new__(mech_cls) else: - return super(Mechanism, cls).__new__(cls, mech_type, params) + return super(Mechanism, cls).__new__(cls) def __init__(self, mech_type="UNKNOWN", params=None): self.mech_type = mech_type @@ -294,7 +294,7 @@ def to_c_mech(self): gcm_params.pIv = cast(ivdata, CK_BYTE_PTR) gcm_params.ulIvLen = ivlen # Assuming 8 bits per entry in IV. - gcm_params.ulIvBits = CK_ULONG(len(self.params['iv'] * 8)) + gcm_params.ulIvBits = CK_ULONG(len(self.params['iv']) * 8) aad, aadlen = to_byte_array(self.params['AAD']) gcm_params.pAAD = cast(aad, CK_BYTE_PTR) gcm_params.ulAADLen = aadlen diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index d33b641..ee27243 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -21,7 +21,7 @@ from .mechanism import Mechanism from .mechanism import NullMech from .sign_verify import do_multipart_sign_or_digest -from .test_functions import make_error_handle_function +from .test_functions import make_error_handle_function, integer_types def c_generate_random(h_session, length): @@ -32,11 +32,12 @@ def c_generate_random(h_session, length): :returns: The result code, A string of random data """ - random_data = cast(create_string_buffer("", length), CK_BYTE_PTR) - ret = C_GenerateRandom(h_session, random_data, CK_ULONG(length)) - char_array = random_data._objects.values()[0] - random_string = string_at(char_array, len(char_array)) + random_data = create_string_buffer(b"", length) + data_ptr = cast(random_data, CK_BYTE_PTR) + ret = C_GenerateRandom(h_session, data_ptr, CK_ULONG(length)) + + random_string = random_data.value return ret, random_string @@ -52,7 +53,7 @@ def c_seed_random(h_session, seed): """ seed_bytes = cast(create_string_buffer(seed), CK_BYTE_PTR) - if isinstance(seed, (int, float, long)): + if isinstance(seed, (integer_types, float)): seed_length = seed else: seed_length = CK_ULONG(len(seed)) @@ -87,7 +88,7 @@ def c_digest(h_session, data_to_digest, digest_flavor, mech=None, extra_params=N # Initialize Digestion ret = C_DigestInit(h_session, mech) if ret != CKR_OK: - return ret + return ret, None # if a list is passed out do an digest operation on each string in the list, otherwise just # do one digest operation diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 99307c9..8449ae0 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -52,7 +52,7 @@ def c_get_attribute_value(h_session, h_object, template): """ c_struct = Attributes(template).get_c_struct() - unknown_key_vals = [key for key, value in template.iteritems() if value is None] + unknown_key_vals = [key for key, value in template.items() if value is None] if unknown_key_vals: LOG.debug("Retrieving Attribute Length for keys %s", unknown_key_vals) # We need to get the size of the target memory area first, then diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py index 7447bfc..4a1fdd6 100644 --- a/pycryptoki/partition_management.py +++ b/pycryptoki/partition_management.py @@ -2,6 +2,7 @@ Functions for managing partitions """ import logging +from functools import reduce from _ctypes import pointer from ctypes import byref, c_ubyte @@ -155,7 +156,7 @@ def _get_container_caps(): ret = _get_container_caps() - return ret, dict(zip(cap_ids, cap_vals)) + return ret, dict(list(zip(cap_ids, cap_vals))) ca_get_container_capability_set_ex = make_error_handle_function(ca_get_container_capability_set) @@ -211,7 +212,7 @@ def _ca_get_container_policy_set(): ret = _ca_get_container_policy_set() - return ret, dict(zip(pol_ids, pol_vals)) + return ret, dict(list(zip(pol_ids, pol_vals))) ca_get_container_policy_set_ex = make_error_handle_function(ca_get_container_policy_set) @@ -348,7 +349,7 @@ def ca_get_container_status(slot, h_container): if ((status_flags.value ^ mask) >> i) & 1: unknown_flags.append(2 ** i) raise Exception("Found unknown flags! {}".format(' '.join(unknown_flags))) - for key, flag in flags_dict.iteritems(): + for key, flag in flags_dict.items(): flags_dict[key] = 1 if key & status_flags.value else 0 failed_logins_dict = { @@ -356,9 +357,9 @@ def ca_get_container_status(slot, h_container): 'failed_user_logins': failed_user_logins.value, 'failed_limited_user_logins': failed_limited_user_logins.value } - for key, val in failed_logins_dict.iteritems(): + for key, val in failed_logins_dict.items(): if not val ^ int('1' * 64, 2) or not val ^ int('1' * 32, 2): - failed_logins_dict[key] = -1L + failed_logins_dict[key] = -1 return ret, flags_dict, failed_logins_dict @@ -399,8 +400,8 @@ def ca_set_container_policies(h_session, h_container, policies): """ h_sess = CK_SESSION_HANDLE(h_session) container_id = CK_ULONG(h_container) - pol_id_list = policies.keys() - pol_val_list = policies.values() + pol_id_list = list(policies.keys()) + pol_val_list = list(policies.values()) pol_ids = AutoCArray(data=pol_id_list, ctype=CK_ULONG) pol_vals = AutoCArray(data=pol_val_list, ctype=CK_ULONG) diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index c3f1e26..65d829d 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -1,3 +1,5 @@ +from __future__ import print_function + """ Contains both a local and remote pycryptoki client """ @@ -44,12 +46,12 @@ def f_retry(*args, **kwargs): while mtries > 1: try: return f(*args, **kwargs) - except ExceptionToCheck, e: + except ExceptionToCheck as e: msg = "%s, Retrying in %d seconds..." % (str(e), mdelay) if logger: logger.warning(msg) else: - print msg + print(msg) time.sleep(mdelay) mtries -= 1 mdelay *= backoff @@ -81,7 +83,7 @@ def wrapper(self, *args, **kwargs): return wrapper -class RemotePycryptokiClient: +class RemotePycryptokiClient(object): """Class to handle connecting to a remote Pycryptoki RPYC daemon. After instantiation, you can use it directly to make calls to a remote @@ -155,7 +157,7 @@ def wrapper(*args, **kwargs): masked_kwargs = kwargs if any(x in name for x in ("login", "create_container")): masked_args = tuple("*" for _ in args) - masked_kwargs = {key: "*" for key, _ in kwargs.items()} + masked_kwargs = {key: "*" for key, _ in list(kwargs.items())} masked_args = ["{:.10}".format(str(arg)) for arg in masked_args] masked_kwargs = ["{:.10}".format(str(kwarg)) for kwarg in masked_kwargs] diff --git a/pycryptoki/return_values.py b/pycryptoki/return_values.py index 8a477a7..b814c42 100755 --- a/pycryptoki/return_values.py +++ b/pycryptoki/return_values.py @@ -10,7 +10,7 @@ """ -from defines import * +from .defines import * ret_vals_dictionary = { CKR_OK: 'CKR_OK', diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index f12c1c7..e75d619 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -88,7 +88,7 @@ def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): """ # OPEN SESSION - arg3 = create_string_buffer("Application") + arg3 = create_string_buffer(b"Application") h_session = CK_SESSION_HANDLE() arg3 = cast(arg3, c_void_p) # CFUNCTYPE(CK_RV, CK_SESSION_HANDLE, CK_NOTIFICATION, CK_VOID_PTR) @@ -117,11 +117,11 @@ def login(h_session, slot_num=1, password=None, user_type=1): LOG.info("C_Login: " "user_type=%s, " "slot=%s, " - "password=%s", user_type, slot_num, password) + "password=***", user_type, slot_num) if password == '': password = None - user_type = CK_USER_TYPE(long(user_type)) + user_type = CK_USER_TYPE(user_type) password = AutoCArray(data=password, ctype=CK_BYTE) ret = C_Login(h_session, user_type, password.array, password.size.contents) @@ -195,8 +195,8 @@ def c_get_token_info(slot_id): c_char_p).value)[0:32].strip() token_info['model'] = str(cast(c_token_info.model, c_char_p).value)[0:16].strip() - token_info['serialNumber'] = int(str(cast(c_token_info.serialNumber, - c_char_p).value)[0:16].strip()) + token_info['serialNumber'] = str(cast(c_token_info.serialNumber, + c_char_p).value)[0:16].strip() token_info['flags'] = c_token_info.flags token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 2008fd0..917a46e 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -103,7 +103,7 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, plain_data_len = len(_get_string_from_list(input_data_list)) remaining_length = plain_data_len - python_string = '' + python_string = b'' i = 0 while remaining_length > 0: current_chunk = input_data_list[i] @@ -128,13 +128,12 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, # Finalizing multipart decrypt operation out_data_len = CK_ULONG(max_data_chunk_size) - output = cast(create_string_buffer("", out_data_len.value), CK_BYTE_PTR) + output = cast(create_string_buffer(b"", out_data_len.value), CK_BYTE_PTR) ret = c_final_function(h_session, output, byref(out_data_len)) # Get output - ck_char_array = output._objects.values()[0] if out_data_len.value > 0: - python_string += string_at(ck_char_array, len(ck_char_array))[0:out_data_len.value] + python_string += string_at(output, out_data_len.value) return ret, python_string diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 41dbd7c..95a53c1 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -1,12 +1,17 @@ """ Functions used for testing, or verifying return values. """ - +import sys import inspect import logging from ctypes import byref from functools import wraps +if sys.version_info < (3,): + integer_types = (int, long,) +else: + integer_types = (int,) + from .cryptoki import CK_OBJECT_HANDLE, CK_ULONG, C_GetObjectSize from .defines import CKR_OBJECT_HANDLE_INVALID from .defines import CKR_OK @@ -227,7 +232,7 @@ def luna_function_exception_handle(*args, **kwargs): else: return_data = return_tuple[0] ret = return_tuple[0] - elif isinstance(return_tuple, long): + elif isinstance(return_tuple, integer_types): ret = return_tuple return_data = return_tuple else: diff --git a/pycryptoki/tests/stress/__init__.py b/pycryptoki/tests/stress/__init__.py deleted file mode 100755 index e69de29..0000000 diff --git a/pycryptoki/tests/stress/conftest.py b/pycryptoki/tests/stress/conftest.py deleted file mode 100755 index df7076f..0000000 --- a/pycryptoki/tests/stress/conftest.py +++ /dev/null @@ -1,32 +0,0 @@ -""" - This allows for configuration of the designated test/testdir - - Currently this adds custom command args (see below) to py.test interface for this test/directory -""" - -from pycryptoki.defaults import DEFAULT_UTILS_PATH -from pycryptoki.utils.common_utils import setLogFile - - -def pytest_addoption(parser): - parser.addoption("--tslot", help="This is the token slot we wish to target ", - type=int, default=1) - parser.addoption("--vdevice", metavar='device', - help="Target device we want to use i.e. /dev/viper0 or /dev/viper1", - default="/dev/viper0") - parser.addoption("--upath", metavar='path', - help="Path to where the utils are stored: vrest, dumpit", - default=DEFAULT_UTILS_PATH) - parser.addoption("--logfile", help="name of log to store output", - default=setLogFile()) - -def pytest_funcarg__logfile(request): - return request.config.option.logfile - -def pytest_funcarg__vdevice(request): - return request.config.option.vdevice - -def pytest_funcarg__upath(request): - return request.config.option.upath - -def pytest_funcarg__tslot(request): - return request.config.option.tslot diff --git a/pycryptoki/tests/stress/setup.cfg b/pycryptoki/tests/stress/setup.cfg deleted file mode 100755 index ba68f97..0000000 --- a/pycryptoki/tests/stress/setup.cfg +++ /dev/null @@ -1,3 +0,0 @@ -# content of setup.cfg -[pytest] -addopts = -s \ No newline at end of file diff --git a/pycryptoki/tests/stress/test_multi_reset.py b/pycryptoki/tests/stress/test_multi_reset.py deleted file mode 100755 index df3e475..0000000 --- a/pycryptoki/tests/stress/test_multi_reset.py +++ /dev/null @@ -1,354 +0,0 @@ -import argparse -import logging -import os -import sys -import threading -from ctypes import * -from pycryptoki.utils.common_utils import setLogFile -from random import randint - -from pycryptoki.cryptoki import CK_SLOT_ID, CA_GetObjectUID, \ - CA_GetUserContainerNumber, CA_GetObjectHandle, \ - CK_ULONG, CK_BYTE -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ - CKM_GENERIC_SECRET_KEY_GEN_TEMP, \ - CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, CKM_RC4_KEY_GEN_TEMP, \ - CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, \ - CKM_ARIA_KEY_GEN_TEMP, CKM_DH_PKCS_PARAMETER_GEN_TEMP -from pycryptoki.defaults import DEFAULT_PASSWORD, DEFAULT_LABEL -from pycryptoki.defaults import DEFAULT_UTILS_PATH, FORMAT -from pycryptoki.defines import CKF_SERIAL_SESSION, CKF_RW_SESSION, \ - CKF_SO_SESSION -from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, \ - CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN, \ - CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, CKM_RC5_KEY_GEN, \ - CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ - CKM_ARIA_KEY_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKR_OK, \ - CKR_DEVICE_ERROR, CK_CRYPTOKI_ELEMENT -from pycryptoki.key_generator import c_destroy_object, c_generate_key -from pycryptoki.session_management import c_initialize, c_finalize, \ - c_close_all_sessions_ex, ca_factory_reset_ex, c_open_session_ex, login_ex, \ - c_get_token_info_ex, c_init_pin_ex, c_logout_ex, c_close_session_ex, c_finalize_ex -from pycryptoki.test_functions import verify_object_attributes, verify_object_exists -from pycryptoki.tests import ResetThread -from pycryptoki.token_management import get_token_by_label_ex, c_init_token_ex - -#Global Scope -logger = logging.getLogger(__name__) - -class MultiResetDuringKeyGen: - """ """ - def __init__(self, slot): - self.slot = slot - self.h_session = 0 - #Setup events - self.trigger = threading.Event() - self.complete = threading.Event() - #Keygen options - 13 options randomly selected - self.keytype_and_template_list = [(CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), - (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), - (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), - (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), - (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP), - (CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_PARAMETER_GEN_TEMP)] - - def close_off(self): - """ """ - c_logout_ex(self.h_session) - c_close_session_ex(self.h_session) - c_finalize_ex() - - def getDefltLabel(self): - """ """ - label = DEFAULT_LABEL+str(self.slot) - return label - - def gen_verify_clean(self, vdevice, upath): - """This method is the core of the test case. - The purpose being to continually generate keys until a random reset causes a DEVICE_ERROR to be returned - at which point we capture the exception generated, and verify the objects that were created. - Once a certain number of keys (currently set to 20000) are generated we delete and repeat the process - - :param vdevice: - :param upath: - - """ - cntNum = CK_ULONG() - generated_objects = [] - logger.info("--- Starting Test ---") - rthread = ResetThread(self.trigger, self.complete,vdevice, upath, logger) - ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) - logger.info("Container Number:[%s]" % str(cntNum)) - if ret != CKR_OK: - rthread.join(1) - logger.info("Error: could not get container number[%s]" % str(cntNum)) - exit(-1) - rthread.start() - self.trigger.set() - self.complete.clear() - for outer in range (1, 1000): - logger.info("**** Iteration: %d *****" % outer) - for num in range (1, 20000): - # Creation stage - ouid = (CK_BYTE*12)() - try: - type_of_keygen = randint(0,12) - #Generate random key type with associated template - gen_ret, hdl = c_generate_key(self.h_session, self.keytype_and_template_list[type_of_keygen][0], self.keytype_and_template_list[type_of_keygen][1]) - if gen_ret == CKR_DEVICE_ERROR: - raise Exception('keygen') - ouid_ret = CA_GetObjectUID(CK_SLOT_ID(self.slot),cntNum,CK_ULONG(CK_CRYPTOKI_ELEMENT),CK_ULONG(hdl),ouid) - if ouid_ret == CKR_DEVICE_ERROR: - raise Exception('ouid') - if ouid_ret == CKR_OK and gen_ret == CKR_OK: - self.trigger.set() - #Store off the object OUID and the template used for keygen - generated_objects.append((ouid,self.keytype_and_template_list[type_of_keygen][1])) - logger.debug("Entry Info: hdl[%d]:num[%d]:ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" % - (hdl,num,ouid[0],ouid[1],ouid[2],ouid[3],ouid[4],ouid[5],ouid[6], - ouid[7],ouid[8], ouid[9], ouid[10], ouid[11])) - except Exception as e: - self.trigger.clear() - msg = e.args[0] - logger.info("Exception:[%s] on entry [%d]" % (msg,num)) - if msg != 'keygen' and msg != 'ouid': - rthread.join(1) - logger.info("Unexpected exception:[%s] - exiting!" % msg) - exit(-1) - if msg == 'keygen': - logger.info("Create: Keygen errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) - if msg == 'ouid': - logger.info("Create: OUID lookup errored out with DEVICE_ERROR on entry [%d]:hdl[%d]" % (num,hdl)) - logger.info("Waiting to verify %d objects" % len(generated_objects)) - self.complete.wait() - self.complete.clear() - self.h_session = c_open_session_ex(self.slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) - login_ex(self.h_session, self.slot, DEFAULT_PASSWORD, 1) - logger.info("Start verification of %d objects" % len(generated_objects)) - ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) - logger.info("Container Number:[%s]" % str(cntNum)) - if ret != CKR_OK: - rthread.join(1) - logger.info("Error: could not get container number[%s]" % str(cntNum)) - exit(-1) - ''' - Verify object that are generated - TODO: Make this set of operations more intensive. - For example: - Encrypt/Decrypt data blob on alternating vreset iterations. - Create EC keys, keypairs etc - ''' - for kouid, temp in generated_objects: - - key = CK_ULONG() - oType = CK_ULONG() - ret = CA_GetObjectHandle(CK_SLOT_ID(self.slot), cntNum, - kouid, byref(oType), - byref(key)) - if ret != CKR_OK: - logger.debug("Verify: Error: could not get handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" - % (key.value,kouid[0],kouid[1],kouid[2],kouid[3],kouid[4],kouid[5],kouid[6], - kouid[7],kouid[8], kouid[9], kouid[10], kouid[11])) - rthread.join(1) - sys.exc_clear() - exit(-1) - logger.debug("Verify: handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" - % (key.value,kouid[0],kouid[1],kouid[2],kouid[3],kouid[4],kouid[5],kouid[6], - kouid[7],kouid[8], kouid[9], kouid[10], kouid[11])) - verify_object_exists(self.h_session, key.value, True) - verify_object_attributes(self.h_session, key.value, temp) - logger.info("Completed verification of %d objects" % len(generated_objects)) - # Clear the memory of the exception - sys.exc_clear() - continue - #Clean-up the objects for this iteration - self.trigger.clear() - delcount = 0 - store_count = len(generated_objects) - #Delete objects which are generated - while len(generated_objects): - key = CK_ULONG() - oType = CK_ULONG() - douid, temp = generated_objects.pop() - try: - gethdl_ret = CA_GetObjectHandle(CK_SLOT_ID(self.slot), cntNum, - douid, byref(oType), - byref(key)) - if gethdl_ret == CKR_DEVICE_ERROR: - raise Exception('get_hdl') - dest_ret = c_destroy_object(self.h_session, key.value) - if dest_ret == CKR_DEVICE_ERROR: - raise Exception('destroy') - if dest_ret == CKR_OK and gethdl_ret == CKR_OK: - delcount+=1 - except Exception as e: - self.trigger.clear() - msg = e.args[0] - logger.info("Exception:[%s] on entry [%d]" % (msg,delcount)) - if msg != 'get_hdl' and msg != 'destroy': - rthread.join(1) - logger.info("Unexpected exception:[%s] - exiting!" % msg) - exit(-1) - if msg == 'get_hdl': - logger.info("Delete: Error: could not get handle[%d] for ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" - % (key.value, douid[0],douid[1],douid[2],douid[3],douid[4],douid[5],douid[6], - douid[7],douid[8], douid[9], douid[10], douid[11])) - if msg == 'destroy': - logger.info("Delete: Error: failed to delete entry [%d] with ouid[%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x]" - % (key.value, douid[0],douid[1],douid[2],douid[3],douid[4],douid[5],douid[6], - douid[7],douid[8], douid[9], douid[10], douid[11])) - self.complete.wait() - self.complete.clear() - self.h_session = c_open_session_ex(CK_SLOT_ID(self.slot), CKF_SERIAL_SESSION | CKF_RW_SESSION) - login_ex(self.h_session, self.slot, DEFAULT_PASSWORD, 1) - ret = CA_GetUserContainerNumber(CK_SLOT_ID(self.slot),byref(cntNum)) - logger.debug("Container Number:[%s]" % str(cntNum)) - if ret != CKR_OK: - rthread.join(1) - logger.info("Error: could not get container number[%s]" % str(cntNum)) - exit(-1) - # Clear the memory of the exception - sys.exc_clear() - continue - logger.info("Deleted: %d of %d Objects" % (delcount,store_count)) - self.trigger.set() - rthread.join(1) - logger.info("--- Ending Test ---") - - def setup_for_test(self, initialize_admin_token, initialize_users, slot): - """A common setup for the configurable roles tests - - :param initialize_admin_token: Whether or not to initialize the admin partition - :param initialize_users: Whether or not to initialize the PIN's of the users - :param slot: Token slot to target - - """ - c_initialize() - - #Factory Reset - logger.info(slot) - # NOTE: This is required always. - c_close_all_sessions_ex(slot) - ca_factory_reset_ex(slot) - - #Initialize the Token - session_flags = (CKF_SERIAL_SESSION | CKF_RW_SESSION | CKF_SO_SESSION) - if initialize_admin_token: - h_session = c_open_session_ex(slot, session_flags) - c_init_token_ex(slot, DEFAULT_PASSWORD, self.getDefltLabel() ) - c_finalize() - c_initialize() - if initialize_users and initialize_admin_token: - islot = get_token_by_label_ex(self.getDefltLabel()) - logger.info("Slot by Label:" + str(islot)) - c_close_all_sessions_ex(islot) - self.h_session = c_open_session_ex(islot, session_flags) - logger.info("Session Handle:" + str(self.h_session)) - login_ex(self.h_session, islot, DEFAULT_PASSWORD, 0) - logger.info(c_get_token_info_ex(islot)) - c_init_pin_ex(self.h_session, DEFAULT_PASSWORD) - c_logout_ex(self.h_session) - c_close_all_sessions_ex(islot) - self.h_session = c_open_session_ex(islot, CKF_SERIAL_SESSION | CKF_RW_SESSION) - login_ex(h_session, islot, DEFAULT_PASSWORD, 1) - logger.info(c_get_token_info_ex(islot)) - -''' -Get the command line args provided as input for test application/case -''' -def get_cmd_args(): - """ """ - parser = argparse.ArgumentParser() - parser.add_argument("--tslot", help="This is the token slot we wish to target ", - type=int, default=1) - parser.add_argument("--vdevice", metavar='device', - help="Target device we want to use i.e. viper0 or viper1", - default="/dev/viper0") - parser.add_argument("--upath", metavar='path', - help="Path to where the utils are stored: vrest, dumpit", - default=DEFAULT_UTILS_PATH) - parser.add_argument("--logfile", help="name of log to store output", - default=setLogFile()) - args = parser.parse_args() - print args - # Check if basic dependencies are present - populated_dev_path = args.vdevice - try: - os.stat(populated_dev_path) - except OSError as e: - print "Startup: Exception: Device node [%s] not present in [%s] - [%s]" % (args.vdevice,populated_dev_path, e.args) - exit(-1) - valid_vreset_path = args.upath + "/vreset" - try: - os.stat(valid_vreset_path) - except OSError as e: - print "Startup: Exception: Invalid utils path [%s] or vreset not present [%s]" % (args.upath, e.args) - exit(-1) - valid_dumpit_path = args.upath + "/dumpit" - try: - os.stat(valid_dumpit_path) - except OSError as e: - print "Startup: Exception: Invalid utils path [%s] or dumpit not present[%s]" % (args.upath, e.args) - exit(-1) - return args - -''' - Setup logging structure - ''' -def config_logging(args): - """ - - :param args: - - """ - print args - logging.basicConfig(format=FORMAT,filename=args.logfile,level=logging.DEBUG,) - - # define a Handler which writes INFO messages or higher to the sys.stderr - console = logging.StreamHandler() - console.setLevel(logging.INFO) - # set a format for logging - formatter = logging.Formatter(FORMAT) - # tell the handler to use this format - console.setFormatter(formatter) - # add the handler to the root logger - logging.getLogger('').addHandler(console) - -''' -PyTest Entry Point: -NOTE: In order to enable console output to the py.test when running this test provide the following in setup.cfg - # content of setup.cfg - [pytest] - addopts = -s -''' -def test_gen_verify_clean(): - """ """ - args = get_cmd_args() - config_logging(args) - Reset = MultiResetDuringKeyGen(args.tslot) - Reset.setup_for_test(True, True, args.tslot) - Reset.gen_verify_clean(args.vdevice, args.upath) - Reset.close_off() - -''' -Application Entry Point: -Call directly from the command line: - python -''' -if __name__ == '__main__': - test_gen_verify_clean() - - - - - - - diff --git a/pycryptoki/tests/stress/vreset_thread.py b/pycryptoki/tests/stress/vreset_thread.py deleted file mode 100755 index d0686c6..0000000 --- a/pycryptoki/tests/stress/vreset_thread.py +++ /dev/null @@ -1,61 +0,0 @@ -import os -import threading -import time -import subprocess -from random import randint - -# Reset Thread class - wanted to be able to stop thread on error -class ResetThread(threading.Thread): - """Input parameters for this class are: - trigger: the event to initiate the reset operation - thread waits on this event - complete: the event to tell the external world that the reset has complete - device: the target device node to reset - upath: the path to the driver utils i.e. vreset and dumpit - - - """ - def __init__(self, trigger, complete, device, upath, logger): - super(ResetThread, self).__init__() - self.trigger = trigger - self.complete = complete - self.stoprequest = threading.Event() - self.count = 0 - self.device = device - self.upath = upath - self.logger = logger - - def run(self): - """ """ - while not self.stoprequest.isSet(): - self.count += 1 - self.trigger.wait() - delay = randint(1,20) - time.sleep(delay) - self.logger.info("Trigger vreset: %d on device [%s]" % (self.count, self.device)) - cmd = self.upath + "/vreset " + self.device - val = os.system(cmd) - if val == 0: - self.complete.set() - else: - self.complete.clear() - self.logger.info("-----Vreset Failed: [%d] on device [%s]-------" % (val,self.device)) - proc_dump = subprocess.Popen([self.upath + str("/dumpit"), self.device], stdout=subprocess.PIPE, shell=True) - (dump_out, dump_err) = proc_dump.communicate() - self.logger.debug("DUMPIT OUTPUT: stdout") - self.logger.debug(dump_out) - self.logger.debug("DUMPIT ERROR: stderr") - self.logger.debug(dump_err) - tail_proc = subprocess.Popen([str("tail -n 100 "), str("/var/log/messages")], stdout=subprocess.PIPE, shell=True) - (tail_out, tail_err) = tail_proc.communicate() - self.logger.debug("TAIL OUTPUT: stdout") - self.logger.debug(tail_out) - self.logger.debug("TAIL ERROR: stderr") - self.logger.debug(tail_err) - def join(self, timeout=None): - """ - - :param timeout: (Default value = None) - - """ - self.stoprequest.set() - super(ResetThread, self).join(timeout) diff --git a/pycryptoki/tests/unittests/__init__.py b/pycryptoki/tests/unittests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index 9af4904..d8de768 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -152,7 +152,7 @@ def _get_token_policies(): ret = _get_token_policies() - return ret, dict(zip(pol_ids, pol_vals)) + return ret, dict(list(zip(pol_ids, pol_vals))) ca_get_token_policies_ex = make_error_handle_function(ca_get_token_policies) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..76f22f3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +rpyc +hypothesis +pytest +future +mock diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..b7e4789 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[aliases] +test=pytest diff --git a/setup.py b/setup.py index 50b09b0..3dbb3eb 100755 --- a/setup.py +++ b/setup.py @@ -1,19 +1,22 @@ -''' +""" Script used by distutils to automatically generate a source code distribution of this python module (a .tar.gz file containing all of the source code). To generate this file run: python setup.py sdist -''' -from distutils.core import setup +""" +from setuptools import setup + setup(name='pycryptoki', description="A python wrapper around the C cryptoki library.", author='Ashley Straw', url='https://github.com/gemalto/pycryptoki', version='1.0', packages=['pycryptoki', - 'pycryptoki.daemon', - 'pycryptoki.utils'], - scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'] + 'pycryptoki.daemon'], + scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'], + setup_requires=['pytest-runner'], + tests_require=['pytest', 'hypothesis', 'mock'], + requires=['future', 'rpyc'] ) diff --git a/pycryptoki/tests/functional/__init__.py b/tests/functional/__init__.py similarity index 100% rename from pycryptoki/tests/functional/__init__.py rename to tests/functional/__init__.py diff --git a/pycryptoki/tests/functional/conftest.py b/tests/functional/conftest.py similarity index 76% rename from pycryptoki/tests/functional/conftest.py rename to tests/functional/conftest.py index af5f8a9..49d6e21 100644 --- a/pycryptoki/tests/functional/conftest.py +++ b/tests/functional/conftest.py @@ -1,21 +1,33 @@ """ Fixtures for pycryptoki functional tests """ +import logging import os +import sys + +# From http://stackoverflow.com/a/7759927 +if sys.version_info < (3,): + def b(x): + return x +else: + import codecs + + def b(x): + return codecs.latin_1_encode(x)[0] import pytest -import logging -from ...attributes import Attributes -from ...key_generator import c_destroy_object -from ...object_attr_lookup import c_find_objects_ex + from . import config as hsm_config -from ...defaults import ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL, CO_PASSWORD -from ...defines import CKF_RW_SESSION, CKF_SERIAL_SESSION, CKF_PROTECTED_AUTHENTICATION_PATH, CKR_OK -from ...defines import CKF_SO_SESSION -from ...session_management import c_initialize_ex, c_close_all_sessions_ex, \ +from pycryptoki.attributes import Attributes +from pycryptoki.defaults import ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL, CO_PASSWORD +from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION, CKF_PROTECTED_AUTHENTICATION_PATH, CKR_OK +from pycryptoki.defines import CKF_SO_SESSION +from pycryptoki.key_generator import c_destroy_object +from pycryptoki.object_attr_lookup import c_find_objects_ex +from pycryptoki.session_management import c_initialize_ex, c_close_all_sessions_ex, \ ca_factory_reset_ex, c_open_session_ex, login_ex, c_finalize_ex, \ c_close_session, c_logout, c_get_token_info_ex -from ...token_management import c_init_token_ex +from pycryptoki.token_management import c_init_token_ex LOG = logging.getLogger(__name__) @@ -46,20 +58,34 @@ def pytest_addoption(parser): optiongroup.addoption("--copassword", help="Password for the Crypto Officer user/slot. Can be None for " "PED-authentication.", - action="store") + action="store", + type=str) optiongroup.addoption("--user", help="User type to test with. Defaults to SO. Can also test w/ " "Crypto Officer", choices=["SO", "CO"], default="SO", action="store") + optiongroup.addoption("--loglevel", + help="Specify what level of logging to run the tests ", + choices=["debug", "info", "warning", "error"], + default="warning") def pytest_configure(config): """ Set up the globals for this test run. """ + if config.getoption("loglevel", None): + logger = logging.getLogger() + log_formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s: %(message)s') + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(log_formatter) + logger.addHandler(console_handler) + logger.setLevel(config.getoption("loglevel").upper()) + hsm_config["test_slot"] = config.getoption("test_slot") + hsm_config["user"] = config.getoption("user") c_initialize_ex() try: # Factory Reset @@ -77,6 +103,11 @@ def pytest_configure(config): admin_pwd = config.getoption("password") co_pwd = config.getoption("copassword", default=CO_PASSWORD) + if admin_pwd: + admin_pwd = b(admin_pwd) + if co_pwd: + co_pwd = b(co_pwd) + hsm_config['admin_pwd'] = admin_pwd hsm_config['co_pwd'] = co_pwd diff --git a/pycryptoki/tests/functional/test_cka_start_and_end.py b/tests/functional/test_cka_start_and_end.py similarity index 86% rename from pycryptoki/tests/functional/test_cka_start_and_end.py rename to tests/functional/test_cka_start_and_end.py index d992f41..d88d570 100755 --- a/pycryptoki/tests/functional/test_cka_start_and_end.py +++ b/tests/functional/test_cka_start_and_end.py @@ -1,26 +1,25 @@ import logging -import os from datetime import datetime import pytest from . import config as hsm_config -from ...audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex -from ...default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 -from ...defaults import CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL -from ...defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ +from pycryptoki.audit_handling import ca_init_audit_ex, ca_time_sync_ex, ca_get_time_ex +from pycryptoki.default_templates import dsa_prime_1024_160, dsa_sub_prime_1024_160, dsa_base_1024_160 +from pycryptoki.defaults import CO_PASSWORD, AUDITOR_PASSWORD, AUDITOR_LABEL +from pycryptoki.defines import CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_DES, CKA_TOKEN, \ CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, \ CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LABEL, \ CKA_MODIFIABLE, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, \ CKK_AES, CKM_DES_ECB, CKR_KEY_NOT_ACTIVE, CKM_RSA_PKCS_KEY_PAIR_GEN, \ CKM_RSA_PKCS, CKM_AES_ECB, CKM_AES_KEY_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA_SHA1 -from ...defines import CKF_SERIAL_SESSION, CKM_DES_KEY_GEN, CKU_USER, \ +from pycryptoki.defines import CKF_SERIAL_SESSION, CKM_DES_KEY_GEN, CKU_USER, \ CKA_END_DATE, CKU_AUDIT, CKF_AUDIT_SESSION -from ...encryption import c_encrypt, c_encrypt_ex -from ...key_generator import c_generate_key_ex, c_generate_key_pair_ex -from ...session_management import login, c_open_session_ex, login_ex, \ +from pycryptoki.encryption import c_encrypt, c_encrypt_ex +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.session_management import login, c_open_session_ex, login_ex, \ c_logout_ex, c_close_session_ex -from ...sign_verify import c_sign_ex, c_sign +from pycryptoki.sign_verify import c_sign_ex, c_sign logger = logging.getLogger(__name__) @@ -50,10 +49,7 @@ def test_symmetric_key_expiry_des(self): "specified in \ CKA_END_DATE attribute") - end_d = {} - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" + end_d = {'year': b"2013", 'month': b"12", 'day': b"31"} CKM_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_DES, @@ -69,13 +65,13 @@ def test_symmetric_key_expiry_des(self): CKA_DERIVE: True, CKA_VALUE_LEN: 8, CKA_EXTRACTABLE: True, - CKA_LABEL: "DES Key", + CKA_LABEL: b"DES Key", CKA_END_DATE: end_d} h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, "a" * 512) + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, b"a" * 512) c_logout_ex(self.h_session) c_close_session_ex(self.h_session) @@ -102,7 +98,7 @@ def test_symmetric_key_expiry_des(self): h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - return_val = c_encrypt(h_session, CKM_DES_ECB, h_key, "This is some data to sign .. ") + return_val = c_encrypt(h_session, CKM_DES_ECB, h_key, b"This is some data to sign .. ") assert return_val == CKR_KEY_NOT_ACTIVE, "return value should be CKR_KEY_NOT_ACTIVE" c_logout_ex(h_session) @@ -124,10 +120,7 @@ def test_symmetric_key_expiry_aes(self): logger.info("Test: Verify that user is not able to use the symmetric aes object after " "date specified in \ CKA_END_DATE attribute") - end_d = {} - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" + end_d = {'year': b"2013", 'month': b"12", 'day': b"31"} CKM_KEY_GEN_TEMP = {CKA_CLASS: CKO_SECRET_KEY, CKA_KEY_TYPE: CKK_AES, @@ -143,13 +136,13 @@ def test_symmetric_key_expiry_aes(self): CKA_DERIVE: True, CKA_VALUE_LEN: 16, CKA_EXTRACTABLE: True, - CKA_LABEL: "AES Key", + CKA_LABEL: b"AES Key", CKA_END_DATE: end_d} h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, template=CKM_KEY_GEN_TEMP) logger.info("Called c-generate: Key handle -" + str(h_key)) - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, b"This is some data to sign .. ") c_logout_ex(self.h_session) c_close_session_ex(self.h_session) @@ -175,7 +168,7 @@ def test_symmetric_key_expiry_aes(self): h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - return_val = c_encrypt(h_session, CKM_AES_ECB, h_key, "This is some data to sign .. ") + return_val = c_encrypt(h_session, CKM_AES_ECB, h_key, b"This is some data to sign .. ") logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" @@ -195,10 +188,7 @@ def test_asymmetric_key_expiry_rsa(self): logger.info("Test: Verify that user is not able to use the rsa asymmetric object after " "date specified in \ CKA_END_DATE attribute") - end_d = {} - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" + end_d = {'year': b"2013", 'month': b"12", 'day': b"31"} CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, @@ -220,7 +210,7 @@ def test_asymmetric_key_expiry_rsa(self): CKA_SIGN: True, CKA_UNWRAP: True, CKA_END_DATE: end_d, - CKA_LABEL: "RSA Private Key"} + CKA_LABEL: b"RSA Private Key"} h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, @@ -230,7 +220,7 @@ def test_asymmetric_key_expiry_rsa(self): "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( h_prkey)) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b"This is some data to sign .. ") c_logout_ex(self.h_session) c_close_session_ex(self.h_session) @@ -256,7 +246,7 @@ def test_asymmetric_key_expiry_rsa(self): h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - return_val = c_encrypt(h_session, CKM_RSA_PKCS, h_pbkey, "This is some data to sign .. ") + return_val = c_encrypt(h_session, CKM_RSA_PKCS, h_pbkey, b"This is some data to sign .. ") logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" @@ -276,10 +266,7 @@ def test_asymmetric_key_expiry_dsa(self): logger.info("Test: Verify that user is not able to use the dsa asymmetric object after " "date specified in \ CKA_END_DATE attribute") - end_d = {} - end_d['year'] = "2013" - end_d['month'] = "12" - end_d['day'] = "31" + end_d = {'year': b"2013", 'month': b"12", 'day': b"31"} CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 = {CKA_TOKEN: True, CKA_PRIVATE: True, @@ -290,7 +277,7 @@ def test_asymmetric_key_expiry_dsa(self): CKA_SUBPRIME: dsa_sub_prime_1024_160, CKA_BASE: dsa_base_1024_160, CKA_END_DATE: end_d, - CKA_LABEL: "DSA 1024_160 Public Key"} + CKA_LABEL: b"DSA 1024_160 Public Key"} CKM_DSA_KEY_PAIR_GEN_PRIVTEMP = {CKA_TOKEN: True, CKA_PRIVATE: True, @@ -300,7 +287,7 @@ def test_asymmetric_key_expiry_dsa(self): CKA_UNWRAP: True, CKA_EXTRACTABLE: True, CKA_END_DATE: end_d, - CKA_LABEL: "DSA Public Key"} + CKA_LABEL: b"DSA Public Key"} h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_DSA_KEY_PAIR_GEN, pbkey_template=CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, @@ -310,7 +297,7 @@ def test_asymmetric_key_expiry_dsa(self): "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( h_prkey)) - c_sign_ex(self.h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) + c_sign_ex(self.h_session, CKM_DSA_SHA1, b"Some data to sign", h_prkey) c_logout_ex(self.h_session) c_close_session_ex(self.h_session) @@ -336,6 +323,6 @@ def test_asymmetric_key_expiry_dsa(self): h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - return_val, sig = c_sign(h_session, CKM_DSA_SHA1, "Some data to sign", h_prkey) + return_val, sig = c_sign(h_session, CKM_DSA_SHA1, b"Some data to sign", h_prkey) logger.info("Called C_Sign, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" diff --git a/pycryptoki/tests/functional/test_digest_data.py b/tests/functional/test_digest_data.py similarity index 77% rename from pycryptoki/tests/functional/test_digest_data.py rename to tests/functional/test_digest_data.py index dfba6b8..d9dc19b 100755 --- a/pycryptoki/tests/functional/test_digest_data.py +++ b/tests/functional/test_digest_data.py @@ -2,10 +2,11 @@ import pytest +from pycryptoki.return_values import ret_vals_dictionary from . import config as hsm_config -from ...defines import CKM_MD2, CKR_OK -from ...encryption import _get_string_from_list -from ...misc import c_digest +from pycryptoki.defines import CKM_MD2, CKR_OK +from pycryptoki.encryption import _get_string_from_list +from pycryptoki.misc import c_digest logger = logging.getLogger(__name__) @@ -20,16 +21,16 @@ def setup_teardown(self, auth_session): def test_digest_data(self): """Calls C_Digest on some data and makes sure there is no failure""" - data_to_digest = "Some arbitrary string" + data_to_digest = b"Some arbitrary string" ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) - assert ret == CKR_OK, "Digesting should occur with no errors" + assert ret == CKR_OK, "Digesting should occur with no errors, got {}".format(ret_vals_dictionary[ret]) assert len(digested_data) > 0, "The digested data should have a length" assert data_to_digest != digested_data, "The digested data should not be the same as the " \ "original string" def test_multipart_digest_data(self): """ """ - data_to_digest = ["Some arbitrary string", "Some second arbitrary string"] + data_to_digest = [b"Some arbitrary string", b"Some second arbitrary string"] ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) assert ret == CKR_OK, "Digesting should occur with no errors" assert len(digested_data) > 0, "The digested data should have a length" diff --git a/pycryptoki/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py similarity index 82% rename from pycryptoki/tests/functional/test_encrypt_decrypt.py rename to tests/functional/test_encrypt_decrypt.py index ca3a937..dcc6cde 100755 --- a/pycryptoki/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -1,15 +1,14 @@ import logging -import os import pytest from . import config as hsm_config -from ...default_templates import CKM_DES_KEY_GEN_TEMP -from ...defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK -from ...encryption import c_encrypt, c_decrypt, _split_string_into_list, \ +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK +from pycryptoki.encryption import c_encrypt, c_decrypt, _split_string_into_list, \ _get_string_from_list -from ...key_generator import c_generate_key_ex -from ...return_values import ret_vals_dictionary +from pycryptoki.key_generator import c_generate_key_ex +from pycryptoki.return_values import ret_vals_dictionary logger = logging.getLogger(__name__) @@ -26,7 +25,7 @@ def test_encrypt_decrypt_string(self): """Tests encrypting and decrypting a string with a key""" h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - data_to_encrypt = "a" * 0xfff0 + data_to_encrypt = b"a" * 0xfff0 ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) assert ret == CKR_OK, \ "Encryption should go through successfully, instead it returned " + \ @@ -48,11 +47,11 @@ def test_multipart_encrypt_decrypt(self): """ h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - data_to_encrypt = ['a' * 512, 'b' * 512, 'c' * 512, 'd' * 512] + data_to_encrypt = [b'a' * 512, b'b' * 512, b'c' * 512, b'd' * 512] ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + \ ret_vals_dictionary[ret] - assert len(encrypted_data) == len(_get_string_from_list(data_to_encrypt)) + assert len(encrypted_data) == len(b"".join(data_to_encrypt)) encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) diff --git a/pycryptoki/tests/functional/test_get_token_info.py b/tests/functional/test_get_token_info.py similarity index 90% rename from pycryptoki/tests/functional/test_get_token_info.py rename to tests/functional/test_get_token_info.py index 3c740c3..3078d9b 100755 --- a/pycryptoki/tests/functional/test_get_token_info.py +++ b/tests/functional/test_get_token_info.py @@ -1,17 +1,16 @@ import logging -import os import pytest from . import config as hsm_config -from ...defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD -from ...defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ +from pycryptoki.defaults import ADMIN_PARTITION_LABEL, ADMINISTRATOR_PASSWORD +from pycryptoki.defines import CKF_TOKEN_PRESENT, CKF_LOGIN_REQUIRED, \ CKF_RESTORE_KEY_NOT_NEEDED, CKF_TOKEN_INITIALIZED, CKF_SERIAL_SESSION, CKF_SO_SESSION, \ CKF_RW_SESSION -from ...session_management import ca_factory_reset_ex, \ +from pycryptoki.session_management import ca_factory_reset_ex, \ c_get_token_info_ex, c_close_all_sessions, c_close_all_sessions_ex, \ c_open_session_ex -from ...token_management import get_token_by_label_ex, c_init_token_ex +from pycryptoki.token_management import c_init_token_ex logger = logging.getLogger(__name__) diff --git a/pycryptoki/tests/functional/test_hsm_management.py b/tests/functional/test_hsm_management.py similarity index 87% rename from pycryptoki/tests/functional/test_hsm_management.py rename to tests/functional/test_hsm_management.py index 824457e..28c4973 100755 --- a/pycryptoki/tests/functional/test_hsm_management.py +++ b/tests/functional/test_hsm_management.py @@ -1,146 +1,148 @@ -""" -Test methods for pycryptoki 'hsm management' set of commands. -""" - -import pytest - -from . import config as hsm_config -from ...default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP -from ...defines import CKU_CRYPTO_USER, CKR_OK, \ - CKR_ATTRIBUTE_VALUE_INVALID, CKR_CANCEL, CKR_USER_NOT_AUTHORIZED, \ - CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_AES, CKA_TOKEN, \ - CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, \ - CKA_VERIFY, CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, \ - CKA_EXTRACTABLE, CKA_LABEL, LUNA_TTYPE_CRYPTO, LUNA_TTYPE_RNG, \ - LUNA_DSS_SIGVERIFY_TEST -from ...hsm_management import ca_settokencertificatesignature, ca_hainit, ca_createloginchallenge, \ - ca_initializeremotepedvector, ca_deleteremotepedvector, ca_mtkrestore, \ - ca_mtkresplit, ca_mtkzeroize, c_performselftest -from ...key_generator import c_generate_key_pair -from ...return_values import ret_vals_dictionary - - -class TestAlgorithm(object): - """Test algorithm class""" - @pytest.fixture(autouse=True) - def setup_teardown(self, auth_session): - self.h_session = auth_session - self.admin_slot = hsm_config["test_slot"] - - @pytest.mark.parametrize("test_type", - [LUNA_TTYPE_CRYPTO, - LUNA_TTYPE_RNG, - LUNA_DSS_SIGVERIFY_TEST]) - def test_performselftest(self, test_type): - """Tests performs self test - - :param test_type: test type - - """ - input_data = range(1000) - input_length = 1000 - - ret, data = c_performselftest(self.admin_slot, - test_type, - input_data, - input_length) - assert ret == CKR_OK, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] - - def test_settokencertsignature(self): - """Tests set token certificate signature - To do: fix attribute value - """ - gen_temp = {CKA_CLASS: CKO_SECRET_KEY, - CKA_KEY_TYPE: CKK_AES, - CKA_TOKEN: True, - CKA_SENSITIVE: True, - CKA_PRIVATE: True, - CKA_ENCRYPT: True, - CKA_DECRYPT: True, - CKA_SIGN: True, - CKA_VERIFY: True, - CKA_WRAP: True, - CKA_UNWRAP: True, - CKA_DERIVE: True, - CKA_VALUE_LEN: 16, - CKA_EXTRACTABLE: True, - CKA_LABEL: "AES Key"} - - access_level = 1 - customer_id = 1 - pub_template = gen_temp - signature = range(4000) - signature_length = 4000 - - ret = ca_settokencertificatesignature(self.h_session, - access_level, - customer_id, - pub_template, - signature, - signature_length) - assert ret == CKR_ATTRIBUTE_VALUE_INVALID, \ - "Return code should be " + \ - ret_vals_dictionary[CKR_ATTRIBUTE_VALUE_INVALID] + \ - " not " + ret_vals_dictionary[ret] - - def test_hainit(self): - """Tests performs HA init""" - ret, pubkey_h, prikey_h = c_generate_key_pair(self.h_session, - CKM_RSA_PKCS_KEY_PAIR_GEN, - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - assert ret == CKR_OK, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] - assert pubkey_h > 0, \ - "The public key handle returned should be non zero" - assert prikey_h > 0, \ - "The private key handle returned should be non zero" - - ret = ca_hainit(self.h_session, prikey_h) - - assert ret == CKR_OK, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] - - @pytest.mark.xfail(reason="Not valid on PWD auth") - def test_initializeremotepedvector(self): - """Tests to initialize remote ped vector""" - ret = ca_initializeremotepedvector(self.h_session) - # since not SO return value must be CKR_USER_NOT_AUTHORIZED - assert ret == CKR_USER_NOT_AUTHORIZED, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] - - @pytest.mark.xfail(reason="Not valid on PWD auth") - def test_deleteremotepedvector(self): - """Tests to delete remote ped vector""" - ret = ca_deleteremotepedvector(self.h_session) - # since not SO return value must be CKR_USER_NOT_AUTHORIZED - assert ret == CKR_USER_NOT_AUTHORIZED, \ - "Return code should be " + ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ - " not " + ret_vals_dictionary[ret] - - def test_mtkrestore(self): - """Tests MTK restore""" - ret = ca_mtkrestore(self.admin_slot) - assert ret == CKR_OK, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] - - def test_mtkresplit(self): - """Tests MTK resplit""" - ret = ca_mtkresplit(self.admin_slot) - assert ret == CKR_OK, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] - - def test_mtkzeroize(self): - """Tests MTK zeroize""" - ret = ca_mtkzeroize(self.admin_slot) - assert ret == CKR_OK, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] +""" +Test methods for pycryptoki 'hsm management' set of commands. +""" + +import pytest + +from . import config as hsm_config +from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN, \ + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP +from pycryptoki.defines import CKR_OK, \ + CKR_ATTRIBUTE_VALUE_INVALID, CKR_USER_NOT_AUTHORIZED, \ + CKA_CLASS, CKO_SECRET_KEY, CKA_KEY_TYPE, CKK_AES, CKA_TOKEN, \ + CKA_SENSITIVE, CKA_PRIVATE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, \ + CKA_VERIFY, CKA_WRAP, CKA_UNWRAP, CKA_DERIVE, CKA_VALUE_LEN, \ + CKA_EXTRACTABLE, CKA_LABEL, LUNA_TTYPE_CRYPTO, LUNA_TTYPE_RNG, \ + LUNA_DSS_SIGVERIFY_TEST +from pycryptoki.hsm_management import ca_settokencertificatesignature, ca_hainit, \ + ca_initializeremotepedvector, ca_deleteremotepedvector, ca_mtkrestore, \ + ca_mtkresplit, ca_mtkzeroize, c_performselftest +from pycryptoki.key_generator import c_generate_key_pair +from pycryptoki.return_values import ret_vals_dictionary + + +class TestAlgorithm(object): + """Test algorithm class""" + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + @pytest.mark.parametrize("test_type", + [LUNA_TTYPE_CRYPTO, + LUNA_TTYPE_RNG, + LUNA_DSS_SIGVERIFY_TEST]) + def test_performselftest(self, test_type): + """Tests performs self test + + :param test_type: test type + + """ + input_data = list(range(1000)) + input_length = 1000 + + ret, data = c_performselftest(self.admin_slot, + test_type, + input_data, + input_length) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + def test_settokencertsignature(self): + """Tests set token certificate signature + To do: fix attribute value + """ + gen_temp = {CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_AES, + CKA_TOKEN: True, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 16, + CKA_EXTRACTABLE: True, + CKA_LABEL: b"AES Key"} + + access_level = 1 + customer_id = 1 + pub_template = gen_temp + signature = list(range(4000)) + signature_length = 4000 + + ret = ca_settokencertificatesignature(self.h_session, + access_level, + customer_id, + pub_template, + signature, + signature_length) + assert ret == CKR_ATTRIBUTE_VALUE_INVALID, \ + "Return code should be " + \ + ret_vals_dictionary[CKR_ATTRIBUTE_VALUE_INVALID] + \ + " not " + ret_vals_dictionary[ret] + + def test_hainit(self): + """Tests performs HA init""" + ret, pubkey_h, prikey_h = c_generate_key_pair(self.h_session, + CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + assert pubkey_h > 0, \ + "The public key handle returned should be non zero" + assert prikey_h > 0, \ + "The private key handle returned should be non zero" + + ret = ca_hainit(self.h_session, prikey_h) + + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + @pytest.mark.xfail(condition=not hsm_config['is_ped'] or hsm_config['user'] == "CO", + reason="Not valid on PWD auth") + def test_initializeremotepedvector(self): + """Tests to initialize remote ped vector""" + ret = ca_initializeremotepedvector(self.h_session) + # since not SO return value must be CKR_USER_NOT_AUTHORIZED + assert ret == CKR_USER_NOT_AUTHORIZED, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + @pytest.mark.xfail(condition=not hsm_config['is_ped'] or hsm_config['user'] == "CO", + reason="Not valid on PWD auth") + def test_deleteremotepedvector(self): + """Tests to delete remote ped vector""" + ret = ca_deleteremotepedvector(self.h_session) + # since not SO return value must be CKR_USER_NOT_AUTHORIZED + assert ret == CKR_USER_NOT_AUTHORIZED, \ + "Return code should be " + ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ + " not " + ret_vals_dictionary[ret] + + def test_mtkrestore(self): + """Tests MTK restore""" + ret = ca_mtkrestore(self.admin_slot) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + def test_mtkresplit(self): + """Tests MTK resplit""" + ret = ca_mtkresplit(self.admin_slot) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + + def test_mtkzeroize(self): + """Tests MTK zeroize""" + ret = ca_mtkzeroize(self.admin_slot) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] diff --git a/pycryptoki/tests/functional/test_key_management.py b/tests/functional/test_key_management.py similarity index 84% rename from pycryptoki/tests/functional/test_key_management.py rename to tests/functional/test_key_management.py index cd8a4e6..e422c0b 100755 --- a/pycryptoki/tests/functional/test_key_management.py +++ b/tests/functional/test_key_management.py @@ -1,21 +1,19 @@ """ Test methods for pycryptoki 'key management' set of commands. """ -import logging -import os import pytest from . import config as hsm_config -from ...cryptoki import CK_ULONG, CK_BYTE, CA_MOFN_GENERATION, \ +from pycryptoki.cryptoki import CK_ULONG, CK_BYTE, CA_MOFN_GENERATION, \ CA_MOFN_GENERATION_PTR -from ...default_templates import CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP -from ...defines import CKR_OK, CKR_USER_NOT_AUTHORIZED, \ +from pycryptoki.default_templates import CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP +from pycryptoki.defines import CKR_OK, CKR_USER_NOT_AUTHORIZED, \ CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, \ CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET -from ...key_generator import c_generate_key -from ...key_management import ca_generatemofn, ca_modifyusagecount -from ...return_values import ret_vals_dictionary +from pycryptoki.key_generator import c_generate_key +from pycryptoki.key_management import ca_generatemofn, ca_modifyusagecount +from pycryptoki.return_values import ret_vals_dictionary class TestAlgorithm(object): diff --git a/pycryptoki/tests/functional/test_key_usage.py b/tests/functional/test_key_usage.py similarity index 82% rename from pycryptoki/tests/functional/test_key_usage.py rename to tests/functional/test_key_usage.py index 2944f54..2ccbc98 100755 --- a/pycryptoki/tests/functional/test_key_usage.py +++ b/tests/functional/test_key_usage.py @@ -5,10 +5,10 @@ import pytest from . import config as hsm_config -from ...defines import CKR_SESSION_HANDLE_INVALID, \ +from pycryptoki.defines import CKR_SESSION_HANDLE_INVALID, \ CKR_USER_NOT_AUTHORIZED -from ...key_usage import ca_clonemofn, ca_duplicatemofn -from ...return_values import ret_vals_dictionary +from pycryptoki.key_usage import ca_clonemofn, ca_duplicatemofn +from pycryptoki.return_values import ret_vals_dictionary class TestAlgorithm(object): diff --git a/pycryptoki/tests/functional/test_keys.py b/tests/functional/test_keys.py similarity index 96% rename from pycryptoki/tests/functional/test_keys.py rename to tests/functional/test_keys.py index 89ac2b4..58bcdc4 100755 --- a/pycryptoki/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -3,7 +3,7 @@ import pytest from . import config as hsm_config -from ...default_templates import CKM_DES_KEY_GEN_TEMP, \ +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, \ @@ -17,7 +17,7 @@ CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, curve_list -from ...defines import CKM_DES_KEY_GEN, CKR_OK, \ +from pycryptoki.defines import CKM_DES_KEY_GEN, CKR_OK, \ CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ @@ -28,15 +28,16 @@ CKM_SHA224_KEY_DERIVATION, CKM_SHA256_KEY_DERIVATION, CKM_SHA1_KEY_DERIVATION, \ CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_MD5_KEY_DERIVATION, \ CKM_MD2_KEY_DERIVATION, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE -from ...key_generator import c_generate_key, c_generate_key_pair, \ +from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, \ c_derive_key, c_generate_key_ex, c_destroy_object -from ...mechanism import NullMech -from ...return_values import ret_vals_dictionary -from ...test_functions import verify_object_attributes +from pycryptoki.mechanism import NullMech +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.test_functions import verify_object_attributes logger = logging.getLogger(__name__) +# noinspection PyArgumentList,PyArgumentList class TestKeys(object): """ """ @@ -126,7 +127,7 @@ def test_generate_key_pair(self, key_type, public_key_template, private_key_temp assert public_key_handle > 0, "The public key handle returned should be non zero" assert private_key_handle > 0, "The private key handle returned should be non zero" - @pytest.mark.parametrize("curve_type", curve_list.keys()) + @pytest.mark.parametrize("curve_type", list(curve_list.keys())) def test_generate_ecdsa_key_pairs(self, curve_type): """ @@ -172,9 +173,6 @@ def test_generate_ecdsa_key_pairs(self, curve_type): def test_derive_key(self, key_type, key_template, derive_type): """Tests deriving a key - :param key_type: - :param key_template: - """ h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) mech = NullMech(derive_type).to_c_mech() diff --git a/pycryptoki/tests/functional/test_object_create.py b/tests/functional/test_object_create.py similarity index 82% rename from pycryptoki/tests/functional/test_object_create.py rename to tests/functional/test_object_create.py index d4d2a71..7238325 100755 --- a/pycryptoki/tests/functional/test_object_create.py +++ b/tests/functional/test_object_create.py @@ -1,14 +1,13 @@ import logging -import os import pytest from . import config as hsm_config -from ...default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE -from ...defines import CKR_OK -from ...misc import c_create_object -from ...return_values import ret_vals_dictionary -from ...test_functions import verify_object_attributes +from pycryptoki.default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE +from pycryptoki.defines import CKR_OK +from pycryptoki.misc import c_create_object +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.test_functions import verify_object_attributes logger = logging.getLogger(__name__) diff --git a/pycryptoki/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py similarity index 91% rename from pycryptoki/tests/functional/test_sign_verify.py rename to tests/functional/test_sign_verify.py index fe4aead..0b5a82b 100755 --- a/pycryptoki/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -3,15 +3,15 @@ import pytest from . import config as hsm_config -from ...default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ +from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 -from ...defines import CKR_OK, CKM_RSA_PKCS, \ +from pycryptoki.defines import CKR_OK, CKM_RSA_PKCS, \ CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA -from ...key_generator import c_generate_key_pair_ex -from ...return_values import ret_vals_dictionary -from ...sign_verify import c_sign, c_verify +from pycryptoki.key_generator import c_generate_key_pair_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.sign_verify import c_sign, c_verify logger = logging.getLogger(__name__) @@ -60,7 +60,7 @@ def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_f h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - data_to_sign = "This is some test string to sign." + data_to_sign = b"This is some test string to sign." ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + \ ret_vals_dictionary[ret] @@ -95,7 +95,7 @@ def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_templa h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, priv_key_template) - data_to_sign = ["a" * 1024, "b" * 1024] + data_to_sign = [b"a" * 1024, b"b" * 1024] ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + \ ret_vals_dictionary[ret] diff --git a/pycryptoki/tests/functional/test_supporting_operations.py b/tests/functional/test_supporting_operations.py similarity index 90% rename from pycryptoki/tests/functional/test_supporting_operations.py rename to tests/functional/test_supporting_operations.py index 96c5a39..b9880b0 100755 --- a/pycryptoki/tests/functional/test_supporting_operations.py +++ b/tests/functional/test_supporting_operations.py @@ -1,13 +1,12 @@ import logging -import os import pytest from . import config as hsm_config -from ...defines import CKR_OK -from ...misc import c_generate_random_ex, c_seed_random, \ +from pycryptoki.defines import CKR_OK +from pycryptoki.misc import c_generate_random_ex, c_seed_random, \ c_generate_random -from ...return_values import ret_vals_dictionary +from pycryptoki.return_values import ret_vals_dictionary logger = logging.getLogger(__name__) @@ -36,7 +35,7 @@ def test_seeded_rng(self): """ - seed = "k" * 1024 + seed = b"k" * 1024 ret = c_seed_random(self.h_session, seed) assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, " \ "it returned " + \ diff --git a/pycryptoki/tests/functional/test_usage_limit_and_count.py b/tests/functional/test_usage_limit_and_count.py similarity index 90% rename from pycryptoki/tests/functional/test_usage_limit_and_count.py rename to tests/functional/test_usage_limit_and_count.py index 6f87e1d..25d91f2 100755 --- a/pycryptoki/tests/functional/test_usage_limit_and_count.py +++ b/tests/functional/test_usage_limit_and_count.py @@ -5,19 +5,18 @@ """ import logging -import os import pytest from . import config as hsm_config -from ...default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP -from ...defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ CKM_DES_ECB, CKM_RSA_PKCS, CKR_KEY_NOT_ACTIVE, CKM_AES_ECB -from ...encryption import c_encrypt, c_encrypt_ex -from ...key_generator import c_generate_key_ex, c_generate_key_pair_ex -from ...object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex +from pycryptoki.encryption import c_encrypt, c_encrypt_ex +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex LOG = logging.getLogger(__name__) @@ -85,9 +84,9 @@ def test_usage_limit_attribute_check_sym_des(self): c_set_attribute_value_ex(self.h_session, h_key, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, b'a' * 2048) - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, 'a' * 2048) + c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, b'a' * 2048) py_template = c_get_attribute_value_ex(self.h_session, h_key, template={CKA_USAGE_COUNT: None}) @@ -120,9 +119,9 @@ def test_usage_limit_attribute_check_sym_aes(self): c_set_attribute_value_ex(self.h_session, h_key, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, b'a' * 2048) - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, 'a' * 2048) + c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, b'a' * 2048) py_template = c_get_attribute_value_ex(self.h_session, h_key, template={CKA_USAGE_COUNT: None}) @@ -194,9 +193,9 @@ def test_usage_limit_attribute_check_Assym(self): c_set_attribute_value_ex(self.h_session, h_pbkey, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_COUNT: None}) @@ -227,11 +226,11 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): c_set_attribute_value_ex(self.h_session, h_key, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) - return_val, data = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, 'a' * 2048) + return_val, data = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) LOG.info("Called C_Encrypt, return code: " + str(return_val)) py_template = c_get_attribute_value_ex(self.h_session, h_key, @@ -267,11 +266,11 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): c_set_attribute_value_ex(self.h_session, h_pbkey, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) - return_val, data = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, 'a' * 20) + return_val, data = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) LOG.info("Called C_Encrypt, return code: " + str(return_val)) py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_COUNT: None}) diff --git a/pycryptoki/tests/functional/test_wrap_unwrap.py b/tests/functional/test_wrap_unwrap.py similarity index 88% rename from pycryptoki/tests/functional/test_wrap_unwrap.py rename to tests/functional/test_wrap_unwrap.py index 638b0a9..fcf3e7f 100755 --- a/pycryptoki/tests/functional/test_wrap_unwrap.py +++ b/tests/functional/test_wrap_unwrap.py @@ -1,17 +1,16 @@ import logging -import os import pytest from . import config as hsm_config -from ...default_templates import CKM_DES_KEY_GEN_TEMP, \ +from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ CKM_DES_UNWRAP_TEMP -from ...defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ +from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ CKM_DES_ECB -from ...encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt -from ...key_generator import c_generate_key_ex -from ...return_values import ret_vals_dictionary -from ...test_functions import verify_object_attributes +from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt +from pycryptoki.key_generator import c_generate_key_ex +from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.test_functions import verify_object_attributes logger = logging.getLogger(__name__) @@ -54,7 +53,7 @@ def test_encrypt_wrap_unwrap_decrypt_key(self): h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) # Encrypt some data - data_to_encrypt = "a" * 512 + data_to_encrypt = b"a" * 512 ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) assert ret == CKR_OK, \ "Encryption should go through successfully, instead it returned " + \ diff --git a/pycryptoki/tests/__init__.py b/tests/unittests/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from pycryptoki/tests/__init__.py rename to tests/unittests/__init__.py diff --git a/pycryptoki/tests/unittests/test_attributes.py b/tests/unittests/test_attributes.py similarity index 67% rename from pycryptoki/tests/unittests/test_attributes.py rename to tests/unittests/test_attributes.py index 772e772..bd098a5 100644 --- a/pycryptoki/tests/unittests/test_attributes.py +++ b/tests/unittests/test_attributes.py @@ -6,7 +6,9 @@ from hypothesis import given from hypothesis.strategies import integers -from ...attributes import to_long + +from pycryptoki.test_functions import integer_types +from pycryptoki.attributes import to_long class TestAttributes(object): @@ -15,6 +17,7 @@ class TestAttributes(object): def test_to_long(self, testval): pointer, len = to_long(testval) assert isinstance(pointer, c_void_p) - assert isinstance(len, (long, int, c_ulong)) + + assert isinstance(len, (integer_types, c_ulong)) finval = cast(pointer, POINTER(c_ulong)).contents - assert finval >= 0 + assert finval.value >= 0 diff --git a/pycryptoki/tests/unittests/test_mechanisms.py b/tests/unittests/test_mechanisms.py similarity index 78% rename from pycryptoki/tests/unittests/test_mechanisms.py rename to tests/unittests/test_mechanisms.py index 797a1b6..db5aef1 100644 --- a/pycryptoki/tests/unittests/test_mechanisms.py +++ b/tests/unittests/test_mechanisms.py @@ -4,36 +4,45 @@ import pytest from ctypes import cast, c_ulong, c_ubyte from mock import patch -from ...cryptoki import CK_RSA_PKCS_PSS_PARAMS, POINTER, CK_ULONG, CK_AES_GCM_PARAMS, CK_MECHANISM -from ...defines import * -from ...mechanism import Mechanism, MechanismException, AutoMech, MECH_LOOKUP, AESGCMMechanism, \ - NullMech - -MECH_PARAMS = {CKM_AES_XTS: {'hTweakKey': 0L, - 'cb': range(12), +from pycryptoki.test_functions import integer_types +from pycryptoki.cryptoki import (CK_RSA_PKCS_PSS_PARAMS, + POINTER, + CK_ULONG, + CK_AES_GCM_PARAMS, + CK_MECHANISM) +from pycryptoki.defines import * +from pycryptoki.mechanism import (Mechanism, + MechanismException, + AutoMech, + MECH_LOOKUP, + AESGCMMechanism, + NullMech) + +MECH_PARAMS = {CKM_AES_XTS: {'hTweakKey': 0, + 'cb': list(range(12)), 'test_id': 'AES_XTS'}, - CKM_DES3_CBC: {'iv': range(12), + CKM_DES3_CBC: {'iv': list(range(12)), 'test_id': 'DES3'}, - CKM_AES_CBC: {'iv': range(16), + CKM_AES_CBC: {'iv': list(range(16)), 'test_id': 'AES_CBC'}, CKM_RC2_ECB: {'usEffectiveBits': 8, 'test_id': 'RC2_ECB'}, CKM_RC2_CBC: {'usEffectiveBits': 8, - 'iv': range(8), + 'iv': list(range(8)), 'test_id': 'RC2_CBC'}, CKM_RC5_ECB: {'ulWordsize': 8, 'ulRounds': 8, 'test_id': 'RC5_ECB'}, CKM_RC5_CBC: {'ulWordsize': 8, 'ulRounds': 2, - 'iv': range(12), + 'iv': list(range(12)), 'test_id': 'RC5_CBC'}, CKM_RSA_PKCS_OAEP: {'hashAlg': CKM_SHA_1, 'mgf': CKG_MGF1_SHA1, - 'sourceData': range(12), + 'sourceData': list(range(12)), 'test_id': 'RSA_OAEP'}, - CKM_AES_GCM: {'iv': range(16), - 'AAD': 'testme', + CKM_AES_GCM: {'iv': list(range(16)), + 'AAD': b'testme', 'ulTagBits': 32, 'test_id': 'AES_GCM'}, CKM_RSA_PKCS_PSS: {'hashAlg': CKM_SHA_1, @@ -45,6 +54,7 @@ def idfn(test): return MECH_PARAMS[test].get('test_id', 'unknown') +# noinspection PyArgumentList class TestMechanisms(object): @pytest.mark.parametrize('flavor,params', [(CKM_AES_XTS, ['hTweakKey', 'cb']), @@ -52,7 +62,7 @@ class TestMechanisms(object): (CKM_RC2_CBC, ['usEffectiveBits', 'iv']), (CKM_RC5_ECB, ['ulWordsize', 'ulRounds']), (CKM_RC5_CBC, ['ulWordsize', 'ulRounds', 'iv']), - (CKM_RSA_PKCS_OAEP, ['hashAlg', 'mgf', 'sourceData']) + (CKM_RSA_PKCS_OAEP, ['hashAlg', 'mgf']) ], ids=["XTS", "RC2", "RC2_CBC", "RC5", "RC5_CBC", "RSA_PKCS_OAEP"]) @@ -67,7 +77,7 @@ def test_missing_params(self, flavor, params): mech = Mechanism(flavor) for x in params: - assert x in excinfo.value.message + assert x in str(excinfo.value) def test_auto_mechanism_simple_vals(self): """ @@ -88,9 +98,9 @@ def test_auto_mechanism_simple_vals(self): assert params.hashAlg == CKM_SHA_1 assert params.mgf == CKG_MGF1_SHA1 assert params.usSaltLen == 8 - assert isinstance(params.usSaltLen, (long, CK_ULONG)) - assert isinstance(params.hashAlg, (long, CK_ULONG)) - assert isinstance(params.mgf, (long, CK_ULONG)) + assert isinstance(params.usSaltLen, (integer_types, CK_ULONG)) + assert isinstance(params.hashAlg, (integer_types, CK_ULONG)) + assert isinstance(params.mgf, (integer_types, CK_ULONG)) def test_null_mechanism_indirect_instantiation(self): """ @@ -115,14 +125,14 @@ def test_exact_mechanism_use(self): :return: """ mech = AESGCMMechanism(mech_type=CKM_AES_GCM, - params={'AAD': 'notsosecret', - 'iv': range(12), + params={'AAD': b'notsosecret', + 'iv': list(range(12)), 'ulTagBits': 32}) cmech = mech.to_c_mech() cparams = cast(cmech.pParameter, POINTER(CK_AES_GCM_PARAMS)).contents - assert cparams.ulTagBits == 32L + assert cparams.ulTagBits == 32 - @pytest.mark.parametrize('flavor', MECH_PARAMS.keys(), + @pytest.mark.parametrize('flavor', list(MECH_PARAMS.keys()), ids=idfn) def test_mech_conversions(self, flavor): """ @@ -134,8 +144,8 @@ def test_mech_conversions(self, flavor): cmech = mech.to_c_mech() # Would prefer to check if it's a c_void_p, but it gets transformed directly to # an int/long depending on memory location. - assert isinstance(cmech.pParameter, (int, long, c_ulong)) - assert isinstance(cmech.usParameterLen, (int, long, c_ulong)) + assert isinstance(cmech.pParameter, (integer_types, c_ulong)) + assert isinstance(cmech.usParameterLen, (integer_types, c_ulong)) assert isinstance(cmech, CK_MECHANISM) assert cmech.mechanism == flavor @@ -180,4 +190,4 @@ def test_no_params_given_automech(self): with pytest.raises(MechanismException) as excinfo: cmech = AutoMech(CKM_DES3_CBC).to_c_mech() - assert "Failed to find a suitable Ctypes Parameter" in excinfo.value.message + assert "Failed to find a suitable Ctypes Parameter" in str(excinfo.value) From eef01eb41ea6a16534203eec27fd1f378b0af591 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 24 Jun 2016 11:48:33 -0400 Subject: [PATCH 053/109] LA-1864 Added license file Change-Id: I05a7ef187adac527ec3e7908c477fba7924f3bad --- LICENSE | 13 +++++++++++++ README.MD | 8 ++++---- setup.cfg | 2 -- tests/functional/test_hsm_management.py | 2 ++ 4 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 LICENSE delete mode 100644 setup.cfg diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ec084ef --- /dev/null +++ b/LICENSE @@ -0,0 +1,13 @@ +Copyright 2016 Gemalto + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/README.MD b/README.MD index 2dbde20..02e6ab4 100755 --- a/README.MD +++ b/README.MD @@ -17,10 +17,10 @@ Unittests can be run on any environment using: py.test tests/unittests ``` -Functional tests require an HSM to test against, and will actively use the libCryptoki library. -These tests *will* factory reset the HSM! We're working on making it so that we don't have to do that, -but in the meantime, don't run this on a production HSM! +Functional tests require an HSM to test against, and will actively test the integration + with the libCryptoki library. This *will* create and destroy objects on the HSM, so don't run + on a production HSM! ``` -py.test tests/functional --slot= +py.test tests/functional --slot= [--reset] [--password=] [--copassword=] [--user=] [--loglevel=] ``` diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index b7e4789..0000000 --- a/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[aliases] -test=pytest diff --git a/tests/functional/test_hsm_management.py b/tests/functional/test_hsm_management.py index 28c4973..d19172e 100755 --- a/tests/functional/test_hsm_management.py +++ b/tests/functional/test_hsm_management.py @@ -86,6 +86,8 @@ def test_settokencertsignature(self): ret_vals_dictionary[CKR_ATTRIBUTE_VALUE_INVALID] + \ " not " + ret_vals_dictionary[ret] + @pytest.mark.xfail(hsm_config["user"] == "CO", + reason="Unable to run on CO slot") def test_hainit(self): """Tests performs HA init""" ret, pubkey_h, prikey_h = c_generate_key_pair(self.h_session, From 259286b87a0e13407cf357a60d3cdd0e5c91a4a5 Mon Sep 17 00:00:00 2001 From: masano Date: Thu, 16 Jun 2016 13:52:27 -0400 Subject: [PATCH 054/109] LA-1854 Test cases for attributes.py Change-Id: I27b9834a43cfcdaeadfe96c2f9b8d505afe9cbbf --- .gitreview | 2 +- pycryptoki/attributes.py | 37 ++- pycryptoki/mechanism.py | 4 +- tests/unittests/__init__.py | 0 tests/unittests/test_attr_conversions.py | 368 +++++++++++++++++++++++ tests/unittests/test_attributes.py | 87 +++++- 6 files changed, 462 insertions(+), 36 deletions(-) delete mode 100644 tests/unittests/__init__.py create mode 100644 tests/unittests/test_attr_conversions.py diff --git a/.gitreview b/.gitreview index d24b732..13373f3 100644 --- a/.gitreview +++ b/.gitreview @@ -1,4 +1,4 @@ [gerrit] host=172.20.10.212 project=Auto/pycryptoki - +defaultbranch=master diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index fb47ebc..0784c78 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -128,11 +128,12 @@ def to_char_array(val, reverse=False): if not isinstance(val, (str, bytes, list)): raise TypeError("Invalid conversion {} to CK_CHAR*!".format(type(val))) + if isinstance(val, list): + val = str("".join(val)) + if isinstance(val, (str, bytes)): string_val = create_string_buffer(val, len(val)) - else: - # TODO: Figure out what, if anything we want to do with a list. - string_val = bytearray(val) + return cast(pointer(string_val), c_void_p), CK_ULONG(sizeof(string_val)) @@ -149,16 +150,18 @@ def to_ck_date(val, reverse=False): if reverse: return string_at(cast(val.pValue, POINTER(c_char)), val.usValueLen) + if isinstance(val, dict): + val = datetime.date(year=val['year'], month=val['month'], day=val['day']) + if isinstance(val, (str, bytes)): if len(val) != 8: raise TypeError("Invalid date string passed! Should be of type YYYYMMDD") date_val = create_string_buffer(val, len(val)) - elif isinstance(val, dict): - date_str = val['year'] + val['month'] + val['day'] - date_val = create_string_buffer(date_str, len(date_str)) + elif isinstance(val, datetime.date): data = val.strftime("%Y%m%d") date_val = create_string_buffer(data, len(data)) + else: raise TypeError("Invalid conversion {} to CK_DATE!".format(type(val))) @@ -167,7 +170,7 @@ def to_ck_date(val, reverse=False): @ret_type(CK_BYTE) def to_byte_array(val, reverse=False): - """Converts an arbitrarily sized integer, list, or hex string + """Converts an arbitrarily sized integer, list, or byte array into a byte array. It'll zero-pad the bit length so it's a multiple of 8, then convert @@ -187,19 +190,13 @@ def to_byte_array(val, reverse=False): fin = binascii.hexlify(bytearray(data_list)) LOG.debug("Final hex data: %s", fin) return fin - - if isinstance(val, (str, bytes)): - # Can be Hex string ('01e4') or a bytestring (ex '\x8p\xb26\x12'G\xa3T\x84\x17\x89') - try: - # Would prefer to use bytearray.fromhex(), but a few testcases use ' ' * 80 or the like, - # which is converted into a zero-length bytearray. - hex_array = [val[i:i + 2] for i in range(0, len(val), 2)] - byte_array = (CK_BYTE * len(val))(*[int(x, 16) for x in hex_array]) - except ValueError: - # Assume a byte array? - py_bytes = bytearray(val) - byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) - elif isinstance(val, collections.Iterable): + if isinstance(val, bytearray): + # Convert to list of ints, and use int-list case + val = [int(x) for x in val] + elif isinstance(val, (str, bytes)): + # Hex-string in form '01e4' + val = int(val, 16) + if isinstance(val, collections.Iterable): py_bytes = bytearray(val) byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) elif isinstance(val, integer_types): diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 53ff75c..1820743 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -6,7 +6,7 @@ from ctypes import c_void_p, cast, pointer, POINTER, sizeof, create_string_buffer, c_char from . import cryptoki -from .attributes import to_byte_array, CONVERSIONS +from .attributes import to_byte_array, to_char_array, CONVERSIONS from .cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_RC2_CBC_PARAMS, \ CK_RC5_PARAMS, CK_RC5_CBC_PARAMS, CK_MECHANISM_TYPE, CK_AES_XTS_PARAMS, \ @@ -295,7 +295,7 @@ def to_c_mech(self): gcm_params.ulIvLen = ivlen # Assuming 8 bits per entry in IV. gcm_params.ulIvBits = CK_ULONG(len(self.params['iv']) * 8) - aad, aadlen = to_byte_array(self.params['AAD']) + aad, aadlen = to_char_array(self.params['AAD']) gcm_params.pAAD = cast(aad, CK_BYTE_PTR) gcm_params.ulAADLen = aadlen gcm_params.ulTagBits = CK_ULONG(self.params['ulTagBits']) diff --git a/tests/unittests/__init__.py b/tests/unittests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/unittests/test_attr_conversions.py b/tests/unittests/test_attr_conversions.py new file mode 100644 index 0000000..5868b9c --- /dev/null +++ b/tests/unittests/test_attr_conversions.py @@ -0,0 +1,368 @@ +""" +Contains unit tests for python -> C type conversion functions in attributes.py. +""" +import pytest +import binascii +import logging + +from string import ascii_letters + +from _ctypes import POINTER +from ctypes import cast, c_void_p, c_ulong, sizeof + +from hypothesis import given +from hypothesis.strategies import integers, floats, text, booleans, lists +from hypothesis.extra.datetime import dates + +from pycryptoki.attributes import CK_ATTRIBUTE, CKA_CLASS, to_long, to_bool, to_char_array, \ + to_ck_date, to_byte_array + +LOG = logging.getLogger(__name__) + +# Max int value +MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 + + +class TestAttrConversions(object): + + def verify_c_type(self, pointer, leng): + """ + Verifies that (pointer, leng) is a proper c type + :param pointer: pointer to c data + :param leng: length of c data + """ + assert isinstance(pointer, c_void_p) + assert isinstance(leng, (long, int, c_ulong)) + + def create_ck_attr(self, pointer, leng): + """ + Given (pointer, leng) creates a c attribute. + :param pointer: pointer to c data + :param leng: length of c data + :return: c attribute + """ + c_attr = CK_ATTRIBUTE(CKA_CLASS, pointer, leng) + return c_attr + + @given(integers(min_value=0, max_value=MAX_INT)) + def test_to_long(self, int_val): + """ + to_long() with param: + :param int_val: random integer >= 0 + """ + pointer, leng = to_long(int_val) + self.verify_c_type(pointer, leng) + + # C type is unsigned integer. Assert result is positive. + assert cast(pointer, POINTER(c_ulong)).contents >= 0 + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_long = to_long(c_attr, reverse=True) + + assert int_val == py_long + + @given(integers(max_value=-1)) + def test_to_long_neg_overflow(self, int_val): + """ + test_to_long() with param: + :param int_val: random negative int. Conversion will result in data loss. + """ + pointer, leng = to_long(int_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_long = to_long(c_attr, reverse=True) + + LOG.debug("to_long() data loss: %s => %s", int_val, py_long) + assert int_val != py_long + + @given(floats()) + def test_to_long_fail_floats(self, flo_val): + """ + to_long() with incompatible param: + :param flo_val: random float -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_long(flo_val) + + @given(text()) + def test_to_long_fail_str(self, txt_val): + """ + to_long() with incompatible param: + :param txt_val: random string -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_long(txt_val) + + @given(booleans()) + def test_to_bool(self, bool_val): + """ + to_bool() with param: + :param bool_val: random boolean + """ + pointer, leng = to_bool(bool_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_bool = to_bool(c_attr, reverse=True) + assert bool_val == py_bool + + @given(integers(min_value=-100, max_value=100)) + def test_to_bool_int(self, int_val): + """ + to_bool() with param: + :param int_val: random int + """ + pointer, leng = to_bool(int_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_bool = to_bool(c_attr, reverse=True) + + assert bool(int_val) == py_bool + + @given(floats()) + def test_to_bool_fail_floats(self, flo_val): + """ + to_bool() with incompatible param: + :param flo_val: random float -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_bool(flo_val) + + @given(text(alphabet=ascii_letters)) + def test_to_bool_fail_text(self, txt_val): + """ + to_bool() with incompatible param: + :param txt_val: random text -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_bool(txt_val) + + @given(text(alphabet=ascii_letters)) + def test_to_char_array_string(self, txt_val): + """ + to_char_array() with param: + :param txt_val: random string + """ + pointer, leng = to_char_array(str(txt_val)) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_txt = to_char_array(c_attr, reverse=True) + assert txt_val == py_txt + + @given(lists(elements=text(alphabet=ascii_letters, min_size=1, max_size=1), min_size=1)) + def test_to_char_array_list(self, list_val): + """ + to_char_array() testing with param: + :param list_val: random list of ascii strings + """ + pointer, leng = to_char_array(list_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_txt = to_char_array(c_attr, reverse=True) + + assert "".join(list_val) == py_txt + + @given(booleans()) + def test_to_char_array_fail_bool(self, bool_val): + """ + to_char_array() with incompatible parameter param: + :param bool_val: random boolean -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_char_array(bool_val) + + @given(dates(min_year=1900)) + def test_to_ck_date_string(self, date_val): + """ + to_ck_date() with param: + :param date_val: random date to be converted to date-string + """ + date_string = str(date_val).replace("-", "") + pointer, leng = to_ck_date(date_string) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_date = to_ck_date(c_attr, reverse=True) + assert date_string == str(py_date) + + @given(dates(min_year=1900)) + def test_to_ck_date_dict(self, date_val): + """ + to_ck_date() with param: + :param date_val: random date to be converted to a dictionary. + """ + date_dict = {'year': date_val.year, 'month': date_val.month, 'day': date_val.day} + pointer, leng = to_ck_date(date_dict) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_date = to_ck_date(c_attr, reverse=True) + + assert (str(date_val).replace("-", "")) == py_date + + @given(dates(min_year=1900)) + def test_to_ck_date(self, date_val): + """ + to_ck_date() with param: + :param date_val: random date, kept as date object + """ + if date_val.year < 1900: + with pytest.raises(ValueError): + pointer, leng = to_ck_date(date_val) + self.verify_c_type(pointer, leng) + else: + pointer, leng = to_ck_date(date_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_date = to_ck_date(c_attr, reverse=True) + assert str(date_val).replace("-", "") == py_date + + @given(text()) + def test_to_ck_date_fail_str(self, txt_val): + """ + to_ck_date() with incompatible param: + :param txt_val: random text. -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_long(txt_val) + + @given(floats()) + def test_to_ck_date_fail_float(self, flo_val): + """ + to_ck_date() with incompatible param: + :param flo_val: random float -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_long(flo_val) + + @given(lists(elements=integers(min_value=0, max_value=255), min_size=1)) + def test_to_byte_array(self, list_val): + """ + to_byte_array() with param: + :param list_val: list of ints in range (0-255), convert to bytearray + """ + # Generate the bytearray from list_val + hex_list = [hex(x)[2:] for x in list_val] + for i in range(len(hex_list)): + if len(hex_list[i]) == 1: + hex_list[i] = '0' + hex_list[i] + b_array = bytearray(h.decode("hex") for h in hex_list) + + pointer, leng = to_byte_array(b_array) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_bytes = to_byte_array(c_attr, reverse=True) + + assert py_bytes == binascii.hexlify(b_array) + + @given(integers(min_value=0)) + def test_to_byte_array_int(self, int_val): + """ + to_byte_array() with param: + :param int_val: random positive integer + """ + pointer, leng = to_byte_array(int_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_bytes = to_byte_array(c_attr, reverse=True) + + assert int(py_bytes, 16) == int_val + + @given(integers(max_value=-1)) + def test_to_byte_array_int_neg_overflow(self, int_val): + """ + to_byte_array() with param: + :param int_val: random int value. Will result in data loss + """ + pointer, leng = to_byte_array(int_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_bytes = to_byte_array(c_attr, reverse=True) + + LOG.debug("to_byte_array() data loss: %s => %s", str(hex(int_val)), str(py_bytes)) + assert int(py_bytes, 16) != int_val + + @given(lists(elements=integers(min_value=0, max_value=255))) + def test_to_byte_array_list(self, list_val): + """ + to_byte_array() with param: + :param list_val: randomly list of postive integers (within byte range). + """ + pointer, leng = to_byte_array(list_val) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_bytes = to_byte_array(c_attr, reverse=True) + + # Create list from returned byte-string + py_list = [] + for i in range(0, len(py_bytes), 2): + py_list.append(int(py_bytes[i:i + 2], 16)) + + assert py_list == list_val + + @given(lists(elements=integers(min_value=256), min_size=1)) + def test_to_byte_array_list_fail_big(self, list_val): + """ + to_byte_array() with incompatible param: + :param list_val: random list of integers > 256 -ValueError + """ + with pytest.raises(ValueError): + pointer, leng = to_byte_array(list_val) + + @given(lists(elements=integers(max_value=-1), min_size=1)) + def test_to_byte_array_list_fail_neg(self, list_val): + """ + to_byte_array() with incompatible param: + :param list_val: random list of negative integers. -ValueError + """ + with pytest.raises(ValueError): + pointer, leng = to_byte_array(list_val) + + @given(text(alphabet=ascii_letters, min_size=1)) + def test_to_byte_array_fail_str(self, txt_val): + """ + to_byte_array() with incompatible param: + :param txt_val: random text -TypeError + :return: + """ + with pytest.raises(TypeError): + pointer, leng = to_byte_array(txt_val) + + @given(integers(min_value=0)) + def test_to_byte_array_hexstring(self, int_val): + """ + to_byte_array() with param: + :param int_val: random integer to be converted to hex string. + """ + hex_string = hex(int_val).replace("0x", "").replace("L", "") + pointer, leng = to_byte_array(hex_string) + self.verify_c_type(pointer, leng) + + # Testing reverse case + c_attr = self.create_ck_attr(pointer, leng) + py_bytes = to_byte_array(c_attr, reverse=True) + + # Convert to int b/c of formating differences (0 != 00) + assert int(py_bytes, 16) == int(hex_string, 16) diff --git a/tests/unittests/test_attributes.py b/tests/unittests/test_attributes.py index bd098a5..8c06035 100644 --- a/tests/unittests/test_attributes.py +++ b/tests/unittests/test_attributes.py @@ -1,23 +1,84 @@ """ - +Test creation of Attributes instance """ -from _ctypes import POINTER -from ctypes import c_void_p, c_ulong, cast + +import pytest +import mock + +from collections import defaultdict + +from pycryptoki.attributes import Attributes, KEY_TRANSFORMS from hypothesis import given -from hypothesis.strategies import integers +from hypothesis.strategies import dictionaries, integers, one_of, none, just + +from ctypes import c_ulong, sizeof + +# Max int value +MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 -from pycryptoki.test_functions import integer_types -from pycryptoki.attributes import to_long +def new_xform(val): + """ + Mock transformation to replace existing xforms in KEY_TRANSFORMS + :param val: Any value. + :return: (1, 1) + """ + return 1, 1 +# Create mock dict w/ all xforms = 'new_xform' +mock_xform_dict = defaultdict(lambda: new_xform) +mock_xform_dict.update({key: new_xform for key in KEY_TRANSFORMS}) +@pytest.yield_fixture() +def setup_mock_dict(): + """ + Fixture for creating dictionary of mockxforms + """ + with mock.patch('pycryptoki.attributes.KEY_TRANSFORMS', new=mock_xform_dict): + yield + + +@pytest.mark.usefixtures('setup_mock_dict') class TestAttributes(object): - @given(integers()) - def test_to_long(self, testval): - pointer, len = to_long(testval) - assert isinstance(pointer, c_void_p) + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), values=none(), dict_class=Attributes)) + def test_null_dictionary(self, test_dic): + """ + Test creation of Attributes class. + :param test_dic: Dictionary of random size, w/ all elements = None + """ + res = test_dic.get_c_struct() + for attr in res: + assert attr.pValue is None + assert attr.usValueLen == 0 + + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), values=just(1), dict_class=Attributes)) + def test_full_dictionary(self, test_dic): + """ + Test creation of Attributes class. + :param test_dic: Dicitonary of random size, w/ all elements = 1 + """ + res = test_dic.get_c_struct() + for attr in res: + assert attr.pValue == 1 + assert attr.usValueLen == 1 + + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), dict_class=Attributes, + values=one_of(just(1), none()))) + def test_rand_dictionary(self, test_dic): + """ + Test creation of Attributes class. + :param test_dic: Dictionary of random size, elements = 1 or None + """ + # Iterate through dictionary and store keys w/ value = 1 + l = [key for key in test_dic if test_dic[key] == 1] + + res = test_dic.get_c_struct() + for attr in res: + if attr.type in l: + assert attr.pValue == 1 + assert attr.usValueLen == 1 + else: + assert attr.pValue is None + assert attr.usValueLen == 0 - assert isinstance(len, (integer_types, c_ulong)) - finval = cast(pointer, POINTER(c_ulong)).contents - assert finval.value >= 0 From 57f58c10242bf362ffd528c5ea46cd78d9c05c4c Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 7 Jul 2016 11:16:49 -0400 Subject: [PATCH 055/109] LA-1864 Updated pylintrc Change-Id: Idecf8ccd93e693ae34fb2355e13a1531027d1fc1 --- pycryptoki/pylintrc | 34 +++++-------------------- tests/functional/conftest.py | 20 ++++++++++----- tests/functional/test_get_token_info.py | 2 +- 3 files changed, 20 insertions(+), 36 deletions(-) diff --git a/pycryptoki/pylintrc b/pycryptoki/pylintrc index 59909cf..20a19f3 100644 --- a/pycryptoki/pylintrc +++ b/pycryptoki/pylintrc @@ -11,12 +11,9 @@ # Specify a configuration file. #rcfile= -# Profiled execution. -profile=no - # Add to the black list. It should be a base name, not a # path. You may set this option multiple times. -ignore=.svn +ignore=.svn,cryptoki.py,defines.py,default_templates.py,return_values.py,lookup_dict.py # Pickle collected data for later comparisons. persistent=yes @@ -49,11 +46,12 @@ load-plugins= #enable-msg= # Disable the message(s) with the given id(s). -disable-msg=W0142,W0703,R0201 +disable=W0142,W0703,R0201,W0614 #Ignoring: #W0142 - Used * or ** for args/kwargs #W0201 - Instance attribute defined outside of __init__ #W0232 - class has no __init__ defined +#W0614 -- Wildcard import (highly useful for defines/cryptoki.py) [REPORTS] @@ -62,15 +60,12 @@ disable-msg=W0142,W0703,R0201 # html output-format=colorized -# Include message's id in output -include-ids=yes - # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no -# Tells wether to display a full report or only the messages +# Tells whether to display a full report or only the messages reports=yes # Python expression which should return a note less than 10 (10 is the highest @@ -80,9 +75,6 @@ reports=yes # (R0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) -# Add a comment according to your evaluation note. This is used by the global -# evaluation report (R0004). -comment=yes # Enable the report(s) with the given id(s). #enable-report= @@ -99,7 +91,7 @@ comment=yes # [VARIABLES] -# Tells wether we should check for unused import in __init__ files. +# Tells whether we should check for unused import in __init__ files. init-import=yes # A regular expression matching names used for dummy variables (i.e. not used). @@ -114,19 +106,14 @@ additional-builtins= # [TYPECHECK] -# Tells wether missing members accessed in mixin class should be ignored. A +# Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes - # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject,pytest -# When zope mode is activated, add a predefined set of Zope acquired attributes -# to generated-members. -zope=no - # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. @@ -147,9 +134,6 @@ generated-members=REQUEST,acl_users,aq_parent,[a-zA-Z_]+_ex # [BASIC] -# Required attributes for module, separated by a comma -required-attributes= - # Regular expression which should only match functions or classes name which do # not require a docstring no-docstring-rgx=__.*__ @@ -260,15 +244,9 @@ int-import-graph= # [CLASSES] -# List of interface methods to ignore, separated by a comma. This is used for -# instance to not check methods defines in Zope's Interface base class. -ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by - # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp -#ignore pytest - # checks for similarities and duplicated code. This computation may be # memory / CPU intensive, so you should disable it if you experiments some # problems. diff --git a/tests/functional/conftest.py b/tests/functional/conftest.py index 49d6e21..880a537 100644 --- a/tests/functional/conftest.py +++ b/tests/functional/conftest.py @@ -6,6 +6,8 @@ import sys # From http://stackoverflow.com/a/7759927 +from pycryptoki.test_functions import LunaException + if sys.version_info < (3,): def b(x): return x @@ -188,10 +190,14 @@ def partition_clearer(auth_session): :return: """ yield - # Use a blank template so we can grab everything. - template = Attributes({}).get_c_struct() - objects = c_find_objects_ex(auth_session, template, 1000) - for handle in objects: - ret = c_destroy_object(auth_session, handle) - if ret != CKR_OK: - LOG.info("Failed to destroy object w/ handle %s", handle) + try: + # Use a blank template so we can grab everything. + template = Attributes({}).get_c_struct() + objects = c_find_objects_ex(auth_session, template, 1000) + for handle in objects: + ret = c_destroy_object(auth_session, handle) + if ret != CKR_OK: + LOG.info("Failed to destroy object w/ handle %s", handle) + except LunaException: + LOG.exception("Failed to destroy all objects created on this session") + diff --git a/tests/functional/test_get_token_info.py b/tests/functional/test_get_token_info.py index 3078d9b..1194515 100755 --- a/tests/functional/test_get_token_info.py +++ b/tests/functional/test_get_token_info.py @@ -40,7 +40,7 @@ def reset_to_defaults(): c_close_all_sessions_ex(slot) -@pytest.mark.skipif("config.getoption('user') != 'SO'") +@pytest.mark.skipif("config.getoption('user') != 'SO' or not config.getoption('reset')") class TestGetTokenInfo(object): """ """ From d834da51ea02518d2d7d300211f24fed3ca830c5 Mon Sep 17 00:00:00 2001 From: masano Date: Mon, 27 Jun 2016 15:50:40 -0400 Subject: [PATCH 056/109] LA-1854 Additonal unittesting Change-Id: I14d99995420c66eace3dcf24a8db7bc937ab3a9a --- pycryptoki/common_utils.py | 2 +- tests/unittests/test_attr_conversions.py | 29 ++++- tests/unittests/test_attributes.py | 1 - tests/unittests/test_auto_c_array.py | 137 +++++++++++++++++++++++ tests/unittests/test_encryption.py | 34 ++++++ 5 files changed, 197 insertions(+), 6 deletions(-) create mode 100644 tests/unittests/test_auto_c_array.py create mode 100644 tests/unittests/test_encryption.py diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index bbfbbfb..242f1e1 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -52,7 +52,7 @@ def __init__(self, data=None, ctype=c_ulong, size=None): if data is not None: # Parse out any given data. if isinstance(data, basestring): - self._array = create_string_buffer(data) + self._array = create_string_buffer(data, len(data)) self._size = c_ulong(len(data)) self.ctype = CK_CHAR elif isinstance(data, list): diff --git a/tests/unittests/test_attr_conversions.py b/tests/unittests/test_attr_conversions.py index 5868b9c..0ed37c9 100644 --- a/tests/unittests/test_attr_conversions.py +++ b/tests/unittests/test_attr_conversions.py @@ -11,11 +11,12 @@ from ctypes import cast, c_void_p, c_ulong, sizeof from hypothesis import given -from hypothesis.strategies import integers, floats, text, booleans, lists +from hypothesis.strategies import integers, floats, text, booleans, lists, dictionaries from hypothesis.extra.datetime import dates from pycryptoki.attributes import CK_ATTRIBUTE, CKA_CLASS, to_long, to_bool, to_char_array, \ - to_ck_date, to_byte_array + to_ck_date, to_byte_array, to_sub_attributes, Attributes, \ + convert_c_ubyte_array_to_string LOG = logging.getLogger(__name__) @@ -238,7 +239,7 @@ def test_to_ck_date_fail_str(self, txt_val): :param txt_val: random text. -TypeError """ with pytest.raises(TypeError): - pointer, leng = to_long(txt_val) + pointer, leng = to_ck_date(txt_val) @given(floats()) def test_to_ck_date_fail_float(self, flo_val): @@ -247,7 +248,7 @@ def test_to_ck_date_fail_float(self, flo_val): :param flo_val: random float -TypeError """ with pytest.raises(TypeError): - pointer, leng = to_long(flo_val) + pointer, leng = to_ck_date(flo_val) @given(lists(elements=integers(min_value=0, max_value=255), min_size=1)) def test_to_byte_array(self, list_val): @@ -340,6 +341,13 @@ def test_to_byte_array_list_fail_neg(self, list_val): with pytest.raises(ValueError): pointer, leng = to_byte_array(list_val) + def test_to_byte_array_fail_obj(self): + """ + to_byte_array() with object param. -TypeError + """ + with pytest.raises(TypeError): + pointer, leng = to_byte_array(object) + @given(text(alphabet=ascii_letters, min_size=1)) def test_to_byte_array_fail_str(self, txt_val): """ @@ -366,3 +374,16 @@ def test_to_byte_array_hexstring(self, int_val): # Convert to int b/c of formating differences (0 != 00) assert int(py_bytes, 16) == int(hex_string, 16) + + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), dict_class=Attributes, + values=booleans())) + def test_to_sub_attributes(self, test_dic): + """ + to_sub_attributes() with param + :param test_dic: random dictionary of bools + :return: + """ + pointer, leng = to_sub_attributes(test_dic) + self.verify_c_type(pointer, leng) + + # TODO: Reverse case diff --git a/tests/unittests/test_attributes.py b/tests/unittests/test_attributes.py index 8c06035..1f782bc 100644 --- a/tests/unittests/test_attributes.py +++ b/tests/unittests/test_attributes.py @@ -81,4 +81,3 @@ def test_rand_dictionary(self, test_dic): else: assert attr.pValue is None assert attr.usValueLen == 0 - diff --git a/tests/unittests/test_auto_c_array.py b/tests/unittests/test_auto_c_array.py new file mode 100644 index 0000000..b94af73 --- /dev/null +++ b/tests/unittests/test_auto_c_array.py @@ -0,0 +1,137 @@ +""" +Unit tests for AutoCArray in common_util.py +""" +import pytest + +from pycryptoki.common_utils import AutoCArray + +from ctypes import * + +from hypothesis import given +from hypothesis.strategies import text, lists, sampled_from, integers + +from string import ascii_letters + +c_types = [c_short, c_ushort, c_long, c_ulong, c_int, c_uint, c_float, c_double, c_longdouble, + c_longlong, c_ulonglong, c_byte, c_ubyte, c_char, c_char_p, c_void_p, c_bool] + +MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 + + +class TestAutoCArray(object): + + @given(sampled_from(c_types)) + def test_auto_c_array_empty(self, typ_val): + """ + Initialize an empty array w/ elements of the given c_type. + :param typ_val: randomly selected ctype + """ + c_array = AutoCArray(ctype=typ_val) + + assert c_array.array is None + assert c_array.size.contents.value == len(c_array) == 0 + assert c_array.ctype == typ_val + + if typ_val == c_char: + assert c_array.array.contents.value == typ_val('\x00').value + else: + assert c_array.array.contents.value == typ_val(0).value + + @given(text(alphabet=ascii_letters)) + def test_auto_c_array_string(self, str_val): + """ + Initialize an array from string. + :param str_val: randomly generated string + """ + c_array = AutoCArray(data=str_val) + + assert c_array.size.contents.value == len(c_array) == len(str_val) + assert c_array.ctype == c_ubyte + assert "".join(c_array) == str_val + + @given(lists(elements=integers(min_value=-128, max_value=127), min_size=1)) + def test_auto_c_array_byte_list(self, list_val): + """ + Initalize an array from list of bytes. + :param list_val: list of ints to be converted to c_byte's + """ + list_val = [c_byte(x) for x in list_val] + c_array = AutoCArray(data=list_val, ctype=c_byte) + + assert c_array.size.contents.value == len(c_array) == len(list_val) + assert c_array.ctype == c_byte + assert "".join([str(c_byte(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert c_array.array[0] == cast(c_array.array, POINTER(c_byte)).contents.value + + @given(lists(elements=integers(min_value=0, max_value=256), min_size=1)) + def test_auto_c_array_ubyte_list(self, list_val): + """ + Initalize an array from list of bytes. + :param list_val: list of ints to be converted to c_ubyte's + """ + list_val = [c_ubyte(x) for x in list_val] + c_array = AutoCArray(data=list_val, ctype=c_ubyte) + + assert c_array.size.contents.value == len(c_array) == len(list_val) + assert c_array.ctype == c_ubyte + assert "".join([str(c_ubyte(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert c_array.array[0] == cast(c_array.array, POINTER(c_ubyte)).contents.value + + @given(lists(elements=integers(min_value=(-MAX_INT/2), max_value=MAX_INT/2), min_size=1)) + def test_auto_c_array_long_list(self, list_val): + """ + Initalize an array from list of long's + :param list_val: list of ints to be converted to c_long's + """ + list_val = [c_long(x) for x in list_val] + c_array = AutoCArray(data=list_val, ctype=c_long) + + assert c_array._size.value == c_long(len(list_val)).value + assert len(c_array) == len(list_val) + assert c_array.ctype == c_long + assert "".join([str(c_long(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert c_array.array[0] == cast(c_array.array, POINTER(c_long)).contents.value + + @given(lists(elements=integers(min_value=0, max_value=MAX_INT), min_size=1)) + def test_auto_c_array_ulong_list(self, list_val): + """ + Initalize an array from list of ulong's + :param list_val: list of ints to be converted to c_ulong's + """ + list_val = [c_ulong(x) for x in list_val] + c_array = AutoCArray(data=list_val, ctype=c_ulong) + + assert c_array.size.contents.value == len(c_array) == len(list_val) + assert c_array.ctype == c_ulong + assert "".join([str(c_ulong(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert c_array.array[0] == cast(c_array.array, POINTER(c_ulong)).contents.value + + @given(lists(elements=text(alphabet=ascii_letters, min_size=1, max_size=1), min_size=1)) + def test_auto_c_array_char_list(self, list_val): + """ + Initalize an array from list of c_chars + :param list_val: list of char to be converted to c_char's + """ + new_list_val = [c_char(str(x)) for x in list_val] + c_array = AutoCArray(data=new_list_val, ctype=c_char) + + assert c_array.size.contents.value == len(c_array) == len(list_val) + assert c_array.ctype == c_char + assert "".join([str(x) for x in c_array]) == "".join([str(x) for x in list_val]) + assert c_array.array[0] == cast(c_array.array, POINTER(c_char)).contents.value + + @given(list_val=lists(elements=integers(min_value=0, max_value=127), min_size=1)) + @pytest.mark.parametrize('test_type', [c_byte, c_ubyte, c_long, c_char]) + def test_auto_c_array_no_type_fail(self, list_val, test_type): + """ + Attempt to initialize an array of 'test_type' without specifying the type. Should error + :param list_val: Generated list, convert to 'test_type' + :param test_type: c_types to test with + """ + if test_type == c_char: + new_list = [c_char(str(x)[0]) for x in list_val] + else: + new_list = [test_type(x) for x in list_val] + + with pytest.raises(TypeError): + c_array = AutoCArray(data=new_list) diff --git a/tests/unittests/test_encryption.py b/tests/unittests/test_encryption.py new file mode 100644 index 0000000..0d3842c --- /dev/null +++ b/tests/unittests/test_encryption.py @@ -0,0 +1,34 @@ +""" +Unit tests for encryption.py +""" +import pytest +from hypothesis import given +from hypothesis.strategies import text, integers, data, lists + +import pycryptoki.encryption as encrypt + +from string import ascii_letters as ascii + + +class TestEncryption(object): + + @given(data()) + def test_split_string_into_list(self, data): + """ + _split_string_into_list() w/ random text and block size + :param data: + """ + txt = data.draw(text(alphabet=ascii, min_size=1)) + block = data.draw(integers(min_value=1, max_value=len(txt))) + + txt_list = [txt[i:i + block] for i in range(0, len(txt), block)] + assert encrypt._split_string_into_list(txt, block) == txt_list + + @given(lists(elements=text(alphabet=ascii), min_size=1)) + def test_get_string_from_list(self, list_val): + """ + _get_string_from_list w/ list of random text + :param list_val: list of random text + """ + assert encrypt._get_string_from_list(list_val) == "".join(list_val) + From 57a7e19d74037b4e45ad7f9bb5c4ca2364ffda81 Mon Sep 17 00:00:00 2001 From: masano Date: Thu, 30 Jun 2016 10:17:53 -0400 Subject: [PATCH 057/109] LA-1854 pycrypotiki unittesting Change-Id: I0c80b9a0acacc7bbab5200f783fb661094efcf6a --- tests/unittests/test_attr_conversions.py | 223 +++++++++-------------- tests/unittests/test_attributes.py | 32 +++- tests/unittests/test_auto_c_array.py | 5 +- 3 files changed, 112 insertions(+), 148 deletions(-) diff --git a/tests/unittests/test_attr_conversions.py b/tests/unittests/test_attr_conversions.py index 0ed37c9..c6e8467 100644 --- a/tests/unittests/test_attr_conversions.py +++ b/tests/unittests/test_attr_conversions.py @@ -1,26 +1,24 @@ """ -Contains unit tests for python -> C type conversion functions in attributes.py. +Unit tests for python/c type conversions """ import pytest -import binascii import logging -from string import ascii_letters +from hypothesis import given +from hypothesis.strategies import integers, floats, text, booleans, lists, dictionaries, one_of +from hypothesis.extra.datetime import dates from _ctypes import POINTER from ctypes import cast, c_void_p, c_ulong, sizeof -from hypothesis import given -from hypothesis.strategies import integers, floats, text, booleans, lists, dictionaries -from hypothesis.extra.datetime import dates - -from pycryptoki.attributes import CK_ATTRIBUTE, CKA_CLASS, to_long, to_bool, to_char_array, \ +from pycryptoki.attributes import CK_ATTRIBUTE, CKA_CLASS, CK_BYTE, to_long, to_bool, to_char_array, \ to_ck_date, to_byte_array, to_sub_attributes, Attributes, \ convert_c_ubyte_array_to_string -LOG = logging.getLogger(__name__) +from binascii import hexlify +from string import ascii_letters as letters -# Max int value +LOG = logging.getLogger(__name__) MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 @@ -45,6 +43,27 @@ def create_ck_attr(self, pointer, leng): c_attr = CK_ATTRIBUTE(CKA_CLASS, pointer, leng) return c_attr + def reverse_case(self, pointer, leng, func): + """ + Perform the reverse operation of the given function on (pointer, leng) + :param pointer: c pointer + :param leng: data length + :param func: function type + :return: python type + """ + c_attr = self.create_ck_attr(pointer, leng) + return func(c_attr, reverse=True) + + def force_fail(self, val, func, error): + """ + run val through func, assert that 'error' is raised + :param val: data + :param func: function + :param error: expected error + """ + with pytest.raises(error): + pointer, leng = func(val) + @given(integers(min_value=0, max_value=MAX_INT)) def test_to_long(self, int_val): """ @@ -57,10 +76,7 @@ def test_to_long(self, int_val): # C type is unsigned integer. Assert result is positive. assert cast(pointer, POINTER(c_ulong)).contents >= 0 - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_long = to_long(c_attr, reverse=True) - + py_long = self.reverse_case(pointer, leng, to_long) assert int_val == py_long @given(integers(max_value=-1)) @@ -72,30 +88,17 @@ def test_to_long_neg_overflow(self, int_val): pointer, leng = to_long(int_val) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_long = to_long(c_attr, reverse=True) - + py_long = self.reverse_case(pointer, leng, to_long) LOG.debug("to_long() data loss: %s => %s", int_val, py_long) assert int_val != py_long - @given(floats()) - def test_to_long_fail_floats(self, flo_val): - """ - to_long() with incompatible param: - :param flo_val: random float -TypeError - """ - with pytest.raises(TypeError): - pointer, leng = to_long(flo_val) - - @given(text()) - def test_to_long_fail_str(self, txt_val): + @given(one_of(floats(), text())) + def test_to_long_fail(self, fail_val): """ - to_long() with incompatible param: - :param txt_val: random string -TypeError + to_long() with incompatible params: + :param fail_val: random data of known incompatible types (floats, text) """ - with pytest.raises(TypeError): - pointer, leng = to_long(txt_val) + self.force_fail(fail_val, to_long, TypeError) @given(booleans()) def test_to_bool(self, bool_val): @@ -106,9 +109,7 @@ def test_to_bool(self, bool_val): pointer, leng = to_bool(bool_val) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_bool = to_bool(c_attr, reverse=True) + py_bool = self.reverse_case(pointer, leng, to_bool) assert bool_val == py_bool @given(integers(min_value=-100, max_value=100)) @@ -120,31 +121,18 @@ def test_to_bool_int(self, int_val): pointer, leng = to_bool(int_val) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_bool = to_bool(c_attr, reverse=True) - + py_bool = self.reverse_case(pointer, leng, to_bool) assert bool(int_val) == py_bool - @given(floats()) - def test_to_bool_fail_floats(self, flo_val): - """ - to_bool() with incompatible param: - :param flo_val: random float -TypeError - """ - with pytest.raises(TypeError): - pointer, leng = to_bool(flo_val) - - @given(text(alphabet=ascii_letters)) - def test_to_bool_fail_text(self, txt_val): + @given(one_of(floats(), text())) + def test_to_bool_fail(self, fail_val): """ to_bool() with incompatible param: - :param txt_val: random text -TypeError + :param fail_val: data of known incompatible type (floats, text) """ - with pytest.raises(TypeError): - pointer, leng = to_bool(txt_val) + self.force_fail(fail_val, to_bool, TypeError) - @given(text(alphabet=ascii_letters)) + @given(text(alphabet=letters)) def test_to_char_array_string(self, txt_val): """ to_char_array() with param: @@ -153,12 +141,10 @@ def test_to_char_array_string(self, txt_val): pointer, leng = to_char_array(str(txt_val)) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_txt = to_char_array(c_attr, reverse=True) + py_txt = self.reverse_case(pointer, leng, to_char_array) assert txt_val == py_txt - @given(lists(elements=text(alphabet=ascii_letters, min_size=1, max_size=1), min_size=1)) + @given(lists(elements=text(alphabet=letters, min_size=1, max_size=1), min_size=1)) def test_to_char_array_list(self, list_val): """ to_char_array() testing with param: @@ -167,20 +153,14 @@ def test_to_char_array_list(self, list_val): pointer, leng = to_char_array(list_val) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_txt = to_char_array(c_attr, reverse=True) - + py_txt = self.reverse_case(pointer, leng, to_char_array) assert "".join(list_val) == py_txt - @given(booleans()) - def test_to_char_array_fail_bool(self, bool_val): + def test_to_char_array_fail_obj(self): """ - to_char_array() with incompatible parameter param: - :param bool_val: random boolean -TypeError + Trigger TypeError in to_char_array() with object as paramater. """ - with pytest.raises(TypeError): - pointer, leng = to_char_array(bool_val) + self.force_fail(object(), to_char_array, TypeError) @given(dates(min_year=1900)) def test_to_ck_date_string(self, date_val): @@ -192,9 +172,7 @@ def test_to_ck_date_string(self, date_val): pointer, leng = to_ck_date(date_string) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_date = to_ck_date(c_attr, reverse=True) + py_date = self.reverse_case(pointer, leng, to_ck_date) assert date_string == str(py_date) @given(dates(min_year=1900)) @@ -207,10 +185,7 @@ def test_to_ck_date_dict(self, date_val): pointer, leng = to_ck_date(date_dict) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_date = to_ck_date(c_attr, reverse=True) - + py_date = self.reverse_case(pointer, leng, to_ck_date) assert (str(date_val).replace("-", "")) == py_date @given(dates(min_year=1900)) @@ -219,36 +194,17 @@ def test_to_ck_date(self, date_val): to_ck_date() with param: :param date_val: random date, kept as date object """ - if date_val.year < 1900: - with pytest.raises(ValueError): - pointer, leng = to_ck_date(date_val) - self.verify_c_type(pointer, leng) - else: - pointer, leng = to_ck_date(date_val) - self.verify_c_type(pointer, leng) - - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_date = to_ck_date(c_attr, reverse=True) - assert str(date_val).replace("-", "") == py_date + pointer, leng = to_ck_date(date_val) + self.verify_c_type(pointer, leng) - @given(text()) - def test_to_ck_date_fail_str(self, txt_val): - """ - to_ck_date() with incompatible param: - :param txt_val: random text. -TypeError - """ - with pytest.raises(TypeError): - pointer, leng = to_ck_date(txt_val) + py_date = self.reverse_case(pointer, leng, to_ck_date) + assert str(date_val).replace("-", "") == py_date - @given(floats()) - def test_to_ck_date_fail_float(self, flo_val): + def test_to_ck_date_fail_obj(self): """ - to_ck_date() with incompatible param: - :param flo_val: random float -TypeError + Trigger TypeError in to_ck_date() with object as paramater. """ - with pytest.raises(TypeError): - pointer, leng = to_ck_date(flo_val) + self.force_fail(object(), to_ck_date, TypeError) @given(lists(elements=integers(min_value=0, max_value=255), min_size=1)) def test_to_byte_array(self, list_val): @@ -256,21 +212,13 @@ def test_to_byte_array(self, list_val): to_byte_array() with param: :param list_val: list of ints in range (0-255), convert to bytearray """ - # Generate the bytearray from list_val - hex_list = [hex(x)[2:] for x in list_val] - for i in range(len(hex_list)): - if len(hex_list[i]) == 1: - hex_list[i] = '0' + hex_list[i] - b_array = bytearray(h.decode("hex") for h in hex_list) + b_array = bytearray(list_val) pointer, leng = to_byte_array(b_array) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_bytes = to_byte_array(c_attr, reverse=True) - - assert py_bytes == binascii.hexlify(b_array) + py_bytes = self.reverse_case(pointer, leng, to_byte_array) + assert py_bytes == hexlify(b_array) @given(integers(min_value=0)) def test_to_byte_array_int(self, int_val): @@ -281,10 +229,7 @@ def test_to_byte_array_int(self, int_val): pointer, leng = to_byte_array(int_val) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_bytes = to_byte_array(c_attr, reverse=True) - + py_bytes = self.reverse_case(pointer, leng, to_byte_array) assert int(py_bytes, 16) == int_val @given(integers(max_value=-1)) @@ -296,10 +241,7 @@ def test_to_byte_array_int_neg_overflow(self, int_val): pointer, leng = to_byte_array(int_val) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_bytes = to_byte_array(c_attr, reverse=True) - + py_bytes = self.reverse_case(pointer, leng, to_byte_array) LOG.debug("to_byte_array() data loss: %s => %s", str(hex(int_val)), str(py_bytes)) assert int(py_bytes, 16) != int_val @@ -312,9 +254,7 @@ def test_to_byte_array_list(self, list_val): pointer, leng = to_byte_array(list_val) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_bytes = to_byte_array(c_attr, reverse=True) + py_bytes = self.reverse_case(pointer, leng, to_byte_array) # Create list from returned byte-string py_list = [] @@ -345,18 +285,15 @@ def test_to_byte_array_fail_obj(self): """ to_byte_array() with object param. -TypeError """ - with pytest.raises(TypeError): - pointer, leng = to_byte_array(object) + self.force_fail(object(), to_byte_array, TypeError) - @given(text(alphabet=ascii_letters, min_size=1)) + @given(text(alphabet=letters, min_size=1)) def test_to_byte_array_fail_str(self, txt_val): """ to_byte_array() with incompatible param: :param txt_val: random text -TypeError - :return: """ - with pytest.raises(TypeError): - pointer, leng = to_byte_array(txt_val) + self.force_fail(txt_val, to_byte_array, TypeError) @given(integers(min_value=0)) def test_to_byte_array_hexstring(self, int_val): @@ -368,22 +305,30 @@ def test_to_byte_array_hexstring(self, int_val): pointer, leng = to_byte_array(hex_string) self.verify_c_type(pointer, leng) - # Testing reverse case - c_attr = self.create_ck_attr(pointer, leng) - py_bytes = to_byte_array(c_attr, reverse=True) - - # Convert to int b/c of formating differences (0 != 00) + py_bytes = self.reverse_case(pointer, leng, to_byte_array) assert int(py_bytes, 16) == int(hex_string, 16) - @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), dict_class=Attributes, - values=booleans())) + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), dict_class=Attributes, values=booleans())) def test_to_sub_attributes(self, test_dic): """ to_sub_attributes() with param :param test_dic: random dictionary of bools - :return: """ pointer, leng = to_sub_attributes(test_dic) self.verify_c_type(pointer, leng) - # TODO: Reverse case + @given(integers()) + def test_to_sub_attributes_fail(self, int_val): + """ + to_sub_attributes() with incompatible param: + :param int_val: random integer + """ + self.force_fail(int_val, to_sub_attributes, TypeError) + + @given(lists(elements=integers(min_value=0, max_value=255), min_size=1)) + def test_c_byte_array_to_string(self, list_val): + b_array = bytearray(list_val) + c_b_array = (CK_BYTE * len(b_array))(*b_array) + + str_result = convert_c_ubyte_array_to_string(c_b_array) + assert str_result == hexlify(b_array) diff --git a/tests/unittests/test_attributes.py b/tests/unittests/test_attributes.py index 1f782bc..bcb6eee 100644 --- a/tests/unittests/test_attributes.py +++ b/tests/unittests/test_attributes.py @@ -7,22 +7,25 @@ from collections import defaultdict -from pycryptoki.attributes import Attributes, KEY_TRANSFORMS +from pycryptoki.attributes import Attributes, KEY_TRANSFORMS, c_struct_to_python from hypothesis import given from hypothesis.strategies import dictionaries, integers, one_of, none, just from ctypes import c_ulong, sizeof -# Max int value MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 -def new_xform(val): + +def new_xform(val, reverse=False): """ Mock transformation to replace existing xforms in KEY_TRANSFORMS :param val: Any value. + :param reverse: 'reverse' place holder for conversion methods :return: (1, 1) """ + if reverse: + return 1 return 1, 1 # Create mock dict w/ all xforms = 'new_xform' mock_xform_dict = defaultdict(lambda: new_xform) @@ -31,9 +34,7 @@ def new_xform(val): @pytest.yield_fixture() def setup_mock_dict(): - """ - Fixture for creating dictionary of mockxforms - """ + """ Fixture for creating dictionary of mockxforms """ with mock.patch('pycryptoki.attributes.KEY_TRANSFORMS', new=mock_xform_dict): yield @@ -41,6 +42,13 @@ def setup_mock_dict(): @pytest.mark.usefixtures('setup_mock_dict') class TestAttributes(object): + def test_no_params(self): + """ Create Attributes object without specifying any parameters """ + attr = Attributes() + c_struct = attr.get_c_struct() + assert isinstance(attr, Attributes) + assert len(attr) == sizeof(c_struct) == 0 + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), values=none(), dict_class=Attributes)) def test_null_dictionary(self, test_dic): """ @@ -52,6 +60,10 @@ def test_null_dictionary(self, test_dic): assert attr.pValue is None assert attr.usValueLen == 0 + # Back to python dictionary + py_dic = c_struct_to_python(res) + assert test_dic == py_dic + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), values=just(1), dict_class=Attributes)) def test_full_dictionary(self, test_dic): """ @@ -63,6 +75,10 @@ def test_full_dictionary(self, test_dic): assert attr.pValue == 1 assert attr.usValueLen == 1 + # Back to python dictionary + py_dic = c_struct_to_python(res) + assert test_dic == py_dic + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), dict_class=Attributes, values=one_of(just(1), none()))) def test_rand_dictionary(self, test_dic): @@ -81,3 +97,7 @@ def test_rand_dictionary(self, test_dic): else: assert attr.pValue is None assert attr.usValueLen == 0 + + # Back to python dictionary + py_dic = c_struct_to_python(res) + assert test_dic == py_dic diff --git a/tests/unittests/test_auto_c_array.py b/tests/unittests/test_auto_c_array.py index b94af73..2e3564a 100644 --- a/tests/unittests/test_auto_c_array.py +++ b/tests/unittests/test_auto_c_array.py @@ -86,8 +86,7 @@ def test_auto_c_array_long_list(self, list_val): list_val = [c_long(x) for x in list_val] c_array = AutoCArray(data=list_val, ctype=c_long) - assert c_array._size.value == c_long(len(list_val)).value - assert len(c_array) == len(list_val) + assert c_array.size.contents.value == len(c_array) == len(list_val) assert c_array.ctype == c_long assert "".join([str(c_long(x)) for x in c_array]) == "".join([str(x) for x in list_val]) assert c_array.array[0] == cast(c_array.array, POINTER(c_long)).contents.value @@ -129,7 +128,7 @@ def test_auto_c_array_no_type_fail(self, list_val, test_type): :param test_type: c_types to test with """ if test_type == c_char: - new_list = [c_char(str(x)[0]) for x in list_val] + new_list = [c_char(chr(x)) for x in list_val] else: new_list = [test_type(x) for x in list_val] From c8266f27d43a82312caad0efba4e41a8a64127f3 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 15 Jul 2016 10:09:02 -0400 Subject: [PATCH 058/109] LA-1864 Fixes for python3 support w/ testing Change-Id: Ie6166dedcbfc0085642096d11fd9cabf7bbd7c15 --- pycryptoki/attributes.py | 27 +++++--- pycryptoki/common_utils.py | 6 +- pycryptoki/defaults.py | 26 +++---- pycryptoki/encryption.py | 6 +- pycryptoki/partition_management.py | 8 +-- pycryptoki/session_management.py | 16 ++--- pycryptoki/sign_verify.py | 6 +- pycryptoki/test_functions.py | 4 +- pycryptoki/token_management.py | 8 ++- setup.py | 4 +- tests/functional/conftest.py | 14 +--- .../functional/test_usage_limit_and_count.py | 29 ++++---- tests/unittests/test_attr_conversions.py | 69 +++++++++++-------- tests/unittests/test_auto_c_array.py | 36 +++++----- tests/unittests/test_encryption.py | 4 +- tests/unittests/test_mechanisms.py | 4 +- 16 files changed, 141 insertions(+), 126 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 0784c78..2433489 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -12,6 +12,8 @@ c_ulong, pointer, POINTER, sizeof, c_char, string_at, c_ubyte from functools import wraps +from six import b, string_types + from .cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ CK_BYTE, CK_CHAR from .defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ @@ -125,13 +127,18 @@ def to_char_array(val, reverse=False): LOG.debug("Converted to : %s", ret_data) return ret_data - if not isinstance(val, (str, bytes, list)): + if not isinstance(val, (string_types, bytes, list)): raise TypeError("Invalid conversion {} to CK_CHAR*!".format(type(val))) if isinstance(val, list): - val = str("".join(val)) + val = "".join(val) - if isinstance(val, (str, bytes)): + # If already a bytestring, go directly to C. + # Otherwise, convert to bytestring, then go to C. + if isinstance(val, bytes): + string_val = create_string_buffer(val, len(val)) + elif isinstance(val, string_types): + val = b(val) string_val = create_string_buffer(val, len(val)) return cast(pointer(string_val), c_void_p), CK_ULONG(sizeof(string_val)) @@ -153,13 +160,13 @@ def to_ck_date(val, reverse=False): if isinstance(val, dict): val = datetime.date(year=val['year'], month=val['month'], day=val['day']) - if isinstance(val, (str, bytes)): + if isinstance(val, string_types): if len(val) != 8: raise TypeError("Invalid date string passed! Should be of type YYYYMMDD") - date_val = create_string_buffer(val, len(val)) + date_val = create_string_buffer(b(val), len(val)) elif isinstance(val, datetime.date): - data = val.strftime("%Y%m%d") + data = b(val.strftime("%Y%m%d")) date_val = create_string_buffer(data, len(data)) else: @@ -190,10 +197,8 @@ def to_byte_array(val, reverse=False): fin = binascii.hexlify(bytearray(data_list)) LOG.debug("Final hex data: %s", fin) return fin - if isinstance(val, bytearray): - # Convert to list of ints, and use int-list case - val = [int(x) for x in val] - elif isinstance(val, (str, bytes)): + + if isinstance(val, string_types): # Hex-string in form '01e4' val = int(val, 16) if isinstance(val, collections.Iterable): @@ -426,4 +431,4 @@ def convert_c_ubyte_array_to_string(byte_array): :param byte_array: """ - return "".join("%02x" % b for b in byte_array) + return b("".join("%02x" % x for x in byte_array)) diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index 242f1e1..93f2e91 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -1,7 +1,7 @@ """ Utilities for pycryptoki """ -from past.builtins import basestring +from six import b, string_types from _ctypes import pointer, POINTER from ctypes import c_ulong, cast, create_string_buffer @@ -51,8 +51,8 @@ def __init__(self, data=None, ctype=c_ulong, size=None): # name was just for logging. if data is not None: # Parse out any given data. - if isinstance(data, basestring): - self._array = create_string_buffer(data, len(data)) + if isinstance(data, (bytes, string_types)): + self._array = create_string_buffer(b(data), len(data)) self._size = c_ulong(len(data)) self.ctype = CK_CHAR elif isinstance(data, list): diff --git a/pycryptoki/defaults.py b/pycryptoki/defaults.py index a4b90d8..dabb185 100755 --- a/pycryptoki/defaults.py +++ b/pycryptoki/defaults.py @@ -12,21 +12,21 @@ # the Chrystoki config file specified be the variable CHRYSTOKI_CONFIG_FILE CHRYSTOKI_DLL_FILE = None -ADMIN_PARTITION_LABEL = b'no label' -AUDITOR_LABEL = b'auditorlabel' +ADMIN_PARTITION_LABEL = 'no label' +AUDITOR_LABEL = 'auditorlabel' -ADMINISTRATOR_USERNAME = b'Administrator' -ADMINISTRATOR_PASSWORD = b'1q@W3e$R' +ADMINISTRATOR_USERNAME = 'Administrator' +ADMINISTRATOR_PASSWORD = '1q@W3e$R' -AUDITOR_USERNAME = b'Auditor' -AUDITOR_PASSWORD = b'W3e$R' +AUDITOR_USERNAME = 'Auditor' +AUDITOR_PASSWORD = 'W3e$R' -CO_USERNAME = b'Crypto Officer' -CO_PASSWORD = b'userpin' +CO_USERNAME = 'Crypto Officer' +CO_PASSWORD = 'userpin' -DEFAULT_USERNAME = b'default_user' -DEFAULT_LABEL = b'default_label' -DEFAULT_PASSWORD = b'userpin' +DEFAULT_USERNAME = 'default_user' +DEFAULT_LABEL = 'default_label' +DEFAULT_PASSWORD = 'userpin' DEFAULT_UTILS_PATH = '/usr/safenet/lunaclient/sbin' FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" @@ -38,7 +38,7 @@ DES3_KEY_SIZE = 120 -MANUFACTURER_ID = b"SafeNet Inc." -MODEL = b"Luna K6" +MANUFACTURER_ID = "SafeNet Inc." +MODEL = "Luna K6" ADMIN_SLOT = int(os.environ.get("ADMIN_SLOT", 1)) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index e1d9ffc..676bc17 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -5,14 +5,14 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from .cryptoki import CK_ULONG, \ - C_EncryptInit, C_Encrypt -from .defines import CKR_OK from .attributes import Attributes, to_char_array from .common_utils import AutoCArray, refresh_c_arrays +from .cryptoki import CK_ULONG, \ + C_EncryptInit, C_Encrypt from .cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ C_DecryptUpdate, C_DecryptFinal +from .defines import CKR_OK from .mechanism import Mechanism from .test_functions import make_error_handle_function diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py index 4a1fdd6..a78efae 100644 --- a/pycryptoki/partition_management.py +++ b/pycryptoki/partition_management.py @@ -2,9 +2,9 @@ Functions for managing partitions """ import logging -from functools import reduce from _ctypes import pointer from ctypes import byref, c_ubyte +from functools import reduce from .common_utils import AutoCArray, refresh_c_arrays from .cryptoki import (CK_SLOT_ID, @@ -56,8 +56,8 @@ def ca_create_container(h_session, storage_size, password=None, label='Inserted """ h_sess = CK_SESSION_HANDLE(h_session) h_container = CK_ULONG() - LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=" + str( - storage_size) + ", pin=" + str(password) + ", label=" + label) + LOG.info("CA_CreateContainer: Inserting token with no SO storage_size=%s, pin=%s, label=%s", + storage_size, password, label) if password == '': password = None @@ -70,7 +70,7 @@ def ca_create_container(h_session, storage_size, password=None, label='Inserted password.array, password.size.contents, CK_ULONG(-1), CK_ULONG(-1), CK_ULONG(0), CK_ULONG(0), CK_ULONG(storage_size), byref(h_container)) - LOG.info("CA_CreateContainer: Inserted token into slot " + str(h_container.value)) + LOG.info("CA_CreateContainer: Inserted token into slot %s", h_container.value) return ret, h_container.value diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index e75d619..c5c196a 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -95,7 +95,7 @@ def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): ret = C_OpenSession(CK_SLOT_ID(slot_num), CK_FLAGS(flags), cast(arg3, CK_VOID_PTR), CK_NOTIFY(0), pointer(h_session)) - LOG.info("C_OpenSession: Opening Session. slot=" + str(slot_num)) + LOG.info("C_OpenSession: Opening Session. slot=%s", slot_num) return ret, h_session.value @@ -186,7 +186,7 @@ def c_get_token_info(slot_id): """ token_info = {} c_token_info = CK_TOKEN_INFO() - LOG.info("Getting token info. slot=" + str(slot_id)) + LOG.info("Getting token info. slot=%s", slot_id) ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) if ret == CKR_OK: @@ -259,7 +259,7 @@ def c_close_session(h_session): """ # CLOSE SESSION - LOG.info("C_CloseSession: Closing session " + str(h_session)) + LOG.info("C_CloseSession: Closing session %s", h_session) ret = C_CloseSession(h_session) return ret @@ -274,7 +274,7 @@ def c_logout(h_session): :returns: The result code """ - LOG.info("C_Logout: Logging out of session " + str(h_session)) + LOG.info("C_Logout: Logging out of session %s", h_session) ret = C_Logout(h_session) return ret @@ -291,7 +291,7 @@ def c_init_pin(h_session, pin): """ - LOG.info("C_InitPIN: Initializing PIN to " + str(pin)) + LOG.info("C_InitPIN: Initializing PIN to %s", pin) pin = AutoCArray(data=pin) ret = C_InitPIN(h_session, pin.array, pin.size.contents) return ret @@ -307,7 +307,7 @@ def ca_factory_reset(slot): :returns: The result code """ - LOG.info("CA_FactoryReset: Factory Reset. slot=" + str(slot)) + LOG.info("CA_FactoryReset: Factory Reset. slot=%s", slot) ret = CA_FactoryReset(CK_SLOT_ID(slot), CK_ULONG(0)) return ret @@ -325,7 +325,7 @@ def c_set_pin(h_session, old_pass, new_pass): """ LOG.info("C_SetPIN: Changing password. " - "old_pass=" + str(old_pass) + ", new_pass=" + str(new_pass)) + "old_pass=%s, new_pass=%s", old_pass, new_pass) old_pass = AutoCArray(data=old_pass) new_pass = AutoCArray(data=new_pass) @@ -347,7 +347,7 @@ def c_close_all_sessions(slot): """ - LOG.info("C_CloseAllSessions: Closing all sessions. slot=" + str(slot)) + LOG.info("C_CloseAllSessions: Closing all sessions. slot=%s", slot) ret = C_CloseAllSessions(CK_ULONG(slot)) return ret diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 917a46e..5c33a0a 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -5,13 +5,13 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from .cryptoki import CK_ULONG, \ - CK_BYTE_PTR, C_SignInit, C_Sign -from .defines import CKR_OK from .attributes import to_char_array from .common_utils import refresh_c_arrays, AutoCArray +from .cryptoki import CK_ULONG, \ + CK_BYTE_PTR, C_SignInit, C_Sign from .cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ C_SignFinal, C_VerifyUpdate, C_VerifyFinal +from .defines import CKR_OK from .encryption import _get_string_from_list from .mechanism import Mechanism, NullMech from .test_functions import make_error_handle_function diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 95a53c1..22b5ec0 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -46,7 +46,7 @@ def assert_test_return_value(value, expected_value, message, print_on_success=Tr assert value == expected_value, "\nERROR: " + message + "\n\tExpected: " + exp_code + \ "\n\tFound: " + code if print_on_success: - LOG.info(exp_code + ": " + message) + LOG.info("%s: %s", exp_code, message) class LunaException(Exception): @@ -69,7 +69,7 @@ def __init__(self, error_code, function_name, arguments): if self.error_code in ret_vals_dictionary: self.error_string = ret_vals_dictionary[self.error_code] else: - self.error_string = "Unknown Code=" + str(hex(self.error_code)) + self.error_string = "Unknown Code=%02x" % self.error_code def __str__(self): data = ("\n\tFunction: {func_name}" diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index d8de768..4fe5159 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -7,6 +7,8 @@ from ctypes import byref # Cryptoki Constants +from six import b + from .cryptoki import (CK_ULONG, CK_BBOOL, CK_MECHANISM_TYPE, @@ -37,10 +39,10 @@ def c_init_token(slot_num, password, token_label='Main Token'): :returns: The result code """ - LOG.info("C_InitToken: Initializing token. slot=" + str( - slot_num) + ", label='" + token_label + "', password='" + str(password) + "'") + LOG.info("C_InitToken: Initializing token (slot=%s, label='%s', password='%s')", + slot_num, token_label, password) - if password == '': + if password == b'': password = None password = AutoCArray(data=password) slot_id = CK_ULONG(slot_num) diff --git a/setup.py b/setup.py index 3dbb3eb..38af492 100755 --- a/setup.py +++ b/setup.py @@ -17,6 +17,6 @@ 'pycryptoki.daemon'], scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'], setup_requires=['pytest-runner'], - tests_require=['pytest', 'hypothesis', 'mock'], - requires=['future', 'rpyc'] + tests_require=['pytest', 'hypothesis', 'mock', 'pytz'], + requires=['future', 'rpyc', 'six'] ) diff --git a/tests/functional/conftest.py b/tests/functional/conftest.py index 880a537..83b2dac 100644 --- a/tests/functional/conftest.py +++ b/tests/functional/conftest.py @@ -8,15 +8,7 @@ # From http://stackoverflow.com/a/7759927 from pycryptoki.test_functions import LunaException -if sys.version_info < (3,): - def b(x): - return x -else: - import codecs - - def b(x): - return codecs.latin_1_encode(x)[0] - +from six import b import pytest from . import config as hsm_config @@ -106,9 +98,9 @@ def pytest_configure(config): co_pwd = config.getoption("copassword", default=CO_PASSWORD) if admin_pwd: - admin_pwd = b(admin_pwd) + admin_pwd = admin_pwd if co_pwd: - co_pwd = b(co_pwd) + co_pwd = co_pwd hsm_config['admin_pwd'] = admin_pwd hsm_config['co_pwd'] = co_pwd diff --git a/tests/functional/test_usage_limit_and_count.py b/tests/functional/test_usage_limit_and_count.py index 25d91f2..aa0341e 100755 --- a/tests/functional/test_usage_limit_and_count.py +++ b/tests/functional/test_usage_limit_and_count.py @@ -47,7 +47,7 @@ def test_set_attribute_usage_limit_sym(self): h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - LOG.info("Called c-generate: Key handle -" + str(h_key)) + LOG.info("Called c-generate: Key handle -%s", h_key) usage_limit = 5 c_set_attribute_value_ex(self.h_session, @@ -57,7 +57,7 @@ def test_set_attribute_usage_limit_sym(self): template={CKA_USAGE_LIMIT: None}) usage_val_out = out_template[CKA_USAGE_LIMIT] - LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :%s", usage_val_out) assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" def test_usage_limit_attribute_check_sym_des(self): @@ -79,7 +79,7 @@ def test_usage_limit_attribute_check_sym_des(self): h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - LOG.info("Called c-generate: Key handle -" + str(h_key)) + LOG.info("Called c-generate: Key handle -%s", h_key) c_set_attribute_value_ex(self.h_session, h_key, usage_lim_template) @@ -92,7 +92,7 @@ def test_usage_limit_attribute_check_sym_des(self): template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" @@ -127,7 +127,7 @@ def test_usage_limit_attribute_check_sym_aes(self): template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" @@ -151,8 +151,7 @@ def test_set_attribute_usage_limit_Assym(self): prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, mech=None) LOG.info( - "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( - h_prkey)) + "Called c-generate: Public Key handle: %s Private Key Handle: %s", h_pbkey, h_prkey) usage_limit = 2 c_set_attribute_value_ex(self.h_session, @@ -161,7 +160,7 @@ def test_set_attribute_usage_limit_Assym(self): py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_LIMIT: None}) usage_val_out = py_template[CKA_USAGE_LIMIT] - LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue: %s", usage_val_out) assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" def test_usage_limit_attribute_check_Assym(self): @@ -188,8 +187,7 @@ def test_usage_limit_attribute_check_Assym(self): mech=None) LOG.info( - "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( - h_prkey)) + "Called c-generate: Public Key handle -%s Private Key Handle -%s", h_pbkey, h_prkey) c_set_attribute_value_ex(self.h_session, h_pbkey, usage_lim_template) @@ -201,7 +199,7 @@ def test_usage_limit_attribute_check_Assym(self): template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): @@ -231,13 +229,13 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) return_val, data = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) - LOG.info("Called C_Encrypt, return code: " + str(return_val)) + LOG.info("Called C_Encrypt, return code: %s", return_val) py_template = c_get_attribute_value_ex(self.h_session, h_key, template={CKA_USAGE_COUNT: None}) usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue :" + str(usage_val_out)) + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" @@ -260,8 +258,7 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): mech=None) LOG.info( - "Called c-generate: Public Key handle -" + str(h_pbkey) + "Private Key Handle" + str( - h_prkey)) + "Called c-generate: Public Key handle -%s Private Key Handle - %s", h_pbkey, h_prkey) c_set_attribute_value_ex(self.h_session, h_pbkey, usage_lim_template) @@ -271,7 +268,7 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) return_val, data = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) - LOG.info("Called C_Encrypt, return code: " + str(return_val)) + LOG.info("Called C_Encrypt, return code: %s", return_val) py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_COUNT: None}) diff --git a/tests/unittests/test_attr_conversions.py b/tests/unittests/test_attr_conversions.py index c6e8467..db90072 100644 --- a/tests/unittests/test_attr_conversions.py +++ b/tests/unittests/test_attr_conversions.py @@ -1,29 +1,38 @@ """ Unit tests for python/c type conversions """ -import pytest import logging - -from hypothesis import given -from hypothesis.strategies import integers, floats, text, booleans, lists, dictionaries, one_of -from hypothesis.extra.datetime import dates - from _ctypes import POINTER -from ctypes import cast, c_void_p, c_ulong, sizeof - -from pycryptoki.attributes import CK_ATTRIBUTE, CKA_CLASS, CK_BYTE, to_long, to_bool, to_char_array, \ - to_ck_date, to_byte_array, to_sub_attributes, Attributes, \ - convert_c_ubyte_array_to_string - from binascii import hexlify +from collections import defaultdict +from ctypes import cast, c_void_p, c_ulong, sizeof from string import ascii_letters as letters +import mock +import pytest +from hypothesis import given +from hypothesis.extra.datetime import dates +from hypothesis.strategies import integers, floats, text, booleans, lists, dictionaries, one_of +from six import b + +from pycryptoki.attributes import (CK_ATTRIBUTE, + CKA_CLASS, + CK_BYTE, + to_long, + to_bool, + to_char_array, + to_ck_date, + to_byte_array, + to_sub_attributes, + Attributes, + convert_c_ubyte_array_to_string, KEY_TRANSFORMS) +from pycryptoki.test_functions import integer_types + LOG = logging.getLogger(__name__) MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 class TestAttrConversions(object): - def verify_c_type(self, pointer, leng): """ Verifies that (pointer, leng) is a proper c type @@ -31,7 +40,7 @@ def verify_c_type(self, pointer, leng): :param leng: length of c data """ assert isinstance(pointer, c_void_p) - assert isinstance(leng, (long, int, c_ulong)) + assert isinstance(leng, (integer_types, c_ulong)) def create_ck_attr(self, pointer, leng): """ @@ -74,7 +83,7 @@ def test_to_long(self, int_val): self.verify_c_type(pointer, leng) # C type is unsigned integer. Assert result is positive. - assert cast(pointer, POINTER(c_ulong)).contents >= 0 + assert cast(pointer, POINTER(c_ulong)).contents.value >= 0 py_long = self.reverse_case(pointer, leng, to_long) assert int_val == py_long @@ -138,11 +147,11 @@ def test_to_char_array_string(self, txt_val): to_char_array() with param: :param txt_val: random string """ - pointer, leng = to_char_array(str(txt_val)) + pointer, leng = to_char_array(txt_val) self.verify_c_type(pointer, leng) py_txt = self.reverse_case(pointer, leng, to_char_array) - assert txt_val == py_txt + assert b(txt_val) == py_txt @given(lists(elements=text(alphabet=letters, min_size=1, max_size=1), min_size=1)) def test_to_char_array_list(self, list_val): @@ -154,7 +163,7 @@ def test_to_char_array_list(self, list_val): self.verify_c_type(pointer, leng) py_txt = self.reverse_case(pointer, leng, to_char_array) - assert "".join(list_val) == py_txt + assert b("".join(list_val)) == py_txt def test_to_char_array_fail_obj(self): """ @@ -168,12 +177,12 @@ def test_to_ck_date_string(self, date_val): to_ck_date() with param: :param date_val: random date to be converted to date-string """ - date_string = str(date_val).replace("-", "") + date_string = date_val.strftime("%Y%m%d") pointer, leng = to_ck_date(date_string) self.verify_c_type(pointer, leng) py_date = self.reverse_case(pointer, leng, to_ck_date) - assert date_string == str(py_date) + assert b(date_string) == py_date @given(dates(min_year=1900)) def test_to_ck_date_dict(self, date_val): @@ -186,7 +195,7 @@ def test_to_ck_date_dict(self, date_val): self.verify_c_type(pointer, leng) py_date = self.reverse_case(pointer, leng, to_ck_date) - assert (str(date_val).replace("-", "")) == py_date + assert b(date_val.strftime("%Y%m%d")) == py_date @given(dates(min_year=1900)) def test_to_ck_date(self, date_val): @@ -198,7 +207,7 @@ def test_to_ck_date(self, date_val): self.verify_c_type(pointer, leng) py_date = self.reverse_case(pointer, leng, to_ck_date) - assert str(date_val).replace("-", "") == py_date + assert b(date_val.strftime("%Y%m%d")) == py_date def test_to_ck_date_fail_obj(self): """ @@ -242,7 +251,7 @@ def test_to_byte_array_int_neg_overflow(self, int_val): self.verify_c_type(pointer, leng) py_bytes = self.reverse_case(pointer, leng, to_byte_array) - LOG.debug("to_byte_array() data loss: %s => %s", str(hex(int_val)), str(py_bytes)) + LOG.debug("to_byte_array() data loss: %s => %s", b(hex(int_val)), py_bytes) assert int(py_bytes, 16) != int_val @given(lists(elements=integers(min_value=0, max_value=255))) @@ -287,13 +296,13 @@ def test_to_byte_array_fail_obj(self): """ self.force_fail(object(), to_byte_array, TypeError) - @given(text(alphabet=letters, min_size=1)) + @given(text(alphabet="ghijklmnopqrstuvwxyz", min_size=1)) def test_to_byte_array_fail_str(self, txt_val): """ to_byte_array() with incompatible param: :param txt_val: random text -TypeError """ - self.force_fail(txt_val, to_byte_array, TypeError) + self.force_fail(txt_val, to_byte_array, ValueError) @given(integers(min_value=0)) def test_to_byte_array_hexstring(self, int_val): @@ -308,14 +317,18 @@ def test_to_byte_array_hexstring(self, int_val): py_bytes = self.reverse_case(pointer, leng, to_byte_array) assert int(py_bytes, 16) == int(hex_string, 16) - @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), dict_class=Attributes, values=booleans())) + @given(dictionaries(keys=integers(min_value=1, max_value=MAX_INT), dict_class=Attributes, + values=booleans())) def test_to_sub_attributes(self, test_dic): """ to_sub_attributes() with param :param test_dic: random dictionary of bools """ - pointer, leng = to_sub_attributes(test_dic) - self.verify_c_type(pointer, leng) + mock_xform_dict = defaultdict(lambda: to_bool) + mock_xform_dict.update({key: to_bool for key in KEY_TRANSFORMS}) + with mock.patch('pycryptoki.attributes.KEY_TRANSFORMS', new=mock_xform_dict): + pointer, leng = to_sub_attributes(test_dic) + self.verify_c_type(pointer, leng) @given(integers()) def test_to_sub_attributes_fail(self, int_val): diff --git a/tests/unittests/test_auto_c_array.py b/tests/unittests/test_auto_c_array.py index 2e3564a..ce56ad6 100644 --- a/tests/unittests/test_auto_c_array.py +++ b/tests/unittests/test_auto_c_array.py @@ -1,16 +1,15 @@ """ Unit tests for AutoCArray in common_util.py """ -import pytest - -from pycryptoki.common_utils import AutoCArray - from ctypes import * +from string import ascii_letters +import pytest from hypothesis import given from hypothesis.strategies import text, lists, sampled_from, integers +from six import b, binary_type -from string import ascii_letters +from pycryptoki.common_utils import AutoCArray c_types = [c_short, c_ushort, c_long, c_ulong, c_int, c_uint, c_float, c_double, c_longdouble, c_longlong, c_ulonglong, c_byte, c_ubyte, c_char, c_char_p, c_void_p, c_bool] @@ -19,7 +18,6 @@ class TestAutoCArray(object): - @given(sampled_from(c_types)) def test_auto_c_array_empty(self, typ_val): """ @@ -33,7 +31,7 @@ def test_auto_c_array_empty(self, typ_val): assert c_array.ctype == typ_val if typ_val == c_char: - assert c_array.array.contents.value == typ_val('\x00').value + assert c_array.array.contents.value == typ_val(b'\x00').value else: assert c_array.array.contents.value == typ_val(0).value @@ -47,7 +45,7 @@ def test_auto_c_array_string(self, str_val): assert c_array.size.contents.value == len(c_array) == len(str_val) assert c_array.ctype == c_ubyte - assert "".join(c_array) == str_val + assert b"".join(c_array) == b(str_val) @given(lists(elements=integers(min_value=-128, max_value=127), min_size=1)) def test_auto_c_array_byte_list(self, list_val): @@ -60,7 +58,7 @@ def test_auto_c_array_byte_list(self, list_val): assert c_array.size.contents.value == len(c_array) == len(list_val) assert c_array.ctype == c_byte - assert "".join([str(c_byte(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert b"".join([bytes(c_byte(x)) for x in c_array]) == b"".join([bytes(x) for x in list_val]) assert c_array.array[0] == cast(c_array.array, POINTER(c_byte)).contents.value @given(lists(elements=integers(min_value=0, max_value=256), min_size=1)) @@ -74,10 +72,13 @@ def test_auto_c_array_ubyte_list(self, list_val): assert c_array.size.contents.value == len(c_array) == len(list_val) assert c_array.ctype == c_ubyte - assert "".join([str(c_ubyte(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert b"".join([bytes(c_ubyte(x)) for x in c_array]) == b"".join( + [bytes(x) for x in list_val]) assert c_array.array[0] == cast(c_array.array, POINTER(c_ubyte)).contents.value - @given(lists(elements=integers(min_value=(-MAX_INT/2), max_value=MAX_INT/2), min_size=1)) + @given(lists(elements=integers(min_value=int(-MAX_INT / 2), + max_value=int(MAX_INT / 2)), + min_size=1)) def test_auto_c_array_long_list(self, list_val): """ Initalize an array from list of long's @@ -88,7 +89,8 @@ def test_auto_c_array_long_list(self, list_val): assert c_array.size.contents.value == len(c_array) == len(list_val) assert c_array.ctype == c_long - assert "".join([str(c_long(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert b"".join([bytes(c_long(x)) for x in c_array]) == b"".join( + [bytes(x) for x in list_val]) assert c_array.array[0] == cast(c_array.array, POINTER(c_long)).contents.value @given(lists(elements=integers(min_value=0, max_value=MAX_INT), min_size=1)) @@ -102,7 +104,8 @@ def test_auto_c_array_ulong_list(self, list_val): assert c_array.size.contents.value == len(c_array) == len(list_val) assert c_array.ctype == c_ulong - assert "".join([str(c_ulong(x)) for x in c_array]) == "".join([str(x) for x in list_val]) + assert b"".join([bytes(c_ulong(x)) for x in c_array]) == b"".join( + [bytes(x) for x in list_val]) assert c_array.array[0] == cast(c_array.array, POINTER(c_ulong)).contents.value @given(lists(elements=text(alphabet=ascii_letters, min_size=1, max_size=1), min_size=1)) @@ -111,12 +114,13 @@ def test_auto_c_array_char_list(self, list_val): Initalize an array from list of c_chars :param list_val: list of char to be converted to c_char's """ - new_list_val = [c_char(str(x)) for x in list_val] + list_val = [bytes(b(x)) for x in list_val] + new_list_val = [c_char(x) for x in list_val] c_array = AutoCArray(data=new_list_val, ctype=c_char) assert c_array.size.contents.value == len(c_array) == len(list_val) assert c_array.ctype == c_char - assert "".join([str(x) for x in c_array]) == "".join([str(x) for x in list_val]) + assert b"".join([x for x in c_array]) == b"".join(list_val) assert c_array.array[0] == cast(c_array.array, POINTER(c_char)).contents.value @given(list_val=lists(elements=integers(min_value=0, max_value=127), min_size=1)) @@ -128,7 +132,7 @@ def test_auto_c_array_no_type_fail(self, list_val, test_type): :param test_type: c_types to test with """ if test_type == c_char: - new_list = [c_char(chr(x)) for x in list_val] + new_list = [c_char(b(chr(x))) for x in list_val] else: new_list = [test_type(x) for x in list_val] diff --git a/tests/unittests/test_encryption.py b/tests/unittests/test_encryption.py index 0d3842c..77497fe 100644 --- a/tests/unittests/test_encryption.py +++ b/tests/unittests/test_encryption.py @@ -4,6 +4,7 @@ import pytest from hypothesis import given from hypothesis.strategies import text, integers, data, lists +from six import b import pycryptoki.encryption as encrypt @@ -30,5 +31,6 @@ def test_get_string_from_list(self, list_val): _get_string_from_list w/ list of random text :param list_val: list of random text """ - assert encrypt._get_string_from_list(list_val) == "".join(list_val) + list_val = [b(x) for x in list_val] + assert encrypt._get_string_from_list(list_val) == b"".join(list_val) diff --git a/tests/unittests/test_mechanisms.py b/tests/unittests/test_mechanisms.py index db5aef1..45f6257 100644 --- a/tests/unittests/test_mechanisms.py +++ b/tests/unittests/test_mechanisms.py @@ -42,7 +42,7 @@ 'sourceData': list(range(12)), 'test_id': 'RSA_OAEP'}, CKM_AES_GCM: {'iv': list(range(16)), - 'AAD': b'testme', + 'AAD': 'testme', 'ulTagBits': 32, 'test_id': 'AES_GCM'}, CKM_RSA_PKCS_PSS: {'hashAlg': CKM_SHA_1, @@ -125,7 +125,7 @@ def test_exact_mechanism_use(self): :return: """ mech = AESGCMMechanism(mech_type=CKM_AES_GCM, - params={'AAD': b'notsosecret', + params={'AAD': 'notsosecret', 'iv': list(range(12)), 'ulTagBits': 32}) cmech = mech.to_c_mech() From 0890fd8294e4dfacc8f8d2f1445661a0e6913613 Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Tue, 5 Jul 2016 15:41:24 -0400 Subject: [PATCH 059/109] LA-1924 pycryptoki functional tests Change-Id: I072d8bdb9ced14136aca708f1418321acb2d72a3 LA-1924 Test encrypt / decrypt Change-Id: I072d8bdb9ced14136aca708f1418321acb2d72a3 --- tests/functional/test_audit_handling.py | 25 ++ tests/functional/test_encrypt_decrypt.py | 267 ++++++++++++++++---- tests/functional/test_session_management.py | 32 +++ 3 files changed, 277 insertions(+), 47 deletions(-) create mode 100644 tests/functional/test_audit_handling.py create mode 100644 tests/functional/test_session_management.py diff --git a/tests/functional/test_audit_handling.py b/tests/functional/test_audit_handling.py new file mode 100644 index 0000000..3f82d12 --- /dev/null +++ b/tests/functional/test_audit_handling.py @@ -0,0 +1,25 @@ +import logging +import pytest + +from . import config as hsm_config +from pycryptoki.defines import CKR_OK +import pycryptoki.audit_handling as audit_handling + +from ctypes import c_ulong + +logger = logging.getLogger(__name__) + + +class TestAuditHandling(object): + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.admin_slot = hsm_config["test_slot"] + self.h_session = auth_session + + def test_ca_get_time(self): + """ ca_get_time() """ + ret, hsm_time = audit_handling.ca_get_time(self.h_session) + assert ret == CKR_OK + # Checks time formatting but not value of returned time + assert isinstance(hsm_time, c_ulong) diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index dcc6cde..b42bc59 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -1,64 +1,237 @@ +""" Functional tests for encryption / decryption """ import logging - import pytest -from . import config as hsm_config -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP -from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK -from pycryptoki.encryption import c_encrypt, c_decrypt, _split_string_into_list, \ - _get_string_from_list -from pycryptoki.key_generator import c_generate_key_ex +from pycryptoki.default_templates import get_default_key_template, get_default_key_pair_template, \ + MECHANISM_LOOKUP_EXT +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex, c_destroy_object +from pycryptoki.encryption import _split_string_into_list, _get_string_from_list, \ + c_encrypt, c_decrypt from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.defines import (CKM_DES_CBC, CKM_DES_KEY_GEN, + CKM_AES_CBC, CKM_AES_ECB, CKM_AES_GCM, CKM_AES_KEY_GEN, + CKM_DES3_CBC, CKM_DES3_ECB, CKM_DES3_CBC_PAD, CKM_DES3_KEY_GEN, + CKM_CAST3_CBC, CKM_CAST3_ECB, CKM_CAST3_KEY_GEN, + CKM_CAST5_CBC, CKM_CAST5_ECB, CKM_CAST5_KEY_GEN, + CKM_RC4, CKM_RC4_KEY_GEN, + CKM_RSA_PKCS, CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_X_509, CKM_RSA_X9_31_KEY_PAIR_GEN,) + +from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_DEVICE_MEMORY) + logger = logging.getLogger(__name__) +SYM_TABLE = {CKM_DES_CBC: CKM_DES_KEY_GEN, + CKM_AES_CBC: CKM_AES_KEY_GEN, + CKM_AES_ECB: CKM_AES_KEY_GEN, + CKM_AES_GCM: CKM_AES_KEY_GEN, + CKM_DES3_CBC: CKM_DES3_KEY_GEN, + CKM_DES3_ECB: CKM_DES3_KEY_GEN, + CKM_DES3_CBC_PAD: CKM_DES3_KEY_GEN, + CKM_CAST3_CBC: CKM_CAST3_KEY_GEN, + CKM_CAST3_ECB: CKM_CAST3_KEY_GEN, + CKM_CAST5_CBC: CKM_CAST5_KEY_GEN, + CKM_CAST5_ECB: CKM_CAST5_KEY_GEN, + CKM_RC4: CKM_RC4_KEY_GEN} +ASYM_TABLE = {CKM_RSA_PKCS: CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_X_509: CKM_RSA_X9_31_KEY_PAIR_GEN} + +# MECH_FLAVOR: () +# *** Update as additional test params are added *** +PARAM_TABLE = {CKM_DES_CBC: [{}, {'iv': list(range(8))}], + CKM_AES_CBC: [{}, {'iv': list(range(16))}], + CKM_AES_ECB: [{}], + CKM_AES_GCM: [{'iv': list(range(16)), 'AAD': b'notsosecret', 'ulTagBits': 32}], + CKM_DES3_CBC: [{}, {'iv': list(range(8))}], + CKM_DES3_ECB: [{}], + CKM_DES3_CBC_PAD: [{}, {'iv': list(range(8))}], + CKM_CAST3_CBC: [{}, {'iv': list(range(8))}], + CKM_CAST3_ECB: [{}], + CKM_CAST5_CBC: [{}], + CKM_CAST5_ECB: [{}], + CKM_RC4: [{}], + CKM_RSA_PKCS: [{}], + CKM_RSA_X_509: [{}]} + +# TESTING DATA +PAD = b"a" * 0xfff0 +RAW = b"abcdefghijk" + +# Flavors which auto-pad (will return 'CKR_OK' on un-padded(RAW) data) +PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, CKM_RC4, CKM_AES_GCM] + +# Flavors which are not compatible with multi encrypt/decrypt +NOT_MULTI = [CKM_AES_GCM] + + +def ret_val(mech, data): + """ + Determine expected ret during encryption of 'data' with 'mech' + :param mech: mechanism + :param data: type of data + :return: expected return value + """ + if data == RAW: + if mech not in PADDING_ALGORITHMS: + return CKR_DATA_LEN_RANGE + else: + return CKR_OK + else: + if mech == CKM_AES_GCM: + return CKR_DEVICE_MEMORY + else: + return CKR_OK + + +def scenarios(which_table): + """ + :param which_table: SYM_KEY_TABLE or ASYM_KEY_TABLE + :return: List of encrypt/decrypt test scenarios + """ + ret_list = [] + for mech in which_table.keys(): + for params in PARAM_TABLE[mech]: + ret_list.append((mech, params)) + + return ret_list + + +def idfn(k_table): + """ Generate test ids """ + id_list = [] + for s in scenarios(k_table): + m_type, params = s + id_str = MECHANISM_LOOKUP_EXT[m_type][0].replace("CKM_", "") + for p in params: + id_str += "-" + str(p) + id_list.append(id_str) + + return id_list + + +@pytest.yield_fixture(scope='class') +def sym_keys(auth_session): + """ Fixture containing all sym. keys""" + keys = {} + try: + for key_type in SYM_TABLE.values(): + template = get_default_key_template(key_type) + keys[key_type] = c_generate_key_ex(auth_session, key_type, template) + yield keys + finally: + for handle in keys.values(): + c_destroy_object(auth_session, handle) + + +@pytest.yield_fixture(scope='class') +def asym_keys(auth_session): + """ Fixture containing all asym. keys """ + keys = {} + try: + for key_type in ASYM_TABLE.values(): + pub_temp, prv_temp = get_default_key_pair_template(key_type) + keys[key_type] = c_generate_key_pair_ex(auth_session, key_type, pub_temp, prv_temp) + yield keys + finally: + for pub_key, prv_key in keys.values(): + c_destroy_object(auth_session, pub_key) + c_destroy_object(auth_session, prv_key) + class TestEncryptData(object): - """ """ - @pytest.fixture(autouse=True) - def setup_teardown(self, auth_session): - self.admin_slot = hsm_config["test_slot"] - self.h_session = auth_session + def verify_ret(self, ret, expected_ret): + """ + Assert that ret is as expected + :param ret: the actual return value + :param expected_ret: the expected return value + """ + assert ret == expected_ret, "Function should return: " + \ + ret_vals_dictionary[expected_ret] + ".\nInstead returned: " + ret_vals_dictionary[ret] - def test_encrypt_decrypt_string(self): - """Tests encrypting and decrypting a string with a key""" - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + def verify_data(self, starting_data, ending_data): + """ + Assert that the data is the same before and after encryption / decryption + :param starting_data: the initial data + :param ending_data: the data after encryption / decryption + """ + assert starting_data == ending_data, "The data after encryption/decryption is incorrect.\n" + \ + "Starting data: " + str(starting_data) + "\nEnding data: " + str(ending_data) - data_to_encrypt = b"a" * 0xfff0 - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, \ - "Encryption should go through successfully, instead it returned " + \ - ret_vals_dictionary[ret] + @pytest.mark.parametrize('data', [PAD, RAW], ids=["Pad", "Raw"]) + @pytest.mark.parametrize(('m_type', 'params'), scenarios(SYM_TABLE), ids=idfn(SYM_TABLE)) + def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session): + """ + test encryption decryption calls of sym. crypto's + :param m_type: mechanism flavor + :param params: extra params + :param data: testing data + :param sym_keys: key fixture + :param auth_session: + """ + exp_ret = ret_val(m_type, data) + h_key = sym_keys[SYM_TABLE[m_type]] - ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data) - assert ret == CKR_OK, \ - "There should be no errors when decrypting, instead found " + ret_vals_dictionary[ret] - assert decrypted_string == data_to_encrypt, \ - "The decrypted data should be the same as the " \ - "data that was encrypted. Instead found " + str(decrypted_string) + ret, encrypted = c_encrypt(auth_session, m_type, h_key, data, extra_params=params) + self.verify_ret(ret, exp_ret) - def test_multipart_encrypt_decrypt(self): - """Tests encryption and decryption using C_EncryptUpdate and C_DecryptUpdate therefore - doing it in multiple - parts + # If not expecting error, proceed with testing + if exp_ret == CKR_OK: + ret, end_data = c_decrypt(auth_session, m_type, h_key, encrypted, extra_params=params) + self.verify_ret(ret, exp_ret) + self.verify_data(data, end_data) + @pytest.mark.parametrize('data', [PAD, RAW], ids=["Pad", "Raw"]) + @pytest.mark.parametrize(('m_type', 'params'), scenarios(SYM_TABLE), ids=idfn(SYM_TABLE)) + def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session): + """ + test encryption decryption calls of sym. crypto's + :param m_type: mechanism flavor + :param params: extra params + :param data: testing data + :param sym_keys: key fixture + :param auth_session: """ - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - - data_to_encrypt = [b'a' * 512, b'b' * 512, b'c' * 512, b'd' * 512] - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, "Encryption should go through successfully, instead it returned " + \ - ret_vals_dictionary[ret] - assert len(encrypted_data) == len(b"".join(data_to_encrypt)) - - encrypted_data_chunks = _split_string_into_list(encrypted_data, 512) - - ret, decrypted_data = c_decrypt(self.h_session, CKM_DES_CBC, h_key, encrypted_data_chunks) - assert ret == CKR_OK, "Decryption should succeed, instead it returned " + \ - ret_vals_dictionary[ret] - assert _get_string_from_list( - data_to_encrypt) == decrypted_data, "The data before encryption should match the data " \ - "" \ - "after encryption" + if m_type in NOT_MULTI: + pytest.xfail("m_type does not support multi encrypt/decrypt") + + exp_ret = ret_val(m_type, data) + h_key = sym_keys[SYM_TABLE[m_type]] + encrypt_this = [data, data, data, data] + + ret, encrypted = c_encrypt(auth_session, m_type, h_key, encrypt_this, extra_params=params) + self.verify_ret(ret, exp_ret) + + # If not expecting error, proceed with testing + if exp_ret == CKR_OK: + if m_type not in PADDING_ALGORITHMS: + assert len(encrypted) == len(b"".join(encrypt_this)) + + decrypt_this = _split_string_into_list(encrypted, len(data)) + ret, end_data = c_decrypt(auth_session, m_type, h_key, decrypt_this, extra_params=params) + self.verify_ret(ret, exp_ret) + + self.verify_data(_get_string_from_list(encrypt_this), end_data) + + @pytest.mark.parametrize(('m_type', 'params'), scenarios(ASYM_TABLE), ids=idfn(ASYM_TABLE)) + def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session): + """ + test encryption decryption calls of asym. crypto's + :param m_type: mechanism flavor + :param params: extra params + :param asym_keys: key fixture + :param auth_session: + """ + pub_key, prv_key = asym_keys[ASYM_TABLE[m_type]] + + ret, decrypt_this = c_encrypt(auth_session, m_type, pub_key, RAW, extra_params=params) + self.verify_ret(ret, CKR_OK) + + ret, decrypted_data = c_decrypt(auth_session, m_type, prv_key, decrypt_this, extra_params=params) + self.verify_ret(ret, CKR_OK) + + # Format to remove leading whitespace which causes problems during assert (RSA_X_509) + decrypted_data = decrypted_data.replace("\x00", "") + self.verify_data(RAW, decrypted_data) diff --git a/tests/functional/test_session_management.py b/tests/functional/test_session_management.py new file mode 100644 index 0000000..4c7ec2b --- /dev/null +++ b/tests/functional/test_session_management.py @@ -0,0 +1,32 @@ +import pytest +import logging + +from . import config as hsm_config +from pycryptoki.defines import CKR_OK +import pycryptoki.session_management as sess_mang + +logger = logging.getLogger(__name__) + + +class TestSessionManagement(object): + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.admin_slot = hsm_config["test_slot"] + self.h_session = auth_session + + def test_c_get_session_info(self): + """ c_get_session_info() """ + ret, sess_info = sess_mang.c_get_session_info(self.h_session) + assert ret == CKR_OK + # Checks that session_info dictionary is the right format. Does not check the values + assert isinstance(sess_info['state'], long) + assert isinstance(sess_info['flags'], long) + assert isinstance(sess_info['slotID'], long) + assert isinstance(sess_info['usDeviceError'], long) + + def test_get_slot_dict(self): + """ get_slot_dict() """ + ret, slot_dict = sess_mang.get_slot_dict() + assert ret == CKR_OK + assert isinstance(slot_dict, dict) From 3f5918306122acf6a4b27a85622858cb2296c77a Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Thu, 21 Jul 2016 15:48:21 -0400 Subject: [PATCH 060/109] LA-1924 Expand on Encrypt / Decrypt tests Change-Id: If264151f91de8f73d9d30c77fde7a086a4e45b67 --- tests/functional/test_encrypt_decrypt.py | 62 +++++++++++++++++++----- 1 file changed, 50 insertions(+), 12 deletions(-) diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index b42bc59..ffd13a7 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -4,7 +4,7 @@ from pycryptoki.default_templates import get_default_key_template, get_default_key_pair_template, \ MECHANISM_LOOKUP_EXT -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex, c_destroy_object +from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, c_destroy_object from pycryptoki.encryption import _split_string_into_list, _get_string_from_list, \ c_encrypt, c_decrypt from pycryptoki.return_values import ret_vals_dictionary @@ -14,11 +14,13 @@ CKM_DES3_CBC, CKM_DES3_ECB, CKM_DES3_CBC_PAD, CKM_DES3_KEY_GEN, CKM_CAST3_CBC, CKM_CAST3_ECB, CKM_CAST3_KEY_GEN, CKM_CAST5_CBC, CKM_CAST5_ECB, CKM_CAST5_KEY_GEN, + CKM_RC2_CBC, CKM_RC2_ECB, CKM_RC2_CBC_PAD, CKM_RC2_KEY_GEN, CKM_RC4, CKM_RC4_KEY_GEN, - CKM_RSA_PKCS, CKM_RSA_PKCS_KEY_PAIR_GEN, - CKM_RSA_X_509, CKM_RSA_X9_31_KEY_PAIR_GEN,) + CKM_RSA_PKCS, CKM_RSA_PKCS_OAEP, CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_X_509, CKM_RSA_X9_31_KEY_PAIR_GEN, + CKM_SHA_1, CKG_MGF1_SHA1) -from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_DEVICE_MEMORY) +from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_DEVICE_MEMORY, CKR_KEY_SIZE_RANGE) logger = logging.getLogger(__name__) @@ -33,8 +35,12 @@ CKM_CAST3_ECB: CKM_CAST3_KEY_GEN, CKM_CAST5_CBC: CKM_CAST5_KEY_GEN, CKM_CAST5_ECB: CKM_CAST5_KEY_GEN, + CKM_RC2_CBC: CKM_RC2_KEY_GEN, + CKM_RC2_ECB: CKM_RC2_KEY_GEN, + CKM_RC2_CBC_PAD: CKM_RC2_KEY_GEN, CKM_RC4: CKM_RC4_KEY_GEN} ASYM_TABLE = {CKM_RSA_PKCS: CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_OAEP: CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X_509: CKM_RSA_X9_31_KEY_PAIR_GEN} # MECH_FLAVOR: () @@ -50,8 +56,12 @@ CKM_CAST3_ECB: [{}], CKM_CAST5_CBC: [{}], CKM_CAST5_ECB: [{}], + CKM_RC2_CBC: [{'iv': list(range(8)), 'usEffectiveBits': 8}], + CKM_RC2_ECB: [{'usEffectiveBits': 8}], + CKM_RC2_CBC_PAD: [{'iv': list(range(8)), 'usEffectiveBits': 8}], CKM_RC4: [{}], CKM_RSA_PKCS: [{}], + CKM_RSA_PKCS_OAEP: [{'hashAlg': CKM_SHA_1, 'mgf': CKG_MGF1_SHA1, 'sourceData': list(range(12))}], CKM_RSA_X_509: [{}]} # TESTING DATA @@ -59,11 +69,14 @@ RAW = b"abcdefghijk" # Flavors which auto-pad (will return 'CKR_OK' on un-padded(RAW) data) -PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, CKM_RC4, CKM_AES_GCM] +PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, CKM_RC2_CBC_PAD, CKM_RC4, CKM_AES_GCM] # Flavors which are not compatible with multi encrypt/decrypt NOT_MULTI = [CKM_AES_GCM] +# Ret error, however encrypt /decrypt is successful. Needs to be addressed at some point +KEY_SIZE_RANGE = [CKM_RC2_CBC, CKM_RC2_ECB, CKM_RC2_CBC_PAD] + def ret_val(mech, data): """ @@ -72,6 +85,10 @@ def ret_val(mech, data): :param data: type of data :return: expected return value """ + # Ret error, however encrypt /decrypt is successful. Needs to be addressed at some point + if mech in KEY_SIZE_RANGE: + return CKR_KEY_SIZE_RANGE + if data == RAW: if mech not in PADDING_ALGORITHMS: return CKR_DATA_LEN_RANGE @@ -117,8 +134,14 @@ def sym_keys(auth_session): try: for key_type in SYM_TABLE.values(): template = get_default_key_template(key_type) - keys[key_type] = c_generate_key_ex(auth_session, key_type, template) + + ret, key_handle = c_generate_key(auth_session, key_type, template) + if ret == CKR_OK: + keys[key_type] = key_handle + else: + logger.info("Failed to generate key: {}\nReturn code: {}".format(key_type, ret)) yield keys + finally: for handle in keys.values(): c_destroy_object(auth_session, handle) @@ -131,8 +154,14 @@ def asym_keys(auth_session): try: for key_type in ASYM_TABLE.values(): pub_temp, prv_temp = get_default_key_pair_template(key_type) - keys[key_type] = c_generate_key_pair_ex(auth_session, key_type, pub_temp, prv_temp) + + ret, pub_key, prv_key = c_generate_key_pair(auth_session, key_type, pub_temp, prv_temp) + if ret == CKR_OK: + keys[key_type] = (pub_key, prv_key) + else: + logger.info("Failed to generate key: {}\nReturn code: {}".format(key_type, ret)) yield keys + finally: for pub_key, prv_key in keys.values(): c_destroy_object(auth_session, pub_key) @@ -170,6 +199,10 @@ def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session) :param sym_keys: key fixture :param auth_session: """ + # Auto-fail when key-generation fails + if sym_keys.get(SYM_TABLE[m_type]) is None: + pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) + exp_ret = ret_val(m_type, data) h_key = sym_keys[SYM_TABLE[m_type]] @@ -177,7 +210,7 @@ def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session) self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing - if exp_ret == CKR_OK: + if exp_ret == (CKR_OK or KEY_SIZE_RANGE): ret, end_data = c_decrypt(auth_session, m_type, h_key, encrypted, extra_params=params) self.verify_ret(ret, exp_ret) @@ -197,6 +230,10 @@ def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_se if m_type in NOT_MULTI: pytest.xfail("m_type does not support multi encrypt/decrypt") + # Auto-fail when key-generation is fails + if sym_keys.get(SYM_TABLE[m_type]) is None: + pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) + exp_ret = ret_val(m_type, data) h_key = sym_keys[SYM_TABLE[m_type]] encrypt_this = [data, data, data, data] @@ -205,7 +242,7 @@ def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_se self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing - if exp_ret == CKR_OK: + if exp_ret == (CKR_OK or KEY_SIZE_RANGE): if m_type not in PADDING_ALGORITHMS: assert len(encrypted) == len(b"".join(encrypt_this)) @@ -224,6 +261,9 @@ def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session): :param asym_keys: key fixture :param auth_session: """ + if asym_keys.get(ASYM_TABLE[m_type]) is None: + pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) + pub_key, prv_key = asym_keys[ASYM_TABLE[m_type]] ret, decrypt_this = c_encrypt(auth_session, m_type, pub_key, RAW, extra_params=params) @@ -232,6 +272,4 @@ def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session): ret, decrypted_data = c_decrypt(auth_session, m_type, prv_key, decrypt_this, extra_params=params) self.verify_ret(ret, CKR_OK) - # Format to remove leading whitespace which causes problems during assert (RSA_X_509) - decrypted_data = decrypted_data.replace("\x00", "") - self.verify_data(RAW, decrypted_data) + self.verify_data(RAW, decrypted_data.replace(b"\x00", b"")) From aedd9153247d31be45ff94f2ed95dd94e9a11b66 Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Thu, 21 Jul 2016 10:16:38 -0400 Subject: [PATCH 061/109] LA-1924 Digest functional test Change-Id: I7a56fc67182f6331ddd00afb56de2f5b4e9372a6 --- tests/functional/test_digest_data.py | 59 +++++++++++++++++----------- 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/tests/functional/test_digest_data.py b/tests/functional/test_digest_data.py index d9dc19b..748fcd4 100755 --- a/tests/functional/test_digest_data.py +++ b/tests/functional/test_digest_data.py @@ -1,39 +1,54 @@ +""" Functional tests for digest data """ import logging - import pytest from pycryptoki.return_values import ret_vals_dictionary -from . import config as hsm_config -from pycryptoki.defines import CKM_MD2, CKR_OK +from pycryptoki.defines import CKR_OK, \ + CKM_MD2, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, CKM_SHA512 from pycryptoki.encryption import _get_string_from_list from pycryptoki.misc import c_digest logger = logging.getLogger(__name__) +MECHS = {CKM_MD2: "MD2", + CKM_SHA_1: "SHA1", + CKM_SHA224: "SHA224", + CKM_SHA256: "SHA256", + CKM_SHA384: "SHA384", + CKM_SHA512: "SHA512"} + +DATA = [b"Some arbitrary string", [b"Some arbitrary string", b"Some second arbitrary string"]] + class TestDigestData(object): - """ """ + + def verify_ret(self, ret, expected_ret): + """ + Assert that ret is as expected + :param ret: the actual return value + :param expected_ret: the expected return value + """ + assert ret == expected_ret, "Function should return: " + \ + ret_vals_dictionary[expected_ret] + ".\nInstead returned: " + ret_vals_dictionary[ret] @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): - self.admin_slot = hsm_config["test_slot"] self.h_session = auth_session - def test_digest_data(self): - """Calls C_Digest on some data and makes sure there is no failure""" - data_to_digest = b"Some arbitrary string" - ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) - assert ret == CKR_OK, "Digesting should occur with no errors, got {}".format(ret_vals_dictionary[ret]) + @pytest.mark.parametrize('data', DATA, ids=['String', 'Blocks']) + @pytest.mark.parametrize('mech', MECHS.keys(), ids=MECHS.values()) + def test_digest_data(self, mech, data): + """ + Tests digest data mechs + :param mech: parametrized mech from 'MECHS' + :param data: parametrized testing data from 'DATA' + """ + ret, digested_data = c_digest(self.h_session, data, mech) + self.verify_ret(ret, CKR_OK) assert len(digested_data) > 0, "The digested data should have a length" - assert data_to_digest != digested_data, "The digested data should not be the same as the " \ - "original string" - - def test_multipart_digest_data(self): - """ """ - data_to_digest = [b"Some arbitrary string", b"Some second arbitrary string"] - ret, digested_data = c_digest(self.h_session, data_to_digest, CKM_MD2) - assert ret == CKR_OK, "Digesting should occur with no errors" - assert len(digested_data) > 0, "The digested data should have a length" - assert _get_string_from_list( - data_to_digest) != digested_data, "The digested data should not be the same as the " \ - "original string" + + # If data is blocks + if type(data) is list: + digested_data = _get_string_from_list(digested_data) + + assert data != digested_data, "Digested data should not be the same as the original string" From 6562259defe4b535d822204ddb833fca299a9d9f Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 22 Jul 2016 09:12:20 -0400 Subject: [PATCH 062/109] LA-1696 Fix test error on Python3 Change-Id: Iaa04f8167f29c14f7c0627e3ed6b9c5b28ff3c0f --- tests/functional/test_session_management.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/functional/test_session_management.py b/tests/functional/test_session_management.py index 4c7ec2b..da55ce2 100644 --- a/tests/functional/test_session_management.py +++ b/tests/functional/test_session_management.py @@ -1,6 +1,8 @@ import pytest import logging +from six import integer_types + from . import config as hsm_config from pycryptoki.defines import CKR_OK import pycryptoki.session_management as sess_mang @@ -20,10 +22,10 @@ def test_c_get_session_info(self): ret, sess_info = sess_mang.c_get_session_info(self.h_session) assert ret == CKR_OK # Checks that session_info dictionary is the right format. Does not check the values - assert isinstance(sess_info['state'], long) - assert isinstance(sess_info['flags'], long) - assert isinstance(sess_info['slotID'], long) - assert isinstance(sess_info['usDeviceError'], long) + assert isinstance(sess_info['state'], integer_types) + assert isinstance(sess_info['flags'], integer_types) + assert isinstance(sess_info['slotID'], integer_types) + assert isinstance(sess_info['usDeviceError'], integer_types) def test_get_slot_dict(self): """ get_slot_dict() """ From 65977238f53330d57612f73fc9df3ff3ddd366f9 Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Tue, 19 Jul 2016 11:17:24 -0400 Subject: [PATCH 063/109] LA-1924 Sign/Verify functional test Change-Id: I8915bd98d791884a027de15b3f0003f3f2cb49c6 --- tests/functional/test_sign_verify.py | 221 ++++++++++++++++----------- 1 file changed, 136 insertions(+), 85 deletions(-) diff --git a/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py index 0b5a82b..5b10014 100755 --- a/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -1,105 +1,156 @@ +""" Functional tests for signature / verification""" import logging - import pytest -from . import config as hsm_config -from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256 -from pycryptoki.defines import CKR_OK, CKM_RSA_PKCS, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA -from pycryptoki.key_generator import c_generate_key_pair_ex -from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.sign_verify import c_sign, c_verify +from pycryptoki.key_generator import c_generate_key_pair, c_generate_key, c_destroy_object +from pycryptoki.defines import (CKM_AES_MAC, CKM_AES_CMAC, CKM_AES_KEY_GEN, + CKM_DES_MAC, CKM_DES_KEY_GEN, + CKM_DES3_MAC, CKM_DES3_CMAC, CKM_DES3_KEY_GEN, + CKM_CAST3_MAC, CKM_CAST3_KEY_GEN, + CKM_CAST5_MAC, CKM_CAST5_KEY_GEN, + + CKM_DSA, CKM_DSA_KEY_PAIR_GEN, + CKM_ECDSA, CKM_ECDSA_KEY_PAIR_GEN, + CKR_OK) +from pycryptoki.default_templates import (CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, + + CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, + + MECHANISM_LOOKUP_EXT, get_default_key_template) + +from pycryptoki.return_values import ret_vals_dictionary + logger = logging.getLogger(__name__) +DATA = [b"This is some test string to sign.", [b"a" * 1024, b"b" * 1024]] + +SYM_PARAMS = [(CKM_AES_KEY_GEN, CKM_AES_MAC), (CKM_AES_KEY_GEN, CKM_AES_CMAC), + (CKM_DES_KEY_GEN, CKM_DES_MAC), + (CKM_DES3_KEY_GEN, CKM_DES3_MAC), (CKM_DES3_KEY_GEN, CKM_DES3_CMAC), + (CKM_CAST3_KEY_GEN, CKM_CAST3_MAC), + (CKM_CAST5_KEY_GEN, CKM_CAST5_MAC)] +SYM_KEYS = [key for key, _ in SYM_PARAMS] + +DSA_PUB_TEMPS = [CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256] +ASYM_PARAMS = \ + [(CKM_ECDSA_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, + CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, CKM_ECDSA)] + \ + [(CKM_DSA_KEY_PAIR_GEN, x, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA) for x in DSA_PUB_TEMPS] + +FORMAT_ASYM = [(key, sig) for (key, _, _, sig) in ASYM_PARAMS] + + +def idfn(params): + """ Generate test ids """ + id_list = [] + for s in params: + id_list.append(MECHANISM_LOOKUP_EXT[s[0]][0]. + replace("CKM_", "").replace("_KEY_PAIR_GEN", "").replace("_KEY_GEN", "")) + return id_list + + +@pytest.yield_fixture(scope='class') +def sym_keys(auth_session): + """ Fixture containing all sym. keys """ + keys = {} + try: + for key_type in SYM_KEYS: + template = get_default_key_template(key_type) + ret, key_handle = c_generate_key(auth_session, key_type, template) + if ret == CKR_OK: + keys[key_type] = key_handle + else: + logger.info("Failed to generate key: {}\nReturn code: {}".format(key_type, ret)) + yield keys + + finally: + for handle in keys.values(): + c_destroy_object(auth_session, handle) + + +@pytest.yield_fixture(scope='class') +def asym_keys(auth_session): + """ Fixture containing all asym. keys """ + keys = {} + try: + for params in ASYM_PARAMS: + key_type, pub_temp, prv_temp, _ = params + ret, pub_key, prv_key = c_generate_key_pair(auth_session, key_type, pub_temp, prv_temp) + if ret == CKR_OK: + keys[key_type] = (pub_key, prv_key) + else: + logger.info("Failed to generate key: {}\nReturn code: {}".format(key_type, ret)) + yield keys + + finally: + for pub_key, prv_key in keys.values(): + c_destroy_object(auth_session, pub_key) + c_destroy_object(auth_session, prv_key) + class TestSignVerify(object): - """ """ + + def verify_ret(self, ret, expected_ret): + """ + Assert that ret is as expected + :param ret: the actual return value + :param expected_ret: the expected return value + """ + assert ret == expected_ret, "Function should return: " + \ + ret_vals_dictionary[expected_ret] + ".\nInstead returned: " + \ + ret_vals_dictionary[ret] @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): self.h_session = auth_session - self.admin_slot = hsm_config["test_slot"] - - @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ - pytest.mark.xfail(reason="Data len failure")((CKM_RSA_PKCS_KEY_PAIR_GEN, - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - CKM_RSA_PKCS)), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA) - ]) - def test_sign_verify(self, key_type, pub_key_template, priv_key_template, sign_flavor): - """Verifies that signing a string and verifying that string works - - :param key_type: The handle of the key to sign the data with - :param pub_key_template: The template for the public key to be generated - :param priv_key_template: The template for the private key to be generated - :param sign_flavor: The flavor of the signature + @pytest.mark.parametrize("data", DATA, ids=['String', 'Block']) + @pytest.mark.parametrize(('key_type', 'sign_flavor'), SYM_PARAMS, ids=idfn(SYM_PARAMS)) + def test_sym_sign_verify(self, key_type, sign_flavor, data, sym_keys): + """ + Test sym. sign / verify + :param key_type: key_gen type + :param sign_flavor: signature mech + :param data: testing data + :param sym_keys: key fixture """ + # Auto-fail when key-generation fails + print sym_keys.get(key_type) + if sym_keys.get(key_type) is None: + pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[key_type][0])) + h_key = sym_keys[key_type] - # Generate a key for the test - h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, - priv_key_template) - - data_to_sign = b"This is some test string to sign." - ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) - assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + \ - ret_vals_dictionary[ret] - - ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) - assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + \ - ret_vals_dictionary[ret] - - @pytest.mark.parametrize(("key_type", "pub_key_template", "priv_key_template", "sign_flavor"), [ - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA), - (CKM_DSA_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, - CKM_DSA) - ]) - def test_multipart_sign_verify(self, key_type, pub_key_template, priv_key_template, - sign_flavor): - """Verifies that signing a string and verifying that string works doing the operation - in multiple parts with c_sign_update and c_verify_update - - :param key_type: The handle of the key to sign the data with - :param pub_key_template: The template for the public key to be generated - :param priv_key_template: The template for the private key to be generated - :param sign_flavor: The flavor of the signature + ret, signature = c_sign(self.h_session, sign_flavor, data, h_key) + self.verify_ret(ret, CKR_OK) - """ + ret = c_verify(self.h_session, h_key, sign_flavor, data, signature) + self.verify_ret(ret, CKR_OK) - # Generate a key for the test - h_pub_key, h_priv_key = c_generate_key_pair_ex(self.h_session, key_type, pub_key_template, - priv_key_template) + @pytest.mark.parametrize("data", DATA, ids=['String', "Block"]) + @pytest.mark.parametrize(("k_type", "sig_mech"), FORMAT_ASYM, ids=idfn(ASYM_PARAMS)) + def test_asym_sign_verify(self, k_type, sig_mech, data, asym_keys): + """ + Test asym. sign / verify + :param k_type: key_gen type + :param sig_mech: signature mech + :param data: testing data + :param asym_keys: key fixture + """ + # Auto-fail when key-generation fails + if asym_keys.get(k_type) is None: + pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[k_type][0])) + pub_key, pub_key = asym_keys[k_type] - data_to_sign = [b"a" * 1024, b"b" * 1024] - ret, signature = c_sign(self.h_session, sign_flavor, data_to_sign, h_priv_key) - assert ret == CKR_OK, "The result code of the sign operation should be CKR_OK not " + \ - ret_vals_dictionary[ret] + ret, signature = c_sign(self.h_session, sig_mech, data, pub_key) + self.verify_ret(ret, CKR_OK) - ret = c_verify(self.h_session, h_pub_key, sign_flavor, data_to_sign, signature) - assert ret == CKR_OK, "The result code of the verify operation should be CKR_OK not " + \ - ret_vals_dictionary[ret] + ret = c_verify(self.h_session, pub_key, sig_mech, data, signature) + self.verify_ret(ret, CKR_OK) From 212c041011db09ec4bb9cf011cc15b65d648a48b Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Fri, 22 Jul 2016 12:07:12 -0400 Subject: [PATCH 064/109] LA-1924 Digest test py3 fix Change-Id: I905a1f3321b86e252da58247f75355161067f3fe --- tests/functional/test_digest_data.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/tests/functional/test_digest_data.py b/tests/functional/test_digest_data.py index 748fcd4..d7dfe31 100755 --- a/tests/functional/test_digest_data.py +++ b/tests/functional/test_digest_data.py @@ -5,7 +5,6 @@ from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.defines import CKR_OK, \ CKM_MD2, CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, CKM_SHA512 -from pycryptoki.encryption import _get_string_from_list from pycryptoki.misc import c_digest logger = logging.getLogger(__name__) @@ -36,7 +35,7 @@ def setup_teardown(self, auth_session): self.h_session = auth_session @pytest.mark.parametrize('data', DATA, ids=['String', 'Blocks']) - @pytest.mark.parametrize('mech', MECHS.keys(), ids=MECHS.values()) + @pytest.mark.parametrize('mech', list(MECHS.keys()), ids=list(MECHS.values())) def test_digest_data(self, mech, data): """ Tests digest data mechs @@ -46,9 +45,4 @@ def test_digest_data(self, mech, data): ret, digested_data = c_digest(self.h_session, data, mech) self.verify_ret(ret, CKR_OK) assert len(digested_data) > 0, "The digested data should have a length" - - # If data is blocks - if type(data) is list: - digested_data = _get_string_from_list(digested_data) - assert data != digested_data, "Digested data should not be the same as the original string" From 4713c17d3bf9f3ebbcc13a7d7c5d60d636b21399 Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Tue, 19 Jul 2016 11:17:24 -0400 Subject: [PATCH 065/109] LA-1924 Sign/Verify py3 fix Change-Id: I4501073fc64d9d8789c9b6b0658f0ccc0cd1f3ed --- tests/functional/test_sign_verify.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py index 5b10014..2a19c7d 100755 --- a/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -123,7 +123,6 @@ def test_sym_sign_verify(self, key_type, sign_flavor, data, sym_keys): :param sym_keys: key fixture """ # Auto-fail when key-generation fails - print sym_keys.get(key_type) if sym_keys.get(key_type) is None: pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[key_type][0])) h_key = sym_keys[key_type] @@ -147,9 +146,9 @@ def test_asym_sign_verify(self, k_type, sig_mech, data, asym_keys): # Auto-fail when key-generation fails if asym_keys.get(k_type) is None: pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[k_type][0])) - pub_key, pub_key = asym_keys[k_type] + pub_key, prv_key = asym_keys[k_type] - ret, signature = c_sign(self.h_session, sig_mech, data, pub_key) + ret, signature = c_sign(self.h_session, sig_mech, data, prv_key) self.verify_ret(ret, CKR_OK) ret = c_verify(self.h_session, pub_key, sig_mech, data, signature) From d56fd08d54d2e051492daa8974311c9cd37a1bed Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Mon, 25 Jul 2016 11:55:44 -0400 Subject: [PATCH 066/109] LA-1924 Encrpy/decrypt add SEED tests Change-Id: If8c51c3da84685059e73f30ecbf5c27d34d00659 --- tests/functional/test_encrypt_decrypt.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index ffd13a7..64e6d4f 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -16,6 +16,7 @@ CKM_CAST5_CBC, CKM_CAST5_ECB, CKM_CAST5_KEY_GEN, CKM_RC2_CBC, CKM_RC2_ECB, CKM_RC2_CBC_PAD, CKM_RC2_KEY_GEN, CKM_RC4, CKM_RC4_KEY_GEN, + CKM_SEED_CBC, CKM_SEED_CBC_PAD, CKM_SEED_ECB, CKM_SEED_KEY_GEN, CKM_RSA_PKCS, CKM_RSA_PKCS_OAEP, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X_509, CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_SHA_1, CKG_MGF1_SHA1) @@ -38,7 +39,11 @@ CKM_RC2_CBC: CKM_RC2_KEY_GEN, CKM_RC2_ECB: CKM_RC2_KEY_GEN, CKM_RC2_CBC_PAD: CKM_RC2_KEY_GEN, - CKM_RC4: CKM_RC4_KEY_GEN} + CKM_RC4: CKM_RC4_KEY_GEN, + CKM_SEED_CBC: CKM_SEED_KEY_GEN, + CKM_SEED_CBC_PAD: CKM_SEED_KEY_GEN, + CKM_SEED_ECB: CKM_SEED_KEY_GEN + } ASYM_TABLE = {CKM_RSA_PKCS: CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_OAEP: CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X_509: CKM_RSA_X9_31_KEY_PAIR_GEN} @@ -60,6 +65,9 @@ CKM_RC2_ECB: [{'usEffectiveBits': 8}], CKM_RC2_CBC_PAD: [{'iv': list(range(8)), 'usEffectiveBits': 8}], CKM_RC4: [{}], + CKM_SEED_CBC: [{}], + CKM_SEED_CBC_PAD: [{}], + CKM_SEED_ECB: [{}], CKM_RSA_PKCS: [{}], CKM_RSA_PKCS_OAEP: [{'hashAlg': CKM_SHA_1, 'mgf': CKG_MGF1_SHA1, 'sourceData': list(range(12))}], CKM_RSA_X_509: [{}]} @@ -69,7 +77,7 @@ RAW = b"abcdefghijk" # Flavors which auto-pad (will return 'CKR_OK' on un-padded(RAW) data) -PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, CKM_RC2_CBC_PAD, CKM_RC4, CKM_AES_GCM] +PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, CKM_RC2_CBC_PAD, CKM_RC4, CKM_AES_GCM, CKM_SEED_CBC_PAD] # Flavors which are not compatible with multi encrypt/decrypt NOT_MULTI = [CKM_AES_GCM] From 0537232e1ec355750c16e0e40244a84af554700d Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Mon, 25 Jul 2016 12:03:06 -0400 Subject: [PATCH 067/109] LA-1924 Sign/Verify add SEED tests Change-Id: I4f94f605f341e6adcd9ea7340551b62eb65c50c8 --- tests/functional/test_sign_verify.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py index 2a19c7d..9fcd761 100755 --- a/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -9,6 +9,7 @@ CKM_DES3_MAC, CKM_DES3_CMAC, CKM_DES3_KEY_GEN, CKM_CAST3_MAC, CKM_CAST3_KEY_GEN, CKM_CAST5_MAC, CKM_CAST5_KEY_GEN, + CKM_SEED_MAC, CKM_SEED_CMAC, CKM_SEED_KEY_GEN, CKM_DSA, CKM_DSA_KEY_PAIR_GEN, CKM_ECDSA, CKM_ECDSA_KEY_PAIR_GEN, @@ -35,7 +36,8 @@ (CKM_DES_KEY_GEN, CKM_DES_MAC), (CKM_DES3_KEY_GEN, CKM_DES3_MAC), (CKM_DES3_KEY_GEN, CKM_DES3_CMAC), (CKM_CAST3_KEY_GEN, CKM_CAST3_MAC), - (CKM_CAST5_KEY_GEN, CKM_CAST5_MAC)] + (CKM_CAST5_KEY_GEN, CKM_CAST5_MAC), + (CKM_SEED_KEY_GEN, CKM_SEED_MAC), (CKM_SEED_KEY_GEN, CKM_SEED_CMAC)] SYM_KEYS = [key for key, _ in SYM_PARAMS] DSA_PUB_TEMPS = [CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, From 38ed4fd5f8a58f21b26ca6dbbaad25ebc3792574 Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Mon, 25 Jul 2016 09:35:31 -0400 Subject: [PATCH 068/109] LA-1924 Test keys Change-Id: Id827b1e3978fc81d11607a11018815dad948ee71 --- tests/functional/test_keys.py | 335 ++++++++++++++-------------------- 1 file changed, 141 insertions(+), 194 deletions(-) diff --git a/tests/functional/test_keys.py b/tests/functional/test_keys.py index 58bcdc4..0c62f40 100755 --- a/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -1,138 +1,128 @@ import logging - import pytest -from . import config as hsm_config -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_DES2_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, CKM_CAST3_KEY_GEN_TEMP, \ - CKM_GENERIC_SECRET_KEY_GEN_TEMP, CKM_CAST5_KEY_GEN_TEMP, CKM_RC2_KEY_GEN_TEMP, \ - CKM_RC4_KEY_GEN_TEMP, CKM_RC5_KEY_GEN_TEMP, CKM_AES_KEY_GEN_TEMP, CKM_SEED_KEY_GEN_TEMP, \ - CKM_ARIA_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, \ - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, \ - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, \ - CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, \ - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, \ - CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP, curve_list -from pycryptoki.defines import CKM_DES_KEY_GEN, CKR_OK, \ - CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, \ - CKM_GENERIC_SECRET_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, \ - CKM_RC5_KEY_GEN, CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, \ - CKM_ARIA_KEY_GEN, \ - CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, \ - CKM_DH_PKCS_KEY_PAIR_GEN, CKM_ECDSA_KEY_PAIR_GEN, CKM_KCDSA_KEY_PAIR_GEN, \ - CKM_RSA_X9_31_KEY_PAIR_GEN, CKA_ECDSA_PARAMS, \ - CKM_SHA224_KEY_DERIVATION, CKM_SHA256_KEY_DERIVATION, CKM_SHA1_KEY_DERIVATION, \ - CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_MD5_KEY_DERIVATION, \ - CKM_MD2_KEY_DERIVATION, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE -from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, \ - c_derive_key, c_generate_key_ex, c_destroy_object +from pycryptoki.default_templates import \ + (CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, + + CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP, CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, + + CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP, + CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, + + curve_list, get_default_key_template, get_default_key_pair_template, + MECHANISM_LOOKUP_EXT) + +from pycryptoki.defines import \ + (CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_CAST5_KEY_GEN, + CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, CKM_RC5_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN, + CKM_AES_KEY_GEN, CKM_ARIA_KEY_GEN, CKM_SEED_KEY_GEN, + + CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DH_PKCS_KEY_PAIR_GEN, + CKM_ECDSA_KEY_PAIR_GEN, CKA_ECDSA_PARAMS, CKM_KCDSA_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN, + + CKM_SHA1_KEY_DERIVATION, CKM_SHA224_KEY_DERIVATION, CKM_SHA256_KEY_DERIVATION, + CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_MD5_KEY_DERIVATION, CKM_MD2_KEY_DERIVATION, + + CKR_OK, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE) + +from pycryptoki.key_generator import \ + c_generate_key, c_generate_key_pair, c_derive_key, c_generate_key_ex, c_destroy_object from pycryptoki.mechanism import NullMech from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.test_functions import verify_object_attributes + logger = logging.getLogger(__name__) +KEYS = [CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_CAST5_KEY_GEN, + CKM_GENERIC_SECRET_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, CKM_RC5_KEY_GEN, + CKM_AES_KEY_GEN, CKM_SEED_KEY_GEN, CKM_ARIA_KEY_GEN] + + +def pair_params(key_gen): + """ Return the params tuple given the key_gen mech """ + return (key_gen,) + get_default_key_pair_template(key_gen) + +DSA_PUB_TEMPS = [CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, + CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256] +KCDSA_P_TEMPS = [CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256] + +KEY_PAIRS = [pair_params(CKM_RSA_PKCS_KEY_PAIR_GEN), + pair_params(CKM_DH_PKCS_KEY_PAIR_GEN), + pair_params(CKM_ECDSA_KEY_PAIR_GEN), + pair_params(CKM_RSA_X9_31_KEY_PAIR_GEN)] +KEY_PAIRS.extend([(CKM_DSA_KEY_PAIR_GEN, x, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP) for x in DSA_PUB_TEMPS]) +KEY_PAIRS.extend([(CKM_KCDSA_KEY_PAIR_GEN, x, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP) for x in KCDSA_P_TEMPS]) + +DERIVE_PARAMS = {CKM_SHA224_KEY_DERIVATION: "SHA224", + CKM_SHA256_KEY_DERIVATION: "SHA256", + CKM_SHA384_KEY_DERIVATION: "SHA384", + CKM_SHA512_KEY_DERIVATION: "SHA512"} +DERIVE_KEYS = {CKM_DES_KEY_GEN: "DES", + CKM_DES2_KEY_GEN: "DES2", + CKM_CAST3_KEY_GEN: "CAST3", + CKM_GENERIC_SECRET_KEY_GEN: "GENERIC", + CKM_CAST5_KEY_GEN: "CAST5", + CKM_SEED_KEY_GEN: "SEED"} +DRV_TOO_LONG = {CKM_SHA1_KEY_DERIVATION: "SHA1", + CKM_MD2_KEY_DERIVATION: "MD2", + CKM_MD5_KEY_DERIVATION: "MD5"} +TOO_LONG_KEY = {CKM_DES3_KEY_GEN: "DES3", + CKM_AES_KEY_GEN: "AES", + CKM_ARIA_KEY_GEN: "ARIA"} +ALL_DERIVES = {k: v for d in [DERIVE_PARAMS, DRV_TOO_LONG] for k, v in d.items()} + -# noinspection PyArgumentList,PyArgumentList class TestKeys(object): - """ """ + + def verify_ret(self, ret, expected_ret): + """ Verify ret check and len > 0""" + assert ret == expected_ret, "Function should return: " + ret_vals_dictionary[expected_ret] \ + + ".\nInstead returned: " + ret_vals_dictionary[ret] + + def verify_key_len(self, k1, k2): + """ Verify that key > 0""" + assert k1 > 0, "Key should be > 0" + assert k2 > 0, "Priv key should be > 0" @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): self.h_session = auth_session - self.admin_slot = hsm_config['test_slot'] - - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), - (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), - (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), - (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_RC2_KEY_GEN, CKM_RC2_KEY_GEN_TEMP), - (CKM_RC4_KEY_GEN, CKM_RC4_KEY_GEN_TEMP), - (CKM_RC5_KEY_GEN, CKM_RC5_KEY_GEN_TEMP), - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) - ]) - def test_generate_key(self, key_type, key_template): - """Tests generating a key, asserts that the operation returns correctly with key handles - greater than 0 - - :param key_type: The type of key to generate (ex. CKM_DES_KEY_GEN) - :param key_template: The key template to generate (ex. CKM_DES_KEY_GEN_TEMP) + @pytest.mark.parametrize("key_type", KEYS, ids=[MECHANISM_LOOKUP_EXT[k][0] for k in KEYS]) + def test_generate_key(self, key_type): + """ + Test generation of keys for sym. crypto systems + :param key_type: key generation mechanism """ + key_template = get_default_key_template(key_type) ret, key_handle = c_generate_key(self.h_session, key_type, key_template) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + \ - ret_vals_dictionary[ret] - assert key_handle > 0, "The key handle returned should be non zero" - - @pytest.mark.parametrize(("key_type", "public_key_template", "private_key_template"), [ - (CKM_RSA_PKCS_KEY_PAIR_GEN, - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DSA_KEY_PAIR_GEN, - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256, - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_DH_PKCS_KEY_PAIR_GEN, - CKM_DH_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_DH_PKCS_KEY_PAIR_GEN_PRIVTEMP), - (CKM_ECDSA_KEY_PAIR_GEN, - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, - CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_KCDSA_KEY_PAIR_GEN, - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, - CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_KCDSA_KEY_PAIR_GEN, - CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256, - CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP), - (CKM_RSA_X9_31_KEY_PAIR_GEN, - CKM_RSA_X9_31_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_X9_31_KEY_PAIR_GEN_PRIVTEMP), - # (CKM_X9_42_DH_KEY_PAIR_GEN, CKM_X9_42_DH_KEY_PAIR_GEN_PUBTEMP, - # CKM_X9_42_DH_KEY_PAIR_GEN_PRIVTEMP) #XXX - ]) - def test_generate_key_pair(self, key_type, public_key_template, private_key_template): - """Tests generating a key pair, asserts that the operation returns correctly with key - handles - greater than 0. - - :param key_type: The type of key to create (ex. CKM_DSA_KEY_PAIR_GEN) - :param public_key_template: The template to use for public key generation (ex. - CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160 - :param private_key_template: The template to use for private key generation (ex. - CKM_DSA_KEY_PAIR_GEN_PRIVTEMP_1024_160 + self.verify_ret(ret, CKR_OK) + self.verify_key_len(key_handle, key_handle) + + @pytest.mark.parametrize(("key_type", "pub_key_temp", "prv_key_temp"), KEY_PAIRS, + ids=[MECHANISM_LOOKUP_EXT[k[0]][0] for k in KEY_PAIRS]) + def test_generate_key_pair(self, key_type, pub_key_temp, prv_key_temp): + """ + Test generation of key pairs for asym. crypto systems + :param key_type: key generation mechanism + :param pub_key_temp: public key template + :param prv_key_temp: private key template """ - ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, key_type, - public_key_template, - private_key_template) - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " + \ - ret_vals_dictionary[ret] - assert public_key_handle > 0, "The public key handle returned should be non zero" - assert private_key_handle > 0, "The private key handle returned should be non zero" + ret, pub_key, prv_key = c_generate_key_pair(self.h_session, key_type, + pub_key_temp, + prv_key_temp) + self.verify_ret(ret, CKR_OK) + self.verify_key_len(pub_key, prv_key) @pytest.mark.parametrize("curve_type", list(curve_list.keys())) def test_generate_ecdsa_key_pairs(self, curve_type): """ - + Test generate ECDSA key pairs :param curve_type: - """ CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, @@ -140,55 +130,35 @@ def test_generate_ecdsa_key_pairs(self, curve_type): CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) try: - assert ret == CKR_OK, "Return code should be " + ret_vals_dictionary[CKR_OK] + " not " \ - "" + \ - ret_vals_dictionary[ret] - assert public_key_handle > 0, "The public key handle returned should be non zero" - assert private_key_handle > 0, "The private key handle returned should be non zero" + self.verify_ret(ret, CKR_OK) + self.verify_key_len(public_key_handle, private_key_handle) finally: if public_key_handle: c_destroy_object(self.h_session, public_key_handle) if private_key_handle: c_destroy_object(self.h_session, private_key_handle) - @pytest.mark.parametrize("derive_type", [CKM_SHA1_KEY_DERIVATION, - CKM_SHA224_KEY_DERIVATION, - CKM_SHA256_KEY_DERIVATION, - CKM_SHA384_KEY_DERIVATION, - CKM_SHA512_KEY_DERIVATION, - CKM_MD5_KEY_DERIVATION, - CKM_MD2_KEY_DERIVATION], - ids=["SHA1", "SHA224", "SHA256", "SHA384", "SHA512", - "MD5", "MD2"]) - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP), - (CKM_DES2_KEY_GEN, CKM_DES2_KEY_GEN_TEMP), - (CKM_CAST3_KEY_GEN, CKM_CAST3_KEY_GEN_TEMP), - (CKM_GENERIC_SECRET_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN_TEMP), - (CKM_CAST5_KEY_GEN, CKM_CAST5_KEY_GEN_TEMP), - (CKM_SEED_KEY_GEN, CKM_SEED_KEY_GEN_TEMP), - ], - ids=["DES", "DES2", 'CAST3', - 'GENERIC', 'CAST5', "SEED", ]) - def test_derive_key(self, key_type, key_template, derive_type): - """Tests deriving a key - + @pytest.mark.parametrize("d_type", list(ALL_DERIVES.keys()), ids=list(ALL_DERIVES.values())) + @pytest.mark.parametrize("key_type", list(DERIVE_KEYS.keys()), ids=list(DERIVE_KEYS.values())) + def test_derive_key(self, key_type, d_type): + """ + Test derive key for using parametrized hash + :param key_type: Key-gen mechanism + :param d_type: Hash mech """ + key_template = get_default_key_template(key_type) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) - mech = NullMech(derive_type).to_c_mech() + mech = NullMech(d_type).to_c_mech() derived_key_template = key_template.copy() del derived_key_template[CKA_VALUE_LEN] - ret, h_derived_key = c_derive_key(self.h_session, - h_base_key, - key_template, - mech_flavor=derive_type, - mech=mech) + ret, h_derived_key = c_derive_key(self.h_session, h_base_key, + key_template, + mech_flavor=d_type, + mech=mech) try: - assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + \ - ret_vals_dictionary[ret] - + self.verify_ret(ret, CKR_OK) verify_object_attributes(self.h_session, h_derived_key, key_template) finally: if h_base_key: @@ -196,78 +166,55 @@ def test_derive_key(self, key_type, key_template, derive_type): if h_derived_key: c_destroy_object(self.h_session, h_derived_key) - @pytest.mark.parametrize("derive_type", [CKM_SHA1_KEY_DERIVATION, - CKM_MD5_KEY_DERIVATION, - CKM_MD2_KEY_DERIVATION], - ids=["SHA1", "MD5", "MD2"]) - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) - ], - ids=['DES3', 'AES', 'ARIA']) - def test_too_long_length_derives(self, key_type, key_template, derive_type): + @pytest.mark.parametrize("d_type", list(DRV_TOO_LONG.keys()), ids=list(DRV_TOO_LONG.values())) + @pytest.mark.parametrize("key_type", list(TOO_LONG_KEY.keys()), ids=list(TOO_LONG_KEY.values())) + def test_too_long_length_derives(self, key_type, d_type): """ Verify that trying to derive a key that is too long for the given derivation function will return CKR_KEY_SIZE_RANGE - :param key_type: - :param key_template: - :param derive_type: - :return: + :param d_type: """ + key_template = get_default_key_template(key_type) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) - mech = NullMech(derive_type).to_c_mech() + mech = NullMech(d_type).to_c_mech() derived_key_template = key_template.copy() del derived_key_template[CKA_VALUE_LEN] - ret, h_derived_key = c_derive_key(self.h_session, - h_base_key, - key_template, - mech_flavor=derive_type, - mech=mech) + ret, h_derived_key = c_derive_key(self.h_session, h_base_key, + key_template, + mech_flavor=d_type, + mech=mech) try: - assert ret == CKR_KEY_SIZE_RANGE + self.verify_ret(ret, CKR_KEY_SIZE_RANGE) finally: if h_base_key: c_destroy_object(self.h_session, h_base_key) if h_derived_key: c_destroy_object(self.h_session, h_derived_key) - @pytest.mark.parametrize("derive_type", [CKM_SHA224_KEY_DERIVATION, - CKM_SHA256_KEY_DERIVATION, - CKM_SHA384_KEY_DERIVATION, - CKM_SHA512_KEY_DERIVATION], - ids=["SHA224", "SHA256", "SHA384", "SHA512"]) - @pytest.mark.parametrize(("key_type", "key_template"), [ - (CKM_DES3_KEY_GEN, CKM_DES3_KEY_GEN_TEMP), - (CKM_AES_KEY_GEN, CKM_AES_KEY_GEN_TEMP), - (CKM_ARIA_KEY_GEN, CKM_ARIA_KEY_GEN_TEMP) - ], - ids=['DES3', 'AES', 'ARIA']) - def test_long_length_derive_key(self, key_type, key_template, derive_type): - """Tests deriving a key - - :param key_type: - :param key_template: - + @pytest.mark.parametrize("d_type", list(DERIVE_PARAMS.keys()), ids=list(DERIVE_PARAMS.values())) + @pytest.mark.parametrize("key_type", list(TOO_LONG_KEY.keys()), ids=list(TOO_LONG_KEY.values())) + def test_long_length_derive_key(self, key_type, d_type): + """ + Test deriving a key + :param key_type: key generation mechanism + :param d_type: derive mechanism """ + key_template = get_default_key_template(key_type) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) - mech = NullMech(derive_type).to_c_mech() + mech = NullMech(d_type).to_c_mech() derived_key_template = key_template.copy() del derived_key_template[CKA_VALUE_LEN] - ret, h_derived_key = c_derive_key(self.h_session, - h_base_key, - key_template, - mech_flavor=derive_type, - mech=mech) + ret, h_derived_key = c_derive_key(self.h_session, h_base_key, + key_template, + mech_flavor=d_type, + mech=mech) try: - assert ret == CKR_OK, "Deriving a key should not fail, instead it failed with " + \ - ret_vals_dictionary[ret] - + self.verify_ret(ret, CKR_OK) verify_object_attributes(self.h_session, h_derived_key, key_template) finally: if h_base_key: From 89190693f013291a1b1572aa81377f7fe46cdf4e Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Mon, 25 Jul 2016 15:22:46 -0400 Subject: [PATCH 069/109] LA-1924 Key wrap/unwrap Change-Id: I9c51a7a62db0a49cdc88da7bf01fbead9f151c55 --- tests/functional/test_wrap_unwrap.py | 213 +++++++++++++++++++++------ 1 file changed, 166 insertions(+), 47 deletions(-) diff --git a/tests/functional/test_wrap_unwrap.py b/tests/functional/test_wrap_unwrap.py index fcf3e7f..9eecc00 100755 --- a/tests/functional/test_wrap_unwrap.py +++ b/tests/functional/test_wrap_unwrap.py @@ -1,83 +1,202 @@ import logging - import pytest -from . import config as hsm_config -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_DES_UNWRAP_TEMP -from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_DES_CBC, CKR_OK, \ - CKM_DES_ECB +from pycryptoki.default_templates import get_default_key_template +from pycryptoki.default_templates import MECHANISM_LOOKUP_EXT as LOOKUP +from pycryptoki.defines import (CKM_DES_ECB, CKM_DES_CBC, CKM_DES_CBC_PAD, CKM_DES_KEY_GEN, + CKM_DES3_ECB, CKM_DES3_CBC, CKM_DES3_CBC_PAD, CKM_DES3_KEY_GEN, + CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, CKM_AES_KEY_GEN, + CKM_CAST3_ECB, CKM_CAST3_CBC, CKM_CAST3_CBC_PAD, CKM_CAST3_KEY_GEN, + CKM_CAST5_ECB, CKM_CAST5_CBC, CKM_CAST5_CBC_PAD, CKM_CAST5_KEY_GEN, + CKM_SEED_ECB, CKM_SEED_CBC, CKM_SEED_KEY_GEN, + + CKR_OK, CKA_DECRYPT, CKA_VERIFY, CKA_UNWRAP, + CKA_VALUE_LEN, CKA_EXTRACTABLE) + + from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt -from pycryptoki.key_generator import c_generate_key_ex +from pycryptoki.key_generator import c_destroy_object, c_generate_key from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.test_functions import verify_object_attributes logger = logging.getLogger(__name__) +PARAM_LIST = [(CKM_DES_ECB, CKM_DES_KEY_GEN), + (CKM_DES_CBC, CKM_DES_KEY_GEN), + (CKM_DES_CBC_PAD, CKM_DES_KEY_GEN), + + (CKM_DES3_ECB, CKM_DES3_KEY_GEN), + (CKM_DES3_CBC, CKM_DES3_KEY_GEN), + (CKM_DES3_CBC_PAD, CKM_DES3_KEY_GEN), + + (CKM_AES_ECB, CKM_AES_KEY_GEN), + (CKM_AES_CBC, CKM_AES_KEY_GEN), + (CKM_AES_CBC_PAD, CKM_AES_KEY_GEN), + + (CKM_CAST3_ECB, CKM_CAST3_KEY_GEN), + (CKM_CAST3_CBC, CKM_CAST3_KEY_GEN), + (CKM_CAST3_CBC_PAD, CKM_CAST3_KEY_GEN), + + (CKM_CAST5_ECB, CKM_CAST5_KEY_GEN), + (CKM_CAST5_CBC, CKM_CAST5_KEY_GEN), + (CKM_CAST5_CBC_PAD, CKM_CAST5_KEY_GEN), + + (CKM_SEED_ECB, CKM_SEED_KEY_GEN), + (CKM_SEED_CBC, CKM_SEED_KEY_GEN)] + +EXTRA_PARAM = {CKM_DES_ECB: {}, + CKM_DES_CBC: {'iv': list(range(8))}, + CKM_DES_CBC_PAD: {}, + + CKM_DES3_ECB: {}, + CKM_DES3_CBC: {'iv': list(range(8))}, + CKM_DES3_CBC_PAD: {'iv': list(range(8))}, + + CKM_AES_ECB: {}, + CKM_AES_CBC: {'iv': list(range(16))}, + CKM_AES_CBC_PAD: {}, + + CKM_CAST3_ECB: {}, + CKM_CAST3_CBC: {'iv': list(range(8))}, + CKM_CAST3_CBC_PAD: {}, + + CKM_CAST5_ECB: {}, + CKM_CAST5_CBC: {}, + CKM_CAST5_CBC_PAD: {}, + + CKM_SEED_ECB: {}, + CKM_SEED_CBC: {}} + +# Don't pop 'CKA_VALUE_LEN' for these mechs +VALUE_LEN = [CKM_AES_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_CAST5_KEY_GEN] + + +@pytest.yield_fixture(scope='class') +def keys(auth_session): + """ Fixture containing keys""" + keys = {} + try: + for key_gen in set(param[1] for param in PARAM_LIST): + template = get_default_key_template(key_gen) + + ret, key_handle = c_generate_key(auth_session, key_gen, template) + ret2, wrap_handle = c_generate_key(auth_session, key_gen, template) + if ret == CKR_OK and ret2 == CKR_OK: + keys[key_gen] = key_handle, wrap_handle + elif ret2 != CKR_OK: + keys[key_gen] = key_handle, None + logger.info("Failed to generate key: {}\nReturn code: {}".format(key_gen, ret2)) + elif ret != CKR_OK: + keys[key_gen] = None, wrap_handle + logger.info("Failed to generate key: {}\nReturn code: {}".format(key_gen, ret)) + else: + logger.info("Failed to generate key: {}\nReturn code: {}".format(key_gen, ret)) + yield keys + + finally: + for key, wrap in keys.values(): + if key is not None: + c_destroy_object(auth_session, key) + if wrap is not None: + c_destroy_object(auth_session, wrap) + class TestWrappingKeys(object): - """ """ + + def verify_ret(self, ret, expected_ret): + """ + Assert that ret is as expected + :param ret: the actual return value + :param expected_ret: the expected return value + """ + assert ret == expected_ret, "Function should return: " + ret_vals_dictionary[expected_ret] \ + + ".\nInstead returned: " + ret_vals_dictionary[ret] @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): self.h_session = auth_session - self.admin_slot = hsm_config["test_slot"] - def test_wrap_unwrap_key(self): - """Tests the attributes of an unwrapped key are idential to the original key""" - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + def generate_unwrap_temp(self, key_gen): + """ + Create an unwrap template which is slightly different then the original template + :param key_gen: + :return: the new unwrap template + """ + unwrap_temp = get_default_key_template(key_gen) + unwrap_temp.pop(CKA_DECRYPT, None) + unwrap_temp.pop(CKA_VERIFY, None) + unwrap_temp.pop(CKA_UNWRAP, None) + unwrap_temp.pop(CKA_EXTRACTABLE, None) + if key_gen not in VALUE_LEN: + unwrap_temp.pop(CKA_VALUE_LEN, None) + + return unwrap_temp + + @pytest.mark.parametrize(('mech', 'k_type'), PARAM_LIST, ids=[LOOKUP[m][0] for m, _ in PARAM_LIST]) + def test_wrap_unwrap_key(self, mech, k_type, keys): + """ + Test key wrapping + :param mech: encryption mech + :param k_type: key gen mech + :param keys: keys fixture + """ + temp = get_default_key_template(k_type) + unwrap_temp = self.generate_unwarp_temp(k_type) + extra_p = EXTRA_PARAM[mech] + h_key, h_wrap_key = keys[k_type] + if h_key is None or h_wrap_key is None: + pytest.fail("No valid key found for {}".format(LOOKUP[mech][0])) # Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) - assert ret == CKR_OK, \ - "Wrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mech, extra_params=extra_p) + self.verify_ret(ret, CKR_OK) # Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, - CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) - assert ret == CKR_OK, \ - "Unwrapping the key should pass, instead it returns " + ret_vals_dictionary[ret] + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrap_key, + wrapped_key, + unwrap_temp, + mech, + extra_params=extra_p) + self.verify_ret(ret, CKR_OK) # Verify all of the attributes against the originally generated attributes - verify_object_attributes(self.h_session, h_unwrapped_key, CKM_DES_KEY_GEN_TEMP) - - def test_encrypt_wrap_unwrap_decrypt_key(self): - """Tests encrypting some data with a key. Then wrapping and unwrapping the key - and using the unwrapped key to decrypt the data. It then compares the data to the - original data. - + verify_object_attributes(self.h_session, h_unwrapped_key, temp) + @pytest.mark.parametrize(('mech', 'k_type'), PARAM_LIST, ids=[LOOKUP[m][0] for m, _ in PARAM_LIST]) + def test_encrypt_wrap_unwrap_decrypt_key(self, mech, k_type, keys): """ - h_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) - h_wrapping_key = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP) + Test that encrypt/decrypt works with wrapped keys + :param mech: encryption mech + :param k_type: key gen mech + :param keys: keys fixture + """ + unwrap_temp = self.generate_unwarp_temp(k_type) + h_key, h_wrap_key = keys[k_type] + extra_p = EXTRA_PARAM[mech] + if h_key is None or h_wrap_key is None: + pytest.fail("No valid key found for {}".format(LOOKUP[mech][0])) # Encrypt some data data_to_encrypt = b"a" * 512 - ret, encrypted_data = c_encrypt(self.h_session, CKM_DES_CBC, h_key, data_to_encrypt) - assert ret == CKR_OK, \ - "Encryption should go through successfully, instead it returned " + \ - ret_vals_dictionary[ret] + ret, encrypted_data = c_encrypt(self.h_session, mech, h_key, data_to_encrypt) + self.verify_ret(ret, CKR_OK) # Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrapping_key, h_key, CKM_DES_ECB) - assert ret == CKR_OK, \ - "Wrapping the key should pass, instead it returns " + \ - ret_vals_dictionary[ret] + ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mech, extra_params=extra_p) + self.verify_ret(ret, CKR_OK) # Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrapping_key, wrapped_key, - CKM_DES_UNWRAP_TEMP, CKM_DES_ECB) - assert ret == CKR_OK, \ - "Unwrapping the key should pass, instead it returns " + \ - ret_vals_dictionary[ret] + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrap_key, + wrapped_key, + unwrap_temp, + mech, + extra_params=extra_p) + self.verify_ret(ret, CKR_OK) # Decrypt the data - ret, decrypted_string = c_decrypt(self.h_session, CKM_DES_CBC, h_unwrapped_key, - encrypted_data) - assert ret == CKR_OK, \ - "There should be no errors when decrypting, instead found " + \ - ret_vals_dictionary[ret] + ret, decrypted_string = c_decrypt(self.h_session, mech, h_unwrapped_key, encrypted_data) + self.verify_ret(ret, CKR_OK) + assert decrypted_string == data_to_encrypt, \ "The decrypted data should be the same as the data that was encrypted. " \ "Instead found " + str(decrypted_string) From 6f66c150dbccf180d7284dfe3ab78e3878ba0b52 Mon Sep 17 00:00:00 2001 From: Asano Mori Date: Mon, 25 Jul 2016 15:22:46 -0400 Subject: [PATCH 070/109] LA-1924 Wrap/Unwrap spelling fix Change-Id: Ica3acd1e5ba1598e47d44583c2bdd9e34def0a7a --- tests/functional/test_wrap_unwrap.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/functional/test_wrap_unwrap.py b/tests/functional/test_wrap_unwrap.py index 9eecc00..f1e8719 100755 --- a/tests/functional/test_wrap_unwrap.py +++ b/tests/functional/test_wrap_unwrap.py @@ -141,7 +141,7 @@ def test_wrap_unwrap_key(self, mech, k_type, keys): :param keys: keys fixture """ temp = get_default_key_template(k_type) - unwrap_temp = self.generate_unwarp_temp(k_type) + unwrap_temp = self.generate_unwrap_temp(k_type) extra_p = EXTRA_PARAM[mech] h_key, h_wrap_key = keys[k_type] if h_key is None or h_wrap_key is None: @@ -170,7 +170,7 @@ def test_encrypt_wrap_unwrap_decrypt_key(self, mech, k_type, keys): :param k_type: key gen mech :param keys: keys fixture """ - unwrap_temp = self.generate_unwarp_temp(k_type) + unwrap_temp = self.generate_unwrap_temp(k_type) h_key, h_wrap_key = keys[k_type] extra_p = EXTRA_PARAM[mech] if h_key is None or h_wrap_key is None: From b437d0591ee58757a092f01713ed70dc6caad67f Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 2 Aug 2016 12:07:45 -0400 Subject: [PATCH 071/109] LA-1864 Added AES_KW tests Fixed AES_GCM tests (use smaller data sizes) Added xfail for FW version on AES_KW Added FW version to config dictionary. Added valid_mechanisms fixture (should be used for checking retcodes). Update AES_GCM constant Change-Id: Ie5303d53546c1744573835aabd8f470e684b4028 --- pycryptoki/defines.py | 2 +- pycryptoki/encryption.py | 45 +++---- pycryptoki/mechanism.py | 32 +++-- tests/functional/conftest.py | 18 ++- tests/functional/test_encrypt_decrypt.py | 160 +++++++++++++++-------- 5 files changed, 171 insertions(+), 86 deletions(-) diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index 5c1ee64..daba2eb 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -1689,7 +1689,7 @@ CKM_AES_CFB8 = (CKM_VENDOR_DEFINED + 0x118) CKM_AES_CFB128 = (CKM_VENDOR_DEFINED + 0x119) CKM_AES_OFB = (CKM_VENDOR_DEFINED + 0x11a) -CKM_AES_GCM = (CKM_VENDOR_DEFINED + 0x11c) +CKM_AES_GCM = 0x00001087 # Used to be vendor defined + 0x11c CKM_ARIA_CFB8 = (CKM_VENDOR_DEFINED + 0x11d) CKM_ARIA_CFB128 = (CKM_VENDOR_DEFINED + 0x11e) CKM_ARIA_OFB = (CKM_VENDOR_DEFINED + 0x11f) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 676bc17..ea3cb1c 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -5,6 +5,7 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte +from .return_values import ret_vals_dictionary from .attributes import Attributes, to_char_array from .common_utils import AutoCArray, refresh_c_arrays from .cryptoki import CK_ULONG, \ @@ -34,7 +35,6 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e :param extra_params: Parameters to be passed to mechanism generation. :returns: Returns the result code of the operation, a python string representing the encrypted data - """ if mech is None: py_mech = Mechanism(mech_type=encryption_flavor, params=extra_params) @@ -130,8 +130,8 @@ def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, ex is_multi_part_operation = isinstance(encrypted_data, (list, tuple)) if is_multi_part_operation: - ret, python_string = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, - encrypted_data) + ret, python_data = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, + encrypted_data) else: # Get the length of the final data @@ -158,9 +158,9 @@ def _decrypt(): return ret, None # Convert the decrypted data to a python readable format - python_string = string_at(decrypted_data.array, len(decrypted_data)) + python_data = string_at(decrypted_data.array, len(decrypted_data)) - return ret, python_string + return ret, python_data c_decrypt_ex = make_error_handle_function(c_decrypt) @@ -170,17 +170,16 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in """Some code which will do a multipart encrypt or decrypt since they are the same with just different functions called - :param h_session: - :param c_update_function: - :param c_finalize_function: - :param input_data_list: - + :param h_session: Session handle. + :param c_update_function: C_Update function to call to update each operation. + :param c_finalize_function: Function to call at end of multipart operation. + :param input_data_list: List of data to call update function on. """ max_data_chunk_size = 0xfff0 - plain_data_len = len(_get_string_from_list(input_data_list)) + plain_data_len = len(b"".join(input_data_list)) remaining_length = plain_data_len - python_string = b'' + python_data = [] i = 0 while remaining_length > 0: current_chunk = input_data_list[i] @@ -189,9 +188,8 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in current_chunk_len = min(len(current_chunk), remaining_length) if current_chunk_len > max_data_chunk_size: - raise Exception( - "chunk_sizes variable too large, the maximum size of a chunk is " + str( - max_data_chunk_size)) + raise ValueError("chunk_sizes variable too large," + " the maximum size of a chunk is %s" % max_data_chunk_size) out_data = create_string_buffer(b'', max_data_chunk_size) out_data_len = CK_ULONG(max_data_chunk_size) @@ -202,25 +200,28 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in data_chunk, data_chunk_len, cast(out_data, CK_BYTE_PTR), byref(out_data_len)) if ret != CKR_OK: + LOG.debug("Failed C_Update operation on chunk %.20s (%s/%s) - ret %s", + current_chunk, i, len(input_data_list), ret_vals_dictionary[ret]) return ret, None remaining_length -= current_chunk_len # Get the output - python_string += out_data.raw[0:int(out_data_len.value)] + python_data.append(string_at(out_data, out_data_len.value)) i += 1 # Finalizing multipart decrypt operation - out_data_len = CK_ULONG(max_data_chunk_size) - out_data = create_string_buffer(b"", out_data_len.value) - output = cast(out_data, CK_BYTE_PTR) - ret = c_finalize_function(h_session, output, byref(out_data_len)) + fin_out_data_len = CK_ULONG(max_data_chunk_size) + fin_out_data = create_string_buffer(b"", fin_out_data_len.value) + output = cast(fin_out_data, CK_BYTE_PTR) + ret = c_finalize_function(h_session, output, byref(fin_out_data_len)) if ret != CKR_OK: return ret, None - python_string += out_data.value + if fin_out_data_len.value > 0: + python_data.append(string_at(fin_out_data, fin_out_data_len.value)) - return ret, python_string + return ret, b"".join(python_data) def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, extra_params=None): diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 1820743..fa04a45 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -117,7 +117,12 @@ def to_c_mech(self): if self.params is None or 'iv' not in self.params: self.params['iv'] = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] LOG.warning("Using static IVs can be insecure! ") - iv_ba, iv_len = to_byte_array(self.params['iv']) + if len(self.params['iv']) == 0: + LOG.debug("Setting IV to NULL (using internal)") + iv_ba = None + iv_len = 0 + else: + iv_ba, iv_len = to_byte_array(self.params['iv']) self.mech.pParameter = iv_ba self.mech.usParameterLen = iv_len return self.mech @@ -134,7 +139,12 @@ def to_c_mech(self): if self.params is None or 'iv' not in self.params: self.params['iv'] = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] LOG.warning("Using static IVs can be insecure! ") - iv_ba, iv_len = to_byte_array(self.params['iv']) + if len(self.params['iv']) == 0: + LOG.debug("Setting IV to NULL (using internal)") + iv_ba = None + iv_len = 0 + else: + iv_ba, iv_len = to_byte_array(self.params['iv']) self.mech.pParameter = iv_ba self.mech.usParameterLen = iv_len return self.mech @@ -290,9 +300,14 @@ def to_c_mech(self): """ super(AESGCMMechanism, self).to_c_mech() gcm_params = CK_AES_GCM_PARAMS() - ivdata, ivlen = to_byte_array(self.params['iv']) - gcm_params.pIv = cast(ivdata, CK_BYTE_PTR) - gcm_params.ulIvLen = ivlen + if len(self.params['iv']) == 0: + LOG.debug("Setting IV to NULL (using internal)") + iv_ba = None + iv_len = 0 + else: + iv_ba, iv_len = to_byte_array(self.params['iv']) + gcm_params.pIv = cast(iv_ba, CK_BYTE_PTR) + gcm_params.ulIvLen = iv_len # Assuming 8 bits per entry in IV. gcm_params.ulIvBits = CK_ULONG(len(self.params['iv']) * 8) aad, aadlen = to_char_array(self.params['AAD']) @@ -378,11 +393,11 @@ def to_c_mech(self): CKM_DES3_CBC_PAD_IPSEC: IvMechanism, CKM_CAST3_CBC_PAD: IvMechanism, CKM_CAST5_CBC_PAD: IvMechanism, - CKM_AES_KW: IvMechanism, - CKM_AES_KWP: IvMechanism, CKM_DES_CFB8: IvMechanism, CKM_DES_CFB64: IvMechanism, CKM_DES_OFB64: IvMechanism, + CKM_AES_KW: IvMechanism, + CKM_AES_KWP: IvMechanism, CKM_AES_CFB8: IvMechanism, CKM_AES_CFB128: IvMechanism, CKM_AES_OFB: IvMechanism, @@ -407,9 +422,10 @@ def to_c_mech(self): CKM_RC5_ECB: RC5Mechanism, CKM_AES_XTS: AESXTSMechanism, + (CKM_VENDOR_DEFINED + 0x11c): AESGCMMechanism, # Backwards compatibility w/ older Lunas. + CKM_AES_GCM: AESGCMMechanism, CKM_RSA_PKCS_OAEP: RSAPKCSOAEPMechanism, - CKM_AES_GCM: AESGCMMechanism, CKM_RSA_PKCS_PSS: RSAPKCSPSSMechanism, CKM_SHA1_RSA_PKCS_PSS: RSAPKCSPSSMechanism, diff --git a/tests/functional/conftest.py b/tests/functional/conftest.py index 83b2dac..23937a5 100644 --- a/tests/functional/conftest.py +++ b/tests/functional/conftest.py @@ -21,7 +21,7 @@ from pycryptoki.session_management import c_initialize_ex, c_close_all_sessions_ex, \ ca_factory_reset_ex, c_open_session_ex, login_ex, c_finalize_ex, \ c_close_session, c_logout, c_get_token_info_ex -from pycryptoki.token_management import c_init_token_ex +from pycryptoki.token_management import c_init_token_ex, c_get_mechanism_list_ex LOG = logging.getLogger(__name__) @@ -89,6 +89,10 @@ def pytest_configure(config): flags = token_info['flags'] is_ped = (flags & CKF_PROTECTED_AUTHENTICATION_PATH) != 0 hsm_config["is_ped"] = is_ped + raw_firmware = token_info['firmwareVersion'] + hsm_config['firmware'] = "{}.{}.{}".format(raw_firmware.major, + raw_firmware.minor / 10, + raw_firmware.minor % 10) if is_ped: admin_pwd = None @@ -193,3 +197,15 @@ def partition_clearer(auth_session): except LunaException: LOG.exception("Failed to destroy all objects created on this session") + +@pytest.yield_fixture(scope="class") +def valid_mechanisms(): + """ + Fixture that will query the active slot to get a list of valid mechanisms. + This can be used for assertions across FW versions/configurations. Note, this ends up being + just a list of constants, but it should match up w/ what you're using from `pycryptoki.defines`. + + :return: list of integers, each corresponding to a mechanism. + """ + raw_mechs = c_get_mechanism_list_ex(slot=hsm_config['test_slot']) + yield raw_mechs diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index 64e6d4f..3c3dbae 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -1,14 +1,12 @@ """ Functional tests for encryption / decryption """ +import collections import logging +from distutils.version import LooseVersion + import pytest from pycryptoki.default_templates import get_default_key_template, get_default_key_pair_template, \ MECHANISM_LOOKUP_EXT -from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, c_destroy_object -from pycryptoki.encryption import _split_string_into_list, _get_string_from_list, \ - c_encrypt, c_decrypt -from pycryptoki.return_values import ret_vals_dictionary - from pycryptoki.defines import (CKM_DES_CBC, CKM_DES_KEY_GEN, CKM_AES_CBC, CKM_AES_ECB, CKM_AES_GCM, CKM_AES_KEY_GEN, CKM_DES3_CBC, CKM_DES3_ECB, CKM_DES3_CBC_PAD, CKM_DES3_KEY_GEN, @@ -19,9 +17,13 @@ CKM_SEED_CBC, CKM_SEED_CBC_PAD, CKM_SEED_ECB, CKM_SEED_KEY_GEN, CKM_RSA_PKCS, CKM_RSA_PKCS_OAEP, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X_509, CKM_RSA_X9_31_KEY_PAIR_GEN, - CKM_SHA_1, CKG_MGF1_SHA1) - -from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_DEVICE_MEMORY, CKR_KEY_SIZE_RANGE) + CKM_SHA_1, CKG_MGF1_SHA1, CKM_AES_KWP, CKM_AES_KW, + CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID) +from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_KEY_SIZE_RANGE) +from pycryptoki.encryption import c_encrypt, c_decrypt +from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, c_destroy_object +from pycryptoki.return_values import ret_vals_dictionary +from . import config as hsm_config logger = logging.getLogger(__name__) @@ -29,6 +31,8 @@ CKM_AES_CBC: CKM_AES_KEY_GEN, CKM_AES_ECB: CKM_AES_KEY_GEN, CKM_AES_GCM: CKM_AES_KEY_GEN, + CKM_AES_KW: CKM_AES_KEY_GEN, + CKM_AES_KWP: CKM_AES_KEY_GEN, # Note: Supported in Q3/Q4 2016 SA CKM_DES3_CBC: CKM_DES3_KEY_GEN, CKM_DES3_ECB: CKM_DES3_KEY_GEN, CKM_DES3_CBC_PAD: CKM_DES3_KEY_GEN, @@ -42,8 +46,8 @@ CKM_RC4: CKM_RC4_KEY_GEN, CKM_SEED_CBC: CKM_SEED_KEY_GEN, CKM_SEED_CBC_PAD: CKM_SEED_KEY_GEN, - CKM_SEED_ECB: CKM_SEED_KEY_GEN - } + CKM_SEED_ECB: CKM_SEED_KEY_GEN} + ASYM_TABLE = {CKM_RSA_PKCS: CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS_OAEP: CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X_509: CKM_RSA_X9_31_KEY_PAIR_GEN} @@ -52,8 +56,13 @@ # *** Update as additional test params are added *** PARAM_TABLE = {CKM_DES_CBC: [{}, {'iv': list(range(8))}], CKM_AES_CBC: [{}, {'iv': list(range(16))}], + CKM_AES_KW: [{'iv': []}, + {'iv': list(range(8))}], + CKM_AES_KWP: [{'iv': []}, + {'iv': list(range(8))}], + # Note: Supported in Q3/Q4 2016 SA CKM_AES_ECB: [{}], - CKM_AES_GCM: [{'iv': list(range(16)), 'AAD': b'notsosecret', 'ulTagBits': 32}], + CKM_AES_GCM: [{'iv': list(range(8)), 'AAD': b'notsosecret', 'ulTagBits': 32}], CKM_DES3_CBC: [{}, {'iv': list(range(8))}], CKM_DES3_ECB: [{}], CKM_DES3_CBC_PAD: [{}, {'iv': list(range(8))}], @@ -69,7 +78,9 @@ CKM_SEED_CBC_PAD: [{}], CKM_SEED_ECB: [{}], CKM_RSA_PKCS: [{}], - CKM_RSA_PKCS_OAEP: [{'hashAlg': CKM_SHA_1, 'mgf': CKG_MGF1_SHA1, 'sourceData': list(range(12))}], + CKM_RSA_PKCS_OAEP: [{'hashAlg': CKM_SHA_1, + 'mgf': CKG_MGF1_SHA1, + 'sourceData': list(range(12))}], CKM_RSA_X_509: [{}]} # TESTING DATA @@ -77,36 +88,44 @@ RAW = b"abcdefghijk" # Flavors which auto-pad (will return 'CKR_OK' on un-padded(RAW) data) -PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, CKM_RC2_CBC_PAD, CKM_RC4, CKM_AES_GCM, CKM_SEED_CBC_PAD] - -# Flavors which are not compatible with multi encrypt/decrypt -NOT_MULTI = [CKM_AES_GCM] +PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, + CKM_RC2_CBC_PAD, + CKM_RC4, + CKM_AES_GCM, + CKM_AES_KWP, + CKM_SEED_CBC_PAD] # Ret error, however encrypt /decrypt is successful. Needs to be addressed at some point KEY_SIZE_RANGE = [CKM_RC2_CBC, CKM_RC2_ECB, CKM_RC2_CBC_PAD] -def ret_val(mech, data): +def ret_val(mech, data, valid_mechs=None): """ Determine expected ret during encryption of 'data' with 'mech' + :param mech: mechanism :param data: type of data + :param valid_mechs: List of valid mechanisms (retrieved by C_GetMechanismList()) :return: expected return value """ + # Ret error, however encrypt /decrypt is successful. Needs to be addressed at some point if mech in KEY_SIZE_RANGE: return CKR_KEY_SIZE_RANGE + if valid_mechs and mech not in valid_mechs: + # If we are checking valid mechanisms and it's not in the list, ret will be incorrect. + logger.warning("Mechanism %s (%s) wasn't found in valid mechanism list!", + mech, MECHANISM_LOOKUP_EXT.get(mech, ("Unknown",))[0]) + return CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID + if data == RAW: - if mech not in PADDING_ALGORITHMS: + if mech not in PADDING_ALGORITHMS and mech not in ASYM_TABLE: return CKR_DATA_LEN_RANGE else: return CKR_OK else: - if mech == CKM_AES_GCM: - return CKR_DEVICE_MEMORY - else: - return CKR_OK + return CKR_OK def scenarios(which_table): @@ -117,7 +136,13 @@ def scenarios(which_table): ret_list = [] for mech in which_table.keys(): for params in PARAM_TABLE[mech]: - ret_list.append((mech, params)) + if mech == CKM_AES_KW: + ret_list.append( + pytest.mark.xfail( + LooseVersion(hsm_config.get('firmware', "6.2.1")) > LooseVersion("6.24.0"), + reason="Mechanism not list in C_GetMechanismList()")((mech, params))) + else: + ret_list.append((mech, params)) return ret_list @@ -125,11 +150,15 @@ def scenarios(which_table): def idfn(k_table): """ Generate test ids """ id_list = [] - for s in scenarios(k_table): - m_type, params = s - id_str = MECHANISM_LOOKUP_EXT[m_type][0].replace("CKM_", "") - for p in params: - id_str += "-" + str(p) + for test_args in scenarios(k_table): + if not isinstance(test_args, tuple): + # For mark decorators. The condition is arg #1 (can't be keyword, due to pytest bug) + # Arg #2 is the tuple we want to unpack. + test_args = test_args.args[1] + m_type, params = test_args + id_str = MECHANISM_LOOKUP_EXT.get(m_type, ("Unknown",))[0].replace("CKM_", "") + for key, value in params.items(): + id_str += "-{}: {}".format(key, value) id_list.append(id_str) return id_list @@ -147,7 +176,7 @@ def sym_keys(auth_session): if ret == CKR_OK: keys[key_type] = key_handle else: - logger.info("Failed to generate key: {}\nReturn code: {}".format(key_type, ret)) + logger.info("Failed to generate key: %s\nReturn code: %s", key_type, ret) yield keys finally: @@ -167,7 +196,7 @@ def asym_keys(auth_session): if ret == CKR_OK: keys[key_type] = (pub_key, prv_key) else: - logger.info("Failed to generate key: {}\nReturn code: {}".format(key_type, ret)) + logger.info("Failed to generate key: %s\nReturn code: %s", key_type, ret) yield keys finally: @@ -177,15 +206,23 @@ def asym_keys(auth_session): class TestEncryptData(object): - def verify_ret(self, ret, expected_ret): """ Assert that ret is as expected :param ret: the actual return value :param expected_ret: the expected return value """ - assert ret == expected_ret, "Function should return: " + \ - ret_vals_dictionary[expected_ret] + ".\nInstead returned: " + ret_vals_dictionary[ret] + if isinstance(expected_ret, collections.Iterable): + ret_codes = ", ".join(("{}".format(ret_vals_dictionary[val] for val in expected_ret))) + err_message = ("Function should return one of: {}.\n" + "Instead returned: {}".format(ret_codes, + ret_vals_dictionary[ret])) + assert ret in expected_ret, err_message + else: + err_message = ("Function should return: {}.\n" + "Instead returned: {}".format(ret_vals_dictionary[expected_ret], + ret_vals_dictionary[ret])) + assert ret == expected_ret, err_message def verify_data(self, starting_data, ending_data): """ @@ -193,12 +230,14 @@ def verify_data(self, starting_data, ending_data): :param starting_data: the initial data :param ending_data: the data after encryption / decryption """ - assert starting_data == ending_data, "The data after encryption/decryption is incorrect.\n" + \ - "Starting data: " + str(starting_data) + "\nEnding data: " + str(ending_data) + assert starting_data == ending_data, ("The data after encryption/decryption is " + "incorrect.\n Starting data: {}\n" + "Ending data: {}".format(starting_data, ending_data)) - @pytest.mark.parametrize('data', [PAD, RAW], ids=["Pad", "Raw"]) + @pytest.mark.parametrize('data', [PAD, RAW], ids=["valid_data", "raw (pad-required)"]) @pytest.mark.parametrize(('m_type', 'params'), scenarios(SYM_TABLE), ids=idfn(SYM_TABLE)) - def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session): + def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session, + valid_mechanisms): """ test encryption decryption calls of sym. crypto's :param m_type: mechanism flavor @@ -211,38 +250,47 @@ def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session) if sym_keys.get(SYM_TABLE[m_type]) is None: pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) - exp_ret = ret_val(m_type, data) + exp_ret = ret_val(m_type, data, valid_mechanisms) h_key = sym_keys[SYM_TABLE[m_type]] + # AES_GCM Requires smaller data sizes. + if m_type == CKM_AES_GCM and data == PAD: + data = "a" * 0xff0 + ret, encrypted = c_encrypt(auth_session, m_type, h_key, data, extra_params=params) self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing - if exp_ret == (CKR_OK or KEY_SIZE_RANGE): + if exp_ret in (CKR_OK, KEY_SIZE_RANGE): ret, end_data = c_decrypt(auth_session, m_type, h_key, encrypted, extra_params=params) self.verify_ret(ret, exp_ret) self.verify_data(data, end_data) - @pytest.mark.parametrize('data', [PAD, RAW], ids=["Pad", "Raw"]) + @pytest.mark.parametrize('data', [PAD, RAW], ids=["valid_data", "raw(pad-required)"]) @pytest.mark.parametrize(('m_type', 'params'), scenarios(SYM_TABLE), ids=idfn(SYM_TABLE)) - def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session): + def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session, + valid_mechanisms): """ test encryption decryption calls of sym. crypto's + :param m_type: mechanism flavor :param params: extra params :param data: testing data :param sym_keys: key fixture :param auth_session: """ - if m_type in NOT_MULTI: - pytest.xfail("m_type does not support multi encrypt/decrypt") # Auto-fail when key-generation is fails if sym_keys.get(SYM_TABLE[m_type]) is None: pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) - exp_ret = ret_val(m_type, data) + # AES_KW will fail on very large data sizes + # AES_GCM requires smaller data sizes as well. + if m_type in (CKM_AES_KW, CKM_AES_GCM) and data == PAD: + data = "a" * 256 + + exp_ret = ret_val(m_type, data, valid_mechanisms) h_key = sym_keys[SYM_TABLE[m_type]] encrypt_this = [data, data, data, data] @@ -250,18 +298,19 @@ def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_se self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing - if exp_ret == (CKR_OK or KEY_SIZE_RANGE): - if m_type not in PADDING_ALGORITHMS: + if exp_ret in (CKR_OK, KEY_SIZE_RANGE): + if m_type not in PADDING_ALGORITHMS and m_type != CKM_AES_KW: assert len(encrypted) == len(b"".join(encrypt_this)) - decrypt_this = _split_string_into_list(encrypted, len(data)) - ret, end_data = c_decrypt(auth_session, m_type, h_key, decrypt_this, extra_params=params) + ret, end_data = c_decrypt(auth_session, m_type, h_key, encrypted, + extra_params=params) self.verify_ret(ret, exp_ret) - - self.verify_data(_get_string_from_list(encrypt_this), end_data) + if m_type in PADDING_ALGORITHMS: + end_data = end_data.rstrip(b"\x00") + self.verify_data(b"".join(encrypt_this), end_data) @pytest.mark.parametrize(('m_type', 'params'), scenarios(ASYM_TABLE), ids=idfn(ASYM_TABLE)) - def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session): + def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session, valid_mechanisms): """ test encryption decryption calls of asym. crypto's :param m_type: mechanism flavor @@ -272,12 +321,15 @@ def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session): if asym_keys.get(ASYM_TABLE[m_type]) is None: pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) + expected_retcode = ret_val(m_type, RAW, valid_mechanisms) pub_key, prv_key = asym_keys[ASYM_TABLE[m_type]] ret, decrypt_this = c_encrypt(auth_session, m_type, pub_key, RAW, extra_params=params) - self.verify_ret(ret, CKR_OK) + self.verify_ret(ret, expected_retcode) - ret, decrypted_data = c_decrypt(auth_session, m_type, prv_key, decrypt_this, extra_params=params) - self.verify_ret(ret, CKR_OK) + if expected_retcode == CKR_OK: + ret, decrypted_data = c_decrypt(auth_session, m_type, prv_key, decrypt_this, + extra_params=params) + self.verify_ret(ret, expected_retcode) self.verify_data(RAW, decrypted_data.replace(b"\x00", b"")) From 13a6ed9c757e08553d6536f292568c5cd3f565c0 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 15 Aug 2016 10:10:34 -0400 Subject: [PATCH 072/109] LA-1864 Fix for Python3 string types in enc tests Change-Id: Id6ffb26a5a56823fc16064fbaa9b961f431d7b92 --- tests/functional/test_encrypt_decrypt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index 3c3dbae..c1f2183 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -255,7 +255,7 @@ def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session, # AES_GCM Requires smaller data sizes. if m_type == CKM_AES_GCM and data == PAD: - data = "a" * 0xff0 + data = b"a" * 0xff0 ret, encrypted = c_encrypt(auth_session, m_type, h_key, data, extra_params=params) self.verify_ret(ret, exp_ret) From 03f5ce43abb31b9e91f373d5cc46c6f31d7573f6 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 16 Aug 2016 15:28:37 -0400 Subject: [PATCH 073/109] LA-2031 Replace individual mechanism parameters * Fixed unicode strings being used as data in multipart testing * Removed individual flavor/extra_params arguments in favor of unified 'mechanism' keyword. This keyword argument can handle dictionaries or direct CK_MECHANISM structures (and CK types for key generation/sig/verify). * Updated tests to fit the change in structure * Moved around some of the order of args for sign/verify, such that it will follow the following pattern: session, key, data, mechanism (some were session, data, key, mech, which contrasted w/ our c_encrypt functions) * Moved all mechanism parsing to single function. * Improved docstrings Change-Id: Ibd4c8a6be9b52b0bee40f927ae0aa69b7236ff7f --- .gitignore | 2 +- .gitreview | 4 - pycryptoki/daemon/rpyc_pycryptoki.py | 57 +------------ pycryptoki/encryption.py | 84 +++++++------------ pycryptoki/key_generator.py | 64 +++++++------- pycryptoki/mechanism.py | 39 +++++++++ pycryptoki/sign_verify.py | 32 ++----- tests/functional/test_cka_start_and_end.py | 6 +- tests/functional/test_encrypt_decrypt.py | 22 +++-- tests/functional/test_hsm_management.py | 11 +-- tests/functional/test_keys.py | 34 ++++---- tests/functional/test_sign_verify.py | 8 +- .../functional/test_usage_limit_and_count.py | 58 +++++++------ tests/functional/test_wrap_unwrap.py | 48 ++++++----- tox.ini | 14 ++++ 15 files changed, 224 insertions(+), 259 deletions(-) delete mode 100644 .gitreview create mode 100644 tox.ini diff --git a/.gitignore b/.gitignore index 63a623f..8ab82f6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ # Created by https://www.gitignore.io - +.gitreview ### PyCharm ### # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm diff --git a/.gitreview b/.gitreview deleted file mode 100644 index 13373f3..0000000 --- a/.gitreview +++ /dev/null @@ -1,4 +0,0 @@ -[gerrit] -host=172.20.10.212 -project=Auto/pycryptoki -defaultbranch=master diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 6906187..c5131b3 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -18,15 +18,13 @@ """ from __future__ import print_function -import ctypes + import logging import multiprocessing import os import signal import sys import time -from _ctypes import pointer -from ctypes import cast from optparse import OptionParser import rpyc @@ -41,7 +39,6 @@ ca_extract, ca_extract_ex, ca_insert, ca_insert_ex) from pycryptoki.cryptoki import CK_ULONG -from pycryptoki.cryptoki import CK_VOID_PTR from pycryptoki.encryption import (c_encrypt, c_encrypt_ex, c_decrypt, c_decrypt_ex, c_wrap_key, c_wrap_key_ex, @@ -65,7 +62,6 @@ ca_get_hsm_capability_setting_ex, ca_set_hsm_policies, ca_set_hsm_policies_ex, ca_set_destructive_hsm_policies, ca_set_destructive_hsm_policies_ex) -from pycryptoki.key_generator import _get_mechanism from pycryptoki.key_generator import (c_destroy_object, c_destroy_object_ex, c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, @@ -358,55 +354,8 @@ def _rpyc_getattr(self, name): exposed_ca_clonemofn_ex = staticmethod(ca_clonemofn_ex) exposed_ca_duplicatemofn = staticmethod(ca_duplicatemofn) exposed_ca_duplicatemofn_ex = staticmethod(ca_duplicatemofn_ex) - - @staticmethod - def exposed_c_derive_key_ex(h_session, h_base_key, h_second_key, template, mech_flavor, - mech=None): - """#key_generator.py - - Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the - daemon side - because it involves pointers. - - :param h_session: - :param h_base_key: - :param h_second_key: - :param template: - :param mech_flavor: - :param mech: (Default value = None) - - """ - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key_ex(h_session, h_base_key, template, mech_flavor, mech) - - @staticmethod - def exposed_c_derive_key(h_session, h_base_key, h_second_key, template, mech_flavor, mech=None): - """#key_generator.py - - Wrapper around the default c_derive_key_ex. Have to do the mechanism creation on the - daemon side - because it involves pointers. - - :param h_session: - :param h_base_key: - :param h_second_key: - :param template: - :param mech_flavor: - :param mech: (Default value = None) - - """ - if mech: - mech = _get_mechanism(mech) - c_second_key = CK_ULONG(h_second_key) - mech.pParameter = cast(pointer(c_second_key), CK_VOID_PTR) - mech.usParameterLen = ctypes.sizeof(c_second_key) - - return c_derive_key(h_session, h_base_key, template, mech_flavor, mech) + exposed_c_derive_key = staticmethod(c_derive_key) + exposed_c_derive_key_ex = staticmethod(c_derive_key_ex) def server_launch(service, ip, port, config): diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index ea3cb1c..4cc47ac 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -5,8 +5,9 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from .return_values import ret_vals_dictionary -from .attributes import Attributes, to_char_array +from six import string_types + +from .attributes import Attributes, to_char_array, to_byte_array from .common_utils import AutoCArray, refresh_c_arrays from .cryptoki import CK_ULONG, \ C_EncryptInit, C_Encrypt @@ -14,35 +15,29 @@ C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ C_DecryptUpdate, C_DecryptFinal from .defines import CKR_OK -from .mechanism import Mechanism +from .mechanism import parse_mechanism +from .return_values import ret_vals_dictionary from .test_functions import make_error_handle_function LOG = logging.getLogger(__name__) -def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, extra_params=None): +def c_encrypt(h_session, h_key, data, mechanism): """Encrypts data with a given key and encryption flavor encryption flavors :param h_session: Current session - :param encryption_flavor: The flavor of encryption to use :param h_key: The key handle to encrypt the data with - :param data_to_encrypt: The data to encrypt, either a string or a list of strings. If this is - a list - a multipart operation will be used - :param mech: The mechanism to use, if None will try to look up a - default mechanism based on the encryption flavor - :param extra_params: Parameters to be passed to mechanism generation. + :param data: The data to encrypt, either a string or a list of strings. If this is + a list a multipart operation will be used + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :returns: Returns the result code of the operation, a python string representing the encrypted data """ - if mech is None: - py_mech = Mechanism(mech_type=encryption_flavor, params=extra_params) - mech = py_mech.to_c_mech() - + mech = parse_mechanism(mechanism) # if a list is passed out do an encrypt operation on each string in the list, otherwise just # do one encrypt operation - is_multi_part_operation = isinstance(data_to_encrypt, (list, tuple)) + is_multi_part_operation = isinstance(data, (list, tuple)) # Initialize encryption ret = C_EncryptInit(h_session, byref(mech), CK_ULONG(h_key)) @@ -51,9 +46,9 @@ def c_encrypt(h_session, encryption_flavor, h_key, data_to_encrypt, mech=None, e if is_multi_part_operation: ret, encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, - C_EncryptFinal, data_to_encrypt) + C_EncryptFinal, data) else: - plain_data, plain_data_length = to_char_array(data_to_encrypt) + plain_data, plain_data_length = to_char_array(data) plain_data = cast(plain_data, POINTER(c_ubyte)) enc_data = AutoCArray(ctype=c_ubyte) @@ -100,26 +95,17 @@ def _get_string_from_list(list_of_strings): return b"".join(list_of_strings) -def c_decrypt(h_session, decryption_flavor, h_key, encrypted_data, mech=None, extra_params=None): +def c_decrypt(h_session, h_key, encrypted_data, mechanism): """Decrypts some data :param h_session: The session to use - :param decryption_flavor: The decryption flavor to create a new mechanism with if no mechanism - is provided :param h_key: The handle of the key to use to decrypt - :param mech: The mechanism, if none is provided a blank one will be - provided based on the decryption_flavor (Default value = None) :param encrypted_data: Data to be decrypted - :param extra_params: Parameters to be passed to mechanism generation. + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :returns: The result code, a python string of the decrypted data """ - - # Get the mechanism - if mech is None: - py_mech = Mechanism(mech_type=decryption_flavor, params=extra_params) - mech = py_mech.to_c_mech() - + mech = parse_mechanism(mechanism) # Initialize Decrypt ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key)) if ret != CKR_OK: @@ -224,23 +210,18 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in return ret, b"".join(python_data) -def c_wrap_key(h_session, h_wrapping_key, h_key, encryption_flavor, mech=None, extra_params=None): +def c_wrap_key(h_session, h_wrapping_key, h_key, mechanism): """Function which wraps a key :param h_session: The session to use :param h_wrapping_key: The handle of the key to use to wrap another key :param h_key: The key to wrap - :param encryption_flavor: The encryption flavor to create a new mechanism with if no mechanism - is provided - :param mech: The mechanism, if none is provided a blank one will be provided based on the encryption flavor (Default value = None) - :param extra_params: Parameters to be passed to mechanism generation. + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :returns: The result code, a ctypes byte array representing the new key """ - if mech is None: - py_mech = Mechanism(mech_type=encryption_flavor, params=extra_params) - mech = py_mech.to_c_mech() + mech = parse_mechanism(mechanism) wrapped_key = AutoCArray(ctype=c_ubyte) @@ -261,33 +242,26 @@ def _wrap(): c_wrap_key_ex = make_error_handle_function(c_wrap_key) -def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, encryption_flavor, - mech=None, extra_params=None): +def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, mechanism): """Function which unwraps a key :param h_session: The session to use :param h_unwrapping_key: The wrapping key handle - :param wrapped_key: The wrapped key in a ctypes CK_CHAR_PTR array + :param wrapped_key: The wrapped key :param key_template: The python template representing the new key's template - :param encryption_flavor: If the mechanism is not specified it will create a - default one based on the encryption flavor - :param mech: The mechanism to use, if null a default one will be created based on the - encryption_flavor - :param h_unwrapping_key: Key to do the unwrapping - :param wrapped_key: Key to be decrypted (unwrapped) - :param extra_params: Parameters to be passed to mechanism generation. + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :returns: The result code, the handle of the unwrapped key """ - if mech is None: - py_mech = Mechanism(mech_type=encryption_flavor, params=extra_params) - mech = py_mech.to_c_mech() - + mech = parse_mechanism(mechanism) c_template = Attributes(key_template).get_c_struct() - byte_wrapped_key = cast(wrapped_key, CK_BYTE_PTR) + if isinstance(wrapped_key, string_types): + wrapped_key = bytearray(wrapped_key) + byte_wrapped_key, key_len = to_byte_array(wrapped_key) + byte_wrapped_key = cast(byte_wrapped_key, CK_BYTE_PTR) h_output_key = CK_ULONG() - ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), byte_wrapped_key, - CK_ULONG(len(wrapped_key)), + ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), + byte_wrapped_key, key_len, c_template, CK_ULONG(len(key_template)), byref(h_output_key)) return ret, h_output_key.value diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 5659453..5e8d85e 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -1,18 +1,17 @@ """ Methods used to generate keys. """ - from ctypes import byref +from .attributes import Attributes +from .cryptoki import C_DeriveKey from .cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, C_GenerateKey, \ C_GenerateKeyPair, \ C_CopyObject from .default_templates import CKM_DES_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP + get_default_key_pair_template from .defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN -from .attributes import Attributes -from .cryptoki import C_DeriveKey -from .mechanism import NullMech +from .mechanism import parse_mechanism from .test_functions import make_error_handle_function @@ -55,28 +54,23 @@ def c_copy_object(h_session, h_object, template=None): c_copy_object_ex = make_error_handle_function(c_copy_object) -def _get_mechanism(flavor): - """Method used to get the CK_MECHANISM variable for key generation. - - :param flavor: The key flavor of the mechanism - :returns: Returns a blank mechanism of type flavor - - """ - return NullMech(flavor).to_c_mech() - - -def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP): +def c_generate_key(h_session, mechanism=None, template=None): """ Generates a symmetric key of a given flavor given the correct template. :param h_session: Current session - :param flavor: The flavour of the DES key to generate :param template: The template to use to generate the key + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :return: Returns the result code and the key's handle """ - # INITALIZE VARIABLES - mech = _get_mechanism(flavor) + if mechanism is None: + mechanism = {"mech_type": CKM_DES_KEY_GEN} + + mech = parse_mechanism(mechanism) + + if template is None: + template = CKM_DES_KEY_GEN_TEMP key_attributes = Attributes(template) us_public_template_size = CK_ULONG(len(template)) @@ -93,24 +87,28 @@ def c_generate_key(h_session, flavor=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_T c_generate_key_ex = make_error_handle_function(c_generate_key) -def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None): +def c_generate_key_pair(h_session, + mechanism=None, + pbkey_template=None, + prkey_template=None): """Generates a private and public key pair for a given flavor, and given public and private key templates. The return value will be the handle for the key. :param h_session: Current session - :param flavor: The flavor of the key to generate (Default value = CKM_DES_KEY_GEN) :param pbkey_template: The public key template to use for key generation :param prkey_template: The private key template to use for key generation - :param mech: The mechanism to generate the key with + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function + :returns: Returns the result code, the public key's handle, and the private key's handle """ - # INITALIZE VARIABLES - if mech is None: - mech = _get_mechanism(flavor) + if mechanism is None: + mechanism = {"mech_type": CKM_RSA_PKCS_KEY_PAIR_GEN} + + if pbkey_template is None and prkey_template is None: + pbkey_template, prkey_template = get_default_key_pair_template(CKM_RSA_PKCS_KEY_PAIR_GEN) + + mech = parse_mechanism(mechanism) pbkey_template_size = len(pbkey_template) pbkey_attributes = Attributes(pbkey_template) @@ -131,21 +129,17 @@ def c_generate_key_pair(h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) -def c_derive_key(h_session, h_base_key, template, mech_flavor, mech=None): +def c_derive_key(h_session, h_base_key, template, mechanism=None): """Calls C_DeriveKey :param h_session: The session handle to use :param h_base_key: The base key :param template: A python template of attributes (ex. CKM_DES_KEY_GEN_TEMP) - :param mech: The mechanism to use, if None a default mechanism will be used - :param mech_flavor: + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :returns: The result code, The derived key's handle """ - - if mech is None: - mech = _get_mechanism(mech_flavor) - + mech = parse_mechanism(mechanism) h_key = CK_OBJECT_HANDLE() c_template = Attributes(template).get_c_struct() ret = C_DeriveKey(h_session, mech, diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index fa04a45..96f4c1b 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -3,8 +3,11 @@ """ import logging +import types from ctypes import c_void_p, cast, pointer, POINTER, sizeof, create_string_buffer, c_char +from six import integer_types + from . import cryptoki from .attributes import to_byte_array, to_char_array, CONVERSIONS from .cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ @@ -534,3 +537,39 @@ def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") return python_dictionary + + +def parse_mechanism(mechanism_param): + """ + Designed for use with any function call that takes in a mechanism, + this will handle a mechanism parameter that is one of the following: + + 1. CKM_ integer constant -- will create a CK_MECHANISM with only mech_type set. + 2. Dictionary with `mech_type` as a mandatory key, and `params` as an optional key. This + will be passed into the `Mechanism` class for conversion to a CK_MECHANISM. + 3. CK_MECHANISM struct -- passed directly into the raw C Call. + 4. Mechanism class -- will call to_c_mech() on the class, and use the results. + + .. warning:: If you're using this with rpyc, you need to make sure the call `to_c_mech` occurs + on the *server* (the machine with the HSM)! If you pass in a :py:class:`Mechanism` class that + was created on the client, the resulting call into `to_c_mech()` will *also* be on the client + side! + + :param mechanism_param: Parameter to convert to a C Mechanism. + :return: `CK_MECHANISM` struct. + """ + + if isinstance(mechanism_param, dict): + mech = Mechanism(**mechanism_param).to_c_mech() + elif isinstance(mechanism_param, CK_MECHANISM): + mech = mechanism_param + elif isinstance(mechanism_param, integer_types): + mech = NullMech(mech_type=mechanism_param).to_c_mech() + elif isinstance(mechanism_param, Mechanism): + mech = mechanism_param.to_c_mech() + else: + raise TypeError("Invalid mechanism type {}, should be CK_MECHANISM, dictionary with " + "kwargs to be passed to `Mechanism`, integer constant, or a " + "Mechanism() class.".format(type(mechanism_param))) + + return mech diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 5c33a0a..dd32b06 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -13,18 +13,17 @@ C_SignFinal, C_VerifyUpdate, C_VerifyFinal from .defines import CKR_OK from .encryption import _get_string_from_list -from .mechanism import Mechanism, NullMech +from .mechanism import parse_mechanism from .test_functions import make_error_handle_function LOG = logging.getLogger(__name__) -def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, extra_params=None): +def c_sign(h_session, h_key, data_to_sign, mechanism): """ Performs a C_SignInit and C_Sign operation on some data :param h_session: The current session - :param sign_flavor: The flavour of signing to do :param data_to_sign: The data to sign, either a string or a list of strings. If this is a list a multipart operation will be used (using C_...Update and C_...Final) @@ -35,19 +34,11 @@ def c_sign(h_session, sign_flavor, data_to_sign, h_key, mech=None, extra_params= "It will operate on these strings in parts"] :param h_key: The key to sign the data with - :param mech: The mechanism to use, if None a blank mechanism will be created based on the - sign_flavor - :param extra_params: Parameters to be passed to the mechanism creation. If None, blank mechanism - will be used. + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :return: The result code, A python string representing the signature """ - # Get the mechanism - if mech is None: - if extra_params is None: - mech = NullMech(sign_flavor).to_c_mech() - else: - mech = Mechanism(sign_flavor, params=extra_params).to_c_mech() + mech = parse_mechanism(mechanism) # Initialize the sign operation ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key)) @@ -181,15 +172,13 @@ def do_multipart_verify(h_session, input_data_list, signature): return ret -def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=None, - extra_params=None): +def c_verify(h_session, h_key, data_to_verify, signature, mechanism): """ Return the result code of C_Verify which indicates whether or not the signature is valid. :param h_session: The current session :param h_key: The key handle to verify the signature against - :param verify_flavor: The flavour of the mechanism to verify against :param data_to_verify: The data to verify, either a string or a list of strings. If this is a list, a multipart operation will be used (using C_...Update and C_...Final) @@ -201,18 +190,11 @@ def c_verify(h_session, h_key, verify_flavor, data_to_verify, signature, mech=No "It will operate on these strings in parts"] :param signature: The signature of the data - :param mech: The mechanism to use, if None is specified the mechanism will - try to be automatically obtained - :param algorithm: The hash algorithm used on data_to_sign; only necessary for RSA PKCS PSS + :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function :return: The result code """ - # Get the mechanism - if mech is None: - if extra_params is None: - mech = NullMech(verify_flavor).to_c_mech() - else: - mech = Mechanism(verify_flavor, extra_params).to_c_mech() + mech = parse_mechanism(mechanism) # Initialize the verify operation ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key)) diff --git a/tests/functional/test_cka_start_and_end.py b/tests/functional/test_cka_start_and_end.py index d88d570..ab22b4e 100755 --- a/tests/functional/test_cka_start_and_end.py +++ b/tests/functional/test_cka_start_and_end.py @@ -98,7 +98,7 @@ def test_symmetric_key_expiry_des(self): h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - return_val = c_encrypt(h_session, CKM_DES_ECB, h_key, b"This is some data to sign .. ") + return_val = c_encrypt(h_session, h_key, b"This is some data to sign .. ", CKM_DES_ECB) assert return_val == CKR_KEY_NOT_ACTIVE, "return value should be CKR_KEY_NOT_ACTIVE" c_logout_ex(h_session) @@ -168,7 +168,7 @@ def test_symmetric_key_expiry_aes(self): h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - return_val = c_encrypt(h_session, CKM_AES_ECB, h_key, b"This is some data to sign .. ") + return_val = c_encrypt(h_session, h_key, b"This is some data to sign .. ", CKM_AES_ECB) logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" @@ -246,7 +246,7 @@ def test_asymmetric_key_expiry_rsa(self): h_session = c_open_session_ex(slot_num=self.admin_slot) login_ex(h_session, self.admin_slot, CO_PASSWORD, CKU_USER) - return_val = c_encrypt(h_session, CKM_RSA_PKCS, h_pbkey, b"This is some data to sign .. ") + return_val = c_encrypt(h_session, h_pbkey, b"This is some data to sign .. ", CKM_RSA_PKCS) logger.info("Called C_Encrypt, return code: " + str(return_val)) assert return_val == CKR_KEY_NOT_ACTIVE, "Expected return code is CKR_KEY_NOT_ACTIVE" diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index c1f2183..b37f2f5 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -257,12 +257,14 @@ def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session, if m_type == CKM_AES_GCM and data == PAD: data = b"a" * 0xff0 - ret, encrypted = c_encrypt(auth_session, m_type, h_key, data, extra_params=params) + mech = {"mech_type": m_type, + "params": params} + ret, encrypted = c_encrypt(auth_session, h_key, data, mechanism=mech) self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing if exp_ret in (CKR_OK, KEY_SIZE_RANGE): - ret, end_data = c_decrypt(auth_session, m_type, h_key, encrypted, extra_params=params) + ret, end_data = c_decrypt(auth_session, h_key, encrypted, mechanism=mech) self.verify_ret(ret, exp_ret) self.verify_data(data, end_data) @@ -288,13 +290,15 @@ def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_se # AES_KW will fail on very large data sizes # AES_GCM requires smaller data sizes as well. if m_type in (CKM_AES_KW, CKM_AES_GCM) and data == PAD: - data = "a" * 256 + data = b"a" * 256 exp_ret = ret_val(m_type, data, valid_mechanisms) h_key = sym_keys[SYM_TABLE[m_type]] encrypt_this = [data, data, data, data] - ret, encrypted = c_encrypt(auth_session, m_type, h_key, encrypt_this, extra_params=params) + mech = {"mech_type": m_type, + "params": params} + ret, encrypted = c_encrypt(auth_session, h_key, encrypt_this, mechanism=mech) self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing @@ -302,8 +306,7 @@ def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_se if m_type not in PADDING_ALGORITHMS and m_type != CKM_AES_KW: assert len(encrypted) == len(b"".join(encrypt_this)) - ret, end_data = c_decrypt(auth_session, m_type, h_key, encrypted, - extra_params=params) + ret, end_data = c_decrypt(auth_session, h_key, encrypted, mechanism=mech) self.verify_ret(ret, exp_ret) if m_type in PADDING_ALGORITHMS: end_data = end_data.rstrip(b"\x00") @@ -324,12 +327,13 @@ def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session, val expected_retcode = ret_val(m_type, RAW, valid_mechanisms) pub_key, prv_key = asym_keys[ASYM_TABLE[m_type]] - ret, decrypt_this = c_encrypt(auth_session, m_type, pub_key, RAW, extra_params=params) + mech = {"mech_type": m_type, + "params": params} + ret, decrypt_this = c_encrypt(auth_session, pub_key, RAW, mechanism=mech) self.verify_ret(ret, expected_retcode) if expected_retcode == CKR_OK: - ret, decrypted_data = c_decrypt(auth_session, m_type, prv_key, decrypt_this, - extra_params=params) + ret, decrypted_data = c_decrypt(auth_session, prv_key, decrypt_this, mechanism=mech) self.verify_ret(ret, expected_retcode) self.verify_data(RAW, decrypted_data.replace(b"\x00", b"")) diff --git a/tests/functional/test_hsm_management.py b/tests/functional/test_hsm_management.py index d19172e..67daae3 100755 --- a/tests/functional/test_hsm_management.py +++ b/tests/functional/test_hsm_management.py @@ -4,7 +4,6 @@ import pytest -from . import config as hsm_config from pycryptoki.default_templates import CKM_RSA_PKCS_KEY_PAIR_GEN, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP from pycryptoki.defines import CKR_OK, \ @@ -19,10 +18,12 @@ ca_mtkresplit, ca_mtkzeroize, c_performselftest from pycryptoki.key_generator import c_generate_key_pair from pycryptoki.return_values import ret_vals_dictionary +from . import config as hsm_config class TestAlgorithm(object): """Test algorithm class""" + @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): self.h_session = auth_session @@ -108,8 +109,8 @@ def test_hainit(self): "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - @pytest.mark.xfail(condition=not hsm_config['is_ped'] or hsm_config['user'] == "CO", - reason="Not valid on PWD auth") + @pytest.mark.skipif(condition=not hsm_config['is_ped'] or hsm_config['user'] == "CO", + reason="Not valid on PWD auth") def test_initializeremotepedvector(self): """Tests to initialize remote ped vector""" ret = ca_initializeremotepedvector(self.h_session) @@ -118,8 +119,8 @@ def test_initializeremotepedvector(self): "Return code should be " + ret_vals_dictionary[CKR_OK] + \ " not " + ret_vals_dictionary[ret] - @pytest.mark.xfail(condition=not hsm_config['is_ped'] or hsm_config['user'] == "CO", - reason="Not valid on PWD auth") + @pytest.mark.skipif(condition=not hsm_config['is_ped'] or hsm_config['user'] == "CO", + reason="Not valid on PWD auth") def test_deleteremotepedvector(self): """Tests to delete remote ped vector""" ret = ca_deleteremotepedvector(self.h_session) diff --git a/tests/functional/test_keys.py b/tests/functional/test_keys.py index 0c62f40..de24b27 100755 --- a/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -1,4 +1,5 @@ import logging + import pytest from pycryptoki.default_templates import \ @@ -13,7 +14,6 @@ curve_list, get_default_key_template, get_default_key_pair_template, MECHANISM_LOOKUP_EXT) - from pycryptoki.defines import \ (CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_CAST5_KEY_GEN, CKM_RC2_KEY_GEN, CKM_RC4_KEY_GEN, CKM_RC5_KEY_GEN, CKM_GENERIC_SECRET_KEY_GEN, @@ -23,17 +23,16 @@ CKM_ECDSA_KEY_PAIR_GEN, CKA_ECDSA_PARAMS, CKM_KCDSA_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_SHA1_KEY_DERIVATION, CKM_SHA224_KEY_DERIVATION, CKM_SHA256_KEY_DERIVATION, - CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_MD5_KEY_DERIVATION, CKM_MD2_KEY_DERIVATION, + CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_MD5_KEY_DERIVATION, + CKM_MD2_KEY_DERIVATION, CKR_OK, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE) - from pycryptoki.key_generator import \ c_generate_key, c_generate_key_pair, c_derive_key, c_generate_key_ex, c_destroy_object from pycryptoki.mechanism import NullMech from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.test_functions import verify_object_attributes - logger = logging.getLogger(__name__) KEYS = [CKM_DES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_CAST3_KEY_GEN, CKM_CAST5_KEY_GEN, @@ -45,6 +44,7 @@ def pair_params(key_gen): """ Return the params tuple given the key_gen mech """ return (key_gen,) + get_default_key_pair_template(key_gen) + DSA_PUB_TEMPS = [CKM_DSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_224, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_2048_256, CKM_DSA_KEY_PAIR_GEN_PUBTEMP_3072_256] KCDSA_P_TEMPS = [CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_1024_160, CKM_KCDSA_KEY_PAIR_GEN_PUBTEMP_2048_256] @@ -54,7 +54,8 @@ def pair_params(key_gen): pair_params(CKM_ECDSA_KEY_PAIR_GEN), pair_params(CKM_RSA_X9_31_KEY_PAIR_GEN)] KEY_PAIRS.extend([(CKM_DSA_KEY_PAIR_GEN, x, CKM_DSA_KEY_PAIR_GEN_PRIVTEMP) for x in DSA_PUB_TEMPS]) -KEY_PAIRS.extend([(CKM_KCDSA_KEY_PAIR_GEN, x, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP) for x in KCDSA_P_TEMPS]) +KEY_PAIRS.extend( + [(CKM_KCDSA_KEY_PAIR_GEN, x, CKM_KCDSA_KEY_PAIR_GEN_PRIVTEMP) for x in KCDSA_P_TEMPS]) DERIVE_PARAMS = {CKM_SHA224_KEY_DERIVATION: "SHA224", CKM_SHA256_KEY_DERIVATION: "SHA256", @@ -76,7 +77,6 @@ def pair_params(key_gen): class TestKeys(object): - def verify_ret(self, ret, expected_ret): """ Verify ret check and len > 0""" assert ret == expected_ret, "Function should return: " + ret_vals_dictionary[expected_ret] \ @@ -113,8 +113,8 @@ def test_generate_key_pair(self, key_type, pub_key_temp, prv_key_temp): :param prv_key_temp: private key template """ ret, pub_key, prv_key = c_generate_key_pair(self.h_session, key_type, - pub_key_temp, - prv_key_temp) + pub_key_temp, + prv_key_temp) self.verify_ret(ret, CKR_OK) self.verify_key_len(pub_key, prv_key) @@ -154,9 +154,8 @@ def test_derive_key(self, key_type, d_type): del derived_key_template[CKA_VALUE_LEN] ret, h_derived_key = c_derive_key(self.h_session, h_base_key, - key_template, - mech_flavor=d_type, - mech=mech) + key_template, + mechanism=mech) try: self.verify_ret(ret, CKR_OK) verify_object_attributes(self.h_session, h_derived_key, key_template) @@ -183,9 +182,8 @@ def test_too_long_length_derives(self, key_type, d_type): del derived_key_template[CKA_VALUE_LEN] ret, h_derived_key = c_derive_key(self.h_session, h_base_key, - key_template, - mech_flavor=d_type, - mech=mech) + key_template, + mechanism=mech) try: self.verify_ret(ret, CKR_KEY_SIZE_RANGE) finally: @@ -209,10 +207,10 @@ def test_long_length_derive_key(self, key_type, d_type): derived_key_template = key_template.copy() del derived_key_template[CKA_VALUE_LEN] - ret, h_derived_key = c_derive_key(self.h_session, h_base_key, - key_template, - mech_flavor=d_type, - mech=mech) + ret, h_derived_key = c_derive_key(self.h_session, + h_base_key, + key_template, + mechanism=mech) try: self.verify_ret(ret, CKR_OK) verify_object_attributes(self.h_session, h_derived_key, key_template) diff --git a/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py index 9fcd761..9be2c66 100755 --- a/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -129,10 +129,10 @@ def test_sym_sign_verify(self, key_type, sign_flavor, data, sym_keys): pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[key_type][0])) h_key = sym_keys[key_type] - ret, signature = c_sign(self.h_session, sign_flavor, data, h_key) + ret, signature = c_sign(self.h_session, h_key, data, mechanism=sign_flavor) self.verify_ret(ret, CKR_OK) - ret = c_verify(self.h_session, h_key, sign_flavor, data, signature) + ret = c_verify(self.h_session, h_key, data, signature, mechanism=sign_flavor) self.verify_ret(ret, CKR_OK) @pytest.mark.parametrize("data", DATA, ids=['String', "Block"]) @@ -150,8 +150,8 @@ def test_asym_sign_verify(self, k_type, sig_mech, data, asym_keys): pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[k_type][0])) pub_key, prv_key = asym_keys[k_type] - ret, signature = c_sign(self.h_session, sig_mech, data, prv_key) + ret, signature = c_sign(self.h_session, prv_key, data, mechanism=sig_mech) self.verify_ret(ret, CKR_OK) - ret = c_verify(self.h_session, pub_key, sig_mech, data, signature) + ret = c_verify(self.h_session, pub_key, data, signature, mechanism=sig_mech) self.verify_ret(ret, CKR_OK) diff --git a/tests/functional/test_usage_limit_and_count.py b/tests/functional/test_usage_limit_and_count.py index aa0341e..a728c02 100755 --- a/tests/functional/test_usage_limit_and_count.py +++ b/tests/functional/test_usage_limit_and_count.py @@ -8,7 +8,6 @@ import pytest -from . import config as hsm_config from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ @@ -17,6 +16,7 @@ from pycryptoki.encryption import c_encrypt, c_encrypt_ex from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex from pycryptoki.object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex +from . import config as hsm_config LOG = logging.getLogger(__name__) @@ -45,7 +45,8 @@ def test_set_attribute_usage_limit_sym(self): usage_template = {CKA_USAGE_LIMIT: 5} - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, + h_key = c_generate_key_ex(self.h_session, + mechanism=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) LOG.info("Called c-generate: Key handle -%s", h_key) usage_limit = 5 @@ -77,16 +78,18 @@ def test_usage_limit_attribute_check_sym_des(self): usage_count = 2 - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES_KEY_GEN, + h_key = c_generate_key_ex(self.h_session, + mechanism=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) LOG.info("Called c-generate: Key handle -%s", h_key) c_set_attribute_value_ex(self.h_session, h_key, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, b'a' * 2048) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES_ECB}) - c_encrypt_ex(self.h_session, CKM_DES_ECB, h_key, b'a' * 2048) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, + mechanism={"mech_type": CKM_DES_ECB}) py_template = c_get_attribute_value_ex(self.h_session, h_key, template={CKA_USAGE_COUNT: None}) @@ -113,15 +116,15 @@ def test_usage_limit_attribute_check_sym_aes(self): usage_count = 2 - h_key = c_generate_key_ex(self.h_session, flavor=CKM_AES_KEY_GEN, + h_key = c_generate_key_ex(self.h_session, mechanism=CKM_AES_KEY_GEN, template=CKM_AES_KEY_GEN_TEMP) LOG.info("Called c-generate: Key handle -" + str(h_key)) c_set_attribute_value_ex(self.h_session, h_key, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, b'a' * 2048) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) - c_encrypt_ex(self.h_session, CKM_AES_ECB, h_key, b'a' * 2048) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) py_template = c_get_attribute_value_ex(self.h_session, h_key, template={CKA_USAGE_COUNT: None}) @@ -146,10 +149,10 @@ def test_set_attribute_usage_limit_Assym(self): an assymetric crypto object") usage_lim_template = {CKA_USAGE_LIMIT: 2} - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, + mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) LOG.info( "Called c-generate: Public Key handle: %s Private Key Handle: %s", h_pbkey, h_prkey) usage_limit = 2 @@ -181,19 +184,19 @@ def test_usage_limit_attribute_check_Assym(self): usage_lim_template = {CKA_USAGE_LIMIT: 2} usage_count = 2 - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, + mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) LOG.info( "Called c-generate: Public Key handle -%s Private Key Handle -%s", h_pbkey, h_prkey) c_set_attribute_value_ex(self.h_session, h_pbkey, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_COUNT: None}) @@ -217,18 +220,20 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") usage_lim_template = {CKA_USAGE_LIMIT: 2} - h_key = c_generate_key_ex(self.h_session, flavor=CKM_DES3_KEY_GEN, + h_key = c_generate_key_ex(self.h_session, + mechanism=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) LOG.info("Called c-generate: Key handle -" + str(h_key)) c_set_attribute_value_ex(self.h_session, h_key, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) - c_encrypt_ex(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) - return_val, data = c_encrypt(self.h_session, CKM_DES3_ECB, h_key, b'a' * 2048) + return_val, data = c_encrypt(self.h_session, h_key, b'a' * 2048, + mechanism={"mech_type": CKM_DES3_ECB}) LOG.info("Called C_Encrypt, return code: %s", return_val) py_template = c_get_attribute_value_ex(self.h_session, h_key, @@ -252,10 +257,10 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): usage_lim_template = {CKA_USAGE_LIMIT: 2} - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, flavor=CKM_RSA_PKCS_KEY_PAIR_GEN, + h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, + mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, - mech=None) + prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) LOG.info( "Called c-generate: Public Key handle -%s Private Key Handle - %s", h_pbkey, h_prkey) @@ -263,11 +268,12 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): c_set_attribute_value_ex(self.h_session, h_pbkey, usage_lim_template) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - c_encrypt_ex(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - return_val, data = c_encrypt(self.h_session, CKM_RSA_PKCS, h_pbkey, b'a' * 20) + return_val, data = c_encrypt(self.h_session, h_pbkey, b'a' * 20, + mechanism={"mech_type": CKM_RSA_PKCS}) LOG.info("Called C_Encrypt, return code: %s", return_val) py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, template={CKA_USAGE_COUNT: None}) diff --git a/tests/functional/test_wrap_unwrap.py b/tests/functional/test_wrap_unwrap.py index f1e8719..da04d53 100755 --- a/tests/functional/test_wrap_unwrap.py +++ b/tests/functional/test_wrap_unwrap.py @@ -1,8 +1,9 @@ import logging + import pytest -from pycryptoki.default_templates import get_default_key_template from pycryptoki.default_templates import MECHANISM_LOOKUP_EXT as LOOKUP +from pycryptoki.default_templates import get_default_key_template from pycryptoki.defines import (CKM_DES_ECB, CKM_DES_CBC, CKM_DES_CBC_PAD, CKM_DES_KEY_GEN, CKM_DES3_ECB, CKM_DES3_CBC, CKM_DES3_CBC_PAD, CKM_DES3_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, CKM_AES_KEY_GEN, @@ -12,8 +13,6 @@ CKR_OK, CKA_DECRYPT, CKA_VERIFY, CKA_UNWRAP, CKA_VALUE_LEN, CKA_EXTRACTABLE) - - from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt from pycryptoki.key_generator import c_destroy_object, c_generate_key from pycryptoki.return_values import ret_vals_dictionary @@ -102,7 +101,6 @@ def keys(auth_session): class TestWrappingKeys(object): - def verify_ret(self, ret, expected_ret): """ Assert that ret is as expected @@ -128,11 +126,12 @@ def generate_unwrap_temp(self, key_gen): unwrap_temp.pop(CKA_UNWRAP, None) unwrap_temp.pop(CKA_EXTRACTABLE, None) if key_gen not in VALUE_LEN: - unwrap_temp.pop(CKA_VALUE_LEN, None) + unwrap_temp.pop(CKA_VALUE_LEN, None) return unwrap_temp - @pytest.mark.parametrize(('mech', 'k_type'), PARAM_LIST, ids=[LOOKUP[m][0] for m, _ in PARAM_LIST]) + @pytest.mark.parametrize(('mech', 'k_type'), PARAM_LIST, + ids=[LOOKUP[m][0] for m, _ in PARAM_LIST]) def test_wrap_unwrap_key(self, mech, k_type, keys): """ Test key wrapping @@ -148,24 +147,28 @@ def test_wrap_unwrap_key(self, mech, k_type, keys): pytest.fail("No valid key found for {}".format(LOOKUP[mech][0])) # Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mech, extra_params=extra_p) + wrap_mech = {"mech_type": mech, + "params": extra_p} + ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mechanism=wrap_mech) self.verify_ret(ret, CKR_OK) # Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrap_key, - wrapped_key, - unwrap_temp, - mech, - extra_params=extra_p) + ret, h_unwrapped_key = c_unwrap_key(self.h_session, + h_wrap_key, + wrapped_key, + unwrap_temp, + mechanism=wrap_mech) self.verify_ret(ret, CKR_OK) # Verify all of the attributes against the originally generated attributes verify_object_attributes(self.h_session, h_unwrapped_key, temp) - @pytest.mark.parametrize(('mech', 'k_type'), PARAM_LIST, ids=[LOOKUP[m][0] for m, _ in PARAM_LIST]) + @pytest.mark.parametrize(('mech', 'k_type'), PARAM_LIST, + ids=[LOOKUP[m][0] for m, _ in PARAM_LIST]) def test_encrypt_wrap_unwrap_decrypt_key(self, mech, k_type, keys): """ Test that encrypt/decrypt works with wrapped keys + :param mech: encryption mech :param k_type: key gen mech :param keys: keys fixture @@ -178,23 +181,28 @@ def test_encrypt_wrap_unwrap_decrypt_key(self, mech, k_type, keys): # Encrypt some data data_to_encrypt = b"a" * 512 - ret, encrypted_data = c_encrypt(self.h_session, mech, h_key, data_to_encrypt) + enc_mech = {"mech_type": mech} + ret, encrypted_data = c_encrypt(self.h_session, h_key, data_to_encrypt, mechanism=enc_mech) self.verify_ret(ret, CKR_OK) # Wrap the key - ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mech, extra_params=extra_p) + wrap_mech = {"mech_type": mech, + "params": extra_p} + ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mechanism=wrap_mech) self.verify_ret(ret, CKR_OK) # Unwrap the Key ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrap_key, - wrapped_key, - unwrap_temp, - mech, - extra_params=extra_p) + wrapped_key, + unwrap_temp, + mechanism=wrap_mech) self.verify_ret(ret, CKR_OK) # Decrypt the data - ret, decrypted_string = c_decrypt(self.h_session, mech, h_unwrapped_key, encrypted_data) + ret, decrypted_string = c_decrypt(self.h_session, + h_unwrapped_key, + encrypted_data, + mechanism=enc_mech) self.verify_ret(ret, CKR_OK) assert decrypted_string == data_to_encrypt, \ diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..5c1767f --- /dev/null +++ b/tox.ini @@ -0,0 +1,14 @@ +[tox] +envlist=py27,py35,pypy +[testenv] +deps=pytest + six + rpyc + hypothesis + mock + pytz + future +commands=py.test \ + tests/unittests \ + --junitxml=junit-{envname}.xml \ + --showlocals From 1173e7be4b6e32da53a40d9f6894df18fe1290a6 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 19 Sep 2016 10:19:29 -0400 Subject: [PATCH 074/109] LA-1696 Allow for empty-strings in bytearrays Allows for only-space strings in byte arrays as well as zero-length strings. Change-Id: I24d6ea54f394845aac016822787c05ba02946cb1 --- pycryptoki/attributes.py | 9 ++++++++- requirements.txt | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 2433489..2cf6e33 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -200,7 +200,14 @@ def to_byte_array(val, reverse=False): if isinstance(val, string_types): # Hex-string in form '01e4' - val = int(val, 16) + try: + val = int(val, 16) + except ValueError: + # To allow for pre-allocation of data with ' ' * 64 + if val.isspace() or len(val) == 0: + val = b(val) + else: + raise if isinstance(val, collections.Iterable): py_bytes = bytearray(val) byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) diff --git a/requirements.txt b/requirements.txt index 76f22f3..4c4084e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,4 @@ hypothesis pytest future mock +six From ca23453ddce858b6dc762973aea9b11a18d2f152 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 19 Sep 2016 14:55:24 -0400 Subject: [PATCH 075/109] LA-1696 Update setup.py requirements Updated version to 2.0, because it's a backwards-compatibility breaking change Fixed requirements in setup.py Change-Id: I8f39c36a6c50acc1e65f9e2ad035be9791574287 --- setup.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 38af492..fce461d 100755 --- a/setup.py +++ b/setup.py @@ -12,11 +12,10 @@ description="A python wrapper around the C cryptoki library.", author='Ashley Straw', url='https://github.com/gemalto/pycryptoki', - version='1.0', + version='2.0', packages=['pycryptoki', 'pycryptoki.daemon'], scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'], - setup_requires=['pytest-runner'], tests_require=['pytest', 'hypothesis', 'mock', 'pytz'], - requires=['future', 'rpyc', 'six'] + install_requires=['future', 'rpyc', 'six'] ) From fa3fd1ec8f3b0c2b50439f67f160647985297765 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 20 Sep 2016 13:57:11 -0400 Subject: [PATCH 076/109] LA-1696 Fix derivation mechanisms Added a couple missing derivation mechanisms Default use regular Mechanism.__new__ to determine what mech class to use (if one isn't configured, use NullMech as usual) default IVs/IV16s work for CKM_AES_CBC and the like Change-Id: I390dfc39a2794c30b074a39f0c620f2dd9da9f75 --- pycryptoki/mechanism.py | 54 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 96f4c1b..f0a3b9b 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -14,7 +14,7 @@ CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_RC2_CBC_PARAMS, \ CK_RC5_PARAMS, CK_RC5_CBC_PARAMS, CK_MECHANISM_TYPE, CK_AES_XTS_PARAMS, \ CK_RSA_PKCS_OAEP_PARAMS, \ - CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS + CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS, CK_KEY_DERIVATION_STRING_DATA, c_ubyte from .defines import * from .test_functions import LunaException @@ -322,6 +322,51 @@ def to_c_mech(self): return self.mech +class ConcatenationDeriveMechanism(Mechanism): + """ + Mechanism class for key derivations. This will take in a second key handle in the parameters, + and use it in the resulting Structure. + + .. warning :: This mechanism is disabled in later versions of PCKS11. + + """ + REQUIRED_PARAMS = ['h_second_key'] + + def to_c_mech(self): + """ + Add in a pointer to the second key in the resulting mech structure. + + :return: Mechanism Structure + """ + super(ConcatenationDeriveMechanism, self).to_c_mech() + c_second_key = CK_ULONG(self.params['h_second_key']) + self.mech.pParameter = cast(pointer(c_second_key), c_void_p) + self.mech.usParameterLen = sizeof(c_second_key) + return self.mech + + +class StringDataDerivationMechanism(Mechanism): + """ + Mechanism class for key derivation using passed in string data. + """ + REQUIRED_PARAMS = ['data'] + + def to_c_mech(self): + """ + Convert data to bytearray, then use in the resulting mech structure. + + :return: Mechanism Structure + """ + super(ConcatenationDeriveMechanism, self).to_c_mech() + parameters = CK_KEY_DERIVATION_STRING_DATA + data, length = to_byte_array(self.params['data']) + parameters.pData = cast(data, POINTER(c_ubyte)) + parameters.ulLen = length + self.mech.pParameter = parameters + self.mech.usParameterLen = sizeof(parameters) + return self.mech + + # TODO: xordf mech class NullMech(Mechanism): @@ -438,6 +483,11 @@ def to_c_mech(self): CKM_SHA512_RSA_PKCS_PSS: RSAPKCSPSSMechanism, CKM_DES_ECB: NullMech, + + CKM_CONCATENATE_BASE_AND_KEY: ConcatenationDeriveMechanism, + CKM_CONCATENATE_BASE_AND_DATA: StringDataDerivationMechanism, + CKM_XOR_BASE_AND_DATA: StringDataDerivationMechanism, + CKM_CONCATENATE_DATA_AND_BASE: StringDataDerivationMechanism, } @@ -564,7 +614,7 @@ def parse_mechanism(mechanism_param): elif isinstance(mechanism_param, CK_MECHANISM): mech = mechanism_param elif isinstance(mechanism_param, integer_types): - mech = NullMech(mech_type=mechanism_param).to_c_mech() + mech = Mechanism(mech_type=mechanism_param).to_c_mech() elif isinstance(mechanism_param, Mechanism): mech = mechanism_param.to_c_mech() else: From b02ef9ae34a3bf9c095dc7e39f4e863d08a31c82 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 16 Dec 2016 10:29:04 -0500 Subject: [PATCH 077/109] LA-2195 Fixed Library loading for 32 bit windows Use CDLL to load 32 bit windows libraries, instead of WinDLL Use configparser to read in crystoki.ini instead of regexes. Change-Id: I469f8e777152f409a8d38158b4a4b2ab60c12d5c --- docs/conf.py | 4 +- pycryptoki/cryptoki_helpers.py | 69 ++++++++++++---------------------- setup.py | 2 +- 3 files changed, 27 insertions(+), 48 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 31ae513..a5e716c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -59,9 +59,9 @@ # built documents. # # The short X.Y version. -version = '1.0' +version = '2.0' # The full version, including alpha/beta/rc tags. -release = '1.0' +release = '2.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index 3a880e0..a127475 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -5,12 +5,17 @@ import os import re import sys +import struct from ctypes import CDLL +from six.moves import configparser + from .defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE LOG = logging.getLogger(__name__) +IS_64B = 8 * struct.calcsize("P") == 64 + def parse_chrystoki_conf(): """Parse the crystoki.ini/Chrystoki.conf file to find the library .so/.dll file so that @@ -44,48 +49,37 @@ def parse_chrystoki_conf(): LOG.info("Searching %s for Chrystoki DLL path...", conf_path) - chrystoki_conf_text = _get_chrystoki_conf_file_text(conf_path) - - dll_path = _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text) + dll_path = _search_for_dll_in_chrystoki_conf(conf_path) LOG.info("Using DLL at location: %s", dll_path) return dll_path -def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): +def _search_for_dll_in_chrystoki_conf(conf_path): """Parses the chrystoki configuration file for the section that specifies the location of the DLL and returns the DLL location. - :param conf_path: The path to the configuration file - :param chrystoki_conf_text: The output of the read in chrystoki configuration file + :param str conf_path: The path to the configuration file :returns: The path to the chrystoki DLL - + :rtype: str """ if 'win' in sys.platform: - chrystoki2_segments = re.findall("\s*\[Chrystoki2\]\s*([^\r\n]*)", chrystoki_conf_text) - - if len(chrystoki2_segments) > 1: - raise Exception("Found %s Chrystoki2 sections in the config file: %s", - chrystoki2_segments, conf_path) - elif len(chrystoki2_segments) < 1: - raise Exception("Found no Chrystoki2 section in the config file: %s", conf_path) - - chrystoki2 = chrystoki2_segments[0].split('\n') - dll_path = "" - for line in chrystoki2: - lib_nt_line = re.findall("^\s*LibNT\s*=\s*([^\n]+)", line) - - if len(lib_nt_line) > 1: - raise Exception("Found more than one LibNT pattern on the same line") - elif len(lib_nt_line) == 1: - if dll_path != "": - raise Exception("Found more than one instance of LibNT in the file.") - dll_path = lib_nt_line[0].strip().strip(';').strip().strip("'").strip('"') + try: + config = configparser.ConfigParser() + config.read(conf_path) - if dll_path == "": - raise Exception("Error finding LibNT declaration in configuration file: %s", conf_path) + dll_path = config.get("Chrystoki2", "LibNT") + except ValueError: + LOG.exception("Failed to read DLL from crystoki.ini.") + raise ValueError("Failed to read DLL location crystoki.ini file!") + else: + if not os.path.isfile(dll_path): + raise ValueError("Cryptoki DLL does not exist at path {}! Check your " + "crystoki.ini file.".format(dll_path)) else: + with open(conf_path) as conf_file: + chrystoki_conf_text = conf_file.read() chrystoki2_segments = re.findall("\s*Chrystoki2\s*=\s*\{([^\}]*)", chrystoki_conf_text) if len(chrystoki2_segments) > 1: @@ -117,20 +111,6 @@ def _search_for_dll_in_chrystoki_conf(conf_path, chrystoki_conf_text): return dll_path -def _get_chrystoki_conf_file_text(conf_path): - """Reads in the chrystoki configuration and returns the text in the file - - :param conf_path: - """ - - try: - chrystoki_conf_file = open(conf_path, "r") - chrystoki_conf_text = chrystoki_conf_file.read() - except IOError: - raise Exception("Could not find/read Chrystoki configuration file at path %s", conf_path) - return chrystoki_conf_text - - class CryptokiDLLException(Exception): """Custom exception class used to print an error when a call to the Cryptoki DLL failed. The late binding makes debugging a little bit more difficult because function calls @@ -160,16 +140,15 @@ def __new__(cls, *args, **kwargs): dll_path = parse_chrystoki_conf() cls._instance.dll_path = dll_path - if 'win' in sys.platform: + if 'win' in sys.platform and IS_64B: import ctypes - cls._instance.loaded_dll_library = ctypes.WinDLL(dll_path) else: cls._instance.loaded_dll_library = CDLL(dll_path) return cls._instance def get_dll(self): - """ """ + """Get the loaded library (parsed from crystoki.ini/Chrystoki.conf)""" if self.loaded_dll_library is None or self.loaded_dll_library == "": raise Exception( "DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read " diff --git a/setup.py b/setup.py index fce461d..9ff27b5 100755 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ description="A python wrapper around the C cryptoki library.", author='Ashley Straw', url='https://github.com/gemalto/pycryptoki', - version='2.0', + version='2.0.1', packages=['pycryptoki', 'pycryptoki.daemon'], scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'], From 3e7d360a01999d0973d3c36371eb2b8ab886733e Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 8 Jun 2017 08:40:28 -0400 Subject: [PATCH 078/109] LA-2460 Migrate exception/parse changes to release Moved over the LunaException path changes from the master branch. Also moved over the conf parsing. Change-Id: I026bbf91213afd504943376d7fc319153b94645b --- pycryptoki/attributes.py | 3 +- pycryptoki/audit_handling.py | 2 +- pycryptoki/backup.py | 2 +- pycryptoki/cryptoki_helpers.py | 58 +++-- pycryptoki/encryption.py | 2 +- pycryptoki/exceptions.py | 139 ++++++++++++ pycryptoki/hsm_management.py | 2 +- pycryptoki/key_generator.py | 2 +- pycryptoki/key_management.py | 2 +- pycryptoki/key_usage.py | 2 +- pycryptoki/lookup_dicts.py | 268 +++++++++++++++++++++++ pycryptoki/luna_threading.py | 2 +- pycryptoki/mechanism.py | 2 +- pycryptoki/misc.py | 7 +- pycryptoki/object_attr_lookup.py | 2 +- pycryptoki/partition_management.py | 2 +- pycryptoki/return_values.py | 215 +----------------- pycryptoki/session_management.py | 2 +- pycryptoki/sign_verify.py | 2 +- pycryptoki/test_functions.py | 131 +---------- pycryptoki/token_management.py | 2 +- tests/unittests/test_attr_conversions.py | 3 +- tests/unittests/test_mechanisms.py | 3 +- 23 files changed, 475 insertions(+), 380 deletions(-) create mode 100644 pycryptoki/exceptions.py create mode 100644 pycryptoki/lookup_dicts.py diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 2cf6e33..9904d67 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -12,7 +12,7 @@ c_ulong, pointer, POINTER, sizeof, c_char, string_at, c_ubyte from functools import wraps -from six import b, string_types +from six import b, string_types, integer_types from .cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ CK_BYTE, CK_CHAR @@ -31,7 +31,6 @@ CKA_CCM_PRIVATE, CKA_FINGERPRINT_SHA1, CKA_FINGERPRINT_SHA256, CKA_OUID, CKA_UNWRAP_TEMPLATE, \ CKA_DERIVE_TEMPLATE, \ CKA_X9_31_GENERATED, CKA_VALUE -from .test_functions import integer_types LOG = logging.getLogger(__name__) diff --git a/pycryptoki/audit_handling.py b/pycryptoki/audit_handling.py index 70a8a17..a299896 100755 --- a/pycryptoki/audit_handling.py +++ b/pycryptoki/audit_handling.py @@ -5,7 +5,7 @@ from ctypes import cast, c_ulong, byref from .cryptoki import CK_ULONG, CA_TimeSync, CA_InitAudit, CK_SLOT_ID, CA_GetTime, CK_CHAR_PTR -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function logger = logging.getLogger(__name__) diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index 15e6b83..efb00c6 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -3,7 +3,7 @@ from .cryptoki import CA_OpenSecureToken, CA_CloseSecureToken, CA_Extract, CA_Insert, CK_ULONG from .mechanism import Mechanism -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function logger = logging.getLogger(__name__) diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index a127475..191568a 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -10,6 +10,7 @@ from six.moves import configparser +from .exceptions import LunaException from .defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE LOG = logging.getLogger(__name__) @@ -17,6 +18,13 @@ IS_64B = 8 * struct.calcsize("P") == 64 +class CryptokiConfigException(LunaException): + """ + Exception raised when we fail to determine the PKCS11 library location + """ + pass + + def parse_chrystoki_conf(): """Parse the crystoki.ini/Chrystoki.conf file to find the library .so/.dll file so that we can use it. @@ -27,11 +35,11 @@ def parse_chrystoki_conf(): if CHRYSTOKI_DLL_FILE is not None: # Use this value for the location of the DLL dll_path = CHRYSTOKI_DLL_FILE - LOG.info("Using DLL Path from defaults.py: %s", dll_path) + LOG.debug("Using DLL Path from defaults.py: %s", dll_path) return dll_path elif CHRYSTOKI_CONFIG_FILE is not None: conf_path = CHRYSTOKI_CONFIG_FILE - LOG.info("Using Chrystoki.conf location from defaults.py: %s", conf_path) + LOG.debug("Using Chrystoki.conf location from defaults.py: %s", conf_path) elif env_conf_path is not None: if 'win' in sys.platform: env_conf_path = env_conf_path.replace('\\\\', '~').replace('~', '\\') + 'crystoki.ini' @@ -39,15 +47,15 @@ def parse_chrystoki_conf(): env_conf_path = os.path.join(env_conf_path, 'Chrystoki.conf') conf_path = env_conf_path - LOG.info("Using Chrystoki.conf location from " - "environment variable ChrystokiConfigurationPath: %s", conf_path) + LOG.debug("Using Chrystoki.conf location from environment variable " + "ChrystokiConfigurationPath: %s", conf_path) if conf_path is None: conf_path = '/etc/Chrystoki.conf' - LOG.info("No DLL Path or Chyrstoki.conf path set in defaults.py, " - "looking up DLL path in %s", conf_path) + LOG.warning("No DLL Path or Chyrstoki.conf path set in defaults.py " + "looking up DLL path in %s", conf_path) - LOG.info("Searching %s for Chrystoki DLL path...", conf_path) + LOG.debug("Searching %s for Chrystoki DLL path...", conf_path) dll_path = _search_for_dll_in_chrystoki_conf(conf_path) @@ -72,21 +80,22 @@ def _search_for_dll_in_chrystoki_conf(conf_path): dll_path = config.get("Chrystoki2", "LibNT") except ValueError: LOG.exception("Failed to read DLL from crystoki.ini.") - raise ValueError("Failed to read DLL location crystoki.ini file!") + raise CryptokiConfigException("Failed to read DLL location crystoki.ini file!") else: if not os.path.isfile(dll_path): - raise ValueError("Cryptoki DLL does not exist at path {}! Check your " - "crystoki.ini file.".format(dll_path)) + raise CryptokiConfigException("Cryptoki DLL does not exist at path {}! Check your " + "crystoki.ini file.".format(dll_path)) else: with open(conf_path) as conf_file: chrystoki_conf_text = conf_file.read() chrystoki2_segments = re.findall("\s*Chrystoki2\s*=\s*\{([^\}]*)", chrystoki_conf_text) if len(chrystoki2_segments) > 1: - raise Exception("Found %s Chrystoki2 sections in the config file: %s", - chrystoki2_segments, conf_path) + raise CryptokiConfigException("Found %d Chrystoki2 sections in the config file: " + "%s" % (len(chrystoki2_segments), conf_path)) elif len(chrystoki2_segments) < 1: - raise Exception("Found no Chrystoki2 section in the config file: %s", conf_path) + raise CryptokiConfigException("Found no Chrystoki2 section in the config file:" + " %s" % conf_path) chrystoki2 = chrystoki2_segments[0].split('\n') dll_path = "" @@ -98,15 +107,17 @@ def _search_for_dll_in_chrystoki_conf(conf_path): lib_unix_line = re.findall("^\s*Lib(?:UNIX|HPUX)\s*=\s*([^\n]+)", line) if len(lib_unix_line) > 1: - raise Exception("Found more than one LibUNIX pattern on the same line") + raise CryptokiConfigException("Found more than one" + " LibUNIX pattern on the same line") elif len(lib_unix_line) == 1: if dll_path != "": - raise Exception("Found more than one instance of LibUNIX in the file.") + raise CryptokiConfigException("Found more than one instance of" + " LibUNIX in the file.") dll_path = lib_unix_line[0].strip().strip(';').strip().strip("'").strip('"') if dll_path == "": - raise Exception("Error finding LibUNIX declaration in configuration file: %s", - conf_path) + raise CryptokiConfigException("Error finding LibUNIX declaration in configuration file:" + " %s" % conf_path) return dll_path @@ -150,9 +161,11 @@ def __new__(cls, *args, **kwargs): def get_dll(self): """Get the loaded library (parsed from crystoki.ini/Chrystoki.conf)""" if self.loaded_dll_library is None or self.loaded_dll_library == "": - raise Exception( - "DLL path never found:\n1. Is the cryptoki client installed?\n2. Can python read " - "/etc/Chrystoki.conf?\n3. Is there a LibUNIX= field in /etc/Chrystoki.conf") + raise CryptokiConfigException( + "DLL path not found:\n" + "1. Is the Luna HSM Client installed?\n" + "2. Can python read the Luna HSM Client config file?\n" + "3. Is there a LibUNIX/LibNT field in the Luna HSM Client config file") return self.loaded_dll_library @@ -179,7 +192,8 @@ def luna_function(*args, **kwargs): return_value = late_binded_function(*args, **kwargs) return return_value except Exception as e: - raise CryptokiDLLException( - "Call to '%s(%s, %s)' failed." % (function_name, args, kwargs), e) + raise CryptokiDLLException("Call to '%s(%s, **%s)' failed.".format(function_name, + args, + kwargs), e) return luna_function diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 4cc47ac..c44b92d 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -17,7 +17,7 @@ from .defines import CKR_OK from .mechanism import parse_mechanism from .return_values import ret_vals_dictionary -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function LOG = logging.getLogger(__name__) diff --git a/pycryptoki/exceptions.py b/pycryptoki/exceptions.py new file mode 100644 index 0000000..a205436 --- /dev/null +++ b/pycryptoki/exceptions.py @@ -0,0 +1,139 @@ +""" +Exception-s and exception handling code. +""" +import inspect +from functools import wraps + +from six import integer_types + +from .defines import CKR_OK +from .lookup_dicts import ret_vals_dictionary + + +def make_error_handle_function(luna_function): + """This function is a helper function that creates a new function which checks the + result code returned from a function in luna. It is called by calling:: + + c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) + + This code will create a c_generate_key_pair_ex which will call c_generate_key_pair and check the + first argument. The first argument is the return code of c_generate_key_pair. If the return + code != CKR_OK then c_generate_key_pair_ex will raise a LunaCallException. You can call + c_generate_key_pair_ex as if it is c_generate_key_pair:: + + c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, + CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, + CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + + The return values of c_generate_pair are (ret, public_key_handle, private_key_handle) + + The return values of c_generate_pair_ex are (public_key_handle, private_key_handle) + + This lets you create two versions of a function. One version is for setup and + the other version is for testing the result. + + Directly testing the result:: + + ret = c_initialize() + assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" + + Expecting the call to go through without error. The test case should have an error (not a + failure):: + + c_initialize_ex() + + This should therefore make for shorter test cases + + :param luna_function: + + """ + + @wraps(luna_function) + def luna_function_exception_handle(*args, **kwargs): + """ + + :param *args: + :param **kwargs: + + """ + return_tuple = luna_function(*args, **kwargs) + if isinstance(return_tuple, tuple): + if len(return_tuple) > 2: + return_data = return_tuple[1:] + ret = return_tuple[0] + elif len(return_tuple) == 2: + return_data = return_tuple[1] + ret = return_tuple[0] + else: + return_data = return_tuple[0] + ret = return_tuple[0] + elif isinstance(return_tuple, integer_types): + ret = return_tuple + return_data = return_tuple + else: + raise Exception( + "Functions wrapped by the exception handler should return a tuple or just the " + "long representing Luna's return code.") + + check_luna_exception(ret, luna_function, args) + return return_data + + return luna_function_exception_handle + + +def check_luna_exception(ret, luna_function, args): + """ + Check the return code from cryptoki.dll, and if it's non-zero raise an + exception with the error code looked up. + + :param ret: Return code from the C call + :param luna_function: pycryptoki function that was called + :param args: Arguments passed to the pycryptoki function. + """ + arg_spec = inspect.getargspec(luna_function).args + nice_args = [x if len(str(x)) < 20 else "{}...{}".format(str(x)[:10], str(x)[-10:]) + for x in args] + arg_string = ", ".join("{}={}".format(key, value) for key, value in zip(arg_spec, nice_args)) + + arg_string = "({})".format(arg_string) + if ret != CKR_OK: + raise LunaCallException(ret, luna_function.__name__, arg_string) + + +class LunaException(Exception): + """ + Base exception class for every custom exception raised by pycryptoki. + """ + pass + + +class LunaCallException(LunaException): + """Exceptions raised from the result of a PKCS11 call that returned a non-zero + return code. This will attempt to look up the error code defines for human-readable output. + """ + + def __init__(self, error_code, function_name, arguments): + """ + :param error_code: The error code of the error + :param function_name: The name of the function + :param arguments: The arguments passed into the function + """ + self.error_code = error_code + self.function_name = function_name + self.arguments = arguments + + if self.error_code in ret_vals_dictionary: + self.error_string = ret_vals_dictionary[self.error_code] + else: + self.error_string = "Unknown Code=" + str(hex(self.error_code)) + + def __str__(self): + data = ("\n\tFunction: {func_name}" + "\n\tError: {err_string}" + "\n\tError Code: {err_code}" + "\n\tArguments: {args}").format(func_name=self.function_name, + err_string=self.error_string, + err_code=hex(self.error_code), + args=self.arguments) + + return data diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 07260f7..05366db 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -24,7 +24,7 @@ CA_SetDestructiveHSMPolicy, CA_SetDestructiveHSMPolicies, CA_GetHSMCapabilitySet, CA_GetHSMCapabilitySetting, CA_GetHSMPolicySet, CA_GetHSMPolicySetting) -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function def c_performselftest(slot, diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 5e8d85e..1c2f9a1 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -12,7 +12,7 @@ get_default_key_pair_template from .defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN from .mechanism import parse_mechanism -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function def c_destroy_object(h_session, h_object_value): diff --git a/pycryptoki/key_management.py b/pycryptoki/key_management.py index 4d03436..5d5c6d9 100755 --- a/pycryptoki/key_management.py +++ b/pycryptoki/key_management.py @@ -3,7 +3,7 @@ """ from .cryptoki import CA_GenerateMofN, CA_ModifyUsageCount, \ CK_VOID_PTR, CK_ULONG, CA_MOFN_GENERATION, CK_BYTE, CA_MOFN_GENERATION_PTR -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function def ca_generatemofn(h_session, diff --git a/pycryptoki/key_usage.py b/pycryptoki/key_usage.py index bcea80e..a757df7 100755 --- a/pycryptoki/key_usage.py +++ b/pycryptoki/key_usage.py @@ -3,7 +3,7 @@ """ from .cryptoki import CA_CloneMofN, CA_DuplicateMofN, \ CK_VOID_PTR, CK_SESSION_HANDLE -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function def ca_clonemofn(h_session): diff --git a/pycryptoki/lookup_dicts.py b/pycryptoki/lookup_dicts.py new file mode 100644 index 0000000..300f4d2 --- /dev/null +++ b/pycryptoki/lookup_dicts.py @@ -0,0 +1,268 @@ +""" +Module that contains lookup dictionaries for easy logging of +error codes and other constants within pycryptoki. +""" + +from .defines import * + +ret_vals_dictionary = { + CKR_OK: 'CKR_OK', + CKR_CANCEL: 'CKR_CANCEL', + CKR_HOST_MEMORY: 'CKR_HOST_MEMORY', + CKR_SLOT_ID_INVALID: 'CKR_SLOT_ID_INVALID', + CKR_GENERAL_ERROR: 'CKR_GENERAL_ERROR', + CKR_FUNCTION_FAILED: 'CKR_FUNCTION_FAILED', + CKR_ARGUMENTS_BAD: 'CKR_ARGUMENTS_BAD', + CKR_NO_EVENT: 'CKR_NO_EVENT', + CKR_NEED_TO_CREATE_THREADS: 'CKR_NEED_TO_CREATE_THREADS', + CKR_CANT_LOCK: 'CKR_CANT_LOCK', + CKR_ATTRIBUTE_READ_ONLY: 'CKR_ATTRIBUTE_READ_ONLY', + CKR_ATTRIBUTE_SENSITIVE: 'CKR_ATTRIBUTE_SENSITIVE', + CKR_ATTRIBUTE_TYPE_INVALID: 'CKR_ATTRIBUTE_TYPE_INVALID', + CKR_ATTRIBUTE_VALUE_INVALID: 'CKR_ATTRIBUTE_VALUE_INVALID', + CKR_DATA_INVALID: 'CKR_DATA_INVALID', + CKR_DATA_LEN_RANGE: 'CKR_DATA_LEN_RANGE', + CKR_DEVICE_ERROR: 'CKR_DEVICE_ERROR', + CKR_DEVICE_MEMORY: 'CKR_DEVICE_MEMORY', + CKR_DEVICE_REMOVED: 'CKR_DEVICE_REMOVED', + CKR_ENCRYPTED_DATA_INVALID: 'CKR_ENCRYPTED_DATA_INVALID', + CKR_ENCRYPTED_DATA_LEN_RANGE: 'CKR_ENCRYPTED_DATA_LEN_RANGE', + CKR_FUNCTION_CANCELED: 'CKR_FUNCTION_CANCELED', + CKR_FUNCTION_NOT_PARALLEL: 'CKR_FUNCTION_NOT_PARALLEL', + CKR_FUNCTION_NOT_SUPPORTED: 'CKR_FUNCTION_NOT_SUPPORTED', + CKR_KEY_HANDLE_INVALID: 'CKR_KEY_HANDLE_INVALID', + CKR_KEY_SIZE_RANGE: 'CKR_KEY_SIZE_RANGE', + CKR_KEY_TYPE_INCONSISTENT: 'CKR_KEY_TYPE_INCONSISTENT', + CKR_KEY_NOT_NEEDED: 'CKR_KEY_NOT_NEEDED', + CKR_KEY_CHANGED: 'CKR_KEY_CHANGED', + CKR_KEY_NEEDED: 'CKR_KEY_NEEDED', + CKR_KEY_INDIGESTIBLE: 'CKR_KEY_INDIGESTIBLE', + CKR_KEY_FUNCTION_NOT_PERMITTED: 'CKR_KEY_FUNCTION_NOT_PERMITTED', + CKR_KEY_NOT_WRAPPABLE: 'CKR_KEY_NOT_WRAPPABLE', + CKR_KEY_UNEXTRACTABLE: 'CKR_KEY_UNEXTRACTABLE', + CKR_MECHANISM_INVALID: 'CKR_MECHANISM_INVALID', + CKR_MECHANISM_PARAM_INVALID: 'CKR_MECHANISM_PARAM_INVALID', + CKR_OBJECT_HANDLE_INVALID: 'CKR_OBJECT_HANDLE_INVALID', + CKR_OPERATION_ACTIVE: 'CKR_OPERATION_ACTIVE', + CKR_OPERATION_NOT_INITIALIZED: 'CKR_OPERATION_NOT_INITIALIZED', + CKR_PIN_INCORRECT: 'CKR_PIN_INCORRECT', + CKR_PIN_INVALID: 'CKR_PIN_INVALID', + CKR_PIN_LEN_RANGE: 'CKR_PIN_LEN_RANGE', + CKR_PIN_EXPIRED: 'CKR_PIN_EXPIRED', + CKR_PIN_LOCKED: 'CKR_PIN_LOCKED', + CKR_SESSION_CLOSED: 'CKR_SESSION_CLOSED', + CKR_SESSION_COUNT: 'CKR_SESSION_COUNT', + CKR_SESSION_HANDLE_INVALID: 'CKR_SESSION_HANDLE_INVALID', + CKR_SESSION_PARALLEL_NOT_SUPPORTED: 'CKR_SESSION_PARALLEL_NOT_SUPPORTED', + CKR_SESSION_READ_ONLY: 'CKR_SESSION_READ_ONLY', + CKR_SESSION_EXISTS: 'CKR_SESSION_EXISTS', + CKR_SESSION_READ_ONLY_EXISTS: 'CKR_SESSION_READ_ONLY_EXISTS', + CKR_SESSION_READ_WRITE_SO_EXISTS: 'CKR_SESSION_READ_WRITE_SO_EXISTS', + CKR_SIGNATURE_INVALID: 'CKR_SIGNATURE_INVALID', + CKR_SIGNATURE_LEN_RANGE: 'CKR_SIGNATURE_LEN_RANGE', + CKR_TEMPLATE_INCOMPLETE: 'CKR_TEMPLATE_INCOMPLETE', + CKR_TEMPLATE_INCONSISTENT: 'CKR_TEMPLATE_INCONSISTENT', + CKR_TOKEN_NOT_PRESENT: 'CKR_TOKEN_NOT_PRESENT', + CKR_TOKEN_NOT_RECOGNIZED: 'CKR_TOKEN_NOT_RECOGNIZED', + CKR_TOKEN_WRITE_PROTECTED: 'CKR_TOKEN_WRITE_PROTECTED', + CKR_UNWRAPPING_KEY_HANDLE_INVALID: 'CKR_UNWRAPPING_KEY_HANDLE_INVALID', + CKR_UNWRAPPING_KEY_SIZE_RANGE: 'CKR_UNWRAPPING_KEY_SIZE_RANGE', + CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: 'CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT', + CKR_USER_ALREADY_LOGGED_IN: 'CKR_USER_ALREADY_LOGGED_IN', + CKR_USER_NOT_LOGGED_IN: 'CKR_USER_NOT_LOGGED_IN', + CKR_USER_PIN_NOT_INITIALIZED: 'CKR_USER_PIN_NOT_INITIALIZED', + CKR_USER_TYPE_INVALID: 'CKR_USER_TYPE_INVALID', + CKR_USER_ANOTHER_ALREADY_LOGGED_IN: 'CKR_USER_ANOTHER_ALREADY_LOGGED_IN', + CKR_USER_TOO_MANY_TYPES: 'CKR_USER_TOO_MANY_TYPES', + CKR_WRAPPED_KEY_INVALID: 'CKR_WRAPPED_KEY_INVALID', + CKR_WRAPPED_KEY_LEN_RANGE: 'CKR_WRAPPED_KEY_LEN_RANGE', + CKR_WRAPPING_KEY_HANDLE_INVALID: 'CKR_WRAPPING_KEY_HANDLE_INVALID', + CKR_WRAPPING_KEY_SIZE_RANGE: 'CKR_WRAPPING_KEY_SIZE_RANGE', + CKR_WRAPPING_KEY_TYPE_INCONSISTENT: 'CKR_WRAPPING_KEY_TYPE_INCONSISTENT', + CKR_RANDOM_SEED_NOT_SUPPORTED: 'CKR_RANDOM_SEED_NOT_SUPPORTED', + CKR_RANDOM_NO_RNG: 'CKR_RANDOM_NO_RNG', + CKR_DOMAIN_PARAMS_INVALID: 'CKR_DOMAIN_PARAMS_INVALID', + CKR_BUFFER_TOO_SMALL: 'CKR_BUFFER_TOO_SMALL', + CKR_SAVED_STATE_INVALID: 'CKR_SAVED_STATE_INVALID', + CKR_INFORMATION_SENSITIVE: 'CKR_INFORMATION_SENSITIVE', + CKR_STATE_UNSAVEABLE: 'CKR_STATE_UNSAVEABLE', + CKR_CRYPTOKI_NOT_INITIALIZED: 'CKR_CRYPTOKI_NOT_INITIALIZED', + CKR_CRYPTOKI_ALREADY_INITIALIZED: 'CKR_CRYPTOKI_ALREADY_INITIALIZED', + CKR_MUTEX_BAD: 'CKR_MUTEX_BAD', + CKR_MUTEX_NOT_LOCKED: 'CKR_MUTEX_NOT_LOCKED', + CKR_NEW_PIN_MODE: 'CKR_NEW_PIN_MODE', + CKR_NEXT_OTP: 'CKR_NEXT_OTP', + CKR_FUNCTION_REJECTED: 'CKR_FUNCTION_REJECTED', + CKR_VENDOR_DEFINED: 'CKR_VENDOR_DEFINED', + CKR_INSERTION_CALLBACK_NOT_SUPPORTED: 'CKR_INSERTION_CALLBACK_NOT_SUPPORTED', + CKR_FUNCTION_PARALLEL: 'CKR_FUNCTION_PARALLEL', + CKR_SESSION_EXCLUSIVE_EXISTS: 'CKR_SESSION_EXCLUSIVE_EXISTS', + CKR_RC_ERROR: 'CKR_RC_ERROR', + CKR_CONTAINER_HANDLE_INVALID: 'CKR_CONTAINER_HANDLE_INVALID', + CKR_TOO_MANY_CONTAINERS: 'CKR_TOO_MANY_CONTAINERS', + CKR_USER_LOCKED_OUT: 'CKR_USER_LOCKED_OUT', + CKR_CLONING_PARAMETER_ALREADY_EXISTS: 'CKR_CLONING_PARAMETER_ALREADY_EXISTS', + CKR_CLONING_PARAMETER_MISSING: 'CKR_CLONING_PARAMETER_MISSING', + CKR_CERTIFICATE_DATA_MISSING: 'CKR_CERTIFICATE_DATA_MISSING', + CKR_CERTIFICATE_DATA_INVALID: 'CKR_CERTIFICATE_DATA_INVALID', + CKR_ACCEL_DEVICE_ERROR: 'CKR_ACCEL_DEVICE_ERROR', + CKR_WRAPPING_ERROR: 'CKR_WRAPPING_ERROR', + CKR_UNWRAPPING_ERROR: 'CKR_UNWRAPPING_ERROR', + CKR_MAC_MISSING: 'CKR_MAC_MISSING', + CKR_DAC_POLICY_PID_MISMATCH: 'CKR_DAC_POLICY_PID_MISMATCH', + CKR_DAC_MISSING: 'CKR_DAC_MISSING', + CKR_BAD_DAC: 'CKR_BAD_DAC', + CKR_SSK_MISSING: 'CKR_SSK_MISSING', + CKR_BAD_MAC: 'CKR_BAD_MAC', + CKR_DAK_MISSING: 'CKR_DAK_MISSING', + CKR_BAD_DAK: 'CKR_BAD_DAK', + CKR_SIM_AUTHORIZATION_FAILED: 'CKR_SIM_AUTHORIZATION_FAILED', + CKR_SIM_VERSION_UNSUPPORTED: 'CKR_SIM_VERSION_UNSUPPORTED', + CKR_SIM_CORRUPT_DATA: 'CKR_SIM_CORRUPT_DATA', + CKR_USER_NOT_AUTHORIZED: 'CKR_USER_NOT_AUTHORIZED', + CKR_MAX_OBJECT_COUNT_EXCEEDED: 'CKR_MAX_OBJECT_COUNT_EXCEEDED', + CKR_SO_LOGIN_FAILURE_THRESHOLD: 'CKR_SO_LOGIN_FAILURE_THRESHOLD', + CKR_SIM_AUTHFORM_INVALID: 'CKR_SIM_AUTHFORM_INVALID', + CKR_CITS_DAK_MISSING: 'CKR_CITS_DAK_MISSING', + CKR_UNABLE_TO_CONNECT: 'CKR_UNABLE_TO_CONNECT', + CKR_PARTITION_DISABLED: 'CKR_PARTITION_DISABLED', + CKR_CALLBACK_ERROR: 'CKR_CALLBACK_ERROR', + CKR_SECURITY_PARAMETER_MISSING: 'CKR_SECURITY_PARAMETER_MISSING', + CKR_SP_TIMEOUT: 'CKR_SP_TIMEOUT', + CKR_TIMEOUT: 'CKR_TIMEOUT', + CKR_ECC_UNKNOWN_CURVE: 'CKR_ECC_UNKNOWN_CURVE', + CKR_MTK_ZEROIZED: 'CKR_MTK_ZEROIZED', + CKR_MTK_STATE_INVALID: 'CKR_MTK_STATE_INVALID', + CKR_INVALID_ENTRY_TYPE: 'CKR_INVALID_ENTRY_TYPE', + CKR_MTK_SPLIT_INVALID: 'CKR_MTK_SPLIT_INVALID', + CKR_HSM_STORAGE_FULL: 'CKR_HSM_STORAGE_FULL', + CKR_DEVICE_TIMEOUT: 'CKR_DEVICE_TIMEOUT', + CKR_CONTAINER_OBJECT_STORAGE_FULL: 'CKR_CONTAINER_OBJECT_STORAGE_FULL', + CKR_PED_CLIENT_NOT_RUNNING: 'CKR_PED_CLIENT_NOT_RUNNING', + CKR_PED_UNPLUGGED: 'CKR_PED_UNPLUGGED', + CKR_ECC_POINT_INVALID: 'CKR_ECC_POINT_INVALID', + CKR_OPERATION_NOT_ALLOWED: 'CKR_OPERATION_NOT_ALLOWED', + CKR_LICENSE_CAPACITY_EXCEEDED: 'CKR_LICENSE_CAPACITY_EXCEEDED', + CKR_LOG_FILE_NOT_OPEN: 'CKR_LOG_FILE_NOT_OPEN', + CKR_LOG_FILE_WRITE_ERROR: 'CKR_LOG_FILE_WRITE_ERROR', + CKR_LOG_BAD_FILE_NAME: 'CKR_LOG_BAD_FILE_NAME', + CKR_LOG_FULL: 'CKR_LOG_FULL', + CKR_LOG_NO_KCV: 'CKR_LOG_NO_KCV', + CKR_LOG_BAD_RECORD_HMAC: 'CKR_LOG_BAD_RECORD_HMAC', + CKR_LOG_BAD_TIME: 'CKR_LOG_BAD_TIME', + CKR_LOG_AUDIT_NOT_INITIALIZED: 'CKR_LOG_AUDIT_NOT_INITIALIZED', + CKR_LOG_RESYNC_NEEDED: 'CKR_LOG_RESYNC_NEEDED', + CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS: 'CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', + CKR_AUDIT_LOGIN_FAILURE_THRESHOLD: 'CKR_AUDIT_LOGIN_FAILURE_THRESHOLD', + CKR_INVALID_FUF_TARGET: 'CKR_INVALID_FUF_TARGET', + CKR_INVALID_FUF_HEADER: 'CKR_INVALID_FUF_HEADER', + CKR_INVALID_FUF_VERSION: 'CKR_INVALID_FUF_VERSION', + CKR_ECC_ECC_RESULT_AT_INF: 'CKR_ECC_ECC_RESULT_AT_INF', + CKR_AGAIN: 'CKR_AGAIN', + CKR_TOKEN_COPIED: 'CKR_TOKEN_COPIED', + CKR_SLOT_NOT_EMPTY: 'CKR_SLOT_NOT_EMPTY', + CKR_USER_ALREADY_ACTIVATED: 'CKR_USER_ALREADY_ACTIVATED', + CKR_STC_NO_CONTEXT: 'CKR_STC_NO_CONTEXT', + CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED: 'CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED', + CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED: 'CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED', + CKR_STC_DH_KEYGEN_ERROR: 'CKR_STC_DH_KEYGEN_ERROR', + CKR_STC_CIPHER_SUITE_REJECTED: 'CKR_STC_CIPHER_SUITE_REJECTED', + CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP: 'CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP', + CKR_STC_COMPUTE_DH_KEY_ERROR: 'CKR_STC_COMPUTE_DH_KEY_ERROR', + CKR_STC_FIRST_PHASE_KDF_ERROR: 'CKR_STC_FIRST_PHASE_KDF_ERROR', + CKR_STC_SECOND_PHASE_KDF_ERROR: 'CKR_STC_SECOND_PHASE_KDF_ERROR', + CKR_STC_KEY_CONFIRMATION_FAILED: 'CKR_STC_KEY_CONFIRMATION_FAILED', + CKR_STC_NO_SESSION_KEY: 'CKR_STC_NO_SESSION_KEY', + CKR_STC_RESPONSE_BAD_MAC: 'CKR_STC_RESPONSE_BAD_MAC', + CKR_STC_NOT_ENABLED: 'CKR_STC_NOT_ENABLED', + CKR_STC_CLIENT_HANDLE_INVALID: 'CKR_STC_CLIENT_HANDLE_INVALID', + CKR_STC_SESSION_INVALID: 'CKR_STC_SESSION_INVALID', + CKR_STC_CONTAINER_INVALID: 'CKR_STC_CONTAINER_INVALID', + CKR_STC_SEQUENCE_NUM_INVALID: 'CKR_STC_SEQUENCE_NUM_INVALID', + CKR_STC_NO_CHANNEL: 'CKR_STC_NO_CHANNEL', + CKR_STC_RESPONSE_DECRYPT_ERROR: 'CKR_STC_RESPONSE_DECRYPT_ERROR', + CKR_STC_RESPONSE_REPLAYED: 'CKR_STC_RESPONSE_REPLAYED', + CKR_STC_REKEY_CHANNEL_MISMATCH: 'CKR_STC_REKEY_CHANNEL_MISMATCH', + CKR_STC_RSA_ENCRYPT_ERROR: 'CKR_STC_RSA_ENCRYPT_ERROR', + CKR_STC_RSA_SIGN_ERROR: 'CKR_STC_RSA_SIGN_ERROR', + CKR_STC_RSA_DECRYPT_ERROR: 'CKR_STC_RSA_DECRYPT_ERROR', + CKR_STC_RESPONSE_UNEXPECTED_KEY: 'CKR_STC_RESPONSE_UNEXPECTED_KEY', + CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE: 'CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE', + CKR_STC_UNEXPECTED_DH_DATA_SIZE: 'CKR_STC_UNEXPECTED_DH_DATA_SIZE', + CKR_STC_OPEN_CIPHER_MISMATCH: 'CKR_STC_OPEN_CIPHER_MISMATCH', + CKR_STC_OPEN_DHNIST_PUBKEY_ERROR: 'CKR_STC_OPEN_DHNIST_PUBKEY_ERROR', + CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL: 'CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL', + CKR_STC_OPEN_RESP_GEN_FAIL: 'CKR_STC_OPEN_RESP_GEN_FAIL', + CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL: 'CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL', + CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL: 'CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL', + CKR_STC_ACTIVATE_RESP_GEN_FAIL: 'CKR_STC_ACTIVATE_RESP_GEN_FAIL', + CKR_CHALLENGE_INCORRECT: 'CKR_CHALLENGE_INCORRECT', + CKR_ACCESS_ID_INVALID: 'CKR_ACCESS_ID_INVALID', + CKR_ACCESS_ID_ALREADY_EXISTS: 'CKR_ACCESS_ID_ALREADY_EXISTS', + CKR_OBJECT_READ_ONLY: 'CKR_OBJECT_READ_ONLY', + CKR_OBJECT_ALREADY_EXISTS: 'CKR_OBJECT_ALREADY_EXISTS', + CKR_KEY_NOT_ACTIVE: 'CKR_KEY_NOT_ACTIVE', + CKR_KEK_RETRY_FAILURE: 'CKR_KEK_RETRY_FAILURE', + CKR_RNG_RESEED_TOO_EARLY: 'CKR_RNG_RESEED_TOO_EARLY' +} + +ATTR_NAME_LOOKUP = { + CKA_CLASS: 'CKA_CLASS', + CKA_CERTIFICATE_TYPE: 'CKA_CERTIFICATE_TYPE', + CKA_KEY_TYPE: 'CKA_KEY_TYPE', + CKA_VALUE_LEN: 'CKA_VALUE_LEN', + CKA_MODULUS_BITS: 'CKA_MODULUS_BITS', + CKA_PRIME_BITS: 'CKA_PRIME_BITS', + CKA_SUBPRIME_BITS: 'CKA_SUBPRIME_BITS', + CKA_VALUE_BITS: 'CKA_VALUE_BITS', + CKA_TOKEN: 'CKA_TOKEN', + CKA_PRIVATE: 'CKA_PRIVATE', + CKA_SENSITIVE: 'CKA_SENSITIVE', + CKA_ENCRYPT: 'CKA_ENCRYPT', + CKA_DECRYPT: 'CKA_DECRYPT', + CKA_WRAP: 'CKA_WRAP', + CKA_UNWRAP: 'CKA_UNWRAP', + CKA_SIGN: 'CKA_SIGN', + CKA_SIGN_RECOVER: 'CKA_SIGN_RECOVER', + CKA_VERIFY: 'CKA_VERIFY', + CKA_VERIFY_RECOVER: 'CKA_VERIFY_RECOVER', + CKA_DERIVE: 'CKA_DERIVE', + CKA_CCM_PRIVATE: 'CKA_CCM_PRIVATE', + CKA_LOCAL: 'CKA_LOCAL', + CKA_MODIFIABLE: 'CKA_MODIFIABLE', + CKA_EXTRACTABLE: 'CKA_EXTRACTABLE', + CKA_ALWAYS_SENSITIVE: 'CKA_ALWAYS_SENSITIVE', + CKA_NEVER_EXTRACTABLE: 'CKA_NEVER_EXTRACTABLE', + CKA_X9_31_GENERATED: 'CKA_X9_31_GENERATED', + CKA_LABEL: 'CKA_LABEL', + CKA_APPLICATION: 'CKA_APPLICATION', + CKA_ISSUER: 'CKA_ISSUER', + CKA_SUBJECT: 'CKA_SUBJECT', + CKA_ID: 'CKA_ID', + CKA_EKM_UID: 'CKA_EKM_UID', + CKA_GENERIC_1: 'CKA_GENERIC_1', + CKA_GENERIC_2: 'CKA_GENERIC_2', + CKA_GENERIC_3: 'CKA_GENERIC_3', + CKA_START_DATE: 'CKA_START_DATE', + CKA_END_DATE: 'CKA_END_DATE', + CKA_VALUE: 'CKA_VALUE', + CKA_SERIAL_NUMBER: 'CKA_SERIAL_NUMBER', + CKA_MODULUS: 'CKA_MODULUS', + CKA_PUBLIC_EXPONENT: 'CKA_PUBLIC_EXPONENT', + CKA_PRIVATE_EXPONENT: 'CKA_PRIVATE_EXPONENT', + CKA_PRIME_1: 'CKA_PRIME_1', + CKA_PRIME_2: 'CKA_PRIME_2', + CKA_EXPONENT_1: 'CKA_EXPONENT_1', + CKA_EXPONENT_2: 'CKA_EXPONENT_2', + CKA_COEFFICIENT: 'CKA_COEFFICIENT', + CKA_PRIME: 'CKA_PRIME', + CKA_SUBPRIME: 'CKA_SUBPRIME', + CKA_BASE: 'CKA_BASE', + CKA_FINGERPRINT_SHA1: 'CKA_FINGERPRINT_SHA1', + CKA_FINGERPRINT_SHA256: 'CKA_FINGERPRINT_SHA256', + CKA_USAGE_COUNT: 'CKA_USAGE_COUNT', + CKA_USAGE_LIMIT: 'CKA_USAGE_LIMIT', + CKA_OUID: 'CKA_OUID', + CKA_UNWRAP_TEMPLATE: 'CKA_UNWRAP_TEMPLATE', + CKA_DERIVE_TEMPLATE: 'CKA_DERIVE_TEMPLATE', +} diff --git a/pycryptoki/luna_threading.py b/pycryptoki/luna_threading.py index cdeddd8..06ed952 100755 --- a/pycryptoki/luna_threading.py +++ b/pycryptoki/luna_threading.py @@ -12,7 +12,7 @@ from .return_values import ret_vals_dictionary from .session_management import c_open_session_ex, c_get_token_info_ex, \ c_open_session, c_close_session -from .test_functions import verify_object_attributes +from .exceptions import verify_object_attributes from .token_management import get_token_by_label_ex, \ c_get_mechanism_list_ex, c_get_mechanism_info_ex diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index f0a3b9b..5bb3d65 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -16,7 +16,7 @@ CK_RSA_PKCS_OAEP_PARAMS, \ CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS, CK_KEY_DERIVATION_STRING_DATA, c_ubyte from .defines import * -from .test_functions import LunaException +from .exceptions import LunaException LOG = logging.getLogger(__name__) diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index ee27243..7830070 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -12,16 +12,17 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte +from six import integer_types + from .attributes import Attributes, to_char_array from .common_utils import refresh_c_arrays, AutoCArray from .cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey from .defines import CKR_OK -from .mechanism import Mechanism -from .mechanism import NullMech +from .mechanism import Mechanism, NullMech from .sign_verify import do_multipart_sign_or_digest -from .test_functions import make_error_handle_function, integer_types +from .exceptions import make_error_handle_function def c_generate_random(h_session, length): diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index 8449ae0..cf1f4b4 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -8,7 +8,7 @@ from .cryptoki import CK_OBJECT_HANDLE, C_FindObjectsInit, CK_ULONG, \ C_FindObjects, C_FindObjectsFinal, C_GetAttributeValue, C_SetAttributeValue from .defines import CKR_OK -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function LOG = logging.getLogger(__name__) diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py index a78efae..3da781b 100644 --- a/pycryptoki/partition_management.py +++ b/pycryptoki/partition_management.py @@ -39,7 +39,7 @@ LUNA_CF_LIMITED_USER_CREATED, LUNA_CF_USER_PIN_TO_BE_CHANGED, LUNA_CF_LIMITED_USER_PIN_TO_BE_CHANGED) -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function LOG = logging.getLogger(__name__) diff --git a/pycryptoki/return_values.py b/pycryptoki/return_values.py index b814c42..e21c4ee 100755 --- a/pycryptoki/return_values.py +++ b/pycryptoki/return_values.py @@ -1,213 +1,10 @@ """ -THIS FILE WAS CREATED AUTOMATICALLY AND CONTAINS AUTOMATICALLY GENERATED CODE -This file should NOT be checked into MKS or modified in any way, this file was -created by setup/initialize.py. Any changes to this file will be wiped out when -it is regenerated. - -This file contains a dictionary lookup for the readable string values -of defines whose variable name starts with CKR_. This convention means they are -a return value for the cryptoki C API. - +Lookup dictionary for converting CK_ULONG return codes into +their string equivalents -- backwards compatibility """ +import warnings -from .defines import * +warnings.warn("Deprecated! Use 'pycryptoki.lookup_dicts' instead", DeprecationWarning) -ret_vals_dictionary = { - CKR_OK: 'CKR_OK', - CKR_CANCEL: 'CKR_CANCEL', - CKR_HOST_MEMORY: 'CKR_HOST_MEMORY', - CKR_SLOT_ID_INVALID: 'CKR_SLOT_ID_INVALID', - CKR_GENERAL_ERROR: 'CKR_GENERAL_ERROR', - CKR_FUNCTION_FAILED: 'CKR_FUNCTION_FAILED', - CKR_ARGUMENTS_BAD: 'CKR_ARGUMENTS_BAD', - CKR_NO_EVENT: 'CKR_NO_EVENT', - CKR_NEED_TO_CREATE_THREADS: 'CKR_NEED_TO_CREATE_THREADS', - CKR_CANT_LOCK: 'CKR_CANT_LOCK', - CKR_ATTRIBUTE_READ_ONLY: 'CKR_ATTRIBUTE_READ_ONLY', - CKR_ATTRIBUTE_SENSITIVE: 'CKR_ATTRIBUTE_SENSITIVE', - CKR_ATTRIBUTE_TYPE_INVALID: 'CKR_ATTRIBUTE_TYPE_INVALID', - CKR_ATTRIBUTE_VALUE_INVALID: 'CKR_ATTRIBUTE_VALUE_INVALID', - CKR_DATA_INVALID: 'CKR_DATA_INVALID', - CKR_DATA_LEN_RANGE: 'CKR_DATA_LEN_RANGE', - CKR_DEVICE_ERROR: 'CKR_DEVICE_ERROR', - CKR_DEVICE_MEMORY: 'CKR_DEVICE_MEMORY', - CKR_DEVICE_REMOVED: 'CKR_DEVICE_REMOVED', - CKR_ENCRYPTED_DATA_INVALID: 'CKR_ENCRYPTED_DATA_INVALID', - CKR_ENCRYPTED_DATA_LEN_RANGE: 'CKR_ENCRYPTED_DATA_LEN_RANGE', - CKR_FUNCTION_CANCELED: 'CKR_FUNCTION_CANCELED', - CKR_FUNCTION_NOT_PARALLEL: 'CKR_FUNCTION_NOT_PARALLEL', - CKR_FUNCTION_NOT_SUPPORTED: 'CKR_FUNCTION_NOT_SUPPORTED', - CKR_KEY_HANDLE_INVALID: 'CKR_KEY_HANDLE_INVALID', - CKR_KEY_SIZE_RANGE: 'CKR_KEY_SIZE_RANGE', - CKR_KEY_TYPE_INCONSISTENT: 'CKR_KEY_TYPE_INCONSISTENT', - CKR_KEY_NOT_NEEDED: 'CKR_KEY_NOT_NEEDED', - CKR_KEY_CHANGED: 'CKR_KEY_CHANGED', - CKR_KEY_NEEDED: 'CKR_KEY_NEEDED', - CKR_KEY_INDIGESTIBLE: 'CKR_KEY_INDIGESTIBLE', - CKR_KEY_FUNCTION_NOT_PERMITTED: 'CKR_KEY_FUNCTION_NOT_PERMITTED', - CKR_KEY_NOT_WRAPPABLE: 'CKR_KEY_NOT_WRAPPABLE', - CKR_KEY_UNEXTRACTABLE: 'CKR_KEY_UNEXTRACTABLE', - CKR_MECHANISM_INVALID: 'CKR_MECHANISM_INVALID', - CKR_MECHANISM_PARAM_INVALID: 'CKR_MECHANISM_PARAM_INVALID', - CKR_OBJECT_HANDLE_INVALID: 'CKR_OBJECT_HANDLE_INVALID', - CKR_OPERATION_ACTIVE: 'CKR_OPERATION_ACTIVE', - CKR_OPERATION_NOT_INITIALIZED: 'CKR_OPERATION_NOT_INITIALIZED', - CKR_PIN_INCORRECT: 'CKR_PIN_INCORRECT', - CKR_PIN_INVALID: 'CKR_PIN_INVALID', - CKR_PIN_LEN_RANGE: 'CKR_PIN_LEN_RANGE', - CKR_PIN_EXPIRED: 'CKR_PIN_EXPIRED', - CKR_PIN_LOCKED: 'CKR_PIN_LOCKED', - CKR_SESSION_CLOSED: 'CKR_SESSION_CLOSED', - CKR_SESSION_COUNT: 'CKR_SESSION_COUNT', - CKR_SESSION_HANDLE_INVALID: 'CKR_SESSION_HANDLE_INVALID', - CKR_SESSION_PARALLEL_NOT_SUPPORTED: 'CKR_SESSION_PARALLEL_NOT_SUPPORTED', - CKR_SESSION_READ_ONLY: 'CKR_SESSION_READ_ONLY', - CKR_SESSION_EXISTS: 'CKR_SESSION_EXISTS', - CKR_SESSION_READ_ONLY_EXISTS: 'CKR_SESSION_READ_ONLY_EXISTS', - CKR_SESSION_READ_WRITE_SO_EXISTS: 'CKR_SESSION_READ_WRITE_SO_EXISTS', - CKR_SIGNATURE_INVALID: 'CKR_SIGNATURE_INVALID', - CKR_SIGNATURE_LEN_RANGE: 'CKR_SIGNATURE_LEN_RANGE', - CKR_TEMPLATE_INCOMPLETE: 'CKR_TEMPLATE_INCOMPLETE', - CKR_TEMPLATE_INCONSISTENT: 'CKR_TEMPLATE_INCONSISTENT', - CKR_TOKEN_NOT_PRESENT: 'CKR_TOKEN_NOT_PRESENT', - CKR_TOKEN_NOT_RECOGNIZED: 'CKR_TOKEN_NOT_RECOGNIZED', - CKR_TOKEN_WRITE_PROTECTED: 'CKR_TOKEN_WRITE_PROTECTED', - CKR_UNWRAPPING_KEY_HANDLE_INVALID: 'CKR_UNWRAPPING_KEY_HANDLE_INVALID', - CKR_UNWRAPPING_KEY_SIZE_RANGE: 'CKR_UNWRAPPING_KEY_SIZE_RANGE', - CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: 'CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT', - CKR_USER_ALREADY_LOGGED_IN: 'CKR_USER_ALREADY_LOGGED_IN', - CKR_USER_NOT_LOGGED_IN: 'CKR_USER_NOT_LOGGED_IN', - CKR_USER_PIN_NOT_INITIALIZED: 'CKR_USER_PIN_NOT_INITIALIZED', - CKR_USER_TYPE_INVALID: 'CKR_USER_TYPE_INVALID', - CKR_USER_ANOTHER_ALREADY_LOGGED_IN: 'CKR_USER_ANOTHER_ALREADY_LOGGED_IN', - CKR_USER_TOO_MANY_TYPES: 'CKR_USER_TOO_MANY_TYPES', - CKR_WRAPPED_KEY_INVALID: 'CKR_WRAPPED_KEY_INVALID', - CKR_WRAPPED_KEY_LEN_RANGE: 'CKR_WRAPPED_KEY_LEN_RANGE', - CKR_WRAPPING_KEY_HANDLE_INVALID: 'CKR_WRAPPING_KEY_HANDLE_INVALID', - CKR_WRAPPING_KEY_SIZE_RANGE: 'CKR_WRAPPING_KEY_SIZE_RANGE', - CKR_WRAPPING_KEY_TYPE_INCONSISTENT: 'CKR_WRAPPING_KEY_TYPE_INCONSISTENT', - CKR_RANDOM_SEED_NOT_SUPPORTED: 'CKR_RANDOM_SEED_NOT_SUPPORTED', - CKR_RANDOM_NO_RNG: 'CKR_RANDOM_NO_RNG', - CKR_DOMAIN_PARAMS_INVALID: 'CKR_DOMAIN_PARAMS_INVALID', - CKR_BUFFER_TOO_SMALL: 'CKR_BUFFER_TOO_SMALL', - CKR_SAVED_STATE_INVALID: 'CKR_SAVED_STATE_INVALID', - CKR_INFORMATION_SENSITIVE: 'CKR_INFORMATION_SENSITIVE', - CKR_STATE_UNSAVEABLE: 'CKR_STATE_UNSAVEABLE', - CKR_CRYPTOKI_NOT_INITIALIZED: 'CKR_CRYPTOKI_NOT_INITIALIZED', - CKR_CRYPTOKI_ALREADY_INITIALIZED: 'CKR_CRYPTOKI_ALREADY_INITIALIZED', - CKR_MUTEX_BAD: 'CKR_MUTEX_BAD', - CKR_MUTEX_NOT_LOCKED: 'CKR_MUTEX_NOT_LOCKED', - CKR_NEW_PIN_MODE: 'CKR_NEW_PIN_MODE', - CKR_NEXT_OTP: 'CKR_NEXT_OTP', - CKR_FUNCTION_REJECTED: 'CKR_FUNCTION_REJECTED', - CKR_VENDOR_DEFINED: 'CKR_VENDOR_DEFINED', - CKR_INSERTION_CALLBACK_NOT_SUPPORTED: 'CKR_INSERTION_CALLBACK_NOT_SUPPORTED', - CKR_FUNCTION_PARALLEL: 'CKR_FUNCTION_PARALLEL', - CKR_SESSION_EXCLUSIVE_EXISTS: 'CKR_SESSION_EXCLUSIVE_EXISTS', - CKR_RC_ERROR: 'CKR_RC_ERROR', - CKR_CONTAINER_HANDLE_INVALID: 'CKR_CONTAINER_HANDLE_INVALID', - CKR_TOO_MANY_CONTAINERS: 'CKR_TOO_MANY_CONTAINERS', - CKR_USER_LOCKED_OUT: 'CKR_USER_LOCKED_OUT', - CKR_CLONING_PARAMETER_ALREADY_EXISTS: 'CKR_CLONING_PARAMETER_ALREADY_EXISTS', - CKR_CLONING_PARAMETER_MISSING: 'CKR_CLONING_PARAMETER_MISSING', - CKR_CERTIFICATE_DATA_MISSING: 'CKR_CERTIFICATE_DATA_MISSING', - CKR_CERTIFICATE_DATA_INVALID: 'CKR_CERTIFICATE_DATA_INVALID', - CKR_ACCEL_DEVICE_ERROR: 'CKR_ACCEL_DEVICE_ERROR', - CKR_WRAPPING_ERROR: 'CKR_WRAPPING_ERROR', - CKR_UNWRAPPING_ERROR: 'CKR_UNWRAPPING_ERROR', - CKR_MAC_MISSING: 'CKR_MAC_MISSING', - CKR_DAC_POLICY_PID_MISMATCH: 'CKR_DAC_POLICY_PID_MISMATCH', - CKR_DAC_MISSING: 'CKR_DAC_MISSING', - CKR_BAD_DAC: 'CKR_BAD_DAC', - CKR_SSK_MISSING: 'CKR_SSK_MISSING', - CKR_BAD_MAC: 'CKR_BAD_MAC', - CKR_DAK_MISSING: 'CKR_DAK_MISSING', - CKR_BAD_DAK: 'CKR_BAD_DAK', - CKR_SIM_AUTHORIZATION_FAILED: 'CKR_SIM_AUTHORIZATION_FAILED', - CKR_SIM_VERSION_UNSUPPORTED: 'CKR_SIM_VERSION_UNSUPPORTED', - CKR_SIM_CORRUPT_DATA: 'CKR_SIM_CORRUPT_DATA', - CKR_USER_NOT_AUTHORIZED: 'CKR_USER_NOT_AUTHORIZED', - CKR_MAX_OBJECT_COUNT_EXCEEDED: 'CKR_MAX_OBJECT_COUNT_EXCEEDED', - CKR_SO_LOGIN_FAILURE_THRESHOLD: 'CKR_SO_LOGIN_FAILURE_THRESHOLD', - CKR_SIM_AUTHFORM_INVALID: 'CKR_SIM_AUTHFORM_INVALID', - CKR_CITS_DAK_MISSING: 'CKR_CITS_DAK_MISSING', - CKR_UNABLE_TO_CONNECT: 'CKR_UNABLE_TO_CONNECT', - CKR_PARTITION_DISABLED: 'CKR_PARTITION_DISABLED', - CKR_CALLBACK_ERROR: 'CKR_CALLBACK_ERROR', - CKR_SECURITY_PARAMETER_MISSING: 'CKR_SECURITY_PARAMETER_MISSING', - CKR_SP_TIMEOUT: 'CKR_SP_TIMEOUT', - CKR_TIMEOUT: 'CKR_TIMEOUT', - CKR_ECC_UNKNOWN_CURVE: 'CKR_ECC_UNKNOWN_CURVE', - CKR_MTK_ZEROIZED: 'CKR_MTK_ZEROIZED', - CKR_MTK_STATE_INVALID: 'CKR_MTK_STATE_INVALID', - CKR_INVALID_ENTRY_TYPE: 'CKR_INVALID_ENTRY_TYPE', - CKR_MTK_SPLIT_INVALID: 'CKR_MTK_SPLIT_INVALID', - CKR_HSM_STORAGE_FULL: 'CKR_HSM_STORAGE_FULL', - CKR_DEVICE_TIMEOUT: 'CKR_DEVICE_TIMEOUT', - CKR_CONTAINER_OBJECT_STORAGE_FULL: 'CKR_CONTAINER_OBJECT_STORAGE_FULL', - CKR_PED_CLIENT_NOT_RUNNING: 'CKR_PED_CLIENT_NOT_RUNNING', - CKR_PED_UNPLUGGED: 'CKR_PED_UNPLUGGED', - CKR_ECC_POINT_INVALID: 'CKR_ECC_POINT_INVALID', - CKR_OPERATION_NOT_ALLOWED: 'CKR_OPERATION_NOT_ALLOWED', - CKR_LICENSE_CAPACITY_EXCEEDED: 'CKR_LICENSE_CAPACITY_EXCEEDED', - CKR_LOG_FILE_NOT_OPEN: 'CKR_LOG_FILE_NOT_OPEN', - CKR_LOG_FILE_WRITE_ERROR: 'CKR_LOG_FILE_WRITE_ERROR', - CKR_LOG_BAD_FILE_NAME: 'CKR_LOG_BAD_FILE_NAME', - CKR_LOG_FULL: 'CKR_LOG_FULL', - CKR_LOG_NO_KCV: 'CKR_LOG_NO_KCV', - CKR_LOG_BAD_RECORD_HMAC: 'CKR_LOG_BAD_RECORD_HMAC', - CKR_LOG_BAD_TIME: 'CKR_LOG_BAD_TIME', - CKR_LOG_AUDIT_NOT_INITIALIZED: 'CKR_LOG_AUDIT_NOT_INITIALIZED', - CKR_LOG_RESYNC_NEEDED: 'CKR_LOG_RESYNC_NEEDED', - CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS: 'CKR_AUDIT_LOGIN_TIMEOUT_IN_PROGRESS', - CKR_AUDIT_LOGIN_FAILURE_THRESHOLD: 'CKR_AUDIT_LOGIN_FAILURE_THRESHOLD', - CKR_INVALID_FUF_TARGET: 'CKR_INVALID_FUF_TARGET', - CKR_INVALID_FUF_HEADER: 'CKR_INVALID_FUF_HEADER', - CKR_INVALID_FUF_VERSION: 'CKR_INVALID_FUF_VERSION', - CKR_ECC_ECC_RESULT_AT_INF: 'CKR_ECC_ECC_RESULT_AT_INF', - CKR_AGAIN: 'CKR_AGAIN', - CKR_TOKEN_COPIED: 'CKR_TOKEN_COPIED', - CKR_SLOT_NOT_EMPTY: 'CKR_SLOT_NOT_EMPTY', - CKR_USER_ALREADY_ACTIVATED: 'CKR_USER_ALREADY_ACTIVATED', - CKR_STC_NO_CONTEXT: 'CKR_STC_NO_CONTEXT', - CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED: 'CKR_STC_CLIENT_IDENTITY_NOT_CONFIGURED', - CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED: 'CKR_STC_PARTITION_IDENTITY_NOT_CONFIGURED', - CKR_STC_DH_KEYGEN_ERROR: 'CKR_STC_DH_KEYGEN_ERROR', - CKR_STC_CIPHER_SUITE_REJECTED: 'CKR_STC_CIPHER_SUITE_REJECTED', - CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP: 'CKR_STC_DH_KEY_NOT_FROM_SAME_GROUP', - CKR_STC_COMPUTE_DH_KEY_ERROR: 'CKR_STC_COMPUTE_DH_KEY_ERROR', - CKR_STC_FIRST_PHASE_KDF_ERROR: 'CKR_STC_FIRST_PHASE_KDF_ERROR', - CKR_STC_SECOND_PHASE_KDF_ERROR: 'CKR_STC_SECOND_PHASE_KDF_ERROR', - CKR_STC_KEY_CONFIRMATION_FAILED: 'CKR_STC_KEY_CONFIRMATION_FAILED', - CKR_STC_NO_SESSION_KEY: 'CKR_STC_NO_SESSION_KEY', - CKR_STC_RESPONSE_BAD_MAC: 'CKR_STC_RESPONSE_BAD_MAC', - CKR_STC_NOT_ENABLED: 'CKR_STC_NOT_ENABLED', - CKR_STC_CLIENT_HANDLE_INVALID: 'CKR_STC_CLIENT_HANDLE_INVALID', - CKR_STC_SESSION_INVALID: 'CKR_STC_SESSION_INVALID', - CKR_STC_CONTAINER_INVALID: 'CKR_STC_CONTAINER_INVALID', - CKR_STC_SEQUENCE_NUM_INVALID: 'CKR_STC_SEQUENCE_NUM_INVALID', - CKR_STC_NO_CHANNEL: 'CKR_STC_NO_CHANNEL', - CKR_STC_RESPONSE_DECRYPT_ERROR: 'CKR_STC_RESPONSE_DECRYPT_ERROR', - CKR_STC_RESPONSE_REPLAYED: 'CKR_STC_RESPONSE_REPLAYED', - CKR_STC_REKEY_CHANNEL_MISMATCH: 'CKR_STC_REKEY_CHANNEL_MISMATCH', - CKR_STC_RSA_ENCRYPT_ERROR: 'CKR_STC_RSA_ENCRYPT_ERROR', - CKR_STC_RSA_SIGN_ERROR: 'CKR_STC_RSA_SIGN_ERROR', - CKR_STC_RSA_DECRYPT_ERROR: 'CKR_STC_RSA_DECRYPT_ERROR', - CKR_STC_RESPONSE_UNEXPECTED_KEY: 'CKR_STC_RESPONSE_UNEXPECTED_KEY', - CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE: 'CKR_STC_UNEXPECTED_NONCE_PAYLOAD_SIZE', - CKR_STC_UNEXPECTED_DH_DATA_SIZE: 'CKR_STC_UNEXPECTED_DH_DATA_SIZE', - CKR_STC_OPEN_CIPHER_MISMATCH: 'CKR_STC_OPEN_CIPHER_MISMATCH', - CKR_STC_OPEN_DHNIST_PUBKEY_ERROR: 'CKR_STC_OPEN_DHNIST_PUBKEY_ERROR', - CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL: 'CKR_STC_OPEN_KEY_MATERIAL_GEN_FAIL', - CKR_STC_OPEN_RESP_GEN_FAIL: 'CKR_STC_OPEN_RESP_GEN_FAIL', - CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL: 'CKR_STC_ACTIVATE_MACTAG_U_VERIFY_FAIL', - CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL: 'CKR_STC_ACTIVATE_MACTAG_V_GEN_FAIL', - CKR_STC_ACTIVATE_RESP_GEN_FAIL: 'CKR_STC_ACTIVATE_RESP_GEN_FAIL', - CKR_CHALLENGE_INCORRECT: 'CKR_CHALLENGE_INCORRECT', - CKR_ACCESS_ID_INVALID: 'CKR_ACCESS_ID_INVALID', - CKR_ACCESS_ID_ALREADY_EXISTS: 'CKR_ACCESS_ID_ALREADY_EXISTS', - CKR_OBJECT_READ_ONLY: 'CKR_OBJECT_READ_ONLY', - CKR_KEY_NOT_ACTIVE: 'CKR_KEY_NOT_ACTIVE', - CKR_KEK_RETRY_FAILURE: 'CKR_KEK_RETRY_FAILURE', - CKR_RNG_RESEED_TOO_EARLY: 'CKR_RNG_RESEED_TOO_EARLY' -} +# Backwards compatibility for now... +from .lookup_dicts import ret_vals_dictionary diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index c5c196a..ecfc774 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -42,7 +42,7 @@ from .common_utils import AutoCArray, refresh_c_arrays from .defines import CKR_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function LOG = logging.getLogger(__name__) diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index dd32b06..25a1658 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -14,7 +14,7 @@ from .defines import CKR_OK from .encryption import _get_string_from_list from .mechanism import parse_mechanism -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function LOG = logging.getLogger(__name__) diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 22b5ec0..6f0f3dd 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -2,10 +2,8 @@ Functions used for testing, or verifying return values. """ import sys -import inspect import logging from ctypes import byref -from functools import wraps if sys.version_info < (3,): integer_types = (int, long,) @@ -16,6 +14,9 @@ from .defines import CKR_OBJECT_HANDLE_INVALID from .defines import CKR_OK from .return_values import ret_vals_dictionary +from .exceptions import (LunaCallException, + LunaException, # Backwards compatibility for external imports + make_error_handle_function) LOG = logging.getLogger(__name__) @@ -49,40 +50,6 @@ def assert_test_return_value(value, expected_value, message, print_on_success=Tr LOG.info("%s: %s", exp_code, message) -class LunaException(Exception): - """A class representing an exception in luna, it's in place because - it has some nice functionailty to print out the contents of the error - - - """ - - def __init__(self, error_code, function_name, arguments): - """ - @param error_code: The error code of the error - @param function_name: The name of the function - @param arguments: The arguments passed into the function - """ - self.error_code = error_code - self.function_name = function_name - self.arguments = arguments - - if self.error_code in ret_vals_dictionary: - self.error_string = ret_vals_dictionary[self.error_code] - else: - self.error_string = "Unknown Code=%02x" % self.error_code - - def __str__(self): - data = ("\n\tFunction: {func_name}" - "\n\tError: {err_string}" - "\n\tError Code: {err_code}" - "\n\tArguments: {args}").format(func_name=self.function_name, - err_string=self.error_string, - err_code=hex(self.error_code), - args=self.arguments) - - return data - - class LunaReturn(object): """ """ @@ -138,7 +105,7 @@ def verify_object_exists(h_session, h_object, should_exist=True): try: ret = C_GetObjectSize(h_session, h_object, byref(us_size)) - except LunaException as e: + except LunaCallException as e: assert e.error_code == expected_ret, out else: assert ret == expected_ret, out @@ -154,93 +121,3 @@ def verify_object_exists(h_session, h_object, should_exist=True): True) assert us_size.value <= 0, \ "Object " + str(h_object.value) + " size is greater than zero." - - -def check_luna_exception(ret, luna_function, args): - """ - Check the return code from cryptoki.dll, and if it's non-zero raise an - exception with the error code looked up. - - :param ret: Return code from the C call - :param luna_function: pycryptoki function that was called - :param args: Arguments passed to the pycryptoki function. - """ - arg_spec = inspect.getargspec(luna_function).args - nice_args = [x if len(str(x)) < 20 else "{}...{}".format(str(x)[:10], str(x)[-10:]) - for x in args] - arg_string = ", ".join("{}={}".format(key, value) for key, value in zip(arg_spec, nice_args)) - - arg_string = "({})".format(arg_string) - if ret != CKR_OK: - raise LunaException(ret, luna_function.__name__, arg_string) - - -def make_error_handle_function(luna_function): - """This function is a helper function that creates a new function which checks the - result code returned from a function in luna. It is called by calling:: - - c_generate_key_pair_ex = make_error_handle_function(c_generate_key_pair) - - This code will create a c_generate_key_pair_ex which will call c_generate_key_pair and check the - first argument. The first argument is the return code of c_generate_key_pair. If the return - code != CKR_OK then c_generate_key_pair_ex will raise a LunaException. You can call - c_generate_key_pair_ex as if it is c_generate_key_pair:: - - c_generate_key_pair_ex(h_session, CKM_RSA_PKCS_KEY_PAIR_GEN, - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - - The return values of c_generate_pair are (ret, public_key_handle, private_key_handle) - - The return values of c_generate_pair_ex are (public_key_handle, private_key_handle) - - This lets you create two versions of a function. One version is for setup and - the other version is for testing the result. - - Directly testing the result:: - - ret = c_initialize() - assert ret == CKR_SOME_ERROR_CODE, "This test case will fail if this condition is not met" - - Expecting the call to go through without error. The test case should have an error (not a - failure):: - - c_initialize_ex() - - This should therefore make for shorter test cases - - :param luna_function: - - """ - - @wraps(luna_function) - def luna_function_exception_handle(*args, **kwargs): - """ - - :param *args: - :param **kwargs: - - """ - return_tuple = luna_function(*args, **kwargs) - if isinstance(return_tuple, tuple): - if len(return_tuple) > 2: - return_data = return_tuple[1:] - ret = return_tuple[0] - elif len(return_tuple) == 2: - return_data = return_tuple[1] - ret = return_tuple[0] - else: - return_data = return_tuple[0] - ret = return_tuple[0] - elif isinstance(return_tuple, integer_types): - ret = return_tuple - return_data = return_tuple - else: - raise Exception( - "Functions wrapped by the exception handler should return a tuple or just the " - "long representing Luna's return code.") - - check_luna_exception(ret, luna_function, args) - return return_data - - return luna_function_exception_handle diff --git a/pycryptoki/token_management.py b/pycryptoki/token_management.py index 4fe5159..72da801 100755 --- a/pycryptoki/token_management.py +++ b/pycryptoki/token_management.py @@ -23,7 +23,7 @@ C_GetMechanismInfo, CA_GetTokenPolicies) from .session_management import c_get_token_info -from .test_functions import make_error_handle_function +from .exceptions import make_error_handle_function from .common_utils import AutoCArray from .common_utils import refresh_c_arrays diff --git a/tests/unittests/test_attr_conversions.py b/tests/unittests/test_attr_conversions.py index db90072..1891f02 100644 --- a/tests/unittests/test_attr_conversions.py +++ b/tests/unittests/test_attr_conversions.py @@ -13,7 +13,7 @@ from hypothesis import given from hypothesis.extra.datetime import dates from hypothesis.strategies import integers, floats, text, booleans, lists, dictionaries, one_of -from six import b +from six import b, integer_types from pycryptoki.attributes import (CK_ATTRIBUTE, CKA_CLASS, @@ -26,7 +26,6 @@ to_sub_attributes, Attributes, convert_c_ubyte_array_to_string, KEY_TRANSFORMS) -from pycryptoki.test_functions import integer_types LOG = logging.getLogger(__name__) MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 diff --git a/tests/unittests/test_mechanisms.py b/tests/unittests/test_mechanisms.py index 45f6257..26866c1 100644 --- a/tests/unittests/test_mechanisms.py +++ b/tests/unittests/test_mechanisms.py @@ -4,7 +4,8 @@ import pytest from ctypes import cast, c_ulong, c_ubyte from mock import patch -from pycryptoki.test_functions import integer_types +from six import integer_types + from pycryptoki.cryptoki import (CK_RSA_PKCS_PSS_PARAMS, POINTER, CK_ULONG, From 7ff2e29ea7f8f8d0fdbc1e9a8f2ca7f7ce1281e1 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 13 Jun 2017 12:11:58 -0400 Subject: [PATCH 079/109] LA-2488 Updating pycryptoki documentation Change-Id: Idf8274c38002343bf9e6298904526575bdf73a7f --- docs/pycryptoki.rst | 9 --- pycryptoki/audit_handling.py | 4 +- pycryptoki/backup.py | 8 +-- pycryptoki/encryption.py | 69 ++++++++++--------- pycryptoki/hsm_management.py | 18 ++--- pycryptoki/key_generator.py | 56 +++++++-------- pycryptoki/key_management.py | 4 +- pycryptoki/key_usage.py | 4 +- pycryptoki/mechanism.py | 84 +++++++++++++++-------- pycryptoki/misc.py | 79 ++++++++++------------ pycryptoki/object_attr_lookup.py | 6 +- pycryptoki/partition_management.py | 10 +-- pycryptoki/session_management.py | 105 ++++++++++++++--------------- pycryptoki/sign_verify.py | 58 ++++++++-------- pycryptoki/test_functions.py | 4 +- 15 files changed, 271 insertions(+), 247 deletions(-) diff --git a/docs/pycryptoki.rst b/docs/pycryptoki.rst index 20e683e..a47370a 100644 --- a/docs/pycryptoki.rst +++ b/docs/pycryptoki.rst @@ -63,15 +63,6 @@ pycryptoki.defaults :show-inheritance: -pycryptoki.dictionary_handling ------------------------------- - -.. automodule:: pycryptoki.dictionary_handling - :members: - :undoc-members: - :show-inheritance: - - diff --git a/pycryptoki/audit_handling.py b/pycryptoki/audit_handling.py index a299896..85be50d 100755 --- a/pycryptoki/audit_handling.py +++ b/pycryptoki/audit_handling.py @@ -32,7 +32,7 @@ def ca_init_audit(slot, audit_pin, audit_label): def ca_time_sync(h_session, ultime): """ - :param h_session: + :param int h_session: Session handle :param ultime: """ @@ -47,7 +47,7 @@ def ca_time_sync(h_session, ultime): def ca_get_time(h_session): """ - :param h_session: + :param int h_session: Session handle """ diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index efb00c6..46a3073 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -11,7 +11,7 @@ def ca_open_secure_token(h_session, storage_path, dev_ID, mode): """ - :param h_session: + :param int h_session: Session handle :param storage_path: :param dev_ID: :param mode: @@ -31,7 +31,7 @@ def ca_open_secure_token(h_session, storage_path, dev_ID, mode): def ca_close_secure_token(h_session, h_ID): """ - :param h_session: + :param int h_session: Session handle :param h_ID: """ @@ -48,7 +48,7 @@ def ca_extract(h_session, mech_type, mech_params): """ :param mech_params: - :param h_session: + :param int h_session: Session handle """ mech = Mechanism(mech_type, params=mech_params) @@ -65,7 +65,7 @@ def ca_extract(h_session, mech_type, mech_params): def ca_insert(h_session, mech_type, mech_params): """ - :param h_session: + :param int h_session: Session handle :param py_mechanism_dict: :param params_type_string: diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index c44b92d..5e90a93 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -26,13 +26,16 @@ def c_encrypt(h_session, h_key, data, mechanism): """Encrypts data with a given key and encryption flavor encryption flavors - :param h_session: Current session - :param h_key: The key handle to encrypt the data with + .. note:: If data is a list or tuple of strings, multi-part encryption will be used. + + :param int h_session: Current session + :param int h_key: The key handle to encrypt the data with :param data: The data to encrypt, either a string or a list of strings. If this is - a list a multipart operation will be used - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - :returns: Returns the result code of the operation, a python string representing the - encrypted data + a list a multipart operation will be used + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :returns: (Retcode, Python bytestring of encrypted data) + :rtype: tuple """ mech = parse_mechanism(mechanism) # if a list is passed out do an encrypt operation on each string in the list, otherwise just @@ -96,14 +99,17 @@ def _get_string_from_list(list_of_strings): def c_decrypt(h_session, h_key, encrypted_data, mechanism): - """Decrypts some data + """Decrypt given data with the given key and mechanism. - :param h_session: The session to use - :param h_key: The handle of the key to use to decrypt - :param encrypted_data: Data to be decrypted - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - :returns: The result code, a python string of the decrypted data + .. note:: If data is a list or tuple of strings, multi-part decryption will be used. + :param int h_session: The session to use + :param int h_key: The handle of the key to use to decrypt + :param bytes encrypted_data: Data to be decrypted + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :returns: (Retcode, Python bytestring of decrypted data)) + :rtype: tuple """ mech = parse_mechanism(mechanism) # Initialize Decrypt @@ -156,7 +162,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in """Some code which will do a multipart encrypt or decrypt since they are the same with just different functions called - :param h_session: Session handle. + :param int h_session: Session handle :param c_update_function: C_Update function to call to update each operation. :param c_finalize_function: Function to call at end of multipart operation. :param input_data_list: List of data to call update function on. @@ -211,15 +217,15 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in def c_wrap_key(h_session, h_wrapping_key, h_key, mechanism): - """Function which wraps a key - - :param h_session: The session to use - :param h_wrapping_key: The handle of the key to use to wrap another key - :param h_key: The key to wrap - based on the encryption flavor (Default value = None) - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - :returns: The result code, a ctypes byte array representing the new key - + """Wrap a key off the HSM into an encrypted data blob. + + :param int h_session: The session to use + :param int h_wrapping_key: The handle of the key to use to wrap another key + :param int h_key: The key to wrap based on the encryption flavor + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :returns: (Retcode, python bytestring representing wrapped key) + :rtype: tuple """ mech = parse_mechanism(mechanism) @@ -243,15 +249,16 @@ def _wrap(): def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, mechanism): - """Function which unwraps a key - - :param h_session: The session to use - :param h_unwrapping_key: The wrapping key handle - :param wrapped_key: The wrapped key - :param key_template: The python template representing the new key's template - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - :returns: The result code, the handle of the unwrapped key - + """Unwrap a key from an encrypted data blob. + + :param int h_session: The session to use + :param int h_unwrapping_key: The wrapping key handle + :param bytes wrapped_key: The wrapped key + :param dict key_template: The python template representing the new key's template + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :returns: (Retcode, unwrapped key handle) + :rtype: tuple """ mech = parse_mechanism(mechanism) c_template = Attributes(key_template).get_c_struct() diff --git a/pycryptoki/hsm_management.py b/pycryptoki/hsm_management.py index 05366db..c46ad84 100755 --- a/pycryptoki/hsm_management.py +++ b/pycryptoki/hsm_management.py @@ -76,7 +76,7 @@ def ca_settokencertificatesignature(h_session, The public key is provided through the template; it must contain a key type, a modulus and a public exponent. - :param h_session: the current session + :param int h_session: Session handle :param access_level: the access level :param customer_id: the customer ID :param pub_template: the public template @@ -110,7 +110,7 @@ def ca_settokencertificatesignature(h_session, def ca_hainit(h_session, h_key): """Creates a login key pair on the primary token. - :param h_session: the current session + :param int h_session: Session handle :param h_key: the login private key :returns: the result code @@ -128,7 +128,7 @@ def ca_createloginchallenge(h_session, challenge): """Creates a login challenge for the given user. - :param h_session: the current session + :param int h_session: Session handle :param user_type: user type :param challenge: challenge :returns: the result code @@ -155,7 +155,7 @@ def ca_createloginchallenge(h_session, def ca_initializeremotepedvector(h_session): """Initializes a remote PED vector - :param h_session: the current session + :param int h_session: Session handle :returns: the result code """ @@ -170,7 +170,7 @@ def ca_initializeremotepedvector(h_session): def ca_deleteremotepedvector(h_session): """Deletes a remote PED vector - :param h_session: the current session + :param int h_session: Session handle :returns: the result code """ @@ -227,7 +227,7 @@ def ca_mtkzeroize(slot): def ca_set_hsm_policy(h_session, policy_id, policy_val): """Sets the HSM policies by calling CA_SetHSMPolicy - :param h_session: The session handle of the administrator setting the HSM policy + :param int h_session: Session handle :param policy_id: The ID of the policy being set :param policy_val: The value of the policy being set :returns: The result code @@ -244,7 +244,7 @@ def ca_set_hsm_policies(h_session, policies): """ Set multiple HSM policies. - :param h_session: session handle + :param int h_session: Session handle :param policies: dict of policy ID ints and value ints :return: result code """ @@ -266,7 +266,7 @@ def ca_set_hsm_policies(h_session, policies): def ca_set_destructive_hsm_policy(h_session, policy_id, policy_val): """Sets the destructive HSM policies by calling CA_SetDestructiveHSMPolicy - :param h_session: The session handle of the administrator setting the HSM policy + :param int h_session: Session handle :param policy_id: The ID of the policy being set :param policy_val: The value of the policy being set :returns: The result code @@ -283,7 +283,7 @@ def ca_set_destructive_hsm_policies(h_session, policies): """ Set multiple HSM policies. - :param h_session: session handle + :param int h_session: Session handle :param policies: dict of policy ID ints and value ints :return: result code """ diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 1c2f9a1..33dd84a 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -18,10 +18,9 @@ def c_destroy_object(h_session, h_object_value): """Deletes the object corresponsing to the passed in object handle - :param h_session: Current session - :param h_object_value: The handle of the object to delete - :returns: The resutl code from the C_DestroyObject operation - + :param int h_session: Session handle + :param int h_object_value: The handle of the object to delete + :returns: Return code """ ret = C_DestroyObject(h_session, CK_OBJECT_HANDLE(h_object_value)) return ret @@ -33,11 +32,11 @@ def c_destroy_object(h_session, h_object_value): def c_copy_object(h_session, h_object, template=None): """Method to call the C_CopyObject cryptoki command. - :param h_session: Handle to the session - :param h_object: Handle to the object to be cloned - :param template: Template for the new object. Defaults to None - :return: Handle to the new cloned object. - + :param int h_session: Session handle + :param int h_object: Handle to the object to be cloned + :param dict template: Template for the new object. Defaults to None + :return: (retcode, Handle to the new cloned object) + :rtype: tuple """ if template is None: template = {} @@ -58,11 +57,12 @@ def c_generate_key(h_session, mechanism=None, template=None): """ Generates a symmetric key of a given flavor given the correct template. - :param h_session: Current session - :param template: The template to use to generate the key - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - - :return: Returns the result code and the key's handle + :param int h_session: Session handle + :param dict template: The template to use to generate the key + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :return: (retcode, generated key handle) + :rtype tuple: """ if mechanism is None: mechanism = {"mech_type": CKM_DES_KEY_GEN} @@ -94,13 +94,13 @@ def c_generate_key_pair(h_session, """Generates a private and public key pair for a given flavor, and given public and private key templates. The return value will be the handle for the key. - :param h_session: Current session - :param pbkey_template: The public key template to use for key generation - :param prkey_template: The private key template to use for key generation - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - - :returns: Returns the result code, the public key's handle, and the private key's handle - + :param int h_session: Session handle + :param dict pbkey_template: The public key template to use for key generation + :param dict prkey_template: The private key template to use for key generation + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :returns: (retcode, public key handle, private key handle) + :rtype: tuple """ if mechanism is None: mechanism = {"mech_type": CKM_RSA_PKCS_KEY_PAIR_GEN} @@ -130,12 +130,13 @@ def c_generate_key_pair(h_session, def c_derive_key(h_session, h_base_key, template, mechanism=None): - """Calls C_DeriveKey + """Derives a key from another key. - :param h_session: The session handle to use - :param h_base_key: The base key - :param template: A python template of attributes (ex. CKM_DES_KEY_GEN_TEMP) - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function + :param int h_session: Session handle + :param int h_base_key: The base key + :param dict template: A python template of attributes to set on derived key + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. :returns: The result code, The derived key's handle """ @@ -155,8 +156,7 @@ def c_derive_key(h_session, h_base_key, template, mechanism=None): def clear_keys(h_session): """Quick hacked together function that can be used to clear the first 10 000 keys. - :param h_session: Current session - + :param int h_session: Session handle """ for i in range(1, 10000): c_destroy_object(h_session, i) diff --git a/pycryptoki/key_management.py b/pycryptoki/key_management.py index 5d5c6d9..9b5553f 100755 --- a/pycryptoki/key_management.py +++ b/pycryptoki/key_management.py @@ -13,7 +13,7 @@ def ca_generatemofn(h_session, is_secure_port_used): """Generates MofN secret information on a token. - :param h_session: the current session + :param int h_session: Session handle :param m_value: m :param vector_count: number of vectors :param is_secure_port_used: is secure port used @@ -52,7 +52,7 @@ def ca_generatemofn(h_session, def ca_modifyusagecount(h_session, h_object, command_type, value): """Modifies CKA_USAGE_COUNT attribute of the object. - :param h_session: the current session + :param int h_session: Session handle :param h_object: object :param command_type: command type :param value: value diff --git a/pycryptoki/key_usage.py b/pycryptoki/key_usage.py index a757df7..54ea2b9 100755 --- a/pycryptoki/key_usage.py +++ b/pycryptoki/key_usage.py @@ -9,7 +9,7 @@ def ca_clonemofn(h_session): """Clones MofN secret from one token to another. - :param h_session: the current session + :param int h_session: Session handle :returns: the result code """ @@ -26,7 +26,7 @@ def ca_clonemofn(h_session): def ca_duplicatemofn(h_session): """Duplicates a set of M of N vectors. - :param h_session: the current session + :param int h_session: Session handle :returns: the result code """ diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 5bb3d65..1770c1b 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -97,7 +97,7 @@ def to_c_mech(self): """ Create the Mechanism structure & set the mech type to the passed-in flavor. - :return: `CK_MECHANISM` + :return: `:class:`~pycryptoki.cryptoki.CK_MECHANISM`` """ self.mech = CK_MECHANISM() self.mech.mechanism = CK_MECHANISM_TYPE(self.mech_type) @@ -114,7 +114,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(IvMechanism, self).to_c_mech() if self.params is None or 'iv' not in self.params: @@ -136,7 +136,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(Iv16Mechanism, self).to_c_mech() if self.params is None or 'iv' not in self.params: @@ -160,7 +160,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(RC2Mechanism, self).to_c_mech() effective_bits = CK_ULONG(self.params['usEffectiveBits']) @@ -176,7 +176,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(RC2CBCMechanism, self).to_c_mech() effective_bits = self.params['usEffectiveBits'] @@ -195,7 +195,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(RC5Mechanism, self).to_c_mech() rc5_params = CK_RC5_PARAMS() @@ -213,7 +213,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(RC5CBCMechanism, self).to_c_mech() rc5_params = CK_RC5_CBC_PARAMS() @@ -234,7 +234,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(AESXTSMechanism, self).to_c_mech() xts_params = CK_AES_XTS_PARAMS() @@ -252,7 +252,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(RSAPKCSOAEPMechanism, self).to_c_mech() oaep_params = CK_RSA_PKCS_OAEP_PARAMS() @@ -280,7 +280,7 @@ def to_c_mech(self): Uses default salt length of 8. Can be overridden w/ a parameter though. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(RSAPKCSPSSMechanism, self).to_c_mech() c_params = CK_RSA_PKCS_PSS_PARAMS() @@ -299,7 +299,7 @@ def to_c_mech(self): """ Convert extra parameters to ctypes, then build out the mechanism. - :return: CK_MECHANISM + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(AESGCMMechanism, self).to_c_mech() gcm_params = CK_AES_GCM_PARAMS() @@ -336,7 +336,7 @@ def to_c_mech(self): """ Add in a pointer to the second key in the resulting mech structure. - :return: Mechanism Structure + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(ConcatenationDeriveMechanism, self).to_c_mech() c_second_key = CK_ULONG(self.params['h_second_key']) @@ -355,7 +355,7 @@ def to_c_mech(self): """ Convert data to bytearray, then use in the resulting mech structure. - :return: Mechanism Structure + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(ConcatenationDeriveMechanism, self).to_c_mech() parameters = CK_KEY_DERIVATION_STRING_DATA @@ -378,7 +378,8 @@ class NullMech(Mechanism): def to_c_mech(self): """ Simply set the pParameter to null pointer. - :return: + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(NullMech, self).to_c_mech() self.mech.pParameter = c_void_p(0) @@ -399,7 +400,8 @@ def to_c_mech(self): """ Attempt to handle generic mechanisms by introspection of the structure. - :return: + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ super(AutoMech, self).to_c_mech() c_params_type = getattr(cryptoki, @@ -495,9 +497,10 @@ def get_c_struct_from_mechanism(python_dictionary, params_type_string): """Gets a c struct from a python dictionary representing that struct :param python_dictionary: The python dictionary representing the C struct, - see CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP for an example + see :class:`CK_AES_CBC_PAD_EXTRACT_PARAMS` for an example :param params_type_string: A string representing the parameter struct. - ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' + ex. for :class:`~pycryptoki.cryptoki.CK_AES_CBC_PAD_EXTRACT_PARAMS` use the + string ``CK_AES_CBC_PAD_EXTRACT_PARAMS`` :returns: A C struct """ @@ -545,9 +548,9 @@ def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): :param c_mechanism: The c mechanism to convert to a python dictionary :param params_type_string: A string representing the parameter struct. - ex. for CK_AES_CBC_PAD_EXTRACT_PARAMS use the string 'CK_AES_CBC_PAD_EXTRACT_PARAMS' + ex. for :class:`~pycryptoki.cryptoki.CK_AES_CBC_PAD_EXTRACT_PARAMS` use the + string ``CK_AES_CBC_PAD_EXTRACT_PARAMS`` :returns: A python dictionary representing the c struct - """ python_dictionary = {} python_dictionary['mechanism'] = c_mechanism.mechanism @@ -594,19 +597,46 @@ def parse_mechanism(mechanism_param): Designed for use with any function call that takes in a mechanism, this will handle a mechanism parameter that is one of the following: - 1. CKM_ integer constant -- will create a CK_MECHANISM with only mech_type set. - 2. Dictionary with `mech_type` as a mandatory key, and `params` as an optional key. This - will be passed into the `Mechanism` class for conversion to a CK_MECHANISM. - 3. CK_MECHANISM struct -- passed directly into the raw C Call. + 1. ``CKM_`` integer constant -- will create a :class:`~pycryptoki.cryptoki.CK_MECHANISM` + with only mech_type set. + + .. code-block :: python + + parse_mechanism(CKM_RSA_PKCS) + # Results in: + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(CKM_RSA_PKCS) + mech.pParameter = None + mech.usParameterLen = 0 + + 2. Dictionary with ``mech_type`` as a mandatory key, and ``params`` as an optional key. This + will be passed into the :class:`Mechanism` class for conversion to + a :class:`~pycryptoki.cryptoki.CK_MECHANISM`. + + .. code-block :: python + + parse_mechanism({'mech_type': CKM_AES_CBC, + 'params': {'iv': list(range(8))}}) + # Results in: + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(CKM_AES_CBC) + iv_ba, iv_len = to_byte_array(list(range(8))) + mech.pParameter = iv_ba + mech.usParameterLen = iv_len + + 3. :class:`~pycryptoki.cryptoki.CK_MECHANISM` struct -- passed directly into the raw C Call. 4. Mechanism class -- will call to_c_mech() on the class, and use the results. .. warning:: If you're using this with rpyc, you need to make sure the call `to_c_mech` occurs - on the *server* (the machine with the HSM)! If you pass in a :py:class:`Mechanism` class that - was created on the client, the resulting call into `to_c_mech()` will *also* be on the client - side! + on the *server* (the machine with the HSM)! If you pass in a :py:class:`Mechanism` class + that was created on the client, the resulting call into `to_c_mech()` will *also* be on + the client side! + + .. note:: You can look at ``REQUIRED_PARAMS`` on each mechanism class to see what parameters are + required. :param mechanism_param: Parameter to convert to a C Mechanism. - :return: `CK_MECHANISM` struct. + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` struct. """ if isinstance(mechanism_param, dict): diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 7830070..20d60b3 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -20,7 +20,7 @@ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey from .defines import CKR_OK -from .mechanism import Mechanism, NullMech +from .mechanism import Mechanism, NullMech, parse_mechanism from .sign_verify import do_multipart_sign_or_digest from .exceptions import make_error_handle_function @@ -28,10 +28,10 @@ def c_generate_random(h_session, length): """Generates a sequence of random numbers - :param h_session: The current session - :param length: The length in bytes of the random number sequence - :returns: The result code, A string of random data - + :param int h_session: Session handle + :param int length: The length in bytes of the random number sequence + :returns: (retcode, A string of random data) + :rtype: tuple """ random_data = create_string_buffer(b"", length) @@ -48,10 +48,10 @@ def c_generate_random(h_session, length): def c_seed_random(h_session, seed): """Seeds the random number generator - :param h_session: The current session - :param seed: A python string of some seed - :returns: The result code - + :param int h_session: Session handle + :param bytes seed: A python string of some seed + :returns: retcode + :rtype: int """ seed_bytes = cast(create_string_buffer(seed), CK_BYTE_PTR) if isinstance(seed, (integer_types, float)): @@ -65,26 +65,23 @@ def c_seed_random(h_session, seed): c_seed_random_ex = make_error_handle_function(c_seed_random) -def c_digest(h_session, data_to_digest, digest_flavor, mech=None, extra_params=None): +def c_digest(h_session, data_to_digest, digest_flavor, mechanism=None): """Digests some data - :param h_session: Current session - :param data_to_digest: The data to digest, either a string or a list of strings. If this is a - list a multipart operation will be used - :param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, + :param int h_session: Session handle + :param bytes data_to_digest: The data to digest, either a string or a list of strings. + If this is a list a multipart operation will be used + :param int digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160, SHA224, SHA256, SHA384, SHA512) - :param mech: The mechanism to be used. If None a blank one with the - digest_flavour will be used (Default value = None) - :returns: The result code, a python string of the digested data - + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. If None will use digest flavor. + :returns: (retcode, a python string of the digested data) + :rtype: tuple """ - - # Get mechanism if none provided - if mech is None: - if extra_params is None: - mech = NullMech(digest_flavor).to_c_mech() - else: - mech = Mechanism(digest_flavor).to_c_mech() + if mechanism is None: + mech = parse_mechanism(digest_flavor) + else: + mech = parse_mechanism(mechanism) # Initialize Digestion ret = C_DigestInit(h_session, mech) @@ -127,21 +124,19 @@ def _digest(): c_digest_ex = make_error_handle_function(c_digest) -def c_digestkey(h_session, h_key, digest_flavor, mech=None, extra_params=None): - """ +def c_digestkey(h_session, h_key, digest_flavor, mechanism=None): + """Digest a key - :param h_session: Logged in session handle - :param h_key: Key to digest - :param digest_flavor: Digest flavor - :param mech: Mechanism to use for digest. Defaults to using the flavor mechanism. (Default - value = None) + :param int h_session: Session handle + :param int h_key: Key to digest + :param int digest_flavor: Digest flavor + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. If None will use digest flavor. """ - # Get mechanism if none provided - if mech is None: - if extra_params is None: - mech = NullMech(digest_flavor).to_c_mech() - else: - mech = Mechanism(digest_flavor).to_c_mech() + if mechanism is None: + mech = parse_mechanism(digest_flavor) + else: + mech = parse_mechanism(mechanism) # Initialize Digestion ret = C_DigestInit(h_session, mech) @@ -159,10 +154,10 @@ def c_digestkey(h_session, h_key, digest_flavor, mech=None, extra_params=None): def c_create_object(h_session, template): """Creates an object based on a given python template - :param h_session: The session handle to use - :param template: The python template which the object will be based on - :returns: The result code, the handle of the object - + :param int h_session: Session handle + :param dict template: The python template which the object will be based on + :returns: (retcode, the handle of the object) + :rtype: tuple """ c_template = Attributes(template).get_c_struct() new_object_handle = CK_ULONG() diff --git a/pycryptoki/object_attr_lookup.py b/pycryptoki/object_attr_lookup.py index cf1f4b4..ee61c87 100755 --- a/pycryptoki/object_attr_lookup.py +++ b/pycryptoki/object_attr_lookup.py @@ -17,7 +17,7 @@ def c_find_objects(h_session, template, num_entries): """Calls c_find_objects and c_find_objects_init to get a python dictionary of the objects found. - :param h_session: The current session + :param int h_session: Session handle :param template: A python dictionary of the object template to look for :param num_entries: The max number of entries to return :returns: Returns a list of handles of objects found @@ -45,7 +45,7 @@ def c_find_objects(h_session, template, num_entries): def c_get_attribute_value(h_session, h_object, template): """Calls C_GetAttrributeValue to get an attribute value based on a python template - :param h_session: The current session + :param int h_session: Session handle :param h_object: The handle of the object to get attributes for :param template: A python dictionary representing the template of the attributes to be retrieved :returns: A python dictionary representing the attributes returned from the HSM/library @@ -82,7 +82,7 @@ def c_get_attribute_value(h_session, h_object, template): def c_set_attribute_value(h_session, h_object, template): """Calls C_SetAttributeValue to set an attribute value based on a python template - :param h_session: The current session + :param int h_session: Session handle :param h_object: The handle of the object to get attributes for :param template: A python dictionary representing the template of the attributes to be written :returns: A python dictionary representing the attributes returned from the HSM/library diff --git a/pycryptoki/partition_management.py b/pycryptoki/partition_management.py index 3da781b..5eb90d5 100644 --- a/pycryptoki/partition_management.py +++ b/pycryptoki/partition_management.py @@ -47,7 +47,7 @@ def ca_create_container(h_session, storage_size, password=None, label='Inserted Token'): """Inserts a token into a slot without a Security Officer on the token - :param h_session: Current session + :param int h_session: Session handle :param storage_size: The storage size of the token (0 for undefined/unlimited) :param password: The password associated with the token (Default value = 'userpin') :param label: The label associated with the token (Default value = 'Inserted Token') @@ -81,7 +81,7 @@ def ca_delete_container_with_handle(h_session, h_container): """ Delete a container by handle - :param h_session: session + :param int h_session: Session handle :param h_container: target container handle :return: result code """ @@ -372,7 +372,7 @@ def ca_set_container_policy(h_session, h_containerber, policy_id, policy_val): NOTE: With per partition SO this method should generally not be used. Instead ca_set_partition_policies should be used - :param h_session: The session handle of the entity with permission to change the policy + :param int h_session: Session handle :param h_containerber: The container number to set the policy on. :param policy_id: The identifier of the policy (ex. CONTAINER_CONFIG_MINIMUM_PIN_LENGTH) :param policy_val: The value to set the policy to @@ -393,7 +393,7 @@ def ca_set_container_policies(h_session, h_container, policies): """ Set multiple container policies. - :param h_session: session handle + :param int h_session: Session handle :param h_container: target container handle :param policies: dict of policy ID ints and value ints :return: result code @@ -421,7 +421,7 @@ def ca_set_container_size(h_session, h_container, size): """ Set a container's size - :param h_session: session handle + :param int h_session: Session handle :param h_container: target container handle :param size: size :return: result code diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index ecfc774..0e9a699 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -48,11 +48,9 @@ def c_initialize(): - """Calls C_Initialize to c_initialize the board - - - :returns: The result code + """Initializes current process for use with PKCS11 + :returns: retcode """ # INITIALIZE LOG.info("C_Initialize: Initializing HSM") @@ -64,12 +62,11 @@ def c_initialize(): def c_finalize(): - """Calls C_Finalize - - - :returns: The result code + """Finalizes PKCS11 usage. + :return: retcode """ + LOG.info("C_Finalize: Finalizing HSM") ret = C_Finalize(0) return ret @@ -79,13 +76,13 @@ def c_finalize(): def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): - """Opens a session on a given slot + """Opens a session on the given slot - :param slot_num: The slot to get a session on - :param flags: The flags to open the session with + :param int slot_num: The slot to get a session on + :param int flags: The flags to open the session with (Default value = (CKF_SERIAL_SESSION | CKF_RW_SESSION) - :returns: The result code, the session handle - + :returns: (retcode, session handle) + :rtype: tuple """ # OPEN SESSION arg3 = create_string_buffer(b"Application") @@ -104,14 +101,14 @@ def c_open_session(slot_num, flags=(CKF_SERIAL_SESSION | CKF_RW_SESSION)): def login(h_session, slot_num=1, password=None, user_type=1): - """Login to the HSM - - :param h_session: Current session - :param slot_num: Slot index to login on (Default value = 1) - :param password: Password to login with (Default value = "userpin") - :param user_type: User type to login as (Default value = 1) - :returns: The result code - + """Login to the given session. + + :param int h_session: Session handle + :param int slot_num: Slot index to login on (Default value = 1) + :param bytes password: Password to login with (Default value = "userpin") + :param int user_type: User type to login as (Default value = 1) + :returns: retcode + :rtype: int """ # LOGIN LOG.info("C_Login: " @@ -156,10 +153,11 @@ def get_slot_info(description): def c_get_session_info(session): - """ - - :param session: return: + """Get information about the given session. + :param int session: session handle + :return: (retcode, dictionary of session information) + :rtype: tuple """ session_info = {} c_session_info = CK_SESSION_INFO() @@ -180,9 +178,9 @@ def c_get_session_info(session): def c_get_token_info(slot_id): """Gets the token info for a given slot id - :param slot_id: Slot index to get the token info for - :returns: The result code, A python dictionary representing the token info - + :param int slot_id: Slot index to get the token info for + :returns: (retcode, A python dictionary representing the token info) + :rtype: tuple """ token_info = {} c_token_info = CK_TOKEN_INFO() @@ -223,7 +221,6 @@ def get_slot_dict(): :returns: A python dictionary of the available slots - """ slot_list = AutoCArray() @@ -254,9 +251,9 @@ def _get_slot_list(): def c_close_session(h_session): """Closes a session - :param h_session: The session to close - :returns: The result code - + :param int h_session: Session handle + :returns: retcode + :rtype: int """ # CLOSE SESSION LOG.info("C_CloseSession: Closing session %s", h_session) @@ -270,9 +267,9 @@ def c_close_session(h_session): def c_logout(h_session): """Logs out of a given session - :param h_session: The session to log out from - :returns: The result code - + :param int h_session: Session handle + :returns: retcode + :rtype: int """ LOG.info("C_Logout: Logging out of session %s", h_session) ret = C_Logout(h_session) @@ -285,7 +282,7 @@ def c_logout(h_session): def c_init_pin(h_session, pin): """Initializes the PIN - :param h_session: Current session + :param int h_session: Session handle :param pin: pin to c_initialize :returns: THe result code @@ -318,7 +315,7 @@ def ca_factory_reset(slot): def c_set_pin(h_session, old_pass, new_pass): """Allows a user to change their PIN - :param h_session: Session of the user + :param int h_session: Session handle :param old_pass: The user's old password :param new_pass: The user's desired new password :returns: The result code @@ -343,8 +340,8 @@ def c_close_all_sessions(slot): """Closes all the sessions on a given slot :param slot: The slot to close all sessions on - :returns: The result code - + :returns: retcode + :rtype: int """ LOG.info("C_CloseAllSessions: Closing all sessions. slot=%s", slot) @@ -356,12 +353,13 @@ def c_close_all_sessions(slot): def ca_openapplicationID(slot, id_high, id_low): - """ - - :param slot: - :param id_high: - :param id_low: + """Open an application ID on the given slot. + :param int slot: Slot on which to open the APP ID + :param int id_high: High value of App ID + :param int id_low: Low value of App ID + :return: retcode + :rtype: int """ uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) @@ -379,12 +377,13 @@ def ca_openapplicationID(slot, id_high, id_low): def ca_closeapplicationID(slot, id_high, id_low): - """ - - :param slot: - :param id_high: - :param id_low: + """Close a given AppID on a slot. + :param int slot: Slot on which to close the APP ID + :param int id_high: High value of App ID + :param int id_low: Low value of App ID + :return: retcode + :rtype: int """ uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) @@ -402,11 +401,12 @@ def ca_closeapplicationID(slot, id_high, id_low): def ca_setapplicationID(id_high, id_low): - """Set the App ID for the current application. - - :param id_high: - :param id_low: + """Set the App ID for the current process. + :param int id_high: High value of App ID + :param int id_low: Low value of App ID + :return: retcode + :rtype: int """ uid_high = CK_ULONG(id_high) uid_low = CK_ULONG(id_low) @@ -427,7 +427,6 @@ def ca_restart(slot): """ :param slot: - """ LOG.info("CA_Restart: attempting to restart") diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 25a1658..3195359 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -20,22 +20,25 @@ def c_sign(h_session, h_key, data_to_sign, mechanism): - """ - Performs a C_SignInit and C_Sign operation on some data + """Signs the given data with given key and mechanism. + + .. note:: If data is a list or tuple of strings, multi-part operations will be used. - :param h_session: The current session + :param int h_session: Session handle :param data_to_sign: The data to sign, either a string or a list of strings. If this is a list - a multipart operation will be used (using C_...Update and C_...Final) + a multipart operation will be used (using C_...Update and C_...Final) - ex: + ex: - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", - "It will operate on these strings in parts"] + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", + "It will operate on these strings in parts"] - :param h_key: The key to sign the data with - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - :return: The result code, A python string representing the signature + :param int h_key: The signing key + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :return: (retcode, python string of signed data) + :rtype: tuple """ mech = parse_mechanism(mechanism) @@ -84,7 +87,7 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, """ Do a multipart sign or digest operation - :param h_session: The current session + :param int h_session: Session handle :param c_update_function: signing update function :param c_final_function: signing finalization function :param input_data_list: @@ -133,7 +136,7 @@ def do_multipart_verify(h_session, input_data_list, signature): """ Do a multipart verify operation - :param h_session: The current session + :param int h_session: Session handle :param input_data_list: list of data to verify with :param signature: signature to verify :return: The result code @@ -173,25 +176,24 @@ def do_multipart_verify(h_session, input_data_list, signature): def c_verify(h_session, h_key, data_to_verify, signature, mechanism): - """ - Return the result code of C_Verify which indicates whether or not the signature is - valid. + """Verifies data with the given signature, key and mechanism. - :param h_session: The current session - :param h_key: The key handle to verify the signature against - :param data_to_verify: The data to verify, either a string or a list of strings. If this is a - list, a multipart operation will be used (using C_...Update and - C_...Final) + .. note:: If data is a list or tuple of strings, multi-part operations will be used. - ex: + :param int h_session: Session handle + :param data_to_verify: The data to sign, either a string or a list of strings. If this is a list + a multipart operation will be used (using C_...Update and C_...Final) - - "This is a proper argument of some data to use in the function" - - ["This is another format of data this", "function will accept.", - "It will operate on these strings in parts"] + ex: - :param signature: The signature of the data - :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function - :return: The result code + - "This is a proper argument of some data to use in the function" + - ["This is another format of data this", "function will accept.", + "It will operate on these strings in parts"] + :param bytes signature: Signature with which to verify the data. + :param int h_key: The verifying key + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. + :return: retcode of verify operation """ mech = parse_mechanism(mechanism) diff --git a/pycryptoki/test_functions.py b/pycryptoki/test_functions.py index 6f0f3dd..2b62ae1 100755 --- a/pycryptoki/test_functions.py +++ b/pycryptoki/test_functions.py @@ -62,7 +62,7 @@ def verify_object_attributes(h_session, h_object, expected_template): """Verifies that an object generated has the correct attributes on the board. The expected attributes are passed in alongside the handle of the object. - :param h_session: Current session + :param int h_session: Session handle :param h_object: Handle of the object to verify the attributes against :param expected_template: The expected template to compare against @@ -87,7 +87,7 @@ def verify_object_exists(h_session, h_object, should_exist=True): """Queries the HSM to determine if an object exists. Asserts whether or not it exists. - :param h_session: The current session + :param int h_session: Session handle :param h_object: The object to verify if it exists :param should_exist: Whether or not the parameter should exist (Default value = True) From 5e7bbc9a7b26daa3cfc8c65d6e5e209f63e7633f Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 14 Jun 2017 10:20:04 -0400 Subject: [PATCH 080/109] LA-2489 Pycryptoki test case cleanup * Added reset marker * Added collection modification w/ reset marker/cmdline * Removed some extraneous tests (haven't been run/passing in ages, badly need to be re-written from scratch) Change-Id: I1b6a05d8bee82d0da485da05c79578ca65a8a51e --- tests/functional/conftest.py | 31 ++- tests/functional/test_get_token_info.py | 2 +- tests/functional/test_hsm_management.py | 5 +- tests/functional/test_key_management.py | 68 ++----- tests/functional/test_key_usage.py | 37 ---- tests/functional/test_keys.py | 18 +- ..._supporting_operations.py => test_misc.py} | 9 +- tests/functional/test_object_create.py | 47 +++-- tests/functional/test_session_management.py | 7 +- tests/functional/test_sign_verify.py | 5 +- .../functional/test_usage_limit_and_count.py | 182 ++++++++++-------- tests/functional/test_wrap_unwrap.py | 8 +- 12 files changed, 201 insertions(+), 218 deletions(-) delete mode 100755 tests/functional/test_key_usage.py rename tests/functional/{test_supporting_operations.py => test_misc.py} (93%) diff --git a/tests/functional/conftest.py b/tests/functional/conftest.py index 23937a5..ee88878 100644 --- a/tests/functional/conftest.py +++ b/tests/functional/conftest.py @@ -80,6 +80,7 @@ def pytest_configure(config): hsm_config["test_slot"] = config.getoption("test_slot") hsm_config["user"] = config.getoption("user") + hsm_config["reset"] = config.getoption("reset") c_initialize_ex() try: # Factory Reset @@ -117,6 +118,16 @@ def pytest_configure(config): c_finalize_ex() +def pytest_collection_modifyitems(session, config, items): + """ + Deselect tests marked with @pytest.mark.reset if --reset isn't given on cmdline. + """ + reset = config.getoption('reset') + for test_item in items[:]: + if test_item.get_marker('reset') and not reset: + items.remove(test_item) + + @pytest.yield_fixture(scope='session', autouse=True) def hsm_configured(pytestconfig): """ @@ -177,26 +188,6 @@ def auth_session(pytestconfig, session): c_logout(session) -@pytest.yield_fixture(scope="class", autouse=True) -def partition_clearer(auth_session): - """ - Autoused fixture to make sure the active session is cleared from all created objects. - - :param auth_session: - :return: - """ - yield - try: - # Use a blank template so we can grab everything. - template = Attributes({}).get_c_struct() - objects = c_find_objects_ex(auth_session, template, 1000) - for handle in objects: - ret = c_destroy_object(auth_session, handle) - if ret != CKR_OK: - LOG.info("Failed to destroy object w/ handle %s", handle) - except LunaException: - LOG.exception("Failed to destroy all objects created on this session") - @pytest.yield_fixture(scope="class") def valid_mechanisms(): diff --git a/tests/functional/test_get_token_info.py b/tests/functional/test_get_token_info.py index 1194515..0fbdd98 100755 --- a/tests/functional/test_get_token_info.py +++ b/tests/functional/test_get_token_info.py @@ -40,7 +40,7 @@ def reset_to_defaults(): c_close_all_sessions_ex(slot) -@pytest.mark.skipif("config.getoption('user') != 'SO' or not config.getoption('reset')") +@pytest.mark.reset class TestGetTokenInfo(object): """ """ diff --git a/tests/functional/test_hsm_management.py b/tests/functional/test_hsm_management.py index 67daae3..70ab36d 100755 --- a/tests/functional/test_hsm_management.py +++ b/tests/functional/test_hsm_management.py @@ -21,8 +21,9 @@ from . import config as hsm_config -class TestAlgorithm(object): - """Test algorithm class""" +@pytest.mark.reset +class TestHSMManagementFunctions(object): + """Test HSM Management functions class""" @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): diff --git a/tests/functional/test_key_management.py b/tests/functional/test_key_management.py index e422c0b..f0cec23 100755 --- a/tests/functional/test_key_management.py +++ b/tests/functional/test_key_management.py @@ -4,19 +4,16 @@ import pytest -from . import config as hsm_config -from pycryptoki.cryptoki import CK_ULONG, CK_BYTE, CA_MOFN_GENERATION, \ - CA_MOFN_GENERATION_PTR from pycryptoki.default_templates import CKM_DES_KEY_GEN, CKM_DES_KEY_GEN_TEMP -from pycryptoki.defines import CKR_OK, CKR_USER_NOT_AUTHORIZED, \ - CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, \ +from pycryptoki.defines import CKR_OK, CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, \ CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET -from pycryptoki.key_generator import c_generate_key -from pycryptoki.key_management import ca_generatemofn, ca_modifyusagecount -from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.key_generator import c_destroy_object, c_generate_key_ex +from pycryptoki.key_management import ca_modifyusagecount +from pycryptoki.lookup_dicts import ret_vals_dictionary +from . import config as hsm_config -class TestAlgorithm(object): +class TestKeyManagementFunctions(object): """Test algorithm class""" @pytest.fixture(autouse=True) @@ -24,32 +21,6 @@ def setup_teardown(self, auth_session): self.h_session = auth_session self.admin_slot = hsm_config["test_slot"] - @pytest.mark.xfail(run=False) - def test_generatemofn(self): - """Test generate M of N""" - m_value = CK_ULONG(1) - value = (CK_BYTE * 16)() - vector_count = CK_ULONG(2) - vector = (CA_MOFN_GENERATION * 2)() - vector[0].ulWeight = CK_ULONG(1) - vector[0].pVector = value - vector[0].ulVectorLen = CK_ULONG(16) - vector[1].ulWeight = CK_ULONG(1) - vector[1].pVector = (CK_BYTE * 16)() - vector[1].ulVectorLen = CK_ULONG(16) - vectors = CA_MOFN_GENERATION_PTR(vector) - is_secure_port_used = CK_ULONG(0) - - ret = ca_generatemofn(self.h_session, - m_value, - vectors, - vector_count, - is_secure_port_used) - assert ret == CKR_USER_NOT_AUTHORIZED, \ - "Return code should be " + \ - ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ - " not " + ret_vals_dictionary[ret] - @pytest.mark.parametrize("command_type", [CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_INCREMENT, CK_MODIFY_USAGE_COUNT_COMMAND_TYPE_SET]) @@ -59,17 +30,16 @@ def test_modifyusagecount(self, command_type): :param command_type: """ - ret, key_handle = c_generate_key(self.h_session, - CKM_DES_KEY_GEN, - CKM_DES_KEY_GEN_TEMP) - assert ret == CKR_OK, "Return code should be " + \ - ret_vals_dictionary[CKR_OK] + " not " + ret_vals_dictionary[ret] - assert key_handle > 0, "The key handle returned should be non zero" - - ret = ca_modifyusagecount(self.h_session, - key_handle, - command_type, - 0) - assert ret == CKR_OK, \ - "Return code should be " + ret_vals_dictionary[CKR_OK] + \ - " not " + ret_vals_dictionary[ret] + key_handle = c_generate_key_ex(self.h_session, + CKM_DES_KEY_GEN, + CKM_DES_KEY_GEN_TEMP) + try: + ret = ca_modifyusagecount(self.h_session, + key_handle, + command_type, + 0) + assert ret == CKR_OK, \ + "Return code should be " + ret_vals_dictionary[CKR_OK] + \ + " not " + ret_vals_dictionary[ret] + finally: + c_destroy_object(self.h_session, key_handle) diff --git a/tests/functional/test_key_usage.py b/tests/functional/test_key_usage.py deleted file mode 100755 index 2ccbc98..0000000 --- a/tests/functional/test_key_usage.py +++ /dev/null @@ -1,37 +0,0 @@ -""" -Test methods for .. 'hsm usage' set of commands. -""" - -import pytest - -from . import config as hsm_config -from pycryptoki.defines import CKR_SESSION_HANDLE_INVALID, \ - CKR_USER_NOT_AUTHORIZED -from pycryptoki.key_usage import ca_clonemofn, ca_duplicatemofn -from pycryptoki.return_values import ret_vals_dictionary - - -class TestAlgorithm(object): - """Test algorithm class""" - - @pytest.fixture(autouse=True) - def setup_teardown(self, auth_session): - self.h_session = auth_session - self.admin_slot = hsm_config["test_slot"] - - def test_clonemofn(self): - """Test clone M of N""" - ret = ca_clonemofn(self.h_session) - assert ret == CKR_SESSION_HANDLE_INVALID, \ - "Return code should be " + \ - ret_vals_dictionary[CKR_SESSION_HANDLE_INVALID] + \ - " not " + ret_vals_dictionary[ret] - - @pytest.mark.xfail(reason="Not valid on PWD auth") - def test_duplicatemofn(self): - """Test duplicate M of N""" - ret = ca_duplicatemofn(self.h_session) - assert ret == CKR_USER_NOT_AUTHORIZED, \ - "Return code should be " + \ - ret_vals_dictionary[CKR_USER_NOT_AUTHORIZED] + \ - " not " + ret_vals_dictionary[ret] diff --git a/tests/functional/test_keys.py b/tests/functional/test_keys.py index de24b27..780ea85 100755 --- a/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -77,6 +77,9 @@ def pair_params(key_gen): class TestKeys(object): + """ + Tests Key & Key pair generation + """ def verify_ret(self, ret, expected_ret): """ Verify ret check and len > 0""" assert ret == expected_ret, "Function should return: " + ret_vals_dictionary[expected_ret] \ @@ -100,8 +103,11 @@ def test_generate_key(self, key_type): key_template = get_default_key_template(key_type) ret, key_handle = c_generate_key(self.h_session, key_type, key_template) - self.verify_ret(ret, CKR_OK) - self.verify_key_len(key_handle, key_handle) + try: + self.verify_ret(ret, CKR_OK) + self.verify_key_len(key_handle, key_handle) + finally: + c_destroy_object(self.h_session, key_handle) @pytest.mark.parametrize(("key_type", "pub_key_temp", "prv_key_temp"), KEY_PAIRS, ids=[MECHANISM_LOOKUP_EXT[k[0]][0] for k in KEY_PAIRS]) @@ -115,8 +121,12 @@ def test_generate_key_pair(self, key_type, pub_key_temp, prv_key_temp): ret, pub_key, prv_key = c_generate_key_pair(self.h_session, key_type, pub_key_temp, prv_key_temp) - self.verify_ret(ret, CKR_OK) - self.verify_key_len(pub_key, prv_key) + try: + self.verify_ret(ret, CKR_OK) + self.verify_key_len(pub_key, prv_key) + finally: + c_destroy_object(self.h_session, prv_key) + c_destroy_object(self.h_session, pub_key) @pytest.mark.parametrize("curve_type", list(curve_list.keys())) def test_generate_ecdsa_key_pairs(self, curve_type): diff --git a/tests/functional/test_supporting_operations.py b/tests/functional/test_misc.py similarity index 93% rename from tests/functional/test_supporting_operations.py rename to tests/functional/test_misc.py index b9880b0..0d3a919 100755 --- a/tests/functional/test_supporting_operations.py +++ b/tests/functional/test_misc.py @@ -1,3 +1,6 @@ +""" +Test RNG functions +""" import logging import pytest @@ -6,13 +9,13 @@ from pycryptoki.defines import CKR_OK from pycryptoki.misc import c_generate_random_ex, c_seed_random, \ c_generate_random -from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.lookup_dicts import ret_vals_dictionary logger = logging.getLogger(__name__) -class TestSupportingOperations(object): - """ """ +class TestRNG(object): + """Test RNG Functions""" @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): diff --git a/tests/functional/test_object_create.py b/tests/functional/test_object_create.py index 7238325..fe497fb 100755 --- a/tests/functional/test_object_create.py +++ b/tests/functional/test_object_create.py @@ -1,20 +1,23 @@ +""" +Testcases for object creation +""" + import logging import pytest +from pycryptoki.defines import CKA_VALUE + +from pycryptoki.object_attr_lookup import c_get_attribute_value_ex -from . import config as hsm_config from pycryptoki.default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE -from pycryptoki.defines import CKR_OK -from pycryptoki.misc import c_create_object -from pycryptoki.return_values import ret_vals_dictionary -from pycryptoki.test_functions import verify_object_attributes +from pycryptoki.misc import c_create_object_ex +from . import config as hsm_config logger = logging.getLogger(__name__) -@pytest.mark.xfail(reason="Attributes do not convert 1-to-1 back to python") -class TestObjectCloning(object): - """ """ +class TestObjectCreation(object): + """Tests certificate & data creation.""" @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): @@ -28,12 +31,14 @@ def test_certificate_create(self): """ - ret, h_object = c_create_object(self.h_session, CERTIFICATE_TEMPLATE) - assert ret == CKR_OK, \ - "The result code of creating a " \ - "certificate should be CKR_OK, not " + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_object, CERTIFICATE_TEMPLATE) + h_object = c_create_object_ex(self.h_session, CERTIFICATE_TEMPLATE) + desired_attrs = {x: None for x in CERTIFICATE_TEMPLATE.keys()} + attr = c_get_attribute_value_ex(self.h_session, h_object, template=desired_attrs) + # CKA_VALUE in the template is a list of ints, but is returned as a single hex string. + # Let's try to convert it back to the list of ints. + value = attr[CKA_VALUE] + attr[CKA_VALUE] = [int(value[x:x+2], 16) for x in range(0, len(value), 2)] + assert attr == CERTIFICATE_TEMPLATE def test_data_create(self): """Tests C_CreateObject with a data template and verifies the object's @@ -41,9 +46,11 @@ def test_data_create(self): """ - ret, h_object = c_create_object(self.h_session, DATA_TEMPLATE) - assert ret == CKR_OK, \ - "The result of creating a data object should be CKR_OK, not" + ret_vals_dictionary[ret] - - verify_object_attributes(self.h_session, h_object, DATA_TEMPLATE) - + h_object = c_create_object_ex(self.h_session, DATA_TEMPLATE) + desired_attrs = {x: None for x in DATA_TEMPLATE.keys()} + attr = c_get_attribute_value_ex(self.h_session, h_object, template=desired_attrs) + # CKA_VALUE in the template is a list of ints, but is returned as a single hex string. + # Let's try to convert it back to the list of ints. + value = attr[CKA_VALUE] + attr[CKA_VALUE] = [int(value[x:x + 2], 16) for x in range(0, len(value), 2)] + assert attr == DATA_TEMPLATE diff --git a/tests/functional/test_session_management.py b/tests/functional/test_session_management.py index da55ce2..00584c9 100644 --- a/tests/functional/test_session_management.py +++ b/tests/functional/test_session_management.py @@ -1,3 +1,6 @@ +""" +Tests session management functions +""" import pytest import logging @@ -11,7 +14,9 @@ class TestSessionManagement(object): - + """ + Tests session management functions + """ @pytest.fixture(autouse=True) def setup_teardown(self, auth_session): self.admin_slot = hsm_config["test_slot"] diff --git a/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py index 9be2c66..1c19711 100755 --- a/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -25,7 +25,7 @@ MECHANISM_LOOKUP_EXT, get_default_key_template) -from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.lookup_dicts import ret_vals_dictionary logger = logging.getLogger(__name__) @@ -99,6 +99,9 @@ def asym_keys(auth_session): class TestSignVerify(object): + """ + Creates key pairs, signs data, and verifies that data. + """ def verify_ret(self, ret, expected_ret): """ diff --git a/tests/functional/test_usage_limit_and_count.py b/tests/functional/test_usage_limit_and_count.py index a728c02..8bafe9c 100755 --- a/tests/functional/test_usage_limit_and_count.py +++ b/tests/functional/test_usage_limit_and_count.py @@ -14,7 +14,7 @@ CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ CKM_DES_ECB, CKM_RSA_PKCS, CKR_KEY_NOT_ACTIVE, CKM_AES_ECB from pycryptoki.encryption import c_encrypt, c_encrypt_ex -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex +from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex, c_destroy_object from pycryptoki.object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex from . import config as hsm_config @@ -48,18 +48,21 @@ def test_set_attribute_usage_limit_sym(self): h_key = c_generate_key_ex(self.h_session, mechanism=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - LOG.info("Called c-generate: Key handle -%s", h_key) - usage_limit = 5 + try: + LOG.info("Called c-generate: Key handle -%s", h_key) + usage_limit = 5 - c_set_attribute_value_ex(self.h_session, - h_key, usage_template) + c_set_attribute_value_ex(self.h_session, + h_key, usage_template) - out_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_LIMIT: None}) + out_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_LIMIT: None}) - usage_val_out = out_template[CKA_USAGE_LIMIT] - LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :%s", usage_val_out) - assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + usage_val_out = out_template[CKA_USAGE_LIMIT] + LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :%s", usage_val_out) + assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + finally: + c_destroy_object(self.h_session, h_key) def test_usage_limit_attribute_check_sym_des(self): """Test: Verify that CKA_USAGE_COUNT attribute increments as user @@ -81,23 +84,26 @@ def test_usage_limit_attribute_check_sym_des(self): h_key = c_generate_key_ex(self.h_session, mechanism=CKM_DES_KEY_GEN, template=CKM_DES_KEY_GEN_TEMP) - LOG.info("Called c-generate: Key handle -%s", h_key) + try: + LOG.info("Called c-generate: Key handle -%s", h_key) - c_set_attribute_value_ex(self.h_session, - h_key, usage_lim_template) + c_set_attribute_value_ex(self.h_session, + h_key, usage_lim_template) - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES_ECB}) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES_ECB}) - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, - mechanism={"mech_type": CKM_DES_ECB}) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, + mechanism={"mech_type": CKM_DES_ECB}) - py_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_COUNT: None}) + py_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_COUNT: None}) - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + usage_val_out = py_template[CKA_USAGE_COUNT] + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + finally: + c_destroy_object(self.h_session, h_key) def test_usage_limit_attribute_check_sym_aes(self): """Test: Verify that CKA_USAGE_COUNT attribute increments as user @@ -118,21 +124,24 @@ def test_usage_limit_attribute_check_sym_aes(self): h_key = c_generate_key_ex(self.h_session, mechanism=CKM_AES_KEY_GEN, template=CKM_AES_KEY_GEN_TEMP) - LOG.info("Called c-generate: Key handle -" + str(h_key)) + try: + LOG.info("Called c-generate: Key handle -" + str(h_key)) - c_set_attribute_value_ex(self.h_session, - h_key, usage_lim_template) - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) + c_set_attribute_value_ex(self.h_session, + h_key, usage_lim_template) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) - py_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_COUNT: None}) + py_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_COUNT: None}) - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + usage_val_out = py_template[CKA_USAGE_COUNT] + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + finally: + c_destroy_object(self.h_session, h_key) def test_set_attribute_usage_limit_Assym(self): """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on @@ -153,18 +162,22 @@ def test_set_attribute_usage_limit_Assym(self): mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - LOG.info( - "Called c-generate: Public Key handle: %s Private Key Handle: %s", h_pbkey, h_prkey) - usage_limit = 2 - - c_set_attribute_value_ex(self.h_session, - h_pbkey, usage_lim_template) - - py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, - template={CKA_USAGE_LIMIT: None}) - usage_val_out = py_template[CKA_USAGE_LIMIT] - LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue: %s", usage_val_out) - assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + try: + LOG.info( + "Called c-generate: Public Key handle: %s Private Key Handle: %s", h_pbkey, h_prkey) + usage_limit = 2 + + c_set_attribute_value_ex(self.h_session, + h_pbkey, usage_lim_template) + + py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, + template={CKA_USAGE_LIMIT: None}) + usage_val_out = py_template[CKA_USAGE_LIMIT] + LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue: %s", usage_val_out) + assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" + finally: + c_destroy_object(self.h_session, h_pbkey) + c_destroy_object(self.h_session, h_prkey) def test_usage_limit_attribute_check_Assym(self): """Test: Verify that CKA_USAGE_COUNT attribute increments as user @@ -189,21 +202,25 @@ def test_usage_limit_attribute_check_Assym(self): pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - LOG.info( - "Called c-generate: Public Key handle -%s Private Key Handle -%s", h_pbkey, h_prkey) + try: + LOG.info( + "Called c-generate: Public Key handle -%s Private Key Handle -%s", h_pbkey, h_prkey) - c_set_attribute_value_ex(self.h_session, - h_pbkey, usage_lim_template) - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) + c_set_attribute_value_ex(self.h_session, + h_pbkey, usage_lim_template) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, - template={CKA_USAGE_COUNT: None}) + py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, + template={CKA_USAGE_COUNT: None}) - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + usage_val_out = py_template[CKA_USAGE_COUNT] + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" + finally: + c_destroy_object(self.h_session, h_pbkey) + c_destroy_object(self.h_session, h_prkey) def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE @@ -224,25 +241,28 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): mechanism=CKM_DES3_KEY_GEN, template=CKM_DES3_KEY_GEN_TEMP) LOG.info("Called c-generate: Key handle -" + str(h_key)) + try: - c_set_attribute_value_ex(self.h_session, - h_key, usage_lim_template) + c_set_attribute_value_ex(self.h_session, + h_key, usage_lim_template) - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) + c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) - return_val, data = c_encrypt(self.h_session, h_key, b'a' * 2048, - mechanism={"mech_type": CKM_DES3_ECB}) - LOG.info("Called C_Encrypt, return code: %s", return_val) + return_val, data = c_encrypt(self.h_session, h_key, b'a' * 2048, + mechanism={"mech_type": CKM_DES3_ECB}) + LOG.info("Called C_Encrypt, return code: %s", return_val) - py_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_COUNT: None}) + py_template = c_get_attribute_value_ex(self.h_session, h_key, + template={CKA_USAGE_COUNT: None}) - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + usage_val_out = py_template[CKA_USAGE_COUNT] + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + finally: + c_destroy_object(self.h_session, h_key) def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE @@ -261,22 +281,26 @@ def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + try: - LOG.info( - "Called c-generate: Public Key handle -%s Private Key Handle - %s", h_pbkey, h_prkey) + LOG.info( + "Called c-generate: Public Key handle -%s Private Key Handle - %s", h_pbkey, h_prkey) - c_set_attribute_value_ex(self.h_session, - h_pbkey, usage_lim_template) + c_set_attribute_value_ex(self.h_session, + h_pbkey, usage_lim_template) - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) + c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - return_val, data = c_encrypt(self.h_session, h_pbkey, b'a' * 20, - mechanism={"mech_type": CKM_RSA_PKCS}) - LOG.info("Called C_Encrypt, return code: %s", return_val) - py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, - template={CKA_USAGE_COUNT: None}) + return_val, data = c_encrypt(self.h_session, h_pbkey, b'a' * 20, + mechanism={"mech_type": CKM_RSA_PKCS}) + LOG.info("Called C_Encrypt, return code: %s", return_val) + py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, + template={CKA_USAGE_COUNT: None}) - usage_val_out = py_template[CKA_USAGE_COUNT] - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + usage_val_out = py_template[CKA_USAGE_COUNT] + assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" + finally: + c_destroy_object(self.h_session, h_pbkey) + c_destroy_object(self.h_session, h_prkey) diff --git a/tests/functional/test_wrap_unwrap.py b/tests/functional/test_wrap_unwrap.py index da04d53..02b9d5d 100755 --- a/tests/functional/test_wrap_unwrap.py +++ b/tests/functional/test_wrap_unwrap.py @@ -1,3 +1,6 @@ +""" +Testcases for wrapping/unwrapping keys. +""" import logging import pytest @@ -15,7 +18,7 @@ CKA_VALUE_LEN, CKA_EXTRACTABLE) from pycryptoki.encryption import c_wrap_key, c_unwrap_key, c_encrypt, c_decrypt from pycryptoki.key_generator import c_destroy_object, c_generate_key -from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.lookup_dicts import ret_vals_dictionary from pycryptoki.test_functions import verify_object_attributes logger = logging.getLogger(__name__) @@ -101,6 +104,9 @@ def keys(auth_session): class TestWrappingKeys(object): + """ + Testcases for wrapping/unwrapping keys. + """ def verify_ret(self, ret, expected_ret): """ Assert that ret is as expected From 20b7b13e4eabc0f8a5b5d87838eb23af4dbd6526 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 6 Jun 2017 15:59:30 -0400 Subject: [PATCH 081/109] LA-2457 Chunk size fixes Removed max chunk limitations from multi_part operations -- User can split the chunks as desired in the passed in tuple/list Reworked how we get data back from Update calls -- Results in 2 library calls for each chunk, to get the cipher data size -- Added early breaks + a C_**Final call to make sure operation isn't left active Reworked UsageCount/UsageLimit tests to use parameters Change-Id: I33b86b01472eb42e2ab8758034aff77c2d636281 --- pycryptoki/cryptoki_helpers.py | 3 +- pycryptoki/encryption.py | 97 +++-- pycryptoki/mechanism.py | 2 +- tests/functional/conftest.py | 10 +- .../functional/test_usage_limit_and_count.py | 410 +++++++----------- tests/functional/testdata/sha1pkcs_plain.der | Bin 0 -> 35 bytes 6 files changed, 235 insertions(+), 287 deletions(-) create mode 100644 tests/functional/testdata/sha1pkcs_plain.der diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index 191568a..96d570a 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -184,7 +184,7 @@ def luna_function(*args, **kwargs): :param **kwargs: """ - late_binded_function = eval("CryptokiDLLSingleton().get_dll()." + function_name) + late_binded_function = getattr(CryptokiDLLSingleton().get_dll(), function_name) late_binded_function.restype = luna_function.restype late_binded_function.argtypes = luna_function.argtypes @@ -196,4 +196,5 @@ def luna_function(*args, **kwargs): args, kwargs), e) + luna_function.__name__ = function_name return luna_function diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 5e90a93..135120c 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -19,10 +19,12 @@ from .return_values import ret_vals_dictionary from .exceptions import make_error_handle_function +MAX_BUFFER = 0xffff + LOG = logging.getLogger(__name__) -def c_encrypt(h_session, h_key, data, mechanism): +def c_encrypt(h_session, h_key, data, mechanism, output_buffers=None): """Encrypts data with a given key and encryption flavor encryption flavors @@ -34,6 +36,9 @@ def c_encrypt(h_session, h_key, data, mechanism): a list a multipart operation will be used :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. + :param list output_buffers: List of integers that specify a size of output buffers to use + for multi-part operations. By default will query with NULL pointer buffer + to get required size of buffer. :returns: (Retcode, Python bytestring of encrypted data) :rtype: tuple """ @@ -49,7 +54,7 @@ def c_encrypt(h_session, h_key, data, mechanism): if is_multi_part_operation: ret, encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, - C_EncryptFinal, data) + C_EncryptFinal, data, output_buffers) else: plain_data, plain_data_length = to_char_array(data) plain_data = cast(plain_data, POINTER(c_ubyte)) @@ -98,7 +103,7 @@ def _get_string_from_list(list_of_strings): return b"".join(list_of_strings) -def c_decrypt(h_session, h_key, encrypted_data, mechanism): +def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffers=None): """Decrypt given data with the given key and mechanism. .. note:: If data is a list or tuple of strings, multi-part decryption will be used. @@ -108,6 +113,9 @@ def c_decrypt(h_session, h_key, encrypted_data, mechanism): :param bytes encrypted_data: Data to be decrypted :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. + :param list output_buffers: List of integers that specify a size of output buffers to use + for multi-part operations. By default will query with NULL pointer buffer + to get required size of buffer. :returns: (Retcode, Python bytestring of decrypted data)) :rtype: tuple """ @@ -123,7 +131,7 @@ def c_decrypt(h_session, h_key, encrypted_data, mechanism): if is_multi_part_operation: ret, python_data = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, - encrypted_data) + encrypted_data, output_buffers) else: # Get the length of the final data @@ -158,7 +166,11 @@ def _decrypt(): c_decrypt_ex = make_error_handle_function(c_decrypt) -def do_multipart_operation(h_session, c_update_function, c_finalize_function, input_data_list): +def do_multipart_operation(h_session, + c_update_function, + c_finalize_function, + input_data_list, + output_buffers=None): """Some code which will do a multipart encrypt or decrypt since they are the same with just different functions called @@ -166,44 +178,67 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, in :param c_update_function: C_Update function to call to update each operation. :param c_finalize_function: Function to call at end of multipart operation. :param input_data_list: List of data to call update function on. + :param list output_buffers: List of integers that specify a size of output buffers to use + for multi-part operations. By default will query with NULL pointer buffer + to get required size of buffer """ - max_data_chunk_size = 0xfff0 - plain_data_len = len(b"".join(input_data_list)) - - remaining_length = plain_data_len python_data = [] - i = 0 - while remaining_length > 0: - current_chunk = input_data_list[i] - - # Prepare arguments for decrypt update operation - current_chunk_len = min(len(current_chunk), remaining_length) - - if current_chunk_len > max_data_chunk_size: - raise ValueError("chunk_sizes variable too large," - " the maximum size of a chunk is %s" % max_data_chunk_size) - - out_data = create_string_buffer(b'', max_data_chunk_size) - out_data_len = CK_ULONG(max_data_chunk_size) - data_chunk, data_chunk_len = to_char_array(current_chunk) + error = None + + for index, chunk in enumerate(input_data_list): + if output_buffers: + out_data_len = CK_ULONG(output_buffers[index]) + out_data = cast(create_string_buffer(b'', output_buffers[index]), CK_BYTE_PTR) + else: + out_data_len = CK_ULONG() + out_data = None + data_chunk, data_chunk_len = to_char_array(chunk) data_chunk = cast(data_chunk, POINTER(c_ubyte)) ret = c_update_function(h_session, data_chunk, data_chunk_len, - cast(out_data, CK_BYTE_PTR), byref(out_data_len)) + out_data, byref(out_data_len)) if ret != CKR_OK: - LOG.debug("Failed C_Update operation on chunk %.20s (%s/%s) - ret %s", - current_chunk, i, len(input_data_list), ret_vals_dictionary[ret]) - return ret, None - - remaining_length -= current_chunk_len + LOG.debug("%s call on chunk %.20s (%s/%s) Failed w/ ret %s (%s)", + c_update_function.__name__, + chunk, index + 1, len(input_data_list), ret_vals_dictionary[ret], ret) + error = ret + break + + if not output_buffers: + # Need a second call to actually get the data. + LOG.debug("Creating cipher data buffer of size %s", out_data_len.value) + out_data = create_string_buffer(b'', out_data_len.value) + ret = c_update_function(h_session, + data_chunk, data_chunk_len, + cast(out_data, CK_BYTE_PTR), byref(out_data_len)) + if ret != CKR_OK: + LOG.debug("%s call on chunk %.20s (%s/%s) Failed w/ ret %s (%s)", + c_update_function.__name__, + chunk, index + 1, len(input_data_list), ret_vals_dictionary[ret], ret) + error = ret + break # Get the output python_data.append(string_at(out_data, out_data_len.value)) - i += 1 + + if error: + # Make sure we finalize the operation -- don't want to leave any operations active. + ret = c_finalize_function(h_session, + cast(create_string_buffer(b'', MAX_BUFFER), CK_BYTE_PTR), + CK_ULONG(MAX_BUFFER)) + LOG.debug("%s call after a %s failure returned: %s (%s)", + c_finalize_function.__name__, + c_update_function.__name__, ret_vals_dictionary[ret], ret) + return error, None # Finalizing multipart decrypt operation - fin_out_data_len = CK_ULONG(max_data_chunk_size) + fin_out_data_len = CK_ULONG() + # Get buffer size for data + ret = c_finalize_function(h_session, None, byref(fin_out_data_len)) + if ret != CKR_OK: + return ret, None + fin_out_data = create_string_buffer(b"", fin_out_data_len.value) output = cast(fin_out_data, CK_BYTE_PTR) ret = c_finalize_function(h_session, output, byref(fin_out_data_len)) diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 1770c1b..43a2a9f 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -357,7 +357,7 @@ def to_c_mech(self): :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` """ - super(ConcatenationDeriveMechanism, self).to_c_mech() + super(StringDataDerivationMechanism, self).to_c_mech() parameters = CK_KEY_DERIVATION_STRING_DATA data, length = to_byte_array(self.params['data']) parameters.pData = cast(data, POINTER(c_ubyte)) diff --git a/tests/functional/conftest.py b/tests/functional/conftest.py index ee88878..31625e9 100644 --- a/tests/functional/conftest.py +++ b/tests/functional/conftest.py @@ -5,22 +5,19 @@ import os import sys -# From http://stackoverflow.com/a/7759927 -from pycryptoki.test_functions import LunaException - -from six import b import pytest from . import config as hsm_config from pycryptoki.attributes import Attributes from pycryptoki.defaults import ADMINISTRATOR_PASSWORD, ADMIN_PARTITION_LABEL, CO_PASSWORD -from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION, CKF_PROTECTED_AUTHENTICATION_PATH, CKR_OK -from pycryptoki.defines import CKF_SO_SESSION +from pycryptoki.defines import CKF_RW_SESSION, CKF_SERIAL_SESSION, CKR_OK, CKF_SO_SESSION, \ + CKF_PROTECTED_AUTHENTICATION_PATH from pycryptoki.key_generator import c_destroy_object from pycryptoki.object_attr_lookup import c_find_objects_ex from pycryptoki.session_management import c_initialize_ex, c_close_all_sessions_ex, \ ca_factory_reset_ex, c_open_session_ex, login_ex, c_finalize_ex, \ c_close_session, c_logout, c_get_token_info_ex +from pycryptoki.test_functions import LunaException from pycryptoki.token_management import c_init_token_ex, c_get_mechanism_list_ex LOG = logging.getLogger(__name__) @@ -188,7 +185,6 @@ def auth_session(pytestconfig, session): c_logout(session) - @pytest.yield_fixture(scope="class") def valid_mechanisms(): """ diff --git a/tests/functional/test_usage_limit_and_count.py b/tests/functional/test_usage_limit_and_count.py index 8bafe9c..e9a9dbf 100755 --- a/tests/functional/test_usage_limit_and_count.py +++ b/tests/functional/test_usage_limit_and_count.py @@ -5,302 +5,218 @@ """ import logging +import os +from collections import namedtuple import pytest +from pycryptoki.sign_verify import c_sign_ex, c_sign -from pycryptoki.default_templates import CKM_DES_KEY_GEN_TEMP, CKM_DES3_KEY_GEN_TEMP, \ - CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP, CKM_AES_KEY_GEN_TEMP +from pycryptoki.default_templates import get_default_key_pair_template, get_default_key_template from pycryptoki.defines import CKM_DES_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES3_KEY_GEN, \ - CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_DES3_ECB, \ - CKM_DES_ECB, CKM_RSA_PKCS, CKR_KEY_NOT_ACTIVE, CKM_AES_ECB + CKA_USAGE_LIMIT, CKA_USAGE_COUNT, CKM_DES3_ECB, \ + CKM_DES_ECB, CKR_KEY_NOT_ACTIVE, CKM_AES_ECB, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS from pycryptoki.encryption import c_encrypt, c_encrypt_ex -from pycryptoki.key_generator import c_generate_key_ex, c_generate_key_pair_ex, c_destroy_object +from pycryptoki.key_generator import c_generate_key_ex, c_destroy_object, c_generate_key_pair_ex from pycryptoki.object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex -from . import config as hsm_config LOG = logging.getLogger(__name__) - -class TestUsageLimitAndCount(object): - """ """ - - @pytest.fixture(autouse=True) - def setup_teardown(self, auth_session): - self.h_session = auth_session - self.admin_slot = hsm_config["test_slot"] - - def test_set_attribute_usage_limit_sym(self): - """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on - an symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 5 - Use C_getAttributeValue to verify - - - """ - - LOG.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an symmetric crypto object") - - usage_template = {CKA_USAGE_LIMIT: 5} - - h_key = c_generate_key_ex(self.h_session, - mechanism=CKM_DES_KEY_GEN, - template=CKM_DES_KEY_GEN_TEMP) - try: - LOG.info("Called c-generate: Key handle -%s", h_key) - usage_limit = 5 - - c_set_attribute_value_ex(self.h_session, +NEW_USAGE_LIMIT = 5 + +KEY_PARAMS = [ + (CKM_DES_KEY_GEN, CKM_DES_ECB), + (CKM_AES_KEY_GEN, CKM_AES_ECB), + (CKM_DES3_KEY_GEN, CKM_DES3_ECB) +] + +SymParams = namedtuple("SymParams", ["key", "mechanism"]) + + +LUNA_1145_XFAIL = pytest.mark.xfail(reason="LUNA-1145: CKA_USAGE_LIMIT set 2x " + "causes counting to no longer work") + + +@pytest.fixture(params=["create", "setattr", + LUNA_1145_XFAIL("both"), + LUNA_1145_XFAIL("create_then_use")]) +def usage_set(request): + """ + Parameterize tests to set up the CKA_USAGE_LIMIT in various forms: + + 1. On creation + 2. After creation, via c_set_attr + 3. On creation, and then set it again + 4. On creation, use the key once, then set it again. + """ + if request.param == "create_then_use": + yield request.param, NEW_USAGE_LIMIT + 1 + else: + yield request.param, NEW_USAGE_LIMIT + + +@pytest.fixture(params=KEY_PARAMS, + ids=["DES", "AES", "DES3"]) +def sym_key_params(request, auth_session, usage_set): + """ + Generate a key, setting the usage limit by the method described in + ``usage_set`` + + Return that key handle. + """ + usage_type, limit = usage_set + key_gen, mechanism = request.param + key_template = get_default_key_template(key_gen) + usage_template = {CKA_USAGE_LIMIT: limit} + if usage_type in ("create", "both", "create_then_use"): + key_template.update(usage_template) + + h_key = c_generate_key_ex(auth_session, + mechanism=key_gen, + template=key_template) + try: + if usage_type in ("create_then_use",): + c_encrypt_ex(auth_session, h_key, b'a' * 2048, + mechanism={"mech_type": mechanism}) + if usage_type in ("setattr", "both", "create_then_use"): + c_set_attribute_value_ex(auth_session, h_key, usage_template) + yield SymParams(h_key, mechanism) + finally: + c_destroy_object(auth_session, h_key) - out_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_LIMIT: None}) - usage_val_out = out_template[CKA_USAGE_LIMIT] - LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :%s", usage_val_out) - assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" - finally: - c_destroy_object(self.h_session, h_key) +def _get_data_file(filename): + """ + Get absolute path to filename. Uses current directory as basis to find the testdata folder. - def test_usage_limit_attribute_check_sym_des(self): - """Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use des key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + :param str filename: Filename to append + :return: full path to file + """ + return os.path.join(os.path.split(os.path.abspath(__file__))[0], "testdata", filename) - """ - LOG.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - usage_lim_template = {CKA_USAGE_LIMIT: 2} - - usage_count = 2 - - h_key = c_generate_key_ex(self.h_session, - mechanism=CKM_DES_KEY_GEN, - template=CKM_DES_KEY_GEN_TEMP) - try: - LOG.info("Called c-generate: Key handle -%s", h_key) - - c_set_attribute_value_ex(self.h_session, - h_key, usage_lim_template) - - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES_ECB}) - - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, - mechanism={"mech_type": CKM_DES_ECB}) +@pytest.fixture() +def asym_key(auth_session, usage_set): + """ + Generate a key pair & set the USAGE limit by some method (on creation or c_setattr, or both) - py_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_COUNT: None}) + :return: private key handle + """ + usage_type, limit = usage_set + pubtemp, privtemp = get_default_key_pair_template(CKM_RSA_PKCS_KEY_PAIR_GEN) + usage_template = {CKA_USAGE_LIMIT: limit} + if usage_type in ("create", "both", "create_then_use"): + privtemp.update(usage_template) - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + pubkey, privkey = c_generate_key_pair_ex(auth_session, CKM_RSA_PKCS_KEY_PAIR_GEN, pubtemp, + privtemp) + try: + if usage_type == "create_then_use": - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - finally: - c_destroy_object(self.h_session, h_key) - - def test_usage_limit_attribute_check_sym_aes(self): - """Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the symmetric crypto object - Procedure: - Generate a DES Key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use aes key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 - - - """ - LOG.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the symmetric crypto object") - usage_lim_template = {CKA_USAGE_LIMIT: 2} + with open(_get_data_file('sha1pkcs_plain.der'), 'rb') as df: + data = df.read() + c_sign_ex(auth_session, privkey, data, CKM_RSA_PKCS) - usage_count = 2 + if usage_type in ("setattr", "both", "create_then_use"): + c_set_attribute_value_ex(auth_session, privkey, usage_template) + yield privkey + finally: + c_destroy_object(auth_session, pubkey) + c_destroy_object(auth_session, privkey) - h_key = c_generate_key_ex(self.h_session, mechanism=CKM_AES_KEY_GEN, - template=CKM_AES_KEY_GEN_TEMP) - try: - LOG.info("Called c-generate: Key handle -" + str(h_key)) - - c_set_attribute_value_ex(self.h_session, - h_key, usage_lim_template) - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) - - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_AES_ECB}) - - py_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_COUNT: None}) - - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) - - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - finally: - c_destroy_object(self.h_session, h_key) - - def test_set_attribute_usage_limit_Assym(self): - """Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on - an assymetric crypto object - Procedure: - Generate a RSA key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 on RSA public key - Use C_getAttributeValue to verify +class TestUsageLimitAndCount(object): + """ + Verify Key usage attributes work + """ + def test_usagelimit_no_use_sym(self, auth_session, sym_key_params, usage_set): + """Verify that CKA_USAGE_LIMIT is reported correctly by C_GetAttribute """ - LOG.info("Test: Verify that user is able to set CKA_USAGE_LIMIT attribute on \ - an assymetric crypto object") - usage_lim_template = {CKA_USAGE_LIMIT: 2} + an symmetric crypto object") + _, new_limit = usage_set + key, _ = sym_key_params + out_template = c_get_attribute_value_ex(auth_session, key, + template={CKA_USAGE_LIMIT: None}) - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, - mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - try: - LOG.info( - "Called c-generate: Public Key handle: %s Private Key Handle: %s", h_pbkey, h_prkey) - usage_limit = 2 - - c_set_attribute_value_ex(self.h_session, - h_pbkey, usage_lim_template) - - py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, - template={CKA_USAGE_LIMIT: None}) - usage_val_out = py_template[CKA_USAGE_LIMIT] - LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue: %s", usage_val_out) - assert usage_limit == usage_val_out, "reported USAGE LIMIT does not match" - finally: - c_destroy_object(self.h_session, h_pbkey) - c_destroy_object(self.h_session, h_prkey) - - def test_usage_limit_attribute_check_Assym(self): - """Test: Verify that CKA_USAGE_COUNT attribute increments as user - use the assymetric crypto object - Procedure: - Generate a RSA Key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key twice for encryption - Use C_getAttributeValue to verify that CKA_USAGE_COUNT is 2 + usage_val_out = out_template[CKA_USAGE_LIMIT] + LOG.info("CKA_USAGE_LIMIT reported by C_GetAttributeValue :%s", usage_val_out) + assert new_limit == usage_val_out, "reported USAGE LIMIT does not match" + def test_usagelimit_sym(self, auth_session, sym_key_params, usage_set): + """Test: Verify that CKA_USAGE_COUNT attribute increments as user + uses the symmetric crypto object + Gen key w/ limit set to 5 + Use key 5x + Verify usage count == 5 """ - + _, new_limit = usage_set LOG.info("Test: Verify that CKA_USAGE_COUNT attribute increments as user \ - use the assymetric crypto object") - - usage_lim_template = {CKA_USAGE_LIMIT: 2} - usage_count = 2 - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, - mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) + uses the symmetric crypto object") - try: - LOG.info( - "Called c-generate: Public Key handle -%s Private Key Handle -%s", h_pbkey, h_prkey) + key, mechanism = sym_key_params - c_set_attribute_value_ex(self.h_session, - h_pbkey, usage_lim_template) - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) + for _ in range(5): + c_encrypt_ex(auth_session, key, b'a' * 2048, + mechanism={"mech_type": mechanism}) - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) + py_template = c_get_attribute_value_ex(auth_session, key, + template={CKA_USAGE_COUNT: None}) - py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, - template={CKA_USAGE_COUNT: None}) + usage_val_out = py_template[CKA_USAGE_COUNT] + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) - assert usage_count == usage_val_out, "reported USAGE LIMIT does not match" - finally: - c_destroy_object(self.h_session, h_pbkey) - c_destroy_object(self.h_session, h_prkey) - - def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_3des(self): - """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT - Procedure: - Generate a 3DES key - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key 3 times for encryption + assert new_limit == usage_val_out, "reported USAGE LIMIT does not match" + @LUNA_1145_XFAIL + def test_usagelimit_exceed_sym(self, auth_session, sym_key_params): + """Test that changing the usage limit works as expected + Gen key w/ limit = 5 + Set limit = 2 + Use key 2x + Verify next usage returns CKR_KEY_NOT_ACTIVE """ - LOG.info("Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE \ if user try to use crypto object more than limit set on CKA_USAGE_LIMIT") usage_lim_template = {CKA_USAGE_LIMIT: 2} - h_key = c_generate_key_ex(self.h_session, - mechanism=CKM_DES3_KEY_GEN, - template=CKM_DES3_KEY_GEN_TEMP) - LOG.info("Called c-generate: Key handle -" + str(h_key)) - try: - - c_set_attribute_value_ex(self.h_session, - h_key, usage_lim_template) - - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) - - c_encrypt_ex(self.h_session, h_key, b'a' * 2048, mechanism={"mech_type": CKM_DES3_ECB}) + key, mechanism = sym_key_params - return_val, data = c_encrypt(self.h_session, h_key, b'a' * 2048, - mechanism={"mech_type": CKM_DES3_ECB}) - LOG.info("Called C_Encrypt, return code: %s", return_val) + c_set_attribute_value_ex(auth_session, + key, usage_lim_template) - py_template = c_get_attribute_value_ex(self.h_session, h_key, - template={CKA_USAGE_COUNT: None}) + c_encrypt_ex(auth_session, key, b'a' * 2048, mechanism=mechanism) - usage_val_out = py_template[CKA_USAGE_COUNT] - LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + c_encrypt_ex(auth_session, key, b'a' * 2048, mechanism=mechanism) - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - finally: - c_destroy_object(self.h_session, h_key) + return_val, data = c_encrypt(auth_session, key, b'a' * 2048, + mechanism=mechanism) - def test_set_attribute_usage_count_check_error_CKR_KEY_NOT_ACTIVE_rsa(self): - """Test: Verify that crypto operation returns error CKR_KEY_NOT_ACTIVE - if user try to use crypto object more than limit set on CKA_USAGE_LIMIT - Procedure: - Generate a RSA Key pair - Use C_SetAttributeValue to set CKA_USAGE_LIMIT to 2 - Use RSA public key 3 times for encryption + py_template = c_get_attribute_value_ex(auth_session, key, + template={CKA_USAGE_COUNT: None}) + usage_val_out = py_template[CKA_USAGE_COUNT] + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + assert return_val == CKR_KEY_NOT_ACTIVE, "Key should be inactive -- exceeded usage count!" + def test_asym_withusage(self, auth_session, asym_key): """ + Test that USAGE_LIMIT works with asymmetric keys (private) too. + """ + key = asym_key + with open(_get_data_file('sha1pkcs_plain.der'), 'rb') as df: + data = df.read() - usage_lim_template = {CKA_USAGE_LIMIT: 2} - - h_pbkey, h_prkey = c_generate_key_pair_ex(self.h_session, - mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, - pbkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PUBTEMP, - prkey_template=CKM_RSA_PKCS_KEY_PAIR_GEN_PRIVTEMP) - try: - - LOG.info( - "Called c-generate: Public Key handle -%s Private Key Handle - %s", h_pbkey, h_prkey) - - c_set_attribute_value_ex(self.h_session, - h_pbkey, usage_lim_template) - - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) - - c_encrypt_ex(self.h_session, h_pbkey, b'a' * 20, mechanism={"mech_type": CKM_RSA_PKCS}) + for _ in range(5): + c_sign_ex(auth_session, key, data, CKM_RSA_PKCS) - return_val, data = c_encrypt(self.h_session, h_pbkey, b'a' * 20, - mechanism={"mech_type": CKM_RSA_PKCS}) - LOG.info("Called C_Encrypt, return code: %s", return_val) - py_template = c_get_attribute_value_ex(self.h_session, h_pbkey, - template={CKA_USAGE_COUNT: None}) + return_val, data = c_sign(auth_session, key, data, CKM_RSA_PKCS) + py_template = c_get_attribute_value_ex(auth_session, key, + template={CKA_USAGE_COUNT: None}) - usage_val_out = py_template[CKA_USAGE_COUNT] - assert return_val == CKR_KEY_NOT_ACTIVE, "reported error code does not match" - finally: - c_destroy_object(self.h_session, h_pbkey) - c_destroy_object(self.h_session, h_prkey) + usage_val_out = py_template[CKA_USAGE_COUNT] + LOG.info("CKA_USAGE_COUNT reported by C_GetAttributeValue: %s", usage_val_out) + assert return_val == CKR_KEY_NOT_ACTIVE, "Key should be inactive -- exceeded usage count!" diff --git a/tests/functional/testdata/sha1pkcs_plain.der b/tests/functional/testdata/sha1pkcs_plain.der new file mode 100644 index 0000000000000000000000000000000000000000..3452f50c2cddb84a08238d35b7d21bce51794a11 GIT binary patch literal 35 rcmXp|G~i@o)#hVnl450G5xFukYkHF}zp;n-Jh5#x>3(On?1}{dd+7=j literal 0 HcmV?d00001 From 34375dda5df3dd288a6347ffb0c006d3cab2bb7c Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 15 Jun 2017 12:19:07 -0400 Subject: [PATCH 082/109] LA-1696 Adding posargs options for tox Switched most templates to default to CKA_TOKEN=false, so they get cleaned up when session closes. Added posargs options & pytest-cov to tox.ini Fixing possible exception raised in finally Change-Id: If01ad9bbf941751723df7b91a79575af5edc7c8d --- tests/functional/test_encrypt_decrypt.py | 9 ++- tests/functional/test_key_management.py | 4 +- tests/functional/test_keys.py | 23 ++++--- tests/functional/test_object_create.py | 44 ++++++++----- tests/functional/test_sign_verify.py | 9 ++- .../functional/test_usage_limit_and_count.py | 9 ++- tests/functional/test_wrap_unwrap.py | 64 +++++++++++-------- tests/functional/util.py | 14 ++++ tests/unittests/test_auto_c_array.py | 5 +- tox.ini | 5 +- 10 files changed, 119 insertions(+), 67 deletions(-) create mode 100644 tests/functional/util.py diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index b37f2f5..ae961c5 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -22,8 +22,9 @@ from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_KEY_SIZE_RANGE) from pycryptoki.encryption import c_encrypt, c_decrypt from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, c_destroy_object -from pycryptoki.return_values import ret_vals_dictionary +from pycryptoki.lookup_dicts import ret_vals_dictionary from . import config as hsm_config +from .util import get_session_template logger = logging.getLogger(__name__) @@ -170,7 +171,7 @@ def sym_keys(auth_session): keys = {} try: for key_type in SYM_TABLE.values(): - template = get_default_key_template(key_type) + template = get_session_template(get_default_key_template(key_type)) ret, key_handle = c_generate_key(auth_session, key_type, template) if ret == CKR_OK: @@ -192,7 +193,9 @@ def asym_keys(auth_session): for key_type in ASYM_TABLE.values(): pub_temp, prv_temp = get_default_key_pair_template(key_type) - ret, pub_key, prv_key = c_generate_key_pair(auth_session, key_type, pub_temp, prv_temp) + ret, pub_key, prv_key = c_generate_key_pair(auth_session, key_type, + get_session_template(pub_temp), + get_session_template(prv_temp)) if ret == CKR_OK: keys[key_type] = (pub_key, prv_key) else: diff --git a/tests/functional/test_key_management.py b/tests/functional/test_key_management.py index f0cec23..c5b71af 100755 --- a/tests/functional/test_key_management.py +++ b/tests/functional/test_key_management.py @@ -11,7 +11,7 @@ from pycryptoki.key_management import ca_modifyusagecount from pycryptoki.lookup_dicts import ret_vals_dictionary from . import config as hsm_config - +from .util import get_session_template class TestKeyManagementFunctions(object): """Test algorithm class""" @@ -32,7 +32,7 @@ def test_modifyusagecount(self, command_type): """ key_handle = c_generate_key_ex(self.h_session, CKM_DES_KEY_GEN, - CKM_DES_KEY_GEN_TEMP) + get_session_template(CKM_DES_KEY_GEN_TEMP)) try: ret = ca_modifyusagecount(self.h_session, key_handle, diff --git a/tests/functional/test_keys.py b/tests/functional/test_keys.py index 780ea85..a36b590 100755 --- a/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -1,6 +1,7 @@ import logging import pytest +from .util import get_session_template from pycryptoki.default_templates import \ (CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, @@ -80,6 +81,7 @@ class TestKeys(object): """ Tests Key & Key pair generation """ + def verify_ret(self, ret, expected_ret): """ Verify ret check and len > 0""" assert ret == expected_ret, "Function should return: " + ret_vals_dictionary[expected_ret] \ @@ -100,7 +102,7 @@ def test_generate_key(self, key_type): Test generation of keys for sym. crypto systems :param key_type: key generation mechanism """ - key_template = get_default_key_template(key_type) + key_template = get_session_template(get_default_key_template(key_type)) ret, key_handle = c_generate_key(self.h_session, key_type, key_template) try: @@ -119,8 +121,8 @@ def test_generate_key_pair(self, key_type, pub_key_temp, prv_key_temp): :param prv_key_temp: private key template """ ret, pub_key, prv_key = c_generate_key_pair(self.h_session, key_type, - pub_key_temp, - prv_key_temp) + get_session_template(pub_key_temp), + get_session_template(prv_key_temp)) try: self.verify_ret(ret, CKR_OK) self.verify_key_len(pub_key, prv_key) @@ -135,10 +137,11 @@ def test_generate_ecdsa_key_pairs(self, curve_type): :param curve_type: """ CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] - ret, public_key_handle, private_key_handle = c_generate_key_pair(self.h_session, - CKM_ECDSA_KEY_PAIR_GEN, - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP, - CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP) + data = c_generate_key_pair(self.h_session, + CKM_ECDSA_KEY_PAIR_GEN, + get_session_template(CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP), + get_session_template(CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP)) + ret, public_key_handle, private_key_handle = data try: self.verify_ret(ret, CKR_OK) self.verify_key_len(public_key_handle, private_key_handle) @@ -156,7 +159,7 @@ def test_derive_key(self, key_type, d_type): :param key_type: Key-gen mechanism :param d_type: Hash mech """ - key_template = get_default_key_template(key_type) + key_template = get_session_template(get_default_key_template(key_type)) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) mech = NullMech(d_type).to_c_mech() @@ -184,7 +187,7 @@ def test_too_long_length_derives(self, key_type, d_type): :param key_type: :param d_type: """ - key_template = get_default_key_template(key_type) + key_template = get_session_template(get_default_key_template(key_type)) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) mech = NullMech(d_type).to_c_mech() @@ -210,7 +213,7 @@ def test_long_length_derive_key(self, key_type, d_type): :param key_type: key generation mechanism :param d_type: derive mechanism """ - key_template = get_default_key_template(key_type) + key_template = get_session_template(get_default_key_template(key_type)) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) mech = NullMech(d_type).to_c_mech() diff --git a/tests/functional/test_object_create.py b/tests/functional/test_object_create.py index fe497fb..fbc4726 100755 --- a/tests/functional/test_object_create.py +++ b/tests/functional/test_object_create.py @@ -5,6 +5,8 @@ import logging import pytest +from pycryptoki.key_generator import c_destroy_object + from pycryptoki.defines import CKA_VALUE from pycryptoki.object_attr_lookup import c_get_attribute_value_ex @@ -12,6 +14,7 @@ from pycryptoki.default_templates import CERTIFICATE_TEMPLATE, DATA_TEMPLATE from pycryptoki.misc import c_create_object_ex from . import config as hsm_config +from .util import get_session_template logger = logging.getLogger(__name__) @@ -30,15 +33,18 @@ def test_certificate_create(self): """ - - h_object = c_create_object_ex(self.h_session, CERTIFICATE_TEMPLATE) - desired_attrs = {x: None for x in CERTIFICATE_TEMPLATE.keys()} - attr = c_get_attribute_value_ex(self.h_session, h_object, template=desired_attrs) - # CKA_VALUE in the template is a list of ints, but is returned as a single hex string. - # Let's try to convert it back to the list of ints. - value = attr[CKA_VALUE] - attr[CKA_VALUE] = [int(value[x:x+2], 16) for x in range(0, len(value), 2)] - assert attr == CERTIFICATE_TEMPLATE + template = get_session_template(CERTIFICATE_TEMPLATE) + h_object = c_create_object_ex(self.h_session, template) + try: + desired_attrs = {x: None for x in template.keys()} + attr = c_get_attribute_value_ex(self.h_session, h_object, template=desired_attrs) + # CKA_VALUE in the template is a list of ints, but is returned as a single hex string. + # Let's try to convert it back to the list of ints. + value = attr[CKA_VALUE] + attr[CKA_VALUE] = [int(value[x:x+2], 16) for x in range(0, len(value), 2)] + assert attr == template + finally: + c_destroy_object(self.h_session, h_object) def test_data_create(self): """Tests C_CreateObject with a data template and verifies the object's @@ -46,11 +52,15 @@ def test_data_create(self): """ - h_object = c_create_object_ex(self.h_session, DATA_TEMPLATE) - desired_attrs = {x: None for x in DATA_TEMPLATE.keys()} - attr = c_get_attribute_value_ex(self.h_session, h_object, template=desired_attrs) - # CKA_VALUE in the template is a list of ints, but is returned as a single hex string. - # Let's try to convert it back to the list of ints. - value = attr[CKA_VALUE] - attr[CKA_VALUE] = [int(value[x:x + 2], 16) for x in range(0, len(value), 2)] - assert attr == DATA_TEMPLATE + template = get_session_template(DATA_TEMPLATE) + h_object = c_create_object_ex(self.h_session, template) + try: + desired_attrs = {x: None for x in template.keys()} + attr = c_get_attribute_value_ex(self.h_session, h_object, template=desired_attrs) + # CKA_VALUE in the template is a list of ints, but is returned as a single hex string. + # Let's try to convert it back to the list of ints. + value = attr[CKA_VALUE] + attr[CKA_VALUE] = [int(value[x:x + 2], 16) for x in range(0, len(value), 2)] + assert attr == template + finally: + c_destroy_object(self.h_session, h_object) diff --git a/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py index 1c19711..dbd1d45 100755 --- a/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -26,7 +26,7 @@ MECHANISM_LOOKUP_EXT, get_default_key_template) from pycryptoki.lookup_dicts import ret_vals_dictionary - +from .util import get_session_template logger = logging.getLogger(__name__) @@ -65,7 +65,7 @@ def sym_keys(auth_session): keys = {} try: for key_type in SYM_KEYS: - template = get_default_key_template(key_type) + template = get_session_template(get_default_key_template(key_type)) ret, key_handle = c_generate_key(auth_session, key_type, template) if ret == CKR_OK: keys[key_type] = key_handle @@ -85,7 +85,10 @@ def asym_keys(auth_session): try: for params in ASYM_PARAMS: key_type, pub_temp, prv_temp, _ = params - ret, pub_key, prv_key = c_generate_key_pair(auth_session, key_type, pub_temp, prv_temp) + ret, pub_key, prv_key = c_generate_key_pair(auth_session, + key_type, + get_session_template(pub_temp), + get_session_template(prv_temp)) if ret == CKR_OK: keys[key_type] = (pub_key, prv_key) else: diff --git a/tests/functional/test_usage_limit_and_count.py b/tests/functional/test_usage_limit_and_count.py index e9a9dbf..d02a935 100755 --- a/tests/functional/test_usage_limit_and_count.py +++ b/tests/functional/test_usage_limit_and_count.py @@ -18,6 +18,7 @@ from pycryptoki.encryption import c_encrypt, c_encrypt_ex from pycryptoki.key_generator import c_generate_key_ex, c_destroy_object, c_generate_key_pair_ex from pycryptoki.object_attr_lookup import c_get_attribute_value_ex, c_set_attribute_value_ex +from .util import get_session_template LOG = logging.getLogger(__name__) @@ -65,7 +66,7 @@ def sym_key_params(request, auth_session, usage_set): """ usage_type, limit = usage_set key_gen, mechanism = request.param - key_template = get_default_key_template(key_gen) + key_template = get_session_template(get_default_key_template(key_gen)) usage_template = {CKA_USAGE_LIMIT: limit} if usage_type in ("create", "both", "create_then_use"): key_template.update(usage_template) @@ -104,12 +105,14 @@ def asym_key(auth_session, usage_set): """ usage_type, limit = usage_set pubtemp, privtemp = get_default_key_pair_template(CKM_RSA_PKCS_KEY_PAIR_GEN) + usage_template = {CKA_USAGE_LIMIT: limit} if usage_type in ("create", "both", "create_then_use"): privtemp.update(usage_template) - pubkey, privkey = c_generate_key_pair_ex(auth_session, CKM_RSA_PKCS_KEY_PAIR_GEN, pubtemp, - privtemp) + pubkey, privkey = c_generate_key_pair_ex(auth_session, CKM_RSA_PKCS_KEY_PAIR_GEN, + get_session_template(pubtemp), + get_session_template(privtemp)) try: if usage_type == "create_then_use": diff --git a/tests/functional/test_wrap_unwrap.py b/tests/functional/test_wrap_unwrap.py index 02b9d5d..1140c66 100755 --- a/tests/functional/test_wrap_unwrap.py +++ b/tests/functional/test_wrap_unwrap.py @@ -158,16 +158,21 @@ def test_wrap_unwrap_key(self, mech, k_type, keys): ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mechanism=wrap_mech) self.verify_ret(ret, CKR_OK) - # Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, - h_wrap_key, - wrapped_key, - unwrap_temp, - mechanism=wrap_mech) - self.verify_ret(ret, CKR_OK) - - # Verify all of the attributes against the originally generated attributes - verify_object_attributes(self.h_session, h_unwrapped_key, temp) + h_unwrapped_key = None + try: + # Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, + h_wrap_key, + wrapped_key, + unwrap_temp, + mechanism=wrap_mech) + self.verify_ret(ret, CKR_OK) + + # Verify all of the attributes against the originally generated attributes + verify_object_attributes(self.h_session, h_unwrapped_key, temp) + finally: + if h_unwrapped_key: + c_destroy_object(self.h_session, h_unwrapped_key) @pytest.mark.parametrize(('mech', 'k_type'), PARAM_LIST, ids=[LOOKUP[m][0] for m, _ in PARAM_LIST]) @@ -197,20 +202,25 @@ def test_encrypt_wrap_unwrap_decrypt_key(self, mech, k_type, keys): ret, wrapped_key = c_wrap_key(self.h_session, h_wrap_key, h_key, mechanism=wrap_mech) self.verify_ret(ret, CKR_OK) - # Unwrap the Key - ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrap_key, - wrapped_key, - unwrap_temp, - mechanism=wrap_mech) - self.verify_ret(ret, CKR_OK) - - # Decrypt the data - ret, decrypted_string = c_decrypt(self.h_session, - h_unwrapped_key, - encrypted_data, - mechanism=enc_mech) - self.verify_ret(ret, CKR_OK) - - assert decrypted_string == data_to_encrypt, \ - "The decrypted data should be the same as the data that was encrypted. " \ - "Instead found " + str(decrypted_string) + h_unwrapped_key = None + try: + # Unwrap the Key + ret, h_unwrapped_key = c_unwrap_key(self.h_session, h_wrap_key, + wrapped_key, + unwrap_temp, + mechanism=wrap_mech) + self.verify_ret(ret, CKR_OK) + + # Decrypt the data + ret, decrypted_string = c_decrypt(self.h_session, + h_unwrapped_key, + encrypted_data, + mechanism=enc_mech) + self.verify_ret(ret, CKR_OK) + + assert decrypted_string == data_to_encrypt, \ + "The decrypted data should be the same as the data that was encrypted. " \ + "Instead found " + str(decrypted_string) + finally: + if h_unwrapped_key: + c_destroy_object(self.h_session, h_unwrapped_key) diff --git a/tests/functional/util.py b/tests/functional/util.py new file mode 100644 index 0000000..39f4535 --- /dev/null +++ b/tests/functional/util.py @@ -0,0 +1,14 @@ +""" +Utility functions for testing +""" +from pycryptoki.defines import CKA_TOKEN + + +def get_session_template(default_template): + """ + Set CKA_TOKEN to false on a template, so that it will be cleaned up on the + session close. + """ + default_template.copy() + default_template[CKA_TOKEN] = False + return default_template diff --git a/tests/unittests/test_auto_c_array.py b/tests/unittests/test_auto_c_array.py index ce56ad6..e2996e8 100644 --- a/tests/unittests/test_auto_c_array.py +++ b/tests/unittests/test_auto_c_array.py @@ -5,19 +5,22 @@ from string import ascii_letters import pytest +import sys from hypothesis import given from hypothesis.strategies import text, lists, sampled_from, integers from six import b, binary_type from pycryptoki.common_utils import AutoCArray -c_types = [c_short, c_ushort, c_long, c_ulong, c_int, c_uint, c_float, c_double, c_longdouble, +c_types = [c_short, c_ushort, c_long, c_ulong, c_int, c_uint, c_float, c_double, c_longlong, c_ulonglong, c_byte, c_ubyte, c_char, c_char_p, c_void_p, c_bool] MAX_INT = 2 ** (sizeof(c_ulong) * 8) - 1 class TestAutoCArray(object): + @pytest.mark.xfail(hasattr(sys, "pypy_version_info"), + reason="Fails on Pypy w/ AssertionError: unknown shape g") @given(sampled_from(c_types)) def test_auto_c_array_empty(self, typ_val): """ diff --git a/tox.ini b/tox.ini index 5c1767f..2dea4be 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,10 @@ deps=pytest mock pytz future + pytest-cov commands=py.test \ tests/unittests \ --junitxml=junit-{envname}.xml \ - --showlocals + --showlocals \ + -ra \ + {posargs} From 33b4e8187fe7ba4057a655c6a06644d61731cb23 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 19 Jun 2017 13:20:39 -0400 Subject: [PATCH 083/109] LA-2485 Add ECDH1 Derive mechanism + testcase Change-Id: I715116e7d58dc193086bb660d0e919899455b409 --- pycryptoki/exceptions.py | 40 +++++++++++------ pycryptoki/mechanism.py | 37 +++++++++++++++- tests/functional/test_keys.py | 82 ++++++++++++++++++++++++++++++++--- 3 files changed, 140 insertions(+), 19 deletions(-) diff --git a/pycryptoki/exceptions.py b/pycryptoki/exceptions.py index a205436..d462182 100644 --- a/pycryptoki/exceptions.py +++ b/pycryptoki/exceptions.py @@ -4,10 +4,10 @@ import inspect from functools import wraps -from six import integer_types +from six import integer_types, string_types from .defines import CKR_OK -from .lookup_dicts import ret_vals_dictionary +from .lookup_dicts import ret_vals_dictionary, ATTR_NAME_LOOKUP def make_error_handle_function(luna_function): @@ -75,13 +75,13 @@ def luna_function_exception_handle(*args, **kwargs): "Functions wrapped by the exception handler should return a tuple or just the " "long representing Luna's return code.") - check_luna_exception(ret, luna_function, args) + check_luna_exception(ret, luna_function, args, kwargs) return return_data return luna_function_exception_handle -def check_luna_exception(ret, luna_function, args): +def check_luna_exception(ret, luna_function, args, kwargs): """ Check the return code from cryptoki.dll, and if it's non-zero raise an exception with the error code looked up. @@ -90,12 +90,26 @@ def check_luna_exception(ret, luna_function, args): :param luna_function: pycryptoki function that was called :param args: Arguments passed to the pycryptoki function. """ - arg_spec = inspect.getargspec(luna_function).args - nice_args = [x if len(str(x)) < 20 else "{}...{}".format(str(x)[:10], str(x)[-10:]) - for x in args] - arg_string = ", ".join("{}={}".format(key, value) for key, value in zip(arg_spec, nice_args)) + log_list = [] + all_args = inspect.getcallargs(luna_function, *args, **kwargs) + for key, value in all_args.items(): + if "template" in key and isinstance(value, dict): + # Means it's a template, so let's perform a lookup on all of the objects within + # this. + log_list.append("\t\t%s: " % key) + for template_key, template_value in all_args[key].items(): + log_list.append("\t\t\t%s: %s" % (ATTR_NAME_LOOKUP.get(template_key, template_key), + template_value)) + elif "password" in key: + log_list.append("\t\t%s: *" % key) + else: + if len(str(value)) > 20: + msg = "\t\t%s: %s[...]%s" % (key, str(value)[:10], str(value)[-10:]) + else: + msg = "\t\t%s: %s" % (key, value) + log_list.append(msg) - arg_string = "({})".format(arg_string) + arg_string = "{}".format("\n".join(log_list)) if ret != CKR_OK: raise LunaCallException(ret, luna_function.__name__, arg_string) @@ -131,9 +145,9 @@ def __str__(self): data = ("\n\tFunction: {func_name}" "\n\tError: {err_string}" "\n\tError Code: {err_code}" - "\n\tArguments: {args}").format(func_name=self.function_name, - err_string=self.error_string, - err_code=hex(self.error_code), - args=self.arguments) + "\n\tArguments:\n{args}").format(func_name=self.function_name, + err_string=self.error_string, + err_code=hex(self.error_code), + args=self.arguments) return data diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 43a2a9f..4b4fdab 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -14,7 +14,8 @@ CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_RC2_CBC_PARAMS, \ CK_RC5_PARAMS, CK_RC5_CBC_PARAMS, CK_MECHANISM_TYPE, CK_AES_XTS_PARAMS, \ CK_RSA_PKCS_OAEP_PARAMS, \ - CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS, CK_KEY_DERIVATION_STRING_DATA, c_ubyte + CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS, CK_KEY_DERIVATION_STRING_DATA, c_ubyte, \ + CK_ECDH1_DERIVE_PARAMS from .defines import * from .exceptions import LunaException @@ -367,6 +368,37 @@ def to_c_mech(self): return self.mech +class ECDH1DeriveMechanism(Mechanism): + """ + ECDH1-specific mechanism + """ + REQUIRED_PARAMS = ["kdf", "sharedData", "publicData"] + + def to_c_mech(self): + """ + Create the Param structure, then convert the data into byte arrays. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(ECDH1DeriveMechanism, self).to_c_mech() + params = CK_ECDH1_DERIVE_PARAMS() + params.kdf = self.params['kdf'] + if self.params['sharedData'] is None: + shared_data = None + shared_data_len = 0 + else: + shared_data, shared_data_len = to_byte_array(self.params['sharedData']) + params.pSharedData = cast(shared_data, CK_BYTE_PTR) + params.ulSharedDataLen = shared_data_len + public_data, public_data_len = to_byte_array(self.params['publicData']) + params.pPublicData = cast(public_data, CK_BYTE_PTR) + params.ulPublicDataLen = public_data_len + self.mech.pParameter = cast(pointer(params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(params)) + return self.mech + + + # TODO: xordf mech class NullMech(Mechanism): @@ -490,6 +522,9 @@ def to_c_mech(self): CKM_CONCATENATE_BASE_AND_DATA: StringDataDerivationMechanism, CKM_XOR_BASE_AND_DATA: StringDataDerivationMechanism, CKM_CONCATENATE_DATA_AND_BASE: StringDataDerivationMechanism, + + + CKM_ECDH1_DERIVE: ECDH1DeriveMechanism, } diff --git a/tests/functional/test_keys.py b/tests/functional/test_keys.py index a36b590..2b2b018 100755 --- a/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -1,7 +1,6 @@ import logging import pytest -from .util import get_session_template from pycryptoki.default_templates import \ (CKM_DSA_KEY_PAIR_GEN_PRIVTEMP, @@ -27,12 +26,18 @@ CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_MD5_KEY_DERIVATION, CKM_MD2_KEY_DERIVATION, - CKR_OK, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE) + CKR_OK, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE, CKD_NULL, CKM_ECDH1_DERIVE, CKA_CLASS, + CKO_SECRET_KEY, CKA_EC_POINT, CKA_SENSITIVE, CKA_PRIVATE, CKA_DECRYPT, CKA_ENCRYPT, CKK_DES, + CKA_KEY_TYPE, CKM_DES_ECB) +from pycryptoki.encryption import c_encrypt_ex, c_decrypt_ex from pycryptoki.key_generator import \ - c_generate_key, c_generate_key_pair, c_derive_key, c_generate_key_ex, c_destroy_object + c_generate_key, c_generate_key_pair, c_derive_key, c_generate_key_ex, c_destroy_object, \ + c_derive_key_ex, c_generate_key_pair_ex from pycryptoki.mechanism import NullMech +from pycryptoki.object_attr_lookup import c_get_attribute_value_ex from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.test_functions import verify_object_attributes +from .util import get_session_template logger = logging.getLogger(__name__) @@ -76,6 +81,8 @@ def pair_params(key_gen): CKM_ARIA_KEY_GEN: "ARIA"} ALL_DERIVES = {k: v for d in [DERIVE_PARAMS, DRV_TOO_LONG] for k, v in d.items()} +DATA = "1234567812345678" + class TestKeys(object): """ @@ -136,10 +143,11 @@ def test_generate_ecdsa_key_pairs(self, curve_type): Test generate ECDSA key pairs :param curve_type: """ - CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP[CKA_ECDSA_PARAMS] = curve_list[curve_type] + pub_temp = CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP.copy() + pub_temp[CKA_ECDSA_PARAMS] = curve_list[curve_type] data = c_generate_key_pair(self.h_session, CKM_ECDSA_KEY_PAIR_GEN, - get_session_template(CKM_ECDSA_KEY_PAIR_GEN_PUBTEMP), + get_session_template(pub_temp), get_session_template(CKM_ECDSA_KEY_PAIR_GEN_PRIVTEMP)) ret, public_key_handle, private_key_handle = data try: @@ -232,3 +240,67 @@ def test_long_length_derive_key(self, key_type, d_type): c_destroy_object(self.h_session, h_base_key) if h_derived_key: c_destroy_object(self.h_session, h_derived_key) + + @pytest.mark.parametrize("curve_type", sorted(list(curve_list.keys()))) + def test_x9_key_derive(self, auth_session, curve_type): + """ + Test we can do X9 key derivation + """ + derived_key2 = derived_key1 = pub_key1 = pub_key2 = prv_key2 = prv_key1 = None + derived_template = { + CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_DES, + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True + } + pub_temp, priv_temp = get_default_key_pair_template(CKM_ECDSA_KEY_PAIR_GEN) + priv_temp = get_session_template(priv_temp) + pub_temp = get_session_template(pub_temp) + pub_temp[CKA_ECDSA_PARAMS] = curve_list[curve_type] + + pub_key1, prv_key1 = c_generate_key_pair_ex(auth_session, + CKM_ECDSA_KEY_PAIR_GEN, + pbkey_template=pub_temp, + prkey_template=priv_temp) + try: + pub_key2, prv_key2 = c_generate_key_pair_ex(auth_session, + CKM_ECDSA_KEY_PAIR_GEN, + pbkey_template=pub_temp, + prkey_template=priv_temp) + + pub_key1_raw = c_get_attribute_value_ex(auth_session, + pub_key1, + {CKA_EC_POINT: None})[CKA_EC_POINT] + pub_key2_raw = c_get_attribute_value_ex(auth_session, + pub_key2, + {CKA_EC_POINT: None})[CKA_EC_POINT] + derived_key1 = c_derive_key_ex(auth_session, + h_base_key=prv_key2, + template=derived_template, + mechanism={"mech_type": CKM_ECDH1_DERIVE, + "params": {"kdf": CKD_NULL, + "sharedData": None, + "publicData": pub_key1_raw}}) + + derived_key2 = c_derive_key_ex(auth_session, + h_base_key=prv_key1, + template=derived_template, + mechanism={"mech_type": CKM_ECDH1_DERIVE, + "params": {"kdf": CKD_NULL, + "sharedData": None, + "publicData": pub_key2_raw}}) + cipher_data = c_encrypt_ex(auth_session, + derived_key1, + data=DATA, + mechanism=CKM_DES_ECB) + restored_text = c_decrypt_ex(auth_session, + derived_key2, + cipher_data, + mechanism=CKM_DES_ECB) + assert DATA == restored_text.rstrip('\x00') + finally: + for key in (pub_key1, prv_key1, pub_key2, prv_key2, derived_key1, derived_key2): + if key: + c_destroy_object(auth_session, key) From 156e8811b63c2e0e3cf5c6ffd51d0dcda8c63e87 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 23 Jun 2017 10:35:11 -0400 Subject: [PATCH 084/109] LA-2498 Added AES* ENCRYPT derive mechanisms Added ECB & CBC ENCRYPT derive mechanisms + lookups Fixed some invalid attribute conversions: * to_byte_array will now handle 0x prefixed bytestrings * Removed unicode handling from to_byte_array Fixed c_generate_random data retrieval Change-Id: I44b83c1cfb76fce4211d33978441ce2e0509e97b --- pycryptoki/attributes.py | 11 +++-- pycryptoki/mechanism.py | 56 +++++++++++++++++++++++- pycryptoki/misc.py | 4 +- tests/functional/test_keys.py | 36 ++++++++++----- tests/unittests/test_attr_conversions.py | 22 +++++++++- 5 files changed, 108 insertions(+), 21 deletions(-) diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 9904d67..77d66a4 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -12,7 +12,7 @@ c_ulong, pointer, POINTER, sizeof, c_char, string_at, c_ubyte from functools import wraps -from six import b, string_types, integer_types +from six import b, string_types, integer_types, text_type, binary_type from .cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ CK_BYTE, CK_CHAR @@ -196,9 +196,12 @@ def to_byte_array(val, reverse=False): fin = binascii.hexlify(bytearray(data_list)) LOG.debug("Final hex data: %s", fin) return fin - - if isinstance(val, string_types): + if isinstance(val, text_type): + raise TypeError("Cannot convert unicode types to byte arrays!") + elif isinstance(val, binary_type): # Hex-string in form '01e4' + if val.startswith(b"0x"): + val = val.replace(b"0x", b"", 1) try: val = int(val, 16) except ValueError: @@ -206,7 +209,7 @@ def to_byte_array(val, reverse=False): if val.isspace() or len(val) == 0: val = b(val) else: - raise + pass # Pass on through to the iterable below. if isinstance(val, collections.Iterable): py_bytes = bytearray(val) byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py index 4b4fdab..ad1d5f1 100755 --- a/pycryptoki/mechanism.py +++ b/pycryptoki/mechanism.py @@ -15,7 +15,7 @@ CK_RC5_PARAMS, CK_RC5_CBC_PARAMS, CK_MECHANISM_TYPE, CK_AES_XTS_PARAMS, \ CK_RSA_PKCS_OAEP_PARAMS, \ CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS, CK_KEY_DERIVATION_STRING_DATA, c_ubyte, \ - CK_ECDH1_DERIVE_PARAMS + CK_AES_CBC_ENCRYPT_DATA_PARAMS, CK_ECDH1_DERIVE_PARAMS from .defines import * from .exceptions import LunaException @@ -323,6 +323,57 @@ def to_c_mech(self): return self.mech +class AESECBEncryptDataMechanism(Mechanism): + """ + AES mechanism for deriving keys from encrypted data. + """ + REQUIRED_PARAMS = ['data'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AESECBEncryptDataMechanism, self).to_c_mech() + # from https://www.cryptsoft.com/pkcs11doc/v220/group__SEC__12__14__2__MECHANISM__PARAMETERS.html + # Note: data should be a multiple of 16 long. + params = CK_KEY_DERIVATION_STRING_DATA() + pdata, data_len = to_byte_array(self.params['data']) + params.pData = pdata + params.ulLen = CK_ULONG(data_len) + self.mech.pParameter = cast(pointer(params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(params)) + return self.mech + + +class AESCBCEncryptDataMechanism(Mechanism): + """ + AES CBC mechanism for deriving keys from encrypted data. + """ + REQUIRED_PARAMS = ['iv', 'data'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AESCBCEncryptDataMechanism, self).to_c_mech() + # https://www.cryptsoft.com/pkcs11doc/v220/group__SEC__12__14__KEY__DERIVATION__BY__DATA__ENCRYPTION______DES______AES.html#CKM_AES_CBC_ENCRYPT_DATA + # Note: data should be a multiple of 16 long. + params = CK_AES_CBC_ENCRYPT_DATA_PARAMS() + pdata, data_len = to_byte_array(self.params['data']) + # Note: IV should always be a length of 8. + p_iv, _ = to_byte_array(self.params['iv']) + params.pData = pdata + params.ulLen = CK_ULONG(data_len) + params.iv = p_iv + self.mech.pParameter = cast(pointer(params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(params)) + return self.mech + + class ConcatenationDeriveMechanism(Mechanism): """ Mechanism class for key derivations. This will take in a second key handle in the parameters, @@ -518,6 +569,9 @@ def to_c_mech(self): CKM_DES_ECB: NullMech, + CKM_AES_CBC_ENCRYPT_DATA: AESCBCEncryptDataMechanism, + CKM_AES_ECB_ENCRYPT_DATA: AESECBEncryptDataMechanism, + CKM_CONCATENATE_BASE_AND_KEY: ConcatenationDeriveMechanism, CKM_CONCATENATE_BASE_AND_DATA: StringDataDerivationMechanism, CKM_XOR_BASE_AND_DATA: StringDataDerivationMechanism, diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 20d60b3..9ccd01c 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -38,8 +38,8 @@ def c_generate_random(h_session, length): data_ptr = cast(random_data, CK_BYTE_PTR) ret = C_GenerateRandom(h_session, data_ptr, CK_ULONG(length)) - random_string = random_data.value - return ret, random_string + data = string_at(data_ptr, length) + return ret, data c_generate_random_ex = make_error_handle_function(c_generate_random) diff --git a/tests/functional/test_keys.py b/tests/functional/test_keys.py index 2b2b018..14ce0b8 100755 --- a/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -28,7 +28,7 @@ CKR_OK, CKA_VALUE_LEN, CKR_KEY_SIZE_RANGE, CKD_NULL, CKM_ECDH1_DERIVE, CKA_CLASS, CKO_SECRET_KEY, CKA_EC_POINT, CKA_SENSITIVE, CKA_PRIVATE, CKA_DECRYPT, CKA_ENCRYPT, CKK_DES, - CKA_KEY_TYPE, CKM_DES_ECB) + CKA_KEY_TYPE, CKM_DES_ECB, CKR_MECHANISM_INVALID) from pycryptoki.encryption import c_encrypt_ex, c_decrypt_ex from pycryptoki.key_generator import \ c_generate_key, c_generate_key_pair, c_derive_key, c_generate_key_ex, c_destroy_object, \ @@ -81,7 +81,7 @@ def pair_params(key_gen): CKM_ARIA_KEY_GEN: "ARIA"} ALL_DERIVES = {k: v for d in [DERIVE_PARAMS, DRV_TOO_LONG] for k, v in d.items()} -DATA = "1234567812345678" +DATA = b"1234567812345678" class TestKeys(object): @@ -104,7 +104,7 @@ def setup_teardown(self, auth_session): self.h_session = auth_session @pytest.mark.parametrize("key_type", KEYS, ids=[MECHANISM_LOOKUP_EXT[k][0] for k in KEYS]) - def test_generate_key(self, key_type): + def test_generate_key(self, key_type, valid_mechanisms): """ Test generation of keys for sym. crypto systems :param key_type: key generation mechanism @@ -113,14 +113,17 @@ def test_generate_key(self, key_type): ret, key_handle = c_generate_key(self.h_session, key_type, key_template) try: - self.verify_ret(ret, CKR_OK) - self.verify_key_len(key_handle, key_handle) + if key_type not in valid_mechanisms: + self.verify_ret(ret, CKR_MECHANISM_INVALID) + else: + self.verify_ret(ret, CKR_OK) + self.verify_key_len(key_handle, key_handle) finally: c_destroy_object(self.h_session, key_handle) @pytest.mark.parametrize(("key_type", "pub_key_temp", "prv_key_temp"), KEY_PAIRS, ids=[MECHANISM_LOOKUP_EXT[k[0]][0] for k in KEY_PAIRS]) - def test_generate_key_pair(self, key_type, pub_key_temp, prv_key_temp): + def test_generate_key_pair(self, key_type, pub_key_temp, prv_key_temp, valid_mechanisms): """ Test generation of key pairs for asym. crypto systems :param key_type: key generation mechanism @@ -131,8 +134,11 @@ def test_generate_key_pair(self, key_type, pub_key_temp, prv_key_temp): get_session_template(pub_key_temp), get_session_template(prv_key_temp)) try: - self.verify_ret(ret, CKR_OK) - self.verify_key_len(pub_key, prv_key) + if key_type not in valid_mechanisms: + self.verify_ret(ret, CKR_MECHANISM_INVALID) + else: + self.verify_ret(ret, CKR_OK) + self.verify_key_len(pub_key, prv_key) finally: c_destroy_object(self.h_session, prv_key) c_destroy_object(self.h_session, pub_key) @@ -161,12 +167,14 @@ def test_generate_ecdsa_key_pairs(self, curve_type): @pytest.mark.parametrize("d_type", list(ALL_DERIVES.keys()), ids=list(ALL_DERIVES.values())) @pytest.mark.parametrize("key_type", list(DERIVE_KEYS.keys()), ids=list(DERIVE_KEYS.values())) - def test_derive_key(self, key_type, d_type): + def test_derive_key(self, key_type, d_type, valid_mechanisms): """ Test derive key for using parametrized hash :param key_type: Key-gen mechanism :param d_type: Hash mech """ + if key_type not in valid_mechanisms: + pytest.skip("Not a valid mechanism on this product") key_template = get_session_template(get_default_key_template(key_type)) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) mech = NullMech(d_type).to_c_mech() @@ -188,13 +196,15 @@ def test_derive_key(self, key_type, d_type): @pytest.mark.parametrize("d_type", list(DRV_TOO_LONG.keys()), ids=list(DRV_TOO_LONG.values())) @pytest.mark.parametrize("key_type", list(TOO_LONG_KEY.keys()), ids=list(TOO_LONG_KEY.values())) - def test_too_long_length_derives(self, key_type, d_type): + def test_too_long_length_derives(self, key_type, d_type, valid_mechanisms): """ Verify that trying to derive a key that is too long for the given derivation function will return CKR_KEY_SIZE_RANGE :param key_type: :param d_type: """ + if key_type not in valid_mechanisms: + pytest.skip("Not a valid mechanism on this product") key_template = get_session_template(get_default_key_template(key_type)) h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) mech = NullMech(d_type).to_c_mech() @@ -215,13 +225,15 @@ def test_too_long_length_derives(self, key_type, d_type): @pytest.mark.parametrize("d_type", list(DERIVE_PARAMS.keys()), ids=list(DERIVE_PARAMS.values())) @pytest.mark.parametrize("key_type", list(TOO_LONG_KEY.keys()), ids=list(TOO_LONG_KEY.values())) - def test_long_length_derive_key(self, key_type, d_type): + def test_long_length_derive_key(self, key_type, d_type, valid_mechanisms): """ Test deriving a key :param key_type: key generation mechanism :param d_type: derive mechanism """ key_template = get_session_template(get_default_key_template(key_type)) + if key_type not in valid_mechanisms: + pytest.skip("Not a valid mechanism on this product") h_base_key = c_generate_key_ex(self.h_session, key_type, key_template) mech = NullMech(d_type).to_c_mech() @@ -299,7 +311,7 @@ def test_x9_key_derive(self, auth_session, curve_type): derived_key2, cipher_data, mechanism=CKM_DES_ECB) - assert DATA == restored_text.rstrip('\x00') + assert DATA == restored_text.rstrip(b'\x00') finally: for key in (pub_key1, prv_key1, pub_key2, prv_key2, derived_key1, derived_key2): if key: diff --git a/tests/unittests/test_attr_conversions.py b/tests/unittests/test_attr_conversions.py index 1891f02..2149407 100644 --- a/tests/unittests/test_attr_conversions.py +++ b/tests/unittests/test_attr_conversions.py @@ -228,6 +228,24 @@ def test_to_byte_array(self, list_val): py_bytes = self.reverse_case(pointer, leng, to_byte_array) assert py_bytes == hexlify(b_array) + @pytest.mark.parametrize("test_val", + [b"deadbeef", + b"\xde\xad\xbe\xef", + b"0xdeadbeef"], + ids=["plain", + "escaped", + "prefixed"]) + def test_to_byte_array_from_hex(self, test_val): + """ + to_byte_array() with param: + :param list_val: list of ints in range (0-255), convert to bytearray + """ + pointer, leng = to_byte_array(test_val) + self.verify_c_type(pointer, leng) + + py_bytes = self.reverse_case(pointer, leng, to_byte_array) + assert py_bytes == b"deadbeef" + @given(integers(min_value=0)) def test_to_byte_array_int(self, int_val): """ @@ -301,7 +319,7 @@ def test_to_byte_array_fail_str(self, txt_val): to_byte_array() with incompatible param: :param txt_val: random text -TypeError """ - self.force_fail(txt_val, to_byte_array, ValueError) + self.force_fail(txt_val, to_byte_array, (ValueError, TypeError)) @given(integers(min_value=0)) def test_to_byte_array_hexstring(self, int_val): @@ -309,7 +327,7 @@ def test_to_byte_array_hexstring(self, int_val): to_byte_array() with param: :param int_val: random integer to be converted to hex string. """ - hex_string = hex(int_val).replace("0x", "").replace("L", "") + hex_string = b(hex(int_val).replace("0x", "").replace("L", "")) pointer, leng = to_byte_array(hex_string) self.verify_c_type(pointer, leng) From ac768b20cd71b8c890023948e7b811f0a39ae863 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 23 Jun 2017 11:08:59 -0400 Subject: [PATCH 085/109] LA-2500 Move mechanisms into a package * Created mechanism package * Split out mechanisms based on type * Improved documentation for mechanisms, including example how to create a new mechanism. * Improved documentation for _ex functions. * Added AES_CTR Mechanism & test case Change-Id: Ie0e5eb5ce6ed553c9a8d81e1599912a3f4e8eafe --- docs/mechanisms.rst | 43 ++ pycryptoki/exceptions.py | 30 +- pycryptoki/mechanism.py | 744 ----------------------- pycryptoki/mechanism/__init__.py | 201 ++++++ pycryptoki/mechanism/aes.py | 197 ++++++ pycryptoki/mechanism/dh.py | 40 ++ pycryptoki/mechanism/generic.py | 117 ++++ pycryptoki/mechanism/helpers.py | 261 ++++++++ pycryptoki/mechanism/rc.py | 107 ++++ pycryptoki/mechanism/rsa.py | 65 ++ pycryptoki/sign_verify.py | 2 +- setup.py | 3 +- tests/functional/test_encrypt_decrypt.py | 7 +- 13 files changed, 1063 insertions(+), 754 deletions(-) delete mode 100755 pycryptoki/mechanism.py create mode 100644 pycryptoki/mechanism/__init__.py create mode 100644 pycryptoki/mechanism/aes.py create mode 100644 pycryptoki/mechanism/dh.py create mode 100644 pycryptoki/mechanism/generic.py create mode 100755 pycryptoki/mechanism/helpers.py create mode 100644 pycryptoki/mechanism/rc.py create mode 100644 pycryptoki/mechanism/rsa.py diff --git a/docs/mechanisms.rst b/docs/mechanisms.rst index 4917e31..ea2d07e 100644 --- a/docs/mechanisms.rst +++ b/docs/mechanisms.rst @@ -5,3 +5,46 @@ Mechanisms :members: :undoc-members: :show-inheritance: + + +Helpers +======= + +.. automodule:: pycryptoki.mechanism.helpers + :members: + :undoc-members: + :show-inheritance: + + +AES Mechanisms +============== + +.. automodule:: pycryptoki.mechanism.aes + :members: + :undoc-members: + :show-inheritance: + +Generic Mechanisms +================== + +.. automodule:: pycryptoki.mechanism.generic + :members: + :undoc-members: + :show-inheritance: + +RC Mechanisms +============= + +.. automodule:: pycryptoki.mechanism.rc + :members: + :undoc-members: + :show-inheritance: + +RSA Mechanisms +============== + +.. automodule:: pycryptoki.mechanism.rsa + :members: + :undoc-members: + :show-inheritance: + diff --git a/pycryptoki/exceptions.py b/pycryptoki/exceptions.py index d462182..2bab122 100644 --- a/pycryptoki/exceptions.py +++ b/pycryptoki/exceptions.py @@ -4,7 +4,7 @@ import inspect from functools import wraps -from six import integer_types, string_types +from six import integer_types from .defines import CKR_OK from .lookup_dicts import ret_vals_dictionary, ATTR_NAME_LOOKUP @@ -44,8 +44,7 @@ def make_error_handle_function(luna_function): This should therefore make for shorter test cases - :param luna_function: - + :param luna_function: Function object to wrap. """ @wraps(luna_function) @@ -78,6 +77,25 @@ def luna_function_exception_handle(*args, **kwargs): check_luna_exception(ret, luna_function, args, kwargs) return return_data + luna_function_exception_handle.__doc__ = """Executes :py:func:`{}`, and checks the +retcode; raising an exception if the return code is not CKR_OK. + + .. note:: By default, this will not return the return code if the function returns additional + data. + + Example:: + + retcode, key_handle = c_generate_key(...) + #vs + key_handle = c_generate_key_ex(...) + + If the function *only* returns the retcode, then that will still be returned:: + + retcode = c_seed_random(...) + retcode = c_seed_random_ex(...) + + + """.format(luna_function.__name__) return luna_function_exception_handle @@ -146,8 +164,8 @@ def __str__(self): "\n\tError: {err_string}" "\n\tError Code: {err_code}" "\n\tArguments:\n{args}").format(func_name=self.function_name, - err_string=self.error_string, - err_code=hex(self.error_code), - args=self.arguments) + err_string=self.error_string, + err_code=hex(self.error_code), + args=self.arguments) return data diff --git a/pycryptoki/mechanism.py b/pycryptoki/mechanism.py deleted file mode 100755 index ad1d5f1..0000000 --- a/pycryptoki/mechanism.py +++ /dev/null @@ -1,744 +0,0 @@ -""" -Mechanism-related utilities -""" - -import logging -import types -from ctypes import c_void_p, cast, pointer, POINTER, sizeof, create_string_buffer, c_char - -from six import integer_types - -from . import cryptoki -from .attributes import to_byte_array, to_char_array, CONVERSIONS -from .cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ - CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_RC2_CBC_PARAMS, \ - CK_RC5_PARAMS, CK_RC5_CBC_PARAMS, CK_MECHANISM_TYPE, CK_AES_XTS_PARAMS, \ - CK_RSA_PKCS_OAEP_PARAMS, \ - CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS, CK_KEY_DERIVATION_STRING_DATA, c_ubyte, \ - CK_AES_CBC_ENCRYPT_DATA_PARAMS, CK_ECDH1_DERIVE_PARAMS -from .defines import * -from .exceptions import LunaException - -LOG = logging.getLogger(__name__) - -CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism': CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, - 'ulType': CK_CRYPTOKI_ELEMENT, - 'ulHandle': 5, - 'ulDeleteAfterExtract': 0, - 'pBuffer': 0, - 'pulBufferLen': 0, - 'ulStorage': CK_STORAGE_HOST, - 'pedId': 0, - 'pbFileName': 0, - 'ctxID': 3 - } - -CK_AES_CBC_PAD_INSERT_PARAMS_TEMP = {'mechanism': CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, - 'ulType': CK_CRYPTOKI_ELEMENT, - 'ulContainerState': 0, - 'pBuffer': 0, - 'pulBufferLen': 0, - 'ulStorageType': CK_STORAGE_HOST, - 'pulType': 0, - 'pulHandle': 0, - 'ctxID': 3, - 'pedID': 3, - 'pbFileName': 0, - 'ulStorage': CK_STORAGE_HOST, - } - -supported_parameters = {'CK_AES_CBC_PAD_EXTRACT_PARAMS': CK_AES_CBC_PAD_EXTRACT_PARAMS, - 'CK_AES_CBC_PAD_INSERT_PARAMS': CK_AES_CBC_PAD_INSERT_PARAMS} - - -class MechanismException(Exception): - """ - Mechanism-related exceptions - """ - - pass - - -class Mechanism(object): - """ - Base class for pycryptoki mechanisms. - Performs checks for missing parameters w/ created mechs, and - creates the base Mechanism Struct for conversion to ctypes. - """ - REQUIRED_PARAMS = [] - - def __new__(cls, mech_type="UNKNOWN", params=None): - """ - Factory for mechs. - """ - - if cls == Mechanism: - mech_cls = MECH_LOOKUP.get(mech_type, NullMech) - return super(Mechanism, cls).__new__(mech_cls) - else: - return super(Mechanism, cls).__new__(cls) - - def __init__(self, mech_type="UNKNOWN", params=None): - self.mech_type = mech_type - if params is None: - params = {} - self.params = params - - missing_params = [] - for req in self.REQUIRED_PARAMS: - if req not in params: - missing_params.append(req) - if missing_params: - raise MechanismException("Cannot create {}, " - "Missing required parameters:\n\t" - "{}".format(self.__class__, - "\n\t".join(missing_params))) - - def to_c_mech(self): - """ - Create the Mechanism structure & set the mech type to the passed-in flavor. - - :return: `:class:`~pycryptoki.cryptoki.CK_MECHANISM`` - """ - self.mech = CK_MECHANISM() - self.mech.mechanism = CK_MECHANISM_TYPE(self.mech_type) - return self.mech - - -class IvMechanism(Mechanism): - """ - Mech class for flavors that require an IV set in the mechanism. - Will default to `[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38]` if no IV is passed in - """ - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(IvMechanism, self).to_c_mech() - if self.params is None or 'iv' not in self.params: - self.params['iv'] = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] - LOG.warning("Using static IVs can be insecure! ") - if len(self.params['iv']) == 0: - LOG.debug("Setting IV to NULL (using internal)") - iv_ba = None - iv_len = 0 - else: - iv_ba, iv_len = to_byte_array(self.params['iv']) - self.mech.pParameter = iv_ba - self.mech.usParameterLen = iv_len - return self.mech - - -class Iv16Mechanism(Mechanism): - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(Iv16Mechanism, self).to_c_mech() - if self.params is None or 'iv' not in self.params: - self.params['iv'] = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] - LOG.warning("Using static IVs can be insecure! ") - if len(self.params['iv']) == 0: - LOG.debug("Setting IV to NULL (using internal)") - iv_ba = None - iv_len = 0 - else: - iv_ba, iv_len = to_byte_array(self.params['iv']) - self.mech.pParameter = iv_ba - self.mech.usParameterLen = iv_len - return self.mech - - -class RC2Mechanism(Mechanism): - REQUIRED_PARAMS = ['usEffectiveBits'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(RC2Mechanism, self).to_c_mech() - effective_bits = CK_ULONG(self.params['usEffectiveBits']) - self.mech.pParameter = cast(pointer(effective_bits), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(effective_bits)) - return self.mech - - -class RC2CBCMechanism(Mechanism): - REQUIRED_PARAMS = ['usEffectiveBits', 'iv'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(RC2CBCMechanism, self).to_c_mech() - effective_bits = self.params['usEffectiveBits'] - cbc_params = CK_RC2_CBC_PARAMS() - cbc_params.usEffectiveBits = CK_ULONG(effective_bits) - cbc_params.iv = (CK_BYTE * 8)(*self.params['iv']) - self.mech.pParameter = cast(pointer(cbc_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(cbc_params)) - return self.mech - - -class RC5Mechanism(Mechanism): - REQUIRED_PARAMS = ['ulWordsize', 'ulRounds'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(RC5Mechanism, self).to_c_mech() - rc5_params = CK_RC5_PARAMS() - rc5_params.ulWordsize = CK_ULONG(self.params['ulWordsize']) - rc5_params.ulRounds = CK_ULONG(self.params['ulRounds']) - self.mech.pParameter = cast(pointer(rc5_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(rc5_params)) - return self.mech - - -class RC5CBCMechanism(Mechanism): - REQUIRED_PARAMS = ['ulWordsize', 'ulRounds', 'iv'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(RC5CBCMechanism, self).to_c_mech() - rc5_params = CK_RC5_CBC_PARAMS() - rc5_params.ulWordsize = CK_ULONG(self.params['ulWordsize']) - rc5_params.ulRounds = CK_ULONG(self.params['ulRounds']) - iv, ivlen = to_byte_array(self.params['iv']) - rc5_params.pIv = cast(iv, CK_BYTE_PTR) - rc5_params.ulIvLen = ivlen - self.mech.pParameter = cast(pointer(rc5_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(rc5_params)) - return self.mech - - -class AESXTSMechanism(Mechanism): - REQUIRED_PARAMS = ['cb', 'hTweakKey'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(AESXTSMechanism, self).to_c_mech() - xts_params = CK_AES_XTS_PARAMS() - xts_params.cb = (CK_BYTE * 16)(*self.params['cb']) - xts_params.hTweakKey = CK_ULONG(self.params['hTweakKey']) - self.mech.pParameter = cast(pointer(xts_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(xts_params)) - return self.mech - - -class RSAPKCSOAEPMechanism(Mechanism): - REQUIRED_PARAMS = ['hashAlg', 'mgf'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(RSAPKCSOAEPMechanism, self).to_c_mech() - oaep_params = CK_RSA_PKCS_OAEP_PARAMS() - oaep_params.hashAlg = CK_ULONG(self.params['hashAlg']) - oaep_params.mgf = CK_ULONG(self.params['mgf']) - # Note: According to - # https://www.cryptsoft.com/pkcs11doc/v220 - # /group__SEC__12__1__7__PKCS____1__RSA__OAEP__MECHANISM__PARAMETERS.html - # there is only one encoding parameter source. - oaep_params.source = CK_ULONG(CKZ_DATA_SPECIFIED) - data, data_len = to_byte_array(self.params.get('sourceData', '')) - oaep_params.pSourceData = data - oaep_params.ulSourceDataLen = data_len - - self.mech.pParameter = cast(pointer(oaep_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(oaep_params)) - return self.mech - - -class RSAPKCSPSSMechanism(Mechanism): - REQUIRED_PARAMS = ['hashAlg', 'mgf'] - - def to_c_mech(self): - """ - Uses default salt length of 8. - Can be overridden w/ a parameter though. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(RSAPKCSPSSMechanism, self).to_c_mech() - c_params = CK_RSA_PKCS_PSS_PARAMS() - c_params.hashAlg = CK_ULONG(self.params['hashAlg']) - c_params.mgf = CK_ULONG(self.params['mgf']) - c_params.usSaltLen = CK_ULONG(self.params.get('usSaltLen', 8)) - self.mech.pParameter = cast(pointer(c_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(c_params)) - return self.mech - - -class AESGCMMechanism(Mechanism): - REQUIRED_PARAMS = ['iv', 'AAD', 'ulTagBits'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(AESGCMMechanism, self).to_c_mech() - gcm_params = CK_AES_GCM_PARAMS() - if len(self.params['iv']) == 0: - LOG.debug("Setting IV to NULL (using internal)") - iv_ba = None - iv_len = 0 - else: - iv_ba, iv_len = to_byte_array(self.params['iv']) - gcm_params.pIv = cast(iv_ba, CK_BYTE_PTR) - gcm_params.ulIvLen = iv_len - # Assuming 8 bits per entry in IV. - gcm_params.ulIvBits = CK_ULONG(len(self.params['iv']) * 8) - aad, aadlen = to_char_array(self.params['AAD']) - gcm_params.pAAD = cast(aad, CK_BYTE_PTR) - gcm_params.ulAADLen = aadlen - gcm_params.ulTagBits = CK_ULONG(self.params['ulTagBits']) - self.mech.pParameter = cast(pointer(gcm_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(gcm_params)) - return self.mech - - -class AESECBEncryptDataMechanism(Mechanism): - """ - AES mechanism for deriving keys from encrypted data. - """ - REQUIRED_PARAMS = ['data'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(AESECBEncryptDataMechanism, self).to_c_mech() - # from https://www.cryptsoft.com/pkcs11doc/v220/group__SEC__12__14__2__MECHANISM__PARAMETERS.html - # Note: data should be a multiple of 16 long. - params = CK_KEY_DERIVATION_STRING_DATA() - pdata, data_len = to_byte_array(self.params['data']) - params.pData = pdata - params.ulLen = CK_ULONG(data_len) - self.mech.pParameter = cast(pointer(params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(params)) - return self.mech - - -class AESCBCEncryptDataMechanism(Mechanism): - """ - AES CBC mechanism for deriving keys from encrypted data. - """ - REQUIRED_PARAMS = ['iv', 'data'] - - def to_c_mech(self): - """ - Convert extra parameters to ctypes, then build out the mechanism. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(AESCBCEncryptDataMechanism, self).to_c_mech() - # https://www.cryptsoft.com/pkcs11doc/v220/group__SEC__12__14__KEY__DERIVATION__BY__DATA__ENCRYPTION______DES______AES.html#CKM_AES_CBC_ENCRYPT_DATA - # Note: data should be a multiple of 16 long. - params = CK_AES_CBC_ENCRYPT_DATA_PARAMS() - pdata, data_len = to_byte_array(self.params['data']) - # Note: IV should always be a length of 8. - p_iv, _ = to_byte_array(self.params['iv']) - params.pData = pdata - params.ulLen = CK_ULONG(data_len) - params.iv = p_iv - self.mech.pParameter = cast(pointer(params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(params)) - return self.mech - - -class ConcatenationDeriveMechanism(Mechanism): - """ - Mechanism class for key derivations. This will take in a second key handle in the parameters, - and use it in the resulting Structure. - - .. warning :: This mechanism is disabled in later versions of PCKS11. - - """ - REQUIRED_PARAMS = ['h_second_key'] - - def to_c_mech(self): - """ - Add in a pointer to the second key in the resulting mech structure. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(ConcatenationDeriveMechanism, self).to_c_mech() - c_second_key = CK_ULONG(self.params['h_second_key']) - self.mech.pParameter = cast(pointer(c_second_key), c_void_p) - self.mech.usParameterLen = sizeof(c_second_key) - return self.mech - - -class StringDataDerivationMechanism(Mechanism): - """ - Mechanism class for key derivation using passed in string data. - """ - REQUIRED_PARAMS = ['data'] - - def to_c_mech(self): - """ - Convert data to bytearray, then use in the resulting mech structure. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(StringDataDerivationMechanism, self).to_c_mech() - parameters = CK_KEY_DERIVATION_STRING_DATA - data, length = to_byte_array(self.params['data']) - parameters.pData = cast(data, POINTER(c_ubyte)) - parameters.ulLen = length - self.mech.pParameter = parameters - self.mech.usParameterLen = sizeof(parameters) - return self.mech - - -class ECDH1DeriveMechanism(Mechanism): - """ - ECDH1-specific mechanism - """ - REQUIRED_PARAMS = ["kdf", "sharedData", "publicData"] - - def to_c_mech(self): - """ - Create the Param structure, then convert the data into byte arrays. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(ECDH1DeriveMechanism, self).to_c_mech() - params = CK_ECDH1_DERIVE_PARAMS() - params.kdf = self.params['kdf'] - if self.params['sharedData'] is None: - shared_data = None - shared_data_len = 0 - else: - shared_data, shared_data_len = to_byte_array(self.params['sharedData']) - params.pSharedData = cast(shared_data, CK_BYTE_PTR) - params.ulSharedDataLen = shared_data_len - public_data, public_data_len = to_byte_array(self.params['publicData']) - params.pPublicData = cast(public_data, CK_BYTE_PTR) - params.ulPublicDataLen = public_data_len - self.mech.pParameter = cast(pointer(params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(params)) - return self.mech - - - -# TODO: xordf mech - -class NullMech(Mechanism): - """ - Class that creates a mechanism from a flavor with null parameters. - Used mostly for signing mechanisms that really don't need anything else. - """ - - def to_c_mech(self): - """ - Simply set the pParameter to null pointer. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(NullMech, self).to_c_mech() - self.mech.pParameter = c_void_p(0) - self.mech.usParameterLen = CK_ULONG(0) - return self.mech - - -class AutoMech(Mechanism): - """ - An attempt to examine underlying C Struct and fill in the appropriate fields, - making some assumptions about the data. This works best with parameter structs that only - have CK_ULONGs within them (though there is a best-effort attempt to handle arrays). - - .. warning : Do not use this if the mechanism is defined! - """ - - def to_c_mech(self): - """ - Attempt to handle generic mechanisms by introspection of the - structure. - - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` - """ - super(AutoMech, self).to_c_mech() - c_params_type = getattr(cryptoki, - self.params.get('params_name', "UNKNOWN"), - None) - if not c_params_type: - raise MechanismException("Failed to find a suitable " - "Ctypes Parameter Struct for type {}. " - "Make sure to set 'params_name' in the arguments!".format( - repr(self.mech_type))) - - fields = c_params_type._fields_ - c_params = c_params_type() - for name, c_type in fields: - # Check if it's an array. - if hasattr(c_type, '_length_'): - c_type = c_type._type_ - if c_type not in CONVERSIONS: - raise LunaException("Cannot convert to c_type: {}".format(c_type)) - ptr, length = CONVERSIONS[c_type](self.params[name]) - setattr(c_params, name, cast(ptr, POINTER(c_type))) - # Otherwise, do a direct conversion. - else: - # c_type = c_type._type_ - setattr(c_params, name, c_type(self.params[name])) - self.mech.pParameter = cast(pointer(c_params), c_void_p) - self.mech.usParameterLen = CK_ULONG(sizeof(c_params)) - return self.mech - - -MECH_LOOKUP = { - # Iv - CKM_DES_CBC: IvMechanism, - CKM_DES3_CBC: IvMechanism, - CKM_CAST3_CBC: IvMechanism, - CKM_CAST5_CBC: IvMechanism, - CKM_DES_CBC_PAD: IvMechanism, - CKM_DES3_CBC_PAD: IvMechanism, - CKM_DES3_CBC_PAD_IPSEC: IvMechanism, - CKM_CAST3_CBC_PAD: IvMechanism, - CKM_CAST5_CBC_PAD: IvMechanism, - CKM_DES_CFB8: IvMechanism, - CKM_DES_CFB64: IvMechanism, - CKM_DES_OFB64: IvMechanism, - CKM_AES_KW: IvMechanism, - CKM_AES_KWP: IvMechanism, - CKM_AES_CFB8: IvMechanism, - CKM_AES_CFB128: IvMechanism, - CKM_AES_OFB: IvMechanism, - CKM_ARIA_CFB8: IvMechanism, - CKM_ARIA_CFB128: IvMechanism, - CKM_ARIA_OFB: IvMechanism, - # Iv16 - CKM_SEED_CBC: Iv16Mechanism, - CKM_SEED_CBC_PAD: Iv16Mechanism, - CKM_AES_CBC: Iv16Mechanism, - CKM_AES_CBC_PAD: Iv16Mechanism, - CKM_AES_CBC_PAD_IPSEC: Iv16Mechanism, - CKM_ARIA_ECB: Iv16Mechanism, - CKM_ARIA_CBC: Iv16Mechanism, - CKM_ARIA_CBC_PAD: Iv16Mechanism, - # Others - CKM_RC2_ECB: RC2Mechanism, - CKM_RC2_MAC: RC2Mechanism, - CKM_RC2_CBC: RC2CBCMechanism, - CKM_RC2_CBC_PAD: RC2CBCMechanism, - CKM_RC5_CBC: RC5CBCMechanism, - CKM_RC5_ECB: RC5Mechanism, - - CKM_AES_XTS: AESXTSMechanism, - (CKM_VENDOR_DEFINED + 0x11c): AESGCMMechanism, # Backwards compatibility w/ older Lunas. - CKM_AES_GCM: AESGCMMechanism, - - CKM_RSA_PKCS_OAEP: RSAPKCSOAEPMechanism, - - CKM_RSA_PKCS_PSS: RSAPKCSPSSMechanism, - CKM_SHA1_RSA_PKCS_PSS: RSAPKCSPSSMechanism, - CKM_SHA224_RSA_PKCS_PSS: RSAPKCSPSSMechanism, - CKM_SHA256_RSA_PKCS_PSS: RSAPKCSPSSMechanism, - CKM_SHA384_RSA_PKCS_PSS: RSAPKCSPSSMechanism, - CKM_SHA512_RSA_PKCS_PSS: RSAPKCSPSSMechanism, - - CKM_DES_ECB: NullMech, - - CKM_AES_CBC_ENCRYPT_DATA: AESCBCEncryptDataMechanism, - CKM_AES_ECB_ENCRYPT_DATA: AESECBEncryptDataMechanism, - - CKM_CONCATENATE_BASE_AND_KEY: ConcatenationDeriveMechanism, - CKM_CONCATENATE_BASE_AND_DATA: StringDataDerivationMechanism, - CKM_XOR_BASE_AND_DATA: StringDataDerivationMechanism, - CKM_CONCATENATE_DATA_AND_BASE: StringDataDerivationMechanism, - - - CKM_ECDH1_DERIVE: ECDH1DeriveMechanism, -} - - -def get_c_struct_from_mechanism(python_dictionary, params_type_string): - """Gets a c struct from a python dictionary representing that struct - - :param python_dictionary: The python dictionary representing the C struct, - see :class:`CK_AES_CBC_PAD_EXTRACT_PARAMS` for an example - :param params_type_string: A string representing the parameter struct. - ex. for :class:`~pycryptoki.cryptoki.CK_AES_CBC_PAD_EXTRACT_PARAMS` use the - string ``CK_AES_CBC_PAD_EXTRACT_PARAMS`` - :returns: A C struct - - """ - params_type = supported_parameters[params_type_string] - params = params_type() - mech = CK_MECHANISM() - mech.mechanism = python_dictionary['mechanism'] - mech.pParameter = cast(pointer(params), c_void_p) - mech.usParameterLen = CK_ULONG(sizeof(params_type)) - - # Automatically handle the simpler fields - for entry in params_type._fields_: - key_name = entry[0] - key_type = entry[1] - - if key_type == CK_ULONG: - setattr(params, key_name, CK_ULONG(python_dictionary[key_name])) - elif key_type == CK_ULONG_PTR: - setattr(params, key_name, pointer(CK_ULONG(python_dictionary[key_name]))) - else: - continue - - # Explicitly handle the more complex fields - if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: - if len(python_dictionary['pBuffer']) == 0: - params.pBuffer = None - else: - params.pBuffer = (CK_BYTE * len(python_dictionary['pBuffer']))() - # params.pbFileName = 0 #TODO convert byte pointer to serializable type - pass - elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: - # params.pbFileName = TODO - params.pBuffer = cast(create_string_buffer(python_dictionary['pBuffer']), CK_BYTE_PTR) - params.ulBufferLen = len(python_dictionary['pBuffer']) - pass - else: - raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") - - return mech - - -def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): - """Gets a python dictionary from a c mechanism's struct for serialization - and easier test case writing - - :param c_mechanism: The c mechanism to convert to a python dictionary - :param params_type_string: A string representing the parameter struct. - ex. for :class:`~pycryptoki.cryptoki.CK_AES_CBC_PAD_EXTRACT_PARAMS` use the - string ``CK_AES_CBC_PAD_EXTRACT_PARAMS`` - :returns: A python dictionary representing the c struct - """ - python_dictionary = {} - python_dictionary['mechanism'] = c_mechanism.mechanism - - params_type = supported_parameters[params_type_string] - params_struct = cast(c_mechanism.pParameter, POINTER(params_type)).contents - - # Automatically handle the simpler fields - for entry in params_type._fields_: - key_name = entry[0] - key_type = entry[1] - - if key_type == CK_ULONG: - python_dictionary[key_name] = getattr(params_struct, key_name) - elif key_type == CK_ULONG_PTR: - python_dictionary[key_name] = getattr(params_struct, key_name).contents.value - else: - continue - - # Explicitly handle the more complex fields - if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: - bufferLength = params_struct.pulBufferLen.contents.value - if params_struct.pBuffer is None: - bufferString = None - else: - char_p_string = cast(params_struct.pBuffer, POINTER(c_char)) - if char_p_string is not None: - bufferString = char_p_string[0:bufferLength] - else: - bufferString = None - python_dictionary['pBuffer'] = bufferString - python_dictionary['pbFileName'] = 0 # TODO - elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: - python_dictionary['pbFileName'] = 0 # TODO - python_dictionary['pBuffer'] = 0 # TODO - else: - raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") - - return python_dictionary - - -def parse_mechanism(mechanism_param): - """ - Designed for use with any function call that takes in a mechanism, - this will handle a mechanism parameter that is one of the following: - - 1. ``CKM_`` integer constant -- will create a :class:`~pycryptoki.cryptoki.CK_MECHANISM` - with only mech_type set. - - .. code-block :: python - - parse_mechanism(CKM_RSA_PKCS) - # Results in: - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(CKM_RSA_PKCS) - mech.pParameter = None - mech.usParameterLen = 0 - - 2. Dictionary with ``mech_type`` as a mandatory key, and ``params`` as an optional key. This - will be passed into the :class:`Mechanism` class for conversion to - a :class:`~pycryptoki.cryptoki.CK_MECHANISM`. - - .. code-block :: python - - parse_mechanism({'mech_type': CKM_AES_CBC, - 'params': {'iv': list(range(8))}}) - # Results in: - mech = CK_MECHANISM() - mech.mechanism = CK_MECHANISM_TYPE(CKM_AES_CBC) - iv_ba, iv_len = to_byte_array(list(range(8))) - mech.pParameter = iv_ba - mech.usParameterLen = iv_len - - 3. :class:`~pycryptoki.cryptoki.CK_MECHANISM` struct -- passed directly into the raw C Call. - 4. Mechanism class -- will call to_c_mech() on the class, and use the results. - - .. warning:: If you're using this with rpyc, you need to make sure the call `to_c_mech` occurs - on the *server* (the machine with the HSM)! If you pass in a :py:class:`Mechanism` class - that was created on the client, the resulting call into `to_c_mech()` will *also* be on - the client side! - - .. note:: You can look at ``REQUIRED_PARAMS`` on each mechanism class to see what parameters are - required. - - :param mechanism_param: Parameter to convert to a C Mechanism. - :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` struct. - """ - - if isinstance(mechanism_param, dict): - mech = Mechanism(**mechanism_param).to_c_mech() - elif isinstance(mechanism_param, CK_MECHANISM): - mech = mechanism_param - elif isinstance(mechanism_param, integer_types): - mech = Mechanism(mech_type=mechanism_param).to_c_mech() - elif isinstance(mechanism_param, Mechanism): - mech = mechanism_param.to_c_mech() - else: - raise TypeError("Invalid mechanism type {}, should be CK_MECHANISM, dictionary with " - "kwargs to be passed to `Mechanism`, integer constant, or a " - "Mechanism() class.".format(type(mechanism_param))) - - return mech diff --git a/pycryptoki/mechanism/__init__.py b/pycryptoki/mechanism/__init__.py new file mode 100644 index 0000000..08ce1c7 --- /dev/null +++ b/pycryptoki/mechanism/__init__.py @@ -0,0 +1,201 @@ +""" +Conversions for pure-python dictionaries to C struct mechanisms. + +To implement a new Mechanism: + + 1. Create a new mechanism class, deriving from + :py:class:`~pycryptoki.mechanism.helpers.Mechanism` + 2. Set ``REQUIRED_PARAMS`` as a class variable. ``REQUIRED_PARAMS`` should be a list of strings, + defining required parameter keys. + + .. code-block:: python + + class IvMechanism(Mechanism): + REQUIRED_PARAMS = ['iv'] + + 3. Override ``to_c_mech()`` on the new mechanism class. This function can access ``self.params`` + to get passed-in parameters, and should create the C parameter struct required by the + mechanism. This should also return ``self.mech`` (which is a ``CK_MECHANISM`` struct). + + .. code-block:: python + :caption: Simple Example + + class IvMechanism(Mechanism): + REQUIRED_PARAMS = ['iv'] + + def to_c_mech(self): + super(IvMechanism, self).to_c_mech() + if len(self.params['iv']) == 0: + LOG.debug("Setting IV to NULL (using internal)") + iv_ba = None + iv_len = 0 + else: + iv_ba, iv_len = to_byte_array(self.params['iv']) + self.mech.pParameter = iv_ba + self.mech.usParameterLen = iv_len + return self.mech + + + .. code-block:: python + :caption: Example with a PARAMS struct + + class AESXTSMechanism(Mechanism): + REQUIRED_PARAMS = ['cb', 'hTweakKey'] + + def to_c_mech(self): + super(AESXTSMechanism, self).to_c_mech() + xts_params = CK_AES_XTS_PARAMS() + xts_params.cb = (CK_BYTE * 16)(*self.params['cb']) + xts_params.hTweakKey = CK_ULONG(self.params['hTweakKey']) + self.mech.pParameter = cast(pointer(xts_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(xts_params)) + return self.mech + +""" +from .helpers import (get_c_struct_from_mechanism, + get_python_dict_from_c_mechanism, + parse_mechanism, + Mechanism, + MechanismException) +from .aes import (AESECBEncryptDataMechanism, + AESCBCEncryptDataMechanism, + AESGCMMechanism, + AESXTSMechanism, + Iv16Mechanism, + IvMechanism, AESCTRMechanism) +from .dh import ECDH1DeriveMechanism +from .generic import (ConcatenationDeriveMechanism, + StringDataDerivationMechanism, + NullMech, + AutoMech) +from .rc import (RC2CBCMechanism, + RC2Mechanism, + RC5CBCMechanism, + RC5Mechanism) +from .rsa import (RSAPKCSOAEPMechanism, + RSAPKCSPSSMechanism) +from ..defines import (CKM_DES_CBC, + CKM_DES3_CBC, + CKM_CAST3_CBC, + CKM_CAST5_CBC, + CKM_DES_CBC_PAD, + CKM_DES3_CBC_PAD, + CKM_DES3_CBC_PAD_IPSEC, + CKM_CAST3_CBC_PAD, + CKM_CAST5_CBC_PAD, + CKM_DES_CFB8, + CKM_DES_CFB64, + CKM_DES_OFB64, + CKM_AES_KW, + CKM_AES_KWP, + CKM_AES_CFB8, + CKM_AES_CFB128, + CKM_AES_OFB, + CKM_ARIA_CFB8, + CKM_ARIA_CFB128, + CKM_ARIA_OFB, + CKM_SEED_CBC, + CKM_SEED_CBC_PAD, + CKM_AES_CBC, + CKM_AES_CBC_PAD, + CKM_AES_CBC_PAD_IPSEC, + CKM_ARIA_ECB, + CKM_ARIA_CBC, + CKM_ARIA_CBC_PAD, + CKM_RC2_ECB, + CKM_RC2_MAC, + CKM_RC2_CBC, + CKM_RC2_CBC_PAD, + CKM_RC5_CBC, + CKM_RC5_ECB, + + CKM_AES_XTS, + CKM_VENDOR_DEFINED, + CKM_AES_GCM, + + CKM_RSA_PKCS_OAEP, + + CKM_RSA_PKCS_PSS, + CKM_SHA1_RSA_PKCS_PSS, + CKM_SHA224_RSA_PKCS_PSS, + CKM_SHA256_RSA_PKCS_PSS, + CKM_SHA384_RSA_PKCS_PSS, + CKM_SHA512_RSA_PKCS_PSS, + + CKM_DES_ECB, + + CKM_AES_CBC_ENCRYPT_DATA, + CKM_AES_ECB_ENCRYPT_DATA, + + CKM_CONCATENATE_BASE_AND_KEY, + CKM_CONCATENATE_BASE_AND_DATA, + CKM_XOR_BASE_AND_DATA, + CKM_CONCATENATE_DATA_AND_BASE, + + CKM_ECDH1_DERIVE, CKM_AES_CTR) + +MECH_LOOKUP = { + # Iv + CKM_DES_CBC: IvMechanism, + CKM_DES3_CBC: IvMechanism, + CKM_CAST3_CBC: IvMechanism, + CKM_CAST5_CBC: IvMechanism, + CKM_DES_CBC_PAD: IvMechanism, + CKM_DES3_CBC_PAD: IvMechanism, + CKM_DES3_CBC_PAD_IPSEC: IvMechanism, + CKM_CAST3_CBC_PAD: IvMechanism, + CKM_CAST5_CBC_PAD: IvMechanism, + CKM_DES_CFB8: IvMechanism, + CKM_DES_CFB64: IvMechanism, + CKM_DES_OFB64: IvMechanism, + CKM_AES_KW: IvMechanism, + CKM_AES_KWP: IvMechanism, + CKM_AES_CFB8: IvMechanism, + CKM_AES_CFB128: IvMechanism, + CKM_AES_OFB: IvMechanism, + CKM_AES_CTR: AESCTRMechanism, + CKM_ARIA_CFB8: IvMechanism, + CKM_ARIA_CFB128: IvMechanism, + CKM_ARIA_OFB: IvMechanism, + # Iv16 + CKM_SEED_CBC: Iv16Mechanism, + CKM_SEED_CBC_PAD: Iv16Mechanism, + CKM_AES_CBC: Iv16Mechanism, + CKM_AES_CBC_PAD: Iv16Mechanism, + CKM_AES_CBC_PAD_IPSEC: Iv16Mechanism, + CKM_ARIA_ECB: Iv16Mechanism, + CKM_ARIA_CBC: Iv16Mechanism, + CKM_ARIA_CBC_PAD: Iv16Mechanism, + # Others + CKM_RC2_ECB: RC2Mechanism, + CKM_RC2_MAC: RC2Mechanism, + CKM_RC2_CBC: RC2CBCMechanism, + CKM_RC2_CBC_PAD: RC2CBCMechanism, + CKM_RC5_CBC: RC5CBCMechanism, + CKM_RC5_ECB: RC5Mechanism, + + CKM_AES_XTS: AESXTSMechanism, + (CKM_VENDOR_DEFINED + 0x11c): AESGCMMechanism, # Backwards compatibility w/ older Lunas. + CKM_AES_GCM: AESGCMMechanism, + + CKM_RSA_PKCS_OAEP: RSAPKCSOAEPMechanism, + + CKM_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA1_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA224_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA256_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA384_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + CKM_SHA512_RSA_PKCS_PSS: RSAPKCSPSSMechanism, + + CKM_DES_ECB: NullMech, + + CKM_AES_CBC_ENCRYPT_DATA: AESCBCEncryptDataMechanism, + CKM_AES_ECB_ENCRYPT_DATA: AESECBEncryptDataMechanism, + + CKM_CONCATENATE_BASE_AND_KEY: ConcatenationDeriveMechanism, + CKM_CONCATENATE_BASE_AND_DATA: StringDataDerivationMechanism, + CKM_XOR_BASE_AND_DATA: StringDataDerivationMechanism, + CKM_CONCATENATE_DATA_AND_BASE: StringDataDerivationMechanism, + + CKM_ECDH1_DERIVE: ECDH1DeriveMechanism, +} diff --git a/pycryptoki/mechanism/aes.py b/pycryptoki/mechanism/aes.py new file mode 100644 index 0000000..0d2f3e7 --- /dev/null +++ b/pycryptoki/mechanism/aes.py @@ -0,0 +1,197 @@ +""" +AES-specific mechanism implementations. +""" +import logging +from ctypes import c_void_p, cast, pointer, sizeof + +from . import Mechanism +from ..attributes import to_byte_array, to_char_array +from ..cryptoki import CK_ULONG, CK_BYTE, CK_BYTE_PTR, CK_AES_XTS_PARAMS, \ + CK_AES_GCM_PARAMS, CK_KEY_DERIVATION_STRING_DATA, CK_AES_CBC_ENCRYPT_DATA_PARAMS, \ + CK_AES_CTR_PARAMS + +LOG = logging.getLogger(__name__) + + +class IvMechanism(Mechanism): + """ + Mech class for flavors that require an IV set in the mechanism. + Will default to `[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38]` if no IV is passed in + """ + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(IvMechanism, self).to_c_mech() + if self.params is None or 'iv' not in self.params: + self.params['iv'] = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] + LOG.warning("Using static IVs can be insecure! ") + if len(self.params['iv']) == 0: + LOG.debug("Setting IV to NULL (using internal)") + iv_ba = None + iv_len = 0 + else: + iv_ba, iv_len = to_byte_array(self.params['iv']) + self.mech.pParameter = iv_ba + self.mech.usParameterLen = iv_len + return self.mech + + +class Iv16Mechanism(Mechanism): + """ + Mech class for flavors that require an IV set in the mechanism. + Will default to `[1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]` if no IV is passed in + """ + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(Iv16Mechanism, self).to_c_mech() + if self.params is None or 'iv' not in self.params: + self.params['iv'] = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8] + LOG.warning("Using static IVs can be insecure! ") + if len(self.params['iv']) == 0: + LOG.debug("Setting IV to NULL (using internal)") + iv_ba = None + iv_len = 0 + else: + iv_ba, iv_len = to_byte_array(self.params['iv']) + self.mech.pParameter = iv_ba + self.mech.usParameterLen = iv_len + return self.mech + + +class AESXTSMechanism(Mechanism): + """ + Creates the AES-XTS specific param structure & converts python types to C types. + """ + REQUIRED_PARAMS = ['cb', 'hTweakKey'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AESXTSMechanism, self).to_c_mech() + xts_params = CK_AES_XTS_PARAMS() + xts_params.cb = (CK_BYTE * 16)(*self.params['cb']) + xts_params.hTweakKey = CK_ULONG(self.params['hTweakKey']) + self.mech.pParameter = cast(pointer(xts_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(xts_params)) + return self.mech + + +class AESGCMMechanism(Mechanism): + """ + Creates the AES-GCM specific param structure & converts python types to C types. + """ + REQUIRED_PARAMS = ['iv', 'AAD', 'ulTagBits'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AESGCMMechanism, self).to_c_mech() + gcm_params = CK_AES_GCM_PARAMS() + if len(self.params['iv']) == 0: + LOG.debug("Setting IV to NULL (using internal)") + iv_ba = None + iv_len = 0 + else: + iv_ba, iv_len = to_byte_array(self.params['iv']) + gcm_params.pIv = cast(iv_ba, CK_BYTE_PTR) + gcm_params.ulIvLen = iv_len + # Assuming 8 bits per entry in IV. + gcm_params.ulIvBits = CK_ULONG(len(self.params['iv']) * 8) + aad, aadlen = to_char_array(self.params['AAD']) + gcm_params.pAAD = cast(aad, CK_BYTE_PTR) + gcm_params.ulAADLen = aadlen + gcm_params.ulTagBits = CK_ULONG(self.params['ulTagBits']) + self.mech.pParameter = cast(pointer(gcm_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(gcm_params)) + return self.mech + + +class AESECBEncryptDataMechanism(Mechanism): + """ + AES mechanism for deriving keys from encrypted data. + """ + REQUIRED_PARAMS = ['data'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AESECBEncryptDataMechanism, self).to_c_mech() + # from https://www.cryptsoft.com/pkcs11doc/v220 + # /group__SEC__12__14__2__MECHANISM__PARAMETERS.html + # Note: data should be a multiple of 16 long. + params = CK_KEY_DERIVATION_STRING_DATA() + pdata, data_len = to_byte_array(self.params['data']) + params.pData = pdata + params.ulLen = CK_ULONG(data_len) + self.mech.pParameter = cast(pointer(params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(params)) + return self.mech + + +class AESCBCEncryptDataMechanism(Mechanism): + """ + AES CBC mechanism for deriving keys from encrypted data. + """ + REQUIRED_PARAMS = ['iv', 'data'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AESCBCEncryptDataMechanism, self).to_c_mech() + # https://www.cryptsoft.com/pkcs11doc/v220 + # /group__SEC__12__14__KEY__DERIVATION__BY__DATA__ENCRYPTION______DES______AES.html + # #CKM_AES_CBC_ENCRYPT_DATA + # Note: data should be a multiple of 16 long. + params = CK_AES_CBC_ENCRYPT_DATA_PARAMS() + pdata, data_len = to_byte_array(self.params['data']) + # Note: IV should always be a length of 8. + p_iv, _ = to_byte_array(self.params['iv']) + params.pData = pdata + params.ulLen = CK_ULONG(data_len) + params.iv = p_iv + self.mech.pParameter = cast(pointer(params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(params)) + return self.mech + + +class AESCTRMechanism(Mechanism): + """ + AES CTR Mechanism param conversion. + """ + + REQUIRED_PARAMS = ['cb'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AESCTRMechanism, self).to_c_mech() + ctr_params = CK_AES_CTR_PARAMS() + ctr_params.cb = (CK_BYTE * 16)(*self.params['cb']) + ctr_params.ulCounterBits = CK_ULONG(len(self.params['cb'])) + self.mech.pParameter = cast(pointer(ctr_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(ctr_params)) + return self.mech diff --git a/pycryptoki/mechanism/dh.py b/pycryptoki/mechanism/dh.py new file mode 100644 index 0000000..5c3b5b9 --- /dev/null +++ b/pycryptoki/mechanism/dh.py @@ -0,0 +1,40 @@ +""" +Diffie-Hellman mechanisms. +""" +from _ctypes import pointer, sizeof +from ctypes import cast, c_void_p + +from ..attributes import to_byte_array +from ..cryptoki import CK_ECDH1_DERIVE_PARAMS, CK_BYTE_PTR, CK_ULONG +from .helpers import Mechanism + + +class ECDH1DeriveMechanism(Mechanism): + """ + ECDH1-specific mechanism + """ + REQUIRED_PARAMS = ["kdf", "sharedData", "publicData"] + + def to_c_mech(self): + """ + Create the Param structure, then convert the data into byte arrays. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(ECDH1DeriveMechanism, self).to_c_mech() + params = CK_ECDH1_DERIVE_PARAMS() + params.kdf = self.params['kdf'] + if self.params['sharedData'] is None: + shared_data = None + shared_data_len = 0 + else: + shared_data, shared_data_len = to_byte_array(self.params['sharedData']) + params.pSharedData = cast(shared_data, CK_BYTE_PTR) + params.ulSharedDataLen = shared_data_len + public_data, public_data_len = to_byte_array(self.params['publicData']) + params.pPublicData = cast(public_data, CK_BYTE_PTR) + params.ulPublicDataLen = public_data_len + self.mech.pParameter = cast(pointer(params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(params)) + return self.mech + diff --git a/pycryptoki/mechanism/generic.py b/pycryptoki/mechanism/generic.py new file mode 100644 index 0000000..fd80366 --- /dev/null +++ b/pycryptoki/mechanism/generic.py @@ -0,0 +1,117 @@ +""" +Generic Mechanisms conversions. +""" +from ctypes import c_void_p, cast, pointer, POINTER, sizeof +from . import Mechanism, MechanismException +from .. import cryptoki +from ..attributes import to_byte_array, CONVERSIONS +from ..cryptoki import CK_ULONG, CK_KEY_DERIVATION_STRING_DATA, c_ubyte +from ..exceptions import LunaException + + +class ConcatenationDeriveMechanism(Mechanism): + """ + Mechanism class for key derivations. This will take in a second key handle in the parameters, + and use it in the resulting Structure. + + .. warning :: This mechanism is disabled in later versions of PCKS11. + + """ + REQUIRED_PARAMS = ['h_second_key'] + + def to_c_mech(self): + """ + Add in a pointer to the second key in the resulting mech structure. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(ConcatenationDeriveMechanism, self).to_c_mech() + c_second_key = CK_ULONG(self.params['h_second_key']) + self.mech.pParameter = cast(pointer(c_second_key), c_void_p) + self.mech.usParameterLen = sizeof(c_second_key) + return self.mech + + +class StringDataDerivationMechanism(Mechanism): + """ + Mechanism class for key derivation using passed in string data. + """ + REQUIRED_PARAMS = ['data'] + + def to_c_mech(self): + """ + Convert data to bytearray, then use in the resulting mech structure. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(StringDataDerivationMechanism, self).to_c_mech() + parameters = CK_KEY_DERIVATION_STRING_DATA() + data, length = to_byte_array(self.params['data']) + parameters.pData = cast(data, POINTER(c_ubyte)) + parameters.ulLen = length + self.mech.pParameter = parameters + self.mech.usParameterLen = sizeof(parameters) + return self.mech + + +class NullMech(Mechanism): + """ + Class that creates a mechanism from a flavor with null parameters. + Used mostly for signing mechanisms that really don't need anything else. + """ + + def to_c_mech(self): + """ + Simply set the pParameter to null pointer. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(NullMech, self).to_c_mech() + self.mech.pParameter = c_void_p(0) + self.mech.usParameterLen = CK_ULONG(0) + return self.mech + + +class AutoMech(Mechanism): + """ + An attempt to examine underlying C Struct and fill in the appropriate fields, + making some assumptions about the data. This works best with parameter structs that only + have CK_ULONGs within them (though there is a best-effort attempt to handle arrays). + + .. warning:: Do not use this if the mechanism is already defined! + """ + + def to_c_mech(self): + """ + Attempt to handle generic mechanisms by introspection of the + structure. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(AutoMech, self).to_c_mech() + c_params_type = getattr(cryptoki, + self.params.get('params_name', "UNKNOWN"), + None) + if not c_params_type: + raise MechanismException("Failed to find a suitable " + "Ctypes Parameter Struct for type {}. " + "Make sure to set 'params_name' in the arguments!".format( + repr(self.mech_type))) + + fields = c_params_type._fields_ + c_params = c_params_type() + for name, c_type in fields: + # Check if it's an array. + if hasattr(c_type, '_length_'): + c_type = c_type._type_ + if c_type not in CONVERSIONS: + raise LunaException("Cannot convert to c_type: {}".format(c_type)) + ptr, length = CONVERSIONS[c_type](self.params[name]) + setattr(c_params, name, cast(ptr, POINTER(c_type))) + # Otherwise, do a direct conversion. + else: + # c_type = c_type._type_ + setattr(c_params, name, c_type(self.params[name])) + self.mech.pParameter = cast(pointer(c_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(c_params)) + return self.mech diff --git a/pycryptoki/mechanism/helpers.py b/pycryptoki/mechanism/helpers.py new file mode 100755 index 0000000..5e19263 --- /dev/null +++ b/pycryptoki/mechanism/helpers.py @@ -0,0 +1,261 @@ +""" +Mechanism base class, as well as helper functions for parsing Mechanism arguments +to pycryptoki functions. +""" + +import logging +from ctypes import c_void_p, cast, pointer, POINTER, sizeof, create_string_buffer, c_char + +from six import integer_types + +from ..cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ + CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_MECHANISM_TYPE +from ..defines import * + +LOG = logging.getLogger(__name__) + +CK_AES_CBC_PAD_EXTRACT_PARAMS_TEMP = {'mechanism': CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL, + 'ulType': CK_CRYPTOKI_ELEMENT, + 'ulHandle': 5, + 'ulDeleteAfterExtract': 0, + 'pBuffer': 0, + 'pulBufferLen': 0, + 'ulStorage': CK_STORAGE_HOST, + 'pedId': 0, + 'pbFileName': 0, + 'ctxID': 3 + } + +CK_AES_CBC_PAD_INSERT_PARAMS_TEMP = {'mechanism': CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL, + 'ulType': CK_CRYPTOKI_ELEMENT, + 'ulContainerState': 0, + 'pBuffer': 0, + 'pulBufferLen': 0, + 'ulStorageType': CK_STORAGE_HOST, + 'pulType': 0, + 'pulHandle': 0, + 'ctxID': 3, + 'pedID': 3, + 'pbFileName': 0, + 'ulStorage': CK_STORAGE_HOST, + } + +supported_parameters = {'CK_AES_CBC_PAD_EXTRACT_PARAMS': CK_AES_CBC_PAD_EXTRACT_PARAMS, + 'CK_AES_CBC_PAD_INSERT_PARAMS': CK_AES_CBC_PAD_INSERT_PARAMS} + + +class MechanismException(Exception): + """ + Exception raised for mechanism errors. Ex: required parameters are missing + """ + + pass + + +class Mechanism(object): + """ + Base class for pycryptoki mechanisms. + Performs checks for missing parameters w/ created mechs, and + creates the base Mechanism Struct for conversion to ctypes. + """ + REQUIRED_PARAMS = [] + + def __new__(cls, mech_type="UNKNOWN", params=None): + """ + Factory for mechs. + """ + + from . import MECH_LOOKUP, NullMech + if cls == Mechanism: + mech_cls = MECH_LOOKUP.get(mech_type, NullMech) + return super(Mechanism, cls).__new__(mech_cls) + else: + return super(Mechanism, cls).__new__(cls) + + def __init__(self, mech_type="UNKNOWN", params=None): + self.mech_type = mech_type + if params is None: + params = {} + self.params = params + + missing_params = [] + for req in self.REQUIRED_PARAMS: + if req not in params: + missing_params.append(req) + if missing_params: + raise MechanismException("Cannot create {}, " + "Missing required parameters:\n\t" + "{}".format(self.__class__, + "\n\t".join(missing_params))) + + def to_c_mech(self): + """ + Create the Mechanism structure & set the mech type to the passed-in flavor. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + self.mech = CK_MECHANISM() + self.mech.mechanism = CK_MECHANISM_TYPE(self.mech_type) + return self.mech + + +def get_c_struct_from_mechanism(python_dictionary, params_type_string): + """Gets a c struct from a python dictionary representing that struct + + :param python_dictionary: The python dictionary representing the C struct, + see :class:`CK_AES_CBC_PAD_EXTRACT_PARAMS` for an example + :param params_type_string: A string representing the parameter struct. + ex. for :class:`~pycryptoki.cryptoki.CK_AES_CBC_PAD_EXTRACT_PARAMS` use the + string ``CK_AES_CBC_PAD_EXTRACT_PARAMS`` + :returns: A C struct + + """ + params_type = supported_parameters[params_type_string] + params = params_type() + mech = CK_MECHANISM() + mech.mechanism = python_dictionary['mechanism'] + mech.pParameter = cast(pointer(params), c_void_p) + mech.usParameterLen = CK_ULONG(sizeof(params_type)) + + # Automatically handle the simpler fields + for entry in params_type._fields_: + key_name = entry[0] + key_type = entry[1] + + if key_type == CK_ULONG: + setattr(params, key_name, CK_ULONG(python_dictionary[key_name])) + elif key_type == CK_ULONG_PTR: + setattr(params, key_name, pointer(CK_ULONG(python_dictionary[key_name]))) + else: + continue + + # Explicitly handle the more complex fields + if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: + if len(python_dictionary['pBuffer']) == 0: + params.pBuffer = None + else: + params.pBuffer = (CK_BYTE * len(python_dictionary['pBuffer']))() + # params.pbFileName = 0 #TODO convert byte pointer to serializable type + pass + elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: + # params.pbFileName = TODO + params.pBuffer = cast(create_string_buffer(python_dictionary['pBuffer']), CK_BYTE_PTR) + params.ulBufferLen = len(python_dictionary['pBuffer']) + pass + else: + raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") + + return mech + + +def get_python_dict_from_c_mechanism(c_mechanism, params_type_string): + """Gets a python dictionary from a c mechanism's struct for serialization + and easier test case writing + + :param c_mechanism: The c mechanism to convert to a python dictionary + :param params_type_string: A string representing the parameter struct. + ex. for :class:`~pycryptoki.cryptoki.CK_AES_CBC_PAD_EXTRACT_PARAMS` use the + string ``CK_AES_CBC_PAD_EXTRACT_PARAMS`` + :returns: A python dictionary representing the c struct + """ + python_dictionary = {} + python_dictionary['mechanism'] = c_mechanism.mechanism + + params_type = supported_parameters[params_type_string] + params_struct = cast(c_mechanism.pParameter, POINTER(params_type)).contents + + # Automatically handle the simpler fields + for entry in params_type._fields_: + key_name = entry[0] + key_type = entry[1] + + if key_type == CK_ULONG: + python_dictionary[key_name] = getattr(params_struct, key_name) + elif key_type == CK_ULONG_PTR: + python_dictionary[key_name] = getattr(params_struct, key_name).contents.value + else: + continue + + # Explicitly handle the more complex fields + if params_type == CK_AES_CBC_PAD_EXTRACT_PARAMS: + bufferLength = params_struct.pulBufferLen.contents.value + if params_struct.pBuffer is None: + bufferString = None + else: + char_p_string = cast(params_struct.pBuffer, POINTER(c_char)) + if char_p_string is not None: + bufferString = char_p_string[0:bufferLength] + else: + bufferString = None + python_dictionary['pBuffer'] = bufferString + python_dictionary['pbFileName'] = 0 # TODO + elif params_type == CK_AES_CBC_PAD_INSERT_PARAMS: + python_dictionary['pbFileName'] = 0 # TODO + python_dictionary['pBuffer'] = 0 # TODO + else: + raise Exception("Unsupported parameter type, pycryptoki can be extended to make it work") + + return python_dictionary + + +def parse_mechanism(mechanism_param): + """ + Designed for use with any function call that takes in a mechanism, + this will handle a mechanism parameter that is one of the following: + + 1. ``CKM_`` integer constant -- will create a :class:`~pycryptoki.cryptoki.CK_MECHANISM` + with only mech_type set. + + .. code-block :: python + + parse_mechanism(CKM_RSA_PKCS) + # Results in: + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(CKM_RSA_PKCS) + mech.pParameter = None + mech.usParameterLen = 0 + + 2. Dictionary with ``mech_type`` as a mandatory key, and ``params`` as an optional key. This + will be passed into the :class:`Mechanism` class for conversion to + a :class:`~pycryptoki.cryptoki.CK_MECHANISM`. + + .. code-block :: python + + parse_mechanism({'mech_type': CKM_AES_CBC, + 'params': {'iv': list(range(8))}}) + # Results in: + mech = CK_MECHANISM() + mech.mechanism = CK_MECHANISM_TYPE(CKM_AES_CBC) + iv_ba, iv_len = to_byte_array(list(range(8))) + mech.pParameter = iv_ba + mech.usParameterLen = iv_len + + 3. :class:`~pycryptoki.cryptoki.CK_MECHANISM` struct -- passed directly into the raw C Call. + 4. Mechanism class -- will call to_c_mech() on the class, and use the results. + + .. warning:: If you're using this with rpyc, you need to make sure the call `to_c_mech` occurs + on the *server* (the machine with the HSM)! If you pass in a :py:class:`Mechanism` class + that was created on the client, the resulting call into `to_c_mech()` will *also* be on + the client side! + + .. note:: You can look at ``REQUIRED_PARAMS`` on each mechanism class to see what parameters are + required. + + :param mechanism_param: Parameter to convert to a C Mechanism. + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` struct. + """ + + if isinstance(mechanism_param, dict): + mech = Mechanism(**mechanism_param).to_c_mech() + elif isinstance(mechanism_param, CK_MECHANISM): + mech = mechanism_param + elif isinstance(mechanism_param, integer_types): + mech = Mechanism(mech_type=mechanism_param).to_c_mech() + elif isinstance(mechanism_param, Mechanism): + mech = mechanism_param.to_c_mech() + else: + raise TypeError("Invalid mechanism type {}, should be CK_MECHANISM, dictionary with " + "kwargs to be passed to `Mechanism`, integer constant, or a " + "Mechanism() class.".format(type(mechanism_param))) + + return mech diff --git a/pycryptoki/mechanism/rc.py b/pycryptoki/mechanism/rc.py new file mode 100644 index 0000000..a8319a2 --- /dev/null +++ b/pycryptoki/mechanism/rc.py @@ -0,0 +1,107 @@ +""" +RC-related Mechanism implementations +""" +import logging +import types +from ctypes import c_void_p, cast, pointer, POINTER, sizeof, create_string_buffer, c_char + +from six import integer_types + +from .. import cryptoki +from . import Mechanism +from ..attributes import to_byte_array, to_char_array, CONVERSIONS +from ..cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ + CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_RC2_CBC_PARAMS, \ + CK_RC5_PARAMS, CK_RC5_CBC_PARAMS, CK_MECHANISM_TYPE, CK_AES_XTS_PARAMS, \ + CK_RSA_PKCS_OAEP_PARAMS, \ + CK_AES_GCM_PARAMS, CK_RSA_PKCS_PSS_PARAMS, CK_KEY_DERIVATION_STRING_DATA, c_ubyte, \ + CK_AES_CBC_ENCRYPT_DATA_PARAMS +from ..defines import * +from ..exceptions import LunaException + + +class RC2Mechanism(Mechanism): + """ + Sets the mechanism parameter to the usEffectiveBits + """ + REQUIRED_PARAMS = ['usEffectiveBits'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(RC2Mechanism, self).to_c_mech() + effective_bits = CK_ULONG(self.params['usEffectiveBits']) + self.mech.pParameter = cast(pointer(effective_bits), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(effective_bits)) + return self.mech + + +class RC2CBCMechanism(Mechanism): + """ + Creates required RC2CBC Param structure & converts python data to C data. + """ + REQUIRED_PARAMS = ['usEffectiveBits', 'iv'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(RC2CBCMechanism, self).to_c_mech() + effective_bits = self.params['usEffectiveBits'] + cbc_params = CK_RC2_CBC_PARAMS() + cbc_params.usEffectiveBits = CK_ULONG(effective_bits) + cbc_params.iv = (CK_BYTE * 8)(*self.params['iv']) + self.mech.pParameter = cast(pointer(cbc_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(cbc_params)) + return self.mech + + +class RC5Mechanism(Mechanism): + """ + Creates required RC5 Param structure & converts python data to C data. + """ + REQUIRED_PARAMS = ['ulWordsize', 'ulRounds'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(RC5Mechanism, self).to_c_mech() + rc5_params = CK_RC5_PARAMS() + rc5_params.ulWordsize = CK_ULONG(self.params['ulWordsize']) + rc5_params.ulRounds = CK_ULONG(self.params['ulRounds']) + self.mech.pParameter = cast(pointer(rc5_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(rc5_params)) + return self.mech + + +class RC5CBCMechanism(Mechanism): + """ + Creates required RC5CBC Param structure & converts python data to C data. + """ + REQUIRED_PARAMS = ['ulWordsize', 'ulRounds', 'iv'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(RC5CBCMechanism, self).to_c_mech() + rc5_params = CK_RC5_CBC_PARAMS() + rc5_params.ulWordsize = CK_ULONG(self.params['ulWordsize']) + rc5_params.ulRounds = CK_ULONG(self.params['ulRounds']) + iv, ivlen = to_byte_array(self.params['iv']) + rc5_params.pIv = cast(iv, CK_BYTE_PTR) + rc5_params.ulIvLen = ivlen + self.mech.pParameter = cast(pointer(rc5_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(rc5_params)) + return self.mech + diff --git a/pycryptoki/mechanism/rsa.py b/pycryptoki/mechanism/rsa.py new file mode 100644 index 0000000..01f05ff --- /dev/null +++ b/pycryptoki/mechanism/rsa.py @@ -0,0 +1,65 @@ +""" +RSA-related Mechanism implementations. +""" +from ctypes import c_void_p, cast, pointer, sizeof + +from .helpers import Mechanism +from ..attributes import to_byte_array +from ..cryptoki import CK_ULONG, CK_RSA_PKCS_OAEP_PARAMS, \ + CK_RSA_PKCS_PSS_PARAMS +from ..defines import * + + +class RSAPKCSOAEPMechanism(Mechanism): + """ + Create the required RSA_PKCS_OAEP param structure & convert python data to + C data. + """ + REQUIRED_PARAMS = ['hashAlg', 'mgf'] + + def to_c_mech(self): + """ + Convert extra parameters to ctypes, then build out the mechanism. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(RSAPKCSOAEPMechanism, self).to_c_mech() + oaep_params = CK_RSA_PKCS_OAEP_PARAMS() + oaep_params.hashAlg = CK_ULONG(self.params['hashAlg']) + oaep_params.mgf = CK_ULONG(self.params['mgf']) + # Note: According to + # https://www.cryptsoft.com/pkcs11doc/v220 + # /group__SEC__12__1__7__PKCS____1__RSA__OAEP__MECHANISM__PARAMETERS.html + # there is only one encoding parameter source. + oaep_params.source = CK_ULONG(CKZ_DATA_SPECIFIED) + data, data_len = to_byte_array(self.params.get('sourceData', '')) + oaep_params.pSourceData = data + oaep_params.ulSourceDataLen = data_len + + self.mech.pParameter = cast(pointer(oaep_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(oaep_params)) + return self.mech + + +class RSAPKCSPSSMechanism(Mechanism): + """ + Create the required RSA_PKCS_PSS param structure & convert python data to + C data. + """ + REQUIRED_PARAMS = ['hashAlg', 'mgf'] + + def to_c_mech(self): + """ + Uses default salt length of 8. + Can be overridden w/ a parameter though. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + """ + super(RSAPKCSPSSMechanism, self).to_c_mech() + c_params = CK_RSA_PKCS_PSS_PARAMS() + c_params.hashAlg = CK_ULONG(self.params['hashAlg']) + c_params.mgf = CK_ULONG(self.params['mgf']) + c_params.usSaltLen = CK_ULONG(self.params.get('usSaltLen', 8)) + self.mech.pParameter = cast(pointer(c_params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(c_params)) + return self.mech diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 3195359..28fcfe5 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -32,7 +32,7 @@ def c_sign(h_session, h_key, data_to_sign, mechanism): - "This is a proper argument of some data to use in the function" - ["This is another format of data this", "function will accept.", - "It will operate on these strings in parts"] + "It will operate on these strings in parts"] :param int h_key: The signing key :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function diff --git a/setup.py b/setup.py index 9ff27b5..e1cf672 100755 --- a/setup.py +++ b/setup.py @@ -14,7 +14,8 @@ url='https://github.com/gemalto/pycryptoki', version='2.0.1', packages=['pycryptoki', - 'pycryptoki.daemon'], + 'pycryptoki.daemon', + 'pycryptoki.mechanism'], scripts=['pycryptoki/daemon/rpyc_pycryptoki.py'], tests_require=['pytest', 'hypothesis', 'mock', 'pytz'], install_requires=['future', 'rpyc', 'six'] diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index ae961c5..9e93711 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -18,7 +18,7 @@ CKM_RSA_PKCS, CKM_RSA_PKCS_OAEP, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X_509, CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_SHA_1, CKG_MGF1_SHA1, CKM_AES_KWP, CKM_AES_KW, - CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID) + CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKM_AES_CTR) from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_KEY_SIZE_RANGE) from pycryptoki.encryption import c_encrypt, c_decrypt from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, c_destroy_object @@ -31,6 +31,7 @@ SYM_TABLE = {CKM_DES_CBC: CKM_DES_KEY_GEN, CKM_AES_CBC: CKM_AES_KEY_GEN, CKM_AES_ECB: CKM_AES_KEY_GEN, + CKM_AES_CTR: CKM_AES_KEY_GEN, CKM_AES_GCM: CKM_AES_KEY_GEN, CKM_AES_KW: CKM_AES_KEY_GEN, CKM_AES_KWP: CKM_AES_KEY_GEN, # Note: Supported in Q3/Q4 2016 SA @@ -61,6 +62,7 @@ {'iv': list(range(8))}], CKM_AES_KWP: [{'iv': []}, {'iv': list(range(8))}], + CKM_AES_CTR: [{'cb': list(range(16))}], # Note: Supported in Q3/Q4 2016 SA CKM_AES_ECB: [{}], CKM_AES_GCM: [{'iv': list(range(8)), 'AAD': b'notsosecret', 'ulTagBits': 32}], @@ -94,7 +96,8 @@ CKM_RC4, CKM_AES_GCM, CKM_AES_KWP, - CKM_SEED_CBC_PAD] + CKM_SEED_CBC_PAD, + CKM_AES_CTR] # Ret error, however encrypt /decrypt is successful. Needs to be addressed at some point KEY_SIZE_RANGE = [CKM_RC2_CBC, CKM_RC2_ECB, CKM_RC2_CBC_PAD] From 6437609a9b8db4d1d0570c162f7cea9f09d74df4 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 5 Jul 2017 15:32:14 -0400 Subject: [PATCH 086/109] LA-2511 Unify Pycryptoki data format Problem: c_encrypt/decrypt/wrap functions assumed everything was a string, running it through to_char_array. this heavily complicates attempting to encrypt/decrypt raw hex data. Solution: create conversion functions that should work for converting between hex/bytestring seamlessly. This eventually gets converted down to hex data before run through to_byte_array within the encrypt/decrypt calls. Change-Id: Id2d868e3170b62a0dd0df392ac7300899f3a6e3e --- docs/attributes.rst | 8 ++ pycryptoki/attributes.py | 31 +++--- pycryptoki/conversions.py | 118 +++++++++++++++++++++++ pycryptoki/encryption.py | 85 +++++++++++++--- pycryptoki/misc.py | 5 +- pycryptoki/sign_verify.py | 11 ++- tests/functional/test_encrypt_decrypt.py | 33 ++++--- tests/functional/test_sign_verify.py | 4 +- tests/functional/test_wrap_unwrap.py | 4 +- 9 files changed, 246 insertions(+), 53 deletions(-) create mode 100644 pycryptoki/conversions.py diff --git a/docs/attributes.rst b/docs/attributes.rst index 34309d1..5646a00 100644 --- a/docs/attributes.rst +++ b/docs/attributes.rst @@ -7,3 +7,11 @@ Attributes and Conversions .. data:: pycryptoki.attributes.KEY_TRANSFORMS :annotation: CK_ATTRIBUTE Types mapped to Python->C transformation functions + + +Conversions +----------- + +.. automodule:: pycryptoki.conversions + :members: + diff --git a/pycryptoki/attributes.py b/pycryptoki/attributes.py index 77d66a4..338d6e3 100755 --- a/pycryptoki/attributes.py +++ b/pycryptoki/attributes.py @@ -14,6 +14,7 @@ from six import b, string_types, integer_types, text_type, binary_type +from pycryptoki.conversions import from_bytestring from .cryptoki import CK_ATTRIBUTE, CK_BBOOL, CK_ATTRIBUTE_TYPE, CK_ULONG, \ CK_BYTE, CK_CHAR from .defines import CKA_EKM_UID, CKA_GENERIC_1, CKA_GENERIC_2, \ @@ -196,24 +197,26 @@ def to_byte_array(val, reverse=False): fin = binascii.hexlify(bytearray(data_list)) LOG.debug("Final hex data: %s", fin) return fin - if isinstance(val, text_type): - raise TypeError("Cannot convert unicode types to byte arrays!") - elif isinstance(val, binary_type): - # Hex-string in form '01e4' + + if not isinstance(val, (binary_type, collections.Iterable, integer_types)): + raise TypeError("Unknown conversion to byte array for type {}".format(type(val))) + + if isinstance(val, binary_type): + # Hex-string in form '0xdeadbeef'' if val.startswith(b"0x"): val = val.replace(b"0x", b"", 1) - try: + # Raw byte data: '\xde\xad\xbe\xef" + if "\\x" in repr(val): + val = list(from_bytestring(val)) + byte_array = (CK_BYTE * len(val))(*val) + # Hex string: '01af' + else: val = int(val, 16) - except ValueError: - # To allow for pre-allocation of data with ' ' * 64 - if val.isspace() or len(val) == 0: - val = b(val) - else: - pass # Pass on through to the iterable below. - if isinstance(val, collections.Iterable): + elif isinstance(val, collections.Iterable): py_bytes = bytearray(val) byte_array = (CK_BYTE * len(py_bytes))(*py_bytes) - elif isinstance(val, integer_types): + + if isinstance(val, integer_types): # Explicitly convert to a long. Python doesn't like X.bit_length() where X is an int # and not a variable assigned an int. x = val @@ -225,8 +228,6 @@ def to_byte_array(val, reverse=False): n = 8 str_array = [str_val[i:i + n] for i in range(0, len(str_val), n)] byte_array = (CK_BYTE * len(str_array))(*[int(x, 2) for x in str_array]) - else: - raise TypeError("Invalid conversion {} to byte array!".format(type(val))) return cast(pointer(byte_array), c_void_p), CK_ULONG(sizeof(byte_array)) diff --git a/pycryptoki/conversions.py b/pycryptoki/conversions.py new file mode 100644 index 0000000..6bfd528 --- /dev/null +++ b/pycryptoki/conversions.py @@ -0,0 +1,118 @@ +""" +Provide low-level conversions between common data types. + +The ``from_xyz`` functions should all return an iterator over a list of integers, +representing the individual bytes in the passed-in value. + +The ``to_xyz`` functions take in an iterable of integers and convert it to the specified type. + + + +**Example 1** + + .. code-block:: python + :caption: Convert a raw bytestring to hex + + raw_bytes = from_bytestring(b"Some test data") + assert raw_bytes = [83, 111, 109, 101, 32, 116, 101, 115, 116, 32, 100, 97, 116, 97] + + hex_data = to_hex(from_bytestring(b"Some test data")) + assert hex_data == b'536f6d6520746573742064617461' + + +**Example 2** + + .. code-block:: python + :caption: Convert hex data to a raw bytestring + + bytestring_data = to_bytestring(from_hex(b'536f6d6520746573742064617461')) + assert bytestring_data == b"Some test data" + + raw_bytes = list(from_hex(b'536f6d6520746573742064617461')) + assert raw_bytes == [83, 111, 109, 101, 32, 116, 101, 115, 116, 32, 100, 97, 116, 97] + + +""" +from six import b + + +def _chunks(inval, chunk_size): + """ + Split an iterable into chunks of the given size. + + :param inval: Iterable to be chunked. + :param chunk_size: Size of chunks. + :return: Iterator + """ + for i in range(0, len(inval), chunk_size): + yield inval[i:i + chunk_size] + + +def from_bytestring(ascii_): + """ + Convert an iterable of strings into an iterable of integers. + + .. note:: For bytestrings on python3, this does effectively nothing, since + iterating over a bytestring in python 3 will return integers. + + :param ascii_: String to convert + :return: iterator + """ + for c in ascii_: + try: + yield ord(c) + except TypeError: + yield c + + +def to_bytestring(ascii_): + """ + Convert an iterable of integers into a bytestring. + + :param iterable ascii_: Iterable of integers + :return: bytestring + """ + return b(''.join(chr(a) for a in ascii_)) + + +def from_bin(bin_): + """ + Convert a string-representation of binary into a list + of integers. + + :param str bin_: String representation of binary data (ex: "10110111") + :return: iterator over integers + """ + for chunk in _chunks(bin_, 8): + yield int(chunk, 2) + + +def to_bin(ascii_): + """ + Convert an iterable of integers to a binary representation. + + :param iterable ascii_: iterable of integers + :return: bytestring of the binary values + """ + return b''.join(b('{:08b}'.format(a)) for a in ascii_) + + +def from_hex(hex_): + """ + Convert a hexademical string to an iterable of integers. + + :param str hex_: Hex string + :return: Iterator + """ + for chunk in _chunks(hex_, 2): + yield int(chunk, 16) + + +def to_hex(ints): + """ + Convert an iterable of integers to a hexadecimal string. + + :param iterable ints: Iterable of integers + :return: bytestring representing the hex data. + """ + return b''.join(b('{:02x}'.format(a)) for a in ints) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 135120c..6e2d388 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -5,9 +5,8 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from six import string_types - -from .attributes import Attributes, to_char_array, to_byte_array +from .conversions import from_bytestring, to_hex +from .attributes import Attributes, to_byte_array from .common_utils import AutoCArray, refresh_c_arrays from .cryptoki import CK_ULONG, \ C_EncryptInit, C_Encrypt @@ -15,9 +14,9 @@ C_WrapKey, C_UnwrapKey, C_EncryptUpdate, C_EncryptFinal, CK_BYTE_PTR, \ C_DecryptUpdate, C_DecryptFinal from .defines import CKR_OK -from .mechanism import parse_mechanism -from .return_values import ret_vals_dictionary from .exceptions import make_error_handle_function +from .mechanism import parse_mechanism +from .lookup_dicts import ret_vals_dictionary MAX_BUFFER = 0xffff @@ -32,8 +31,24 @@ def c_encrypt(h_session, h_key, data, mechanism, output_buffers=None): :param int h_session: Current session :param int h_key: The key handle to encrypt the data with - :param data: The data to encrypt, either a string or a list of strings. If this is + :param data: The data to encrypt, either a bytestring or a list of bytestrings. If this is a list a multipart operation will be used + + .. note:: This will be converted to hexadecimal by calling:: + + to_hex(from_bytestring(data)) + + If you need to pass in raw hex data, call:: + + to_bytestring(from_hex(hex-data)) + + + References: + * :py:func:`~pycryptoki.conversions.to_hex` + * :py:func:`~pycryptoki.conversions.from_hex` + * :py:func:`~pycryptoki.conversions.to_bytestring` + * :py:func:`~pycryptoki.conversions.from_bytestring` + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. :param list output_buffers: List of integers that specify a size of output buffers to use @@ -56,7 +71,7 @@ def c_encrypt(h_session, h_key, data, mechanism, output_buffers=None): ret, encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, C_EncryptFinal, data, output_buffers) else: - plain_data, plain_data_length = to_char_array(data) + plain_data, plain_data_length = to_byte_array(from_bytestring(data)) plain_data = cast(plain_data, POINTER(c_ubyte)) enc_data = AutoCArray(ctype=c_ubyte) @@ -111,6 +126,22 @@ def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffers=None): :param int h_session: The session to use :param int h_key: The handle of the key to use to decrypt :param bytes encrypted_data: Data to be decrypted + + .. note:: Data will be converted to hexadecimal by calling:: + + to_hex(from_bytestring(data)) + + If you need to pass in raw hex data, call:: + + to_bytestring(from_hex(hex-data)) + + + References: + * :py:func:`~pycryptoki.conversions.to_hex` + * :py:func:`~pycryptoki.conversions.from_hex` + * :py:func:`~pycryptoki.conversions.to_bytestring` + * :py:func:`~pycryptoki.conversions.from_bytestring` + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. :param list output_buffers: List of integers that specify a size of output buffers to use @@ -141,7 +172,7 @@ def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffers=None): # number of bytes needed. So the python string that's returned in the # end needs to be adjusted based on the second called to C_Decrypt # which will have the right length - c_enc_data, c_enc_data_len = to_char_array(encrypted_data) + c_enc_data, c_enc_data_len = to_byte_array(from_bytestring(encrypted_data)) c_enc_data = cast(c_enc_data, POINTER(c_ubyte)) decrypted_data = AutoCArray(ctype=c_ubyte) @@ -178,6 +209,22 @@ def do_multipart_operation(h_session, :param c_update_function: C_Update function to call to update each operation. :param c_finalize_function: Function to call at end of multipart operation. :param input_data_list: List of data to call update function on. + + .. note:: Data will be converted to hexadecimal by calling:: + + to_hex(from_bytestring(data)) + + If you need to pass in raw hex data, call:: + + to_bytestring(from_hex(hex-data)) + + + References: + * :py:func:`~pycryptoki.conversions.to_hex` + * :py:func:`~pycryptoki.conversions.from_hex` + * :py:func:`~pycryptoki.conversions.to_bytestring` + * :py:func:`~pycryptoki.conversions.from_bytestring` + :param list output_buffers: List of integers that specify a size of output buffers to use for multi-part operations. By default will query with NULL pointer buffer to get required size of buffer @@ -192,7 +239,7 @@ def do_multipart_operation(h_session, else: out_data_len = CK_ULONG() out_data = None - data_chunk, data_chunk_len = to_char_array(chunk) + data_chunk, data_chunk_len = to_byte_array(from_bytestring(chunk)) data_chunk = cast(data_chunk, POINTER(c_ubyte)) ret = c_update_function(h_session, @@ -289,6 +336,22 @@ def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, mechani :param int h_session: The session to use :param int h_unwrapping_key: The wrapping key handle :param bytes wrapped_key: The wrapped key + + .. note:: Data will be converted to hexadecimal by calling:: + + to_hex(from_bytestring(data)) + + If you need to pass in raw hex data, call:: + + to_bytestring(from_hex(hex-data)) + + + References: + * :py:func:`~pycryptoki.conversions.to_hex` + * :py:func:`~pycryptoki.conversions.from_hex` + * :py:func:`~pycryptoki.conversions.to_bytestring` + * :py:func:`~pycryptoki.conversions.from_bytestring` + :param dict key_template: The python template representing the new key's template :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. @@ -297,9 +360,7 @@ def c_unwrap_key(h_session, h_unwrapping_key, wrapped_key, key_template, mechani """ mech = parse_mechanism(mechanism) c_template = Attributes(key_template).get_c_struct() - if isinstance(wrapped_key, string_types): - wrapped_key = bytearray(wrapped_key) - byte_wrapped_key, key_len = to_byte_array(wrapped_key) + byte_wrapped_key, key_len = to_byte_array(from_bytestring(wrapped_key)) byte_wrapped_key = cast(byte_wrapped_key, CK_BYTE_PTR) h_output_key = CK_ULONG() ret = C_UnwrapKey(h_session, mech, CK_OBJECT_HANDLE(h_unwrapping_key), diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 9ccd01c..706b550 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -14,7 +14,8 @@ from six import integer_types -from .attributes import Attributes, to_char_array +from pycryptoki.conversions import from_bytestring +from .attributes import Attributes, to_char_array, to_byte_array from .common_utils import refresh_c_arrays, AutoCArray from .cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ @@ -98,7 +99,7 @@ def c_digest(h_session, data_to_digest, digest_flavor, mechanism=None): data_to_digest) else: # Get arguments - c_data_to_digest, c_digest_data_len = to_char_array(data_to_digest) + c_data_to_digest, c_digest_data_len = to_byte_array(from_bytestring(data_to_digest)) c_data_to_digest = cast(c_data_to_digest, POINTER(c_ubyte)) digested_data = AutoCArray(ctype=c_ubyte) diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 28fcfe5..773d88f 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -5,7 +5,8 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from .attributes import to_char_array +from pycryptoki.conversions import from_bytestring +from .attributes import to_char_array, to_byte_array from .common_utils import refresh_c_arrays, AutoCArray from .cryptoki import CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign @@ -59,7 +60,7 @@ def c_sign(h_session, h_key, data_to_sign, mechanism): data_to_sign) else: # Prepare the data to sign - c_data_to_sign, plain_date_len = to_char_array(data_to_sign) + c_data_to_sign, plain_date_len = to_byte_array(from_bytestring(data_to_sign)) c_data_to_sign = cast(c_data_to_sign, POINTER(c_ubyte)) signed_data = AutoCArray(ctype=c_ubyte) @@ -109,7 +110,7 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - data_chunk, data_chunk_len = to_char_array(current_chunk) + data_chunk, data_chunk_len = to_byte_array(from_bytestring(current_chunk)) data_chunk = cast(data_chunk, POINTER(c_ubyte)) ret = c_update_function(h_session, data_chunk, data_chunk_len) @@ -156,7 +157,7 @@ def do_multipart_verify(h_session, input_data_list, signature): raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + str(max_data_chunk_size)) - data_chunk, data_chunk_len = to_char_array(current_chunk) + data_chunk, data_chunk_len = to_byte_array(from_bytestring(current_chunk)) data_chunk = cast(data_chunk, POINTER(c_ubyte)) ret = C_VerifyUpdate(h_session, data_chunk, data_chunk_len) @@ -211,7 +212,7 @@ def c_verify(h_session, h_key, data_to_verify, signature, mechanism): ret = do_multipart_verify(h_session, data_to_verify, signature) else: # Prepare the data to verify - c_data_to_verify, plain_date_len = to_char_array(data_to_verify) + c_data_to_verify, plain_date_len = to_byte_array(from_bytestring(data_to_verify)) c_data_to_verify = cast(c_data_to_verify, POINTER(c_ubyte)) c_signature, c_sig_length = to_char_array(signature) diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index 9e93711..e412b0a 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -89,6 +89,15 @@ # TESTING DATA PAD = b"a" * 0xfff0 RAW = b"abcdefghijk" +MULTIPART_DATA_PAD = [b"a" * 32, + b"b" * 32, + b"c" * 32, + b"d" * 32] + +MULTIPART_DATA_RAW = [b"a" * 11, + b"b" * 11, + b"c" * 11, + b"d" * 11] # Flavors which auto-pad (will return 'CKR_OK' on un-padded(RAW) data) PADDING_ALGORITHMS = [CKM_DES3_CBC_PAD, @@ -123,7 +132,7 @@ def ret_val(mech, data, valid_mechs=None): mech, MECHANISM_LOOKUP_EXT.get(mech, ("Unknown",))[0]) return CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID - if data == RAW: + if data in (RAW, MULTIPART_DATA_RAW): if mech not in PADDING_ALGORITHMS and mech not in ASYM_TABLE: return CKR_DATA_LEN_RANGE else: @@ -254,7 +263,7 @@ def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session, """ # Auto-fail when key-generation fails if sym_keys.get(SYM_TABLE[m_type]) is None: - pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) + pytest.skip("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) exp_ret = ret_val(m_type, data, valid_mechanisms) h_key = sym_keys[SYM_TABLE[m_type]] @@ -275,7 +284,8 @@ def test_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session, self.verify_data(data, end_data) - @pytest.mark.parametrize('data', [PAD, RAW], ids=["valid_data", "raw(pad-required)"]) + @pytest.mark.parametrize('data', [MULTIPART_DATA_PAD, MULTIPART_DATA_RAW], + ids=["valid_data", "raw(pad-required)"]) @pytest.mark.parametrize(('m_type', 'params'), scenarios(SYM_TABLE), ids=idfn(SYM_TABLE)) def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_session, valid_mechanisms): @@ -291,27 +301,20 @@ def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_se # Auto-fail when key-generation is fails if sym_keys.get(SYM_TABLE[m_type]) is None: - pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) - - # AES_KW will fail on very large data sizes - # AES_GCM requires smaller data sizes as well. - if m_type in (CKM_AES_KW, CKM_AES_GCM) and data == PAD: - data = b"a" * 256 + pytest.skip("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) exp_ret = ret_val(m_type, data, valid_mechanisms) h_key = sym_keys[SYM_TABLE[m_type]] - encrypt_this = [data, data, data, data] + encrypt_this = data mech = {"mech_type": m_type, "params": params} - ret, encrypted = c_encrypt(auth_session, h_key, encrypt_this, mechanism=mech) + ret, encrypted = c_encrypt(auth_session, h_key, encrypt_this, mechanism=mech, + output_buffers=[0xffff, 0xffff, 0xffff, 0xffff]) self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing if exp_ret in (CKR_OK, KEY_SIZE_RANGE): - if m_type not in PADDING_ALGORITHMS and m_type != CKM_AES_KW: - assert len(encrypted) == len(b"".join(encrypt_this)) - ret, end_data = c_decrypt(auth_session, h_key, encrypted, mechanism=mech) self.verify_ret(ret, exp_ret) if m_type in PADDING_ALGORITHMS: @@ -328,7 +331,7 @@ def test_asym_encrypt_decrypt(self, m_type, params, asym_keys, auth_session, val :param auth_session: """ if asym_keys.get(ASYM_TABLE[m_type]) is None: - pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) + pytest.skip("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[m_type][0])) expected_retcode = ret_val(m_type, RAW, valid_mechanisms) pub_key, prv_key = asym_keys[ASYM_TABLE[m_type]] diff --git a/tests/functional/test_sign_verify.py b/tests/functional/test_sign_verify.py index dbd1d45..3001231 100755 --- a/tests/functional/test_sign_verify.py +++ b/tests/functional/test_sign_verify.py @@ -132,7 +132,7 @@ def test_sym_sign_verify(self, key_type, sign_flavor, data, sym_keys): """ # Auto-fail when key-generation fails if sym_keys.get(key_type) is None: - pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[key_type][0])) + pytest.skip("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[key_type][0])) h_key = sym_keys[key_type] ret, signature = c_sign(self.h_session, h_key, data, mechanism=sign_flavor) @@ -153,7 +153,7 @@ def test_asym_sign_verify(self, k_type, sig_mech, data, asym_keys): """ # Auto-fail when key-generation fails if asym_keys.get(k_type) is None: - pytest.fail("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[k_type][0])) + pytest.skip("No valid key found for {}".format(MECHANISM_LOOKUP_EXT[k_type][0])) pub_key, prv_key = asym_keys[k_type] ret, signature = c_sign(self.h_session, prv_key, data, mechanism=sig_mech) diff --git a/tests/functional/test_wrap_unwrap.py b/tests/functional/test_wrap_unwrap.py index 1140c66..730a2c8 100755 --- a/tests/functional/test_wrap_unwrap.py +++ b/tests/functional/test_wrap_unwrap.py @@ -150,7 +150,7 @@ def test_wrap_unwrap_key(self, mech, k_type, keys): extra_p = EXTRA_PARAM[mech] h_key, h_wrap_key = keys[k_type] if h_key is None or h_wrap_key is None: - pytest.fail("No valid key found for {}".format(LOOKUP[mech][0])) + pytest.skip("No valid key found for {}".format(LOOKUP[mech][0])) # Wrap the key wrap_mech = {"mech_type": mech, @@ -188,7 +188,7 @@ def test_encrypt_wrap_unwrap_decrypt_key(self, mech, k_type, keys): h_key, h_wrap_key = keys[k_type] extra_p = EXTRA_PARAM[mech] if h_key is None or h_wrap_key is None: - pytest.fail("No valid key found for {}".format(LOOKUP[mech][0])) + pytest.skip("No valid key found for {}".format(LOOKUP[mech][0])) # Encrypt some data data_to_encrypt = b"a" * 512 From d3c1c3ef499b00eb8ca99967ac899e7cea680841 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 12 Jul 2017 13:54:17 -0400 Subject: [PATCH 087/109] LA-2534 Allow for pre-allocation of cipher buffers There are 2 major ways to call PKCS functions that return data in a buffer: 1. Call with a NULL ptr to ask the library to get required size of buffer, then create that buffer & call again. 2. Pre-allocate a large enough buffer to hold the data, then call the function with that buffer. See https://www.cryptsoft.com/pkcs11doc/v220/group__SEC__11__2__CONVENTIONS__FOR__FUNCTIONS__RETURNING__OUTPUT__IN__A__VARIABLE__LENGTH__BUFFER.html#SECTION_11_2 for more details This commit allows us to do either method we desire by adding the 'output_buffer' argument to each function that returns data in a variable buffer. Change-Id: Ic639ab7e8124b400231232dcce2d06c567f1999d --- pycryptoki/encryption.py | 116 +++++++++------- pycryptoki/misc.py | 46 ++++--- pycryptoki/sign_verify.py | 162 +++++++++++++---------- tests/functional/test_encrypt_decrypt.py | 2 +- 4 files changed, 195 insertions(+), 131 deletions(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 6e2d388..cef92c7 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -5,9 +5,9 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from .conversions import from_bytestring, to_hex from .attributes import Attributes, to_byte_array from .common_utils import AutoCArray, refresh_c_arrays +from .conversions import from_bytestring from .cryptoki import CK_ULONG, \ C_EncryptInit, C_Encrypt from .cryptoki import C_Decrypt, C_DecryptInit, CK_OBJECT_HANDLE, \ @@ -15,15 +15,15 @@ C_DecryptUpdate, C_DecryptFinal from .defines import CKR_OK from .exceptions import make_error_handle_function -from .mechanism import parse_mechanism from .lookup_dicts import ret_vals_dictionary +from .mechanism import parse_mechanism MAX_BUFFER = 0xffff LOG = logging.getLogger(__name__) -def c_encrypt(h_session, h_key, data, mechanism, output_buffers=None): +def c_encrypt(h_session, h_key, data, mechanism, output_buffer=None): """Encrypts data with a given key and encryption flavor encryption flavors @@ -51,8 +51,8 @@ def c_encrypt(h_session, h_key, data, mechanism, output_buffers=None): :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. - :param list output_buffers: List of integers that specify a size of output buffers to use - for multi-part operations. By default will query with NULL pointer buffer + :param list|int output_buffer: Integer or list of integers that specify a size of output + buffer to use for an operation. By default will query with NULL pointer buffer to get required size of buffer. :returns: (Retcode, Python bytestring of encrypted data) :rtype: tuple @@ -69,26 +69,35 @@ def c_encrypt(h_session, h_key, data, mechanism, output_buffers=None): if is_multi_part_operation: ret, encrypted_python_string = do_multipart_operation(h_session, C_EncryptUpdate, - C_EncryptFinal, data, output_buffers) + C_EncryptFinal, data, output_buffer) else: plain_data, plain_data_length = to_byte_array(from_bytestring(data)) plain_data = cast(plain_data, POINTER(c_ubyte)) + if output_buffer is not None: + size = CK_ULONG(output_buffer) + enc_data = AutoCArray(ctype=c_ubyte, + size=size) - enc_data = AutoCArray(ctype=c_ubyte) + ret = C_Encrypt(h_session, + plain_data, plain_data_length, + enc_data.array, enc_data.size) - @refresh_c_arrays(1) - def _encrypt(): - """Closure for getting the buffer size with encrypt.""" - return C_Encrypt(h_session, - plain_data, plain_data_length, - enc_data.array, enc_data.size) + else: + enc_data = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _encrypt(): + """Closure for getting the buffer size with encrypt.""" + return C_Encrypt(h_session, + plain_data, plain_data_length, + enc_data.array, enc_data.size) - ret = _encrypt() + ret = _encrypt() if ret != CKR_OK: return ret, None # Convert encrypted data into a python string - encrypted_python_string = string_at(enc_data.array, len(enc_data)) + encrypted_python_string = string_at(enc_data.array, enc_data.size.contents.value) return ret, encrypted_python_string @@ -118,7 +127,7 @@ def _get_string_from_list(list_of_strings): return b"".join(list_of_strings) -def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffers=None): +def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffer=None): """Decrypt given data with the given key and mechanism. .. note:: If data is a list or tuple of strings, multi-part decryption will be used. @@ -144,8 +153,8 @@ def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffers=None): :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. - :param list output_buffers: List of integers that specify a size of output buffers to use - for multi-part operations. By default will query with NULL pointer buffer + :param list|int output_buffer: Integer or list of integers that specify a size of output + buffer to use for an operation. By default will query with NULL pointer buffer to get required size of buffer. :returns: (Retcode, Python bytestring of decrypted data)) :rtype: tuple @@ -162,7 +171,7 @@ def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffers=None): if is_multi_part_operation: ret, python_data = do_multipart_operation(h_session, C_DecryptUpdate, C_DecryptFinal, - encrypted_data, output_buffers) + encrypted_data, output_buffer) else: # Get the length of the final data @@ -174,22 +183,30 @@ def c_decrypt(h_session, h_key, encrypted_data, mechanism, output_buffers=None): # which will have the right length c_enc_data, c_enc_data_len = to_byte_array(from_bytestring(encrypted_data)) c_enc_data = cast(c_enc_data, POINTER(c_ubyte)) + if output_buffer is not None: + size = CK_ULONG(output_buffer) + decrypted_data = AutoCArray(ctype=c_ubyte, + size=size) + + ret = C_Decrypt(h_session, + c_enc_data, c_enc_data_len, + decrypted_data.array, decrypted_data.size) + else: + decrypted_data = AutoCArray(ctype=c_ubyte) - decrypted_data = AutoCArray(ctype=c_ubyte) - - @refresh_c_arrays(1) - def _decrypt(): - """ Perform the decryption ops""" - return C_Decrypt(h_session, - c_enc_data, c_enc_data_len, - decrypted_data.array, decrypted_data.size) + @refresh_c_arrays(1) + def _decrypt(): + """ Perform the decryption ops""" + return C_Decrypt(h_session, + c_enc_data, c_enc_data_len, + decrypted_data.array, decrypted_data.size) - ret = _decrypt() + ret = _decrypt() if ret != CKR_OK: return ret, None # Convert the decrypted data to a python readable format - python_data = string_at(decrypted_data.array, len(decrypted_data)) + python_data = string_at(decrypted_data.array, decrypted_data.size.contents.value) return ret, python_data @@ -201,7 +218,7 @@ def do_multipart_operation(h_session, c_update_function, c_finalize_function, input_data_list, - output_buffers=None): + output_buffer=None): """Some code which will do a multipart encrypt or decrypt since they are the same with just different functions called @@ -225,7 +242,7 @@ def do_multipart_operation(h_session, * :py:func:`~pycryptoki.conversions.to_bytestring` * :py:func:`~pycryptoki.conversions.from_bytestring` - :param list output_buffers: List of integers that specify a size of output buffers to use + :param list output_buffer: List of integers that specify a size of output buffers to use for multi-part operations. By default will query with NULL pointer buffer to get required size of buffer """ @@ -233,9 +250,9 @@ def do_multipart_operation(h_session, error = None for index, chunk in enumerate(input_data_list): - if output_buffers: - out_data_len = CK_ULONG(output_buffers[index]) - out_data = cast(create_string_buffer(b'', output_buffers[index]), CK_BYTE_PTR) + if output_buffer: + out_data_len = CK_ULONG(output_buffer[index]) + out_data = cast(create_string_buffer(b'', output_buffer[index]), CK_BYTE_PTR) else: out_data_len = CK_ULONG() out_data = None @@ -252,7 +269,7 @@ def do_multipart_operation(h_session, error = ret break - if not output_buffers: + if not output_buffer: # Need a second call to actually get the data. LOG.debug("Creating cipher data buffer of size %s", out_data_len.value) out_data = create_string_buffer(b'', out_data_len.value) @@ -298,7 +315,7 @@ def do_multipart_operation(h_session, return ret, b"".join(python_data) -def c_wrap_key(h_session, h_wrapping_key, h_key, mechanism): +def c_wrap_key(h_session, h_wrapping_key, h_key, mechanism, output_buffer=None): """Wrap a key off the HSM into an encrypted data blob. :param int h_session: The session to use @@ -311,20 +328,29 @@ def c_wrap_key(h_session, h_wrapping_key, h_key, mechanism): """ mech = parse_mechanism(mechanism) - wrapped_key = AutoCArray(ctype=c_ubyte) + if output_buffer is not None: + size = CK_ULONG(output_buffer) + wrapped_key = AutoCArray(ctype=c_ubyte, + size=size) + ret = C_WrapKey(h_session, mech, + CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), + wrapped_key.array, wrapped_key.size) + else: + wrapped_key = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _wrap(): + """ Perform the Wrapping operation""" + return C_WrapKey(h_session, mech, + CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), + wrapped_key.array, wrapped_key.size) - @refresh_c_arrays(1) - def _wrap(): - """ Perform the Wrapping operation""" - return C_WrapKey(h_session, mech, - CK_OBJECT_HANDLE(h_wrapping_key), CK_OBJECT_HANDLE(h_key), - wrapped_key.array, wrapped_key.size) + ret = _wrap() - ret = _wrap() if ret != CKR_OK: return ret, None - return ret, string_at(wrapped_key.array, len(wrapped_key)) + return ret, string_at(wrapped_key.array, wrapped_key.size.contents.value) c_wrap_key_ex = make_error_handle_function(c_wrap_key) diff --git a/pycryptoki/misc.py b/pycryptoki/misc.py index 706b550..0e29373 100755 --- a/pycryptoki/misc.py +++ b/pycryptoki/misc.py @@ -15,15 +15,15 @@ from six import integer_types from pycryptoki.conversions import from_bytestring -from .attributes import Attributes, to_char_array, to_byte_array +from .attributes import Attributes, to_byte_array from .common_utils import refresh_c_arrays, AutoCArray from .cryptoki import C_GenerateRandom, CK_BYTE_PTR, CK_ULONG, \ C_SeedRandom, C_DigestInit, C_DigestUpdate, C_DigestFinal, C_Digest, C_CreateObject, \ CA_SetPedId, CK_SLOT_ID, CA_GetPedId, C_DigestKey from .defines import CKR_OK -from .mechanism import Mechanism, NullMech, parse_mechanism -from .sign_verify import do_multipart_sign_or_digest from .exceptions import make_error_handle_function +from .mechanism import parse_mechanism +from .sign_verify import do_multipart_sign_or_digest def c_generate_random(h_session, length): @@ -66,7 +66,7 @@ def c_seed_random(h_session, seed): c_seed_random_ex = make_error_handle_function(c_seed_random) -def c_digest(h_session, data_to_digest, digest_flavor, mechanism=None): +def c_digest(h_session, data_to_digest, digest_flavor, mechanism=None, output_buffer=None): """Digests some data :param int h_session: Session handle @@ -76,6 +76,9 @@ def c_digest(h_session, data_to_digest, digest_flavor, mechanism=None): SHA224, SHA256, SHA384, SHA512) :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. If None will use digest flavor. + :param list|int output_buffer: Integer or list of integers that specify a size of output + buffer to use for an operation. By default will query with NULL pointer buffer + to get required size of buffer. :returns: (retcode, a python string of the digested data) :rtype: tuple """ @@ -96,28 +99,39 @@ def c_digest(h_session, data_to_digest, digest_flavor, mechanism=None): if is_multi_part_operation: ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate, C_DigestFinal, - data_to_digest) + data_to_digest, + output_buffer=output_buffer) else: # Get arguments c_data_to_digest, c_digest_data_len = to_byte_array(from_bytestring(data_to_digest)) c_data_to_digest = cast(c_data_to_digest, POINTER(c_ubyte)) - digested_data = AutoCArray(ctype=c_ubyte) - - @refresh_c_arrays(1) - def _digest(): - """ Perform the digest operations - """ - return C_Digest(h_session, - c_data_to_digest, c_digest_data_len, - digested_data.array, digested_data.size) + if output_buffer is not None: + size = CK_ULONG(output_buffer) + digested_data = AutoCArray(ctype=c_ubyte, + size=size) + ret = C_Digest(h_session, + c_data_to_digest, c_digest_data_len, + digested_data.array, digested_data.size) + else: + digested_data = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _digest(): + """ Perform the digest operations + """ + return C_Digest(h_session, + c_data_to_digest, c_digest_data_len, + digested_data.array, digested_data.size) + + ret = _digest() - ret = _digest() if ret != CKR_OK: return ret, None # Convert Digested data into a python string - digested_python_string = string_at(digested_data.array, len(digested_data)) + digested_python_string = string_at(digested_data.array, + digested_data.size.contents.value) return ret, digested_python_string diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 773d88f..85690e2 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -5,22 +5,23 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte -from pycryptoki.conversions import from_bytestring from .attributes import to_char_array, to_byte_array from .common_utils import refresh_c_arrays, AutoCArray +from .conversions import from_bytestring from .cryptoki import CK_ULONG, \ CK_BYTE_PTR, C_SignInit, C_Sign from .cryptoki import C_VerifyInit, C_Verify, C_SignUpdate, \ C_SignFinal, C_VerifyUpdate, C_VerifyFinal from .defines import CKR_OK -from .encryption import _get_string_from_list -from .mechanism import parse_mechanism +from .encryption import MAX_BUFFER from .exceptions import make_error_handle_function +from .lookup_dicts import ret_vals_dictionary +from .mechanism import parse_mechanism LOG = logging.getLogger(__name__) -def c_sign(h_session, h_key, data_to_sign, mechanism): +def c_sign(h_session, h_key, data_to_sign, mechanism, output_buffer=None): """Signs the given data with given key and mechanism. .. note:: If data is a list or tuple of strings, multi-part operations will be used. @@ -38,6 +39,9 @@ def c_sign(h_session, h_key, data_to_sign, mechanism): :param int h_key: The signing key :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function for possible values. + :param list|int output_buffer: Integer or list of integers that specify a size of output + buffer to use for an operation. By default will query with NULL pointer buffer + to get required size of buffer. :return: (retcode, python string of signed data) :rtype: tuple """ @@ -57,26 +61,35 @@ def c_sign(h_session, h_key, data_to_sign, mechanism): ret, signature_string = do_multipart_sign_or_digest(h_session, C_SignUpdate, C_SignFinal, - data_to_sign) + data_to_sign, + output_buffer=output_buffer) else: # Prepare the data to sign c_data_to_sign, plain_date_len = to_byte_array(from_bytestring(data_to_sign)) c_data_to_sign = cast(c_data_to_sign, POINTER(c_ubyte)) - signed_data = AutoCArray(ctype=c_ubyte) - - @refresh_c_arrays(1) - def _sign(): - """Perform the signing operation""" - return C_Sign(h_session, - c_data_to_sign, plain_date_len, - signed_data.array, signed_data.size) - - ret = _sign() + if output_buffer is not None: + size = CK_ULONG(output_buffer) + signed_data = AutoCArray(ctype=c_ubyte, + size=size) + ret = C_Sign(h_session, + c_data_to_sign, plain_date_len, + signed_data.array, signed_data.size) + else: + signed_data = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def _sign(): + """Perform the signing operation""" + return C_Sign(h_session, + c_data_to_sign, plain_date_len, + signed_data.array, signed_data.size) + + ret = _sign() if ret != CKR_OK: return ret, None - signature_string = string_at(signed_data.array, len(signed_data)) + signature_string = string_at(signed_data.array, signed_data.size.contents.value) return ret, signature_string @@ -84,53 +97,69 @@ def _sign(): c_sign_ex = make_error_handle_function(c_sign) -def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, input_data_list): +def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, + input_data_list, output_buffer=None): """ Do a multipart sign or digest operation :param int h_session: Session handle - :param c_update_function: signing update function - :param c_final_function: signing finalization function - :param input_data_list: + :param func c_update_function: signing update function + :param func c_final_function: signing finalization function + :param iterable input_data_list: Iterable of data to sign. + :param int output_buffer: Integer that specifies a size of an output bufffer to use + for the Sign/Digeste operation. By default will query with NULL pointer buffer + to get required size of buffer :return: The result code, A python string representing the signature """ - max_data_chunk_size = 0xfff0 - plain_data_len = len(_get_string_from_list(input_data_list)) - - remaining_length = plain_data_len - python_string = b'' - i = 0 - while remaining_length > 0: - current_chunk = input_data_list[i] + error = None - # Prepare arguments for decrypt update operation - current_chunk_len = min(len(current_chunk), remaining_length) - - if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + - str(max_data_chunk_size)) - - data_chunk, data_chunk_len = to_byte_array(from_bytestring(current_chunk)) + for index, chunk in enumerate(input_data_list): + data_chunk, data_chunk_len = to_byte_array(from_bytestring(chunk)) data_chunk = cast(data_chunk, POINTER(c_ubyte)) ret = c_update_function(h_session, data_chunk, data_chunk_len) if ret != CKR_OK: - return ret, None + LOG.debug("%s call on chunk %.20s (%s/%s) Failed w/ ret %s (%s)", + c_update_function.__name__, + chunk, index + 1, len(input_data_list), ret_vals_dictionary[ret], ret) + error = ret + break + + # An Update function failed. We should still try to call C_**Final() though to ensure that the + # operation is still finalized, but we'll return the original error code. + if error: + ret = c_final_function(h_session, + cast(create_string_buffer(b'', MAX_BUFFER), CK_BYTE_PTR), + CK_ULONG(MAX_BUFFER)) + LOG.debug("%s call after a %s failure returned: %s (%s)", + c_final_function.__name__, + c_update_function.__name__, ret_vals_dictionary[ret], ret) + return error, None + + if output_buffer is not None: + size = CK_ULONG(output_buffer) + out_data = AutoCArray(ctype=c_ubyte, + size=size) + + ret = c_final_function(h_session, out_data.array, out_data.size) - remaining_length -= current_chunk_len - - i += 1 + else: + out_data = AutoCArray(ctype=c_ubyte) - # Finalizing multipart decrypt operation - out_data_len = CK_ULONG(max_data_chunk_size) - output = cast(create_string_buffer(b"", out_data_len.value), CK_BYTE_PTR) - ret = c_final_function(h_session, output, byref(out_data_len)) + @refresh_c_arrays(1) + def _final(): + """ + Closure to acces AutoCArray properties correctly + """ + return c_final_function(h_session, out_data.array, out_data.size) - # Get output - if out_data_len.value > 0: - python_string += string_at(output, out_data_len.value) + ret = _final() - return ret, python_string + if ret != CKR_OK: + return ret, None + else: + python_string = string_at(out_data.array, out_data.size.contents.value) + return ret, python_string def do_multipart_verify(h_session, input_data_list, signature): @@ -142,37 +171,32 @@ def do_multipart_verify(h_session, input_data_list, signature): :param signature: signature to verify :return: The result code """ - max_data_chunk_size = 0xfff0 - plain_data_len = len(_get_string_from_list(input_data_list)) - - remaining_length = plain_data_len - i = 0 - while remaining_length > 0: - current_chunk = input_data_list[i] + error = None + for index, chunk in enumerate(input_data_list): - # Prepare arguments for decrypt update operation - current_chunk_len = min(len(current_chunk), remaining_length) - - if current_chunk_len > max_data_chunk_size: - raise Exception("chunk_sizes variable too large, the maximum size of a chunk is " + - str(max_data_chunk_size)) - - data_chunk, data_chunk_len = to_byte_array(from_bytestring(current_chunk)) + data_chunk, data_chunk_len = to_byte_array(from_bytestring(chunk)) data_chunk = cast(data_chunk, POINTER(c_ubyte)) ret = C_VerifyUpdate(h_session, data_chunk, data_chunk_len) if ret != CKR_OK: - return ret - - remaining_length -= current_chunk_len - - i += 1 + error = ret + break + + # An C_VerifyUpdate failed. We should still try to call C_**Final() though to ensure + # that the + # operation is still finalized, but we'll return the original error code. + if error: + ret = C_VerifyFinal(h_session, + cast(create_string_buffer(b"", MAX_BUFFER), CK_BYTE_PTR), + CK_ULONG(MAX_BUFFER)) + LOG.debug("C_VerifyFinal call after a C_VerifyUpdate failure returned:" + " %s (%s)", ret_vals_dictionary[ret], ret) + return error, None # Finalizing multipart decrypt operation c_sig_data, c_sig_data_len = to_char_array(signature) output = cast(c_sig_data, CK_BYTE_PTR) ret = C_VerifyFinal(h_session, output, c_sig_data_len) - return ret diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index e412b0a..042b03b 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -310,7 +310,7 @@ def test_multi_sym_encrypt_decrypt(self, m_type, params, data, sym_keys, auth_se mech = {"mech_type": m_type, "params": params} ret, encrypted = c_encrypt(auth_session, h_key, encrypt_this, mechanism=mech, - output_buffers=[0xffff, 0xffff, 0xffff, 0xffff]) + output_buffer=[0xffff, 0xffff, 0xffff, 0xffff]) self.verify_ret(ret, exp_ret) # If not expecting error, proceed with testing From 8656fae74b1b4125a03df6fb3c048f1bd7f7aee6 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 17 Jul 2017 08:37:37 -0400 Subject: [PATCH 088/109] LA-2546 Adding AES_GMAC to mechanisms Change-Id: I42d5bdfc6b08f6e33def626db8b3785d10c2c72e --- pycryptoki/mechanism/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pycryptoki/mechanism/__init__.py b/pycryptoki/mechanism/__init__.py index 08ce1c7..2baaa70 100644 --- a/pycryptoki/mechanism/__init__.py +++ b/pycryptoki/mechanism/__init__.py @@ -132,7 +132,7 @@ def to_c_mech(self): CKM_XOR_BASE_AND_DATA, CKM_CONCATENATE_DATA_AND_BASE, - CKM_ECDH1_DERIVE, CKM_AES_CTR) + CKM_ECDH1_DERIVE, CKM_AES_CTR, CKM_AES_GMAC) MECH_LOOKUP = { # Iv @@ -177,6 +177,7 @@ def to_c_mech(self): CKM_AES_XTS: AESXTSMechanism, (CKM_VENDOR_DEFINED + 0x11c): AESGCMMechanism, # Backwards compatibility w/ older Lunas. CKM_AES_GCM: AESGCMMechanism, + CKM_AES_GMAC: AESGCMMechanism, CKM_RSA_PKCS_OAEP: RSAPKCSOAEPMechanism, From 637746cf66d3b1518ac19fbe6dfa06d1005bd2ed Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 18 Jul 2017 09:12:36 -0400 Subject: [PATCH 089/109] LA-2555 Switch AAD conversion to use to_byte_array AAD should be in the form of a bytestring (or other such iterable that can be converted down to bytes), which means we should use to_byte_array instead of to_char_array Also added C_GetInfo() method Change-Id: If1a531d0fc7abfe9c0bcc254ee2ab805f3a74ee0 --- docs/conf.py | 2 +- pycryptoki/mechanism/aes.py | 6 ++-- pycryptoki/session_management.py | 38 +++++++++++++++++++++--- setup.py | 2 +- tests/functional/test_encrypt_decrypt.py | 6 ++-- tests/unittests/test_mechanisms.py | 5 ++-- 6 files changed, 46 insertions(+), 13 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index a5e716c..e29cad0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -61,7 +61,7 @@ # The short X.Y version. version = '2.0' # The full version, including alpha/beta/rc tags. -release = '2.0.1' +release = '2.0.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/pycryptoki/mechanism/aes.py b/pycryptoki/mechanism/aes.py index 0d2f3e7..6bdba55 100644 --- a/pycryptoki/mechanism/aes.py +++ b/pycryptoki/mechanism/aes.py @@ -5,7 +5,7 @@ from ctypes import c_void_p, cast, pointer, sizeof from . import Mechanism -from ..attributes import to_byte_array, to_char_array +from ..attributes import to_byte_array from ..cryptoki import CK_ULONG, CK_BYTE, CK_BYTE_PTR, CK_AES_XTS_PARAMS, \ CK_AES_GCM_PARAMS, CK_KEY_DERIVATION_STRING_DATA, CK_AES_CBC_ENCRYPT_DATA_PARAMS, \ CK_AES_CTR_PARAMS @@ -90,7 +90,7 @@ def to_c_mech(self): class AESGCMMechanism(Mechanism): """ - Creates the AES-GCM specific param structure & converts python types to C types. + Creates the AES-GCM specific param structure & converts python types to C types. """ REQUIRED_PARAMS = ['iv', 'AAD', 'ulTagBits'] @@ -112,7 +112,7 @@ def to_c_mech(self): gcm_params.ulIvLen = iv_len # Assuming 8 bits per entry in IV. gcm_params.ulIvBits = CK_ULONG(len(self.params['iv']) * 8) - aad, aadlen = to_char_array(self.params['AAD']) + aad, aadlen = to_byte_array(self.params['AAD']) gcm_params.pAAD = cast(aad, CK_BYTE_PTR) gcm_params.ulAADLen = aadlen gcm_params.ulTagBits = CK_ULONG(self.params['ulTagBits']) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 0e9a699..546e851 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -6,6 +6,7 @@ from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ byref, pointer +from .common_utils import AutoCArray, refresh_c_arrays # cryptoki constants from .cryptoki import (CK_ULONG, CK_BBOOL, @@ -18,8 +19,7 @@ CK_USER_TYPE, CK_TOKEN_INFO, CK_VOID_PTR, - CK_BYTE) - + CK_BYTE, CK_INFO, C_GetInfo) # Cryptoki Functions from .cryptoki import (C_Initialize, C_GetSlotList, @@ -39,8 +39,6 @@ CA_CloseApplicationID, CA_Restart, CA_SetApplicationID) - -from .common_utils import AutoCArray, refresh_c_arrays from .defines import CKR_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION from .exceptions import make_error_handle_function @@ -129,6 +127,38 @@ def login(h_session, slot_num=1, password=None, user_type=1): login_ex = make_error_handle_function(login) +def c_get_info(): + """ + Get general information about the Cryptoki Library + + Returns a dictionary containing the following keys: + + * cryptokiVersion + * manufacturerID + * flags + * libraryDescription + * libraryVersion + + ``cryptokiVersion`` and ``libraryVersion`` are :ref:`~pycryptoki.cryptoki.CK_VERSION` structs, + and the major/minor values can be accessed directly (``info['cryptokiVersion'].major == 2``) + + :return: (retcode, info dictionary) + """ + info = {} + info_struct = CK_INFO() + ret = C_GetInfo(byref(info_struct)) + if ret == CKR_OK: + info['cryptokiVersion'] = info_struct.cryptokiVersion + info['manufacturerID'] = info_struct.manufacturerID + info['flags'] = info_struct.flags + info['libraryDescription'] = info_struct.libraryDescription + info['libraryVersion'] = info_struct.libraryVersion + return ret, info + + +c_get_info_ex = make_error_handle_function(c_get_info) + + def get_slot_info(description): """Returns a slot with a certain descriptor diff --git a/setup.py b/setup.py index e1cf672..662a63c 100755 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ description="A python wrapper around the C cryptoki library.", author='Ashley Straw', url='https://github.com/gemalto/pycryptoki', - version='2.0.1', + version='2.0.2', packages=['pycryptoki', 'pycryptoki.daemon', 'pycryptoki.mechanism'], diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index 042b03b..5342a1d 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -18,7 +18,8 @@ CKM_RSA_PKCS, CKM_RSA_PKCS_OAEP, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X_509, CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_SHA_1, CKG_MGF1_SHA1, CKM_AES_KWP, CKM_AES_KW, - CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKM_AES_CTR) + CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKM_AES_CTR, + CKM_AES_GMAC) from pycryptoki.defines import (CKR_OK, CKR_DATA_LEN_RANGE, CKR_KEY_SIZE_RANGE) from pycryptoki.encryption import c_encrypt, c_decrypt from pycryptoki.key_generator import c_generate_key, c_generate_key_pair, c_destroy_object @@ -65,7 +66,8 @@ CKM_AES_CTR: [{'cb': list(range(16))}], # Note: Supported in Q3/Q4 2016 SA CKM_AES_ECB: [{}], - CKM_AES_GCM: [{'iv': list(range(8)), 'AAD': b'notsosecret', 'ulTagBits': 32}], + CKM_AES_GCM: [{'iv': list(range(8)), 'AAD': b'deadbeef', 'ulTagBits': 32}], + CKM_AES_GMAC: [{'iv': list(range(8)), 'AAD': b'deadbeef', 'ulTagBits': 32}], CKM_DES3_CBC: [{}, {'iv': list(range(8))}], CKM_DES3_ECB: [{}], CKM_DES3_CBC_PAD: [{}, {'iv': list(range(8))}], diff --git a/tests/unittests/test_mechanisms.py b/tests/unittests/test_mechanisms.py index 26866c1..f1a57b4 100644 --- a/tests/unittests/test_mechanisms.py +++ b/tests/unittests/test_mechanisms.py @@ -6,6 +6,7 @@ from mock import patch from six import integer_types +from pycryptoki.conversions import from_hex, to_bytestring from pycryptoki.cryptoki import (CK_RSA_PKCS_PSS_PARAMS, POINTER, CK_ULONG, @@ -43,7 +44,7 @@ 'sourceData': list(range(12)), 'test_id': 'RSA_OAEP'}, CKM_AES_GCM: {'iv': list(range(16)), - 'AAD': 'testme', + 'AAD': b'deadbeef', 'ulTagBits': 32, 'test_id': 'AES_GCM'}, CKM_RSA_PKCS_PSS: {'hashAlg': CKM_SHA_1, @@ -126,7 +127,7 @@ def test_exact_mechanism_use(self): :return: """ mech = AESGCMMechanism(mech_type=CKM_AES_GCM, - params={'AAD': 'notsosecret', + params={'AAD': to_bytestring(from_hex(b'deadbeef')), 'iv': list(range(12)), 'ulTagBits': 32}) cmech = mech.to_c_mech() From ce932d39b24816e5e974919053d627bb9d93a429 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 20 Jul 2017 11:42:36 -0400 Subject: [PATCH 090/109] LA-2561 AES_CTR should take in ulCounterBits Added ulCounterBits to required params & modified test. Change-Id: I1dd4a2140582fee18ab9b252e492a10ecb1c0204 --- pycryptoki/mechanism/aes.py | 6 ++++-- tests/functional/test_encrypt_decrypt.py | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/pycryptoki/mechanism/aes.py b/pycryptoki/mechanism/aes.py index 6bdba55..7ff63aa 100644 --- a/pycryptoki/mechanism/aes.py +++ b/pycryptoki/mechanism/aes.py @@ -178,9 +178,11 @@ def to_c_mech(self): class AESCTRMechanism(Mechanism): """ AES CTR Mechanism param conversion. + + """ - REQUIRED_PARAMS = ['cb'] + REQUIRED_PARAMS = ['cb', 'ulCounterBits'] def to_c_mech(self): """ @@ -191,7 +193,7 @@ def to_c_mech(self): super(AESCTRMechanism, self).to_c_mech() ctr_params = CK_AES_CTR_PARAMS() ctr_params.cb = (CK_BYTE * 16)(*self.params['cb']) - ctr_params.ulCounterBits = CK_ULONG(len(self.params['cb'])) + ctr_params.ulCounterBits = CK_ULONG(self.params['ulCounterBits']) self.mech.pParameter = cast(pointer(ctr_params), c_void_p) self.mech.usParameterLen = CK_ULONG(sizeof(ctr_params)) return self.mech diff --git a/tests/functional/test_encrypt_decrypt.py b/tests/functional/test_encrypt_decrypt.py index 5342a1d..a49fe3f 100755 --- a/tests/functional/test_encrypt_decrypt.py +++ b/tests/functional/test_encrypt_decrypt.py @@ -63,7 +63,8 @@ {'iv': list(range(8))}], CKM_AES_KWP: [{'iv': []}, {'iv': list(range(8))}], - CKM_AES_CTR: [{'cb': list(range(16))}], + CKM_AES_CTR: [{'cb': list(range(16)), + 'ulCounterBits': 16}], # Note: Supported in Q3/Q4 2016 SA CKM_AES_ECB: [{}], CKM_AES_GCM: [{'iv': list(range(8)), 'AAD': b'deadbeef', 'ulTagBits': 32}], From 001f58a97ee6d01fb4a1a254808dd84daf82c89d Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Fri, 21 Jul 2017 11:59:04 -0400 Subject: [PATCH 091/109] LA-1696 Fix conversions for C_Verify Problem: Uses to_char_array, which can cause confusion with conversions. Solution: Use to_byte_array w/ from_bytestring to explicitly state what data types we are expecting Change-Id: Ifb75f9f83b0f1217cfaa63ad092dbef45adbf995 --- pycryptoki/sign_verify.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 85690e2..1fb4c31 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -5,6 +5,8 @@ from _ctypes import POINTER from ctypes import create_string_buffer, cast, byref, string_at, c_ubyte +from pycryptoki.conversions import from_bytestring + from .attributes import to_char_array, to_byte_array from .common_utils import refresh_c_arrays, AutoCArray from .conversions import from_bytestring @@ -194,7 +196,7 @@ def do_multipart_verify(h_session, input_data_list, signature): return error, None # Finalizing multipart decrypt operation - c_sig_data, c_sig_data_len = to_char_array(signature) + c_sig_data, c_sig_data_len = to_byte_array(from_bytestring(signature)) output = cast(c_sig_data, CK_BYTE_PTR) ret = C_VerifyFinal(h_session, output, c_sig_data_len) return ret @@ -236,15 +238,15 @@ def c_verify(h_session, h_key, data_to_verify, signature, mechanism): ret = do_multipart_verify(h_session, data_to_verify, signature) else: # Prepare the data to verify - c_data_to_verify, plain_date_len = to_byte_array(from_bytestring(data_to_verify)) + c_data_to_verify, plain_data_len = to_byte_array(from_bytestring(data_to_verify)) c_data_to_verify = cast(c_data_to_verify, POINTER(c_ubyte)) - c_signature, c_sig_length = to_char_array(signature) + c_signature, c_sig_length = to_byte_array(from_bytestring(signature)) c_signature = cast(c_signature, POINTER(c_ubyte)) # Actually verify the data ret = C_Verify(h_session, - c_data_to_verify, plain_date_len, + c_data_to_verify, plain_data_len, c_signature, c_sig_length) return ret From 271aba12ac9e5aea2be41f1634122eaee559ac91 Mon Sep 17 00:00:00 2001 From: hhahn Date: Thu, 3 Aug 2017 13:44:32 -0400 Subject: [PATCH 092/109] LA-2583 Pycryptoki return data for failed multipart operation. * Returns data that successfully got processed even when multipart operation fails. Change-Id: I6662cd08b2a54ca16e9c5a60095a03fefcccbf6b --- pycryptoki/encryption.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index cef92c7..471e153 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -294,20 +294,20 @@ def do_multipart_operation(h_session, LOG.debug("%s call after a %s failure returned: %s (%s)", c_finalize_function.__name__, c_update_function.__name__, ret_vals_dictionary[ret], ret) - return error, None + return error, b"".join(python_data) # Finalizing multipart decrypt operation fin_out_data_len = CK_ULONG() # Get buffer size for data ret = c_finalize_function(h_session, None, byref(fin_out_data_len)) if ret != CKR_OK: - return ret, None + return ret, b"".join(python_data) fin_out_data = create_string_buffer(b"", fin_out_data_len.value) output = cast(fin_out_data, CK_BYTE_PTR) ret = c_finalize_function(h_session, output, byref(fin_out_data_len)) if ret != CKR_OK: - return ret, None + return ret, b"".join(python_data) if fin_out_data_len.value > 0: python_data.append(string_at(fin_out_data, fin_out_data_len.value)) From 4661511f5c9291291c4fe6d6b0e7bc4941de3241 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 1 Aug 2017 09:21:58 -0400 Subject: [PATCH 093/109] LA-2578 Display mechanism info via __repr__ Added lookup dict for mechanism names Added __repr__ override to the base Mechanism class Change-Id: Id4cd0a166ec8c01b5016202aeb2bd7505e93eb61 --- pycryptoki/cryptoki_helpers.py | 25 ++- pycryptoki/lookup_dicts.py | 386 ++++++++++++++++++++++++++++++++ pycryptoki/mechanism/helpers.py | 11 + 3 files changed, 415 insertions(+), 7 deletions(-) diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index 96d570a..6003893 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -4,14 +4,14 @@ import logging import os import re -import sys import struct +import sys from ctypes import CDLL from six.moves import configparser -from .exceptions import LunaException from .defaults import CHRYSTOKI_DLL_FILE, CHRYSTOKI_CONFIG_FILE +from .exceptions import LunaException LOG = logging.getLogger(__name__) @@ -169,6 +169,17 @@ def get_dll(self): return self.loaded_dll_library +def log_args(funcname, args): + """Log function name & arguments for a cryptoki ctypes call. + + :param str funcname: Function name + :param tuple args: Arguments to be passed to ctypes function. + """ + log_msg = "Cryptoki call: {}({})".format(funcname, + ", ".join(str(arg) for arg in args)) + LOG.debug(log_msg) + + def make_late_binding_function(function_name): """A function factory for creating a function that will bind to the cryptoki DLL only when the function is called. @@ -177,7 +188,7 @@ def make_late_binding_function(function_name): """ - def luna_function(*args, **kwargs): + def luna_function(*args): """ :param *args: @@ -188,13 +199,13 @@ def luna_function(*args, **kwargs): late_binded_function.restype = luna_function.restype late_binded_function.argtypes = luna_function.argtypes + log_args(function_name, args) try: - return_value = late_binded_function(*args, **kwargs) + return_value = late_binded_function(*args) return return_value except Exception as e: - raise CryptokiDLLException("Call to '%s(%s, **%s)' failed.".format(function_name, - args, - kwargs), e) + raise CryptokiDLLException("Call to '%s(%s)' failed.".format(function_name, + ", ".join(args)), e) luna_function.__name__ = function_name return luna_function diff --git a/pycryptoki/lookup_dicts.py b/pycryptoki/lookup_dicts.py index 300f4d2..b5dcffe 100644 --- a/pycryptoki/lookup_dicts.py +++ b/pycryptoki/lookup_dicts.py @@ -266,3 +266,389 @@ CKA_UNWRAP_TEMPLATE: 'CKA_UNWRAP_TEMPLATE', CKA_DERIVE_TEMPLATE: 'CKA_DERIVE_TEMPLATE', } + +MECH_NAME_LOOKUP = { + 0x00000000: "CKM_RSA_PKCS_KEY_PAIR_GEN", + 0x00000001: "CKM_RSA_PKCS", + 0x00000002: "CKM_RSA_9796", + 0x00000003: "CKM_RSA_X_509", + 0x00000004: "CKM_MD2_RSA_PKCS", + 0x00000005: "CKM_MD5_RSA_PKCS", + 0x00000006: "CKM_SHA1_RSA_PKCS", + 0x00000007: "CKM_RIPEMD128_RSA_PKCS", + 0x00000008: "CKM_RIPEMD160_RSA_PKCS", + 0x00000009: "CKM_RSA_PKCS_OAEP", + 0x0000000A: "CKM_RSA_X9_31_KEY_PAIR_GEN", + 0x0000000B: "CKM_RSA_X9_31", + 0x0000000C: "CKM_SHA1_RSA_X9_31", + 0x0000000D: "CKM_RSA_PKCS_PSS", + 0x0000000E: "CKM_SHA1_RSA_PKCS_PSS", + 0x00000010: "CKM_DSA_KEY_PAIR_GEN", + 0x00000011: "CKM_DSA", + 0x00000012: "CKM_DSA_SHA1", + 0x00000020: "CKM_DH_PKCS_KEY_PAIR_GEN", + 0x00000021: "CKM_DH_PKCS_DERIVE", + 0x00000030: "CKM_X9_42_DH_KEY_PAIR_GEN", + 0x00000031: "CKM_X9_42_DH_DERIVE", + 0x00000032: "CKM_X9_42_DH_HYBRID_DERIVE", + 0x00000033: "CKM_X9_42_MQV_DERIVE", + 0x00000040: "CKM_SHA256_RSA_PKCS", + 0x00000041: "CKM_SHA384_RSA_PKCS", + 0x00000042: "CKM_SHA512_RSA_PKCS", + 0x00000043: "CKM_SHA256_RSA_PKCS_PSS", + 0x00000044: "CKM_SHA384_RSA_PKCS_PSS", + 0x00000045: "CKM_SHA512_RSA_PKCS_PSS", + 0x00000046: "CKM_SHA224_RSA_PKCS", + 0x00000047: "CKM_SHA224_RSA_PKCS_PSS", + 0x00000100: "CKM_RC2_KEY_GEN", + 0x00000101: "CKM_RC2_ECB", + 0x00000102: "CKM_RC2_CBC", + 0x00000103: "CKM_RC2_MAC", + 0x00000104: "CKM_RC2_MAC_GENERAL", + 0x00000105: "CKM_RC2_CBC_PAD", + 0x00000110: "CKM_RC4_KEY_GEN", + 0x00000111: "CKM_RC4", + 0x00000120: "CKM_DES_KEY_GEN", + 0x00000121: "CKM_DES_ECB", + 0x00000122: "CKM_DES_CBC", + 0x00000123: "CKM_DES_MAC", + 0x00000124: "CKM_DES_MAC_GENERAL", + 0x00000125: "CKM_DES_CBC_PAD", + 0x00000130: "CKM_DES2_KEY_GEN", + 0x00000131: "CKM_DES3_KEY_GEN", + 0x00000132: "CKM_DES3_ECB", + 0x00000133: "CKM_DES3_CBC", + 0x00000134: "CKM_DES3_MAC", + 0x00000135: "CKM_DES3_MAC_GENERAL", + 0x00000136: "CKM_DES3_CBC_PAD", + 0x00000137: "CKM_DES3_CMAC_GENERAL", + 0x00000138: "CKM_DES3_CMAC", + 0x00000140: "CKM_CDMF_KEY_GEN", + 0x00000141: "CKM_CDMF_ECB", + 0x00000142: "CKM_CDMF_CBC", + 0x00000143: "CKM_CDMF_MAC", + 0x00000144: "CKM_CDMF_MAC_GENERAL", + 0x00000145: "CKM_CDMF_CBC_PAD", + 0x00000150: "CKM_DES_OFB64", + 0x00000151: "CKM_DES_OFB8", + 0x00000152: "CKM_DES_CFB64", + 0x00000153: "CKM_DES_CFB8", + 0x00000200: "CKM_MD2", + 0x00000201: "CKM_MD2_HMAC", + 0x00000202: "CKM_MD2_HMAC_GENERAL", + 0x00000210: "CKM_MD5", + 0x00000211: "CKM_MD5_HMAC", + 0x00000212: "CKM_MD5_HMAC_GENERAL", + 0x00000220: "CKM_SHA_1", + 0x00000221: "CKM_SHA_1_HMAC", + 0x00000222: "CKM_SHA_1_HMAC_GENERAL", + 0x00000230: "CKM_RIPEMD128", + 0x00000231: "CKM_RIPEMD128_HMAC", + 0x00000232: "CKM_RIPEMD128_HMAC_GENERAL", + 0x00000240: "CKM_RIPEMD160", + 0x00000241: "CKM_RIPEMD160_HMAC", + 0x00000242: "CKM_RIPEMD160_HMAC_GENERAL", + 0x00000250: "CKM_SHA256", + 0x00000251: "CKM_SHA256_HMAC", + 0x00000252: "CKM_SHA256_HMAC_GENERAL", + 0x00000255: "CKM_SHA224", + 0x00000256: "CKM_SHA224_HMAC", + 0x00000257: "CKM_SHA224_HMAC_GENERAL", + 0x00000260: "CKM_SHA384", + 0x00000261: "CKM_SHA384_HMAC", + 0x00000262: "CKM_SHA384_HMAC_GENERAL", + 0x00000270: "CKM_SHA512", + 0x00000271: "CKM_SHA512_HMAC", + 0x00000272: "CKM_SHA512_HMAC_GENERAL", + 0x00000280: "CKM_SECURID_KEY_GEN", + 0x00000282: "CKM_SECURID", + 0x00000290: "CKM_HOTP_KEY_GEN", + 0x00000291: "CKM_HOTP", + 0x000002A0: "CKM_ACTI", + 0x000002A1: "CKM_ACTI_KEY_GEN", + 0x00000300: "CKM_CAST_KEY_GEN", + 0x00000301: "CKM_CAST_ECB", + 0x00000302: "CKM_CAST_CBC", + 0x00000303: "CKM_CAST_MAC", + 0x00000304: "CKM_CAST_MAC_GENERAL", + 0x00000305: "CKM_CAST_CBC_PAD", + 0x00000310: "CKM_CAST3_KEY_GEN", + 0x00000311: "CKM_CAST3_ECB", + 0x00000312: "CKM_CAST3_CBC", + 0x00000313: "CKM_CAST3_MAC", + 0x00000314: "CKM_CAST3_MAC_GENERAL", + 0x00000315: "CKM_CAST3_CBC_PAD", + 0x00000320: "CKM_CAST_KEY_GEN", # Note: each of these could be CAST5 or CAST128 + 0x00000321: "CKM_CAST_ECB", + 0x00000322: "CKM_CAST_CBC", + 0x00000323: "CKM_CAST_MAC", + 0x00000324: "CKM_CAST_MAC_GENERAL", + 0x00000325: "CKM_CAST_CBC_PAD", + 0x00000330: "CKM_RC5_KEY_GEN", + 0x00000331: "CKM_RC5_ECB", + 0x00000332: "CKM_RC5_CBC", + 0x00000333: "CKM_RC5_MAC", + 0x00000334: "CKM_RC5_MAC_GENERAL", + 0x00000335: "CKM_RC5_CBC_PAD", + 0x00000340: "CKM_IDEA_KEY_GEN", + 0x00000341: "CKM_IDEA_ECB", + 0x00000342: "CKM_IDEA_CBC", + 0x00000343: "CKM_IDEA_MAC", + 0x00000344: "CKM_IDEA_MAC_GENERAL", + 0x00000345: "CKM_IDEA_CBC_PAD", + 0x00000350: "CKM_GENERIC_SECRET_KEY_GEN", + 0x00000360: "CKM_CONCATENATE_BASE_AND_KEY", + 0x00000362: "CKM_CONCATENATE_BASE_AND_DATA", + 0x00000363: "CKM_CONCATENATE_DATA_AND_BASE", + 0x00000364: "CKM_XOR_BASE_AND_DATA", + 0x00000365: "CKM_EXTRACT_KEY_FROM_KEY", + 0x00000370: "CKM_SSL3_PRE_MASTER_KEY_GEN", + 0x00000371: "CKM_SSL3_MASTER_KEY_DERIVE", + 0x00000372: "CKM_SSL3_KEY_AND_MAC_DERIVE", + 0x00000373: "CKM_SSL3_MASTER_KEY_DERIVE_DH", + 0x00000374: "CKM_TLS_PRE_MASTER_KEY_GEN", + 0x00000375: "CKM_TLS_MASTER_KEY_DERIVE", + 0x00000376: "CKM_TLS_KEY_AND_MAC_DERIVE", + 0x00000377: "CKM_TLS_MASTER_KEY_DERIVE_DH", + 0x00000378: "CKM_TLS_PRF", + 0x00000380: "CKM_SSL3_MD5_MAC", + 0x00000381: "CKM_SSL3_SHA1_MAC", + 0x00000390: "CKM_MD5_KEY_DERIVATION", + 0x00000391: "CKM_MD2_KEY_DERIVATION", + 0x00000392: "CKM_SHA1_KEY_DERIVATION", + 0x00000393: "CKM_SHA256_KEY_DERIVATION", + 0x00000394: "CKM_SHA384_KEY_DERIVATION", + 0x00000395: "CKM_SHA512_KEY_DERIVATION", + 0x00000396: "CKM_SHA224_KEY_DERIVATION", + 0x000003A0: "CKM_PBE_MD2_DES_CBC", + 0x000003A1: "CKM_PBE_MD5_DES_CBC", + 0x000003A2: "CKM_PBE_MD5_CAST_CBC", + 0x000003A3: "CKM_PBE_MD5_CAST3_CBC", + 0x000003A4: "CKM_PBE_HASH_CAST5_CBC", # Note, HASH could be MD5, SHA1, etc + 0x000003A6: "CKM_PBE_SHA1_RC4_128", + 0x000003A7: "CKM_PBE_SHA1_RC4_40", + 0x000003A8: "CKM_PBE_SHA1_DES3_EDE_CBC", + 0x000003A9: "CKM_PBE_SHA1_DES2_EDE_CBC", + 0x000003AA: "CKM_PBE_SHA1_RC2_128_CBC", + 0x000003AB: "CKM_PBE_SHA1_RC2_40_CBC", + 0x000003B0: "CKM_PKCS5_PBKD2", + 0x000003C0: "CKM_PBA_SHA1_WITH_SHA1_HMAC", + 0x000003D0: "CKM_WTLS_PRE_MASTER_KEY_GEN", + 0x000003D1: "CKM_WTLS_MASTER_KEY_DERIVE", + 0x000003D2: "CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC", + 0x000003D3: "CKM_WTLS_PRF", + 0x000003D4: "CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE", + 0x000003D5: "CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE", + 0x00000400: "CKM_KEY_WRAP_LYNKS", + 0x00000401: "CKM_KEY_WRAP_SET_OAEP", + 0x00000500: "CKM_CMS_SIG", + 0x00000510: "CKM_KIP_DERIVE", + 0x00000511: "CKM_KIP_WRAP", + 0x00000512: "CKM_KIP_MAC", + 0x00000550: "CKM_CAMELLIA_KEY_GEN", + 0x00000551: "CKM_CAMELLIA_ECB", + 0x00000552: "CKM_CAMELLIA_CBC", + 0x00000553: "CKM_CAMELLIA_MAC", + 0x00000554: "CKM_CAMELLIA_MAC_GENERAL", + 0x00000555: "CKM_CAMELLIA_CBC_PAD", + 0x00000556: "CKM_CAMELLIA_ECB_ENCRYPT_DATA", + 0x00000557: "CKM_CAMELLIA_CBC_ENCRYPT_DATA", + 0x00000558: "CKM_CAMELLIA_CTR", + 0x00000560: "CKM_ARIA_KEY_GEN", + 0x00000561: "CKM_ARIA_ECB", + 0x00000562: "CKM_ARIA_CBC", + 0x00000563: "CKM_ARIA_MAC", + 0x00000564: "CKM_ARIA_MAC_GENERAL", + 0x00000565: "CKM_ARIA_CBC_PAD", + 0x00000566: "CKM_ARIA_ECB_ENCRYPT_DATA", + 0x00000567: "CKM_ARIA_CBC_ENCRYPT_DATA", + 0x00001000: "CKM_SKIPJACK_KEY_GEN", + 0x00001001: "CKM_SKIPJACK_ECB64", + 0x00001002: "CKM_SKIPJACK_CBC64", + 0x00001003: "CKM_SKIPJACK_OFB64", + 0x00001004: "CKM_SKIPJACK_CFB64", + 0x00001005: "CKM_SKIPJACK_CFB32", + 0x00001006: "CKM_SKIPJACK_CFB16", + 0x00001007: "CKM_SKIPJACK_CFB8", + 0x00001008: "CKM_SKIPJACK_WRAP", + 0x00001009: "CKM_SKIPJACK_PRIVATE_WRAP", + 0x0000100a: "CKM_SKIPJACK_RELAYX", + 0x00001010: "CKM_KEA_KEY_PAIR_GEN", + 0x00001011: "CKM_KEA_KEY_DERIVE", + 0x00001020: "CKM_FORTEZZA_TIMESTAMP", + 0x00001030: "CKM_BATON_KEY_GEN", + 0x00001031: "CKM_BATON_ECB128", + 0x00001032: "CKM_BATON_ECB96", + 0x00001033: "CKM_BATON_CBC128", + 0x00001034: "CKM_BATON_COUNTER", + 0x00001035: "CKM_BATON_SHUFFLE", + 0x00001036: "CKM_BATON_WRAP", + 0x00001040: "CKM_EC_KEY_PAIR_GEN", + 0x00001041: "CKM_ECDSA", + 0x00001042: "CKM_ECDSA_SHA1", + 0x00001050: "CKM_ECDH1_DERIVE", + 0x00001051: "CKM_ECDH1_COFACTOR_DERIVE", + 0x00001052: "CKM_ECMQV_DERIVE", + 0x00001060: "CKM_JUNIPER_KEY_GEN", + 0x00001061: "CKM_JUNIPER_ECB128", + 0x00001062: "CKM_JUNIPER_CBC128", + 0x00001063: "CKM_JUNIPER_COUNTER", + 0x00001064: "CKM_JUNIPER_SHUFFLE", + 0x00001065: "CKM_JUNIPER_WRAP", + 0x00001070: "CKM_FASTHASH", + 0x00001080: "CKM_AES_KEY_GEN", + 0x00001081: "CKM_AES_ECB", + 0x00001082: "CKM_AES_CBC", + 0x00001083: "CKM_AES_MAC", + 0x00001084: "CKM_AES_MAC_GENERAL", + 0x00001085: "CKM_AES_CBC_PAD", + 0x00001086: "CKM_AES_CTR", + 0x00001089: "CKM_AES_CMAC_GENERAL", + 0x0000108A: "CKM_AES_CMAC", + 0x00001090: "CKM_BLOWFISH_KEY_GEN", + 0x00001091: "CKM_BLOWFISH_CBC", + 0x00001092: "CKM_TWOFISH_KEY_GEN", + 0x00001093: "CKM_TWOFISH_CBC", + 0x00001100: "CKM_DES_ECB_ENCRYPT_DATA", + 0x00001101: "CKM_DES_CBC_ENCRYPT_DATA", + 0x00001102: "CKM_DES3_ECB_ENCRYPT_DATA", + 0x00001103: "CKM_DES3_CBC_ENCRYPT_DATA", + 0x00001104: "CKM_AES_ECB_ENCRYPT_DATA", + 0x00001105: "CKM_AES_CBC_ENCRYPT_DATA", + 0x00002000: "CKM_DSA_PARAMETER_GEN", + 0x00002001: "CKM_DH_PKCS_PARAMETER_GEN", + 0x00002002: "CKM_X9_42_DH_PARAMETER_GEN", + 0x00002109: "CKM_AES_KEY_WRAP", + 0x0000210A: "CKM_AES_KEY_WRAP_PAD", + 0x80000000: "CKM_VENDOR_DEFINED", + 0x00008000: "CKM_VENDOR_DEFINED_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 0: "CKM_CAST_KEY_GEN_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 1: "CKM_CAST_ECB_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 2: "CKM_CAST_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 3: "CKM_CAST_MAC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 4: "CKM_CAST3_KEY_GEN_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 5: "CKM_CAST3_ECB_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 6: "CKM_CAST3_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 7: "CKM_CAST3_MAC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 8: "CKM_PBE_MD2_DES_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 9: "CKM_PBE_MD5_DES_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 10: "CKM_PBE_MD5_CAST_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 11: "CKM_PBE_MD5_CAST3_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 12: "CKM_CONCATENATE_BASE_AND_KEY_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 13: "CKM_CONCATENATE_KEY_AND_BASE_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 14: "CKM_CONCATENATE_BASE_AND_DATA_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 15: "CKM_CONCATENATE_DATA_AND_BASE_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 16: "CKM_XOR_BASE_AND_DATA_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 17: "CKM_EXTRACT_KEY_FROM_KEY_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 18: "CKM_MD5_KEY_DERIVATION_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 19: "CKM_MD2_KEY_DERIVATION_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 20: "CKM_SHA1_KEY_DERIVATION_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 21: "CKM_GENERIC_SECRET_KEY_GEN_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 22: "CKM_CAST5_KEY_GEN_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 23: "CKM_CAST5_ECB_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 24: "CKM_CAST5_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 25: "CKM_CAST5_MAC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 26: "CKM_PBE_SHA1_CAST5_CBC_OLD_XXX", + CKM_VENDOR_DEFINED_OLD_XXX + 27: "CKM_KEY_TRANSLATION", + CKM_VENDOR_DEFINED + 27: "CKM_XOR_BASE_AND_KEY", + CKM_VENDOR_DEFINED_OLD_XXX + 28: "CKM_2DES_KEY_DERIVATION", + CKM_VENDOR_DEFINED_OLD_XXX + 29: "CKM_INDIRECT_LOGIN_REENCRYPT", + CKM_VENDOR_DEFINED_OLD_XXX + 30: "CKM_PBE_SHA1_DES3_EDE_CBC_OLD", + CKM_VENDOR_DEFINED_OLD_XXX + 31: "CKM_PBE_SHA1_DES2_EDE_CBC_OLD", + (CKM_VENDOR_DEFINED + 0x100): "CKM_HAS160", + (CKM_VENDOR_DEFINED + 0x101): "CKM_KCDSA_KEY_PAIR_GEN", + (CKM_VENDOR_DEFINED + 0x102): "CKM_KCDSA_HAS160", + (CKM_VENDOR_DEFINED + 0x103): "CKM_SEED_KEY_GEN", + (CKM_VENDOR_DEFINED + 0x104): "CKM_SEED_ECB", + (CKM_VENDOR_DEFINED + 0x105): "CKM_SEED_CBC", + (CKM_VENDOR_DEFINED + 0x106): "CKM_SEED_CBC_PAD", + (CKM_VENDOR_DEFINED + 0x107): "CKM_SEED_MAC", + (CKM_VENDOR_DEFINED + 0x108): "CKM_SEED_MAC_GENERAL", + (CKM_VENDOR_DEFINED + 0x109): "CKM_KCDSA_SHA1", + (CKM_VENDOR_DEFINED + 0x10A): "CKM_KCDSA_SHA224", + (CKM_VENDOR_DEFINED + 0x10B): "CKM_KCDSA_SHA256", + (CKM_VENDOR_DEFINED + 0x10C): "CKM_KCDSA_SHA384", + (CKM_VENDOR_DEFINED + 0x10D): "CKM_KCDSA_SHA512", + (CKM_VENDOR_DEFINED + 0x10F): "CKM_KCDSA_PARAMETER_GEN", + (CKM_VENDOR_DEFINED + 0x110): "CKM_SHA224_RSA_PKCS_OLD", + (CKM_VENDOR_DEFINED + 0x111): "CKM_SHA224_RSA_PKCS_PSS_OLD", + (CKM_VENDOR_DEFINED + 0x112): "CKM_SHA224_OLD", + (CKM_VENDOR_DEFINED + 0x113): "CKM_SHA224_HMAC_OLD", + (CKM_VENDOR_DEFINED + 0x114): "CKM_SHA224_HMAC_GENERAL_OLD", + (CKM_VENDOR_DEFINED + 0x115): "CKM_SHA224_KEY_DERIVATION_OLD", + (CKM_VENDOR_DEFINED + 0x116): "CKM_DES3_CTR", + (CKM_VENDOR_DEFINED + 0x118): "CKM_AES_CFB8", + (CKM_VENDOR_DEFINED + 0x119): "CKM_AES_CFB128", + (CKM_VENDOR_DEFINED + 0x11a): "CKM_AES_OFB", + 0x00001087 : "CKM_AES_GCM", # Used to be vendor defined + 0x11c + (CKM_VENDOR_DEFINED + 0x11d): "CKM_ARIA_CFB8", + (CKM_VENDOR_DEFINED + 0x11e): "CKM_ARIA_CFB128", + (CKM_VENDOR_DEFINED + 0x11f): "CKM_ARIA_OFB", + (CKM_VENDOR_DEFINED + 0x120): "CKM_ARIA_CTR", + (CKM_VENDOR_DEFINED + 0x121): "CKM_ARIA_GCM", + (CKM_VENDOR_DEFINED + 0x122): "CKM_ECDSA_SHA224", + (CKM_VENDOR_DEFINED + 0x123): "CKM_ECDSA_SHA256", + (CKM_VENDOR_DEFINED + 0x124): "CKM_ECDSA_SHA384", + (CKM_VENDOR_DEFINED + 0x125): "CKM_ECDSA_SHA512", + (CKM_VENDOR_DEFINED + 0x126): "CKM_AES_GMAC", + (CKM_VENDOR_DEFINED + 0x128): "CKM_ARIA_CMAC", + (CKM_VENDOR_DEFINED + 0x129): "CKM_ARIA_CMAC_GENERAL", + (CKM_VENDOR_DEFINED + 0x12c): "CKM_SEED_CMAC", + (CKM_VENDOR_DEFINED + 0x12d): "CKM_SEED_CMAC_GENERAL", + (CKM_VENDOR_DEFINED + 0x12e): "CKM_DES3_CBC_PAD_IPSEC", + (CKM_VENDOR_DEFINED + 0x12f): "CKM_AES_CBC_PAD_IPSEC", + (CKM_VENDOR_DEFINED + 0x130): "CKM_ARIA_L_ECB", + (CKM_VENDOR_DEFINED + 0x131): "CKM_ARIA_L_CBC", + (CKM_VENDOR_DEFINED + 0x132): "CKM_ARIA_L_CBC_PAD", + (CKM_VENDOR_DEFINED + 0x133): "CKM_ARIA_L_MAC", + (CKM_VENDOR_DEFINED + 0x134): "CKM_ARIA_L_MAC_GENERAL", + (CKM_VENDOR_DEFINED + 0x135): "CKM_SHA224_RSA_X9_31", + (CKM_VENDOR_DEFINED + 0x136): "CKM_SHA256_RSA_X9_31", + (CKM_VENDOR_DEFINED + 0x137): "CKM_SHA384_RSA_X9_31", + (CKM_VENDOR_DEFINED + 0x138): "CKM_SHA512_RSA_X9_31", + (CKM_VENDOR_DEFINED + 0x139): "CKM_SHA1_RSA_X9_31_NON_FIPS", + (CKM_VENDOR_DEFINED + 0x13a): "CKM_SHA224_RSA_X9_31_NON_FIPS", + (CKM_VENDOR_DEFINED + 0x13b): "CKM_SHA256_RSA_X9_31_NON_FIPS", + (CKM_VENDOR_DEFINED + 0x13c): "CKM_SHA384_RSA_X9_31_NON_FIPS", + (CKM_VENDOR_DEFINED + 0x13d): "CKM_SHA512_RSA_X9_31_NON_FIPS", + (CKM_VENDOR_DEFINED + 0x13e): "CKM_RSA_X9_31_NON_FIPS", + (CKM_VENDOR_DEFINED + 0x140): "CKM_DSA_SHA224", + (CKM_VENDOR_DEFINED + 0x141): "CKM_DSA_SHA256", + (CKM_VENDOR_DEFINED + 0x142): "CKM_RSA_FIPS_186_3_AUX_PRIME_KEY_PAIR_GEN", + (CKM_VENDOR_DEFINED + 0x143): "CKM_RSA_FIPS_186_3_PRIME_KEY_PAIR_GEN", + (CKM_VENDOR_DEFINED + 0x144): "CKM_SEED_CTR", + (CKM_VENDOR_DEFINED + 0x145): "CKM_KCDSA_HAS160_NO_PAD", + (CKM_VENDOR_DEFINED + 0x146): "CKM_KCDSA_SHA1_NO_PAD", + (CKM_VENDOR_DEFINED + 0x147): "CKM_KCDSA_SHA224_NO_PAD", + (CKM_VENDOR_DEFINED + 0x148): "CKM_KCDSA_SHA256_NO_PAD", + (CKM_VENDOR_DEFINED + 0x149): "CKM_KCDSA_SHA384_NO_PAD", + (CKM_VENDOR_DEFINED + 0x151): "CKM_KCDSA_SHA512_NO_PAD", + (CKM_VENDOR_DEFINED + 0x150): "CKM_DES3_X919_MAC", + (CKM_VENDOR_DEFINED + 0x160): "CKM_ECDSA_KEY_PAIR_GEN_W_EXTRA_BITS", + (CKM_VENDOR_DEFINED + 0x161): "CKM_ECDSA_GBCS_SHA256", + (CKM_VENDOR_DEFINED + 0x170): "CKM_AES_KW", + (CKM_VENDOR_DEFINED + 0x171): "CKM_AES_KWP", + (CKM_VENDOR_DEFINED + 0x172): "CKM_TDEA_KW", + (CKM_VENDOR_DEFINED + 0x173): "CKM_TDEA_KWP", + (CKM_VENDOR_DEFINED + 0x200): "CKM_AES_CBC_PAD_EXTRACT", + (CKM_VENDOR_DEFINED + 0x201): "CKM_AES_CBC_PAD_INSERT", + (CKM_VENDOR_DEFINED + 0x202): "CKM_AES_CBC_PAD_EXTRACT_FLATTENED", + (CKM_VENDOR_DEFINED + 0x203): "CKM_AES_CBC_PAD_INSERT_FLATTENED", + (CKM_VENDOR_DEFINED + 0x204): "CKM_AES_CBC_PAD_EXTRACT_DOMAIN_CTRL", + (CKM_VENDOR_DEFINED + 0x205): "CKM_AES_CBC_PAD_INSERT_DOMAIN_CTRL", + (CKM_VENDOR_DEFINED + 0x502): "CKM_PLACE_HOLDER_FOR_ERACOME_DEF_IN_SHIM", + (CKM_VENDOR_DEFINED + 0x611): "CKM_DES2_DUKPT_PIN", + (CKM_VENDOR_DEFINED + 0x612): "CKM_DES2_DUKPT_MAC", + (CKM_VENDOR_DEFINED + 0x613): "CKM_DES2_DUKPT_MAC_RESP", + (CKM_VENDOR_DEFINED + 0x614): "CKM_DES2_DUKPT_DATA", + (CKM_VENDOR_DEFINED + 0x615): "CKM_DES2_DUKPT_DATA_RESP", + (CKM_VENDOR_DEFINED + 0xA00): "CKM_ECIES", + (CKM_VENDOR_DEFINED + 0xA01): "CKM_XOR_BASE_AND_DATA_W_KDF", + (CKM_VENDOR_DEFINED + 0xA02): "CKM_NIST_PRF_KDF", + (CKM_VENDOR_DEFINED + 0xA03): "CKM_PRF_KDF", + (CKM_VENDOR_DEFINED + 0xA04): "CKM_AES_XTS", + (CKM_VENDOR_DEFINED + 0xB01): "CKM_SM3", + (CKM_VENDOR_DEFINED + 0xB02): "CKM_SM3_HMAC", + (CKM_VENDOR_DEFINED + 0xB03): "CKM_SM3_HMAC_GENERAL", + (CKM_VENDOR_DEFINED + 0xB04): "CKM_SM3_KEY_DERIVATION" +} diff --git a/pycryptoki/mechanism/helpers.py b/pycryptoki/mechanism/helpers.py index 5e19263..cbe62e1 100755 --- a/pycryptoki/mechanism/helpers.py +++ b/pycryptoki/mechanism/helpers.py @@ -8,6 +8,7 @@ from six import integer_types +from pycryptoki.lookup_dicts import MECH_NAME_LOOKUP from ..cryptoki import CK_AES_CBC_PAD_EXTRACT_PARAMS, CK_MECHANISM, \ CK_ULONG, CK_ULONG_PTR, CK_AES_CBC_PAD_INSERT_PARAMS, CK_BYTE, CK_BYTE_PTR, CK_MECHANISM_TYPE from ..defines import * @@ -88,6 +89,16 @@ def __init__(self, mech_type="UNKNOWN", params=None): "{}".format(self.__class__, "\n\t".join(missing_params))) + def __repr__(self): + """ + Return a human-readable string of the mechanism data. + """ + # todo: lookup dict for the mechanism name. + return "{}(mech_type: {}," \ + " {})".format(self.__class__.__name__, + MECH_NAME_LOOKUP.get(self.mech_type, "UNKNOWN"), + ", ".join("{}: {}".format(k, v) for k, v in self.params.items())) + def to_c_mech(self): """ Create the Mechanism structure & set the mech type to the passed-in flavor. From 84b1e996bbb1dfb096579e28ebc39766fec62645 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 24 Aug 2017 09:28:58 -0400 Subject: [PATCH 094/109] LA-2605 Add CA_GetFirmwareVersion for 6.3+ According to DJ: With the version of 6.x (product/client version... not FW version) that came out before 7.0, we switch from major=X and minor=(Y*10+Z) to major=X and minor=Y and Z is no longer available. We do have a CA_GetFirmwareVersion() function that returns X,Y and Z as three individual values. Added reference to CA_GetFirmwareVersion(), as well as a function that will get the current FW, attempting prior function first, then defaulting to C_GetTokenInfo Change-Id: Icd9a9e7a8ca39a3ca1c3e414510a658ac7dafc30 --- pycryptoki/cryptoki.py | 8 +++++++ pycryptoki/session_management.py | 36 ++++++++++++++++++++++++++++++-- tests/functional/conftest.py | 8 ++----- 3 files changed, 44 insertions(+), 8 deletions(-) diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index 21eb47a..3c2c24a 100755 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -1328,6 +1328,8 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CK_CA_GetSlotListFromServerInstance = CFUNCTYPE(CK_RV, CK_ULONG, CK_SLOT_ID_PTR, CK_ULONG_PTR) CK_CA_PerformSelfTest = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR) +CK_CA_GetFirmwareVersion = CFUNCTYPE(CK_RV, CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR) + if 'win' in sys.platform: CK_SFNT_CA_FUNCTION_LIST._pack_ = 1 CK_SFNT_CA_FUNCTION_LIST._fields_ = [ @@ -1564,6 +1566,7 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): ('CA_GetServerInstanceBySlotID', CK_CA_GetServerInstanceBySlotID), ('CA_GetSlotListFromServerInstance', CK_CA_GetSlotListFromServerInstance), ('CA_PerformSelfTest', CK_CA_PerformSelfTest), + ('CA_GetFirmwareVersion', CK_CA_GetFirmwareVersion), ] CA_GetFunctionList = make_late_binding_function('CA_GetFunctionList') CA_GetFunctionList.restype = CK_RV @@ -2355,6 +2358,11 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CA_Get = make_late_binding_function('CA_Get') CA_Get.restype = CK_RV CA_Get.argtypes = [CK_SLOT_ID, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR] + +CA_GetFirmwareVersion = make_late_binding_function('CA_GetFirmwareVersion') +CA_GetFirmwareVersion.restype = CK_RV +CA_GetFirmwareVersion.argypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] + CK_GetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(c_int)) CK_ResetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 546e851..1fed2b1 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -19,7 +19,7 @@ CK_USER_TYPE, CK_TOKEN_INFO, CK_VOID_PTR, - CK_BYTE, CK_INFO, C_GetInfo) + CK_BYTE, CK_INFO, C_GetInfo, CA_GetFirmwareVersion, c_ulong) # Cryptoki Functions from .cryptoki import (C_Initialize, C_GetSlotList, @@ -40,7 +40,7 @@ CA_Restart, CA_SetApplicationID) from .defines import CKR_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION -from .exceptions import make_error_handle_function +from .exceptions import make_error_handle_function, LunaCallException LOG = logging.getLogger(__name__) @@ -468,3 +468,35 @@ def ca_restart(slot): ca_restart_ex = make_error_handle_function(ca_restart) + + +def get_firmware_version(slot): + """ + Returns a string representing the firmware version of the given slot. + + It will first try to call ``CA_GetFirmwareVersion``, and if that fails (not present on older + cryptoki libraries), will call ``C_GetTokenInfo``. + + :param int slot: Token slot number + :return: Firmware String in the format "X.Y.Z", where X is major, Y is minor, Z is subminor. + :rtype: str + """ + + # Note, CA_GetFirmwareVersion should be available from 6.3+. + try: + ul_major, ul_minor, ul_subminor = c_ulong(), c_ulong(), c_ulong() + ret = CA_GetFirmwareVersion(slot, byref(ul_major), byref(ul_minor), byref(ul_subminor)) + if ret != 0: + LOG.warning("Failed retrieving Firmware information from slot '%s'", slot) + raise LunaCallException(ret, "CA_GetFirmwareVersion", (0,)) + else: + major = ul_major.value + minor = ul_minor.value + subminor = ul_subminor.value + except AttributeError: + raw_firmware = c_get_token_info_ex(slot)['firmwareVersion'] + major = raw_firmware.major + minor = raw_firmware.minor / 10 + subminor = raw_firmware.minor % 10 + + return "{}.{}.{}".format(major, minor, subminor) diff --git a/tests/functional/conftest.py b/tests/functional/conftest.py index 31625e9..455b20e 100644 --- a/tests/functional/conftest.py +++ b/tests/functional/conftest.py @@ -16,7 +16,7 @@ from pycryptoki.object_attr_lookup import c_find_objects_ex from pycryptoki.session_management import c_initialize_ex, c_close_all_sessions_ex, \ ca_factory_reset_ex, c_open_session_ex, login_ex, c_finalize_ex, \ - c_close_session, c_logout, c_get_token_info_ex + c_close_session, c_logout, c_get_token_info_ex, get_firmware_version from pycryptoki.test_functions import LunaException from pycryptoki.token_management import c_init_token_ex, c_get_mechanism_list_ex @@ -87,11 +87,7 @@ def pytest_configure(config): flags = token_info['flags'] is_ped = (flags & CKF_PROTECTED_AUTHENTICATION_PATH) != 0 hsm_config["is_ped"] = is_ped - raw_firmware = token_info['firmwareVersion'] - hsm_config['firmware'] = "{}.{}.{}".format(raw_firmware.major, - raw_firmware.minor / 10, - raw_firmware.minor % 10) - + hsm_config['firmware'] = get_firmware_version(slot) if is_ped: admin_pwd = None co_pwd = config.getoption("copassword", default=None) From 8733422133a0ea9403495dac65047d180841109f Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 24 Aug 2017 10:37:33 -0400 Subject: [PATCH 095/109] LA-2605 Fix typo in argtypes Was causing attribute error, and missing a branch. Change-Id: I0048482179b0484d01abc68548a0cd7bef0a176d --- pycryptoki/cryptoki.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pycryptoki/cryptoki.py b/pycryptoki/cryptoki.py index 3c2c24a..ad95c51 100755 --- a/pycryptoki/cryptoki.py +++ b/pycryptoki/cryptoki.py @@ -2361,7 +2361,7 @@ class CK_SFNT_CA_FUNCTION_LIST(Structure): CA_GetFirmwareVersion = make_late_binding_function('CA_GetFirmwareVersion') CA_GetFirmwareVersion.restype = CK_RV -CA_GetFirmwareVersion.argypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] +CA_GetFirmwareVersion.argtypes = [CK_SLOT_ID, CK_ULONG_PTR, CK_ULONG_PTR, CK_ULONG_PTR] CK_GetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID, POINTER(c_int)) CK_ResetTotalOperations = CFUNCTYPE(CK_RV, CK_SLOT_ID) From 523f228248cb2c26d5eb6bbcfbe01e48434b5f75 Mon Sep 17 00:00:00 2001 From: hhahn Date: Wed, 16 Aug 2017 15:33:29 -0400 Subject: [PATCH 096/109] LA-2599 Pycryptoki implement KDF Mechanism * Adding PRF KDF mechanism. Change-Id: Ia371bcd4c6d1cb69fa7c84c84beecf812899596f --- pycryptoki/mechanism/__init__.py | 9 +++++- pycryptoki/mechanism/kdf.py | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 pycryptoki/mechanism/kdf.py diff --git a/pycryptoki/mechanism/__init__.py b/pycryptoki/mechanism/__init__.py index 2baaa70..70812be 100644 --- a/pycryptoki/mechanism/__init__.py +++ b/pycryptoki/mechanism/__init__.py @@ -74,6 +74,7 @@ def to_c_mech(self): RC5Mechanism) from .rsa import (RSAPKCSOAEPMechanism, RSAPKCSPSSMechanism) +from .kdf import PRFKDFDeriveMechanism from ..defines import (CKM_DES_CBC, CKM_DES3_CBC, CKM_CAST3_CBC, @@ -132,7 +133,11 @@ def to_c_mech(self): CKM_XOR_BASE_AND_DATA, CKM_CONCATENATE_DATA_AND_BASE, - CKM_ECDH1_DERIVE, CKM_AES_CTR, CKM_AES_GMAC) + CKM_ECDH1_DERIVE, + CKM_AES_CTR, + CKM_AES_GMAC, + + CKM_PRF_KDF) MECH_LOOKUP = { # Iv @@ -199,4 +204,6 @@ def to_c_mech(self): CKM_CONCATENATE_DATA_AND_BASE: StringDataDerivationMechanism, CKM_ECDH1_DERIVE: ECDH1DeriveMechanism, + + CKM_PRF_KDF: PRFKDFDeriveMechanism, } diff --git a/pycryptoki/mechanism/kdf.py b/pycryptoki/mechanism/kdf.py new file mode 100644 index 0000000..48e9999 --- /dev/null +++ b/pycryptoki/mechanism/kdf.py @@ -0,0 +1,49 @@ +"""KDF-specific mechanism implementations.""" + +from _ctypes import pointer, sizeof +from ctypes import cast, c_void_p + +from . import Mechanism +from ..attributes import to_byte_array +from ..cryptoki import CK_PRF_KDF_PARAMS, CK_BYTE_PTR, CK_ULONG + + +class PRFKDFDeriveMechanism(Mechanism): + """PRF KDF-specific mechanism.""" + REQUIRED_PARAMS = ['prf_type', 'label', 'context', 'counter', 'encoding_scheme'] + + def to_c_mech(self): + """ + Create the Param structure, then convert the data into byte arrays. + + :return: :class:`~pycryptoki.cryptoki.CK_MECHANISM` + + """ + super(PRFKDFDeriveMechanism, self).to_c_mech() + params = CK_PRF_KDF_PARAMS() + params.prfType = self.params['prf_type'] + if self.params['label'] is None: + label = '' + label_len = 0 + else: + label, label_len = to_byte_array(self.params['label']) + if self.params['context'] is None: + context = '' + context_len = 0 + else: + context, context_len = to_byte_array(self.params['context']) + if self.params['counter'] is None: + counter = 1 + else: + counter = self.params['counter'] + ul_encoding_scheme = self.params['encoding_scheme'] + + params.pLabel = cast(label, CK_BYTE_PTR) + params.ulLabelLen = label_len + params.pContext = cast(context, CK_BYTE_PTR) + params.ulContextLen = context_len + params.ulCounter = counter + params.ulEncodingScheme = ul_encoding_scheme + self.mech.pParameter = cast(pointer(params), c_void_p) + self.mech.usParameterLen = CK_ULONG(sizeof(params)) + return self.mech From 8270aeef9803611b1e938df26f77edad06e44f9c Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 19 Sep 2017 09:55:54 -0400 Subject: [PATCH 097/109] LA-2679 Merging changes from master to release * rpyc_pycryptoki logging options * pycryptoki_client logging changes * ca_sim* methods * Fixed RSA OAEP mechanism creation -- Encoded source parameter data is allowed to be NULL. Change-Id: I9c2e39dccfa69f347f0c587b96887a8ca2f39693 --- pycryptoki/backup.py | 158 ++++++++++++++++++++++++--- pycryptoki/common_utils.py | 19 ++++ pycryptoki/daemon/rpyc_pycryptoki.py | 95 +++++++++++----- pycryptoki/exceptions.py | 7 +- pycryptoki/mechanism/rsa.py | 6 +- pycryptoki/pycryptoki_client.py | 83 +++++++++++--- 6 files changed, 307 insertions(+), 61 deletions(-) diff --git a/pycryptoki/backup.py b/pycryptoki/backup.py index 46a3073..451bc5b 100755 --- a/pycryptoki/backup.py +++ b/pycryptoki/backup.py @@ -1,12 +1,32 @@ +""" +Backup related commands +""" import logging from ctypes import byref -from .cryptoki import CA_OpenSecureToken, CA_CloseSecureToken, CA_Extract, CA_Insert, CK_ULONG -from .mechanism import Mechanism +from .common_utils import AutoCArray, refresh_c_arrays +from .cryptoki import CA_OpenSecureToken, CA_CloseSecureToken, CA_Extract, CA_Insert, \ + CK_ULONG, \ + CA_SIMExtract, CK_BYTE, string_at, create_string_buffer, POINTER, cast, pointer, \ + CK_BYTE_PTR, c_ubyte, CA_SIMInsert +from .defines import (CKA_SIM_NO_AUTHORIZATION, CKA_SIM_PASSWORD, CKA_SIM_CHALLENGE, + CKA_SIM_SECURE_PORT, CKA_SIM_PORTABLE_NO_AUTHORIZATION, + CKA_SIM_PORTABLE_PASSWORD, CKA_SIM_PORTABLE_CHALLENGE, + CKA_SIM_PORTABLE_SECURE_PORT) from .exceptions import make_error_handle_function +from .mechanism import parse_mechanism logger = logging.getLogger(__name__) +SIM_AUTH_FORMS = (CKA_SIM_NO_AUTHORIZATION, + CKA_SIM_PASSWORD, + CKA_SIM_CHALLENGE, + CKA_SIM_SECURE_PORT, + CKA_SIM_PORTABLE_NO_AUTHORIZATION, + CKA_SIM_PORTABLE_PASSWORD, + CKA_SIM_PORTABLE_CHALLENGE, + CKA_SIM_PORTABLE_SECURE_PORT) + def ca_open_secure_token(h_session, storage_path, dev_ID, mode): """ @@ -43,18 +63,16 @@ def ca_close_secure_token(h_session, h_ID): ca_close_secure_token_ex = make_error_handle_function(ca_close_secure_token) -# noinspection PyIncorrectDocstring -def ca_extract(h_session, mech_type, mech_params): +def ca_extract(h_session, mechanism): """ - :param mech_params: :param int h_session: Session handle + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. """ - mech = Mechanism(mech_type, params=mech_params) - - cmech = mech.to_c_mech() - ret = CA_Extract(h_session, cmech) + mech = parse_mechanism(mechanism) + ret = CA_Extract(h_session, mech) return ret @@ -62,19 +80,125 @@ def ca_extract(h_session, mech_type, mech_params): ca_extract_ex = make_error_handle_function(ca_extract) -def ca_insert(h_session, mech_type, mech_params): +def ca_insert(h_session, mechanism): """ :param int h_session: Session handle - :param py_mechanism_dict: - :param params_type_string: - + :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function + for possible values. """ - mech = Mechanism(mech_type, params=mech_params) - - cmech = mech.to_c_mech() - ret = CA_Insert(h_session, cmech) + mech = parse_mechanism(mechanism) + ret = CA_Insert(h_session, mech) return ret ca_insert_ex = make_error_handle_function(ca_insert) + + +def ca_sim_extract(h_session, key_handles, authform, auth_secrets=None, subset_size=0, + delete_after_extract=False): + """ + Extract multiple keys to a wrapped blob. The returned blob can then be written into + a file. + + :param int h_session: Session handle + :param list[int] key_handles: List of key handles to extract + :param int authform: Type of authentication to use. See :class:`pycryptoki.backup.SIM_AUTH` + for details + :param list(str) auth_secrets: Authorization secrets to use (Length will correspond to the + ``N`` value in ckdemo) + :param int subset_size: Subset size required for key use (Corresponds to the ``M`` value in + ckdemo) + :param bool delete_after_extract: If true, will destroy the original keys after they have been + extracted. + :return: retcode, blob_data tuple. + """ + + if auth_secrets is None: + auth_secrets = [] + + if authform not in SIM_AUTH_FORMS: + raise ValueError("Invalid authform, import and use SIM_AUTH to select an authentication " + "type.") + + if subset_size > len(auth_secrets): + raise ValueError("Subset size cannot be larger than the N value (length of auth secrets)") + + auth_secrets = AutoCArray(data=[cast(pointer(create_string_buffer(x, len(x))), + CK_BYTE_PTR) for x in auth_secrets], + ctype=POINTER(CK_BYTE)) + c_key_handles = AutoCArray(key_handles) + blob_data = AutoCArray(ctype=c_ubyte) + + @refresh_c_arrays(1) + def extract(): + """ + Closure to allow us to get the size of the blob_data. + """ + blobarr, bloblen = blob_data.array, blob_data.size + return CA_SIMExtract(h_session, + len(c_key_handles), c_key_handles.array, + CK_ULONG(len(auth_secrets)), CK_ULONG(subset_size), + authform, + auth_secrets.size, auth_secrets.array, + delete_after_extract, + bloblen, blobarr) + + ret = extract() + if ret == 0: + ret_blob_data = string_at(blob_data.array, len(blob_data)) + else: + ret_blob_data = None + return ret, ret_blob_data + + +ca_sim_extract_ex = make_error_handle_function(ca_sim_extract) + + +def ca_sim_insert(h_session, blob_data, authform, auth_secrets=None): + """ + Insert keys into the HSM from blob data that was wrapped off using SIM. + + :param int h_session: Session handle + :param str blob_data: Read in raw wrapped data. Typically read in from a file. + :param int authform: Type of authentication to use. See :class:`pycryptoki.backup.SIM_AUTH` + for details + :param list[str] auth_secrets: Authorization secrets to use (Length will correspond to the + ``N`` value in ckdemo) + :return: retcode, keys tuple, where ``keys`` is a list of integers. + """ + + if auth_secrets is None: + auth_secrets = [] + + if authform not in SIM_AUTH_FORMS: + raise ValueError("Invalid authform, import and use SIM_AUTH to select an authentication " + "type.") + + auth_secrets = AutoCArray(data=[cast(pointer(create_string_buffer(x, len(x))), + CK_BYTE_PTR) for x in auth_secrets], + ctype=POINTER(CK_BYTE)) + c_key_handles = AutoCArray() + c_blob_data = create_string_buffer(blob_data, len(blob_data)) + + @refresh_c_arrays(1) + def insert(): + """ + Closure to allow us to get the size of the blob_data. + """ + key_array, key_array_len = c_key_handles.array, c_key_handles.size + return CA_SIMInsert(h_session, + CK_ULONG(len(auth_secrets)), authform, + auth_secrets.size, auth_secrets.array, + len(blob_data), cast(c_blob_data, POINTER(CK_BYTE)), + key_array_len, key_array) + + ret = insert() + if ret == 0: + handles = [int(x) for x in c_key_handles] + else: + handles = None + return ret, handles + + +ca_sim_insert_ex = make_error_handle_function(ca_sim_insert) diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index 93f2e91..eddef25 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -72,6 +72,15 @@ def array(self): If size is not None, and internal array is not None, returna pointer to the allocated memory of the internal array. + .. warning:: This will ONLY work properly if ``array`` is read before ``size``! + You can assign to temporary values to work around this if the PKCS call requires the + size first:: + + array, len = autoarray.array, autoarray.size + + This is because after ``size`` is read, ``array`` is initialized to a C array of the + given value. + :return: pointer to the internal array. :rtype: POINTER @@ -92,6 +101,16 @@ def size(self): """ Return a pointer to a c_ulong + .. warning:: This will ONLY work properly if ``array`` is read before ``size``! + You can assign to temporary values to work around this if the PKCS call requires the + size first:: + + array, len = autoarray.array, autoarray.size + + This is because after ``size`` is read, ``array`` is initialized to a C array of the + given value. + + :return: Pointer to a CK_ULONG :rtype: pointer """ diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index c5131b3..b5e4b25 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -19,25 +19,27 @@ """ from __future__ import print_function -import logging import multiprocessing import os import signal import sys import time -from optparse import OptionParser +from argparse import ArgumentParser +from logging.handlers import RotatingFileHandler import rpyc from rpyc.utils.server import ThreadedServer import pycryptoki +from pycryptoki.attributes import * from pycryptoki.audit_handling import (ca_get_time, ca_get_time_ex, ca_init_audit, ca_init_audit_ex, ca_time_sync, ca_time_sync_ex) from pycryptoki.backup import (ca_open_secure_token, ca_open_secure_token_ex, ca_close_secure_token, ca_close_secure_token_ex, ca_extract, ca_extract_ex, - ca_insert, ca_insert_ex) + ca_insert, ca_insert_ex, ca_sim_insert, ca_sim_insert_ex, + ca_sim_extract_ex, ca_sim_extract) from pycryptoki.cryptoki import CK_ULONG from pycryptoki.encryption import (c_encrypt, c_encrypt_ex, c_decrypt, c_decrypt_ex, @@ -133,7 +135,7 @@ CRYPTO_OPS = pycryptoki.cryptoki.__all__[:] -logger = logging.getLogger(__name__) +MAX_LOG_SIZE = 5242880 class PycryptokiService(rpyc.SlaveService): @@ -162,6 +164,14 @@ def _rpyc_getattr(self, name): name = "exposed_" + name return getattr(self, name) + # attribute transforms + exposed_to_byte_array = staticmethod(to_byte_array) + exposed_to_char_array = staticmethod(to_char_array) + exposed_to_bool = staticmethod(to_bool) + exposed_to_long = staticmethod(to_long) + exposed_to_ck_date = staticmethod(to_ck_date) + exposed_to_subattributes = staticmethod(to_sub_attributes) + # encryption.py exposed_c_wrap_key = staticmethod(c_wrap_key) exposed_c_wrap_key_ex = staticmethod(c_wrap_key_ex) @@ -267,6 +277,10 @@ def _rpyc_getattr(self, name): exposed_ca_extract_ex = staticmethod(ca_extract_ex) exposed_ca_insert = staticmethod(ca_insert) exposed_ca_insert_ex = staticmethod(ca_insert_ex) + exposed_ca_sim_insert = staticmethod(ca_sim_insert) + exposed_ca_sim_insert_ex = staticmethod(ca_sim_insert_ex) + exposed_ca_sim_extract = staticmethod(ca_sim_extract) + exposed_ca_sim_extract_ex = staticmethod(ca_sim_extract_ex) # audit_handling.py exposed_ca_get_time = staticmethod(ca_get_time) @@ -401,28 +415,57 @@ def sighandler(signum, frame): return server -if __name__ == '__main__': +def configure_logging(logfile=None): + """ + Setup logging. If a log file is specified, will log to that file. + + :param str logfile: Log file path/name to use for logging. + :return: Configured logger. + """ + logger = logging.getLogger("pycryptoki") + logger.setLevel(getattr(logging, args.loglevel)) + if not logfile: + handler = logging.StreamHandler(sys.stdout) + else: + # 5 megabyte file, max of 10 files. + handler = RotatingFileHandler(logfile, maxBytes=MAX_LOG_SIZE, backupCount=10) + handler.setFormatter(logging.Formatter('%(asctime)s:%(name)s:%(levelname)s: %(message)s')) + logger.addHandler(handler) + return logger - logging.basicConfig(stream=sys.stdout, - level=logging.DEBUG, - format='%(asctime)s:%(name)s:%(levelname)s: %(message)s') - logger = logging.getLogger(__name__) - - parser = OptionParser() - parser.add_option("-i", "--ip_address", dest="i", - help="pycryptoki daemon IP address", metavar="") - parser.add_option("-p", "--port", dest="p", - help="pycryptoki daemon IP port", metavar="") - parser.add_option("-f", "--forked", dest="forked", - help="Fork the daemon from the parent process so we can recover from " - "segfaults", default=False, action="store_true") - (options, args) = parser.parse_args() - - # Default arguments - ip = options.i if options.i is not None else 'localhost' - port = int(options.p if options.p is not None else '8001') - logger.info("Pycryptoki Daemon ip=" + str(ip) + ", port=" + - str(port) + ", PID=" + str(os.getpid())) + +if __name__ == '__main__': + parser = ArgumentParser() + parser.add_argument("-i", "--ip_address", + dest="i", + help="pycryptoki daemon IP address", + metavar="", + default="localhost", + action="store") + parser.add_argument("-p", "--port", dest="p", + help="pycryptoki daemon IP port", metavar="", + default=8001, + action="store", + type=int) + parser.add_argument("-f", "--forked", dest="forked", + help="Fork the daemon from the parent process so we can recover from " + "segfaults", default=False, action="store_true") + parser.add_argument("-l", "--loglevel", + choices=["DEBUG", "INFO", "WARNING", "ERROR"], + default="DEBUG", + action="store", + help="Log level.") + parser.add_argument("-lf", "--logfile", + action="store", + dest="logfile", + help="Specifies a logfile to output to. Will perform log rotation based " + "on file size. If specified, will NOT output to stdout.") + args = parser.parse_args() + ip = args.i + port = args.p + + logger = configure_logging(args.logfile) + logger.info("Pycryptoki Daemon ip={}, port={}, PID={}".format(ip, port, os.getpid())) server_config = {'allow_public_attrs': True, 'allow_all_attrs': True, @@ -435,7 +478,7 @@ def sighandler(signum, frame): ip, port, server_config)) - if options.forked: + if args.forked: logger.info("Starting PycryptokiServer in a separate process...") server = create_server_subprocess(**server_kwargs) if server.exitcode is not None and not server.is_alive(): diff --git a/pycryptoki/exceptions.py b/pycryptoki/exceptions.py index 2bab122..a41f4f3 100644 --- a/pycryptoki/exceptions.py +++ b/pycryptoki/exceptions.py @@ -2,6 +2,7 @@ Exception-s and exception handling code. """ import inspect +import logging from functools import wraps from six import integer_types @@ -9,6 +10,8 @@ from .defines import CKR_OK from .lookup_dicts import ret_vals_dictionary, ATTR_NAME_LOOKUP +LOG = logging.getLogger(__name__) + def make_error_handle_function(luna_function): """This function is a helper function that creates a new function which checks the @@ -127,7 +130,9 @@ def check_luna_exception(ret, luna_function, args, kwargs): msg = "\t\t%s: %s" % (key, value) log_list.append(msg) - arg_string = "{}".format("\n".join(log_list)) + arg_string = "({})".format("\n".join(log_list)) + LOG.debug("Call to %s returned %s (%s)", luna_function, + ret_vals_dictionary.get(ret, "Unknown"), ret) if ret != CKR_OK: raise LunaCallException(ret, luna_function.__name__, arg_string) diff --git a/pycryptoki/mechanism/rsa.py b/pycryptoki/mechanism/rsa.py index 01f05ff..ff4e8a8 100644 --- a/pycryptoki/mechanism/rsa.py +++ b/pycryptoki/mechanism/rsa.py @@ -32,7 +32,11 @@ def to_c_mech(self): # /group__SEC__12__1__7__PKCS____1__RSA__OAEP__MECHANISM__PARAMETERS.html # there is only one encoding parameter source. oaep_params.source = CK_ULONG(CKZ_DATA_SPECIFIED) - data, data_len = to_byte_array(self.params.get('sourceData', '')) + if 'sourceData' in self.params: + data, data_len = to_byte_array(self.params['sourceData']) + else: + data = None + data_len = 0 oaep_params.pSourceData = data oaep_params.ulSourceDataLen = data_len diff --git a/pycryptoki/pycryptoki_client.py b/pycryptoki/pycryptoki_client.py index 65d829d..563e8c5 100755 --- a/pycryptoki/pycryptoki_client.py +++ b/pycryptoki/pycryptoki_client.py @@ -1,8 +1,11 @@ from __future__ import print_function +from six import string_types, binary_type + """ Contains both a local and remote pycryptoki client """ +import inspect import logging import socket from functools import wraps @@ -13,8 +16,9 @@ from rpyc.core.protocol import PingError from .daemon import rpyc_pycryptoki +from .lookup_dicts import ATTR_NAME_LOOKUP, ret_vals_dictionary -log = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) # from https://github.com/saltycrane/retry-decorator/blob/master/decorators.py @@ -83,6 +87,42 @@ def wrapper(self, *args, **kwargs): return wrapper +def log_args(funcname, arg_dict): + """ + This will run through each of the key, value pairs of the argument spec passed into + pycryptoki and perform the following checks: + + if key is a template, format the template data through a dict lookup + if key is password, set the log data to be '*' + if value is longer than 10 characters, shorten it. + + :param arg_dict: + :return: + """ + log_msg = "Running remote pycryptoki command {}()".format(funcname) + if arg_dict: + log_msg += " with args:" + log_list = [log_msg] + for key, value in arg_dict.items(): + if "template" in key and isinstance(value, dict): + # Means it's a template, so let's perform a lookup on all of the objects within + # this. + log_list.append("\t%s: " % key) + for template_key, template_value in arg_dict[key].items(): + log_list.append("\t\t%s: %s" % (ATTR_NAME_LOOKUP.get(template_key, template_key), + template_value)) + elif "password" in key: + log_list.append("\t%s: *" % key) + else: + if isinstance(value, (string_types, binary_type)) and len(value) > 20: + msg = "\t%s: %s[...]%s" % (key, value[:10], value[-10:]) + else: + msg = "\t%s: %s" % (key, value) + log_list.append(msg) + + LOG.debug("\n".join(log_list)) + + class RemotePycryptokiClient(object): """Class to handle connecting to a remote Pycryptoki RPYC daemon. @@ -106,16 +146,16 @@ def kill(self): """ # maybe we should be reloading cryptoki dll? if self.started and not self.connection.closed: - log.info("Stopping remote pycryptoki connection.") + LOG.info("Stopping remote pycryptoki connection.") self.connection.close() - @retry((socket.error, EOFError, PingError), logger=log) + @retry((socket.error, EOFError, PingError), logger=LOG) def start(self): """ Start the connection to the remote RPYC daemon. """ if not self.started: - log.info("Starting remote pycryptoki connection") + LOG.info("Starting remote pycryptoki connection") self.connection = rpyc.classic.connect(self.ip, port=self.port) self.connection.ping() self.server = self.connection.root @@ -153,17 +193,28 @@ def wrapper(*args, **kwargs): Closer to allow us to log the full args & keyword argument list of all calls. """ - masked_args = args - masked_kwargs = kwargs - if any(x in name for x in ("login", "create_container")): - masked_args = tuple("*" for _ in args) - masked_kwargs = {key: "*" for key, _ in list(kwargs.items())} - - masked_args = ["{:.10}".format(str(arg)) for arg in masked_args] - masked_kwargs = ["{:.10}".format(str(kwarg)) for kwarg in masked_kwargs] - log.info("Running remote pycryptoki command: " - "{0}(args={1}, kwargs={2})".format(name, masked_args, masked_kwargs)) - return getattr(self.server, name)(*args, **kwargs) + will_raise = False + if name.endswith("_ex"): + func = getattr(self.server, name.rsplit("_ex", 1)[0]) + will_raise = True + else: + func = getattr(self.server, name) + nice_args = inspect.getcallargs(func, *args, **kwargs) + + log_args(name, nice_args) + ret = getattr(self.server, name)(*args, **kwargs) + # Two major calling types for pycryptoki: + # 1. with _ex appended, which will raise an exception if retcode != 0 + # 2. without _ex, which will return either just the retcode, or a tuple where the + # first item is the retcode. + # We can assume the calls that could raise an exception will *also* log the retcode. + if not will_raise: + retcode = ret + if isinstance(ret, tuple): + retcode = ret[0] + LOG.debug("Remote call '%s' returned %s (%s)", name, + ret_vals_dictionary.get(retcode, "Unknown"), retcode) + return ret return wrapper else: @@ -186,7 +237,7 @@ def __getattr__(self, name): Function that overrides python attribute lookup; automagically calls functions in pycryptoki if they're listed in the daemon """ - log.info("Running local pycryptoki command: {0}".format(name)) + LOG.info("Running local pycryptoki command: {0}".format(name)) return getattr(rpyc_pycryptoki, name) def kill(self): From 8cc009fb83dc81742a36a5bf2b7733f66bb5b5d2 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 25 Sep 2017 09:10:34 -0400 Subject: [PATCH 098/109] LA-2686 Fix pre-allocating buffers for Final ops We would always query the library for the size of buffer required for the C_(Encrypt/Decrypt)Final operations. There are bugs in our PKCS11 implementation which doesn't always support querying for buffer size, so we need to respect the output_buffer variable for all cases of getting data. Change-Id: I7562943398b7b8d364a0d2a3f571113c0bf242ed --- pycryptoki/encryption.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 471e153..9f24076 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -296,18 +296,27 @@ def do_multipart_operation(h_session, c_update_function.__name__, ret_vals_dictionary[ret], ret) return error, b"".join(python_data) - # Finalizing multipart decrypt operation - fin_out_data_len = CK_ULONG() - # Get buffer size for data - ret = c_finalize_function(h_session, None, byref(fin_out_data_len)) - if ret != CKR_OK: - return ret, b"".join(python_data) + if output_buffer: + fin_out_data_len = CK_ULONG(max(output_buffer)) + fin_out_data = create_string_buffer(b"", fin_out_data_len.value) - fin_out_data = create_string_buffer(b"", fin_out_data_len.value) - output = cast(fin_out_data, CK_BYTE_PTR) - ret = c_finalize_function(h_session, output, byref(fin_out_data_len)) - if ret != CKR_OK: - return ret, b"".join(python_data) + ret = c_finalize_function(h_session, cast(fin_out_data, CK_BYTE_PTR), + byref(fin_out_data_len)) + if ret != CKR_OK: + return ret, b"".join(python_data) + else: + # Finalizing multipart decrypt operation + fin_out_data_len = CK_ULONG() + # Get buffer size for data + ret = c_finalize_function(h_session, None, byref(fin_out_data_len)) + if ret != CKR_OK: + return ret, b"".join(python_data) + + fin_out_data = create_string_buffer(b"", fin_out_data_len.value) + output = cast(fin_out_data, CK_BYTE_PTR) + ret = c_finalize_function(h_session, output, byref(fin_out_data_len)) + if ret != CKR_OK: + return ret, b"".join(python_data) if fin_out_data_len.value > 0: python_data.append(string_at(fin_out_data, fin_out_data_len.value)) From bd0f77dffa7c6766c3a780adfc2d1be2228bcbda Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 28 Sep 2017 13:49:02 -0400 Subject: [PATCH 099/109] LA-2690 Log cryptoki buffer sizes To assist with debugging buffer too small errors or anythign similar, log out the size of buffers that we are creating with AutoCArray. Change-Id: Ic01b5d9a76c1d8a8e08bda5f89ace16b1e315371 --- pycryptoki/common_utils.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pycryptoki/common_utils.py b/pycryptoki/common_utils.py index eddef25..0e1e60b 100644 --- a/pycryptoki/common_utils.py +++ b/pycryptoki/common_utils.py @@ -2,12 +2,15 @@ Utilities for pycryptoki """ from six import b, string_types +import logging from _ctypes import pointer, POINTER from ctypes import c_ulong, cast, create_string_buffer from .cryptoki import CK_CHAR from .defines import CKR_OK +LOG = logging.getLogger(__name__) + class CException(Exception): """ @@ -93,6 +96,7 @@ def array(self): # If we get to this point, we have a specified size, a ctype, # And our array is still none, but we're trying to access it. # Therefore, we go ahead & allocate the memory + LOG.debug("Allocating %s buffer of size: %s", self.ctype, self._size.value) self._array = (self.ctype * self._size.value)() return cast(self._array, POINTER(self.ctype)) From 4e528a00555cd190db3b9cc412b0f77e3af9c276 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Thu, 12 Oct 2017 10:21:36 -0400 Subject: [PATCH 100/109] LA-2699 Improve logging on retcode lookup failure If retcode isn't in our lookup, display the hex value of the retcode instead of the integer value. Change-Id: I5cffeaff9798e97ff2ed9dc79b8c9884772b2ba9 --- pycryptoki/encryption.py | 9 ++++++--- pycryptoki/exceptions.py | 2 +- pycryptoki/sign_verify.py | 8 +++++--- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/pycryptoki/encryption.py b/pycryptoki/encryption.py index 471e153..71582b2 100755 --- a/pycryptoki/encryption.py +++ b/pycryptoki/encryption.py @@ -265,7 +265,8 @@ def do_multipart_operation(h_session, if ret != CKR_OK: LOG.debug("%s call on chunk %.20s (%s/%s) Failed w/ ret %s (%s)", c_update_function.__name__, - chunk, index + 1, len(input_data_list), ret_vals_dictionary[ret], ret) + chunk, index + 1, len(input_data_list), + ret_vals_dictionary.get(ret, "Unknown retcode"), str(hex(ret))) error = ret break @@ -279,7 +280,8 @@ def do_multipart_operation(h_session, if ret != CKR_OK: LOG.debug("%s call on chunk %.20s (%s/%s) Failed w/ ret %s (%s)", c_update_function.__name__, - chunk, index + 1, len(input_data_list), ret_vals_dictionary[ret], ret) + chunk, index + 1, len(input_data_list), + ret_vals_dictionary.get(ret, "Unknown retcode"), str(hex(ret))) error = ret break @@ -293,7 +295,8 @@ def do_multipart_operation(h_session, CK_ULONG(MAX_BUFFER)) LOG.debug("%s call after a %s failure returned: %s (%s)", c_finalize_function.__name__, - c_update_function.__name__, ret_vals_dictionary[ret], ret) + c_update_function.__name__, + ret_vals_dictionary.get(ret, "Unknown retcode"), str(hex(ret))) return error, b"".join(python_data) # Finalizing multipart decrypt operation diff --git a/pycryptoki/exceptions.py b/pycryptoki/exceptions.py index a41f4f3..cdbc33b 100644 --- a/pycryptoki/exceptions.py +++ b/pycryptoki/exceptions.py @@ -132,7 +132,7 @@ def check_luna_exception(ret, luna_function, args, kwargs): arg_string = "({})".format("\n".join(log_list)) LOG.debug("Call to %s returned %s (%s)", luna_function, - ret_vals_dictionary.get(ret, "Unknown"), ret) + ret_vals_dictionary.get(ret, "Unknown retcode"), str(hex(ret))) if ret != CKR_OK: raise LunaCallException(ret, luna_function.__name__, arg_string) diff --git a/pycryptoki/sign_verify.py b/pycryptoki/sign_verify.py index 1fb4c31..ac511c5 100755 --- a/pycryptoki/sign_verify.py +++ b/pycryptoki/sign_verify.py @@ -123,7 +123,8 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, if ret != CKR_OK: LOG.debug("%s call on chunk %.20s (%s/%s) Failed w/ ret %s (%s)", c_update_function.__name__, - chunk, index + 1, len(input_data_list), ret_vals_dictionary[ret], ret) + chunk, index + 1, len(input_data_list), + ret_vals_dictionary.get(ret, "Unknown retcode"), str(hex(ret))) error = ret break @@ -135,7 +136,8 @@ def do_multipart_sign_or_digest(h_session, c_update_function, c_final_function, CK_ULONG(MAX_BUFFER)) LOG.debug("%s call after a %s failure returned: %s (%s)", c_final_function.__name__, - c_update_function.__name__, ret_vals_dictionary[ret], ret) + c_update_function.__name__, + ret_vals_dictionary.get(ret, "Unknown retcode"), str(hex(ret))) return error, None if output_buffer is not None: @@ -192,7 +194,7 @@ def do_multipart_verify(h_session, input_data_list, signature): cast(create_string_buffer(b"", MAX_BUFFER), CK_BYTE_PTR), CK_ULONG(MAX_BUFFER)) LOG.debug("C_VerifyFinal call after a C_VerifyUpdate failure returned:" - " %s (%s)", ret_vals_dictionary[ret], ret) + " %s (%s)", ret_vals_dictionary.get(ret, "Unknown retcode"), str(hex(ret))) return error, None # Finalizing multipart decrypt operation From 26cc91186a260f5ba3df542c0b1911ce0e0ce1e9 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 17 Oct 2017 10:14:43 -0400 Subject: [PATCH 101/109] LA-2702 Adding EC Edwards/Mongtomery defines Change-Id: Iccefc128699799f772d781e8303804f38c6fa3d3 --- docs/conf.py | 2 +- pycryptoki/defines.py | 2 ++ setup.py | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index e29cad0..5c52c87 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -61,7 +61,7 @@ # The short X.Y version. version = '2.0' # The full version, including alpha/beta/rc tags. -release = '2.0.2' +release = '2.0.3' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/pycryptoki/defines.py b/pycryptoki/defines.py index daba2eb..3645527 100755 --- a/pycryptoki/defines.py +++ b/pycryptoki/defines.py @@ -994,6 +994,8 @@ CKK_CAMELLIA = 0x00000025 CKK_ARIA = 0x00000026 CKK_VENDOR_DEFINED = 0x80000000 +CKK_EC_EDWARDS = (CKK_VENDOR_DEFINED + 0x12) +CKK_EC_MONTGOMERY = (CKK_VENDOR_DEFINED + 0x13) CKC_X_509 = 0x00000000 CKC_X_509_ATTR_CERT = 0x00000001 CKC_WTLS = 0x00000002 diff --git a/setup.py b/setup.py index 662a63c..a50ac33 100755 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ description="A python wrapper around the C cryptoki library.", author='Ashley Straw', url='https://github.com/gemalto/pycryptoki', - version='2.0.2', + version='2.0.3', packages=['pycryptoki', 'pycryptoki.daemon', 'pycryptoki.mechanism'], From 350935a2a5636217f913ae225eaba4ec8877dda6 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 18 Oct 2017 12:45:59 -0400 Subject: [PATCH 102/109] LA-2708 Updating Pycryptoki documentation Adding a bunch more examples, and sections to the documentation. Updated ToC Change-Id: I61ede1ecc3afc7b5bb096e5c2bfce2d95ccb56f4 --- README.MD | 44 ++++- docs/{attributes.rst => api.attributes.rst} | 1 + .../{pycryptoki.daemon.rst => api.daemon.rst} | 6 +- docs/api.encryption.rst | 36 ++++ docs/api.helpers.rst | 46 +++++ docs/{keys.rst => api.keys.rst} | 0 docs/{mechanisms.rst => api.mechanisms.rst} | 0 docs/{misc.rst => api.misc.rst} | 0 docs/api.rst | 25 +++ docs/{sessions.rst => api.sessions.rst} | 0 docs/api.sigver.rst | 23 +++ docs/encryption.rst | 8 - docs/examples.rst | 181 ++++++++++++++++++ docs/getting_started.rst | 44 +++++ docs/index.rst | 67 +++---- docs/modules.rst | 7 - docs/pycryptoki.rst | 73 ------- docs/sigver.rst | 7 - pycryptoki/daemon/rpyc_pycryptoki.py | 10 +- pycryptoki/lookup_dicts.py | 2 + pycryptoki/session_management.py | 19 +- 21 files changed, 451 insertions(+), 148 deletions(-) rename docs/{attributes.rst => api.attributes.rst} (95%) rename docs/{pycryptoki.daemon.rst => api.daemon.rst} (79%) create mode 100644 docs/api.encryption.rst create mode 100644 docs/api.helpers.rst rename docs/{keys.rst => api.keys.rst} (100%) rename docs/{mechanisms.rst => api.mechanisms.rst} (100%) rename docs/{misc.rst => api.misc.rst} (100%) create mode 100644 docs/api.rst rename docs/{sessions.rst => api.sessions.rst} (100%) create mode 100644 docs/api.sigver.rst delete mode 100644 docs/encryption.rst create mode 100644 docs/examples.rst create mode 100644 docs/getting_started.rst delete mode 100644 docs/modules.rst delete mode 100644 docs/pycryptoki.rst delete mode 100644 docs/sigver.rst diff --git a/README.MD b/README.MD index 02e6ab4..f7d5362 100755 --- a/README.MD +++ b/README.MD @@ -1,18 +1,60 @@ ## Pycryptoki +[![Doc Status](https://readthedocs.org/projects/pycryptoki/badge/?version=latest)](http://pycryptoki.readthedocs.io/en/latest/) Pycryptoki is a python wrapper around the PKCS11 library. +## Documentation + +Latest API documentation can be found on [readthedocs](http://pycryptoki.readthedocs.io/en/latest/index.html). ## Installation pip install git+https://github.com/gemalto/pycryptoki +## Key Generation Example + +```py +from pycryptoki.default_templates import * +from pycryptoki.defines import * +from pycryptoki.key_generator import * +from pycryptoki.session_management import * +from pycryptoki.encryption import * + + +c_initialize_ex() +auth_session = c_open_session_ex(0) # HSM slot # in this example is 0 +login_ex(auth_session, 0, 'userpin') # 0 is still the slot number, ‘userpin’ should be replaced by your password (None if PED or no challenge) + +# Get some default templates +# They are simple python dictionaries, and can be modified to suit needs. +pub_template, priv_template = get_default_key_pair_template(CKM_RSA_PKCS_KEY_PAIR_GEN) + +# Modifying template would look like: +pub_template[CKA_LABEL] = "RSA PKCS Pub Key" +pub_template[CKA_MODULUS_BITS] = 2048 # 2048 key size +pubkey, privkey = c_generate_key_pair_ex(auth_session, CKM_RSA_PKCS_KEY_PAIR_GEN, pub_template, priv_template) +print("Generated Private key at %s and Public key at %s" % (privkey, pubkey)) + +c_logout_ex(auth_session) +c_close_session_ex(auth_session) +c_finalize_ex() +``` +## Verbose logging + +If you want to see what calls to the C library are being performed, set pycryptoki logging to `DEBUG`: + +```py +import logging +logging.basicConfig(level=logging.DEBUG) +``` ## Tests -Unittests can be run on any environment using: +Test requirements can be installed via `pip install -r test_requirements.txt`. + +Unittests can be run on any environment via: ``` py.test tests/unittests ``` diff --git a/docs/attributes.rst b/docs/api.attributes.rst similarity index 95% rename from docs/attributes.rst rename to docs/api.attributes.rst index 5646a00..56de0fd 100644 --- a/docs/attributes.rst +++ b/docs/api.attributes.rst @@ -8,6 +8,7 @@ Attributes and Conversions .. data:: pycryptoki.attributes.KEY_TRANSFORMS :annotation: CK_ATTRIBUTE Types mapped to Python->C transformation functions +.. _conversions: Conversions ----------- diff --git a/docs/pycryptoki.daemon.rst b/docs/api.daemon.rst similarity index 79% rename from docs/pycryptoki.daemon.rst rename to docs/api.daemon.rst index 316d700..aa84f6e 100644 --- a/docs/pycryptoki.daemon.rst +++ b/docs/api.daemon.rst @@ -1,17 +1,17 @@ Pycryptoki Daemon Package ========================= -Start the following daemon on your remote client, then connect to it +Start ``pycryptoki.daemon.rpyc_pycryptoki.py`` on your remote client, then connect to it using :class:`~pycryptoki.pycryptoki_client.RemotePycryptokiClient`. You can then use the RemotePycryptokiClient as if it were local:: pycryptoki = RemotePycryptokiClient('10.2.96.130', port=8001) pycryptoki.c_initialize_ex() # Executed on the daemon! - session = pycryptoki.c_open_session_ex(SLOT) + session = pycryptoki.c_open_session_ex(0) #etc -rpyc_pycryptoki +daemon.rpyc_pycryptoki --------------- .. automodule:: pycryptoki.daemon.rpyc_pycryptoki diff --git a/docs/api.encryption.rst b/docs/api.encryption.rst new file mode 100644 index 0000000..2f56ff5 --- /dev/null +++ b/docs/api.encryption.rst @@ -0,0 +1,36 @@ +Encryption/Decryption +===================== + +.. contents:: + +Encryption +---------- + +.. autofunction:: pycryptoki.encryption.c_encrypt + +.. autofunction:: pycryptoki.encryption.c_encrypt_ex + +Decryption +---------- + +.. autofunction:: pycryptoki.encryption.c_decrypt + + +.. autofunction:: pycryptoki.encryption.c_decrypt_ex + +Key Wrapping/Unwrapping +----------------------- + +.. autofunction:: pycryptoki.encryption.c_wrap_key + +.. autofunction:: pycryptoki.encryption.c_wrap_key_ex + +.. autofunction:: pycryptoki.encryption.c_unwrap_key + +.. autofunction:: pycryptoki.encryption.c_unwrap_key_ex + + +Multipart Helper +---------------- + +.. autofunction:: pycryptoki.encryption.do_multipart_operation diff --git a/docs/api.helpers.rst b/docs/api.helpers.rst new file mode 100644 index 0000000..a4eea78 --- /dev/null +++ b/docs/api.helpers.rst @@ -0,0 +1,46 @@ +Pycryptoki Helpers +================== + +These are various helper modules and functions. They contain constant definitions, +C parameter structs, configuration parsing, and default templates. + +cryptoki_helpers +---------------- + +.. automodule:: pycryptoki.cryptoki_helpers + :members: + :undoc-members: + :show-inheritance: + + +lookup_dicts +------------ + +.. automodule:: pycryptoki.lookup_dicts + :members: + :undoc-members: + +default_templates +----------------- + +.. automodule:: pycryptoki.default_templates + :members: + :undoc-members: + :show-inheritance: + +defaults +-------- + +.. automodule:: pycryptoki.defaults + :members: + :undoc-members: + :show-inheritance: + + +cryptoki +-------- + +.. automodule:: pycryptoki.cryptoki + :members: + :undoc-members: + diff --git a/docs/keys.rst b/docs/api.keys.rst similarity index 100% rename from docs/keys.rst rename to docs/api.keys.rst diff --git a/docs/mechanisms.rst b/docs/api.mechanisms.rst similarity index 100% rename from docs/mechanisms.rst rename to docs/api.mechanisms.rst diff --git a/docs/misc.rst b/docs/api.misc.rst similarity index 100% rename from docs/misc.rst rename to docs/api.misc.rst diff --git a/docs/api.rst b/docs/api.rst new file mode 100644 index 0000000..f4cfc3e --- /dev/null +++ b/docs/api.rst @@ -0,0 +1,25 @@ +API Reference +============= + +There are some general guidelines to using pycryptoki: + + + 1. If you want to perform a PKCS11 operation as a multi-part operation, provide the input data + as a list or a tuple. + 2. Data should always be passed into ``c_`` functions as raw byte data (bytestrings). + Conversions are available to convert hex data or binary data to bytes at + :ref:`pycryptoki.conversions` + 3. Returned encrypted/decrypted data is always raw bytestrings. + + +.. toctree:: + + Session/Token Management + Key Generation/Management + Encryption/Decryption + Sign/Verify + Attributes + Mechanisms + Miscellaneous + Helpers + RPYC Daemon diff --git a/docs/sessions.rst b/docs/api.sessions.rst similarity index 100% rename from docs/sessions.rst rename to docs/api.sessions.rst diff --git a/docs/api.sigver.rst b/docs/api.sigver.rst new file mode 100644 index 0000000..c50c629 --- /dev/null +++ b/docs/api.sigver.rst @@ -0,0 +1,23 @@ +Sign/Verify operations +====================== + +.. contents:: + + +Sign +---- + +.. autofunction:: pycryptoki.sign_verify.c_sign + +.. autofunction:: pycryptoki.sign_verify.c_sign_ex + + +Verify +------ + +.. autofunction:: pycryptoki.sign_verify.c_verify + +.. autofunction:: pycryptoki.sign_verify.c_verify_ex + +.. autofunction:: pycryptoki.sign_verify.do_multipart_verify + diff --git a/docs/encryption.rst b/docs/encryption.rst deleted file mode 100644 index e9dedba..0000000 --- a/docs/encryption.rst +++ /dev/null @@ -1,8 +0,0 @@ -Encryption/Decryption ---------------------- - - -.. automodule:: pycryptoki.encryption - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/examples.rst b/docs/examples.rst new file mode 100644 index 0000000..1de3403 --- /dev/null +++ b/docs/examples.rst @@ -0,0 +1,181 @@ +Examples +======== + + +-------------------------- +Generating an RSA Key Pair +-------------------------- + +This example creates a 1024b RSA Key Pair. + + + .. code-block:: python + + from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, + c_open_session_ex, c_close_session_ex, + login_ex) + from pycryptoki.defines import CKM_RSA_PKCS_KEY_PAIR_GEN + from pycryptoki.key_generator import c_generate_key_pair_ex + + c_initialize_ex() + session = c_open_session_ex(0) # 0 -> slot number + login_ex(session, 0, 'userpin') # 0 -> Slot number, 'userpin' -> token password + + # Templates are dictionaries in pycryptoki + pub_template = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_MODIFIABLE: True, + CKA_ENCRYPT: True, + CKA_VERIFY: True, + CKA_WRAP: True, + CKA_MODULUS_BITS: 1024, # long 0 - MAX_RSA_KEY_NBITS + CKA_PUBLIC_EXPONENT: 3, # byte + CKA_LABEL: b"RSA Public Key"} + priv_template = {CKA_TOKEN: True, + CKA_PRIVATE: True, + CKA_SENSITIVE: True, + CKA_MODIFIABLE: True, + CKA_EXTRACTABLE: True, + CKA_DECRYPT: True, + CKA_SIGN: True, + CKA_UNWRAP: True, + CKA_LABEL: b"RSA Private Key"} + + pub_key, priv_key = c_generate_key_pair_ex(session, + mechanism=CKM_RSA_PKCS_KEY_PAIR_GEN, + pbkey_template=pub_template, + prkey_template=priv_template) + + c_close_session_ex(session) + c_finalize_ex() + + +-------------------------------- +Encrypting data with AES-CBC-PAD +-------------------------------- + +This example generates a 24-byte AES key, then encrypts some data +with that key using the AES-CBC-PAD mechanism. + + .. code-block:: python + + + from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, + c_open_session_ex, c_close_session_ex, + login_ex) + from pycryptoki.defines import (CKM_AES_KEY_GEN, + CKA_LABEL, + CKA_ENCRYPT, + CKA_DECRYPT, + CKA_TOKEN, + CKA_CLASS, + CKA_KEY_TYPE, + CKK_AES, + CKO_SECRET_KEY, + CKA_SENSITIVE, + CKA_WRAP, + CKA_UNWRAP, + CKA_DERIVE, + CKA_VALUE_LEN, + CKA_EXTRACTABLE, + CKA_PRIVATE, + CKM_AES_CBC_PAD) + from pycryptoki.key_generator import c_generate_key_ex + from pycryptoki.encryption import c_encrypt_ex + from pycryptoki.conversions import to_bytestring, from_hex + from pycryptoki.mechanism import Mechanism + + c_initialize_ex() + session = c_open_session_ex(0) # 0 = slot number + login_ex(session, 0, 'userpin') # 'userpin' = token password + + + template = {CKA_LABEL: b"Sample AES Key", + CKA_ENCRYPT: True, + CKA_DECRYPT: True, + CKA_TOKEN: False, + CKA_CLASS: CKO_SECRET_KEY, + CKA_KEY_TYPE: CKK_AES, + CKA_SENSITIVE: True, + CKA_PRIVATE: True, + CKA_WRAP: True, + CKA_UNWRAP: True, + CKA_DERIVE: True, + CKA_VALUE_LEN: 24, + CKA_EXTRACTABLE: True,} + aes_key = c_generate_key_ex(session, CKM_AES_KEY_GEN, template) + + # Data is in hex format here + raw_data = "d0d77c63ab61e75a5fd4719fa77cc2de1d817efedcbd43e7663736007672e8c7" + + # Convert to raw bytes before passing into c_encrypt: + data_to_encrypt = to_bytestring(from_hex(raw_data)) + + + # Note: this is *bad crypto practice*! DO NOT USE STATIC IVS!! + mechanism = Mechanism(mech_type=CKM_AES_CBC_PAD, + params={"iv": list(range(16))}) + static_iv_encrypted_data = c_encrypt_ex(session, aes_key, data_to_encrypt, mechanism) + + c_close_session_ex(session) + c_finalize_ex() + + +--------------------------------- +Finding a key and decrypting Data +--------------------------------- + +This example follows from the previous one, except instead of generating a key, +we'll find one that was already used. + + +.. code-block:: python + + from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, + c_open_session_ex, c_close_session_ex, + login_ex) + from pycryptoki.object_attr_lookup import c_find_objects_ex + from pycryptoki.defines import (CKM_AES_KEY_GEN, + CKA_LABEL, + CKA_ENCRYPT, + CKA_DECRYPT, + CKA_TOKEN, + CKA_CLASS, + CKA_KEY_TYPE, + CKK_AES, + CKO_SECRET_KEY, + CKA_SENSITIVE, + CKA_WRAP, + CKA_UNWRAP, + CKA_DERIVE, + CKA_VALUE_LEN, + CKA_EXTRACTABLE, + CKA_PRIVATE, + CKM_AES_CBC_PAD) + from pycryptoki.encryption import c_decrypt_ex + from pycryptoki.conversions import to_bytestring, from_hex + from pycryptoki.mechanism import Mechanism + + c_initialize_ex() + session = c_open_session_ex(0) # 0 = slot number + login_ex(session, 0, 'userpin') # 'userpin' = token password + + template = {CKA_LABEL: b"Sample AES key"} + + keys = c_find_objects_ex(session, template, 1) + aes_key = keys.pop(0) # Use the first key found. + + # Data is in hex format here + raw_data = "95e28bc6da451f3064d688dd283c5c43a5dd374cb21064df836e2970e1024c2448f129062aacbae3e45abd098b893346" + + # Convert to raw bytes before passing into c_decrypt: + data_to_decrypt = to_bytestring(from_hex(raw_data)) + + + # Note: this is *bad crypto practice*! DO NOT USE STATIC IVS!! + mechanism = Mechanism(mech_type=CKM_AES_CBC_PAD, + params={"iv": list(range(16))}) + original_data = c_decrypt_ex(session, aes_key, data_to_decrypt, mechanism) + + c_close_session_ex(session) + c_finalize_ex() diff --git a/docs/getting_started.rst b/docs/getting_started.rst new file mode 100644 index 0000000..18bf280 --- /dev/null +++ b/docs/getting_started.rst @@ -0,0 +1,44 @@ + +Getting Started +=============== + +To use pycryptoki, you must have SafeNet LunaClient installed. + +Installation +------------ + +Pycryptoki can be installed on any machine that has Python installed. Python versions >= 2.7 +are supported.:: + + pip install git+https://github.com/gemalto/pycryptoki + + +Pycryptoki will attempt to auto-locate the SafeNet Cryptoki shared library when pycryptoki +is first called. It will use the configuration files as defined by the LunaClient documentation to +determine which library to use. + + +Simple Example +-------------- + +This example will print out information about the given token slot. + + + .. code-block:: python + + from pycryptoki.session_management import (c_initialize_ex, + c_get_info_ex, + get_firmware_version, + c_get_token_info_ex, + c_finalize_ex) + + + c_initialize_ex() + print("C_GetInfo: ") + print("\n".join("\t{}: {}".format(x, y) for x, y in c_get_info_ex().items())) + token_info = c_get_token_info_ex(0) + print("C_GetTokenInfo:") + print("\n".join("\t{}: {}".format(x, y) for x, y in token_info.items())) + print("Firmware version: {}".format(get_firmware_version(0))) + + c_finalize_ex() diff --git a/docs/index.rst b/docs/index.rst index ed89cea..6e22b3a 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,53 +1,54 @@ -.. Pycryptoki documentation master file, created by - sphinx-quickstart on Wed May 20 08:09:23 2015. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +Pycryptoki +========== -Welcome to Pycryptoki's documentation! -====================================== +Overview +-------- + +Pycryptoki is an open-source Python wrapper around Safenet's C PKCS11 library. Using python's ctypes library, +we can simplify memory management, and provide easy, pythonic access to a PKCS11 shared library. This package contains a python wrapper for our C PKCS11 libraries. It provides automatic conversion to C types for the most commonly used functions. -You can use it similarly to how you would use the C version of the PKCS11 library:: +The primary function of pycryptoki is to *simplify* PKCS11 calls. Rather than needing to calculate +data sizes, buffers, or other low-level memory manipulation, you simply need to pass in data. from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, c_open_session_ex, c_close_session_ex, login_ex) - from pycryptoki.key_generator import c_generate_key_pair_ex - - c_initialize_ex() - session = c_open_session_ex(SLOT) - login_ex(session, 'userpin') +.. code-block:: python - pub_key_handle, priv_key_handle = c_generate_key_pair_ex(session) # Will default to RSA PKCS templates + from pycryptoki.default_templates import * + from pycryptoki.defines import * + from pycryptoki.key_generator import * + from pycryptoki.session_management import * - c_close_session_ex(session) - c_finalize_ex() + c_initialize_ex() + auth_session = c_open_session_ex(0) # HSM slot # in this example is 0 + login_ex(auth_session, 0, 'userpin') # 0 is still the slot number, ‘userpin’ should be replaced by your password (None if PED or no challenge) -.. toctree:: - :maxdepth: 2 - :numbered: - :includehidden: + # Get some default templates + # They are simple python dictionaries, and can be modified to suit needs. + pub_template, priv_template = get_default_key_pair_template(CKM_RSA_PKCS_KEY_PAIR_GEN) - Session/Token Management - Key Generation/Management - Encryption/Decryption - Sign/Verify - Attributes - Mechanisms - Miscellaneous - RPYC Daemon + # Modifying template would look like: + pub_template[CKA_LABEL] = b"RSA PKCS Pub Key" + pub_template[CKA_MODULUS_BITS] = 2048 # 2048 key size + pubkey, privkey = c_generate_key_pair_ex(auth_session, CKM_RSA_PKCS_KEY_PAIR_GEN, pub_template, priv_template) + print("Generated Private key at %s and Public key at %s" % (privkey, pubkey)) + c_logout_ex(auth_session) + c_close_session_ex(auth_session) + c_finalize_ex() +.. toctree:: + :maxdepth: 4 + :includehidden: -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` + Getting Started + Examples + API Reference diff --git a/docs/modules.rst b/docs/modules.rst deleted file mode 100644 index dec241b..0000000 --- a/docs/modules.rst +++ /dev/null @@ -1,7 +0,0 @@ -pycryptoki -========== - -.. toctree:: - :maxdepth: 4 - - pycryptoki diff --git a/docs/pycryptoki.rst b/docs/pycryptoki.rst deleted file mode 100644 index a47370a..0000000 --- a/docs/pycryptoki.rst +++ /dev/null @@ -1,73 +0,0 @@ -Pycryptoki Package -================== - -This package contains a python wrapper for our C PKCS11 libraries. -It provides automatic conversion to C types for the most commonly used functions. - -You can use it similarly to how you would use the C version of the PKCS11 library:: - - from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, - c_open_session_ex, c_close_session_ex, - login_ex) - - from pycryptoki.key_generator import c_generate_key_pair_ex - - c_initialize_ex() - session = c_open_session_ex(SLOT) - login_ex(session, 'userpin') - - pub_key_handle, priv_key_handle = c_generate_key_pair_ex(session) # Will default to RSA PKCS templates - - c_close_session_ex(session) - c_finalize_ex() - -To use pycryptoki in LunaTAP on a remote client, use the daemon -:mod:`pycryptoki.daemon.rpyc_pycryptoki` as well as the client :mod:`pycryptoki.pycryptoki_client`. - -.. toctree:: - :hidden: - - daemon - - -pycryptoki.cryptoki module --------------------------- - -.. automodule:: pycryptoki.cryptoki - :members: - :undoc-members: - - -pycryptoki.cryptoki_helpers ---------------------------- - -.. automodule:: pycryptoki.cryptoki_helpers - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.default_templates ----------------------------- - -.. automodule:: pycryptoki.default_templates - :members: - :undoc-members: - :show-inheritance: - -pycryptoki.defaults -------------------- - -.. automodule:: pycryptoki.defaults - :members: - :undoc-members: - :show-inheritance: - - - - - - - - - - diff --git a/docs/sigver.rst b/docs/sigver.rst deleted file mode 100644 index 864f7ec..0000000 --- a/docs/sigver.rst +++ /dev/null @@ -1,7 +0,0 @@ -Sign/Verify operations -====================== - -.. automodule:: pycryptoki.sign_verify - :members: - :undoc-members: - :show-inheritance: diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index b5e4b25..7500f5c 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -3,13 +3,13 @@ RPYC-based daemon that allows for remote execution of pycryptoki commands. -Start via "./rpyc\_pycryptoki.py -i -p " -or "python rpyc\_pycryptoki.py -i -p " +Start via ``./rpyc_pycryptoki.py -i -p `` +or ``python rpyc_pycryptoki.py -i -p `` -All methods starting with 'exposed\_' are useable via just -rpyc\_conn. instead of rpyc\_conn.exposed_ +All methods starting with ``exposed_`` are useable via just +``rpyc_conn.`` instead of ``rpyc_conn.exposed_`` -All methods ending with '\_ex' will automatically check the return code from +All methods ending with ``_ex`` will automatically check the return code from cryptoki & raise an exception if it is not CKR_OK. It will *NOT* give you the return code, instead just returning the second part of the regular return tuple:: diff --git a/pycryptoki/lookup_dicts.py b/pycryptoki/lookup_dicts.py index b5dcffe..2ff2b04 100644 --- a/pycryptoki/lookup_dicts.py +++ b/pycryptoki/lookup_dicts.py @@ -5,6 +5,7 @@ from .defines import * +#: ret_vals_dictionary = { CKR_OK: 'CKR_OK', CKR_CANCEL: 'CKR_CANCEL', @@ -206,6 +207,7 @@ CKR_RNG_RESEED_TOO_EARLY: 'CKR_RNG_RESEED_TOO_EARLY' } +#: ATTR_NAME_LOOKUP = { CKA_CLASS: 'CKA_CLASS', CKA_CERTIFICATE_TYPE: 'CKA_CERTIFICATE_TYPE', diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 1fed2b1..35f3fb4 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -4,7 +4,7 @@ import logging import re from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ - byref, pointer + byref, pointer, string_at from .common_utils import AutoCArray, refresh_c_arrays # cryptoki constants @@ -149,9 +149,9 @@ def c_get_info(): ret = C_GetInfo(byref(info_struct)) if ret == CKR_OK: info['cryptokiVersion'] = info_struct.cryptokiVersion - info['manufacturerID'] = info_struct.manufacturerID + info['manufacturerID'] = string_at(info_struct.manufacturerID) info['flags'] = info_struct.flags - info['libraryDescription'] = info_struct.libraryDescription + info['libraryDescription'] = string_at(info_struct.libraryDescription) info['libraryVersion'] = info_struct.libraryVersion return ret, info @@ -218,13 +218,10 @@ def c_get_token_info(slot_id): ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) if ret == CKR_OK: - token_info['label'] = str(cast(c_token_info.label, c_char_p).value)[0:32].strip() - token_info['manufacturerID'] = str(cast(c_token_info.manufacturerID, - c_char_p).value)[0:32].strip() - token_info['model'] = str(cast(c_token_info.model, - c_char_p).value)[0:16].strip() - token_info['serialNumber'] = str(cast(c_token_info.serialNumber, - c_char_p).value)[0:16].strip() + token_info['label'] = string_at(c_token_info.label) + token_info['manufacturerID'] = string_at(c_token_info.manufacturerID) + token_info['model'] = string_at(c_token_info.model) + token_info['serialNumber'] = string_at(c_token_info.serialNumber) token_info['flags'] = c_token_info.flags token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory @@ -238,7 +235,7 @@ def c_get_token_info(slot_id): token_info['ulFreePublicMemory'] = c_token_info.ulFreePublicMemory token_info['hardwareVersion'] = c_token_info.hardwareVersion token_info['firmwareVersion'] = c_token_info.firmwareVersion - token_info['utcTime'] = str(cast(c_token_info.utcTime, c_char_p).value)[0:16].strip() + token_info['utcTime'] = string_at(c_token_info.utcTime) return ret, token_info From 08e4de486ec0a96aff2faf961a96c9c2cb523912 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Mon, 23 Oct 2017 15:58:42 -0400 Subject: [PATCH 103/109] LA-2708 Adding Frequent issue section Change-Id: I9ebd3a0c865517128d7b76639f5a9000c371ea4f --- docs/index.rst | 10 ++-- docs/problems.rst | 126 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+), 6 deletions(-) create mode 100644 docs/problems.rst diff --git a/docs/index.rst b/docs/index.rst index 6e22b3a..ee618f2 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,15 +7,12 @@ Overview Pycryptoki is an open-source Python wrapper around Safenet's C PKCS11 library. Using python's ctypes library, we can simplify memory management, and provide easy, pythonic access to a PKCS11 shared library. -This package contains a python wrapper for our C PKCS11 libraries. -It provides automatic conversion to C types for the most commonly used functions. - The primary function of pycryptoki is to *simplify* PKCS11 calls. Rather than needing to calculate data sizes, buffers, or other low-level memory manipulation, you simply need to pass in data. - from pycryptoki.session_management import (c_initialize_ex, c_finalize_ex, - c_open_session_ex, c_close_session_ex, - login_ex) +It's highly recommended that you have the `PKCS11`_ documentation +handy, as pycryptoki uses that as the underlying C interface. Session management, object management, +and other concepts are unchanged from PKCS11. .. code-block:: python @@ -50,5 +47,6 @@ data sizes, buffers, or other low-level memory manipulation, you simply need to Getting Started Examples + Frequent Issues API Reference diff --git a/docs/problems.rst b/docs/problems.rst new file mode 100644 index 0000000..a0afffb --- /dev/null +++ b/docs/problems.rst @@ -0,0 +1,126 @@ +Frequent Issues +=============== + +.. contents:: + + +Wrong data type +--------------- + +Any cryptographic function working on data (ex. ``c_encrypt``, ``c_unwrap``) will expect a +bytestring. A string object in Python2 is by default a *bytestring*, but in Python3 is a +*unicode* string. + +For example:: + + c_encrypt(session, key, "this is some test data", mechanism) + +Will work in Python 2, but NOT Python 3. Instead, use the :ref:`pycryptoki.conversions` +module to ensure that any data you pass into the cryptoki library is of the correct form. + +Another 'gotcha' is that hex data represented as a string that is then used in an encrypt call would +result in 2x the length of expected data:: + + from pycryptoki.conversions import to_bytestring, from_hex + hex_data = "deadbeef" + assert len(hex_data) == 8 + raw_data = list(from_hex(hex_data)) + assert len(raw_data) == 4 + print (raw_data) + # Prints: [222, 173, 190, 239] + +Another example:: + + from pycryptoki.conversions import to_bytestring, from_hex + some_hex_data = "06abde23df89" + data_to_encrypt = to_bytestring(from_hex(some_hex_data)) + c_encrypt(session, key, data_to_encrypt, mechanism) + +.. note:: + See this article for more details about the differences between unicode and bytestrings in + python: http://lucumr.pocoo.org/2014/1/5/unicode-in-2-and-3/ + +Internal Initialization Vectors +------------------------------- + +When you use an internal IV for AES mechanisms, the IV is appended to the cipher text. This needs to +be stripped off and used to create the mechanism for decryption:: + + from pycryptoki.encryption import c_encrypt_ex + + data_to_encrypt = b"a" * 64 + mech = Mechanism(CKM_AES_KW, + params={"iv": []}) # Uses an internal IV + + enc_data = c_encrypt_ex(session, key, data_to_encrypt, mech) + iv = enc_data[-16:] # Strip off the last 16 bytes of the encrypted data. + decrypt_mech = Mechanism(CKM_AES_KW, + params={"iv": iv}) + decrypted_data = c_decrypt_ex(session, key, enc_data[:-16], decrypt_mech) + + +PKCS11 Calling Conventions +-------------------------- + +.. _Calling Convention: https://www.cryptsoft.com/pkcs11doc/v220/group__SEC__11__2__CONVENTIONS__FOR__FUNCTIONS__RETURNING__OUTPUT__IN__A__VARIABLE__LENGTH__BUFFER.html#SECTION_11_2 + +`The PKCS11 library has two main methods for returning data to the caller `_: + + 1. Allocate a large enough buffer for the resulting data and make the PKCS11 call with that buffer. + 2. Call the function with a NULL pointer for the buffer. The PKCS11 library will then place the + required buffer size in ``*pulBufLen``. + + +Pycryptoki will let you perform either method for any function that returns data in a variable-length +buffer with the ``output_buffer`` keyword argument. This argument takes either an integer, or a list +of integers. The integer specifies the *size* of the buffer to use for the returned output. This means +if you use a very small integer, you could get back ``CKR_BUFFER_TOO_SMALL`` (and you could also +allocate a buffer that is incredibly large -- limited by the memory of your system). + + +By default, pycryptoki will use method #2 (querying the library for buffer size):: + + data = b"deadbeef" + c_decrypt_ex(session, key, data, mechanism) + + +Will result in the raw underlying PKCS11 calls: + + +.. code-block:: none + + DEBUG: Cryptoki call: C_DecryptInit(8, , c_ulong(26)) + DEBUG: Cryptoki call: C_Decrypt(8, , c_ulong(2056), None, ) + DEBUG: Allocating buffer of size: 2048 + DEBUG: Cryptoki call: C_Decrypt(8, , c_ulong(2056), , ) + + +.. note:: + ``None`` in python is the equivalent to ``NULL`` in C. + +An example using a pre-allocated buffer:: + + + data = b"deadbeef" + c_decrypt_ex(session, key, data, mechanism, output_buffer=0xffff) + + +And the resulting PKCS11 calls: + +.. code-block:: none + + DEBUG: Cryptoki call: C_DecryptInit(8, , c_ulong(26)) + DEBUG: Allocating buffer of size: 2048 + DEBUG: Cryptoki call: C_Decrypt(8, , c_ulong(2056), , ) + + +For multi-part operations, ``output_buffer`` should be a list of integers of equal size to the +number of parts in the operation:: + + data = [b"a" * 8, b"b" * 8, b"c" * 8, b"d" * 8] + output_buffer = [0xffff] * len(data) # Equivalent to: [0xffff, 0xffff, 0xffff, 0xffff] + c_encrypt_ex(session, key, data, mechanism, output_buffer=output_buffer) + + +For a multi-part operation that returns data in the ``C_*Final`` function, the output buffer will be +equivalent to the largest buffer size specified in the output_buffer list. From fd1d014979be7cd2443be8e33ba580f3443a04bd Mon Sep 17 00:00:00 2001 From: syoung Date: Wed, 1 Nov 2017 12:27:10 -0400 Subject: [PATCH 104/109] LA-2721: c_get_token_info returning incorrect data * The cryptoki call returns strings which conatain additional data. The data conversion now extracts the spec defined number of characters from non-null terminated strings. Note: The spec calls for the fixed size strings to be " " padded to 32 or 16 characters. Values returned by c_get_token_info has trailing whitespace stripped from the string. Change-Id: Ia08c77f553dd1ce150a893c92c2ccfc7edaec928 --- pycryptoki/session_management.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 35f3fb4..c2564e3 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -218,10 +218,10 @@ def c_get_token_info(slot_id): ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) if ret == CKR_OK: - token_info['label'] = string_at(c_token_info.label) - token_info['manufacturerID'] = string_at(c_token_info.manufacturerID) - token_info['model'] = string_at(c_token_info.model) - token_info['serialNumber'] = string_at(c_token_info.serialNumber) + token_info['label'] = string_at(c_token_info.label, 32).rstrip() + token_info['manufacturerID'] = string_at(c_token_info.manufacturerID, 32).rstrip() + token_info['model'] = string_at(c_token_info.model, 16).rstrip() + token_info['serialNumber'] = string_at(c_token_info.serialNumber, 16).rstrip() token_info['flags'] = c_token_info.flags token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory @@ -235,7 +235,7 @@ def c_get_token_info(slot_id): token_info['ulFreePublicMemory'] = c_token_info.ulFreePublicMemory token_info['hardwareVersion'] = c_token_info.hardwareVersion token_info['firmwareVersion'] = c_token_info.firmwareVersion - token_info['utcTime'] = string_at(c_token_info.utcTime) + token_info['utcTime'] = string_at(c_token_info.utcTime, 16).rstrip() return ret, token_info From 1a8d45b2f01b85ce1b3e4430c4a450c1c5541f89 Mon Sep 17 00:00:00 2001 From: shliao Date: Fri, 2 Feb 2018 14:39:58 -0500 Subject: [PATCH 105/109] LA-2786: add destorymultipleobjects to pycryptoki Change-Id: I2b9909515ad938eebcc1a00d8c5f42cfdd589f45 --- pycryptoki/daemon/rpyc_pycryptoki.py | 2 ++ pycryptoki/key_generator.py | 19 ++++++++++++++++-- tests/functional/test_keys.py | 30 ++++++++++++++++++++++++++-- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 7500f5c..802ba98 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -362,6 +362,8 @@ def _rpyc_getattr(self, name): exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) exposed_ca_modifyusagecount = staticmethod(ca_modifyusagecount) exposed_ca_modifyusagecount_ex = staticmethod(ca_modifyusagecount_ex) + exposed_ca_destroy_multiple_objects = staticmethod(ca_destroymultipleobjects) + exposed_ca_destroy_multiple_objects_ex = staticmethod(ca_destroymultipleobjects_ex) # key_usage.py exposed_ca_clonemofn = staticmethod(ca_clonemofn) diff --git a/pycryptoki/key_generator.py b/pycryptoki/key_generator.py index 33dd84a..3356ad5 100755 --- a/pycryptoki/key_generator.py +++ b/pycryptoki/key_generator.py @@ -6,13 +6,13 @@ from .attributes import Attributes from .cryptoki import C_DeriveKey from .cryptoki import C_DestroyObject, CK_OBJECT_HANDLE, CK_ULONG, C_GenerateKey, \ - C_GenerateKeyPair, \ - C_CopyObject + C_GenerateKeyPair, CA_DestroyMultipleObjects, C_CopyObject from .default_templates import CKM_DES_KEY_GEN_TEMP, \ get_default_key_pair_template from .defines import CKM_DES_KEY_GEN, CKM_RSA_PKCS_KEY_PAIR_GEN from .mechanism import parse_mechanism from .exceptions import make_error_handle_function +from .common_utils import AutoCArray def c_destroy_object(h_session, h_object_value): @@ -28,6 +28,21 @@ def c_destroy_object(h_session, h_object_value): c_destroy_object_ex = make_error_handle_function(c_destroy_object) +def ca_destroy_multiple_objects(h_session, objects): + """Delete multiple objects corresponding to given object handles + + :param int h_session: Session handle + :param list objects: The handles of the objects to delete + :returns: Return code + """ + handles_count = len(objects) + handles = AutoCArray(data=objects, ctype=CK_ULONG) + ret = CA_DestroyMultipleObjects(h_session, handles_count, handles.array, byref(CK_ULONG())) + return ret + + +ca_destroy_multiple_objects_ex = make_error_handle_function(ca_destroy_multiple_objects) + def c_copy_object(h_session, h_object, template=None): """Method to call the C_CopyObject cryptoki command. diff --git a/tests/functional/test_keys.py b/tests/functional/test_keys.py index 14ce0b8..02a0718 100755 --- a/tests/functional/test_keys.py +++ b/tests/functional/test_keys.py @@ -32,9 +32,9 @@ from pycryptoki.encryption import c_encrypt_ex, c_decrypt_ex from pycryptoki.key_generator import \ c_generate_key, c_generate_key_pair, c_derive_key, c_generate_key_ex, c_destroy_object, \ - c_derive_key_ex, c_generate_key_pair_ex + c_derive_key_ex, c_generate_key_pair_ex, ca_destroy_multiple_objects_ex from pycryptoki.mechanism import NullMech -from pycryptoki.object_attr_lookup import c_get_attribute_value_ex +from pycryptoki.object_attr_lookup import c_get_attribute_value_ex, c_find_objects_ex from pycryptoki.return_values import ret_vals_dictionary from pycryptoki.test_functions import verify_object_attributes from .util import get_session_template @@ -316,3 +316,29 @@ def test_x9_key_derive(self, auth_session, curve_type): for key in (pub_key1, prv_key1, pub_key2, prv_key2, derived_key1, derived_key2): if key: c_destroy_object(auth_session, key) + + def test_destroymultipleobjects(self): + """ + Test deletion of multiple keys + Tested by RSA key pair + """ + + key_type, pub_key_temp, priv_key_temp = pair_params(CKM_RSA_PKCS_KEY_PAIR_GEN) + session_pub_template = get_session_template(pub_key_temp) + session_priv_template = get_session_template(priv_key_temp) + ret, pub_key, prv_key = c_generate_key_pair(self.h_session, key_type, + session_pub_template, + session_priv_template) + + try: + + ret = ca_destroy_multiple_objects_ex(self.h_session, [pub_key, prv_key]) + self.verify_ret(ret, CKR_OK) + for templ in (session_pub_template, session_priv_template): + objs = c_find_objects_ex(self.h_session, templ, 1) + assert len(objs) == 0 + + except Exception: + for key in (pub_key, prv_key): + c_destroy_object(self.h_session, key) + From 8cef4d78c0c57ff9e602c42dc66cf7efda894548 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 6 Feb 2018 14:20:33 -0500 Subject: [PATCH 106/109] LA-2786 Fix missing import & incorrect name Change-Id: I348c5734351ae9ea92e426f8eccd668740c109e3 --- pycryptoki/daemon/rpyc_pycryptoki.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index 802ba98..b865db0 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -68,7 +68,8 @@ c_generate_key_pair, c_generate_key_pair_ex, c_generate_key, c_generate_key_ex, c_derive_key, c_derive_key_ex, - c_copy_object_ex, c_copy_object) + c_copy_object_ex, c_copy_object, ca_destroy_multiple_objects, + ca_destroy_multiple_objects_ex) from pycryptoki.key_management import (ca_generatemofn, ca_generatemofn_ex, ca_modifyusagecount, ca_modifyusagecount_ex) from pycryptoki.key_usage import (ca_clonemofn, ca_clonemofn_ex, @@ -362,8 +363,8 @@ def _rpyc_getattr(self, name): exposed_ca_generatemofn_ex = staticmethod(ca_generatemofn_ex) exposed_ca_modifyusagecount = staticmethod(ca_modifyusagecount) exposed_ca_modifyusagecount_ex = staticmethod(ca_modifyusagecount_ex) - exposed_ca_destroy_multiple_objects = staticmethod(ca_destroymultipleobjects) - exposed_ca_destroy_multiple_objects_ex = staticmethod(ca_destroymultipleobjects_ex) + exposed_ca_destroy_multiple_objects = staticmethod(ca_destroy_multiple_objects) + exposed_ca_destroy_multiple_objects_ex = staticmethod(ca_destroy_multiple_objects_ex) # key_usage.py exposed_ca_clonemofn = staticmethod(ca_clonemofn) From 6a47bf88581bcc475602915d296e781bb9d6b862 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Wed, 21 Feb 2018 14:03:17 -0500 Subject: [PATCH 107/109] LA-2795 Add c_get_slot_list, and fixed a few calls C_GetSlotList can be called with a bool to get all slots or just token slots with a tokne present, added functionality to support that. Fixed some handling around get_slot_dict Replaced get_slot_info with a proper c_get_slot_info call Change-Id: Ieb2222a5828d803271b16fa202dd124dca017818 --- .gitignore | 1 + pycryptoki/cryptoki_helpers.py | 5 +- pycryptoki/daemon/rpyc_pycryptoki.py | 11 ++- pycryptoki/session_management.py | 82 +++++++++++++-------- setup.py | 2 +- tests/functional/test_session_management.py | 18 +++++ 6 files changed, 83 insertions(+), 36 deletions(-) diff --git a/.gitignore b/.gitignore index 8ab82f6..25bf4d3 100644 --- a/.gitignore +++ b/.gitignore @@ -104,6 +104,7 @@ coverage.xml # Sphinx documentation docs/_build/ +_docbuild # PyBuilder target/ diff --git a/pycryptoki/cryptoki_helpers.py b/pycryptoki/cryptoki_helpers.py index 6003893..fe123dd 100755 --- a/pycryptoki/cryptoki_helpers.py +++ b/pycryptoki/cryptoki_helpers.py @@ -204,8 +204,9 @@ def luna_function(*args): return_value = late_binded_function(*args) return return_value except Exception as e: - raise CryptokiDLLException("Call to '%s(%s)' failed.".format(function_name, - ", ".join(args)), e) + raise CryptokiDLLException("Call to '{}({})' " + "failed.".format(function_name, + ", ".join([str(arg) for arg in args])), e) luna_function.__name__ = function_name return luna_function diff --git a/pycryptoki/daemon/rpyc_pycryptoki.py b/pycryptoki/daemon/rpyc_pycryptoki.py index b865db0..2e44a56 100755 --- a/pycryptoki/daemon/rpyc_pycryptoki.py +++ b/pycryptoki/daemon/rpyc_pycryptoki.py @@ -125,7 +125,10 @@ ca_openapplicationID_ex, ca_openapplicationID, ca_closeapplicationID, ca_closeapplicationID_ex, ca_restart, ca_restart_ex, - ca_setapplicationID, ca_setapplicationID_ex) + ca_setapplicationID, ca_setapplicationID_ex, + c_get_slot_list, c_get_slot_list_ex, + c_get_slot_info, c_get_slot_info_ex, + c_get_info, c_get_info_ex) from pycryptoki.sign_verify import (c_sign, c_sign_ex, c_verify, c_verify_ex) from pycryptoki.token_management import (c_init_token, c_init_token_ex, @@ -238,6 +241,12 @@ def _rpyc_getattr(self, name): exposed_ca_setapplicationID = staticmethod(ca_setapplicationID) exposed_ca_restart_ex = staticmethod(ca_restart_ex) exposed_ca_restart = staticmethod(ca_restart) + exposed_c_get_slot_list = staticmethod(c_get_slot_list) + exposed_c_get_slot_list_ex = staticmethod(c_get_slot_list_ex) + exposed_c_get_slot_info = staticmethod(c_get_slot_info) + exposed_c_get_slot_info_ex = staticmethod(c_get_slot_info_ex) + exposed_c_get_info = staticmethod(c_get_info) + exposed_c_get_info_ex = staticmethod(c_get_info_ex) # object_attr_lookup.py exposed_c_find_objects = staticmethod(c_find_objects) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index c2564e3..1c5a025 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -6,7 +6,7 @@ from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ byref, pointer, string_at -from .common_utils import AutoCArray, refresh_c_arrays +from .common_utils import AutoCArray # cryptoki constants from .cryptoki import (CK_ULONG, CK_BBOOL, @@ -159,27 +159,55 @@ def c_get_info(): c_get_info_ex = make_error_handle_function(c_get_info) -def get_slot_info(description): - """Returns a slot with a certain descriptor +def c_get_slot_list(token_present=True): + """ + Get a list of all slots. - Limitation: Only returns the first slot it finds that fits the description + :param bool token_present: If true, will only return slots that have a token present. + :return: List of slots + """ + slots = AutoCArray(ctype=CK_ULONG) - :param description: The name of the slot to find - :returns: THe result code, a Python dictionary representing the slots + rc = C_GetSlotList(CK_BBOOL(token_present), + slots.array, + slots.size) + if rc != CKR_OK: + return rc, [] + rc = C_GetSlotList(CK_BBOOL(token_present), + slots.array, + slots.size) + return rc, [x for x in slots] - """ - ret, slot_dict = get_slot_dict() - return_dict = {} +c_get_slot_list_ex = make_error_handle_function(c_get_slot_list) - for key in slot_dict: - if re.match(description, slot_dict[key]): - return_dict[key] = slot_dict[key] - return ret, return_dict +def c_get_slot_info(slot): + """ + Get information about the given slot number. + :param int slot: Target slot + :return: Dictionary of slot information + """ + slot_info = CK_SLOT_INFO() + slot_info_dict = {} + ret = C_GetSlotInfo(slot, byref(slot_info)) + if ret != CKR_OK: + return ret, {} -get_slot_info_ex = make_error_handle_function(get_slot_info) + slot_info_dict['slotDescription'] = string_at(slot_info.slotDescription, 64).rstrip() + slot_info_dict['manufacturerID'] = string_at(slot_info.manufacturerID, 32).rstrip() + slot_info_dict['flags'] = slot_info.flags + hw_version = "{}.{}".format(slot_info.hardwareVersion.major, + slot_info.hardwareVersion.minor) + slot_info_dict['hardwareVersion'] = hw_version + fw_version = "{}.{}.{}".format(slot_info.firmwareVersion.major, + slot_info.firmwareVersion.minor / 10, + slot_info.firmwareVersion.minor % 10) + slot_info_dict['firmwareVersion'] = fw_version + return ret, slot_info_dict + +c_get_slot_info_ex = make_error_handle_function(c_get_slot_info) def c_get_session_info(session): @@ -243,31 +271,21 @@ def c_get_token_info(slot_id): c_get_token_info_ex = make_error_handle_function(c_get_token_info) -def get_slot_dict(): +def get_slot_dict(token_present=False): """Compiles a dictionary of the available slots :returns: A python dictionary of the available slots """ - slot_list = AutoCArray() - - @refresh_c_arrays(1) - def _get_slot_list(): - """ - Closure to refresh properties. - """ - return C_GetSlotList(CK_BBOOL(0), slot_list.array, slot_list.size) - - ret = _get_slot_list() - if ret != CKR_OK: - return ret, None - - slot_info = CK_SLOT_INFO() + slot_list = c_get_slot_list_ex(token_present) slot_dict = {} + ret = CKR_OK for slot in slot_list: - C_GetSlotInfo(slot, byref(slot_info)) - slot_description = str(cast(slot_info.slotDescription, c_char_p).value)[0:63].strip() - slot_dict[slot] = slot_description + ret, data = c_get_slot_info(slot) + if ret != CKR_OK: + LOG.error("C_GetSlotInfo failed at slot %s") + break + slot_dict[slot] = data return ret, slot_dict diff --git a/setup.py b/setup.py index a50ac33..4b54d10 100755 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ description="A python wrapper around the C cryptoki library.", author='Ashley Straw', url='https://github.com/gemalto/pycryptoki', - version='2.0.3', + version='2.0.4', packages=['pycryptoki', 'pycryptoki.daemon', 'pycryptoki.mechanism'], diff --git a/tests/functional/test_session_management.py b/tests/functional/test_session_management.py index 00584c9..7da4a9b 100644 --- a/tests/functional/test_session_management.py +++ b/tests/functional/test_session_management.py @@ -35,5 +35,23 @@ def test_c_get_session_info(self): def test_get_slot_dict(self): """ get_slot_dict() """ ret, slot_dict = sess_mang.get_slot_dict() + logger.debug("Slots: %s", slot_dict) assert ret == CKR_OK assert isinstance(slot_dict, dict) + + def test_get_slot_dict_token_present(self): + """ + Verify this also works with token_present = True + """ + slot_dict = sess_mang.get_slot_dict_ex(token_present=True) + for slot in slot_dict.keys(): + assert sess_mang.c_get_token_info(slot)[0] == CKR_OK + + def test_get_slot_list(self): + """ + Verify get slot list works as expected. + """ + slot_list = sess_mang.c_get_slot_list_ex(token_present=True) + for slot in slot_list: + assert isinstance(slot, integer_types) + assert sess_mang.c_get_token_info(slot)[0] == CKR_OK From b2c0bafe90a091e1d2ec99b603f9a5fb4e1acb3a Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 27 Feb 2018 13:57:39 -0500 Subject: [PATCH 108/109] LA-2803 Add rstrip option to get_token_info Default to rstripping data (backwards compatibility) Add option to not strip the data for raw comparisons -- since the HSM typically pads out data fields. Change-Id: I60ccd53d2d6d13346d1f8cc813fdf2a1c26d5a76 --- pycryptoki/session_management.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/pycryptoki/session_management.py b/pycryptoki/session_management.py index 1c5a025..1f5b157 100755 --- a/pycryptoki/session_management.py +++ b/pycryptoki/session_management.py @@ -2,8 +2,7 @@ Methods responsible for managing a user's session and login/c_logout """ import logging -import re -from ctypes import cast, c_char_p, c_void_p, create_string_buffer, \ +from ctypes import cast, c_void_p, create_string_buffer, \ byref, pointer, string_at from .common_utils import AutoCArray @@ -207,6 +206,7 @@ def c_get_slot_info(slot): slot_info_dict['firmwareVersion'] = fw_version return ret, slot_info_dict + c_get_slot_info_ex = make_error_handle_function(c_get_slot_info) @@ -233,10 +233,11 @@ def c_get_session_info(session): c_get_session_info_ex = make_error_handle_function(c_get_session_info) -def c_get_token_info(slot_id): +def c_get_token_info(slot_id, rstrip=True): """Gets the token info for a given slot id - :param int slot_id: Slot index to get the token info for + :param int slot_id: Token slot ID + :param bool rstrip: If true, will strip trailing whitespace from char data. :returns: (retcode, A python dictionary representing the token info) :rtype: tuple """ @@ -246,10 +247,10 @@ def c_get_token_info(slot_id): ret = C_GetTokenInfo(CK_ULONG(slot_id), byref(c_token_info)) if ret == CKR_OK: - token_info['label'] = string_at(c_token_info.label, 32).rstrip() - token_info['manufacturerID'] = string_at(c_token_info.manufacturerID, 32).rstrip() - token_info['model'] = string_at(c_token_info.model, 16).rstrip() - token_info['serialNumber'] = string_at(c_token_info.serialNumber, 16).rstrip() + token_info['label'] = string_at(c_token_info.label, 32) + token_info['manufacturerID'] = string_at(c_token_info.manufacturerID, 32) + token_info['model'] = string_at(c_token_info.model, 16) + token_info['serialNumber'] = string_at(c_token_info.serialNumber, 16) token_info['flags'] = c_token_info.flags token_info['ulFreePrivateMemory'] = c_token_info.ulFreePrivateMemory token_info['ulTotalPrivateMemory'] = c_token_info.ulTotalPrivateMemory @@ -263,7 +264,13 @@ def c_get_token_info(slot_id): token_info['ulFreePublicMemory'] = c_token_info.ulFreePublicMemory token_info['hardwareVersion'] = c_token_info.hardwareVersion token_info['firmwareVersion'] = c_token_info.firmwareVersion - token_info['utcTime'] = string_at(c_token_info.utcTime, 16).rstrip() + token_info['utcTime'] = string_at(c_token_info.utcTime, 16) + if rstrip: + token_info['label'] = token_info['label'].rstrip() + token_info['manufacturerID'] = token_info['manufacturerID'].rstrip() + token_info['model'] = token_info['model'].rstrip() + token_info['serialNumber'] = token_info['serialNumber'].rstrip() + token_info['utcTime'] = token_info['utcTime'].rstrip() return ret, token_info From ffc2c488035c0033144c374c9444f4fb35340041 Mon Sep 17 00:00:00 2001 From: Ashley Straw Date: Tue, 6 Mar 2018 13:38:57 -0500 Subject: [PATCH 109/109] LA-2808 Mergin changes from github to gerrit Change-Id: I04ea2a625b316197d323d00f11dfd42abc7c93bd --- LICENSE | 208 +++++++++++++++++- docs/conf.py | 6 +- docs/index.rst | 5 +- docs/requirements.txt | 3 + setup.py | 2 +- test_requirements.txt | 4 + .../functional/test_supporting_operations.py | 52 +++++ 7 files changed, 265 insertions(+), 15 deletions(-) create mode 100644 docs/requirements.txt create mode 100644 test_requirements.txt create mode 100755 tests/functional/test_supporting_operations.py diff --git a/LICENSE b/LICENSE index ec084ef..1e448e7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,13 +1,201 @@ -Copyright 2016 Gemalto + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - http://www.apache.org/licenses/LICENSE-2.0 + 1. Definitions. -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016 - Gemalto + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/docs/conf.py b/docs/conf.py index 5c52c87..7c939d7 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -52,16 +52,16 @@ # General information about the project. project = u'Pycryptoki' -copyright = u'2016, Gemalto' +copyright = u'2018, Gemalto' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '2.0' +version = '2.1' # The full version, including alpha/beta/rc tags. -release = '2.0.3' +release = '2.1.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/docs/index.rst b/docs/index.rst index ee618f2..2e60053 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,6 +1,7 @@ Pycryptoki ========== + Overview -------- @@ -10,7 +11,7 @@ we can simplify memory management, and provide easy, pythonic access to a PKCS11 The primary function of pycryptoki is to *simplify* PKCS11 calls. Rather than needing to calculate data sizes, buffers, or other low-level memory manipulation, you simply need to pass in data. -It's highly recommended that you have the `PKCS11`_ documentation +It's highly recommended that you have the `PKCS11 `_ documentation handy, as pycryptoki uses that as the underlying C interface. Session management, object management, and other concepts are unchanged from PKCS11. @@ -41,6 +42,8 @@ and other concepts are unchanged from PKCS11. c_close_session_ex(auth_session) c_finalize_ex() + + .. toctree:: :maxdepth: 4 :includehidden: diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..53de3b4 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,3 @@ +sphinx +sphinx_rtd_theme +sphinxcontrib-napoleon diff --git a/setup.py b/setup.py index 4b54d10..ec7be6d 100755 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ description="A python wrapper around the C cryptoki library.", author='Ashley Straw', url='https://github.com/gemalto/pycryptoki', - version='2.0.4', + version='2.1.1', packages=['pycryptoki', 'pycryptoki.daemon', 'pycryptoki.mechanism'], diff --git a/test_requirements.txt b/test_requirements.txt new file mode 100644 index 0000000..ca66ecb --- /dev/null +++ b/test_requirements.txt @@ -0,0 +1,4 @@ +pytz +mock +pytest +hypothesis diff --git a/tests/functional/test_supporting_operations.py b/tests/functional/test_supporting_operations.py new file mode 100755 index 0000000..b9880b0 --- /dev/null +++ b/tests/functional/test_supporting_operations.py @@ -0,0 +1,52 @@ +import logging + +import pytest + +from . import config as hsm_config +from pycryptoki.defines import CKR_OK +from pycryptoki.misc import c_generate_random_ex, c_seed_random, \ + c_generate_random +from pycryptoki.return_values import ret_vals_dictionary + +logger = logging.getLogger(__name__) + + +class TestSupportingOperations(object): + """ """ + + @pytest.fixture(autouse=True) + def setup_teardown(self, auth_session): + self.h_session = auth_session + self.admin_slot = hsm_config["test_slot"] + + def test_rng(self): + """Tests generating a random number""" + length = 15 + ret, random_string = c_generate_random(self.h_session, length) + assert ret == CKR_OK, "C_GenerateRandom should return CKR_OK, instead it returned " + \ + ret_vals_dictionary[ret] + assert len( + random_string) == length, "The length of the random string should be the same as the " \ + "length of the requested data." + + def test_seeded_rng(self): + """Tests that seeding the random number generator with the same data will + generate the same random number + + + """ + seed = b"k" * 1024 + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator shouldn't return an error, " \ + "it returned " + \ + ret_vals_dictionary[ret] + + random_string_one = c_generate_random_ex(self.h_session, 10) + + ret = c_seed_random(self.h_session, seed) + assert ret == CKR_OK, "Seeding the random number generator a second time shouldn't return " \ + "" \ + "an error, it returned " + \ + ret_vals_dictionary[ret] + + random_string_two = c_generate_random_ex(self.h_session, 10)