EVP_CIPHER_CTX will become opaque, so this will need to change.
Allocate ctx once in esp_init() and modify all accesses accordingly.

Two more things:

Fix the error check of EVP_CipherInit() in esp_init(). The return
values are 1 for success and 1 for failure, so the usual OpenSSL idiom
applies.

In esp_decrypt() I'm not 100% sure how to react to EVP_CipherInit() or
EVP_Cipher() failure (both are currently unchecked). If decryption
fails, the function will likely return a few lines down since the
padding doesn't check out, so a silent return seemed like the
appropriate action.

Index: print-ipsec.c
===================================================================
RCS file: /cvs/src/usr.sbin/tcpdump/print-ipsec.c,v
retrieving revision 1.26
diff -u -p -r1.26 print-ipsec.c
--- print-ipsec.c       24 Jan 2020 22:46:37 -0000      1.26
+++ print-ipsec.c       27 Nov 2021 16:57:20 -0000
@@ -59,7 +59,7 @@ struct esp_hdr {
 
 static int espinit = 0;
 static int espauthlen = 12;
-static EVP_CIPHER_CTX ctx;
+static EVP_CIPHER_CTX *ctx;
 
 int
 esp_init (char *espspec)
@@ -105,8 +105,12 @@ esp_init (char *espspec)
                }
                key[i] = strtoul(s, NULL, 16);
        }
-       EVP_CIPHER_CTX_init(&ctx);
-       if (EVP_CipherInit(&ctx, evp, key, NULL, 0) < 0) {
+       if ((ctx = EVP_CIPHER_CTX_new()) == NULL) {
+               free(key);
+               error("espkey init failed");
+       }
+       if (!EVP_CipherInit(ctx, evp, key, NULL, 0)) {
+               EVP_CIPHER_CTX_free(ctx);
                free(key);
                error("espkey init failed");
        }
@@ -115,16 +119,16 @@ esp_init (char *espspec)
        return (0);
 }
 
-void 
+void
 esp_decrypt (const u_char *bp, u_int len, const u_char *bp2)
 {
        const struct ip *ip;
        u_char *data, pad, nh;
        int blocksz;
- 
+
        ip = (const struct ip *)bp2;
 
-       blocksz = EVP_CIPHER_CTX_block_size(&ctx);
+       blocksz = EVP_CIPHER_CTX_block_size(ctx);
 
        /* Skip fragments and short packets */
        if (ntohs(ip->ip_off) & 0x3fff)
@@ -149,12 +153,15 @@ esp_decrypt (const u_char *bp, u_int len
        len -= espauthlen;
 
        /* the first block contains the IV */
-       EVP_CipherInit(&ctx, NULL, NULL, data, 0);
+       if (!EVP_CipherInit(ctx, NULL, NULL, data, 0))
+               return;
+
        len -= blocksz;
        data += blocksz;
 
        /* decrypt remaining payload */
-       EVP_Cipher(&ctx, data, data, len);
+       if (!EVP_Cipher(ctx, data, data, len))
+               return;
 
        nh = data[len - 1];
        pad = data[len - 2];

Reply via email to