1 // SPDX-License-Identifier: GPL-2.0-only
2 /* FTP extension for connection tracking. */
3
4 /* (C) 1999-2001 Paul `Rusty' Russell
5 * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
6 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
7 * (C) 2006-2012 Patrick McHardy <kaber@trash.net>
8 */
9
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/netfilter.h>
15 #include <linux/ip.h>
16 #include <linux/slab.h>
17 #include <linux/ipv6.h>
18 #include <linux/ctype.h>
19 #include <linux/inet.h>
20 #include <net/checksum.h>
21 #include <net/tcp.h>
22
23 #include <net/netfilter/nf_conntrack.h>
24 #include <net/netfilter/nf_conntrack_expect.h>
25 #include <net/netfilter/nf_conntrack_ecache.h>
26 #include <net/netfilter/nf_conntrack_helper.h>
27 #include <linux/netfilter/nf_conntrack_ftp.h>
28
29 #define HELPER_NAME "ftp"
30
31 MODULE_LICENSE("GPL");
32 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
33 MODULE_DESCRIPTION("ftp connection tracking helper");
34 MODULE_ALIAS("ip_conntrack_ftp");
35 MODULE_ALIAS_NFCT_HELPER(HELPER_NAME);
36 static DEFINE_SPINLOCK(nf_ftp_lock);
37
38 static bool loose;
39 module_param(loose, bool, 0600);
40
41 nf_nat_ftp_hook_fn __rcu *nf_nat_ftp_hook;
42 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
43
44 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *,
45 char, unsigned int *);
46 static int try_rfc1123(const char *, size_t, struct nf_conntrack_man *,
47 char, unsigned int *);
48 static int try_eprt(const char *, size_t, struct nf_conntrack_man *,
49 char, unsigned int *);
50 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
51 char, unsigned int *);
52
53 static struct ftp_search {
54 const char *pattern;
55 size_t plen;
56 char skip;
57 char term;
58 enum nf_ct_ftp_type ftptype;
59 int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char, unsigned int *);
60 } search[IP_CT_DIR_MAX][2] = {
61 [IP_CT_DIR_ORIGINAL] = {
62 {
63 .pattern = "PORT",
64 .plen = sizeof("PORT") - 1,
65 .skip = ' ',
66 .term = '\r',
67 .ftptype = NF_CT_FTP_PORT,
68 .getnum = try_rfc959,
69 },
70 {
71 .pattern = "EPRT",
72 .plen = sizeof("EPRT") - 1,
73 .skip = ' ',
74 .term = '\r',
75 .ftptype = NF_CT_FTP_EPRT,
76 .getnum = try_eprt,
77 },
78 },
79 [IP_CT_DIR_REPLY] = {
80 {
81 .pattern = "227 ",
82 .plen = sizeof("227 ") - 1,
83 .ftptype = NF_CT_FTP_PASV,
84 .getnum = try_rfc1123,
85 },
86 {
87 .pattern = "229 ",
88 .plen = sizeof("229 ") - 1,
89 .skip = '(',
90 .term = ')',
91 .ftptype = NF_CT_FTP_EPSV,
92 .getnum = try_epsv_response,
93 },
94 },
95 };
96
97 static int
get_ipv6_addr(const char * src,size_t dlen,struct in6_addr * dst,u_int8_t term)98 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
99 {
100 const char *end;
101 int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
102 if (ret > 0)
103 return (int)(end - src);
104 return 0;
105 }
106
try_number(const char * data,size_t dlen,u_int32_t array[],int array_size,char sep,char term)107 static int try_number(const char *data, size_t dlen, u_int32_t array[],
108 int array_size, char sep, char term)
109 {
110 u_int32_t i, len;
111
112 memset(array, 0, sizeof(array[0])*array_size);
113
114 /* Keep data pointing at next char. */
115 for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
116 if (*data >= '0' && *data <= '9') {
117 array[i] = array[i]*10 + *data - '0';
118 if (array[i] > 255)
119 return 0;
120 }
121 else if (*data == sep)
122 i++;
123 else {
124 /* Unexpected character; true if it's the
125 terminator (or we don't care about one)
126 and we're finished. */
127 if ((*data == term || !term) && i == array_size - 1)
128 return len;
129
130 pr_debug("Char %u (got %u nums) `%u' unexpected\n",
131 len, i, *data);
132 return 0;
133 }
134 }
135 pr_debug("Failed to fill %u numbers separated by %c\n",
136 array_size, sep);
137 return 0;
138 }
139
140 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
try_rfc959(const char * data,size_t dlen,struct nf_conntrack_man * cmd,char term,unsigned int * offset)141 static int try_rfc959(const char *data, size_t dlen,
142 struct nf_conntrack_man *cmd, char term,
143 unsigned int *offset)
144 {
145 int length;
146 u_int32_t array[6];
147
148 length = try_number(data, dlen, array, 6, ',', term);
149 if (length == 0)
150 return 0;
151
152 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16) |
153 (array[2] << 8) | array[3]);
154 cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
155 return length;
156 }
157
158 /*
159 * From RFC 1123:
160 * The format of the 227 reply to a PASV command is not
161 * well standardized. In particular, an FTP client cannot
162 * assume that the parentheses shown on page 40 of RFC-959
163 * will be present (and in fact, Figure 3 on page 43 omits
164 * them). Therefore, a User-FTP program that interprets
165 * the PASV reply must scan the reply for the first digit
166 * of the host and port numbers.
167 */
try_rfc1123(const char * data,size_t dlen,struct nf_conntrack_man * cmd,char term,unsigned int * offset)168 static int try_rfc1123(const char *data, size_t dlen,
169 struct nf_conntrack_man *cmd, char term,
170 unsigned int *offset)
171 {
172 int i;
173 for (i = 0; i < dlen; i++)
174 if (isdigit(data[i]))
175 break;
176
177 if (i == dlen)
178 return 0;
179
180 *offset += i;
181
182 return try_rfc959(data + i, dlen - i, cmd, 0, offset);
183 }
184
185 /* Grab port: number up to delimiter */
get_port(const char * data,int start,size_t dlen,char delim,__be16 * port)186 static int get_port(const char *data, int start, size_t dlen, char delim,
187 __be16 *port)
188 {
189 u32 tmp_port = 0;
190 int i;
191
192 for (i = start; i < dlen; i++) {
193 /* Finished? */
194 if (data[i] == delim) {
195 if (tmp_port == 0)
196 break;
197 *port = htons(tmp_port);
198 pr_debug("get_port: return %d\n", tmp_port);
199 return i + 1;
200 } else if (data[i] >= '0' && data[i] <= '9') {
201 tmp_port = tmp_port*10 + data[i] - '0';
202 if (tmp_port > 65535)
203 break;
204 } else { /* Some other crap */
205 pr_debug("get_port: invalid char.\n");
206 break;
207 }
208 }
209 return 0;
210 }
211
212 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
try_eprt(const char * data,size_t dlen,struct nf_conntrack_man * cmd,char term,unsigned int * offset)213 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
214 char term, unsigned int *offset)
215 {
216 char delim;
217 int length;
218
219 /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
220 then delimiter again. */
221 if (dlen <= 3) {
222 pr_debug("EPRT: too short\n");
223 return 0;
224 }
225 delim = data[0];
226 if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
227 pr_debug("try_eprt: invalid delimiter.\n");
228 return 0;
229 }
230
231 if ((cmd->l3num == PF_INET && data[1] != '1') ||
232 (cmd->l3num == PF_INET6 && data[1] != '2')) {
233 pr_debug("EPRT: invalid protocol number.\n");
234 return 0;
235 }
236
237 pr_debug("EPRT: Got %c%c%c\n", delim, data[1], delim);
238
239 if (data[1] == '1') {
240 u_int32_t array[4];
241
242 /* Now we have IP address. */
243 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
244 if (length != 0)
245 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
246 | (array[2] << 8) | array[3]);
247 } else {
248 /* Now we have IPv6 address. */
249 length = get_ipv6_addr(data + 3, dlen - 3,
250 (struct in6_addr *)cmd->u3.ip6, delim);
251 }
252
253 if (length == 0)
254 return 0;
255 pr_debug("EPRT: Got IP address!\n");
256 /* Start offset includes initial "|1|", and trailing delimiter */
257 return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
258 }
259
260 /* Returns 0, or length of numbers: |||6446| */
try_epsv_response(const char * data,size_t dlen,struct nf_conntrack_man * cmd,char term,unsigned int * offset)261 static int try_epsv_response(const char *data, size_t dlen,
262 struct nf_conntrack_man *cmd, char term,
263 unsigned int *offset)
264 {
265 char delim;
266
267 /* Three delimiters. */
268 if (dlen <= 3) return 0;
269 delim = data[0];
270 if (isdigit(delim) || delim < 33 || delim > 126 ||
271 data[1] != delim || data[2] != delim)
272 return 0;
273
274 return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
275 }
276
277 /* Return 1 for match, 0 for accept, -1 for partial. */
find_pattern(const char * data,size_t dlen,const char * pattern,size_t plen,char skip,char term,unsigned int * numoff,unsigned int * numlen,struct nf_conntrack_man * cmd,int (* getnum)(const char *,size_t,struct nf_conntrack_man *,char,unsigned int *))278 static int find_pattern(const char *data, size_t dlen,
279 const char *pattern, size_t plen,
280 char skip, char term,
281 unsigned int *numoff,
282 unsigned int *numlen,
283 struct nf_conntrack_man *cmd,
284 int (*getnum)(const char *, size_t,
285 struct nf_conntrack_man *, char,
286 unsigned int *))
287 {
288 size_t i = plen;
289
290 pr_debug("find_pattern `%s': dlen = %zu\n", pattern, dlen);
291
292 if (dlen <= plen) {
293 /* Short packet: try for partial? */
294 if (strncasecmp(data, pattern, dlen) == 0)
295 return -1;
296 else return 0;
297 }
298
299 if (strncasecmp(data, pattern, plen) != 0)
300 return 0;
301
302 pr_debug("Pattern matches!\n");
303 /* Now we've found the constant string, try to skip
304 to the 'skip' character */
305 if (skip) {
306 for (i = plen; data[i] != skip; i++)
307 if (i == dlen - 1) return -1;
308
309 /* Skip over the last character */
310 i++;
311 }
312
313 pr_debug("Skipped up to 0x%hhx delimiter!\n", skip);
314
315 *numoff = i;
316 *numlen = getnum(data + i, dlen - i, cmd, term, numoff);
317 if (!*numlen)
318 return -1;
319
320 pr_debug("Match succeeded!\n");
321 return 1;
322 }
323
324 /* Look up to see if we're just after a \n. */
find_nl_seq(u32 seq,const struct nf_ct_ftp_master * info,int dir)325 static int find_nl_seq(u32 seq, const struct nf_ct_ftp_master *info, int dir)
326 {
327 unsigned int i;
328
329 for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
330 if (info->seq_aft_nl[dir][i] == seq)
331 return 1;
332 return 0;
333 }
334
335 /* We don't update if it's older than what we have. */
update_nl_seq(struct nf_conn * ct,u32 nl_seq,struct nf_ct_ftp_master * info,int dir,struct sk_buff * skb)336 static void update_nl_seq(struct nf_conn *ct, u32 nl_seq,
337 struct nf_ct_ftp_master *info, int dir,
338 struct sk_buff *skb)
339 {
340 unsigned int i, oldest;
341
342 /* Look for oldest: if we find exact match, we're done. */
343 for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
344 if (info->seq_aft_nl[dir][i] == nl_seq)
345 return;
346 }
347
348 if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
349 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
350 } else {
351 if (before(info->seq_aft_nl[dir][0], info->seq_aft_nl[dir][1]))
352 oldest = 0;
353 else
354 oldest = 1;
355
356 if (after(nl_seq, info->seq_aft_nl[dir][oldest]))
357 info->seq_aft_nl[dir][oldest] = nl_seq;
358 }
359 }
360
help(struct sk_buff * skb,unsigned int protoff,struct nf_conn * ct,enum ip_conntrack_info ctinfo)361 static int help(struct sk_buff *skb,
362 unsigned int protoff,
363 struct nf_conn *ct,
364 enum ip_conntrack_info ctinfo)
365 {
366 unsigned int dataoff, datalen;
367 const struct tcphdr *th;
368 struct tcphdr _tcph;
369 const char *fb_ptr;
370 int ret;
371 u32 seq;
372 int dir = CTINFO2DIR(ctinfo);
373 unsigned int matchlen, matchoff;
374 struct nf_ct_ftp_master *ct_ftp_info = nfct_help_data(ct);
375 struct nf_conntrack_expect *exp;
376 union nf_inet_addr *daddr;
377 struct nf_conntrack_man cmd = {};
378 unsigned int i;
379 int found = 0, ends_in_nl;
380 nf_nat_ftp_hook_fn *nf_nat_ftp;
381
382 if (!ct_ftp_info)
383 return NF_DROP;
384
385 /* Until there's been traffic both ways, don't look in packets. */
386 if (ctinfo != IP_CT_ESTABLISHED &&
387 ctinfo != IP_CT_ESTABLISHED_REPLY) {
388 pr_debug("ftp: Conntrackinfo = %u\n", ctinfo);
389 return NF_ACCEPT;
390 }
391
392 if (unlikely(skb_linearize(skb)))
393 return NF_DROP;
394
395 th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
396 if (th == NULL)
397 return NF_ACCEPT;
398
399 dataoff = protoff + th->doff * 4;
400 /* No data? */
401 if (dataoff >= skb->len) {
402 pr_debug("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
403 skb->len);
404 return NF_ACCEPT;
405 }
406 datalen = skb->len - dataoff;
407
408 /* seqadj (nat) uses ct->lock internally, nf_nat_ftp would cause deadlock */
409 spin_lock_bh(&nf_ftp_lock);
410 fb_ptr = skb->data + dataoff;
411
412 ends_in_nl = (fb_ptr[datalen - 1] == '\n');
413 seq = ntohl(th->seq) + datalen;
414
415 /* Look up to see if we're just after a \n. */
416 if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
417 /* We're picking up this, clear flags and let it continue */
418 if (unlikely(ct_ftp_info->flags[dir] & NF_CT_FTP_SEQ_PICKUP)) {
419 ct_ftp_info->flags[dir] ^= NF_CT_FTP_SEQ_PICKUP;
420 goto skip_nl_seq;
421 }
422
423 /* Now if this ends in \n, update ftp info. */
424 pr_debug("nf_conntrack_ftp: wrong seq pos %s(%u) or %s(%u)\n",
425 ct_ftp_info->seq_aft_nl_num[dir] > 0 ? "" : "(UNSET)",
426 ct_ftp_info->seq_aft_nl[dir][0],
427 ct_ftp_info->seq_aft_nl_num[dir] > 1 ? "" : "(UNSET)",
428 ct_ftp_info->seq_aft_nl[dir][1]);
429 ret = NF_ACCEPT;
430 goto out_update_nl;
431 }
432
433 skip_nl_seq:
434 /* Initialize IP/IPv6 addr to expected address (it's not mentioned
435 in EPSV responses) */
436 cmd.l3num = nf_ct_l3num(ct);
437 memcpy(cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
438 sizeof(cmd.u3.all));
439
440 for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
441 found = find_pattern(fb_ptr, datalen,
442 search[dir][i].pattern,
443 search[dir][i].plen,
444 search[dir][i].skip,
445 search[dir][i].term,
446 &matchoff, &matchlen,
447 &cmd,
448 search[dir][i].getnum);
449 if (found) break;
450 }
451 if (found == -1) {
452 /* We don't usually drop packets. After all, this is
453 connection tracking, not packet filtering.
454 However, it is necessary for accurate tracking in
455 this case. */
456 nf_ct_helper_log(skb, ct, "partial matching of `%s'",
457 search[dir][i].pattern);
458 ret = NF_DROP;
459 goto out;
460 } else if (found == 0) { /* No match */
461 ret = NF_ACCEPT;
462 goto out_update_nl;
463 }
464
465 pr_debug("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
466 matchlen, fb_ptr + matchoff,
467 matchlen, ntohl(th->seq) + matchoff);
468
469 exp = nf_ct_expect_alloc(ct);
470 if (exp == NULL) {
471 nf_ct_helper_log(skb, ct, "cannot alloc expectation");
472 ret = NF_DROP;
473 goto out;
474 }
475
476 /* We refer to the reverse direction ("!dir") tuples here,
477 * because we're expecting something in the other direction.
478 * Doesn't matter unless NAT is happening. */
479 daddr = &ct->tuplehash[!dir].tuple.dst.u3;
480
481 /* Update the ftp info */
482 if ((cmd.l3num == nf_ct_l3num(ct)) &&
483 memcmp(&cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
484 sizeof(cmd.u3.all))) {
485 /* Enrico Scholz's passive FTP to partially RNAT'd ftp
486 server: it really wants us to connect to a
487 different IP address. Simply don't record it for
488 NAT. */
489 if (cmd.l3num == PF_INET) {
490 pr_debug("NOT RECORDING: %pI4 != %pI4\n",
491 &cmd.u3.ip,
492 &ct->tuplehash[dir].tuple.src.u3.ip);
493 } else {
494 pr_debug("NOT RECORDING: %pI6 != %pI6\n",
495 cmd.u3.ip6,
496 ct->tuplehash[dir].tuple.src.u3.ip6);
497 }
498
499 /* Thanks to Cristiano Lincoln Mattos
500 <lincoln@cesar.org.br> for reporting this potential
501 problem (DMZ machines opening holes to internal
502 networks, or the packet filter itself). */
503 if (!loose) {
504 ret = NF_ACCEPT;
505 goto out_put_expect;
506 }
507 daddr = &cmd.u3;
508 }
509
510 nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, cmd.l3num,
511 &ct->tuplehash[!dir].tuple.src.u3, daddr,
512 IPPROTO_TCP, NULL, &cmd.u.tcp.port);
513
514 /* Now, NAT might want to mangle the packet, and register the
515 * (possibly changed) expectation itself. */
516 nf_nat_ftp = rcu_dereference(nf_nat_ftp_hook);
517 if (nf_nat_ftp && ct->status & IPS_NAT_MASK)
518 ret = nf_nat_ftp(skb, ct, ctinfo, search[dir][i].ftptype,
519 protoff, matchoff, matchlen, exp);
520 else {
521 /* Can't expect this? Best to drop packet now. */
522 if (nf_ct_expect_related(exp, 0) != 0) {
523 nf_ct_helper_log(skb, ct, "cannot add expectation");
524 ret = NF_DROP;
525 } else
526 ret = NF_ACCEPT;
527 }
528
529 out_put_expect:
530 nf_ct_expect_put(exp);
531
532 out_update_nl:
533 /* Now if this ends in \n, update ftp info. Seq may have been
534 * adjusted by NAT code. */
535 if (ends_in_nl)
536 update_nl_seq(ct, seq, ct_ftp_info, dir, skb);
537 out:
538 spin_unlock_bh(&nf_ftp_lock);
539 return ret;
540 }
541
nf_ct_ftp_from_nlattr(struct nlattr * attr,struct nf_conn * ct)542 static int nf_ct_ftp_from_nlattr(struct nlattr *attr, struct nf_conn *ct)
543 {
544 struct nf_ct_ftp_master *ftp = nfct_help_data(ct);
545
546 if (!ftp)
547 return -ENOENT;
548
549 /* This conntrack has been injected from user-space, always pick up
550 * sequence tracking. Otherwise, the first FTP command after the
551 * failover breaks.
552 */
553 ftp->flags[IP_CT_DIR_ORIGINAL] |= NF_CT_FTP_SEQ_PICKUP;
554 ftp->flags[IP_CT_DIR_REPLY] |= NF_CT_FTP_SEQ_PICKUP;
555 return 0;
556 }
557
558 static struct nf_conntrack_helper ftp __read_mostly;
559 static struct nf_conntrack_helper *ftp_ptr __read_mostly;
560
561 static const struct nf_conntrack_expect_policy ftp_exp_policy = {
562 .max_expected = 1,
563 .timeout = 5 * 60,
564 };
565
nf_conntrack_ftp_fini(void)566 static void __exit nf_conntrack_ftp_fini(void)
567 {
568 nf_conntrack_helper_unregister(ftp_ptr);
569 }
570
nf_conntrack_ftp_init(void)571 static int __init nf_conntrack_ftp_init(void)
572 {
573 int ret = 0;
574
575 NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_ftp_master));
576
577 /* FIXME should be configurable whether IPv4 and IPv6 FTP connections
578 are tracked or not - YK */
579 nf_ct_helper_init(&ftp, NFPROTO_UNSPEC, IPPROTO_TCP,
580 HELPER_NAME,
581 &ftp_exp_policy, 0, help,
582 nf_ct_ftp_from_nlattr, THIS_MODULE);
583
584 ret = nf_conntrack_helper_register(&ftp, &ftp_ptr);
585 if (ret < 0) {
586 pr_err("failed to register helpers\n");
587 return ret;
588 }
589
590 return 0;
591 }
592
593 module_init(nf_conntrack_ftp_init);
594 module_exit(nf_conntrack_ftp_fini);
595