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