Home | History | Annotate | Line # | Download | only in dist
      1 /*	NetBSD: print-ah.c,v 1.4 1996/05/20 00:41:16 fvdl Exp 	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that: (1) source code distributions
      9  * retain the above copyright notice and this paragraph in its entirety, (2)
     10  * distributions including binary code include the above copyright notice and
     11  * this paragraph in its entirety in the documentation or other materials
     12  * provided with the distribution, and (3) all advertising materials mentioning
     13  * features or use of this software display the following acknowledgement:
     14  * ``This product includes software developed by the University of California,
     15  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
     16  * the University nor the names of its contributors may be used to endorse
     17  * or promote products derived from this software without specific prior
     18  * written permission.
     19  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
     20  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
     21  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
     22  */
     23 
     24 #include <sys/cdefs.h>
     25 #ifndef lint
     26 __RCSID("$NetBSD: print-esp.c,v 1.13 2024/09/02 16:15:31 christos Exp $");
     27 #endif
     28 
     29 /* \summary: IPSEC Encapsulating Security Payload (ESP) printer */
     30 
     31 #include <config.h>
     32 
     33 #include "netdissect-stdinc.h"
     34 
     35 #include <string.h>
     36 #include <stdlib.h>
     37 
     38 #ifdef HAVE_LIBCRYPTO
     39 #include <openssl/evp.h>
     40 #endif
     41 
     42 #include "netdissect.h"
     43 #include "extract.h"
     44 
     45 #include "diag-control.h"
     46 
     47 #ifdef HAVE_LIBCRYPTO
     48 #include "strtoaddr.h"
     49 #include "ascii_strcasecmp.h"
     50 #endif
     51 
     52 #include "ip.h"
     53 #include "ip6.h"
     54 
     55 /*
     56  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
     57  * All rights reserved.
     58  *
     59  * Redistribution and use in source and binary forms, with or without
     60  * modification, are permitted provided that the following conditions
     61  * are met:
     62  * 1. Redistributions of source code must retain the above copyright
     63  *    notice, this list of conditions and the following disclaimer.
     64  * 2. Redistributions in binary form must reproduce the above copyright
     65  *    notice, this list of conditions and the following disclaimer in the
     66  *    documentation and/or other materials provided with the distribution.
     67  * 3. Neither the name of the project nor the names of its contributors
     68  *    may be used to endorse or promote products derived from this software
     69  *    without specific prior written permission.
     70  *
     71  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     72  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     73  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     74  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     75  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     76  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     77  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     78  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     79  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     80  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     81  * SUCH DAMAGE.
     82  */
     83 
     84 /*
     85  * RFC1827/2406 Encapsulated Security Payload.
     86  */
     87 
     88 struct newesp {
     89 	nd_uint32_t	esp_spi;	/* ESP */
     90 	nd_uint32_t	esp_seq;	/* Sequence number */
     91 	/*variable size*/		/* (IV and) Payload data */
     92 	/*variable size*/		/* padding */
     93 	/*8bit*/			/* pad size */
     94 	/*8bit*/			/* next header */
     95 	/*8bit*/			/* next header */
     96 	/*variable size, 32bit bound*/	/* Authentication data */
     97 };
     98 
     99 #ifdef HAVE_LIBCRYPTO
    100 union inaddr_u {
    101 	nd_ipv4 in4;
    102 	nd_ipv6 in6;
    103 };
    104 struct sa_list {
    105 	struct sa_list	*next;
    106 	u_int		daddr_version;
    107 	union inaddr_u	daddr;
    108 	uint32_t	spi;          /* if == 0, then IKEv2 */
    109 	int             initiator;
    110 	u_char          spii[8];      /* for IKEv2 */
    111 	u_char          spir[8];
    112 	const EVP_CIPHER *evp;
    113 	u_int		ivlen;
    114 	int		authlen;
    115 	u_char          authsecret[256];
    116 	int             authsecret_len;
    117 	u_char		secret[256];  /* is that big enough for all secrets? */
    118 	int		secretlen;
    119 };
    120 
    121 #ifndef HAVE_EVP_CIPHER_CTX_NEW
    122 /*
    123  * Allocate an EVP_CIPHER_CTX.
    124  * Used if we have an older version of OpenSSL that doesn't provide
    125  * routines to allocate and free them.
    126  */
    127 static EVP_CIPHER_CTX *
    128 EVP_CIPHER_CTX_new(void)
    129 {
    130 	EVP_CIPHER_CTX *ctx;
    131 
    132 	ctx = malloc(sizeof(*ctx));
    133 	if (ctx == NULL)
    134 		return (NULL);
    135 	memset(ctx, 0, sizeof(*ctx));
    136 	return (ctx);
    137 }
    138 
    139 static void
    140 EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
    141 {
    142 	EVP_CIPHER_CTX_cleanup(ctx);
    143 	free(ctx);
    144 }
    145 #endif
    146 
    147 #ifdef HAVE_EVP_DECRYPTINIT_EX
    148 /*
    149  * Initialize the cipher by calling EVP_DecryptInit_ex(), because
    150  * calling EVP_DecryptInit() will reset the cipher context, clearing
    151  * the cipher, so calling it twice, with the second call having a
    152  * null cipher, will clear the already-set cipher.  EVP_DecryptInit_ex(),
    153  * however, won't reset the cipher context, so you can use it to specify
    154  * the IV in a second call after a first call to EVP_DecryptInit_ex()
    155  * to set the cipher and the key.
    156  *
    157  * XXX - is there some reason why we need to make two calls?
    158  */
    159 static int
    160 set_cipher_parameters(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
    161 		      const unsigned char *key,
    162 		      const unsigned char *iv)
    163 {
    164 	return EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv);
    165 }
    166 #else
    167 /*
    168  * Initialize the cipher by calling EVP_DecryptInit(), because we don't
    169  * have EVP_DecryptInit_ex(); we rely on it not trashing the context.
    170  */
    171 static int
    172 set_cipher_parameters(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
    173 		      const unsigned char *key,
    174 		      const unsigned char *iv)
    175 {
    176 	return EVP_DecryptInit(ctx, cipher, key, iv);
    177 }
    178 #endif
    179 
    180 static u_char *
    181 do_decrypt(netdissect_options *ndo, const char *caller, struct sa_list *sa,
    182     const u_char *iv, const u_char *ct, unsigned int ctlen)
    183 {
    184 	EVP_CIPHER_CTX *ctx;
    185 	unsigned int block_size;
    186 	unsigned int ptlen;
    187 	u_char *pt;
    188 	int len;
    189 
    190 	ctx = EVP_CIPHER_CTX_new();
    191 	if (ctx == NULL) {
    192 		/*
    193 		 * Failed to initialize the cipher context.
    194 		 * From a look at the OpenSSL code, this appears to
    195 		 * mean "couldn't allocate memory for the cipher context";
    196 		 * note that we're not passing any parameters, so there's
    197 		 * not much else it can mean.
    198 		 */
    199 		(*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
    200 		    "%s: can't allocate memory for cipher context", caller);
    201 		return NULL;
    202 	}
    203 
    204 	if (set_cipher_parameters(ctx, sa->evp, sa->secret, NULL) < 0) {
    205 		EVP_CIPHER_CTX_free(ctx);
    206 		(*ndo->ndo_warning)(ndo, "%s: espkey init failed", caller);
    207 		return NULL;
    208 	}
    209 	if (set_cipher_parameters(ctx, NULL, NULL, iv) < 0) {
    210 		EVP_CIPHER_CTX_free(ctx);
    211 		(*ndo->ndo_warning)(ndo, "%s: IV init failed", caller);
    212 		return NULL;
    213 	}
    214 
    215 	/*
    216 	 * At least as I read RFC 5996 section 3.14 and RFC 4303 section 2.4,
    217 	 * if the cipher has a block size of which the ciphertext's size must
    218 	 * be a multiple, the payload must be padded to make that happen, so
    219 	 * the ciphertext length must be a multiple of the block size.  Fail
    220 	 * if that's not the case.
    221 	 */
    222 	block_size = (unsigned int)EVP_CIPHER_CTX_block_size(ctx);
    223 	if ((ctlen % block_size) != 0) {
    224 		EVP_CIPHER_CTX_free(ctx);
    225 		(*ndo->ndo_warning)(ndo,
    226 		    "%s: ciphertext size %u is not a multiple of the cipher block size %u",
    227 		    caller, ctlen, block_size);
    228 		return NULL;
    229 	}
    230 
    231 	/*
    232 	 * Attempt to allocate a buffer for the decrypted data, because
    233 	 * we can't decrypt on top of the input buffer.
    234 	 */
    235 	ptlen = ctlen;
    236 	pt = (u_char *)calloc(1, ptlen);
    237 	if (pt == NULL) {
    238 		EVP_CIPHER_CTX_free(ctx);
    239 		(*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
    240 		    "%s: can't allocate memory for decryption buffer", caller);
    241 		return NULL;
    242 	}
    243 
    244 	/*
    245 	 * The size of the ciphertext handed to us is a multiple of the
    246 	 * cipher block size, so we don't need to worry about padding.
    247 	 */
    248 	if (!EVP_CIPHER_CTX_set_padding(ctx, 0)) {
    249 		free(pt);
    250 		EVP_CIPHER_CTX_free(ctx);
    251 		(*ndo->ndo_warning)(ndo,
    252 		    "%s: EVP_CIPHER_CTX_set_padding failed", caller);
    253 		return NULL;
    254 	}
    255 	if (!EVP_DecryptUpdate(ctx, pt, &len, ct, ctlen)) {
    256 		free(pt);
    257 		EVP_CIPHER_CTX_free(ctx);
    258 		(*ndo->ndo_warning)(ndo, "%s: EVP_DecryptUpdate failed",
    259 		    caller);
    260 		return NULL;
    261 	}
    262 	EVP_CIPHER_CTX_free(ctx);
    263 	return pt;
    264 }
    265 
    266 /*
    267  * This will allocate a new buffer containing the decrypted data.
    268  * It returns 1 on success and 0 on failure.
    269  *
    270  * It will push the new buffer and the values of ndo->ndo_packetp and
    271  * ndo->ndo_snapend onto the buffer stack, and change ndo->ndo_packetp
    272  * and ndo->ndo_snapend to refer to the new buffer.
    273  *
    274  * Our caller must pop the buffer off the stack when it's finished
    275  * dissecting anything in it and before it does any dissection of
    276  * anything in the old buffer.  That will free the new buffer.
    277  */
    278 DIAG_OFF_DEPRECATION
    279 int esp_decrypt_buffer_by_ikev2_print(netdissect_options *ndo,
    280 				      int initiator,
    281 				      const u_char spii[8],
    282 				      const u_char spir[8],
    283 				      const u_char *buf, const u_char *end)
    284 {
    285 	struct sa_list *sa;
    286 	const u_char *iv;
    287 	const u_char *ct;
    288 	unsigned int ctlen;
    289 	u_char *pt;
    290 
    291 	/* initiator arg is any non-zero value */
    292 	if(initiator) initiator=1;
    293 
    294 	/* see if we can find the SA, and if so, decode it */
    295 	for (sa = ndo->ndo_sa_list_head; sa != NULL; sa = sa->next) {
    296 		if (sa->spi == 0
    297 		    && initiator == sa->initiator
    298 		    && memcmp(spii, sa->spii, 8) == 0
    299 		    && memcmp(spir, sa->spir, 8) == 0)
    300 			break;
    301 	}
    302 
    303 	if(sa == NULL) return 0;
    304 	if(sa->evp == NULL) return 0;
    305 
    306 	/*
    307 	 * remove authenticator, and see if we still have something to
    308 	 * work with
    309 	 */
    310 	end = end - sa->authlen;
    311 	iv  = buf;
    312 	ct = iv + sa->ivlen;
    313 	ctlen = end-ct;
    314 
    315 	if(end <= ct) return 0;
    316 
    317 	pt = do_decrypt(ndo, __func__, sa, iv,
    318 	    ct, ctlen);
    319 	if (pt == NULL)
    320 		return 0;
    321 
    322 	/*
    323 	 * Switch to the output buffer for dissection, and save it
    324 	 * on the buffer stack so it can be freed; our caller must
    325 	 * pop it when done.
    326 	 */
    327 	if (!nd_push_buffer(ndo, pt, pt, ctlen)) {
    328 		free(pt);
    329 		(*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
    330 			"%s: can't push buffer on buffer stack", __func__);
    331 	}
    332 
    333 	return 1;
    334 }
    335 DIAG_ON_DEPRECATION
    336 
    337 static void esp_print_addsa(netdissect_options *ndo,
    338 			    const struct sa_list *sa, int sa_def)
    339 {
    340 	/* copy the "sa" */
    341 
    342 	struct sa_list *nsa;
    343 
    344 	/* malloc() return used in a 'struct sa_list': do not free() */
    345 	nsa = (struct sa_list *)malloc(sizeof(struct sa_list));
    346 	if (nsa == NULL)
    347 		(*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
    348 				  "%s: malloc", __func__);
    349 
    350 	*nsa = *sa;
    351 
    352 	if (sa_def)
    353 		ndo->ndo_sa_default = nsa;
    354 
    355 	nsa->next = ndo->ndo_sa_list_head;
    356 	ndo->ndo_sa_list_head = nsa;
    357 }
    358 
    359 
    360 static u_int hexdigit(netdissect_options *ndo, char hex)
    361 {
    362 	if (hex >= '0' && hex <= '9')
    363 		return (hex - '0');
    364 	else if (hex >= 'A' && hex <= 'F')
    365 		return (hex - 'A' + 10);
    366 	else if (hex >= 'a' && hex <= 'f')
    367 		return (hex - 'a' + 10);
    368 	else {
    369 		(*ndo->ndo_error)(ndo, S_ERR_ND_ESP_SECRET,
    370 				  "invalid hex digit %c in espsecret\n", hex);
    371 	}
    372 }
    373 
    374 static u_int hex2byte(netdissect_options *ndo, char *hexstring)
    375 {
    376 	u_int byte;
    377 
    378 	byte = (hexdigit(ndo, hexstring[0]) << 4) + hexdigit(ndo, hexstring[1]);
    379 	return byte;
    380 }
    381 
    382 /*
    383  * returns size of binary, 0 on failure.
    384  */
    385 static int
    386 espprint_decode_hex(netdissect_options *ndo,
    387 		    u_char *binbuf, unsigned int binbuf_len, char *hex)
    388 {
    389 	unsigned int len;
    390 	int i;
    391 
    392 	len = strlen(hex) / 2;
    393 
    394 	if (len > binbuf_len) {
    395 		(*ndo->ndo_warning)(ndo, "secret is too big: %u\n", len);
    396 		return 0;
    397 	}
    398 
    399 	i = 0;
    400 	while (hex[0] != '\0' && hex[1]!='\0') {
    401 		binbuf[i] = hex2byte(ndo, hex);
    402 		hex += 2;
    403 		i++;
    404 	}
    405 
    406 	return i;
    407 }
    408 
    409 /*
    410  * decode the form:    SPINUM@IP <tab> ALGONAME:0xsecret
    411  */
    412 
    413 DIAG_OFF_DEPRECATION
    414 static int
    415 espprint_decode_encalgo(netdissect_options *ndo,
    416 			char *decode, struct sa_list *sa)
    417 {
    418 	size_t i;
    419 	const EVP_CIPHER *evp;
    420 	int authlen = 0;
    421 	char *colon, *p;
    422 	const char *real_decode;
    423 
    424 	colon = strchr(decode, ':');
    425 	if (colon == NULL) {
    426 		(*ndo->ndo_warning)(ndo, "failed to decode espsecret: %s\n", decode);
    427 		return 0;
    428 	}
    429 	*colon = '\0';
    430 
    431 	if (strlen(decode) > strlen("-hmac96") &&
    432 	    !strcmp(decode + strlen(decode) - strlen("-hmac96"),
    433 		    "-hmac96")) {
    434 		p = strstr(decode, "-hmac96");
    435 		*p = '\0';
    436 		authlen = 12;
    437 	}
    438 	if (strlen(decode) > strlen("-cbc") &&
    439 	    !strcmp(decode + strlen(decode) - strlen("-cbc"), "-cbc")) {
    440 		p = strstr(decode, "-cbc");
    441 		*p = '\0';
    442 	}
    443 	/*
    444 	 * Not all versions of libcrypto support calls to add aliases
    445 	 * to ciphers - newer versions of libressl don't - so, instead
    446 	 * of making "3des" an alias for "des_ede3_cbc", if attempting
    447 	 * to get the cipher fails and the name is "3des", we try
    448 	 * "des_ede3_cbc".
    449 	 */
    450 	real_decode = decode;
    451 	if (strcmp(real_decode, "3des") == 0)
    452 		real_decode = "des-ede3-cbc";
    453 	evp = EVP_get_cipherbyname(real_decode);
    454 
    455 	if (!evp) {
    456 		if (decode != real_decode)
    457 			(*ndo->ndo_warning)(ndo, "failed to find cipher algo %s (%s)\n", real_decode, decode);
    458 		else
    459 			(*ndo->ndo_warning)(ndo, "failed to find cipher algo %s\n", decode);
    460 		sa->evp = NULL;
    461 		sa->authlen = 0;
    462 		sa->ivlen = 0;
    463 		return 0;
    464 	}
    465 
    466 	sa->evp = evp;
    467 	sa->authlen = authlen;
    468 	/* This returns an int, but it should never be negative */
    469 	sa->ivlen = EVP_CIPHER_iv_length(evp);
    470 
    471 	colon++;
    472 	if (colon[0] == '0' && colon[1] == 'x') {
    473 		/* decode some hex! */
    474 
    475 		colon += 2;
    476 		sa->secretlen = espprint_decode_hex(ndo, sa->secret, sizeof(sa->secret), colon);
    477 		if(sa->secretlen == 0) return 0;
    478 	} else {
    479 		i = strlen(colon);
    480 
    481 		if (i < sizeof(sa->secret)) {
    482 			memcpy(sa->secret, colon, i);
    483 			sa->secretlen = i;
    484 		} else {
    485 			memcpy(sa->secret, colon, sizeof(sa->secret));
    486 			sa->secretlen = sizeof(sa->secret);
    487 		}
    488 	}
    489 
    490 	return 1;
    491 }
    492 DIAG_ON_DEPRECATION
    493 
    494 /*
    495  * for the moment, ignore the auth algorithm, just hard code the authenticator
    496  * length. Need to research how openssl looks up HMAC stuff.
    497  */
    498 static int
    499 espprint_decode_authalgo(netdissect_options *ndo,
    500 			 char *decode, struct sa_list *sa)
    501 {
    502 	char *colon;
    503 
    504 	colon = strchr(decode, ':');
    505 	if (colon == NULL) {
    506 		(*ndo->ndo_warning)(ndo, "failed to decode espsecret: %s\n", decode);
    507 		return 0;
    508 	}
    509 	*colon = '\0';
    510 
    511 	if(ascii_strcasecmp(decode,"sha1") == 0 ||
    512 	   ascii_strcasecmp(decode,"md5") == 0) {
    513 		sa->authlen = 12;
    514 	}
    515 	return 1;
    516 }
    517 
    518 static void esp_print_decode_ikeline(netdissect_options *ndo, char *line,
    519 				     const char *file, int lineno)
    520 {
    521 	/* it's an IKEv2 secret, store it instead */
    522 	struct sa_list sa1;
    523 
    524 	char *init;
    525 	char *icookie, *rcookie;
    526 	int   ilen, rlen;
    527 	char *authkey;
    528 	char *enckey;
    529 
    530 	init = strsep(&line, " \t");
    531 	icookie = strsep(&line, " \t");
    532 	rcookie = strsep(&line, " \t");
    533 	authkey = strsep(&line, " \t");
    534 	enckey  = strsep(&line, " \t");
    535 
    536 	/* if any fields are missing */
    537 	if(!init || !icookie || !rcookie || !authkey || !enckey) {
    538 		(*ndo->ndo_warning)(ndo, "print_esp: failed to find all fields for ikev2 at %s:%u",
    539 				    file, lineno);
    540 
    541 		return;
    542 	}
    543 
    544 	ilen = strlen(icookie);
    545 	rlen = strlen(rcookie);
    546 
    547 	if((init[0]!='I' && init[0]!='R')
    548 	   || icookie[0]!='0' || icookie[1]!='x'
    549 	   || rcookie[0]!='0' || rcookie[1]!='x'
    550 	   || ilen!=18
    551 	   || rlen!=18) {
    552 		(*ndo->ndo_warning)(ndo, "print_esp: line %s:%u improperly formatted.",
    553 				    file, lineno);
    554 
    555 		(*ndo->ndo_warning)(ndo, "init=%s icookie=%s(%u) rcookie=%s(%u)",
    556 				    init, icookie, ilen, rcookie, rlen);
    557 
    558 		return;
    559 	}
    560 
    561 	sa1.spi = 0;
    562 	sa1.initiator = (init[0] == 'I');
    563 	if(espprint_decode_hex(ndo, sa1.spii, sizeof(sa1.spii), icookie+2)!=8)
    564 		return;
    565 
    566 	if(espprint_decode_hex(ndo, sa1.spir, sizeof(sa1.spir), rcookie+2)!=8)
    567 		return;
    568 
    569 	if(!espprint_decode_encalgo(ndo, enckey, &sa1)) return;
    570 
    571 	if(!espprint_decode_authalgo(ndo, authkey, &sa1)) return;
    572 
    573 	esp_print_addsa(ndo, &sa1, FALSE);
    574 }
    575 
    576 /*
    577  *
    578  * special form: file /name
    579  * causes us to go read from this file instead.
    580  *
    581  */
    582 static void esp_print_decode_onesecret(netdissect_options *ndo, char *line,
    583 				       const char *file, int lineno)
    584 {
    585 	struct sa_list sa1;
    586 	int sa_def;
    587 
    588 	char *spikey;
    589 	char *decode;
    590 
    591 	spikey = strsep(&line, " \t");
    592 	sa_def = 0;
    593 	memset(&sa1, 0, sizeof(struct sa_list));
    594 
    595 	/* if there is only one token, then it is an algo:key token */
    596 	if (line == NULL) {
    597 		decode = spikey;
    598 		spikey = NULL;
    599 		/* sa1.daddr.version = 0; */
    600 		/* memset(&sa1.daddr, 0, sizeof(sa1.daddr)); */
    601 		/* sa1.spi = 0; */
    602 		sa_def    = 1;
    603 	} else
    604 		decode = line;
    605 
    606 	if (spikey && ascii_strcasecmp(spikey, "file") == 0) {
    607 		/* open file and read it */
    608 		FILE *secretfile;
    609 		char  fileline[1024];
    610 		int   subfile_lineno=0;
    611 		char  *nl;
    612 		char *filename = line;
    613 
    614 		secretfile = fopen(filename, FOPEN_READ_TXT);
    615 		if (secretfile == NULL) {
    616 			(*ndo->ndo_error)(ndo, S_ERR_ND_OPEN_FILE,
    617 					  "%s: can't open %s: %s\n",
    618 					  __func__, filename, strerror(errno));
    619 		}
    620 
    621 		while (fgets(fileline, sizeof(fileline)-1, secretfile) != NULL) {
    622 			subfile_lineno++;
    623 			/* remove newline from the line */
    624 			nl = strchr(fileline, '\n');
    625 			if (nl)
    626 				*nl = '\0';
    627 			if (fileline[0] == '#') continue;
    628 			if (fileline[0] == '\0') continue;
    629 
    630 			esp_print_decode_onesecret(ndo, fileline, filename, subfile_lineno);
    631 		}
    632 		fclose(secretfile);
    633 
    634 		return;
    635 	}
    636 
    637 	if (spikey && ascii_strcasecmp(spikey, "ikev2") == 0) {
    638 		esp_print_decode_ikeline(ndo, line, file, lineno);
    639 		return;
    640 	}
    641 
    642 	if (spikey) {
    643 
    644 		char *spistr, *foo;
    645 		uint32_t spino;
    646 
    647 		spistr = strsep(&spikey, "@");
    648 		if (spistr == NULL) {
    649 			(*ndo->ndo_warning)(ndo, "print_esp: failed to find the @ token");
    650 			return;
    651 		}
    652 
    653 		spino = strtoul(spistr, &foo, 0);
    654 		if (spistr == foo || !spikey) {
    655 			(*ndo->ndo_warning)(ndo, "print_esp: failed to decode spi# %s\n", foo);
    656 			return;
    657 		}
    658 
    659 		sa1.spi = spino;
    660 
    661 		if (strtoaddr6(spikey, &sa1.daddr.in6) == 1) {
    662 			sa1.daddr_version = 6;
    663 		} else if (strtoaddr(spikey, &sa1.daddr.in4) == 1) {
    664 			sa1.daddr_version = 4;
    665 		} else {
    666 			(*ndo->ndo_warning)(ndo, "print_esp: can not decode IP# %s\n", spikey);
    667 			return;
    668 		}
    669 	}
    670 
    671 	if (decode) {
    672 		/* skip any blank spaces */
    673 		while (*decode == ' ' || *decode == '\t' || *decode == '\r' || *decode == '\n')
    674 			decode++;
    675 
    676 		if(!espprint_decode_encalgo(ndo, decode, &sa1)) {
    677 			return;
    678 		}
    679 	}
    680 
    681 	esp_print_addsa(ndo, &sa1, sa_def);
    682 }
    683 
    684 DIAG_OFF_DEPRECATION
    685 static void esp_init(netdissect_options *ndo _U_)
    686 {
    687 	/*
    688 	 * 0.9.6 doesn't appear to define OPENSSL_API_COMPAT, so
    689 	 * we check whether it's undefined or it's less than the
    690 	 * value for 1.1.0.
    691 	 */
    692 #if !defined(OPENSSL_API_COMPAT) || OPENSSL_API_COMPAT < 0x10100000L
    693 	OpenSSL_add_all_algorithms();
    694 #endif
    695 }
    696 DIAG_ON_DEPRECATION
    697 
    698 void esp_decodesecret_print(netdissect_options *ndo)
    699 {
    700 	char *line;
    701 	char *p;
    702 	static int initialized = 0;
    703 
    704 	if (!initialized) {
    705 		esp_init(ndo);
    706 		initialized = 1;
    707 	}
    708 
    709 	p = ndo->ndo_espsecret;
    710 
    711 	while (p && p[0] != '\0') {
    712 		/* pick out the first line or first thing until a comma */
    713 		if ((line = strsep(&p, "\n,")) == NULL) {
    714 			line = p;
    715 			p = NULL;
    716 		}
    717 
    718 		esp_print_decode_onesecret(ndo, line, "cmdline", 0);
    719 	}
    720 
    721 	ndo->ndo_espsecret = NULL;
    722 }
    723 
    724 #endif
    725 
    726 #ifdef HAVE_LIBCRYPTO
    727 #define USED_IF_LIBCRYPTO
    728 #else
    729 #define USED_IF_LIBCRYPTO _U_
    730 #endif
    731 
    732 #ifdef HAVE_LIBCRYPTO
    733 DIAG_OFF_DEPRECATION
    734 #endif
    735 void
    736 esp_print(netdissect_options *ndo,
    737 	  const u_char *bp, u_int length,
    738 	  const u_char *bp2 USED_IF_LIBCRYPTO,
    739 	  u_int ver USED_IF_LIBCRYPTO,
    740 	  int fragmented USED_IF_LIBCRYPTO,
    741 	  u_int ttl_hl USED_IF_LIBCRYPTO)
    742 {
    743 	const struct newesp *esp;
    744 	const u_char *ep;
    745 #ifdef HAVE_LIBCRYPTO
    746 	const struct ip *ip;
    747 	struct sa_list *sa = NULL;
    748 	const struct ip6_hdr *ip6 = NULL;
    749 	const u_char *iv;
    750 	u_int ivlen;
    751 	u_int payloadlen;
    752 	const u_char *ct;
    753 	u_char *pt;
    754 	u_int padlen;
    755 	u_int nh;
    756 #endif
    757 
    758 	ndo->ndo_protocol = "esp";
    759 	esp = (const struct newesp *)bp;
    760 
    761 	/* 'ep' points to the end of available data. */
    762 	ep = ndo->ndo_snapend;
    763 
    764 	if ((const u_char *)(esp + 1) >= ep) {
    765 		nd_print_trunc(ndo);
    766 		return;
    767 	}
    768 	ND_PRINT("ESP(spi=0x%08x", GET_BE_U_4(esp->esp_spi));
    769 	ND_PRINT(",seq=0x%x)", GET_BE_U_4(esp->esp_seq));
    770 	ND_PRINT(", length %u", length);
    771 
    772 #ifdef HAVE_LIBCRYPTO
    773 	/* initialize SAs */
    774 	if (ndo->ndo_sa_list_head == NULL) {
    775 		if (!ndo->ndo_espsecret)
    776 			return;
    777 
    778 		esp_decodesecret_print(ndo);
    779 	}
    780 
    781 	if (ndo->ndo_sa_list_head == NULL)
    782 		return;
    783 
    784 	ip = (const struct ip *)bp2;
    785 	switch (ver) {
    786 	case 6:
    787 		ip6 = (const struct ip6_hdr *)bp2;
    788 		/* we do not attempt to decrypt jumbograms */
    789 		if (!GET_BE_U_2(ip6->ip6_plen))
    790 			return;
    791 		/* XXX - check whether it's fragmented? */
    792 		/* if we can't get nexthdr, we do not need to decrypt it */
    793 
    794 		/* see if we can find the SA, and if so, decode it */
    795 		for (sa = ndo->ndo_sa_list_head; sa != NULL; sa = sa->next) {
    796 			if (sa->spi == GET_BE_U_4(esp->esp_spi) &&
    797 			    sa->daddr_version == 6 &&
    798 			    UNALIGNED_MEMCMP(&sa->daddr.in6, &ip6->ip6_dst,
    799 				   sizeof(nd_ipv6)) == 0) {
    800 				break;
    801 			}
    802 		}
    803 		break;
    804 	case 4:
    805 		/* nexthdr & padding are in the last fragment */
    806 		if (fragmented)
    807 			return;
    808 
    809 		/* see if we can find the SA, and if so, decode it */
    810 		for (sa = ndo->ndo_sa_list_head; sa != NULL; sa = sa->next) {
    811 			if (sa->spi == GET_BE_U_4(esp->esp_spi) &&
    812 			    sa->daddr_version == 4 &&
    813 			    UNALIGNED_MEMCMP(&sa->daddr.in4, &ip->ip_dst,
    814 				   sizeof(nd_ipv4)) == 0) {
    815 				break;
    816 			}
    817 		}
    818 		break;
    819 	default:
    820 		return;
    821 	}
    822 
    823 	/* if we didn't find the specific one, then look for
    824 	 * an unspecified one.
    825 	 */
    826 	if (sa == NULL)
    827 		sa = ndo->ndo_sa_default;
    828 
    829 	/* if not found fail */
    830 	if (sa == NULL)
    831 		return;
    832 
    833 	/* pointer to the IV, if there is one */
    834 	iv = (const u_char *)(esp + 1) + 0;
    835 	/* length of the IV, if there is one; 0, if there isn't */
    836 	ivlen = sa->ivlen;
    837 
    838 	/*
    839 	 * Get a pointer to the ciphertext.
    840 	 *
    841 	 * p points to the beginning of the payload, i.e. to the
    842 	 * initialization vector, so if we skip past the initialization
    843 	 * vector, it points to the beginning of the ciphertext.
    844 	 */
    845 	ct = iv + ivlen;
    846 
    847 	/*
    848 	 * Make sure the authentication data/integrity check value length
    849 	 * isn't bigger than the total amount of data available after
    850 	 * the ESP header and initialization vector is removed and,
    851 	 * if not, slice the authentication data/ICV off.
    852 	 */
    853 	if (ep - ct < sa->authlen) {
    854 		nd_print_trunc(ndo);
    855 		return;
    856 	}
    857 	ep = ep - sa->authlen;
    858 
    859 	/*
    860 	 * Calculate the length of the ciphertext.  ep points to
    861 	 * the beginning of the authentication data/integrity check
    862 	 * value, i.e. right past the end of the ciphertext;
    863 	 */
    864 	payloadlen = ep - ct;
    865 
    866 	if (sa->evp == NULL)
    867 		return;
    868 
    869 	/*
    870 	 * If the next header value is past the end of the available
    871 	 * data, we won't be able to fetch it once we've decrypted
    872 	 * the ciphertext, so there's no point in decrypting the data.
    873 	 *
    874 	 * Report it as truncation.
    875 	 */
    876 	if (!ND_TTEST_1(ep - 1)) {
    877 		nd_print_trunc(ndo);
    878 		return;
    879 	}
    880 
    881 	pt = do_decrypt(ndo, __func__, sa, iv, ct, payloadlen);
    882 	if (pt == NULL)
    883 		return;
    884 
    885 	/*
    886 	 * Switch to the output buffer for dissection, and
    887 	 * save it on the buffer stack so it can be freed.
    888 	 */
    889 	if (!nd_push_buffer(ndo, pt, pt, payloadlen)) {
    890 		free(pt);
    891 		(*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
    892 			"%s: can't push buffer on buffer stack", __func__);
    893 	}
    894 
    895 	/*
    896 	 * Sanity check for pad length; if it, plus 2 for the pad
    897 	 * length and next header fields, is bigger than the ciphertext
    898 	 * length (which is also the plaintext length), it's too big.
    899 	 *
    900 	 * XXX - the check can fail if the packet is corrupt *or* if
    901 	 * it was not decrypted with the correct key, so that the
    902 	 * "plaintext" is not what was being sent.
    903 	 */
    904 	padlen = GET_U_1(pt + payloadlen - 2);
    905 	if (padlen + 2 > payloadlen) {
    906 		nd_print_trunc(ndo);
    907 		return;
    908 	}
    909 
    910 	/* Get the next header */
    911 	nh = GET_U_1(pt + payloadlen - 1);
    912 
    913 	ND_PRINT(": ");
    914 
    915 	/*
    916 	 * Don't put padding + padding length(1 byte) + next header(1 byte)
    917 	 * in the buffer because they are not part of the plaintext to decode.
    918 	 */
    919 	if (!nd_push_snaplen(ndo, pt, payloadlen - (padlen + 2))) {
    920 		(*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
    921 			"%s: can't push snaplen on buffer stack", __func__);
    922 	}
    923 
    924 	/* Now dissect the plaintext. */
    925 	ip_demux_print(ndo, pt, payloadlen - (padlen + 2), ver, fragmented,
    926 		       ttl_hl, nh, bp2);
    927 
    928 	/* Pop the buffer, freeing it. */
    929 	nd_pop_packet_info(ndo);
    930 	/* Pop the nd_push_snaplen */
    931 	nd_pop_packet_info(ndo);
    932 #endif
    933 }
    934 #ifdef HAVE_LIBCRYPTO
    935 DIAG_ON_DEPRECATION
    936 #endif
    937