From 627bd655347cb3aaf04b352e4f0a0207d64c8cb1 Mon Sep 17 00:00:00 2001 From: dec05eba Date: Wed, 16 May 2018 11:00:10 +0200 Subject: Fix memory leak (mismatch free/delete/delete[]), fix invalid memory access --- src/Database.cpp | 50 +++++++++++++++++++++++++------------------------ src/DatabaseStorage.cpp | 36 +++++++++++++++++------------------ src/FileUtils.cpp | 4 ++-- src/PasswordHash.cpp | 4 ++-- 4 files changed, 48 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/src/Database.cpp b/src/Database.cpp index df11b3c..b4d0e12 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -41,26 +41,26 @@ namespace odhtdb RequestQuarantineException() : runtime_error("Request quarantine, will be processed later (can be real of fake request)") {} }; - OwnedMemory combine(sibs::SafeSerializer &headerSerializer, const Encryption &encryptedData) + OwnedByteArray combine(sibs::SafeSerializer &headerSerializer, const Encryption &encryptedData) { usize allocationSize = headerSerializer.getBuffer().size() + encryptedData.getNonce().size + encryptedData.getCipherText().size; - char *result = new char[allocationSize]; + u8 *result = new u8[allocationSize]; memcpy(result, headerSerializer.getBuffer().data(), headerSerializer.getBuffer().size()); memcpy(result + headerSerializer.getBuffer().size(), encryptedData.getNonce().data, encryptedData.getNonce().size); memcpy(result + headerSerializer.getBuffer().size() + encryptedData.getNonce().size, encryptedData.getCipherText().data, encryptedData.getCipherText().size); - return OwnedMemory(result, allocationSize); + return OwnedByteArray(result, allocationSize); } - OwnedMemory combine(const Signature::PublicKey &publicKey, const string &signedEncryptedData) + OwnedByteArray combine(const Signature::PublicKey &publicKey, const string &signedEncryptedData) { usize allocationSize = publicKey.getSize() + signedEncryptedData.size(); - char *result = new char[allocationSize]; + u8 *result = new u8[allocationSize]; memcpy(result, publicKey.getData(), publicKey.getSize()); memcpy(result + publicKey.getSize(), signedEncryptedData.data(), signedEncryptedData.size()); - return OwnedMemory(result, allocationSize); + return OwnedByteArray(result, allocationSize); } - DatabaseCreateResponse::DatabaseCreateResponse(std::shared_ptr _nodeAdminKeyPair, std::shared_ptr _nodeAdminGroupId, shared_ptr _key, shared_ptr _hash) : + DatabaseCreateResponse::DatabaseCreateResponse(std::shared_ptr _nodeAdminKeyPair, std::shared_ptr _nodeAdminGroupId, shared_ptr _key, shared_ptr _hash) : nodeAdminKeyPair(_nodeAdminKeyPair), nodeAdminGroupId(_nodeAdminGroupId), key(_key), @@ -74,12 +74,12 @@ namespace odhtdb return nodeAdminKeyPair; } - const shared_ptr DatabaseCreateResponse::getNodeAdminGroupId() const + const shared_ptr DatabaseCreateResponse::getNodeAdminGroupId() const { return nodeAdminGroupId; } - const shared_ptr DatabaseCreateResponse::getNodeEncryptionKey() const + const shared_ptr DatabaseCreateResponse::getNodeEncryptionKey() const { return key; } @@ -336,25 +336,27 @@ namespace odhtdb bool iHaveCreateNode = databaseStorage.doesNodeExist(*nodeToSeed.getRequestHash()); serializer.add(iHaveCreateNode ? (u8)0 : (u8)1); serializer.add(fetchOrder); - DataViewMap userLatestActionCounter; + Signature::MapPublicKey userLatestActionCounter; - databaseStorage.fetchNodeUserActionGaps(*nodeToSeed.getRequestHash(), [&serializer, &userLatestActionCounter](const DataView userPublicKey, u64 actionGapStart, u64 actionGapRange) + databaseStorage.fetchNodeUserActionGaps(*nodeToSeed.getRequestHash(), [&serializer, &userLatestActionCounter](const DataView userPublicKeyRaw, u64 actionGapStart, u64 actionGapRange) { - serializer.add((const u8*)userPublicKey.data, PUBLIC_KEY_NUM_BYTES); + serializer.add((const u8*)userPublicKeyRaw.data, PUBLIC_KEY_NUM_BYTES); serializer.add(actionGapStart); serializer.add(actionGapRange); + Signature::PublicKey userPublicKey((const char*)userPublicKeyRaw.data, userPublicKeyRaw.size); userLatestActionCounter[userPublicKey] = std::max(userLatestActionCounter[userPublicKey], actionGapStart + actionGapRange); }); - databaseStorage.fetchNodeUserLatestActionCounter(*nodeToSeed.getRequestHash(), [&userLatestActionCounter](const DataView userPublicKey, u64 latestActionCounter) + databaseStorage.fetchNodeUserLatestActionCounter(*nodeToSeed.getRequestHash(), [&userLatestActionCounter](const DataView userPublicKeyRaw, u64 latestActionCounter) { + Signature::PublicKey userPublicKey((const char*)userPublicKeyRaw.data, userPublicKeyRaw.size); userLatestActionCounter[userPublicKey] = std::max(userLatestActionCounter[userPublicKey], latestActionCounter); }); for(auto userLatestActionCounterData : userLatestActionCounter) { // Public key - serializer.add((const u8*)userLatestActionCounterData.first.data, PUBLIC_KEY_NUM_BYTES); + serializer.add((const u8*)userLatestActionCounterData.first.getData(), PUBLIC_KEY_NUM_BYTES); // Latest action counter start serializer.add(userLatestActionCounterData.second); // Latest action counter range (infinite range, meaning we want all packets older than start (latest known packet by user)) @@ -407,7 +409,7 @@ namespace odhtdb { unsigned char *encryptionKeyRaw = new unsigned char[ENCRYPTION_KEY_BYTE_SIZE]; Encryption::generateKey(encryptionKeyRaw); - shared_ptr encryptionKey = make_shared(encryptionKeyRaw, ENCRYPTION_KEY_BYTE_SIZE); + shared_ptr encryptionKey = make_shared(encryptionKeyRaw, ENCRYPTION_KEY_BYTE_SIZE); shared_ptr hashRequestKey = make_shared(serializer.getBuffer().data(), serializer.getBuffer().size()); databaseStorage.setNodeDecryptionKey(*hashRequestKey, DataView(encryptionKey->data, encryptionKey->size)); @@ -422,7 +424,7 @@ namespace odhtdb Log::warn("Failed to put: %s, what to do?", "Database::create"); }); - shared_ptr adminGroupIdResponse = make_shared(new u8[GROUP_ID_LENGTH], GROUP_ID_LENGTH); + shared_ptr adminGroupIdResponse = make_shared(new u8[GROUP_ID_LENGTH], GROUP_ID_LENGTH); memcpy(adminGroupIdResponse->data, adminGroupId.data, GROUP_ID_LENGTH); return make_unique(creatorKeyPair, adminGroupIdResponse, encryptionKey, hashRequestKey); } @@ -444,9 +446,9 @@ namespace odhtdb DataView encryptionKey(nodeInfo.getNodeEncryptionKey()->data, ENCRYPTION_KEY_BYTE_SIZE); Encryption encryptedBody(dataToAdd, encryptionKey); - OwnedMemory requestData = combine(serializer, encryptedBody); + OwnedByteArray requestData = combine(serializer, encryptedBody); string signedRequestData = userToPerformActionWith.getPrivateKey().sign(requestData.getView()); - OwnedMemory stagedAddObject = combine(userToPerformActionWith.getPublicKey(), signedRequestData); + OwnedByteArray stagedAddObject = combine(userToPerformActionWith.getPublicKey(), signedRequestData); Hash requestDataHash(stagedAddObject.data, stagedAddObject.size); DataView encryptedDataView((char*)requestData.data + serializer.getBuffer().size(), requestData.size - serializer.getBuffer().size()); databaseStorage.appendStorage(*nodeInfo.getRequestHash(), requestDataHash, DatabaseOperation::ADD_DATA, newActionCounter, userToPerformActionWith.getPublicKey(), timestampCombined, (u8*)stagedAddObject.data, stagedAddObject.size, encryptedDataView); @@ -480,7 +482,7 @@ namespace odhtdb DataView requestData { serializer.getBuffer().data(), serializer.getBuffer().size() }; string signedRequestData = userToPerformActionWith.getPrivateKey().sign(requestData); - OwnedMemory stagedAddObject = combine(userToPerformActionWith.getPublicKey(), signedRequestData); + OwnedByteArray stagedAddObject = combine(userToPerformActionWith.getPublicKey(), signedRequestData); Hash requestDataHash(stagedAddObject.data, stagedAddObject.size); DataView additionalDataView((void*)(static_cast(requestData.data) + additionalDataOffset), requestData.size - additionalDataOffset); databaseStorage.appendStorage(*nodeInfo.getRequestHash(), requestDataHash, DatabaseOperation::ADD_USER, newActionCounter, userToPerformActionWith.getPublicKey(), timestampCombined, (u8*)stagedAddObject.data, stagedAddObject.size, additionalDataView); @@ -511,7 +513,7 @@ namespace odhtdb return timestamp; } - void Database::deserializeCreateRequest(const shared_ptr &value, const Hash &hash, const shared_ptr encryptionKey) + void Database::deserializeCreateRequest(const shared_ptr &value, const Hash &hash, const shared_ptr encryptionKey) { sibs::SafeDeserializer deserializer(value->data.data(), value->data.size()); u16 packetStructureVersion = deserializer.extract(); @@ -551,7 +553,7 @@ namespace odhtdb databaseStorage.createStorage(hash, userPublicKey, DataView(adminGroupId, GROUP_ID_LENGTH), creationDate, value->data.data(), value->data.size()); } - void Database::deserializeAddRequest(const shared_ptr &value, const Hash &requestDataHash, const std::shared_ptr &nodeHash, const shared_ptr encryptionKey) + void Database::deserializeAddRequest(const shared_ptr &value, const Hash &requestDataHash, const std::shared_ptr &nodeHash, const shared_ptr encryptionKey) { sibs::SafeDeserializer deserializer(value->data.data(), value->data.size()); char creatorPublicKeyRaw[PUBLIC_KEY_NUM_BYTES]; @@ -593,7 +595,7 @@ namespace odhtdb databaseStorage.appendStorage(*nodeHash, requestDataHash, operation, newActionCounter, creatorPublicKey, creationDate, value->data.data(), value->data.size(), additionalDataView); } - bool Database::listenCreateData(shared_ptr value, const Hash &hash, const shared_ptr encryptionKey) + bool Database::listenCreateData(shared_ptr value, const Hash &hash, const shared_ptr encryptionKey) { Log::debug("Got create data"); try @@ -611,7 +613,7 @@ namespace odhtdb return true; } - bool Database::listenAddData(shared_ptr value, const Hash &requestDataHash, const std::shared_ptr nodeHash, const shared_ptr encryptionKey) + bool Database::listenAddData(shared_ptr value, const Hash &requestDataHash, const std::shared_ptr nodeHash, const shared_ptr encryptionKey) { Log::debug("Got add data"); try @@ -653,7 +655,7 @@ namespace odhtdb return databaseStorage.getStoredNodeUserInfoDecrypted(username, password); } - vector Database::getUserGroups(const Hash &nodeHash, const Signature::PublicKey &userPublicKey) const + vector Database::getUserGroups(const Hash &nodeHash, const Signature::PublicKey &userPublicKey) const { return databaseStorage.getUserGroups(nodeHash, userPublicKey); } diff --git a/src/DatabaseStorage.cpp b/src/DatabaseStorage.cpp index 016c498..ccf5d26 100644 --- a/src/DatabaseStorage.cpp +++ b/src/DatabaseStorage.cpp @@ -285,7 +285,7 @@ namespace odhtdb // TODO: There is no need to allocate/deallocate several times, this can be moved outside the while loop const void *decryptedDataRaw = sqlite3_column_blob(selectNodeAddDataAdditionalStmt, 0); int decryptedDataSize = sqlite3_column_bytes(selectNodeAddDataAdditionalStmt, 0); - OwnedMemory decryptedData(new u8[decryptedDataSize], decryptedDataSize); + OwnedByteArray decryptedData(new u8[decryptedDataSize], decryptedDataSize); memcpy(decryptedData.data, decryptedDataRaw, decryptedDataSize); const DatabaseAddNodeRequest addNodeRequest(&nodeHash, &requestHash, timestamp, &creatorPublicKey, DataView(decryptedData.data, decryptedData.size)); @@ -324,7 +324,7 @@ namespace odhtdb void DatabaseStorage::loadMetadataFromFile() { - OwnedMemory metadataFileContent = fileGetContent(metadataFilePath); + OwnedByteArray metadataFileContent = fileGetContent(metadataFilePath); sibs::SafeDeserializer deserializer((u8*)metadataFileContent.data, metadataFileContent.size); u16 storageVersion = deserializer.extract(); @@ -350,7 +350,7 @@ namespace odhtdb void DatabaseStorage::loadRemoteNodesFromFile() { - OwnedMemory remoteNodesFileContent = fileGetContent(remoteNodesFilePath); + OwnedByteArray remoteNodesFileContent = fileGetContent(remoteNodesFilePath); msgpack::unpacker pac; pac.reserve_buffer(remoteNodesFileContent.size); memcpy(pac.buffer(), remoteNodesFileContent.data, remoteNodesFileContent.size); @@ -846,7 +846,7 @@ namespace odhtdb void DatabaseStorage::storeUserWithoutNodes(const string &username, const string &password) { - OwnedMemory hashedPassword = hashPassword(DataView((void*)password.data(), password.size()), DataView((void*)passwordSalt, PASSWORD_SALT_LEN)); + OwnedByteArray hashedPassword = hashPassword(DataView((void*)password.data(), password.size()), DataView((void*)passwordSalt, PASSWORD_SALT_LEN)); DataView hashedPasswordView(hashedPassword.data, hashedPassword.size); DataView usernameView((void*)username.data(), username.size()); @@ -884,7 +884,7 @@ namespace odhtdb void DatabaseStorage::storeNodeInfoForUserEncrypted(const DatabaseNode &nodeInfo, const string &username, const string &password, const Signature::KeyPair &keyPair) { - OwnedMemory hashedPassword = hashPassword(DataView((void*)password.data(), password.size()), DataView((void*)passwordSalt, PASSWORD_SALT_LEN)); + OwnedByteArray hashedPassword = hashPassword(DataView((void*)password.data(), password.size()), DataView((void*)passwordSalt, PASSWORD_SALT_LEN)); DataView hashedPasswordView(hashedPassword.data, hashedPassword.size); DataView privateKeyView((void*)keyPair.getPrivateKey().getData(), PRIVATE_KEY_NUM_BYTES); @@ -929,7 +929,7 @@ namespace odhtdb MapHash DatabaseStorage::getStoredNodeUserInfoDecrypted(const string &username, const string &password) const { - OwnedMemory hashedPassword = hashPassword(DataView((void*)password.data(), password.size()), DataView((void*)passwordSalt, PASSWORD_SALT_LEN)); + OwnedByteArray hashedPassword = hashPassword(DataView((void*)password.data(), password.size()), DataView((void*)passwordSalt, PASSWORD_SALT_LEN)); DataView hashedPasswordView(hashedPassword.data, hashedPassword.size); i64 encryptedUserRowId = getStoredUserId(username, hashedPasswordView); @@ -953,7 +953,7 @@ namespace odhtdb throw DatabaseStorageException("Encrypted data size is of unexpected size"); Signature::PrivateKey userPrivateKey((const char*)decryptedStoredNodeUserPrivateKey.getDecryptedText().data, PRIVATE_KEY_NUM_BYTES); shared_ptr keyPair = make_shared(userPublicKey, userPrivateKey); - shared_ptr nodeEncryptionKey = make_shared(new u8[ENCRYPTION_KEY_BYTE_SIZE], ENCRYPTION_KEY_BYTE_SIZE); + shared_ptr nodeEncryptionKey = make_shared(new u8[ENCRYPTION_KEY_BYTE_SIZE], ENCRYPTION_KEY_BYTE_SIZE); memcpy(nodeEncryptionKey->data, (char*)decryptedStoredNodeUserPrivateKey.getDecryptedText().data + PRIVATE_KEY_NUM_BYTES, ENCRYPTION_KEY_BYTE_SIZE); result[nodeHash] = { nodeEncryptionKey, keyPair }; } @@ -965,7 +965,7 @@ namespace odhtdb return result; } - pair> DatabaseStorage::getNodeDecryptionKey(const Hash &nodeHash) + pair> DatabaseStorage::getNodeDecryptionKey(const Hash &nodeHash) { sqlite3_reset(getNodeDecryptionKeyStmt); sqlite3_clear_bindings(getNodeDecryptionKeyStmt); @@ -976,12 +976,12 @@ namespace odhtdb rc = sqlite3_step(getNodeDecryptionKeyStmt); if(rc != SQLITE_ROW) - return make_pair(false, make_shared()); + return make_pair(false, make_shared()); const void *decryptionKeyRaw = sqlite3_column_blob(getNodeDecryptionKeyStmt, 0); u8 *decryptionKeyRawCopy = new u8[ENCRYPTION_KEY_BYTE_SIZE]; memcpy(decryptionKeyRawCopy, decryptionKeyRaw, ENCRYPTION_KEY_BYTE_SIZE); - shared_ptr decryptionKey = make_shared(decryptionKeyRawCopy, ENCRYPTION_KEY_BYTE_SIZE); + shared_ptr decryptionKey = make_shared(decryptionKeyRawCopy, ENCRYPTION_KEY_BYTE_SIZE); return make_pair(true, decryptionKey); } @@ -1033,21 +1033,21 @@ namespace odhtdb fileOverwrite(remoteNodesFilePath, DataView(remoteNodePacker.serializer.getBuffer().data(), remoteNodePacker.serializer.getBuffer().size())); } - vector DatabaseStorage::getUserGroups(const Hash &nodeHash, const Signature::PublicKey &userPublicKey) const + vector DatabaseStorage::getUserGroups(const Hash &nodeHash, const Signature::PublicKey &userPublicKey) const { - vector result; + vector result; SqlQuery query(sqliteDb, "SELECT groupId FROM NodeUserGroupAssoc WHERE node = ? AND userPublicKey = ?", { DataView(nodeHash.getData(), nodeHash.getSize()), DataView((void*)userPublicKey.getData(), userPublicKey.getSize()) }); while(query.next()) { const DataView groupIdRaw = query.getBlob(0); - OwnedMemory groupId(new u8[groupIdRaw.size], groupIdRaw.size); + OwnedByteArray groupId(new u8[groupIdRaw.size], groupIdRaw.size); memcpy(groupId.data, groupIdRaw.data, groupIdRaw.size); result.emplace_back(move(groupId)); } return result; } - bool DatabaseStorage::decryptNodeData(const Hash &nodeHash, const shared_ptr decryptionKey) + bool DatabaseStorage::decryptNodeData(const Hash &nodeHash, const shared_ptr decryptionKey) { sqlite3_reset(selectNodeStmt); sqlite3_clear_bindings(selectNodeStmt); @@ -1076,7 +1076,7 @@ namespace odhtdb return decryptNodeData(nodeHash, decryptionKey, &creatorPublicKey, DataView(adminGroup, GROUP_ID_LENGTH), timestamp); } - bool DatabaseStorage::decryptNodeData(const Hash &nodeHash, const shared_ptr decryptionKey, const Signature::PublicKey *creatorPublicKey, const DataView &adminGroupId, u64 timestamp) + bool DatabaseStorage::decryptNodeData(const Hash &nodeHash, const shared_ptr decryptionKey, const Signature::PublicKey *creatorPublicKey, const DataView &adminGroupId, u64 timestamp) { const DatabaseCreateNodeRequest createNodeRequest(&nodeHash, timestamp, creatorPublicKey, adminGroupId); if(database->onCreateNodeCallbackFunc) @@ -1129,7 +1129,7 @@ namespace odhtdb // TODO: There is no need to allocate/deallocate several times, this can be moved outside the while loop const void *encryptedDataRaw = sqlite3_column_blob(selectNodeAddDataAdditionalStmt, 0); int encryptedDataSize = sqlite3_column_bytes(selectNodeAddDataAdditionalStmt, 0); - OwnedMemory encryptedData(new u8[encryptedDataSize], encryptedDataSize); + OwnedByteArray encryptedData(new u8[encryptedDataSize], encryptedDataSize); memcpy(encryptedData.data, encryptedDataRaw, encryptedDataSize); bool appendObjectResult = decryptNodeAddData(rowId, nodeHash, requestHash, timestamp, &creatorPublicKey, DataView(encryptedData.data, encryptedData.size), decryptionKey); @@ -1212,7 +1212,7 @@ namespace odhtdb sqlite_step_throw_on_failure(sqliteDb, setNodeAddDataAdditionalDataStmt, "set NodeAddData decrypted"); } - bool DatabaseStorage::decryptNodeAddData(i64 rowId, const Hash &nodeHash, const Hash &dataHash, u64 timestamp, const Signature::PublicKey *creatorPublicKey, const DataView &encryptedData, const shared_ptr decryptionKey) + bool DatabaseStorage::decryptNodeAddData(i64 rowId, const Hash &nodeHash, const Hash &dataHash, u64 timestamp, const Signature::PublicKey *creatorPublicKey, const DataView &encryptedData, const shared_ptr decryptionKey) { if(!isUserAllowedToAddDataInNode(nodeHash, *creatorPublicKey)) { @@ -1240,7 +1240,7 @@ namespace odhtdb return true; } - bool DatabaseStorage::decryptNodeAddUser(i64 rowId, const Hash &nodeHash, const Hash &dataHash, u64 timestamp, const Signature::PublicKey *creatorPublicKey, const Signature::PublicKey *userToAddPublicKey, const DataView &groupToAddUserTo, const shared_ptr decryptionKey) + bool DatabaseStorage::decryptNodeAddUser(i64 rowId, const Hash &nodeHash, const Hash &dataHash, u64 timestamp, const Signature::PublicKey *creatorPublicKey, const Signature::PublicKey *userToAddPublicKey, const DataView &groupToAddUserTo, const shared_ptr decryptionKey) { if(!isUserAllowedToAddUserToGroupInNode(nodeHash, *creatorPublicKey, groupToAddUserTo)) { diff --git a/src/FileUtils.cpp b/src/FileUtils.cpp index c4fb318..28bce29 100644 --- a/src/FileUtils.cpp +++ b/src/FileUtils.cpp @@ -5,7 +5,7 @@ using namespace std; namespace odhtdb { - OwnedMemory fileGetContent(const boost::filesystem::path &filepath) + OwnedByteArray fileGetContent(const boost::filesystem::path &filepath) { #if OS_FAMILY == OS_FAMILY_POSIX FILE *file = fopen(filepath.string().c_str(), "rb"); @@ -27,7 +27,7 @@ namespace odhtdb size_t fileSize = ftell(file); fseek(file, 0, SEEK_SET); - char *result = new char[fileSize]; + u8 *result = new u8[fileSize]; fread(result, 1, fileSize, file); fclose(file); return { result, fileSize }; diff --git a/src/PasswordHash.cpp b/src/PasswordHash.cpp index 329733b..f877d20 100644 --- a/src/PasswordHash.cpp +++ b/src/PasswordHash.cpp @@ -3,9 +3,9 @@ namespace odhtdb { - OwnedMemory hashPassword(const DataView &plainPassword, const DataView &salt) + OwnedByteArray hashPassword(const DataView &plainPassword, const DataView &salt) { - OwnedMemory result; + OwnedByteArray result; const uint32_t tCost = 2; const uint32_t mCost = 1 << 16; -- cgit v1.2.3