]> git.saurik.com Git - apple/xnu.git/blob - bsd/net/pf_norm.c
xnu-6153.121.1.tar.gz
[apple/xnu.git] / bsd / net / pf_norm.c
1 /*
2 * Copyright (c) 2007-2018 Apple Inc. All rights reserved.
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 #include <netinet6/ip6_var.h>
88 #endif /* INET6 */
89
90 #include <net/pfvar.h>
91
92 struct pf_frent {
93 LIST_ENTRY(pf_frent) fr_next;
94 struct mbuf *fr_m;
95 #define fr_ip fr_u.fru_ipv4
96 #define fr_ip6 fr_u.fru_ipv6
97 union {
98 struct ip *fru_ipv4;
99 struct ip6_hdr *fru_ipv6;
100 } fr_u;
101 struct ip6_frag fr_ip6f_opt;
102 uint16_t fr_ip6f_hlen; /* total header length */
103 uint16_t fr_ip6f_extoff; /* last extension header offset or 0 */
104 };
105
106 struct pf_frcache {
107 LIST_ENTRY(pf_frcache) fr_next;
108 uint16_t fr_off;
109 uint16_t fr_end;
110 };
111
112 #define PFFRAG_SEENLAST 0x0001 /* Seen the last fragment for this */
113 #define PFFRAG_NOBUFFER 0x0002 /* Non-buffering fragment cache */
114 #define PFFRAG_DROP 0x0004 /* Drop all fragments */
115 #define BUFFER_FRAGMENTS(fr) (!((fr)->fr_flags & PFFRAG_NOBUFFER))
116
117 struct pf_fragment {
118 RB_ENTRY(pf_fragment) fr_entry;
119 TAILQ_ENTRY(pf_fragment) frag_next;
120 struct pf_addr fr_srcx;
121 struct pf_addr fr_dstx;
122 u_int8_t fr_p; /* protocol of this fragment */
123 u_int8_t fr_flags; /* status flags */
124 u_int16_t fr_max; /* fragment data max */
125 #define fr_id fr_uid.fru_id4
126 #define fr_id6 fr_uid.fru_id6
127 union {
128 u_int16_t fru_id4;
129 u_int32_t fru_id6;
130 } fr_uid;
131 int fr_af;
132 u_int32_t fr_timeout;
133 #define fr_queue fr_u.fru_queue
134 #define fr_cache fr_u.fru_cache
135 union {
136 LIST_HEAD(pf_fragq, pf_frent) fru_queue; /* buffering */
137 LIST_HEAD(pf_cacheq, pf_frcache) fru_cache; /* non-buf */
138 } fr_u;
139 uint32_t fr_csum_flags; /* checksum flags */
140 uint32_t fr_csum; /* partial checksum value */
141 uint16_t fr_ip6_maxlen; /* maximum length of a single fragment in IPv6 */
142 };
143
144 static TAILQ_HEAD(pf_fragqueue, pf_fragment) pf_fragqueue;
145 static TAILQ_HEAD(pf_cachequeue, pf_fragment) pf_cachequeue;
146
147 static __inline int pf_frag_compare(struct pf_fragment *,
148 struct pf_fragment *);
149 static RB_HEAD(pf_frag_tree, pf_fragment) pf_frag_tree, pf_cache_tree;
150 RB_PROTOTYPE_SC(__private_extern__, pf_frag_tree, pf_fragment, fr_entry,
151 pf_frag_compare);
152 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
153
154 /* Private prototypes */
155 static void pf_ip6hdr2key(struct pf_fragment *, struct ip6_hdr *,
156 struct ip6_frag *);
157 static void pf_ip2key(struct pf_fragment *, struct ip *);
158 static void pf_remove_fragment(struct pf_fragment *);
159 static void pf_flush_fragments(void);
160 static void pf_free_fragment(struct pf_fragment *);
161 static struct pf_fragment *pf_find_fragment_by_key(struct pf_fragment *,
162 struct pf_frag_tree *);
163 static __inline struct pf_fragment *
164 pf_find_fragment_by_ipv4_header(struct ip *, struct pf_frag_tree *);
165 static struct mbuf *pf_reassemble(struct mbuf *, struct pf_fragment **,
166 struct pf_frent *, int);
167 static struct mbuf *pf_fragcache(struct mbuf **, struct ip *,
168 struct pf_fragment **, int, int, int *);
169 static int pf_normalize_tcpopt(struct pf_rule *, int, struct pfi_kif *,
170 struct pf_pdesc *, pbuf_t *, struct tcphdr *, int, int *);
171 #if INET6
172 static __inline struct pf_fragment *
173 pf_find_fragment_by_ipv6_header(struct ip6_hdr *, struct ip6_frag *,
174 struct pf_frag_tree *);
175 static struct mbuf *pf_reassemble6(struct mbuf **, struct pf_fragment **,
176 struct pf_frent *, int);
177 static struct mbuf *pf_frag6cache(struct mbuf **, struct ip6_hdr*,
178 struct ip6_frag *, struct pf_fragment **, int, int, int, int *);
179 #endif /* INET6 */
180
181 #define DPFPRINTF(x) do { \
182 if (pf_status.debug >= PF_DEBUG_MISC) { \
183 printf("%s: ", __func__); \
184 printf x ; \
185 } \
186 } while (0)
187
188 /* Globals */
189 struct pool pf_frent_pl, pf_frag_pl;
190 static struct pool pf_cache_pl, pf_cent_pl;
191 struct pool pf_state_scrub_pl;
192
193 static int pf_nfrents, pf_ncache;
194
195 void
196 pf_normalize_init(void)
197 {
198 pool_init(&pf_frent_pl, sizeof(struct pf_frent), 0, 0, 0, "pffrent",
199 NULL);
200 pool_init(&pf_frag_pl, sizeof(struct pf_fragment), 0, 0, 0, "pffrag",
201 NULL);
202 pool_init(&pf_cache_pl, sizeof(struct pf_fragment), 0, 0, 0,
203 "pffrcache", NULL);
204 pool_init(&pf_cent_pl, sizeof(struct pf_frcache), 0, 0, 0, "pffrcent",
205 NULL);
206 pool_init(&pf_state_scrub_pl, sizeof(struct pf_state_scrub), 0, 0, 0,
207 "pfstscr", NULL);
208
209 pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
210 pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
211 pool_sethardlimit(&pf_cache_pl, PFFRAG_FRCACHE_HIWAT, NULL, 0);
212 pool_sethardlimit(&pf_cent_pl, PFFRAG_FRCENT_HIWAT, NULL, 0);
213
214 TAILQ_INIT(&pf_fragqueue);
215 TAILQ_INIT(&pf_cachequeue);
216 }
217
218 #if 0
219 void
220 pf_normalize_destroy(void)
221 {
222 pool_destroy(&pf_state_scrub_pl);
223 pool_destroy(&pf_cent_pl);
224 pool_destroy(&pf_cache_pl);
225 pool_destroy(&pf_frag_pl);
226 pool_destroy(&pf_frent_pl);
227 }
228 #endif
229
230 int
231 pf_normalize_isempty(void)
232 {
233 return TAILQ_EMPTY(&pf_fragqueue) && TAILQ_EMPTY(&pf_cachequeue);
234 }
235
236 static __inline int
237 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
238 {
239 int diff;
240
241 if ((diff = a->fr_af - b->fr_af)) {
242 return diff;
243 } else if ((diff = a->fr_p - b->fr_p)) {
244 return diff;
245 } else {
246 struct pf_addr *sa = &a->fr_srcx;
247 struct pf_addr *sb = &b->fr_srcx;
248 struct pf_addr *da = &a->fr_dstx;
249 struct pf_addr *db = &b->fr_dstx;
250
251 switch (a->fr_af) {
252 #ifdef INET
253 case AF_INET:
254 if ((diff = a->fr_id - b->fr_id)) {
255 return diff;
256 } else if (sa->v4addr.s_addr < sb->v4addr.s_addr) {
257 return -1;
258 } else if (sa->v4addr.s_addr > sb->v4addr.s_addr) {
259 return 1;
260 } else if (da->v4addr.s_addr < db->v4addr.s_addr) {
261 return -1;
262 } else if (da->v4addr.s_addr > db->v4addr.s_addr) {
263 return 1;
264 }
265 break;
266 #endif
267 #ifdef INET6
268 case AF_INET6:
269 if ((diff = a->fr_id6 - b->fr_id6)) {
270 return diff;
271 } else if (sa->addr32[3] < sb->addr32[3]) {
272 return -1;
273 } else if (sa->addr32[3] > sb->addr32[3]) {
274 return 1;
275 } else if (sa->addr32[2] < sb->addr32[2]) {
276 return -1;
277 } else if (sa->addr32[2] > sb->addr32[2]) {
278 return 1;
279 } else if (sa->addr32[1] < sb->addr32[1]) {
280 return -1;
281 } else if (sa->addr32[1] > sb->addr32[1]) {
282 return 1;
283 } else if (sa->addr32[0] < sb->addr32[0]) {
284 return -1;
285 } else if (sa->addr32[0] > sb->addr32[0]) {
286 return 1;
287 } else if (da->addr32[3] < db->addr32[3]) {
288 return -1;
289 } else if (da->addr32[3] > db->addr32[3]) {
290 return 1;
291 } else if (da->addr32[2] < db->addr32[2]) {
292 return -1;
293 } else if (da->addr32[2] > db->addr32[2]) {
294 return 1;
295 } else if (da->addr32[1] < db->addr32[1]) {
296 return -1;
297 } else if (da->addr32[1] > db->addr32[1]) {
298 return 1;
299 } else if (da->addr32[0] < db->addr32[0]) {
300 return -1;
301 } else if (da->addr32[0] > db->addr32[0]) {
302 return 1;
303 }
304 break;
305 #endif
306 default:
307 VERIFY(!0 && "only IPv4 and IPv6 supported!");
308 break;
309 }
310 }
311 return 0;
312 }
313
314 void
315 pf_purge_expired_fragments(void)
316 {
317 struct pf_fragment *frag;
318 u_int32_t expire = pf_time_second() -
319 pf_default_rule.timeout[PFTM_FRAG];
320
321 while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
322 VERIFY(BUFFER_FRAGMENTS(frag));
323 if (frag->fr_timeout > expire) {
324 break;
325 }
326
327 switch (frag->fr_af) {
328 case AF_INET:
329 DPFPRINTF(("expiring IPv4 %d(0x%llx) from queue.\n",
330 ntohs(frag->fr_id),
331 (uint64_t)VM_KERNEL_ADDRPERM(frag)));
332 break;
333 case AF_INET6:
334 DPFPRINTF(("expiring IPv6 %d(0x%llx) from queue.\n",
335 ntohl(frag->fr_id6),
336 (uint64_t)VM_KERNEL_ADDRPERM(frag)));
337 break;
338 default:
339 VERIFY(0 && "only IPv4 and IPv6 supported");
340 break;
341 }
342 pf_free_fragment(frag);
343 }
344
345 while ((frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue)) != NULL) {
346 VERIFY(!BUFFER_FRAGMENTS(frag));
347 if (frag->fr_timeout > expire) {
348 break;
349 }
350
351 switch (frag->fr_af) {
352 case AF_INET:
353 DPFPRINTF(("expiring IPv4 %d(0x%llx) from cache.\n",
354 ntohs(frag->fr_id),
355 (uint64_t)VM_KERNEL_ADDRPERM(frag)));
356 break;
357 case AF_INET6:
358 DPFPRINTF(("expiring IPv6 %d(0x%llx) from cache.\n",
359 ntohl(frag->fr_id6),
360 (uint64_t)VM_KERNEL_ADDRPERM(frag)));
361 break;
362 default:
363 VERIFY(0 && "only IPv4 and IPv6 supported");
364 break;
365 }
366 pf_free_fragment(frag);
367 VERIFY(TAILQ_EMPTY(&pf_cachequeue) ||
368 TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag);
369 }
370 }
371
372 /*
373 * Try to flush old fragments to make space for new ones
374 */
375
376 static void
377 pf_flush_fragments(void)
378 {
379 struct pf_fragment *frag;
380 int goal;
381
382 goal = pf_nfrents * 9 / 10;
383 DPFPRINTF(("trying to free > %d frents\n",
384 pf_nfrents - goal));
385 while (goal < pf_nfrents) {
386 frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue);
387 if (frag == NULL) {
388 break;
389 }
390 pf_free_fragment(frag);
391 }
392
393
394 goal = pf_ncache * 9 / 10;
395 DPFPRINTF(("trying to free > %d cache entries\n",
396 pf_ncache - goal));
397 while (goal < pf_ncache) {
398 frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue);
399 if (frag == NULL) {
400 break;
401 }
402 pf_free_fragment(frag);
403 }
404 }
405
406 /* Frees the fragments and all associated entries */
407
408 static void
409 pf_free_fragment(struct pf_fragment *frag)
410 {
411 struct pf_frent *frent;
412 struct pf_frcache *frcache;
413
414 /* Free all fragments */
415 if (BUFFER_FRAGMENTS(frag)) {
416 for (frent = LIST_FIRST(&frag->fr_queue); frent;
417 frent = LIST_FIRST(&frag->fr_queue)) {
418 LIST_REMOVE(frent, fr_next);
419
420 m_freem(frent->fr_m);
421 pool_put(&pf_frent_pl, frent);
422 pf_nfrents--;
423 }
424 } else {
425 for (frcache = LIST_FIRST(&frag->fr_cache); frcache;
426 frcache = LIST_FIRST(&frag->fr_cache)) {
427 LIST_REMOVE(frcache, fr_next);
428
429 VERIFY(LIST_EMPTY(&frag->fr_cache) ||
430 LIST_FIRST(&frag->fr_cache)->fr_off >
431 frcache->fr_end);
432
433 pool_put(&pf_cent_pl, frcache);
434 pf_ncache--;
435 }
436 }
437
438 pf_remove_fragment(frag);
439 }
440
441 static void
442 pf_ip6hdr2key(struct pf_fragment *key, struct ip6_hdr *ip6,
443 struct ip6_frag *fh)
444 {
445 key->fr_p = fh->ip6f_nxt;
446 key->fr_id6 = fh->ip6f_ident;
447 key->fr_af = AF_INET6;
448 key->fr_srcx.v6addr = ip6->ip6_src;
449 key->fr_dstx.v6addr = ip6->ip6_dst;
450 }
451
452 static void
453 pf_ip2key(struct pf_fragment *key, struct ip *ip)
454 {
455 key->fr_p = ip->ip_p;
456 key->fr_id = ip->ip_id;
457 key->fr_af = AF_INET;
458 key->fr_srcx.v4addr.s_addr = ip->ip_src.s_addr;
459 key->fr_dstx.v4addr.s_addr = ip->ip_dst.s_addr;
460 }
461
462 static struct pf_fragment *
463 pf_find_fragment_by_key(struct pf_fragment *key, struct pf_frag_tree *tree)
464 {
465 struct pf_fragment *frag;
466
467 frag = RB_FIND(pf_frag_tree, tree, key);
468 if (frag != NULL) {
469 /* XXX Are we sure we want to update the timeout? */
470 frag->fr_timeout = pf_time_second();
471 if (BUFFER_FRAGMENTS(frag)) {
472 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
473 TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
474 } else {
475 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
476 TAILQ_INSERT_HEAD(&pf_cachequeue, frag, frag_next);
477 }
478 }
479
480 return frag;
481 }
482
483 static __inline struct pf_fragment *
484 pf_find_fragment_by_ipv4_header(struct ip *ip, struct pf_frag_tree *tree)
485 {
486 struct pf_fragment key;
487 pf_ip2key(&key, ip);
488 return pf_find_fragment_by_key(&key, tree);
489 }
490
491 /* Removes a fragment from the fragment queue and frees the fragment */
492 static void
493 pf_remove_fragment(struct pf_fragment *frag)
494 {
495 if (BUFFER_FRAGMENTS(frag)) {
496 RB_REMOVE(pf_frag_tree, &pf_frag_tree, frag);
497 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
498 pool_put(&pf_frag_pl, frag);
499 } else {
500 RB_REMOVE(pf_frag_tree, &pf_cache_tree, frag);
501 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
502 pool_put(&pf_cache_pl, frag);
503 }
504 }
505
506 #define FR_IP_OFF(fr) ((ntohs((fr)->fr_ip->ip_off) & IP_OFFMASK) << 3)
507 static struct mbuf *
508 pf_reassemble(struct mbuf *m0, struct pf_fragment **frag,
509 struct pf_frent *frent, int mff)
510 {
511 struct mbuf *m = m0, *m2;
512 struct pf_frent *frea, *next;
513 struct pf_frent *frep = NULL;
514 struct ip *ip = frent->fr_ip;
515 uint32_t hlen = ip->ip_hl << 2;
516 u_int16_t off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
517 u_int16_t ip_len = ntohs(ip->ip_len) - ip->ip_hl * 4;
518 u_int16_t fr_max = ip_len + off;
519 uint32_t csum, csum_flags;
520
521 VERIFY(*frag == NULL || BUFFER_FRAGMENTS(*frag));
522
523 /*
524 * Leverage partial checksum offload for IP fragments. Narrow down
525 * the scope to cover only UDP without IP options, as that is the
526 * most common case.
527 *
528 * Perform 1's complement adjustment of octets that got included/
529 * excluded in the hardware-calculated checksum value. Ignore cases
530 * where the value includes the entire IPv4 header span, as the sum
531 * for those octets would already be 0 by the time we get here; IP
532 * has already performed its header checksum validation. Also take
533 * care of any trailing bytes and subtract out their partial sum.
534 */
535 if (ip->ip_p == IPPROTO_UDP && hlen == sizeof(struct ip) &&
536 (m->m_pkthdr.csum_flags &
537 (CSUM_DATA_VALID | CSUM_PARTIAL | CSUM_PSEUDO_HDR)) ==
538 (CSUM_DATA_VALID | CSUM_PARTIAL)) {
539 uint32_t start = m->m_pkthdr.csum_rx_start;
540 int32_t trailer = (m_pktlen(m) - ntohs(ip->ip_len));
541 uint32_t swbytes = (uint32_t)trailer;
542
543 csum = m->m_pkthdr.csum_rx_val;
544
545 ASSERT(trailer >= 0);
546 if ((start != 0 && start != hlen) || trailer != 0) {
547 #if BYTE_ORDER != BIG_ENDIAN
548 if (start < hlen) {
549 HTONS(ip->ip_len);
550 HTONS(ip->ip_off);
551 }
552 #endif /* BYTE_ORDER != BIG_ENDIAN */
553 /* callee folds in sum */
554 csum = m_adj_sum16(m, start, hlen,
555 (ip->ip_len - hlen), csum);
556 if (hlen > start) {
557 swbytes += (hlen - start);
558 } else {
559 swbytes += (start - hlen);
560 }
561 #if BYTE_ORDER != BIG_ENDIAN
562 if (start < hlen) {
563 NTOHS(ip->ip_off);
564 NTOHS(ip->ip_len);
565 }
566 #endif /* BYTE_ORDER != BIG_ENDIAN */
567 }
568 csum_flags = m->m_pkthdr.csum_flags;
569
570 if (swbytes != 0) {
571 udp_in_cksum_stats(swbytes);
572 }
573 if (trailer != 0) {
574 m_adj(m, -trailer);
575 }
576 } else {
577 csum = 0;
578 csum_flags = 0;
579 }
580
581 /* Invalidate checksum */
582 m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
583
584 /* Strip off ip header */
585 m->m_data += hlen;
586 m->m_len -= hlen;
587
588 /* Create a new reassembly queue for this packet */
589 if (*frag == NULL) {
590 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
591 if (*frag == NULL) {
592 pf_flush_fragments();
593 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
594 if (*frag == NULL) {
595 goto drop_fragment;
596 }
597 }
598
599 (*frag)->fr_flags = 0;
600 (*frag)->fr_max = 0;
601 (*frag)->fr_af = AF_INET;
602 (*frag)->fr_srcx.v4addr = frent->fr_ip->ip_src;
603 (*frag)->fr_dstx.v4addr = frent->fr_ip->ip_dst;
604 (*frag)->fr_p = frent->fr_ip->ip_p;
605 (*frag)->fr_id = frent->fr_ip->ip_id;
606 (*frag)->fr_timeout = pf_time_second();
607 if (csum_flags != 0) {
608 (*frag)->fr_csum_flags = csum_flags;
609 (*frag)->fr_csum = csum;
610 }
611 LIST_INIT(&(*frag)->fr_queue);
612
613 RB_INSERT(pf_frag_tree, &pf_frag_tree, *frag);
614 TAILQ_INSERT_HEAD(&pf_fragqueue, *frag, frag_next);
615
616 /* We do not have a previous fragment */
617 frep = NULL;
618 goto insert;
619 }
620
621 /*
622 * If this fragment contains similar checksum offload info
623 * as that of the existing ones, accumulate checksum. Otherwise,
624 * invalidate checksum offload info for the entire datagram.
625 */
626 if (csum_flags != 0 && csum_flags == (*frag)->fr_csum_flags) {
627 (*frag)->fr_csum += csum;
628 } else if ((*frag)->fr_csum_flags != 0) {
629 (*frag)->fr_csum_flags = 0;
630 }
631
632 /*
633 * Find a fragment after the current one:
634 * - off contains the real shifted offset.
635 */
636 LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
637 if (FR_IP_OFF(frea) > off) {
638 break;
639 }
640 frep = frea;
641 }
642
643 VERIFY(frep != NULL || frea != NULL);
644
645 if (frep != NULL &&
646 FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl *
647 4 > off) {
648 u_int16_t precut;
649
650 precut = FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) -
651 frep->fr_ip->ip_hl * 4 - off;
652 if (precut >= ip_len) {
653 goto drop_fragment;
654 }
655 m_adj(frent->fr_m, precut);
656 DPFPRINTF(("overlap -%d\n", precut));
657 /* Enforce 8 byte boundaries */
658 ip->ip_off = htons(ntohs(ip->ip_off) + (precut >> 3));
659 off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
660 ip_len -= precut;
661 ip->ip_len = htons(ip_len);
662 }
663
664 for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
665 frea = next) {
666 u_int16_t aftercut;
667
668 aftercut = ip_len + off - FR_IP_OFF(frea);
669 DPFPRINTF(("adjust overlap %d\n", aftercut));
670 if (aftercut < ntohs(frea->fr_ip->ip_len) - frea->fr_ip->ip_hl
671 * 4) {
672 frea->fr_ip->ip_len =
673 htons(ntohs(frea->fr_ip->ip_len) - aftercut);
674 frea->fr_ip->ip_off = htons(ntohs(frea->fr_ip->ip_off) +
675 (aftercut >> 3));
676 m_adj(frea->fr_m, aftercut);
677 break;
678 }
679
680 /* This fragment is completely overlapped, lose it */
681 next = LIST_NEXT(frea, fr_next);
682 m_freem(frea->fr_m);
683 LIST_REMOVE(frea, fr_next);
684 pool_put(&pf_frent_pl, frea);
685 pf_nfrents--;
686 }
687
688 insert:
689 /* Update maximum data size */
690 if ((*frag)->fr_max < fr_max) {
691 (*frag)->fr_max = fr_max;
692 }
693 /* This is the last segment */
694 if (!mff) {
695 (*frag)->fr_flags |= PFFRAG_SEENLAST;
696 }
697
698 if (frep == NULL) {
699 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
700 } else {
701 LIST_INSERT_AFTER(frep, frent, fr_next);
702 }
703
704 /* Check if we are completely reassembled */
705 if (!((*frag)->fr_flags & PFFRAG_SEENLAST)) {
706 return NULL;
707 }
708
709 /* Check if we have all the data */
710 off = 0;
711 for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
712 next = LIST_NEXT(frep, fr_next);
713
714 off += ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl * 4;
715 if (off < (*frag)->fr_max &&
716 (next == NULL || FR_IP_OFF(next) != off)) {
717 DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
718 off, next == NULL ? -1 : FR_IP_OFF(next),
719 (*frag)->fr_max));
720 return NULL;
721 }
722 }
723 DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
724 if (off < (*frag)->fr_max) {
725 return NULL;
726 }
727
728 /* We have all the data */
729 frent = LIST_FIRST(&(*frag)->fr_queue);
730 VERIFY(frent != NULL);
731 if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
732 DPFPRINTF(("drop: too big: %d\n", off));
733 pf_free_fragment(*frag);
734 *frag = NULL;
735 return NULL;
736 }
737 next = LIST_NEXT(frent, fr_next);
738
739 /* Magic from ip_input */
740 ip = frent->fr_ip;
741 m = frent->fr_m;
742 m2 = m->m_next;
743 m->m_next = NULL;
744 m_cat(m, m2);
745 pool_put(&pf_frent_pl, frent);
746 pf_nfrents--;
747 for (frent = next; frent != NULL; frent = next) {
748 next = LIST_NEXT(frent, fr_next);
749
750 m2 = frent->fr_m;
751 pool_put(&pf_frent_pl, frent);
752 pf_nfrents--;
753 m_cat(m, m2);
754 }
755
756 ip->ip_src = (*frag)->fr_srcx.v4addr;
757 ip->ip_dst = (*frag)->fr_dstx.v4addr;
758
759 if ((*frag)->fr_csum_flags != 0) {
760 csum = (*frag)->fr_csum;
761
762 ADDCARRY(csum);
763
764 m->m_pkthdr.csum_rx_val = csum;
765 m->m_pkthdr.csum_rx_start = sizeof(struct ip);
766 m->m_pkthdr.csum_flags = (*frag)->fr_csum_flags;
767 } else if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
768 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
769 /* loopback checksums are always OK */
770 m->m_pkthdr.csum_data = 0xffff;
771 m->m_pkthdr.csum_flags =
772 CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
773 CSUM_IP_CHECKED | CSUM_IP_VALID;
774 }
775
776 /* Remove from fragment queue */
777 pf_remove_fragment(*frag);
778 *frag = NULL;
779
780 hlen = ip->ip_hl << 2;
781 ip->ip_len = htons(off + hlen);
782 m->m_len += hlen;
783 m->m_data -= hlen;
784
785 /* some debugging cruft by sklower, below, will go away soon */
786 /* XXX this should be done elsewhere */
787 if (m->m_flags & M_PKTHDR) {
788 int plen = 0;
789 for (m2 = m; m2; m2 = m2->m_next) {
790 plen += m2->m_len;
791 }
792 m->m_pkthdr.len = plen;
793 }
794
795 DPFPRINTF(("complete: 0x%llx(%d)\n",
796 (uint64_t)VM_KERNEL_ADDRPERM(m), ntohs(ip->ip_len)));
797 return m;
798
799 drop_fragment:
800 /* Oops - fail safe - drop packet */
801 pool_put(&pf_frent_pl, frent);
802 pf_nfrents--;
803 m_freem(m);
804 return NULL;
805 }
806
807 static struct mbuf *
808 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
809 int drop, int *nomem)
810 {
811 struct mbuf *m = *m0;
812 struct pf_frcache *frp, *fra, *cur = NULL;
813 int ip_len = ntohs(h->ip_len) - (h->ip_hl << 2);
814 u_int16_t off = ntohs(h->ip_off) << 3;
815 u_int16_t fr_max = ip_len + off;
816 int hosed = 0;
817
818 VERIFY(*frag == NULL || !BUFFER_FRAGMENTS(*frag));
819
820 /* Create a new range queue for this packet */
821 if (*frag == NULL) {
822 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
823 if (*frag == NULL) {
824 pf_flush_fragments();
825 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
826 if (*frag == NULL) {
827 goto no_mem;
828 }
829 }
830
831 /* Get an entry for the queue */
832 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
833 if (cur == NULL) {
834 pool_put(&pf_cache_pl, *frag);
835 *frag = NULL;
836 goto no_mem;
837 }
838 pf_ncache++;
839
840 (*frag)->fr_flags = PFFRAG_NOBUFFER;
841 (*frag)->fr_max = 0;
842 (*frag)->fr_af = AF_INET;
843 (*frag)->fr_srcx.v4addr = h->ip_src;
844 (*frag)->fr_dstx.v4addr = h->ip_dst;
845 (*frag)->fr_p = h->ip_p;
846 (*frag)->fr_id = h->ip_id;
847 (*frag)->fr_timeout = pf_time_second();
848
849 cur->fr_off = off;
850 cur->fr_end = fr_max;
851 LIST_INIT(&(*frag)->fr_cache);
852 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
853
854 RB_INSERT(pf_frag_tree, &pf_cache_tree, *frag);
855 TAILQ_INSERT_HEAD(&pf_cachequeue, *frag, frag_next);
856
857 DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off,
858 fr_max));
859
860 goto pass;
861 }
862
863 /*
864 * Find a fragment after the current one:
865 * - off contains the real shifted offset.
866 */
867 frp = NULL;
868 LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
869 if (fra->fr_off > off) {
870 break;
871 }
872 frp = fra;
873 }
874
875 VERIFY(frp != NULL || fra != NULL);
876
877 if (frp != NULL) {
878 int precut;
879
880 precut = frp->fr_end - off;
881 if (precut >= ip_len) {
882 /* Fragment is entirely a duplicate */
883 DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
884 h->ip_id, frp->fr_off, frp->fr_end, off, fr_max));
885 goto drop_fragment;
886 }
887 if (precut == 0) {
888 /* They are adjacent. Fixup cache entry */
889 DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
890 h->ip_id, frp->fr_off, frp->fr_end, off, fr_max));
891 frp->fr_end = fr_max;
892 } else if (precut > 0) {
893 /*
894 * The first part of this payload overlaps with a
895 * fragment that has already been passed.
896 * Need to trim off the first part of the payload.
897 * But to do so easily, we need to create another
898 * mbuf to throw the original header into.
899 */
900
901 DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
902 h->ip_id, precut, frp->fr_off, frp->fr_end, off,
903 fr_max));
904
905 off += precut;
906 fr_max -= precut;
907 /* Update the previous frag to encompass this one */
908 frp->fr_end = fr_max;
909
910 if (!drop) {
911 /*
912 * XXX Optimization opportunity
913 * This is a very heavy way to trim the payload.
914 * we could do it much faster by diddling mbuf
915 * internals but that would be even less legible
916 * than this mbuf magic. For my next trick,
917 * I'll pull a rabbit out of my laptop.
918 */
919 *m0 = m_copym(m, 0, h->ip_hl << 2, M_NOWAIT);
920 if (*m0 == NULL) {
921 goto no_mem;
922 }
923 VERIFY((*m0)->m_next == NULL);
924 m_adj(m, precut + (h->ip_hl << 2));
925 m_cat(*m0, m);
926 m = *m0;
927 if (m->m_flags & M_PKTHDR) {
928 int plen = 0;
929 struct mbuf *t;
930 for (t = m; t; t = t->m_next) {
931 plen += t->m_len;
932 }
933 m->m_pkthdr.len = plen;
934 }
935
936
937 h = mtod(m, struct ip *);
938
939
940 VERIFY((int)m->m_len ==
941 ntohs(h->ip_len) - precut);
942 h->ip_off = htons(ntohs(h->ip_off) +
943 (precut >> 3));
944 h->ip_len = htons(ntohs(h->ip_len) - precut);
945 } else {
946 hosed++;
947 }
948 } else {
949 /* There is a gap between fragments */
950
951 DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
952 h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
953 fr_max));
954
955 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
956 if (cur == NULL) {
957 goto no_mem;
958 }
959 pf_ncache++;
960
961 cur->fr_off = off;
962 cur->fr_end = fr_max;
963 LIST_INSERT_AFTER(frp, cur, fr_next);
964 }
965 }
966
967 if (fra != NULL) {
968 int aftercut;
969 int merge = 0;
970
971 aftercut = fr_max - fra->fr_off;
972 if (aftercut == 0) {
973 /* Adjacent fragments */
974 DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
975 h->ip_id, off, fr_max, fra->fr_off, fra->fr_end));
976 fra->fr_off = off;
977 merge = 1;
978 } else if (aftercut > 0) {
979 /* Need to chop off the tail of this fragment */
980 DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
981 h->ip_id, aftercut, off, fr_max, fra->fr_off,
982 fra->fr_end));
983 fra->fr_off = off;
984 fr_max -= aftercut;
985
986 merge = 1;
987
988 if (!drop) {
989 m_adj(m, -aftercut);
990 if (m->m_flags & M_PKTHDR) {
991 int plen = 0;
992 struct mbuf *t;
993 for (t = m; t; t = t->m_next) {
994 plen += t->m_len;
995 }
996 m->m_pkthdr.len = plen;
997 }
998 h = mtod(m, struct ip *);
999 VERIFY((int)m->m_len ==
1000 ntohs(h->ip_len) - aftercut);
1001 h->ip_len = htons(ntohs(h->ip_len) - aftercut);
1002 } else {
1003 hosed++;
1004 }
1005 } else if (frp == NULL) {
1006 /* There is a gap between fragments */
1007 DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
1008 h->ip_id, -aftercut, off, fr_max, fra->fr_off,
1009 fra->fr_end));
1010
1011 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
1012 if (cur == NULL) {
1013 goto no_mem;
1014 }
1015 pf_ncache++;
1016
1017 cur->fr_off = off;
1018 cur->fr_end = fr_max;
1019 LIST_INSERT_BEFORE(fra, cur, fr_next);
1020 }
1021
1022
1023 /* Need to glue together two separate fragment descriptors */
1024 if (merge) {
1025 if (cur && fra->fr_off <= cur->fr_end) {
1026 /* Need to merge in a previous 'cur' */
1027 DPFPRINTF(("fragcache[%d]: adjacent(merge "
1028 "%d-%d) %d-%d (%d-%d)\n",
1029 h->ip_id, cur->fr_off, cur->fr_end, off,
1030 fr_max, fra->fr_off, fra->fr_end));
1031 fra->fr_off = cur->fr_off;
1032 LIST_REMOVE(cur, fr_next);
1033 pool_put(&pf_cent_pl, cur);
1034 pf_ncache--;
1035 cur = NULL;
1036 } else if (frp && fra->fr_off <= frp->fr_end) {
1037 /* Need to merge in a modified 'frp' */
1038 VERIFY(cur == NULL);
1039 DPFPRINTF(("fragcache[%d]: adjacent(merge "
1040 "%d-%d) %d-%d (%d-%d)\n",
1041 h->ip_id, frp->fr_off, frp->fr_end, off,
1042 fr_max, fra->fr_off, fra->fr_end));
1043 fra->fr_off = frp->fr_off;
1044 LIST_REMOVE(frp, fr_next);
1045 pool_put(&pf_cent_pl, frp);
1046 pf_ncache--;
1047 frp = NULL;
1048 }
1049 }
1050 }
1051
1052 if (hosed) {
1053 /*
1054 * We must keep tracking the overall fragment even when
1055 * we're going to drop it anyway so that we know when to
1056 * free the overall descriptor. Thus we drop the frag late.
1057 */
1058 goto drop_fragment;
1059 }
1060
1061
1062 pass:
1063 /* Update maximum data size */
1064 if ((*frag)->fr_max < fr_max) {
1065 (*frag)->fr_max = fr_max;
1066 }
1067
1068 /* This is the last segment */
1069 if (!mff) {
1070 (*frag)->fr_flags |= PFFRAG_SEENLAST;
1071 }
1072
1073 /* Check if we are completely reassembled */
1074 if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
1075 LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
1076 LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
1077 /* Remove from fragment queue */
1078 DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
1079 (*frag)->fr_max));
1080 pf_free_fragment(*frag);
1081 *frag = NULL;
1082 }
1083
1084 return m;
1085
1086 no_mem:
1087 *nomem = 1;
1088
1089 /* Still need to pay attention to !IP_MF */
1090 if (!mff && *frag != NULL) {
1091 (*frag)->fr_flags |= PFFRAG_SEENLAST;
1092 }
1093
1094 m_freem(m);
1095 return NULL;
1096
1097 drop_fragment:
1098
1099 /* Still need to pay attention to !IP_MF */
1100 if (!mff && *frag != NULL) {
1101 (*frag)->fr_flags |= PFFRAG_SEENLAST;
1102 }
1103
1104 if (drop) {
1105 /* This fragment has been deemed bad. Don't reass */
1106 if (((*frag)->fr_flags & PFFRAG_DROP) == 0) {
1107 DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
1108 h->ip_id));
1109 }
1110 (*frag)->fr_flags |= PFFRAG_DROP;
1111 }
1112
1113 m_freem(m);
1114 return NULL;
1115 }
1116
1117 #if INET6
1118 #define FR_IP6_OFF(fr) \
1119 (ntohs((fr)->fr_ip6f_opt.ip6f_offlg & IP6F_OFF_MASK))
1120 #define FR_IP6_PLEN(fr) (ntohs((fr)->fr_ip6->ip6_plen))
1121 struct mbuf *
1122 pf_reassemble6(struct mbuf **m0, struct pf_fragment **frag,
1123 struct pf_frent *frent, int mff)
1124 {
1125 struct mbuf *m, *m2;
1126 struct pf_frent *frea, *frep, *next;
1127 struct ip6_hdr *ip6;
1128 struct ip6_frag *ip6f;
1129 int plen, off, fr_max, pktlen;
1130 uint32_t uoff, csum, csum_flags;
1131
1132 VERIFY(*frag == NULL || BUFFER_FRAGMENTS(*frag));
1133 m = *m0;
1134 frep = NULL;
1135 ip6 = frent->fr_ip6;
1136 ip6f = &frent->fr_ip6f_opt;
1137 off = FR_IP6_OFF(frent);
1138 uoff = frent->fr_ip6f_hlen;
1139 plen = FR_IP6_PLEN(frent);
1140 fr_max = off + plen - (frent->fr_ip6f_hlen - sizeof(*ip6));
1141 pktlen = plen + sizeof(*ip6);
1142
1143 DPFPRINTF(("0x%llx IPv6 frag plen %u off %u fr_ip6f_hlen %u "
1144 "fr_max %u m_len %u\n", (uint64_t)VM_KERNEL_ADDRPERM(m), plen, off,
1145 frent->fr_ip6f_hlen, fr_max, m->m_len));
1146
1147 /*
1148 * Leverage partial checksum offload for simple UDP/IP fragments,
1149 * as that is the most common case.
1150 *
1151 * Perform 1's complement adjustment of octets that got included/
1152 * excluded in the hardware-calculated checksum value. Also take
1153 * care of any trailing bytes and subtract out their partial sum.
1154 */
1155 if (ip6f->ip6f_nxt == IPPROTO_UDP &&
1156 uoff == (sizeof(*ip6) + sizeof(*ip6f)) &&
1157 (m->m_pkthdr.csum_flags &
1158 (CSUM_DATA_VALID | CSUM_PARTIAL | CSUM_PSEUDO_HDR)) ==
1159 (CSUM_DATA_VALID | CSUM_PARTIAL)) {
1160 uint32_t start = m->m_pkthdr.csum_rx_start;
1161 uint32_t ip_len = (sizeof(*ip6) + ntohs(ip6->ip6_plen));
1162 int32_t trailer = (m_pktlen(m) - ip_len);
1163 uint32_t swbytes = (uint32_t)trailer;
1164
1165 csum = m->m_pkthdr.csum_rx_val;
1166
1167 ASSERT(trailer >= 0);
1168 if (start != uoff || trailer != 0) {
1169 uint16_t s = 0, d = 0;
1170
1171 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1172 s = ip6->ip6_src.s6_addr16[1];
1173 ip6->ip6_src.s6_addr16[1] = 0;
1174 }
1175 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1176 d = ip6->ip6_dst.s6_addr16[1];
1177 ip6->ip6_dst.s6_addr16[1] = 0;
1178 }
1179
1180 /* callee folds in sum */
1181 csum = m_adj_sum16(m, start, uoff,
1182 (ip_len - uoff), csum);
1183 if (uoff > start) {
1184 swbytes += (uoff - start);
1185 } else {
1186 swbytes += (start - uoff);
1187 }
1188
1189 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
1190 ip6->ip6_src.s6_addr16[1] = s;
1191 }
1192 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1193 ip6->ip6_dst.s6_addr16[1] = d;
1194 }
1195 }
1196 csum_flags = m->m_pkthdr.csum_flags;
1197
1198 if (swbytes != 0) {
1199 udp_in6_cksum_stats(swbytes);
1200 }
1201 if (trailer != 0) {
1202 m_adj(m, -trailer);
1203 }
1204 } else {
1205 csum = 0;
1206 csum_flags = 0;
1207 }
1208
1209 /* Invalidate checksum */
1210 m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
1211
1212 /* strip off headers up to the fragment payload */
1213 m->m_data += frent->fr_ip6f_hlen;
1214 m->m_len -= frent->fr_ip6f_hlen;
1215
1216 /* Create a new reassembly queue for this packet */
1217 if (*frag == NULL) {
1218 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
1219 if (*frag == NULL) {
1220 pf_flush_fragments();
1221 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
1222 if (*frag == NULL) {
1223 goto drop_fragment;
1224 }
1225 }
1226
1227 (*frag)->fr_flags = 0;
1228 (*frag)->fr_max = 0;
1229 (*frag)->fr_ip6_maxlen = pktlen;
1230 (*frag)->fr_af = AF_INET6;
1231 (*frag)->fr_srcx.v6addr = frent->fr_ip6->ip6_src;
1232 (*frag)->fr_dstx.v6addr = frent->fr_ip6->ip6_dst;
1233 (*frag)->fr_p = frent->fr_ip6f_opt.ip6f_nxt;
1234 (*frag)->fr_id6 = frent->fr_ip6f_opt.ip6f_ident;
1235 (*frag)->fr_timeout = pf_time_second();
1236 if (csum_flags != 0) {
1237 (*frag)->fr_csum_flags = csum_flags;
1238 (*frag)->fr_csum = csum;
1239 }
1240 LIST_INIT(&(*frag)->fr_queue);
1241
1242 RB_INSERT(pf_frag_tree, &pf_frag_tree, *frag);
1243 TAILQ_INSERT_HEAD(&pf_fragqueue, *frag, frag_next);
1244
1245 /* We do not have a previous fragment */
1246 frep = NULL;
1247 goto insert;
1248 }
1249
1250 /* Remember maximum fragment len for refragmentation */
1251 if (pktlen > (*frag)->fr_ip6_maxlen) {
1252 (*frag)->fr_ip6_maxlen = pktlen;
1253 }
1254 /*
1255 * If this fragment contains similar checksum offload info
1256 * as that of the existing ones, accumulate checksum. Otherwise,
1257 * invalidate checksum offload info for the entire datagram.
1258 */
1259 if (csum_flags != 0 && csum_flags == (*frag)->fr_csum_flags) {
1260 (*frag)->fr_csum += csum;
1261 } else if ((*frag)->fr_csum_flags != 0) {
1262 (*frag)->fr_csum_flags = 0;
1263 }
1264
1265 /*
1266 * Find a fragment after the current one:
1267 * - off contains the real shifted offset.
1268 */
1269 LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
1270 if (FR_IP6_OFF(frea) > off) {
1271 break;
1272 }
1273 frep = frea;
1274 }
1275
1276 VERIFY(frep != NULL || frea != NULL);
1277
1278 if (frep != NULL &&
1279 FR_IP6_OFF(frep) + FR_IP6_PLEN(frep) - frep->fr_ip6f_hlen > off) {
1280 u_int16_t precut;
1281
1282 precut = FR_IP6_OFF(frep) + FR_IP6_PLEN(frep) -
1283 frep->fr_ip6f_hlen - off;
1284 if (precut >= plen) {
1285 goto drop_fragment;
1286 }
1287 m_adj(frent->fr_m, precut);
1288 DPFPRINTF(("overlap -%d\n", precut));
1289 /* Enforce 8 byte boundaries */
1290 frent->fr_ip6f_opt.ip6f_offlg =
1291 htons(ntohs(frent->fr_ip6f_opt.ip6f_offlg) +
1292 (precut >> 3));
1293 off = FR_IP6_OFF(frent);
1294 plen -= precut;
1295 ip6->ip6_plen = htons(plen);
1296 }
1297
1298 for (; frea != NULL && plen + off > FR_IP6_OFF(frea); frea = next) {
1299 u_int16_t aftercut;
1300
1301 aftercut = plen + off - FR_IP6_OFF(frea);
1302 DPFPRINTF(("adjust overlap %d\n", aftercut));
1303 if (aftercut < FR_IP6_PLEN(frea) - frea->fr_ip6f_hlen) {
1304 frea->fr_ip6->ip6_plen = htons(FR_IP6_PLEN(frea) -
1305 aftercut);
1306 frea->fr_ip6f_opt.ip6f_offlg =
1307 htons(ntohs(frea->fr_ip6f_opt.ip6f_offlg) +
1308 (aftercut >> 3));
1309 m_adj(frea->fr_m, aftercut);
1310 break;
1311 }
1312
1313 /* This fragment is completely overlapped, lose it */
1314 next = LIST_NEXT(frea, fr_next);
1315 m_freem(frea->fr_m);
1316 LIST_REMOVE(frea, fr_next);
1317 pool_put(&pf_frent_pl, frea);
1318 pf_nfrents--;
1319 }
1320
1321 insert:
1322 /* Update maximum data size */
1323 if ((*frag)->fr_max < fr_max) {
1324 (*frag)->fr_max = fr_max;
1325 }
1326 /* This is the last segment */
1327 if (!mff) {
1328 (*frag)->fr_flags |= PFFRAG_SEENLAST;
1329 }
1330
1331 if (frep == NULL) {
1332 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
1333 } else {
1334 LIST_INSERT_AFTER(frep, frent, fr_next);
1335 }
1336
1337 /* Check if we are completely reassembled */
1338 if (!((*frag)->fr_flags & PFFRAG_SEENLAST)) {
1339 return NULL;
1340 }
1341
1342 /* Check if we have all the data */
1343 off = 0;
1344 for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
1345 next = LIST_NEXT(frep, fr_next);
1346 off += FR_IP6_PLEN(frep) - (frent->fr_ip6f_hlen - sizeof *ip6);
1347 DPFPRINTF(("frep at %d, next %d, max %d\n",
1348 off, next == NULL ? -1 : FR_IP6_OFF(next),
1349 (*frag)->fr_max));
1350 if (off < (*frag)->fr_max &&
1351 (next == NULL || FR_IP6_OFF(next) != off)) {
1352 DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
1353 off, next == NULL ? -1 : FR_IP6_OFF(next),
1354 (*frag)->fr_max));
1355 return NULL;
1356 }
1357 }
1358 DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
1359 if (off < (*frag)->fr_max) {
1360 return NULL;
1361 }
1362
1363 /* We have all the data */
1364 frent = LIST_FIRST(&(*frag)->fr_queue);
1365 VERIFY(frent != NULL);
1366 if (frent->fr_ip6f_hlen + off > IP_MAXPACKET) {
1367 DPFPRINTF(("drop: too big: %d\n", off));
1368 pf_free_fragment(*frag);
1369 *frag = NULL;
1370 return NULL;
1371 }
1372
1373 ASSERT(*frag != NULL);
1374 ASSERT(frent != NULL);
1375 next = LIST_NEXT(frent, fr_next);
1376 if (next == NULL) {
1377 DPFPRINTF(("drop: atomic fragment\n"));
1378 pf_free_fragment(*frag);
1379 *frag = NULL;
1380 return NULL;
1381 }
1382
1383 /* retrieve the values to be filled in to reassembled tag */
1384 uint16_t hdrlen, unfragpartlen, extoff, maxlen;
1385 uint32_t id;
1386
1387 /* Get total extension header length from the first fragment */
1388 hdrlen = frent->fr_ip6f_hlen - sizeof(struct ip6_frag);
1389 /*
1390 * Get total extension header length of per-fragment headers from the
1391 * subsequent fragment.
1392 */
1393 unfragpartlen = next->fr_ip6f_hlen - sizeof(struct ip6_frag);
1394 extoff = frent->fr_ip6f_extoff;
1395 maxlen = (*frag)->fr_ip6_maxlen;
1396 id = (*frag)->fr_id6;
1397
1398 ip6 = frent->fr_ip6;
1399 ip6->ip6_nxt = (*frag)->fr_p;
1400 ip6->ip6_plen = htons(off);
1401 ip6->ip6_src = (*frag)->fr_srcx.v6addr;
1402 ip6->ip6_dst = (*frag)->fr_dstx.v6addr;
1403
1404 if ((*frag)->fr_csum_flags != 0) {
1405 csum = (*frag)->fr_csum;
1406
1407 ADDCARRY(csum);
1408
1409 m->m_pkthdr.csum_rx_val = csum;
1410 m->m_pkthdr.csum_rx_start = sizeof(struct ip6_hdr);
1411 m->m_pkthdr.csum_flags = (*frag)->fr_csum_flags;
1412 } else if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
1413 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1414 /* loopback checksums are always OK */
1415 m->m_pkthdr.csum_data = 0xffff;
1416 m->m_pkthdr.csum_flags = CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1417 }
1418
1419 /* Remove from fragment queue */
1420 pf_remove_fragment(*frag);
1421 *frag = NULL;
1422
1423 m = frent->fr_m;
1424 m->m_len += sizeof(struct ip6_hdr);
1425 m->m_data -= sizeof(struct ip6_hdr);
1426 memmove(m->m_data, ip6, sizeof(struct ip6_hdr));
1427
1428 next = LIST_NEXT(frent, fr_next);
1429 pool_put(&pf_frent_pl, frent);
1430 pf_nfrents--;
1431 for (frent = next; next != NULL; frent = next) {
1432 m2 = frent->fr_m;
1433
1434 m_cat(m, m2);
1435 next = LIST_NEXT(frent, fr_next);
1436 pool_put(&pf_frent_pl, frent);
1437 pf_nfrents--;
1438 }
1439
1440 /* XXX this should be done elsewhere */
1441 if (m->m_flags & M_PKTHDR) {
1442 int len = 0;
1443 for (m2 = m; m2; m2 = m2->m_next) {
1444 len += m2->m_len;
1445 }
1446 m->m_pkthdr.len = len;
1447 }
1448
1449 DPFPRINTF(("complete: 0x%llx ip6_plen %d m_pkthdr.len %d\n",
1450 (uint64_t)VM_KERNEL_ADDRPERM(m), ntohs(ip6->ip6_plen),
1451 m->m_pkthdr.len));
1452
1453 /* Add the reassembled tag */
1454 struct m_tag *mtag;
1455 struct pf_fragment_tag *ftag;
1456 mtag = m_tag_create(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_PF_REASS,
1457 sizeof(*ftag), M_NOWAIT, m);
1458 if (mtag == NULL) {
1459 /* XXX: add stats */
1460 m_freem(m);
1461 return NULL;
1462 }
1463 ftag = (struct pf_fragment_tag *)(mtag + 1);
1464 ftag->ft_hdrlen = hdrlen;
1465 ftag->ft_unfragpartlen = unfragpartlen;
1466 ftag->ft_extoff = extoff;
1467 ftag->ft_maxlen = maxlen;
1468 ftag->ft_id = id;
1469 m_tag_prepend(m, mtag);
1470
1471 struct pf_mtag *pftag = pf_get_mtag(m);
1472 ASSERT(pftag != NULL);
1473 pftag->pftag_flags |= PF_TAG_REASSEMBLED;
1474 return m;
1475
1476 drop_fragment:
1477 /* Oops - fail safe - drop packet */
1478 pool_put(&pf_frent_pl, frent);
1479 --pf_nfrents;
1480 m_freem(m);
1481 return NULL;
1482 }
1483
1484 static struct mbuf *
1485 pf_frag6cache(struct mbuf **m0, struct ip6_hdr *h, struct ip6_frag *fh,
1486 struct pf_fragment **frag, int hlen, int mff, int drop, int *nomem)
1487 {
1488 struct mbuf *m = *m0;
1489 u_int16_t plen, off, fr_max;
1490 struct pf_frcache *frp, *fra, *cur = NULL;
1491 int hosed = 0;
1492
1493 VERIFY(*frag == NULL || !BUFFER_FRAGMENTS(*frag));
1494 m = *m0;
1495 off = ntohs(fh->ip6f_offlg & IP6F_OFF_MASK);
1496 plen = ntohs(h->ip6_plen) - (hlen - sizeof *h);
1497
1498 /*
1499 * Apple Modification: dimambro@apple.com. The hlen, being passed
1500 * into this function Includes all the headers associated with
1501 * the packet, and may include routing headers, so to get to
1502 * the data payload as stored in the original IPv6 header we need
1503 * to subtract al those headers and the IP header.
1504 *
1505 * The 'max' local variable should also contain the offset from the start
1506 * of the reassembled packet to the octet just past the end of the octets
1507 * in the current fragment where:
1508 * - 'off' is the offset from the start of the reassembled packet to the
1509 * first octet in the fragment,
1510 * - 'plen' is the length of the "payload data length" Excluding all the
1511 * IPv6 headers of the fragment.
1512 * - 'hlen' is computed in pf_normalize_ip6() as the offset from the start
1513 * of the IPv6 packet to the beginning of the data.
1514 */
1515 fr_max = off + plen;
1516
1517 DPFPRINTF(("0x%llx plen %u off %u fr_max %u\n",
1518 (uint64_t)VM_KERNEL_ADDRPERM(m), plen, off, fr_max));
1519
1520 /* Create a new range queue for this packet */
1521 if (*frag == NULL) {
1522 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
1523 if (*frag == NULL) {
1524 pf_flush_fragments();
1525 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
1526 if (*frag == NULL) {
1527 goto no_mem;
1528 }
1529 }
1530
1531 /* Get an entry for the queue */
1532 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
1533 if (cur == NULL) {
1534 pool_put(&pf_cache_pl, *frag);
1535 *frag = NULL;
1536 goto no_mem;
1537 }
1538 pf_ncache++;
1539
1540 (*frag)->fr_flags = PFFRAG_NOBUFFER;
1541 (*frag)->fr_max = 0;
1542 (*frag)->fr_af = AF_INET6;
1543 (*frag)->fr_srcx.v6addr = h->ip6_src;
1544 (*frag)->fr_dstx.v6addr = h->ip6_dst;
1545 (*frag)->fr_p = fh->ip6f_nxt;
1546 (*frag)->fr_id6 = fh->ip6f_ident;
1547 (*frag)->fr_timeout = pf_time_second();
1548
1549 cur->fr_off = off;
1550 cur->fr_end = fr_max;
1551 LIST_INIT(&(*frag)->fr_cache);
1552 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
1553
1554 RB_INSERT(pf_frag_tree, &pf_cache_tree, *frag);
1555 TAILQ_INSERT_HEAD(&pf_cachequeue, *frag, frag_next);
1556
1557 DPFPRINTF(("frag6cache[%d]: new %d-%d\n", ntohl(fh->ip6f_ident),
1558 off, fr_max));
1559
1560 goto pass;
1561 }
1562
1563 /*
1564 * Find a fragment after the current one:
1565 * - off contains the real shifted offset.
1566 */
1567 frp = NULL;
1568 LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
1569 if (fra->fr_off > off) {
1570 break;
1571 }
1572 frp = fra;
1573 }
1574
1575 VERIFY(frp != NULL || fra != NULL);
1576
1577 if (frp != NULL) {
1578 int precut;
1579
1580 precut = frp->fr_end - off;
1581 if (precut >= plen) {
1582 /* Fragment is entirely a duplicate */
1583 DPFPRINTF(("frag6cache[%u]: dead (%d-%d) %d-%d\n",
1584 ntohl(fh->ip6f_ident), frp->fr_off, frp->fr_end,
1585 off, fr_max));
1586 goto drop_fragment;
1587 }
1588 if (precut == 0) {
1589 /* They are adjacent. Fixup cache entry */
1590 DPFPRINTF(("frag6cache[%u]: adjacent (%d-%d) %d-%d\n",
1591 ntohl(fh->ip6f_ident), frp->fr_off, frp->fr_end,
1592 off, fr_max));
1593 frp->fr_end = fr_max;
1594 } else if (precut > 0) {
1595 /* The first part of this payload overlaps with a
1596 * fragment that has already been passed.
1597 * Need to trim off the first part of the payload.
1598 * But to do so easily, we need to create another
1599 * mbuf to throw the original header into.
1600 */
1601
1602 DPFPRINTF(("frag6cache[%u]: chop %d (%d-%d) %d-%d\n",
1603 ntohl(fh->ip6f_ident), precut, frp->fr_off,
1604 frp->fr_end, off, fr_max));
1605
1606 off += precut;
1607 fr_max -= precut;
1608 /* Update the previous frag to encompass this one */
1609 frp->fr_end = fr_max;
1610
1611 if (!drop) {
1612 /* XXX Optimization opportunity
1613 * This is a very heavy way to trim the payload.
1614 * we could do it much faster by diddling mbuf
1615 * internals but that would be even less legible
1616 * than this mbuf magic. For my next trick,
1617 * I'll pull a rabbit out of my laptop.
1618 */
1619 *m0 = m_copym(m, 0, hlen, M_NOWAIT);
1620 if (*m0 == NULL) {
1621 goto no_mem;
1622 }
1623 VERIFY((*m0)->m_next == NULL);
1624 m_adj(m, precut + hlen);
1625 m_cat(*m0, m);
1626 m = *m0;
1627 if (m->m_flags & M_PKTHDR) {
1628 int pktlen = 0;
1629 struct mbuf *t;
1630 for (t = m; t; t = t->m_next) {
1631 pktlen += t->m_len;
1632 }
1633 m->m_pkthdr.len = pktlen;
1634 }
1635
1636 h = mtod(m, struct ip6_hdr *);
1637
1638 VERIFY((int)m->m_len ==
1639 ntohs(h->ip6_plen) - precut);
1640 fh->ip6f_offlg &= ~IP6F_OFF_MASK;
1641 fh->ip6f_offlg |=
1642 htons(ntohs(fh->ip6f_offlg & IP6F_OFF_MASK)
1643 + (precut >> 3));
1644 h->ip6_plen = htons(ntohs(h->ip6_plen) -
1645 precut);
1646 } else {
1647 hosed++;
1648 }
1649 } else {
1650 /* There is a gap between fragments */
1651
1652 DPFPRINTF(("frag6cache[%u]: gap %d (%d-%d) %d-%d\n",
1653 ntohl(fh->ip6f_ident), -precut, frp->fr_off,
1654 frp->fr_end, off, fr_max));
1655
1656 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
1657 if (cur == NULL) {
1658 goto no_mem;
1659 }
1660 pf_ncache++;
1661
1662 cur->fr_off = off;
1663 cur->fr_end = fr_max;
1664 LIST_INSERT_AFTER(frp, cur, fr_next);
1665 }
1666 }
1667
1668 if (fra != NULL) {
1669 int aftercut;
1670 int merge = 0;
1671
1672 aftercut = fr_max - fra->fr_off;
1673 if (aftercut == 0) {
1674 /* Adjacent fragments */
1675 DPFPRINTF(("frag6cache[%u]: adjacent %d-%d (%d-%d)\n",
1676 ntohl(fh->ip6f_ident), off, fr_max, fra->fr_off,
1677 fra->fr_end));
1678 fra->fr_off = off;
1679 merge = 1;
1680 } else if (aftercut > 0) {
1681 /* Need to chop off the tail of this fragment */
1682 DPFPRINTF(("frag6cache[%u]: chop %d %d-%d (%d-%d)\n",
1683 ntohl(fh->ip6f_ident), aftercut, off, fr_max,
1684 fra->fr_off, fra->fr_end));
1685 fra->fr_off = off;
1686 fr_max -= aftercut;
1687
1688 merge = 1;
1689
1690 if (!drop) {
1691 m_adj(m, -aftercut);
1692 if (m->m_flags & M_PKTHDR) {
1693 int pktlen = 0;
1694 struct mbuf *t;
1695 for (t = m; t; t = t->m_next) {
1696 pktlen += t->m_len;
1697 }
1698 m->m_pkthdr.len = pktlen;
1699 }
1700 h = mtod(m, struct ip6_hdr *);
1701 VERIFY((int)m->m_len ==
1702 ntohs(h->ip6_plen) - aftercut);
1703 h->ip6_plen =
1704 htons(ntohs(h->ip6_plen) - aftercut);
1705 } else {
1706 hosed++;
1707 }
1708 } else if (frp == NULL) {
1709 /* There is a gap between fragments */
1710 DPFPRINTF(("frag6cache[%u]: gap %d %d-%d (%d-%d)\n",
1711 ntohl(fh->ip6f_ident), -aftercut, off, fr_max,
1712 fra->fr_off, fra->fr_end));
1713
1714 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
1715 if (cur == NULL) {
1716 goto no_mem;
1717 }
1718 pf_ncache++;
1719
1720 cur->fr_off = off;
1721 cur->fr_end = fr_max;
1722 LIST_INSERT_BEFORE(fra, cur, fr_next);
1723 }
1724
1725 /* Need to glue together two separate fragment descriptors */
1726 if (merge) {
1727 if (cur && fra->fr_off <= cur->fr_end) {
1728 /* Need to merge in a previous 'cur' */
1729 DPFPRINTF(("frag6cache[%u]: adjacent(merge "
1730 "%d-%d) %d-%d (%d-%d)\n",
1731 ntohl(fh->ip6f_ident), cur->fr_off,
1732 cur->fr_end, off, fr_max, fra->fr_off,
1733 fra->fr_end));
1734 fra->fr_off = cur->fr_off;
1735 LIST_REMOVE(cur, fr_next);
1736 pool_put(&pf_cent_pl, cur);
1737 pf_ncache--;
1738 cur = NULL;
1739 } else if (frp && fra->fr_off <= frp->fr_end) {
1740 /* Need to merge in a modified 'frp' */
1741 VERIFY(cur == NULL);
1742 DPFPRINTF(("frag6cache[%u]: adjacent(merge "
1743 "%d-%d) %d-%d (%d-%d)\n",
1744 ntohl(fh->ip6f_ident), frp->fr_off,
1745 frp->fr_end, off, fr_max, fra->fr_off,
1746 fra->fr_end));
1747 fra->fr_off = frp->fr_off;
1748 LIST_REMOVE(frp, fr_next);
1749 pool_put(&pf_cent_pl, frp);
1750 pf_ncache--;
1751 frp = NULL;
1752 }
1753 }
1754 }
1755
1756 if (hosed) {
1757 /*
1758 * We must keep tracking the overall fragment even when
1759 * we're going to drop it anyway so that we know when to
1760 * free the overall descriptor. Thus we drop the frag late.
1761 */
1762 goto drop_fragment;
1763 }
1764
1765 pass:
1766 /* Update maximum data size */
1767 if ((*frag)->fr_max < fr_max) {
1768 (*frag)->fr_max = fr_max;
1769 }
1770
1771 /* This is the last segment */
1772 if (!mff) {
1773 (*frag)->fr_flags |= PFFRAG_SEENLAST;
1774 }
1775
1776 /* Check if we are completely reassembled */
1777 if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
1778 LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
1779 LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
1780 /* Remove from fragment queue */
1781 DPFPRINTF(("frag6cache[%u]: done 0-%d\n",
1782 ntohl(fh->ip6f_ident), (*frag)->fr_max));
1783 pf_free_fragment(*frag);
1784 *frag = NULL;
1785 }
1786
1787 return m;
1788
1789 no_mem:
1790 *nomem = 1;
1791
1792 /* Still need to pay attention to !IP_MF */
1793 if (!mff && *frag != NULL) {
1794 (*frag)->fr_flags |= PFFRAG_SEENLAST;
1795 }
1796
1797 m_freem(m);
1798 return NULL;
1799
1800 drop_fragment:
1801
1802 /* Still need to pay attention to !IP_MF */
1803 if (!mff && *frag != NULL) {
1804 (*frag)->fr_flags |= PFFRAG_SEENLAST;
1805 }
1806
1807 if (drop) {
1808 /* This fragment has been deemed bad. Don't reass */
1809 if (((*frag)->fr_flags & PFFRAG_DROP) == 0) {
1810 DPFPRINTF(("frag6cache[%u]: dropping overall fragment\n",
1811 ntohl(fh->ip6f_ident)));
1812 }
1813 (*frag)->fr_flags |= PFFRAG_DROP;
1814 }
1815
1816 m_freem(m);
1817 return NULL;
1818 }
1819
1820 int
1821 pf_refragment6(struct ifnet *ifp, pbuf_t **pbufp, struct pf_fragment_tag *ftag)
1822 {
1823 struct mbuf *m;
1824 uint32_t frag_id;
1825 uint16_t hdrlen, extoff, maxlen, unfragpartlen;
1826 uint8_t proto;
1827 int error, action;
1828 uint8_t *lexthdrsp;
1829 struct route_in6 ip6route;
1830 struct route_in6 *ro;
1831 struct sockaddr_in6 *dst;
1832 struct ip6_hdr *hdr;
1833 struct pf_mtag *mtag;
1834 struct m_tag *tag;
1835
1836 if (pbufp == NULL || !pbuf_is_valid(*pbufp) || ftag == NULL) {
1837 panic("pf_route6: invalid parameters");
1838 /* NOT REACHED */
1839 }
1840 m = pbuf_to_mbuf(*pbufp, FALSE);
1841 hdr = mtod(m, struct ip6_hdr *);
1842 mtag = pf_find_mtag(m);
1843 hdrlen = ftag->ft_hdrlen - sizeof(struct ip6_hdr);
1844 extoff = ftag->ft_extoff;
1845 maxlen = ftag->ft_maxlen;
1846 frag_id = ftag->ft_id;
1847 unfragpartlen = ftag->ft_unfragpartlen;
1848 tag = (struct m_tag *)(void *)ftag;
1849 tag = tag - 1;
1850 m_tag_delete(m, tag);
1851 ftag = NULL;
1852 tag = NULL;
1853 mtag->pftag_flags &= ~PF_TAG_REASSEMBLED;
1854 ro = &ip6route;
1855 bzero((caddr_t)ro, sizeof(*ro));
1856 dst = (struct sockaddr_in6 *)&ro->ro_dst;
1857 dst->sin6_family = AF_INET6;
1858 dst->sin6_len = sizeof(*dst);
1859 dst->sin6_addr = hdr->ip6_dst;
1860
1861 if (extoff) {
1862 int off;
1863 struct mbuf *mexthdr;
1864
1865 /* Use protocol from next field of last extension header */
1866 mexthdr = m_getptr(m, extoff +
1867 offsetof(struct ip6_ext, ip6e_nxt), &off);
1868 ASSERT(mexthdr != NULL);
1869 lexthdrsp = (mtod(mexthdr, uint8_t *) + off);
1870 proto = *lexthdrsp;
1871 if (proto == IPPROTO_DSTOPTS) {
1872 struct ip6_ext ext;
1873 if (!pf_pull_hdr(*pbufp, off, &ext, sizeof(ext), NULL,
1874 NULL, AF_INET6)) {
1875 DPFPRINTF(("pkt too short"));
1876 action = PF_DROP;
1877 goto done;
1878 }
1879 proto = ext.ip6e_nxt;
1880 }
1881 } else {
1882 lexthdrsp = NULL;
1883 proto = hdr->ip6_nxt;
1884 }
1885
1886 /*
1887 * The MTU must be a multiple of 8 bytes, or we risk doing the
1888 * fragmentation wrong.
1889 */
1890 maxlen = maxlen & ~7;
1891
1892 error = ip6_do_fragmentation(&m, hdrlen, NULL, unfragpartlen,
1893 hdr, lexthdrsp, maxlen, proto, frag_id);
1894
1895 if (error == 0) {
1896 /*
1897 * PF_TAG_REFRAGMENTED flag set to indicate ip6_forward()
1898 * and pf_route6() that the mbuf contains a chain of fragments.
1899 */
1900 mtag->pftag_flags |= PF_TAG_REFRAGMENTED;
1901 action = PF_PASS;
1902 pbuf_init_mbuf(*pbufp, m, ifp);
1903 } else {
1904 DPFPRINTF(("refragment error %d", error));
1905 action = PF_DROP;
1906 goto done;
1907 }
1908 done:
1909 return action;
1910 }
1911 #endif /* INET6 */
1912
1913 int
1914 pf_normalize_ip(pbuf_t *pbuf, int dir, struct pfi_kif *kif, u_short *reason,
1915 struct pf_pdesc *pd)
1916 {
1917 struct mbuf *m;
1918 struct pf_rule *r;
1919 struct pf_frent *frent;
1920 struct pf_fragment *frag = NULL;
1921 struct ip *h = pbuf->pb_data;
1922 int mff = (ntohs(h->ip_off) & IP_MF);
1923 int hlen = h->ip_hl << 2;
1924 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1925 u_int16_t fr_max;
1926 int ip_len;
1927 int ip_off;
1928 int asd = 0;
1929 struct pf_ruleset *ruleset = NULL;
1930 struct ifnet *ifp = pbuf->pb_ifp;
1931
1932 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1933 while (r != NULL) {
1934 r->evaluations++;
1935 if (pfi_kif_match(r->kif, kif) == r->ifnot) {
1936 r = r->skip[PF_SKIP_IFP].ptr;
1937 } else if (r->direction && r->direction != dir) {
1938 r = r->skip[PF_SKIP_DIR].ptr;
1939 } else if (r->af && r->af != AF_INET) {
1940 r = r->skip[PF_SKIP_AF].ptr;
1941 } else if (r->proto && r->proto != h->ip_p) {
1942 r = r->skip[PF_SKIP_PROTO].ptr;
1943 } else if (PF_MISMATCHAW(&r->src.addr,
1944 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
1945 r->src.neg, kif)) {
1946 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1947 } else if (PF_MISMATCHAW(&r->dst.addr,
1948 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
1949 r->dst.neg, NULL)) {
1950 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1951 } else {
1952 if (r->anchor == NULL) {
1953 break;
1954 } else {
1955 pf_step_into_anchor(&asd, &ruleset,
1956 PF_RULESET_SCRUB, &r, NULL, NULL);
1957 }
1958 }
1959 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
1960 PF_RULESET_SCRUB, &r, NULL, NULL)) {
1961 break;
1962 }
1963 }
1964
1965 if (r == NULL || r->action == PF_NOSCRUB) {
1966 return PF_PASS;
1967 } else {
1968 r->packets[dir == PF_OUT]++;
1969 r->bytes[dir == PF_OUT] += pd->tot_len;
1970 }
1971
1972 /* Check for illegal packets */
1973 if (hlen < (int)sizeof(struct ip)) {
1974 goto drop;
1975 }
1976
1977 if (hlen > ntohs(h->ip_len)) {
1978 goto drop;
1979 }
1980
1981 /* Clear IP_DF if the rule uses the no-df option */
1982 if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1983 u_int16_t ipoff = h->ip_off;
1984
1985 h->ip_off &= htons(~IP_DF);
1986 h->ip_sum = pf_cksum_fixup(h->ip_sum, ipoff, h->ip_off, 0);
1987 }
1988
1989 /* We will need other tests here */
1990 if (!fragoff && !mff) {
1991 goto no_fragment;
1992 }
1993
1994 /*
1995 * We're dealing with a fragment now. Don't allow fragments
1996 * with IP_DF to enter the cache. If the flag was cleared by
1997 * no-df above, fine. Otherwise drop it.
1998 */
1999 if (h->ip_off & htons(IP_DF)) {
2000 DPFPRINTF(("IP_DF\n"));
2001 goto bad;
2002 }
2003
2004 ip_len = ntohs(h->ip_len) - hlen;
2005 ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
2006
2007 /* All fragments are 8 byte aligned */
2008 if (mff && (ip_len & 0x7)) {
2009 DPFPRINTF(("mff and %d\n", ip_len));
2010 goto bad;
2011 }
2012
2013 /* Respect maximum length */
2014 if (fragoff + ip_len > IP_MAXPACKET) {
2015 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
2016 goto bad;
2017 }
2018 fr_max = fragoff + ip_len;
2019
2020 if ((r->rule_flag & (PFRULE_FRAGCROP | PFRULE_FRAGDROP)) == 0) {
2021 /* Fully buffer all of the fragments */
2022
2023 frag = pf_find_fragment_by_ipv4_header(h, &pf_frag_tree);
2024 /* Check if we saw the last fragment already */
2025 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
2026 fr_max > frag->fr_max) {
2027 goto bad;
2028 }
2029
2030 if ((m = pbuf_to_mbuf(pbuf, TRUE)) == NULL) {
2031 REASON_SET(reason, PFRES_MEMORY);
2032 return PF_DROP;
2033 }
2034
2035 VERIFY(!pbuf_is_valid(pbuf));
2036
2037 /* Restore iph pointer after pbuf_to_mbuf() */
2038 h = mtod(m, struct ip *);
2039
2040 /* Get an entry for the fragment queue */
2041 frent = pool_get(&pf_frent_pl, PR_NOWAIT);
2042 if (frent == NULL) {
2043 REASON_SET(reason, PFRES_MEMORY);
2044 m_freem(m);
2045 return PF_DROP;
2046 }
2047 pf_nfrents++;
2048 frent->fr_ip = h;
2049 frent->fr_m = m;
2050
2051 /* Might return a completely reassembled mbuf, or NULL */
2052 DPFPRINTF(("reass IPv4 frag %d @ %d-%d\n", ntohs(h->ip_id),
2053 fragoff, fr_max));
2054 m = pf_reassemble(m, &frag, frent, mff);
2055
2056 if (m == NULL) {
2057 return PF_DROP;
2058 }
2059
2060 VERIFY(m->m_flags & M_PKTHDR);
2061 pbuf_init_mbuf(pbuf, m, ifp);
2062
2063 /* use mtag from concatenated mbuf chain */
2064 pd->pf_mtag = pf_find_mtag_pbuf(pbuf);
2065 #if 0
2066 // SCW: This check is superfluous
2067 #if DIAGNOSTIC
2068 if (pd->pf_mtag == NULL) {
2069 printf("%s: pf_find_mtag returned NULL(1)\n", __func__);
2070 if ((pd->pf_mtag = pf_get_mtag(m)) == NULL) {
2071 m_freem(m);
2072 m = NULL;
2073 goto no_mem;
2074 }
2075 }
2076 #endif
2077 #endif
2078
2079 h = mtod(m, struct ip *);
2080
2081 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP)) {
2082 goto drop;
2083 }
2084 } else {
2085 /* non-buffering fragment cache (drops or masks overlaps) */
2086 int nomem = 0;
2087
2088 if (dir == PF_OUT && (pd->pf_mtag->pftag_flags & PF_TAG_FRAGCACHE)) {
2089 /*
2090 * Already passed the fragment cache in the
2091 * input direction. If we continued, it would
2092 * appear to be a dup and would be dropped.
2093 */
2094 goto fragment_pass;
2095 }
2096
2097 frag = pf_find_fragment_by_ipv4_header(h, &pf_cache_tree);
2098
2099 /* Check if we saw the last fragment already */
2100 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
2101 fr_max > frag->fr_max) {
2102 if (r->rule_flag & PFRULE_FRAGDROP) {
2103 frag->fr_flags |= PFFRAG_DROP;
2104 }
2105 goto bad;
2106 }
2107
2108 if ((m = pbuf_to_mbuf(pbuf, TRUE)) == NULL) {
2109 REASON_SET(reason, PFRES_MEMORY);
2110 goto bad;
2111 }
2112
2113 VERIFY(!pbuf_is_valid(pbuf));
2114
2115 /* Restore iph pointer after pbuf_to_mbuf() */
2116 h = mtod(m, struct ip *);
2117
2118 m = pf_fragcache(&m, h, &frag, mff,
2119 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
2120 if (m == NULL) {
2121 // Note: pf_fragcache() has already m_freem'd the mbuf
2122 if (nomem) {
2123 goto no_mem;
2124 }
2125 goto drop;
2126 }
2127
2128 VERIFY(m->m_flags & M_PKTHDR);
2129 pbuf_init_mbuf(pbuf, m, ifp);
2130
2131 /* use mtag from copied and trimmed mbuf chain */
2132 pd->pf_mtag = pf_find_mtag_pbuf(pbuf);
2133 #if 0
2134 // SCW: This check is superfluous
2135 #if DIAGNOSTIC
2136 if (pd->pf_mtag == NULL) {
2137 printf("%s: pf_find_mtag returned NULL(2)\n", __func__);
2138 if ((pd->pf_mtag = pf_get_mtag(m)) == NULL) {
2139 m_freem(m);
2140 m = NULL;
2141 goto no_mem;
2142 }
2143 }
2144 #endif
2145 #endif
2146 if (dir == PF_IN) {
2147 pd->pf_mtag->pftag_flags |= PF_TAG_FRAGCACHE;
2148 }
2149
2150 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP)) {
2151 goto drop;
2152 }
2153
2154 goto fragment_pass;
2155 }
2156
2157 no_fragment:
2158 /* At this point, only IP_DF is allowed in ip_off */
2159 if (h->ip_off & ~htons(IP_DF)) {
2160 u_int16_t ipoff = h->ip_off;
2161
2162 h->ip_off &= htons(IP_DF);
2163 h->ip_sum = pf_cksum_fixup(h->ip_sum, ipoff, h->ip_off, 0);
2164 }
2165
2166 /* Enforce a minimum ttl, may cause endless packet loops */
2167 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
2168 u_int16_t ip_ttl = h->ip_ttl;
2169
2170 h->ip_ttl = r->min_ttl;
2171 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
2172 }
2173 if (r->rule_flag & PFRULE_RANDOMID) {
2174 u_int16_t oip_id = h->ip_id;
2175
2176 if (rfc6864 && IP_OFF_IS_ATOMIC(ntohs(h->ip_off))) {
2177 h->ip_id = 0;
2178 } else {
2179 h->ip_id = ip_randomid();
2180 }
2181 h->ip_sum = pf_cksum_fixup(h->ip_sum, oip_id, h->ip_id, 0);
2182 }
2183 if ((r->rule_flag & (PFRULE_FRAGCROP | PFRULE_FRAGDROP)) == 0) {
2184 pd->flags |= PFDESC_IP_REAS;
2185 }
2186
2187 return PF_PASS;
2188
2189 fragment_pass:
2190 /* Enforce a minimum ttl, may cause endless packet loops */
2191 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
2192 u_int16_t ip_ttl = h->ip_ttl;
2193
2194 h->ip_ttl = r->min_ttl;
2195 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
2196 }
2197 if ((r->rule_flag & (PFRULE_FRAGCROP | PFRULE_FRAGDROP)) == 0) {
2198 pd->flags |= PFDESC_IP_REAS;
2199 }
2200 return PF_PASS;
2201
2202 no_mem:
2203 REASON_SET(reason, PFRES_MEMORY);
2204 if (r != NULL && r->log && pbuf_is_valid(pbuf)) {
2205 PFLOG_PACKET(kif, h, pbuf, AF_INET, dir, *reason, r,
2206 NULL, NULL, pd);
2207 }
2208 return PF_DROP;
2209
2210 drop:
2211 REASON_SET(reason, PFRES_NORM);
2212 if (r != NULL && r->log && pbuf_is_valid(pbuf)) {
2213 PFLOG_PACKET(kif, h, pbuf, AF_INET, dir, *reason, r,
2214 NULL, NULL, pd);
2215 }
2216 return PF_DROP;
2217
2218 bad:
2219 DPFPRINTF(("dropping bad IPv4 fragment\n"));
2220
2221 /* Free associated fragments */
2222 if (frag != NULL) {
2223 pf_free_fragment(frag);
2224 }
2225
2226 REASON_SET(reason, PFRES_FRAG);
2227 if (r != NULL && r->log && pbuf_is_valid(pbuf)) {
2228 PFLOG_PACKET(kif, h, pbuf, AF_INET, dir, *reason, r, NULL, NULL, pd);
2229 }
2230
2231 return PF_DROP;
2232 }
2233
2234 #if INET6
2235 static __inline struct pf_fragment *
2236 pf_find_fragment_by_ipv6_header(struct ip6_hdr *ip6, struct ip6_frag *fh,
2237 struct pf_frag_tree *tree)
2238 {
2239 struct pf_fragment key;
2240 pf_ip6hdr2key(&key, ip6, fh);
2241 return pf_find_fragment_by_key(&key, tree);
2242 }
2243
2244 int
2245 pf_normalize_ip6(pbuf_t *pbuf, int dir, struct pfi_kif *kif,
2246 u_short *reason, struct pf_pdesc *pd)
2247 {
2248 struct mbuf *m = NULL;
2249 struct pf_rule *r;
2250 struct ip6_hdr *h = pbuf->pb_data;
2251 int extoff;
2252 int off;
2253 struct ip6_ext ext;
2254 struct ip6_opt opt;
2255 struct ip6_opt_jumbo jumbo;
2256 int optend;
2257 int ooff;
2258 struct ip6_frag frag;
2259 u_int32_t jumbolen = 0, plen;
2260 u_int16_t fragoff = 0;
2261 u_int8_t proto;
2262 int terminal;
2263 struct pf_frent *frent;
2264 struct pf_fragment *pff = NULL;
2265 int mff = 0, rh_cnt = 0;
2266 u_int16_t fr_max;
2267 int asd = 0;
2268 struct pf_ruleset *ruleset = NULL;
2269 struct ifnet *ifp = pbuf->pb_ifp;
2270
2271 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
2272 while (r != NULL) {
2273 r->evaluations++;
2274 if (pfi_kif_match(r->kif, kif) == r->ifnot) {
2275 r = r->skip[PF_SKIP_IFP].ptr;
2276 } else if (r->direction && r->direction != dir) {
2277 r = r->skip[PF_SKIP_DIR].ptr;
2278 } else if (r->af && r->af != AF_INET6) {
2279 r = r->skip[PF_SKIP_AF].ptr;
2280 }
2281 #if 0 /* header chain! */
2282 else if (r->proto && r->proto != h->ip6_nxt) {
2283 r = r->skip[PF_SKIP_PROTO].ptr;
2284 }
2285 #endif
2286 else if (PF_MISMATCHAW(&r->src.addr,
2287 (struct pf_addr *)(uintptr_t)&h->ip6_src, AF_INET6,
2288 r->src.neg, kif)) {
2289 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
2290 } else if (PF_MISMATCHAW(&r->dst.addr,
2291 (struct pf_addr *)(uintptr_t)&h->ip6_dst, AF_INET6,
2292 r->dst.neg, NULL)) {
2293 r = r->skip[PF_SKIP_DST_ADDR].ptr;
2294 } else {
2295 if (r->anchor == NULL) {
2296 break;
2297 } else {
2298 pf_step_into_anchor(&asd, &ruleset,
2299 PF_RULESET_SCRUB, &r, NULL, NULL);
2300 }
2301 }
2302 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
2303 PF_RULESET_SCRUB, &r, NULL, NULL)) {
2304 break;
2305 }
2306 }
2307
2308 if (r == NULL || r->action == PF_NOSCRUB) {
2309 return PF_PASS;
2310 } else {
2311 r->packets[dir == PF_OUT]++;
2312 r->bytes[dir == PF_OUT] += pd->tot_len;
2313 }
2314
2315 /* Check for illegal packets */
2316 if ((uint32_t)(sizeof(struct ip6_hdr) + IPV6_MAXPACKET) <
2317 pbuf->pb_packet_len) {
2318 goto drop;
2319 }
2320
2321 extoff = 0;
2322 off = sizeof(struct ip6_hdr);
2323 proto = h->ip6_nxt;
2324 terminal = 0;
2325 do {
2326 pd->proto = proto;
2327 switch (proto) {
2328 case IPPROTO_FRAGMENT:
2329 goto fragment;
2330 case IPPROTO_AH:
2331 case IPPROTO_ROUTING:
2332 case IPPROTO_DSTOPTS:
2333 if (!pf_pull_hdr(pbuf, off, &ext, sizeof(ext), NULL,
2334 NULL, AF_INET6)) {
2335 goto shortpkt;
2336 }
2337 extoff = off;
2338 /*
2339 * <jhw@apple.com>
2340 * Multiple routing headers not allowed.
2341 * Routing header type zero considered harmful.
2342 */
2343 if (proto == IPPROTO_ROUTING) {
2344 const struct ip6_rthdr *rh =
2345 (const struct ip6_rthdr *)&ext;
2346 if (rh_cnt++) {
2347 goto drop;
2348 }
2349 if (rh->ip6r_type == IPV6_RTHDR_TYPE_0) {
2350 goto drop;
2351 }
2352 } else if (proto == IPPROTO_AH) {
2353 off += (ext.ip6e_len + 2) * 4;
2354 } else {
2355 off += (ext.ip6e_len + 1) * 8;
2356 }
2357 proto = ext.ip6e_nxt;
2358 break;
2359 case IPPROTO_HOPOPTS:
2360 if (!pf_pull_hdr(pbuf, off, &ext, sizeof(ext), NULL,
2361 NULL, AF_INET6)) {
2362 goto shortpkt;
2363 }
2364 extoff = off;
2365 optend = off + (ext.ip6e_len + 1) * 8;
2366 ooff = off + sizeof(ext);
2367 do {
2368 if (!pf_pull_hdr(pbuf, ooff, &opt.ip6o_type,
2369 sizeof(opt.ip6o_type), NULL, NULL,
2370 AF_INET6)) {
2371 goto shortpkt;
2372 }
2373 if (opt.ip6o_type == IP6OPT_PAD1) {
2374 ooff++;
2375 continue;
2376 }
2377 if (!pf_pull_hdr(pbuf, ooff, &opt, sizeof(opt),
2378 NULL, NULL, AF_INET6)) {
2379 goto shortpkt;
2380 }
2381 if ((ooff + (int) sizeof(opt) + opt.ip6o_len) >
2382 optend) {
2383 goto drop;
2384 }
2385 switch (opt.ip6o_type) {
2386 case IP6OPT_JUMBO:
2387 if (h->ip6_plen != 0) {
2388 goto drop;
2389 }
2390 if (!pf_pull_hdr(pbuf, ooff, &jumbo,
2391 sizeof(jumbo), NULL, NULL,
2392 AF_INET6)) {
2393 goto shortpkt;
2394 }
2395 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
2396 sizeof(jumbolen));
2397 jumbolen = ntohl(jumbolen);
2398 if (jumbolen <= IPV6_MAXPACKET) {
2399 goto drop;
2400 }
2401 if ((sizeof(struct ip6_hdr) +
2402 jumbolen) != pbuf->pb_packet_len) {
2403 goto drop;
2404 }
2405 break;
2406 default:
2407 break;
2408 }
2409 ooff += sizeof(opt) + opt.ip6o_len;
2410 } while (ooff < optend);
2411
2412 off = optend;
2413 proto = ext.ip6e_nxt;
2414 break;
2415 default:
2416 terminal = 1;
2417 break;
2418 }
2419 } while (!terminal);
2420
2421 /* jumbo payload option must be present, or plen > 0 */
2422 if (ntohs(h->ip6_plen) == 0) {
2423 plen = jumbolen;
2424 } else {
2425 plen = ntohs(h->ip6_plen);
2426 }
2427 if (plen == 0) {
2428 goto drop;
2429 }
2430 if ((uint32_t)(sizeof(struct ip6_hdr) + plen) > pbuf->pb_packet_len) {
2431 goto shortpkt;
2432 }
2433
2434 /* Enforce a minimum ttl, may cause endless packet loops */
2435 if (r->min_ttl && h->ip6_hlim < r->min_ttl) {
2436 h->ip6_hlim = r->min_ttl;
2437 }
2438
2439 return PF_PASS;
2440
2441 fragment:
2442 plen = ntohs(h->ip6_plen);
2443 /* Jumbo payload packets cannot be fragmented */
2444 if (plen == 0 || jumbolen) {
2445 goto drop;
2446 }
2447
2448 if (!pf_pull_hdr(pbuf, off, &frag, sizeof(frag), NULL, NULL, AF_INET6)) {
2449 goto shortpkt;
2450 }
2451 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
2452 pd->proto = frag.ip6f_nxt;
2453 mff = ntohs(frag.ip6f_offlg & IP6F_MORE_FRAG);
2454 off += sizeof(frag);
2455 if (fragoff + (plen - off) > IPV6_MAXPACKET) {
2456 goto badfrag;
2457 }
2458
2459 fr_max = fragoff + plen - (off - sizeof(struct ip6_hdr));
2460 // XXX SCW: mbuf-specific
2461 // DPFPRINTF(("0x%llx IPv6 frag plen %u mff %d off %u fragoff %u "
2462 // "fr_max %u\n", (uint64_t)VM_KERNEL_ADDRPERM(m), plen, mff, off,
2463 // fragoff, fr_max));
2464
2465 if ((r->rule_flag & (PFRULE_FRAGCROP | PFRULE_FRAGDROP)) == 0) {
2466 /* Fully buffer all of the fragments */
2467 pd->flags |= PFDESC_IP_REAS;
2468
2469 pff = pf_find_fragment_by_ipv6_header(h, &frag,
2470 &pf_frag_tree);
2471
2472 /* Check if we saw the last fragment already */
2473 if (pff != NULL && (pff->fr_flags & PFFRAG_SEENLAST) &&
2474 fr_max > pff->fr_max) {
2475 goto badfrag;
2476 }
2477
2478 if ((m = pbuf_to_mbuf(pbuf, TRUE)) == NULL) {
2479 REASON_SET(reason, PFRES_MEMORY);
2480 return PF_DROP;
2481 }
2482
2483 /* Restore iph pointer after pbuf_to_mbuf() */
2484 h = mtod(m, struct ip6_hdr *);
2485
2486 /* Get an entry for the fragment queue */
2487 frent = pool_get(&pf_frent_pl, PR_NOWAIT);
2488 if (frent == NULL) {
2489 REASON_SET(reason, PFRES_MEMORY);
2490 return PF_DROP;
2491 }
2492
2493 pf_nfrents++;
2494 frent->fr_ip6 = h;
2495 frent->fr_m = m;
2496 frent->fr_ip6f_opt = frag;
2497 frent->fr_ip6f_extoff = extoff;
2498 frent->fr_ip6f_hlen = off;
2499 /* account for 2nd Destination Options header if present */
2500 if (pd->proto == IPPROTO_DSTOPTS) {
2501 if (!pf_pull_hdr(pbuf, off, &ext, sizeof(ext), NULL,
2502 NULL, AF_INET6)) {
2503 goto shortpkt;
2504 }
2505 frent->fr_ip6f_hlen += (ext.ip6e_len + 1) * 8;
2506 }
2507
2508 /* Might return a completely reassembled mbuf, or NULL */
2509 DPFPRINTF(("reass IPv6 frag %d @ %d-%d\n",
2510 ntohl(frag.ip6f_ident), fragoff, fr_max));
2511 m = pf_reassemble6(&m, &pff, frent, mff);
2512
2513 if (m == NULL) {
2514 return PF_DROP;
2515 }
2516
2517 pbuf_init_mbuf(pbuf, m, ifp);
2518 h = pbuf->pb_data;
2519
2520 if (pff != NULL && (pff->fr_flags & PFFRAG_DROP)) {
2521 goto drop;
2522 }
2523 } else if (dir == PF_IN ||
2524 !(pd->pf_mtag->pftag_flags & PF_TAG_FRAGCACHE)) {
2525 /* non-buffering fragment cache (overlaps: see RFC 5722) */
2526 int nomem = 0;
2527
2528 pff = pf_find_fragment_by_ipv6_header(h, &frag,
2529 &pf_cache_tree);
2530
2531 /* Check if we saw the last fragment already */
2532 if (pff != NULL && (pff->fr_flags & PFFRAG_SEENLAST) &&
2533 fr_max > pff->fr_max) {
2534 if (r->rule_flag & PFRULE_FRAGDROP) {
2535 pff->fr_flags |= PFFRAG_DROP;
2536 }
2537 goto badfrag;
2538 }
2539
2540 if ((m = pbuf_to_mbuf(pbuf, TRUE)) == NULL) {
2541 goto no_mem;
2542 }
2543
2544 /* Restore iph pointer after pbuf_to_mbuf() */
2545 h = mtod(m, struct ip6_hdr *);
2546
2547 m = pf_frag6cache(&m, h, &frag, &pff, off, mff,
2548 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
2549 if (m == NULL) {
2550 // Note: pf_frag6cache() has already m_freem'd the mbuf
2551 if (nomem) {
2552 goto no_mem;
2553 }
2554 goto drop;
2555 }
2556
2557 pbuf_init_mbuf(pbuf, m, ifp);
2558 pd->pf_mtag = pf_find_mtag_pbuf(pbuf);
2559 h = pbuf->pb_data;
2560
2561 if (dir == PF_IN) {
2562 pd->pf_mtag->pftag_flags |= PF_TAG_FRAGCACHE;
2563 }
2564
2565 if (pff != NULL && (pff->fr_flags & PFFRAG_DROP)) {
2566 goto drop;
2567 }
2568 }
2569
2570 /* Enforce a minimum ttl, may cause endless packet loops */
2571 if (r->min_ttl && h->ip6_hlim < r->min_ttl) {
2572 h->ip6_hlim = r->min_ttl;
2573 }
2574 return PF_PASS;
2575
2576 no_mem:
2577 REASON_SET(reason, PFRES_MEMORY);
2578 goto dropout;
2579
2580 shortpkt:
2581 REASON_SET(reason, PFRES_SHORT);
2582 goto dropout;
2583
2584 drop:
2585 REASON_SET(reason, PFRES_NORM);
2586 goto dropout;
2587
2588 badfrag:
2589 DPFPRINTF(("dropping bad IPv6 fragment\n"));
2590 REASON_SET(reason, PFRES_FRAG);
2591 goto dropout;
2592
2593 dropout:
2594 if (pff != NULL) {
2595 pf_free_fragment(pff);
2596 }
2597 if (r != NULL && r->log && pbuf_is_valid(pbuf)) {
2598 PFLOG_PACKET(kif, h, pbuf, AF_INET6, dir, *reason, r, NULL, NULL, pd);
2599 }
2600 return PF_DROP;
2601 }
2602 #endif /* INET6 */
2603
2604 int
2605 pf_normalize_tcp(int dir, struct pfi_kif *kif, pbuf_t *pbuf, int ipoff,
2606 int off, void *h, struct pf_pdesc *pd)
2607 {
2608 #pragma unused(ipoff, h)
2609 struct pf_rule *r, *rm = NULL;
2610 struct tcphdr *th = pd->hdr.tcp;
2611 int rewrite = 0;
2612 int asd = 0;
2613 u_short reason;
2614 u_int8_t flags;
2615 sa_family_t af = pd->af;
2616 struct pf_ruleset *ruleset = NULL;
2617 union pf_state_xport sxport, dxport;
2618
2619 sxport.port = th->th_sport;
2620 dxport.port = th->th_dport;
2621
2622 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
2623 while (r != NULL) {
2624 r->evaluations++;
2625 if (pfi_kif_match(r->kif, kif) == r->ifnot) {
2626 r = r->skip[PF_SKIP_IFP].ptr;
2627 } else if (r->direction && r->direction != dir) {
2628 r = r->skip[PF_SKIP_DIR].ptr;
2629 } else if (r->af && r->af != af) {
2630 r = r->skip[PF_SKIP_AF].ptr;
2631 } else if (r->proto && r->proto != pd->proto) {
2632 r = r->skip[PF_SKIP_PROTO].ptr;
2633 } else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
2634 r->src.neg, kif)) {
2635 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
2636 } else if (r->src.xport.range.op &&
2637 !pf_match_xport(r->src.xport.range.op, r->proto_variant,
2638 &r->src.xport, &sxport)) {
2639 r = r->skip[PF_SKIP_SRC_PORT].ptr;
2640 } else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
2641 r->dst.neg, NULL)) {
2642 r = r->skip[PF_SKIP_DST_ADDR].ptr;
2643 } else if (r->dst.xport.range.op &&
2644 !pf_match_xport(r->dst.xport.range.op, r->proto_variant,
2645 &r->dst.xport, &dxport)) {
2646 r = r->skip[PF_SKIP_DST_PORT].ptr;
2647 } else if (r->os_fingerprint != PF_OSFP_ANY &&
2648 !pf_osfp_match(pf_osfp_fingerprint(pd, pbuf, off, th),
2649 r->os_fingerprint)) {
2650 r = TAILQ_NEXT(r, entries);
2651 } else {
2652 if (r->anchor == NULL) {
2653 rm = r;
2654 break;
2655 } else {
2656 pf_step_into_anchor(&asd, &ruleset,
2657 PF_RULESET_SCRUB, &r, NULL, NULL);
2658 }
2659 }
2660 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
2661 PF_RULESET_SCRUB, &r, NULL, NULL)) {
2662 break;
2663 }
2664 }
2665
2666 if (rm == NULL || rm->action == PF_NOSCRUB) {
2667 return PF_PASS;
2668 } else {
2669 r->packets[dir == PF_OUT]++;
2670 r->bytes[dir == PF_OUT] += pd->tot_len;
2671 }
2672
2673 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP) {
2674 pd->flags |= PFDESC_TCP_NORM;
2675 }
2676
2677 flags = th->th_flags;
2678 if (flags & TH_SYN) {
2679 /* Illegal packet */
2680 if (flags & TH_RST) {
2681 goto tcp_drop;
2682 }
2683
2684 if (flags & TH_FIN) {
2685 flags &= ~TH_FIN;
2686 }
2687 } else {
2688 /* Illegal packet */
2689 if (!(flags & (TH_ACK | TH_RST))) {
2690 goto tcp_drop;
2691 }
2692 }
2693
2694 if (!(flags & TH_ACK)) {
2695 /* These flags are only valid if ACK is set */
2696 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG)) {
2697 goto tcp_drop;
2698 }
2699 }
2700
2701 /* Check for illegal header length */
2702 if (th->th_off < (sizeof(struct tcphdr) >> 2)) {
2703 goto tcp_drop;
2704 }
2705
2706 /* If flags changed, or reserved data set, then adjust */
2707 if (flags != th->th_flags || th->th_x2 != 0) {
2708 u_int16_t ov, nv;
2709
2710 ov = *(u_int16_t *)(&th->th_ack + 1);
2711 th->th_flags = flags;
2712 th->th_x2 = 0;
2713 nv = *(u_int16_t *)(&th->th_ack + 1);
2714
2715 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
2716 rewrite = 1;
2717 }
2718
2719 /* Remove urgent pointer, if TH_URG is not set */
2720 if (!(flags & TH_URG) && th->th_urp) {
2721 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
2722 th->th_urp = 0;
2723 rewrite = 1;
2724 }
2725
2726 /* copy back packet headers if we sanitized */
2727 /* Process options */
2728 if (r->max_mss) {
2729 int rv = pf_normalize_tcpopt(r, dir, kif, pd, pbuf, th, off,
2730 &rewrite);
2731 if (rv == PF_DROP) {
2732 return rv;
2733 }
2734 pbuf = pd->mp;
2735 }
2736
2737 if (rewrite) {
2738 if (pf_lazy_makewritable(pd, pbuf,
2739 off + sizeof(*th)) == NULL) {
2740 REASON_SET(&reason, PFRES_MEMORY);
2741 if (r->log) {
2742 PFLOG_PACKET(kif, h, pbuf, AF_INET, dir, reason,
2743 r, 0, 0, pd);
2744 }
2745 return PF_DROP;
2746 }
2747
2748 pbuf_copy_back(pbuf, off, sizeof(*th), th);
2749 }
2750
2751 return PF_PASS;
2752
2753 tcp_drop:
2754 REASON_SET(&reason, PFRES_NORM);
2755 if (rm != NULL && r->log) {
2756 PFLOG_PACKET(kif, h, pbuf, AF_INET, dir, reason, r, NULL, NULL, pd);
2757 }
2758 return PF_DROP;
2759 }
2760
2761 int
2762 pf_normalize_tcp_init(pbuf_t *pbuf, int off, struct pf_pdesc *pd,
2763 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
2764 {
2765 #pragma unused(dst)
2766 u_int32_t tsval, tsecr;
2767 u_int8_t hdr[60];
2768 u_int8_t *opt;
2769
2770 VERIFY(src->scrub == NULL);
2771
2772 src->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
2773 if (src->scrub == NULL) {
2774 return 1;
2775 }
2776 bzero(src->scrub, sizeof(*src->scrub));
2777
2778 switch (pd->af) {
2779 #if INET
2780 case AF_INET: {
2781 struct ip *h = pbuf->pb_data;
2782 src->scrub->pfss_ttl = h->ip_ttl;
2783 break;
2784 }
2785 #endif /* INET */
2786 #if INET6
2787 case AF_INET6: {
2788 struct ip6_hdr *h = pbuf->pb_data;
2789 src->scrub->pfss_ttl = h->ip6_hlim;
2790 break;
2791 }
2792 #endif /* INET6 */
2793 }
2794
2795
2796 /*
2797 * All normalizations below are only begun if we see the start of
2798 * the connections. They must all set an enabled bit in pfss_flags
2799 */
2800 if ((th->th_flags & TH_SYN) == 0) {
2801 return 0;
2802 }
2803
2804
2805 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
2806 pf_pull_hdr(pbuf, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
2807 /* Diddle with TCP options */
2808 int hlen;
2809 opt = hdr + sizeof(struct tcphdr);
2810 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
2811 while (hlen >= TCPOLEN_TIMESTAMP) {
2812 switch (*opt) {
2813 case TCPOPT_EOL: /* FALLTHROUGH */
2814 case TCPOPT_NOP:
2815 opt++;
2816 hlen--;
2817 break;
2818 case TCPOPT_TIMESTAMP:
2819 if (opt[1] >= TCPOLEN_TIMESTAMP) {
2820 src->scrub->pfss_flags |=
2821 PFSS_TIMESTAMP;
2822 src->scrub->pfss_ts_mod =
2823 htonl(random());
2824
2825 /* note PFSS_PAWS not set yet */
2826 memcpy(&tsval, &opt[2],
2827 sizeof(u_int32_t));
2828 memcpy(&tsecr, &opt[6],
2829 sizeof(u_int32_t));
2830 src->scrub->pfss_tsval0 = ntohl(tsval);
2831 src->scrub->pfss_tsval = ntohl(tsval);
2832 src->scrub->pfss_tsecr = ntohl(tsecr);
2833 getmicrouptime(&src->scrub->pfss_last);
2834 }
2835 /* FALLTHROUGH */
2836 default:
2837 hlen -= MAX(opt[1], 2);
2838 opt += MAX(opt[1], 2);
2839 break;
2840 }
2841 }
2842 }
2843
2844 return 0;
2845 }
2846
2847 void
2848 pf_normalize_tcp_cleanup(struct pf_state *state)
2849 {
2850 if (state->src.scrub) {
2851 pool_put(&pf_state_scrub_pl, state->src.scrub);
2852 }
2853 if (state->dst.scrub) {
2854 pool_put(&pf_state_scrub_pl, state->dst.scrub);
2855 }
2856
2857 /* Someday... flush the TCP segment reassembly descriptors. */
2858 }
2859
2860 int
2861 pf_normalize_tcp_stateful(pbuf_t *pbuf, int off, struct pf_pdesc *pd,
2862 u_short *reason, struct tcphdr *th, struct pf_state *state,
2863 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
2864 {
2865 struct timeval uptime;
2866 u_int32_t tsval = 0, tsecr = 0;
2867 u_int tsval_from_last;
2868 u_int8_t hdr[60];
2869 u_int8_t *opt;
2870 int copyback = 0;
2871 int got_ts = 0;
2872
2873 VERIFY(src->scrub || dst->scrub);
2874
2875 /*
2876 * Enforce the minimum TTL seen for this connection. Negate a common
2877 * technique to evade an intrusion detection system and confuse
2878 * firewall state code.
2879 */
2880 switch (pd->af) {
2881 #if INET
2882 case AF_INET: {
2883 if (src->scrub) {
2884 struct ip *h = pbuf->pb_data;
2885 if (h->ip_ttl > src->scrub->pfss_ttl) {
2886 src->scrub->pfss_ttl = h->ip_ttl;
2887 }
2888 h->ip_ttl = src->scrub->pfss_ttl;
2889 }
2890 break;
2891 }
2892 #endif /* INET */
2893 #if INET6
2894 case AF_INET6: {
2895 if (src->scrub) {
2896 struct ip6_hdr *h = pbuf->pb_data;
2897 if (h->ip6_hlim > src->scrub->pfss_ttl) {
2898 src->scrub->pfss_ttl = h->ip6_hlim;
2899 }
2900 h->ip6_hlim = src->scrub->pfss_ttl;
2901 }
2902 break;
2903 }
2904 #endif /* INET6 */
2905 }
2906
2907 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
2908 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
2909 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
2910 pf_pull_hdr(pbuf, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
2911 /* Diddle with TCP options */
2912 int hlen;
2913 opt = hdr + sizeof(struct tcphdr);
2914 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
2915 while (hlen >= TCPOLEN_TIMESTAMP) {
2916 switch (*opt) {
2917 case TCPOPT_EOL: /* FALLTHROUGH */
2918 case TCPOPT_NOP:
2919 opt++;
2920 hlen--;
2921 break;
2922 case TCPOPT_TIMESTAMP:
2923 /*
2924 * Modulate the timestamps. Can be used for
2925 * NAT detection, OS uptime determination or
2926 * reboot detection.
2927 */
2928
2929 if (got_ts) {
2930 /* Huh? Multiple timestamps!? */
2931 if (pf_status.debug >= PF_DEBUG_MISC) {
2932 DPFPRINTF(("multiple TS??"));
2933 pf_print_state(state);
2934 printf("\n");
2935 }
2936 REASON_SET(reason, PFRES_TS);
2937 return PF_DROP;
2938 }
2939 if (opt[1] >= TCPOLEN_TIMESTAMP) {
2940 memcpy(&tsval, &opt[2],
2941 sizeof(u_int32_t));
2942 if (tsval && src->scrub &&
2943 (src->scrub->pfss_flags &
2944 PFSS_TIMESTAMP)) {
2945 tsval = ntohl(tsval);
2946 pf_change_a(&opt[2],
2947 &th->th_sum,
2948 htonl(tsval +
2949 src->scrub->pfss_ts_mod),
2950 0);
2951 copyback = 1;
2952 }
2953
2954 /* Modulate TS reply iff valid (!0) */
2955 memcpy(&tsecr, &opt[6],
2956 sizeof(u_int32_t));
2957 if (tsecr && dst->scrub &&
2958 (dst->scrub->pfss_flags &
2959 PFSS_TIMESTAMP)) {
2960 tsecr = ntohl(tsecr)
2961 - dst->scrub->pfss_ts_mod;
2962 pf_change_a(&opt[6],
2963 &th->th_sum, htonl(tsecr),
2964 0);
2965 copyback = 1;
2966 }
2967 got_ts = 1;
2968 }
2969 /* FALLTHROUGH */
2970 default:
2971 hlen -= MAX(opt[1], 2);
2972 opt += MAX(opt[1], 2);
2973 break;
2974 }
2975 }
2976 if (copyback) {
2977 /* Copyback the options, caller copys back header */
2978 int optoff = off + sizeof(*th);
2979 int optlen = (th->th_off << 2) - sizeof(*th);
2980 if (pf_lazy_makewritable(pd, pbuf, optoff + optlen) ==
2981 NULL) {
2982 REASON_SET(reason, PFRES_MEMORY);
2983 return PF_DROP;
2984 }
2985 *writeback = optoff + optlen;
2986 pbuf_copy_back(pbuf, optoff, optlen, hdr + sizeof(*th));
2987 }
2988 }
2989
2990
2991 /*
2992 * Must invalidate PAWS checks on connections idle for too long.
2993 * The fastest allowed timestamp clock is 1ms. That turns out to
2994 * be about 24 days before it wraps. XXX Right now our lowerbound
2995 * TS echo check only works for the first 12 days of a connection
2996 * when the TS has exhausted half its 32bit space
2997 */
2998 #define TS_MAX_IDLE (24*24*60*60)
2999 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
3000
3001 getmicrouptime(&uptime);
3002 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
3003 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
3004 pf_time_second() - state->creation > TS_MAX_CONN)) {
3005 if (pf_status.debug >= PF_DEBUG_MISC) {
3006 DPFPRINTF(("src idled out of PAWS\n"));
3007 pf_print_state(state);
3008 printf("\n");
3009 }
3010 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
3011 | PFSS_PAWS_IDLED;
3012 }
3013 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
3014 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
3015 if (pf_status.debug >= PF_DEBUG_MISC) {
3016 DPFPRINTF(("dst idled out of PAWS\n"));
3017 pf_print_state(state);
3018 printf("\n");
3019 }
3020 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
3021 | PFSS_PAWS_IDLED;
3022 }
3023
3024 if (got_ts && src->scrub && dst->scrub &&
3025 (src->scrub->pfss_flags & PFSS_PAWS) &&
3026 (dst->scrub->pfss_flags & PFSS_PAWS)) {
3027 /*
3028 * Validate that the timestamps are "in-window".
3029 * RFC1323 describes TCP Timestamp options that allow
3030 * measurement of RTT (round trip time) and PAWS
3031 * (protection against wrapped sequence numbers). PAWS
3032 * gives us a set of rules for rejecting packets on
3033 * long fat pipes (packets that were somehow delayed
3034 * in transit longer than the time it took to send the
3035 * full TCP sequence space of 4Gb). We can use these
3036 * rules and infer a few others that will let us treat
3037 * the 32bit timestamp and the 32bit echoed timestamp
3038 * as sequence numbers to prevent a blind attacker from
3039 * inserting packets into a connection.
3040 *
3041 * RFC1323 tells us:
3042 * - The timestamp on this packet must be greater than
3043 * or equal to the last value echoed by the other
3044 * endpoint. The RFC says those will be discarded
3045 * since it is a dup that has already been acked.
3046 * This gives us a lowerbound on the timestamp.
3047 * timestamp >= other last echoed timestamp
3048 * - The timestamp will be less than or equal to
3049 * the last timestamp plus the time between the
3050 * last packet and now. The RFC defines the max
3051 * clock rate as 1ms. We will allow clocks to be
3052 * up to 10% fast and will allow a total difference
3053 * or 30 seconds due to a route change. And this
3054 * gives us an upperbound on the timestamp.
3055 * timestamp <= last timestamp + max ticks
3056 * We have to be careful here. Windows will send an
3057 * initial timestamp of zero and then initialize it
3058 * to a random value after the 3whs; presumably to
3059 * avoid a DoS by having to call an expensive RNG
3060 * during a SYN flood. Proof MS has at least one
3061 * good security geek.
3062 *
3063 * - The TCP timestamp option must also echo the other
3064 * endpoints timestamp. The timestamp echoed is the
3065 * one carried on the earliest unacknowledged segment
3066 * on the left edge of the sequence window. The RFC
3067 * states that the host will reject any echoed
3068 * timestamps that were larger than any ever sent.
3069 * This gives us an upperbound on the TS echo.
3070 * tescr <= largest_tsval
3071 * - The lowerbound on the TS echo is a little more
3072 * tricky to determine. The other endpoint's echoed
3073 * values will not decrease. But there may be
3074 * network conditions that re-order packets and
3075 * cause our view of them to decrease. For now the
3076 * only lowerbound we can safely determine is that
3077 * the TS echo will never be less than the original
3078 * TS. XXX There is probably a better lowerbound.
3079 * Remove TS_MAX_CONN with better lowerbound check.
3080 * tescr >= other original TS
3081 *
3082 * It is also important to note that the fastest
3083 * timestamp clock of 1ms will wrap its 32bit space in
3084 * 24 days. So we just disable TS checking after 24
3085 * days of idle time. We actually must use a 12d
3086 * connection limit until we can come up with a better
3087 * lowerbound to the TS echo check.
3088 */
3089 struct timeval delta_ts;
3090 int ts_fudge;
3091
3092
3093 /*
3094 * PFTM_TS_DIFF is how many seconds of leeway to allow
3095 * a host's timestamp. This can happen if the previous
3096 * packet got delayed in transit for much longer than
3097 * this packet.
3098 */
3099 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0) {
3100 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
3101 }
3102
3103
3104 /* Calculate max ticks since the last timestamp */
3105 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
3106 #define TS_MICROSECS 1000000 /* microseconds per second */
3107 timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
3108 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
3109 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS / TS_MAXFREQ);
3110
3111
3112 if ((src->state >= TCPS_ESTABLISHED &&
3113 dst->state >= TCPS_ESTABLISHED) &&
3114 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
3115 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
3116 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
3117 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
3118 /*
3119 * Bad RFC1323 implementation or an insertion attack.
3120 *
3121 * - Solaris 2.6 and 2.7 are known to send another ACK
3122 * after the FIN,FIN|ACK,ACK closing that carries
3123 * an old timestamp.
3124 */
3125
3126 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
3127 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
3128 SEQ_GT(tsval, src->scrub->pfss_tsval +
3129 tsval_from_last) ? '1' : ' ',
3130 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
3131 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
3132 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
3133 "idle: %lus %ums\n",
3134 tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
3135 delta_ts.tv_usec / 1000));
3136 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
3137 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
3138 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u\n",
3139 dst->scrub->pfss_tsval, dst->scrub->pfss_tsecr,
3140 dst->scrub->pfss_tsval0));
3141 if (pf_status.debug >= PF_DEBUG_MISC) {
3142 pf_print_state(state);
3143 pf_print_flags(th->th_flags);
3144 printf("\n");
3145 }
3146 REASON_SET(reason, PFRES_TS);
3147 return PF_DROP;
3148 }
3149
3150 /* XXX I'd really like to require tsecr but it's optional */
3151 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
3152 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
3153 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
3154 src->scrub && dst->scrub &&
3155 (src->scrub->pfss_flags & PFSS_PAWS) &&
3156 (dst->scrub->pfss_flags & PFSS_PAWS)) {
3157 /*
3158 * Didn't send a timestamp. Timestamps aren't really useful
3159 * when:
3160 * - connection opening or closing (often not even sent).
3161 * but we must not let an attacker to put a FIN on a
3162 * data packet to sneak it through our ESTABLISHED check.
3163 * - on a TCP reset. RFC suggests not even looking at TS.
3164 * - on an empty ACK. The TS will not be echoed so it will
3165 * probably not help keep the RTT calculation in sync and
3166 * there isn't as much danger when the sequence numbers
3167 * got wrapped. So some stacks don't include TS on empty
3168 * ACKs :-(
3169 *
3170 * To minimize the disruption to mostly RFC1323 conformant
3171 * stacks, we will only require timestamps on data packets.
3172 *
3173 * And what do ya know, we cannot require timestamps on data
3174 * packets. There appear to be devices that do legitimate
3175 * TCP connection hijacking. There are HTTP devices that allow
3176 * a 3whs (with timestamps) and then buffer the HTTP request.
3177 * If the intermediate device has the HTTP response cache, it
3178 * will spoof the response but not bother timestamping its
3179 * packets. So we can look for the presence of a timestamp in
3180 * the first data packet and if there, require it in all future
3181 * packets.
3182 */
3183
3184 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
3185 /*
3186 * Hey! Someone tried to sneak a packet in. Or the
3187 * stack changed its RFC1323 behavior?!?!
3188 */
3189 if (pf_status.debug >= PF_DEBUG_MISC) {
3190 DPFPRINTF(("Did not receive expected RFC1323 "
3191 "timestamp\n"));
3192 pf_print_state(state);
3193 pf_print_flags(th->th_flags);
3194 printf("\n");
3195 }
3196 REASON_SET(reason, PFRES_TS);
3197 return PF_DROP;
3198 }
3199 }
3200
3201
3202 /*
3203 * We will note if a host sends his data packets with or without
3204 * timestamps. And require all data packets to contain a timestamp
3205 * if the first does. PAWS implicitly requires that all data packets be
3206 * timestamped. But I think there are middle-man devices that hijack
3207 * TCP streams immediately after the 3whs and don't timestamp their
3208 * packets (seen in a WWW accelerator or cache).
3209 */
3210 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
3211 (PFSS_TIMESTAMP | PFSS_DATA_TS | PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
3212 if (got_ts) {
3213 src->scrub->pfss_flags |= PFSS_DATA_TS;
3214 } else {
3215 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
3216 if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
3217 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
3218 /* Don't warn if other host rejected RFC1323 */
3219 DPFPRINTF(("Broken RFC1323 stack did not "
3220 "timestamp data packet. Disabled PAWS "
3221 "security.\n"));
3222 pf_print_state(state);
3223 pf_print_flags(th->th_flags);
3224 printf("\n");
3225 }
3226 }
3227 }
3228
3229
3230 /*
3231 * Update PAWS values
3232 */
3233 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
3234 (PFSS_PAWS_IDLED | PFSS_TIMESTAMP))) {
3235 getmicrouptime(&src->scrub->pfss_last);
3236 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
3237 (src->scrub->pfss_flags & PFSS_PAWS) == 0) {
3238 src->scrub->pfss_tsval = tsval;
3239 }
3240
3241 if (tsecr) {
3242 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
3243 (src->scrub->pfss_flags & PFSS_PAWS) == 0) {
3244 src->scrub->pfss_tsecr = tsecr;
3245 }
3246
3247 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
3248 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
3249 src->scrub->pfss_tsval0 == 0)) {
3250 /* tsval0 MUST be the lowest timestamp */
3251 src->scrub->pfss_tsval0 = tsval;
3252 }
3253
3254 /* Only fully initialized after a TS gets echoed */
3255 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0) {
3256 src->scrub->pfss_flags |= PFSS_PAWS;
3257 }
3258 }
3259 }
3260
3261 /* I have a dream.... TCP segment reassembly.... */
3262 return 0;
3263 }
3264
3265 static int
3266 pf_normalize_tcpopt(struct pf_rule *r, int dir, struct pfi_kif *kif,
3267 struct pf_pdesc *pd, pbuf_t *pbuf, struct tcphdr *th, int off,
3268 int *rewrptr)
3269 {
3270 #pragma unused(dir, kif)
3271 sa_family_t af = pd->af;
3272 u_int16_t *mss;
3273 int thoff;
3274 int opt, cnt, optlen = 0;
3275 int rewrite = 0;
3276 u_char opts[MAX_TCPOPTLEN];
3277 u_char *optp = opts;
3278
3279 thoff = th->th_off << 2;
3280 cnt = thoff - sizeof(struct tcphdr);
3281
3282 if (cnt > 0 && !pf_pull_hdr(pbuf, off + sizeof(*th), opts, cnt,
3283 NULL, NULL, af)) {
3284 return PF_DROP;
3285 }
3286
3287 for (; cnt > 0; cnt -= optlen, optp += optlen) {
3288 opt = optp[0];
3289 if (opt == TCPOPT_EOL) {
3290 break;
3291 }
3292 if (opt == TCPOPT_NOP) {
3293 optlen = 1;
3294 } else {
3295 if (cnt < 2) {
3296 break;
3297 }
3298 optlen = optp[1];
3299 if (optlen < 2 || optlen > cnt) {
3300 break;
3301 }
3302 }
3303 switch (opt) {
3304 case TCPOPT_MAXSEG:
3305 mss = (u_int16_t *)(void *)(optp + 2);
3306 if ((ntohs(*mss)) > r->max_mss) {
3307 /*
3308 * <jhw@apple.com>
3309 * Only do the TCP checksum fixup if delayed
3310 * checksum calculation will not be performed.
3311 */
3312 if (pbuf->pb_ifp ||
3313 !(*pbuf->pb_csum_flags & CSUM_TCP)) {
3314 th->th_sum = pf_cksum_fixup(th->th_sum,
3315 *mss, htons(r->max_mss), 0);
3316 }
3317 *mss = htons(r->max_mss);
3318 rewrite = 1;
3319 }
3320 break;
3321 default:
3322 break;
3323 }
3324 }
3325
3326 if (rewrite) {
3327 u_short reason;
3328
3329 VERIFY(pbuf == pd->mp);
3330
3331 if (pf_lazy_makewritable(pd, pd->mp,
3332 off + sizeof(*th) + thoff) == NULL) {
3333 REASON_SET(&reason, PFRES_MEMORY);
3334 if (r->log) {
3335 PFLOG_PACKET(kif, h, pbuf, AF_INET, dir, reason,
3336 r, 0, 0, pd);
3337 }
3338 return PF_DROP;
3339 }
3340
3341 *rewrptr = 1;
3342 pbuf_copy_back(pd->mp, off + sizeof(*th), thoff - sizeof(*th), opts);
3343 }
3344
3345 return PF_PASS;
3346 }