Showing with 36 additions and 7 deletions.
  1. +36 −7 tools/tpm2_import.c
43 changes: 36 additions & 7 deletions tools/tpm2_import.c
Expand Up @@ -94,6 +94,7 @@ static tpm_import_ctx ctx = {
.import_key_private = TPM2B_EMPTY_INIT,
};

#if OPENSSL_VERSION_NUMBER < 0x1010000fL /* OpenSSL 1.1.0 */
static void ssl_RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) {

if ((r->n == NULL && n == NULL) || (r->e == NULL && e == NULL)) {
Expand All @@ -115,8 +116,11 @@ static void ssl_RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) {
r->d = d;
}
}
#endif

static bool encrypt_seed_with_tpm2_rsa_public_key(void) {
bool rval = false;

//Public Modulus
FILE *fp = fopen(ctx.parent_key_public_file, "rb");
if (fp == NULL) {
Expand All @@ -125,12 +129,14 @@ static bool encrypt_seed_with_tpm2_rsa_public_key(void) {
}
if (fseek(fp, 102, SEEK_SET) != 0) {
LOG_ERR("Expected parent key public data file size failure");
fclose(fp);
return false;
}
unsigned char pub_modulus[MAX_RSA_KEY_BYTES] = { 0 };
int ret = fread(pub_modulus, 1, MAX_RSA_KEY_BYTES, fp);
if (ret != MAX_RSA_KEY_BYTES) {
LOG_ERR("Failed reading public modulus from parent key public file");
fclose(fp);
return false;
}
fclose(fp);
Expand All @@ -145,32 +151,55 @@ static bool encrypt_seed_with_tpm2_rsa_public_key(void) {
return false;
}
BIGNUM* bne = BN_new();
if (!bne) {
LOG_ERR("BN_new for bne failed\n");
return false;
}
return_code = BN_set_word(bne, RSA_F4);
if (return_code != 1) {
LOG_ERR("BN_set_word failed\n");
return 1;
BN_free(bne);
return false;
}
rsa = RSA_new();
if (!rsa) {
LOG_ERR("RSA_new failed\n");
BN_free(bne);
return false;
}
return_code = RSA_generate_key_ex(rsa, 2048, bne, NULL);
BN_free(bne);
if (return_code != 1) {
LOG_ERR("RSA_generate_key_ex failed\n");
return 1;
goto error;
}
BIGNUM *n = BN_bin2bn(pub_modulus, MAX_RSA_KEY_BYTES, NULL);
ssl_RSA_set0_key(rsa, n, NULL, NULL);
if (n == NULL) {
LOG_ERR("Failed RSA_set0_key\n");
return 1;
LOG_ERR("BN_bin2bn failed\n");
goto error;
}
#if OPENSSL_VERSION_NUMBER < 0x1010000fL /* OpenSSL 1.1.0 */
ssl_RSA_set0_key(rsa, n, NULL, NULL);
#else
if (!RSA_set0_key(rsa, n, NULL, NULL)) {
LOG_ERR("RSA_set0_key failed\n");
BN_free(n);
goto error;
}
#endif
// Encrypting
return_code = RSA_public_encrypt(MAX_RSA_KEY_BYTES, encoded,
ctx.encrypted_protection_seed_data, rsa, RSA_NO_PADDING);
if (return_code < 0) {
LOG_ERR("Failed RSA_public_encrypt\n");
goto error;
}

rval = true;

error:
RSA_free(rsa);
BN_free(bne);
return true;
return rval;
}

static void aes_128_cfb_encrypt_buffers(uint8_t *buffer1, uint16_t buffer1_size,
Expand Down