xref: /freebsd-src/sys/netipsec/ipsec.c (revision 0ff2d00d2aa37cd883ffd8c7363dddef9cba267e)
188768458SSam Leffler /*	$KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $	*/
288768458SSam Leffler 
3c398230bSWarner Losh /*-
451369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
551369649SPedro F. Giffuni  *
688768458SSam Leffler  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
788768458SSam Leffler  * All rights reserved.
888768458SSam Leffler  *
988768458SSam Leffler  * Redistribution and use in source and binary forms, with or without
1088768458SSam Leffler  * modification, are permitted provided that the following conditions
1188768458SSam Leffler  * are met:
1288768458SSam Leffler  * 1. Redistributions of source code must retain the above copyright
1388768458SSam Leffler  *    notice, this list of conditions and the following disclaimer.
1488768458SSam Leffler  * 2. Redistributions in binary form must reproduce the above copyright
1588768458SSam Leffler  *    notice, this list of conditions and the following disclaimer in the
1688768458SSam Leffler  *    documentation and/or other materials provided with the distribution.
1788768458SSam Leffler  * 3. Neither the name of the project nor the names of its contributors
1888768458SSam Leffler  *    may be used to endorse or promote products derived from this software
1988768458SSam Leffler  *    without specific prior written permission.
2088768458SSam Leffler  *
2188768458SSam Leffler  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
2288768458SSam Leffler  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2388768458SSam Leffler  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2488768458SSam Leffler  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
2588768458SSam Leffler  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2688768458SSam Leffler  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2788768458SSam Leffler  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2888768458SSam Leffler  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2988768458SSam Leffler  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3088768458SSam Leffler  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3188768458SSam Leffler  * SUCH DAMAGE.
3288768458SSam Leffler  */
3388768458SSam Leffler 
3488768458SSam Leffler /*
3588768458SSam Leffler  * IPsec controller part.
3688768458SSam Leffler  */
3788768458SSam Leffler 
3888768458SSam Leffler #include "opt_inet.h"
3988768458SSam Leffler #include "opt_inet6.h"
4088768458SSam Leffler #include "opt_ipsec.h"
4188768458SSam Leffler 
4288768458SSam Leffler #include <sys/param.h>
4388768458SSam Leffler #include <sys/systm.h>
4488768458SSam Leffler #include <sys/malloc.h>
4588768458SSam Leffler #include <sys/mbuf.h>
4688768458SSam Leffler #include <sys/domain.h>
4746ee43b2SRobert Watson #include <sys/priv.h>
4888768458SSam Leffler #include <sys/protosw.h>
4988768458SSam Leffler #include <sys/socket.h>
5088768458SSam Leffler #include <sys/socketvar.h>
5188768458SSam Leffler #include <sys/errno.h>
52ef91a976SAndrey V. Elsukov #include <sys/hhook.h>
5388768458SSam Leffler #include <sys/time.h>
5488768458SSam Leffler #include <sys/kernel.h>
5588768458SSam Leffler #include <sys/syslog.h>
5688768458SSam Leffler #include <sys/sysctl.h>
5788768458SSam Leffler #include <sys/proc.h>
5888768458SSam Leffler 
5988768458SSam Leffler #include <net/if.h>
60ef91a976SAndrey V. Elsukov #include <net/if_enc.h>
6176039bc8SGleb Smirnoff #include <net/if_var.h>
62eddfbb76SRobert Watson #include <net/vnet.h>
6388768458SSam Leffler 
6488768458SSam Leffler #include <netinet/in.h>
6588768458SSam Leffler #include <netinet/in_systm.h>
6688768458SSam Leffler #include <netinet/ip.h>
6788768458SSam Leffler #include <netinet/ip_var.h>
6888768458SSam Leffler #include <netinet/in_var.h>
6988768458SSam Leffler #include <netinet/udp.h>
7088768458SSam Leffler #include <netinet/udp_var.h>
7188768458SSam Leffler #include <netinet/tcp.h>
7288768458SSam Leffler #include <netinet/udp.h>
7388768458SSam Leffler 
7488768458SSam Leffler #include <netinet/ip6.h>
7588768458SSam Leffler #ifdef INET6
7688768458SSam Leffler #include <netinet6/ip6_var.h>
7788768458SSam Leffler #endif
7888768458SSam Leffler #include <netinet/in_pcb.h>
7988768458SSam Leffler #ifdef INET6
8088768458SSam Leffler #include <netinet/icmp6.h>
8188768458SSam Leffler #endif
8288768458SSam Leffler 
832cb64cb2SGeorge V. Neville-Neil #include <sys/types.h>
8488768458SSam Leffler #include <netipsec/ipsec.h>
8588768458SSam Leffler #ifdef INET6
8688768458SSam Leffler #include <netipsec/ipsec6.h>
8788768458SSam Leffler #endif
88ef2a572bSKonstantin Belousov #include <netipsec/ipsec_offload.h>
8988768458SSam Leffler #include <netipsec/ah_var.h>
9088768458SSam Leffler #include <netipsec/esp_var.h>
9188768458SSam Leffler #include <netipsec/ipcomp.h>		/*XXX*/
9288768458SSam Leffler #include <netipsec/ipcomp_var.h>
93fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
9488768458SSam Leffler 
9588768458SSam Leffler #include <netipsec/key.h>
9688768458SSam Leffler #include <netipsec/keydb.h>
9788768458SSam Leffler #include <netipsec/key_debug.h>
9888768458SSam Leffler 
9988768458SSam Leffler #include <netipsec/xform.h>
10088768458SSam Leffler 
10188768458SSam Leffler #include <machine/in_cksum.h>
10288768458SSam Leffler 
1037aee3dd1SSam Leffler #include <opencrypto/cryptodev.h>
1047aee3dd1SSam Leffler 
105de47c390SBjoern A. Zeeb /* NB: name changed so netstat doesn't use it. */
106db8c0879SAndrey V. Elsukov VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec4stat);
107db8c0879SAndrey V. Elsukov VNET_PCPUSTAT_SYSINIT(ipsec4stat);
108db8c0879SAndrey V. Elsukov 
109db8c0879SAndrey V. Elsukov #ifdef VIMAGE
110db8c0879SAndrey V. Elsukov VNET_PCPUSTAT_SYSUNINIT(ipsec4stat);
111db8c0879SAndrey V. Elsukov #endif /* VIMAGE */
112db8c0879SAndrey V. Elsukov 
113eddfbb76SRobert Watson /* DF bit on encap. 0: clear 1: set 2: copy */
114eddfbb76SRobert Watson VNET_DEFINE(int, ip4_ipsec_dfbit) = 0;
115d9d59bb1SWojciech Macek VNET_DEFINE(int, ip4_ipsec_min_pmtu) = 576;
116eddfbb76SRobert Watson VNET_DEFINE(int, ip4_esp_trans_deflev) = IPSEC_LEVEL_USE;
117eddfbb76SRobert Watson VNET_DEFINE(int, ip4_esp_net_deflev) = IPSEC_LEVEL_USE;
118eddfbb76SRobert Watson VNET_DEFINE(int, ip4_ah_trans_deflev) = IPSEC_LEVEL_USE;
119eddfbb76SRobert Watson VNET_DEFINE(int, ip4_ah_net_deflev) = IPSEC_LEVEL_USE;
120eddfbb76SRobert Watson /* ECN ignore(-1)/forbidden(0)/allowed(1) */
121eddfbb76SRobert Watson VNET_DEFINE(int, ip4_ipsec_ecn) = 0;
122eddfbb76SRobert Watson 
1235f901c92SAndrew Turner VNET_DEFINE_STATIC(int, ip4_filtertunnel) = 0;
124fcf59617SAndrey V. Elsukov #define	V_ip4_filtertunnel VNET(ip4_filtertunnel)
1255f901c92SAndrew Turner VNET_DEFINE_STATIC(int, check_policy_history) = 0;
126fcf59617SAndrey V. Elsukov #define	V_check_policy_history	VNET(check_policy_history)
1275f901c92SAndrew Turner VNET_DEFINE_STATIC(struct secpolicy *, def_policy) = NULL;
12893201211SAndrey V. Elsukov #define	V_def_policy	VNET(def_policy)
129fcf59617SAndrey V. Elsukov static int
130fcf59617SAndrey V. Elsukov sysctl_def_policy(SYSCTL_HANDLER_ARGS)
131fcf59617SAndrey V. Elsukov {
132fcf59617SAndrey V. Elsukov 	int error, value;
133fcf59617SAndrey V. Elsukov 
134fcf59617SAndrey V. Elsukov 	value = V_def_policy->policy;
135fcf59617SAndrey V. Elsukov 	error = sysctl_handle_int(oidp, &value, 0, req);
136fcf59617SAndrey V. Elsukov 	if (error == 0) {
137fcf59617SAndrey V. Elsukov 		if (value != IPSEC_POLICY_DISCARD &&
138fcf59617SAndrey V. Elsukov 		    value != IPSEC_POLICY_NONE)
139fcf59617SAndrey V. Elsukov 			return (EINVAL);
140fcf59617SAndrey V. Elsukov 		V_def_policy->policy = value;
141fcf59617SAndrey V. Elsukov 	}
142fcf59617SAndrey V. Elsukov 	return (error);
143fcf59617SAndrey V. Elsukov }
144fcf59617SAndrey V. Elsukov 
14588768458SSam Leffler /*
14688768458SSam Leffler  * Crypto support requirements:
14788768458SSam Leffler  *
14888768458SSam Leffler  *  1	require hardware support
14988768458SSam Leffler  * -1	require software support
15088768458SSam Leffler  *  0	take anything
15188768458SSam Leffler  */
152eddfbb76SRobert Watson VNET_DEFINE(int, crypto_support) = CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
15339bbca6fSFabien Thomas 
15439bbca6fSFabien Thomas /*
15539bbca6fSFabien Thomas  * Use asynchronous mode to parallelize crypto jobs:
15639bbca6fSFabien Thomas  *
15739bbca6fSFabien Thomas  *  0 - disabled
15839bbca6fSFabien Thomas  *  1 - enabled
15939bbca6fSFabien Thomas  */
16039bbca6fSFabien Thomas VNET_DEFINE(int, async_crypto) = 0;
16139bbca6fSFabien Thomas 
162fcf59617SAndrey V. Elsukov /*
163fcf59617SAndrey V. Elsukov  * TCP/UDP checksum handling policy for transport mode NAT-T (RFC3948)
164fcf59617SAndrey V. Elsukov  *
165fcf59617SAndrey V. Elsukov  * 0 - auto: incrementally recompute, when checksum delta is known;
166fcf59617SAndrey V. Elsukov  *     if checksum delta isn't known, reset checksum to zero for UDP,
167fcf59617SAndrey V. Elsukov  *     and mark csum_flags as valid for TCP.
168fcf59617SAndrey V. Elsukov  * 1 - fully recompute TCP/UDP checksum.
169fcf59617SAndrey V. Elsukov  */
170fcf59617SAndrey V. Elsukov VNET_DEFINE(int, natt_cksum_policy) = 0;
17188768458SSam Leffler 
17213a6cf24SBjoern A. Zeeb FEATURE(ipsec, "Internet Protocol Security (IPsec)");
17313a6cf24SBjoern A. Zeeb FEATURE(ipsec_natt, "UDP Encapsulation of IPsec ESP Packets ('NAT-T')");
17413a6cf24SBjoern A. Zeeb 
17588768458SSam Leffler /* net.inet.ipsec */
176fcf59617SAndrey V. Elsukov SYSCTL_PROC(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy,
1777029da5cSPawel Biernacki     CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
1787029da5cSPawel Biernacki     0, 0, sysctl_def_policy, "I",
179be6b1304STom Rhodes     "IPsec default policy.");
1806df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
1816df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0,
1828b615593SMarko Zec 	"Default ESP transport mode level");
1836df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
1846df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0,
1858b615593SMarko Zec 	"Default ESP tunnel mode level.");
1866df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
1876df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0,
1888b615593SMarko Zec 	"AH transfer mode default level.");
1896df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
1906df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0,
1918b615593SMarko Zec 	"AH tunnel mode default level.");
1926df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos,
1936df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0,
194fcf59617SAndrey V. Elsukov 	"If set, clear type-of-service field when doing AH computation.");
1956df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit,
1966df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0,
1978b615593SMarko Zec 	"Do not fragment bit on encap.");
198d9d59bb1SWojciech Macek SYSCTL_INT(_net_inet_ipsec, IPSECCTL_MIN_PMTU, min_pmtu,
199d9d59bb1SWojciech Macek 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_min_pmtu), 0,
200d9d59bb1SWojciech Macek 	"Lowest acceptable PMTU value.");
2016df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn,
2026df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0,
203be6b1304STom Rhodes 	"Explicit Congestion Notification handling.");
2046df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, OID_AUTO, crypto_support,
2056df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(crypto_support), 0,
206be6b1304STom Rhodes 	"Crypto driver selection.");
20739bbca6fSFabien Thomas SYSCTL_INT(_net_inet_ipsec, OID_AUTO, async_crypto,
20839bbca6fSFabien Thomas 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(async_crypto), 0,
20939bbca6fSFabien Thomas 	"Use asynchronous mode to parallelize crypto jobs.");
210fcf59617SAndrey V. Elsukov SYSCTL_INT(_net_inet_ipsec, OID_AUTO, check_policy_history,
211fcf59617SAndrey V. Elsukov 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(check_policy_history), 0,
212fcf59617SAndrey V. Elsukov 	"Use strict check of inbound packets to security policy compliance.");
213fcf59617SAndrey V. Elsukov SYSCTL_INT(_net_inet_ipsec, OID_AUTO, natt_cksum_policy,
214fcf59617SAndrey V. Elsukov 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(natt_cksum_policy), 0,
215fcf59617SAndrey V. Elsukov 	"Method to fix TCP/UDP checksum for transport mode IPsec after NAT.");
216fcf59617SAndrey V. Elsukov SYSCTL_INT(_net_inet_ipsec, OID_AUTO, filtertunnel,
217fcf59617SAndrey V. Elsukov 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_filtertunnel), 0,
218fcf59617SAndrey V. Elsukov 	"If set, filter packets from an IPsec tunnel.");
219db8c0879SAndrey V. Elsukov SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat,
220db8c0879SAndrey V. Elsukov     ipsec4stat, "IPsec IPv4 statistics.");
22188768458SSam Leffler 
2226131838bSPawel Jakub Dawidek #ifdef REGRESSION
223dfa9422bSPawel Jakub Dawidek /*
224dfa9422bSPawel Jakub Dawidek  * When set to 1, IPsec will send packets with the same sequence number.
225dfa9422bSPawel Jakub Dawidek  * This allows to verify if the other side has proper replay attacks detection.
226dfa9422bSPawel Jakub Dawidek  */
227eddfbb76SRobert Watson VNET_DEFINE(int, ipsec_replay) = 0;
2286df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay,
2296df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0,
230eddfbb76SRobert Watson 	"Emulate replay attack");
231dfa9422bSPawel Jakub Dawidek /*
232dfa9422bSPawel Jakub Dawidek  * When set 1, IPsec will send packets with corrupted HMAC.
233dfa9422bSPawel Jakub Dawidek  * This allows to verify if the other side properly detects modified packets.
234dfa9422bSPawel Jakub Dawidek  */
235eddfbb76SRobert Watson VNET_DEFINE(int, ipsec_integrity) = 0;
2366df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity,
2376df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0,
238eddfbb76SRobert Watson 	"Emulate man-in-the-middle attack");
2396131838bSPawel Jakub Dawidek #endif
240dfa9422bSPawel Jakub Dawidek 
24188768458SSam Leffler #ifdef INET6
242db8c0879SAndrey V. Elsukov VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat);
243db8c0879SAndrey V. Elsukov VNET_PCPUSTAT_SYSINIT(ipsec6stat);
244db8c0879SAndrey V. Elsukov 
245db8c0879SAndrey V. Elsukov #ifdef VIMAGE
246db8c0879SAndrey V. Elsukov VNET_PCPUSTAT_SYSUNINIT(ipsec6stat);
247db8c0879SAndrey V. Elsukov #endif /* VIMAGE */
248db8c0879SAndrey V. Elsukov 
249eddfbb76SRobert Watson VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE;
250eddfbb76SRobert Watson VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE;
251eddfbb76SRobert Watson VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE;
252eddfbb76SRobert Watson VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE;
253eddfbb76SRobert Watson VNET_DEFINE(int, ip6_ipsec_ecn) = 0;	/* ECN ignore(-1)/forbidden(0)/allowed(1) */
25488768458SSam Leffler 
2555f901c92SAndrew Turner VNET_DEFINE_STATIC(int, ip6_filtertunnel) = 0;
256fcf59617SAndrey V. Elsukov #define	V_ip6_filtertunnel	VNET(ip6_filtertunnel)
257fcf59617SAndrey V. Elsukov 
25888768458SSam Leffler /* net.inet6.ipsec6 */
259fcf59617SAndrey V. Elsukov SYSCTL_PROC(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy,
2607029da5cSPawel Biernacki     CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
2617029da5cSPawel Biernacki     0, 0, sysctl_def_policy, "I",
2628b615593SMarko Zec     "IPsec default policy.");
2636df8a710SGleb Smirnoff SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
2646df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0,
2658b615593SMarko Zec 	"Default ESP transport mode level.");
2666df8a710SGleb Smirnoff SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
2676df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev), 0,
2688b615593SMarko Zec 	"Default ESP tunnel mode level.");
2696df8a710SGleb Smirnoff SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
2706df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev), 0,
2718b615593SMarko Zec 	"AH transfer mode default level.");
2726df8a710SGleb Smirnoff SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
2736df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev), 0,
2748b615593SMarko Zec 	"AH tunnel mode default level.");
2756df8a710SGleb Smirnoff SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN, ecn,
2766df8a710SGleb Smirnoff 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn), 0,
2773377c961STom Rhodes 	"Explicit Congestion Notification handling.");
278fcf59617SAndrey V. Elsukov SYSCTL_INT(_net_inet6_ipsec6, OID_AUTO, filtertunnel,
279fcf59617SAndrey V. Elsukov 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_filtertunnel),  0,
280fcf59617SAndrey V. Elsukov 	"If set, filter packets from an IPsec tunnel.");
281db8c0879SAndrey V. Elsukov SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats,
282db8c0879SAndrey V. Elsukov     struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics.");
28388768458SSam Leffler #endif /* INET6 */
28488768458SSam Leffler 
285fcf59617SAndrey V. Elsukov static int ipsec_in_reject(struct secpolicy *, struct inpcb *,
286fcf59617SAndrey V. Elsukov     const struct mbuf *);
287fcf59617SAndrey V. Elsukov 
288fcf59617SAndrey V. Elsukov #ifdef INET
289*0ff2d00dSKonstantin Belousov static void ipsec4_get_ulp(const struct mbuf *, const struct ip *,
290*0ff2d00dSKonstantin Belousov     struct secpolicyindex *, int);
291*0ff2d00dSKonstantin Belousov static void ipsec4_setspidx_ipaddr(const struct mbuf *, struct ip *,
292fcf59617SAndrey V. Elsukov     struct secpolicyindex *);
293fcf59617SAndrey V. Elsukov #endif
29488768458SSam Leffler #ifdef INET6
295efb10c3cSAndrey V. Elsukov static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
296fcf59617SAndrey V. Elsukov static void ipsec6_setspidx_ipaddr(const struct mbuf *,
297fcf59617SAndrey V. Elsukov     struct secpolicyindex *);
29888768458SSam Leffler #endif
2996464079fSSam Leffler 
30088768458SSam Leffler /*
30188768458SSam Leffler  * Return a held reference to the default SP.
30288768458SSam Leffler  */
30388768458SSam Leffler static struct secpolicy *
304fcf59617SAndrey V. Elsukov key_allocsp_default(void)
305fcf59617SAndrey V. Elsukov {
306fcf59617SAndrey V. Elsukov 
307fcf59617SAndrey V. Elsukov 	key_addref(V_def_policy);
308fcf59617SAndrey V. Elsukov 	return (V_def_policy);
309fcf59617SAndrey V. Elsukov }
310fcf59617SAndrey V. Elsukov 
311fcf59617SAndrey V. Elsukov static void
312fcf59617SAndrey V. Elsukov ipsec_invalidate_cache(struct inpcb *inp, u_int dir)
31388768458SSam Leffler {
31488768458SSam Leffler 	struct secpolicy *sp;
31588768458SSam Leffler 
316fcf59617SAndrey V. Elsukov 	INP_WLOCK_ASSERT(inp);
317fcf59617SAndrey V. Elsukov 	if (dir == IPSEC_DIR_OUTBOUND) {
318fcf59617SAndrey V. Elsukov 		if (inp->inp_sp->flags & INP_INBOUND_POLICY)
319fcf59617SAndrey V. Elsukov 			return;
320fcf59617SAndrey V. Elsukov 		sp = inp->inp_sp->sp_in;
321fcf59617SAndrey V. Elsukov 		inp->inp_sp->sp_in = NULL;
322fcf59617SAndrey V. Elsukov 	} else {
323fcf59617SAndrey V. Elsukov 		if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
324fcf59617SAndrey V. Elsukov 			return;
325fcf59617SAndrey V. Elsukov 		sp = inp->inp_sp->sp_out;
326fcf59617SAndrey V. Elsukov 		inp->inp_sp->sp_out = NULL;
32788768458SSam Leffler 	}
328fcf59617SAndrey V. Elsukov 	if (sp != NULL)
329fcf59617SAndrey V. Elsukov 		key_freesp(&sp); /* release extra reference */
33088768458SSam Leffler }
33188768458SSam Leffler 
332fcf59617SAndrey V. Elsukov static void
333fcf59617SAndrey V. Elsukov ipsec_cachepolicy(struct inpcb *inp, struct secpolicy *sp, u_int dir)
334fcf59617SAndrey V. Elsukov {
335fcf59617SAndrey V. Elsukov 	uint32_t genid;
336fcf59617SAndrey V. Elsukov 	int downgrade;
337fcf59617SAndrey V. Elsukov 
338fcf59617SAndrey V. Elsukov 	INP_LOCK_ASSERT(inp);
339fcf59617SAndrey V. Elsukov 
340fcf59617SAndrey V. Elsukov 	if (dir == IPSEC_DIR_OUTBOUND) {
341fcf59617SAndrey V. Elsukov 		/* Do we have configured PCB policy? */
342fcf59617SAndrey V. Elsukov 		if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
343fcf59617SAndrey V. Elsukov 			return;
344fcf59617SAndrey V. Elsukov 		/* Another thread has already set cached policy */
345fcf59617SAndrey V. Elsukov 		if (inp->inp_sp->sp_out != NULL)
346fcf59617SAndrey V. Elsukov 			return;
34788768458SSam Leffler 		/*
348fcf59617SAndrey V. Elsukov 		 * Do not cache OUTBOUND policy if PCB isn't connected,
349fcf59617SAndrey V. Elsukov 		 * i.e. foreign address is INADDR_ANY/UNSPECIFIED.
35088768458SSam Leffler 		 */
351fcf59617SAndrey V. Elsukov #ifdef INET
352fcf59617SAndrey V. Elsukov 		if ((inp->inp_vflag & INP_IPV4) != 0 &&
353fcf59617SAndrey V. Elsukov 		    inp->inp_faddr.s_addr == INADDR_ANY)
354fcf59617SAndrey V. Elsukov 			return;
355fcf59617SAndrey V. Elsukov #endif
356fcf59617SAndrey V. Elsukov #ifdef INET6
357fcf59617SAndrey V. Elsukov 		if ((inp->inp_vflag & INP_IPV6) != 0 &&
358fcf59617SAndrey V. Elsukov 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
359fcf59617SAndrey V. Elsukov 			return;
360fcf59617SAndrey V. Elsukov #endif
361fcf59617SAndrey V. Elsukov 	} else {
362fcf59617SAndrey V. Elsukov 		/* Do we have configured PCB policy? */
363fcf59617SAndrey V. Elsukov 		if (inp->inp_sp->flags & INP_INBOUND_POLICY)
364fcf59617SAndrey V. Elsukov 			return;
365fcf59617SAndrey V. Elsukov 		/* Another thread has already set cached policy */
366fcf59617SAndrey V. Elsukov 		if (inp->inp_sp->sp_in != NULL)
367fcf59617SAndrey V. Elsukov 			return;
36888768458SSam Leffler 		/*
369fcf59617SAndrey V. Elsukov 		 * Do not cache INBOUND policy for listen socket,
370fcf59617SAndrey V. Elsukov 		 * that is bound to INADDR_ANY/UNSPECIFIED address.
37188768458SSam Leffler 		 */
372fcf59617SAndrey V. Elsukov #ifdef INET
373fcf59617SAndrey V. Elsukov 		if ((inp->inp_vflag & INP_IPV4) != 0 &&
374fcf59617SAndrey V. Elsukov 		    inp->inp_faddr.s_addr == INADDR_ANY)
375fcf59617SAndrey V. Elsukov 			return;
376fcf59617SAndrey V. Elsukov #endif
377fcf59617SAndrey V. Elsukov #ifdef INET6
378fcf59617SAndrey V. Elsukov 		if ((inp->inp_vflag & INP_IPV6) != 0 &&
379fcf59617SAndrey V. Elsukov 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
380fcf59617SAndrey V. Elsukov 			return;
381fcf59617SAndrey V. Elsukov #endif
382c1fc5e96SErmal Luçi 	}
383fcf59617SAndrey V. Elsukov 	downgrade = 0;
384fcf59617SAndrey V. Elsukov 	if (!INP_WLOCKED(inp)) {
385fcf59617SAndrey V. Elsukov 		if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
386fcf59617SAndrey V. Elsukov 			return;
38788768458SSam Leffler 	}
388fcf59617SAndrey V. Elsukov 	if (dir == IPSEC_DIR_OUTBOUND)
389fcf59617SAndrey V. Elsukov 		inp->inp_sp->sp_out = sp;
39088768458SSam Leffler 	else
391fcf59617SAndrey V. Elsukov 		inp->inp_sp->sp_in = sp;
392fcf59617SAndrey V. Elsukov 	/*
393fcf59617SAndrey V. Elsukov 	 * SP is already referenced by the lookup code.
394fcf59617SAndrey V. Elsukov 	 * We take extra reference here to avoid race in the
395fcf59617SAndrey V. Elsukov 	 * ipsec_getpcbpolicy() function - SP will not be freed in the
396fcf59617SAndrey V. Elsukov 	 * time between we take SP pointer from the cache and key_addref()
397fcf59617SAndrey V. Elsukov 	 * call.
398fcf59617SAndrey V. Elsukov 	 */
399fcf59617SAndrey V. Elsukov 	key_addref(sp);
400fcf59617SAndrey V. Elsukov 	genid = key_getspgen();
401fcf59617SAndrey V. Elsukov 	if (genid != inp->inp_sp->genid) {
402fcf59617SAndrey V. Elsukov 		ipsec_invalidate_cache(inp, dir);
403fcf59617SAndrey V. Elsukov 		inp->inp_sp->genid = genid;
40488768458SSam Leffler 	}
405fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_STAMP,
406fcf59617SAndrey V. Elsukov 	    printf("%s: PCB(%p): cached %s SP(%p)\n",
407fcf59617SAndrey V. Elsukov 	    __func__, inp, dir == IPSEC_DIR_OUTBOUND ? "OUTBOUND":
408fcf59617SAndrey V. Elsukov 	    "INBOUND", sp));
409fcf59617SAndrey V. Elsukov 	if (downgrade != 0)
410fcf59617SAndrey V. Elsukov 		INP_DOWNGRADE(inp);
411fcf59617SAndrey V. Elsukov }
412fcf59617SAndrey V. Elsukov 
413fcf59617SAndrey V. Elsukov static struct secpolicy *
414fcf59617SAndrey V. Elsukov ipsec_checkpolicy(struct secpolicy *sp, struct inpcb *inp, int *error)
415fcf59617SAndrey V. Elsukov {
416fcf59617SAndrey V. Elsukov 
417fcf59617SAndrey V. Elsukov 	/* Save found OUTBOUND policy into PCB SP cache. */
418fcf59617SAndrey V. Elsukov 	if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_out == NULL)
419fcf59617SAndrey V. Elsukov 		ipsec_cachepolicy(inp, sp, IPSEC_DIR_OUTBOUND);
420fcf59617SAndrey V. Elsukov 
42188768458SSam Leffler 	switch (sp->policy) {
42288768458SSam Leffler 	default:
4239ffa9677SSam Leffler 		printf("%s: invalid policy %u\n", __func__, sp->policy);
424de47c390SBjoern A. Zeeb 		/* FALLTHROUGH */
42588768458SSam Leffler 	case IPSEC_POLICY_DISCARD:
426de47c390SBjoern A. Zeeb 		*error = -EINVAL;	/* Packet is discarded by caller. */
427fcf59617SAndrey V. Elsukov 		/* FALLTHROUGH */
42888768458SSam Leffler 	case IPSEC_POLICY_BYPASS:
42988768458SSam Leffler 	case IPSEC_POLICY_NONE:
430fcf59617SAndrey V. Elsukov 		key_freesp(&sp);
431de47c390SBjoern A. Zeeb 		sp = NULL;		/* NB: force NULL result. */
43288768458SSam Leffler 		break;
43388768458SSam Leffler 	case IPSEC_POLICY_IPSEC:
434fcf59617SAndrey V. Elsukov 		/* XXXAE: handle LARVAL SP */
43588768458SSam Leffler 		break;
43688768458SSam Leffler 	}
437fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_DUMP,
438fcf59617SAndrey V. Elsukov 	    printf("%s: get SP(%p), error %d\n", __func__, sp, *error));
439de47c390SBjoern A. Zeeb 	return (sp);
44088768458SSam Leffler }
44188768458SSam Leffler 
442fcf59617SAndrey V. Elsukov static struct secpolicy *
443fcf59617SAndrey V. Elsukov ipsec_getpcbpolicy(struct inpcb *inp, u_int dir)
44488768458SSam Leffler {
445fcf59617SAndrey V. Elsukov 	struct secpolicy *sp;
446fcf59617SAndrey V. Elsukov 	int flags, downgrade;
44788768458SSam Leffler 
448fcf59617SAndrey V. Elsukov 	if (inp == NULL || inp->inp_sp == NULL)
449fcf59617SAndrey V. Elsukov 		return (NULL);
45088768458SSam Leffler 
451fcf59617SAndrey V. Elsukov 	INP_LOCK_ASSERT(inp);
452fcf59617SAndrey V. Elsukov 
453fcf59617SAndrey V. Elsukov 	flags = inp->inp_sp->flags;
454fcf59617SAndrey V. Elsukov 	if (dir == IPSEC_DIR_OUTBOUND) {
455fcf59617SAndrey V. Elsukov 		sp = inp->inp_sp->sp_out;
456fcf59617SAndrey V. Elsukov 		flags &= INP_OUTBOUND_POLICY;
45788768458SSam Leffler 	} else {
458fcf59617SAndrey V. Elsukov 		sp = inp->inp_sp->sp_in;
459fcf59617SAndrey V. Elsukov 		flags &= INP_INBOUND_POLICY;
46088768458SSam Leffler 	}
46188768458SSam Leffler 	/*
462fcf59617SAndrey V. Elsukov 	 * Check flags. If we have PCB SP, just return it.
463fcf59617SAndrey V. Elsukov 	 * Otherwise we need to check that cached SP entry isn't stale.
46488768458SSam Leffler 	 */
465fcf59617SAndrey V. Elsukov 	if (flags == 0) {
466fcf59617SAndrey V. Elsukov 		if (sp == NULL)
467fcf59617SAndrey V. Elsukov 			return (NULL);
468fcf59617SAndrey V. Elsukov 		if (inp->inp_sp->genid != key_getspgen()) {
469fcf59617SAndrey V. Elsukov 			/* Invalidate the cache. */
470fcf59617SAndrey V. Elsukov 			downgrade = 0;
471fcf59617SAndrey V. Elsukov 			if (!INP_WLOCKED(inp)) {
472fcf59617SAndrey V. Elsukov 				if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
473fcf59617SAndrey V. Elsukov 					return (NULL);
474fcf59617SAndrey V. Elsukov 			}
475fcf59617SAndrey V. Elsukov 			ipsec_invalidate_cache(inp, IPSEC_DIR_OUTBOUND);
476fcf59617SAndrey V. Elsukov 			ipsec_invalidate_cache(inp, IPSEC_DIR_INBOUND);
477fcf59617SAndrey V. Elsukov 			if (downgrade != 0)
478fcf59617SAndrey V. Elsukov 				INP_DOWNGRADE(inp);
479fcf59617SAndrey V. Elsukov 			return (NULL);
480fcf59617SAndrey V. Elsukov 		}
481fcf59617SAndrey V. Elsukov 		KEYDBG(IPSEC_STAMP,
482fcf59617SAndrey V. Elsukov 		    printf("%s: PCB(%p): cache hit SP(%p)\n",
483fcf59617SAndrey V. Elsukov 		    __func__, inp, sp));
484fcf59617SAndrey V. Elsukov 		/* Return referenced cached policy */
485fcf59617SAndrey V. Elsukov 	}
486fcf59617SAndrey V. Elsukov 	key_addref(sp);
487fcf59617SAndrey V. Elsukov 	return (sp);
48888768458SSam Leffler }
48988768458SSam Leffler 
490fcf59617SAndrey V. Elsukov #ifdef INET
49188768458SSam Leffler static void
492*0ff2d00dSKonstantin Belousov ipsec4_get_ulp(const struct mbuf *m, const struct ip *ip1,
493*0ff2d00dSKonstantin Belousov     struct secpolicyindex *spidx, int needport)
49488768458SSam Leffler {
495fcf59617SAndrey V. Elsukov 	uint8_t nxt;
49688768458SSam Leffler 	int off;
49788768458SSam Leffler 
498de47c390SBjoern A. Zeeb 	/* Sanity check. */
499fcf59617SAndrey V. Elsukov 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
500fcf59617SAndrey V. Elsukov 	    ("packet too short"));
50188768458SSam Leffler 
502*0ff2d00dSKonstantin Belousov 	if (ip1->ip_off & htons(IP_MF | IP_OFFMASK))
50388768458SSam Leffler 		goto done;
504*0ff2d00dSKonstantin Belousov 	off = ip1->ip_hl << 2;
505*0ff2d00dSKonstantin Belousov 	nxt = ip1->ip_p;
50688768458SSam Leffler 
50788768458SSam Leffler 	while (off < m->m_pkthdr.len) {
50888768458SSam Leffler 		struct ip6_ext ip6e;
50988768458SSam Leffler 		struct tcphdr th;
51088768458SSam Leffler 		struct udphdr uh;
51188768458SSam Leffler 
51288768458SSam Leffler 		switch (nxt) {
51388768458SSam Leffler 		case IPPROTO_TCP:
51488768458SSam Leffler 			spidx->ul_proto = nxt;
51588768458SSam Leffler 			if (!needport)
51688768458SSam Leffler 				goto done_proto;
51788768458SSam Leffler 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
51888768458SSam Leffler 				goto done;
51988768458SSam Leffler 			m_copydata(m, off, sizeof (th), (caddr_t) &th);
52088768458SSam Leffler 			spidx->src.sin.sin_port = th.th_sport;
52188768458SSam Leffler 			spidx->dst.sin.sin_port = th.th_dport;
52288768458SSam Leffler 			return;
52388768458SSam Leffler 		case IPPROTO_UDP:
52488768458SSam Leffler 			spidx->ul_proto = nxt;
52588768458SSam Leffler 			if (!needport)
52688768458SSam Leffler 				goto done_proto;
52788768458SSam Leffler 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
52888768458SSam Leffler 				goto done;
52988768458SSam Leffler 			m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
53088768458SSam Leffler 			spidx->src.sin.sin_port = uh.uh_sport;
53188768458SSam Leffler 			spidx->dst.sin.sin_port = uh.uh_dport;
53288768458SSam Leffler 			return;
53388768458SSam Leffler 		case IPPROTO_AH:
534afa3570dSSam Leffler 			if (off + sizeof(ip6e) > m->m_pkthdr.len)
53588768458SSam Leffler 				goto done;
536de47c390SBjoern A. Zeeb 			/* XXX Sigh, this works but is totally bogus. */
53788768458SSam Leffler 			m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
53888768458SSam Leffler 			off += (ip6e.ip6e_len + 2) << 2;
53988768458SSam Leffler 			nxt = ip6e.ip6e_nxt;
54088768458SSam Leffler 			break;
54188768458SSam Leffler 		case IPPROTO_ICMP:
54288768458SSam Leffler 		default:
543de47c390SBjoern A. Zeeb 			/* XXX Intermediate headers??? */
54488768458SSam Leffler 			spidx->ul_proto = nxt;
54588768458SSam Leffler 			goto done_proto;
54688768458SSam Leffler 		}
54788768458SSam Leffler 	}
54888768458SSam Leffler done:
54988768458SSam Leffler 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
55088768458SSam Leffler done_proto:
55188768458SSam Leffler 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
55288768458SSam Leffler 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
553fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_DUMP,
554fcf59617SAndrey V. Elsukov 	    printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
55588768458SSam Leffler }
55688768458SSam Leffler 
557fcf59617SAndrey V. Elsukov static void
558*0ff2d00dSKonstantin Belousov ipsec4_setspidx_ipaddr(const struct mbuf *m, struct ip *ip1,
559*0ff2d00dSKonstantin Belousov     struct secpolicyindex *spidx)
56088768458SSam Leffler {
56188768458SSam Leffler 
562*0ff2d00dSKonstantin Belousov 	ipsec4_setsockaddrs(m, ip1, &spidx->src, &spidx->dst);
56388768458SSam Leffler 	spidx->prefs = sizeof(struct in_addr) << 3;
56488768458SSam Leffler 	spidx->prefd = sizeof(struct in_addr) << 3;
56588768458SSam Leffler }
56688768458SSam Leffler 
567fcf59617SAndrey V. Elsukov static struct secpolicy *
568*0ff2d00dSKonstantin Belousov ipsec4_getpolicy(const struct mbuf *m, struct inpcb *inp, struct ip *ip1,
569*0ff2d00dSKonstantin Belousov     u_int dir, int needport)
570fcf59617SAndrey V. Elsukov {
571fcf59617SAndrey V. Elsukov 	struct secpolicyindex spidx;
572fcf59617SAndrey V. Elsukov 	struct secpolicy *sp;
573fcf59617SAndrey V. Elsukov 
574fcf59617SAndrey V. Elsukov 	sp = ipsec_getpcbpolicy(inp, dir);
575fcf59617SAndrey V. Elsukov 	if (sp == NULL && key_havesp(dir)) {
576fcf59617SAndrey V. Elsukov 		/* Make an index to look for a policy. */
577*0ff2d00dSKonstantin Belousov 		ipsec4_setspidx_ipaddr(m, ip1, &spidx);
578*0ff2d00dSKonstantin Belousov 		ipsec4_get_ulp(m, ip1, &spidx, needport);
579fcf59617SAndrey V. Elsukov 		spidx.dir = dir;
580fcf59617SAndrey V. Elsukov 		sp = key_allocsp(&spidx, dir);
581fcf59617SAndrey V. Elsukov 	}
582fcf59617SAndrey V. Elsukov 	if (sp == NULL)		/* No SP found, use system default. */
583fcf59617SAndrey V. Elsukov 		sp = key_allocsp_default();
584fcf59617SAndrey V. Elsukov 	return (sp);
585fcf59617SAndrey V. Elsukov }
586fcf59617SAndrey V. Elsukov 
587fcf59617SAndrey V. Elsukov /*
588fcf59617SAndrey V. Elsukov  * Check security policy for *OUTBOUND* IPv4 packet.
589fcf59617SAndrey V. Elsukov  */
590fcf59617SAndrey V. Elsukov struct secpolicy *
591*0ff2d00dSKonstantin Belousov ipsec4_checkpolicy(const struct mbuf *m, struct inpcb *inp, struct ip *ip1,
592*0ff2d00dSKonstantin Belousov     int *error, int needport)
593fcf59617SAndrey V. Elsukov {
594fcf59617SAndrey V. Elsukov 	struct secpolicy *sp;
595fcf59617SAndrey V. Elsukov 
596fcf59617SAndrey V. Elsukov 	*error = 0;
597*0ff2d00dSKonstantin Belousov 	sp = ipsec4_getpolicy(m, inp, ip1, IPSEC_DIR_OUTBOUND, needport);
598fcf59617SAndrey V. Elsukov 	if (sp != NULL)
599fcf59617SAndrey V. Elsukov 		sp = ipsec_checkpolicy(sp, inp, error);
600fcf59617SAndrey V. Elsukov 	if (sp == NULL) {
601fcf59617SAndrey V. Elsukov 		switch (*error) {
602fcf59617SAndrey V. Elsukov 		case 0: /* No IPsec required: BYPASS or NONE */
603fcf59617SAndrey V. Elsukov 			break;
604fcf59617SAndrey V. Elsukov 		case -EINVAL:
605fcf59617SAndrey V. Elsukov 			IPSECSTAT_INC(ips_out_polvio);
606fcf59617SAndrey V. Elsukov 			break;
607fcf59617SAndrey V. Elsukov 		default:
608fcf59617SAndrey V. Elsukov 			IPSECSTAT_INC(ips_out_inval);
609fcf59617SAndrey V. Elsukov 		}
610fcf59617SAndrey V. Elsukov 	}
611fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_STAMP,
612fcf59617SAndrey V. Elsukov 	    printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
613fcf59617SAndrey V. Elsukov 	if (sp != NULL)
614fcf59617SAndrey V. Elsukov 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
615fcf59617SAndrey V. Elsukov 	return (sp);
616fcf59617SAndrey V. Elsukov }
617fcf59617SAndrey V. Elsukov 
618fcf59617SAndrey V. Elsukov /*
619fcf59617SAndrey V. Elsukov  * Check IPv4 packet against *INBOUND* security policy.
620fcf59617SAndrey V. Elsukov  * This function is called from tcp_input(), udp_input(),
621fcf59617SAndrey V. Elsukov  * rip_input() and sctp_input().
622fcf59617SAndrey V. Elsukov  */
623fcf59617SAndrey V. Elsukov int
624*0ff2d00dSKonstantin Belousov ipsec4_in_reject1(const struct mbuf *m, struct ip *ip1, struct inpcb *inp)
625fcf59617SAndrey V. Elsukov {
626fcf59617SAndrey V. Elsukov 	struct secpolicy *sp;
627ef2a572bSKonstantin Belousov #ifdef IPSEC_OFFLOAD
628ef2a572bSKonstantin Belousov 	struct ipsec_accel_in_tag *tag;
629ef2a572bSKonstantin Belousov #endif
630*0ff2d00dSKonstantin Belousov 	struct ip ip_hdr;
631fcf59617SAndrey V. Elsukov 	int result;
632fcf59617SAndrey V. Elsukov 
633ef2a572bSKonstantin Belousov #ifdef IPSEC_OFFLOAD
634ef2a572bSKonstantin Belousov 	tag = ipsec_accel_input_tag_lookup(m);
635ef2a572bSKonstantin Belousov 	if (tag != NULL)
636ef2a572bSKonstantin Belousov 		return (0);
637ef2a572bSKonstantin Belousov #endif
638*0ff2d00dSKonstantin Belousov 
639*0ff2d00dSKonstantin Belousov 	if (ip1 == NULL) {
640*0ff2d00dSKonstantin Belousov 		ip1 = &ip_hdr;
641*0ff2d00dSKonstantin Belousov 		m_copydata(m, 0, sizeof(*ip1), (char *)ip1);
642*0ff2d00dSKonstantin Belousov 	}
643*0ff2d00dSKonstantin Belousov 
644*0ff2d00dSKonstantin Belousov 	sp = ipsec4_getpolicy(m, inp, ip1, IPSEC_DIR_INBOUND, 0);
645fcf59617SAndrey V. Elsukov 	result = ipsec_in_reject(sp, inp, m);
646fcf59617SAndrey V. Elsukov 	key_freesp(&sp);
647fcf59617SAndrey V. Elsukov 	if (result != 0)
648fcf59617SAndrey V. Elsukov 		IPSECSTAT_INC(ips_in_polvio);
649fcf59617SAndrey V. Elsukov 	return (result);
650fcf59617SAndrey V. Elsukov }
651fcf59617SAndrey V. Elsukov 
652*0ff2d00dSKonstantin Belousov int
653*0ff2d00dSKonstantin Belousov ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
654*0ff2d00dSKonstantin Belousov {
655*0ff2d00dSKonstantin Belousov 	return (ipsec4_in_reject1(m, NULL, inp));
656*0ff2d00dSKonstantin Belousov }
657*0ff2d00dSKonstantin Belousov 
658fcf59617SAndrey V. Elsukov /*
659fcf59617SAndrey V. Elsukov  * IPSEC_CAP() method implementation for IPv4.
660fcf59617SAndrey V. Elsukov  */
661fcf59617SAndrey V. Elsukov int
662fcf59617SAndrey V. Elsukov ipsec4_capability(struct mbuf *m, u_int cap)
663fcf59617SAndrey V. Elsukov {
664fcf59617SAndrey V. Elsukov 
665fcf59617SAndrey V. Elsukov 	switch (cap) {
666fcf59617SAndrey V. Elsukov 	case IPSEC_CAP_BYPASS_FILTER:
667fcf59617SAndrey V. Elsukov 		/*
668fcf59617SAndrey V. Elsukov 		 * Bypass packet filtering for packets previously handled
669fcf59617SAndrey V. Elsukov 		 * by IPsec.
670fcf59617SAndrey V. Elsukov 		 */
671fcf59617SAndrey V. Elsukov 		if (!V_ip4_filtertunnel &&
672fcf59617SAndrey V. Elsukov 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
673fcf59617SAndrey V. Elsukov 			return (1);
674fcf59617SAndrey V. Elsukov 		return (0);
675fcf59617SAndrey V. Elsukov 	case IPSEC_CAP_OPERABLE:
676fcf59617SAndrey V. Elsukov 		/* Do we have active security policies? */
677c1bfe8c5SMateusz Guzik 		return (key_havesp_any());
678fcf59617SAndrey V. Elsukov 	};
679fcf59617SAndrey V. Elsukov 	return (EOPNOTSUPP);
680fcf59617SAndrey V. Elsukov }
681fcf59617SAndrey V. Elsukov 
682fcf59617SAndrey V. Elsukov #endif /* INET */
683fcf59617SAndrey V. Elsukov 
68488768458SSam Leffler #ifdef INET6
68588768458SSam Leffler static void
686efb10c3cSAndrey V. Elsukov ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
687efb10c3cSAndrey V. Elsukov     int needport)
68888768458SSam Leffler {
68988768458SSam Leffler 	struct tcphdr th;
69088768458SSam Leffler 	struct udphdr uh;
6910e3c2be4SBjoern A. Zeeb 	struct icmp6_hdr ih;
692fcf59617SAndrey V. Elsukov 	int off, nxt;
69388768458SSam Leffler 
694fcf59617SAndrey V. Elsukov 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip6_hdr),
695fcf59617SAndrey V. Elsukov 	    ("packet too short"));
69688768458SSam Leffler 
697de47c390SBjoern A. Zeeb 	/* Set default. */
69888768458SSam Leffler 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
699fcf59617SAndrey V. Elsukov 	spidx->src.sin6.sin6_port = IPSEC_PORT_ANY;
700fcf59617SAndrey V. Elsukov 	spidx->dst.sin6.sin6_port = IPSEC_PORT_ANY;
70188768458SSam Leffler 
70288768458SSam Leffler 	nxt = -1;
70388768458SSam Leffler 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
70488768458SSam Leffler 	if (off < 0 || m->m_pkthdr.len < off)
70588768458SSam Leffler 		return;
70688768458SSam Leffler 
70788768458SSam Leffler 	switch (nxt) {
70888768458SSam Leffler 	case IPPROTO_TCP:
70988768458SSam Leffler 		spidx->ul_proto = nxt;
71088768458SSam Leffler 		if (!needport)
71188768458SSam Leffler 			break;
71288768458SSam Leffler 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
71388768458SSam Leffler 			break;
71488768458SSam Leffler 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
715fcf59617SAndrey V. Elsukov 		spidx->src.sin6.sin6_port = th.th_sport;
716fcf59617SAndrey V. Elsukov 		spidx->dst.sin6.sin6_port = th.th_dport;
71788768458SSam Leffler 		break;
71888768458SSam Leffler 	case IPPROTO_UDP:
71988768458SSam Leffler 		spidx->ul_proto = nxt;
72088768458SSam Leffler 		if (!needport)
72188768458SSam Leffler 			break;
72288768458SSam Leffler 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
72388768458SSam Leffler 			break;
72488768458SSam Leffler 		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
725fcf59617SAndrey V. Elsukov 		spidx->src.sin6.sin6_port = uh.uh_sport;
726fcf59617SAndrey V. Elsukov 		spidx->dst.sin6.sin6_port = uh.uh_dport;
72788768458SSam Leffler 		break;
72888768458SSam Leffler 	case IPPROTO_ICMPV6:
7290e3c2be4SBjoern A. Zeeb 		spidx->ul_proto = nxt;
7300e3c2be4SBjoern A. Zeeb 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
7310e3c2be4SBjoern A. Zeeb 			break;
7320e3c2be4SBjoern A. Zeeb 		m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
733fcf59617SAndrey V. Elsukov 		spidx->src.sin6.sin6_port = htons((uint16_t)ih.icmp6_type);
734fcf59617SAndrey V. Elsukov 		spidx->dst.sin6.sin6_port = htons((uint16_t)ih.icmp6_code);
7350e3c2be4SBjoern A. Zeeb 		break;
73688768458SSam Leffler 	default:
737de47c390SBjoern A. Zeeb 		/* XXX Intermediate headers??? */
73888768458SSam Leffler 		spidx->ul_proto = nxt;
73988768458SSam Leffler 		break;
74088768458SSam Leffler 	}
741fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_DUMP,
742fcf59617SAndrey V. Elsukov 	    printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
74388768458SSam Leffler }
74488768458SSam Leffler 
745fcf59617SAndrey V. Elsukov static void
746efb10c3cSAndrey V. Elsukov ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
74788768458SSam Leffler {
74888768458SSam Leffler 
749fcf59617SAndrey V. Elsukov 	ipsec6_setsockaddrs(m, &spidx->src, &spidx->dst);
75088768458SSam Leffler 	spidx->prefs = sizeof(struct in6_addr) << 3;
75188768458SSam Leffler 	spidx->prefd = sizeof(struct in6_addr) << 3;
75288768458SSam Leffler }
753fcf59617SAndrey V. Elsukov 
754fcf59617SAndrey V. Elsukov static struct secpolicy *
75522bbefb2SAndrey V. Elsukov ipsec6_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
75622bbefb2SAndrey V. Elsukov     int needport)
757fcf59617SAndrey V. Elsukov {
758fcf59617SAndrey V. Elsukov 	struct secpolicyindex spidx;
759fcf59617SAndrey V. Elsukov 	struct secpolicy *sp;
760fcf59617SAndrey V. Elsukov 
761fcf59617SAndrey V. Elsukov 	sp = ipsec_getpcbpolicy(inp, dir);
762fcf59617SAndrey V. Elsukov 	if (sp == NULL && key_havesp(dir)) {
763fcf59617SAndrey V. Elsukov 		/* Make an index to look for a policy. */
764fcf59617SAndrey V. Elsukov 		ipsec6_setspidx_ipaddr(m, &spidx);
76522bbefb2SAndrey V. Elsukov 		ipsec6_get_ulp(m, &spidx, needport);
766fcf59617SAndrey V. Elsukov 		spidx.dir = dir;
767fcf59617SAndrey V. Elsukov 		sp = key_allocsp(&spidx, dir);
768fcf59617SAndrey V. Elsukov 	}
769fcf59617SAndrey V. Elsukov 	if (sp == NULL)		/* No SP found, use system default. */
770fcf59617SAndrey V. Elsukov 		sp = key_allocsp_default();
771fcf59617SAndrey V. Elsukov 	return (sp);
772fcf59617SAndrey V. Elsukov }
773fcf59617SAndrey V. Elsukov 
774fcf59617SAndrey V. Elsukov /*
775fcf59617SAndrey V. Elsukov  * Check security policy for *OUTBOUND* IPv6 packet.
776fcf59617SAndrey V. Elsukov  */
777fcf59617SAndrey V. Elsukov struct secpolicy *
77822bbefb2SAndrey V. Elsukov ipsec6_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
77922bbefb2SAndrey V. Elsukov     int needport)
780fcf59617SAndrey V. Elsukov {
781fcf59617SAndrey V. Elsukov 	struct secpolicy *sp;
782fcf59617SAndrey V. Elsukov 
783fcf59617SAndrey V. Elsukov 	*error = 0;
78422bbefb2SAndrey V. Elsukov 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
785fcf59617SAndrey V. Elsukov 	if (sp != NULL)
786fcf59617SAndrey V. Elsukov 		sp = ipsec_checkpolicy(sp, inp, error);
787fcf59617SAndrey V. Elsukov 	if (sp == NULL) {
788fcf59617SAndrey V. Elsukov 		switch (*error) {
789fcf59617SAndrey V. Elsukov 		case 0: /* No IPsec required: BYPASS or NONE */
790fcf59617SAndrey V. Elsukov 			break;
791fcf59617SAndrey V. Elsukov 		case -EINVAL:
792fcf59617SAndrey V. Elsukov 			IPSEC6STAT_INC(ips_out_polvio);
793fcf59617SAndrey V. Elsukov 			break;
794fcf59617SAndrey V. Elsukov 		default:
795fcf59617SAndrey V. Elsukov 			IPSEC6STAT_INC(ips_out_inval);
796fcf59617SAndrey V. Elsukov 		}
797fcf59617SAndrey V. Elsukov 	}
798fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_STAMP,
799fcf59617SAndrey V. Elsukov 	    printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
800fcf59617SAndrey V. Elsukov 	if (sp != NULL)
801fcf59617SAndrey V. Elsukov 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
802fcf59617SAndrey V. Elsukov 	return (sp);
803fcf59617SAndrey V. Elsukov }
804fcf59617SAndrey V. Elsukov 
805fcf59617SAndrey V. Elsukov /*
806fcf59617SAndrey V. Elsukov  * Check IPv6 packet against inbound security policy.
807fcf59617SAndrey V. Elsukov  * This function is called from tcp6_input(), udp6_input(),
808fcf59617SAndrey V. Elsukov  * rip6_input() and sctp_input().
809fcf59617SAndrey V. Elsukov  */
810fcf59617SAndrey V. Elsukov int
811fcf59617SAndrey V. Elsukov ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
812fcf59617SAndrey V. Elsukov {
813fcf59617SAndrey V. Elsukov 	struct secpolicy *sp;
814ef2a572bSKonstantin Belousov #ifdef IPSEC_OFFLOAD
815ef2a572bSKonstantin Belousov 	struct ipsec_accel_in_tag *tag;
816ef2a572bSKonstantin Belousov #endif
817fcf59617SAndrey V. Elsukov 	int result;
818fcf59617SAndrey V. Elsukov 
819ef2a572bSKonstantin Belousov #ifdef IPSEC_OFFLOAD
820ef2a572bSKonstantin Belousov 	tag = ipsec_accel_input_tag_lookup(m);
821ef2a572bSKonstantin Belousov 	if (tag != NULL)
822ef2a572bSKonstantin Belousov 		return (0);
823ef2a572bSKonstantin Belousov #endif
82422bbefb2SAndrey V. Elsukov 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
825fcf59617SAndrey V. Elsukov 	result = ipsec_in_reject(sp, inp, m);
826fcf59617SAndrey V. Elsukov 	key_freesp(&sp);
827fcf59617SAndrey V. Elsukov 	if (result)
828fcf59617SAndrey V. Elsukov 		IPSEC6STAT_INC(ips_in_polvio);
829fcf59617SAndrey V. Elsukov 	return (result);
830fcf59617SAndrey V. Elsukov }
831fcf59617SAndrey V. Elsukov 
832fcf59617SAndrey V. Elsukov /*
833fcf59617SAndrey V. Elsukov  * IPSEC_CAP() method implementation for IPv6.
834fcf59617SAndrey V. Elsukov  */
835fcf59617SAndrey V. Elsukov int
836fcf59617SAndrey V. Elsukov ipsec6_capability(struct mbuf *m, u_int cap)
837fcf59617SAndrey V. Elsukov {
838fcf59617SAndrey V. Elsukov 
839fcf59617SAndrey V. Elsukov 	switch (cap) {
840fcf59617SAndrey V. Elsukov 	case IPSEC_CAP_BYPASS_FILTER:
841fcf59617SAndrey V. Elsukov 		/*
842fcf59617SAndrey V. Elsukov 		 * Bypass packet filtering for packets previously handled
843fcf59617SAndrey V. Elsukov 		 * by IPsec.
844fcf59617SAndrey V. Elsukov 		 */
845fcf59617SAndrey V. Elsukov 		if (!V_ip6_filtertunnel &&
846fcf59617SAndrey V. Elsukov 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
847fcf59617SAndrey V. Elsukov 			return (1);
848fcf59617SAndrey V. Elsukov 		return (0);
849fcf59617SAndrey V. Elsukov 	case IPSEC_CAP_OPERABLE:
850fcf59617SAndrey V. Elsukov 		/* Do we have active security policies? */
851c1bfe8c5SMateusz Guzik 		return (key_havesp_any());
852fcf59617SAndrey V. Elsukov 	};
853fcf59617SAndrey V. Elsukov 	return (EOPNOTSUPP);
854fcf59617SAndrey V. Elsukov }
855fcf59617SAndrey V. Elsukov #endif /* INET6 */
85688768458SSam Leffler 
857ef91a976SAndrey V. Elsukov int
858ef91a976SAndrey V. Elsukov ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type)
859ef91a976SAndrey V. Elsukov {
860ef91a976SAndrey V. Elsukov 	int idx;
861ef91a976SAndrey V. Elsukov 
862ef91a976SAndrey V. Elsukov 	switch (ctx->af) {
863ef91a976SAndrey V. Elsukov #ifdef INET
864ef91a976SAndrey V. Elsukov 	case AF_INET:
865ef91a976SAndrey V. Elsukov 		idx = HHOOK_IPSEC_INET;
866ef91a976SAndrey V. Elsukov 		break;
867ef91a976SAndrey V. Elsukov #endif
868ef91a976SAndrey V. Elsukov #ifdef INET6
869ef91a976SAndrey V. Elsukov 	case AF_INET6:
870ef91a976SAndrey V. Elsukov 		idx = HHOOK_IPSEC_INET6;
871ef91a976SAndrey V. Elsukov 		break;
872ef91a976SAndrey V. Elsukov #endif
873ef91a976SAndrey V. Elsukov 	default:
874ef91a976SAndrey V. Elsukov 		return (EPFNOSUPPORT);
875ef91a976SAndrey V. Elsukov 	}
876ef91a976SAndrey V. Elsukov 	if (type == HHOOK_TYPE_IPSEC_IN)
877ef91a976SAndrey V. Elsukov 		HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL);
878ef91a976SAndrey V. Elsukov 	else
879ef91a976SAndrey V. Elsukov 		HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL);
880ef91a976SAndrey V. Elsukov 	if (*ctx->mp == NULL)
881ef91a976SAndrey V. Elsukov 		return (EACCES);
882ef91a976SAndrey V. Elsukov 	return (0);
883ef91a976SAndrey V. Elsukov }
884ef91a976SAndrey V. Elsukov 
88588768458SSam Leffler /*
886de47c390SBjoern A. Zeeb  * Return current level.
88788768458SSam Leffler  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
88888768458SSam Leffler  */
88988768458SSam Leffler u_int
890fcf59617SAndrey V. Elsukov ipsec_get_reqlevel(struct secpolicy *sp, u_int idx)
89188768458SSam Leffler {
892fcf59617SAndrey V. Elsukov 	struct ipsecrequest *isr;
89388768458SSam Leffler 	u_int esp_trans_deflev, esp_net_deflev;
89488768458SSam Leffler 	u_int ah_trans_deflev, ah_net_deflev;
895fcf59617SAndrey V. Elsukov 	u_int level = 0;
89688768458SSam Leffler 
897fcf59617SAndrey V. Elsukov 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
898de47c390SBjoern A. Zeeb /* XXX Note that we have ipseclog() expanded here - code sync issue. */
89988768458SSam Leffler #define IPSEC_CHECK_DEFAULT(lev) \
900fcf59617SAndrey V. Elsukov 	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE &&	\
901fcf59617SAndrey V. Elsukov 	  (lev) != IPSEC_LEVEL_UNIQUE)					\
902fcf59617SAndrey V. Elsukov 		? (V_ipsec_debug  ?					\
903fcf59617SAndrey V. Elsukov 		log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
904fcf59617SAndrey V. Elsukov 		(lev), IPSEC_LEVEL_REQUIRE) : 0),			\
905fcf59617SAndrey V. Elsukov 		(lev) = IPSEC_LEVEL_REQUIRE, (lev) : (lev))
906fcf59617SAndrey V. Elsukov 
907fcf59617SAndrey V. Elsukov 	/*
908fcf59617SAndrey V. Elsukov 	 * IPsec VTI uses unique security policy with fake spidx filled
909fcf59617SAndrey V. Elsukov 	 * with zeroes. Just return IPSEC_LEVEL_REQUIRE instead of doing
910fcf59617SAndrey V. Elsukov 	 * full level lookup for such policies.
911fcf59617SAndrey V. Elsukov 	 */
912fcf59617SAndrey V. Elsukov 	if (sp->state == IPSEC_SPSTATE_IFNET) {
913fcf59617SAndrey V. Elsukov 		IPSEC_ASSERT(sp->req[idx]->level == IPSEC_LEVEL_UNIQUE,
914fcf59617SAndrey V. Elsukov 		    ("Wrong IPsec request level %d", sp->req[idx]->level));
915fcf59617SAndrey V. Elsukov 		return (IPSEC_LEVEL_REQUIRE);
916fcf59617SAndrey V. Elsukov 	}
91788768458SSam Leffler 
918de47c390SBjoern A. Zeeb 	/* Set default level. */
919fcf59617SAndrey V. Elsukov 	switch (sp->spidx.src.sa.sa_family) {
92088768458SSam Leffler #ifdef INET
92188768458SSam Leffler 	case AF_INET:
922603724d3SBjoern A. Zeeb 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev);
923603724d3SBjoern A. Zeeb 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev);
924603724d3SBjoern A. Zeeb 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev);
925603724d3SBjoern A. Zeeb 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev);
92688768458SSam Leffler 		break;
92788768458SSam Leffler #endif
92888768458SSam Leffler #ifdef INET6
92988768458SSam Leffler 	case AF_INET6:
930603724d3SBjoern A. Zeeb 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev);
931603724d3SBjoern A. Zeeb 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev);
932603724d3SBjoern A. Zeeb 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev);
933603724d3SBjoern A. Zeeb 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev);
93488768458SSam Leffler 		break;
93588768458SSam Leffler #endif /* INET6 */
93688768458SSam Leffler 	default:
9379ffa9677SSam Leffler 		panic("%s: unknown af %u",
938fcf59617SAndrey V. Elsukov 			__func__, sp->spidx.src.sa.sa_family);
93988768458SSam Leffler 	}
94088768458SSam Leffler 
94188768458SSam Leffler #undef IPSEC_CHECK_DEFAULT
94288768458SSam Leffler 
943fcf59617SAndrey V. Elsukov 	isr = sp->req[idx];
944de47c390SBjoern A. Zeeb 	/* Set level. */
94588768458SSam Leffler 	switch (isr->level) {
94688768458SSam Leffler 	case IPSEC_LEVEL_DEFAULT:
94788768458SSam Leffler 		switch (isr->saidx.proto) {
94888768458SSam Leffler 		case IPPROTO_ESP:
94988768458SSam Leffler 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
95088768458SSam Leffler 				level = esp_net_deflev;
95188768458SSam Leffler 			else
95288768458SSam Leffler 				level = esp_trans_deflev;
95388768458SSam Leffler 			break;
95488768458SSam Leffler 		case IPPROTO_AH:
95588768458SSam Leffler 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
95688768458SSam Leffler 				level = ah_net_deflev;
95788768458SSam Leffler 			else
95888768458SSam Leffler 				level = ah_trans_deflev;
9598381996eSSam Leffler 			break;
96088768458SSam Leffler 		case IPPROTO_IPCOMP:
96188768458SSam Leffler 			/*
962de47c390SBjoern A. Zeeb 			 * We don't really care, as IPcomp document says that
963de47c390SBjoern A. Zeeb 			 * we shouldn't compress small packets.
96488768458SSam Leffler 			 */
96588768458SSam Leffler 			level = IPSEC_LEVEL_USE;
96688768458SSam Leffler 			break;
96788768458SSam Leffler 		default:
9689ffa9677SSam Leffler 			panic("%s: Illegal protocol defined %u\n", __func__,
96988768458SSam Leffler 				isr->saidx.proto);
97088768458SSam Leffler 		}
97188768458SSam Leffler 		break;
97288768458SSam Leffler 
97388768458SSam Leffler 	case IPSEC_LEVEL_USE:
97488768458SSam Leffler 	case IPSEC_LEVEL_REQUIRE:
97588768458SSam Leffler 		level = isr->level;
97688768458SSam Leffler 		break;
97788768458SSam Leffler 	case IPSEC_LEVEL_UNIQUE:
97888768458SSam Leffler 		level = IPSEC_LEVEL_REQUIRE;
97988768458SSam Leffler 		break;
98088768458SSam Leffler 
98188768458SSam Leffler 	default:
9829ffa9677SSam Leffler 		panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
98388768458SSam Leffler 	}
98488768458SSam Leffler 
985de47c390SBjoern A. Zeeb 	return (level);
98688768458SSam Leffler }
98788768458SSam Leffler 
988fcf59617SAndrey V. Elsukov static int
989fcf59617SAndrey V. Elsukov ipsec_check_history(const struct mbuf *m, struct secpolicy *sp, u_int idx)
990fcf59617SAndrey V. Elsukov {
991fcf59617SAndrey V. Elsukov 	struct xform_history *xh;
992fcf59617SAndrey V. Elsukov 	struct m_tag *mtag;
993fcf59617SAndrey V. Elsukov 
994fcf59617SAndrey V. Elsukov 	mtag = NULL;
995fcf59617SAndrey V. Elsukov 	while ((mtag = m_tag_find(__DECONST(struct mbuf *, m),
996fcf59617SAndrey V. Elsukov 	    PACKET_TAG_IPSEC_IN_DONE, mtag)) != NULL) {
997fcf59617SAndrey V. Elsukov 		xh = (struct xform_history *)(mtag + 1);
998fcf59617SAndrey V. Elsukov 		KEYDBG(IPSEC_DATA,
999fcf59617SAndrey V. Elsukov 		    char buf[IPSEC_ADDRSTRLEN];
1000fcf59617SAndrey V. Elsukov 		    printf("%s: mode %s proto %u dst %s\n", __func__,
1001fcf59617SAndrey V. Elsukov 			kdebug_secasindex_mode(xh->mode), xh->proto,
1002fcf59617SAndrey V. Elsukov 			ipsec_address(&xh->dst, buf, sizeof(buf))));
1003fcf59617SAndrey V. Elsukov 		if (xh->proto != sp->req[idx]->saidx.proto)
1004fcf59617SAndrey V. Elsukov 			continue;
1005fcf59617SAndrey V. Elsukov 		/* If SA had IPSEC_MODE_ANY, consider this as match. */
1006fcf59617SAndrey V. Elsukov 		if (xh->mode != sp->req[idx]->saidx.mode &&
1007fcf59617SAndrey V. Elsukov 		    xh->mode != IPSEC_MODE_ANY)
1008fcf59617SAndrey V. Elsukov 			continue;
1009fcf59617SAndrey V. Elsukov 		/*
1010fcf59617SAndrey V. Elsukov 		 * For transport mode IPsec request doesn't contain
1011fcf59617SAndrey V. Elsukov 		 * addresses. We need to use address from spidx.
1012fcf59617SAndrey V. Elsukov 		 */
1013fcf59617SAndrey V. Elsukov 		if (sp->req[idx]->saidx.mode == IPSEC_MODE_TRANSPORT) {
1014fcf59617SAndrey V. Elsukov 			if (key_sockaddrcmp_withmask(&xh->dst.sa,
1015fcf59617SAndrey V. Elsukov 			    &sp->spidx.dst.sa, sp->spidx.prefd) != 0)
1016fcf59617SAndrey V. Elsukov 				continue;
1017fcf59617SAndrey V. Elsukov 		} else {
1018fcf59617SAndrey V. Elsukov 			if (key_sockaddrcmp(&xh->dst.sa,
1019fcf59617SAndrey V. Elsukov 			    &sp->req[idx]->saidx.dst.sa, 0) != 0)
1020fcf59617SAndrey V. Elsukov 				continue;
1021fcf59617SAndrey V. Elsukov 		}
1022fcf59617SAndrey V. Elsukov 		return (0); /* matched */
1023fcf59617SAndrey V. Elsukov 	}
1024fcf59617SAndrey V. Elsukov 	return (1);
1025fcf59617SAndrey V. Elsukov }
1026fcf59617SAndrey V. Elsukov 
102788768458SSam Leffler /*
102888768458SSam Leffler  * Check security policy requirements against the actual
102988768458SSam Leffler  * packet contents.  Return one if the packet should be
1030424f1296SKonstantin Belousov  * rejected as "invalid"; otherwise return zero to have the
103188768458SSam Leffler  * packet treated as "valid".
103288768458SSam Leffler  *
103388768458SSam Leffler  * OUT:
103488768458SSam Leffler  *	0: valid
103588768458SSam Leffler  *	1: invalid
103688768458SSam Leffler  */
1037a9b9f6b6SAndrey V. Elsukov static int
1038fcf59617SAndrey V. Elsukov ipsec_in_reject(struct secpolicy *sp, struct inpcb *inp, const struct mbuf *m)
103988768458SSam Leffler {
1040fcf59617SAndrey V. Elsukov 	int i;
104188768458SSam Leffler 
1042fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_STAMP,
1043fcf59617SAndrey V. Elsukov 	    printf("%s: PCB(%p): using SP(%p)\n", __func__, inp, sp));
1044fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1045fcf59617SAndrey V. Elsukov 
1046fcf59617SAndrey V. Elsukov 	if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_in == NULL)
1047fcf59617SAndrey V. Elsukov 		ipsec_cachepolicy(inp, sp, IPSEC_DIR_INBOUND);
104888768458SSam Leffler 
1049de47c390SBjoern A. Zeeb 	/* Check policy. */
105088768458SSam Leffler 	switch (sp->policy) {
105188768458SSam Leffler 	case IPSEC_POLICY_DISCARD:
1052de47c390SBjoern A. Zeeb 		return (1);
105388768458SSam Leffler 	case IPSEC_POLICY_BYPASS:
105488768458SSam Leffler 	case IPSEC_POLICY_NONE:
1055de47c390SBjoern A. Zeeb 		return (0);
105688768458SSam Leffler 	}
105788768458SSam Leffler 
10589ffa9677SSam Leffler 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
10599ffa9677SSam Leffler 		("invalid policy %u", sp->policy));
106088768458SSam Leffler 
1061fcf59617SAndrey V. Elsukov 	/*
1062fcf59617SAndrey V. Elsukov 	 * ipsec[46]_common_input_cb after each transform adds
1063fcf59617SAndrey V. Elsukov 	 * PACKET_TAG_IPSEC_IN_DONE mbuf tag. It contains SPI, proto, mode
1064fcf59617SAndrey V. Elsukov 	 * and destination address from saidx. We can compare info from
1065fcf59617SAndrey V. Elsukov 	 * these tags with requirements in SP.
1066fcf59617SAndrey V. Elsukov 	 */
1067fcf59617SAndrey V. Elsukov 	for (i = 0; i < sp->tcount; i++) {
1068fcf59617SAndrey V. Elsukov 		/*
1069fcf59617SAndrey V. Elsukov 		 * Do not check IPcomp, since IPcomp document
1070fcf59617SAndrey V. Elsukov 		 * says that we shouldn't compress small packets.
1071fcf59617SAndrey V. Elsukov 		 * IPComp policy should always be treated as being
1072fcf59617SAndrey V. Elsukov 		 * in "use" level.
1073fcf59617SAndrey V. Elsukov 		 */
1074fcf59617SAndrey V. Elsukov 		if (sp->req[i]->saidx.proto == IPPROTO_IPCOMP ||
1075fcf59617SAndrey V. Elsukov 		    ipsec_get_reqlevel(sp, i) != IPSEC_LEVEL_REQUIRE)
107688768458SSam Leffler 			continue;
1077fcf59617SAndrey V. Elsukov 		if (V_check_policy_history != 0 &&
1078fcf59617SAndrey V. Elsukov 		    ipsec_check_history(m, sp, i) != 0)
1079fcf59617SAndrey V. Elsukov 			return (1);
1080fcf59617SAndrey V. Elsukov 		else switch (sp->req[i]->saidx.proto) {
108188768458SSam Leffler 		case IPPROTO_ESP:
108288768458SSam Leffler 			if ((m->m_flags & M_DECRYPTED) == 0) {
1083fcf59617SAndrey V. Elsukov 				KEYDBG(IPSEC_DUMP,
10849ffa9677SSam Leffler 				    printf("%s: ESP m_flags:%x\n", __func__,
108588768458SSam Leffler 					    m->m_flags));
1086de47c390SBjoern A. Zeeb 				return (1);
108788768458SSam Leffler 			}
108888768458SSam Leffler 			break;
108988768458SSam Leffler 		case IPPROTO_AH:
109088768458SSam Leffler 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1091fcf59617SAndrey V. Elsukov 				KEYDBG(IPSEC_DUMP,
10929ffa9677SSam Leffler 				    printf("%s: AH m_flags:%x\n", __func__,
109388768458SSam Leffler 					    m->m_flags));
1094de47c390SBjoern A. Zeeb 				return (1);
109588768458SSam Leffler 			}
109688768458SSam Leffler 			break;
109788768458SSam Leffler 		}
109888768458SSam Leffler 	}
1099de47c390SBjoern A. Zeeb 	return (0);		/* Valid. */
110088768458SSam Leffler }
110188768458SSam Leffler 
1102a91150daSAndrey V. Elsukov /*
1103de47c390SBjoern A. Zeeb  * Compute the byte size to be occupied by IPsec header.
1104de47c390SBjoern A. Zeeb  * In case it is tunnelled, it includes the size of outer IP header.
110588768458SSam Leffler  */
11066b66194bSKornel Duleba size_t
110797aa4a51SBjoern A. Zeeb ipsec_hdrsiz_internal(struct secpolicy *sp)
110888768458SSam Leffler {
11091f8bd75eSBjoern A. Zeeb 	size_t size;
1110fcf59617SAndrey V. Elsukov 	int i;
111188768458SSam Leffler 
1112fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_STAMP, printf("%s: using SP(%p)\n", __func__, sp));
1113fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
111488768458SSam Leffler 
111588768458SSam Leffler 	switch (sp->policy) {
111688768458SSam Leffler 	case IPSEC_POLICY_DISCARD:
111788768458SSam Leffler 	case IPSEC_POLICY_BYPASS:
111888768458SSam Leffler 	case IPSEC_POLICY_NONE:
1119de47c390SBjoern A. Zeeb 		return (0);
112088768458SSam Leffler 	}
112188768458SSam Leffler 
11229ffa9677SSam Leffler 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
11239ffa9677SSam Leffler 		("invalid policy %u", sp->policy));
112488768458SSam Leffler 
1125fcf59617SAndrey V. Elsukov 	/*
1126fcf59617SAndrey V. Elsukov 	 * XXX: for each transform we need to lookup suitable SA
1127fcf59617SAndrey V. Elsukov 	 * and use info from SA to calculate headers size.
1128fcf59617SAndrey V. Elsukov 	 * XXX: for NAT-T we need to cosider UDP header size.
1129fcf59617SAndrey V. Elsukov 	 */
11301f8bd75eSBjoern A. Zeeb 	size = 0;
1131fcf59617SAndrey V. Elsukov 	for (i = 0; i < sp->tcount; i++) {
1132fcf59617SAndrey V. Elsukov 		switch (sp->req[i]->saidx.proto) {
113388768458SSam Leffler 		case IPPROTO_ESP:
1134fcf59617SAndrey V. Elsukov 			size += esp_hdrsiz(NULL);
113588768458SSam Leffler 			break;
113688768458SSam Leffler 		case IPPROTO_AH:
1137fcf59617SAndrey V. Elsukov 			size += ah_hdrsiz(NULL);
113888768458SSam Leffler 			break;
113988768458SSam Leffler 		case IPPROTO_IPCOMP:
1140fcf59617SAndrey V. Elsukov 			size += sizeof(struct ipcomp);
114188768458SSam Leffler 			break;
114288768458SSam Leffler 		}
114388768458SSam Leffler 
1144fcf59617SAndrey V. Elsukov 		if (sp->req[i]->saidx.mode == IPSEC_MODE_TUNNEL) {
1145fcf59617SAndrey V. Elsukov 			switch (sp->req[i]->saidx.dst.sa.sa_family) {
1146fcf59617SAndrey V. Elsukov #ifdef INET
114788768458SSam Leffler 			case AF_INET:
1148fcf59617SAndrey V. Elsukov 				size += sizeof(struct ip);
114988768458SSam Leffler 				break;
1150fcf59617SAndrey V. Elsukov #endif
115188768458SSam Leffler #ifdef INET6
115288768458SSam Leffler 			case AF_INET6:
1153fcf59617SAndrey V. Elsukov 				size += sizeof(struct ip6_hdr);
115488768458SSam Leffler 				break;
115588768458SSam Leffler #endif
115688768458SSam Leffler 			default:
11579ffa9677SSam Leffler 				ipseclog((LOG_ERR, "%s: unknown AF %d in "
11589ffa9677SSam Leffler 				    "IPsec tunnel SA\n", __func__,
1159fcf59617SAndrey V. Elsukov 				    sp->req[i]->saidx.dst.sa.sa_family));
116088768458SSam Leffler 				break;
116188768458SSam Leffler 			}
116288768458SSam Leffler 		}
116388768458SSam Leffler 	}
11641f8bd75eSBjoern A. Zeeb 	return (size);
116588768458SSam Leffler }
116688768458SSam Leffler 
116797aa4a51SBjoern A. Zeeb /*
1168fcf59617SAndrey V. Elsukov  * Compute ESP/AH header size for protocols with PCB, including
1169fcf59617SAndrey V. Elsukov  * outer IP header. Currently only tcp_output() uses it.
117097aa4a51SBjoern A. Zeeb  */
117188768458SSam Leffler size_t
1172fcf59617SAndrey V. Elsukov ipsec_hdrsiz_inpcb(struct inpcb *inp)
117388768458SSam Leffler {
1174fcf59617SAndrey V. Elsukov 	struct secpolicyindex spidx;
117588768458SSam Leffler 	struct secpolicy *sp;
1176fcf59617SAndrey V. Elsukov 	size_t sz;
117788768458SSam Leffler 
1178fcf59617SAndrey V. Elsukov 	sp = ipsec_getpcbpolicy(inp, IPSEC_DIR_OUTBOUND);
1179fcf59617SAndrey V. Elsukov 	if (sp == NULL && key_havesp(IPSEC_DIR_OUTBOUND)) {
1180fcf59617SAndrey V. Elsukov 		ipsec_setspidx_inpcb(inp, &spidx, IPSEC_DIR_OUTBOUND);
1181fcf59617SAndrey V. Elsukov 		sp = key_allocsp(&spidx, IPSEC_DIR_OUTBOUND);
118288768458SSam Leffler 	}
1183fcf59617SAndrey V. Elsukov 	if (sp == NULL)
1184fcf59617SAndrey V. Elsukov 		sp = key_allocsp_default();
1185fcf59617SAndrey V. Elsukov 	sz = ipsec_hdrsiz_internal(sp);
1186fcf59617SAndrey V. Elsukov 	key_freesp(&sp);
1187fcf59617SAndrey V. Elsukov 	return (sz);
118888768458SSam Leffler }
118988768458SSam Leffler 
11908b7f3994SMarcin Wojtas 
11918b7f3994SMarcin Wojtas #define IPSEC_BITMAP_INDEX_MASK(w)	(w - 1)
11928b7f3994SMarcin Wojtas #define IPSEC_REDUNDANT_BIT_SHIFTS	5
11938b7f3994SMarcin Wojtas #define IPSEC_REDUNDANT_BITS		(1 << IPSEC_REDUNDANT_BIT_SHIFTS)
11948b7f3994SMarcin Wojtas #define IPSEC_BITMAP_LOC_MASK		(IPSEC_REDUNDANT_BITS - 1)
11958b7f3994SMarcin Wojtas 
11968b7f3994SMarcin Wojtas /*
11978b7f3994SMarcin Wojtas  * Functions below are responsible for checking and updating bitmap.
11988b7f3994SMarcin Wojtas  * These are used to separate ipsec_chkreplay() and ipsec_updatereplay()
11998b7f3994SMarcin Wojtas  * from window implementation
12008b7f3994SMarcin Wojtas  *
12018b7f3994SMarcin Wojtas  * Based on RFC 6479. Blocks are 32 bits unsigned integers
12028b7f3994SMarcin Wojtas  */
12038b7f3994SMarcin Wojtas 
12048b7f3994SMarcin Wojtas static inline int
12058b7f3994SMarcin Wojtas check_window(const struct secreplay *replay, uint64_t seq)
12068b7f3994SMarcin Wojtas {
12078b7f3994SMarcin Wojtas 	int index, bit_location;
12088b7f3994SMarcin Wojtas 
12090361f165SKristof Provost 	SECREPLAY_ASSERT(replay);
12100361f165SKristof Provost 
12118b7f3994SMarcin Wojtas 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
12128b7f3994SMarcin Wojtas 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
12138b7f3994SMarcin Wojtas 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
12148b7f3994SMarcin Wojtas 
12158b7f3994SMarcin Wojtas 	/* This packet already seen? */
12168b7f3994SMarcin Wojtas 	return ((replay->bitmap)[index] & (1 << bit_location));
12178b7f3994SMarcin Wojtas }
12188b7f3994SMarcin Wojtas 
12198b7f3994SMarcin Wojtas static inline void
12208b7f3994SMarcin Wojtas advance_window(const struct secreplay *replay, uint64_t seq)
12218b7f3994SMarcin Wojtas {
12228b7f3994SMarcin Wojtas 	int i;
12238b7f3994SMarcin Wojtas 	uint64_t index, index_cur, diff;
12248b7f3994SMarcin Wojtas 
12250361f165SKristof Provost 	SECREPLAY_ASSERT(replay);
12260361f165SKristof Provost 
12278b7f3994SMarcin Wojtas 	index_cur = replay->last >> IPSEC_REDUNDANT_BIT_SHIFTS;
12288b7f3994SMarcin Wojtas 	index = seq >> IPSEC_REDUNDANT_BIT_SHIFTS;
12298b7f3994SMarcin Wojtas 	diff = index - index_cur;
12308b7f3994SMarcin Wojtas 
12318b7f3994SMarcin Wojtas 	if (diff > replay->bitmap_size) {
12328b7f3994SMarcin Wojtas 		/* something unusual in this case */
12338b7f3994SMarcin Wojtas 		diff = replay->bitmap_size;
12348b7f3994SMarcin Wojtas 	}
12358b7f3994SMarcin Wojtas 
12368b7f3994SMarcin Wojtas 	for (i = 0; i < diff; i++) {
12378b7f3994SMarcin Wojtas 		replay->bitmap[(i + index_cur + 1)
12388b7f3994SMarcin Wojtas 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
12398b7f3994SMarcin Wojtas 	}
12408b7f3994SMarcin Wojtas }
12418b7f3994SMarcin Wojtas 
12428b7f3994SMarcin Wojtas static inline void
12438b7f3994SMarcin Wojtas set_window(const struct secreplay *replay, uint64_t seq)
12448b7f3994SMarcin Wojtas {
12458b7f3994SMarcin Wojtas 	int index, bit_location;
12468b7f3994SMarcin Wojtas 
12470361f165SKristof Provost 	SECREPLAY_ASSERT(replay);
12480361f165SKristof Provost 
12498b7f3994SMarcin Wojtas 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
12508b7f3994SMarcin Wojtas 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
12518b7f3994SMarcin Wojtas 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
12528b7f3994SMarcin Wojtas 
12538b7f3994SMarcin Wojtas 	replay->bitmap[index] |= (1 << bit_location);
12548b7f3994SMarcin Wojtas }
12558b7f3994SMarcin Wojtas 
125688768458SSam Leffler /*
125788768458SSam Leffler  * Check the variable replay window.
125888768458SSam Leffler  * ipsec_chkreplay() performs replay check before ICV verification.
125988768458SSam Leffler  * ipsec_updatereplay() updates replay bitmap.  This must be called after
126088768458SSam Leffler  * ICV verification (it also performs replay check, which is usually done
126188768458SSam Leffler  * beforehand).
126288768458SSam Leffler  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
126388768458SSam Leffler  *
12648b7f3994SMarcin Wojtas  * Based on RFC 4303
126588768458SSam Leffler  */
1266bf435626SFabien Thomas 
126788768458SSam Leffler int
12688b7f3994SMarcin Wojtas ipsec_chkreplay(uint32_t seq, uint32_t *seqhigh, struct secasvar *sav)
126988768458SSam Leffler {
12708b7f3994SMarcin Wojtas 	char buf[128];
12718b7f3994SMarcin Wojtas 	struct secreplay *replay;
12728b7f3994SMarcin Wojtas 	uint32_t window;
12738b7f3994SMarcin Wojtas 	uint32_t tl, th, bl;
12748b7f3994SMarcin Wojtas 	uint32_t seqh;
127588768458SSam Leffler 
12769ffa9677SSam Leffler 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
12779ffa9677SSam Leffler 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
127888768458SSam Leffler 
127988768458SSam Leffler 	replay = sav->replay;
128088768458SSam Leffler 
1281bf435626SFabien Thomas 	/* No need to check replay if disabled. */
12820361f165SKristof Provost 	if (replay->wsize == 0) {
1283fcf59617SAndrey V. Elsukov 		return (1);
12840361f165SKristof Provost 	}
12850361f165SKristof Provost 
12860361f165SKristof Provost 	SECREPLAY_LOCK(replay);
128788768458SSam Leffler 
12888b7f3994SMarcin Wojtas 	/* Zero sequence number is not allowed. */
12890361f165SKristof Provost 	if (seq == 0 && replay->last == 0) {
12900361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
1291fcf59617SAndrey V. Elsukov 		return (0);
12920361f165SKristof Provost 	}
129388768458SSam Leffler 
12948b7f3994SMarcin Wojtas 	window = replay->wsize << 3;		/* Size of window */
12958b7f3994SMarcin Wojtas 	tl = (uint32_t)replay->last;		/* Top of window, lower part */
12968b7f3994SMarcin Wojtas 	th = (uint32_t)(replay->last >> 32);	/* Top of window, high part */
12978b7f3994SMarcin Wojtas 	bl = tl - window + 1;			/* Bottom of window, lower part */
129888768458SSam Leffler 
12998b7f3994SMarcin Wojtas 	/*
13008b7f3994SMarcin Wojtas 	 * We keep the high part intact when:
13018b7f3994SMarcin Wojtas 	 * 1) the seq is within [bl, 0xffffffff] and the whole window is
13028b7f3994SMarcin Wojtas 	 *    within one subspace;
13038b7f3994SMarcin Wojtas 	 * 2) the seq is within [0, bl) and window spans two subspaces.
1304bf435626SFabien Thomas 	 */
13058b7f3994SMarcin Wojtas 	if ((tl >= window - 1 && seq >= bl) ||
13068b7f3994SMarcin Wojtas 	    (tl < window - 1 && seq < bl)) {
13078b7f3994SMarcin Wojtas 		*seqhigh = th;
13088b7f3994SMarcin Wojtas 		if (seq <= tl) {
13098b7f3994SMarcin Wojtas 			/* Sequence number inside window - check against replay */
13100361f165SKristof Provost 			if (check_window(replay, seq)) {
13110361f165SKristof Provost 				SECREPLAY_UNLOCK(replay);
1312fcf59617SAndrey V. Elsukov 				return (0);
13138b7f3994SMarcin Wojtas 			}
13140361f165SKristof Provost 		}
13158b7f3994SMarcin Wojtas 
13160361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
13178b7f3994SMarcin Wojtas 		/* Sequence number above top of window or not found in bitmap */
13188b7f3994SMarcin Wojtas 		return (1);
13198b7f3994SMarcin Wojtas 	}
13208b7f3994SMarcin Wojtas 
13218b7f3994SMarcin Wojtas 	/*
13228b7f3994SMarcin Wojtas 	 * If ESN is not enabled and packet with highest sequence number
13238b7f3994SMarcin Wojtas 	 * was received we should report overflow
13248b7f3994SMarcin Wojtas 	 */
13258b7f3994SMarcin Wojtas 	if (tl == 0xffffffff && !(sav->flags & SADB_X_SAFLAGS_ESN)) {
13268b7f3994SMarcin Wojtas 		/* Set overflow flag. */
13278b7f3994SMarcin Wojtas 		replay->overflow++;
13288b7f3994SMarcin Wojtas 
13298b7f3994SMarcin Wojtas 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
13308b7f3994SMarcin Wojtas 			if (sav->sah->saidx.proto == IPPROTO_ESP)
13318b7f3994SMarcin Wojtas 				ESPSTAT_INC(esps_wrap);
13328b7f3994SMarcin Wojtas 			else if (sav->sah->saidx.proto == IPPROTO_AH)
13338b7f3994SMarcin Wojtas 				AHSTAT_INC(ahs_wrap);
13340361f165SKristof Provost 			SECREPLAY_UNLOCK(replay);
13358b7f3994SMarcin Wojtas 			return (0);
13368b7f3994SMarcin Wojtas 		}
13378b7f3994SMarcin Wojtas 
13388b7f3994SMarcin Wojtas 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
13398b7f3994SMarcin Wojtas 		    __func__, replay->overflow,
13408b7f3994SMarcin Wojtas 		    ipsec_sa2str(sav, buf, sizeof(buf))));
13418b7f3994SMarcin Wojtas 	}
13428b7f3994SMarcin Wojtas 
13438b7f3994SMarcin Wojtas 	/*
13448b7f3994SMarcin Wojtas 	 * Seq is within [bl, 0xffffffff] and bl is within
13458b7f3994SMarcin Wojtas 	 * [0xffffffff-window, 0xffffffff].  This means we got a seq
13468b7f3994SMarcin Wojtas 	 * which is within our replay window, but in the previous
13478b7f3994SMarcin Wojtas 	 * subspace.
13488b7f3994SMarcin Wojtas 	 */
13498b7f3994SMarcin Wojtas 	if (tl < window - 1 && seq >= bl) {
13508b7f3994SMarcin Wojtas 		if (th == 0)
13518b7f3994SMarcin Wojtas 			return (0);
13528b7f3994SMarcin Wojtas 		*seqhigh = th - 1;
13538b7f3994SMarcin Wojtas 		seqh = th - 1;
13540361f165SKristof Provost 		if (check_window(replay, seq)) {
13550361f165SKristof Provost 			SECREPLAY_UNLOCK(replay);
13568b7f3994SMarcin Wojtas 			return (0);
13570361f165SKristof Provost 		}
13580361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
13598b7f3994SMarcin Wojtas 		return (1);
13608b7f3994SMarcin Wojtas 	}
13618b7f3994SMarcin Wojtas 
13628b7f3994SMarcin Wojtas 	/*
13638b7f3994SMarcin Wojtas 	 * Seq is within [0, bl) but the whole window is within one subspace.
13648b7f3994SMarcin Wojtas 	 * This means that seq has wrapped and is in next subspace
13658b7f3994SMarcin Wojtas 	 */
13668b7f3994SMarcin Wojtas 	*seqhigh = th + 1;
13678b7f3994SMarcin Wojtas 	seqh = th + 1;
13688b7f3994SMarcin Wojtas 
13698b7f3994SMarcin Wojtas 	/* Don't let high part wrap. */
13708b7f3994SMarcin Wojtas 	if (seqh == 0) {
13718b7f3994SMarcin Wojtas 		/* Set overflow flag. */
13728b7f3994SMarcin Wojtas 		replay->overflow++;
13738b7f3994SMarcin Wojtas 
13748b7f3994SMarcin Wojtas 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
13758b7f3994SMarcin Wojtas 			if (sav->sah->saidx.proto == IPPROTO_ESP)
13768b7f3994SMarcin Wojtas 				ESPSTAT_INC(esps_wrap);
13778b7f3994SMarcin Wojtas 			else if (sav->sah->saidx.proto == IPPROTO_AH)
13788b7f3994SMarcin Wojtas 				AHSTAT_INC(ahs_wrap);
13790361f165SKristof Provost 			SECREPLAY_UNLOCK(replay);
13808b7f3994SMarcin Wojtas 			return (0);
13818b7f3994SMarcin Wojtas 		}
13828b7f3994SMarcin Wojtas 
13838b7f3994SMarcin Wojtas 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
13848b7f3994SMarcin Wojtas 		    __func__, replay->overflow,
13858b7f3994SMarcin Wojtas 		    ipsec_sa2str(sav, buf, sizeof(buf))));
13868b7f3994SMarcin Wojtas 	}
13878b7f3994SMarcin Wojtas 
13880361f165SKristof Provost 	SECREPLAY_UNLOCK(replay);
1389fcf59617SAndrey V. Elsukov 	return (1);
139088768458SSam Leffler }
139188768458SSam Leffler 
139288768458SSam Leffler /*
1393de47c390SBjoern A. Zeeb  * Check replay counter whether to update or not.
139488768458SSam Leffler  * OUT:	0:	OK
139588768458SSam Leffler  *	1:	NG
139688768458SSam Leffler  */
139788768458SSam Leffler int
1398fcf59617SAndrey V. Elsukov ipsec_updatereplay(uint32_t seq, struct secasvar *sav)
139988768458SSam Leffler {
140088768458SSam Leffler 	struct secreplay *replay;
14018b7f3994SMarcin Wojtas 	uint32_t window;
14028b7f3994SMarcin Wojtas 	uint32_t tl, th, bl;
14038b7f3994SMarcin Wojtas 	uint32_t seqh;
140488768458SSam Leffler 
14059ffa9677SSam Leffler 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
14069ffa9677SSam Leffler 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
140788768458SSam Leffler 
140888768458SSam Leffler 	replay = sav->replay;
140988768458SSam Leffler 
14108b7f3994SMarcin Wojtas 	/* No need to check replay if disabled. */
141188768458SSam Leffler 	if (replay->wsize == 0)
14128b7f3994SMarcin Wojtas 		return (0);
141388768458SSam Leffler 
14140361f165SKristof Provost 	SECREPLAY_LOCK(replay);
14150361f165SKristof Provost 
14168b7f3994SMarcin Wojtas 	/* Zero sequence number is not allowed. */
14170361f165SKristof Provost 	if (seq == 0 && replay->last == 0) {
14180361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
1419fcf59617SAndrey V. Elsukov 		return (1);
14200361f165SKristof Provost 	}
142188768458SSam Leffler 
14228b7f3994SMarcin Wojtas 	window = replay->wsize << 3;		/* Size of window */
14238b7f3994SMarcin Wojtas 	tl = (uint32_t)replay->last;		/* Top of window, lower part */
14248b7f3994SMarcin Wojtas 	th = (uint32_t)(replay->last >> 32);	/* Top of window, high part */
14258b7f3994SMarcin Wojtas 	bl = tl - window + 1;			/* Bottom of window, lower part */
142688768458SSam Leffler 
14278b7f3994SMarcin Wojtas 	/*
14288b7f3994SMarcin Wojtas 	 * We keep the high part intact when:
14298b7f3994SMarcin Wojtas 	 * 1) the seq is within [bl, 0xffffffff] and the whole window is
14308b7f3994SMarcin Wojtas 	 *    within one subspace;
14318b7f3994SMarcin Wojtas 	 * 2) the seq is within [0, bl) and window spans two subspaces.
14328b7f3994SMarcin Wojtas 	 */
14338b7f3994SMarcin Wojtas 	if ((tl >= window - 1 && seq >= bl) ||
14348b7f3994SMarcin Wojtas 	    (tl < window - 1 && seq < bl)) {
14358b7f3994SMarcin Wojtas 		seqh = th;
14368b7f3994SMarcin Wojtas 		if (seq <= tl) {
14378b7f3994SMarcin Wojtas 			/* Sequence number inside window - check against replay */
14380361f165SKristof Provost 			if (check_window(replay, seq)) {
14390361f165SKristof Provost 				SECREPLAY_UNLOCK(replay);
1440fcf59617SAndrey V. Elsukov 				return (1);
14410361f165SKristof Provost 			}
14428b7f3994SMarcin Wojtas 			set_window(replay, seq);
14438b7f3994SMarcin Wojtas 		} else {
14448b7f3994SMarcin Wojtas 			advance_window(replay, ((uint64_t)seqh << 32) | seq);
14458b7f3994SMarcin Wojtas 			set_window(replay, seq);
14468b7f3994SMarcin Wojtas 			replay->last = ((uint64_t)seqh << 32) | seq;
1447fcf59617SAndrey V. Elsukov 		}
144888768458SSam Leffler 
14498b7f3994SMarcin Wojtas 		/* Sequence number above top of window or not found in bitmap */
1450d5f39c34SFabien Thomas 		replay->count++;
14510361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
1452fcf59617SAndrey V. Elsukov 		return (0);
145388768458SSam Leffler 	}
145488768458SSam Leffler 
14550361f165SKristof Provost 	if (!(sav->flags & SADB_X_SAFLAGS_ESN)) {
14560361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
14578b7f3994SMarcin Wojtas 		return (1);
14580361f165SKristof Provost 	}
14598b7f3994SMarcin Wojtas 
14608b7f3994SMarcin Wojtas 	/*
14618b7f3994SMarcin Wojtas 	 * Seq is within [bl, 0xffffffff] and bl is within
14628b7f3994SMarcin Wojtas 	 * [0xffffffff-window, 0xffffffff].  This means we got a seq
14638b7f3994SMarcin Wojtas 	 * which is within our replay window, but in the previous
14648b7f3994SMarcin Wojtas 	 * subspace.
14658b7f3994SMarcin Wojtas 	 */
14668b7f3994SMarcin Wojtas 	if (tl < window - 1 && seq >= bl) {
14670361f165SKristof Provost 		if (th == 0) {
14680361f165SKristof Provost 			SECREPLAY_UNLOCK(replay);
14698b7f3994SMarcin Wojtas 			return (1);
14700361f165SKristof Provost 		}
14710361f165SKristof Provost 		if (check_window(replay, seq)) {
14720361f165SKristof Provost 			SECREPLAY_UNLOCK(replay);
14738b7f3994SMarcin Wojtas 			return (1);
14740361f165SKristof Provost 		}
14758b7f3994SMarcin Wojtas 
14768b7f3994SMarcin Wojtas 		set_window(replay, seq);
14778b7f3994SMarcin Wojtas 		replay->count++;
14780361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
14798b7f3994SMarcin Wojtas 		return (0);
14808b7f3994SMarcin Wojtas 	}
14818b7f3994SMarcin Wojtas 
14828b7f3994SMarcin Wojtas 	/*
14838b7f3994SMarcin Wojtas 	 * Seq is within [0, bl) but the whole window is within one subspace.
14848b7f3994SMarcin Wojtas 	 * This means that seq has wrapped and is in next subspace
14858b7f3994SMarcin Wojtas 	 */
14868b7f3994SMarcin Wojtas 	seqh = th + 1;
14878b7f3994SMarcin Wojtas 
14888b7f3994SMarcin Wojtas 	/* Don't let high part wrap. */
14890361f165SKristof Provost 	if (seqh == 0) {
14900361f165SKristof Provost 		SECREPLAY_UNLOCK(replay);
14918b7f3994SMarcin Wojtas 		return (1);
14920361f165SKristof Provost 	}
14938b7f3994SMarcin Wojtas 
14948b7f3994SMarcin Wojtas 	advance_window(replay, ((uint64_t)seqh << 32) | seq);
14958b7f3994SMarcin Wojtas 	set_window(replay, seq);
14968b7f3994SMarcin Wojtas 	replay->last = ((uint64_t)seqh << 32) | seq;
14978b7f3994SMarcin Wojtas 	replay->count++;
14980361f165SKristof Provost 
14990361f165SKristof Provost 	SECREPLAY_UNLOCK(replay);
15008b7f3994SMarcin Wojtas 	return (0);
15018b7f3994SMarcin Wojtas }
1502fcf59617SAndrey V. Elsukov int
15032e08e39fSConrad Meyer ipsec_updateid(struct secasvar *sav, crypto_session_t *new,
15042e08e39fSConrad Meyer     crypto_session_t *old)
1505fcf59617SAndrey V. Elsukov {
15062e08e39fSConrad Meyer 	crypto_session_t tmp;
150788768458SSam Leffler 
1508fcf59617SAndrey V. Elsukov 	/*
1509fcf59617SAndrey V. Elsukov 	 * tdb_cryptoid is initialized by xform_init().
1510fcf59617SAndrey V. Elsukov 	 * Then it can be changed only when some crypto error occurred or
1511fcf59617SAndrey V. Elsukov 	 * when SA is deleted. We stored used cryptoid in the xform_data
1512fcf59617SAndrey V. Elsukov 	 * structure. In case when crypto error occurred and crypto
1513fcf59617SAndrey V. Elsukov 	 * subsystem has reinited the session, it returns new cryptoid
1514fcf59617SAndrey V. Elsukov 	 * and EAGAIN error code.
1515fcf59617SAndrey V. Elsukov 	 *
1516fcf59617SAndrey V. Elsukov 	 * This function will be called when we got EAGAIN from crypto
1517fcf59617SAndrey V. Elsukov 	 * subsystem.
1518fcf59617SAndrey V. Elsukov 	 * *new is cryptoid that was returned by crypto subsystem in
1519fcf59617SAndrey V. Elsukov 	 * the crp_sid.
1520fcf59617SAndrey V. Elsukov 	 * *old is the original cryptoid that we stored in xform_data.
1521fcf59617SAndrey V. Elsukov 	 *
1522fcf59617SAndrey V. Elsukov 	 * For first failed request *old == sav->tdb_cryptoid, then
1523fcf59617SAndrey V. Elsukov 	 * we update sav->tdb_cryptoid and redo crypto_dispatch().
1524fcf59617SAndrey V. Elsukov 	 * For next failed request *old != sav->tdb_cryptoid, then
1525fcf59617SAndrey V. Elsukov 	 * we store cryptoid from first request into the *new variable
1526fcf59617SAndrey V. Elsukov 	 * and crp_sid from this second session will be returned via
1527fcf59617SAndrey V. Elsukov 	 * *old pointer, so caller can release second session.
1528fcf59617SAndrey V. Elsukov 	 *
1529fcf59617SAndrey V. Elsukov 	 * XXXAE: check this more carefully.
1530fcf59617SAndrey V. Elsukov 	 */
1531fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_STAMP,
15321b0909d5SConrad Meyer 	    printf("%s: SA(%p) moves cryptoid %p -> %p\n",
15331b0909d5SConrad Meyer 		__func__, sav, *old, *new));
1534fcf59617SAndrey V. Elsukov 	KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
15350361f165SKristof Provost 	SECASVAR_WLOCK(sav);
1536fcf59617SAndrey V. Elsukov 	if (sav->tdb_cryptoid != *old) {
1537fcf59617SAndrey V. Elsukov 		/* cryptoid was already updated */
1538fcf59617SAndrey V. Elsukov 		tmp = *new;
1539fcf59617SAndrey V. Elsukov 		*new = sav->tdb_cryptoid;
1540fcf59617SAndrey V. Elsukov 		*old = tmp;
15410361f165SKristof Provost 		SECASVAR_WUNLOCK(sav);
1542fcf59617SAndrey V. Elsukov 		return (1);
1543fcf59617SAndrey V. Elsukov 	}
1544fcf59617SAndrey V. Elsukov 	sav->tdb_cryptoid = *new;
15450361f165SKristof Provost 	SECASVAR_WUNLOCK(sav);
1546fcf59617SAndrey V. Elsukov 	return (0);
154788768458SSam Leffler }
154888768458SSam Leffler 
1549fcf59617SAndrey V. Elsukov int
1550fcf59617SAndrey V. Elsukov ipsec_initialized(void)
155188768458SSam Leffler {
1552de47c390SBjoern A. Zeeb 
1553fcf59617SAndrey V. Elsukov 	return (V_def_policy != NULL);
155488768458SSam Leffler }
155588768458SSam Leffler 
15568381996eSSam Leffler static void
155793201211SAndrey V. Elsukov def_policy_init(const void *unused __unused)
15581ed81b73SMarko Zec {
15591ed81b73SMarko Zec 
1560fcf59617SAndrey V. Elsukov 	V_def_policy = key_newsp();
1561fcf59617SAndrey V. Elsukov 	if (V_def_policy != NULL) {
1562fcf59617SAndrey V. Elsukov 		V_def_policy->policy = IPSEC_POLICY_NONE;
1563fcf59617SAndrey V. Elsukov 		/* Force INPCB SP cache invalidation */
1564fcf59617SAndrey V. Elsukov 		key_bumpspgen();
1565fcf59617SAndrey V. Elsukov 	} else
1566fcf59617SAndrey V. Elsukov 		printf("%s: failed to initialize default policy\n", __func__);
15678381996eSSam Leffler }
1568fcf59617SAndrey V. Elsukov 
1569fcf59617SAndrey V. Elsukov static void
1570fcf59617SAndrey V. Elsukov def_policy_uninit(const void *unused __unused)
1571fcf59617SAndrey V. Elsukov {
1572fcf59617SAndrey V. Elsukov 
1573fcf59617SAndrey V. Elsukov 	if (V_def_policy != NULL) {
1574fcf59617SAndrey V. Elsukov 		key_freesp(&V_def_policy);
1575fcf59617SAndrey V. Elsukov 		key_bumpspgen();
1576fcf59617SAndrey V. Elsukov 	}
1577fcf59617SAndrey V. Elsukov }
1578fcf59617SAndrey V. Elsukov 
157989856f7eSBjoern A. Zeeb VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
158093201211SAndrey V. Elsukov     def_policy_init, NULL);
1581fcf59617SAndrey V. Elsukov VNET_SYSUNINIT(def_policy_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1582fcf59617SAndrey V. Elsukov     def_policy_uninit, NULL);
1583