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