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