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