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