Skip to content

Commit 62d8e04

Browse files
committed
ASN.1: Guarantee serial numbers to be always positive
Signed-off-by: Stephan Mueller <smueller@chronox.de>
1 parent 579a698 commit 62d8e04

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

asn1/src/x509_cert_generator.c

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -955,14 +955,35 @@ int lc_x509_note_serial_enc(void *context, uint8_t *data, size_t *avail_datalen,
955955
{
956956
struct x509_generate_context *ctx = context;
957957
const struct lc_x509_certificate *cert = ctx->cert;
958+
size_t serial_size = cert->raw_serial_size;
958959
int ret = 0;
960+
uint8_t add_sign = 0;
959961

960962
(void)tag;
961963

962-
CKINT(lc_x509_sufficient_size(avail_datalen, cert->raw_serial_size));
964+
if (!serial_size)
965+
return 0;
963966

967+
/*
968+
* From RFC5280 appendix B:
969+
*
970+
* CAs MUST force the serialNumber to be a non-negative integer, that
971+
* is, the sign bit in the DER encoding of the INTEGER value MUST be
972+
* zero.
973+
*/
974+
if (cert->raw_serial[0] & 0x80) {
975+
serial_size++;
976+
add_sign = 1;
977+
}
978+
979+
CKINT(lc_x509_sufficient_size(avail_datalen, serial_size));
980+
981+
if (add_sign) {
982+
data[0] = 0;
983+
data++;
984+
}
964985
memcpy(data, cert->raw_serial, cert->raw_serial_size);
965-
*avail_datalen -= cert->raw_serial_size;
986+
*avail_datalen -= serial_size;
966987
bin2print_debug(cert->raw_serial, cert->raw_serial_size, stdout,
967988
"Serial");
968989

asn1/src/x509_cert_generator_set_data.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,10 @@ LC_INTERFACE_FUNCTION(int, lc_x509_cert_set_serial,
558558
CKNULL(cert, -EINVAL);
559559
CKNULL(serial, -EINVAL);
560560

561+
/* RFC5280 requires the serial to be not longer than 20 bytes. */
562+
if (serial_len > 20)
563+
return -EINVAL;
564+
561565
cert->raw_serial = serial;
562566
cert->raw_serial_size = serial_len;
563567

0 commit comments

Comments
 (0)