mac80211: don't compare TKIP TX MIC key in reinstall prevention
[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 (tcph->rst && seq == 0 && state->state == TCP_CONNTRACK_SYN_SENT)
629                 /*
630                  * RST sent answering SYN.
631                  */
632                 seq = end = sender->td_end;
633
634         pr_debug("tcp_in_window: ");
635         nf_ct_dump_tuple(tuple);
636         pr_debug("seq=%u ack=%u+(%d) sack=%u+(%d) win=%u end=%u\n",
637                  seq, ack, receiver_offset, sack, receiver_offset, win, end);
638         pr_debug("tcp_in_window: sender end=%u maxend=%u maxwin=%u scale=%i "
639                  "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
640                  sender->td_end, sender->td_maxend, sender->td_maxwin,
641                  sender->td_scale,
642                  receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
643                  receiver->td_scale);
644
645         pr_debug("tcp_in_window: I=%i II=%i III=%i IV=%i\n",
646                  before(seq, sender->td_maxend + 1),
647                  after(end, sender->td_end - receiver->td_maxwin - 1),
648                  before(sack, receiver->td_end + 1),
649                  after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1));
650
651         if (before(seq, sender->td_maxend + 1) &&
652             after(end, sender->td_end - receiver->td_maxwin - 1) &&
653             before(sack, receiver->td_end + 1) &&
654             after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1)) {
655                 /*
656                  * Take into account window scaling (RFC 1323).
657                  */
658                 if (!tcph->syn)
659                         win <<= sender->td_scale;
660
661                 /*
662                  * Update sender data.
663                  */
664                 swin = win + (sack - ack);
665                 if (sender->td_maxwin < swin)
666                         sender->td_maxwin = swin;
667                 if (after(end, sender->td_end)) {
668                         sender->td_end = end;
669                         sender->flags |= IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED;
670                 }
671                 if (tcph->ack) {
672                         if (!(sender->flags & IP_CT_TCP_FLAG_MAXACK_SET)) {
673                                 sender->td_maxack = ack;
674                                 sender->flags |= IP_CT_TCP_FLAG_MAXACK_SET;
675                         } else if (after(ack, sender->td_maxack))
676                                 sender->td_maxack = ack;
677                 }
678
679                 /*
680                  * Update receiver data.
681                  */
682                 if (receiver->td_maxwin != 0 && after(end, sender->td_maxend))
683                         receiver->td_maxwin += end - sender->td_maxend;
684                 if (after(sack + win, receiver->td_maxend - 1)) {
685                         receiver->td_maxend = sack + win;
686                         if (win == 0)
687                                 receiver->td_maxend++;
688                 }
689                 if (ack == receiver->td_end)
690                         receiver->flags &= ~IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED;
691
692                 /*
693                  * Check retransmissions.
694                  */
695                 if (index == TCP_ACK_SET) {
696                         if (state->last_dir == dir
697                             && state->last_seq == seq
698                             && state->last_ack == ack
699                             && state->last_end == end
700                             && state->last_win == win)
701                                 state->retrans++;
702                         else {
703                                 state->last_dir = dir;
704                                 state->last_seq = seq;
705                                 state->last_ack = ack;
706                                 state->last_end = end;
707                                 state->last_win = win;
708                                 state->retrans = 0;
709                         }
710                 }
711                 res = true;
712         } else {
713                 res = false;
714                 if (sender->flags & IP_CT_TCP_FLAG_BE_LIBERAL ||
715                     nf_ct_tcp_be_liberal)
716                         res = true;
717                 if (!res && LOG_INVALID(net, IPPROTO_TCP))
718                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
719                         "nf_ct_tcp: %s ",
720                         before(seq, sender->td_maxend + 1) ?
721                         after(end, sender->td_end - receiver->td_maxwin - 1) ?
722                         before(sack, receiver->td_end + 1) ?
723                         after(sack, receiver->td_end - MAXACKWINDOW(sender) - 1) ? "BUG"
724                         : "ACK is under the lower bound (possible overly delayed ACK)"
725                         : "ACK is over the upper bound (ACKed data not seen yet)"
726                         : "SEQ is under the lower bound (already ACKed data retransmitted)"
727                         : "SEQ is over the upper bound (over the window of the receiver)");
728         }
729
730         pr_debug("tcp_in_window: res=%u sender end=%u maxend=%u maxwin=%u "
731                  "receiver end=%u maxend=%u maxwin=%u\n",
732                  res, sender->td_end, sender->td_maxend, sender->td_maxwin,
733                  receiver->td_end, receiver->td_maxend, receiver->td_maxwin);
734
735         return res;
736 }
737
738 /* table of valid flag combinations - PUSH, ECE and CWR are always valid */
739 static const u8 tcp_valid_flags[(TCPHDR_FIN|TCPHDR_SYN|TCPHDR_RST|TCPHDR_ACK|
740                                  TCPHDR_URG) + 1] =
741 {
742         [TCPHDR_SYN]                            = 1,
743         [TCPHDR_SYN|TCPHDR_URG]                 = 1,
744         [TCPHDR_SYN|TCPHDR_ACK]                 = 1,
745         [TCPHDR_RST]                            = 1,
746         [TCPHDR_RST|TCPHDR_ACK]                 = 1,
747         [TCPHDR_FIN|TCPHDR_ACK]                 = 1,
748         [TCPHDR_FIN|TCPHDR_ACK|TCPHDR_URG]      = 1,
749         [TCPHDR_ACK]                            = 1,
750         [TCPHDR_ACK|TCPHDR_URG]                 = 1,
751 };
752
753 /* Protect conntrack agaist broken packets. Code taken from ipt_unclean.c.  */
754 static int tcp_error(struct net *net, struct nf_conn *tmpl,
755                      struct sk_buff *skb,
756                      unsigned int dataoff,
757                      enum ip_conntrack_info *ctinfo,
758                      u_int8_t pf,
759                      unsigned int hooknum)
760 {
761         const struct tcphdr *th;
762         struct tcphdr _tcph;
763         unsigned int tcplen = skb->len - dataoff;
764         u_int8_t tcpflags;
765
766         /* Smaller that minimal TCP header? */
767         th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
768         if (th == NULL) {
769                 if (LOG_INVALID(net, IPPROTO_TCP))
770                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
771                                 "nf_ct_tcp: short packet ");
772                 return -NF_ACCEPT;
773         }
774
775         /* Not whole TCP header or malformed packet */
776         if (th->doff*4 < sizeof(struct tcphdr) || tcplen < th->doff*4) {
777                 if (LOG_INVALID(net, IPPROTO_TCP))
778                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
779                                 "nf_ct_tcp: truncated/malformed packet ");
780                 return -NF_ACCEPT;
781         }
782
783         /* Checksum invalid? Ignore.
784          * We skip checking packets on the outgoing path
785          * because the checksum is assumed to be correct.
786          */
787         /* FIXME: Source route IP option packets --RR */
788         if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING &&
789             nf_checksum(skb, hooknum, dataoff, IPPROTO_TCP, pf)) {
790                 if (LOG_INVALID(net, IPPROTO_TCP))
791                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
792                                   "nf_ct_tcp: bad TCP checksum ");
793                 return -NF_ACCEPT;
794         }
795
796         /* Check TCP flags. */
797         tcpflags = (tcp_flag_byte(th) & ~(TCPHDR_ECE|TCPHDR_CWR|TCPHDR_PSH));
798         if (!tcp_valid_flags[tcpflags]) {
799                 if (LOG_INVALID(net, IPPROTO_TCP))
800                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
801                                   "nf_ct_tcp: invalid TCP flag combination ");
802                 return -NF_ACCEPT;
803         }
804
805         return NF_ACCEPT;
806 }
807
808 /* Returns verdict for packet, or -1 for invalid. */
809 static int tcp_packet(struct nf_conn *ct,
810                       const struct sk_buff *skb,
811                       unsigned int dataoff,
812                       enum ip_conntrack_info ctinfo,
813                       u_int8_t pf,
814                       unsigned int hooknum)
815 {
816         struct net *net = nf_ct_net(ct);
817         struct nf_conntrack_tuple *tuple;
818         enum tcp_conntrack new_state, old_state;
819         enum ip_conntrack_dir dir;
820         const struct tcphdr *th;
821         struct tcphdr _tcph;
822         unsigned long timeout;
823         unsigned int index;
824
825         th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
826         BUG_ON(th == NULL);
827
828         spin_lock_bh(&ct->lock);
829         old_state = ct->proto.tcp.state;
830         dir = CTINFO2DIR(ctinfo);
831         index = get_conntrack_index(th);
832         new_state = tcp_conntracks[dir][index][old_state];
833         tuple = &ct->tuplehash[dir].tuple;
834
835         switch (new_state) {
836         case TCP_CONNTRACK_SYN_SENT:
837                 if (old_state < TCP_CONNTRACK_TIME_WAIT)
838                         break;
839                 /* RFC 1122: "When a connection is closed actively,
840                  * it MUST linger in TIME-WAIT state for a time 2xMSL
841                  * (Maximum Segment Lifetime). However, it MAY accept
842                  * a new SYN from the remote TCP to reopen the connection
843                  * directly from TIME-WAIT state, if..."
844                  * We ignore the conditions because we are in the
845                  * TIME-WAIT state anyway.
846                  *
847                  * Handle aborted connections: we and the server
848                  * think there is an existing connection but the client
849                  * aborts it and starts a new one.
850                  */
851                 if (((ct->proto.tcp.seen[dir].flags
852                       | ct->proto.tcp.seen[!dir].flags)
853                      & IP_CT_TCP_FLAG_CLOSE_INIT)
854                     || (ct->proto.tcp.last_dir == dir
855                         && ct->proto.tcp.last_index == TCP_RST_SET)) {
856                         /* Attempt to reopen a closed/aborted connection.
857                          * Delete this connection and look up again. */
858                         spin_unlock_bh(&ct->lock);
859
860                         /* Only repeat if we can actually remove the timer.
861                          * Destruction may already be in progress in process
862                          * context and we must give it a chance to terminate.
863                          */
864                         if (nf_ct_kill(ct))
865                                 return -NF_REPEAT;
866                         return NF_DROP;
867                 }
868                 /* Fall through */
869         case TCP_CONNTRACK_IGNORE:
870                 /* Ignored packets:
871                  *
872                  * Our connection entry may be out of sync, so ignore
873                  * packets which may signal the real connection between
874                  * the client and the server.
875                  *
876                  * a) SYN in ORIGINAL
877                  * b) SYN/ACK in REPLY
878                  * c) ACK in reply direction after initial SYN in original.
879                  *
880                  * If the ignored packet is invalid, the receiver will send
881                  * a RST we'll catch below.
882                  */
883                 if (index == TCP_SYNACK_SET
884                     && ct->proto.tcp.last_index == TCP_SYN_SET
885                     && ct->proto.tcp.last_dir != dir
886                     && ntohl(th->ack_seq) == ct->proto.tcp.last_end) {
887                         /* b) This SYN/ACK acknowledges a SYN that we earlier
888                          * ignored as invalid. This means that the client and
889                          * the server are both in sync, while the firewall is
890                          * not. We get in sync from the previously annotated
891                          * values.
892                          */
893                         old_state = TCP_CONNTRACK_SYN_SENT;
894                         new_state = TCP_CONNTRACK_SYN_RECV;
895                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_end =
896                                 ct->proto.tcp.last_end;
897                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_maxend =
898                                 ct->proto.tcp.last_end;
899                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_maxwin =
900                                 ct->proto.tcp.last_win == 0 ?
901                                         1 : ct->proto.tcp.last_win;
902                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].td_scale =
903                                 ct->proto.tcp.last_wscale;
904                         ct->proto.tcp.seen[ct->proto.tcp.last_dir].flags =
905                                 ct->proto.tcp.last_flags;
906                         memset(&ct->proto.tcp.seen[dir], 0,
907                                sizeof(struct ip_ct_tcp_state));
908                         break;
909                 }
910                 ct->proto.tcp.last_index = index;
911                 ct->proto.tcp.last_dir = dir;
912                 ct->proto.tcp.last_seq = ntohl(th->seq);
913                 ct->proto.tcp.last_end =
914                     segment_seq_plus_len(ntohl(th->seq), skb->len, dataoff, th);
915                 ct->proto.tcp.last_win = ntohs(th->window);
916
917                 /* a) This is a SYN in ORIGINAL. The client and the server
918                  * may be in sync but we are not. In that case, we annotate
919                  * the TCP options and let the packet go through. If it is a
920                  * valid SYN packet, the server will reply with a SYN/ACK, and
921                  * then we'll get in sync. Otherwise, the server ignores it. */
922                 if (index == TCP_SYN_SET && dir == IP_CT_DIR_ORIGINAL) {
923                         struct ip_ct_tcp_state seen = {};
924
925                         ct->proto.tcp.last_flags =
926                         ct->proto.tcp.last_wscale = 0;
927                         tcp_options(skb, dataoff, th, &seen);
928                         if (seen.flags & IP_CT_TCP_FLAG_WINDOW_SCALE) {
929                                 ct->proto.tcp.last_flags |=
930                                         IP_CT_TCP_FLAG_WINDOW_SCALE;
931                                 ct->proto.tcp.last_wscale = seen.td_scale;
932                         }
933                         if (seen.flags & IP_CT_TCP_FLAG_SACK_PERM) {
934                                 ct->proto.tcp.last_flags |=
935                                         IP_CT_TCP_FLAG_SACK_PERM;
936                         }
937                 }
938                 spin_unlock_bh(&ct->lock);
939                 if (LOG_INVALID(net, IPPROTO_TCP))
940                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
941                                   "nf_ct_tcp: invalid packet ignored ");
942                 return NF_ACCEPT;
943         case TCP_CONNTRACK_MAX:
944                 /* Invalid packet */
945                 pr_debug("nf_ct_tcp: Invalid dir=%i index=%u ostate=%u\n",
946                          dir, get_conntrack_index(th), old_state);
947                 spin_unlock_bh(&ct->lock);
948                 if (LOG_INVALID(net, IPPROTO_TCP))
949                         nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
950                                   "nf_ct_tcp: invalid state ");
951                 return -NF_ACCEPT;
952         case TCP_CONNTRACK_CLOSE:
953                 if (index == TCP_RST_SET
954                     && (ct->proto.tcp.seen[!dir].flags & IP_CT_TCP_FLAG_MAXACK_SET)
955                     && before(ntohl(th->seq), ct->proto.tcp.seen[!dir].td_maxack)) {
956                         /* Invalid RST  */
957                         spin_unlock_bh(&ct->lock);
958                         if (LOG_INVALID(net, IPPROTO_TCP))
959                                 nf_log_packet(pf, 0, skb, NULL, NULL, NULL,
960                                           "nf_ct_tcp: invalid RST ");
961                         return -NF_ACCEPT;
962                 }
963                 if (index == TCP_RST_SET
964                     && ((test_bit(IPS_SEEN_REPLY_BIT, &ct->status)
965                          && ct->proto.tcp.last_index == TCP_SYN_SET)
966                         || (!test_bit(IPS_ASSURED_BIT, &ct->status)
967                             && ct->proto.tcp.last_index == TCP_ACK_SET))
968                     && ntohl(th->ack_seq) == ct->proto.tcp.last_end) {
969                         /* RST sent to invalid SYN or ACK we had let through
970                          * at a) and c) above:
971                          *
972                          * a) SYN was in window then
973                          * c) we hold a half-open connection.
974                          *
975                          * Delete our connection entry.
976                          * We skip window checking, because packet might ACK
977                          * segments we ignored. */
978                         goto in_window;
979                 }
980                 /* Just fall through */
981         default:
982                 /* Keep compilers happy. */
983                 break;
984         }
985
986         if (!tcp_in_window(ct, &ct->proto.tcp, dir, index,
987                            skb, dataoff, th, pf)) {
988                 spin_unlock_bh(&ct->lock);
989                 return -NF_ACCEPT;
990         }
991      in_window:
992         /* From now on we have got in-window packets */
993         ct->proto.tcp.last_index = index;
994         ct->proto.tcp.last_dir = dir;
995
996         pr_debug("tcp_conntracks: ");
997         nf_ct_dump_tuple(tuple);
998         pr_debug("syn=%i ack=%i fin=%i rst=%i old=%i new=%i\n",
999                  (th->syn ? 1 : 0), (th->ack ? 1 : 0),
1000                  (th->fin ? 1 : 0), (th->rst ? 1 : 0),
1001                  old_state, new_state);
1002
1003         ct->proto.tcp.state = new_state;
1004         if (old_state != new_state
1005             && new_state == TCP_CONNTRACK_FIN_WAIT)
1006                 ct->proto.tcp.seen[dir].flags |= IP_CT_TCP_FLAG_CLOSE_INIT;
1007
1008         if (ct->proto.tcp.retrans >= nf_ct_tcp_max_retrans &&
1009             tcp_timeouts[new_state] > nf_ct_tcp_timeout_max_retrans)
1010                 timeout = nf_ct_tcp_timeout_max_retrans;
1011         else if ((ct->proto.tcp.seen[0].flags | ct->proto.tcp.seen[1].flags) &
1012                  IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED &&
1013                  tcp_timeouts[new_state] > nf_ct_tcp_timeout_unacknowledged)
1014                 timeout = nf_ct_tcp_timeout_unacknowledged;
1015         else
1016                 timeout = tcp_timeouts[new_state];
1017         spin_unlock_bh(&ct->lock);
1018
1019         if (new_state != old_state)
1020                 nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
1021
1022         if (!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1023                 /* If only reply is a RST, we can consider ourselves not to
1024                    have an established connection: this is a fairly common
1025                    problem case, so we can delete the conntrack
1026                    immediately.  --RR */
1027                 if (th->rst) {
1028                         nf_ct_kill_acct(ct, ctinfo, skb);
1029                         return NF_ACCEPT;
1030                 }
1031         } else if (!test_bit(IPS_ASSURED_BIT, &ct->status)
1032                    && (old_state == TCP_CONNTRACK_SYN_RECV
1033                        || old_state == TCP_CONNTRACK_ESTABLISHED)
1034                    && new_state == TCP_CONNTRACK_ESTABLISHED) {
1035                 /* Set ASSURED if we see see valid ack in ESTABLISHED
1036                    after SYN_RECV or a valid answer for a picked up
1037                    connection. */
1038                 set_bit(IPS_ASSURED_BIT, &ct->status);
1039                 nf_conntrack_event_cache(IPCT_ASSURED, ct);
1040         }
1041         nf_ct_refresh_acct(ct, ctinfo, skb, timeout);
1042
1043         return NF_ACCEPT;
1044 }
1045
1046 /* Called when a new connection for this protocol found. */
1047 static bool tcp_new(struct nf_conn *ct, const struct sk_buff *skb,
1048                     unsigned int dataoff)
1049 {
1050         enum tcp_conntrack new_state;
1051         const struct tcphdr *th;
1052         struct tcphdr _tcph;
1053         const struct ip_ct_tcp_state *sender = &ct->proto.tcp.seen[0];
1054         const struct ip_ct_tcp_state *receiver = &ct->proto.tcp.seen[1];
1055
1056         th = skb_header_pointer(skb, dataoff, sizeof(_tcph), &_tcph);
1057         BUG_ON(th == NULL);
1058
1059         /* Don't need lock here: this conntrack not in circulation yet */
1060         new_state = tcp_conntracks[0][get_conntrack_index(th)][TCP_CONNTRACK_NONE];
1061
1062         /* Invalid: delete conntrack */
1063         if (new_state >= TCP_CONNTRACK_MAX) {
1064                 pr_debug("nf_ct_tcp: invalid new deleting.\n");
1065                 return false;
1066         }
1067
1068         if (new_state == TCP_CONNTRACK_SYN_SENT) {
1069                 memset(&ct->proto.tcp, 0, sizeof(ct->proto.tcp));
1070                 /* SYN packet */
1071                 ct->proto.tcp.seen[0].td_end =
1072                         segment_seq_plus_len(ntohl(th->seq), skb->len,
1073                                              dataoff, th);
1074                 ct->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
1075                 if (ct->proto.tcp.seen[0].td_maxwin == 0)
1076                         ct->proto.tcp.seen[0].td_maxwin = 1;
1077                 ct->proto.tcp.seen[0].td_maxend =
1078                         ct->proto.tcp.seen[0].td_end;
1079
1080                 tcp_options(skb, dataoff, th, &ct->proto.tcp.seen[0]);
1081         } else if (nf_ct_tcp_loose == 0) {
1082                 /* Don't try to pick up connections. */
1083                 return false;
1084         } else {
1085                 memset(&ct->proto.tcp, 0, sizeof(ct->proto.tcp));
1086                 /*
1087                  * We are in the middle of a connection,
1088                  * its history is lost for us.
1089                  * Let's try to use the data from the packet.
1090                  */
1091                 ct->proto.tcp.seen[0].td_end =
1092                         segment_seq_plus_len(ntohl(th->seq), skb->len,
1093                                              dataoff, th);
1094                 ct->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
1095                 if (ct->proto.tcp.seen[0].td_maxwin == 0)
1096                         ct->proto.tcp.seen[0].td_maxwin = 1;
1097                 ct->proto.tcp.seen[0].td_maxend =
1098                         ct->proto.tcp.seen[0].td_end +
1099                         ct->proto.tcp.seen[0].td_maxwin;
1100
1101                 /* We assume SACK and liberal window checking to handle
1102                  * window scaling */
1103                 ct->proto.tcp.seen[0].flags =
1104                 ct->proto.tcp.seen[1].flags = IP_CT_TCP_FLAG_SACK_PERM |
1105                                               IP_CT_TCP_FLAG_BE_LIBERAL;
1106         }
1107
1108         /* tcp_packet will set them */
1109         ct->proto.tcp.last_index = TCP_NONE_SET;
1110
1111         pr_debug("tcp_new: sender end=%u maxend=%u maxwin=%u scale=%i "
1112                  "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
1113                  sender->td_end, sender->td_maxend, sender->td_maxwin,
1114                  sender->td_scale,
1115                  receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
1116                  receiver->td_scale);
1117         return true;
1118 }
1119
1120 #if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
1121
1122 #include <linux/netfilter/nfnetlink.h>
1123 #include <linux/netfilter/nfnetlink_conntrack.h>
1124
1125 static int tcp_to_nlattr(struct sk_buff *skb, struct nlattr *nla,
1126                          struct nf_conn *ct)
1127 {
1128         struct nlattr *nest_parms;
1129         struct nf_ct_tcp_flags tmp = {};
1130
1131         spin_lock_bh(&ct->lock);
1132         nest_parms = nla_nest_start(skb, CTA_PROTOINFO_TCP | NLA_F_NESTED);
1133         if (!nest_parms)
1134                 goto nla_put_failure;
1135
1136         NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_STATE, ct->proto.tcp.state);
1137
1138         NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_WSCALE_ORIGINAL,
1139                    ct->proto.tcp.seen[0].td_scale);
1140
1141         NLA_PUT_U8(skb, CTA_PROTOINFO_TCP_WSCALE_REPLY,
1142                    ct->proto.tcp.seen[1].td_scale);
1143
1144         tmp.flags = ct->proto.tcp.seen[0].flags;
1145         NLA_PUT(skb, CTA_PROTOINFO_TCP_FLAGS_ORIGINAL,
1146                 sizeof(struct nf_ct_tcp_flags), &tmp);
1147
1148         tmp.flags = ct->proto.tcp.seen[1].flags;
1149         NLA_PUT(skb, CTA_PROTOINFO_TCP_FLAGS_REPLY,
1150                 sizeof(struct nf_ct_tcp_flags), &tmp);
1151         spin_unlock_bh(&ct->lock);
1152
1153         nla_nest_end(skb, nest_parms);
1154
1155         return 0;
1156
1157 nla_put_failure:
1158         spin_unlock_bh(&ct->lock);
1159         return -1;
1160 }
1161
1162 static const struct nla_policy tcp_nla_policy[CTA_PROTOINFO_TCP_MAX+1] = {
1163         [CTA_PROTOINFO_TCP_STATE]           = { .type = NLA_U8 },
1164         [CTA_PROTOINFO_TCP_WSCALE_ORIGINAL] = { .type = NLA_U8 },
1165         [CTA_PROTOINFO_TCP_WSCALE_REPLY]    = { .type = NLA_U8 },
1166         [CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]  = { .len = sizeof(struct nf_ct_tcp_flags) },
1167         [CTA_PROTOINFO_TCP_FLAGS_REPLY]     = { .len =  sizeof(struct nf_ct_tcp_flags) },
1168 };
1169
1170 static int nlattr_to_tcp(struct nlattr *cda[], struct nf_conn *ct)
1171 {
1172         struct nlattr *pattr = cda[CTA_PROTOINFO_TCP];
1173         struct nlattr *tb[CTA_PROTOINFO_TCP_MAX+1];
1174         int err;
1175
1176         /* updates could not contain anything about the private
1177          * protocol info, in that case skip the parsing */
1178         if (!pattr)
1179                 return 0;
1180
1181         err = nla_parse_nested(tb, CTA_PROTOINFO_TCP_MAX, pattr, tcp_nla_policy);
1182         if (err < 0)
1183                 return err;
1184
1185         if (tb[CTA_PROTOINFO_TCP_STATE] &&
1186             nla_get_u8(tb[CTA_PROTOINFO_TCP_STATE]) >= TCP_CONNTRACK_MAX)
1187                 return -EINVAL;
1188
1189         spin_lock_bh(&ct->lock);
1190         if (tb[CTA_PROTOINFO_TCP_STATE])
1191                 ct->proto.tcp.state = nla_get_u8(tb[CTA_PROTOINFO_TCP_STATE]);
1192
1193         if (tb[CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]) {
1194                 struct nf_ct_tcp_flags *attr =
1195                         nla_data(tb[CTA_PROTOINFO_TCP_FLAGS_ORIGINAL]);
1196                 ct->proto.tcp.seen[0].flags &= ~attr->mask;
1197                 ct->proto.tcp.seen[0].flags |= attr->flags & attr->mask;
1198         }
1199
1200         if (tb[CTA_PROTOINFO_TCP_FLAGS_REPLY]) {
1201                 struct nf_ct_tcp_flags *attr =
1202                         nla_data(tb[CTA_PROTOINFO_TCP_FLAGS_REPLY]);
1203                 ct->proto.tcp.seen[1].flags &= ~attr->mask;
1204                 ct->proto.tcp.seen[1].flags |= attr->flags & attr->mask;
1205         }
1206
1207         if (tb[CTA_PROTOINFO_TCP_WSCALE_ORIGINAL] &&
1208             tb[CTA_PROTOINFO_TCP_WSCALE_REPLY] &&
1209             ct->proto.tcp.seen[0].flags & IP_CT_TCP_FLAG_WINDOW_SCALE &&
1210             ct->proto.tcp.seen[1].flags & IP_CT_TCP_FLAG_WINDOW_SCALE) {
1211                 ct->proto.tcp.seen[0].td_scale =
1212                         nla_get_u8(tb[CTA_PROTOINFO_TCP_WSCALE_ORIGINAL]);
1213                 ct->proto.tcp.seen[1].td_scale =
1214                         nla_get_u8(tb[CTA_PROTOINFO_TCP_WSCALE_REPLY]);
1215         }
1216         spin_unlock_bh(&ct->lock);
1217
1218         return 0;
1219 }
1220
1221 static int tcp_nlattr_size(void)
1222 {
1223         return nla_total_size(0)           /* CTA_PROTOINFO_TCP */
1224                 + nla_policy_len(tcp_nla_policy, CTA_PROTOINFO_TCP_MAX + 1);
1225 }
1226
1227 static int tcp_nlattr_tuple_size(void)
1228 {
1229         return nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1230 }
1231 #endif
1232
1233 #ifdef CONFIG_SYSCTL
1234 static unsigned int tcp_sysctl_table_users;
1235 static struct ctl_table_header *tcp_sysctl_header;
1236 static struct ctl_table tcp_sysctl_table[] = {
1237         {
1238                 .procname       = "nf_conntrack_tcp_timeout_syn_sent",
1239                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT],
1240                 .maxlen         = sizeof(unsigned int),
1241                 .mode           = 0644,
1242                 .proc_handler   = proc_dointvec_jiffies,
1243         },
1244         {
1245                 .procname       = "nf_conntrack_tcp_timeout_syn_recv",
1246                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_RECV],
1247                 .maxlen         = sizeof(unsigned int),
1248                 .mode           = 0644,
1249                 .proc_handler   = proc_dointvec_jiffies,
1250         },
1251         {
1252                 .procname       = "nf_conntrack_tcp_timeout_established",
1253                 .data           = &tcp_timeouts[TCP_CONNTRACK_ESTABLISHED],
1254                 .maxlen         = sizeof(unsigned int),
1255                 .mode           = 0644,
1256                 .proc_handler   = proc_dointvec_jiffies,
1257         },
1258         {
1259                 .procname       = "nf_conntrack_tcp_timeout_fin_wait",
1260                 .data           = &tcp_timeouts[TCP_CONNTRACK_FIN_WAIT],
1261                 .maxlen         = sizeof(unsigned int),
1262                 .mode           = 0644,
1263                 .proc_handler   = proc_dointvec_jiffies,
1264         },
1265         {
1266                 .procname       = "nf_conntrack_tcp_timeout_close_wait",
1267                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE_WAIT],
1268                 .maxlen         = sizeof(unsigned int),
1269                 .mode           = 0644,
1270                 .proc_handler   = proc_dointvec_jiffies,
1271         },
1272         {
1273                 .procname       = "nf_conntrack_tcp_timeout_last_ack",
1274                 .data           = &tcp_timeouts[TCP_CONNTRACK_LAST_ACK],
1275                 .maxlen         = sizeof(unsigned int),
1276                 .mode           = 0644,
1277                 .proc_handler   = proc_dointvec_jiffies,
1278         },
1279         {
1280                 .procname       = "nf_conntrack_tcp_timeout_time_wait",
1281                 .data           = &tcp_timeouts[TCP_CONNTRACK_TIME_WAIT],
1282                 .maxlen         = sizeof(unsigned int),
1283                 .mode           = 0644,
1284                 .proc_handler   = proc_dointvec_jiffies,
1285         },
1286         {
1287                 .procname       = "nf_conntrack_tcp_timeout_close",
1288                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE],
1289                 .maxlen         = sizeof(unsigned int),
1290                 .mode           = 0644,
1291                 .proc_handler   = proc_dointvec_jiffies,
1292         },
1293         {
1294                 .procname       = "nf_conntrack_tcp_timeout_max_retrans",
1295                 .data           = &nf_ct_tcp_timeout_max_retrans,
1296                 .maxlen         = sizeof(unsigned int),
1297                 .mode           = 0644,
1298                 .proc_handler   = proc_dointvec_jiffies,
1299         },
1300         {
1301                 .procname       = "nf_conntrack_tcp_timeout_unacknowledged",
1302                 .data           = &nf_ct_tcp_timeout_unacknowledged,
1303                 .maxlen         = sizeof(unsigned int),
1304                 .mode           = 0644,
1305                 .proc_handler   = proc_dointvec_jiffies,
1306         },
1307         {
1308                 .procname       = "nf_conntrack_tcp_loose",
1309                 .data           = &nf_ct_tcp_loose,
1310                 .maxlen         = sizeof(unsigned int),
1311                 .mode           = 0644,
1312                 .proc_handler   = proc_dointvec,
1313         },
1314         {
1315                 .procname       = "nf_conntrack_tcp_be_liberal",
1316                 .data           = &nf_ct_tcp_be_liberal,
1317                 .maxlen         = sizeof(unsigned int),
1318                 .mode           = 0644,
1319                 .proc_handler   = proc_dointvec,
1320         },
1321         {
1322                 .procname       = "nf_conntrack_tcp_max_retrans",
1323                 .data           = &nf_ct_tcp_max_retrans,
1324                 .maxlen         = sizeof(unsigned int),
1325                 .mode           = 0644,
1326                 .proc_handler   = proc_dointvec,
1327         },
1328         { }
1329 };
1330
1331 #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
1332 static struct ctl_table tcp_compat_sysctl_table[] = {
1333         {
1334                 .procname       = "ip_conntrack_tcp_timeout_syn_sent",
1335                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT],
1336                 .maxlen         = sizeof(unsigned int),
1337                 .mode           = 0644,
1338                 .proc_handler   = proc_dointvec_jiffies,
1339         },
1340         {
1341                 .procname       = "ip_conntrack_tcp_timeout_syn_sent2",
1342                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_SENT2],
1343                 .maxlen         = sizeof(unsigned int),
1344                 .mode           = 0644,
1345                 .proc_handler   = proc_dointvec_jiffies,
1346         },
1347         {
1348                 .procname       = "ip_conntrack_tcp_timeout_syn_recv",
1349                 .data           = &tcp_timeouts[TCP_CONNTRACK_SYN_RECV],
1350                 .maxlen         = sizeof(unsigned int),
1351                 .mode           = 0644,
1352                 .proc_handler   = proc_dointvec_jiffies,
1353         },
1354         {
1355                 .procname       = "ip_conntrack_tcp_timeout_established",
1356                 .data           = &tcp_timeouts[TCP_CONNTRACK_ESTABLISHED],
1357                 .maxlen         = sizeof(unsigned int),
1358                 .mode           = 0644,
1359                 .proc_handler   = proc_dointvec_jiffies,
1360         },
1361         {
1362                 .procname       = "ip_conntrack_tcp_timeout_fin_wait",
1363                 .data           = &tcp_timeouts[TCP_CONNTRACK_FIN_WAIT],
1364                 .maxlen         = sizeof(unsigned int),
1365                 .mode           = 0644,
1366                 .proc_handler   = proc_dointvec_jiffies,
1367         },
1368         {
1369                 .procname       = "ip_conntrack_tcp_timeout_close_wait",
1370                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE_WAIT],
1371                 .maxlen         = sizeof(unsigned int),
1372                 .mode           = 0644,
1373                 .proc_handler   = proc_dointvec_jiffies,
1374         },
1375         {
1376                 .procname       = "ip_conntrack_tcp_timeout_last_ack",
1377                 .data           = &tcp_timeouts[TCP_CONNTRACK_LAST_ACK],
1378                 .maxlen         = sizeof(unsigned int),
1379                 .mode           = 0644,
1380                 .proc_handler   = proc_dointvec_jiffies,
1381         },
1382         {
1383                 .procname       = "ip_conntrack_tcp_timeout_time_wait",
1384                 .data           = &tcp_timeouts[TCP_CONNTRACK_TIME_WAIT],
1385                 .maxlen         = sizeof(unsigned int),
1386                 .mode           = 0644,
1387                 .proc_handler   = proc_dointvec_jiffies,
1388         },
1389         {
1390                 .procname       = "ip_conntrack_tcp_timeout_close",
1391                 .data           = &tcp_timeouts[TCP_CONNTRACK_CLOSE],
1392                 .maxlen         = sizeof(unsigned int),
1393                 .mode           = 0644,
1394                 .proc_handler   = proc_dointvec_jiffies,
1395         },
1396         {
1397                 .procname       = "ip_conntrack_tcp_timeout_max_retrans",
1398                 .data           = &nf_ct_tcp_timeout_max_retrans,
1399                 .maxlen         = sizeof(unsigned int),
1400                 .mode           = 0644,
1401                 .proc_handler   = proc_dointvec_jiffies,
1402         },
1403         {
1404                 .procname       = "ip_conntrack_tcp_loose",
1405                 .data           = &nf_ct_tcp_loose,
1406                 .maxlen         = sizeof(unsigned int),
1407                 .mode           = 0644,
1408                 .proc_handler   = proc_dointvec,
1409         },
1410         {
1411                 .procname       = "ip_conntrack_tcp_be_liberal",
1412                 .data           = &nf_ct_tcp_be_liberal,
1413                 .maxlen         = sizeof(unsigned int),
1414                 .mode           = 0644,
1415                 .proc_handler   = proc_dointvec,
1416         },
1417         {
1418                 .procname       = "ip_conntrack_tcp_max_retrans",
1419                 .data           = &nf_ct_tcp_max_retrans,
1420                 .maxlen         = sizeof(unsigned int),
1421                 .mode           = 0644,
1422                 .proc_handler   = proc_dointvec,
1423         },
1424         { }
1425 };
1426 #endif /* CONFIG_NF_CONNTRACK_PROC_COMPAT */
1427 #endif /* CONFIG_SYSCTL */
1428
1429 struct nf_conntrack_l4proto nf_conntrack_l4proto_tcp4 __read_mostly =
1430 {
1431         .l3proto                = PF_INET,
1432         .l4proto                = IPPROTO_TCP,
1433         .name                   = "tcp",
1434         .pkt_to_tuple           = tcp_pkt_to_tuple,
1435         .invert_tuple           = tcp_invert_tuple,
1436         .print_tuple            = tcp_print_tuple,
1437         .print_conntrack        = tcp_print_conntrack,
1438         .packet                 = tcp_packet,
1439         .new                    = tcp_new,
1440         .error                  = tcp_error,
1441 #if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
1442         .to_nlattr              = tcp_to_nlattr,
1443         .nlattr_size            = tcp_nlattr_size,
1444         .from_nlattr            = nlattr_to_tcp,
1445         .tuple_to_nlattr        = nf_ct_port_tuple_to_nlattr,
1446         .nlattr_to_tuple        = nf_ct_port_nlattr_to_tuple,
1447         .nlattr_tuple_size      = tcp_nlattr_tuple_size,
1448         .nla_policy             = nf_ct_port_nla_policy,
1449 #endif
1450 #ifdef CONFIG_SYSCTL
1451         .ctl_table_users        = &tcp_sysctl_table_users,
1452         .ctl_table_header       = &tcp_sysctl_header,
1453         .ctl_table              = tcp_sysctl_table,
1454 #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
1455         .ctl_compat_table       = tcp_compat_sysctl_table,
1456 #endif
1457 #endif
1458 };
1459 EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_tcp4);
1460
1461 struct nf_conntrack_l4proto nf_conntrack_l4proto_tcp6 __read_mostly =
1462 {
1463         .l3proto                = PF_INET6,
1464         .l4proto                = IPPROTO_TCP,
1465         .name                   = "tcp",
1466         .pkt_to_tuple           = tcp_pkt_to_tuple,
1467         .invert_tuple           = tcp_invert_tuple,
1468         .print_tuple            = tcp_print_tuple,
1469         .print_conntrack        = tcp_print_conntrack,
1470         .packet                 = tcp_packet,
1471         .new                    = tcp_new,
1472         .error                  = tcp_error,
1473 #if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
1474         .to_nlattr              = tcp_to_nlattr,
1475         .nlattr_size            = tcp_nlattr_size,
1476         .from_nlattr            = nlattr_to_tcp,
1477         .tuple_to_nlattr        = nf_ct_port_tuple_to_nlattr,
1478         .nlattr_to_tuple        = nf_ct_port_nlattr_to_tuple,
1479         .nlattr_tuple_size      = tcp_nlattr_tuple_size,
1480         .nla_policy             = nf_ct_port_nla_policy,
1481 #endif
1482 #ifdef CONFIG_SYSCTL
1483         .ctl_table_users        = &tcp_sysctl_table_users,
1484         .ctl_table_header       = &tcp_sysctl_header,
1485         .ctl_table              = tcp_sysctl_table,
1486 #endif
1487 };
1488 EXPORT_SYMBOL_GPL(nf_conntrack_l4proto_tcp6);