Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
/*	$NetBSD: ipsec_output.c,v 1.86 2023/01/27 09:33:43 ozaki-r Exp $	*/

/*
 * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: sys/netipsec/ipsec_output.c,v 1.3.2.2 2003/03/28 20:32:53 sam Exp $
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: ipsec_output.c,v 1.86 2023/01/27 09:33:43 ozaki-r Exp $");

#if defined(_KERNEL_OPT)
#include "opt_inet.h"
#include "opt_net_mpsafe.h"
#endif

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/domain.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <sys/syslog.h>

#include <net/if.h>
#include <net/route.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/in_var.h>
#include <netinet/ip_ecn.h>

#include <netinet/ip6.h>
#ifdef INET6
#include <netinet6/ip6_var.h>
#endif
#include <netinet/in_pcb.h>
#ifdef INET6
#include <netinet/icmp6.h>
#endif
#include <netinet/udp.h>

#include <netipsec/ipsec.h>
#include <netipsec/ipsec_var.h>
#include <netipsec/ipsec_private.h>
#ifdef INET6
#include <netipsec/ipsec6.h>
#endif
#include <netipsec/ah_var.h>
#include <netipsec/esp_var.h>
#include <netipsec/ipcomp_var.h>

#include <netipsec/xform.h>

#include <netipsec/key.h>
#include <netipsec/keydb.h>
#include <netipsec/key_debug.h>

static percpu_t *ipsec_rtcache_percpu __cacheline_aligned;

/*
 * Add a IPSEC_OUT_DONE tag to mark that we have finished the ipsec processing
 * It will be used by ip{,6}_output to check if we have already or not
 * processed this packet.
 */
static int
ipsec_register_done(struct mbuf *m, int *error)
{
	struct m_tag *mtag;

	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE, 0, M_NOWAIT);
	if (mtag == NULL) {
		IPSECLOG(LOG_DEBUG, "could not get packet tag\n");
		*error = ENOMEM;
		return -1;
	}

	m_tag_prepend(m, mtag);
	return 0;
}

static int
ipsec_reinject_ipstack(struct mbuf *m, int af, int flags)
{
	int rv = -1;
	struct route *ro;

	KASSERT(af == AF_INET || af == AF_INET6);

	KERNEL_LOCK_UNLESS_NET_MPSAFE();
	ro = rtcache_percpu_getref(ipsec_rtcache_percpu);
	switch (af) {
#ifdef INET
	case AF_INET:
		rv = ip_output(m, NULL, ro, IP_RAWOUTPUT|IP_NOIPNEWID,
		    NULL, NULL);
		break;
#endif
#ifdef INET6
	case AF_INET6:
		/*
		 * We don't need massage, IPv6 header fields are always in
		 * net endian.
		 */
		rv = ip6_output(m, NULL, ro, flags, NULL, NULL, NULL);
		break;
#endif
	}
	rtcache_percpu_putref(ipsec_rtcache_percpu);
	KERNEL_UNLOCK_UNLESS_NET_MPSAFE();

	return rv;
}

int
ipsec_process_done(struct mbuf *m, const struct ipsecrequest *isr,
    struct secasvar *sav, int flags)
{
	struct secasindex *saidx;
	int error;
#ifdef INET
	struct ip *ip;
#endif
#ifdef INET6
	struct ip6_hdr *ip6;
#endif
	struct mbuf *mo;
	struct udphdr *udp = NULL;
	int hlen, roff, iphlen;

	KASSERT(m != NULL);
	KASSERT(isr != NULL);
	KASSERT(sav != NULL);

	saidx = &sav->sah->saidx;

	if (sav->natt_type != 0) {
		hlen = sizeof(struct udphdr);

		switch (saidx->dst.sa.sa_family) {
#ifdef INET
		case AF_INET:
			ip = mtod(m, struct ip *);
			mo = m_makespace(m, sizeof(struct ip), hlen, &roff);
			iphlen = ip->ip_hl << 2;
			break;
#endif
#ifdef INET6
		case AF_INET6:
			ip6 = mtod(m, struct ip6_hdr *);
			mo = m_makespace(m, sizeof(struct ip6_hdr), hlen, &roff);
			iphlen = sizeof(*ip6);
			break;
#endif
		default:
			IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
			    saidx->dst.sa.sa_family);
			error = ENXIO;
			goto bad;
		}

