]> The Tcpdump Group git mirrors - tcpdump/blob - print-esp.c
Merge pull request #703 from nmap/update-gitignore
[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 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 oin 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 set_cipher_parameters(ctx, NULL, NULL, iv, 0);
230 /*
231 * Allocate buffers for the encrypted and decrypted data.
232 * Both buffers' sizes must be a multiple of the cipher block
233 * size, and the output buffer must be separate from the input
234 * buffer.
235 */
236 block_size = (unsigned int)EVP_CIPHER_CTX_block_size(ctx);
237 buffer_size = len + (block_size - len % block_size);
238
239 /*
240 * Attempt to allocate the input buffer.
241 */
242 input_buffer = (u_char *)malloc(buffer_size);
243 if (input_buffer == NULL) {
244 EVP_CIPHER_CTX_free(ctx);
245 (*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
246 "can't allocate memory for encrypted data buffer");
247 }
248 /*
249 * Copy the input data to the encrypted data buffer, and pad it
250 * with zeroes.
251 */
252 memcpy(input_buffer, buf, len);
253 memset(input_buffer + len, 0, buffer_size - len);
254
255 /*
256 * Attempt to allocate the output buffer.
257 */
258 output_buffer = (u_char *)malloc(buffer_size);
259 if (output_buffer == NULL) {
260 free(input_buffer);
261 EVP_CIPHER_CTX_free(ctx);
262 (*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
263 "can't allocate memory for decryption buffer");
264 }
265 EVP_Cipher(ctx, output_buffer, input_buffer, len);
266 EVP_CIPHER_CTX_free(ctx);
267
268 /*
269 * XXX - of course this is wrong, because buf is a const buffer,
270 * but changing this would require a more complicated fix.
271 */
272 memcpy(buf, output_buffer, len);
273 free(input_buffer);
274 free(output_buffer);
275
276 ndo->ndo_packetp = buf;
277 ndo->ndo_snapend = end;
278
279 return 1;
280 }
281 USES_APPLE_RST
282
283 static void esp_print_addsa(netdissect_options *ndo,
284 struct sa_list *sa, int sa_def)
285 {
286 /* copy the "sa" */
287
288 struct sa_list *nsa;
289
290 /* malloc() return used in a 'struct sa_list': do not free() */
291 nsa = (struct sa_list *)malloc(sizeof(struct sa_list));
292 if (nsa == NULL)
293 (*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
294 "esp_print_addsa: malloc");
295
296 *nsa = *sa;
297
298 if (sa_def)
299 ndo->ndo_sa_default = nsa;
300
301 nsa->next = ndo->ndo_sa_list_head;
302 ndo->ndo_sa_list_head = nsa;
303 }
304
305
306 static u_int hexdigit(netdissect_options *ndo, char hex)
307 {
308 if (hex >= '0' && hex <= '9')
309 return (hex - '0');
310 else if (hex >= 'A' && hex <= 'F')
311 return (hex - 'A' + 10);
312 else if (hex >= 'a' && hex <= 'f')
313 return (hex - 'a' + 10);
314 else {
315 (*ndo->ndo_error)(ndo, S_ERR_ND_ESP_SECRET,
316 "invalid hex digit %c in espsecret\n", hex);
317 }
318 }
319
320 static u_int hex2byte(netdissect_options *ndo, char *hexstring)
321 {
322 u_int byte;
323
324 byte = (hexdigit(ndo, hexstring[0]) << 4) + hexdigit(ndo, hexstring[1]);
325 return byte;
326 }
327
328 /*
329 * returns size of binary, 0 on failure.
330 */
331 static
332 int espprint_decode_hex(netdissect_options *ndo,
333 u_char *binbuf, unsigned int binbuf_len,
334 char *hex)
335 {
336 unsigned int len;
337 int i;
338
339 len = strlen(hex) / 2;
340
341 if (len > binbuf_len) {
342 (*ndo->ndo_warning)(ndo, "secret is too big: %u\n", len);
343 return 0;
344 }
345
346 i = 0;
347 while (hex[0] != '\0' && hex[1]!='\0') {
348 binbuf[i] = hex2byte(ndo, hex);
349 hex += 2;
350 i++;
351 }
352
353 return i;
354 }
355
356 /*
357 * decode the form: SPINUM@IP <tab> ALGONAME:0xsecret
358 */
359
360 USES_APPLE_DEPRECATED_API
361 static int
362 espprint_decode_encalgo(netdissect_options *ndo,
363 char *decode, struct sa_list *sa)
364 {
365 size_t i;
366 const EVP_CIPHER *evp;
367 int authlen = 0;
368 char *colon, *p;
369
370 colon = strchr(decode, ':');
371 if (colon == NULL) {
372 (*ndo->ndo_warning)(ndo, "failed to decode espsecret: %s\n", decode);
373 return 0;
374 }
375 *colon = '\0';
376
377 if (strlen(decode) > strlen("-hmac96") &&
378 !strcmp(decode + strlen(decode) - strlen("-hmac96"),
379 "-hmac96")) {
380 p = strstr(decode, "-hmac96");
381 *p = '\0';
382 authlen = 12;
383 }
384 if (strlen(decode) > strlen("-cbc") &&
385 !strcmp(decode + strlen(decode) - strlen("-cbc"), "-cbc")) {
386 p = strstr(decode, "-cbc");
387 *p = '\0';
388 }
389 evp = EVP_get_cipherbyname(decode);
390
391 if (!evp) {
392 (*ndo->ndo_warning)(ndo, "failed to find cipher algo %s\n", decode);
393 sa->evp = NULL;
394 sa->authlen = 0;
395 sa->ivlen = 0;
396 return 0;
397 }
398
399 sa->evp = evp;
400 sa->authlen = authlen;
401 sa->ivlen = EVP_CIPHER_iv_length(evp);
402
403 colon++;
404 if (colon[0] == '0' && colon[1] == 'x') {
405 /* decode some hex! */
406
407 colon += 2;
408 sa->secretlen = espprint_decode_hex(ndo, sa->secret, sizeof(sa->secret), colon);
409 if(sa->secretlen == 0) return 0;
410 } else {
411 i = strlen(colon);
412
413 if (i < sizeof(sa->secret)) {
414 memcpy(sa->secret, colon, i);
415 sa->secretlen = i;
416 } else {
417 memcpy(sa->secret, colon, sizeof(sa->secret));
418 sa->secretlen = sizeof(sa->secret);
419 }
420 }
421
422 return 1;
423 }
424 USES_APPLE_RST
425
426 /*
427 * for the moment, ignore the auth algorithm, just hard code the authenticator
428 * length. Need to research how openssl looks up HMAC stuff.
429 */
430 static int
431 espprint_decode_authalgo(netdissect_options *ndo,
432 char *decode, struct sa_list *sa)
433 {
434 char *colon;
435
436 colon = strchr(decode, ':');
437 if (colon == NULL) {
438 (*ndo->ndo_warning)(ndo, "failed to decode espsecret: %s\n", decode);
439 return 0;
440 }
441 *colon = '\0';
442
443 if(ascii_strcasecmp(colon,"sha1") == 0 ||
444 ascii_strcasecmp(colon,"md5") == 0) {
445 sa->authlen = 12;
446 }
447 return 1;
448 }
449
450 static void esp_print_decode_ikeline(netdissect_options *ndo, char *line,
451 const char *file, int lineno)
452 {
453 /* it's an IKEv2 secret, store it instead */
454 struct sa_list sa1;
455
456 char *init;
457 char *icookie, *rcookie;
458 int ilen, rlen;
459 char *authkey;
460 char *enckey;
461
462 init = strsep(&line, " \t");
463 icookie = strsep(&line, " \t");
464 rcookie = strsep(&line, " \t");
465 authkey = strsep(&line, " \t");
466 enckey = strsep(&line, " \t");
467
468 /* if any fields are missing */
469 if(!init || !icookie || !rcookie || !authkey || !enckey) {
470 (*ndo->ndo_warning)(ndo, "print_esp: failed to find all fields for ikev2 at %s:%u",
471 file, lineno);
472
473 return;
474 }
475
476 ilen = strlen(icookie);
477 rlen = strlen(rcookie);
478
479 if((init[0]!='I' && init[0]!='R')
480 || icookie[0]!='0' || icookie[1]!='x'
481 || rcookie[0]!='0' || rcookie[1]!='x'
482 || ilen!=18
483 || rlen!=18) {
484 (*ndo->ndo_warning)(ndo, "print_esp: line %s:%u improperly formatted.",
485 file, lineno);
486
487 (*ndo->ndo_warning)(ndo, "init=%s icookie=%s(%u) rcookie=%s(%u)",
488 init, icookie, ilen, rcookie, rlen);
489
490 return;
491 }
492
493 sa1.spi = 0;
494 sa1.initiator = (init[0] == 'I');
495 if(espprint_decode_hex(ndo, sa1.spii, sizeof(sa1.spii), icookie+2)!=8)
496 return;
497
498 if(espprint_decode_hex(ndo, sa1.spir, sizeof(sa1.spir), rcookie+2)!=8)
499 return;
500
501 if(!espprint_decode_encalgo(ndo, enckey, &sa1)) return;
502
503 if(!espprint_decode_authalgo(ndo, authkey, &sa1)) return;
504
505 esp_print_addsa(ndo, &sa1, FALSE);
506 }
507
508 /*
509 *
510 * special form: file /name
511 * causes us to go read from this file instead.
512 *
513 */
514 static void esp_print_decode_onesecret(netdissect_options *ndo, char *line,
515 const char *file, int lineno)
516 {
517 struct sa_list sa1;
518 int sa_def;
519
520 char *spikey;
521 char *decode;
522
523 spikey = strsep(&line, " \t");
524 sa_def = 0;
525 memset(&sa1, 0, sizeof(struct sa_list));
526
527 /* if there is only one token, then it is an algo:key token */
528 if (line == NULL) {
529 decode = spikey;
530 spikey = NULL;
531 /* sa1.daddr.version = 0; */
532 /* memset(&sa1.daddr, 0, sizeof(sa1.daddr)); */
533 /* sa1.spi = 0; */
534 sa_def = 1;
535 } else
536 decode = line;
537
538 if (spikey && ascii_strcasecmp(spikey, "file") == 0) {
539 /* open file and read it */
540 FILE *secretfile;
541 char fileline[1024];
542 int subfile_lineno=0;
543 char *nl;
544 char *filename = line;
545
546 secretfile = fopen(filename, FOPEN_READ_TXT);
547 if (secretfile == NULL) {
548 (*ndo->ndo_error)(ndo, S_ERR_ND_OPEN_FILE,
549 "print_esp: can't open %s: %s\n",
550 filename, strerror(errno));
551 }
552
553 while (fgets(fileline, sizeof(fileline)-1, secretfile) != NULL) {
554 subfile_lineno++;
555 /* remove newline from the line */
556 nl = strchr(fileline, '\n');
557 if (nl)
558 *nl = '\0';
559 if (fileline[0] == '#') continue;
560 if (fileline[0] == '\0') continue;
561
562 esp_print_decode_onesecret(ndo, fileline, filename, subfile_lineno);
563 }
564 fclose(secretfile);
565
566 return;
567 }
568
569 if (spikey && ascii_strcasecmp(spikey, "ikev2") == 0) {
570 esp_print_decode_ikeline(ndo, line, file, lineno);
571 return;
572 }
573
574 if (spikey) {
575
576 char *spistr, *foo;
577 uint32_t spino;
578
579 spistr = strsep(&spikey, "@");
580 if (spistr == NULL) {
581 (*ndo->ndo_warning)(ndo, "print_esp: failed to find the @ token");
582 return;
583 }
584
585 spino = strtoul(spistr, &foo, 0);
586 if (spistr == foo || !spikey) {
587 (*ndo->ndo_warning)(ndo, "print_esp: failed to decode spi# %s\n", foo);
588 return;
589 }
590
591 sa1.spi = spino;
592
593 if (strtoaddr6(spikey, &sa1.daddr.in6) == 1) {
594 sa1.daddr_version = 6;
595 } else if (strtoaddr(spikey, &sa1.daddr.in4) == 1) {
596 sa1.daddr_version = 4;
597 } else {
598 (*ndo->ndo_warning)(ndo, "print_esp: can not decode IP# %s\n", spikey);
599 return;
600 }
601 }
602
603 if (decode) {
604 /* skip any blank spaces */
605 while (isspace((unsigned char)*decode))
606 decode++;
607
608 if(!espprint_decode_encalgo(ndo, decode, &sa1)) {
609 return;
610 }
611 }
612
613 esp_print_addsa(ndo, &sa1, sa_def);
614 }
615
616 USES_APPLE_DEPRECATED_API
617 static void esp_init(netdissect_options *ndo _U_)
618 {
619 /*
620 * 0.9.6 doesn't appear to define OPENSSL_API_COMPAT, so
621 * we check whether it's undefined or it's less than the
622 * value for 1.1.0.
623 */
624 #if !defined(OPENSSL_API_COMPAT) || OPENSSL_API_COMPAT < 0x10100000L
625 OpenSSL_add_all_algorithms();
626 #endif
627 EVP_add_cipher_alias(SN_des_ede3_cbc, "3des");
628 }
629 USES_APPLE_RST
630
631 void esp_print_decodesecret(netdissect_options *ndo)
632 {
633 char *line;
634 char *p;
635 static int initialized = 0;
636
637 if (!initialized) {
638 esp_init(ndo);
639 initialized = 1;
640 }
641
642 p = ndo->ndo_espsecret;
643
644 while (p && p[0] != '\0') {
645 /* pick out the first line or first thing until a comma */
646 if ((line = strsep(&p, "\n,")) == NULL) {
647 line = p;
648 p = NULL;
649 }
650
651 esp_print_decode_onesecret(ndo, line, "cmdline", 0);
652 }
653
654 ndo->ndo_espsecret = NULL;
655 }
656
657 #endif
658
659 #ifdef HAVE_LIBCRYPTO
660 USES_APPLE_DEPRECATED_API
661 #endif
662 int
663 esp_print(netdissect_options *ndo,
664 const u_char *bp, const int length, const u_char *bp2
665 #ifndef HAVE_LIBCRYPTO
666 _U_
667 #endif
668 ,
669 u_int *nhdr
670 #ifndef HAVE_LIBCRYPTO
671 _U_
672 #endif
673 ,
674 u_int *padlen
675 #ifndef HAVE_LIBCRYPTO
676 _U_
677 #endif
678 )
679 {
680 const struct newesp *esp;
681 const u_char *ep;
682 #ifdef HAVE_LIBCRYPTO
683 const struct ip *ip;
684 struct sa_list *sa = NULL;
685 const struct ip6_hdr *ip6 = NULL;
686 int advance;
687 int len;
688 u_char *secret;
689 int ivlen = 0;
690 const u_char *ivoff;
691 const u_char *p;
692 EVP_CIPHER_CTX *ctx;
693 unsigned int block_size, buffer_size;
694 u_char *input_buffer, *output_buffer;
695 #endif
696
697 ndo->ndo_protocol = "esp";
698 esp = (const struct newesp *)bp;
699
700 #ifdef HAVE_LIBCRYPTO
701 secret = NULL;
702 advance = 0;
703 #endif
704
705 #if 0
706 /* keep secret out of a register */
707 p = (u_char *)&secret;
708 #endif
709
710 /* 'ep' points to the end of available data. */
711 ep = ndo->ndo_snapend;
712
713 if ((const u_char *)(esp + 1) >= ep) {
714 nd_print_trunc(ndo);
715 goto fail;
716 }
717 ND_PRINT("ESP(spi=0x%08x", EXTRACT_BE_U_4(esp->esp_spi));
718 ND_PRINT(",seq=0x%x)", EXTRACT_BE_U_4(esp->esp_seq));
719 ND_PRINT(", length %u", length);
720
721 #ifndef HAVE_LIBCRYPTO
722 goto fail;
723 #else
724 /* initiailize SAs */
725 if (ndo->ndo_sa_list_head == NULL) {
726 if (!ndo->ndo_espsecret)
727 goto fail;
728
729 esp_print_decodesecret(ndo);
730 }
731
732 if (ndo->ndo_sa_list_head == NULL)
733 goto fail;
734
735 ip = (const struct ip *)bp2;
736 switch (IP_V(ip)) {
737 case 6:
738 ip6 = (const struct ip6_hdr *)bp2;
739 /* we do not attempt to decrypt jumbograms */
740 if (!EXTRACT_BE_U_2(ip6->ip6_plen))
741 goto fail;
742 /* if we can't get nexthdr, we do not need to decrypt it */
743 len = sizeof(struct ip6_hdr) + EXTRACT_BE_U_2(ip6->ip6_plen);
744
745 /* see if we can find the SA, and if so, decode it */
746 for (sa = ndo->ndo_sa_list_head; sa != NULL; sa = sa->next) {
747 if (sa->spi == EXTRACT_BE_U_4(esp->esp_spi) &&
748 sa->daddr_version == 6 &&
749 UNALIGNED_MEMCMP(&sa->daddr.in6, &ip6->ip6_dst,
750 sizeof(nd_ipv6)) == 0) {
751 break;
752 }
753 }
754 break;
755 case 4:
756 /* nexthdr & padding are in the last fragment */
757 if (EXTRACT_BE_U_2(ip->ip_off) & IP_MF)
758 goto fail;
759 len = EXTRACT_BE_U_2(ip->ip_len);
760
761 /* see if we can find the SA, and if so, decode it */
762 for (sa = ndo->ndo_sa_list_head; sa != NULL; sa = sa->next) {
763 if (sa->spi == EXTRACT_BE_U_4(esp->esp_spi) &&
764 sa->daddr_version == 4 &&
765 UNALIGNED_MEMCMP(&sa->daddr.in4, &ip->ip_dst,
766 sizeof(nd_ipv4)) == 0) {
767 break;
768 }
769 }
770 break;
771 default:
772 goto fail;
773 }
774
775 /* if we didn't find the specific one, then look for
776 * an unspecified one.
777 */
778 if (sa == NULL)
779 sa = ndo->ndo_sa_default;
780
781 /* if not found fail */
782 if (sa == NULL)
783 goto fail;
784
785 /* if we can't get nexthdr, we do not need to decrypt it */
786 if (ep - bp2 < len)
787 goto fail;
788 if (ep - bp2 > len) {
789 /* FCS included at end of frame (NetBSD 1.6 or later) */
790 ep = bp2 + len;
791 }
792
793 /* pointer to the IV, if there is one */
794 ivoff = (const u_char *)(esp + 1) + 0;
795 /* length of the IV, if there is one; 0, if there isn't */
796 ivlen = sa->ivlen;
797 secret = sa->secret;
798 ep = ep - sa->authlen;
799
800 if (sa->evp) {
801 ctx = EVP_CIPHER_CTX_new();
802 if (ctx != NULL) {
803 if (set_cipher_parameters(ctx, sa->evp, secret, NULL, 0) < 0)
804 (*ndo->ndo_warning)(ndo, "espkey init failed");
805
806 p = ivoff;
807 set_cipher_parameters(ctx, NULL, NULL, p, 0);
808 len = ep - (p + ivlen);
809
810 /*
811 * Allocate buffers for the encrypted and decrypted
812 * data. Both buffers' sizes must be a multiple of
813 * the cipher block size, and the output buffer must
814 * be separate from the input buffer.
815 */
816 block_size = (unsigned int)EVP_CIPHER_CTX_block_size(ctx);
817 buffer_size = len + (block_size - len % block_size);
818
819 /*
820 * Attempt to allocate the input buffer.
821 */
822 input_buffer = (u_char *)malloc(buffer_size);
823 if (input_buffer == NULL) {
824 EVP_CIPHER_CTX_free(ctx);
825 (*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
826 "esp_print: can't allocate memory for encrypted data buffer");
827 }
828 /*
829 * Copy the input data to the encrypted data buffer,
830 * and pad it with zeroes.
831 */
832 memcpy(input_buffer, p + ivlen, len);
833 memset(input_buffer + len, 0, buffer_size - len);
834
835 /*
836 * Attempt to allocate the output buffer.
837 */
838 output_buffer = (u_char *)malloc(buffer_size);
839 if (output_buffer == NULL) {
840 free(input_buffer);
841 EVP_CIPHER_CTX_free(ctx);
842 (*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
843 "esp_print: can't allocate memory for decryption buffer");
844 }
845
846 EVP_Cipher(ctx, output_buffer, input_buffer, len);
847 free(input_buffer);
848 EVP_CIPHER_CTX_free(ctx);
849 /*
850 * XXX - of course this is wrong, because buf is a
851 * const buffer, but changing this would require a
852 * more complicated fix.
853 */
854 memcpy(p + ivlen, output_buffer, len);
855 free(output_buffer);
856 advance = ivoff - (const u_char *)esp + ivlen;
857 } else
858 advance = sizeof(struct newesp);
859 } else
860 advance = sizeof(struct newesp);
861
862 /* sanity check for pad length */
863 if (ep - bp < EXTRACT_U_1(ep - 2))
864 goto fail;
865
866 if (padlen)
867 *padlen = EXTRACT_U_1(ep - 2) + 2;
868
869 if (nhdr)
870 *nhdr = EXTRACT_U_1(ep - 1);
871
872 ND_PRINT(": ");
873 return advance;
874 #endif
875
876 fail:
877 return -1;
878 }
879 #ifdef HAVE_LIBCRYPTO
880 USES_APPLE_RST
881 #endif