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