From f28275617f206cde53a7ada04cad3abbd6d38fc7 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Tue, 21 Feb 2023 09:21:29 +0100 Subject: [PATCH] QMessageAuthenticationCode: fix result() non-re-entrancy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While QMessageAuthenticationCode is not copyable, result() is nevertheless const, so a user could prepare a QMessageAuthenticationCode object with setKey() and addData(), pass it by const reference to two threads, which each just call result() on it. This should be safe, but because result() performed lazy evaluation without being internally synchronized, this would cause data races. Fix in the same was as b904de43a5acfc4067fc9e4146babd45c6ac1138 did for QCryptographicHash. See there for a detailed discussion of the solution. Fixes: QTBUG-111347 Change-Id: I1feb380973c480ad6268349a0a46ac471b9ca0f7 Reviewed-by: Fabian Kosmale Reviewed-by: MÃ¥rten Nordheim Reviewed-by: David Faure (cherry picked from commit 2449af142fa3d8ccb114262e994f308043ef6d70) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/tools/qmessageauthenticationcode.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/corelib/tools/qmessageauthenticationcode.cpp b/src/corelib/tools/qmessageauthenticationcode.cpp index 8f131e45a07..5853e9951ec 100644 --- a/src/corelib/tools/qmessageauthenticationcode.cpp +++ b/src/corelib/tools/qmessageauthenticationcode.cpp @@ -1,8 +1,11 @@ +// Copyright (C) 2023 The Qt Company Ltd. // Copyright (C) 2013 Ruslan Nigmatullin // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qmessageauthenticationcode.h" #include "qvarlengtharray.h" +#include "qmutex.h" +#include "private/qlocking_p.h" #include "qtcore-config_p.h" @@ -70,6 +73,7 @@ public: QByteArray key; QByteArray result; + QBasicMutex finalizeMutex; QCryptographicHash messageHash; QCryptographicHash::Algorithm method; bool messageHashInited; @@ -77,7 +81,10 @@ public: void initMessageHash(); void finalize(); + // when not called from the static hash() function, this function needs to be + // called with finalizeMutex held: void finalizeUnchecked(); + // END functions that need to be called with finalizeMutex held }; void QMessageAuthenticationCodePrivate::initMessageHash() @@ -217,6 +224,7 @@ QByteArray QMessageAuthenticationCode::result() const void QMessageAuthenticationCodePrivate::finalize() { + const auto lock = qt_scoped_lock(finalizeMutex); if (!result.isEmpty()) return; initMessageHash();