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