1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright 2001 Niels Provos <provos@citi.umich.edu>
5 * Copyright 2011-2018 Alexander Bluhm <bluhm@openbsd.org>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * $OpenBSD: pf_norm.c,v 1.114 2009/01/29 14:11:45 henning Exp $
29 */
30
31 #include <sys/cdefs.h>
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_pf.h"
35
36 #include <sys/param.h>
37 #include <sys/kernel.h>
38 #include <sys/lock.h>
39 #include <sys/mbuf.h>
40 #include <sys/mutex.h>
41 #include <sys/refcount.h>
42 #include <sys/socket.h>
43
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_private.h>
47 #include <net/vnet.h>
48 #include <net/pfvar.h>
49 #include <net/if_pflog.h>
50
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <netinet/ip_var.h>
54 #include <netinet6/in6_var.h>
55 #include <netinet6/nd6.h>
56 #include <netinet6/ip6_var.h>
57 #include <netinet6/scope6_var.h>
58 #include <netinet/tcp.h>
59 #include <netinet/tcp_fsm.h>
60 #include <netinet/tcp_seq.h>
61 #include <netinet/sctp_constants.h>
62 #include <netinet/sctp_header.h>
63
64 #ifdef INET6
65 #include <netinet/ip6.h>
66 #endif /* INET6 */
67
68 struct pf_frent {
69 TAILQ_ENTRY(pf_frent) fr_next;
70 struct mbuf *fe_m;
71 uint16_t fe_hdrlen; /* ipv4 header length with ip options
72 ipv6, extension, fragment header */
73 uint16_t fe_extoff; /* last extension header offset or 0 */
74 uint16_t fe_len; /* fragment length */
75 uint16_t fe_off; /* fragment offset */
76 uint16_t fe_mff; /* more fragment flag */
77 };
78
79 RB_HEAD(pf_frag_tree, pf_fragment);
80 struct pf_frnode {
81 struct pf_addr fn_src; /* ip source address */
82 struct pf_addr fn_dst; /* ip destination address */
83 sa_family_t fn_af; /* address family */
84 u_int8_t fn_proto; /* protocol for fragments in fn_tree */
85 u_int32_t fn_fragments; /* number of entries in fn_tree */
86
87 RB_ENTRY(pf_frnode) fn_entry;
88 struct pf_frag_tree fn_tree; /* matching fragments, lookup by id */
89 };
90
91 struct pf_fragment {
92 uint32_t fr_id; /* fragment id for reassemble */
93
94 /* pointers to queue element */
95 struct pf_frent *fr_firstoff[PF_FRAG_ENTRY_POINTS];
96 /* count entries between pointers */
97 uint8_t fr_entries[PF_FRAG_ENTRY_POINTS];
98 RB_ENTRY(pf_fragment) fr_entry;
99 TAILQ_ENTRY(pf_fragment) frag_next;
100 uint32_t fr_timeout;
101 TAILQ_HEAD(pf_fragq, pf_frent) fr_queue;
102 uint16_t fr_maxlen; /* maximum length of single fragment */
103 u_int16_t fr_holes; /* number of holes in the queue */
104 struct pf_frnode *fr_node; /* ip src/dst/proto/af for fragments */
105 };
106
107 VNET_DEFINE_STATIC(struct mtx, pf_frag_mtx);
108 #define V_pf_frag_mtx VNET(pf_frag_mtx)
109 #define PF_FRAG_LOCK() mtx_lock(&V_pf_frag_mtx)
110 #define PF_FRAG_UNLOCK() mtx_unlock(&V_pf_frag_mtx)
111 #define PF_FRAG_ASSERT() mtx_assert(&V_pf_frag_mtx, MA_OWNED)
112
113 VNET_DEFINE(uma_zone_t, pf_state_scrub_z); /* XXX: shared with pfsync */
114
115 VNET_DEFINE_STATIC(uma_zone_t, pf_frent_z);
116 #define V_pf_frent_z VNET(pf_frent_z)
117 VNET_DEFINE_STATIC(uma_zone_t, pf_frnode_z);
118 #define V_pf_frnode_z VNET(pf_frnode_z)
119 VNET_DEFINE_STATIC(uma_zone_t, pf_frag_z);
120 #define V_pf_frag_z VNET(pf_frag_z)
121 VNET_DEFINE(uma_zone_t, pf_anchor_z);
122 VNET_DEFINE(uma_zone_t, pf_eth_anchor_z);
123
124 TAILQ_HEAD(pf_fragqueue, pf_fragment);
125 TAILQ_HEAD(pf_cachequeue, pf_fragment);
126 RB_HEAD(pf_frnode_tree, pf_frnode);
127 VNET_DEFINE_STATIC(struct pf_fragqueue, pf_fragqueue);
128 #define V_pf_fragqueue VNET(pf_fragqueue)
129 static __inline int pf_frnode_compare(struct pf_frnode *,
130 struct pf_frnode *);
131 VNET_DEFINE_STATIC(struct pf_frnode_tree, pf_frnode_tree);
132 #define V_pf_frnode_tree VNET(pf_frnode_tree)
133 RB_PROTOTYPE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
134 RB_GENERATE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
135
136 static int pf_frag_compare(struct pf_fragment *,
137 struct pf_fragment *);
138 static RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
139 static RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
140
141 static void pf_flush_fragments(void);
142 static void pf_free_fragment(struct pf_fragment *);
143
144 static struct pf_frent *pf_create_fragment(u_short *);
145 static int pf_frent_holes(struct pf_frent *frent);
146 static struct pf_fragment *pf_find_fragment(struct pf_frnode *, u_int32_t);
147 static inline int pf_frent_index(struct pf_frent *);
148 static int pf_frent_insert(struct pf_fragment *,
149 struct pf_frent *, struct pf_frent *);
150 void pf_frent_remove(struct pf_fragment *,
151 struct pf_frent *);
152 struct pf_frent *pf_frent_previous(struct pf_fragment *,
153 struct pf_frent *);
154 static struct pf_fragment *pf_fillup_fragment(struct pf_frnode *, u_int32_t,
155 struct pf_frent *, u_short *);
156 static struct mbuf *pf_join_fragment(struct pf_fragment *);
157 #ifdef INET
158 static int pf_reassemble(struct mbuf **, u_short *);
159 #endif /* INET */
160 #ifdef INET6
161 static int pf_reassemble6(struct mbuf **,
162 struct ip6_frag *, uint16_t, uint16_t, u_short *);
163 #endif /* INET6 */
164
165 #ifdef INET
166 static void
pf_ip2key(struct ip * ip,struct pf_frnode * key)167 pf_ip2key(struct ip *ip, struct pf_frnode *key)
168 {
169
170 key->fn_src.v4 = ip->ip_src;
171 key->fn_dst.v4 = ip->ip_dst;
172 key->fn_af = AF_INET;
173 key->fn_proto = ip->ip_p;
174 }
175 #endif /* INET */
176
177 void
pf_normalize_init(void)178 pf_normalize_init(void)
179 {
180
181 V_pf_frag_z = uma_zcreate("pf frags", sizeof(struct pf_fragment),
182 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
183 V_pf_frnode_z = uma_zcreate("pf fragment node",
184 sizeof(struct pf_frnode), NULL, NULL, NULL, NULL,
185 UMA_ALIGN_PTR, 0);
186 V_pf_frent_z = uma_zcreate("pf frag entries", sizeof(struct pf_frent),
187 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
188 V_pf_state_scrub_z = uma_zcreate("pf state scrubs",
189 sizeof(struct pf_state_scrub), NULL, NULL, NULL, NULL,
190 UMA_ALIGN_PTR, 0);
191
192 mtx_init(&V_pf_frag_mtx, "pf fragments", NULL, MTX_DEF);
193
194 V_pf_limits[PF_LIMIT_FRAGS].zone = V_pf_frent_z;
195 V_pf_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT;
196 uma_zone_set_max(V_pf_frent_z, PFFRAG_FRENT_HIWAT);
197 uma_zone_set_warning(V_pf_frent_z, "PF frag entries limit reached");
198
199 TAILQ_INIT(&V_pf_fragqueue);
200 }
201
202 void
pf_normalize_cleanup(void)203 pf_normalize_cleanup(void)
204 {
205
206 uma_zdestroy(V_pf_state_scrub_z);
207 uma_zdestroy(V_pf_frent_z);
208 uma_zdestroy(V_pf_frnode_z);
209 uma_zdestroy(V_pf_frag_z);
210
211 mtx_destroy(&V_pf_frag_mtx);
212 }
213
214 static int
pf_frnode_compare(struct pf_frnode * a,struct pf_frnode * b)215 pf_frnode_compare(struct pf_frnode *a, struct pf_frnode *b)
216 {
217 int diff;
218
219 if ((diff = a->fn_proto - b->fn_proto) != 0)
220 return (diff);
221 if ((diff = a->fn_af - b->fn_af) != 0)
222 return (diff);
223 if ((diff = pf_addr_cmp(&a->fn_src, &b->fn_src, a->fn_af)) != 0)
224 return (diff);
225 if ((diff = pf_addr_cmp(&a->fn_dst, &b->fn_dst, a->fn_af)) != 0)
226 return (diff);
227 return (0);
228 }
229
230 static __inline int
pf_frag_compare(struct pf_fragment * a,struct pf_fragment * b)231 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
232 {
233 int diff;
234
235 if ((diff = a->fr_id - b->fr_id) != 0)
236 return (diff);
237
238 return (0);
239 }
240
241 void
pf_purge_expired_fragments(void)242 pf_purge_expired_fragments(void)
243 {
244 u_int32_t expire = time_uptime -
245 V_pf_default_rule.timeout[PFTM_FRAG];
246
247 pf_purge_fragments(expire);
248 }
249
250 void
pf_purge_fragments(uint32_t expire)251 pf_purge_fragments(uint32_t expire)
252 {
253 struct pf_fragment *frag;
254
255 PF_FRAG_LOCK();
256 while ((frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue)) != NULL) {
257 if (frag->fr_timeout > expire)
258 break;
259
260 DPFPRINTF(PF_DEBUG_MISC, "expiring %d(%p)",
261 frag->fr_id, frag);
262 pf_free_fragment(frag);
263 }
264
265 PF_FRAG_UNLOCK();
266 }
267
268 /*
269 * Try to flush old fragments to make space for new ones
270 */
271 static void
pf_flush_fragments(void)272 pf_flush_fragments(void)
273 {
274 struct pf_fragment *frag;
275 int goal;
276
277 PF_FRAG_ASSERT();
278
279 goal = uma_zone_get_cur(V_pf_frent_z) * 9 / 10;
280 DPFPRINTF(PF_DEBUG_MISC, "trying to free %d frag entriess", goal);
281 while (goal < uma_zone_get_cur(V_pf_frent_z)) {
282 frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue);
283 if (frag)
284 pf_free_fragment(frag);
285 else
286 break;
287 }
288 }
289
290 /*
291 * Remove a fragment from the fragment queue, free its fragment entries,
292 * and free the fragment itself.
293 */
294 static void
pf_free_fragment(struct pf_fragment * frag)295 pf_free_fragment(struct pf_fragment *frag)
296 {
297 struct pf_frent *frent;
298 struct pf_frnode *frnode;
299
300 PF_FRAG_ASSERT();
301
302 frnode = frag->fr_node;
303 RB_REMOVE(pf_frag_tree, &frnode->fn_tree, frag);
304 MPASS(frnode->fn_fragments >= 1);
305 frnode->fn_fragments--;
306 if (frnode->fn_fragments == 0) {
307 MPASS(RB_EMPTY(&frnode->fn_tree));
308 RB_REMOVE(pf_frnode_tree, &V_pf_frnode_tree, frnode);
309 uma_zfree(V_pf_frnode_z, frnode);
310 }
311
312 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
313
314 /* Free all fragment entries */
315 while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
316 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
317
318 m_freem(frent->fe_m);
319 uma_zfree(V_pf_frent_z, frent);
320 }
321
322 uma_zfree(V_pf_frag_z, frag);
323 }
324
325 static struct pf_fragment *
pf_find_fragment(struct pf_frnode * key,uint32_t id)326 pf_find_fragment(struct pf_frnode *key, uint32_t id)
327 {
328 struct pf_fragment *frag, idkey;
329 struct pf_frnode *frnode;
330
331 PF_FRAG_ASSERT();
332
333 frnode = RB_FIND(pf_frnode_tree, &V_pf_frnode_tree, key);
334 if (frnode == NULL)
335 return (NULL);
336 MPASS(frnode->fn_fragments >= 1);
337 idkey.fr_id = id;
338 frag = RB_FIND(pf_frag_tree, &frnode->fn_tree, &idkey);
339 if (frag == NULL)
340 return (NULL);
341 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
342 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
343
344 return (frag);
345 }
346
347 static struct pf_frent *
pf_create_fragment(u_short * reason)348 pf_create_fragment(u_short *reason)
349 {
350 struct pf_frent *frent;
351
352 PF_FRAG_ASSERT();
353
354 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
355 if (frent == NULL) {
356 pf_flush_fragments();
357 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
358 if (frent == NULL) {
359 REASON_SET(reason, PFRES_MEMORY);
360 return (NULL);
361 }
362 }
363
364 return (frent);
365 }
366
367 /*
368 * Calculate the additional holes that were created in the fragment
369 * queue by inserting this fragment. A fragment in the middle
370 * creates one more hole by splitting. For each connected side,
371 * it loses one hole.
372 * Fragment entry must be in the queue when calling this function.
373 */
374 static int
pf_frent_holes(struct pf_frent * frent)375 pf_frent_holes(struct pf_frent *frent)
376 {
377 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
378 struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
379 int holes = 1;
380
381 if (prev == NULL) {
382 if (frent->fe_off == 0)
383 holes--;
384 } else {
385 KASSERT(frent->fe_off != 0, ("frent->fe_off != 0"));
386 if (frent->fe_off == prev->fe_off + prev->fe_len)
387 holes--;
388 }
389 if (next == NULL) {
390 if (!frent->fe_mff)
391 holes--;
392 } else {
393 KASSERT(frent->fe_mff, ("frent->fe_mff"));
394 if (next->fe_off == frent->fe_off + frent->fe_len)
395 holes--;
396 }
397 return holes;
398 }
399
400 static inline int
pf_frent_index(struct pf_frent * frent)401 pf_frent_index(struct pf_frent *frent)
402 {
403 /*
404 * We have an array of 16 entry points to the queue. A full size
405 * 65535 octet IP packet can have 8192 fragments. So the queue
406 * traversal length is at most 512 and at most 16 entry points are
407 * checked. We need 128 additional bytes on a 64 bit architecture.
408 */
409 CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) ==
410 16 - 1);
411 CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1);
412
413 return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS);
414 }
415
416 static int
pf_frent_insert(struct pf_fragment * frag,struct pf_frent * frent,struct pf_frent * prev)417 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent,
418 struct pf_frent *prev)
419 {
420 int index;
421
422 CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff);
423
424 /*
425 * A packet has at most 65536 octets. With 16 entry points, each one
426 * spawns 4096 octets. We limit these to 64 fragments each, which
427 * means on average every fragment must have at least 64 octets.
428 */
429 index = pf_frent_index(frent);
430 if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT)
431 return ENOBUFS;
432 frag->fr_entries[index]++;
433
434 if (prev == NULL) {
435 TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
436 } else {
437 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
438 ("overlapping fragment"));
439 TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next);
440 }
441
442 if (frag->fr_firstoff[index] == NULL) {
443 KASSERT(prev == NULL || pf_frent_index(prev) < index,
444 ("prev == NULL || pf_frent_index(pref) < index"));
445 frag->fr_firstoff[index] = frent;
446 } else {
447 if (frent->fe_off < frag->fr_firstoff[index]->fe_off) {
448 KASSERT(prev == NULL || pf_frent_index(prev) < index,
449 ("prev == NULL || pf_frent_index(pref) < index"));
450 frag->fr_firstoff[index] = frent;
451 } else {
452 KASSERT(prev != NULL, ("prev != NULL"));
453 KASSERT(pf_frent_index(prev) == index,
454 ("pf_frent_index(prev) == index"));
455 }
456 }
457
458 frag->fr_holes += pf_frent_holes(frent);
459
460 return 0;
461 }
462
463 void
pf_frent_remove(struct pf_fragment * frag,struct pf_frent * frent)464 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent)
465 {
466 #ifdef INVARIANTS
467 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
468 #endif /* INVARIANTS */
469 struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
470 int index;
471
472 frag->fr_holes -= pf_frent_holes(frent);
473
474 index = pf_frent_index(frent);
475 KASSERT(frag->fr_firstoff[index] != NULL, ("frent not found"));
476 if (frag->fr_firstoff[index]->fe_off == frent->fe_off) {
477 if (next == NULL) {
478 frag->fr_firstoff[index] = NULL;
479 } else {
480 KASSERT(frent->fe_off + frent->fe_len <= next->fe_off,
481 ("overlapping fragment"));
482 if (pf_frent_index(next) == index) {
483 frag->fr_firstoff[index] = next;
484 } else {
485 frag->fr_firstoff[index] = NULL;
486 }
487 }
488 } else {
489 KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off,
490 ("frag->fr_firstoff[index]->fe_off < frent->fe_off"));
491 KASSERT(prev != NULL, ("prev != NULL"));
492 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
493 ("overlapping fragment"));
494 KASSERT(pf_frent_index(prev) == index,
495 ("pf_frent_index(prev) == index"));
496 }
497
498 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
499
500 KASSERT(frag->fr_entries[index] > 0, ("No fragments remaining"));
501 frag->fr_entries[index]--;
502 }
503
504 struct pf_frent *
pf_frent_previous(struct pf_fragment * frag,struct pf_frent * frent)505 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent)
506 {
507 struct pf_frent *prev, *next;
508 int index;
509
510 /*
511 * If there are no fragments after frag, take the final one. Assume
512 * that the global queue is not empty.
513 */
514 prev = TAILQ_LAST(&frag->fr_queue, pf_fragq);
515 KASSERT(prev != NULL, ("prev != NULL"));
516 if (prev->fe_off <= frent->fe_off)
517 return prev;
518 /*
519 * We want to find a fragment entry that is before frag, but still
520 * close to it. Find the first fragment entry that is in the same
521 * entry point or in the first entry point after that. As we have
522 * already checked that there are entries behind frag, this will
523 * succeed.
524 */
525 for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS;
526 index++) {
527 prev = frag->fr_firstoff[index];
528 if (prev != NULL)
529 break;
530 }
531 KASSERT(prev != NULL, ("prev != NULL"));
532 /*
533 * In prev we may have a fragment from the same entry point that is
534 * before frent, or one that is just one position behind frent.
535 * In the latter case, we go back one step and have the predecessor.
536 * There may be none if the new fragment will be the first one.
537 */
538 if (prev->fe_off > frent->fe_off) {
539 prev = TAILQ_PREV(prev, pf_fragq, fr_next);
540 if (prev == NULL)
541 return NULL;
542 KASSERT(prev->fe_off <= frent->fe_off,
543 ("prev->fe_off <= frent->fe_off"));
544 return prev;
545 }
546 /*
547 * In prev is the first fragment of the entry point. The offset
548 * of frag is behind it. Find the closest previous fragment.
549 */
550 for (next = TAILQ_NEXT(prev, fr_next); next != NULL;
551 next = TAILQ_NEXT(next, fr_next)) {
552 if (next->fe_off > frent->fe_off)
553 break;
554 prev = next;
555 }
556 return prev;
557 }
558
559 static struct pf_fragment *
pf_fillup_fragment(struct pf_frnode * key,uint32_t id,struct pf_frent * frent,u_short * reason)560 pf_fillup_fragment(struct pf_frnode *key, uint32_t id,
561 struct pf_frent *frent, u_short *reason)
562 {
563 struct pf_frent *after, *next, *prev;
564 struct pf_fragment *frag;
565 struct pf_frnode *frnode;
566 uint16_t total;
567
568 PF_FRAG_ASSERT();
569
570 /* No empty fragments. */
571 if (frent->fe_len == 0) {
572 DPFPRINTF(PF_DEBUG_MISC, "bad fragment: len 0");
573 goto bad_fragment;
574 }
575
576 /* All fragments are 8 byte aligned. */
577 if (frent->fe_mff && (frent->fe_len & 0x7)) {
578 DPFPRINTF(PF_DEBUG_MISC, "bad fragment: mff and len %d",
579 frent->fe_len);
580 goto bad_fragment;
581 }
582
583 /* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET. */
584 if (frent->fe_off + frent->fe_len > IP_MAXPACKET) {
585 DPFPRINTF(PF_DEBUG_MISC, "bad fragment: max packet %d",
586 frent->fe_off + frent->fe_len);
587 goto bad_fragment;
588 }
589
590 if (key->fn_af == AF_INET)
591 DPFPRINTF(PF_DEBUG_MISC, "reass frag %d @ %d-%d\n",
592 id, frent->fe_off, frent->fe_off + frent->fe_len);
593 else
594 DPFPRINTF(PF_DEBUG_MISC, "reass frag %#08x @ %d-%d",
595 id, frent->fe_off, frent->fe_off + frent->fe_len);
596
597 /* Fully buffer all of the fragments in this fragment queue. */
598 frag = pf_find_fragment(key, id);
599
600 /* Create a new reassembly queue for this packet. */
601 if (frag == NULL) {
602 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
603 if (frag == NULL) {
604 pf_flush_fragments();
605 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
606 if (frag == NULL) {
607 REASON_SET(reason, PFRES_MEMORY);
608 goto drop_fragment;
609 }
610 }
611
612 frnode = RB_FIND(pf_frnode_tree, &V_pf_frnode_tree, key);
613 if (frnode == NULL) {
614 frnode = uma_zalloc(V_pf_frnode_z, M_NOWAIT);
615 if (frnode == NULL) {
616 pf_flush_fragments();
617 frnode = uma_zalloc(V_pf_frnode_z, M_NOWAIT);
618 if (frnode == NULL) {
619 REASON_SET(reason, PFRES_MEMORY);
620 uma_zfree(V_pf_frag_z, frag);
621 goto drop_fragment;
622 }
623 }
624 *frnode = *key;
625 RB_INIT(&frnode->fn_tree);
626 frnode->fn_fragments = 0;
627 }
628 memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff));
629 memset(frag->fr_entries, 0, sizeof(frag->fr_entries));
630 frag->fr_timeout = time_uptime;
631 TAILQ_INIT(&frag->fr_queue);
632 frag->fr_maxlen = frent->fe_len;
633 frag->fr_holes = 1;
634
635 frag->fr_id = id;
636 frag->fr_node = frnode;
637 /* RB_INSERT cannot fail as pf_find_fragment() found nothing */
638 RB_INSERT(pf_frag_tree, &frnode->fn_tree, frag);
639 frnode->fn_fragments++;
640 if (frnode->fn_fragments == 1)
641 RB_INSERT(pf_frnode_tree, &V_pf_frnode_tree, frnode);
642
643 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
644
645 /* We do not have a previous fragment, cannot fail. */
646 pf_frent_insert(frag, frent, NULL);
647
648 return (frag);
649 }
650
651 KASSERT(!TAILQ_EMPTY(&frag->fr_queue), ("!TAILQ_EMPTY()->fr_queue"));
652 MPASS(frag->fr_node);
653
654 /* Remember maximum fragment len for refragmentation. */
655 if (frent->fe_len > frag->fr_maxlen)
656 frag->fr_maxlen = frent->fe_len;
657
658 /* Maximum data we have seen already. */
659 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
660 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
661
662 /* Non terminal fragments must have more fragments flag. */
663 if (frent->fe_off + frent->fe_len < total && !frent->fe_mff)
664 goto free_ipv6_fragment;
665
666 /* Check if we saw the last fragment already. */
667 if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) {
668 if (frent->fe_off + frent->fe_len > total ||
669 (frent->fe_off + frent->fe_len == total && frent->fe_mff))
670 goto free_ipv6_fragment;
671 } else {
672 if (frent->fe_off + frent->fe_len == total && !frent->fe_mff)
673 goto free_ipv6_fragment;
674 }
675
676 /* Find neighbors for newly inserted fragment */
677 prev = pf_frent_previous(frag, frent);
678 if (prev == NULL) {
679 after = TAILQ_FIRST(&frag->fr_queue);
680 KASSERT(after != NULL, ("after != NULL"));
681 } else {
682 after = TAILQ_NEXT(prev, fr_next);
683 }
684
685 if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) {
686 uint16_t precut;
687
688 if (frag->fr_node->fn_af == AF_INET6)
689 goto free_fragment;
690
691 precut = prev->fe_off + prev->fe_len - frent->fe_off;
692 if (precut >= frent->fe_len) {
693 DPFPRINTF(PF_DEBUG_MISC, "new frag overlapped");
694 goto drop_fragment;
695 }
696 DPFPRINTF(PF_DEBUG_MISC, "frag head overlap %d", precut);
697 m_adj(frent->fe_m, precut);
698 frent->fe_off += precut;
699 frent->fe_len -= precut;
700 }
701
702 for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off;
703 after = next) {
704 uint16_t aftercut;
705
706 aftercut = frent->fe_off + frent->fe_len - after->fe_off;
707 if (aftercut < after->fe_len) {
708 DPFPRINTF(PF_DEBUG_MISC, "frag tail overlap %d",
709 aftercut);
710 m_adj(after->fe_m, aftercut);
711 /* Fragment may switch queue as fe_off changes */
712 pf_frent_remove(frag, after);
713 after->fe_off += aftercut;
714 after->fe_len -= aftercut;
715 /* Insert into correct queue */
716 if (pf_frent_insert(frag, after, prev)) {
717 DPFPRINTF(PF_DEBUG_MISC,
718 "fragment requeue limit exceeded");
719 m_freem(after->fe_m);
720 uma_zfree(V_pf_frent_z, after);
721 /* There is not way to recover */
722 goto free_fragment;
723 }
724 break;
725 }
726
727 /* This fragment is completely overlapped, lose it. */
728 DPFPRINTF(PF_DEBUG_MISC, "old frag overlapped");
729 next = TAILQ_NEXT(after, fr_next);
730 pf_frent_remove(frag, after);
731 m_freem(after->fe_m);
732 uma_zfree(V_pf_frent_z, after);
733 }
734
735 /* If part of the queue gets too long, there is not way to recover. */
736 if (pf_frent_insert(frag, frent, prev)) {
737 DPFPRINTF(PF_DEBUG_MISC, "fragment queue limit exceeded");
738 goto bad_fragment;
739 }
740
741 return (frag);
742
743 free_ipv6_fragment:
744 if (frag->fr_node->fn_af == AF_INET)
745 goto bad_fragment;
746 free_fragment:
747 /*
748 * RFC 5722, Errata 3089: When reassembling an IPv6 datagram, if one
749 * or more its constituent fragments is determined to be an overlapping
750 * fragment, the entire datagram (and any constituent fragments) MUST
751 * be silently discarded.
752 */
753 DPFPRINTF(PF_DEBUG_MISC, "flush overlapping fragments");
754 pf_free_fragment(frag);
755
756 bad_fragment:
757 REASON_SET(reason, PFRES_FRAG);
758 drop_fragment:
759 uma_zfree(V_pf_frent_z, frent);
760 return (NULL);
761 }
762
763 static struct mbuf *
pf_join_fragment(struct pf_fragment * frag)764 pf_join_fragment(struct pf_fragment *frag)
765 {
766 struct mbuf *m, *m2;
767 struct pf_frent *frent;
768
769 frent = TAILQ_FIRST(&frag->fr_queue);
770 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
771
772 m = frent->fe_m;
773 if ((frent->fe_hdrlen + frent->fe_len) < m->m_pkthdr.len)
774 m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len);
775 uma_zfree(V_pf_frent_z, frent);
776 while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
777 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
778
779 m2 = frent->fe_m;
780 /* Strip off ip header. */
781 m_adj(m2, frent->fe_hdrlen);
782 /* Strip off any trailing bytes. */
783 if (frent->fe_len < m2->m_pkthdr.len)
784 m_adj(m2, frent->fe_len - m2->m_pkthdr.len);
785
786 uma_zfree(V_pf_frent_z, frent);
787 m_cat(m, m2);
788 }
789
790 /* Remove from fragment queue. */
791 pf_free_fragment(frag);
792
793 return (m);
794 }
795
796 #ifdef INET
797 static int
pf_reassemble(struct mbuf ** m0,u_short * reason)798 pf_reassemble(struct mbuf **m0, u_short *reason)
799 {
800 struct mbuf *m = *m0;
801 struct ip *ip = mtod(m, struct ip *);
802 struct pf_frent *frent;
803 struct pf_fragment *frag;
804 struct m_tag *mtag;
805 struct pf_fragment_tag *ftag;
806 struct pf_frnode key;
807 uint16_t total, hdrlen;
808 uint32_t frag_id;
809 uint16_t maxlen;
810
811 /* Get an entry for the fragment queue */
812 if ((frent = pf_create_fragment(reason)) == NULL)
813 return (PF_DROP);
814
815 frent->fe_m = m;
816 frent->fe_hdrlen = ip->ip_hl << 2;
817 frent->fe_extoff = 0;
818 frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
819 frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
820 frent->fe_mff = ntohs(ip->ip_off) & IP_MF;
821
822 pf_ip2key(ip, &key);
823
824 if ((frag = pf_fillup_fragment(&key, ip->ip_id, frent, reason)) == NULL)
825 return (PF_DROP);
826
827 /* The mbuf is part of the fragment entry, no direct free or access */
828 m = *m0 = NULL;
829
830 if (frag->fr_holes) {
831 DPFPRINTF(PF_DEBUG_MISC, "frag %d, holes %d",
832 frag->fr_id, frag->fr_holes);
833 return (PF_PASS); /* drop because *m0 is NULL, no error */
834 }
835
836 /* We have all the data */
837 frent = TAILQ_FIRST(&frag->fr_queue);
838 KASSERT(frent != NULL, ("frent != NULL"));
839 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
840 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
841 hdrlen = frent->fe_hdrlen;
842
843 maxlen = frag->fr_maxlen;
844 frag_id = frag->fr_id;
845 m = *m0 = pf_join_fragment(frag);
846 frag = NULL;
847
848 if (m->m_flags & M_PKTHDR) {
849 int plen = 0;
850 for (m = *m0; m; m = m->m_next)
851 plen += m->m_len;
852 m = *m0;
853 m->m_pkthdr.len = plen;
854 }
855
856 if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED,
857 sizeof(struct pf_fragment_tag), M_NOWAIT)) == NULL) {
858 REASON_SET(reason, PFRES_SHORT);
859 /* PF_DROP requires a valid mbuf *m0 in pf_test() */
860 return (PF_DROP);
861 }
862 ftag = (struct pf_fragment_tag *)(mtag + 1);
863 ftag->ft_hdrlen = hdrlen;
864 ftag->ft_extoff = 0;
865 ftag->ft_maxlen = maxlen;
866 ftag->ft_id = frag_id;
867 m_tag_prepend(m, mtag);
868
869 ip = mtod(m, struct ip *);
870 ip->ip_sum = pf_cksum_fixup(ip->ip_sum, ip->ip_len,
871 htons(hdrlen + total), 0);
872 ip->ip_len = htons(hdrlen + total);
873 ip->ip_sum = pf_cksum_fixup(ip->ip_sum, ip->ip_off,
874 ip->ip_off & ~(IP_MF|IP_OFFMASK), 0);
875 ip->ip_off &= ~(IP_MF|IP_OFFMASK);
876
877 if (hdrlen + total > IP_MAXPACKET) {
878 DPFPRINTF(PF_DEBUG_MISC, "drop: too big: %d", total);
879 ip->ip_len = 0;
880 REASON_SET(reason, PFRES_SHORT);
881 /* PF_DROP requires a valid mbuf *m0 in pf_test() */
882 return (PF_DROP);
883 }
884
885 DPFPRINTF(PF_DEBUG_MISC, "complete: %p(%d)", m, ntohs(ip->ip_len));
886 return (PF_PASS);
887 }
888 #endif /* INET */
889
890 #ifdef INET6
891 static int
pf_reassemble6(struct mbuf ** m0,struct ip6_frag * fraghdr,uint16_t hdrlen,uint16_t extoff,u_short * reason)892 pf_reassemble6(struct mbuf **m0, struct ip6_frag *fraghdr,
893 uint16_t hdrlen, uint16_t extoff, u_short *reason)
894 {
895 struct mbuf *m = *m0;
896 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
897 struct pf_frent *frent;
898 struct pf_fragment *frag;
899 struct pf_frnode key;
900 struct m_tag *mtag;
901 struct pf_fragment_tag *ftag;
902 int off;
903 uint32_t frag_id;
904 uint16_t total, maxlen;
905 uint8_t proto;
906
907 PF_FRAG_LOCK();
908
909 /* Get an entry for the fragment queue. */
910 if ((frent = pf_create_fragment(reason)) == NULL) {
911 PF_FRAG_UNLOCK();
912 return (PF_DROP);
913 }
914
915 frent->fe_m = m;
916 frent->fe_hdrlen = hdrlen;
917 frent->fe_extoff = extoff;
918 frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen;
919 frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK);
920 frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG;
921
922 key.fn_src.v6 = ip6->ip6_src;
923 key.fn_dst.v6 = ip6->ip6_dst;
924 key.fn_af = AF_INET6;
925 /* Only the first fragment's protocol is relevant. */
926 key.fn_proto = 0;
927
928 if ((frag = pf_fillup_fragment(&key, fraghdr->ip6f_ident, frent, reason)) == NULL) {
929 PF_FRAG_UNLOCK();
930 return (PF_DROP);
931 }
932
933 /* The mbuf is part of the fragment entry, no direct free or access. */
934 m = *m0 = NULL;
935
936 if (frag->fr_holes) {
937 DPFPRINTF(PF_DEBUG_MISC, "frag %d, holes %d", frag->fr_id,
938 frag->fr_holes);
939 PF_FRAG_UNLOCK();
940 return (PF_PASS); /* Drop because *m0 is NULL, no error. */
941 }
942
943 /* We have all the data. */
944 frent = TAILQ_FIRST(&frag->fr_queue);
945 KASSERT(frent != NULL, ("frent != NULL"));
946 extoff = frent->fe_extoff;
947 maxlen = frag->fr_maxlen;
948 frag_id = frag->fr_id;
949 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
950 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
951 hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
952
953 m = *m0 = pf_join_fragment(frag);
954 frag = NULL;
955
956 PF_FRAG_UNLOCK();
957
958 /* Take protocol from first fragment header. */
959 m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off);
960 KASSERT(m, ("%s: short mbuf chain", __func__));
961 proto = *(mtod(m, uint8_t *) + off);
962 m = *m0;
963
964 /* Delete frag6 header */
965 if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0)
966 goto fail;
967
968 if (m->m_flags & M_PKTHDR) {
969 int plen = 0;
970 for (m = *m0; m; m = m->m_next)
971 plen += m->m_len;
972 m = *m0;
973 m->m_pkthdr.len = plen;
974 }
975
976 if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED,
977 sizeof(struct pf_fragment_tag), M_NOWAIT)) == NULL)
978 goto fail;
979 ftag = (struct pf_fragment_tag *)(mtag + 1);
980 ftag->ft_hdrlen = hdrlen;
981 ftag->ft_extoff = extoff;
982 ftag->ft_maxlen = maxlen;
983 ftag->ft_id = frag_id;
984 m_tag_prepend(m, mtag);
985
986 ip6 = mtod(m, struct ip6_hdr *);
987 ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
988 if (extoff) {
989 /* Write protocol into next field of last extension header. */
990 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
991 &off);
992 KASSERT(m, ("%s: short mbuf chain", __func__));
993 *(mtod(m, char *) + off) = proto;
994 m = *m0;
995 } else
996 ip6->ip6_nxt = proto;
997
998 if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
999 DPFPRINTF(PF_DEBUG_MISC, "drop: too big: %d", total);
1000 ip6->ip6_plen = 0;
1001 REASON_SET(reason, PFRES_SHORT);
1002 /* PF_DROP requires a valid mbuf *m0 in pf_test6(). */
1003 return (PF_DROP);
1004 }
1005
1006 DPFPRINTF(PF_DEBUG_MISC, "complete: %p(%d)", m,
1007 ntohs(ip6->ip6_plen));
1008 return (PF_PASS);
1009
1010 fail:
1011 REASON_SET(reason, PFRES_MEMORY);
1012 /* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */
1013 return (PF_DROP);
1014 }
1015 #endif /* INET6 */
1016
1017 #ifdef INET6
1018 int
pf_max_frag_size(struct mbuf * m)1019 pf_max_frag_size(struct mbuf *m)
1020 {
1021 struct m_tag *tag;
1022 struct pf_fragment_tag *ftag;
1023
1024 tag = m_tag_find(m, PACKET_TAG_PF_REASSEMBLED, NULL);
1025 if (tag == NULL)
1026 return (m->m_pkthdr.len);
1027
1028 ftag = (struct pf_fragment_tag *)(tag + 1);
1029
1030 return (ftag->ft_maxlen);
1031 }
1032
1033 int
pf_refragment6(struct ifnet * ifp,struct mbuf ** m0,struct m_tag * mtag,struct ifnet * rt,bool forward)1034 pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag,
1035 struct ifnet *rt, bool forward)
1036 {
1037 struct mbuf *m = *m0, *t;
1038 struct ip6_hdr *hdr;
1039 struct pf_fragment_tag *ftag = (struct pf_fragment_tag *)(mtag + 1);
1040 struct pf_pdesc pd;
1041 uint32_t frag_id;
1042 uint16_t hdrlen, extoff, maxlen;
1043 uint8_t proto;
1044 int error, action;
1045
1046 hdrlen = ftag->ft_hdrlen;
1047 extoff = ftag->ft_extoff;
1048 maxlen = ftag->ft_maxlen;
1049 frag_id = ftag->ft_id;
1050 m_tag_delete(m, mtag);
1051 mtag = NULL;
1052 ftag = NULL;
1053
1054 if (extoff) {
1055 int off;
1056
1057 /* Use protocol from next field of last extension header */
1058 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
1059 &off);
1060 KASSERT((m != NULL), ("pf_refragment6: short mbuf chain"));
1061 proto = *(mtod(m, uint8_t *) + off);
1062 *(mtod(m, char *) + off) = IPPROTO_FRAGMENT;
1063 m = *m0;
1064 } else {
1065 hdr = mtod(m, struct ip6_hdr *);
1066 proto = hdr->ip6_nxt;
1067 hdr->ip6_nxt = IPPROTO_FRAGMENT;
1068 }
1069
1070 /* In case of link-local traffic we'll need a scope set. */
1071 hdr = mtod(m, struct ip6_hdr *);
1072
1073 in6_setscope(&hdr->ip6_src, ifp, NULL);
1074 in6_setscope(&hdr->ip6_dst, ifp, NULL);
1075
1076 /* The MTU must be a multiple of 8 bytes, or we risk doing the
1077 * fragmentation wrong. */
1078 maxlen = maxlen & ~7;
1079
1080 /*
1081 * Maxlen may be less than 8 if there was only a single
1082 * fragment. As it was fragmented before, add a fragment
1083 * header also for a single fragment. If total or maxlen
1084 * is less than 8, ip6_fragment() will return EMSGSIZE and
1085 * we drop the packet.
1086 */
1087 error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
1088 m = (*m0)->m_nextpkt;
1089 (*m0)->m_nextpkt = NULL;
1090 if (error == 0) {
1091 /* The first mbuf contains the unfragmented packet. */
1092 m_freem(*m0);
1093 *m0 = NULL;
1094 action = PF_PASS;
1095 } else {
1096 /* Drop expects an mbuf to free. */
1097 DPFPRINTF(PF_DEBUG_MISC, "refragment error %d", error);
1098 action = PF_DROP;
1099 }
1100 for (; m; m = t) {
1101 t = m->m_nextpkt;
1102 m->m_nextpkt = NULL;
1103 m->m_flags |= M_SKIP_FIREWALL;
1104 memset(&pd, 0, sizeof(pd));
1105 pd.pf_mtag = pf_find_mtag(m);
1106 if (error != 0) {
1107 m_freem(m);
1108 continue;
1109 }
1110 if (rt != NULL) {
1111 struct sockaddr_in6 dst;
1112 hdr = mtod(m, struct ip6_hdr *);
1113
1114 bzero(&dst, sizeof(dst));
1115 dst.sin6_family = AF_INET6;
1116 dst.sin6_len = sizeof(dst);
1117 dst.sin6_addr = hdr->ip6_dst;
1118
1119 if (m->m_pkthdr.len <= if_getmtu(ifp)) {
1120 nd6_output_ifp(rt, rt, m, &dst, NULL);
1121 } else {
1122 in6_ifstat_inc(ifp, ifs6_in_toobig);
1123 icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0,
1124 if_getmtu(ifp));
1125 }
1126 } else if (forward) {
1127 MPASS(m->m_pkthdr.rcvif != NULL);
1128 ip6_forward(m, 0);
1129 } else {
1130 (void)ip6_output(m, NULL, NULL, 0, NULL, NULL,
1131 NULL);
1132 }
1133 }
1134
1135 return (action);
1136 }
1137 #endif /* INET6 */
1138
1139 #ifdef INET
1140 int
pf_normalize_ip(u_short * reason,struct pf_pdesc * pd)1141 pf_normalize_ip(u_short *reason, struct pf_pdesc *pd)
1142 {
1143 struct pf_krule *r;
1144 struct ip *h = mtod(pd->m, struct ip *);
1145 int mff = (ntohs(h->ip_off) & IP_MF);
1146 int hlen = h->ip_hl << 2;
1147 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1148 u_int16_t max;
1149 int ip_len;
1150 int tag = -1;
1151 int verdict;
1152 bool scrub_compat;
1153
1154 PF_RULES_RASSERT();
1155
1156 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1157 /*
1158 * Check if there are any scrub rules, matching or not.
1159 * Lack of scrub rules means:
1160 * - enforced packet normalization operation just like in OpenBSD
1161 * - fragment reassembly depends on V_pf_status.reass
1162 * With scrub rules:
1163 * - packet normalization is performed if there is a matching scrub rule
1164 * - fragment reassembly is performed if the matching rule has no
1165 * PFRULE_FRAGMENT_NOREASS flag
1166 */
1167 scrub_compat = (r != NULL);
1168 while (r != NULL) {
1169 pf_counter_u64_add(&r->evaluations, 1);
1170 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
1171 r = r->skip[PF_SKIP_IFP];
1172 else if (r->direction && r->direction != pd->dir)
1173 r = r->skip[PF_SKIP_DIR];
1174 else if (r->af && r->af != AF_INET)
1175 r = r->skip[PF_SKIP_AF];
1176 else if (r->proto && r->proto != h->ip_p)
1177 r = r->skip[PF_SKIP_PROTO];
1178 else if (PF_MISMATCHAW(&r->src.addr,
1179 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
1180 r->src.neg, pd->kif, M_GETFIB(pd->m)))
1181 r = r->skip[PF_SKIP_SRC_ADDR];
1182 else if (PF_MISMATCHAW(&r->dst.addr,
1183 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
1184 r->dst.neg, NULL, M_GETFIB(pd->m)))
1185 r = r->skip[PF_SKIP_DST_ADDR];
1186 else if (r->match_tag && !pf_match_tag(pd->m, r, &tag,
1187 pd->pf_mtag ? pd->pf_mtag->tag : 0))
1188 r = TAILQ_NEXT(r, entries);
1189 else
1190 break;
1191 }
1192
1193 if (scrub_compat) {
1194 /* With scrub rules present IPv4 normalization happens only
1195 * if one of rules has matched and it's not a "no scrub" rule */
1196 if (r == NULL || r->action == PF_NOSCRUB)
1197 return (PF_PASS);
1198
1199 pf_counter_u64_critical_enter();
1200 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
1201 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
1202 pf_counter_u64_critical_exit();
1203 pf_rule_to_actions(r, &pd->act);
1204 }
1205
1206 /* Check for illegal packets */
1207 if (hlen < (int)sizeof(struct ip)) {
1208 REASON_SET(reason, PFRES_NORM);
1209 goto drop;
1210 }
1211
1212 if (hlen > ntohs(h->ip_len)) {
1213 REASON_SET(reason, PFRES_NORM);
1214 goto drop;
1215 }
1216
1217 /* Clear IP_DF if the rule uses the no-df option or we're in no-df mode */
1218 if (((!scrub_compat && V_pf_status.reass & PF_REASS_NODF) ||
1219 (r != NULL && r->rule_flag & PFRULE_NODF)) &&
1220 (h->ip_off & htons(IP_DF))
1221 ) {
1222 u_int16_t ip_off = h->ip_off;
1223
1224 h->ip_off &= htons(~IP_DF);
1225 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1226 }
1227
1228 /* We will need other tests here */
1229 if (!fragoff && !mff)
1230 goto no_fragment;
1231
1232 /* We're dealing with a fragment now. Don't allow fragments
1233 * with IP_DF to enter the cache. If the flag was cleared by
1234 * no-df above, fine. Otherwise drop it.
1235 */
1236 if (h->ip_off & htons(IP_DF)) {
1237 DPFPRINTF(PF_DEBUG_MISC, "IP_DF");
1238 goto bad;
1239 }
1240
1241 ip_len = ntohs(h->ip_len) - hlen;
1242
1243 /* All fragments are 8 byte aligned */
1244 if (mff && (ip_len & 0x7)) {
1245 DPFPRINTF(PF_DEBUG_MISC, "mff and %d", ip_len);
1246 goto bad;
1247 }
1248
1249 /* Respect maximum length */
1250 if (fragoff + ip_len > IP_MAXPACKET) {
1251 DPFPRINTF(PF_DEBUG_MISC, "max packet %d", fragoff + ip_len);
1252 goto bad;
1253 }
1254
1255 if ((!scrub_compat && V_pf_status.reass) ||
1256 (r != NULL && !(r->rule_flag & PFRULE_FRAGMENT_NOREASS))
1257 ) {
1258 max = fragoff + ip_len;
1259
1260 /* Fully buffer all of the fragments
1261 * Might return a completely reassembled mbuf, or NULL */
1262 PF_FRAG_LOCK();
1263 DPFPRINTF(PF_DEBUG_MISC, "reass frag %d @ %d-%d",
1264 h->ip_id, fragoff, max);
1265 verdict = pf_reassemble(&pd->m, reason);
1266 PF_FRAG_UNLOCK();
1267
1268 if (verdict != PF_PASS)
1269 return (PF_DROP);
1270
1271 if (pd->m == NULL)
1272 return (PF_DROP);
1273
1274 h = mtod(pd->m, struct ip *);
1275 pd->tot_len = htons(h->ip_len);
1276
1277 no_fragment:
1278 /* At this point, only IP_DF is allowed in ip_off */
1279 if (h->ip_off & ~htons(IP_DF)) {
1280 u_int16_t ip_off = h->ip_off;
1281
1282 h->ip_off &= htons(IP_DF);
1283 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1284 }
1285 }
1286
1287 return (PF_PASS);
1288
1289 bad:
1290 DPFPRINTF(PF_DEBUG_MISC, "dropping bad fragment");
1291 REASON_SET(reason, PFRES_FRAG);
1292 drop:
1293 if (r != NULL && r->log)
1294 PFLOG_PACKET(PF_DROP, *reason, r, NULL, NULL, pd, 1, NULL);
1295
1296 return (PF_DROP);
1297 }
1298 #endif
1299
1300 #ifdef INET6
1301 int
pf_normalize_ip6(int off,u_short * reason,struct pf_pdesc * pd)1302 pf_normalize_ip6(int off, u_short *reason,
1303 struct pf_pdesc *pd)
1304 {
1305 struct pf_krule *r;
1306 struct ip6_hdr *h;
1307 struct ip6_frag frag;
1308 bool scrub_compat;
1309
1310 PF_RULES_RASSERT();
1311
1312 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1313 /*
1314 * Check if there are any scrub rules, matching or not.
1315 * Lack of scrub rules means:
1316 * - enforced packet normalization operation just like in OpenBSD
1317 * With scrub rules:
1318 * - packet normalization is performed if there is a matching scrub rule
1319 * XXX: Fragment reassembly always performed for IPv6!
1320 */
1321 scrub_compat = (r != NULL);
1322 while (r != NULL) {
1323 pf_counter_u64_add(&r->evaluations, 1);
1324 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
1325 r = r->skip[PF_SKIP_IFP];
1326 else if (r->direction && r->direction != pd->dir)
1327 r = r->skip[PF_SKIP_DIR];
1328 else if (r->af && r->af != AF_INET6)
1329 r = r->skip[PF_SKIP_AF];
1330 else if (r->proto && r->proto != pd->proto)
1331 r = r->skip[PF_SKIP_PROTO];
1332 else if (PF_MISMATCHAW(&r->src.addr,
1333 (struct pf_addr *)&pd->src, AF_INET6,
1334 r->src.neg, pd->kif, M_GETFIB(pd->m)))
1335 r = r->skip[PF_SKIP_SRC_ADDR];
1336 else if (PF_MISMATCHAW(&r->dst.addr,
1337 (struct pf_addr *)&pd->dst, AF_INET6,
1338 r->dst.neg, NULL, M_GETFIB(pd->m)))
1339 r = r->skip[PF_SKIP_DST_ADDR];
1340 else
1341 break;
1342 }
1343
1344 if (scrub_compat) {
1345 /* With scrub rules present IPv6 normalization happens only
1346 * if one of rules has matched and it's not a "no scrub" rule */
1347 if (r == NULL || r->action == PF_NOSCRUB)
1348 return (PF_PASS);
1349
1350 pf_counter_u64_critical_enter();
1351 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
1352 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
1353 pf_counter_u64_critical_exit();
1354 pf_rule_to_actions(r, &pd->act);
1355 }
1356
1357 if (!pf_pull_hdr(pd->m, off, &frag, sizeof(frag), NULL, reason, AF_INET6))
1358 return (PF_DROP);
1359
1360 /* Offset now points to data portion. */
1361 off += sizeof(frag);
1362
1363 if (pd->virtual_proto == PF_VPROTO_FRAGMENT) {
1364 /* Returns PF_DROP or *m0 is NULL or completely reassembled
1365 * mbuf. */
1366 if (pf_reassemble6(&pd->m, &frag, off, pd->extoff, reason) != PF_PASS)
1367 return (PF_DROP);
1368 if (pd->m == NULL)
1369 return (PF_DROP);
1370 h = mtod(pd->m, struct ip6_hdr *);
1371 pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
1372 }
1373
1374 return (PF_PASS);
1375 }
1376 #endif /* INET6 */
1377
1378 int
pf_normalize_tcp(struct pf_pdesc * pd)1379 pf_normalize_tcp(struct pf_pdesc *pd)
1380 {
1381 struct pf_krule *r, *rm = NULL;
1382 struct tcphdr *th = &pd->hdr.tcp;
1383 int rewrite = 0;
1384 u_short reason;
1385 u_int16_t flags;
1386 sa_family_t af = pd->af;
1387 int srs;
1388
1389 PF_RULES_RASSERT();
1390
1391 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1392 /* Check if there any scrub rules. Lack of scrub rules means enforced
1393 * packet normalization operation just like in OpenBSD. */
1394 srs = (r != NULL);
1395 while (r != NULL) {
1396 pf_counter_u64_add(&r->evaluations, 1);
1397 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
1398 r = r->skip[PF_SKIP_IFP];
1399 else if (r->direction && r->direction != pd->dir)
1400 r = r->skip[PF_SKIP_DIR];
1401 else if (r->af && r->af != af)
1402 r = r->skip[PF_SKIP_AF];
1403 else if (r->proto && r->proto != pd->proto)
1404 r = r->skip[PF_SKIP_PROTO];
1405 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1406 r->src.neg, pd->kif, M_GETFIB(pd->m)))
1407 r = r->skip[PF_SKIP_SRC_ADDR];
1408 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1409 r->src.port[0], r->src.port[1], th->th_sport))
1410 r = r->skip[PF_SKIP_SRC_PORT];
1411 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1412 r->dst.neg, NULL, M_GETFIB(pd->m)))
1413 r = r->skip[PF_SKIP_DST_ADDR];
1414 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1415 r->dst.port[0], r->dst.port[1], th->th_dport))
1416 r = r->skip[PF_SKIP_DST_PORT];
1417 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1418 pf_osfp_fingerprint(pd, th),
1419 r->os_fingerprint))
1420 r = TAILQ_NEXT(r, entries);
1421 else {
1422 rm = r;
1423 break;
1424 }
1425 }
1426
1427 if (srs) {
1428 /* With scrub rules present TCP normalization happens only
1429 * if one of rules has matched and it's not a "no scrub" rule */
1430 if (rm == NULL || rm->action == PF_NOSCRUB)
1431 return (PF_PASS);
1432
1433 pf_counter_u64_critical_enter();
1434 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
1435 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
1436 pf_counter_u64_critical_exit();
1437 pf_rule_to_actions(rm, &pd->act);
1438 }
1439
1440 if (rm && rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1441 pd->flags |= PFDESC_TCP_NORM;
1442
1443 flags = tcp_get_flags(th);
1444 if (flags & TH_SYN) {
1445 /* Illegal packet */
1446 if (flags & TH_RST)
1447 goto tcp_drop;
1448
1449 if (flags & TH_FIN)
1450 goto tcp_drop;
1451 } else {
1452 /* Illegal packet */
1453 if (!(flags & (TH_ACK|TH_RST)))
1454 goto tcp_drop;
1455 }
1456
1457 if (!(flags & TH_ACK)) {
1458 /* These flags are only valid if ACK is set */
1459 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1460 goto tcp_drop;
1461 }
1462
1463 /* Check for illegal header length */
1464 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1465 goto tcp_drop;
1466
1467 /* If flags changed, or reserved data set, then adjust */
1468 if (flags != tcp_get_flags(th) ||
1469 (tcp_get_flags(th) & (TH_RES1|TH_RES2|TH_RES2)) != 0) {
1470 u_int16_t ov, nv;
1471
1472 ov = *(u_int16_t *)(&th->th_ack + 1);
1473 flags &= ~(TH_RES1 | TH_RES2 | TH_RES3);
1474 tcp_set_flags(th, flags);
1475 nv = *(u_int16_t *)(&th->th_ack + 1);
1476
1477 th->th_sum = pf_proto_cksum_fixup(pd->m, th->th_sum, ov, nv, 0);
1478 rewrite = 1;
1479 }
1480
1481 /* Remove urgent pointer, if TH_URG is not set */
1482 if (!(flags & TH_URG) && th->th_urp) {
1483 th->th_sum = pf_proto_cksum_fixup(pd->m, th->th_sum, th->th_urp,
1484 0, 0);
1485 th->th_urp = 0;
1486 rewrite = 1;
1487 }
1488
1489 /* copy back packet headers if we sanitized */
1490 if (rewrite)
1491 m_copyback(pd->m, pd->off, sizeof(*th), (caddr_t)th);
1492
1493 return (PF_PASS);
1494
1495 tcp_drop:
1496 REASON_SET(&reason, PFRES_NORM);
1497 if (rm != NULL && r->log)
1498 PFLOG_PACKET(PF_DROP, reason, r, NULL, NULL, pd, 1, NULL);
1499 return (PF_DROP);
1500 }
1501
1502 int
pf_normalize_tcp_init(struct pf_pdesc * pd,struct tcphdr * th,struct pf_state_peer * src)1503 pf_normalize_tcp_init(struct pf_pdesc *pd, struct tcphdr *th,
1504 struct pf_state_peer *src)
1505 {
1506 u_int32_t tsval, tsecr;
1507 int olen;
1508 uint8_t opts[MAX_TCPOPTLEN], *opt;
1509
1510 KASSERT((src->scrub == NULL),
1511 ("pf_normalize_tcp_init: src->scrub != NULL"));
1512
1513 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1514 if (src->scrub == NULL)
1515 return (1);
1516
1517 switch (pd->af) {
1518 #ifdef INET
1519 case AF_INET: {
1520 struct ip *h = mtod(pd->m, struct ip *);
1521 src->scrub->pfss_ttl = h->ip_ttl;
1522 break;
1523 }
1524 #endif /* INET */
1525 #ifdef INET6
1526 case AF_INET6: {
1527 struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1528 src->scrub->pfss_ttl = h->ip6_hlim;
1529 break;
1530 }
1531 #endif /* INET6 */
1532 default:
1533 unhandled_af(pd->af);
1534 }
1535
1536 /*
1537 * All normalizations below are only begun if we see the start of
1538 * the connections. They must all set an enabled bit in pfss_flags
1539 */
1540 if ((tcp_get_flags(th) & TH_SYN) == 0)
1541 return (0);
1542
1543 olen = (th->th_off << 2) - sizeof(*th);
1544 if (olen < TCPOLEN_TIMESTAMP || !pf_pull_hdr(pd->m,
1545 pd->off + sizeof(*th), opts, olen, NULL, NULL, pd->af))
1546 return (0);
1547
1548 opt = opts;
1549 while ((opt = pf_find_tcpopt(opt, opts, olen,
1550 TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1551 src->scrub->pfss_flags |= PFSS_TIMESTAMP;
1552 src->scrub->pfss_ts_mod = arc4random();
1553 /* note PFSS_PAWS not set yet */
1554 memcpy(&tsval, &opt[2], sizeof(u_int32_t));
1555 memcpy(&tsecr, &opt[6], sizeof(u_int32_t));
1556 src->scrub->pfss_tsval0 = ntohl(tsval);
1557 src->scrub->pfss_tsval = ntohl(tsval);
1558 src->scrub->pfss_tsecr = ntohl(tsecr);
1559 getmicrouptime(&src->scrub->pfss_last);
1560
1561 opt += opt[1];
1562 }
1563
1564 return (0);
1565 }
1566
1567 void
pf_normalize_tcp_cleanup(struct pf_kstate * state)1568 pf_normalize_tcp_cleanup(struct pf_kstate *state)
1569 {
1570 /* XXX Note: this also cleans up SCTP. */
1571 uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1572 uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1573
1574 /* Someday... flush the TCP segment reassembly descriptors. */
1575 }
1576 int
pf_normalize_sctp_init(struct pf_pdesc * pd,struct pf_state_peer * src,struct pf_state_peer * dst)1577 pf_normalize_sctp_init(struct pf_pdesc *pd, struct pf_state_peer *src,
1578 struct pf_state_peer *dst)
1579 {
1580 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1581 if (src->scrub == NULL)
1582 return (1);
1583
1584 dst->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1585 if (dst->scrub == NULL) {
1586 uma_zfree(V_pf_state_scrub_z, src);
1587 return (1);
1588 }
1589
1590 dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
1591
1592 return (0);
1593 }
1594
1595 int
pf_normalize_tcp_stateful(struct pf_pdesc * pd,u_short * reason,struct tcphdr * th,struct pf_kstate * state,struct pf_state_peer * src,struct pf_state_peer * dst,int * writeback)1596 pf_normalize_tcp_stateful(struct pf_pdesc *pd,
1597 u_short *reason, struct tcphdr *th, struct pf_kstate *state,
1598 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1599 {
1600 struct timeval uptime;
1601 u_int tsval_from_last;
1602 uint32_t tsval, tsecr;
1603 int copyback = 0;
1604 int got_ts = 0;
1605 int olen;
1606 uint8_t opts[MAX_TCPOPTLEN], *opt;
1607
1608 KASSERT((src->scrub || dst->scrub),
1609 ("%s: src->scrub && dst->scrub!", __func__));
1610
1611 /*
1612 * Enforce the minimum TTL seen for this connection. Negate a common
1613 * technique to evade an intrusion detection system and confuse
1614 * firewall state code.
1615 */
1616 switch (pd->af) {
1617 #ifdef INET
1618 case AF_INET: {
1619 if (src->scrub) {
1620 struct ip *h = mtod(pd->m, struct ip *);
1621 if (h->ip_ttl > src->scrub->pfss_ttl)
1622 src->scrub->pfss_ttl = h->ip_ttl;
1623 h->ip_ttl = src->scrub->pfss_ttl;
1624 }
1625 break;
1626 }
1627 #endif /* INET */
1628 #ifdef INET6
1629 case AF_INET6: {
1630 if (src->scrub) {
1631 struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1632 if (h->ip6_hlim > src->scrub->pfss_ttl)
1633 src->scrub->pfss_ttl = h->ip6_hlim;
1634 h->ip6_hlim = src->scrub->pfss_ttl;
1635 }
1636 break;
1637 }
1638 #endif /* INET6 */
1639 default:
1640 unhandled_af(pd->af);
1641 }
1642
1643 olen = (th->th_off << 2) - sizeof(*th);
1644
1645 if (olen >= TCPOLEN_TIMESTAMP &&
1646 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1647 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1648 pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, olen, NULL, NULL, pd->af)) {
1649 /* Modulate the timestamps. Can be used for NAT detection, OS
1650 * uptime determination or reboot detection.
1651 */
1652 opt = opts;
1653 while ((opt = pf_find_tcpopt(opt, opts, olen,
1654 TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1655 uint8_t *ts = opt + 2;
1656 uint8_t *tsr = opt + 6;
1657
1658 if (got_ts) {
1659 /* Huh? Multiple timestamps!? */
1660 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1661 printf("pf: %s: multiple TS??", __func__);
1662 pf_print_state(state);
1663 printf("\n");
1664 }
1665 REASON_SET(reason, PFRES_TS);
1666 return (PF_DROP);
1667 }
1668
1669 memcpy(&tsval, ts, sizeof(u_int32_t));
1670 memcpy(&tsecr, tsr, sizeof(u_int32_t));
1671
1672 /* modulate TS */
1673 if (tsval && src->scrub &&
1674 (src->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1675 /* tsval used further on */
1676 tsval = ntohl(tsval);
1677 pf_patch_32(pd,
1678 ts, htonl(tsval + src->scrub->pfss_ts_mod),
1679 PF_ALGNMNT(ts - opts));
1680 copyback = 1;
1681 }
1682
1683 /* modulate TS reply if any (!0) */
1684 if (tsecr && dst->scrub &&
1685 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1686 /* tsecr used further on */
1687 tsecr = ntohl(tsecr) - dst->scrub->pfss_ts_mod;
1688 pf_patch_32(pd, tsr, htonl(tsecr),
1689 PF_ALGNMNT(tsr - opts));
1690 copyback = 1;
1691 }
1692
1693 got_ts = 1;
1694 opt += opt[1];
1695 }
1696
1697 if (copyback) {
1698 /* Copyback the options, caller copys back header */
1699 *writeback = 1;
1700 m_copyback(pd->m, pd->off + sizeof(*th), olen, opts);
1701 }
1702 }
1703
1704 /*
1705 * Must invalidate PAWS checks on connections idle for too long.
1706 * The fastest allowed timestamp clock is 1ms. That turns out to
1707 * be about 24 days before it wraps. XXX Right now our lowerbound
1708 * TS echo check only works for the first 12 days of a connection
1709 * when the TS has exhausted half its 32bit space
1710 */
1711 #define TS_MAX_IDLE (24*24*60*60)
1712 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1713
1714 getmicrouptime(&uptime);
1715 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1716 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1717 time_uptime - (state->creation / 1000) > TS_MAX_CONN)) {
1718 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1719 DPFPRINTF(PF_DEBUG_MISC, "src idled out of PAWS");
1720 pf_print_state(state);
1721 printf("\n");
1722 }
1723 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1724 | PFSS_PAWS_IDLED;
1725 }
1726 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1727 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1728 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1729 DPFPRINTF(PF_DEBUG_MISC, "dst idled out of PAWS");
1730 pf_print_state(state);
1731 printf("\n");
1732 }
1733 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1734 | PFSS_PAWS_IDLED;
1735 }
1736
1737 if (got_ts && src->scrub && dst->scrub &&
1738 (src->scrub->pfss_flags & PFSS_PAWS) &&
1739 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1740 /* Validate that the timestamps are "in-window".
1741 * RFC1323 describes TCP Timestamp options that allow
1742 * measurement of RTT (round trip time) and PAWS
1743 * (protection against wrapped sequence numbers). PAWS
1744 * gives us a set of rules for rejecting packets on
1745 * long fat pipes (packets that were somehow delayed
1746 * in transit longer than the time it took to send the
1747 * full TCP sequence space of 4Gb). We can use these
1748 * rules and infer a few others that will let us treat
1749 * the 32bit timestamp and the 32bit echoed timestamp
1750 * as sequence numbers to prevent a blind attacker from
1751 * inserting packets into a connection.
1752 *
1753 * RFC1323 tells us:
1754 * - The timestamp on this packet must be greater than
1755 * or equal to the last value echoed by the other
1756 * endpoint. The RFC says those will be discarded
1757 * since it is a dup that has already been acked.
1758 * This gives us a lowerbound on the timestamp.
1759 * timestamp >= other last echoed timestamp
1760 * - The timestamp will be less than or equal to
1761 * the last timestamp plus the time between the
1762 * last packet and now. The RFC defines the max
1763 * clock rate as 1ms. We will allow clocks to be
1764 * up to 10% fast and will allow a total difference
1765 * or 30 seconds due to a route change. And this
1766 * gives us an upperbound on the timestamp.
1767 * timestamp <= last timestamp + max ticks
1768 * We have to be careful here. Windows will send an
1769 * initial timestamp of zero and then initialize it
1770 * to a random value after the 3whs; presumably to
1771 * avoid a DoS by having to call an expensive RNG
1772 * during a SYN flood. Proof MS has at least one
1773 * good security geek.
1774 *
1775 * - The TCP timestamp option must also echo the other
1776 * endpoints timestamp. The timestamp echoed is the
1777 * one carried on the earliest unacknowledged segment
1778 * on the left edge of the sequence window. The RFC
1779 * states that the host will reject any echoed
1780 * timestamps that were larger than any ever sent.
1781 * This gives us an upperbound on the TS echo.
1782 * tescr <= largest_tsval
1783 * - The lowerbound on the TS echo is a little more
1784 * tricky to determine. The other endpoint's echoed
1785 * values will not decrease. But there may be
1786 * network conditions that re-order packets and
1787 * cause our view of them to decrease. For now the
1788 * only lowerbound we can safely determine is that
1789 * the TS echo will never be less than the original
1790 * TS. XXX There is probably a better lowerbound.
1791 * Remove TS_MAX_CONN with better lowerbound check.
1792 * tescr >= other original TS
1793 *
1794 * It is also important to note that the fastest
1795 * timestamp clock of 1ms will wrap its 32bit space in
1796 * 24 days. So we just disable TS checking after 24
1797 * days of idle time. We actually must use a 12d
1798 * connection limit until we can come up with a better
1799 * lowerbound to the TS echo check.
1800 */
1801 struct timeval delta_ts;
1802 int ts_fudge;
1803
1804 /*
1805 * PFTM_TS_DIFF is how many seconds of leeway to allow
1806 * a host's timestamp. This can happen if the previous
1807 * packet got delayed in transit for much longer than
1808 * this packet.
1809 */
1810 if ((ts_fudge = state->rule->timeout[PFTM_TS_DIFF]) == 0)
1811 ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1812
1813 /* Calculate max ticks since the last timestamp */
1814 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1815 #define TS_MICROSECS 1000000 /* microseconds per second */
1816 delta_ts = uptime;
1817 timevalsub(&delta_ts, &src->scrub->pfss_last);
1818 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1819 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1820
1821 if ((src->state >= TCPS_ESTABLISHED &&
1822 dst->state >= TCPS_ESTABLISHED) &&
1823 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1824 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1825 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1826 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1827 /* Bad RFC1323 implementation or an insertion attack.
1828 *
1829 * - Solaris 2.6 and 2.7 are known to send another ACK
1830 * after the FIN,FIN|ACK,ACK closing that carries
1831 * an old timestamp.
1832 */
1833
1834 DPFPRINTF(PF_DEBUG_MISC, "Timestamp failed %c%c%c%c",
1835 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1836 SEQ_GT(tsval, src->scrub->pfss_tsval +
1837 tsval_from_last) ? '1' : ' ',
1838 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1839 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' ');
1840 DPFPRINTF(PF_DEBUG_MISC, " tsval: %u tsecr: %u +ticks: "
1841 "%u idle: %jus %lums",
1842 tsval, tsecr, tsval_from_last,
1843 (uintmax_t)delta_ts.tv_sec,
1844 delta_ts.tv_usec / 1000);
1845 DPFPRINTF(PF_DEBUG_MISC, " src->tsval: %u tsecr: %u",
1846 src->scrub->pfss_tsval, src->scrub->pfss_tsecr);
1847 DPFPRINTF(PF_DEBUG_MISC, " dst->tsval: %u tsecr: %u "
1848 "tsval0: %u", dst->scrub->pfss_tsval,
1849 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0);
1850 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1851 pf_print_state(state);
1852 pf_print_flags(tcp_get_flags(th));
1853 printf("\n");
1854 }
1855 REASON_SET(reason, PFRES_TS);
1856 return (PF_DROP);
1857 }
1858
1859 /* XXX I'd really like to require tsecr but it's optional */
1860
1861 } else if (!got_ts && (tcp_get_flags(th) & TH_RST) == 0 &&
1862 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1863 || pd->p_len > 0 || (tcp_get_flags(th) & TH_SYN)) &&
1864 src->scrub && dst->scrub &&
1865 (src->scrub->pfss_flags & PFSS_PAWS) &&
1866 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1867 /* Didn't send a timestamp. Timestamps aren't really useful
1868 * when:
1869 * - connection opening or closing (often not even sent).
1870 * but we must not let an attacker to put a FIN on a
1871 * data packet to sneak it through our ESTABLISHED check.
1872 * - on a TCP reset. RFC suggests not even looking at TS.
1873 * - on an empty ACK. The TS will not be echoed so it will
1874 * probably not help keep the RTT calculation in sync and
1875 * there isn't as much danger when the sequence numbers
1876 * got wrapped. So some stacks don't include TS on empty
1877 * ACKs :-(
1878 *
1879 * To minimize the disruption to mostly RFC1323 conformant
1880 * stacks, we will only require timestamps on data packets.
1881 *
1882 * And what do ya know, we cannot require timestamps on data
1883 * packets. There appear to be devices that do legitimate
1884 * TCP connection hijacking. There are HTTP devices that allow
1885 * a 3whs (with timestamps) and then buffer the HTTP request.
1886 * If the intermediate device has the HTTP response cache, it
1887 * will spoof the response but not bother timestamping its
1888 * packets. So we can look for the presence of a timestamp in
1889 * the first data packet and if there, require it in all future
1890 * packets.
1891 */
1892
1893 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1894 /*
1895 * Hey! Someone tried to sneak a packet in. Or the
1896 * stack changed its RFC1323 behavior?!?!
1897 */
1898 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1899 DPFPRINTF(PF_DEBUG_MISC, "Did not receive expected "
1900 "RFC1323 timestamp");
1901 pf_print_state(state);
1902 pf_print_flags(tcp_get_flags(th));
1903 printf("\n");
1904 }
1905 REASON_SET(reason, PFRES_TS);
1906 return (PF_DROP);
1907 }
1908 }
1909
1910 /*
1911 * We will note if a host sends his data packets with or without
1912 * timestamps. And require all data packets to contain a timestamp
1913 * if the first does. PAWS implicitly requires that all data packets be
1914 * timestamped. But I think there are middle-man devices that hijack
1915 * TCP streams immediately after the 3whs and don't timestamp their
1916 * packets (seen in a WWW accelerator or cache).
1917 */
1918 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1919 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1920 if (got_ts)
1921 src->scrub->pfss_flags |= PFSS_DATA_TS;
1922 else {
1923 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1924 if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1925 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1926 /* Don't warn if other host rejected RFC1323 */
1927 DPFPRINTF(PF_DEBUG_MISC, "Broken RFC1323 stack did "
1928 "not timestamp data packet. Disabled PAWS "
1929 "security.");
1930 pf_print_state(state);
1931 pf_print_flags(tcp_get_flags(th));
1932 printf("\n");
1933 }
1934 }
1935 }
1936
1937 /*
1938 * Update PAWS values
1939 */
1940 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1941 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1942 getmicrouptime(&src->scrub->pfss_last);
1943 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1944 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1945 src->scrub->pfss_tsval = tsval;
1946
1947 if (tsecr) {
1948 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1949 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1950 src->scrub->pfss_tsecr = tsecr;
1951
1952 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1953 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1954 src->scrub->pfss_tsval0 == 0)) {
1955 /* tsval0 MUST be the lowest timestamp */
1956 src->scrub->pfss_tsval0 = tsval;
1957 }
1958
1959 /* Only fully initialized after a TS gets echoed */
1960 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1961 src->scrub->pfss_flags |= PFSS_PAWS;
1962 }
1963 }
1964
1965 /* I have a dream.... TCP segment reassembly.... */
1966 return (0);
1967 }
1968
1969 int
pf_normalize_mss(struct pf_pdesc * pd)1970 pf_normalize_mss(struct pf_pdesc *pd)
1971 {
1972 int olen, optsoff;
1973 uint8_t opts[MAX_TCPOPTLEN], *opt;
1974
1975 olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr);
1976 optsoff = pd->off + sizeof(struct tcphdr);
1977 if (olen < TCPOLEN_MAXSEG ||
1978 !pf_pull_hdr(pd->m, optsoff, opts, olen, NULL, NULL, pd->af))
1979 return (0);
1980
1981 opt = opts;
1982 while ((opt = pf_find_tcpopt(opt, opts, olen,
1983 TCPOPT_MAXSEG, TCPOLEN_MAXSEG)) != NULL) {
1984 uint16_t mss;
1985 uint8_t *mssp = opt + 2;
1986 memcpy(&mss, mssp, sizeof(mss));
1987 if (ntohs(mss) > pd->act.max_mss) {
1988 size_t mssoffopts = mssp - opts;
1989 pf_patch_16(pd, &mss,
1990 htons(pd->act.max_mss), PF_ALGNMNT(mssoffopts));
1991 m_copyback(pd->m, optsoff + mssoffopts,
1992 sizeof(mss), (caddr_t)&mss);
1993 m_copyback(pd->m, pd->off,
1994 sizeof(struct tcphdr), (caddr_t)&pd->hdr.tcp);
1995 }
1996
1997 opt += opt[1];
1998 }
1999
2000 return (0);
2001 }
2002
2003 int
pf_scan_sctp(struct pf_pdesc * pd)2004 pf_scan_sctp(struct pf_pdesc *pd)
2005 {
2006 struct sctp_chunkhdr ch = { };
2007 int chunk_off = sizeof(struct sctphdr);
2008 int chunk_start;
2009 int ret;
2010
2011 while (pd->off + chunk_off < pd->tot_len) {
2012 if (!pf_pull_hdr(pd->m, pd->off + chunk_off, &ch, sizeof(ch), NULL,
2013 NULL, pd->af))
2014 return (PF_DROP);
2015
2016 /* Length includes the header, this must be at least 4. */
2017 if (ntohs(ch.chunk_length) < 4)
2018 return (PF_DROP);
2019
2020 chunk_start = chunk_off;
2021 chunk_off += roundup(ntohs(ch.chunk_length), 4);
2022
2023 switch (ch.chunk_type) {
2024 case SCTP_INITIATION:
2025 case SCTP_INITIATION_ACK: {
2026 struct sctp_init_chunk init;
2027
2028 if (!pf_pull_hdr(pd->m, pd->off + chunk_start, &init,
2029 sizeof(init), NULL, NULL, pd->af))
2030 return (PF_DROP);
2031
2032 /*
2033 * RFC 9620, Section 3.3.2, "The Initiate Tag is allowed to have
2034 * any value except 0."
2035 */
2036 if (init.init.initiate_tag == 0)
2037 return (PF_DROP);
2038 if (init.init.num_inbound_streams == 0)
2039 return (PF_DROP);
2040 if (init.init.num_outbound_streams == 0)
2041 return (PF_DROP);
2042 if (ntohl(init.init.a_rwnd) < SCTP_MIN_RWND)
2043 return (PF_DROP);
2044
2045 /*
2046 * RFC 9260, Section 3.1, INIT chunks MUST have zero
2047 * verification tag.
2048 */
2049 if (ch.chunk_type == SCTP_INITIATION &&
2050 pd->hdr.sctp.v_tag != 0)
2051 return (PF_DROP);
2052
2053 pd->sctp_initiate_tag = init.init.initiate_tag;
2054
2055 if (ch.chunk_type == SCTP_INITIATION)
2056 pd->sctp_flags |= PFDESC_SCTP_INIT;
2057 else
2058 pd->sctp_flags |= PFDESC_SCTP_INIT_ACK;
2059
2060 ret = pf_multihome_scan_init(pd->off + chunk_start,
2061 ntohs(init.ch.chunk_length), pd);
2062 if (ret != PF_PASS)
2063 return (ret);
2064
2065 break;
2066 }
2067 case SCTP_ABORT_ASSOCIATION:
2068 pd->sctp_flags |= PFDESC_SCTP_ABORT;
2069 break;
2070 case SCTP_SHUTDOWN:
2071 case SCTP_SHUTDOWN_ACK:
2072 pd->sctp_flags |= PFDESC_SCTP_SHUTDOWN;
2073 break;
2074 case SCTP_SHUTDOWN_COMPLETE:
2075 pd->sctp_flags |= PFDESC_SCTP_SHUTDOWN_COMPLETE;
2076 break;
2077 case SCTP_COOKIE_ECHO:
2078 pd->sctp_flags |= PFDESC_SCTP_COOKIE;
2079 break;
2080 case SCTP_COOKIE_ACK:
2081 pd->sctp_flags |= PFDESC_SCTP_COOKIE_ACK;
2082 break;
2083 case SCTP_DATA:
2084 pd->sctp_flags |= PFDESC_SCTP_DATA;
2085 break;
2086 case SCTP_HEARTBEAT_REQUEST:
2087 pd->sctp_flags |= PFDESC_SCTP_HEARTBEAT;
2088 break;
2089 case SCTP_HEARTBEAT_ACK:
2090 pd->sctp_flags |= PFDESC_SCTP_HEARTBEAT_ACK;
2091 break;
2092 case SCTP_ASCONF:
2093 pd->sctp_flags |= PFDESC_SCTP_ASCONF;
2094
2095 ret = pf_multihome_scan_asconf(pd->off + chunk_start,
2096 ntohs(ch.chunk_length), pd);
2097 if (ret != PF_PASS)
2098 return (ret);
2099 break;
2100 default:
2101 pd->sctp_flags |= PFDESC_SCTP_OTHER;
2102 break;
2103 }
2104 }
2105
2106 /* Validate chunk lengths vs. packet length. */
2107 if (pd->off + chunk_off != pd->tot_len)
2108 return (PF_DROP);
2109
2110 /*
2111 * INIT, INIT_ACK or SHUTDOWN_COMPLETE chunks must always be the only
2112 * one in a packet.
2113 */
2114 if ((pd->sctp_flags & PFDESC_SCTP_INIT) &&
2115 (pd->sctp_flags & ~PFDESC_SCTP_INIT))
2116 return (PF_DROP);
2117 if ((pd->sctp_flags & PFDESC_SCTP_INIT_ACK) &&
2118 (pd->sctp_flags & ~PFDESC_SCTP_INIT_ACK))
2119 return (PF_DROP);
2120 if ((pd->sctp_flags & PFDESC_SCTP_SHUTDOWN_COMPLETE) &&
2121 (pd->sctp_flags & ~PFDESC_SCTP_SHUTDOWN_COMPLETE))
2122 return (PF_DROP);
2123 if ((pd->sctp_flags & PFDESC_SCTP_ABORT) &&
2124 (pd->sctp_flags & PFDESC_SCTP_DATA)) {
2125 /*
2126 * RFC4960 3.3.7: DATA chunks MUST NOT be
2127 * bundled with ABORT.
2128 */
2129 return (PF_DROP);
2130 }
2131
2132 return (PF_PASS);
2133 }
2134
2135 int
pf_normalize_sctp(struct pf_pdesc * pd)2136 pf_normalize_sctp(struct pf_pdesc *pd)
2137 {
2138 struct pf_krule *r, *rm = NULL;
2139 struct sctphdr *sh = &pd->hdr.sctp;
2140 u_short reason;
2141 sa_family_t af = pd->af;
2142 int srs;
2143
2144 PF_RULES_RASSERT();
2145
2146 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
2147 /* Check if there any scrub rules. Lack of scrub rules means enforced
2148 * packet normalization operation just like in OpenBSD. */
2149 srs = (r != NULL);
2150 while (r != NULL) {
2151 pf_counter_u64_add(&r->evaluations, 1);
2152 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot)
2153 r = r->skip[PF_SKIP_IFP];
2154 else if (r->direction && r->direction != pd->dir)
2155 r = r->skip[PF_SKIP_DIR];
2156 else if (r->af && r->af != af)
2157 r = r->skip[PF_SKIP_AF];
2158 else if (r->proto && r->proto != pd->proto)
2159 r = r->skip[PF_SKIP_PROTO];
2160 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
2161 r->src.neg, pd->kif, M_GETFIB(pd->m)))
2162 r = r->skip[PF_SKIP_SRC_ADDR];
2163 else if (r->src.port_op && !pf_match_port(r->src.port_op,
2164 r->src.port[0], r->src.port[1], sh->src_port))
2165 r = r->skip[PF_SKIP_SRC_PORT];
2166 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
2167 r->dst.neg, NULL, M_GETFIB(pd->m)))
2168 r = r->skip[PF_SKIP_DST_ADDR];
2169 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
2170 r->dst.port[0], r->dst.port[1], sh->dest_port))
2171 r = r->skip[PF_SKIP_DST_PORT];
2172 else {
2173 rm = r;
2174 break;
2175 }
2176 }
2177
2178 if (srs) {
2179 /* With scrub rules present SCTP normalization happens only
2180 * if one of rules has matched and it's not a "no scrub" rule */
2181 if (rm == NULL || rm->action == PF_NOSCRUB)
2182 return (PF_PASS);
2183
2184 pf_counter_u64_critical_enter();
2185 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1);
2186 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len);
2187 pf_counter_u64_critical_exit();
2188 }
2189
2190 /* Verify we're a multiple of 4 bytes long */
2191 if ((pd->tot_len - pd->off - sizeof(struct sctphdr)) % 4)
2192 goto sctp_drop;
2193
2194 /* INIT chunk needs to be the only chunk */
2195 if (pd->sctp_flags & PFDESC_SCTP_INIT)
2196 if (pd->sctp_flags & ~PFDESC_SCTP_INIT)
2197 goto sctp_drop;
2198
2199 return (PF_PASS);
2200
2201 sctp_drop:
2202 REASON_SET(&reason, PFRES_NORM);
2203 if (rm != NULL && r->log)
2204 PFLOG_PACKET(PF_DROP, reason, r, NULL, NULL, pd,
2205 1, NULL);
2206
2207 return (PF_DROP);
2208 }
2209
2210 #if defined(INET) || defined(INET6)
2211 void
pf_scrub(struct pf_pdesc * pd)2212 pf_scrub(struct pf_pdesc *pd)
2213 {
2214
2215 struct ip *h = mtod(pd->m, struct ip *);
2216 #ifdef INET6
2217 struct ip6_hdr *h6 = mtod(pd->m, struct ip6_hdr *);
2218 #endif /* INET6 */
2219
2220 /* Clear IP_DF if no-df was requested */
2221 if (pd->af == AF_INET && pd->act.flags & PFSTATE_NODF &&
2222 h->ip_off & htons(IP_DF))
2223 {
2224 u_int16_t ip_off = h->ip_off;
2225
2226 h->ip_off &= htons(~IP_DF);
2227 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
2228 }
2229
2230 /* Enforce a minimum ttl, may cause endless packet loops */
2231 if (pd->af == AF_INET && pd->act.min_ttl &&
2232 h->ip_ttl < pd->act.min_ttl) {
2233 u_int16_t ip_ttl = h->ip_ttl;
2234
2235 h->ip_ttl = pd->act.min_ttl;
2236 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
2237 }
2238 #ifdef INET6
2239 /* Enforce a minimum ttl, may cause endless packet loops */
2240 if (pd->af == AF_INET6 && pd->act.min_ttl &&
2241 h6->ip6_hlim < pd->act.min_ttl)
2242 h6->ip6_hlim = pd->act.min_ttl;
2243 #endif /* INET6 */
2244 /* Enforce tos */
2245 if (pd->act.flags & PFSTATE_SETTOS) {
2246 switch (pd->af) {
2247 case AF_INET: {
2248 u_int16_t ov, nv;
2249
2250 ov = *(u_int16_t *)h;
2251 h->ip_tos = pd->act.set_tos | (h->ip_tos & IPTOS_ECN_MASK);
2252 nv = *(u_int16_t *)h;
2253
2254 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
2255 break;
2256 }
2257 #ifdef INET6
2258 case AF_INET6:
2259 h6->ip6_flow &= IPV6_FLOWLABEL_MASK | IPV6_VERSION_MASK;
2260 h6->ip6_flow |= htonl((pd->act.set_tos | IPV6_ECN(h6)) << 20);
2261 break;
2262 #endif /* INET6 */
2263 }
2264 }
2265
2266 /* random-id, but not for fragments */
2267 #ifdef INET
2268 if (pd->af == AF_INET &&
2269 pd->act.flags & PFSTATE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
2270 uint16_t ip_id = h->ip_id;
2271
2272 ip_fillid(h, V_ip_random_id);
2273 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
2274 }
2275 #endif /* INET */
2276 }
2277 #endif /* INET || INET6 */
2278