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