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