From: Kirill Isakov Date: Wed, 27 Apr 2022 09:49:32 +0000 (+0600) Subject: Fix reading broken BER in gcrypt/rsa.c X-Git-Url: https://tinc-vpn.org/git/browse?a=commitdiff_plain;h=76de8e3924fc36e5a3e906741bf640dceb846800;p=tinc Fix reading broken BER in gcrypt/rsa.c Our hand-rolled BER parser was reading ASN.1 sequence length without checking if there's a sequence tag (0x10) before it. --- diff --git a/src/gcrypt/asn1.h b/src/gcrypt/asn1.h new file mode 100644 index 00000000..6709fa33 --- /dev/null +++ b/src/gcrypt/asn1.h @@ -0,0 +1,10 @@ +#ifndef TINC_GCRYPT_ASN1_H +#define TINC_GCRYPT_ASN1_H + +// https://luca.ntop.org/Teaching/Appunti/asn1.html +typedef enum { + TAG_INTEGER = 2, + TAG_SEQUENCE = 16, +} asn1_tag_t; + +#endif // TINC_GCRYPT_ASN1_H diff --git a/src/gcrypt/rsa.c b/src/gcrypt/rsa.c index 83f177b8..04aa358d 100644 --- a/src/gcrypt/rsa.c +++ b/src/gcrypt/rsa.c @@ -23,6 +23,7 @@ #include "pem.h" +#include "asn1.h" #include "rsa.h" #include "../logger.h" #include "../rsa.h" @@ -84,20 +85,11 @@ static size_t ber_read_len(unsigned char **p, size_t *buflen) { } } - -static bool ber_read_sequence(unsigned char **p, size_t *buflen, size_t *result) { +static bool ber_skip_sequence(unsigned char **p, size_t *buflen) { int tag = ber_read_id(p, buflen); - size_t len = ber_read_len(p, buflen); - - if(tag == 0x10) { - if(result) { - *result = len; - } - return true; - } else { - return false; - } + return tag == TAG_SEQUENCE && + ber_read_len(p, buflen) > 0; } static bool ber_read_mpi(unsigned char **p, size_t *buflen, gcry_mpi_t *mpi) { @@ -172,7 +164,7 @@ rsa_t *rsa_read_pem_public_key(FILE *fp) { rsa_t *rsa = xzalloc(sizeof(rsa_t)); - if(!ber_read_sequence(&derp, &derlen, NULL) + if(!ber_skip_sequence(&derp, &derlen) || !ber_read_mpi(&derp, &derlen, &rsa->n) || !ber_read_mpi(&derp, &derlen, &rsa->e) || derlen) { @@ -195,7 +187,7 @@ rsa_t *rsa_read_pem_private_key(FILE *fp) { rsa_t *rsa = xzalloc(sizeof(rsa_t)); - if(!ber_read_sequence(&derp, &derlen, NULL) + if(!ber_skip_sequence(&derp, &derlen) || !ber_read_mpi(&derp, &derlen, NULL) || !ber_read_mpi(&derp, &derlen, &rsa->n) || !ber_read_mpi(&derp, &derlen, &rsa->e) diff --git a/src/gcrypt/rsagen.c b/src/gcrypt/rsagen.c index 85765557..b89225d4 100644 --- a/src/gcrypt/rsagen.c +++ b/src/gcrypt/rsagen.c @@ -22,18 +22,13 @@ #include #include +#include "asn1.h" #include "rsa.h" #include "pem.h" #include "../rsagen.h" #include "../xalloc.h" #include "../utils.h" -// ASN.1 tags. -typedef enum { - TAG_INTEGER = 2, - TAG_SEQUENCE = 16, -} asn1_tag_t; - static size_t der_tag_len(size_t n) { if(n < 128) { return 2;