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 /* DF bit on encap. 0: clear 1: set 2: copy */
112 VNET_DEFINE(int, ip4_ipsec_dfbit) = 0;
113 VNET_DEFINE(int, ip4_esp_trans_deflev) = IPSEC_LEVEL_USE;
114 VNET_DEFINE(int, ip4_esp_net_deflev) = IPSEC_LEVEL_USE;
115 VNET_DEFINE(int, ip4_ah_trans_deflev) = IPSEC_LEVEL_USE;
116 VNET_DEFINE(int, ip4_ah_net_deflev) = IPSEC_LEVEL_USE;
117 /* ECN ignore(-1)/forbidden(0)/allowed(1) */
118 VNET_DEFINE(int, ip4_ipsec_ecn) = 0;
120 static VNET_DEFINE(int, ip4_filtertunnel) = 0;
121 #define V_ip4_filtertunnel VNET(ip4_filtertunnel)
122 static VNET_DEFINE(int, check_policy_history) = 0;
123 #define V_check_policy_history VNET(check_policy_history)
124 static VNET_DEFINE(struct secpolicy *, def_policy) = NULL;
125 #define V_def_policy VNET(def_policy)
127 sysctl_def_policy(SYSCTL_HANDLER_ARGS)
131 value = V_def_policy->policy;
132 error = sysctl_handle_int(oidp, &value, 0, req);
134 if (value != IPSEC_POLICY_DISCARD &&
135 value != IPSEC_POLICY_NONE)
137 V_def_policy->policy = value;
143 * Crypto support requirements:
145 * 1 require hardware support
146 * -1 require software support
149 VNET_DEFINE(int, crypto_support) = CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
151 * TCP/UDP checksum handling policy for transport mode NAT-T (RFC3948)
153 * 0 - auto: incrementally recompute, when checksum delta is known;
154 * if checksum delta isn't known, reset checksum to zero for UDP,
155 * and mark csum_flags as valid for TCP.
156 * 1 - fully recompute TCP/UDP checksum.
158 VNET_DEFINE(int, natt_cksum_policy) = 0;
160 FEATURE(ipsec, "Internet Protocol Security (IPsec)");
161 FEATURE(ipsec_natt, "UDP Encapsulation of IPsec ESP Packets ('NAT-T')");
163 SYSCTL_DECL(_net_inet_ipsec);
166 SYSCTL_PROC(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy,
167 CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW, 0, 0, sysctl_def_policy, "I",
168 "IPsec default policy.");
169 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
170 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0,
171 "Default ESP transport mode level");
172 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
173 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0,
174 "Default ESP tunnel mode level.");
175 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
176 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0,
177 "AH transfer mode default level.");
178 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
179 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0,
180 "AH tunnel mode default level.");
181 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos,
182 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0,
183 "If set, clear type-of-service field when doing AH computation.");
184 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit,
185 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0,
186 "Do not fragment bit on encap.");
187 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn,
188 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0,
189 "Explicit Congestion Notification handling.");
190 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, crypto_support,
191 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(crypto_support), 0,
192 "Crypto driver selection.");
193 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, check_policy_history,
194 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(check_policy_history), 0,
195 "Use strict check of inbound packets to security policy compliance.");
196 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, natt_cksum_policy,
197 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(natt_cksum_policy), 0,
198 "Method to fix TCP/UDP checksum for transport mode IPsec after NAT.");
199 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, filtertunnel,
200 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_filtertunnel), 0,
201 "If set, filter packets from an IPsec tunnel.");
202 SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat,
203 ipsec4stat, "IPsec IPv4 statistics.");
207 * When set to 1, IPsec will send packets with the same sequence number.
208 * This allows to verify if the other side has proper replay attacks detection.
210 VNET_DEFINE(int, ipsec_replay) = 0;
211 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay,
212 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0,
213 "Emulate replay attack");
215 * When set 1, IPsec will send packets with corrupted HMAC.
216 * This allows to verify if the other side properly detects modified packets.
218 VNET_DEFINE(int, ipsec_integrity) = 0;
219 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity,
220 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0,
221 "Emulate man-in-the-middle attack");
225 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat);
226 VNET_PCPUSTAT_SYSINIT(ipsec6stat);
229 VNET_PCPUSTAT_SYSUNINIT(ipsec6stat);
232 VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE;
233 VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE;
234 VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE;
235 VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE;
236 VNET_DEFINE(int, ip6_ipsec_ecn) = 0; /* ECN ignore(-1)/forbidden(0)/allowed(1) */
238 static VNET_DEFINE(int, ip6_filtertunnel) = 0;
239 #define V_ip6_filtertunnel VNET(ip6_filtertunnel)
241 SYSCTL_DECL(_net_inet6_ipsec6);
243 /* net.inet6.ipsec6 */
244 SYSCTL_PROC(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy,
245 CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW, 0, 0, sysctl_def_policy, "I",
246 "IPsec default policy.");
247 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
248 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0,
249 "Default ESP transport mode level.");
250 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
251 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev), 0,
252 "Default ESP tunnel mode level.");
253 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
254 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev), 0,
255 "AH transfer mode default level.");
256 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
257 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev), 0,
258 "AH tunnel mode default level.");
259 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN, ecn,
260 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn), 0,
261 "Explicit Congestion Notification handling.");
262 SYSCTL_INT(_net_inet6_ipsec6, OID_AUTO, filtertunnel,
263 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_filtertunnel), 0,
264 "If set, filter packets from an IPsec tunnel.");
265 SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats,
266 struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics.");
269 static int ipsec_in_reject(struct secpolicy *, struct inpcb *,
270 const struct mbuf *);
273 static void ipsec4_get_ulp(const struct mbuf *, struct secpolicyindex *, int);
274 static void ipsec4_setspidx_ipaddr(const struct mbuf *,
275 struct secpolicyindex *);
278 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
279 static void ipsec6_setspidx_ipaddr(const struct mbuf *,
280 struct secpolicyindex *);
284 * Return a held reference to the default SP.
286 static struct secpolicy *
287 key_allocsp_default(void)
290 key_addref(V_def_policy);
291 return (V_def_policy);
295 ipsec_invalidate_cache(struct inpcb *inp, u_int dir)
297 struct secpolicy *sp;
299 INP_WLOCK_ASSERT(inp);
300 if (dir == IPSEC_DIR_OUTBOUND) {
301 if (inp->inp_sp->flags & INP_INBOUND_POLICY)
303 sp = inp->inp_sp->sp_in;
304 inp->inp_sp->sp_in = NULL;
306 if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
308 sp = inp->inp_sp->sp_out;
309 inp->inp_sp->sp_out = NULL;
312 key_freesp(&sp); /* release extra reference */
316 ipsec_cachepolicy(struct inpcb *inp, struct secpolicy *sp, u_int dir)
321 INP_LOCK_ASSERT(inp);
323 if (dir == IPSEC_DIR_OUTBOUND) {
324 /* Do we have configured PCB policy? */
325 if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
327 /* Another thread has already set cached policy */
328 if (inp->inp_sp->sp_out != NULL)
331 * Do not cache OUTBOUND policy if PCB isn't connected,
332 * i.e. foreign address is INADDR_ANY/UNSPECIFIED.
335 if ((inp->inp_vflag & INP_IPV4) != 0 &&
336 inp->inp_faddr.s_addr == INADDR_ANY)
340 if ((inp->inp_vflag & INP_IPV6) != 0 &&
341 IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
345 /* Do we have configured PCB policy? */
346 if (inp->inp_sp->flags & INP_INBOUND_POLICY)
348 /* Another thread has already set cached policy */
349 if (inp->inp_sp->sp_in != NULL)
352 * Do not cache INBOUND policy for listen socket,
353 * that is bound to INADDR_ANY/UNSPECIFIED address.
356 if ((inp->inp_vflag & INP_IPV4) != 0 &&
357 inp->inp_faddr.s_addr == INADDR_ANY)
361 if ((inp->inp_vflag & INP_IPV6) != 0 &&
362 IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
367 if (!INP_WLOCKED(inp)) {
368 if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
371 if (dir == IPSEC_DIR_OUTBOUND)
372 inp->inp_sp->sp_out = sp;
374 inp->inp_sp->sp_in = sp;
376 * SP is already referenced by the lookup code.
377 * We take extra reference here to avoid race in the
378 * ipsec_getpcbpolicy() function - SP will not be freed in the
379 * time between we take SP pointer from the cache and key_addref()
383 genid = key_getspgen();
384 if (genid != inp->inp_sp->genid) {
385 ipsec_invalidate_cache(inp, dir);
386 inp->inp_sp->genid = genid;
389 printf("%s: PCB(%p): cached %s SP(%p)\n",
390 __func__, inp, dir == IPSEC_DIR_OUTBOUND ? "OUTBOUND":
396 static struct secpolicy *
397 ipsec_checkpolicy(struct secpolicy *sp, struct inpcb *inp, int *error)
400 /* Save found OUTBOUND policy into PCB SP cache. */
401 if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_out == NULL)
402 ipsec_cachepolicy(inp, sp, IPSEC_DIR_OUTBOUND);
404 switch (sp->policy) {
406 printf("%s: invalid policy %u\n", __func__, sp->policy);
408 case IPSEC_POLICY_DISCARD:
409 *error = -EINVAL; /* Packet is discarded by caller. */
411 case IPSEC_POLICY_BYPASS:
412 case IPSEC_POLICY_NONE:
414 sp = NULL; /* NB: force NULL result. */
416 case IPSEC_POLICY_IPSEC:
417 /* XXXAE: handle LARVAL SP */
421 printf("%s: get SP(%p), error %d\n", __func__, sp, *error));
425 static struct secpolicy *
426 ipsec_getpcbpolicy(struct inpcb *inp, u_int dir)
428 struct secpolicy *sp;
429 int flags, downgrade;
431 if (inp == NULL || inp->inp_sp == NULL)
434 INP_LOCK_ASSERT(inp);
436 flags = inp->inp_sp->flags;
437 if (dir == IPSEC_DIR_OUTBOUND) {
438 sp = inp->inp_sp->sp_out;
439 flags &= INP_OUTBOUND_POLICY;
441 sp = inp->inp_sp->sp_in;
442 flags &= INP_INBOUND_POLICY;
445 * Check flags. If we have PCB SP, just return it.
446 * Otherwise we need to check that cached SP entry isn't stale.
451 if (inp->inp_sp->genid != key_getspgen()) {
452 /* Invalidate the cache. */
454 if (!INP_WLOCKED(inp)) {
455 if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
458 ipsec_invalidate_cache(inp, IPSEC_DIR_OUTBOUND);
459 ipsec_invalidate_cache(inp, IPSEC_DIR_INBOUND);
465 printf("%s: PCB(%p): cache hit SP(%p)\n",
467 /* Return referenced cached policy */
475 ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
482 IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
483 ("packet too short"));
485 if (m->m_len >= sizeof (struct ip)) {
486 const struct ip *ip = mtod(m, const struct ip *);
487 if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
489 off = ip->ip_hl << 2;
494 m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
495 if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
501 while (off < m->m_pkthdr.len) {
508 spidx->ul_proto = nxt;
511 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
513 m_copydata(m, off, sizeof (th), (caddr_t) &th);
514 spidx->src.sin.sin_port = th.th_sport;
515 spidx->dst.sin.sin_port = th.th_dport;
518 spidx->ul_proto = nxt;
521 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
523 m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
524 spidx->src.sin.sin_port = uh.uh_sport;
525 spidx->dst.sin.sin_port = uh.uh_dport;
528 if (off + sizeof(ip6e) > m->m_pkthdr.len)
530 /* XXX Sigh, this works but is totally bogus. */
531 m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
532 off += (ip6e.ip6e_len + 2) << 2;
537 /* XXX Intermediate headers??? */
538 spidx->ul_proto = nxt;
543 spidx->ul_proto = IPSEC_ULPROTO_ANY;
545 spidx->src.sin.sin_port = IPSEC_PORT_ANY;
546 spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
548 printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
552 ipsec4_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
555 ipsec4_setsockaddrs(m, &spidx->src, &spidx->dst);
556 spidx->prefs = sizeof(struct in_addr) << 3;
557 spidx->prefd = sizeof(struct in_addr) << 3;
560 static struct secpolicy *
561 ipsec4_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
564 struct secpolicyindex spidx;
565 struct secpolicy *sp;
567 sp = ipsec_getpcbpolicy(inp, dir);
568 if (sp == NULL && key_havesp(dir)) {
569 /* Make an index to look for a policy. */
570 ipsec4_setspidx_ipaddr(m, &spidx);
571 ipsec4_get_ulp(m, &spidx, needport);
573 sp = key_allocsp(&spidx, dir);
575 if (sp == NULL) /* No SP found, use system default. */
576 sp = key_allocsp_default();
581 * Check security policy for *OUTBOUND* IPv4 packet.
584 ipsec4_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
587 struct secpolicy *sp;
590 sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
592 sp = ipsec_checkpolicy(sp, inp, error);
595 case 0: /* No IPsec required: BYPASS or NONE */
598 IPSECSTAT_INC(ips_out_polvio);
601 IPSECSTAT_INC(ips_out_inval);
605 printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
607 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
612 * Check IPv4 packet against *INBOUND* security policy.
613 * This function is called from tcp_input(), udp_input(),
614 * rip_input() and sctp_input().
617 ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
619 struct secpolicy *sp;
622 sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
623 result = ipsec_in_reject(sp, inp, m);
626 IPSECSTAT_INC(ips_in_polvio);
631 * IPSEC_CAP() method implementation for IPv4.
634 ipsec4_capability(struct mbuf *m, u_int cap)
638 case IPSEC_CAP_BYPASS_FILTER:
640 * Bypass packet filtering for packets previously handled
643 if (!V_ip4_filtertunnel &&
644 m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
647 case IPSEC_CAP_OPERABLE:
648 /* Do we have active security policies? */
649 if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
650 key_havesp(IPSEC_DIR_OUTBOUND) != 0)
661 ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
669 IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip6_hdr),
670 ("packet too short"));
673 spidx->ul_proto = IPSEC_ULPROTO_ANY;
674 spidx->src.sin6.sin6_port = IPSEC_PORT_ANY;
675 spidx->dst.sin6.sin6_port = IPSEC_PORT_ANY;
678 off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
679 if (off < 0 || m->m_pkthdr.len < off)
684 spidx->ul_proto = nxt;
687 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
689 m_copydata(m, off, sizeof(th), (caddr_t)&th);
690 spidx->src.sin6.sin6_port = th.th_sport;
691 spidx->dst.sin6.sin6_port = th.th_dport;
694 spidx->ul_proto = nxt;
697 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
699 m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
700 spidx->src.sin6.sin6_port = uh.uh_sport;
701 spidx->dst.sin6.sin6_port = uh.uh_dport;
704 spidx->ul_proto = nxt;
705 if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
707 m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
708 spidx->src.sin6.sin6_port = htons((uint16_t)ih.icmp6_type);
709 spidx->dst.sin6.sin6_port = htons((uint16_t)ih.icmp6_code);
712 /* XXX Intermediate headers??? */
713 spidx->ul_proto = nxt;
717 printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
721 ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
724 ipsec6_setsockaddrs(m, &spidx->src, &spidx->dst);
725 spidx->prefs = sizeof(struct in6_addr) << 3;
726 spidx->prefd = sizeof(struct in6_addr) << 3;
729 static struct secpolicy *
730 ipsec6_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
733 struct secpolicyindex spidx;
734 struct secpolicy *sp;
736 sp = ipsec_getpcbpolicy(inp, dir);
737 if (sp == NULL && key_havesp(dir)) {
738 /* Make an index to look for a policy. */
739 ipsec6_setspidx_ipaddr(m, &spidx);
740 ipsec6_get_ulp(m, &spidx, needport);
742 sp = key_allocsp(&spidx, dir);
744 if (sp == NULL) /* No SP found, use system default. */
745 sp = key_allocsp_default();
750 * Check security policy for *OUTBOUND* IPv6 packet.
753 ipsec6_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
756 struct secpolicy *sp;
759 sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
761 sp = ipsec_checkpolicy(sp, inp, error);
764 case 0: /* No IPsec required: BYPASS or NONE */
767 IPSEC6STAT_INC(ips_out_polvio);
770 IPSEC6STAT_INC(ips_out_inval);
774 printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
776 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
781 * Check IPv6 packet against inbound security policy.
782 * This function is called from tcp6_input(), udp6_input(),
783 * rip6_input() and sctp_input().
786 ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
788 struct secpolicy *sp;
791 sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
792 result = ipsec_in_reject(sp, inp, m);
795 IPSEC6STAT_INC(ips_in_polvio);
800 * IPSEC_CAP() method implementation for IPv6.
803 ipsec6_capability(struct mbuf *m, u_int cap)
807 case IPSEC_CAP_BYPASS_FILTER:
809 * Bypass packet filtering for packets previously handled
812 if (!V_ip6_filtertunnel &&
813 m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
816 case IPSEC_CAP_OPERABLE:
817 /* Do we have active security policies? */
818 if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
819 key_havesp(IPSEC_DIR_OUTBOUND) != 0)
828 ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type)
835 idx = HHOOK_IPSEC_INET;
840 idx = HHOOK_IPSEC_INET6;
844 return (EPFNOSUPPORT);
846 if (type == HHOOK_TYPE_IPSEC_IN)
847 HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL);
849 HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL);
850 if (*ctx->mp == NULL)
856 * Return current level.
857 * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
860 ipsec_get_reqlevel(struct secpolicy *sp, u_int idx)
862 struct ipsecrequest *isr;
863 u_int esp_trans_deflev, esp_net_deflev;
864 u_int ah_trans_deflev, ah_net_deflev;
867 IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
868 /* XXX Note that we have ipseclog() expanded here - code sync issue. */
869 #define IPSEC_CHECK_DEFAULT(lev) \
870 (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE && \
871 (lev) != IPSEC_LEVEL_UNIQUE) \
873 log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
874 (lev), IPSEC_LEVEL_REQUIRE) : 0), \
875 (lev) = IPSEC_LEVEL_REQUIRE, (lev) : (lev))
878 * IPsec VTI uses unique security policy with fake spidx filled
879 * with zeroes. Just return IPSEC_LEVEL_REQUIRE instead of doing
880 * full level lookup for such policies.
882 if (sp->state == IPSEC_SPSTATE_IFNET) {
883 IPSEC_ASSERT(sp->req[idx]->level == IPSEC_LEVEL_UNIQUE,
884 ("Wrong IPsec request level %d", sp->req[idx]->level));
885 return (IPSEC_LEVEL_REQUIRE);
888 /* Set default level. */
889 switch (sp->spidx.src.sa.sa_family) {
892 esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev);
893 esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev);
894 ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev);
895 ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev);
900 esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev);
901 esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev);
902 ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev);
903 ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev);
907 panic("%s: unknown af %u",
908 __func__, sp->spidx.src.sa.sa_family);
911 #undef IPSEC_CHECK_DEFAULT
915 switch (isr->level) {
916 case IPSEC_LEVEL_DEFAULT:
917 switch (isr->saidx.proto) {
919 if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
920 level = esp_net_deflev;
922 level = esp_trans_deflev;
925 if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
926 level = ah_net_deflev;
928 level = ah_trans_deflev;
932 * We don't really care, as IPcomp document says that
933 * we shouldn't compress small packets.
935 level = IPSEC_LEVEL_USE;
938 panic("%s: Illegal protocol defined %u\n", __func__,
943 case IPSEC_LEVEL_USE:
944 case IPSEC_LEVEL_REQUIRE:
947 case IPSEC_LEVEL_UNIQUE:
948 level = IPSEC_LEVEL_REQUIRE;
952 panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
959 ipsec_check_history(const struct mbuf *m, struct secpolicy *sp, u_int idx)
961 struct xform_history *xh;
965 while ((mtag = m_tag_find(__DECONST(struct mbuf *, m),
966 PACKET_TAG_IPSEC_IN_DONE, mtag)) != NULL) {
967 xh = (struct xform_history *)(mtag + 1);
969 char buf[IPSEC_ADDRSTRLEN];
970 printf("%s: mode %s proto %u dst %s\n", __func__,
971 kdebug_secasindex_mode(xh->mode), xh->proto,
972 ipsec_address(&xh->dst, buf, sizeof(buf))));
973 if (xh->proto != sp->req[idx]->saidx.proto)
975 /* If SA had IPSEC_MODE_ANY, consider this as match. */
976 if (xh->mode != sp->req[idx]->saidx.mode &&
977 xh->mode != IPSEC_MODE_ANY)
980 * For transport mode IPsec request doesn't contain
981 * addresses. We need to use address from spidx.
983 if (sp->req[idx]->saidx.mode == IPSEC_MODE_TRANSPORT) {
984 if (key_sockaddrcmp_withmask(&xh->dst.sa,
985 &sp->spidx.dst.sa, sp->spidx.prefd) != 0)
988 if (key_sockaddrcmp(&xh->dst.sa,
989 &sp->req[idx]->saidx.dst.sa, 0) != 0)
992 return (0); /* matched */
998 * Check security policy requirements against the actual
999 * packet contents. Return one if the packet should be
1000 * reject as "invalid"; otherwiser return zero to have the
1001 * packet treated as "valid".
1008 ipsec_in_reject(struct secpolicy *sp, struct inpcb *inp, const struct mbuf *m)
1013 printf("%s: PCB(%p): using SP(%p)\n", __func__, inp, sp));
1014 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1016 if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_in == NULL)
1017 ipsec_cachepolicy(inp, sp, IPSEC_DIR_INBOUND);
1020 switch (sp->policy) {
1021 case IPSEC_POLICY_DISCARD:
1023 case IPSEC_POLICY_BYPASS:
1024 case IPSEC_POLICY_NONE:
1028 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1029 ("invalid policy %u", sp->policy));
1032 * ipsec[46]_common_input_cb after each transform adds
1033 * PACKET_TAG_IPSEC_IN_DONE mbuf tag. It contains SPI, proto, mode
1034 * and destination address from saidx. We can compare info from
1035 * these tags with requirements in SP.
1037 for (i = 0; i < sp->tcount; i++) {
1039 * Do not check IPcomp, since IPcomp document
1040 * says that we shouldn't compress small packets.
1041 * IPComp policy should always be treated as being
1044 if (sp->req[i]->saidx.proto == IPPROTO_IPCOMP ||
1045 ipsec_get_reqlevel(sp, i) != IPSEC_LEVEL_REQUIRE)
1047 if (V_check_policy_history != 0 &&
1048 ipsec_check_history(m, sp, i) != 0)
1050 else switch (sp->req[i]->saidx.proto) {
1052 if ((m->m_flags & M_DECRYPTED) == 0) {
1054 printf("%s: ESP m_flags:%x\n", __func__,
1060 if ((m->m_flags & M_AUTHIPHDR) == 0) {
1062 printf("%s: AH m_flags:%x\n", __func__,
1069 return (0); /* Valid. */
1073 * Compute the byte size to be occupied by IPsec header.
1074 * In case it is tunnelled, it includes the size of outer IP header.
1077 ipsec_hdrsiz_internal(struct secpolicy *sp)
1082 KEYDBG(IPSEC_STAMP, printf("%s: using SP(%p)\n", __func__, sp));
1083 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1085 switch (sp->policy) {
1086 case IPSEC_POLICY_DISCARD:
1087 case IPSEC_POLICY_BYPASS:
1088 case IPSEC_POLICY_NONE:
1092 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1093 ("invalid policy %u", sp->policy));
1096 * XXX: for each transform we need to lookup suitable SA
1097 * and use info from SA to calculate headers size.
1098 * XXX: for NAT-T we need to cosider UDP header size.
1101 for (i = 0; i < sp->tcount; i++) {
1102 switch (sp->req[i]->saidx.proto) {
1104 size += esp_hdrsiz(NULL);
1107 size += ah_hdrsiz(NULL);
1109 case IPPROTO_IPCOMP:
1110 size += sizeof(struct ipcomp);
1114 if (sp->req[i]->saidx.mode == IPSEC_MODE_TUNNEL) {
1115 switch (sp->req[i]->saidx.dst.sa.sa_family) {
1118 size += sizeof(struct ip);
1123 size += sizeof(struct ip6_hdr);
1127 ipseclog((LOG_ERR, "%s: unknown AF %d in "
1128 "IPsec tunnel SA\n", __func__,
1129 sp->req[i]->saidx.dst.sa.sa_family));
1138 * Compute ESP/AH header size for protocols with PCB, including
1139 * outer IP header. Currently only tcp_output() uses it.
1142 ipsec_hdrsiz_inpcb(struct inpcb *inp)
1144 struct secpolicyindex spidx;
1145 struct secpolicy *sp;
1148 sp = ipsec_getpcbpolicy(inp, IPSEC_DIR_OUTBOUND);
1149 if (sp == NULL && key_havesp(IPSEC_DIR_OUTBOUND)) {
1150 ipsec_setspidx_inpcb(inp, &spidx, IPSEC_DIR_OUTBOUND);
1151 sp = key_allocsp(&spidx, IPSEC_DIR_OUTBOUND);
1154 sp = key_allocsp_default();
1155 sz = ipsec_hdrsiz_internal(sp);
1161 * Check the variable replay window.
1162 * ipsec_chkreplay() performs replay check before ICV verification.
1163 * ipsec_updatereplay() updates replay bitmap. This must be called after
1164 * ICV verification (it also performs replay check, which is usually done
1166 * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1168 * Based on RFC 6479. Blocks are 32 bits unsigned integers
1171 #define IPSEC_BITMAP_INDEX_MASK(w) (w - 1)
1172 #define IPSEC_REDUNDANT_BIT_SHIFTS 5
1173 #define IPSEC_REDUNDANT_BITS (1 << IPSEC_REDUNDANT_BIT_SHIFTS)
1174 #define IPSEC_BITMAP_LOC_MASK (IPSEC_REDUNDANT_BITS - 1)
1177 ipsec_chkreplay(uint32_t seq, struct secasvar *sav)
1179 const struct secreplay *replay;
1180 uint32_t wsizeb; /* Constant: window size. */
1181 int index, bit_location;
1183 IPSEC_ASSERT(sav != NULL, ("Null SA"));
1184 IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1186 replay = sav->replay;
1188 /* No need to check replay if disabled. */
1189 if (replay->wsize == 0)
1193 wsizeb = replay->wsize << 3;
1195 /* Sequence number of 0 is invalid. */
1199 /* First time is always okay. */
1200 if (replay->count == 0)
1203 /* Larger sequences are okay. */
1204 if (seq > replay->lastseq)
1207 /* Over range to check, i.e. too old or wrapped. */
1208 if (replay->lastseq - seq >= wsizeb)
1211 /* The sequence is inside the sliding window
1212 * now check the bit in the bitmap
1213 * bit location only depends on the sequence number
1215 bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1216 index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1217 & IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1219 /* This packet already seen? */
1220 if ((replay->bitmap)[index] & (1 << bit_location))
1226 * Check replay counter whether to update or not.
1231 ipsec_updatereplay(uint32_t seq, struct secasvar *sav)
1234 struct secreplay *replay;
1235 uint32_t wsizeb; /* Constant: window size. */
1236 int diff, index, bit_location;
1238 IPSEC_ASSERT(sav != NULL, ("Null SA"));
1239 IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1241 replay = sav->replay;
1243 if (replay->wsize == 0)
1244 goto ok; /* No need to check replay. */
1247 wsizeb = replay->wsize << 3;
1249 /* Sequence number of 0 is invalid. */
1253 /* The packet is too old, no need to update */
1254 if (wsizeb + seq < replay->lastseq)
1257 /* Now update the bit */
1258 index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS);
1260 /* First check if the sequence number is in the range */
1261 if (seq > replay->lastseq) {
1263 int index_cur = replay->lastseq >> IPSEC_REDUNDANT_BIT_SHIFTS;
1265 diff = index - index_cur;
1266 if (diff > replay->bitmap_size) {
1267 /* something unusual in this case */
1268 diff = replay->bitmap_size;
1271 for (id = 0; id < diff; ++id) {
1272 replay->bitmap[(id + index_cur + 1)
1273 & IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
1276 replay->lastseq = seq;
1279 index &= IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1280 bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1282 /* this packet has already been received */
1283 if (replay->bitmap[index] & (1 << bit_location))
1286 replay->bitmap[index] |= (1 << bit_location);
1289 if (replay->count == ~0) {
1291 /* Set overflow flag. */
1294 /* Don't increment, no more packets accepted. */
1295 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1296 if (sav->sah->saidx.proto == IPPROTO_AH)
1297 AHSTAT_INC(ahs_wrap);
1298 else if (sav->sah->saidx.proto == IPPROTO_ESP)
1299 ESPSTAT_INC(esps_wrap);
1303 ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1304 __func__, replay->overflow,
1305 ipsec_sa2str(sav, buf, sizeof(buf))));
1311 ipsec_updateid(struct secasvar *sav, uint64_t *new, uint64_t *old)
1316 * tdb_cryptoid is initialized by xform_init().
1317 * Then it can be changed only when some crypto error occurred or
1318 * when SA is deleted. We stored used cryptoid in the xform_data
1319 * structure. In case when crypto error occurred and crypto
1320 * subsystem has reinited the session, it returns new cryptoid
1321 * and EAGAIN error code.
1323 * This function will be called when we got EAGAIN from crypto
1325 * *new is cryptoid that was returned by crypto subsystem in
1327 * *old is the original cryptoid that we stored in xform_data.
1329 * For first failed request *old == sav->tdb_cryptoid, then
1330 * we update sav->tdb_cryptoid and redo crypto_dispatch().
1331 * For next failed request *old != sav->tdb_cryptoid, then
1332 * we store cryptoid from first request into the *new variable
1333 * and crp_sid from this second session will be returned via
1334 * *old pointer, so caller can release second session.
1336 * XXXAE: check this more carefully.
1339 printf("%s: SA(%p) moves cryptoid %jd -> %jd\n",
1340 __func__, sav, (uintmax_t)(*old), (uintmax_t)(*new)));
1341 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1343 if (sav->tdb_cryptoid != *old) {
1344 /* cryptoid was already updated */
1346 *new = sav->tdb_cryptoid;
1348 SECASVAR_UNLOCK(sav);
1351 sav->tdb_cryptoid = *new;
1352 SECASVAR_UNLOCK(sav);
1357 ipsec_initialized(void)
1360 return (V_def_policy != NULL);
1364 def_policy_init(const void *unused __unused)
1367 V_def_policy = key_newsp();
1368 if (V_def_policy != NULL) {
1369 V_def_policy->policy = IPSEC_POLICY_NONE;
1370 /* Force INPCB SP cache invalidation */
1373 printf("%s: failed to initialize default policy\n", __func__);
1378 def_policy_uninit(const void *unused __unused)
1381 if (V_def_policy != NULL) {
1382 key_freesp(&V_def_policy);
1387 VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1388 def_policy_init, NULL);
1389 VNET_SYSUNINIT(def_policy_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1390 def_policy_uninit, NULL);