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