Skip to content

Commit

Permalink
Convert memset calls to OPENSSL_cleanse
Browse files Browse the repository at this point in the history
to securely erase sensitive keys values from memory.
  • Loading branch information
sats0k committed Sep 23, 2021
1 parent 8b02775 commit aba816b
Showing 1 changed file with 22 additions and 22 deletions.
44 changes: 22 additions & 22 deletions src/db.h
Original file line number Diff line number Diff line change
Expand Up @@ -131,23 +131,23 @@ class CDB
Dbt datValue;
datValue.set_flags(DB_DBT_MALLOC);
int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
memset(datKey.get_data(), 0, datKey.get_size());
if (datValue.get_data() == NULL)
return false;

// Unserialize value
try {
CDataStream ssValue((char*)datValue.get_data(), (char*)datValue.get_data() + datValue.get_size(), SER_DISK, CLIENT_VERSION);
ssValue >> value;
}
catch (std::exception &e) {
return false;
OPENSSL_cleanse(datKey.get_data(), datKey.get_size());
bool success = false;
if (datValue.get_data() != nullptr) {
// Unserialize value
try {
CDataStream ssValue((char*)datValue.get_data(), (char*)datValue.get_data() + datValue.get_size(), SER_DISK, CLIENT_VERSION);
ssValue >> value;
success = true;
} catch (const std::exception&) {
// In this case success remains 'false'
}

// Clear and free memory
OPENSSL_cleanse(datValue.get_data(), datValue.get_size());
free(datValue.get_data());
}

// Clear and free memory
memset(datValue.get_data(), 0, datValue.get_size());
free(datValue.get_data());
return (ret == 0);
return(ret == 0 && success);
}

template<typename K, typename T>
Expand All @@ -174,8 +174,8 @@ class CDB
int ret = pdb->put(activeTxn, &datKey, &datValue, (fOverwrite ? 0 : DB_NOOVERWRITE));

// Clear memory in case it was a private key
memset(datKey.get_data(), 0, datKey.get_size());
memset(datValue.get_data(), 0, datValue.get_size());
OPENSSL_cleanse(datKey.get_data(), datKey.get_size());
OPENSSL_cleanse(datValue.get_data(), datValue.get_size());
return (ret == 0);
}

Expand All @@ -197,7 +197,7 @@ class CDB
int ret = pdb->del(activeTxn, &datKey, 0);

// Clear memory
memset(datKey.get_data(), 0, datKey.get_size());
OPENSSL_cleanse(datKey.get_data(), datKey.get_size());
return (ret == 0 || ret == DB_NOTFOUND);
}

Expand All @@ -217,7 +217,7 @@ class CDB
int ret = pdb->exists(activeTxn, &datKey, 0);

// Clear memory
memset(datKey.get_data(), 0, datKey.get_size());
OPENSSL_cleanse(datKey.get_data(), datKey.get_size());
return (ret == 0);
}

Expand Down Expand Up @@ -264,8 +264,8 @@ class CDB
ssValue.write((char*)datValue.get_data(), datValue.get_size());

// Clear and free memory
memset(datKey.get_data(), 0, datKey.get_size());
memset(datValue.get_data(), 0, datValue.get_size());
OPENSSL_cleanse(datKey.get_data(), datKey.get_size());
OPENSSL_cleanse(datValue.get_data(), datValue.get_size());
free(datKey.get_data());
free(datValue.get_data());
return 0;
Expand Down

0 comments on commit aba816b

Please sign in to comment.