		if (mo == NULL) {
			char buf[IPSEC_ADDRSTRLEN];
			IPSECLOG(LOG_DEBUG,
			    "failed to inject %u byte UDP for SA %s/%08lx\n",
			    hlen, ipsec_address(&saidx->dst, buf, sizeof(buf)),
			    (u_long)ntohl(sav->spi));
			error = ENOBUFS;
			goto bad;
		}

		udp = (struct udphdr *)(mtod(mo, char *) + roff);
		udp->uh_sport = key_portfromsaddr(&saidx->src);
		udp->uh_dport = key_portfromsaddr(&saidx->dst);
		udp->uh_sum = 0;
		udp->uh_ulen = htons(m->m_pkthdr.len - iphlen);
	}

	/*
	 * Fix the header length, for AH processing.
	 */
	switch (saidx->dst.sa.sa_family) {
#ifdef INET
	case AF_INET:
		ip = mtod(m, struct ip *);
		ip->ip_len = htons(m->m_pkthdr.len);
		/* IPv4 packet does not have to be set UDP checksum. */
		if (sav->natt_type != 0)
			ip->ip_p = IPPROTO_UDP;
		break;
#endif
#ifdef INET6
	case AF_INET6:
		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
			error = ENXIO;
			goto bad;
		}
		if (m->m_pkthdr.len - sizeof(struct ip6_hdr) > IPV6_MAXPACKET) {
			/* No jumbogram support. */
			error = ENXIO;	/*?*/
			goto bad;
		}
		ip6 = mtod(m, struct ip6_hdr *);
		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
		/* IPv6 packet should be set UDP checksum. */
		if (sav->natt_type != 0) {
			ip6->ip6_nxt = IPPROTO_UDP;
			ipsec6_udp_cksum(m);
		}
		break;
#endif
	default:
		IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
		    saidx->dst.sa.sa_family);
		error = ENXIO;
		goto bad;
	}

	key_sa_recordxfer(sav, m);

	/*
	 * If there's another (bundled) SA to apply, do so.
	 * Note that this puts a burden on the kernel stack size.
	 * If this is a problem we'll need to introduce a queue
	 * to set the packet on so we can unwind the stack before
	 * doing further processing.
	 */
	if (isr->next) {
		IPSEC_STATINC(IPSEC_STAT_OUT_BUNDLESA);
		switch (saidx->dst.sa.sa_family) {
#ifdef INET
		case AF_INET:
			return ipsec4_process_packet(m, isr->next, NULL);
#endif
#ifdef INET6
		case AF_INET6:
			return ipsec6_process_packet(m, isr->next, flags);
#endif
		default:
			IPSECLOG(LOG_DEBUG, "unknown protocol family %u\n",
			    saidx->dst.sa.sa_family);
			error = ENXIO;
			goto bad;
		}
	}

	/*
	 * We're done with IPsec processing, mark the packet as processed,
	 * and transmit it using the appropriate network protocol
	 * (IPv4/IPv6).
	 */

	if (ipsec_register_done(m, &error) < 0)
		goto bad;

	return ipsec_reinject_ipstack(m, saidx->dst.sa.sa_family, flags);

bad:
	m_freem(m);
	return error;
}

