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