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