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