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