static void
ipsec_fill_saidx_bymbuf(struct secasindex *saidx, const struct mbuf *m,
    const int af)
{
	struct m_tag *mtag;
	u_int16_t natt_src = IPSEC_PORT_ANY;
	u_int16_t natt_dst = IPSEC_PORT_ANY;

	/*
	 * For NAT-T enabled ipsecif(4), set NAT-T port numbers
	 * even if the saidx uses transport mode.
	 *
	 * See also ipsecif[46]_output().
	 */
	mtag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS);
	if (mtag) {
		u_int16_t *natt_ports;

		natt_ports = (u_int16_t *)(mtag + 1);
		natt_src = natt_ports[1];
		natt_dst = natt_ports[0];
	}

	if (af == AF_INET) {
		struct sockaddr_in *sin;
		struct ip *ip = mtod(m, struct ip *);

		if (saidx->src.sa.sa_len == 0) {
			sin = &saidx->src.sin;
			sin->sin_len = sizeof(*sin);
			sin->sin_family = AF_INET;
			sin->sin_port = natt_src;
			sin->sin_addr = ip->ip_src;
		}
		if (saidx->dst.sa.sa_len == 0) {
			sin = &saidx->dst.sin;
			sin->sin_len = sizeof(*sin);
			sin->sin_family = AF_INET;
			sin->sin_port = natt_dst;
			sin->sin_addr = ip->ip_dst;
		}
	} else {
		struct sockaddr_in6 *sin6;
		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);

		if (saidx->src.sin6.sin6_len == 0) {
			sin6 = (struct sockaddr_in6 *)&saidx->src;
			sin6->sin6_len = sizeof(*sin6);
			sin6->sin6_family = AF_INET6;
			sin6->sin6_port = natt_src;
			sin6->sin6_addr = ip6->ip6_src;
			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
				/* fix scope id for comparing SPD */
				sin6->sin6_addr.s6_addr16[1] = 0;
				sin6->sin6_scope_id =
				    ntohs(ip6->ip6_src.s6_addr16[1]);
			}
		}
		if (saidx->dst.sin6.sin6_len == 0) {
			sin6 = (struct sockaddr_in6 *)&saidx->dst;
			sin6->sin6_len = sizeof(*sin6);
			sin6->sin6_family = AF_INET6;
			sin6->sin6_port = natt_dst;
			sin6->sin6_addr = ip6->ip6_dst;
			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
				/* fix scope id for comparing SPD */
				sin6->sin6_addr.s6_addr16[1] = 0;
				sin6->sin6_scope_id =
				    ntohs(ip6->ip6_dst.s6_addr16[1]);
			}
		}
	}
}

struct secasvar *
ipsec_lookup_sa(const struct ipsecrequest *isr, const struct mbuf *m)
{
	struct secasindex saidx;

	saidx = isr->saidx;
	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
		/* Fillin unspecified SA peers only for transport mode */
		ipsec_fill_saidx_bymbuf(&saidx, m, isr->saidx.dst.sa.sa_family);
	}

	return key_lookup_sa_bysaidx(&saidx);
}

/*
 * ipsec_nextisr can return :
 * - isr == NULL and error != 0 => something is bad : the packet must be
 *   discarded
 * - isr == NULL and error == 0 => no more rules to apply, ipsec processing
 *   is done, reinject it in ip stack
 * - isr != NULL (error == 0) => we need to apply one rule to the packet
 */
