Double free during gnutls_pkcs7_verify
## Description of problem: The [Sharemind](https://sharemind.cyber.ee/) team at [Cybernetica](https://cyber.ee/) team found a heap corruption and crash issue, first experienced on Ubuntu 20.04 during a call to `gnutls_pkcs7_verify`. Here is the first part of the relevant valgrind information. ``` ==4428== Invalid read of size 8 ==4428== at 0x4D9B752: gnutls_x509_crt_deinit (x509.c:296) ==4428== by 0x4D88183: find_signer (pkcs7.c:1364) ==4428== by 0x4D88183: gnutls_pkcs7_verify (pkcs7.c:1440) ==4428== by 0x1796EA: ??? ==4428== by 0x1880CD: ??? ==4428== by 0x1BDB48: ??? ==4428== by 0x177FB5: main (in /usr/bin/???) ==4428== Address 0x60ddc10 is 0 bytes inside a block of size 136 free'd ==4428== at 0x483CA3F: free (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) ==4428== by 0x4D884F6: find_signer (pkcs7.c:1321) ==4428== by 0x4D884F6: gnutls_pkcs7_verify (pkcs7.c:1440) ==4428== by 0x1796EA: ??? ==4428== by 0x1880CD: ??? ==4428== by 0x1BDB48: ??? ==4428== by 0x177FB5: main (in /usr/bin/???) ==4428== Block was alloc'd at ==4428== at 0x483DD99: calloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) ==4428== by 0x4D9C2E8: gnutls_x509_crt_init (x509.c:207) ==4428== by 0x4D86642: find_child_of_with_serial (pkcs7.c:1142) ==4428== by 0x4D87D94: find_signer (pkcs7.c:1298) ==4428== by 0x4D87D94: gnutls_pkcs7_verify (pkcs7.c:1440) ==4428== by 0x1796EA: ??? ==4428== by 0x1880CD: ??? ==4428== by 0x1BDB48: ??? ==4428== by 0x177FB5: main (in ???) ``` ## Version of gnutls used: libgnutls30 (3.6.13-2ubuntu1.6) ## Distributor of gnutls (e.g., Ubuntu, Fedora, RHEL) Ubuntu Focal (20.04) ## Notes I'm not familiar with the code, but I suspect that pkcs7.c:1321 should also check for `prev == signer`: ```diff -if (prev) gnutls_x509_crt_deinit(prev); +if (prev && prev != signer) { + gnutls_x509_crt_deinit(prev); +} ``` or that `NULL` should be assigned to `signer` at some later point to prevent it from being double-freed.
issue