ipsec.c revision 1.113 1 /* $NetBSD: ipsec.c,v 1.113 2017/08/02 01:28:03 ozaki-r Exp $ */
2 /* $FreeBSD: /usr/local/www/cvsroot/FreeBSD/src/sys/netipsec/ipsec.c,v 1.2.2.2 2003/07/01 01:38:13 sam Exp $ */
3 /* $KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $ */
4
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 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: ipsec.c,v 1.113 2017/08/02 01:28:03 ozaki-r Exp $");
36
37 /*
38 * IPsec controller part.
39 */
40
41 #if defined(_KERNEL_OPT)
42 #include "opt_inet.h"
43 #include "opt_ipsec.h"
44 #endif
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/mbuf.h>
49 #include <sys/domain.h>
50 #include <sys/protosw.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/errno.h>
54 #include <sys/time.h>
55 #include <sys/kernel.h>
56 #include <sys/syslog.h>
57 #include <sys/sysctl.h>
58 #include <sys/proc.h>
59 #include <sys/kauth.h>
60 #include <sys/cpu.h>
61 #include <sys/kmem.h>
62 #include <sys/pserialize.h>
63
64 #include <net/if.h>
65 #include <net/route.h>
66
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/in_var.h>
72 #include <netinet/udp.h>
73 #include <netinet/udp_var.h>
74 #include <netinet/tcp.h>
75 #include <netinet/udp.h>
76 #include <netinet/ip_icmp.h>
77 #include <netinet/ip_private.h>
78
79 #include <netinet/ip6.h>
80 #ifdef INET6
81 #include <netinet6/ip6_var.h>
82 #endif
83 #include <netinet/in_pcb.h>
84 #ifdef INET6
85 #include <netinet6/in6_pcb.h>
86 #include <netinet/icmp6.h>
87 #endif
88
89 #include <netipsec/ipsec.h>
90 #include <netipsec/ipsec_var.h>
91 #include <netipsec/ipsec_private.h>
92 #ifdef INET6
93 #include <netipsec/ipsec6.h>
94 #endif
95 #include <netipsec/ah_var.h>
96 #include <netipsec/esp_var.h>
97 #include <netipsec/ipcomp.h> /*XXX*/
98 #include <netipsec/ipcomp_var.h>
99
100 #include <netipsec/key.h>
101 #include <netipsec/keydb.h>
102 #include <netipsec/key_debug.h>
103
104 #include <netipsec/xform.h>
105
106 #include <net/net_osdep.h>
107
108 int ipsec_used = 0;
109 int ipsec_enabled = 1;
110
111 #ifdef IPSEC_DEBUG
112 int ipsec_debug = 1;
113
114 /*
115 * When set to 1, IPsec will send packets with the same sequence number.
116 * This allows to verify if the other side has proper replay attacks detection.
117 */
118 int ipsec_replay = 0;
119
120 /*
121 * When set 1, IPsec will send packets with corrupted HMAC.
122 * This allows to verify if the other side properly detects modified packets.
123 */
124 int ipsec_integrity = 0;
125 #else
126 int ipsec_debug = 0;
127 #endif
128
129 percpu_t *ipsecstat_percpu;
130 int ip4_ah_offsetmask = 0; /* maybe IP_DF? */
131 int ip4_ipsec_dfbit = 2; /* DF bit on encap. 0: clear 1: set 2: copy */
132 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
133 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
134 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
135 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
136 struct secpolicy ip4_def_policy;
137 int ip4_ipsec_ecn = 0; /* ECN ignore(-1)/forbidden(0)/allowed(1) */
138 int ip4_esp_randpad = -1;
139
140 u_int ipsec_spdgen = 1; /* SPD generation # */
141
142 static struct secpolicy *ipsec_checkpcbcache (struct mbuf *,
143 struct inpcbpolicy *, int);
144 static int ipsec_fillpcbcache (struct inpcbpolicy *, struct mbuf *,
145 struct secpolicy *, int);
146 static int ipsec_invalpcbcache (struct inpcbpolicy *, int);
147
148 /*
149 * Crypto support requirements:
150 *
151 * 1 require hardware support
152 * -1 require software support
153 * 0 take anything
154 */
155 int crypto_support = 0;
156
157 static struct secpolicy *ipsec_getpolicybysock(struct mbuf *, u_int,
158 struct inpcb_hdr *, int *);
159
160 #ifdef __FreeBSD__
161 /* net.inet.ipsec */
162 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
163 esp_randpad, CTLFLAG_RW, &ip4_esp_randpad, 0, "");
164 SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
165 crypto_support, CTLFLAG_RW, &crypto_support,0, "");
166 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay, CTLFLAG_RW, &ipsec_replay, 0,
167 "Emulate replay attack");
168 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity, CTLFLAG_RW,
169 &ipsec_integrity, 0, "Emulate man-in-the-middle attack");
170 #endif /* __FreeBSD__ */
171
172 #ifdef INET6
173 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
174 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
175 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
176 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
177 struct secpolicy ip6_def_policy;
178 int ip6_ipsec_ecn = 0; /* ECN ignore(-1)/forbidden(0)/allowed(1) */
179 int ip6_esp_randpad = -1;
180
181
182 #ifdef __FreeBSD__
183 /* net.inet6.ipsec6 */
184 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
185 esp_randpad, CTLFLAG_RW, &ip6_esp_randpad, 0, "");
186 #endif /* __FreeBSD__ */
187 #endif /* INET6 */
188
189 static int ipsec4_setspidx_inpcb (struct mbuf *, struct inpcb *);
190 #ifdef INET6
191 static int ipsec6_setspidx_in6pcb (struct mbuf *, struct in6pcb *);
192 #endif
193 static int ipsec_setspidx (struct mbuf *, struct secpolicyindex *, int);
194 static void ipsec4_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
195 static int ipsec4_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
196 #ifdef INET6
197 static void ipsec6_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
198 static int ipsec6_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
199 #endif
200 static void ipsec_delpcbpolicy (struct inpcbpolicy *);
201 static struct secpolicy *ipsec_deepcopy_policy (const struct secpolicy *);
202 static int ipsec_set_policy (struct secpolicy **, int, const void *, size_t,
203 kauth_cred_t);
204 static int ipsec_get_policy (struct secpolicy *, struct mbuf **);
205 static void ipsec_destroy_policy(struct secpolicy *);
206 static void vshiftl (unsigned char *, int, int);
207 static size_t ipsec_hdrsiz (const struct secpolicy *);
208
209 /*
210 * Try to validate and use cached policy on a PCB.
211 */
212 static struct secpolicy *
213 ipsec_checkpcbcache(struct mbuf *m, struct inpcbpolicy *pcbsp, int dir)
214 {
215 struct secpolicyindex spidx;
216 struct secpolicy *sp = NULL;
217 int s;
218
219 KASSERT(IPSEC_DIR_IS_VALID(dir));
220 KASSERT(pcbsp != NULL);
221 KASSERT(dir < __arraycount(pcbsp->sp_cache));
222 KASSERT(inph_locked(pcbsp->sp_inph));
223
224 /*
225 * Checking the generation and sp->state and taking a reference to an SP
226 * must be in a critical section of pserialize. See key_unlink_sp.
227 */
228 s = pserialize_read_enter();
229 /* SPD table change invalidate all the caches. */
230 if (ipsec_spdgen != pcbsp->sp_cache[dir].cachegen) {
231 ipsec_invalpcbcache(pcbsp, dir);
232 goto out;
233 }
234 sp = pcbsp->sp_cache[dir].cachesp;
235 if (sp == NULL)
236 goto out;
237 if (sp->state != IPSEC_SPSTATE_ALIVE) {
238 sp = NULL;
239 ipsec_invalpcbcache(pcbsp, dir);
240 goto out;
241 }
242 if ((pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) == 0) {
243 /* NB: assume ipsec_setspidx never sleep */
244 if (ipsec_setspidx(m, &spidx, 1) != 0) {
245 sp = NULL;
246 goto out;
247 }
248
249 /*
250 * We have to make an exact match here since the cached rule
251 * might have lower priority than a rule that would otherwise
252 * have matched the packet.
253 */
254 if (memcmp(&pcbsp->sp_cache[dir].cacheidx, &spidx,
255 sizeof(spidx))) {
256 sp = NULL;
257 goto out;
258 }
259 } else {
260 /*
261 * The pcb is connected, and the L4 code is sure that:
262 * - outgoing side uses inp_[lf]addr
263 * - incoming side looks up policy after inpcb lookup
264 * and address pair is know to be stable. We do not need
265 * to generate spidx again, nor check the address match again.
266 *
267 * For IPv4/v6 SOCK_STREAM sockets, this assumptions holds
268 * and there are calls to ipsec_pcbconn() from in_pcbconnect().
269 */
270 }
271
272 sp->lastused = time_second;
273 KEY_SP_REF(sp);
274 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
275 "DP cause refcnt++:%d SP:%p\n",
276 key_sp_refcnt(sp), pcbsp->sp_cache[dir].cachesp);
277 out:
278 pserialize_read_exit(s);
279 return sp;
280 }
281
282 static int
283 ipsec_fillpcbcache(struct inpcbpolicy *pcbsp, struct mbuf *m,
284 struct secpolicy *sp, int dir)
285 {
286
287 KASSERT(IPSEC_DIR_IS_INOROUT(dir));
288 KASSERT(dir < __arraycount(pcbsp->sp_cache));
289 KASSERT(inph_locked(pcbsp->sp_inph));
290
291 pcbsp->sp_cache[dir].cachesp = NULL;
292 pcbsp->sp_cache[dir].cachehint = IPSEC_PCBHINT_UNKNOWN;
293 if (ipsec_setspidx(m, &pcbsp->sp_cache[dir].cacheidx, 1) != 0) {
294 return EINVAL;
295 }
296 pcbsp->sp_cache[dir].cachesp = sp;
297 if (pcbsp->sp_cache[dir].cachesp) {
298 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
299 "DP cause refcnt++:%d SP:%p\n",
300 key_sp_refcnt(pcbsp->sp_cache[dir].cachesp),
301 pcbsp->sp_cache[dir].cachesp);
302
303 /*
304 * If the PCB is connected, we can remember a hint to
305 * possibly short-circuit IPsec processing in other places.
306 */
307 if (pcbsp->sp_cacheflags & IPSEC_PCBSP_CONNECTED) {
308 switch (pcbsp->sp_cache[dir].cachesp->policy) {
309 case IPSEC_POLICY_NONE:
310 case IPSEC_POLICY_BYPASS:
311 pcbsp->sp_cache[dir].cachehint =
312 IPSEC_PCBHINT_NO;
313 break;
314 default:
315 pcbsp->sp_cache[dir].cachehint =
316 IPSEC_PCBHINT_YES;
317 }
318 }
319 }
320 pcbsp->sp_cache[dir].cachegen = ipsec_spdgen;
321
322 return 0;
323 }
324
325 static int
326 ipsec_invalpcbcache(struct inpcbpolicy *pcbsp, int dir)
327 {
328 int i;
329
330 KASSERT(inph_locked(pcbsp->sp_inph));
331
332 for (i = IPSEC_DIR_INBOUND; i <= IPSEC_DIR_OUTBOUND; i++) {
333 if (dir != IPSEC_DIR_ANY && i != dir)
334 continue;
335 pcbsp->sp_cache[i].cachesp = NULL;
336 pcbsp->sp_cache[i].cachehint = IPSEC_PCBHINT_UNKNOWN;
337 pcbsp->sp_cache[i].cachegen = 0;
338 memset(&pcbsp->sp_cache[i].cacheidx, 0,
339 sizeof(pcbsp->sp_cache[i].cacheidx));
340 }
341 return 0;
342 }
343
344 void
345 ipsec_pcbconn(struct inpcbpolicy *pcbsp)
346 {
347
348 KASSERT(inph_locked(pcbsp->sp_inph));
349
350 pcbsp->sp_cacheflags |= IPSEC_PCBSP_CONNECTED;
351 ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
352 }
353
354 void
355 ipsec_pcbdisconn(struct inpcbpolicy *pcbsp)
356 {
357
358 KASSERT(inph_locked(pcbsp->sp_inph));
359
360 pcbsp->sp_cacheflags &= ~IPSEC_PCBSP_CONNECTED;
361 ipsec_invalpcbcache(pcbsp, IPSEC_DIR_ANY);
362 }
363
364 void
365 ipsec_invalpcbcacheall(void)
366 {
367
368 if (ipsec_spdgen == UINT_MAX)
369 ipsec_spdgen = 1;
370 else
371 ipsec_spdgen++;
372 }
373
374 /*
375 * Return a held reference to the default SP.
376 */
377 static struct secpolicy *
378 key_get_default_sp(int af, const char *where, int tag)
379 {
380 struct secpolicy *sp;
381
382 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
383
384 switch(af) {
385 case AF_INET:
386 sp = &ip4_def_policy;
387 break;
388 #ifdef INET6
389 case AF_INET6:
390 sp = &ip6_def_policy;
391 break;
392 #endif
393 default:
394 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
395 "unexpected protocol family %u\n", af);
396 return NULL;
397 }
398
399 if (sp->policy != IPSEC_POLICY_DISCARD &&
400 sp->policy != IPSEC_POLICY_NONE) {
401 IPSECLOG(LOG_INFO, "fixed system default policy: %d->%d\n",
402 sp->policy, IPSEC_POLICY_NONE);
403 sp->policy = IPSEC_POLICY_NONE;
404 }
405 KEY_SP_REF(sp);
406
407 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP returns SP:%p (%u)\n",
408 sp, key_sp_refcnt(sp));
409 return sp;
410 }
411 #define KEY_GET_DEFAULT_SP(af) \
412 key_get_default_sp((af), __func__, __LINE__)
413
414 /*
415 * For OUTBOUND packet having a socket. Searching SPD for packet,
416 * and return a pointer to SP.
417 * OUT: NULL: no apropreate SP found, the following value is set to error.
418 * 0 : bypass
419 * EACCES : discard packet.
420 * ENOENT : ipsec_acquire() in progress, maybe.
421 * others : error occurred.
422 * others: a pointer to SP
423 *
424 * NOTE: IPv6 mapped address concern is implemented here.
425 */
426 static struct secpolicy *
427 ipsec_getpolicybysock(struct mbuf *m, u_int dir, struct inpcb_hdr *inph,
428 int *error)
429 {
430 struct inpcbpolicy *pcbsp = NULL;
431 struct secpolicy *currsp = NULL; /* policy on socket */
432 struct secpolicy *sp;
433 int af;
434
435 KASSERT(m != NULL);
436 KASSERT(inph != NULL);
437 KASSERT(error != NULL);
438 KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
439
440 KASSERT(inph->inph_socket != NULL);
441 KASSERT(inph_locked(inph));
442
443 /* XXX FIXME inpcb/in6pcb vs socket*/
444 af = inph->inph_af;
445 KASSERTMSG(af == AF_INET || af == AF_INET6,
446 "unexpected protocol family %u", af);
447
448 KASSERT(inph->inph_sp != NULL);
449 /* If we have a cached entry, and if it is still valid, use it. */
450 IPSEC_STATINC(IPSEC_STAT_SPDCACHELOOKUP);
451 currsp = ipsec_checkpcbcache(m, inph->inph_sp, dir);
452 if (currsp) {
453 *error = 0;
454 return currsp;
455 }
456 IPSEC_STATINC(IPSEC_STAT_SPDCACHEMISS);
457
458 switch (af) {
459 case AF_INET: {
460 struct inpcb *in4p = (struct inpcb *)inph;
461 /* set spidx in pcb */
462 *error = ipsec4_setspidx_inpcb(m, in4p);
463 pcbsp = in4p->inp_sp;
464 break;
465 }
466
467 #if defined(INET6)
468 case AF_INET6: {
469 struct in6pcb *in6p = (struct in6pcb *)inph;
470 /* set spidx in pcb */
471 *error = ipsec6_setspidx_in6pcb(m, in6p);
472 pcbsp = in6p->in6p_sp;
473 break;
474 }
475 #endif
476 default:
477 *error = EPFNOSUPPORT;
478 break;
479 }
480 if (*error)
481 return NULL;
482
483 KASSERT(pcbsp != NULL);
484 switch (dir) {
485 case IPSEC_DIR_INBOUND:
486 currsp = pcbsp->sp_in;
487 break;
488 case IPSEC_DIR_OUTBOUND:
489 currsp = pcbsp->sp_out;
490 break;
491 }
492 KASSERT(currsp != NULL);
493
494 if (pcbsp->priv) { /* when privilieged socket */
495 switch (currsp->policy) {
496 case IPSEC_POLICY_BYPASS:
497 case IPSEC_POLICY_IPSEC:
498 KEY_SP_REF(currsp);
499 sp = currsp;
500 break;
501
502 case IPSEC_POLICY_ENTRUST:
503 /* look for a policy in SPD */
504 sp = KEY_LOOKUP_SP_BYSPIDX(&currsp->spidx, dir);
505 if (sp == NULL) /* no SP found */
506 sp = KEY_GET_DEFAULT_SP(af);
507 break;
508
509 default:
510 IPSECLOG(LOG_ERR, "Invalid policy for PCB %d\n",
511 currsp->policy);
512 *error = EINVAL;
513 return NULL;
514 }
515 } else { /* unpriv, SPD has policy */
516 sp = KEY_LOOKUP_SP_BYSPIDX(&currsp->spidx, dir);
517 if (sp == NULL) { /* no SP found */
518 switch (currsp->policy) {
519 case IPSEC_POLICY_BYPASS:
520 IPSECLOG(LOG_ERR, "Illegal policy for "
521 "non-priviliged defined %d\n",
522 currsp->policy);
523 *error = EINVAL;
524 return NULL;
525
526 case IPSEC_POLICY_ENTRUST:
527 sp = KEY_GET_DEFAULT_SP(af);
528 break;
529
530 case IPSEC_POLICY_IPSEC:
531 KEY_SP_REF(currsp);
532 sp = currsp;
533 break;
534
535 default:
536 IPSECLOG(LOG_ERR, "Invalid policy for "
537 "PCB %d\n", currsp->policy);
538 *error = EINVAL;
539 return NULL;
540 }
541 }
542 }
543 KASSERTMSG(sp != NULL, "null SP (priv %u policy %u", pcbsp->priv,
544 currsp->policy);
545 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
546 "DP (priv %u policy %u) allocates SP:%p (refcnt %u)\n",
547 pcbsp->priv, currsp->policy, sp, key_sp_refcnt(sp));
548 ipsec_fillpcbcache(pcbsp, m, sp, dir);
549 return sp;
550 }
551
552 /*
553 * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
554 * and return a pointer to SP.
555 * OUT: positive: a pointer to the entry for security policy leaf matched.
556 * NULL: no apropreate SP found, the following value is set to error.
557 * 0 : bypass
558 * EACCES : discard packet.
559 * ENOENT : ipsec_acquire() in progress, maybe.
560 * others : error occurred.
561 */
562 struct secpolicy *
563 ipsec_getpolicybyaddr(struct mbuf *m, u_int dir, int flag, int *error)
564 {
565 struct secpolicyindex spidx;
566 struct secpolicy *sp;
567
568 KASSERT(m != NULL);
569 KASSERT(error != NULL);
570 KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
571
572 sp = NULL;
573
574 /* Make an index to look for a policy. */
575 *error = ipsec_setspidx(m, &spidx, (flag & IP_FORWARDING) ? 0 : 1);
576 if (*error != 0) {
577 IPSECLOG(LOG_DEBUG, "setpidx failed, dir %u flag %u\n", dir, flag);
578 memset(&spidx, 0, sizeof (spidx));
579 return NULL;
580 }
581
582 spidx.dir = dir;
583
584 if (key_havesp(dir)) {
585 sp = KEY_LOOKUP_SP_BYSPIDX(&spidx, dir);
586 }
587
588 if (sp == NULL) /* no SP found, use system default */
589 sp = KEY_GET_DEFAULT_SP(spidx.dst.sa.sa_family);
590 KASSERT(sp != NULL);
591 return sp;
592 }
593
594 struct secpolicy *
595 ipsec4_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
596 struct inpcb *inp)
597 {
598 struct secpolicy *sp;
599
600 *error = 0;
601
602 if (inp == NULL) {
603 sp = ipsec_getpolicybyaddr(m, dir, flag, error);
604 } else {
605 KASSERT(inp->inp_socket != NULL);
606 sp = ipsec_getpolicybysock(m, dir, (struct inpcb_hdr *)inp, error);
607 }
608 if (sp == NULL) {
609 KASSERTMSG(*error != 0, "getpolicy failed w/o error");
610 IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
611 return NULL;
612 }
613 KASSERTMSG(*error == 0, "sp w/ error set to %u", *error);
614 switch (sp->policy) {
615 case IPSEC_POLICY_ENTRUST:
616 default:
617 printf("%s: invalid policy %u\n", __func__, sp->policy);
618 /* fall thru... */
619 case IPSEC_POLICY_DISCARD:
620 IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
621 *error = -EINVAL; /* packet is discarded by caller */
622 break;
623 case IPSEC_POLICY_BYPASS:
624 case IPSEC_POLICY_NONE:
625 KEY_SP_UNREF(&sp);
626 sp = NULL; /* NB: force NULL result */
627 break;
628 case IPSEC_POLICY_IPSEC:
629 KASSERT(sp->req != NULL);
630 break;
631 }
632 if (*error != 0) {
633 KEY_SP_UNREF(&sp);
634 sp = NULL;
635 IPSECLOG(LOG_DEBUG, "done, error %d\n", *error);
636 }
637 return sp;
638 }
639
640 int
641 ipsec4_output(struct mbuf *m, struct inpcb *inp, int flags,
642 u_long *mtu, bool *natt_frag, bool *done)
643 {
644 struct secpolicy *sp = NULL;
645 int error, s;
646
647 /*
648 * Check the security policy (SP) for the packet and, if required,
649 * do IPsec-related processing. There are two cases here; the first
650 * time a packet is sent through it will be untagged and handled by
651 * ipsec4_checkpolicy(). If the packet is resubmitted to ip_output
652 * (e.g. after AH, ESP, etc. processing), there will be a tag to
653 * bypass the lookup and related policy checking.
654 */
655 if (ipsec_outdone(m)) {
656 return 0;
657 }
658 s = splsoftnet();
659 if (inp && ipsec_pcb_skip_ipsec(inp->inp_sp, IPSEC_DIR_OUTBOUND)) {
660 splx(s);
661 return 0;
662 }
663 sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, inp);
664
665 /*
666 * There are four return cases:
667 * sp != NULL apply IPsec policy
668 * sp == NULL, error == 0 no IPsec handling needed
669 * sp == NULL, error == -EINVAL discard packet w/o error
670 * sp == NULL, error != 0 discard packet, report error
671 */
672 if (sp == NULL) {
673 splx(s);
674 if (error) {
675 /*
676 * Hack: -EINVAL is used to signal that a packet
677 * should be silently discarded. This is typically
678 * because we asked key management for an SA and
679 * it was delayed (e.g. kicked up to IKE).
680 */
681 if (error == -EINVAL)
682 error = 0;
683 m_freem(m);
684 *done = true;
685 return error;
686 }
687 /* No IPsec processing for this packet. */
688 return 0;
689 }
690
691 /*
692 * Do delayed checksums now because we send before
693 * this is done in the normal processing path.
694 */
695 if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
696 in_delayed_cksum(m);
697 m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
698 }
699
700 {
701 u_long _mtu = 0;
702
703 /* Note: callee frees mbuf */
704 error = ipsec4_process_packet(m, sp->req, &_mtu);
705
706 if (error == 0 && _mtu != 0) {
707 /*
708 * NAT-T ESP fragmentation: do not do IPSec processing
709 * now, we will do it on each fragmented packet.
710 */
711 *mtu = _mtu;
712 *natt_frag = true;
713 KEY_SP_UNREF(&sp);
714 splx(s);
715 return 0;
716 }
717 }
718 /*
719 * Preserve KAME behaviour: ENOENT can be returned
720 * when an SA acquire is in progress. Don't propagate
721 * this to user-level; it confuses applications.
722 *
723 * XXX this will go away when the SADB is redone.
724 */
725 if (error == ENOENT)
726 error = 0;
727 KEY_SP_UNREF(&sp);
728 splx(s);
729 *done = true;
730 return error;
731 }
732
733 int
734 ipsec4_input(struct mbuf *m, int flags)
735 {
736 struct secpolicy *sp;
737 int error, s;
738
739 s = splsoftnet();
740 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
741 if (sp == NULL) {
742 splx(s);
743 return EINVAL;
744 }
745
746 /*
747 * Check security policy against packet attributes.
748 */
749 error = ipsec_in_reject(sp, m);
750 KEY_SP_UNREF(&sp);
751 splx(s);
752 if (error) {
753 return error;
754 }
755
756 if (flags == 0) {
757 /* We are done. */
758 return 0;
759 }
760
761 /*
762 * Peek at the outbound SP for this packet to determine if
763 * it is a Fast Forward candidate.
764 */
765 s = splsoftnet();
766 sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error, NULL);
767 if (sp != NULL) {
768 m->m_flags &= ~M_CANFASTFWD;
769 KEY_SP_UNREF(&sp);
770 }
771 splx(s);
772 return 0;
773 }
774
775 int
776 ipsec4_forward(struct mbuf *m, int *destmtu)
777 {
778 /*
779 * If the packet is routed over IPsec tunnel, tell the
780 * originator the tunnel MTU.
781 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
782 * XXX quickhack!!!
783 */
784 struct secpolicy *sp;
785 size_t ipsechdr;
786 int error;
787
788 sp = ipsec4_getpolicybyaddr(m,
789 IPSEC_DIR_OUTBOUND, IP_FORWARDING, &error);
790 if (sp == NULL) {
791 return EINVAL;
792 }
793
794 /* Count IPsec header size. */
795 ipsechdr = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, NULL);
796
797 /*
798 * Find the correct route for outer IPv4 header, compute tunnel MTU.
799 */
800 if (sp->req) {
801 struct route *ro;
802 struct rtentry *rt;
803 struct secasvar *sav = NULL;
804
805 error = key_checkrequest(sp->req, &sav);
806 if (error != 0)
807 return error;
808 ro = &sav->sah->sa_route;
809 rt = rtcache_validate(ro);
810 if (rt && rt->rt_ifp) {
811 *destmtu = rt->rt_rmx.rmx_mtu ?
812 rt->rt_rmx.rmx_mtu : rt->rt_ifp->if_mtu;
813 *destmtu -= ipsechdr;
814 }
815 rtcache_unref(rt, ro);
816 KEY_FREESAV(&sav);
817 }
818 KEY_SP_UNREF(&sp);
819 return 0;
820 }
821
822 #ifdef INET6
823 struct secpolicy *
824 ipsec6_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
825 struct in6pcb *in6p)
826 {
827 struct secpolicy *sp;
828
829 *error = 0;
830
831 if (in6p == NULL) {
832 sp = ipsec_getpolicybyaddr(m, dir, flag, error);
833 } else {
834 KASSERT(in6p->in6p_socket != NULL);
835 sp = ipsec_getpolicybysock(m, dir, (struct inpcb_hdr *)in6p, error);
836 }
837 if (sp == NULL) {
838 KASSERTMSG(*error != 0, "getpolicy failed w/o error");
839 IPSEC_STATINC(IPSEC_STAT_OUT_INVAL);
840 return NULL;
841 }
842 KASSERTMSG(*error == 0, "sp w/ error set to %u", *error);
843 switch (sp->policy) {
844 case IPSEC_POLICY_ENTRUST:
845 default:
846 printf("%s: invalid policy %u\n", __func__, sp->policy);
847 /* fall thru... */
848 case IPSEC_POLICY_DISCARD:
849 IPSEC_STATINC(IPSEC_STAT_OUT_POLVIO);
850 *error = -EINVAL; /* packet is discarded by caller */
851 break;
852 case IPSEC_POLICY_BYPASS:
853 case IPSEC_POLICY_NONE:
854 KEY_SP_UNREF(&sp);
855 sp = NULL; /* NB: force NULL result */
856 break;
857 case IPSEC_POLICY_IPSEC:
858 KASSERT(sp->req != NULL);
859 break;
860 }
861 if (*error != 0) {
862 KEY_SP_UNREF(&sp);
863 sp = NULL;
864 IPSECLOG(LOG_DEBUG, "done, error %d\n", *error);
865 }
866 return sp;
867 }
868 #endif /* INET6 */
869
870 static int
871 ipsec4_setspidx_inpcb(struct mbuf *m, struct inpcb *pcb)
872 {
873 int error;
874
875 KASSERT(pcb != NULL);
876 KASSERT(pcb->inp_sp != NULL);
877 KASSERT(pcb->inp_sp->sp_out != NULL);
878 KASSERT(pcb->inp_sp->sp_in != NULL);
879
880 error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
881 if (error == 0) {
882 pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
883 pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
884 pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
885 } else {
886 memset(&pcb->inp_sp->sp_in->spidx, 0,
887 sizeof(pcb->inp_sp->sp_in->spidx));
888 memset(&pcb->inp_sp->sp_out->spidx, 0,
889 sizeof(pcb->inp_sp->sp_in->spidx));
890 }
891 return error;
892 }
893
894 #ifdef INET6
895 static int
896 ipsec6_setspidx_in6pcb(struct mbuf *m, struct in6pcb *pcb)
897 {
898 struct secpolicyindex *spidx;
899 int error;
900
901 KASSERT(pcb != NULL);
902 KASSERT(pcb->in6p_sp != NULL);
903 KASSERT(pcb->in6p_sp->sp_out != NULL);
904 KASSERT(pcb->in6p_sp->sp_in != NULL);
905
906 memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
907 memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
908
909 spidx = &pcb->in6p_sp->sp_in->spidx;
910 error = ipsec_setspidx(m, spidx, 1);
911 if (error)
912 goto bad;
913 spidx->dir = IPSEC_DIR_INBOUND;
914
915 spidx = &pcb->in6p_sp->sp_out->spidx;
916 error = ipsec_setspidx(m, spidx, 1);
917 if (error)
918 goto bad;
919 spidx->dir = IPSEC_DIR_OUTBOUND;
920
921 return 0;
922
923 bad:
924 memset(&pcb->in6p_sp->sp_in->spidx, 0, sizeof(*spidx));
925 memset(&pcb->in6p_sp->sp_out->spidx, 0, sizeof(*spidx));
926 return error;
927 }
928 #endif
929
930 /*
931 * configure security policy index (src/dst/proto/sport/dport)
932 * by looking at the content of mbuf.
933 * the caller is responsible for error recovery (like clearing up spidx).
934 */
935 static int
936 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
937 {
938 struct ip *ip = NULL;
939 struct ip ipbuf;
940 u_int v;
941 struct mbuf *n;
942 int len;
943 int error;
944
945 KASSERT(m != NULL);
946
947 /*
948 * validate m->m_pkthdr.len. we see incorrect length if we
949 * mistakenly call this function with inconsistent mbuf chain
950 * (like 4.4BSD tcp/udp processing). XXX should we panic here?
951 */
952 len = 0;
953 for (n = m; n; n = n->m_next)
954 len += n->m_len;
955 if (m->m_pkthdr.len != len) {
956 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
957 "total of m_len(%d) != pkthdr.len(%d), ignored.\n",
958 len, m->m_pkthdr.len);
959 return EINVAL;
960 }
961
962 if (m->m_pkthdr.len < sizeof(struct ip)) {
963 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
964 "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
965 m->m_pkthdr.len);
966 return EINVAL;
967 }
968
969 if (m->m_len >= sizeof(*ip))
970 ip = mtod(m, struct ip *);
971 else {
972 m_copydata(m, 0, sizeof(ipbuf), &ipbuf);
973 ip = &ipbuf;
974 }
975 v = ip->ip_v;
976 switch (v) {
977 case 4:
978 error = ipsec4_setspidx_ipaddr(m, spidx);
979 if (error)
980 return error;
981 ipsec4_get_ulp(m, spidx, needport);
982 return 0;
983 #ifdef INET6
984 case 6:
985 if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
986 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
987 "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
988 "ignored.\n", m->m_pkthdr.len);
989 return EINVAL;
990 }
991 error = ipsec6_setspidx_ipaddr(m, spidx);
992 if (error)
993 return error;
994 ipsec6_get_ulp(m, spidx, needport);
995 return 0;
996 #endif
997 default:
998 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
999 "unknown IP version %u, ignored.\n", v);
1000 return EINVAL;
1001 }
1002 }
1003
1004 static void
1005 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
1006 {
1007 u_int8_t nxt;
1008 int off;
1009
1010 /* sanity check */
1011 KASSERT(m != NULL);
1012 KASSERTMSG(m->m_pkthdr.len >= sizeof(struct ip), "packet too short");
1013
1014 /* NB: ip_input() flips it into host endian XXX need more checking */
1015 if (m->m_len >= sizeof(struct ip)) {
1016 struct ip *ip = mtod(m, struct ip *);
1017 if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
1018 goto done;
1019 off = ip->ip_hl << 2;
1020 nxt = ip->ip_p;
1021 } else {
1022 struct ip ih;
1023
1024 m_copydata(m, 0, sizeof (struct ip), &ih);
1025 if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
1026 goto done;
1027 off = ih.ip_hl << 2;
1028 nxt = ih.ip_p;
1029 }
1030
1031 while (off < m->m_pkthdr.len) {
1032 struct ip6_ext ip6e;
1033 struct tcphdr th;
1034 struct udphdr uh;
1035 struct icmp icmph;
1036
1037 switch (nxt) {
1038 case IPPROTO_TCP:
1039 spidx->ul_proto = nxt;
1040 if (!needport)
1041 goto done_proto;
1042 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
1043 goto done;
1044 m_copydata(m, off, sizeof (th), &th);
1045 spidx->src.sin.sin_port = th.th_sport;
1046 spidx->dst.sin.sin_port = th.th_dport;
1047 return;
1048 case IPPROTO_UDP:
1049 spidx->ul_proto = nxt;
1050 if (!needport)
1051 goto done_proto;
1052 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
1053 goto done;
1054 m_copydata(m, off, sizeof (uh), &uh);
1055 spidx->src.sin.sin_port = uh.uh_sport;
1056 spidx->dst.sin.sin_port = uh.uh_dport;
1057 return;
1058 case IPPROTO_AH:
1059 if (m->m_pkthdr.len > off + sizeof(ip6e))
1060 goto done;
1061 /* XXX sigh, this works but is totally bogus */
1062 m_copydata(m, off, sizeof(ip6e), &ip6e);
1063 off += (ip6e.ip6e_len + 2) << 2;
1064 nxt = ip6e.ip6e_nxt;
1065 break;
1066 case IPPROTO_ICMP:
1067 spidx->ul_proto = nxt;
1068 if (off + sizeof(struct icmp) > m->m_pkthdr.len)
1069 return;
1070 m_copydata(m, off, sizeof(icmph), &icmph);
1071 ((struct sockaddr_in *)&spidx->src)->sin_port =
1072 htons((uint16_t)icmph.icmp_type);
1073 ((struct sockaddr_in *)&spidx->dst)->sin_port =
1074 htons((uint16_t)icmph.icmp_code);
1075 return;
1076 default:
1077 /* XXX intermediate headers??? */
1078 spidx->ul_proto = nxt;
1079 goto done_proto;
1080 }
1081 }
1082 done:
1083 spidx->ul_proto = IPSEC_ULPROTO_ANY;
1084 done_proto:
1085 spidx->src.sin.sin_port = IPSEC_PORT_ANY;
1086 spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
1087 }
1088
1089 /* assumes that m is sane */
1090 static int
1091 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
1092 {
1093 static const struct sockaddr_in template = {
1094 sizeof (struct sockaddr_in),
1095 AF_INET,
1096 0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
1097 };
1098
1099 spidx->src.sin = template;
1100 spidx->dst.sin = template;
1101
1102 if (m->m_len < sizeof (struct ip)) {
1103 m_copydata(m, offsetof(struct ip, ip_src),
1104 sizeof(struct in_addr), &spidx->src.sin.sin_addr);
1105 m_copydata(m, offsetof(struct ip, ip_dst),
1106 sizeof(struct in_addr), &spidx->dst.sin.sin_addr);
1107 } else {
1108 struct ip *ip = mtod(m, struct ip *);
1109 spidx->src.sin.sin_addr = ip->ip_src;
1110 spidx->dst.sin.sin_addr = ip->ip_dst;
1111 }
1112
1113 spidx->prefs = sizeof(struct in_addr) << 3;
1114 spidx->prefd = sizeof(struct in_addr) << 3;
1115
1116 return 0;
1117 }
1118
1119 #ifdef INET6
1120 static void
1121 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx,
1122 int needport)
1123 {
1124 int off, nxt;
1125 struct tcphdr th;
1126 struct udphdr uh;
1127 struct icmp6_hdr icmph;
1128
1129 KASSERT(m != NULL);
1130
1131 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
1132 printf("%s:\n", __func__);
1133 kdebug_mbuf(m);
1134 }
1135
1136 /* set default */
1137 spidx->ul_proto = IPSEC_ULPROTO_ANY;
1138 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
1139 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
1140
1141 nxt = -1;
1142 off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
1143 if (off < 0 || m->m_pkthdr.len < off)
1144 return;
1145
1146 switch (nxt) {
1147 case IPPROTO_TCP:
1148 spidx->ul_proto = nxt;
1149 if (!needport)
1150 break;
1151 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
1152 break;
1153 m_copydata(m, off, sizeof(th), &th);
1154 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
1155 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
1156 break;
1157 case IPPROTO_UDP:
1158 spidx->ul_proto = nxt;
1159 if (!needport)
1160 break;
1161 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
1162 break;
1163 m_copydata(m, off, sizeof(uh), &uh);
1164 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
1165 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
1166 break;
1167 case IPPROTO_ICMPV6:
1168 spidx->ul_proto = nxt;
1169 if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
1170 break;
1171 m_copydata(m, off, sizeof(icmph), &icmph);
1172 ((struct sockaddr_in6 *)&spidx->src)->sin6_port =
1173 htons((uint16_t)icmph.icmp6_type);
1174 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
1175 htons((uint16_t)icmph.icmp6_code);
1176 break;
1177 default:
1178 /* XXX intermediate headers??? */
1179 spidx->ul_proto = nxt;
1180 break;
1181 }
1182 }
1183
1184 /* assumes that m is sane */
1185 static int
1186 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
1187 {
1188 struct ip6_hdr *ip6 = NULL;
1189 struct ip6_hdr ip6buf;
1190 struct sockaddr_in6 *sin6;
1191
1192 if (m->m_len >= sizeof(*ip6))
1193 ip6 = mtod(m, struct ip6_hdr *);
1194 else {
1195 m_copydata(m, 0, sizeof(ip6buf), &ip6buf);
1196 ip6 = &ip6buf;
1197 }
1198
1199 sin6 = (struct sockaddr_in6 *)&spidx->src;
1200 memset(sin6, 0, sizeof(*sin6));
1201 sin6->sin6_family = AF_INET6;
1202 sin6->sin6_len = sizeof(struct sockaddr_in6);
1203 memcpy(&sin6->sin6_addr, &ip6->ip6_src, sizeof(ip6->ip6_src));
1204 if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
1205 sin6->sin6_addr.s6_addr16[1] = 0;
1206 sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
1207 }
1208 spidx->prefs = sizeof(struct in6_addr) << 3;
1209
1210 sin6 = (struct sockaddr_in6 *)&spidx->dst;
1211 memset(sin6, 0, sizeof(*sin6));
1212 sin6->sin6_family = AF_INET6;
1213 sin6->sin6_len = sizeof(struct sockaddr_in6);
1214 memcpy(&sin6->sin6_addr, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
1215 if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
1216 sin6->sin6_addr.s6_addr16[1] = 0;
1217 sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
1218 }
1219 spidx->prefd = sizeof(struct in6_addr) << 3;
1220
1221 return 0;
1222 }
1223 #endif
1224
1225 static void
1226 ipsec_delpcbpolicy(struct inpcbpolicy *p)
1227 {
1228
1229 kmem_intr_free(p, sizeof(*p));
1230 }
1231
1232 /* initialize policy in PCB */
1233 int
1234 ipsec_init_policy(struct socket *so, struct inpcbpolicy **policy)
1235 {
1236 struct inpcbpolicy *new;
1237
1238 KASSERT(so != NULL);
1239 KASSERT(policy != NULL);
1240
1241 new = kmem_intr_zalloc(sizeof(*new), KM_NOSLEEP);
1242 if (new == NULL) {
1243 IPSECLOG(LOG_DEBUG, "No more memory.\n");
1244 return ENOBUFS;
1245 }
1246
1247 if (IPSEC_PRIVILEGED_SO(so))
1248 new->priv = 1;
1249 else
1250 new->priv = 0;
1251
1252 /*
1253 * These SPs are dummy. Never be used because the policy
1254 * is ENTRUST. See ipsec_getpolicybysock.
1255 */
1256 if ((new->sp_in = KEY_NEWSP()) == NULL) {
1257 ipsec_delpcbpolicy(new);
1258 return ENOBUFS;
1259 }
1260 new->sp_in->state = IPSEC_SPSTATE_ALIVE;
1261 new->sp_in->policy = IPSEC_POLICY_ENTRUST;
1262 new->sp_in->created = 0; /* Indicates dummy */
1263
1264 if ((new->sp_out = KEY_NEWSP()) == NULL) {
1265 KEY_SP_UNREF(&new->sp_in);
1266 ipsec_delpcbpolicy(new);
1267 return ENOBUFS;
1268 }
1269 new->sp_out->state = IPSEC_SPSTATE_ALIVE;
1270 new->sp_out->policy = IPSEC_POLICY_ENTRUST;
1271 new->sp_out->created = 0; /* Indicates dummy */
1272
1273 *policy = new;
1274
1275 return 0;
1276 }
1277
1278 /* copy old ipsec policy into new */
1279 int
1280 ipsec_copy_policy(const struct inpcbpolicy *old, struct inpcbpolicy *new)
1281 {
1282 struct secpolicy *sp;
1283
1284 sp = ipsec_deepcopy_policy(old->sp_in);
1285 if (sp) {
1286 KEY_SP_UNREF(&new->sp_in);
1287 new->sp_in = sp;
1288 } else
1289 return ENOBUFS;
1290
1291 sp = ipsec_deepcopy_policy(old->sp_out);
1292 if (sp) {
1293 KEY_SP_UNREF(&new->sp_out);
1294 new->sp_out = sp;
1295 } else
1296 return ENOBUFS;
1297
1298 new->priv = old->priv;
1299
1300 return 0;
1301 }
1302
1303 /* deep-copy a policy in PCB */
1304 static struct secpolicy *
1305 ipsec_deepcopy_policy(const struct secpolicy *src)
1306 {
1307 struct ipsecrequest *newchain = NULL;
1308 const struct ipsecrequest *p;
1309 struct ipsecrequest **q;
1310 struct secpolicy *dst;
1311
1312 if (src == NULL)
1313 return NULL;
1314 dst = KEY_NEWSP();
1315 if (dst == NULL)
1316 return NULL;
1317
1318 /*
1319 * deep-copy IPsec request chain. This is required since struct
1320 * ipsecrequest is not reference counted.
1321 */
1322 q = &newchain;
1323 for (p = src->req; p; p = p->next) {
1324 *q = kmem_zalloc(sizeof(**q), KM_SLEEP);
1325 (*q)->next = NULL;
1326
1327 (*q)->saidx.proto = p->saidx.proto;
1328 (*q)->saidx.mode = p->saidx.mode;
1329 (*q)->level = p->level;
1330 (*q)->saidx.reqid = p->saidx.reqid;
1331
1332 memcpy(&(*q)->saidx.src, &p->saidx.src, sizeof((*q)->saidx.src));
1333 memcpy(&(*q)->saidx.dst, &p->saidx.dst, sizeof((*q)->saidx.dst));
1334
1335 (*q)->sp = dst;
1336
1337 q = &((*q)->next);
1338 }
1339
1340 dst->req = newchain;
1341 dst->state = src->state;
1342 dst->policy = src->policy;
1343 /* do not touch the refcnt fields */
1344
1345 return dst;
1346 }
1347
1348 static void
1349 ipsec_destroy_policy(struct secpolicy *sp)
1350 {
1351
1352 if (sp->created == 0)
1353 /* It's dummy. We can simply free it */
1354 key_free_sp(sp);
1355 else {
1356 /*
1357 * We cannot destroy here because it can be called in
1358 * softint. So mark the SP as DEAD and let the timer
1359 * destroy it. See key_timehandler_spd.
1360 */
1361 sp->state = IPSEC_SPSTATE_DEAD;
1362 }
1363 }
1364
1365 /* set policy and ipsec request if present. */
1366 static int
1367 ipsec_set_policy(
1368 struct secpolicy **policy,
1369 int optname,
1370 const void *request,
1371 size_t len,
1372 kauth_cred_t cred
1373 )
1374 {
1375 const struct sadb_x_policy *xpl;
1376 struct secpolicy *newsp = NULL, *oldsp;
1377 int error;
1378
1379 KASSERT(!cpu_softintr_p());
1380
1381 /* sanity check. */
1382 if (policy == NULL || *policy == NULL || request == NULL)
1383 return EINVAL;
1384 if (len < sizeof(*xpl))
1385 return EINVAL;
1386 xpl = (const struct sadb_x_policy *)request;
1387
1388 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
1389 printf("%s: passed policy\n", __func__);
1390 kdebug_sadb_x_policy((const struct sadb_ext *)xpl);
1391 }
1392
1393 /* check policy type */
1394 /* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
1395 if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
1396 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
1397 return EINVAL;
1398
1399 /* check privileged socket */
1400 if (xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1401 error = kauth_authorize_network(cred, KAUTH_NETWORK_IPSEC,
1402 KAUTH_REQ_NETWORK_IPSEC_BYPASS, NULL, NULL, NULL);
1403 if (error)
1404 return (error);
1405 }
1406
1407 /* allocation new SP entry */
1408 if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
1409 return error;
1410
1411 key_init_sp(newsp);
1412 newsp->created = time_uptime;
1413 /* Insert the global list for SPs for sockets */
1414 key_socksplist_add(newsp);
1415
1416 /* clear old SP and set new SP */
1417 oldsp = *policy;
1418 *policy = newsp;
1419 ipsec_destroy_policy(oldsp);
1420
1421 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
1422 printf("%s: new policy\n", __func__);
1423 kdebug_secpolicy(newsp);
1424 }
1425
1426 return 0;
1427 }
1428
1429 static int
1430 ipsec_get_policy(struct secpolicy *policy, struct mbuf **mp)
1431 {
1432
1433 /* sanity check. */
1434 if (policy == NULL || mp == NULL)
1435 return EINVAL;
1436
1437 *mp = key_sp2msg(policy);
1438 if (!*mp) {
1439 IPSECLOG(LOG_DEBUG, "No more memory.\n");
1440 return ENOBUFS;
1441 }
1442
1443 (*mp)->m_type = MT_DATA;
1444 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DUMP)) {
1445 printf("%s:\n", __func__);
1446 kdebug_mbuf(*mp);
1447 }
1448
1449 return 0;
1450 }
1451
1452 int
1453 ipsec4_set_policy(struct inpcb *inp, int optname, const void *request,
1454 size_t len, kauth_cred_t cred)
1455 {
1456 const struct sadb_x_policy *xpl;
1457 struct secpolicy **policy;
1458
1459 KASSERT(!cpu_softintr_p());
1460 KASSERT(inp_locked(inp));
1461
1462 /* sanity check. */
1463 if (inp == NULL || request == NULL)
1464 return EINVAL;
1465 if (len < sizeof(*xpl))
1466 return EINVAL;
1467 xpl = (const struct sadb_x_policy *)request;
1468
1469 KASSERT(inp->inp_sp != NULL);
1470
1471 /* select direction */
1472 switch (xpl->sadb_x_policy_dir) {
1473 case IPSEC_DIR_INBOUND:
1474 policy = &inp->inp_sp->sp_in;
1475 break;
1476 case IPSEC_DIR_OUTBOUND:
1477 policy = &inp->inp_sp->sp_out;
1478 break;
1479 default:
1480 IPSECLOG(LOG_ERR, "invalid direction=%u\n",
1481 xpl->sadb_x_policy_dir);
1482 return EINVAL;
1483 }
1484
1485 return ipsec_set_policy(policy, optname, request, len, cred);
1486 }
1487
1488 int
1489 ipsec4_get_policy(struct inpcb *inp, const void *request, size_t len,
1490 struct mbuf **mp)
1491 {
1492 const struct sadb_x_policy *xpl;
1493 struct secpolicy *policy;
1494
1495 /* sanity check. */
1496 if (inp == NULL || request == NULL || mp == NULL)
1497 return EINVAL;
1498 KASSERT(inp->inp_sp != NULL);
1499 if (len < sizeof(*xpl))
1500 return EINVAL;
1501 xpl = (const struct sadb_x_policy *)request;
1502
1503 /* select direction */
1504 switch (xpl->sadb_x_policy_dir) {
1505 case IPSEC_DIR_INBOUND:
1506 policy = inp->inp_sp->sp_in;
1507 break;
1508 case IPSEC_DIR_OUTBOUND:
1509 policy = inp->inp_sp->sp_out;
1510 break;
1511 default:
1512 IPSECLOG(LOG_ERR, "invalid direction=%u\n",
1513 xpl->sadb_x_policy_dir);
1514 return EINVAL;
1515 }
1516
1517 return ipsec_get_policy(policy, mp);
1518 }
1519
1520 /* delete policy in PCB */
1521 int
1522 ipsec4_delete_pcbpolicy(struct inpcb *inp)
1523 {
1524
1525 KASSERT(inp != NULL);
1526
1527 if (inp->inp_sp == NULL)
1528 return 0;
1529
1530 if (inp->inp_sp->sp_in != NULL)
1531 ipsec_destroy_policy(inp->inp_sp->sp_in);
1532
1533 if (inp->inp_sp->sp_out != NULL)
1534 ipsec_destroy_policy(inp->inp_sp->sp_out);
1535
1536 ipsec_invalpcbcache(inp->inp_sp, IPSEC_DIR_ANY);
1537
1538 ipsec_delpcbpolicy(inp->inp_sp);
1539 inp->inp_sp = NULL;
1540
1541 return 0;
1542 }
1543
1544 #ifdef INET6
1545 int
1546 ipsec6_set_policy(struct in6pcb *in6p, int optname, const void *request,
1547 size_t len, kauth_cred_t cred)
1548 {
1549 const struct sadb_x_policy *xpl;
1550 struct secpolicy **policy;
1551
1552 KASSERT(!cpu_softintr_p());
1553 KASSERT(in6p_locked(in6p));
1554
1555 /* sanity check. */
1556 if (in6p == NULL || request == NULL)
1557 return EINVAL;
1558 if (len < sizeof(*xpl))
1559 return EINVAL;
1560 xpl = (const struct sadb_x_policy *)request;
1561
1562 /* select direction */
1563 switch (xpl->sadb_x_policy_dir) {
1564 case IPSEC_DIR_INBOUND:
1565 policy = &in6p->in6p_sp->sp_in;
1566 break;
1567 case IPSEC_DIR_OUTBOUND:
1568 policy = &in6p->in6p_sp->sp_out;
1569 break;
1570 default:
1571 IPSECLOG(LOG_ERR, "invalid direction=%u\n",
1572 xpl->sadb_x_policy_dir);
1573 return EINVAL;
1574 }
1575
1576 return ipsec_set_policy(policy, optname, request, len, cred);
1577 }
1578
1579 int
1580 ipsec6_get_policy(struct in6pcb *in6p, const void *request, size_t len,
1581 struct mbuf **mp)
1582 {
1583 const struct sadb_x_policy *xpl;
1584 struct secpolicy *policy;
1585
1586 /* sanity check. */
1587 if (in6p == NULL || request == NULL || mp == NULL)
1588 return EINVAL;
1589 KASSERT(in6p->in6p_sp != NULL);
1590 if (len < sizeof(*xpl))
1591 return EINVAL;
1592 xpl = (const struct sadb_x_policy *)request;
1593
1594 /* select direction */
1595 switch (xpl->sadb_x_policy_dir) {
1596 case IPSEC_DIR_INBOUND:
1597 policy = in6p->in6p_sp->sp_in;
1598 break;
1599 case IPSEC_DIR_OUTBOUND:
1600 policy = in6p->in6p_sp->sp_out;
1601 break;
1602 default:
1603 IPSECLOG(LOG_ERR, "invalid direction=%u\n",
1604 xpl->sadb_x_policy_dir);
1605 return EINVAL;
1606 }
1607
1608 return ipsec_get_policy(policy, mp);
1609 }
1610
1611 int
1612 ipsec6_delete_pcbpolicy(struct in6pcb *in6p)
1613 {
1614
1615 KASSERT(in6p != NULL);
1616
1617 if (in6p->in6p_sp == NULL)
1618 return 0;
1619
1620 if (in6p->in6p_sp->sp_in != NULL)
1621 ipsec_destroy_policy(in6p->in6p_sp->sp_in);
1622
1623 if (in6p->in6p_sp->sp_out != NULL)
1624 ipsec_destroy_policy(in6p->in6p_sp->sp_out);
1625
1626 ipsec_invalpcbcache(in6p->in6p_sp, IPSEC_DIR_ANY);
1627
1628 ipsec_delpcbpolicy(in6p->in6p_sp);
1629 in6p->in6p_sp = NULL;
1630
1631 return 0;
1632 }
1633 #endif
1634
1635 /*
1636 * return current level.
1637 * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1638 */
1639 u_int
1640 ipsec_get_reqlevel(const struct ipsecrequest *isr)
1641 {
1642 u_int level = 0;
1643 u_int esp_trans_deflev, esp_net_deflev;
1644 u_int ah_trans_deflev, ah_net_deflev;
1645
1646 KASSERT(isr != NULL);
1647 KASSERT(isr->sp != NULL);
1648 KASSERTMSG(
1649 isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
1650 "af family mismatch, src %u, dst %u",
1651 isr->sp->spidx.src.sa.sa_family, isr->sp->spidx.dst.sa.sa_family);
1652
1653 /* XXX note that we have ipseclog() expanded here - code sync issue */
1654 #define IPSEC_CHECK_DEFAULT(lev) \
1655 (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE \
1656 && (lev) != IPSEC_LEVEL_UNIQUE) ? \
1657 (ipsec_debug ? log(LOG_INFO, "fixed system default level " #lev \
1658 ":%d->%d\n", (lev), IPSEC_LEVEL_REQUIRE) : (void)0), \
1659 (lev) = IPSEC_LEVEL_REQUIRE, (lev) \
1660 : (lev))
1661
1662 /* set default level */
1663 switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1664 #ifdef INET
1665 case AF_INET:
1666 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
1667 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
1668 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
1669 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
1670 break;
1671 #endif
1672 #ifdef INET6
1673 case AF_INET6:
1674 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
1675 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
1676 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
1677 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
1678 break;
1679 #endif /* INET6 */
1680 default:
1681 panic("%s: unknown af %u", __func__,
1682 isr->sp->spidx.src.sa.sa_family);
1683 }
1684
1685 #undef IPSEC_CHECK_DEFAULT
1686
1687 /* set level */
1688 switch (isr->level) {
1689 case IPSEC_LEVEL_DEFAULT:
1690 switch (isr->saidx.proto) {
1691 case IPPROTO_ESP:
1692 if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1693 level = esp_net_deflev;
1694 else
1695 level = esp_trans_deflev;
1696 break;
1697 case IPPROTO_AH:
1698 if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1699 level = ah_net_deflev;
1700 else
1701 level = ah_trans_deflev;
1702 break;
1703 case IPPROTO_IPCOMP:
1704 /*
1705 * we don't really care, as IPcomp document says that
1706 * we shouldn't compress small packets
1707 */
1708 level = IPSEC_LEVEL_USE;
1709 break;
1710 default:
1711 panic("%s: Illegal protocol defined %u", __func__,
1712 isr->saidx.proto);
1713 }
1714 break;
1715
1716 case IPSEC_LEVEL_USE:
1717 case IPSEC_LEVEL_REQUIRE:
1718 level = isr->level;
1719 break;
1720 case IPSEC_LEVEL_UNIQUE:
1721 level = IPSEC_LEVEL_REQUIRE;
1722 break;
1723
1724 default:
1725 panic("%s: Illegal IPsec level %u", __func__, isr->level);
1726 }
1727
1728 return level;
1729 }
1730
1731 /*
1732 * Check security policy requirements against the actual
1733 * packet contents. Return one if the packet should be
1734 * reject as "invalid"; otherwiser return zero to have the
1735 * packet treated as "valid".
1736 *
1737 * OUT:
1738 * 0: valid
1739 * 1: invalid
1740 */
1741 int
1742 ipsec_in_reject(const struct secpolicy *sp, const struct mbuf *m)
1743 {
1744 struct ipsecrequest *isr;
1745
1746 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
1747 printf("%s: using SP\n", __func__);
1748 kdebug_secpolicy(sp);
1749 }
1750
1751 /* check policy */
1752 switch (sp->policy) {
1753 case IPSEC_POLICY_DISCARD:
1754 return 1;
1755 case IPSEC_POLICY_BYPASS:
1756 case IPSEC_POLICY_NONE:
1757 return 0;
1758 }
1759
1760 KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
1761 "invalid policy %u", sp->policy);
1762
1763 /* XXX should compare policy against ipsec header history */
1764
1765 for (isr = sp->req; isr != NULL; isr = isr->next) {
1766 if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1767 continue;
1768 switch (isr->saidx.proto) {
1769 case IPPROTO_ESP:
1770 if ((m->m_flags & M_DECRYPTED) == 0) {
1771 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
1772 "ESP m_flags:%x\n", m->m_flags);
1773 return 1;
1774 }
1775 break;
1776 case IPPROTO_AH:
1777 if ((m->m_flags & M_AUTHIPHDR) == 0) {
1778 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DUMP,
1779 "AH m_flags:%x\n", m->m_flags);
1780 return 1;
1781 }
1782 break;
1783 case IPPROTO_IPCOMP:
1784 /*
1785 * we don't really care, as IPcomp document
1786 * says that we shouldn't compress small
1787 * packets, IPComp policy should always be
1788 * treated as being in "use" level.
1789 */
1790 break;
1791 }
1792 }
1793 return 0; /* valid */
1794 }
1795
1796 /*
1797 * Check AH/ESP integrity.
1798 * This function is called from tcp_input(), udp_input(),
1799 * and {ah,esp}4_input for tunnel mode
1800 */
1801 int
1802 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
1803 {
1804 struct secpolicy *sp;
1805 int error;
1806 int result;
1807
1808 KASSERT(m != NULL);
1809
1810 /* get SP for this packet.
1811 * When we are called from ip_forward(), we call
1812 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1813 */
1814 if (inp == NULL)
1815 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1816 else
1817 sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1818 (struct inpcb_hdr *)inp, &error);
1819
1820 if (sp != NULL) {
1821 result = ipsec_in_reject(sp, m);
1822 if (result)
1823 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1824 KEY_SP_UNREF(&sp);
1825 } else {
1826 result = 0; /* XXX should be panic ?
1827 * -> No, there may be error. */
1828 }
1829 return result;
1830 }
1831
1832
1833 #ifdef INET6
1834 /*
1835 * Check AH/ESP integrity.
1836 * This function is called from tcp6_input(), udp6_input(),
1837 * and {ah,esp}6_input for tunnel mode
1838 */
1839 int
1840 ipsec6_in_reject(struct mbuf *m, struct in6pcb *in6p)
1841 {
1842 struct secpolicy *sp = NULL;
1843 int error;
1844 int result;
1845
1846 KASSERT(m != NULL);
1847
1848 /* get SP for this packet.
1849 * When we are called from ip_forward(), we call
1850 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1851 */
1852 if (in6p == NULL)
1853 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1854 else
1855 sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND,
1856 (struct inpcb_hdr *)in6p,
1857 &error);
1858
1859 if (sp != NULL) {
1860 result = ipsec_in_reject(sp, m);
1861 if (result)
1862 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1863 KEY_SP_UNREF(&sp);
1864 } else {
1865 result = 0;
1866 }
1867 return result;
1868 }
1869 #endif
1870
1871 /*
1872 * compute the byte size to be occupied by IPsec header.
1873 * in case it is tunneled, it includes the size of outer IP header.
1874 * NOTE: SP passed is free in this function.
1875 */
1876 static size_t
1877 ipsec_hdrsiz(const struct secpolicy *sp)
1878 {
1879 struct ipsecrequest *isr;
1880 size_t siz;
1881
1882 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
1883 printf("%s: using SP\n", __func__);
1884 kdebug_secpolicy(sp);
1885 }
1886
1887 switch (sp->policy) {
1888 case IPSEC_POLICY_DISCARD:
1889 case IPSEC_POLICY_BYPASS:
1890 case IPSEC_POLICY_NONE:
1891 return 0;
1892 }
1893
1894 KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
1895 "invalid policy %u", sp->policy);
1896
1897 siz = 0;
1898 for (isr = sp->req; isr != NULL; isr = isr->next) {
1899 size_t clen = 0;
1900 struct secasvar *sav = NULL;
1901 int error;
1902
1903 switch (isr->saidx.proto) {
1904 case IPPROTO_ESP:
1905 error = key_checkrequest(isr, &sav);
1906 if (error == 0) {
1907 clen = esp_hdrsiz(sav);
1908 KEY_FREESAV(&sav);
1909 } else
1910 clen = esp_hdrsiz(NULL);
1911 break;
1912 case IPPROTO_AH:
1913 error = key_checkrequest(isr, &sav);
1914 if (error == 0) {
1915 clen = ah_hdrsiz(sav);
1916 KEY_FREESAV(&sav);
1917 } else
1918 clen = ah_hdrsiz(NULL);
1919 break;
1920 case IPPROTO_IPCOMP:
1921 clen = sizeof(struct ipcomp);
1922 break;
1923 }
1924
1925 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1926 switch (isr->saidx.dst.sa.sa_family) {
1927 case AF_INET:
1928 clen += sizeof(struct ip);
1929 break;
1930 #ifdef INET6
1931 case AF_INET6:
1932 clen += sizeof(struct ip6_hdr);
1933 break;
1934 #endif
1935 default:
1936 IPSECLOG(LOG_ERR, "unknown AF %d in "
1937 "IPsec tunnel SA\n",
1938 ((const struct sockaddr *)&isr->saidx.dst)
1939 ->sa_family);
1940 break;
1941 }
1942 }
1943 siz += clen;
1944 }
1945
1946 return siz;
1947 }
1948
1949 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
1950 size_t
1951 ipsec4_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
1952 {
1953 struct secpolicy *sp;
1954 int error;
1955 size_t size;
1956
1957 KASSERT(m != NULL);
1958 KASSERTMSG(inp == NULL || inp->inp_socket != NULL, "socket w/o inpcb");
1959
1960 /* get SP for this packet.
1961 * When we are called from ip_forward(), we call
1962 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1963 */
1964 if (inp == NULL)
1965 sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1966 else
1967 sp = ipsec_getpolicybysock(m, dir,
1968 (struct inpcb_hdr *)inp, &error);
1969
1970 if (sp != NULL) {
1971 size = ipsec_hdrsiz(sp);
1972 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DATA, "size:%lu.\n",
1973 (unsigned long)size);
1974
1975 KEY_SP_UNREF(&sp);
1976 } else {
1977 size = 0; /* XXX should be panic ? */
1978 }
1979 return size;
1980 }
1981
1982 #ifdef INET6
1983 /* This function is called from ipsec6_hdrsize_tcp(),
1984 * and maybe from ip6_forward.()
1985 */
1986 size_t
1987 ipsec6_hdrsiz(struct mbuf *m, u_int dir, struct in6pcb *in6p)
1988 {
1989 struct secpolicy *sp;
1990 int error;
1991 size_t size;
1992
1993 KASSERT(m != NULL);
1994 KASSERTMSG(in6p == NULL || in6p->in6p_socket != NULL,
1995 "socket w/o inpcb");
1996
1997 /* get SP for this packet */
1998 /* XXX Is it right to call with IP_FORWARDING. */
1999 if (in6p == NULL)
2000 sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
2001 else
2002 sp = ipsec_getpolicybysock(m, dir,
2003 (struct inpcb_hdr *)in6p,
2004 &error);
2005
2006 if (sp == NULL)
2007 return 0;
2008 size = ipsec_hdrsiz(sp);
2009 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_DATA, "size:%zu.\n", size);
2010 KEY_SP_UNREF(&sp);
2011
2012 return size;
2013 }
2014 #endif /*INET6*/
2015
2016 /*
2017 * Check the variable replay window.
2018 * ipsec_chkreplay() performs replay check before ICV verification.
2019 * ipsec_updatereplay() updates replay bitmap. This must be called after
2020 * ICV verification (it also performs replay check, which is usually done
2021 * beforehand).
2022 * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
2023 *
2024 * based on RFC 2401.
2025 */
2026 int
2027 ipsec_chkreplay(u_int32_t seq, const struct secasvar *sav)
2028 {
2029 const struct secreplay *replay;
2030 u_int32_t diff;
2031 int fr;
2032 u_int32_t wsizeb; /* constant: bits of window size */
2033 int frlast; /* constant: last frame */
2034
2035 IPSEC_SPLASSERT_SOFTNET(__func__);
2036
2037 KASSERT(sav != NULL);
2038 KASSERT(sav->replay != NULL);
2039
2040 replay = sav->replay;
2041
2042 if (replay->wsize == 0)
2043 return 1; /* no need to check replay. */
2044
2045 /* constant */
2046 frlast = replay->wsize - 1;
2047 wsizeb = replay->wsize << 3;
2048
2049 /* sequence number of 0 is invalid */
2050 if (seq == 0)
2051 return 0;
2052
2053 /* first time is always okay */
2054 if (replay->count == 0)
2055 return 1;
2056
2057 if (seq > replay->lastseq) {
2058 /* larger sequences are okay */
2059 return 1;
2060 } else {
2061 /* seq is equal or less than lastseq. */
2062 diff = replay->lastseq - seq;
2063
2064 /* over range to check, i.e. too old or wrapped */
2065 if (diff >= wsizeb)
2066 return 0;
2067
2068 fr = frlast - diff / 8;
2069
2070 /* this packet already seen ? */
2071 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
2072 return 0;
2073
2074 /* out of order but good */
2075 return 1;
2076 }
2077 }
2078
2079 /*
2080 * check replay counter whether to update or not.
2081 * OUT: 0: OK
2082 * 1: NG
2083 */
2084 int
2085 ipsec_updatereplay(u_int32_t seq, const struct secasvar *sav)
2086 {
2087 struct secreplay *replay;
2088 u_int32_t diff;
2089 int fr;
2090 u_int32_t wsizeb; /* constant: bits of window size */
2091 int frlast; /* constant: last frame */
2092 char buf[INET6_ADDRSTRLEN];
2093
2094 IPSEC_SPLASSERT_SOFTNET(__func__);
2095
2096 KASSERT(sav != NULL);
2097 KASSERT(sav->replay != NULL);
2098
2099 replay = sav->replay;
2100
2101 if (replay->wsize == 0)
2102 goto ok; /* no need to check replay. */
2103
2104 /* constant */
2105 frlast = replay->wsize - 1;
2106 wsizeb = replay->wsize << 3;
2107
2108 /* sequence number of 0 is invalid */
2109 if (seq == 0)
2110 return 1;
2111
2112 /* first time */
2113 if (replay->count == 0) {
2114 replay->lastseq = seq;
2115 memset(replay->bitmap, 0, replay->wsize);
2116 (replay->bitmap)[frlast] = 1;
2117 goto ok;
2118 }
2119
2120 if (seq > replay->lastseq) {
2121 /* seq is larger than lastseq. */
2122 diff = seq - replay->lastseq;
2123
2124 /* new larger sequence number */
2125 if (diff < wsizeb) {
2126 /* In window */
2127 /* set bit for this packet */
2128 vshiftl(replay->bitmap, diff, replay->wsize);
2129 (replay->bitmap)[frlast] |= 1;
2130 } else {
2131 /* this packet has a "way larger" */
2132 memset(replay->bitmap, 0, replay->wsize);
2133 (replay->bitmap)[frlast] = 1;
2134 }
2135 replay->lastseq = seq;
2136
2137 /* larger is good */
2138 } else {
2139 /* seq is equal or less than lastseq. */
2140 diff = replay->lastseq - seq;
2141
2142 /* over range to check, i.e. too old or wrapped */
2143 if (diff >= wsizeb)
2144 return 1;
2145
2146 fr = frlast - diff / 8;
2147
2148 /* this packet already seen ? */
2149 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
2150 return 1;
2151
2152 /* mark as seen */
2153 (replay->bitmap)[fr] |= (1 << (diff % 8));
2154
2155 /* out of order but good */
2156 }
2157
2158 ok:
2159 if (replay->count == ~0) {
2160
2161 /* set overflow flag */
2162 replay->overflow++;
2163
2164 /* don't increment, no more packets accepted */
2165 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
2166 return 1;
2167
2168 IPSECLOG(LOG_WARNING, "replay counter made %d cycle. %s\n",
2169 replay->overflow, ipsec_logsastr(sav, buf, sizeof(buf)));
2170 }
2171
2172 replay->count++;
2173
2174 return 0;
2175 }
2176
2177 /*
2178 * shift variable length bunffer to left.
2179 * IN: bitmap: pointer to the buffer
2180 * nbit: the number of to shift.
2181 * wsize: buffer size (bytes).
2182 */
2183 static void
2184 vshiftl(unsigned char *bitmap, int nbit, int wsize)
2185 {
2186 int s, j, i;
2187 unsigned char over;
2188
2189 for (j = 0; j < nbit; j += 8) {
2190 s = (nbit - j < 8) ? (nbit - j): 8;
2191 bitmap[0] <<= s;
2192 for (i = 1; i < wsize; i++) {
2193 over = (bitmap[i] >> (8 - s));
2194 bitmap[i] <<= s;
2195 bitmap[i-1] |= over;
2196 }
2197 }
2198
2199 return;
2200 }
2201
2202 /* Return a printable string for the address. */
2203 const char *
2204 ipsec_address(const union sockaddr_union *sa, char *buf, size_t size)
2205 {
2206 switch (sa->sa.sa_family) {
2207 #if INET
2208 case AF_INET:
2209 in_print(buf, size, &sa->sin.sin_addr);
2210 return buf;
2211 #endif /* INET */
2212
2213 #if INET6
2214 case AF_INET6:
2215 in6_print(buf, size, &sa->sin6.sin6_addr);
2216 return buf;
2217 #endif /* INET6 */
2218
2219 default:
2220 return "(unknown address family)";
2221 }
2222 }
2223
2224 const char *
2225 ipsec_logsastr(const struct secasvar *sav, char *buf, size_t size)
2226 {
2227 const struct secasindex *saidx = &sav->sah->saidx;
2228 char sbuf[IPSEC_ADDRSTRLEN], dbuf[IPSEC_ADDRSTRLEN];
2229
2230 KASSERTMSG(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
2231 "af family mismatch, src %u, dst %u",
2232 saidx->src.sa.sa_family, saidx->dst.sa.sa_family);
2233
2234 snprintf(buf, size, "SA(SPI=%u src=%s dst=%s)",
2235 (u_int32_t)ntohl(sav->spi),
2236 ipsec_address(&saidx->src, sbuf, sizeof(sbuf)),
2237 ipsec_address(&saidx->dst, dbuf, sizeof(dbuf)));
2238
2239 return buf;
2240 }
2241
2242 void
2243 ipsec_dumpmbuf(struct mbuf *m)
2244 {
2245 int totlen;
2246 int i;
2247 u_char *p;
2248
2249 totlen = 0;
2250 printf("---\n");
2251 while (m) {
2252 p = mtod(m, u_char *);
2253 for (i = 0; i < m->m_len; i++) {
2254 printf("%02x ", p[i]);
2255 totlen++;
2256 if (totlen % 16 == 0)
2257 printf("\n");
2258 }
2259 m = m->m_next;
2260 }
2261 if (totlen % 16 != 0)
2262 printf("\n");
2263 printf("---\n");
2264 }
2265
2266 #ifdef INET6
2267 struct secpolicy *
2268 ipsec6_check_policy(struct mbuf *m, struct in6pcb *in6p,
2269 int flags, int *needipsecp, int *errorp)
2270 {
2271 struct secpolicy *sp = NULL;
2272 int s;
2273 int error = 0;
2274 int needipsec = 0;
2275
2276 if (!ipsec_outdone(m)) {
2277 s = splsoftnet();
2278 if (in6p != NULL &&
2279 ipsec_pcb_skip_ipsec(in6p->in6p_sp, IPSEC_DIR_OUTBOUND)) {
2280 splx(s);
2281 goto skippolicycheck;
2282 }
2283 sp = ipsec6_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags, &error,in6p);
2284
2285 /*
2286 * There are four return cases:
2287 * sp != NULL apply IPsec policy
2288 * sp == NULL, error == 0 no IPsec handling needed
2289 * sp == NULL, error == -EINVAL discard packet w/o error
2290 * sp == NULL, error != 0 discard packet, report error
2291 */
2292
2293 splx(s);
2294 if (sp == NULL) {
2295 /*
2296 * Caller must check the error return to see if it needs to discard
2297 * the packet.
2298 */
2299 needipsec = 0;
2300 } else {
2301 needipsec = 1;
2302 }
2303 }
2304 skippolicycheck:;
2305
2306 *errorp = error;
2307 *needipsecp = needipsec;
2308 return sp;
2309 }
2310
2311 int
2312 ipsec6_input(struct mbuf *m)
2313 {
2314 struct secpolicy *sp;
2315 int s, error;
2316
2317 s = splsoftnet();
2318 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
2319 if (sp != NULL) {
2320 /*
2321 * Check security policy against packet
2322 * attributes.
2323 */
2324 error = ipsec_in_reject(sp, m);
2325 KEY_SP_UNREF(&sp);
2326 } else {
2327 /* XXX error stat??? */
2328 error = EINVAL;
2329 IPSECLOG(LOG_DEBUG, "no SP, packet discarded\n");/*XXX*/
2330 }
2331 splx(s);
2332
2333 return error;
2334 }
2335 #endif /* INET6 */
2336
2337
2338
2339 /* XXX this stuff doesn't belong here... */
2340
2341 static struct xformsw *xforms = NULL;
2342
2343 /*
2344 * Register a transform; typically at system startup.
2345 */
2346 void
2347 xform_register(struct xformsw *xsp)
2348 {
2349 xsp->xf_next = xforms;
2350 xforms = xsp;
2351 }
2352
2353 /*
2354 * Initialize transform support in an sav.
2355 */
2356 int
2357 xform_init(struct secasvar *sav, int xftype)
2358 {
2359 struct xformsw *xsp;
2360
2361 if (sav->tdb_xform != NULL) /* previously initialized */
2362 return 0;
2363 for (xsp = xforms; xsp; xsp = xsp->xf_next)
2364 if (xsp->xf_type == xftype)
2365 return (*xsp->xf_init)(sav, xsp);
2366
2367 IPSECLOG(LOG_DEBUG, "no match for xform type %d\n", xftype);
2368 return EINVAL;
2369 }
2370
2371 void
2372 nat_t_ports_get(struct mbuf *m, u_int16_t *dport, u_int16_t *sport) {
2373 struct m_tag *tag;
2374
2375 if ((tag = m_tag_find(m, PACKET_TAG_IPSEC_NAT_T_PORTS, NULL))) {
2376 *sport = ((u_int16_t *)(tag + 1))[0];
2377 *dport = ((u_int16_t *)(tag + 1))[1];
2378 } else
2379 *sport = *dport = 0;
2380 }
2381
2382 /*
2383 * XXXJRT This should be done as a protosw init call.
2384 */
2385 void
2386 ipsec_attach(void)
2387 {
2388
2389 ipsecstat_percpu = percpu_alloc(sizeof(uint64_t) * IPSEC_NSTATS);
2390
2391 sysctl_net_inet_ipsec_setup(NULL);
2392 #ifdef INET6
2393 sysctl_net_inet6_ipsec6_setup(NULL);
2394 #endif
2395
2396 ah_attach();
2397 esp_attach();
2398 ipcomp_attach();
2399 ipe4_attach();
2400 #ifdef TCP_SIGNATURE
2401 tcpsignature_attach();
2402 #endif
2403 }
2404