#include "config.h"
#include "ApduCommand.h"
#if ENABLE(WEB_AUTHN)
namespace apdu {
namespace {
uint16_t parseMessageLength(const Vector<uint8_t>& message, size_t offset)
{
ASSERT(message.size() >= offset + 2);
return (message[offset] << 8) | message[offset + 1];
}
}
Optional<ApduCommand> ApduCommand::createFromMessage(const Vector<uint8_t>& message)
{
if (message.size() < kApduMinHeader || message.size() > kApduMaxLength)
return WTF::nullopt;
uint8_t cla = message[0];
uint8_t ins = message[1];
uint8_t p1 = message[2];
uint8_t p2 = message[3];
size_t responseLength = 0;
Vector<uint8_t> data;
switch (message.size()) {
case kApduMinHeader:
break;
case kApduMinHeader + 1:
case kApduMinHeader + 2:
return WTF::nullopt;
case kApduMinHeader + 3:
if (message[4])
return WTF::nullopt;
responseLength = parseMessageLength(message, kApduCommandLengthOffset);
if (!responseLength)
responseLength = kApduMaxResponseLength;
break;
default:
if (message[4])
return WTF::nullopt;
auto dataLength = parseMessageLength(message, kApduCommandLengthOffset);
if (message.size() == dataLength + kApduCommandDataOffset) {
data.appendRange(message.begin() + kApduCommandDataOffset, message.end());
} else if (message.size() == dataLength + kApduCommandDataOffset + 2) {
data.appendRange(message.begin() + kApduCommandDataOffset, message.end() - 2);
auto responseLengthOffset = kApduCommandDataOffset + dataLength;
responseLength = parseMessageLength(message, responseLengthOffset);
if (!responseLength)
responseLength = kApduMaxResponseLength;
} else
return WTF::nullopt;
break;
}
return ApduCommand(cla, ins, p1, p2, responseLength, WTFMove(data));
}
ApduCommand::ApduCommand(uint8_t cla, uint8_t ins, uint8_t p1, uint8_t p2, size_t responseLength, Vector<uint8_t>&& data)
: m_cla(cla)
, m_ins(ins)
, m_p1(p1)
, m_p2(p2)
, m_responseLength(responseLength)
, m_data(WTFMove(data))
{
}
Vector<uint8_t> ApduCommand::getEncodedCommand() const
{
Vector<uint8_t> encoded = { m_cla, m_ins, m_p1, m_p2 };
if (!m_data.isEmpty()) {
size_t dataLength = m_data.size();
encoded.append(0x0);
if (dataLength > kApduMaxDataLength)
dataLength = kApduMaxDataLength;
encoded.append((dataLength >> 8) & 0xff);
encoded.append(dataLength & 0xff);
encoded.appendRange(m_data.begin(), m_data.begin() + dataLength);
} else if (m_responseLength > 0)
encoded.append(0x0);
if (m_responseLength > 0) {
size_t responseLength = m_responseLength;
if (responseLength > kApduMaxResponseLength)
responseLength = kApduMaxResponseLength;
encoded.append((responseLength >> 8) & 0xff);
encoded.append(responseLength & 0xff);
}
return encoded;
}
}
#endif // ENABLE(WEB_AUTHN)