Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve fixme-s in code #303

Merged
merged 2 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/controller/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ add_library(controller STATIC
threads/controllerchildthread.hpp
threads/waitforcardthread.hpp
ui.hpp
utils/erasedata.hpp
utils/observer_ptr.hpp
utils/qdisablecopymove.hpp
utils/utils.hpp
Expand Down
13 changes: 7 additions & 6 deletions src/controller/command-handlers/authenticate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include <QJsonDocument>
#include <QCryptographicHash>
#include <QDir>
#include <QScopeGuard>

#include <map>

Expand Down Expand Up @@ -122,17 +123,17 @@ QVariantMap Authenticate::onConfirm(WebEidUI* window,
const auto signatureAlgorithm =
QString::fromStdString(cardCertAndPin.cardInfo->eid().authSignatureAlgorithm());

auto pin = getPin(cardCertAndPin.cardInfo->eid(), window);
pcsc_cpp::byte_vector pin;
getPin(pin, cardCertAndPin.cardInfo->eid(), window);
auto pin_cleanup = qScopeGuard([&pin] {
// Erase PIN memory.
std::fill(pin.begin(), pin.end(), '\0');
});

try {
const auto signature =
createSignature(origin.url(), challengeNonce, cardCertAndPin.cardInfo->eid(), pin);

// Erase the PIN memory.
// TODO: Use a scope guard. Verify that the buffers are actually zeroed and no copies
// remain.
std::fill(pin.begin(), pin.end(), '\0');

return createAuthenticationToken(signatureAlgorithm, cardCertAndPin.certificateBytesInDer,
signature);

Expand Down
14 changes: 8 additions & 6 deletions src/controller/command-handlers/sign.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
#include "signauthutils.hpp"
#include "utils/utils.hpp"

#include <QScopeGuard>

using namespace electronic_id;

namespace
Expand Down Expand Up @@ -95,16 +97,16 @@ void Sign::emitCertificatesReady(const std::vector<CardCertificateAndPinInfo>& c

QVariantMap Sign::onConfirm(WebEidUI* window, const CardCertificateAndPinInfo& cardCertAndPin)
{
auto pin = getPin(cardCertAndPin.cardInfo->eid(), window);
pcsc_cpp::byte_vector pin;
getPin(pin, cardCertAndPin.cardInfo->eid(), window);
auto pin_cleanup = qScopeGuard([&pin] {
// Erase PIN memory.
std::fill(pin.begin(), pin.end(), '\0');
});

try {
const auto signature = signHash(cardCertAndPin.cardInfo->eid(), pin, docHash, hashAlgo);

// Erase PIN memory.
// TODO: Use a scope guard. Verify that the buffers are actually zeroed
// and no copies remain.
std::fill(pin.begin(), pin.end(), '\0');

return {{QStringLiteral("signature"), signature.first},
{QStringLiteral("signatureAlgorithm"), signature.second}};

Expand Down
38 changes: 13 additions & 25 deletions src/controller/command-handlers/signauthutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
* SOFTWARE.
*/

#include "utils/erasedata.hpp"
#include "signauthutils.hpp"

#include "ui.hpp"
#include "commandhandler.hpp"
#include "utils/utils.hpp"

using namespace electronic_id;

Expand Down Expand Up @@ -67,40 +67,28 @@ template QString validateAndGetArgument<QString>(const QString& argName, const Q
template QByteArray validateAndGetArgument<QByteArray>(const QString& argName,
const QVariantMap& args, bool allowNull);

template <typename T, typename C>
inline void eraseData(T& data)
void getPin(pcsc_cpp::byte_vector& pin, const ElectronicID& eid, WebEidUI* window)
{
// According to docs, constData() never causes a deep copy to occur, so we can abuse it
// to overwrite the underlying buffer since the underlying data is not really const.
C* chars = const_cast<C*>(data.constData());
for (int i = 0; i < data.length(); ++i) {
chars[i] = '\0';
}
}

pcsc_cpp::byte_vector getPin(const ElectronicID& card, WebEidUI* window)
{
// Doesn't apply to PIN pads.
if (card.smartcard().readerHasPinPad() || card.providesExternalPinDialog()) {
lauris71 marked this conversation as resolved.
Show resolved Hide resolved
return {};
// If the reader has a PIN pad or when enternal PIN dialog is used, do nothing.
if (eid.smartcard().readerHasPinPad() || eid.providesExternalPinDialog()) {
return;
}

REQUIRE_NON_NULL(window)

auto pin = window->getPin();
if (pin.isEmpty()) {
QString pinQStr = window->getPin();
if (pinQStr.isEmpty()) {
THROW(ProgrammingError, "Empty PIN");
}

// TODO: Avoid making copies of the PIN in memory.
auto pinQByteArray = pin.toUtf8();
pcsc_cpp::byte_vector pinBytes {pinQByteArray.begin(), pinQByteArray.end()};
uint len = pinQStr.length();
pin.resize(len);

// TODO: Verify that the buffers are actually zeroed and no copies remain.
eraseData<QString, QChar>(pin);
eraseData<QByteArray, char>(pinQByteArray);
for (uint i = 0; i < len; i++) {
pin[i] = pinQStr[i].unicode() & 0xff;
}

return pinBytes;
eraseData(pinQStr);
}

QVariantMap signatureAlgoToVariantMap(const SignatureAlgorithm signatureAlgo)
Expand Down
2 changes: 1 addition & 1 deletion src/controller/command-handlers/signauthutils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,6 @@ extern template QString validateAndGetArgument<QString>(const QString& argName,
extern template QByteArray
validateAndGetArgument<QByteArray>(const QString& argName, const QVariantMap& args, bool allowNull);

pcsc_cpp::byte_vector getPin(const electronic_id::ElectronicID& card, WebEidUI* window);
void getPin(pcsc_cpp::byte_vector& pin, const electronic_id::ElectronicID& eid, WebEidUI* window);
metsma marked this conversation as resolved.
Show resolved Hide resolved

QVariantMap signatureAlgoToVariantMap(const electronic_id::SignatureAlgorithm signatureAlgo);
9 changes: 9 additions & 0 deletions src/controller/controller.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,15 @@ void Controller::run()

startCommandExecution();

} catch (const std::invalid_argument& exc) {
if (isInStdinMode) {
lauris71 marked this conversation as resolved.
Show resolved Hide resolved
// Pass invalid argument message to the caller just in case it may be interested
// The result will be {"invalid-argument" : message}
// Command parameter is only used if exception will be raised during json creation
writeResponseToStdOut(isInStdinMode, {{QStringLiteral("invalid-argument"), exc.what()}},
"invalid-argument");
}
onCriticalFailure(exc.what());
} catch (const std::exception& error) {
onCriticalFailure(error.what());
}
Expand Down
3 changes: 0 additions & 3 deletions src/controller/inputoutputmode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ CommandWithArgumentsPtr readCommandFromStdin()
const auto messageLength = readMessageLength(std::cin);

if (messageLength < 5) {
// FIXME: Pass errors back up to caller in stdin mode.
throw std::invalid_argument("readCommandFromStdin: Message length is "
+ std::to_string(messageLength) + ", at least 5 required");
}
Expand All @@ -88,7 +87,6 @@ CommandWithArgumentsPtr readCommandFromStdin()
const auto json = QJsonDocument::fromJson(message);

if (!json.isObject()) {
// FIXME: Pass errors back up to caller in stdin mode.
throw std::invalid_argument("readCommandFromStdin: Invalid JSON, not an object");
}

Expand All @@ -97,7 +95,6 @@ CommandWithArgumentsPtr readCommandFromStdin()
const auto arguments = jsonObject["arguments"];

if (!command.isString() || !arguments.isObject()) {
// FIXME: Pass errors back up to caller in stdin mode.
throw std::invalid_argument("readCommandFromStdin: Invalid JSON, the main object does not "
"contain a 'command' string and 'arguments' object");
}
Expand Down
35 changes: 35 additions & 0 deletions src/controller/utils/erasedata.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright (c) 2020-2024 Estonian Information System Authority
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

#pragma once

#include <QString>

inline void eraseData(QString& data)
{
// According to docs, constData() never causes a deep copy to occur, so we can abuse it
// to overwrite the underlying buffer since the underlying data is not really const.
QChar* chars = const_cast<QChar*>(data.constData());
for (int i = 0; i < data.length(); ++i) {
chars[i] = '\0';
}
}
2 changes: 1 addition & 1 deletion src/mac/js
Submodule js updated 1 files
+3 −3 package-lock.json
32 changes: 28 additions & 4 deletions src/ui/webeiddialog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
* SOFTWARE.
*/

#include "utils/erasedata.hpp"

metsma marked this conversation as resolved.
Show resolved Hide resolved
#include "webeiddialog.hpp"
#include "application.hpp"
#include "punycode.hpp"
Expand Down Expand Up @@ -137,7 +139,8 @@ WebEidDialog::WebEidDialog(QWidget* parent) : WebEidUI(parent), ui(new Private)
++i;
}
menu->show();
menu->move(ui->langButton->geometry().bottomRight() - menu->geometry().topRight() + QPoint(0, 2));
menu->move(ui->langButton->geometry().bottomRight() - menu->geometry().topRight()
+ QPoint(0, 2));
connect(langGroup, qOverload<QAbstractButton*>(&QButtonGroup::buttonClicked), menu,
[this, menu](QAbstractButton* action) {
QSettings().setValue(QStringLiteral("lang"), action->property("lang"));
Expand Down Expand Up @@ -287,7 +290,11 @@ QString WebEidDialog::getPin()
{
// getPin() is called from background threads and must be thread-safe.
// QString uses QAtomicPointer internally and is thread-safe.
return pin;
// There should be only single reference and this is transferred to the caller for safety
QString ret = pin;
eraseData(pin);
pin.clear();
return ret;
metsma marked this conversation as resolved.
Show resolved Hide resolved
}

void WebEidDialog::onSmartCardStatusUpdate(const RetriableError status)
Expand Down Expand Up @@ -335,7 +342,8 @@ void WebEidDialog::onMultipleCertificatesReady(
ui->selectAnotherCertificate->setVisible(certificateAndPinInfos.size() > 1);
connect(ui->selectAnotherCertificate, &QPushButton::clicked, this,
[this, origin, certificateAndPinInfos] {
ui->pinInput->clear();
// We set pinInput to empty text instead of clear() to also reset undo buffer
ui->pinInput->setText({});
onMultipleCertificatesReady(origin, certificateAndPinInfos);
});
setupOK([this, origin] {
Expand Down Expand Up @@ -446,7 +454,6 @@ void WebEidDialog::onVerifyPinFailed(const VerifyPinFailed::Status status, const

std::function<QString()> message;

// FIXME: don't allow retry in case of UNKNOWN_ERROR
switch (status) {
case Status::RETRY_ALLOWED:
message = [retriesLeft]() -> QString {
Expand All @@ -469,8 +476,11 @@ void WebEidDialog::onVerifyPinFailed(const VerifyPinFailed::Status status, const
message = [] { return tr("PIN entry cancelled."); };
break;
case Status::PIN_ENTRY_DISABLED:
message = [] { return tr("PIN entry disabled"); };
break;
case Status::UNKNOWN_ERROR:
message = [] { return tr("Technical error"); };
displayFatalError(message);
break;
}

Expand Down Expand Up @@ -684,6 +694,20 @@ void WebEidDialog::displayPinBlockedError()
ui->helpButton->show();
}

void WebEidDialog::displayFatalError(std::function<QString()> message)
lauris71 marked this conversation as resolved.
Show resolved Hide resolved
{
ui->pinTitleLabel->hide();
ui->pinInput->hide();
ui->pinTimeoutTimer->stop();
ui->pinTimeRemaining->hide();
ui->pinEntryTimeoutProgressBar->hide();
setTrText(ui->pinErrorLabel, message);
ui->pinErrorLabel->show();
ui->okButton->hide();
ui->cancelButton->setEnabled(true);
ui->cancelButton->show();
}

void WebEidDialog::showPinInputWarning(bool show)
{
style()->unpolish(ui->pinInput);
Expand Down
1 change: 1 addition & 0 deletions src/ui/webeiddialog.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ class WebEidDialog final : public WebEidUI
template <typename Func>
void setupOK(Func func, const char* text = {}, bool enabled = false);
void displayPinBlockedError();
void displayFatalError(std::function<QString()> message);

void showPinInputWarning(bool show);
void resizeHeight();
Expand Down
Loading