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