2 /* $KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $ */
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * IPsec controller part.
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
45 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/errno.h>
51 #include <sys/hhook.h>
53 #include <sys/kernel.h>
54 #include <sys/syslog.h>
55 #include <sys/sysctl.h>
59 #include <net/if_enc.h>
60 #include <net/if_var.h>
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip_var.h>
67 #include <netinet/in_var.h>
68 #include <netinet/udp.h>
69 #include <netinet/udp_var.h>
70 #include <netinet/tcp.h>
71 #include <netinet/udp.h>
73 #include <netinet/ip6.h>
75 #include <netinet6/ip6_var.h>
77 #include <netinet/in_pcb.h>
79 #include <netinet/icmp6.h>
82 #include <sys/types.h>
83 #include <netipsec/ipsec.h>
85 #include <netipsec/ipsec6.h>
87 #include <netipsec/ah_var.h>
88 #include <netipsec/esp_var.h>
89 #include <netipsec/ipcomp.h> /*XXX*/
90 #include <netipsec/ipcomp_var.h>
91 #include <netipsec/ipsec_support.h>
93 #include <netipsec/key.h>
94 #include <netipsec/keydb.h>
95 #include <netipsec/key_debug.h>
97 #include <netipsec/xform.h>
99 #include <machine/in_cksum.h>
101 #include <opencrypto/cryptodev.h>
103 /* NB: name changed so netstat doesn't use it. */
104 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec4stat);
105 VNET_PCPUSTAT_SYSINIT(ipsec4stat);
108 VNET_PCPUSTAT_SYSUNINIT(ipsec4stat);
111 VNET_DEFINE(int, ip4_ah_offsetmask) = 0; /* maybe IP_DF? */
112 /* DF bit on encap. 0: clear 1: set 2: copy */
113 VNET_DEFINE(int, ip4_ipsec_dfbit) = 0;
114 VNET_DEFINE(int, ip4_esp_trans_deflev) = IPSEC_LEVEL_USE;
115 VNET_DEFINE(int, ip4_esp_net_deflev) = IPSEC_LEVEL_USE;
116 VNET_DEFINE(int, ip4_ah_trans_deflev) = IPSEC_LEVEL_USE;
117 VNET_DEFINE(int, ip4_ah_net_deflev) = IPSEC_LEVEL_USE;
118 /* ECN ignore(-1)/forbidden(0)/allowed(1) */
119 VNET_DEFINE(int, ip4_ipsec_ecn) = 0;
120 VNET_DEFINE(int, ip4_esp_randpad) = -1;
122 static VNET_DEFINE(int, ip4_filtertunnel) = 0;
123 #define V_ip4_filtertunnel VNET(ip4_filtertunnel)
124 static VNET_DEFINE(int, check_policy_history) = 0;
125 #define V_check_policy_history VNET(check_policy_history)
126 static VNET_DEFINE(struct secpolicy *, def_policy) = NULL;
127 #define V_def_policy VNET(def_policy)
129 sysctl_def_policy(SYSCTL_HANDLER_ARGS)
133 value = V_def_policy->policy;
134 error = sysctl_handle_int(oidp, &value, 0, req);
136 if (value != IPSEC_POLICY_DISCARD &&
137 value != IPSEC_POLICY_NONE)
139 V_def_policy->policy = value;
145 * Crypto support requirements:
147 * 1 require hardware support
148 * -1 require software support
151 VNET_DEFINE(int, crypto_support) = CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
153 * TCP/UDP checksum handling policy for transport mode NAT-T (RFC3948)
155 * 0 - auto: incrementally recompute, when checksum delta is known;
156 * if checksum delta isn't known, reset checksum to zero for UDP,
157 * and mark csum_flags as valid for TCP.
158 * 1 - fully recompute TCP/UDP checksum.
160 VNET_DEFINE(int, natt_cksum_policy) = 0;
162 FEATURE(ipsec, "Internet Protocol Security (IPsec)");
163 FEATURE(ipsec_natt, "UDP Encapsulation of IPsec ESP Packets ('NAT-T')");
165 SYSCTL_DECL(_net_inet_ipsec);
168 SYSCTL_PROC(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy,
169 CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW, 0, 0, sysctl_def_policy, "I",
170 "IPsec default policy.");
171 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
172 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0,
173 "Default ESP transport mode level");
174 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
175 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0,
176 "Default ESP tunnel mode level.");
177 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
178 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0,
179 "AH transfer mode default level.");
180 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
181 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0,
182 "AH tunnel mode default level.");
183 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos,
184 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0,
185 "If set, clear type-of-service field when doing AH computation.");
186 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK, ah_offsetmask,
187 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_offsetmask), 0,
188 "If not set, clear offset field mask when doing AH computation.");
189 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit,
190 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0,
191 "Do not fragment bit on encap.");
192 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn,
193 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0,
194 "Explicit Congestion Notification handling.");
195 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, crypto_support,
196 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(crypto_support), 0,
197 "Crypto driver selection.");
198 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, check_policy_history,
199 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(check_policy_history), 0,
200 "Use strict check of inbound packets to security policy compliance.");
201 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, natt_cksum_policy,
202 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(natt_cksum_policy), 0,
203 "Method to fix TCP/UDP checksum for transport mode IPsec after NAT.");
204 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, filtertunnel,
205 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_filtertunnel), 0,
206 "If set, filter packets from an IPsec tunnel.");
207 SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat,
208 ipsec4stat, "IPsec IPv4 statistics.");
212 * When set to 1, IPsec will send packets with the same sequence number.
213 * This allows to verify if the other side has proper replay attacks detection.
215 VNET_DEFINE(int, ipsec_replay) = 0;
216 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay,
217 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0,
218 "Emulate replay attack");
220 * When set 1, IPsec will send packets with corrupted HMAC.
221 * This allows to verify if the other side properly detects modified packets.
223 VNET_DEFINE(int, ipsec_integrity) = 0;
224 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity,
225 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0,
226 "Emulate man-in-the-middle attack");
230 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat);
231 VNET_PCPUSTAT_SYSINIT(ipsec6stat);
234 VNET_PCPUSTAT_SYSUNINIT(ipsec6stat);
237 VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE;
238 VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE;
239 VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE;
240 VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE;
241 VNET_DEFINE(int, ip6_ipsec_ecn) = 0; /* ECN ignore(-1)/forbidden(0)/allowed(1) */
243 static VNET_DEFINE(int, ip6_filtertunnel) = 0;
244 #define V_ip6_filtertunnel VNET(ip6_filtertunnel)
246 SYSCTL_DECL(_net_inet6_ipsec6);
248 /* net.inet6.ipsec6 */
249 SYSCTL_PROC(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy,
250 CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW, 0, 0, sysctl_def_policy, "I",
251 "IPsec default policy.");
252 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
253 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0,
254 "Default ESP transport mode level.");
255 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
256 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev), 0,
257 "Default ESP tunnel mode level.");
258 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
259 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev), 0,
260 "AH transfer mode default level.");
261 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
262 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev), 0,
263 "AH tunnel mode default level.");
264 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN, ecn,
265 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn), 0,
266 "Explicit Congestion Notification handling.");
267 SYSCTL_INT(_net_inet6_ipsec6, OID_AUTO, filtertunnel,
268 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_filtertunnel), 0,
269 "If set, filter packets from an IPsec tunnel.");
270 SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats,
271 struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics.");
274 static int ipsec_in_reject(struct secpolicy *, struct inpcb *,
275 const struct mbuf *);
278 static void ipsec4_get_ulp(const struct mbuf *, struct secpolicyindex *, int);
279 static void ipsec4_setspidx_ipaddr(const struct mbuf *,
280 struct secpolicyindex *);
283 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
284 static void ipsec6_setspidx_ipaddr(const struct mbuf *,
285 struct secpolicyindex *);
289 * Return a held reference to the default SP.
291 static struct secpolicy *
292 key_allocsp_default(void)
295 key_addref(V_def_policy);
296 return (V_def_policy);
300 ipsec_invalidate_cache(struct inpcb *inp, u_int dir)
302 struct secpolicy *sp;
304 INP_WLOCK_ASSERT(inp);
305 if (dir == IPSEC_DIR_OUTBOUND) {
306 if (inp->inp_sp->flags & INP_INBOUND_POLICY)
308 sp = inp->inp_sp->sp_in;
309 inp->inp_sp->sp_in = NULL;
311 if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
313 sp = inp->inp_sp->sp_out;
314 inp->inp_sp->sp_out = NULL;
317 key_freesp(&sp); /* release extra reference */
321 ipsec_cachepolicy(struct inpcb *inp, struct secpolicy *sp, u_int dir)
326 INP_LOCK_ASSERT(inp);
328 if (dir == IPSEC_DIR_OUTBOUND) {
329 /* Do we have configured PCB policy? */
330 if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
332 /* Another thread has already set cached policy */
333 if (inp->inp_sp->sp_out != NULL)
336 * Do not cache OUTBOUND policy if PCB isn't connected,
337 * i.e. foreign address is INADDR_ANY/UNSPECIFIED.
340 if ((inp->inp_vflag & INP_IPV4) != 0 &&
341 inp->inp_faddr.s_addr == INADDR_ANY)
345 if ((inp->inp_vflag & INP_IPV6) != 0 &&
346 IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
350 /* Do we have configured PCB policy? */
351 if (inp->inp_sp->flags & INP_INBOUND_POLICY)
353 /* Another thread has already set cached policy */
354 if (inp->inp_sp->sp_in != NULL)
357 * Do not cache INBOUND policy for listen socket,
358 * that is bound to INADDR_ANY/UNSPECIFIED address.
361 if ((inp->inp_vflag & INP_IPV4) != 0 &&
362 inp->inp_faddr.s_addr == INADDR_ANY)
366 if ((inp->inp_vflag & INP_IPV6) != 0 &&
367 IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
372 if (!INP_WLOCKED(inp)) {
373 if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
376 if (dir == IPSEC_DIR_OUTBOUND)
377 inp->inp_sp->sp_out = sp;
379 inp->inp_sp->sp_in = sp;
381 * SP is already referenced by the lookup code.
382 * We take extra reference here to avoid race in the
383 * ipsec_getpcbpolicy() function - SP will not be freed in the
384 * time between we take SP pointer from the cache and key_addref()
388 genid = key_getspgen();
389 if (genid != inp->inp_sp->genid) {
390 ipsec_invalidate_cache(inp, dir);
391 inp->inp_sp->genid = genid;
394 printf("%s: PCB(%p): cached %s SP(%p)\n",
395 __func__, inp, dir == IPSEC_DIR_OUTBOUND ? "OUTBOUND":
401 static struct secpolicy *
402 ipsec_checkpolicy(struct secpolicy *sp, struct inpcb *inp, int *error)
405 /* Save found OUTBOUND policy into PCB SP cache. */
406 if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_out == NULL)
407 ipsec_cachepolicy(inp, sp, IPSEC_DIR_OUTBOUND);
409 switch (sp->policy) {
411 printf("%s: invalid policy %u\n", __func__, sp->policy);
413 case IPSEC_POLICY_DISCARD:
414 *error = -EINVAL; /* Packet is discarded by caller. */
416 case IPSEC_POLICY_BYPASS:
417 case IPSEC_POLICY_NONE:
419 sp = NULL; /* NB: force NULL result. */
421 case IPSEC_POLICY_IPSEC:
422 /* XXXAE: handle LARVAL SP */
426 printf("%s: get SP(%p), error %d\n", __func__, sp, *error));
430 static struct secpolicy *
431 ipsec_getpcbpolicy(struct inpcb *inp, u_int dir)
433 struct secpolicy *sp;
434 int flags, downgrade;
436 if (inp == NULL || inp->inp_sp == NULL)
439 INP_LOCK_ASSERT(inp);
441 flags = inp->inp_sp->flags;
442 if (dir == IPSEC_DIR_OUTBOUND) {
443 sp = inp->inp_sp->sp_out;
444 flags &= INP_OUTBOUND_POLICY;
446 sp = inp->inp_sp->sp_in;
447 flags &= INP_INBOUND_POLICY;
450 * Check flags. If we have PCB SP, just return it.
451 * Otherwise we need to check that cached SP entry isn't stale.
456 if (inp->inp_sp->genid != key_getspgen()) {
457 /* Invalidate the cache. */
459 if (!INP_WLOCKED(inp)) {
460 if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
463 ipsec_invalidate_cache(inp, IPSEC_DIR_OUTBOUND);
464 ipsec_invalidate_cache(inp, IPSEC_DIR_INBOUND);
470 printf("%s: PCB(%p): cache hit SP(%p)\n",
472 /* Return referenced cached policy */
480 ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
487 IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
488 ("packet too short"));
490 if (m->m_len >= sizeof (struct ip)) {
491 const struct ip *ip = mtod(m, const struct ip *);
492 if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
494 off = ip->ip_hl << 2;
499 m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
500 if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
506 while (off < m->m_pkthdr.len) {
513 spidx->ul_proto = nxt;
516 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
518 m_copydata(m, off, sizeof (th), (caddr_t) &th);
519 spidx->src.sin.sin_port = th.th_sport;
520 spidx->dst.sin.sin_port = th.th_dport;
523 spidx->ul_proto = nxt;
526 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
528 m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
529 spidx->src.sin.sin_port = uh.uh_sport;
530 spidx->dst.sin.sin_port = uh.uh_dport;
533 if (off + sizeof(ip6e) > m->m_pkthdr.len)
535 /* XXX Sigh, this works but is totally bogus. */
536 m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
537 off += (ip6e.ip6e_len + 2) << 2;
542 /* XXX Intermediate headers??? */
543 spidx->ul_proto = nxt;
548 spidx->ul_proto = IPSEC_ULPROTO_ANY;
550 spidx->src.sin.sin_port = IPSEC_PORT_ANY;
551 spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
553 printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
557 ipsec4_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
560 ipsec4_setsockaddrs(m, &spidx->src, &spidx->dst);
561 spidx->prefs = sizeof(struct in_addr) << 3;
562 spidx->prefd = sizeof(struct in_addr) << 3;
565 static struct secpolicy *
566 ipsec4_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir)
568 struct secpolicyindex spidx;
569 struct secpolicy *sp;
571 sp = ipsec_getpcbpolicy(inp, dir);
572 if (sp == NULL && key_havesp(dir)) {
573 /* Make an index to look for a policy. */
574 ipsec4_setspidx_ipaddr(m, &spidx);
575 /* Fill ports in spidx if we have inpcb. */
576 ipsec4_get_ulp(m, &spidx, inp != NULL);
578 sp = key_allocsp(&spidx, dir);
580 if (sp == NULL) /* No SP found, use system default. */
581 sp = key_allocsp_default();
586 * Check security policy for *OUTBOUND* IPv4 packet.
589 ipsec4_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error)
591 struct secpolicy *sp;
594 sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_OUTBOUND);
596 sp = ipsec_checkpolicy(sp, inp, error);
599 case 0: /* No IPsec required: BYPASS or NONE */
602 IPSECSTAT_INC(ips_out_polvio);
605 IPSECSTAT_INC(ips_out_inval);
609 printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
611 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
616 * Check IPv4 packet against *INBOUND* security policy.
617 * This function is called from tcp_input(), udp_input(),
618 * rip_input() and sctp_input().
621 ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
623 struct secpolicy *sp;
626 sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_INBOUND);
627 result = ipsec_in_reject(sp, inp, m);
630 IPSECSTAT_INC(ips_in_polvio);
635 * IPSEC_CAP() method implementation for IPv4.
638 ipsec4_capability(struct mbuf *m, u_int cap)
642 case IPSEC_CAP_BYPASS_FILTER:
644 * Bypass packet filtering for packets previously handled
647 if (!V_ip4_filtertunnel &&
648 m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
651 case IPSEC_CAP_OPERABLE:
652 /* Do we have active security policies? */
653 if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
654 key_havesp(IPSEC_DIR_OUTBOUND) != 0)
665 ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
673 IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip6_hdr),
674 ("packet too short"));
677 spidx->ul_proto = IPSEC_ULPROTO_ANY;
678 spidx->src.sin6.sin6_port = IPSEC_PORT_ANY;
679 spidx->dst.sin6.sin6_port = IPSEC_PORT_ANY;
682 off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
683 if (off < 0 || m->m_pkthdr.len < off)
688 spidx->ul_proto = nxt;
691 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
693 m_copydata(m, off, sizeof(th), (caddr_t)&th);
694 spidx->src.sin6.sin6_port = th.th_sport;
695 spidx->dst.sin6.sin6_port = th.th_dport;
698 spidx->ul_proto = nxt;
701 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
703 m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
704 spidx->src.sin6.sin6_port = uh.uh_sport;
705 spidx->dst.sin6.sin6_port = uh.uh_dport;
708 spidx->ul_proto = nxt;
709 if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
711 m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
712 spidx->src.sin6.sin6_port = htons((uint16_t)ih.icmp6_type);
713 spidx->dst.sin6.sin6_port = htons((uint16_t)ih.icmp6_code);
716 /* XXX Intermediate headers??? */
717 spidx->ul_proto = nxt;
721 printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
725 ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
728 ipsec6_setsockaddrs(m, &spidx->src, &spidx->dst);
729 spidx->prefs = sizeof(struct in6_addr) << 3;
730 spidx->prefd = sizeof(struct in6_addr) << 3;
733 static struct secpolicy *
734 ipsec6_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir)
736 struct secpolicyindex spidx;
737 struct secpolicy *sp;
739 sp = ipsec_getpcbpolicy(inp, dir);
740 if (sp == NULL && key_havesp(dir)) {
741 /* Make an index to look for a policy. */
742 ipsec6_setspidx_ipaddr(m, &spidx);
743 /* Fill ports in spidx if we have inpcb. */
744 ipsec6_get_ulp(m, &spidx, inp != NULL);
746 sp = key_allocsp(&spidx, dir);
748 if (sp == NULL) /* No SP found, use system default. */
749 sp = key_allocsp_default();
754 * Check security policy for *OUTBOUND* IPv6 packet.
757 ipsec6_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error)
759 struct secpolicy *sp;
762 sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_OUTBOUND);
764 sp = ipsec_checkpolicy(sp, inp, error);
767 case 0: /* No IPsec required: BYPASS or NONE */
770 IPSEC6STAT_INC(ips_out_polvio);
773 IPSEC6STAT_INC(ips_out_inval);
777 printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
779 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
784 * Check IPv6 packet against inbound security policy.
785 * This function is called from tcp6_input(), udp6_input(),
786 * rip6_input() and sctp_input().
789 ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
791 struct secpolicy *sp;
794 sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_INBOUND);
795 result = ipsec_in_reject(sp, inp, m);
798 IPSEC6STAT_INC(ips_in_polvio);
803 * IPSEC_CAP() method implementation for IPv6.
806 ipsec6_capability(struct mbuf *m, u_int cap)
810 case IPSEC_CAP_BYPASS_FILTER:
812 * Bypass packet filtering for packets previously handled
815 if (!V_ip6_filtertunnel &&
816 m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
819 case IPSEC_CAP_OPERABLE:
820 /* Do we have active security policies? */
821 if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
822 key_havesp(IPSEC_DIR_OUTBOUND) != 0)
831 ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type)
838 idx = HHOOK_IPSEC_INET;
843 idx = HHOOK_IPSEC_INET6;
847 return (EPFNOSUPPORT);
849 if (type == HHOOK_TYPE_IPSEC_IN)
850 HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL);
852 HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL);
853 if (*ctx->mp == NULL)
859 * Return current level.
860 * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
863 ipsec_get_reqlevel(struct secpolicy *sp, u_int idx)
865 struct ipsecrequest *isr;
866 u_int esp_trans_deflev, esp_net_deflev;
867 u_int ah_trans_deflev, ah_net_deflev;
870 IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
871 /* XXX Note that we have ipseclog() expanded here - code sync issue. */
872 #define IPSEC_CHECK_DEFAULT(lev) \
873 (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE && \
874 (lev) != IPSEC_LEVEL_UNIQUE) \
876 log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
877 (lev), IPSEC_LEVEL_REQUIRE) : 0), \
878 (lev) = IPSEC_LEVEL_REQUIRE, (lev) : (lev))
881 * IPsec VTI uses unique security policy with fake spidx filled
882 * with zeroes. Just return IPSEC_LEVEL_REQUIRE instead of doing
883 * full level lookup for such policies.
885 if (sp->state == IPSEC_SPSTATE_IFNET) {
886 IPSEC_ASSERT(sp->req[idx]->level == IPSEC_LEVEL_UNIQUE,
887 ("Wrong IPsec request level %d", sp->req[idx]->level));
888 return (IPSEC_LEVEL_REQUIRE);
891 /* Set default level. */
892 switch (sp->spidx.src.sa.sa_family) {
895 esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev);
896 esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev);
897 ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev);
898 ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev);
903 esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev);
904 esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev);
905 ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev);
906 ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev);
910 panic("%s: unknown af %u",
911 __func__, sp->spidx.src.sa.sa_family);
914 #undef IPSEC_CHECK_DEFAULT
918 switch (isr->level) {
919 case IPSEC_LEVEL_DEFAULT:
920 switch (isr->saidx.proto) {
922 if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
923 level = esp_net_deflev;
925 level = esp_trans_deflev;
928 if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
929 level = ah_net_deflev;
931 level = ah_trans_deflev;
935 * We don't really care, as IPcomp document says that
936 * we shouldn't compress small packets.
938 level = IPSEC_LEVEL_USE;
941 panic("%s: Illegal protocol defined %u\n", __func__,
946 case IPSEC_LEVEL_USE:
947 case IPSEC_LEVEL_REQUIRE:
950 case IPSEC_LEVEL_UNIQUE:
951 level = IPSEC_LEVEL_REQUIRE;
955 panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
962 ipsec_check_history(const struct mbuf *m, struct secpolicy *sp, u_int idx)
964 struct xform_history *xh;
968 while ((mtag = m_tag_find(__DECONST(struct mbuf *, m),
969 PACKET_TAG_IPSEC_IN_DONE, mtag)) != NULL) {
970 xh = (struct xform_history *)(mtag + 1);
972 char buf[IPSEC_ADDRSTRLEN];
973 printf("%s: mode %s proto %u dst %s\n", __func__,
974 kdebug_secasindex_mode(xh->mode), xh->proto,
975 ipsec_address(&xh->dst, buf, sizeof(buf))));
976 if (xh->proto != sp->req[idx]->saidx.proto)
978 /* If SA had IPSEC_MODE_ANY, consider this as match. */
979 if (xh->mode != sp->req[idx]->saidx.mode &&
980 xh->mode != IPSEC_MODE_ANY)
983 * For transport mode IPsec request doesn't contain
984 * addresses. We need to use address from spidx.
986 if (sp->req[idx]->saidx.mode == IPSEC_MODE_TRANSPORT) {
987 if (key_sockaddrcmp_withmask(&xh->dst.sa,
988 &sp->spidx.dst.sa, sp->spidx.prefd) != 0)
991 if (key_sockaddrcmp(&xh->dst.sa,
992 &sp->req[idx]->saidx.dst.sa, 0) != 0)
995 return (0); /* matched */
1001 * Check security policy requirements against the actual
1002 * packet contents. Return one if the packet should be
1003 * reject as "invalid"; otherwiser return zero to have the
1004 * packet treated as "valid".
1011 ipsec_in_reject(struct secpolicy *sp, struct inpcb *inp, const struct mbuf *m)
1016 printf("%s: PCB(%p): using SP(%p)\n", __func__, inp, sp));
1017 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1019 if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_in == NULL)
1020 ipsec_cachepolicy(inp, sp, IPSEC_DIR_INBOUND);
1023 switch (sp->policy) {
1024 case IPSEC_POLICY_DISCARD:
1026 case IPSEC_POLICY_BYPASS:
1027 case IPSEC_POLICY_NONE:
1031 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1032 ("invalid policy %u", sp->policy));
1035 * ipsec[46]_common_input_cb after each transform adds
1036 * PACKET_TAG_IPSEC_IN_DONE mbuf tag. It contains SPI, proto, mode
1037 * and destination address from saidx. We can compare info from
1038 * these tags with requirements in SP.
1040 for (i = 0; i < sp->tcount; i++) {
1042 * Do not check IPcomp, since IPcomp document
1043 * says that we shouldn't compress small packets.
1044 * IPComp policy should always be treated as being
1047 if (sp->req[i]->saidx.proto == IPPROTO_IPCOMP ||
1048 ipsec_get_reqlevel(sp, i) != IPSEC_LEVEL_REQUIRE)
1050 if (V_check_policy_history != 0 &&
1051 ipsec_check_history(m, sp, i) != 0)
1053 else switch (sp->req[i]->saidx.proto) {
1055 if ((m->m_flags & M_DECRYPTED) == 0) {
1057 printf("%s: ESP m_flags:%x\n", __func__,
1063 if ((m->m_flags & M_AUTHIPHDR) == 0) {
1065 printf("%s: AH m_flags:%x\n", __func__,
1072 return (0); /* Valid. */
1076 * Compute the byte size to be occupied by IPsec header.
1077 * In case it is tunnelled, it includes the size of outer IP header.
1080 ipsec_hdrsiz_internal(struct secpolicy *sp)
1085 KEYDBG(IPSEC_STAMP, printf("%s: using SP(%p)\n", __func__, sp));
1086 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1088 switch (sp->policy) {
1089 case IPSEC_POLICY_DISCARD:
1090 case IPSEC_POLICY_BYPASS:
1091 case IPSEC_POLICY_NONE:
1095 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1096 ("invalid policy %u", sp->policy));
1099 * XXX: for each transform we need to lookup suitable SA
1100 * and use info from SA to calculate headers size.
1101 * XXX: for NAT-T we need to cosider UDP header size.
1104 for (i = 0; i < sp->tcount; i++) {
1105 switch (sp->req[i]->saidx.proto) {
1107 size += esp_hdrsiz(NULL);
1110 size += ah_hdrsiz(NULL);
1112 case IPPROTO_IPCOMP:
1113 size += sizeof(struct ipcomp);
1117 if (sp->req[i]->saidx.mode == IPSEC_MODE_TUNNEL) {
1118 switch (sp->req[i]->saidx.dst.sa.sa_family) {
1121 size += sizeof(struct ip);
1126 size += sizeof(struct ip6_hdr);
1130 ipseclog((LOG_ERR, "%s: unknown AF %d in "
1131 "IPsec tunnel SA\n", __func__,
1132 sp->req[i]->saidx.dst.sa.sa_family));
1141 * Compute ESP/AH header size for protocols with PCB, including
1142 * outer IP header. Currently only tcp_output() uses it.
1145 ipsec_hdrsiz_inpcb(struct inpcb *inp)
1147 struct secpolicyindex spidx;
1148 struct secpolicy *sp;
1151 sp = ipsec_getpcbpolicy(inp, IPSEC_DIR_OUTBOUND);
1152 if (sp == NULL && key_havesp(IPSEC_DIR_OUTBOUND)) {
1153 ipsec_setspidx_inpcb(inp, &spidx, IPSEC_DIR_OUTBOUND);
1154 sp = key_allocsp(&spidx, IPSEC_DIR_OUTBOUND);
1157 sp = key_allocsp_default();
1158 sz = ipsec_hdrsiz_internal(sp);
1164 * Check the variable replay window.
1165 * ipsec_chkreplay() performs replay check before ICV verification.
1166 * ipsec_updatereplay() updates replay bitmap. This must be called after
1167 * ICV verification (it also performs replay check, which is usually done
1169 * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1171 * Based on RFC 6479. Blocks are 32 bits unsigned integers
1174 #define IPSEC_BITMAP_INDEX_MASK(w) (w - 1)
1175 #define IPSEC_REDUNDANT_BIT_SHIFTS 5
1176 #define IPSEC_REDUNDANT_BITS (1 << IPSEC_REDUNDANT_BIT_SHIFTS)
1177 #define IPSEC_BITMAP_LOC_MASK (IPSEC_REDUNDANT_BITS - 1)
1180 ipsec_chkreplay(uint32_t seq, struct secasvar *sav)
1182 const struct secreplay *replay;
1183 uint32_t wsizeb; /* Constant: window size. */
1184 int index, bit_location;
1186 IPSEC_ASSERT(sav != NULL, ("Null SA"));
1187 IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1189 replay = sav->replay;
1191 /* No need to check replay if disabled. */
1192 if (replay->wsize == 0)
1196 wsizeb = replay->wsize << 3;
1198 /* Sequence number of 0 is invalid. */
1202 /* First time is always okay. */
1203 if (replay->count == 0)
1206 /* Larger sequences are okay. */
1207 if (seq > replay->lastseq)
1210 /* Over range to check, i.e. too old or wrapped. */
1211 if (replay->lastseq - seq >= wsizeb)
1214 /* The sequence is inside the sliding window
1215 * now check the bit in the bitmap
1216 * bit location only depends on the sequence number
1218 bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1219 index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1220 & IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1222 /* This packet already seen? */
1223 if ((replay->bitmap)[index] & (1 << bit_location))
1229 * Check replay counter whether to update or not.
1234 ipsec_updatereplay(uint32_t seq, struct secasvar *sav)
1237 struct secreplay *replay;
1238 uint32_t wsizeb; /* Constant: window size. */
1239 int diff, index, bit_location;
1241 IPSEC_ASSERT(sav != NULL, ("Null SA"));
1242 IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1244 replay = sav->replay;
1246 if (replay->wsize == 0)
1247 goto ok; /* No need to check replay. */
1250 wsizeb = replay->wsize << 3;
1252 /* Sequence number of 0 is invalid. */
1256 /* The packet is too old, no need to update */
1257 if (wsizeb + seq < replay->lastseq)
1260 /* Now update the bit */
1261 index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS);
1263 /* First check if the sequence number is in the range */
1264 if (seq > replay->lastseq) {
1266 int index_cur = replay->lastseq >> IPSEC_REDUNDANT_BIT_SHIFTS;
1268 diff = index - index_cur;
1269 if (diff > replay->bitmap_size) {
1270 /* something unusual in this case */
1271 diff = replay->bitmap_size;
1274 for (id = 0; id < diff; ++id) {
1275 replay->bitmap[(id + index_cur + 1)
1276 & IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
1279 replay->lastseq = seq;
1282 index &= IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1283 bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1285 /* this packet has already been received */
1286 if (replay->bitmap[index] & (1 << bit_location))
1289 replay->bitmap[index] |= (1 << bit_location);
1292 if (replay->count == ~0) {
1294 /* Set overflow flag. */
1297 /* Don't increment, no more packets accepted. */
1298 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1299 if (sav->sah->saidx.proto == IPPROTO_AH)
1300 AHSTAT_INC(ahs_wrap);
1301 else if (sav->sah->saidx.proto == IPPROTO_ESP)
1302 ESPSTAT_INC(esps_wrap);
1306 ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1307 __func__, replay->overflow,
1308 ipsec_sa2str(sav, buf, sizeof(buf))));
1314 ipsec_updateid(struct secasvar *sav, uint64_t *new, uint64_t *old)
1319 * tdb_cryptoid is initialized by xform_init().
1320 * Then it can be changed only when some crypto error occurred or
1321 * when SA is deleted. We stored used cryptoid in the xform_data
1322 * structure. In case when crypto error occurred and crypto
1323 * subsystem has reinited the session, it returns new cryptoid
1324 * and EAGAIN error code.
1326 * This function will be called when we got EAGAIN from crypto
1328 * *new is cryptoid that was returned by crypto subsystem in
1330 * *old is the original cryptoid that we stored in xform_data.
1332 * For first failed request *old == sav->tdb_cryptoid, then
1333 * we update sav->tdb_cryptoid and redo crypto_dispatch().
1334 * For next failed request *old != sav->tdb_cryptoid, then
1335 * we store cryptoid from first request into the *new variable
1336 * and crp_sid from this second session will be returned via
1337 * *old pointer, so caller can release second session.
1339 * XXXAE: check this more carefully.
1342 printf("%s: SA(%p) moves cryptoid %jd -> %jd\n",
1343 __func__, sav, (uintmax_t)(*old), (uintmax_t)(*new)));
1344 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1346 if (sav->tdb_cryptoid != *old) {
1347 /* cryptoid was already updated */
1349 *new = sav->tdb_cryptoid;
1351 SECASVAR_UNLOCK(sav);
1354 sav->tdb_cryptoid = *new;
1355 SECASVAR_UNLOCK(sav);
1360 ipsec_initialized(void)
1363 return (V_def_policy != NULL);
1367 def_policy_init(const void *unused __unused)
1370 V_def_policy = key_newsp();
1371 if (V_def_policy != NULL) {
1372 V_def_policy->policy = IPSEC_POLICY_NONE;
1373 /* Force INPCB SP cache invalidation */
1376 printf("%s: failed to initialize default policy\n", __func__);
1381 def_policy_uninit(const void *unused __unused)
1384 if (V_def_policy != NULL) {
1385 key_freesp(&V_def_policy);
1390 VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1391 def_policy_init, NULL);
1392 VNET_SYSUNINIT(def_policy_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1393 def_policy_uninit, NULL);