Skip to content

Commit

Permalink
Pars cert TLVs
Browse files Browse the repository at this point in the history
  • Loading branch information
qpernil committed Nov 29, 2023
1 parent 6fa2c7a commit 7da6604
Showing 1 changed file with 40 additions and 39 deletions.
79 changes: 40 additions & 39 deletions lib/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -1387,51 +1387,52 @@ uint32_t ykpiv_util_slot_object(uint8_t slot) {
}

ykpiv_rc ykpiv_util_get_certdata(uint8_t *buf, size_t buf_len, uint8_t* certdata, unsigned long *certdata_len) {
const unsigned char *x509ptr = buf;
X509 *x509 = d2i_X509(NULL, &x509ptr, buf_len);
if(x509 != NULL) {
DBG("Found raw certificate");
if (*certdata_len < buf_len) {
DBG("Buffer too small");
*certdata_len = 0;
return YKPIV_SIZE_ERROR;
}
memmove(certdata, buf, buf_len);
*certdata_len = buf_len;
return YKPIV_OK;
}

uint8_t compress_info = 0;
uint8_t *certptr;
uint8_t compress_info = YKPIV_CERTINFO_UNCOMPRESSED;
uint8_t *certptr = 0;
size_t cert_len = 0;
uint8_t *ptr = buf;

while (ptr < buf + buf_len) {
switch (*ptr++) {
case TAG_CERT: {
size_t offs = _ykpiv_get_length(ptr, buf + buf_len, &cert_len);
if(!offs) {
*certdata_len = 0;
return YKPIV_OK;
}
ptr += offs; // move to after length bytes
certptr = ptr;
ptr += cert_len; // move to after cert bytes
break;
}
case TAG_CERT_COMPRESS:
ptr++; // move to after length byte
compress_info = *ptr++;
break;
default:
DBG("Found cert tag 0x%02x. Ignoring it", *(ptr-1));
size_t value_len = 0;
ptr += _ykpiv_get_length(ptr, buf + buf_len, &value_len);
ptr += value_len; // move to after value bytes
break;
}
uint8_t tag = *ptr++;
size_t len = 0;
size_t offs = _ykpiv_get_length(ptr, buf + buf_len, &len);
if(!offs) {
DBG("Found invalid length for tag 0x%02x.", tag);
goto invalid;
}
ptr += offs; // move to after length bytes
switch (tag) {
case TAG_CERT:
certptr = ptr;
cert_len = len;
DBG("Found TAG_CERT with length %zu", len);
break;
case TAG_CERT_COMPRESS:
if(len != 1) {
DBG("Found TAG_CERT_COMPRESS with invalid length %zu", len);
goto invalid;
}
compress_info = *ptr;
DBG("Found TAG_CERT_COMPRESS with length %zu value 0x%02x", len, compress_info);
break;
case TAG_CERT_LRC:
// Ignore
DBG("Found TAG_CERT_LRC with length %zu", len);
break;
default:
DBG("Found invalid tag 0x%02x.", tag);
goto invalid;
}
ptr += len; // move to after value bytes
}

invalid:
if(certptr == 0 || cert_len == 0 || ptr != buf + buf_len) {
DBG("Invalid TLV encoding, treating as a raw certificate");
certptr = buf;
cert_len = buf_len;
}

if (compress_info == YKPIV_CERTINFO_GZIP) { // This byte is set to 1 if certinfo is YKPIV_CERTINFO_GZIP
z_stream zs;
zs.zalloc = Z_NULL;
Expand Down

0 comments on commit 7da6604

Please sign in to comment.