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