]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netipsec/ipsec.c
MFV r358511,r358532:
[FreeBSD/FreeBSD.git] / sys / netipsec / ipsec.c
1 /*      $FreeBSD$       */
2 /*      $KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $ */
3
4 /*-
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the project nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * IPsec controller part.
37  */
38
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_ipsec.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/domain.h>
48 #include <sys/priv.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/errno.h>
53 #include <sys/hhook.h>
54 #include <sys/time.h>
55 #include <sys/kernel.h>
56 #include <sys/syslog.h>
57 #include <sys/sysctl.h>
58 #include <sys/proc.h>
59
60 #include <net/if.h>
61 #include <net/if_enc.h>
62 #include <net/if_var.h>
63 #include <net/vnet.h>
64
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_var.h>
69 #include <netinet/in_var.h>
70 #include <netinet/udp.h>
71 #include <netinet/udp_var.h>
72 #include <netinet/tcp.h>
73 #include <netinet/udp.h>
74
75 #include <netinet/ip6.h>
76 #ifdef INET6
77 #include <netinet6/ip6_var.h>
78 #endif
79 #include <netinet/in_pcb.h>
80 #ifdef INET6
81 #include <netinet/icmp6.h>
82 #endif
83
84 #include <sys/types.h>
85 #include <netipsec/ipsec.h>
86 #ifdef INET6
87 #include <netipsec/ipsec6.h>
88 #endif
89 #include <netipsec/ah_var.h>
90 #include <netipsec/esp_var.h>
91 #include <netipsec/ipcomp.h>            /*XXX*/
92 #include <netipsec/ipcomp_var.h>
93 #include <netipsec/ipsec_support.h>
94
95 #include <netipsec/key.h>
96 #include <netipsec/keydb.h>
97 #include <netipsec/key_debug.h>
98
99 #include <netipsec/xform.h>
100
101 #include <machine/in_cksum.h>
102
103 #include <opencrypto/cryptodev.h>
104
105 /* NB: name changed so netstat doesn't use it. */
106 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec4stat);
107 VNET_PCPUSTAT_SYSINIT(ipsec4stat);
108
109 #ifdef VIMAGE
110 VNET_PCPUSTAT_SYSUNINIT(ipsec4stat);
111 #endif /* VIMAGE */
112
113 /* DF bit on encap. 0: clear 1: set 2: copy */
114 VNET_DEFINE(int, ip4_ipsec_dfbit) = 0;
115 VNET_DEFINE(int, ip4_esp_trans_deflev) = IPSEC_LEVEL_USE;
116 VNET_DEFINE(int, ip4_esp_net_deflev) = IPSEC_LEVEL_USE;
117 VNET_DEFINE(int, ip4_ah_trans_deflev) = IPSEC_LEVEL_USE;
118 VNET_DEFINE(int, ip4_ah_net_deflev) = IPSEC_LEVEL_USE;
119 /* ECN ignore(-1)/forbidden(0)/allowed(1) */
120 VNET_DEFINE(int, ip4_ipsec_ecn) = 0;
121
122 VNET_DEFINE_STATIC(int, ip4_filtertunnel) = 0;
123 #define V_ip4_filtertunnel VNET(ip4_filtertunnel)
124 VNET_DEFINE_STATIC(int, check_policy_history) = 0;
125 #define V_check_policy_history  VNET(check_policy_history)
126 VNET_DEFINE_STATIC(struct secpolicy *, def_policy) = NULL;
127 #define V_def_policy    VNET(def_policy)
128 static int
129 sysctl_def_policy(SYSCTL_HANDLER_ARGS)
130 {
131         int error, value;
132
133         value = V_def_policy->policy;
134         error = sysctl_handle_int(oidp, &value, 0, req);
135         if (error == 0) {
136                 if (value != IPSEC_POLICY_DISCARD &&
137                     value != IPSEC_POLICY_NONE)
138                         return (EINVAL);
139                 V_def_policy->policy = value;
140         }
141         return (error);
142 }
143
144 /*
145  * Crypto support requirements:
146  *
147  *  1   require hardware support
148  * -1   require software support
149  *  0   take anything
150  */
151 VNET_DEFINE(int, crypto_support) = CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
152
153 /*
154  * Use asynchronous mode to parallelize crypto jobs:
155  *
156  *  0 - disabled
157  *  1 - enabled
158  */
159 VNET_DEFINE(int, async_crypto) = 0;
160
161 /*
162  * TCP/UDP checksum handling policy for transport mode NAT-T (RFC3948)
163  *
164  * 0 - auto: incrementally recompute, when checksum delta is known;
165  *     if checksum delta isn't known, reset checksum to zero for UDP,
166  *     and mark csum_flags as valid for TCP.
167  * 1 - fully recompute TCP/UDP checksum.
168  */
169 VNET_DEFINE(int, natt_cksum_policy) = 0;
170
171 FEATURE(ipsec, "Internet Protocol Security (IPsec)");
172 FEATURE(ipsec_natt, "UDP Encapsulation of IPsec ESP Packets ('NAT-T')");
173
174 SYSCTL_DECL(_net_inet_ipsec);
175
176 /* net.inet.ipsec */
177 SYSCTL_PROC(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy,
178     CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
179     0, 0, sysctl_def_policy, "I",
180     "IPsec default policy.");
181 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
182         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0,
183         "Default ESP transport mode level");
184 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
185         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0,
186         "Default ESP tunnel mode level.");
187 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
188         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0,
189         "AH transfer mode default level.");
190 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
191         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0,
192         "AH tunnel mode default level.");
193 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos,
194         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0,
195         "If set, clear type-of-service field when doing AH computation.");
196 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit,
197         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0,
198         "Do not fragment bit on encap.");
199 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn,
200         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0,
201         "Explicit Congestion Notification handling.");
202 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, crypto_support,
203         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(crypto_support), 0,
204         "Crypto driver selection.");
205 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, async_crypto,
206         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(async_crypto), 0,
207         "Use asynchronous mode to parallelize crypto jobs.");
208 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, check_policy_history,
209         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(check_policy_history), 0,
210         "Use strict check of inbound packets to security policy compliance.");
211 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, natt_cksum_policy,
212         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(natt_cksum_policy), 0,
213         "Method to fix TCP/UDP checksum for transport mode IPsec after NAT.");
214 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, filtertunnel,
215         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_filtertunnel), 0,
216         "If set, filter packets from an IPsec tunnel.");
217 SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat,
218     ipsec4stat, "IPsec IPv4 statistics.");
219
220 struct timeval ipsec_warn_interval = { .tv_sec = 1, .tv_usec = 0 };
221 SYSCTL_TIMEVAL_SEC(_net_inet_ipsec, OID_AUTO, crypto_warn_interval, CTLFLAG_RW,
222     &ipsec_warn_interval,
223     "Delay in seconds between warnings of deprecated IPsec crypto algorithms.");
224
225 #ifdef REGRESSION
226 /*
227  * When set to 1, IPsec will send packets with the same sequence number.
228  * This allows to verify if the other side has proper replay attacks detection.
229  */
230 VNET_DEFINE(int, ipsec_replay) = 0;
231 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay,
232         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0,
233         "Emulate replay attack");
234 /*
235  * When set 1, IPsec will send packets with corrupted HMAC.
236  * This allows to verify if the other side properly detects modified packets.
237  */
238 VNET_DEFINE(int, ipsec_integrity) = 0;
239 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity,
240         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0,
241         "Emulate man-in-the-middle attack");
242 #endif
243
244 #ifdef INET6 
245 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat);
246 VNET_PCPUSTAT_SYSINIT(ipsec6stat);
247
248 #ifdef VIMAGE
249 VNET_PCPUSTAT_SYSUNINIT(ipsec6stat);
250 #endif /* VIMAGE */
251
252 VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE;
253 VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE;
254 VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE;
255 VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE;
256 VNET_DEFINE(int, ip6_ipsec_ecn) = 0;    /* ECN ignore(-1)/forbidden(0)/allowed(1) */
257
258 VNET_DEFINE_STATIC(int, ip6_filtertunnel) = 0;
259 #define V_ip6_filtertunnel      VNET(ip6_filtertunnel)
260
261 SYSCTL_DECL(_net_inet6_ipsec6);
262
263 /* net.inet6.ipsec6 */
264 SYSCTL_PROC(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy,
265     CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
266     0, 0, sysctl_def_policy, "I",
267     "IPsec default policy.");
268 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
269         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0,
270         "Default ESP transport mode level.");
271 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
272         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev), 0,
273         "Default ESP tunnel mode level.");
274 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
275         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev), 0,
276         "AH transfer mode default level.");
277 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
278         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev), 0,
279         "AH tunnel mode default level.");
280 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN, ecn,
281         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn), 0,
282         "Explicit Congestion Notification handling.");
283 SYSCTL_INT(_net_inet6_ipsec6, OID_AUTO, filtertunnel,
284         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_filtertunnel),  0,
285         "If set, filter packets from an IPsec tunnel.");
286 SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats,
287     struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics.");
288 #endif /* INET6 */
289
290 static int ipsec_in_reject(struct secpolicy *, struct inpcb *,
291     const struct mbuf *);
292
293 #ifdef INET
294 static void ipsec4_get_ulp(const struct mbuf *, struct secpolicyindex *, int);
295 static void ipsec4_setspidx_ipaddr(const struct mbuf *,
296     struct secpolicyindex *);
297 #endif
298 #ifdef INET6
299 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
300 static void ipsec6_setspidx_ipaddr(const struct mbuf *,
301     struct secpolicyindex *);
302 #endif
303
304 /*
305  * Return a held reference to the default SP.
306  */
307 static struct secpolicy *
308 key_allocsp_default(void)
309 {
310
311         key_addref(V_def_policy);
312         return (V_def_policy);
313 }
314
315 static void
316 ipsec_invalidate_cache(struct inpcb *inp, u_int dir)
317 {
318         struct secpolicy *sp;
319
320         INP_WLOCK_ASSERT(inp);
321         if (dir == IPSEC_DIR_OUTBOUND) {
322                 if (inp->inp_sp->flags & INP_INBOUND_POLICY)
323                         return;
324                 sp = inp->inp_sp->sp_in;
325                 inp->inp_sp->sp_in = NULL;
326         } else {
327                 if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
328                         return;
329                 sp = inp->inp_sp->sp_out;
330                 inp->inp_sp->sp_out = NULL;
331         }
332         if (sp != NULL)
333                 key_freesp(&sp); /* release extra reference */
334 }
335
336 static void
337 ipsec_cachepolicy(struct inpcb *inp, struct secpolicy *sp, u_int dir)
338 {
339         uint32_t genid;
340         int downgrade;
341
342         INP_LOCK_ASSERT(inp);
343
344         if (dir == IPSEC_DIR_OUTBOUND) {
345                 /* Do we have configured PCB policy? */
346                 if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
347                         return;
348                 /* Another thread has already set cached policy */
349                 if (inp->inp_sp->sp_out != NULL)
350                         return;
351                 /*
352                  * Do not cache OUTBOUND policy if PCB isn't connected,
353                  * i.e. foreign address is INADDR_ANY/UNSPECIFIED.
354                  */
355 #ifdef INET
356                 if ((inp->inp_vflag & INP_IPV4) != 0 &&
357                     inp->inp_faddr.s_addr == INADDR_ANY)
358                         return;
359 #endif
360 #ifdef INET6
361                 if ((inp->inp_vflag & INP_IPV6) != 0 &&
362                     IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
363                         return;
364 #endif
365         } else {
366                 /* Do we have configured PCB policy? */
367                 if (inp->inp_sp->flags & INP_INBOUND_POLICY)
368                         return;
369                 /* Another thread has already set cached policy */
370                 if (inp->inp_sp->sp_in != NULL)
371                         return;
372                 /*
373                  * Do not cache INBOUND policy for listen socket,
374                  * that is bound to INADDR_ANY/UNSPECIFIED address.
375                  */
376 #ifdef INET
377                 if ((inp->inp_vflag & INP_IPV4) != 0 &&
378                     inp->inp_faddr.s_addr == INADDR_ANY)
379                         return;
380 #endif
381 #ifdef INET6
382                 if ((inp->inp_vflag & INP_IPV6) != 0 &&
383                     IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
384                         return;
385 #endif
386         }
387         downgrade = 0;
388         if (!INP_WLOCKED(inp)) {
389                 if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
390                         return;
391         }
392         if (dir == IPSEC_DIR_OUTBOUND)
393                 inp->inp_sp->sp_out = sp;
394         else
395                 inp->inp_sp->sp_in = sp;
396         /*
397          * SP is already referenced by the lookup code.
398          * We take extra reference here to avoid race in the
399          * ipsec_getpcbpolicy() function - SP will not be freed in the
400          * time between we take SP pointer from the cache and key_addref()
401          * call.
402          */
403         key_addref(sp);
404         genid = key_getspgen();
405         if (genid != inp->inp_sp->genid) {
406                 ipsec_invalidate_cache(inp, dir);
407                 inp->inp_sp->genid = genid;
408         }
409         KEYDBG(IPSEC_STAMP,
410             printf("%s: PCB(%p): cached %s SP(%p)\n",
411             __func__, inp, dir == IPSEC_DIR_OUTBOUND ? "OUTBOUND":
412             "INBOUND", sp));
413         if (downgrade != 0)
414                 INP_DOWNGRADE(inp);
415 }
416
417 static struct secpolicy *
418 ipsec_checkpolicy(struct secpolicy *sp, struct inpcb *inp, int *error)
419 {
420
421         /* Save found OUTBOUND policy into PCB SP cache. */
422         if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_out == NULL)
423                 ipsec_cachepolicy(inp, sp, IPSEC_DIR_OUTBOUND);
424
425         switch (sp->policy) {
426         default:
427                 printf("%s: invalid policy %u\n", __func__, sp->policy);
428                 /* FALLTHROUGH */
429         case IPSEC_POLICY_DISCARD:
430                 *error = -EINVAL;       /* Packet is discarded by caller. */
431                 /* FALLTHROUGH */
432         case IPSEC_POLICY_BYPASS:
433         case IPSEC_POLICY_NONE:
434                 key_freesp(&sp);
435                 sp = NULL;              /* NB: force NULL result. */
436                 break;
437         case IPSEC_POLICY_IPSEC:
438                 /* XXXAE: handle LARVAL SP */
439                 break;
440         }
441         KEYDBG(IPSEC_DUMP,
442             printf("%s: get SP(%p), error %d\n", __func__, sp, *error));
443         return (sp);
444 }
445
446 static struct secpolicy *
447 ipsec_getpcbpolicy(struct inpcb *inp, u_int dir)
448 {
449         struct secpolicy *sp;
450         int flags, downgrade;
451
452         if (inp == NULL || inp->inp_sp == NULL)
453                 return (NULL);
454
455         INP_LOCK_ASSERT(inp);
456
457         flags = inp->inp_sp->flags;
458         if (dir == IPSEC_DIR_OUTBOUND) {
459                 sp = inp->inp_sp->sp_out;
460                 flags &= INP_OUTBOUND_POLICY;
461         } else {
462                 sp = inp->inp_sp->sp_in;
463                 flags &= INP_INBOUND_POLICY;
464         }
465         /*
466          * Check flags. If we have PCB SP, just return it.
467          * Otherwise we need to check that cached SP entry isn't stale.
468          */
469         if (flags == 0) {
470                 if (sp == NULL)
471                         return (NULL);
472                 if (inp->inp_sp->genid != key_getspgen()) {
473                         /* Invalidate the cache. */
474                         downgrade = 0;
475                         if (!INP_WLOCKED(inp)) {
476                                 if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
477                                         return (NULL);
478                         }
479                         ipsec_invalidate_cache(inp, IPSEC_DIR_OUTBOUND);
480                         ipsec_invalidate_cache(inp, IPSEC_DIR_INBOUND);
481                         if (downgrade != 0)
482                                 INP_DOWNGRADE(inp);
483                         return (NULL);
484                 }
485                 KEYDBG(IPSEC_STAMP,
486                     printf("%s: PCB(%p): cache hit SP(%p)\n",
487                     __func__, inp, sp));
488                 /* Return referenced cached policy */
489         }
490         key_addref(sp);
491         return (sp);
492 }
493
494 #ifdef INET
495 static void
496 ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
497     int needport)
498 {
499         uint8_t nxt;
500         int off;
501
502         /* Sanity check. */
503         IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
504             ("packet too short"));
505
506         if (m->m_len >= sizeof (struct ip)) {
507                 const struct ip *ip = mtod(m, const struct ip *);
508                 if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
509                         goto done;
510                 off = ip->ip_hl << 2;
511                 nxt = ip->ip_p;
512         } else {
513                 struct ip ih;
514
515                 m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
516                 if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
517                         goto done;
518                 off = ih.ip_hl << 2;
519                 nxt = ih.ip_p;
520         }
521
522         while (off < m->m_pkthdr.len) {
523                 struct ip6_ext ip6e;
524                 struct tcphdr th;
525                 struct udphdr uh;
526
527                 switch (nxt) {
528                 case IPPROTO_TCP:
529                         spidx->ul_proto = nxt;
530                         if (!needport)
531                                 goto done_proto;
532                         if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
533                                 goto done;
534                         m_copydata(m, off, sizeof (th), (caddr_t) &th);
535                         spidx->src.sin.sin_port = th.th_sport;
536                         spidx->dst.sin.sin_port = th.th_dport;
537                         return;
538                 case IPPROTO_UDP:
539                         spidx->ul_proto = nxt;
540                         if (!needport)
541                                 goto done_proto;
542                         if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
543                                 goto done;
544                         m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
545                         spidx->src.sin.sin_port = uh.uh_sport;
546                         spidx->dst.sin.sin_port = uh.uh_dport;
547                         return;
548                 case IPPROTO_AH:
549                         if (off + sizeof(ip6e) > m->m_pkthdr.len)
550                                 goto done;
551                         /* XXX Sigh, this works but is totally bogus. */
552                         m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
553                         off += (ip6e.ip6e_len + 2) << 2;
554                         nxt = ip6e.ip6e_nxt;
555                         break;
556                 case IPPROTO_ICMP:
557                 default:
558                         /* XXX Intermediate headers??? */
559                         spidx->ul_proto = nxt;
560                         goto done_proto;
561                 }
562         }
563 done:
564         spidx->ul_proto = IPSEC_ULPROTO_ANY;
565 done_proto:
566         spidx->src.sin.sin_port = IPSEC_PORT_ANY;
567         spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
568         KEYDBG(IPSEC_DUMP,
569             printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
570 }
571
572 static void
573 ipsec4_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
574 {
575
576         ipsec4_setsockaddrs(m, &spidx->src, &spidx->dst);
577         spidx->prefs = sizeof(struct in_addr) << 3;
578         spidx->prefd = sizeof(struct in_addr) << 3;
579 }
580
581 static struct secpolicy *
582 ipsec4_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
583     int needport)
584 {
585         struct secpolicyindex spidx;
586         struct secpolicy *sp;
587
588         sp = ipsec_getpcbpolicy(inp, dir);
589         if (sp == NULL && key_havesp(dir)) {
590                 /* Make an index to look for a policy. */
591                 ipsec4_setspidx_ipaddr(m, &spidx);
592                 ipsec4_get_ulp(m, &spidx, needport);
593                 spidx.dir = dir;
594                 sp = key_allocsp(&spidx, dir);
595         }
596         if (sp == NULL)         /* No SP found, use system default. */
597                 sp = key_allocsp_default();
598         return (sp);
599 }
600
601 /*
602  * Check security policy for *OUTBOUND* IPv4 packet.
603  */
604 struct secpolicy *
605 ipsec4_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
606     int needport)
607 {
608         struct secpolicy *sp;
609
610         *error = 0;
611         sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
612         if (sp != NULL)
613                 sp = ipsec_checkpolicy(sp, inp, error);
614         if (sp == NULL) {
615                 switch (*error) {
616                 case 0: /* No IPsec required: BYPASS or NONE */
617                         break;
618                 case -EINVAL:
619                         IPSECSTAT_INC(ips_out_polvio);
620                         break;
621                 default:
622                         IPSECSTAT_INC(ips_out_inval);
623                 }
624         }
625         KEYDBG(IPSEC_STAMP,
626             printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
627         if (sp != NULL)
628                 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
629         return (sp);
630 }
631
632 /*
633  * Check IPv4 packet against *INBOUND* security policy.
634  * This function is called from tcp_input(), udp_input(),
635  * rip_input() and sctp_input().
636  */
637 int
638 ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
639 {
640         struct secpolicy *sp;
641         int result;
642
643         sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
644         result = ipsec_in_reject(sp, inp, m);
645         key_freesp(&sp);
646         if (result != 0)
647                 IPSECSTAT_INC(ips_in_polvio);
648         return (result);
649 }
650
651 /*
652  * IPSEC_CAP() method implementation for IPv4.
653  */
654 int
655 ipsec4_capability(struct mbuf *m, u_int cap)
656 {
657
658         switch (cap) {
659         case IPSEC_CAP_BYPASS_FILTER:
660                 /*
661                  * Bypass packet filtering for packets previously handled
662                  * by IPsec.
663                  */
664                 if (!V_ip4_filtertunnel &&
665                     m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
666                         return (1);
667                 return (0);
668         case IPSEC_CAP_OPERABLE:
669                 /* Do we have active security policies? */
670                 if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
671                     key_havesp(IPSEC_DIR_OUTBOUND) != 0)
672                         return (1);
673                 return (0);
674         };
675         return (EOPNOTSUPP);
676 }
677
678 #endif /* INET */
679
680 #ifdef INET6
681 static void
682 ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
683     int needport)
684 {
685         struct tcphdr th;
686         struct udphdr uh;
687         struct icmp6_hdr ih;
688         int off, nxt;
689
690         IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip6_hdr),
691             ("packet too short"));
692
693         /* Set default. */
694         spidx->ul_proto = IPSEC_ULPROTO_ANY;
695         spidx->src.sin6.sin6_port = IPSEC_PORT_ANY;
696         spidx->dst.sin6.sin6_port = IPSEC_PORT_ANY;
697
698         nxt = -1;
699         off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
700         if (off < 0 || m->m_pkthdr.len < off)
701                 return;
702
703         switch (nxt) {
704         case IPPROTO_TCP:
705                 spidx->ul_proto = nxt;
706                 if (!needport)
707                         break;
708                 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
709                         break;
710                 m_copydata(m, off, sizeof(th), (caddr_t)&th);
711                 spidx->src.sin6.sin6_port = th.th_sport;
712                 spidx->dst.sin6.sin6_port = th.th_dport;
713                 break;
714         case IPPROTO_UDP:
715                 spidx->ul_proto = nxt;
716                 if (!needport)
717                         break;
718                 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
719                         break;
720                 m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
721                 spidx->src.sin6.sin6_port = uh.uh_sport;
722                 spidx->dst.sin6.sin6_port = uh.uh_dport;
723                 break;
724         case IPPROTO_ICMPV6:
725                 spidx->ul_proto = nxt;
726                 if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
727                         break;
728                 m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
729                 spidx->src.sin6.sin6_port = htons((uint16_t)ih.icmp6_type);
730                 spidx->dst.sin6.sin6_port = htons((uint16_t)ih.icmp6_code);
731                 break;
732         default:
733                 /* XXX Intermediate headers??? */
734                 spidx->ul_proto = nxt;
735                 break;
736         }
737         KEYDBG(IPSEC_DUMP,
738             printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
739 }
740
741 static void
742 ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
743 {
744
745         ipsec6_setsockaddrs(m, &spidx->src, &spidx->dst);
746         spidx->prefs = sizeof(struct in6_addr) << 3;
747         spidx->prefd = sizeof(struct in6_addr) << 3;
748 }
749
750 static struct secpolicy *
751 ipsec6_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
752     int needport)
753 {
754         struct secpolicyindex spidx;
755         struct secpolicy *sp;
756
757         sp = ipsec_getpcbpolicy(inp, dir);
758         if (sp == NULL && key_havesp(dir)) {
759                 /* Make an index to look for a policy. */
760                 ipsec6_setspidx_ipaddr(m, &spidx);
761                 ipsec6_get_ulp(m, &spidx, needport);
762                 spidx.dir = dir;
763                 sp = key_allocsp(&spidx, dir);
764         }
765         if (sp == NULL)         /* No SP found, use system default. */
766                 sp = key_allocsp_default();
767         return (sp);
768 }
769
770 /*
771  * Check security policy for *OUTBOUND* IPv6 packet.
772  */
773 struct secpolicy *
774 ipsec6_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
775     int needport)
776 {
777         struct secpolicy *sp;
778
779         *error = 0;
780         sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
781         if (sp != NULL)
782                 sp = ipsec_checkpolicy(sp, inp, error);
783         if (sp == NULL) {
784                 switch (*error) {
785                 case 0: /* No IPsec required: BYPASS or NONE */
786                         break;
787                 case -EINVAL:
788                         IPSEC6STAT_INC(ips_out_polvio);
789                         break;
790                 default:
791                         IPSEC6STAT_INC(ips_out_inval);
792                 }
793         }
794         KEYDBG(IPSEC_STAMP,
795             printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
796         if (sp != NULL)
797                 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
798         return (sp);
799 }
800
801 /*
802  * Check IPv6 packet against inbound security policy.
803  * This function is called from tcp6_input(), udp6_input(),
804  * rip6_input() and sctp_input().
805  */
806 int
807 ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
808 {
809         struct secpolicy *sp;
810         int result;
811
812         sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
813         result = ipsec_in_reject(sp, inp, m);
814         key_freesp(&sp);
815         if (result)
816                 IPSEC6STAT_INC(ips_in_polvio);
817         return (result);
818 }
819
820 /*
821  * IPSEC_CAP() method implementation for IPv6.
822  */
823 int
824 ipsec6_capability(struct mbuf *m, u_int cap)
825 {
826
827         switch (cap) {
828         case IPSEC_CAP_BYPASS_FILTER:
829                 /*
830                  * Bypass packet filtering for packets previously handled
831                  * by IPsec.
832                  */
833                 if (!V_ip6_filtertunnel &&
834                     m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
835                         return (1);
836                 return (0);
837         case IPSEC_CAP_OPERABLE:
838                 /* Do we have active security policies? */
839                 if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
840                     key_havesp(IPSEC_DIR_OUTBOUND) != 0)
841                         return (1);
842                 return (0);
843         };
844         return (EOPNOTSUPP);
845 }
846 #endif /* INET6 */
847
848 int
849 ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type)
850 {
851         int idx;
852
853         switch (ctx->af) {
854 #ifdef INET
855         case AF_INET:
856                 idx = HHOOK_IPSEC_INET;
857                 break;
858 #endif
859 #ifdef INET6
860         case AF_INET6:
861                 idx = HHOOK_IPSEC_INET6;
862                 break;
863 #endif
864         default:
865                 return (EPFNOSUPPORT);
866         }
867         if (type == HHOOK_TYPE_IPSEC_IN)
868                 HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL);
869         else
870                 HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL);
871         if (*ctx->mp == NULL)
872                 return (EACCES);
873         return (0);
874 }
875
876 /*
877  * Return current level.
878  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
879  */
880 u_int
881 ipsec_get_reqlevel(struct secpolicy *sp, u_int idx)
882 {
883         struct ipsecrequest *isr;
884         u_int esp_trans_deflev, esp_net_deflev;
885         u_int ah_trans_deflev, ah_net_deflev;
886         u_int level = 0;
887
888         IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
889 /* XXX Note that we have ipseclog() expanded here - code sync issue. */
890 #define IPSEC_CHECK_DEFAULT(lev) \
891         (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE &&   \
892           (lev) != IPSEC_LEVEL_UNIQUE)                                  \
893                 ? (V_ipsec_debug  ?                                     \
894                 log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
895                 (lev), IPSEC_LEVEL_REQUIRE) : 0),                       \
896                 (lev) = IPSEC_LEVEL_REQUIRE, (lev) : (lev))
897
898         /*
899          * IPsec VTI uses unique security policy with fake spidx filled
900          * with zeroes. Just return IPSEC_LEVEL_REQUIRE instead of doing
901          * full level lookup for such policies.
902          */
903         if (sp->state == IPSEC_SPSTATE_IFNET) {
904                 IPSEC_ASSERT(sp->req[idx]->level == IPSEC_LEVEL_UNIQUE,
905                     ("Wrong IPsec request level %d", sp->req[idx]->level));
906                 return (IPSEC_LEVEL_REQUIRE);
907         }
908
909         /* Set default level. */
910         switch (sp->spidx.src.sa.sa_family) {
911 #ifdef INET
912         case AF_INET:
913                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev);
914                 esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev);
915                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev);
916                 ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev);
917                 break;
918 #endif
919 #ifdef INET6
920         case AF_INET6:
921                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev);
922                 esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev);
923                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev);
924                 ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev);
925                 break;
926 #endif /* INET6 */
927         default:
928                 panic("%s: unknown af %u",
929                         __func__, sp->spidx.src.sa.sa_family);
930         }
931
932 #undef IPSEC_CHECK_DEFAULT
933
934         isr = sp->req[idx];
935         /* Set level. */
936         switch (isr->level) {
937         case IPSEC_LEVEL_DEFAULT:
938                 switch (isr->saidx.proto) {
939                 case IPPROTO_ESP:
940                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
941                                 level = esp_net_deflev;
942                         else
943                                 level = esp_trans_deflev;
944                         break;
945                 case IPPROTO_AH:
946                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
947                                 level = ah_net_deflev;
948                         else
949                                 level = ah_trans_deflev;
950                         break;
951                 case IPPROTO_IPCOMP:
952                         /*
953                          * We don't really care, as IPcomp document says that
954                          * we shouldn't compress small packets.
955                          */
956                         level = IPSEC_LEVEL_USE;
957                         break;
958                 default:
959                         panic("%s: Illegal protocol defined %u\n", __func__,
960                                 isr->saidx.proto);
961                 }
962                 break;
963
964         case IPSEC_LEVEL_USE:
965         case IPSEC_LEVEL_REQUIRE:
966                 level = isr->level;
967                 break;
968         case IPSEC_LEVEL_UNIQUE:
969                 level = IPSEC_LEVEL_REQUIRE;
970                 break;
971
972         default:
973                 panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
974         }
975
976         return (level);
977 }
978
979 static int
980 ipsec_check_history(const struct mbuf *m, struct secpolicy *sp, u_int idx)
981 {
982         struct xform_history *xh;
983         struct m_tag *mtag;
984
985         mtag = NULL;
986         while ((mtag = m_tag_find(__DECONST(struct mbuf *, m),
987             PACKET_TAG_IPSEC_IN_DONE, mtag)) != NULL) {
988                 xh = (struct xform_history *)(mtag + 1);
989                 KEYDBG(IPSEC_DATA,
990                     char buf[IPSEC_ADDRSTRLEN];
991                     printf("%s: mode %s proto %u dst %s\n", __func__,
992                         kdebug_secasindex_mode(xh->mode), xh->proto,
993                         ipsec_address(&xh->dst, buf, sizeof(buf))));
994                 if (xh->proto != sp->req[idx]->saidx.proto)
995                         continue;
996                 /* If SA had IPSEC_MODE_ANY, consider this as match. */
997                 if (xh->mode != sp->req[idx]->saidx.mode &&
998                     xh->mode != IPSEC_MODE_ANY)
999                         continue;
1000                 /*
1001                  * For transport mode IPsec request doesn't contain
1002                  * addresses. We need to use address from spidx.
1003                  */
1004                 if (sp->req[idx]->saidx.mode == IPSEC_MODE_TRANSPORT) {
1005                         if (key_sockaddrcmp_withmask(&xh->dst.sa,
1006                             &sp->spidx.dst.sa, sp->spidx.prefd) != 0)
1007                                 continue;
1008                 } else {
1009                         if (key_sockaddrcmp(&xh->dst.sa,
1010                             &sp->req[idx]->saidx.dst.sa, 0) != 0)
1011                                 continue;
1012                 }
1013                 return (0); /* matched */
1014         }
1015         return (1);
1016 }
1017
1018 /*
1019  * Check security policy requirements against the actual
1020  * packet contents.  Return one if the packet should be
1021  * reject as "invalid"; otherwiser return zero to have the
1022  * packet treated as "valid".
1023  *
1024  * OUT:
1025  *      0: valid
1026  *      1: invalid
1027  */
1028 static int
1029 ipsec_in_reject(struct secpolicy *sp, struct inpcb *inp, const struct mbuf *m)
1030 {
1031         int i;
1032
1033         KEYDBG(IPSEC_STAMP,
1034             printf("%s: PCB(%p): using SP(%p)\n", __func__, inp, sp));
1035         KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1036
1037         if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_in == NULL)
1038                 ipsec_cachepolicy(inp, sp, IPSEC_DIR_INBOUND);
1039
1040         /* Check policy. */
1041         switch (sp->policy) {
1042         case IPSEC_POLICY_DISCARD:
1043                 return (1);
1044         case IPSEC_POLICY_BYPASS:
1045         case IPSEC_POLICY_NONE:
1046                 return (0);
1047         }
1048
1049         IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1050                 ("invalid policy %u", sp->policy));
1051
1052         /*
1053          * ipsec[46]_common_input_cb after each transform adds
1054          * PACKET_TAG_IPSEC_IN_DONE mbuf tag. It contains SPI, proto, mode
1055          * and destination address from saidx. We can compare info from
1056          * these tags with requirements in SP.
1057          */
1058         for (i = 0; i < sp->tcount; i++) {
1059                 /*
1060                  * Do not check IPcomp, since IPcomp document
1061                  * says that we shouldn't compress small packets.
1062                  * IPComp policy should always be treated as being
1063                  * in "use" level.
1064                  */
1065                 if (sp->req[i]->saidx.proto == IPPROTO_IPCOMP ||
1066                     ipsec_get_reqlevel(sp, i) != IPSEC_LEVEL_REQUIRE)
1067                         continue;
1068                 if (V_check_policy_history != 0 &&
1069                     ipsec_check_history(m, sp, i) != 0)
1070                         return (1);
1071                 else switch (sp->req[i]->saidx.proto) {
1072                 case IPPROTO_ESP:
1073                         if ((m->m_flags & M_DECRYPTED) == 0) {
1074                                 KEYDBG(IPSEC_DUMP,
1075                                     printf("%s: ESP m_flags:%x\n", __func__,
1076                                             m->m_flags));
1077                                 return (1);
1078                         }
1079                         break;
1080                 case IPPROTO_AH:
1081                         if ((m->m_flags & M_AUTHIPHDR) == 0) {
1082                                 KEYDBG(IPSEC_DUMP,
1083                                     printf("%s: AH m_flags:%x\n", __func__,
1084                                             m->m_flags));
1085                                 return (1);
1086                         }
1087                         break;
1088                 }
1089         }
1090         return (0);             /* Valid. */
1091 }
1092
1093 /*
1094  * Compute the byte size to be occupied by IPsec header.
1095  * In case it is tunnelled, it includes the size of outer IP header.
1096  */
1097 static size_t
1098 ipsec_hdrsiz_internal(struct secpolicy *sp)
1099 {
1100         size_t size;
1101         int i;
1102
1103         KEYDBG(IPSEC_STAMP, printf("%s: using SP(%p)\n", __func__, sp));
1104         KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1105
1106         switch (sp->policy) {
1107         case IPSEC_POLICY_DISCARD:
1108         case IPSEC_POLICY_BYPASS:
1109         case IPSEC_POLICY_NONE:
1110                 return (0);
1111         }
1112
1113         IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1114                 ("invalid policy %u", sp->policy));
1115
1116         /*
1117          * XXX: for each transform we need to lookup suitable SA
1118          * and use info from SA to calculate headers size.
1119          * XXX: for NAT-T we need to cosider UDP header size.
1120          */
1121         size = 0;
1122         for (i = 0; i < sp->tcount; i++) {
1123                 switch (sp->req[i]->saidx.proto) {
1124                 case IPPROTO_ESP:
1125                         size += esp_hdrsiz(NULL);
1126                         break;
1127                 case IPPROTO_AH:
1128                         size += ah_hdrsiz(NULL);
1129                         break;
1130                 case IPPROTO_IPCOMP:
1131                         size += sizeof(struct ipcomp);
1132                         break;
1133                 }
1134
1135                 if (sp->req[i]->saidx.mode == IPSEC_MODE_TUNNEL) {
1136                         switch (sp->req[i]->saidx.dst.sa.sa_family) {
1137 #ifdef INET
1138                         case AF_INET:
1139                                 size += sizeof(struct ip);
1140                                 break;
1141 #endif
1142 #ifdef INET6
1143                         case AF_INET6:
1144                                 size += sizeof(struct ip6_hdr);
1145                                 break;
1146 #endif
1147                         default:
1148                                 ipseclog((LOG_ERR, "%s: unknown AF %d in "
1149                                     "IPsec tunnel SA\n", __func__,
1150                                     sp->req[i]->saidx.dst.sa.sa_family));
1151                                 break;
1152                         }
1153                 }
1154         }
1155         return (size);
1156 }
1157
1158 /*
1159  * Compute ESP/AH header size for protocols with PCB, including
1160  * outer IP header. Currently only tcp_output() uses it.
1161  */
1162 size_t
1163 ipsec_hdrsiz_inpcb(struct inpcb *inp)
1164 {
1165         struct secpolicyindex spidx;
1166         struct secpolicy *sp;
1167         size_t sz;
1168
1169         sp = ipsec_getpcbpolicy(inp, IPSEC_DIR_OUTBOUND);
1170         if (sp == NULL && key_havesp(IPSEC_DIR_OUTBOUND)) {
1171                 ipsec_setspidx_inpcb(inp, &spidx, IPSEC_DIR_OUTBOUND);
1172                 sp = key_allocsp(&spidx, IPSEC_DIR_OUTBOUND);
1173         }
1174         if (sp == NULL)
1175                 sp = key_allocsp_default();
1176         sz = ipsec_hdrsiz_internal(sp);
1177         key_freesp(&sp);
1178         return (sz);
1179 }
1180
1181 /*
1182  * Check the variable replay window.
1183  * ipsec_chkreplay() performs replay check before ICV verification.
1184  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1185  * ICV verification (it also performs replay check, which is usually done
1186  * beforehand).
1187  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1188  *
1189  * Based on RFC 6479. Blocks are 32 bits unsigned integers
1190  */
1191
1192 #define IPSEC_BITMAP_INDEX_MASK(w)      (w - 1)
1193 #define IPSEC_REDUNDANT_BIT_SHIFTS      5
1194 #define IPSEC_REDUNDANT_BITS            (1 << IPSEC_REDUNDANT_BIT_SHIFTS)
1195 #define IPSEC_BITMAP_LOC_MASK           (IPSEC_REDUNDANT_BITS - 1)
1196
1197 int
1198 ipsec_chkreplay(uint32_t seq, struct secasvar *sav)
1199 {
1200         const struct secreplay *replay;
1201         uint32_t wsizeb;                /* Constant: window size. */
1202         int index, bit_location;
1203
1204         IPSEC_ASSERT(sav != NULL, ("Null SA"));
1205         IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1206
1207         replay = sav->replay;
1208
1209         /* No need to check replay if disabled. */
1210         if (replay->wsize == 0)
1211                 return (1);
1212
1213         /* Constant. */
1214         wsizeb = replay->wsize << 3;
1215
1216         /* Sequence number of 0 is invalid. */
1217         if (seq == 0)
1218                 return (0);
1219
1220         /* First time is always okay. */
1221         if (replay->count == 0)
1222                 return (1);
1223
1224         /* Larger sequences are okay. */
1225         if (seq > replay->lastseq)
1226                 return (1);
1227
1228         /* Over range to check, i.e. too old or wrapped. */
1229         if (replay->lastseq - seq >= wsizeb)
1230                 return (0);
1231
1232         /* The sequence is inside the sliding window
1233          * now check the bit in the bitmap
1234          * bit location only depends on the sequence number
1235          */
1236         bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1237         index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1238                 & IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1239
1240         /* This packet already seen? */
1241         if ((replay->bitmap)[index] & (1 << bit_location))
1242                 return (0);
1243         return (1);
1244 }
1245
1246 /*
1247  * Check replay counter whether to update or not.
1248  * OUT: 0:      OK
1249  *      1:      NG
1250  */
1251 int
1252 ipsec_updatereplay(uint32_t seq, struct secasvar *sav)
1253 {
1254         char buf[128];
1255         struct secreplay *replay;
1256         uint32_t wsizeb;                /* Constant: window size. */
1257         int diff, index, bit_location;
1258
1259         IPSEC_ASSERT(sav != NULL, ("Null SA"));
1260         IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1261
1262         replay = sav->replay;
1263
1264         if (replay->wsize == 0)
1265                 goto ok;        /* No need to check replay. */
1266
1267         /* Constant. */
1268         wsizeb = replay->wsize << 3;
1269
1270         /* Sequence number of 0 is invalid. */
1271         if (seq == 0)
1272                 return (1);
1273
1274         /* The packet is too old, no need to update */
1275         if (wsizeb + seq < replay->lastseq)
1276                 goto ok;
1277
1278         /* Now update the bit */
1279         index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS);
1280
1281         /* First check if the sequence number is in the range */
1282         if (seq > replay->lastseq) {
1283                 int id;
1284                 int index_cur = replay->lastseq >> IPSEC_REDUNDANT_BIT_SHIFTS;
1285
1286                 diff = index - index_cur;
1287                 if (diff > replay->bitmap_size) {
1288                         /* something unusual in this case */
1289                         diff = replay->bitmap_size;
1290                 }
1291
1292                 for (id = 0; id < diff; ++id) {
1293                         replay->bitmap[(id + index_cur + 1)
1294                         & IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
1295                 }
1296
1297                 replay->lastseq = seq;
1298         }
1299
1300         index &= IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1301         bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1302
1303         /* this packet has already been received */
1304         if (replay->bitmap[index] & (1 << bit_location))
1305                 return (1);
1306
1307         replay->bitmap[index] |= (1 << bit_location);
1308
1309 ok:
1310         if (replay->count == ~0) {
1311
1312                 /* Set overflow flag. */
1313                 replay->overflow++;
1314
1315                 /* Don't increment, no more packets accepted. */
1316                 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1317                         if (sav->sah->saidx.proto == IPPROTO_AH)
1318                                 AHSTAT_INC(ahs_wrap);
1319                         else if (sav->sah->saidx.proto == IPPROTO_ESP)
1320                                 ESPSTAT_INC(esps_wrap);
1321                         return (1);
1322                 }
1323
1324                 ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1325                     __func__, replay->overflow,
1326                     ipsec_sa2str(sav, buf, sizeof(buf))));
1327         }
1328
1329         replay->count++;
1330         return (0);
1331 }
1332
1333 int
1334 ipsec_updateid(struct secasvar *sav, crypto_session_t *new,
1335     crypto_session_t *old)
1336 {
1337         crypto_session_t tmp;
1338
1339         /*
1340          * tdb_cryptoid is initialized by xform_init().
1341          * Then it can be changed only when some crypto error occurred or
1342          * when SA is deleted. We stored used cryptoid in the xform_data
1343          * structure. In case when crypto error occurred and crypto
1344          * subsystem has reinited the session, it returns new cryptoid
1345          * and EAGAIN error code.
1346          *
1347          * This function will be called when we got EAGAIN from crypto
1348          * subsystem.
1349          * *new is cryptoid that was returned by crypto subsystem in
1350          * the crp_sid.
1351          * *old is the original cryptoid that we stored in xform_data.
1352          *
1353          * For first failed request *old == sav->tdb_cryptoid, then
1354          * we update sav->tdb_cryptoid and redo crypto_dispatch().
1355          * For next failed request *old != sav->tdb_cryptoid, then
1356          * we store cryptoid from first request into the *new variable
1357          * and crp_sid from this second session will be returned via
1358          * *old pointer, so caller can release second session.
1359          *
1360          * XXXAE: check this more carefully.
1361          */
1362         KEYDBG(IPSEC_STAMP,
1363             printf("%s: SA(%p) moves cryptoid %p -> %p\n",
1364                 __func__, sav, *old, *new));
1365         KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1366         SECASVAR_LOCK(sav);
1367         if (sav->tdb_cryptoid != *old) {
1368                 /* cryptoid was already updated */
1369                 tmp = *new;
1370                 *new = sav->tdb_cryptoid;
1371                 *old = tmp;
1372                 SECASVAR_UNLOCK(sav);
1373                 return (1);
1374         }
1375         sav->tdb_cryptoid = *new;
1376         SECASVAR_UNLOCK(sav);
1377         return (0);
1378 }
1379
1380 int
1381 ipsec_initialized(void)
1382 {
1383
1384         return (V_def_policy != NULL);
1385 }
1386
1387 static void
1388 def_policy_init(const void *unused __unused)
1389 {
1390
1391         V_def_policy = key_newsp();
1392         if (V_def_policy != NULL) {
1393                 V_def_policy->policy = IPSEC_POLICY_NONE;
1394                 /* Force INPCB SP cache invalidation */
1395                 key_bumpspgen();
1396         } else
1397                 printf("%s: failed to initialize default policy\n", __func__);
1398 }
1399
1400
1401 static void
1402 def_policy_uninit(const void *unused __unused)
1403 {
1404
1405         if (V_def_policy != NULL) {
1406                 key_freesp(&V_def_policy);
1407                 key_bumpspgen();
1408         }
1409 }
1410
1411 VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1412     def_policy_init, NULL);
1413 VNET_SYSUNINIT(def_policy_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1414     def_policy_uninit, NULL);