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