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