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 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 #5
0
 def close(self):
     """Close the session. Finalize if we initialized."""
     c_close_session_ex(self.session)
     if self.manage_init:
         c_finalize_ex()
    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 = {'year': b"2013", 'month': b"12", 'day': b"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: 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, b"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, 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)
        c_close_session_ex(h_session)
    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 = {'year': b"2013", 'month': b"12", 'day': b"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: end_d,
            CKA_LABEL: b"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: 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,
            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, b"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, 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"