static const struct ipsecrequest *
ipsec_nextisr(struct mbuf *m, const struct ipsecrequest *isr, int af,
    int *error, struct secasvar **ret)
{
#define	IPSEC_OSTAT(type)						\
do {									\
	switch (isr->saidx.proto) {					\
	case IPPROTO_ESP:						\
		ESP_STATINC(ESP_STAT_ ## type);				\
		break;							\
	case IPPROTO_AH:						\
		AH_STATINC(AH_STAT_ ## type);				\
		break;							\
	default:							\
		IPCOMP_STATINC(IPCOMP_STAT_ ## type);			\
		break;							\
	}								\
} while (/*CONSTCOND*/0)

	struct secasvar *sav = NULL;
	struct secasindex saidx;

	KASSERTMSG(af == AF_INET || af == AF_INET6,
	    "invalid address family %u", af);
again:
	/*
	 * Craft SA index to search for proper SA.  Note that
	 * we only fillin unspecified SA peers for transport
	 * mode; for tunnel mode they must already be filled in.
	 */
	saidx = isr->saidx;
	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
		/* Fillin unspecified SA peers only for transport mode */
		ipsec_fill_saidx_bymbuf(&saidx, m, af);
	}

	/*
	 * Lookup SA and validate it.
	 */
	*error = key_checkrequest(isr, &saidx, &sav);
	if (*error != 0) {
		/*
		 * IPsec processing is required, but no SA found.
		 * I assume that key_acquire() had been called
		 * to get/establish the SA. Here I discard
		 * this packet because it is responsibility for
		 * upper layer to retransmit the packet.
		 */
		IPSEC_STATINC(IPSEC_STAT_OUT_NOSA);
		goto bad;
	}
	/* sav may be NULL here if we have an USE rule */
	if (sav == NULL) {
		KASSERTMSG(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
		    "no SA found, but required; level %u",
		    ipsec_get_reqlevel(isr));
		isr = isr->next;
		/*
		 * No more rules to apply, return NULL isr and no error.
		 * It can happen when the last rules are USE rules.
		 */
		if (isr == NULL) {
			*ret = NULL;
			*error = 0;
			return isr;
		}
		goto again;
	}

	/*
	 * Check system global policy controls.
	 */
	if ((isr->saidx.proto == IPPROTO_ESP && !esp_enable) ||
	    (isr->saidx.proto == IPPROTO_AH && !ah_enable) ||
	    (isr->saidx.proto == IPPROTO_IPCOMP && !ipcomp_enable)) {
		IPSECLOG(LOG_DEBUG, "IPsec outbound packet dropped due"
		    " to policy (check your sysctls)\n");
		IPSEC_OSTAT(PDROPS);
		*error = EHOSTUNREACH;
		KEY_SA_UNREF(&sav);
		goto bad;
	}

	/*
	 * Sanity check the SA contents for the caller
	 * before they invoke the xform output method.
	 */
	KASSERT(sav->tdb_xform != NULL);
	*ret = sav;
	return isr;

bad:
	KASSERTMSG(*error != 0, "error return w/ no error code");
	return NULL;
#undef IPSEC_OSTAT
}

#ifdef INET
/*
 * IPsec output logic for IPv4.
 */
int
ipsec4_process_packet(struct mbuf *m, const struct ipsecrequest *isr,
    u_long *mtu)
{
	struct secasvar *sav = NULL;
	struct ip *ip;
	int error, i, off;
	union sockaddr_union *dst;
	int setdf;

	KASSERT(m != NULL);
	KASSERT(m->m_nextpkt == NULL);
	KASSERT(isr != NULL);

	isr = ipsec_nextisr(m, isr, AF_INET, &error, &sav);
	if (isr == NULL) {
		if (error != 0) {
			goto bad;
		} else {
			if (ipsec_register_done(m, &error) < 0)
				goto bad;

			return ipsec_reinject_ipstack(m, AF_INET, 0);
		}
	}
	KASSERT(sav != NULL);

	if (m->m_len < sizeof(struct ip) &&
	    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
		error = ENOBUFS;
		goto unrefsav;
	}

	/*
	 * Check if we need to handle NAT-T fragmentation.
	 */
	if (isr == isr->sp->req) { /* Check only if called from ipsec4_output */
		KASSERT(mtu != NULL);
		ip = mtod(m, struct ip *);
		if (!(sav->natt_type & UDP_ENCAP_ESPINUDP)) {
			goto noneed;
		}
		if (ntohs(ip->ip_len) <= sav->esp_frag)
			goto noneed;
		*mtu = sav->esp_frag;
		KEY_SA_UNREF(&sav);
		return 0;
	}
noneed:
	dst = &sav->sah->saidx.dst;

	/*
	 * Collect IP_DF state from the outer header.
	 */
	if (dst->sa.sa_family == AF_INET) {
		ip = mtod(m, struct ip *);
		/* Honor system-wide control of how to handle IP_DF */
		switch (ip4_ipsec_dfbit) {
		case 0:			/* clear in outer header */
		case 1:			/* set in outer header */
			setdf = ip4_ipsec_dfbit;
			break;
		default:		/* propagate to outer header */
			setdf = ip->ip_off;
			setdf = ntohs(setdf);
			setdf = htons(setdf & IP_DF);
			break;
		}
	} else {
		ip = NULL;		/* keep compiler happy */
		setdf = 0;
	}

	/* Do the appropriate encapsulation, if necessary */
	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
	    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
	    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
	     dst->sin.sin_addr.s_addr != INADDR_ANY &&
	     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
		struct mbuf *mp;

		/* Fix IPv4 header checksum and length */
		ip = mtod(m, struct ip *);
		ip->ip_len = htons(m->m_pkthdr.len);
		ip->ip_sum = 0;
		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);

		/* Encapsulate the packet */
		error = ipip_output(m, sav, &mp);
		if (mp == NULL && !error) {
			/* Should never happen. */
			IPSECLOG(LOG_DEBUG,
			    "ipip_output returns no mbuf and no error!");
			error = EFAULT;
		}
		if (error) {
			if (mp) {
				/* XXX: Should never happen! */
				m_freem(mp);
			}
			m = NULL; /* ipip_output() already freed it */
			goto unrefsav;
		}
		m = mp, mp = NULL;

		/*
		 * ipip_output clears IP_DF in the new header.  If
		 * we need to propagate IP_DF from the outer header,
		 * then we have to do it here.
		 *
		 * XXX shouldn't assume what ipip_output does.
		 */
		if (dst->sa.sa_family == AF_INET && setdf) {
			if (m->m_len < sizeof(struct ip) &&
			    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
				error = ENOBUFS;
				goto unrefsav;
			}
			ip = mtod(m, struct ip *);
			ip->ip_off |= htons(IP_DF);
		}
	}

	/*
	 * Dispatch to the appropriate IPsec transform logic.  The
	 * packet will be returned for transmission after crypto
	 * processing, etc. are completed.  For encapsulation we
	 * bypass this call because of the explicit call done above
	 * (necessary to deal with IP_DF handling for IPv4).
	 *
	 * NB: m & sav are ``passed to caller'' who's responsible for
	 *     for reclaiming their resources.
	 */
	if (sav->tdb_xform->xf_type != XF_IP4) {
		if (dst->sa.sa_family == AF_INET) {
			ip = mtod(m, struct ip *);
			i = ip->ip_hl << 2;
			off = offsetof(struct ip, ip_p);
		} else {
			i = sizeof(struct ip6_hdr);
			off = offsetof(struct ip6_hdr, ip6_nxt);
		}
		error = (*sav->tdb_xform->xf_output)(m, isr, sav, i, off, 0);
	} else {
		error = ipsec_process_done(m, isr, sav, 0);
	}
	KEY_SA_UNREF(&sav);
	return error;

unrefsav:
	KEY_SA_UNREF(&sav);
bad:
	if (m)
		m_freem(m);
	return error;
}
#endif

