Fix out-of-bounds writing to browser messages

This commit is contained in:
varjolintu authored and Janek Bevendorff committed 2026-09-22 21:46:36 +02:00
1 parent dfdd561fc5
commit 80e68bb4e8
8 files changed
+591 -74

No files matched your search

+115 -14
View File
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2020 KeePassXC Team <[email protected]>
* Copyright (C) 2026 KeePassXC Team <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -69,31 +69,29 @@ void BrowserHost::proxyConnected()
void BrowserHost::readProxyMessage()
{
QLocalSocket* socket = qobject_cast<QLocalSocket*>(QObject::sender());
auto* socket = qobject_cast<QLocalSocket*>(QObject::sender());
if (!socket || socket->bytesAvailable() <= 0) {
return;
}
socket->setReadBufferSize(BrowserShared::NATIVEMSG_MAX_LENGTH);
socket->setReadBufferSize(BrowserShared::SOCKET_BUFFER_SIZE);
int socketDesc = socket->socketDescriptor();
if (socketDesc) {
int max = BrowserShared::NATIVEMSG_MAX_LENGTH;
int max = BrowserShared::SOCKET_BUFFER_SIZE;
setsockopt(socketDesc, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<char*>(&max), sizeof(max));
}
QJsonParseError error;
auto json = QJsonDocument::fromJson(socket->readAll(), &error);
if (json.isNull()) {
qWarning() << "Failed to read proxy message: " << error.errorString();
return;
const auto messages = parseSocketData(socket->readAll(), socketDesc);
for (const auto& message : messages) {
if (!message.isEmpty()) {
emit clientMessageReceived(socket, message);
}
}
emit clientMessageReceived(socket, json.object());
}
void BrowserHost::broadcastClientMessage(const QJsonObject& json)
{
QString reply(QJsonDocument(json).toJson(QJsonDocument::Compact));
const auto reply(QJsonDocument(json).toJson(QJsonDocument::Compact));
for (const auto socket : m_socketList) {
sendClientData(socket, reply);
}
@@ -101,19 +99,122 @@ void BrowserHost::broadcastClientMessage(const QJsonObject& json)
void BrowserHost::sendClientMessage(QLocalSocket* socket, const QJsonObject& json)
{
QString reply(QJsonDocument(json).toJson(QJsonDocument::Compact));
const auto reply(QJsonDocument(json).toJson(QJsonDocument::Compact));
sendClientData(socket, reply);
}
void BrowserHost::sendClientData(QLocalSocket* socket, const QString& data)
{
if (socket && socket->isValid() && socket->state() == QLocalSocket::ConnectedState) {
QByteArray arr = data.toUtf8();
const auto arr = data.toUtf8();
socket->write(arr.constData(), arr.length());
socket->flush();
}
}
// Parses coalesced messages
QList<QJsonObject>
BrowserHost::parseSocketData(const QByteArray& socketData, const int socketDesc, const qsizetype maxLength)
{
QList<QJsonObject> messages;
// Split, and put } back to the messages
auto splittedSocketData = socketData.split('}');
for (auto i = 0; i < splittedSocketData.size() - 1; ++i) {
splittedSocketData[i].append('}');
}
for (const auto& data : splittedSocketData) {
if (data.length() > 0) {
const auto parsedMessage = parseMessage(data, socketDesc, maxLength);
if (!parsedMessage.isEmpty()) {
messages << parsedMessage;
}
}
}
return messages;
}
// Parses fragmented messages, or messages with garbage data
// The JSON data recevied is always just one object with keys & values. No nested objects, arrays etc. are present.
// Coalesced messages rely entirely on that message format.
QJsonObject BrowserHost::parseMessage(const QByteArray& socketData, const int socketDesc, const qsizetype maxLength)
{
if (socketData.isEmpty()) {
return {};
}
// Ignore any garbage at the beginning and try to find the position where JSON data starts
auto startPos = socketData.indexOf('{');
if (startPos < 0) {
// Allow -1 because message can be fragmented. Set startPos back to 0.
startPos = 0;
}
const auto message = socketData.mid(startPos);
QJsonParseError error;
auto json = QJsonDocument::fromJson(message, &error);
if (json.isNull()) {
qWarning() << "Failed to read proxy message: " << error.error << error.errorString();
// First fragmented message is of these errors. Partial message must be stored to a temporary buffer.
if (error.error == QJsonParseError::UnterminatedObject || error.error == QJsonParseError::UnterminatedArray
|| error.error == QJsonParseError::UnterminatedString) {
m_messageBuffer.insert(socketDesc, message);
return {};
}
// Nth fragmented message can be an illegal value or illegal number
if (error.error == QJsonParseError::IllegalValue || error.error == QJsonParseError::IllegalNumber) {
return parseFragmentedMessage(message, socketDesc, maxLength);
}
// This error can happen with two different scenarios:
// 1. Identifies a non-fragmented message with garbage at the end.
// 2. Identifies a fragmented message and passes it forward.
if (error.error == QJsonParseError::GarbageAtEnd && error.offset > 0) {
// Parse message before the error offset and parse the JSON again
const auto parsedMessage = message.left(error.offset);
if (parsedMessage.startsWith('{')) {
json = QJsonDocument::fromJson(parsedMessage, &error);
if (!json.isNull() && error.error == QJsonParseError::NoError) {
m_messageBuffer.remove(socketDesc);
return json.object();
}
} else {
return parseFragmentedMessage(message, socketDesc, maxLength);
}
}
} else {
m_messageBuffer.remove(socketDesc);
return json.object();
}
return {};
}
// Returns the previous message(s) from the buffer, combines them with the current one, and parses again
QJsonObject
BrowserHost::parseFragmentedMessage(const QByteArray& message, const int socketDesc, const qsizetype maxLength)
{
auto currentBuffer = m_messageBuffer.value(socketDesc);
if (currentBuffer.length() == 0) {
qWarning() << "Previous buffer not found.";
m_messageBuffer.remove(socketDesc);
return {};
}
if (currentBuffer.length() + message.length() > maxLength) {
qWarning() << "Combined fragmented messages exceeded the maximum allowed length.";
m_messageBuffer.remove(socketDesc);
return {};
}
currentBuffer.append(message);
return parseMessage(currentBuffer, socketDesc, maxLength);
}
void BrowserHost::proxyDisconnected()
{
auto socket = qobject_cast<QLocalSocket*>(QObject::sender());
+19 -4
View File
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2020 KeePassXC Team <[email protected]>
* Copyright (C) 2026 KeePassXC Team <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -15,10 +15,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KEEPASSXC_NATIVEMESSAGINGHOST_H
#define KEEPASSXC_NATIVEMESSAGINGHOST_H
#ifndef KEEPASSXC_BROWSERHOST_H
#define KEEPASSXC_BROWSERHOST_H
#include "BrowserShared.h"
#include <QJsonObject>
#include <QMap>
#include <QObject>
#include <QPointer>
@@ -50,10 +53,22 @@ private slots:
private:
void sendClientData(QLocalSocket* socket, const QString& data);
QList<QJsonObject> parseSocketData(const QByteArray& socketData,
const int socketDesc,
const qsizetype maxLength = BrowserShared::SOCKET_BUFFER_SIZE);
QJsonObject parseMessage(const QByteArray& socketData,
const int socketDesc,
const qsizetype maxLength = BrowserShared::SOCKET_BUFFER_SIZE);
QJsonObject parseFragmentedMessage(const QByteArray& message,
const int socketDesc,
const qsizetype maxLength = BrowserShared::SOCKET_BUFFER_SIZE);
private:
QPointer<QLocalServer> m_localServer;
QList<QLocalSocket*> m_socketList;
QMap<int, QByteArray> m_messageBuffer;
friend class TestBrowser;
};
#endif // KEEPASSXC_NATIVEMESSAGINGHOST_H
#endif // KEEPASSXC_BROWSERHOST_H
+115 -45
View File
@@ -28,10 +28,6 @@
#include <QDebug>
#endif
#include <botan/sodium.h>
using namespace Botan::Sodium;
Q_GLOBAL_STATIC(BrowserMessageBuilder, s_browserMessageBuilder);
BrowserMessageBuilder* BrowserMessageBuilder::instance()
@@ -166,15 +162,17 @@ QString BrowserMessageBuilder::getErrorMessage(const int errorCode) const
QString BrowserMessageBuilder::encryptMessage(const QJsonObject& message,
const QString& nonce,
const QString& publicKey,
const QString& secretKey)
const QString& secretKey,
const qsizetype maxLength,
const qsizetype macBytes)
{
if (message.isEmpty() || nonce.isEmpty()) {
return {};
}
const QString reply(QJsonDocument(message).toJson());
const auto reply(QJsonDocument(message).toJson());
if (!reply.isEmpty()) {
return encrypt(reply, nonce, publicKey, secretKey);
return encrypt(reply, nonce, publicKey, secretKey, maxLength, macBytes);
}
return {};
@@ -183,13 +181,15 @@ QString BrowserMessageBuilder::encryptMessage(const QJsonObject& message,
QJsonObject BrowserMessageBuilder::decryptMessage(const QString& message,
const QString& nonce,
const QString& publicKey,
const QString& secretKey)
const QString& secretKey,
const qsizetype maxLength,
const qsizetype macBytes)
{
if (message.isEmpty() || nonce.isEmpty()) {
return {};
}
QByteArray ba = decrypt(message, nonce, publicKey, secretKey);
const auto ba = decrypt(message, nonce, publicKey, secretKey, maxLength, macBytes);
if (ba.isEmpty()) {
return {};
}
@@ -200,28 +200,59 @@ QJsonObject BrowserMessageBuilder::decryptMessage(const QString& message,
QString BrowserMessageBuilder::encrypt(const QString& plaintext,
const QString& nonce,
const QString& publicKey,
const QString& secretKey)
const QString& secretKey,
const qsizetype maxLength,
const qsizetype macBytes)
{
const QByteArray ma = plaintext.toUtf8();
const QByteArray na = base64Decode(nonce);
const QByteArray ca = base64Decode(publicKey);
const QByteArray sa = base64Decode(secretKey);
std::vector<unsigned char> m(ma.cbegin(), ma.cend());
std::vector<unsigned char> n(na.cbegin(), na.cend());
std::vector<unsigned char> ck(ca.cbegin(), ca.cend());
std::vector<unsigned char> sk(sa.cbegin(), sa.cend());
std::vector<unsigned char> e;
e.resize(BrowserShared::NATIVEMSG_MAX_LENGTH);
if (m.empty() || n.empty() || ck.empty() || sk.empty()) {
const QByteArray messageBytes = plaintext.toUtf8();
if (messageBytes.length() > maxLength) {
qWarning() << "Message length" << messageBytes.length() << "exceeds the maximum size.";
return {};
}
if (crypto_box_easy(e.data(), m.data(), m.size(), n.data(), ck.data(), sk.data()) == 0) {
QByteArray res = getQByteArray(e.data(), (crypto_box_MACBYTES + ma.length()));
return res.toBase64();
const QByteArray nonceBytes = base64Decode(nonce);
if (nonceBytes.length() != crypto_box_NONCEBYTES) {
qWarning() << "Nonce length" << nonceBytes.length() << "is invalid.";
return {};
}
const QByteArray publicKeyBytes = base64Decode(publicKey);
if (publicKeyBytes.length() != crypto_box_PUBLICKEYBYTES) {
qWarning() << "Public key length" << publicKeyBytes.length() << "is invalid.";
return {};
}
const QByteArray secretKeyBytes = base64Decode(secretKey);
if (secretKeyBytes.length() != crypto_box_SECRETKEYBYTES) {
qWarning() << "Secret key length" << secretKeyBytes.length() << "is invalid.";
return {};
}
const std::vector<unsigned char> messageVec(messageBytes.cbegin(), messageBytes.cend());
const std::vector<unsigned char> nonceVec(nonceBytes.cbegin(), nonceBytes.cend());
const std::vector<unsigned char> publicKeyVec(publicKeyBytes.cbegin(), publicKeyBytes.cend());
const std::vector<unsigned char> secretKeyVec(secretKeyBytes.cbegin(), secretKeyBytes.cend());
if (messageVec.empty() || nonceVec.empty() || publicKeyVec.empty() || secretKeyVec.empty()) {
return {};
}
std::vector<unsigned char> encryptedData;
encryptedData.resize(maxLength + macBytes);
if (crypto_box_easy(encryptedData.data(),
messageVec.data(),
messageVec.size(),
nonceVec.data(),
publicKeyVec.data(),
secretKeyVec.data())
== 0) {
const auto res = getQByteArray(encryptedData.data(), (macBytes + messageBytes.length()));
const auto resBase64 = res.toBase64();
if (resBase64.length() > BrowserShared::SOCKET_BUFFER_SIZE) {
qWarning() << "Encoded message length" << resBase64.length() << "exceeds the maximum socket buffer size.";
return {};
}
return resBase64;
}
return {};
@@ -230,27 +261,60 @@ QString BrowserMessageBuilder::encrypt(const QString& plaintext,
QByteArray BrowserMessageBuilder::decrypt(const QString& encrypted,
const QString& nonce,
const QString& publicKey,
const QString& secretKey)
const QString& secretKey,
const qsizetype maxLength,
const qsizetype macBytes)
{
const QByteArray ma = base64Decode(encrypted);
const QByteArray na = base64Decode(nonce);
const QByteArray ca = base64Decode(publicKey);
const QByteArray sa = base64Decode(secretKey);
std::vector<unsigned char> m(ma.cbegin(), ma.cend());
std::vector<unsigned char> n(na.cbegin(), na.cend());
std::vector<unsigned char> ck(ca.cbegin(), ca.cend());
std::vector<unsigned char> sk(sa.cbegin(), sa.cend());
std::vector<unsigned char> d;
d.resize(BrowserShared::NATIVEMSG_MAX_LENGTH);
if (m.empty() || n.empty() || ck.empty() || sk.empty()) {
const QByteArray encryptedBytes = base64Decode(encrypted);
if (encryptedBytes.size() == 0 && encrypted.size() > 0) {
qWarning() << "Message is not a valid base64 encoded string.";
}
if (maxLength < 0 || encryptedBytes.size() < macBytes) {
qWarning() << "Message length" << encryptedBytes.length() << "is smaller than required.";
return {};
}
if (encryptedBytes.size() - macBytes > maxLength) {
qWarning() << "Message length" << encryptedBytes.length() << "exceeds the maximum size.";
return {};
}
if (crypto_box_open_easy(d.data(), m.data(), ma.length(), n.data(), ck.data(), sk.data()) == 0) {
return getQByteArray(d.data(), std::char_traits<char>::length(reinterpret_cast<const char*>(d.data())));
const QByteArray nonceBytes = base64Decode(nonce);
if (nonceBytes.length() != crypto_box_NONCEBYTES) {
qWarning() << "Nonce length" << nonceBytes.length() << "is invalid.";
return {};
}
const QByteArray publicKeyBytes = base64Decode(publicKey);
if (publicKeyBytes.length() != crypto_box_PUBLICKEYBYTES) {
qWarning() << "Public key length" << publicKeyBytes.length() << "is invalid.";
return {};
}
const QByteArray secretKeyBytes = base64Decode(secretKey);
if (secretKeyBytes.length() != crypto_box_SECRETKEYBYTES) {
qWarning() << "Secret key length" << secretKeyBytes.length() << "is invalid.";
return {};
}
const std::vector<unsigned char> encryptedVec(encryptedBytes.cbegin(), encryptedBytes.cend());
const std::vector<unsigned char> nonceVec(nonceBytes.cbegin(), nonceBytes.cend());
const std::vector<unsigned char> publicKeyVec(publicKeyBytes.cbegin(), publicKeyBytes.cend());
const std::vector<unsigned char> secretKeyVec(secretKeyBytes.cbegin(), secretKeyBytes.cend());
if (encryptedVec.empty() || nonceVec.empty() || publicKeyVec.empty() || secretKeyVec.empty()) {
return {};
}
std::vector<unsigned char> decryptedData;
decryptedData.resize(encryptedVec.size() - macBytes);
if (crypto_box_open_easy(decryptedData.data(),
encryptedVec.data(),
encryptedBytes.length(),
nonceVec.data(),
publicKeyVec.data(),
secretKeyVec.data())
== 0) {
return getQByteArray(decryptedData.data(), decryptedData.size());
}
return {};
@@ -299,12 +363,18 @@ QJsonObject BrowserMessageBuilder::getJsonObject(const QByteArray& ba) const
QByteArray BrowserMessageBuilder::base64Decode(const QString& str)
{
return QByteArray::fromBase64(str.toUtf8());
// Returns an empty QByteArray if the string is not valid base64
return QByteArray::fromBase64(str.toUtf8(), QByteArray::AbortOnBase64DecodingErrors);
}
QString BrowserMessageBuilder::incrementNonce(const QString& nonce)
{
const QByteArray nonceArray = base64Decode(nonce);
if (nonceArray.length() != crypto_box_NONCEBYTES) {
qWarning() << "Nonce length" << nonceArray.length() << "is invalid.";
return {};
}
std::vector<unsigned char> n(nonceArray.cbegin(), nonceArray.cend());
sodium_increment(n.data(), n.size());
+29 -6
View File
@@ -18,10 +18,18 @@
#ifndef KEEPASSXC_BROWSERMESSAGEBUILDER_H
#define KEEPASSXC_BROWSERMESSAGEBUILDER_H
#include "BrowserShared.h"
#include <QPair>
#include <QString>
#include <QVariant>
#include <botan/sodium.h>
using namespace Botan::Sodium;
constexpr auto MacBytes = static_cast<qsizetype>(crypto_box_MACBYTES);
class QJsonObject;
typedef QMap<QString, QVariant> Parameters;
@@ -86,12 +94,27 @@ public:
QString encryptMessage(const QJsonObject& message,
const QString& nonce,
const QString& publicKey,
const QString& secretKey);
QJsonObject
decryptMessage(const QString& message, const QString& nonce, const QString& publicKey, const QString& secretKey);
QString encrypt(const QString& plaintext, const QString& nonce, const QString& publicKey, const QString& secretKey);
QByteArray
decrypt(const QString& encrypted, const QString& nonce, const QString& publicKey, const QString& secretKey);
const QString& secretKey,
const qsizetype maxLength = BrowserShared::NATIVEMSG_MAX_LENGTH,
const qsizetype macBytes = MacBytes);
QJsonObject decryptMessage(const QString& message,
const QString& nonce,
const QString& publicKey,
const QString& secretKey,
const qsizetype maxLength = BrowserShared::NATIVEMSG_MAX_LENGTH,
const qsizetype macBytes = MacBytes);
QString encrypt(const QString& plaintext,
const QString& nonce,
const QString& publicKey,
const QString& secretKey,
const qsizetype maxLength = BrowserShared::NATIVEMSG_MAX_LENGTH,
const qsizetype macBytes = MacBytes);
QByteArray decrypt(const QString& encrypted,
const QString& nonce,
const QString& publicKey,
const QString& secretKey,
const qsizetype maxLength = BrowserShared::NATIVEMSG_MAX_LENGTH,
const qsizetype macBytes = MacBytes);
QString getBase64FromKey(const uchar* array, const uint len);
QByteArray getQByteArray(const uchar* array, const uint len) const;
+2 -1
View File
@@ -22,7 +22,8 @@
namespace BrowserShared
{
constexpr int NATIVEMSG_MAX_LENGTH = 1024 * 1024;
constexpr int SOCKET_BUFFER_SIZE = 1024 * 1024;
constexpr int NATIVEMSG_MAX_LENGTH = SOCKET_BUFFER_SIZE / 1.6; // 655 360
enum SupportedBrowsers : int
{