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