#ifdef INET6
static int
compute_ipsec_pos(struct mbuf *m, int *i, int *off)
{
	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
	struct ip6_ext ip6e;
	int dstopt = 0;
	int nxt;

	*i = sizeof(struct ip6_hdr);
	*off = offsetof(struct ip6_hdr, ip6_nxt);
	nxt = ip6->ip6_nxt;

	/*
	 * chase mbuf chain to find the appropriate place to
	 * put AH/ESP/IPcomp header.
	 *     IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
	 */
	while (1) {
		switch (nxt) {
		case IPPROTO_AH:
		case IPPROTO_ESP:
		case IPPROTO_IPCOMP:
			/*
			 * We should not skip security header added
			 * beforehand.
			 */
			return 0;

		case IPPROTO_HOPOPTS:
		case IPPROTO_DSTOPTS:
		case IPPROTO_ROUTING:
			if (*i + sizeof(ip6e) > m->m_pkthdr.len) {
				return EINVAL;
			}

			/*
			 * If we see 2nd destination option header,
			 * we should stop there.
			 */
			if (nxt == IPPROTO_DSTOPTS && dstopt)
				return 0;

			if (nxt == IPPROTO_DSTOPTS) {
				/*
				 * Seen 1st or 2nd destination option.
				 * next time we see one, it must be 2nd.
				 */
				dstopt = 1;
			} else if (nxt == IPPROTO_ROUTING) {
				/*
				 * If we see destination option next
				 * time, it must be dest2.
				 */
				dstopt = 2;
			}

			/* skip this header */
			m_copydata(m, *i, sizeof(ip6e), &ip6e);
			nxt = ip6e.ip6e_nxt;
			*off = *i + offsetof(struct ip6_ext, ip6e_nxt);
			*i += (ip6e.ip6e_len + 1) << 3;
			if (*i > m->m_pkthdr.len) {
				return EINVAL;
			}
			break;
		default:
			return 0;
		}
	}

	return 0;
}

