What changed, and why it matters
This commit rewrites the OpenPGP signature verification code used by the Monero GUI's automatic updater. The changes add stricter parsing of PGP armor, enforce that subkeys used for verification are actually allowed to sign data, reject unexpected signature types, and fix several fragile coding patterns. Because this code protects the update-download path, any weakness here could let an attacker trick the wallet into installing a malicious update. The patch appears to be a hardening/correctness fix rather than a simple refactor, but the commit message does not call it a security fix and no advisory is supplied.
Treat this commit as a security-hardening fix for the software-update trust mechanism. Reviewers should verify that decode_armored_contents correctly handles all RFC 4880 length/checksum edge cases, that subkey binding signature verification is completed (the TODO remains), and that the new EMSA-PKCS1-v1.5 construction matches RFC 3447 exactly. Users should upgrade to a build containing this commit and verify that release binaries are signed with the expected release keys.
Security signals we found
OpenPGP signature verification in update path
Added subkey binding signature key-flags check (Sign Data)
Added armor tail validation and CRC24 checksum verification
Restricted accepted signature types to binary/text document
Explicit EMSA-PKCS1-v1.5 encoding before RSA verify
Added libgcrypt initialization wrapper
Hardened shasum output parsing against malformed lines
TODO comment updated from 'Subkey binding checks' to 'Subkey binding signature verification'
Evidence from the diff
The diff substantially modifies src/openpgp/openpgp.cpp/h and related headers. Key behavioral changes: (1) adds openpgp::initialize() and calls it at startup; (2) replaces a naive base64 stripper with decode_armored_contents() that validates base64 alphabet, enforces an armor tail line, and verifies the RFC 4880 CRC24 checksum; (3) parses cleartext-signed messages per RFC 4880 section 7.1 (dash-escaping and trailing-whitespace handling); (4) only loads public subkeys when a binding signature with the Sign Data key flag is present; (5) rejects signature types other than binary_document and canonical_text_document; (6) restructures signature_rsa::verify() to compute EMSA-PKCS1-v1.5 encoding explicitly and compare hash leftmost bytes before calling gcry_pk_verify(); (7) fixes deserializer packet-tag parsing to support new-format packets and subpacket lengths; (8) hardens updater hash parsing with QRegularExpression and hex validation. Several of these changes close plausible verification bypasses, but the commit message only says ‘fix some fragile code’.
Changed components
src/openpgp/openpgp.cppsrc/openpgp/openpgp.hsrc/openpgp/serialization.hsrc/openpgp/packet_stream.hsrc/openpgp/hash.hsrc/openpgp/mpi.hsrc/openpgp/s_expression.hsrc/qt/updater.cppsrc/qt/updater.hsrc/main/main.cppInspect captured patch +461 / −191
### src/main/main.cpp
@@ -66,6 +66,7 @@
#include "qt/ipc.h"
#include "qt/network.h"
#include "qt/updater.h"
+#include "openpgp/openpgp.h"
#include "qt/utils.h"
#include "qt/TailsOS.h"
#include "qt/KeysFiles.h"
@@ -256,6 +257,11 @@ Verify update binary using 'shasum'-compatible (SHA256 algo) output signed by tw
Logger logger(app, parser.value(logPathOption));
+ if (!openpgp::initialize())
+ {
+ qCritical() << "Failed to initialize libgcrypt";
+ }
+
// loglevel is configured in main.qml. Anything lower than
// qWarning is not shown here unless MONERO_LOG_LEVEL env var is set
bool logLevelOk;
### src/openpgp/hash.h
@@ -28,6 +28,8 @@
#pragma once
+#include <cstdint>
+#include <cstring>
#include <stdexcept>
#include <vector>
@@ -48,9 +50,8 @@ class hash
hash(const hash &) = delete;
hash &operator=(const hash &) = delete;
- hash(uint8_t algorithm)
+ explicit hash(uint8_t algorithm)
: algo(algorithm)
- , consumed(0)
{
if (gcry_md_test_algo(algo) != GPG_ERR_NO_ERROR)
{
@@ -68,17 +69,9 @@ class hash
gcry_md_close(md);
}
- hash &operator<<(uint8_t byte)
- {
- gcry_md_putc(md, byte);
- ++consumed;
- return *this;
- }
-
hash &operator<<(const epee::span<const uint8_t> &bytes)
{
- gcry_md_write(md, &bytes[0], bytes.size());
- consumed += bytes.size();
+ gcry_md_write(md, bytes.data(), bytes.size());
return *this;
}
@@ -95,19 +88,13 @@ class hash
{
throw std::runtime_error("failed to read the digest");
}
- memcpy(&result[0], digest, result.size());
+ std::memcpy(result.data(), digest, result.size());
return result;
}
- size_t consumed_bytes() const
- {
- return consumed;
- }
-
private:
const uint8_t algo;
gcry_md_hd_t md;
- size_t consumed;
};
-}
+} // namespace openpgp
### src/openpgp/mpi.h
@@ -28,6 +28,10 @@
#pragma once
+#include <cstddef>
+#include <stdexcept>
+#include <type_traits>
+
#include <gcrypt.h>
namespace openpgp
@@ -39,7 +43,7 @@ class mpi
mpi(const mpi &) = delete;
mpi &operator=(const mpi &) = delete;
- mpi(mpi &&other)
+ mpi(mpi &&other) noexcept
: data(other.data)
{
other.data = nullptr;
@@ -48,12 +52,13 @@ class mpi
template <
typename byte_container,
typename = typename std::enable_if<(sizeof(typename byte_container::value_type) == 1)>::type>
- mpi(const byte_container &buffer, gcry_mpi_format format = GCRYMPI_FMT_USG)
- : mpi(&buffer[0], buffer.size(), format)
+ explicit mpi(const byte_container &buffer, gcry_mpi_format format = GCRYMPI_FMT_USG)
+ : mpi(buffer.data(), buffer.size(), format)
{
}
mpi(const void *buffer, size_t size, gcry_mpi_format format = GCRYMPI_FMT_USG)
+ : data(nullptr)
{
if (gcry_mpi_scan(&data, format, buffer, size, nullptr) != GPG_ERR_NO_ERROR)
{
### src/openpgp/openpgp.cpp
@@ -29,7 +29,10 @@
#include "openpgp.h"
#include <algorithm>
-#include <locale>
+#include <locale> // needed by string_coding.h
+#include <stdexcept>
+#include <string>
+#include <utility>
#include <vector>
#include <string_coding.h>
@@ -45,6 +48,10 @@ namespace openpgp
namespace
{
+constexpr const uint8_t signature_type_subkey_binding = 0x18;
+constexpr const uint8_t subpacket_type_key_flags = 27;
+constexpr const uint8_t key_flag_sign_data = 0x02;
+
std::string::const_iterator find_next_line(std::string::const_iterator begin, const std::string::const_iterator &end)
{
begin = std::find(begin, end, '\n');
@@ -76,10 +83,15 @@ std::string::const_iterator find_empty_line(std::string::const_iterator it, cons
return it;
}
-std::string get_armored_block_contents(const std::string &text, const std::string &block_name)
+bool is_trailing_whitespace(char character)
+{
+ return character == ' ' || character == '\t' || character == '\r';
+}
+
+std::string get_armored_block_contents(const std::string &text, const std::string &header, const std::string &tail)
{
static constexpr const char dashes[] = "-----";
- const std::string armor_header = dashes + block_name + dashes;
+ const std::string armor_header = dashes + header + dashes;
auto block_start = find_line_starting_with(text.begin(), text.end(), armor_header);
auto block_headers = find_next_line(block_start, text.end());
auto block_end = find_line_starting_with(block_headers, text.end(), dashes);
@@ -88,11 +100,234 @@ std::string get_armored_block_contents(const std::string &text, const std::strin
{
throw std::runtime_error("armored block not found");
}
+
+ const std::string armor_tail = dashes + tail + dashes;
+ if (static_cast<size_t>(std::distance(block_end, text.end())) < armor_tail.size() ||
+ !std::equal(armor_tail.begin(), armor_tail.end(), block_end))
+ {
+ throw std::runtime_error("armor tail line not found");
+ }
+
return std::string(contents_begin, block_end);
}
+bool is_base64(const std::string &base64)
+{
+ if (base64.size() % 4 != 0)
+ {
+ return false;
+ }
+
+ size_t padding = 0;
+ while (padding < 2 && padding < base64.size() && base64[base64.size() - 1 - padding] == '=')
+ {
+ ++padding;
+ }
+
+ return std::all_of(base64.begin(), base64.end() - padding, [](char character) {
+ return (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z') ||
+ (character >= '0' && character <= '9') || character == '+' || character == '/';
+ });
+}
+
+uint32_t crc24(const std::string &data)
+{
+ uint32_t crc = 0xb704ce;
+ for (const char character : data)
+ {
+ crc ^= static_cast<uint32_t>(static_cast<uint8_t>(character)) << 16;
+ for (size_t bit = 0; bit < 8; ++bit)
+ {
+ crc <<= 1;
+ if (crc & 0x1000000)
+ {
+ crc ^= 0x1864cfb;
+ }
+ }
+ }
+ return crc & 0xffffff;
+}
+
+std::string decode_armored_contents(const std::string &contents)
+{
+ std::string base64;
+ base64.reserve(contents.size());
+ std::string checksum;
+ bool checksum_found = false;
+ for (auto line_begin = contents.begin(); line_begin != contents.end();)
+ {
+ const auto next_line = find_next_line(line_begin, contents.end());
+ auto line_end = next_line;
+ while (line_end != line_begin && (*(line_end - 1) == '\n' || is_trailing_whitespace(*(line_end - 1))))
+ {
+ --line_end;
+ }
+
+ if (line_begin != line_end)
+ {
+ if (checksum_found)
+ {
+ throw std::runtime_error("unexpected data after armor checksum");
+ }
+
+ if (*line_begin == '=')
+ {
+ checksum.assign(line_begin + 1, line_end);
+ checksum_found = true;
+ }
+ else
+ {
+ base64.append(line_begin, line_end);
+ }
+ }
+
+ line_begin = next_line;
+ }
+
+ if (!is_base64(base64))
+ {
+ throw std::runtime_error("invalid armored data");
+ }
+ std::string decoded = epee::string_encoding::base64_decode(base64);
+
+ if (checksum_found)
+ {
+ if (checksum.size() != 4 || !is_base64(checksum))
+ {
+ throw std::runtime_error("invalid armor checksum");
+ }
+ const std::string checksum_decoded = epee::string_encoding::base64_decode(checksum);
+ if (checksum_decoded.size() != 3)
+ {
+ throw std::runtime_error("invalid armor checksum");
+ }
+ const uint32_t expected = (static_cast<uint32_t>(static_cast<uint8_t>(checksum_decoded[0])) << 16) |
+ (static_cast<uint32_t>(static_cast<uint8_t>(checksum_decoded[1])) << 8) |
+ static_cast<uint32_t>(static_cast<uint8_t>(checksum_decoded[2]));
+ if (crc24(decoded) != expected)
+ {
+ throw std::runtime_error("armor checksum mismatch");
+ }
+ }
+
+ return decoded;
+}
+
+// RFC 4880 section 7.1
+std::string get_cleartext_signed_text(const std::string &contents)
+{
+ std::string text;
+ text.reserve(contents.size());
+ for (auto line_begin = contents.begin(); line_begin != contents.end();)
+ {
+ const auto line_end = std::find(line_begin, contents.end(), '\n');
+
+ if (line_begin != contents.begin())
+ {
+ text.push_back('\n');
+ }
+
+ auto begin = line_begin;
+ if (std::distance(begin, line_end) >= 2 && *begin == '-' && *(begin + 1) == ' ')
+ {
+ begin += 2;
+ }
+ auto end = line_end;
+ while (end != begin && is_trailing_whitespace(*(end - 1)))
+ {
+ --end;
+ }
+ text.append(begin, end);
+
+ line_begin = line_end != contents.end() ? line_end + 1 : line_end;
+ }
+ return text;
+}
+
+bool is_rsa_public_key(const std::vector<uint8_t> &data)
+{
+ constexpr const size_t algorithm_offset = sizeof(uint8_t) + sizeof(uint32_t);
+ return data.size() > algorithm_offset && data[0] == 4 && data[algorithm_offset] == openpgp::algorithm::rsa;
+}
+
+public_key_rsa read_public_key(const std::vector<uint8_t> &data)
+{
+ deserializer<epee::span<const uint8_t>> serialized(epee::to_span(data));
+
+ const auto version = serialized.read_big_endian<uint8_t>();
+ if (version != 4)
+ {
+ throw std::runtime_error("unsupported public key version");
+ }
+
+ /* const auto timestamp = */ serialized.read_big_endian<uint32_t>();
+
+ const auto algorithm = serialized.read_big_endian<uint8_t>();
+ if (algorithm != openpgp::algorithm::rsa)
+ {
+ throw std::runtime_error("unsupported public key algorithm");
+ }
+
+ const mpi public_key_n = serialized.read_mpi();
+ const mpi public_key_e = serialized.read_mpi();
+
+ return public_key_rsa(
+ s_expression("(public-key (rsa (n %m) (e %m)))", public_key_n.get(), public_key_e.get()),
+ gcry_mpi_get_nbits(public_key_n.get()));
+}
+
+bool subkey_binding_allows_signing(const std::vector<uint8_t> &data)
+{
+ deserializer<epee::span<const uint8_t>> signature(epee::to_span(data));
+
+ if (signature.read_big_endian<uint8_t>() != 4 ||
+ signature.read_big_endian<uint8_t>() != signature_type_subkey_binding)
+ {
+ return false;
+ }
+
+ /* const auto algorithm = */ signature.read_big_endian<uint8_t>();
+ /* const auto hash_algorithm = */ signature.read_big_endian<uint8_t>();
+
+ const auto hashed_data_length = signature.read_big_endian<uint16_t>();
+ deserializer<epee::span<const uint8_t>> subpackets(signature.read_span(hashed_data_length));
+ while (!subpackets.empty())
+ {
+ const size_t length = subpackets.read_subpacket_length();
+ if (length == 0)
+ {
+ throw std::runtime_error("invalid signature subpacket length");
+ }
+
+ const uint8_t type = subpackets.read_big_endian<uint8_t>() & 0x7f;
+ const epee::span<const uint8_t> subpacket = subpackets.read_span(length - 1);
+ if (type == subpacket_type_key_flags)
+ {
+ return subpacket.size() > 0 && (subpacket[0] & key_flag_sign_data) != 0;
+ }
+ }
+
+ return false;
+}
+
} // namespace
+bool initialize()
+{
+ if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
+ {
+ return true;
+ }
+
+ if (gcry_check_version(GCRYPT_VERSION) == nullptr)
+ {
+ return false;
+ }
+ gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
+ gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
+ return true;
+}
+
public_key_rsa::public_key_rsa(s_expression expression, size_t bits)
: m_expression(std::move(expression))
, m_bits(bits)
@@ -110,15 +345,15 @@ size_t public_key_rsa::bits() const
}
public_key_block::public_key_block(const std::string &armored)
- : public_key_block(epee::to_byte_span(epee::to_span(epee::string_encoding::base64_decode(
- strip_line_breaks(get_armored_block_contents(armored, "BEGIN PGP PUBLIC KEY BLOCK"))))))
+ : public_key_block(epee::to_byte_span(epee::to_span(decode_armored_contents(
+ get_armored_block_contents(armored, "BEGIN PGP PUBLIC KEY BLOCK", "END PGP PUBLIC KEY BLOCK")))))
{
}
-// TODO: Public-Key expiration, User ID and Public-Key certification, Subkey binding checks
+// TODO: Public-Key expiration, User ID and Public-Key certification, Subkey binding signature verification
public_key_block::public_key_block(const epee::span<const uint8_t> buffer)
{
- packet_stream packets(buffer);
+ const packet_stream packets(buffer);
const std::vector<uint8_t> *data = packets.find_first(packet_tag::type::user_id);
if (data == nullptr)
@@ -127,41 +362,43 @@ public_key_block::public_key_block(const epee::span<const uint8_t> buffer)
}
m_user_id.assign(data->begin(), data->end());
- const auto append_public_key = [this](const std::vector<uint8_t> &data) {
- deserializer<std::vector<uint8_t>> serialized(data);
-
- const auto version = serialized.read_big_endian<uint8_t>();
- if (version != 4)
- {
- throw std::runtime_error("unsupported public key version");
- }
-
- /* const auto timestamp = */ serialized.read_big_endian<uint32_t>();
-
- const auto algorithm = serialized.read_big_endian<uint8_t>();
- if (algorithm != openpgp::algorithm::rsa)
- {
- throw std::runtime_error("unsupported public key algorithm");
- }
-
+ // Only use subkeys allowed to sign
+ bool primary_key_found = false;
+ const std::vector<uint8_t> *subkey = nullptr;
+ packets.for_each([this, &primary_key_found, &subkey](packet_tag::type type, const std::vector<uint8_t> &packet) {
+ switch (type)
{
- const mpi public_key_n = serialized.read_mpi();
- const mpi public_key_e = serialized.read_mpi();
-
- emplace_back(
- s_expression("(public-key (rsa (n %m) (e %m)))", public_key_n.get(), public_key_e.get()),
- gcry_mpi_get_nbits(public_key_n.get()));
+ case packet_tag::type::public_key:
+ if (primary_key_found)
+ {
+ throw std::runtime_error("multiple public keys");
+ }
+ push_back(read_public_key(packet));
+ primary_key_found = true;
+ subkey = nullptr;
+ break;
+ case packet_tag::type::public_subkey:
+ subkey = &packet;
+ break;
+ case packet_tag::type::signature:
+ if (subkey != nullptr)
+ {
+ if (is_rsa_public_key(*subkey) && subkey_binding_allows_signing(packet))
+ {
+ push_back(read_public_key(*subkey));
+ }
+ subkey = nullptr;
+ }
+ break;
+ default:
+ break;
}
- };
+ });
- data = packets.find_first(packet_tag::type::public_key);
- if (data == nullptr)
+ if (!primary_key_found)
{
throw std::runtime_error("public key is missing");
}
- append_public_key(*data);
-
- packets.for_each(packet_tag::type::public_subkey, append_public_key);
}
std::string public_key_block::user_id() const
@@ -175,40 +412,40 @@ signature_rsa::signature_rsa(
std::pair<uint8_t, uint8_t> hash_leftmost_bytes,
uint8_t hash_algorithm,
const std::vector<uint8_t> &hashed_data,
- type type,
+ type signature_type,
s_expression signature,
uint8_t version)
: m_hash_algorithm(hash_algorithm)
, m_hash_leftmost_bytes(hash_leftmost_bytes)
- , m_hashed_appendix(format_hashed_appendix(algorithm, hash_algorithm, hashed_data, type, version))
+ , m_hashed_appendix(format_hashed_appendix(algorithm, hash_algorithm, hashed_data, signature_type, version))
, m_signature(std::move(signature))
- , m_type(type)
+ , m_type(signature_type)
{
}
signature_rsa signature_rsa::from_armored(const std::string &armored_signed_message)
{
- return from_base64(get_armored_block_contents(armored_signed_message, "BEGIN PGP SIGNATURE"));
+ const std::string decoded = decode_armored_contents(
+ get_armored_block_contents(armored_signed_message, "BEGIN PGP SIGNATURE", "END PGP SIGNATURE"));
+ return from_buffer(epee::to_byte_span(epee::to_span(decoded)));
}
signature_rsa signature_rsa::from_base64(const std::string &base64)
{
- std::string decoded = epee::string_encoding::base64_decode(strip_line_breaks(base64));
- epee::span<const uint8_t> buffer(reinterpret_cast<const uint8_t *>(&decoded[0]), decoded.size());
- return from_buffer(buffer);
+ return from_buffer(epee::to_byte_span(epee::to_span(decode_armored_contents(base64))));
}
signature_rsa signature_rsa::from_buffer(const epee::span<const uint8_t> input)
{
- packet_stream packets(input);
+ const packet_stream packets(input);
const std::vector<uint8_t> *data = packets.find_first(packet_tag::type::signature);
if (data == nullptr)
{
throw std::runtime_error("signature is missing");
}
- deserializer<std::vector<uint8_t>> buffer(*data);
+ deserializer<epee::span<const uint8_t>> buffer(epee::to_span(*data));
const auto version = buffer.read_big_endian<uint8_t>();
if (version != 4)
@@ -217,6 +454,10 @@ signature_rsa signature_rsa::from_buffer(const epee::span<const uint8_t> input)
}
const auto signature_type = static_cast<type>(buffer.read_big_endian<uint8_t>());
+ if (signature_type != type::binary_document && signature_type != type::canonical_text_document)
+ {
+ throw std::runtime_error("unsupported signature type");
+ }
const auto algorithm = buffer.read_big_endian<uint8_t>();
if (algorithm != openpgp::algorithm::rsa)
@@ -231,18 +472,19 @@ signature_rsa signature_rsa::from_buffer(const epee::span<const uint8_t> input)
}
const auto hashed_data_length = buffer.read_big_endian<uint16_t>();
- std::vector<uint8_t> hashed_data = buffer.read(hashed_data_length);
+ const std::vector<uint8_t> hashed_data = buffer.read(hashed_data_length);
const auto unhashed_data_length = buffer.read_big_endian<uint16_t>();
buffer.read_span(unhashed_data_length);
- std::pair<uint8_t, uint8_t> hash_leftmost_bytes{buffer.read_big_endian<uint8_t>(), buffer.read_big_endian<uint8_t>()};
+ const auto hash_leftmost_byte_0 = buffer.read_big_endian<uint8_t>();
+ const auto hash_leftmost_byte_1 = buffer.read_big_endian<uint8_t>();
const mpi signature = buffer.read_mpi();
return signature_rsa(
algorithm,
- std::move(hash_leftmost_bytes),
+ {hash_leftmost_byte_0, hash_leftmost_byte_1},
hash_algorithm,
hashed_data,
signature_type,
@@ -252,16 +494,45 @@ signature_rsa signature_rsa::from_buffer(const epee::span<const uint8_t> input)
bool signature_rsa::verify(const epee::span<const uint8_t> message, const public_key_rsa &public_key) const
{
- const s_expression signed_data = hash_message(message, public_key.bits());
+ const std::vector<uint8_t> plain_hash = hash_message(message);
+ if (plain_hash.size() < 2)
+ {
+ throw std::runtime_error("insufficient message hash size");
+ }
+ if (plain_hash[0] != m_hash_leftmost_bytes.first || plain_hash[1] != m_hash_leftmost_bytes.second)
+ {
+ return false;
+ }
+
+ const std::vector<uint8_t> asn_object_id = hash_asn_object_id();
+
+ const size_t public_key_bytes = bits_to_bytes(public_key.bits());
+ if (public_key_bytes < plain_hash.size() + asn_object_id.size() + 11)
+ {
+ return false;
+ }
+
+ std::vector<uint8_t> emsa_pkcs1_v1_5_encoded;
+ emsa_pkcs1_v1_5_encoded.reserve(public_key_bytes);
+ emsa_pkcs1_v1_5_encoded.push_back(0);
+ emsa_pkcs1_v1_5_encoded.push_back(1);
+ const size_t ps_size = public_key_bytes - plain_hash.size() - asn_object_id.size() - 3;
+ emsa_pkcs1_v1_5_encoded.insert(emsa_pkcs1_v1_5_encoded.end(), ps_size, 0xff);
+ emsa_pkcs1_v1_5_encoded.push_back(0);
+ emsa_pkcs1_v1_5_encoded.insert(emsa_pkcs1_v1_5_encoded.end(), asn_object_id.begin(), asn_object_id.end());
+ emsa_pkcs1_v1_5_encoded.insert(emsa_pkcs1_v1_5_encoded.end(), plain_hash.begin(), plain_hash.end());
+
+ const mpi value(emsa_pkcs1_v1_5_encoded);
+ const s_expression signed_data("(data (flags raw) (value %m))", value.get());
return gcry_pk_verify(m_signature.get(), signed_data.get(), public_key.get()) == 0;
}
-s_expression signature_rsa::hash_message(const epee::span<const uint8_t> message, size_t public_key_bits) const
+std::vector<uint8_t> signature_rsa::hash_message(const epee::span<const uint8_t> message) const
{
switch (m_type)
{
case type::binary_document:
- return hash_bytes(message, public_key_bits);
+ return (hash(m_hash_algorithm) << message << m_hashed_appendix).finish();
case type::canonical_text_document:
{
std::vector<uint8_t> crlf_formatted;
@@ -270,22 +541,17 @@ s_expression signature_rsa::hash_message(const epee::span<const uint8_t> message
for (size_t offset = 0; offset < message_size; ++offset)
{
const auto &character = message[offset];
- if (character == '\r')
+ if (character == '\r' && offset + 1 < message_size && message[offset + 1] == '\n')
{
continue;
}
if (character == '\n')
{
- const bool skip_last_crlf = offset + 1 == message_size;
- if (skip_last_crlf)
- {
- break;
- }
crlf_formatted.push_back('\r');
}
crlf_formatted.push_back(character);
}
- return hash_bytes(epee::to_span(crlf_formatted), public_key_bits);
+ return (hash(m_hash_algorithm) << crlf_formatted << m_hashed_appendix).finish();
}
default:
throw std::runtime_error("unsupported signature type");
@@ -305,48 +571,14 @@ std::vector<uint8_t> signature_rsa::hash_asn_object_id() const
}
std::vector<uint8_t> asn_object_id(size);
- if (gcry_md_algo_info(m_hash_algorithm, GCRYCTL_GET_ASNOID, &asn_object_id[0], &size) != GPG_ERR_NO_ERROR)
+ if (gcry_md_algo_info(m_hash_algorithm, GCRYCTL_GET_ASNOID, asn_object_id.data(), &size) != GPG_ERR_NO_ERROR)
{
throw std::runtime_error("failed to get ASN.1 Object Identifier (OID)");
}
return asn_object_id;
}
-s_expression signature_rsa::hash_bytes(const epee::span<const uint8_t> message, size_t public_key_bits) const
-{
- const std::vector<uint8_t> plain_hash = (hash(m_hash_algorithm) << message << m_hashed_appendix).finish();
- if (plain_hash.size() < 2)
- {
- throw std::runtime_error("insufficient message hash size");
- }
- if (plain_hash[0] != m_hash_leftmost_bytes.first || plain_hash[1] != m_hash_leftmost_bytes.second)
- {
- throw std::runtime_error("signature checksum doesn't match the expected value");
- }
-
- std::vector<uint8_t> asn_object_id = hash_asn_object_id();
-
- const size_t public_key_bytes = bits_to_bytes(public_key_bits);
- if (public_key_bytes < plain_hash.size() + asn_object_id.size() + 11)
- {
- throw std::runtime_error("insufficient public key bit length");
- }
-
- std::vector<uint8_t> emsa_pkcs1_v1_5_encoded;
- emsa_pkcs1_v1_5_encoded.reserve(public_key_bytes);
- emsa_pkcs1_v1_5_encoded.push_back(0);
- emsa_pkcs1_v1_5_encoded.push_back(1);
- const size_t ps_size = public_key_bytes - plain_hash.size() - asn_object_id.size() - 3;
- emsa_pkcs1_v1_5_encoded.insert(emsa_pkcs1_v1_5_encoded.end(), ps_size, 0xff);
- emsa_pkcs1_v1_5_encoded.push_back(0);
- emsa_pkcs1_v1_5_encoded.insert(emsa_pkcs1_v1_5_encoded.end(), asn_object_id.begin(), asn_object_id.end());
- emsa_pkcs1_v1_5_encoded.insert(emsa_pkcs1_v1_5_encoded.end(), plain_hash.begin(), plain_hash.end());
-
- mpi value(emsa_pkcs1_v1_5_encoded);
- return s_expression("(data (flags raw) (value %m))", value.get());
-}
-
std::vector<uint8_t> signature_rsa::format_hashed_appendix(
uint8_t algorithm,
uint8_t hash_algorithm,
@@ -355,11 +587,11 @@ std::vector<uint8_t> signature_rsa::format_hashed_appendix(
uint8_t version)
{
const uint16_t hashed_data_size = static_cast<uint16_t>(hashed_data.size());
- const uint32_t hashed_pefix_size = sizeof(version) + sizeof(type) + sizeof(algorithm) + sizeof(hash_algorithm) +
+ const uint32_t hashed_prefix_size = sizeof(version) + sizeof(type) + sizeof(algorithm) + sizeof(hash_algorithm) +
sizeof(hashed_data_size) + hashed_data.size();
std::vector<uint8_t> appendix;
- appendix.reserve(hashed_pefix_size + sizeof(version) + sizeof(uint8_t) + sizeof(hashed_pefix_size));
+ appendix.reserve(hashed_prefix_size + sizeof(version) + sizeof(uint8_t) + sizeof(hashed_prefix_size));
appendix.push_back(version);
appendix.push_back(type);
appendix.push_back(algorithm);
@@ -369,16 +601,17 @@ std::vector<uint8_t> signature_rsa::format_hashed_appendix(
appendix.insert(appendix.end(), hashed_data.begin(), hashed_data.end());
appendix.push_back(version);
appendix.push_back(0xff);
- appendix.push_back(static_cast<uint8_t>(hashed_pefix_size >> 24));
- appendix.push_back(static_cast<uint8_t>(hashed_pefix_size >> 16));
- appendix.push_back(static_cast<uint8_t>(hashed_pefix_size >> 8));
- appendix.push_back(static_cast<uint8_t>(hashed_pefix_size));
+ appendix.push_back(static_cast<uint8_t>(hashed_prefix_size >> 24));
+ appendix.push_back(static_cast<uint8_t>(hashed_prefix_size >> 16));
+ appendix.push_back(static_cast<uint8_t>(hashed_prefix_size >> 8));
+ appendix.push_back(static_cast<uint8_t>(hashed_prefix_size));
return appendix;
}
message_armored::message_armored(const std::string &message_armored)
- : m_message(get_armored_block_contents(message_armored, "BEGIN PGP SIGNED MESSAGE"))
+ : m_message(get_cleartext_signed_text(
+ get_armored_block_contents(message_armored, "BEGIN PGP SIGNED MESSAGE", "BEGIN PGP SIGNATURE")))
{
}
### src/openpgp/openpgp.h
@@ -28,7 +28,10 @@
#pragma once
+#include <cstddef>
+#include <cstdint>
#include <string>
+#include <utility>
#include <vector>
#include <gcrypt.h>
@@ -40,6 +43,9 @@
namespace openpgp
{
+// Call once at startup
+bool initialize();
+
enum algorithm : uint8_t
{
rsa = 1,
@@ -61,8 +67,8 @@ class public_key_rsa
class public_key_block : public std::vector<public_key_rsa>
{
public:
- public_key_block(const std::string &armored);
- public_key_block(const epee::span<const uint8_t> buffer);
+ explicit public_key_block(const std::string &armored);
+ explicit public_key_block(const epee::span<const uint8_t> buffer);
std::string user_id() const;
@@ -84,7 +90,7 @@ class signature_rsa
std::pair<uint8_t, uint8_t> hash_leftmost_bytes,
uint8_t hash_algorithm,
const std::vector<uint8_t> &hashed_data,
- type type,
+ type signature_type,
s_expression signature,
uint8_t version);
@@ -95,9 +101,8 @@ class signature_rsa
bool verify(const epee::span<const uint8_t> message, const public_key_rsa &public_key) const;
private:
- s_expression hash_message(const epee::span<const uint8_t> message, size_t public_key_bits) const;
+ std::vector<uint8_t> hash_message(const epee::span<const uint8_t> message) const;
std::vector<uint8_t> hash_asn_object_id() const;
- s_expression hash_bytes(const epee::span<const uint8_t> message, size_t public_key_bits) const;
static std::vector<uint8_t> format_hashed_appendix(
uint8_t algorithm,
@@ -117,7 +122,7 @@ class signature_rsa
class message_armored
{
public:
- message_armored(const std::string &message_armored);
+ explicit message_armored(const std::string &message_armored);
operator epee::span<const uint8_t>() const;
### src/openpgp/packet_stream.h
@@ -28,6 +28,8 @@
#pragma once
+#include <type_traits>
+#include <utility>
#include <vector>
#include <span.h>
@@ -53,7 +55,7 @@ class packet_stream
while (!buffer.empty())
{
packet_tag tag = buffer.read_packet_tag();
- packets.push_back({std::move(tag), buffer.read(tag.length)});
+ packets.push_back({tag, buffer.read(tag.length)});
}
}
@@ -70,14 +72,11 @@ class packet_stream
}
template <typename Callback>
- void for_each(packet_tag::type type, Callback &callback) const
+ void for_each(Callback &&callback) const
{
for (const auto &packet : packets)
{
- if (packet.first.packet_type == type)
- {
- callback(packet.second);
- }
+ callback(packet.first.packet_type, packet.second);
}
}
### src/openpgp/s_expression.h
@@ -28,8 +28,8 @@
#pragma once
-#include <algorithm>
#include <stdexcept>
+#include <utility>
#include <gcrypt.h>
@@ -43,24 +43,19 @@ class s_expression
s_expression &operator=(const s_expression &) = delete;
template <typename... Args>
- s_expression(Args... args)
+ explicit s_expression(const char *format, Args... args)
{
- if (gcry_sexp_build(&data, nullptr, args...) != GPG_ERR_NO_ERROR)
+ if (gcry_sexp_build(&data, nullptr, format, args...) != GPG_ERR_NO_ERROR)
{
throw std::runtime_error("failed to build S-expression");
}
}
- s_expression(s_expression &&other)
+ s_expression(s_expression &&other) noexcept
{
std::swap(data, other.data);
}
- s_expression(gcry_sexp_t data)
- : data(data)
- {
- }
-
~s_expression()
{
gcry_sexp_release(data);
### src/openpgp/serialization.h
@@ -28,31 +28,25 @@
#pragma once
+#include <cstddef>
+#include <cstdint>
+#include <stdexcept>
+#include <type_traits>
+#include <vector>
+
+#include <span.h>
+
#include "mpi.h"
namespace openpgp
{
-size_t bits_to_bytes(size_t bits)
+inline size_t bits_to_bytes(size_t bits)
{
constexpr const uint16_t bits_in_byte = 8;
return (bits + bits_in_byte - 1) / bits_in_byte;
}
-std::string strip_line_breaks(const std::string &string)
-{
- std::string result;
- result.reserve(string.size());
- for (const auto &character : string)
- {
- if (character != '\r' && character != '\n')
- {
- result.push_back(character);
- }
- }
- return result;
-}
-
struct packet_tag
{
enum type : uint8_t
@@ -88,13 +82,39 @@ class deserializer
{
const auto tag = read_big_endian<uint8_t>();
- constexpr const uint8_t format_mask = 0b11000000;
- constexpr const uint8_t format_old_tag = 0b10000000;
- if ((tag & format_mask) != format_old_tag)
+ constexpr const uint8_t tag_bit = 0b10000000;
+ constexpr const uint8_t format_new_bit = 0b01000000;
+ if ((tag & tag_bit) == 0)
{
throw std::runtime_error("invalid packet tag");
}
+ if ((tag & format_new_bit) != 0)
+ {
+ const packet_tag::type packet_type = static_cast<packet_tag::type>(tag & 0b00111111);
+
+ size_t length;
+ const size_t first_octet = read_big_endian<uint8_t>();
+ if (first_octet < 192)
+ {
+ length = first_octet;
+ }
+ else if (first_octet < 224)
+ {
+ length = ((first_octet - 192) << 8) + read_big_endian<uint8_t>() + 192;
+ }
+ else if (first_octet == 255)
+ {
+ length = read_big_endian<uint32_t>();
+ }
+ else
+ {
+ throw std::runtime_error("unsupported partial body length");
+ }
+
+ return {packet_type, length};
+ }
+
const packet_tag::type packet_type = static_cast<packet_tag::type>((tag & 0b00111100) >> 2);
const uint8_t length_type = tag & 0b00000011;
@@ -117,6 +137,20 @@ class deserializer
return {packet_type, length};
}
+ size_t read_subpacket_length()
+ {
+ const size_t first_octet = read_big_endian<uint8_t>();
+ if (first_octet < 192)
+ {
+ return first_octet;
+ }
+ if (first_octet < 255)
+ {
+ return ((first_octet - 192) << 8) + read_big_endian<uint8_t>() + 192;
+ }
+ return read_big_endian<uint32_t>();
+ }
+
mpi read_mpi()
{
const size_t bit_length = read_big_endian<uint16_t>();
@@ -125,15 +159,8 @@ class deserializer
std::vector<uint8_t> read(size_t size)
{
- if (buffer.size() - cursor < size)
- {
- throw std::runtime_error("insufficient buffer size");
- }
-
- const size_t offset = cursor;
- cursor += size;
-
- return {&buffer[offset], &buffer[cursor]};
+ const epee::span<const uint8_t> span = read_span(size);
+ return {span.data(), span.data() + span.size()};
}
template <typename T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
@@ -161,7 +188,7 @@ class deserializer
const size_t offset = cursor;
cursor += size;
- return {reinterpret_cast<const uint8_t *>(&buffer[offset]), size};
+ return {reinterpret_cast<const uint8_t *>(buffer.data()) + offset, size};
}
private:
### src/qt/updater.cpp
@@ -33,9 +33,9 @@
#include "updater.h"
-#include <common/util.h>
+#include <QRegularExpression>
-#include <openpgp/hash.h>
+#include <common/util.h>
#include "network.h"
#include "utils.h"
@@ -60,7 +60,7 @@ QByteArray Updater::fetchSignedHash(
std::string hashesTxt = network.get(hashesTxtUrl);
std::string hashesTxtSig = network.get(hashesTxtSigUrl);
- const QByteArray signedHash = verifyParseSignedHahes(
+ const QByteArray signedHash = verifyParseSignedHashes(
QByteArray(&hashesTxt[0], hashesTxt.size()),
QByteArray(&hashesTxtSig[0], hashesTxtSig.size()),
binaryFilename,
@@ -74,7 +74,7 @@ QByteArray Updater::fetchSignedHash(
return signedHash;
}
-QByteArray Updater::verifyParseSignedHahes(
+QByteArray Updater::verifyParseSignedHashes(
const QByteArray &armoredSignedHashes,
const QByteArray &secondDetachedSignature,
const QString &binaryFilename,
@@ -107,7 +107,7 @@ QPair<QString, QString> Updater::verifySignaturesAndHashSum(
{
QPair<QString, QString> signers;
const QByteArray signedHash =
- verifyParseSignedHahes(armoredSignedHashes, secondDetachedSignature, binaryFilename, signers);
+ verifyParseSignedHashes(armoredSignedHashes, secondDetachedSignature, binaryFilename, signers);
const QByteArray calculatedHash = getHash(binaryData, binarySize);
if (signedHash != calculatedHash)
{
@@ -120,30 +120,43 @@ QPair<QString, QString> Updater::verifySignaturesAndHashSum(
QByteArray Updater::getHash(const void *data, size_t size) const
{
QByteArray hash(sizeof(crypto::hash), 0);
- tools::sha256sum(static_cast<const uint8_t *>(data), size, *reinterpret_cast<crypto::hash *>(hash.data()));
+ if (!tools::sha256sum(static_cast<const uint8_t *>(data), size, *reinterpret_cast<crypto::hash *>(hash.data())))
+ {
+ throw std::runtime_error("failed to calculate hash sum");
+ }
return hash;
}
QByteArray Updater::parseShasumOutput(const QString &message, const QString &filename) const
{
+ static const QRegularExpression whitespace("\\s+");
for (const auto &line : message.split('\n'))
{
- const auto trimmed = line.trimmed();
- if (trimmed.endsWith(filename))
+ const QStringList fields = line.split(whitespace, Qt::SkipEmptyParts);
+ if (fields.size() != 2)
{
- const int pos = trimmed.indexOf(' ');
- if (pos != -1)
- {
- return QByteArray::fromHex(trimmed.left(pos).toUtf8());
- }
+ continue;
}
- else if (trimmed.startsWith(filename))
+
+ // "<hash> <filename>" or "<filename> <hash>"
+ QString hash;
+ if (fields[1] == filename || fields[1] == '*' + filename)
{
- const int pos = trimmed.lastIndexOf(' ');
- if (pos != -1)
- {
- return QByteArray::fromHex(trimmed.right(trimmed.size() - pos).toUtf8());
- }
+ hash = fields[0];
+ }
+ else if (fields[0] == filename || fields[0] == filename + ',' || fields[0] == filename + ':')
+ {
+ hash = fields[1];
+ }
+ else
+ {
+ continue;
+ }
+
+ const QByteArray decoded = QByteArray::fromHex(hash.toUtf8());
+ if (decoded.size() == static_cast<qsizetype>(sizeof(crypto::hash)) && decoded.toHex() == hash.toLower().toUtf8())
+ {
+ return decoded;
}
}
### src/qt/updater.h
@@ -51,7 +51,7 @@ class Updater
size_t binarySize) const;
private:
- QByteArray verifyParseSignedHahes(
+ QByteArray verifyParseSignedHashes(
const QByteArray &armoredSignedHashes,
const QByteArray &secondDetachedSignature,
const QString &binaryFilename,Why this scored 71/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.