encoding: avoid UB when casting to tlv::SignatureTypeValue
Change-Id: I52ec0bef8527b6a52208dc07be75e790e504c47e
Refs: #4370
diff --git a/src/signature-info.cpp b/src/signature-info.cpp
index 0b3b0a1..6210eff 100644
--- a/src/signature-info.cpp
+++ b/src/signature-info.cpp
@@ -79,10 +79,11 @@
if (m_hasKeyLocator)
totalLength += m_keyLocator.wireEncode(encoder);
- totalLength += prependNonNegativeIntegerBlock(encoder, tlv::SignatureType, m_type);
-
+ totalLength += prependNonNegativeIntegerBlock(encoder, tlv::SignatureType,
+ static_cast<uint64_t>(m_type));
totalLength += encoder.prependVarNumber(totalLength);
totalLength += encoder.prependVarNumber(tlv::SignatureInfo);
+
return totalLength;
}
@@ -107,6 +108,7 @@
void
SignatureInfo::wireDecode(const Block& wire)
{
+ m_type = -1;
m_hasKeyLocator = false;
m_otherTlvs.clear();
@@ -116,16 +118,15 @@
if (m_wire.type() != tlv::SignatureInfo)
BOOST_THROW_EXCEPTION(Error("Decoding SignatureInfo, but TLV-TYPE is " + to_string(m_wire.type())));
- Block::element_const_iterator it = m_wire.elements_begin();
+ auto it = m_wire.elements_begin();
// the first sub-element must be SignatureType
- if (it != m_wire.elements_end() && it->type() == tlv::SignatureType) {
- m_type = readNonNegativeIntegerAs<int32_t>(*it);
- ++it;
- }
- else
+ if (it == m_wire.elements_end() || it->type() != tlv::SignatureType)
BOOST_THROW_EXCEPTION(Error("Missing SignatureType in SignatureInfo"));
+ m_type = readNonNegativeIntegerAs<tlv::SignatureTypeValue>(*it);
+ ++it;
+
// the second sub-element could be KeyLocator
if (it != m_wire.elements_end() && it->type() == tlv::KeyLocator) {
m_keyLocator.wireDecode(*it);
@@ -228,6 +229,9 @@
std::ostream&
operator<<(std::ostream& os, const SignatureInfo& info)
{
+ if (info.getSignatureType() == -1)
+ return os << "Invalid SignatureInfo";
+
os << static_cast<tlv::SignatureTypeValue>(info.getSignatureType());
if (info.hasKeyLocator()) {
os << " " << info.getKeyLocator();
@@ -239,6 +243,7 @@
}
os << "}";
}
+
return os;
}