static int
in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa,
    const struct in6_addr *ia)
{
	struct in6_addr ia2;

	memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr))
		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);

	return IN6_ARE_ADDR_EQUAL(ia, &ia2);
}

int
ipsec6_process_packet(struct mbuf *m, const struct ipsecrequest *isr, int flags)
{
	struct secasvar *sav = NULL;
	struct ip6_hdr *ip6;
	int error, i, off;
	union sockaddr_union *dst;

	KASSERT(m != NULL);
	KASSERT(m->m_nextpkt == NULL);
	KASSERT(isr != NULL);

	isr = ipsec_nextisr(m, isr, AF_INET6, &error, &sav);
	if (isr == NULL) {
		if (error != 0) {
			/* XXX Should we send a notification ? */
			goto bad;
		} else {
			if (ipsec_register_done(m, &error) < 0)
				goto bad;

			return ipsec_reinject_ipstack(m, AF_INET6, flags);
		}
	}

	KASSERT(sav != NULL);
	dst = &sav->sah->saidx.dst;

	if (m->m_len < sizeof(struct ip6_hdr)) {
		if ((m = m_pullup(m,sizeof(struct ip6_hdr))) == NULL) {
			error = ENOBUFS;
			goto unrefsav;
		}
	}
	ip6 = mtod(m, struct ip6_hdr *);

	/* Do the appropriate encapsulation, if necessary */
	if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
	    dst->sa.sa_family != AF_INET6 ||        /* AF mismatch */
	    ((dst->sa.sa_family == AF_INET6) &&
	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
	     (!in6_sa_equal_addrwithscope(&dst->sin6, &ip6->ip6_dst)))) {
		struct mbuf *mp;

		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
			/* No jumbogram support. */
			error = ENXIO;   /*XXX*/
			goto unrefsav;
		}

		/* Fix IPv6 header payload length. */
		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));

		/* Encapsulate the packet */
		error = ipip_output(m, sav, &mp);
		if (mp == NULL && !error) {
			/* Should never happen. */
			IPSECLOG(LOG_DEBUG,
			    "ipip_output returns no mbuf and no error!");
			error = EFAULT;
		}

		if (error) {
			if (mp) {
				/* XXX: Should never happen! */
				m_freem(mp);
			}
			m = NULL; /* ipip_output() already freed it */
			goto unrefsav;
		}

		m = mp;
		mp = NULL;
	}

	if (dst->sa.sa_family == AF_INET) {
		struct ip *ip;
		ip = mtod(m, struct ip *);
		i = ip->ip_hl << 2;
		off = offsetof(struct ip, ip_p);
	} else {
		error = compute_ipsec_pos(m, &i, &off);
		if (error)
			goto unrefsav;
	}
	error = (*sav->tdb_xform->xf_output)(m, isr, sav, i, off, flags);
	KEY_SA_UNREF(&sav);
	return error;

unrefsav:
	KEY_SA_UNREF(&sav);
bad:
	if (m)
		m_freem(m);
	return error;
}
#endif /* INET6 */

void
ipsec_output_init(void)
{

	ipsec_rtcache_percpu = rtcache_percpu_alloc();
}