Merge from vendor branch TNFTP:
[dragonfly.git] / sys / net / pf / pf_norm.c
1 /*      $FreeBSD: src/sys/contrib/pf/net/pf_norm.c,v 1.10 2004/08/14 15:32:40 dwmalone Exp $    */
2 /*      $OpenBSD: pf_norm.c,v 1.80.2.1 2004/04/30 21:46:33 brad Exp $ */
3 /* add  $OpenBSD: pf_norm.c,v 1.87 2004/05/11 07:34:11 dhartmei Exp $ */
4 /*      $DragonFly: src/sys/net/pf/pf_norm.c,v 1.9 2007/08/11 18:53:31 dillon Exp $ */
5
6 /*
7  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
8  *
9  * Copyright 2001 Niels Provos <provos@citi.umich.edu>
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/mbuf.h>
39 #include <sys/filio.h>
40 #include <sys/fcntl.h>
41 #include <sys/socket.h>
42 #include <sys/kernel.h>
43 #include <sys/time.h>
44 #include <vm/vm_zone.h>
45
46 #include <net/if.h>
47 #include <net/if_types.h>
48 #include <net/bpf.h>
49 #include <net/route.h>
50 #include <net/pf/if_pflog.h>
51
52 #include <netinet/in.h>
53 #include <netinet/in_var.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/ip_var.h>
57 #include <netinet/tcp.h>
58 #include <netinet/tcp_seq.h>
59 #include <netinet/udp.h>
60 #include <netinet/ip_icmp.h>
61
62 #ifdef INET6
63 #include <netinet/ip6.h>
64 #endif /* INET6 */
65
66 #include <net/pf/pfvar.h>
67
68 #ifdef INET6
69 /*
70  * XXX: This should go to netinet/ip6.h (KAME)
71  */
72 /* IPv6 options: common part */
73 struct ip6_opt {
74         u_int8_t ip6o_type;
75         u_int8_t ip6o_len;
76 } __packed;
77
78 /* Jumbo Payload Option */
79 struct ip6_opt_jumbo {
80         u_int8_t ip6oj_type;
81         u_int8_t ip6oj_len;
82         u_int8_t ip6oj_jumbo_len[4];
83 } __packed;
84
85 /* NSAP Address Option */
86 struct ip6_opt_nsap {
87         u_int8_t ip6on_type;
88         u_int8_t ip6on_len;
89         u_int8_t ip6on_src_nsap_len;
90         u_int8_t ip6on_dst_nsap_len;
91         /* followed by source NSAP */
92         /* followed by destination NSAP */
93 } __packed;
94
95 /* Tunnel Limit Option */
96 struct ip6_opt_tunnel {
97         u_int8_t ip6ot_type;
98         u_int8_t ip6ot_len;
99         u_int8_t ip6ot_encap_limit;
100 } __packed;
101
102 /* Router Alert Option */
103 struct ip6_opt_router {
104         u_int8_t ip6or_type;
105         u_int8_t ip6or_len;
106         u_int8_t ip6or_value[2];
107 } __packed;
108 #endif /* INET6 */
109
110 #define PFFRAG_SEENLAST 0x0001          /* Seen the last fragment for this */
111 #define PFFRAG_NOBUFFER 0x0002          /* Non-buffering fragment cache */
112 #define PFFRAG_DROP     0x0004          /* Drop all fragments */
113 #define BUFFER_FRAGMENTS(fr)    (!((fr)->fr_flags & PFFRAG_NOBUFFER))
114
115
116 TAILQ_HEAD(pf_fragqueue, pf_fragment)   pf_fragqueue;
117 TAILQ_HEAD(pf_cachequeue, pf_fragment)  pf_cachequeue;
118
119 static int              pf_frag_compare(struct pf_fragment *,
120                                         struct pf_fragment *);
121 RB_HEAD(pf_frag_tree, pf_fragment)      pf_frag_tree, pf_cache_tree;
122 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
123 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
124
125 /* Private prototypes */
126 void                     pf_ip2key(struct pf_fragment *, struct ip *);
127 void                     pf_remove_fragment(struct pf_fragment *);
128 void                     pf_flush_fragments(void);
129 void                     pf_free_fragment(struct pf_fragment *);
130 struct pf_fragment      *pf_find_fragment(struct ip *, struct pf_frag_tree *);
131 struct mbuf             *pf_reassemble(struct mbuf **, struct pf_fragment **,
132                             struct pf_frent *, int);
133 struct mbuf             *pf_fragcache(struct mbuf **, struct ip*,
134                             struct pf_fragment **, int, int, int *);
135 u_int16_t                pf_cksum_fixup(u_int16_t, u_int16_t, u_int16_t);
136 int                      pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
137                             struct tcphdr *, int);
138
139 #define DPFPRINTF(x)    if (pf_status.debug >= PF_DEBUG_MISC) \
140                             { kprintf("%s: ", __func__); kprintf x ;}
141
142 /* Globals */
143 vm_zone_t                pf_frent_pl, pf_frag_pl, pf_cache_pl, pf_cent_pl;
144 vm_zone_t                pf_state_scrub_pl;
145 int                      pf_nfrents, pf_ncache;
146
147 void
148 pf_normalize_init(void)
149 {
150         /* XXX
151         pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
152         pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
153         pool_sethardlimit(&pf_cache_pl, PFFRAG_FRCACHE_HIWAT, NULL, 0);
154         pool_sethardlimit(&pf_cent_pl, PFFRAG_FRCENT_HIWAT, NULL, 0);
155         */
156
157         TAILQ_INIT(&pf_fragqueue);
158         TAILQ_INIT(&pf_cachequeue);
159 }
160
161 static int
162 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
163 {
164         int     diff;
165
166         if ((diff = a->fr_id - b->fr_id))
167                 return (diff);
168         else if ((diff = a->fr_p - b->fr_p))
169                 return (diff);
170         else if (a->fr_src.s_addr < b->fr_src.s_addr)
171                 return (-1);
172         else if (a->fr_src.s_addr > b->fr_src.s_addr)
173                 return (1);
174         else if (a->fr_dst.s_addr < b->fr_dst.s_addr)
175                 return (-1);
176         else if (a->fr_dst.s_addr > b->fr_dst.s_addr)
177                 return (1);
178         return (0);
179 }
180
181 void
182 pf_purge_expired_fragments(void)
183 {
184         struct pf_fragment      *frag;
185         u_int32_t                expire = time_second -
186                                     pf_default_rule.timeout[PFTM_FRAG];
187
188         while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
189                 KASSERT((BUFFER_FRAGMENTS(frag)),
190                         ("BUFFER_FRAGMENTS(frag) == 0: %s", __func__));
191                 if (frag->fr_timeout > expire)
192                         break;
193
194                 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
195                 pf_free_fragment(frag);
196         }
197
198         while ((frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue)) != NULL) {
199                 KASSERT((!BUFFER_FRAGMENTS(frag)),
200                         ("BUFFER_FRAGMENTS(frag) != 0: %s", __func__));
201                 if (frag->fr_timeout > expire)
202                         break;
203
204                 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
205                 pf_free_fragment(frag);
206                 KASSERT((TAILQ_EMPTY(&pf_cachequeue) ||
207                     TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag),
208                     ("!(TAILQ_EMPTY() || TAILQ_LAST() == farg): %s",
209                     __func__));
210         }
211 }
212
213 /*
214  * Try to flush old fragments to make space for new ones
215  */
216
217 void
218 pf_flush_fragments(void)
219 {
220         struct pf_fragment      *frag;
221         int                      goal;
222
223         goal = pf_nfrents * 9 / 10;
224         DPFPRINTF(("trying to free > %d frents\n",
225             pf_nfrents - goal));
226         while (goal < pf_nfrents) {
227                 frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue);
228                 if (frag == NULL)
229                         break;
230                 pf_free_fragment(frag);
231         }
232
233
234         goal = pf_ncache * 9 / 10;
235         DPFPRINTF(("trying to free > %d cache entries\n",
236             pf_ncache - goal));
237         while (goal < pf_ncache) {
238                 frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue);
239                 if (frag == NULL)
240                         break;
241                 pf_free_fragment(frag);
242         }
243 }
244
245 /* Frees the fragments and all associated entries */
246
247 void
248 pf_free_fragment(struct pf_fragment *frag)
249 {
250         struct pf_frent         *frent;
251         struct pf_frcache       *frcache;
252
253         /* Free all fragments */
254         if (BUFFER_FRAGMENTS(frag)) {
255                 for (frent = LIST_FIRST(&frag->fr_queue); frent;
256                     frent = LIST_FIRST(&frag->fr_queue)) {
257                         LIST_REMOVE(frent, fr_next);
258
259                         m_freem(frent->fr_m);
260                         pool_put(&pf_frent_pl, frent);
261                         pf_nfrents--;
262                 }
263         } else {
264                 for (frcache = LIST_FIRST(&frag->fr_cache); frcache;
265                     frcache = LIST_FIRST(&frag->fr_cache)) {
266                         LIST_REMOVE(frcache, fr_next);
267
268                         KASSERT((LIST_EMPTY(&frag->fr_cache) ||
269                             LIST_FIRST(&frag->fr_cache)->fr_off >
270                             frcache->fr_end),
271                             ("! (LIST_EMPTY() || LIST_FIRST()->fr_off >"
272                              " frcache->fr_end): %s", __func__));
273
274                         pool_put(&pf_cent_pl, frcache);
275                         pf_ncache--;
276                 }
277         }
278
279         pf_remove_fragment(frag);
280 }
281
282 void
283 pf_ip2key(struct pf_fragment *key, struct ip *ip)
284 {
285         key->fr_p = ip->ip_p;
286         key->fr_id = ip->ip_id;
287         key->fr_src.s_addr = ip->ip_src.s_addr;
288         key->fr_dst.s_addr = ip->ip_dst.s_addr;
289 }
290
291 struct pf_fragment *
292 pf_find_fragment(struct ip *ip, struct pf_frag_tree *tree)
293 {
294         struct pf_fragment       key;
295         struct pf_fragment      *frag;
296
297         pf_ip2key(&key, ip);
298
299         frag = RB_FIND(pf_frag_tree, tree, &key);
300         if (frag != NULL) {
301                 /* XXX Are we sure we want to update the timeout? */
302                 frag->fr_timeout = time_second;
303                 if (BUFFER_FRAGMENTS(frag)) {
304                         TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
305                         TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
306                 } else {
307                         TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
308                         TAILQ_INSERT_HEAD(&pf_cachequeue, frag, frag_next);
309                 }
310         }
311
312         return (frag);
313 }
314
315 /* Removes a fragment from the fragment queue and frees the fragment */
316
317 void
318 pf_remove_fragment(struct pf_fragment *frag)
319 {
320         if (BUFFER_FRAGMENTS(frag)) {
321                 RB_REMOVE(pf_frag_tree, &pf_frag_tree, frag);
322                 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
323                 pool_put(&pf_frag_pl, frag);
324         } else {
325                 RB_REMOVE(pf_frag_tree, &pf_cache_tree, frag);
326                 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
327                 pool_put(&pf_cache_pl, frag);
328         }
329 }
330
331 #define FR_IP_OFF(fr)   (((fr)->fr_ip->ip_off & IP_OFFMASK) << 3)
332 struct mbuf *
333 pf_reassemble(struct mbuf **m0, struct pf_fragment **frag,
334     struct pf_frent *frent, int mff)
335 {
336         struct mbuf     *m = *m0, *m2;
337         struct pf_frent *frea, *next;
338         struct pf_frent *frep = NULL;
339         struct ip       *ip = frent->fr_ip;
340         int              hlen = ip->ip_hl << 2;
341         u_int16_t        off = (ip->ip_off & IP_OFFMASK) << 3;
342         u_int16_t        ip_len = ip->ip_len - ip->ip_hl * 4;
343         u_int16_t        max = ip_len + off;
344
345         KASSERT((*frag == NULL || BUFFER_FRAGMENTS(*frag)),
346             ("! (*frag == NULL || BUFFER_FRAGMENTS(*frag)): %s", __func__));
347
348         /* Strip off ip header */
349         m->m_data += hlen;
350         m->m_len -= hlen;
351
352         /* Create a new reassembly queue for this packet */
353         if (*frag == NULL) {
354                 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
355                 if (*frag == NULL) {
356                         pf_flush_fragments();
357                         *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
358                         if (*frag == NULL)
359                                 goto drop_fragment;
360                 }
361
362                 (*frag)->fr_flags = 0;
363                 (*frag)->fr_max = 0;
364                 (*frag)->fr_src = frent->fr_ip->ip_src;
365                 (*frag)->fr_dst = frent->fr_ip->ip_dst;
366                 (*frag)->fr_p = frent->fr_ip->ip_p;
367                 (*frag)->fr_id = frent->fr_ip->ip_id;
368                 (*frag)->fr_timeout = time_second;
369                 LIST_INIT(&(*frag)->fr_queue);
370
371                 RB_INSERT(pf_frag_tree, &pf_frag_tree, *frag);
372                 TAILQ_INSERT_HEAD(&pf_fragqueue, *frag, frag_next);
373
374                 /* We do not have a previous fragment */
375                 frep = NULL;
376                 goto insert;
377         }
378
379         /*
380          * Find a fragment after the current one:
381          *  - off contains the real shifted offset.
382          */
383         LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
384                 if (FR_IP_OFF(frea) > off)
385                         break;
386                 frep = frea;
387         }
388
389         KASSERT((frep != NULL || frea != NULL),
390             ("!(frep != NULL || frea != NULL): %s", __func__));
391
392         if (frep != NULL &&
393             FR_IP_OFF(frep) + frep->fr_ip->ip_len - frep->fr_ip->ip_hl *
394             4 > off)
395         {
396                 u_int16_t       precut;
397
398                 precut = FR_IP_OFF(frep) + frep->fr_ip->ip_len -
399                     frep->fr_ip->ip_hl * 4 - off;
400                 if (precut >= ip_len)
401                         goto drop_fragment;
402                 m_adj(frent->fr_m, precut);
403                 DPFPRINTF(("overlap -%d\n", precut));
404                 /* Enforce 8 byte boundaries */
405                 ip->ip_off = ip->ip_off + (precut >> 3);
406                 off = (ip->ip_off & IP_OFFMASK) << 3;
407                 ip_len -= precut;
408                 ip->ip_len = ip_len;
409         }
410
411         for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
412             frea = next)
413         {
414                 u_int16_t       aftercut;
415
416                 aftercut = ip_len + off - FR_IP_OFF(frea);
417                 DPFPRINTF(("adjust overlap %d\n", aftercut));
418                 if (aftercut < frea->fr_ip->ip_len - frea->fr_ip->ip_hl
419                     * 4)
420                 {
421                         frea->fr_ip->ip_len =
422                             frea->fr_ip->ip_len - aftercut;
423                         frea->fr_ip->ip_off = frea->fr_ip->ip_off +
424                             (aftercut >> 3);
425                         m_adj(frea->fr_m, aftercut);
426                         break;
427                 }
428
429                 /* This fragment is completely overlapped, loose it */
430                 next = LIST_NEXT(frea, fr_next);
431                 m_freem(frea->fr_m);
432                 LIST_REMOVE(frea, fr_next);
433                 pool_put(&pf_frent_pl, frea);
434                 pf_nfrents--;
435         }
436
437  insert:
438         /* Update maximum data size */
439         if ((*frag)->fr_max < max)
440                 (*frag)->fr_max = max;
441         /* This is the last segment */
442         if (!mff)
443                 (*frag)->fr_flags |= PFFRAG_SEENLAST;
444
445         if (frep == NULL)
446                 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
447         else
448                 LIST_INSERT_AFTER(frep, frent, fr_next);
449
450         /* Check if we are completely reassembled */
451         if (!((*frag)->fr_flags & PFFRAG_SEENLAST))
452                 return (NULL);
453
454         /* Check if we have all the data */
455         off = 0;
456         for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
457                 next = LIST_NEXT(frep, fr_next);
458
459                 off += frep->fr_ip->ip_len - frep->fr_ip->ip_hl * 4;
460                 if (off < (*frag)->fr_max &&
461                     (next == NULL || FR_IP_OFF(next) != off))
462                 {
463                         DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
464                             off, next == NULL ? -1 : FR_IP_OFF(next),
465                             (*frag)->fr_max));
466                         return (NULL);
467                 }
468         }
469         DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
470         if (off < (*frag)->fr_max)
471                 return (NULL);
472
473         /* We have all the data */
474         frent = LIST_FIRST(&(*frag)->fr_queue);
475         KASSERT((frent != NULL), ("frent == NULL: %s", __func__));
476         if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
477                 DPFPRINTF(("drop: too big: %d\n", off));
478                 pf_free_fragment(*frag);
479                 *frag = NULL;
480                 return (NULL);
481         }
482         next = LIST_NEXT(frent, fr_next);
483
484         /* Magic from ip_input */
485         ip = frent->fr_ip;
486         m = frent->fr_m;
487         m2 = m->m_next;
488         m->m_next = NULL;
489         m_cat(m, m2);
490         pool_put(&pf_frent_pl, frent);
491         pf_nfrents--;
492         for (frent = next; frent != NULL; frent = next) {
493                 next = LIST_NEXT(frent, fr_next);
494
495                 m2 = frent->fr_m;
496                 pool_put(&pf_frent_pl, frent);
497                 pf_nfrents--;
498                 m->m_pkthdr.csum_flags &= m2->m_pkthdr.csum_flags;
499                 m->m_pkthdr.csum_data += m2->m_pkthdr.csum_data;
500                 m_cat(m, m2);
501         }
502
503         /*
504          * Note: this 1's complement optimization with <= 65535 fragments.
505          *
506          * Handle 1's complement carry for the 16 bit result.  This can
507          * result in another carry which must also be handled.
508          */
509         m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
510                                 (m->m_pkthdr.csum_data >> 16);
511         if (m->m_pkthdr.csum_data > 0xFFFF)
512                 m->m_pkthdr.csum_data -= 0xFFFF;
513
514
515         ip->ip_src = (*frag)->fr_src;
516         ip->ip_dst = (*frag)->fr_dst;
517
518         /* Remove from fragment queue */
519         pf_remove_fragment(*frag);
520         *frag = NULL;
521
522         hlen = ip->ip_hl << 2;
523         ip->ip_len = off + hlen;
524         m->m_len += hlen;
525         m->m_data -= hlen;
526
527         /* some debugging cruft by sklower, below, will go away soon */
528         /* XXX this should be done elsewhere */
529         if (m->m_flags & M_PKTHDR) {
530                 int plen = 0;
531                 for (m2 = m; m2; m2 = m2->m_next)
532                         plen += m2->m_len;
533                 m->m_pkthdr.len = plen;
534         }
535
536         DPFPRINTF(("complete: %p(%d)\n", m, ip->ip_len));
537         return (m);
538
539  drop_fragment:
540         /* Oops - fail safe - drop packet */
541         pool_put(&pf_frent_pl, frent);
542         pf_nfrents--;
543         m_freem(m);
544         return (NULL);
545 }
546
547 struct mbuf *
548 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
549     int drop, int *nomem)
550 {
551         struct mbuf             *m = *m0;
552         struct pf_frcache       *frp, *fra, *cur = NULL;
553         int                      ip_len = h->ip_len - (h->ip_hl << 2);
554         u_int16_t                off = h->ip_off << 3;
555         u_int16_t                max = ip_len + off;
556         int                      hosed = 0;
557
558         KASSERT((*frag == NULL || !BUFFER_FRAGMENTS(*frag)),
559             ("!(*frag == NULL || !BUFFER_FRAGMENTS(*frag)): %s", __func__));
560
561         /* Create a new range queue for this packet */
562         if (*frag == NULL) {
563                 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
564                 if (*frag == NULL) {
565                         pf_flush_fragments();
566                         *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
567                         if (*frag == NULL)
568                                 goto no_mem;
569                 }
570
571                 /* Get an entry for the queue */
572                 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
573                 if (cur == NULL) {
574                         pool_put(&pf_cache_pl, *frag);
575                         *frag = NULL;
576                         goto no_mem;
577                 }
578                 pf_ncache++;
579
580                 (*frag)->fr_flags = PFFRAG_NOBUFFER;
581                 (*frag)->fr_max = 0;
582                 (*frag)->fr_src = h->ip_src;
583                 (*frag)->fr_dst = h->ip_dst;
584                 (*frag)->fr_p = h->ip_p;
585                 (*frag)->fr_id = h->ip_id;
586                 (*frag)->fr_timeout = time_second;
587
588                 cur->fr_off = off;
589                 cur->fr_end = max;
590                 LIST_INIT(&(*frag)->fr_cache);
591                 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
592
593                 RB_INSERT(pf_frag_tree, &pf_cache_tree, *frag);
594                 TAILQ_INSERT_HEAD(&pf_cachequeue, *frag, frag_next);
595
596                 DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off, max));
597
598                 goto pass;
599         }
600
601         /*
602          * Find a fragment after the current one:
603          *  - off contains the real shifted offset.
604          */
605         frp = NULL;
606         LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
607                 if (fra->fr_off > off)
608                         break;
609                 frp = fra;
610         }
611
612         KASSERT((frp != NULL || fra != NULL),
613             ("!(frp != NULL || fra != NULL): %s", __func__));
614
615         if (frp != NULL) {
616                 int     precut;
617
618                 precut = frp->fr_end - off;
619                 if (precut >= ip_len) {
620                         /* Fragment is entirely a duplicate */
621                         DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
622                             h->ip_id, frp->fr_off, frp->fr_end, off, max));
623                         goto drop_fragment;
624                 }
625                 if (precut == 0) {
626                         /* They are adjacent.  Fixup cache entry */
627                         DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
628                             h->ip_id, frp->fr_off, frp->fr_end, off, max));
629                         frp->fr_end = max;
630                 } else if (precut > 0) {
631                         /* The first part of this payload overlaps with a
632                          * fragment that has already been passed.
633                          * Need to trim off the first part of the payload.
634                          * But to do so easily, we need to create another
635                          * mbuf to throw the original header into.
636                          */
637
638                         DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
639                             h->ip_id, precut, frp->fr_off, frp->fr_end, off,
640                             max));
641
642                         off += precut;
643                         max -= precut;
644                         /* Update the previous frag to encompass this one */
645                         frp->fr_end = max;
646
647                         if (!drop) {
648                                 /* XXX Optimization opportunity
649                                  * This is a very heavy way to trim the payload.
650                                  * we could do it much faster by diddling mbuf
651                                  * internals but that would be even less legible
652                                  * than this mbuf magic.  For my next trick,
653                                  * I'll pull a rabbit out of my laptop.
654                                  */
655                                 *m0 = m_dup(m, MB_DONTWAIT);
656                                 /* From KAME Project : We have missed this! */
657                                 m_adj(*m0, (h->ip_hl << 2) -
658                                     (*m0)->m_pkthdr.len);
659                                 if (*m0 == NULL)
660                                         goto no_mem;
661                                 KASSERT(((*m0)->m_next == NULL), 
662                                     ("(*m0)->m_next != NULL: %s", 
663                                     __func__));
664                                 m_adj(m, precut + (h->ip_hl << 2));
665                                 m_cat(*m0, m);
666                                 m = *m0;
667                                 if (m->m_flags & M_PKTHDR) {
668                                         int plen = 0;
669                                         struct mbuf *t;
670                                         for (t = m; t; t = t->m_next)
671                                                 plen += t->m_len;
672                                         m->m_pkthdr.len = plen;
673                                 }
674
675
676                                 h = mtod(m, struct ip *);
677
678                                 KASSERT(((int)m->m_len ==
679                                     h->ip_len - precut),
680                                     ("m->m_len != h->ip_len - precut: %s",
681                                     __func__));
682                                 h->ip_off = h->ip_off +
683                                     (precut >> 3);
684                                 h->ip_len = h->ip_len - precut;
685                         } else {
686                                 hosed++;
687                         }
688                 } else {
689                         /* There is a gap between fragments */
690
691                         DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
692                             h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
693                             max));
694
695                         cur = pool_get(&pf_cent_pl, PR_NOWAIT);
696                         if (cur == NULL)
697                                 goto no_mem;
698                         pf_ncache++;
699
700                         cur->fr_off = off;
701                         cur->fr_end = max;
702                         LIST_INSERT_AFTER(frp, cur, fr_next);
703                 }
704         }
705
706         if (fra != NULL) {
707                 int     aftercut;
708                 int     merge = 0;
709
710                 aftercut = max - fra->fr_off;
711                 if (aftercut == 0) {
712                         /* Adjacent fragments */
713                         DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
714                             h->ip_id, off, max, fra->fr_off, fra->fr_end));
715                         fra->fr_off = off;
716                         merge = 1;
717                 } else if (aftercut > 0) {
718                         /* Need to chop off the tail of this fragment */
719                         DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
720                             h->ip_id, aftercut, off, max, fra->fr_off,
721                             fra->fr_end));
722                         fra->fr_off = off;
723                         max -= aftercut;
724
725                         merge = 1;
726
727                         if (!drop) {
728                                 m_adj(m, -aftercut);
729                                 if (m->m_flags & M_PKTHDR) {
730                                         int plen = 0;
731                                         struct mbuf *t;
732                                         for (t = m; t; t = t->m_next)
733                                                 plen += t->m_len;
734                                         m->m_pkthdr.len = plen;
735                                 }
736                                 h = mtod(m, struct ip *);
737                                 KASSERT(((int)m->m_len == h->ip_len - aftercut),
738                                     ("m->m_len != h->ip_len - aftercut: %s",
739                                     __func__));
740                                 h->ip_len = h->ip_len - aftercut;
741                         } else {
742                                 hosed++;
743                         }
744                 } else if (frp == NULL) {
745                         /* There is a gap between fragments */
746                         DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
747                             h->ip_id, -aftercut, off, max, fra->fr_off,
748                             fra->fr_end));
749
750                         cur = pool_get(&pf_cent_pl, PR_NOWAIT);
751                         if (cur == NULL)
752                                 goto no_mem;
753                         pf_ncache++;
754
755                         cur->fr_off = off;
756                         cur->fr_end = max;
757                         LIST_INSERT_BEFORE(fra, cur, fr_next);
758                 }
759
760
761                 /* Need to glue together two separate fragment descriptors */
762                 if (merge) {
763                         if (cur && fra->fr_off <= cur->fr_end) {
764                                 /* Need to merge in a previous 'cur' */
765                                 DPFPRINTF(("fragcache[%d]: adjacent(merge "
766                                     "%d-%d) %d-%d (%d-%d)\n",
767                                     h->ip_id, cur->fr_off, cur->fr_end, off,
768                                     max, fra->fr_off, fra->fr_end));
769                                 fra->fr_off = cur->fr_off;
770                                 LIST_REMOVE(cur, fr_next);
771                                 pool_put(&pf_cent_pl, cur);
772                                 pf_ncache--;
773                                 cur = NULL;
774
775                         } else if (frp && fra->fr_off <= frp->fr_end) {
776                                 /* Need to merge in a modified 'frp' */
777                                 KASSERT((cur == NULL), ("cur != NULL: %s",
778                                     __func__));
779                                 DPFPRINTF(("fragcache[%d]: adjacent(merge "
780                                     "%d-%d) %d-%d (%d-%d)\n",
781                                     h->ip_id, frp->fr_off, frp->fr_end, off,
782                                     max, fra->fr_off, fra->fr_end));
783                                 fra->fr_off = frp->fr_off;
784                                 LIST_REMOVE(frp, fr_next);
785                                 pool_put(&pf_cent_pl, frp);
786                                 pf_ncache--;
787                                 frp = NULL;
788
789                         }
790                 }
791         }
792
793         if (hosed) {
794                 /*
795                  * We must keep tracking the overall fragment even when
796                  * we're going to drop it anyway so that we know when to
797                  * free the overall descriptor.  Thus we drop the frag late.
798                  */
799                 goto drop_fragment;
800         }
801
802
803  pass:
804         /* Update maximum data size */
805         if ((*frag)->fr_max < max)
806                 (*frag)->fr_max = max;
807
808         /* This is the last segment */
809         if (!mff)
810                 (*frag)->fr_flags |= PFFRAG_SEENLAST;
811
812         /* Check if we are completely reassembled */
813         if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
814             LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
815             LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
816                 /* Remove from fragment queue */
817                 DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
818                     (*frag)->fr_max));
819                 pf_free_fragment(*frag);
820                 *frag = NULL;
821         }
822
823         return (m);
824
825  no_mem:
826         *nomem = 1;
827
828         /* Still need to pay attention to !IP_MF */
829         if (!mff && *frag != NULL)
830                 (*frag)->fr_flags |= PFFRAG_SEENLAST;
831
832         m_freem(m);
833         return (NULL);
834
835  drop_fragment:
836
837         /* Still need to pay attention to !IP_MF */
838         if (!mff && *frag != NULL)
839                 (*frag)->fr_flags |= PFFRAG_SEENLAST;
840
841         if (drop) {
842                 /* This fragment has been deemed bad.  Don't reass */
843                 if (((*frag)->fr_flags & PFFRAG_DROP) == 0)
844                         DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
845                             h->ip_id));
846                 (*frag)->fr_flags |= PFFRAG_DROP;
847         }
848
849         m_freem(m);
850         return (NULL);
851 }
852
853 int
854 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason)
855 {
856         struct mbuf             *m = *m0;
857         struct pf_rule          *r;
858         struct pf_frent         *frent;
859         struct pf_fragment      *frag = NULL;
860         struct ip               *h = mtod(m, struct ip *);
861         int                      mff = (h->ip_off & IP_MF);
862         int                      hlen = h->ip_hl << 2;
863         u_int16_t                fragoff = (h->ip_off & IP_OFFMASK) << 3;
864         u_int16_t                max;
865         int                      ip_len;
866         int                      ip_off;
867
868         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
869         while (r != NULL) {
870                 r->evaluations++;
871                 if (r->kif != NULL &&
872                     (r->kif != kif && r->kif != kif->pfik_parent) == !r->ifnot)
873                         r = r->skip[PF_SKIP_IFP].ptr;
874                 else if (r->direction && r->direction != dir)
875                         r = r->skip[PF_SKIP_DIR].ptr;
876                 else if (r->af && r->af != AF_INET)
877                         r = r->skip[PF_SKIP_AF].ptr;
878                 else if (r->proto && r->proto != h->ip_p)
879                         r = r->skip[PF_SKIP_PROTO].ptr;
880                 else if (PF_MISMATCHAW(&r->src.addr,
881                     (struct pf_addr *)&h->ip_src.s_addr, AF_INET, r->src.not))
882                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
883                 else if (PF_MISMATCHAW(&r->dst.addr,
884                     (struct pf_addr *)&h->ip_dst.s_addr, AF_INET, r->dst.not))
885                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
886                 else
887                         break;
888         }
889
890         if (r == NULL)
891                 return (PF_PASS);
892         else
893                 r->packets++;
894
895         /* Check for illegal packets */
896         if (hlen < (int)sizeof(struct ip))
897                 goto drop;
898
899         if (hlen > h->ip_len)
900                 goto drop;
901
902         /* Clear IP_DF if the rule uses the no-df option */
903         if (r->rule_flag & PFRULE_NODF)
904                 h->ip_off &= ~IP_DF;
905
906         /* We will need other tests here */
907         if (!fragoff && !mff)
908                 goto no_fragment;
909
910         /* We're dealing with a fragment now. Don't allow fragments
911          * with IP_DF to enter the cache. If the flag was cleared by
912          * no-df above, fine. Otherwise drop it.
913          */
914         if (h->ip_off & IP_DF) {
915                 DPFPRINTF(("IP_DF\n"));
916                 goto bad;
917         }
918
919         ip_len = h->ip_len - hlen;
920         ip_off = (h->ip_off & IP_OFFMASK) << 3;
921
922         /* All fragments are 8 byte aligned */
923         if (mff && (ip_len & 0x7)) {
924                 DPFPRINTF(("mff and %d\n", ip_len));
925                 goto bad;
926         }
927
928         /* Respect maximum length */
929         if (fragoff + ip_len > IP_MAXPACKET) {
930                 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
931                 goto bad;
932         }
933         max = fragoff + ip_len;
934
935         if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
936                 /* Fully buffer all of the fragments */
937
938                 frag = pf_find_fragment(h, &pf_frag_tree);
939
940                 /* Check if we saw the last fragment already */
941                 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
942                     max > frag->fr_max)
943                         goto bad;
944
945                 /* Get an entry for the fragment queue */
946                 frent = pool_get(&pf_frent_pl, PR_NOWAIT);
947                 if (frent == NULL) {
948                         REASON_SET(reason, PFRES_MEMORY);
949                         return (PF_DROP);
950                 }
951                 pf_nfrents++;
952                 frent->fr_ip = h;
953                 frent->fr_m = m;
954
955                 /* Might return a completely reassembled mbuf, or NULL */
956                 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
957                 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
958
959                 if (m == NULL)
960                         return (PF_DROP);
961
962                 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
963                         goto drop;
964
965                 h = mtod(m, struct ip *);
966         } else {
967                 /* non-buffering fragment cache (drops or masks overlaps) */
968                 int     nomem = 0;
969
970                 if (dir == PF_OUT) {
971                         if (m->m_pkthdr.fw_flags & PF_MBUF_FRAGCACHE) {
972                                 /* Already passed the fragment cache in the
973                                  * input direction.  If we continued, it would
974                                  * appear to be a dup and would be dropped.
975                                  */
976                                 goto fragment_pass;
977                         }
978                 }
979
980                 frag = pf_find_fragment(h, &pf_cache_tree);
981
982                 /* Check if we saw the last fragment already */
983                 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
984                     max > frag->fr_max) {
985                         if (r->rule_flag & PFRULE_FRAGDROP)
986                                 frag->fr_flags |= PFFRAG_DROP;
987                         goto bad;
988                 }
989
990                 *m0 = m = pf_fragcache(m0, h, &frag, mff,
991                     (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
992                 if (m == NULL) {
993                         if (nomem)
994                                 goto no_mem;
995                         goto drop;
996                 }
997
998                 if (dir == PF_IN)
999                         m->m_pkthdr.fw_flags |= PF_MBUF_FRAGCACHE;
1000
1001                 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
1002                         goto drop;
1003                 goto fragment_pass;
1004         }
1005
1006  no_fragment:
1007         /* At this point, only IP_DF is allowed in ip_off */
1008         h->ip_off &= IP_DF;
1009
1010         /* Enforce a minimum ttl, may cause endless packet loops */
1011         if (r->min_ttl && h->ip_ttl < r->min_ttl)
1012                 h->ip_ttl = r->min_ttl;
1013
1014         if (r->rule_flag & PFRULE_RANDOMID) {
1015 #ifdef RANDOM_IP_ID
1016                 h->ip_id = ip_randomid();
1017 #else
1018                 h->ip_id = htons(ip_id++);
1019 #endif
1020         }
1021
1022         return (PF_PASS);
1023
1024  fragment_pass:
1025         /* Enforce a minimum ttl, may cause endless packet loops */
1026         if (r->min_ttl && h->ip_ttl < r->min_ttl)
1027                 h->ip_ttl = r->min_ttl;
1028
1029         return (PF_PASS);
1030
1031  no_mem:
1032         REASON_SET(reason, PFRES_MEMORY);
1033         if (r != NULL && r->log)
1034                 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL);
1035         return (PF_DROP);
1036
1037  drop:
1038         REASON_SET(reason, PFRES_NORM);
1039         if (r != NULL && r->log)
1040                 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL);
1041         return (PF_DROP);
1042
1043  bad:
1044         DPFPRINTF(("dropping bad fragment\n"));
1045
1046         /* Free associated fragments */
1047         if (frag != NULL)
1048                 pf_free_fragment(frag);
1049
1050         REASON_SET(reason, PFRES_FRAG);
1051         if (r != NULL && r->log)
1052                 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL);
1053
1054         return (PF_DROP);
1055 }
1056
1057 #ifdef INET6
1058 int
1059 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1060     u_short *reason)
1061 {
1062         struct mbuf             *m = *m0;
1063         struct pf_rule          *r;
1064         struct ip6_hdr          *h = mtod(m, struct ip6_hdr *);
1065         int                      off;
1066         struct ip6_ext           ext;
1067         struct ip6_opt           opt;
1068         struct ip6_opt_jumbo     jumbo;
1069         struct ip6_frag          frag;
1070         u_int32_t                jumbolen = 0, plen;
1071         u_int16_t                fragoff = 0;
1072         int                      optend;
1073         int                      ooff;
1074         u_int8_t                 proto;
1075         int                      terminal;
1076
1077         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1078         while (r != NULL) {
1079                 r->evaluations++;
1080                 if (r->kif != NULL &&
1081                     (r->kif != kif && r->kif != kif->pfik_parent) == !r->ifnot)
1082                         r = r->skip[PF_SKIP_IFP].ptr;
1083                 else if (r->direction && r->direction != dir)
1084                         r = r->skip[PF_SKIP_DIR].ptr;
1085                 else if (r->af && r->af != AF_INET6)
1086                         r = r->skip[PF_SKIP_AF].ptr;
1087 #if 0 /* header chain! */
1088                 else if (r->proto && r->proto != h->ip6_nxt)
1089                         r = r->skip[PF_SKIP_PROTO].ptr;
1090 #endif
1091                 else if (PF_MISMATCHAW(&r->src.addr,
1092                     (struct pf_addr *)&h->ip6_src, AF_INET6, r->src.not))
1093                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1094                 else if (PF_MISMATCHAW(&r->dst.addr,
1095                     (struct pf_addr *)&h->ip6_dst, AF_INET6, r->dst.not))
1096                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
1097                 else
1098                         break;
1099         }
1100
1101         if (r == NULL)
1102                 return (PF_PASS);
1103         else
1104                 r->packets++;
1105
1106         /* Check for illegal packets */
1107         if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1108                 goto drop;
1109
1110         off = sizeof(struct ip6_hdr);
1111         proto = h->ip6_nxt;
1112         terminal = 0;
1113         do {
1114                 switch (proto) {
1115                 case IPPROTO_FRAGMENT:
1116                         goto fragment;
1117                         break;
1118                 case IPPROTO_AH:
1119                 case IPPROTO_ROUTING:
1120                 case IPPROTO_DSTOPTS:
1121                         if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1122                             NULL, AF_INET6))
1123                                 goto shortpkt;
1124                         if (proto == IPPROTO_AH)
1125                                 off += (ext.ip6e_len + 2) * 4;
1126                         else
1127                                 off += (ext.ip6e_len + 1) * 8;
1128                         proto = ext.ip6e_nxt;
1129                         break;
1130                 case IPPROTO_HOPOPTS:
1131                         if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1132                             NULL, AF_INET6))
1133                                 goto shortpkt;
1134                         optend = off + (ext.ip6e_len + 1) * 8;
1135                         ooff = off + sizeof(ext);
1136                         do {
1137                                 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1138                                     sizeof(opt.ip6o_type), NULL, NULL,
1139                                     AF_INET6))
1140                                         goto shortpkt;
1141                                 if (opt.ip6o_type == IP6OPT_PAD1) {
1142                                         ooff++;
1143                                         continue;
1144                                 }
1145                                 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1146                                     NULL, NULL, AF_INET6))
1147                                         goto shortpkt;
1148                                 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1149                                         goto drop;
1150                                 switch (opt.ip6o_type) {
1151                                 case IP6OPT_JUMBO:
1152                                         if (h->ip6_plen != 0)
1153                                                 goto drop;
1154                                         if (!pf_pull_hdr(m, ooff, &jumbo,
1155                                             sizeof(jumbo), NULL, NULL,
1156                                             AF_INET6))
1157                                                 goto shortpkt;
1158                                         memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1159                                             sizeof(jumbolen));
1160                                         jumbolen = ntohl(jumbolen);
1161                                         if (jumbolen <= IPV6_MAXPACKET)
1162                                                 goto drop;
1163                                         if (sizeof(struct ip6_hdr) + jumbolen !=
1164                                             m->m_pkthdr.len)
1165                                                 goto drop;
1166                                         break;
1167                                 default:
1168                                         break;
1169                                 }
1170                                 ooff += sizeof(opt) + opt.ip6o_len;
1171                         } while (ooff < optend);
1172
1173                         off = optend;
1174                         proto = ext.ip6e_nxt;
1175                         break;
1176                 default:
1177                         terminal = 1;
1178                         break;
1179                 }
1180         } while (!terminal);
1181
1182         /* jumbo payload option must be present, or plen > 0 */
1183         if (ntohs(h->ip6_plen) == 0)
1184                 plen = jumbolen;
1185         else
1186                 plen = ntohs(h->ip6_plen);
1187         if (plen == 0)
1188                 goto drop;
1189         if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1190                 goto shortpkt;
1191
1192         /* Enforce a minimum ttl, may cause endless packet loops */
1193         if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1194                 h->ip6_hlim = r->min_ttl;
1195
1196         return (PF_PASS);
1197
1198  fragment:
1199         if (ntohs(h->ip6_plen) == 0 || jumbolen)
1200                 goto drop;
1201         plen = ntohs(h->ip6_plen);
1202
1203         if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1204                 goto shortpkt;
1205         fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1206         if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1207                 goto badfrag;
1208
1209         /* do something about it */
1210         return (PF_PASS);
1211
1212  shortpkt:
1213         REASON_SET(reason, PFRES_SHORT);
1214         if (r != NULL && r->log)
1215                 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL);
1216         return (PF_DROP);
1217
1218  drop:
1219         REASON_SET(reason, PFRES_NORM);
1220         if (r != NULL && r->log)
1221                 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL);
1222         return (PF_DROP);
1223
1224  badfrag:
1225         REASON_SET(reason, PFRES_FRAG);
1226         if (r != NULL && r->log)
1227                 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL);
1228         return (PF_DROP);
1229 }
1230 #endif
1231
1232 int
1233 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1234     int off, void *h, struct pf_pdesc *pd)
1235 {
1236         struct pf_rule  *r, *rm = NULL;
1237         struct tcphdr   *th = pd->hdr.tcp;
1238         int              rewrite = 0;
1239         u_short          reason;
1240         u_int8_t         flags;
1241         sa_family_t      af = pd->af;
1242
1243         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1244         while (r != NULL) {
1245                 r->evaluations++;
1246                 if (r->kif != NULL &&
1247                     (r->kif != kif && r->kif != kif->pfik_parent) == !r->ifnot)
1248                         r = r->skip[PF_SKIP_IFP].ptr;
1249                 else if (r->direction && r->direction != dir)
1250                         r = r->skip[PF_SKIP_DIR].ptr;
1251                 else if (r->af && r->af != af)
1252                         r = r->skip[PF_SKIP_AF].ptr;
1253                 else if (r->proto && r->proto != pd->proto)
1254                         r = r->skip[PF_SKIP_PROTO].ptr;
1255                 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af, r->src.not))
1256                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1257                 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1258                             r->src.port[0], r->src.port[1], th->th_sport))
1259                         r = r->skip[PF_SKIP_SRC_PORT].ptr;
1260                 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af, r->dst.not))
1261                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
1262                 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1263                             r->dst.port[0], r->dst.port[1], th->th_dport))
1264                         r = r->skip[PF_SKIP_DST_PORT].ptr;
1265                 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1266                             pf_osfp_fingerprint(pd, m, off, th),
1267                             r->os_fingerprint))
1268                         r = TAILQ_NEXT(r, entries);
1269                 else {
1270                         rm = r;
1271                         break;
1272                 }
1273         }
1274
1275         if (rm == NULL)
1276                 return (PF_PASS);
1277         else
1278                 r->packets++;
1279
1280         if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1281                 pd->flags |= PFDESC_TCP_NORM;
1282
1283         flags = th->th_flags;
1284         if (flags & TH_SYN) {
1285                 /* Illegal packet */
1286                 if (flags & TH_RST)
1287                         goto tcp_drop;
1288
1289                 if (flags & TH_FIN)
1290                         flags &= ~TH_FIN;
1291         } else {
1292                 /* Illegal packet */
1293                 if (!(flags & (TH_ACK|TH_RST)))
1294                         goto tcp_drop;
1295         }
1296
1297         if (!(flags & TH_ACK)) {
1298                 /* These flags are only valid if ACK is set */
1299                 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1300                         goto tcp_drop;
1301         }
1302
1303         /* Check for illegal header length */
1304         if (th->th_off < (sizeof(struct tcphdr) >> 2))
1305                 goto tcp_drop;
1306
1307         /* If flags changed, or reserved data set, then adjust */
1308         if (flags != th->th_flags || th->th_x2 != 0) {
1309                 u_int16_t       ov, nv;
1310
1311                 ov = *(u_int16_t *)(&th->th_ack + 1);
1312                 th->th_flags = flags;
1313                 th->th_x2 = 0;
1314                 nv = *(u_int16_t *)(&th->th_ack + 1);
1315
1316                 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv);
1317                 rewrite = 1;
1318         }
1319
1320         /* Remove urgent pointer, if TH_URG is not set */
1321         if (!(flags & TH_URG) && th->th_urp) {
1322                 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0);
1323                 th->th_urp = 0;
1324                 rewrite = 1;
1325         }
1326
1327         /* Process options */
1328         if (r->max_mss && pf_normalize_tcpopt(r, m, th, off))
1329                 rewrite = 1;
1330
1331         /* copy back packet headers if we sanitized */
1332         if (rewrite)
1333                 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1334
1335         return (PF_PASS);
1336
1337  tcp_drop:
1338         REASON_SET(&reason, PFRES_NORM);
1339         if (rm != NULL && r->log)
1340                 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL);
1341         return (PF_DROP);
1342 }
1343
1344 int
1345 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1346     struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1347 {
1348         u_int8_t hdr[60];
1349         u_int8_t *opt;
1350
1351         KASSERT((src->scrub == NULL), 
1352             ("pf_normalize_tcp_init: src->scrub != NULL"));
1353
1354         src->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
1355         if (src->scrub == NULL)
1356                 return (1);
1357         bzero(src->scrub, sizeof(*src->scrub));
1358
1359         switch (pd->af) {
1360 #ifdef INET
1361         case AF_INET: {
1362                 struct ip *h = mtod(m, struct ip *);
1363                 src->scrub->pfss_ttl = h->ip_ttl;
1364                 break;
1365         }
1366 #endif /* INET */
1367 #ifdef INET6
1368         case AF_INET6: {
1369                 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1370                 src->scrub->pfss_ttl = h->ip6_hlim;
1371                 break;
1372         }
1373 #endif /* INET6 */
1374         }
1375
1376
1377         /*
1378          * All normalizations below are only begun if we see the start of
1379          * the connections.  They must all set an enabled bit in pfss_flags
1380          */
1381         if ((th->th_flags & TH_SYN) == 0)
1382                 return (0);
1383
1384
1385         if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1386             pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1387                 /* Diddle with TCP options */
1388                 int hlen;
1389                 opt = hdr + sizeof(struct tcphdr);
1390                 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1391                 while (hlen >= TCPOLEN_TIMESTAMP) {
1392                         switch (*opt) {
1393                         case TCPOPT_EOL:        /* FALLTHROUGH */
1394                         case TCPOPT_NOP:
1395                                 opt++;
1396                                 hlen--;
1397                                 break;
1398                         case TCPOPT_TIMESTAMP:
1399                                 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1400                                         src->scrub->pfss_flags |=
1401                                             PFSS_TIMESTAMP;
1402                                         src->scrub->pfss_ts_mod = karc4random();
1403                                 }
1404                                 /* FALLTHROUGH */
1405                         default:
1406                                 hlen -= MAX(opt[1], 2);
1407                                 opt += MAX(opt[1], 2);
1408                                 break;
1409                         }
1410                 }
1411         }
1412
1413         return (0);
1414 }
1415
1416 void
1417 pf_normalize_tcp_cleanup(struct pf_state *state)
1418 {
1419         if (state->src.scrub)
1420                 pool_put(&pf_state_scrub_pl, state->src.scrub);
1421         if (state->dst.scrub)
1422                 pool_put(&pf_state_scrub_pl, state->dst.scrub);
1423
1424         /* Someday... flush the TCP segment reassembly descriptors. */
1425 }
1426
1427 int
1428 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1429     u_short *reason, struct tcphdr *th, struct pf_state_peer *src,
1430     struct pf_state_peer *dst, int *writeback)
1431 {
1432         u_int8_t hdr[60];
1433         u_int8_t *opt;
1434         int copyback = 0;
1435
1436         KASSERT((src->scrub || dst->scrub), 
1437             ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1438
1439         /*
1440          * Enforce the minimum TTL seen for this connection.  Negate a common
1441          * technique to evade an intrusion detection system and confuse
1442          * firewall state code.
1443          */
1444         switch (pd->af) {
1445 #ifdef INET
1446         case AF_INET: {
1447                 if (src->scrub) {
1448                         struct ip *h = mtod(m, struct ip *);
1449                         if (h->ip_ttl > src->scrub->pfss_ttl)
1450                                 src->scrub->pfss_ttl = h->ip_ttl;
1451                         h->ip_ttl = src->scrub->pfss_ttl;
1452                 }
1453                 break;
1454         }
1455 #endif /* INET */
1456 #ifdef INET6
1457         case AF_INET6: {
1458                 if (src->scrub) {
1459                         struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1460                         if (h->ip6_hlim > src->scrub->pfss_ttl)
1461                                 src->scrub->pfss_ttl = h->ip6_hlim;
1462                         h->ip6_hlim = src->scrub->pfss_ttl;
1463                 }
1464                 break;
1465         }
1466 #endif /* INET6 */
1467         }
1468
1469         if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1470             ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1471             (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1472             pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1473                 /* Diddle with TCP options */
1474                 int hlen;
1475                 opt = hdr + sizeof(struct tcphdr);
1476                 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1477                 while (hlen >= TCPOLEN_TIMESTAMP) {
1478                         switch (*opt) {
1479                         case TCPOPT_EOL:        /* FALLTHROUGH */
1480                         case TCPOPT_NOP:
1481                                 opt++;
1482                                 hlen--;
1483                                 break;
1484                         case TCPOPT_TIMESTAMP:
1485                                 /* Modulate the timestamps.  Can be used for
1486                                  * NAT detection, OS uptime determination or
1487                                  * reboot detection.
1488                                  */
1489                                 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1490                                         u_int32_t ts_value;
1491                                         if (src->scrub &&
1492                                             (src->scrub->pfss_flags &
1493                                             PFSS_TIMESTAMP)) {
1494                                                 memcpy(&ts_value, &opt[2],
1495                                                     sizeof(u_int32_t));
1496                                                 ts_value = htonl(ntohl(ts_value)
1497                                                     + src->scrub->pfss_ts_mod);
1498                                                 pf_change_a(&opt[2],
1499                                                     &th->th_sum, ts_value, 0);
1500                                                 copyback = 1;
1501                                         }
1502
1503                                         /* Modulate TS reply iff valid (!0) */
1504                                         memcpy(&ts_value, &opt[6],
1505                                             sizeof(u_int32_t));
1506                                         if (ts_value && dst->scrub &&
1507                                             (dst->scrub->pfss_flags &
1508                                             PFSS_TIMESTAMP)) {
1509                                                 ts_value = htonl(ntohl(ts_value)
1510                                                     - dst->scrub->pfss_ts_mod);
1511                                                 pf_change_a(&opt[6],
1512                                                     &th->th_sum, ts_value, 0);
1513                                                 copyback = 1;
1514                                         }
1515                                 }
1516                                 /* FALLTHROUGH */
1517                         default:
1518                                 hlen -= MAX(opt[1], 2);
1519                                 opt += MAX(opt[1], 2);
1520                                 break;
1521                         }
1522                 }
1523                 if (copyback) {
1524                         /* Copyback the options, caller copys back header */
1525                         *writeback = 1;
1526                         m_copyback(m, off + sizeof(struct tcphdr),
1527                             (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1528                             sizeof(struct tcphdr));
1529                 }
1530         }
1531
1532
1533         /* I have a dream....  TCP segment reassembly.... */
1534         return (0);
1535 }
1536
1537 int
1538 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1539     int off)
1540 {
1541         u_int16_t       *mss;
1542         int              thoff;
1543         int              opt, cnt, optlen = 0;
1544         int              rewrite = 0;
1545         u_char          *optp;
1546
1547         thoff = th->th_off << 2;
1548         cnt = thoff - sizeof(struct tcphdr);
1549         optp = mtod(m, caddr_t) + off + sizeof(struct tcphdr);
1550
1551         for (; cnt > 0; cnt -= optlen, optp += optlen) {
1552                 opt = optp[0];
1553                 if (opt == TCPOPT_EOL)
1554                         break;
1555                 if (opt == TCPOPT_NOP)
1556                         optlen = 1;
1557                 else {
1558                         if (cnt < 2)
1559                                 break;
1560                         optlen = optp[1];
1561                         if (optlen < 2 || optlen > cnt)
1562                                 break;
1563                 }
1564                 switch (opt) {
1565                 case TCPOPT_MAXSEG:
1566                         mss = (u_int16_t *)(optp + 2);
1567                         if ((ntohs(*mss)) > r->max_mss) {
1568                                 th->th_sum = pf_cksum_fixup(th->th_sum,
1569                                     *mss, htons(r->max_mss));
1570                                 *mss = htons(r->max_mss);
1571                                 rewrite = 1;
1572                         }
1573                         break;
1574                 default:
1575                         break;
1576                 }
1577         }
1578
1579         return (rewrite);
1580 }