netfilter: Mark SYN/ACK packets as invalid from original direction
[pandora-kernel.git] / net / netfilter / nf_conntrack_proto_tcp.c
1 /* (C) 1999-2001 Paul `Rusty' Russell
2  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  */
8
9 #include <linux/types.h>
10 #include <linux/timer.h>
11 #include <linux/module.h>
12 #include <linux/in.h>
13 #include <linux/tcp.h>
14 #include <linux/spinlock.h>
15 #include <linux/skbuff.h>
16 #include <linux/ipv6.h>
17 #include <net/ip6_checksum.h>
18 #include <asm/unaligned.h>
19
20 #include <net/tcp.h>
21
22 #include <linux/netfilter.h>
23 #include <linux/netfilter_ipv4.h>
24 #include <linux/netfilter_ipv6.h>
25 #include <net/netfilter/nf_conntrack.h>
26 #include <net/netfilter/nf_conntrack_l4proto.h>
27 #include <net/netfilter/nf_conntrack_ecache.h>
28 #include <net/netfilter/nf_log.h>
29 #include <net/netfilter/ipv4/nf_conntrack_ipv4.h>
30 #include <net/netfilter/ipv6/nf_conntrack_ipv6.h>
31
32 /* "Be conservative in what you do,
33     be liberal in what you accept from others."
34     If it's non-zero, we mark only out of window RST segments as INVALID. */
35 static int nf_ct_tcp_be_liberal __read_mostly = 0;
36
37 /* If it is set to zero, we disable picking up already established
38    connections. */
39 static int nf_ct_tcp_loose __read_mostly = 1;
40
41 /* Max number of the retransmitted packets without receiving an (acceptable)
42    ACK from the destination. If this number is reached, a shorter timer
43    will be started. */
44 static int nf_ct_tcp_max_retrans __read_mostly = 3;
45
46   /* FIXME: Examine ipfilter's timeouts and conntrack transitions more
47      closely.  They're more complex. --RR */
48
49 static const char *const tcp_conntrack_names[] = {
50         "NONE",
51         "SYN_SENT",
52         "SYN_RECV",
53         "ESTABLISHED",
54         "FIN_WAIT",
55         "CLOSE_WAIT",
56         "LAST_ACK",
57         "TIME_WAIT",
58         "CLOSE",
59         "SYN_SENT2",
60 };
61
62 #define SECS * HZ
63 #define MINS * 60 SECS
64 #define HOURS * 60 MINS
65 #define DAYS * 24 HOURS
66
67 /* RFC1122 says the R2 limit should be at least 100 seconds.
68    Linux uses 15 packets as limit, which corresponds
69    to ~13-30min depending on RTO. */
70 static unsigned int nf_ct_tcp_timeout_max_retrans __read_mostly    =   5 MINS;
71 static unsigned int nf_ct_tcp_timeout_unacknowledged __read_mostly =   5 MINS;
72
73 static unsigned int tcp_timeouts[TCP_CONNTRACK_MAX] __read_mostly = {
74         [TCP_CONNTRACK_SYN_SENT]        = 2 MINS,
75         [TCP_CONNTRACK_SYN_RECV]        = 60 SECS,
76         [TCP_CONNTRACK_ESTABLISHED]     = 5 DAYS,
77         [TCP_CONNTRACK_FIN_WAIT]        = 2 MINS,
78         [TCP_CONNTRACK_CLOSE_WAIT]      = 60 SECS,
79         [TCP_CONNTRACK_LAST_ACK]        = 30 SECS,
80         [TCP_CONNTRACK_TIME_WAIT]       = 2 MINS,
81         [TCP_CONNTRACK_CLOSE]           = 10 SECS,
82         [TCP_CONNTRACK_SYN_SENT2]       = 2 MINS,
83 };
84
85 #define sNO TCP_CONNTRACK_NONE
86 #define sSS TCP_CONNTRACK_SYN_SENT
87 #define sSR TCP_CONNTRACK_SYN_RECV
88 #define sES TCP_CONNTRACK_ESTABLISHED
89 #define sFW TCP_CONNTRACK_FIN_WAIT
90 #define sCW TCP_CONNTRACK_CLOSE_WAIT
91 #define sLA TCP_CONNTRACK_LAST_ACK
92 #define sTW TCP_CONNTRACK_TIME_WAIT
93 #define sCL TCP_CONNTRACK_CLOSE
94 #define sS2 TCP_CONNTRACK_SYN_SENT2
95 #define sIV TCP_CONNTRACK_MAX
96 #define sIG TCP_CONNTRACK_IGNORE
97
98 /* What TCP flags are set from RST/SYN/FIN/ACK. */
99 enum tcp_bit_set {
100         TCP_SYN_SET,
101         TCP_SYNACK_SET,
102         TCP_FIN_SET,
103         TCP_ACK_SET,
104         TCP_RST_SET,
105         TCP_NONE_SET,
106 };
107
108 /*
109  * The TCP state transition table needs a few words...
110  *
111  * We are the man in the middle. All the packets go through us
112  * but might get lost in transit to the destination.
113  * It is assumed that the destinations can't receive segments
114  * we haven't seen.
115  *
116  * The checked segment is in window, but our windows are *not*
117  * equivalent with the ones of the sender/receiver. We always
118  * try to guess the state of the current sender.
119  *
120  * The meaning of the states are:
121  *
122  * NONE:        initial state
123  * SYN_SENT:    SYN-only packet seen
124  * SYN_SENT2:   SYN-only packet seen from reply dir, simultaneous open
125  * SYN_RECV:    SYN-ACK packet seen
126  * ESTABLISHED: ACK packet seen
127  * FIN_WAIT:    FIN packet seen
128  * CLOSE_WAIT:  ACK seen (after FIN)
129  * LAST_ACK:    FIN seen (after FIN)
130  * TIME_WAIT:   last ACK seen
131  * CLOSE:       closed connection (RST)
132  *
133  * Packets marked as IGNORED (sIG):
134  *      if they may be either invalid or valid
135  *      and the receiver may send back a connection
136  *      closing RST or a SYN/ACK.
137  *
138  * Packets marked as INVALID (sIV):
139  *      if we regard them as truly invalid packets
140  */
141 static const u8 tcp_conntracks[2][6][TCP_CONNTRACK_MAX] = {
142         {
143 /* ORIGINAL */
144 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
145 /*syn*/    { sSS, sSS, sIG, sIG, sIG, sIG, sIG, sSS, sSS, sS2 },
146 /*
147  *      sNO -> sSS      Initialize a new connection
148  *      sSS -> sSS      Retransmitted SYN
149  *      sS2 -> sS2      Late retransmitted SYN
150  *      sSR -> sIG
151  *      sES -> sIG      Error: SYNs in window outside the SYN_SENT state
152  *                      are errors. Receiver will reply with RST
153  *                      and close the connection.
154  *                      Or we are not in sync and hold a dead connection.
155  *      sFW -> sIG
156  *      sCW -> sIG
157  *      sLA -> sIG
158  *      sTW -> sSS      Reopened connection (RFC 1122).
159  *      sCL -> sSS
160  */
161 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
162 /*synack*/ { sIV, sIV, sSR, sIV, sIV, sIV, sIV, sIV, sIV, sSR },
163 /*
164  *      sNO -> sIV      Too late and no reason to do anything
165  *      sSS -> sIV      Client can't send SYN and then SYN/ACK
166  *      sS2 -> sSR      SYN/ACK sent to SYN2 in simultaneous open
167  *      sSR -> sSR      Late retransmitted SYN/ACK in simultaneous open
168  *      sES -> sIV      Invalid SYN/ACK packets sent by the client
169  *      sFW -> sIV
170  *      sCW -> sIV
171  *      sLA -> sIV
172  *      sTW -> sIV
173  *      sCL -> sIV
174  */
175 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
176 /*fin*/    { sIV, sIV, sFW, sFW, sLA, sLA, sLA, sTW, sCL, sIV },
177 /*
178  *      sNO -> sIV      Too late and no reason to do anything...
179  *      sSS -> sIV      Client migth not send FIN in this state:
180  *                      we enforce waiting for a SYN/ACK reply first.
181  *      sS2 -> sIV
182  *      sSR -> sFW      Close started.
183  *      sES -> sFW
184  *      sFW -> sLA      FIN seen in both directions, waiting for
185  *                      the last ACK.
186  *                      Migth be a retransmitted FIN as well...
187  *      sCW -> sLA
188  *      sLA -> sLA      Retransmitted FIN. Remain in the same state.
189  *      sTW -> sTW
190  *      sCL -> sCL
191  */
192 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
193 /*ack*/    { sES, sIV, sES, sES, sCW, sCW, sTW, sTW, sCL, sIV },
194 /*
195  *      sNO -> sES      Assumed.
196  *      sSS -> sIV      ACK is invalid: we haven't seen a SYN/ACK yet.
197  *      sS2 -> sIV
198  *      sSR -> sES      Established state is reached.
199  *      sES -> sES      :-)
200  *      sFW -> sCW      Normal close request answered by ACK.
201  *      sCW -> sCW
202  *      sLA -> sTW      Last ACK detected.
203  *      sTW -> sTW      Retransmitted last ACK. Remain in the same state.
204  *      sCL -> sCL
205  */
206 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
207 /*rst*/    { sIV, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL },
208 /*none*/   { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV }
209         },
210         {
211 /* REPLY */
212 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
213 /*syn*/    { sIV, sS2, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sS2 },
214 /*
215  *      sNO -> sIV      Never reached.
216  *      sSS -> sS2      Simultaneous open
217  *      sS2 -> sS2      Retransmitted simultaneous SYN
218  *      sSR -> sIV      Invalid SYN packets sent by the server
219  *      sES -> sIV
220  *      sFW -> sIV
221  *      sCW -> sIV
222  *      sLA -> sIV
223  *      sTW -> sIV      Reopened connection, but server may not do it.
224  *      sCL -> sIV
225  */
226 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
227 /*synack*/ { sIV, sSR, sIG, sIG, sIG, sIG, sIG, sIG, sIG, sSR },
228 /*
229  *      sSS -> sSR      Standard open.
230  *      sS2 -> sSR      Simultaneous open
231  *      sSR -> sIG      Retransmitted SYN/ACK, ignore it.
232  *      sES -> sIG      Late retransmitted SYN/ACK?
233  *      sFW -> sIG      Might be SYN/ACK answering ignored SYN
234  *      sCW -> sIG
235  *      sLA -> sIG
236  *      sTW -> sIG
237  *      sCL -> sIG
238  */
239 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
240 /*fin*/    { sIV, sIV, sFW, sFW, sLA, sLA, sLA, sTW, sCL, sIV },
241 /*
242  *      sSS -> sIV      Server might not send FIN in this state.
243  *      sS2 -> sIV
244  *      sSR -> sFW      Close started.
245  *      sES -> sFW
246  *      sFW -> sLA      FIN seen in both directions.
247  *      sCW -> sLA
248  *      sLA -> sLA      Retransmitted FIN.
249  *      sTW -> sTW
250  *      sCL -> sCL
251  */
252 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
253 /*ack*/    { sIV, sIG, sSR, sES, sCW, sCW, sTW, sTW, sCL, sIG },
254 /*
255  *      sSS -> sIG      Might be a half-open connection.
256  *      sS2 -> sIG
257  *      sSR -> sSR      Might answer late resent SYN.
258  *      sES -> sES      :-)
259  *      sFW -> sCW      Normal close request answered by ACK.
260  *      sCW -> sCW
261  *      sLA -> sTW      Last ACK detected.
262  *      sTW -> sTW      Retransmitted last ACK.
263  *      sCL -> sCL
264  */
265 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sS2   */
266 /*rst*/    { sIV, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL },
267 /*none*/   { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV }
268         }
269 };
270
271 static bool tcp_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff,
272                              struct nf_conntrack_tuple *tuple)
273 {
274         const struct tcphdr *hp;
275         struct tcphdr _hdr;
276
277         /* Actually only need first 8 bytes. */
278         hp = skb_header_pointer(skb, dataoff, 8, &_hdr);
279         if (hp == NULL)
280                 return false;
281
282         tuple->src.u.tcp.port = hp->source;
283         tuple->dst.u.tcp.port = hp->dest;
284
285         return true;
286 }
287
288 static bool tcp_invert_tuple(struct nf_conntrack_tuple *tuple,
289                              const struct nf_conntrack_tuple *orig)
290 {
291         tuple->src.u.tcp.port = orig->dst.u.tcp.port;
292         tuple->dst.u.tcp.port = orig->src.u.tcp.port;
293         return true;
294 }
295
296 /* Print out the per-protocol part of the tuple. */
297 static int tcp_print_tuple(struct seq_file *s,
298                            const struct nf_conntrack_tuple *tuple)
299 {
300         return seq_printf(s, "sport=%hu dport=%hu ",
301                           ntohs(tuple->src.u.tcp.port),
302                           ntohs(tuple->dst.u.tcp.port));
303 }
304
305 /* Print out the private part of the conntrack. */
306 static int tcp_print_conntrack(struct seq_file *s, struct nf_conn *ct)
307 {
308         enum tcp_conntrack state;
309
310         spin_lock_bh(&ct->lock);
311         state = ct->proto.tcp.state;
312         spin_unlock_bh(&ct->lock);
313
314         return seq_printf(s, "%s ", tcp_conntrack_names[state]);
315 }
316
317 static unsigned int get_conntrack_index(const struct tcphdr *tcph)
318 {
319         if (tcph->rst) return TCP_RST_SET;
320         else if (tcph->syn) return (tcph->ack ? TCP_SYNACK_SET : TCP_SYN_SET);
321         else if (tcph->fin) return TCP_FIN_SET;
322         else if (tcph->ack) return TCP_ACK_SET;
323         else return TCP_NONE_SET;
324 }
325
326 /* TCP connection tracking based on 'Real Stateful TCP Packet Filtering
327    in IP Filter' by Guido van Rooij.
328
329    http://www.sane.nl/events/sane2000/papers.html
330    http://www.darkart.com/mirrors/www.obfuscation.org/ipf/
331
332    The boundaries and the conditions are changed according to RFC793:
333    the packet must intersect the window (i.e. segments may be
334    after the right or before the left edge) and thus receivers may ACK
335    segments after the right edge of the window.
336
337         td_maxend = max(sack + max(win,1)) seen in reply packets
338         td_maxwin = max(max(win, 1)) + (sack - ack) seen in sent packets
339         td_maxwin += seq + len - sender.td_maxend
340                         if seq + len > sender.td_maxend
341         td_end    = max(seq + len) seen in sent packets
342
343    I.   Upper bound for valid data:     seq <= sender.td_maxend
344    II.  Lower bound for valid data:     seq + len >= sender.td_end - receiver.td_maxwin
345    III. Upper bound for valid (s)ack:   sack <= receiver.td_end
346    IV.  Lower bound for valid (s)ack:   sack >= receiver.td_end - MAXACKWINDOW
347
348    where sack is the highest right edge of sack block found in the packet
349    or ack in the case of packet without SACK option.
350
351    The upper bound limit for a valid (s)ack is not ignored -
352    we doesn't have to deal with fragments.
353 */
354
355 static inline __u32 segment_seq_plus_len(__u32 seq,
356                                          size_t len,
357                                          unsigned int dataoff,
358                                          const struct tcphdr *tcph)
359 {
360         /* XXX Should I use payload length field in IP/IPv6 header ?
361          * - YK */
362         return (seq + len - dataoff - tcph->doff*4
363                 + (tcph->syn ? 1 : 0) + (tcph->fin ? 1 : 0));
364 }
365
366 /* Fixme: what about big packets? */
367 #define MAXACKWINCONST                  66000
368 #define MAXACKWINDOW(sender)                                            \
369         ((sender)->td_maxwin > MAXACKWINCONST ? (sender)->td_maxwin     \
370                                               : MAXACKWINCONST)
371
372 /*
373  * Simplified tcp_parse_options routine from tcp_input.c
374  */
375 static void tcp_options(const struct sk_buff *skb,
376                         unsigned int dataoff,
377                         const struct tcphdr *tcph,
378                         struct ip_ct_tcp_state *state)
379 {
380         unsigned char buff[(15 * 4) - sizeof(struct tcphdr)];
381         const unsigned char *ptr;
382         int length = (tcph->doff*4) - sizeof(struct tcphdr);
383
384         if (!length)
385                 return;
386
387         ptr = skb_header_pointer(skb, dataoff + sizeof(struct tcphdr),
388                                  length, buff);
389         BUG_ON(ptr == NULL);
390
391         state->td_scale =
392         state->flags = 0;
393
394         while (length > 0) {
395                 int opcode=*ptr++;
396                 int opsize;
397
398                 switch (opcode) {
399                 case TCPOPT_EOL:
400                         return;
401                 case TCPOPT_NOP:        /* Ref: RFC 793 section 3.1 */
402                         length--;
403                         continue;
404                 default:
405                         opsize=*ptr++;
406                         if (opsize < 2) /* "silly options" */
407                                 return;
408                         if (opsize > length)
409                                 return; /* don't parse partial options */
410
411                         if (opcode == TCPOPT_SACK_PERM
412                             && opsize == TCPOLEN_SACK_PERM)
413                                 state->flags |= IP_CT_TCP_FLAG_SACK_PERM;
414                         else if (opcode == TCPOPT_WINDOW
415                                  && opsize == TCPOLEN_WINDOW) {
416                                 state->td_scale = *(u_int8_t *)ptr;
417
418                                 if (state->td_scale > 14) {
419                                         /* See RFC1323 */
420                                         state->td_scale = 14;
421                                 }
422                                 state->flags |=
423                                         IP_CT_TCP_FLAG_WINDOW_SCALE;
424                         }
425                         ptr += opsize - 2;
426                         length -= opsize;
427                 }
428         }
429 }
430
431 static void tcp_sack(const struct sk_buff *skb, unsigned int dataoff,
432                      const struct tcphdr *tcph, __u32 *sack)
433 {
434         unsigned char buff[(15 * 4) - sizeof(struct tcphdr)];
435         const unsigned char *ptr;
436         int length = (tcph->doff*4) - sizeof(struct tcphdr);
437         __u32 tmp;
438
439         if (!length)
440                 return;
441
442         ptr = skb_header_pointer(skb, dataoff + sizeof(struct tcphdr),
443                                  length, buff);
444         BUG_ON(ptr == NULL);
445
446         /* Fast path for timestamp-only option */
447         if (length == TCPOLEN_TSTAMP_ALIGNED
448             && *(__be32 *)ptr == htonl((TCPOPT_NOP << 24)
449                                        | (TCPOPT_NOP << 16)
450                                        | (TCPOPT_TIMESTAMP << 8)
451                                        | TCPOLEN_TIMESTAMP))
452                 return;
453
454         while (length > 0) {
455                 int opcode = *ptr++;
456                 int opsize, i;
457
458                 switch (opcode) {
459                 case TCPOPT_EOL:
460                         return;
461                 case TCPOPT_NOP:        /* Ref: RFC 793 section 3.1 */
462                         length--;
463                         continue;
464                 default:
465                         opsize = *ptr++;
466                         if (opsize < 2) /* "silly options" */
467                                 return;
468                         if (opsize > length)
469                                 return; /* don't parse partial options */
470
471                         if (opcode == TCPOPT_SACK
472                             && opsize >= (TCPOLEN_SACK_BASE
473                                           + TCPOLEN_SACK_PERBLOCK)
474                             && !((opsize - TCPOLEN_SACK_BASE)
475                                  % TCPOLEN_SACK_PERBLOCK)) {
476                                 for (i = 0;
477                                      i < (opsize - TCPOLEN_SACK_BASE);
478                                      i += TCPOLEN_SACK_PERBLOCK) {
479                                         tmp = get_unaligned_be32((__be32 *)(ptr+i)+1);
480
481                                         if (after(tmp, *sack))
482                                                 *sack = tmp;
483                                 }
484                                 return;
485                         }
486                         ptr += opsize - 2;
487                         length -= opsize;
488                 }
489         }
490 }
491
492 #ifdef CONFIG_NF_NAT_NEEDED
493 static inline s16 nat_offset(const struct nf_conn *ct,
494                              enum ip_conntrack_dir dir,
495                              u32 seq)
496 {
497         typeof(nf_ct_nat_offset) get_offset = rcu_dereference(nf_ct_nat_offset);
498
499         return get_offset != NULL ? get_offset(ct, dir, seq) : 0;
500 }
501 #define NAT_OFFSET(pf, ct, dir, seq) \
502         (pf == NFPROTO_IPV4 ? nat_offset(ct, dir, seq) : 0)
503 #else
504 #define NAT_OFFSET(pf, ct, dir, seq)    0
505 #endif
506
507 static bool tcp_in_window(const struct nf_conn *ct,
508                           struct ip_ct_tcp *state,
509                           enum ip_conntrack_dir dir,
510                           unsigned int index,
511                           const struct sk_buff *skb,
512                           unsigned int dataoff,
513                           const struct tcphdr *tcph,
514                           u_int8_t pf)
515 {
516         struct net *net = nf_ct_net(ct);
517         struct ip_ct_tcp_state *sender = &state->seen[dir];
518         struct ip_ct_tcp_state *receiver = &state->seen[!dir];
519         const struct nf_conntrack_tuple *tuple = &ct->tuplehash[dir].tuple;
520         __u32 seq, ack, sack, end, win, swin;
521         s16 receiver_offset;
522         bool res;
523
524         /*
525          * Get the required data from the packet.
526          */
527         seq = ntohl(tcph->seq);
528         ack = sack = ntohl(tcph->ack_seq);
529         win = ntohs(tcph->window);
530         end = segment_seq_plus_len(seq, skb->len, dataoff, tcph);
531
532         if (receiver->flags & IP_CT_TCP_FLAG_SACK_PERM)
533                 tcp_sack(skb, dataoff, tcph, &sack);
534
535         /* Take into account NAT sequence number mangling */
536         receiver_offset = NAT_OFFSET(pf, ct, !dir, ack - 1);
537         ack -= receiver_offset;
538         sack -= receiver_offset;
539
540         pr_debug("tcp_in_window: START\n");
541         pr_debug("tcp_in_window: ");
542         nf_ct_dump_tuple(tuple);
543         pr_debug("seq=%u ack=%u+(%d) sack=%u+(%d) win=%u end=%u\n",
544                  seq, ack, receiver_offset, sack, receiver_offset, win, end);
545         pr_debug("tcp_in_window: sender end=%u maxend=%u maxwin=%u scale=%i "
546                  "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
547                  sender->td_end, sender->td_maxend, sender->td_maxwin,
548                  sender->td_scale,
549                  receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
550                  receiver->td_scale);
551
552         if (sender->td_maxwin == 0) {
553                 /*
554                  * Initialize sender data.
555                  */
556                 if (tcph->syn) {
557                         /*
558                          * SYN-ACK in reply to a SYN
559                          * or SYN from reply direction in simultaneous open.
560                          */
561                         sender->td_end =
562                         sender->td_maxend = end;
563                         sender->td_maxwin = (win == 0 ? 1 : win);
564
565                         tcp_options(skb, dataoff, tcph, sender);
566                         /*
567                          * RFC 1323:
568                          * Both sides must send the Window Scale option
569                          * to enable window scaling in either direction.
570                          */
571                         if (!(sender->flags & IP_CT_TCP_FLAG_WINDOW_SCALE
572                               && receiver->flags & IP_CT_TCP_FLAG_WINDOW_SCALE))
573                                 sender->td_scale =
574                                 receiver->td_scale = 0;
575                         if (!tcph->ack)
576                                 /* Simultaneous open */
577                                 return true;
578                 } else {
579                         /*
580                          * We are in the middle of a connection,
581                          * its history is lost for us.
582                          * Let's try to use the data from the packet.
583                          */
584                         sender->td_end = end;
585                         win <<= sender->td_scale;
586                         sender->td_maxwin = (win == 0 ? 1 : win);
587                         sender->td_maxend = end + sender->td_maxwin;
588                         /*
589                          * We haven't seen traffic in the other direction yet
590                          * but we have to tweak window tracking to pass III
591                          * and IV until that happens.
592                          */
593                         if (receiver->td_maxwin == 0)
594                                 receiver->td_end = receiver->td_maxend = sack;
595                 }
596         } else if (((state->state == TCP_CONNTRACK_SYN_SENT
597                      && dir == IP_CT_DIR_ORIGINAL)
598                    || (state->state == TCP_CONNTRACK_SYN_RECV
599                      && dir == IP_CT_DIR_REPLY))
600                    && after(end, sender->td_end)) {
601                 /*
602                  * RFC 793: "if a TCP is reinitialized ... then it need
603                  * not wait at all; it must only be sure to use sequence
604                  * numbers larger than those recently used."
605                  */
606                 sender->td_end =
607                 sender->td_maxend = end;
608                 sender->td_maxwin = (win == 0 ? 1 : win);
609
610                 tcp_options(skb, dataoff, tcph, sender);
611         }
612
613         if (!(tcph->ack)) {
614                 /*
615                  * If there is no ACK, just pretend it was set and OK.
616                  */
617                 ack = sack = receiver->td_end;
618         } else if (((tcp_flag_word(tcph) & (TCP_FLAG_ACK|TCP_FLAG_RST)) ==
619                     (TCP_FLAG_ACK|TCP_FLAG_RST))
620                    && (ack == 0)) {
621                 /*
622                  * Broken TCP stacks, that set ACK in RST packets as well
623                  * with zero ack value.
624                  */
625                 ack = sack = receiver->td_end;
626         }
627
628         if (seq == end
629             && (!tcph->rst
630                 || (seq == 0 && state->state == TCP_CONNTRACK_SYN_SENT)))
631                 /*
632                  * Packets contains no data: we assume it is valid
633                  * and check the ack value only.
634                  * However RST segments are always validated by their
635                  * SEQ number, except when seq == 0 (reset sent answering
636                  * SYN.
637                  */
638                 seq = end = sender->td_end;
639
640         pr_debug("tcp_in_window: ");
641         nf_ct_dump_tuple(tuple);
642         pr_debug("seq=%u ack=%u+(%d) sack=%u+(%d) win=%u end=%u\n",
643                  seq, ack, receiver_offset, sack, receiver_offset, win, end);
644         pr_debug("tcp_in_window: sender end=%u maxend=%u maxwin=%u scale=%i "
645                  "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
646                  sender->td_end, sender->td_maxend, sender->td_maxwin,
647                  sender->td_scale,
648                  receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
649                  receiver->td_scale);
650
651         pr_debug("tcp_in_window: I=%i II=%i III=%i IV=%i\n",
652                  before(seq, sender->td_maxend + 1),
653                  after(end, sender->td_end - receiver->td_maxwin - 1),
654                  before(sack, receiver->td_end + 1),
655                  after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1));
656
657         if (before(seq, sender->td_maxend + 1) &&
658             after(end, sender->td_end - receiver->td_maxwin - 1) &&
659             before(sack, receiver->td_end + 1) &&
660             after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1)) {
661                 /*
662                  * Take into account window scaling (RFC 1323).
663                  */
664                 if (!tcph->syn)
665                         win <<= sender->td_scale;
666
667                 /*
668                  * Update sender data.
669                  */
670                 swin = win + (sack - ack);
671                 if (sender->td_maxwin < swin)
672                         sender->td_maxwin = swin;
673                 if (after(end, sender->td_end)) {
674                         sender->td_end = end;
675                         sender->flags |= IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED;
676                 }
677                 if (tcph->ack) {
678                         if (!(sender->flags & IP_CT_TCP_FLAG_MAXACK_SET)) {
679                                 sender->td_maxack = ack;
680                                 sender->flags |= IP_CT_TCP_FLAG_MAXACK_SET;
681                         } else if (after(ack, sender->td_maxack))
682                                 sender->td_maxack = ack;
683                 }
684
685                 /*
686                  * Update receiver data.
687                  */
688                 if (receiver->td_maxwin != 0 && after(end, sender->td_maxend))
689                         receiver->td_maxwin += end - sender->td_maxend;
690                 if (after(sack + win, receiver->td_maxend - 1)) {
691                         receiver->td_maxend = sack + win;
692                         if (win == 0)
693                                 receiver->td_maxend++;
694                 }
695                 if (ack == receiver->td_end)
696                         receiver->flags &= ~IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED;
697
698                 /*
699                  * Check retransmissions.
700                  */
701                 if (index == TCP_ACK_SET) {
702                         if (state->last_dir == dir
703                             && state->last_seq == seq
704                             && state->last_ack == ack
705                             && state->last_end == end
706                             && state->last_win == win)
707                                 state->retrans++;
708                         else {
709                                 state->last_dir = dir;
710                                 state->last_seq = seq;
711                                 state->last_ack = ack;
712                                 state->last_end = end;
713                                 state->last_win = win;
714                                 state->retrans = 0;
715                         }
716                 }
717                 res = true;
718         } else {
719                 res = false;
720                 if (sender->flags & IP_CT_TCP_FLAG_BE_LIBERAL ||
721                     nf_ct_tcp_be_liberal)
722                         res = true;
723                 if (!res && LOG_INVALID(net, IPPROTO_TCP))
724                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
725                         "nf_ct_tcp: %s ",
726                         before(seq, sender->td_maxend + 1) ?
727                         after(end, sender->td_end - receiver->td_maxwin - 1) ?
728                         before(sack, receiver->td_end + 1) ?
729                         after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1) ? "BUG"
730                         : "ACK is under the lower bound (possible overly delayed ACK)"
731                         : "ACK is over the upper bound (ACKed data not seen yet)"
732                         : "SEQ is under the lower bound (already ACKed data retransmitted)"
733                         : "SEQ is over the upper bound (over the window of the receiver)");
734         }
735
736         pr_debug("tcp_in_window: res=%u sender end=%u maxend=%u maxwin=%u "
737                  "receiver end=%u maxend=%u maxwin=%u\n",
738                  res, sender->td_end, sender->td_maxend, sender->td_maxwin,
739                  receiver->td_end, receiver->td_maxend, receiver->td_maxwin);
740
741         return res;
742 }
743
744 /* table of valid flag combinations - PUSH, ECE and CWR are always valid */
745 static const u8 tcp_valid_flags[(TCPHDR_FIN|TCPHDR_SYN|TCPHDR_RST|TCPHDR_ACK|
746                                  TCPHDR_URG) + 1] =
747 {
748         [TCPHDR_SYN]                            = 1,
749         [TCPHDR_SYN|TCPHDR_URG]                 = 1,
750         [TCPHDR_SYN|TCPHDR_ACK]                 = 1,
751         [TCPHDR_RST]                            = 1,
752         [TCPHDR_RST|TCPHDR_ACK]                 = 1,
753         [TCPHDR_FIN|TCPHDR_ACK]                 = 1,
754         [TCPHDR_FIN|TCPHDR_ACK|TCPHDR_URG]      = 1,
755         [TCPHDR_ACK]                            = 1,
756         [TCPHDR_ACK|TCPHDR_URG]                 = 1,
757 };
758
759 /* Protect conntrack agaist broken packets. Code taken from ipt_unclean.c.  */
760 static int tcp_error(struct net *net, struct nf_conn *tmpl,
761                      struct sk_buff *skb,
762                      unsigned int dataoff,
763                      enum ip_conntrack_info *ctinfo,
764                      u_int8_t pf,
765                      unsigned int hooknum)
766 {
767         const struct tcphdr *th;
768         struct tcphdr _tcph;
769         unsigned int tcplen = skb->len - dataoff;
770         u_int8_t tcpflags;
771
772         /* Smaller that minimal TCP header? */
773         th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
774         if (th == NULL) {
775                 if (LOG_INVALID(net, IPPROTO_TCP))
776                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
777                                 "nf_ct_tcp: short packet ");
778                 return -NF_ACCEPT;
779         }
780
781         /* Not whole TCP header or malformed packet */
782         if (th->doff*4 < sizeof(struct tcphdr) || tcplen < th->doff*4) {
783                 if (LOG_INVALID(net, IPPROTO_TCP))
784                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
785                                 "nf_ct_tcp: truncated/malformed packet ");
786                 return -NF_ACCEPT;
787         }
788
789         /* Checksum invalid? Ignore.
790          * We skip checking packets on the outgoing path
791          * because the checksum is assumed to be correct.
792          */
793         /* FIXME: Source route IP option packets --RR */
794         if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING &&
795             nf_checksum(skb, hooknum, dataoff, IPPROTO_TCP, pf)) {
796                 if (LOG_INVALID(net, IPPROTO_TCP))
797                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
798                                   "nf_ct_tcp: bad TCP checksum ");
799                 return -NF_ACCEPT;
800         }
801
802         /* Check TCP flags. */
803         tcpflags = (tcp_flag_byte(th) & ~(TCPHDR_ECE|TCPHDR_CWR|TCPHDR_PSH));
804         if (!tcp_valid_flags[tcpflags]) {
805                 if (LOG_INVALID(net, IPPROTO_TCP))
806                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
807                                   "nf_ct_tcp: invalid TCP flag combination ");
808                 return -NF_ACCEPT;
809         }
810
811         return NF_ACCEPT;
812 }
813
814 /* Returns verdict for packet, or -1 for invalid. */
815 static int tcp_packet(struct nf_conn *ct,
816                       const struct sk_buff *skb,
817                       unsigned int dataoff,
818                       enum ip_conntrack_info ctinfo,
819                       u_int8_t pf,
820                       unsigned int hooknum)
821 {
822         struct net *net = nf_ct_net(ct);
823         struct nf_conntrack_tuple *tuple;
824         enum tcp_conntrack new_state, old_state;
825         enum ip_conntrack_dir dir;
826         const struct tcphdr *th;
827         struct tcphdr _tcph;
828         unsigned long timeout;
829         unsigned int index;
830
831         th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
832         BUG_ON(th == NULL);
833
834         spin_lock_bh(&ct->lock);
835         old_state = ct->proto.tcp.state;
836         dir = CTINFO2DIR(ctinfo);
837         index = get_conntrack_index(th);
838         new_state = tcp_conntracks[dir][index][old_state];
839         tuple = &ct->tuplehash[dir].tuple;
840
841         switch (new_state) {
842         case TCP_CONNTRACK_SYN_SENT:
843                 if (old_state < TCP_CONNTRACK_TIME_WAIT)
844                         break;
845                 /* RFC 1122: "When a connection is closed actively,
846                  * it MUST linger in TIME-WAIT state for a time 2xMSL
847                  * (Maximum Segment Lifetime). However, it MAY accept
848                  * a new SYN from the remote TCP to reopen the connection
849                  * directly from TIME-WAIT state, if..."
850                  * We ignore the conditions because we are in the
851                  * TIME-WAIT state anyway.
852                  *
853                  * Handle aborted connections: we and the server
854                  * think there is an existing connection but the client
855                  * aborts it and starts a new one.
856                  */
857                 if (((ct->proto.tcp.seen[dir].flags
858                       | ct->proto.tcp.seen[!dir].flags)
859                      & IP_CT_TCP_FLAG_CLOSE_INIT)
860                     || (ct->proto.tcp.last_dir == dir
861                         && ct->proto.tcp.last_index == TCP_RST_SET)) {
862                         /* Attempt to reopen a closed/aborted connection.
863                          * Delete this connection and look up again. */
864                         spin_unlock_bh(&ct->lock);
865
866                         /* Only repeat if we can actually remove the timer.
867                          * Destruction may already be in progress in process
868                          * context and we must give it a chance to terminate.
869                          */
870                         if (nf_ct_kill(ct))
871                                 return -NF_REPEAT;
872                         return NF_DROP;
873                 }
874                 /* Fall through */
875         case TCP_CONNTRACK_IGNORE:
876                 /* Ignored packets:
877                  *
878                  * Our connection entry may be out of sync, so ignore
879                  * packets which may signal the real connection between
880                  * the client and the server.
881                  *
882                  * a) SYN in ORIGINAL
883                  * b) SYN/ACK in REPLY
884                  * c) ACK in reply direction after initial SYN in original.
885                  *
886                  * If the ignored packet is invalid, the receiver will send
887                  * a RST we'll catch below.
888                  */
889                 if (index == TCP_SYNACK_SET
890                     && ct->proto.tcp.last_index == TCP_SYN_SET
891                     && ct->proto.tcp.last_dir != dir
892                     && ntohl(th->ack_seq) == ct->proto.tcp.last_end) {
893                         /* b) This SYN/ACK acknowledges a SYN that we earlier
894                          * ignored as invalid. This means that the client and
895                          * the server are both in sync, while the firewall is
896                          * not. We get in sync from the previously annotated
897                          * values.
898                          */
899                         old_state = TCP_CONNTRACK_SYN_SENT;
900                         new_state = TCP_CONNTRACK_SYN_RECV;
901                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_end =
902                                 ct->proto.tcp.last_end;
903                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_maxend =
904                                 ct->proto.tcp.last_end;
905                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_maxwin =
906                                 ct->proto.tcp.last_win == 0 ?
907                                         1 : ct->proto.tcp.last_win;
908                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_scale =
909                                 ct->proto.tcp.last_wscale;
910                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].flags =
911                                 ct->proto.tcp.last_flags;
912                         memset(&ct->proto.tcp.seen[dir], 0,
913                                sizeof(struct ip_ct_tcp_state));
914                         break;
915                 }
916                 ct->proto.tcp.last_index = index;
917                 ct->proto.tcp.last_dir = dir;
918                 ct->proto.tcp.last_seq = ntohl(th->seq);
919                 ct->proto.tcp.last_end =
920                     segment_seq_plus_len(ntohl(th->seq), skb->len, dataoff, th);
921                 ct->proto.tcp.last_win = ntohs(th->window);
922
923                 /* a) This is a SYN in ORIGINAL. The client and the server
924                  * may be in sync but we are not. In that case, we annotate
925                  * the TCP options and let the packet go through. If it is a
926                  * valid SYN packet, the server will reply with a SYN/ACK, and
927                  * then we'll get in sync. Otherwise, the server ignores it. */
928                 if (index == TCP_SYN_SET && dir == IP_CT_DIR_ORIGINAL) {
929                         struct ip_ct_tcp_state seen = {};
930
931                         ct->proto.tcp.last_flags =
932                         ct->proto.tcp.last_wscale = 0;
933                         tcp_options(skb, dataoff, th, &seen);
934                         if (seen.flags & IP_CT_TCP_FLAG_WINDOW_SCALE) {
935                                 ct->proto.tcp.last_flags |=
936                                         IP_CT_TCP_FLAG_WINDOW_SCALE;
937                                 ct->proto.tcp.last_wscale = seen.td_scale;
938                         }
939                         if (seen.flags & IP_CT_TCP_FLAG_SACK_PERM) {
940                                 ct->proto.tcp.last_flags |=
941                                         IP_CT_TCP_FLAG_SACK_PERM;
942                         }
943                 }
944                 spin_unlock_bh(&ct->lock);
945                 if (LOG_INVALID(net, IPPROTO_TCP))
946                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
947                                   "nf_ct_tcp: invalid packet ignored ");
948                 return NF_ACCEPT;
949         case TCP_CONNTRACK_MAX:
950                 /* Invalid packet */
951                 pr_debug("nf_ct_tcp: Invalid dir=%i index=%u ostate=%u\n",
952                          dir, get_conntrack_index(th), old_state);
953                 spin_unlock_bh(&ct->lock);
954                 if (LOG_INVALID(net, IPPROTO_TCP))
955                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
956                                   "nf_ct_tcp: invalid state ");
957                 return -NF_ACCEPT;
958         case TCP_CONNTRACK_CLOSE:
959                 if (index == TCP_RST_SET
960                     && (ct->proto.tcp.seen[!dir].flags & IP_CT_TCP_FLAG_MAXACK_SET)
961                     && before(ntohl(th->seq), ct->proto.tcp.seen[!dir].td_maxack)) {
962                         /* Invalid RST  */
963                         spin_unlock_bh(&ct->lock);
964                         if (LOG_INVALID(net, IPPROTO_TCP))
965                                 nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
966                                           "nf_ct_tcp: invalid RST ");
967                         return -NF_ACCEPT;
968                 }
969                 if (index == TCP_RST_SET
970                     && ((test_bit(IPS_SEEN_REPLY_BIT, &ct->status)
971                          && ct->proto.tcp.last_index == TCP_SYN_SET)
972                         || (!test_bit(IPS_ASSURED_BIT, &ct->status)
973                             && ct->proto.tcp.last_index == TCP_ACK_SET))
974                     && ntohl(th->ack_seq) == ct->proto.tcp.last_end) {
975                         /* RST sent to invalid SYN or ACK we had let through
976                          * at a) and c) above:
977                          *
978                          * a) SYN was in window then
979                          * c) we hold a half-open connection.
980                          *
981                          * Delete our connection entry.
982                          * We skip window checking, because packet might ACK
983                          * segments we ignored. */
984                         goto in_window;
985                 }
986                 /* Just fall through */
987         default:
988                 /* Keep compilers happy. */
989                 break;
990         }
991
992         if (!tcp_in_window(ct, &ct->proto.tcp, dir, index,
993                            skb, dataoff, th, pf)) {
994                 spin_unlock_bh(&ct->lock);
995                 return -NF_ACCEPT;
996         }
997      in_window:
998         /* From now on we have got in-window packets */
999         ct->proto.tcp.last_index = index;
1000         ct->proto.tcp.last_dir = dir;
1001
1002         pr_debug("tcp_conntracks: ");
1003         nf_ct_dump_tuple(tuple);
1004         pr_debug("syn=%i ack=%i fin=%i rst=%i old=%i new=%i\n",
1005                  (th->syn ? 1 : 0), (th->ack ? 1 : 0),
1006                  (th->fin ? 1 : 0), (th->rst ? 1 : 0),
1007                  old_state, new_state);
1008
1009         ct->proto.tcp.state = new_state;
1010         if (old_state != new_state
1011             && new_state == TCP_CONNTRACK_FIN_WAIT)
1012                 ct->proto.tcp.seen[dir].flags |= IP_CT_TCP_FLAG_CLOSE_INIT;
1013
1014         if (ct->proto.tcp.retrans >= nf_ct_tcp_max_retrans &&
1015             tcp_timeouts[new_state] > nf_ct_tcp_timeout_max_retrans)
1016                 timeout = nf_ct_tcp_timeout_max_retrans;
1017         else if ((ct->proto.tcp.seen[0].flags | ct->proto.tcp.seen[1].flags) &
1018                  IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED &&
1019                  tcp_timeouts[new_state] > nf_ct_tcp_timeout_unacknowledged)
1020                 timeout = nf_ct_tcp_timeout_unacknowledged;
1021         else
1022                 timeout = tcp_timeouts[new_state];
1023         spin_unlock_bh(&ct->lock);
1024
1025         if (new_state != old_state)
1026                 nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
1027
1028         if (!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1029                 /* If only reply is a RST, we can consider ourselves not to
1030                    have an established connection: this is a fairly common
1031                    problem case, so we can delete the conntrack
1032                    immediately.  --RR */
1033                 if (th->rst) {
1034                         nf_ct_kill_acct(ct, ctinfo, skb);
1035                         return NF_ACCEPT;
1036                 }
1037         } else if (!test_bit(IPS_ASSURED_BIT, &ct->status)
1038                    && (old_state == TCP_CONNTRACK_SYN_RECV
1039                        || old_state == TCP_CONNTRACK_ESTABLISHED)
1040                    && new_state == TCP_CONNTRACK_ESTABLISHED) {
1041                 /* Set ASSURED if we see see valid ack in ESTABLISHED
1042                    after SYN_RECV or a valid answer for a picked up
1043                    connection. */
1044                 set_bit(IPS_ASSURED_BIT, &ct->status);
1045                 nf_conntrack_event_cache(IPCT_ASSURED, ct);
1046         }
1047         nf_ct_refresh_acct(ct, ctinfo, skb, timeout);
1048
1049         return NF_ACCEPT;
1050 }
1051
1052 /* Called when a new connection for this protocol found. */
1053 static bool tcp_new(struct nf_conn *ct, const struct sk_buff *skb,
1054                     unsigned int dataoff)
1055 {
1056         enum tcp_conntrack new_state;
1057         const struct tcphdr *th;
1058         struct tcphdr _tcph;
1059         const struct ip_ct_tcp_state *sender = &ct->proto.tcp.seen[0];
1060         const struct ip_ct_tcp_state *receiver = &ct->proto.tcp.seen[1];
1061
1062         th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
1063         BUG_ON(th == NULL);
1064
1065         /* Don't need lock here: this conntrack not in circulation yet */
1066         new_state = tcp_conntracks[0][get_conntrack_index(th)][TCP_CONNTRACK_NONE];
1067
1068         /* Invalid: delete conntrack */
1069         if (new_state >= TCP_CONNTRACK_MAX) {
1070                 pr_debug("nf_ct_tcp: invalid new deleting.\n");
1071                 return false;
1072         }
1073
1074         if (new_state == TCP_CONNTRACK_SYN_SENT) {
1075                 memset(&ct->proto.tcp, 0, sizeof(ct->proto.tcp));
1076                 /* SYN packet */
1077                 ct->proto.tcp.seen[0].td_end =
1078                         segment_seq_plus_len(ntohl(th->seq), skb->len,
1079                                              dataoff, th);
1080                 ct->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
1081                 if (ct->proto.tcp.seen[0].td_maxwin == 0)
1082                         ct->proto.tcp.seen[0].td_maxwin = 1;
1083                 ct->proto.tcp.seen[0].td_maxend =
1084                         ct->proto.tcp.seen[0].td_end;
1085
1086                 tcp_options(skb, dataoff, th, &ct->proto.tcp.seen[0]);
1087         } else if (nf_ct_tcp_loose == 0) {
1088                 /* Don't try to pick up connections. */
1089                 return false;
1090         } else {
1091                 memset(&ct->proto.tcp, 0, sizeof(ct->proto.tcp));
1092                 /*
1093                  * We are in the middle of a connection,
1094                  * its history is lost for us.
1095                  * Let's try to use the data from the packet.
1096                  */
1097                 ct->proto.tcp.seen[0].td_end =
1098                         segment_seq_plus_len(ntohl(th->seq), skb->len,
1099                                              dataoff, th);
1100                 ct->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
1101                 if (ct->proto.tcp.seen[0].td_maxwin == 0)
1102                         ct->proto.tcp.seen[0].td_maxwin = 1;
1103                 ct->proto.tcp.seen[0].td_maxend =
1104                         ct->proto.tcp.seen[0].td_end +
1105                         ct->proto.tcp.seen[0].td_maxwin;
1106
1107                 /* We assume SACK and liberal window checking to handle
1108                  * window scaling */
1109                 ct->proto.tcp.seen[0].flags =
1110                 ct->proto.tcp.seen[1].flags = IP_CT_TCP_FLAG_SACK_PERM |
1111                                               IP_CT_TCP_FLAG_BE_LIBERAL;
1112         }
1113
1114         /* tcp_packet will set them */
1115         ct->proto.tcp.last_index = TCP_NONE_SET;
1116
1117         pr_debug("tcp_new: sender end=%u maxend=%u maxwin=%u scale=%i "
1118                  "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
1119                  sender->td_end, sender->td_maxend, sender->td_maxwin,
1120                  sender->td_scale,
1121                  receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
1122                  receiver->td_scale);
1123         return true;
1124 }
1125
1126 #if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
1127
1128 #include <linux/netfilter/nfnetlink.h>
1129 #include <linux/netfilter/nfnetlink_conntrack.h>
1130
1131 static int tcp_to_nlattr(struct sk_buff *skb, struct nlattr *nla,
1132                          struct nf_conn *ct)
1133 {
1134         struct nlattr *nest_parms;
1135         struct nf_ct_tcp_flags tmp = {};
1136
1137         spin_lock_bh(&ct->lock);
1138         nest_parms = nla_nest_start(skb, CTA_PROTOINFO_TCP | NLA_F_NESTED);
1139         if (!nest_parms)
1140                 goto nla_put_failure;
1141
1142         NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_STATE, ct->proto.tcp.state);
1143
1144         NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_WSCALE_ORIGINAL,
1145                    ct->proto.tcp.seen[0].td_scale);
1146
1147         NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_WSCALE_REPLY,
1148                    ct->proto.tcp.seen[1].td_scale);
1149
1150         tmp.flags = ct->proto.tcp.seen[0].flags;
1151         NLA_PUT(skb, CTA_PROTOINFO_TCP_FLAGS_ORIGINAL,
1152                 sizeof(struct nf_ct_tcp_flags), &tmp);
1153
1154         tmp.flags = ct->proto.tcp.seen[1].flags;
1155         NLA_PUT(skb, CTA_PROTOINFO_TCP_FLAGS_REPLY,
1156                 sizeof(struct nf_ct_tcp_flags), &tmp);
1157         spin_unlock_bh(&ct->lock);
1158
1159         nla_nest_end(skb, nest_parms);
1160
1161         return 0;
1162
1163 nla_put_failure:
1164         spin_unlock_bh(&ct->lock);
1165         return -1;
1166 }
1167
1168 static const struct nla_policy tcp_nla_policy[CTA_PROTOINFO_TCP_MAX+1] = {
1169         [CTA_PROTOINFO_TCP_STATE]           = { .type = NLA_U8 },
1170         [CTA_PROTOINFO_TCP_WSCALE_ORIGINAL] = { .type = NLA_U8 },
1171         [CTA_PROTOINFO_TCP_WSCALE_REPLY]    = { .type = NLA_U8 },
1172         [CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]  = { .len = sizeof(struct nf_ct_tcp_flags) },
1173         [CTA_PROTOINFO_TCP_FLAGS_REPLY]     = { .len =  sizeof(struct nf_ct_tcp_flags) },
1174 };
1175
1176 static int nlattr_to_tcp(struct nlattr *cda[], struct nf_conn *ct)
1177 {
1178         struct nlattr *pattr = cda[CTA_PROTOINFO_TCP];
1179         struct nlattr *tb[CTA_PROTOINFO_TCP_MAX+1];
1180         int err;
1181
1182         /* updates could not contain anything about the private
1183          * protocol info, in that case skip the parsing */
1184         if (!pattr)
1185                 return 0;
1186
1187         err = nla_parse_nested(tb, CTA_PROTOINFO_TCP_MAX, pattr, tcp_nla_policy);
1188         if (err < 0)
1189                 return err;
1190
1191         if (tb[CTA_PROTOINFO_TCP_STATE] &&
1192             nla_get_u8(tb[CTA_PROTOINFO_TCP_STATE]) >= TCP_CONNTRACK_MAX)
1193                 return -EINVAL;
1194
1195         spin_lock_bh(&ct->lock);
1196         if (tb[CTA_PROTOINFO_TCP_STATE])
1197                 ct->proto.tcp.state = nla_get_u8(tb[CTA_PROTOINFO_TCP_STATE]);
1198
1199         if (tb[CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]) {
1200                 struct nf_ct_tcp_flags *attr =
1201                         nla_data(tb[CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]);
1202                 ct->proto.tcp.seen[0].flags &= ~attr->mask;
1203                 ct->proto.tcp.seen[0].flags |= attr->flags & attr->mask;
1204         }
1205
1206         if (tb[CTA_PROTOINFO_TCP_FLAGS_REPLY]) {
1207                 struct nf_ct_tcp_flags *attr =
1208                         nla_data(tb[CTA_PROTOINFO_TCP_FLAGS_REPLY]);
1209                 ct->proto.tcp.seen[1].flags &= ~attr->mask;
1210                 ct->proto.tcp.seen[1].flags |= attr->flags & attr->mask;
1211         }
1212
1213         if (tb[CTA_PROTOINFO_TCP_WSCALE_ORIGINAL] &&
1214             tb[CTA_PROTOINFO_TCP_WSCALE_REPLY] &&
1215             ct->proto.tcp.seen[0].flags & IP_CT_TCP_FLAG_WINDOW_SCALE &&
1216             ct->proto.tcp.seen[1].flags & IP_CT_TCP_FLAG_WINDOW_SCALE) {
1217                 ct->proto.tcp.seen[0].td_scale =
1218                         nla_get_u8(tb[CTA_PROTOINFO_TCP_WSCALE_ORIGINAL]);
1219                 ct->proto.tcp.seen[1].td_scale =
1220                         nla_get_u8(tb[CTA_PROTOINFO_TCP_WSCALE_REPLY]);
1221         }
1222         spin_unlock_bh(&ct->lock);
1223
1224         return 0;
1225 }
1226
1227 static int tcp_nlattr_size(void)
1228 {
1229         return nla_total_size(0)           /* CTA_PROTOINFO_TCP */
1230                 + nla_policy_len(tcp_nla_policy, CTA_PROTOINFO_TCP_MAX + 1);
1231 }
1232
1233 static int tcp_nlattr_tuple_size(void)
1234 {
1235         return nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1236 }
1237 #endif
1238
1239 #ifdef CONFIG_SYSCTL
1240 static unsigned int tcp_sysctl_table_users;
1241 static struct ctl_table_header *tcp_sysctl_header;
1242 static struct ctl_table tcp_sysctl_table[] = {
1243         {
1244                 .procname       = "nf_conntrack_tcp_timeout_syn_sent",
1245                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT],
1246                 .maxlen         = sizeof(unsigned int),
1247                 .mode           = 0644,
1248                 .proc_handler   = proc_dointvec_jiffies,
1249         },
1250         {
1251                 .procname       = "nf_conntrack_tcp_timeout_syn_recv",
1252                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_RECV],
1253                 .maxlen         = sizeof(unsigned int),
1254                 .mode           = 0644,
1255                 .proc_handler   = proc_dointvec_jiffies,
1256         },
1257         {
1258                 .procname       = "nf_conntrack_tcp_timeout_established",
1259                 .data           = &tcp_timeouts[TCP_CONNTRACK_ESTABLISHED],
1260                 .maxlen         = sizeof(unsigned int),
1261                 .mode           = 0644,
1262                 .proc_handler   = proc_dointvec_jiffies,
1263         },
1264         {
1265                 .procname       = "nf_conntrack_tcp_timeout_fin_wait",
1266                 .data           = &tcp_timeouts[TCP_CONNTRACK_FIN_WAIT],
1267                 .maxlen         = sizeof(unsigned int),
1268                 .mode           = 0644,
1269                 .proc_handler   = proc_dointvec_jiffies,
1270         },
1271         {
1272                 .procname       = "nf_conntrack_tcp_timeout_close_wait",
1273                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE_WAIT],
1274                 .maxlen         = sizeof(unsigned int),
1275                 .mode           = 0644,
1276                 .proc_handler   = proc_dointvec_jiffies,
1277         },
1278         {
1279                 .procname       = "nf_conntrack_tcp_timeout_last_ack",
1280                 .data           = &tcp_timeouts[TCP_CONNTRACK_LAST_ACK],
1281                 .maxlen         = sizeof(unsigned int),
1282                 .mode           = 0644,
1283                 .proc_handler   = proc_dointvec_jiffies,
1284         },
1285         {
1286                 .procname       = "nf_conntrack_tcp_timeout_time_wait",
1287                 .data           = &tcp_timeouts[TCP_CONNTRACK_TIME_WAIT],
1288                 .maxlen         = sizeof(unsigned int),
1289                 .mode           = 0644,
1290                 .proc_handler   = proc_dointvec_jiffies,
1291         },
1292         {
1293                 .procname       = "nf_conntrack_tcp_timeout_close",
1294                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE],
1295                 .maxlen         = sizeof(unsigned int),
1296                 .mode           = 0644,
1297                 .proc_handler   = proc_dointvec_jiffies,
1298         },
1299         {
1300                 .procname       = "nf_conntrack_tcp_timeout_max_retrans",
1301                 .data           = &nf_ct_tcp_timeout_max_retrans,
1302                 .maxlen         = sizeof(unsigned int),
1303                 .mode           = 0644,
1304                 .proc_handler   = proc_dointvec_jiffies,
1305         },
1306         {
1307                 .procname       = "nf_conntrack_tcp_timeout_unacknowledged",
1308                 .data           = &nf_ct_tcp_timeout_unacknowledged,
1309                 .maxlen         = sizeof(unsigned int),
1310                 .mode           = 0644,
1311                 .proc_handler   = proc_dointvec_jiffies,
1312         },
1313         {
1314                 .procname       = "nf_conntrack_tcp_loose",
1315                 .data           = &nf_ct_tcp_loose,
1316                 .maxlen         = sizeof(unsigned int),
1317                 .mode           = 0644,
1318                 .proc_handler   = proc_dointvec,
1319         },
1320         {
1321                 .procname       = "nf_conntrack_tcp_be_liberal",
1322                 .data           = &nf_ct_tcp_be_liberal,
1323                 .maxlen         = sizeof(unsigned int),
1324                 .mode           = 0644,
1325                 .proc_handler   = proc_dointvec,
1326         },
1327         {
1328                 .procname       = "nf_conntrack_tcp_max_retrans",
1329                 .data           = &nf_ct_tcp_max_retrans,
1330                 .maxlen         = sizeof(unsigned int),
1331                 .mode           = 0644,
1332                 .proc_handler   = proc_dointvec,
1333         },
1334         { }
1335 };
1336
1337 #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
1338 static struct ctl_table tcp_compat_sysctl_table[] = {
1339         {
1340                 .procname       = "ip_conntrack_tcp_timeout_syn_sent",
1341                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT],
1342                 .maxlen         = sizeof(unsigned int),
1343                 .mode           = 0644,
1344                 .proc_handler   = proc_dointvec_jiffies,
1345         },
1346         {
1347                 .procname       = "ip_conntrack_tcp_timeout_syn_sent2",
1348                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT2],
1349                 .maxlen         = sizeof(unsigned int),
1350                 .mode           = 0644,
1351                 .proc_handler   = proc_dointvec_jiffies,
1352         },
1353         {
1354                 .procname       = "ip_conntrack_tcp_timeout_syn_recv",
1355                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_RECV],
1356                 .maxlen         = sizeof(unsigned int),
1357                 .mode           = 0644,
1358                 .proc_handler   = proc_dointvec_jiffies,
1359         },
1360         {
1361                 .procname       = "ip_conntrack_tcp_timeout_established",
1362                 .data           = &tcp_timeouts[TCP_CONNTRACK_ESTABLISHED],
1363                 .maxlen         = sizeof(unsigned int),
1364                 .mode           = 0644,
1365                 .proc_handler   = proc_dointvec_jiffies,
1366         },
1367         {
1368                 .procname       = "ip_conntrack_tcp_timeout_fin_wait",
1369                 .data           = &tcp_timeouts[TCP_CONNTRACK_FIN_WAIT],
1370                 .maxlen         = sizeof(unsigned int),
1371                 .mode           = 0644,
1372                 .proc_handler   = proc_dointvec_jiffies,
1373         },
1374         {
1375                 .procname       = "ip_conntrack_tcp_timeout_close_wait",
1376                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE_WAIT],
1377                 .maxlen         = sizeof(unsigned int),
1378                 .mode           = 0644,
1379                 .proc_handler   = proc_dointvec_jiffies,
1380         },
1381         {
1382                 .procname       = "ip_conntrack_tcp_timeout_last_ack",
1383                 .data           = &tcp_timeouts[TCP_CONNTRACK_LAST_ACK],
1384                 .maxlen         = sizeof(unsigned int),
1385                 .mode           = 0644,
1386                 .proc_handler   = proc_dointvec_jiffies,
1387         },
1388         {
1389                 .procname       = "ip_conntrack_tcp_timeout_time_wait",
1390                 .data           = &tcp_timeouts[TCP_CONNTRACK_TIME_WAIT],
1391                 .maxlen         = sizeof(unsigned int),
1392                 .mode           = 0644,
1393                 .proc_handler   = proc_dointvec_jiffies,
1394         },
1395         {
1396                 .procname       = "ip_conntrack_tcp_timeout_close",
1397                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE],
1398                 .maxlen         = sizeof(unsigned int),
1399                 .mode           = 0644,
1400                 .proc_handler   = proc_dointvec_jiffies,
1401         },
1402         {
1403                 .procname       = "ip_conntrack_tcp_timeout_max_retrans",
1404                 .data           = &nf_ct_tcp_timeout_max_retrans,
1405                 .maxlen         = sizeof(unsigned int),
1406                 .mode           = 0644,
1407                 .proc_handler   = proc_dointvec_jiffies,
1408         },
1409         {
1410                 .procname       = "ip_conntrack_tcp_loose",
1411                 .data           = &nf_ct_tcp_loose,
1412                 .maxlen         = sizeof(unsigned int),
1413                 .mode           = 0644,
1414                 .proc_handler   = proc_dointvec,
1415         },
1416         {
1417                 .procname       = "ip_conntrack_tcp_be_liberal",
1418                 .data           = &nf_ct_tcp_be_liberal,
1419                 .maxlen         = sizeof(unsigned int),
1420                 .mode           = 0644,
1421                 .proc_handler   = proc_dointvec,
1422         },
1423         {
1424                 .procname       = "ip_conntrack_tcp_max_retrans",
1425                 .data           = &nf_ct_tcp_max_retrans,
1426                 .maxlen         = sizeof(unsigned int),
1427                 .mode           = 0644,
1428                 .proc_handler   = proc_dointvec,
1429         },
1430         { }
1431 };
1432 #endif /* CONFIG_NF_CONNTRACK_PROC_COMPAT */
1433 #endif /* CONFIG_SYSCTL */
1434
1435 struct nf_conntrack_l4proto nf_conntrack_l4proto_tcp4 __read_mostly =
1436 {
1437         .l3proto                = PF_INET,
1438         .l4proto                = IPPROTO_TCP,
1439         .name                   = "tcp",
1440         .pkt_to_tuple           = tcp_pkt_to_tuple,
1441         .invert_tuple           = tcp_invert_tuple,
1442         .print_tuple            = tcp_print_tuple,
1443         .print_conntrack        = tcp_print_conntrack,
1444         .packet                 = tcp_packet,
1445         .new                    = tcp_new,
1446         .error                  = tcp_error,
1447 #if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
1448         .to_nlattr              = tcp_to_nlattr,
1449         .nlattr_size            = tcp_nlattr_size,
1450         .from_nlattr            = nlattr_to_tcp,
1451         .tuple_to_nlattr        = nf_ct_port_tuple_to_nlattr,
1452         .nlattr_to_tuple        = nf_ct_port_nlattr_to_tuple,
1453         .nlattr_tuple_size      = tcp_nlattr_tuple_size,
1454         .nla_policy             = nf_ct_port_nla_policy,
1455 #endif
1456 #ifdef CONFIG_SYSCTL
1457         .ctl_table_users        = &tcp_sysctl_table_users,
1458         .ctl_table_header       = &tcp_sysctl_header,
1459         .ctl_table              = tcp_sysctl_table,
1460 #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
1461         .ctl_compat_table       = tcp_compat_sysctl_table,
1462 #endif
1463 #endif
1464 };
1465 EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_tcp4);
1466
1467 struct nf_conntrack_l4proto nf_conntrack_l4proto_tcp6 __read_mostly =
1468 {
1469         .l3proto                = PF_INET6,
1470         .l4proto                = IPPROTO_TCP,
1471         .name                   = "tcp",
1472         .pkt_to_tuple           = tcp_pkt_to_tuple,
1473         .invert_tuple           = tcp_invert_tuple,
1474         .print_tuple            = tcp_print_tuple,
1475         .print_conntrack        = tcp_print_conntrack,
1476         .packet                 = tcp_packet,
1477         .new                    = tcp_new,
1478         .error                  = tcp_error,
1479 #if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
1480         .to_nlattr              = tcp_to_nlattr,
1481         .nlattr_size            = tcp_nlattr_size,
1482         .from_nlattr            = nlattr_to_tcp,
1483         .tuple_to_nlattr        = nf_ct_port_tuple_to_nlattr,
1484         .nlattr_to_tuple        = nf_ct_port_nlattr_to_tuple,
1485         .nlattr_tuple_size      = tcp_nlattr_tuple_size,
1486         .nla_policy             = nf_ct_port_nla_policy,
1487 #endif
1488 #ifdef CONFIG_SYSCTL
1489         .ctl_table_users        = &tcp_sysctl_table_users,
1490         .ctl_table_header       = &tcp_sysctl_header,
1491         .ctl_table              = tcp_sysctl_table,
1492 #endif
1493 };
1494 EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_tcp6);