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