def list_kek_labels(password):
    '''
        List labels of upto 100 keys
        password - string CryptoUser role password
    '''

    # HSM slot id for HA
    slot_id = 5
    labels = []
    try:
        auth_session = None
        _initialize()
        auth_session = c_open_session_ex(slot_id)
        login_ex(auth_session, slot_id, password, CKU_CRYPTO_USER)

        key_handles = c_find_objects_ex(auth_session, {CKA_KEY_TYPE: CKK_AES},
                                        100)
        for handle in key_handles:
            label = c_get_attribute_value_ex(
                auth_session, handle,
                Attributes({CKA_LABEL: b'01234567890123456789012345'}))
            labels.append(label[3].decode("utf-8"))
    except LunaCallException:
        print("Exception running key mgmt operation")
        print(traceback.format_exc())
        raise Exception('Exception running key mgmt operation')
    finally:
        if auth_session:
            c_logout_ex(auth_session)
            c_close_session_ex(auth_session)
        c_finalize_ex()

    return labels
Example #2
0
def hsm_configured(pytestconfig):
    """
    Factory reset & init the hsm.
    """
    c_initialize_ex()
    try:
        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()
Example #3
0
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
        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
        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
            co_pwd = config.getoption("copassword", default=None)
        else:
            admin_pwd = config.getoption("password")
            co_pwd = config.getoption("copassword", default=CO_PASSWORD)

        if admin_pwd:
            admin_pwd = admin_pwd
        if co_pwd:
            co_pwd = co_pwd

        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()
Example #4
0
    def open(self):
        """
        Open the session, initializing cryptoki if necessary.

        :return: session handle
        """
        if self.manage_init:
            c_initialize_ex()
        try:
            self.session = c_open_session_ex(self.slot, self.flags)
            return self.session
        except:
            if self.manage_init:
                c_finalize_ex()
            raise
Example #5
0
def encrypt(password, kek_label, plaintext_path):
    '''
        Encrypt plain text to cipher text
        password - string CryptoUser role password
        kek_label - string label of decryption key in HSM
        plaintext_path - path of base64 encoded data to be encrypted
    '''
    plaintext = open(plaintext_path, 'rb').read()
    encrypted = None
    i = 0
    while i < 2:
        try:
            auth_session = None
            _initialize()
            auth_session = c_open_session_ex(i)
            login_ex(auth_session, i, password, CKU_CRYPTO_USER)

            kek_handle = None
            kek_handle = c_find_objects_ex(auth_session, {
                CKA_KEY_TYPE: CKK_AES,
                CKA_LABEL: kek_label
            }, 1)
            if kek_handle:
                params = {"iv": list(range(16)), "AAD": [], "ulTagBits": 128}
                mechanism = Mechanism(mech_type=CKM_AES_GCM, params=params)
                encrypted = c_encrypt_ex(auth_session, kek_handle[0],
                                         plaintext, mechanism)
                encrypted = array.array('B', list(
                    range(16))).tostring() + encrypted
                break
            else:
                i += 1
        except LunaCallException:
            print("Exception running key mgmt operation on slot " + str(i))
            print(traceback.format_exc())
            i += 1
        finally:
            if auth_session:
                c_logout_ex(auth_session)
                c_close_session_ex(auth_session)
            c_finalize_ex()

    if encrypted:
        ciphertext = base64.b64encode(encrypted)
        return ciphertext
    else:
        raise Exception("Failed to encrypt DEK")
def decrypt(password, kek_label, path_to_plain_text):
    '''
        Decrypt cipher text to plain text
        password - string CryptoUser role password
        kek_label - string label of decryption key in HSM
        path_to_plain_text - path of base64 encoded data to be decrypted
    '''
    ciphertext = open(path_to_plain_text, 'rb').read()
    decrypted = None
    i = 0
    while i < 2:
        try:
            cipher = base64.b64decode(ciphertext)
            auth_session = None
            _initialize()
            auth_session = c_open_session_ex(i)
            login_ex(auth_session, i, password, CKU_CRYPTO_USER)

            kek_handle = None
            kek_handle = c_find_objects_ex(auth_session,
                                           {CKA_KEY_TYPE: CKK_AES, CKA_LABEL: kek_label},
                                           1)
            if kek_handle:
                params = {"iv": cipher[:16], "AAD": [], "ulTagBits": 128}
                mechanism = Mechanism(mech_type=CKM_AES_GCM, params=params)
                decrypted = c_decrypt_ex(auth_session, kek_handle[0], cipher[16:], mechanism)
                break
            else:
                i += 1
        except LunaCallException:
            i += 1
        except Exception:
            raise("Failed to decrypt DEK")
        finally:
            if auth_session:
                c_logout_ex(auth_session)
                c_close_session_ex(auth_session)
            c_finalize_ex()

    if decrypted:
        return decrypted
    else:
        raise Exception("Failed to decrypt DEK")
def generate_keys(password, kek_plain_text):
    '''
    Generate AES keys
    password - string CryptoOfficer role password
    kek_plain_text - kek label
    '''

    # HSM slot id for HA
    slot_id = 5

    c_initialize_ex()
    auth_session = c_open_session_ex(slot_id)
    login_ex(auth_session, slot_id, password)

    CKM_AES_KEY_GEN_TEMP[CKA_LABEL] = bytes(kek_plain_text, 'utf-8')
    key_handle = c_generate_key_ex(auth_session, CKM_AES_KEY_GEN,
                                   CKM_AES_KEY_GEN_TEMP)

    c_logout_ex(auth_session)
    c_close_session_ex(auth_session)
    c_finalize_ex()

    return key_handle
Example #8
0
 def close(self):
     """Close the session. Finalize if we initialized."""
     c_close_session_ex(self.session)
     if self.manage_init:
         c_finalize_ex()
Example #9
0
 def __exit__(self, exc_type, exc_value, exc_traceback):
     """Finalize cryptoki"""
     c_finalize_ex()
from pycryptoki.session_management import (c_initialize_ex, c_get_info_ex,
                                           c_get_slot_list_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()))
slot_list = c_get_slot_list_ex()
print("C_GetSlotList:")
print("\n".join("\t{}".format(x) for x in slot_list))
# Use the first available Slot ID:
slot_id = slot_list[0]
token_info = c_get_token_info_ex(slot_id)
print("C_GetTokenInfo:")
print("\n".join("\t{}: {}".format(x, y) for x, y in token_info.items()))
print("Firmware version: {}".format(get_firmware_version(slot_id)))

c_finalize_ex()