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