]> git.proxmox.com Git - mirror_ovs.git/blob - lib/conntrack.c
ovsdb-idl: Fix iteration over tracked rows with no actual data.
[mirror_ovs.git] / lib / conntrack.c
1 /*
2 * Copyright (c) 2015-2019 Nicira, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <config.h>
18 #include <ctype.h>
19 #include <errno.h>
20 #include <sys/types.h>
21 #include <netinet/in.h>
22 #include <netinet/icmp6.h>
23 #include <string.h>
24
25 #include "bitmap.h"
26 #include "conntrack.h"
27 #include "conntrack-private.h"
28 #include "conntrack-tp.h"
29 #include "coverage.h"
30 #include "csum.h"
31 #include "ct-dpif.h"
32 #include "dp-packet.h"
33 #include "flow.h"
34 #include "netdev.h"
35 #include "odp-netlink.h"
36 #include "openvswitch/hmap.h"
37 #include "openvswitch/vlog.h"
38 #include "ovs-rcu.h"
39 #include "ovs-thread.h"
40 #include "openvswitch/poll-loop.h"
41 #include "random.h"
42 #include "timeval.h"
43
44 VLOG_DEFINE_THIS_MODULE(conntrack);
45
46 COVERAGE_DEFINE(conntrack_full);
47 COVERAGE_DEFINE(conntrack_long_cleanup);
48 COVERAGE_DEFINE(conntrack_l4csum_err);
49
50 struct conn_lookup_ctx {
51 struct conn_key key;
52 struct conn *conn;
53 uint32_t hash;
54 bool reply;
55 bool icmp_related;
56 };
57
58 enum ftp_ctl_pkt {
59 /* Control packets with address and/or port specifiers. */
60 CT_FTP_CTL_INTEREST,
61 /* Control packets without address and/or port specifiers. */
62 CT_FTP_CTL_OTHER,
63 CT_FTP_CTL_INVALID,
64 };
65
66 enum ct_alg_mode {
67 CT_FTP_MODE_ACTIVE,
68 CT_FTP_MODE_PASSIVE,
69 CT_TFTP_MODE,
70 };
71
72 enum ct_alg_ctl_type {
73 CT_ALG_CTL_NONE,
74 CT_ALG_CTL_FTP,
75 CT_ALG_CTL_TFTP,
76 /* SIP is not enabled through Openflow and presently only used as
77 * an example of an alg that allows a wildcard src ip. */
78 CT_ALG_CTL_SIP,
79 };
80
81 struct zone_limit {
82 struct hmap_node node;
83 struct conntrack_zone_limit czl;
84 };
85
86 static bool conn_key_extract(struct conntrack *, struct dp_packet *,
87 ovs_be16 dl_type, struct conn_lookup_ctx *,
88 uint16_t zone);
89 static uint32_t conn_key_hash(const struct conn_key *, uint32_t basis);
90 static void conn_key_reverse(struct conn_key *);
91 static bool valid_new(struct dp_packet *pkt, struct conn_key *);
92 static struct conn *new_conn(struct conntrack *ct, struct dp_packet *pkt,
93 struct conn_key *, long long now,
94 uint32_t tp_id);
95 static void delete_conn_cmn(struct conn *);
96 static void delete_conn(struct conn *);
97 static void delete_conn_one(struct conn *conn);
98 static enum ct_update_res conn_update(struct conntrack *ct, struct conn *conn,
99 struct dp_packet *pkt,
100 struct conn_lookup_ctx *ctx,
101 long long now);
102 static bool conn_expired(struct conn *, long long now);
103 static void set_mark(struct dp_packet *, struct conn *,
104 uint32_t val, uint32_t mask);
105 static void set_label(struct dp_packet *, struct conn *,
106 const struct ovs_key_ct_labels *val,
107 const struct ovs_key_ct_labels *mask);
108 static void *clean_thread_main(void *f_);
109
110 static bool
111 nat_select_range_tuple(struct conntrack *ct, const struct conn *conn,
112 struct conn *nat_conn);
113
114 static uint8_t
115 reverse_icmp_type(uint8_t type);
116 static uint8_t
117 reverse_icmp6_type(uint8_t type);
118 static inline bool
119 extract_l3_ipv4(struct conn_key *key, const void *data, size_t size,
120 const char **new_data, bool validate_checksum);
121 static inline bool
122 extract_l3_ipv6(struct conn_key *key, const void *data, size_t size,
123 const char **new_data);
124 static struct alg_exp_node *
125 expectation_lookup(struct hmap *alg_expectations, const struct conn_key *key,
126 uint32_t basis, bool src_ip_wc);
127
128 static int
129 repl_ftp_v4_addr(struct dp_packet *pkt, ovs_be32 v4_addr_rep,
130 char *ftp_data_v4_start,
131 size_t addr_offset_from_ftp_data_start, size_t addr_size);
132
133 static enum ftp_ctl_pkt
134 process_ftp_ctl_v4(struct conntrack *ct,
135 struct dp_packet *pkt,
136 const struct conn *conn_for_expectation,
137 ovs_be32 *v4_addr_rep,
138 char **ftp_data_v4_start,
139 size_t *addr_offset_from_ftp_data_start,
140 size_t *addr_size);
141
142 static enum ftp_ctl_pkt
143 detect_ftp_ctl_type(const struct conn_lookup_ctx *ctx,
144 struct dp_packet *pkt);
145
146 static void
147 expectation_clean(struct conntrack *ct, const struct conn_key *parent_key);
148
149 static struct ct_l4_proto *l4_protos[] = {
150 [IPPROTO_TCP] = &ct_proto_tcp,
151 [IPPROTO_UDP] = &ct_proto_other,
152 [IPPROTO_ICMP] = &ct_proto_icmp4,
153 [IPPROTO_ICMPV6] = &ct_proto_icmp6,
154 };
155
156 static void
157 handle_ftp_ctl(struct conntrack *ct, const struct conn_lookup_ctx *ctx,
158 struct dp_packet *pkt, struct conn *ec, long long now,
159 enum ftp_ctl_pkt ftp_ctl, bool nat);
160
161 static void
162 handle_tftp_ctl(struct conntrack *ct,
163 const struct conn_lookup_ctx *ctx OVS_UNUSED,
164 struct dp_packet *pkt, struct conn *conn_for_expectation,
165 long long now OVS_UNUSED, enum ftp_ctl_pkt ftp_ctl OVS_UNUSED,
166 bool nat OVS_UNUSED);
167
168 typedef void (*alg_helper)(struct conntrack *ct,
169 const struct conn_lookup_ctx *ctx,
170 struct dp_packet *pkt,
171 struct conn *conn_for_expectation,
172 long long now, enum ftp_ctl_pkt ftp_ctl,
173 bool nat);
174
175 static alg_helper alg_helpers[] = {
176 [CT_ALG_CTL_NONE] = NULL,
177 [CT_ALG_CTL_FTP] = handle_ftp_ctl,
178 [CT_ALG_CTL_TFTP] = handle_tftp_ctl,
179 };
180
181 /* The maximum TCP or UDP port number. */
182 #define CT_MAX_L4_PORT 65535
183 /* String buffer used for parsing FTP string messages.
184 * This is sized about twice what is needed to leave some
185 * margin of error. */
186 #define LARGEST_FTP_MSG_OF_INTEREST 128
187 /* FTP port string used in active mode. */
188 #define FTP_PORT_CMD "PORT"
189 /* FTP pasv string used in passive mode. */
190 #define FTP_PASV_REPLY_CODE "227"
191 /* Maximum decimal digits for port in FTP command.
192 * The port is represented as two 3 digit numbers with the
193 * high part a multiple of 256. */
194 #define MAX_FTP_PORT_DGTS 3
195
196 /* FTP extension EPRT string used for active mode. */
197 #define FTP_EPRT_CMD "EPRT"
198 /* FTP extension EPSV string used for passive mode. */
199 #define FTP_EPSV_REPLY "EXTENDED PASSIVE"
200 /* Maximum decimal digits for port in FTP extended command. */
201 #define MAX_EXT_FTP_PORT_DGTS 5
202 /* FTP extended command code for IPv6. */
203 #define FTP_AF_V6 '2'
204 /* Used to indicate a wildcard L4 source port number for ALGs.
205 * This is used for port numbers that we cannot predict in
206 * expectations. */
207 #define ALG_WC_SRC_PORT 0
208
209 /* If the total number of connections goes above this value, no new connections
210 * are accepted; this is for CT_CONN_TYPE_DEFAULT connections. */
211 #define DEFAULT_N_CONN_LIMIT 3000000
212
213 /* Does a member by member comparison of two conn_keys; this
214 * function must be kept in sync with struct conn_key; returns 0
215 * if the keys are equal or 1 if the keys are not equal. */
216 static int
217 conn_key_cmp(const struct conn_key *key1, const struct conn_key *key2)
218 {
219 if (!memcmp(&key1->src.addr, &key2->src.addr, sizeof key1->src.addr) &&
220 !memcmp(&key1->dst.addr, &key2->dst.addr, sizeof key1->dst.addr) &&
221 (key1->src.icmp_id == key2->src.icmp_id) &&
222 (key1->src.icmp_type == key2->src.icmp_type) &&
223 (key1->src.icmp_code == key2->src.icmp_code) &&
224 (key1->dst.icmp_id == key2->dst.icmp_id) &&
225 (key1->dst.icmp_type == key2->dst.icmp_type) &&
226 (key1->dst.icmp_code == key2->dst.icmp_code) &&
227 (key1->dl_type == key2->dl_type) &&
228 (key1->zone == key2->zone) &&
229 (key1->nw_proto == key2->nw_proto)) {
230
231 return 0;
232 }
233 return 1;
234 }
235
236 static void
237 ct_print_conn_info(const struct conn *c, const char *log_msg,
238 enum vlog_level vll, bool force, bool rl_on)
239 {
240 #define CT_VLOG(RL_ON, LEVEL, ...) \
241 do { \
242 if (RL_ON) { \
243 static struct vlog_rate_limit rl_ = VLOG_RATE_LIMIT_INIT(5, 5); \
244 vlog_rate_limit(&this_module, LEVEL, &rl_, __VA_ARGS__); \
245 } else { \
246 vlog(&this_module, LEVEL, __VA_ARGS__); \
247 } \
248 } while (0)
249
250 if (OVS_UNLIKELY(force || vlog_is_enabled(&this_module, vll))) {
251 if (c->key.dl_type == htons(ETH_TYPE_IP)) {
252 CT_VLOG(rl_on, vll, "%s: src ip "IP_FMT" dst ip "IP_FMT" rev src "
253 "ip "IP_FMT" rev dst ip "IP_FMT" src/dst ports "
254 "%"PRIu16"/%"PRIu16" rev src/dst ports "
255 "%"PRIu16"/%"PRIu16" zone/rev zone "
256 "%"PRIu16"/%"PRIu16" nw_proto/rev nw_proto "
257 "%"PRIu8"/%"PRIu8, log_msg,
258 IP_ARGS(c->key.src.addr.ipv4),
259 IP_ARGS(c->key.dst.addr.ipv4),
260 IP_ARGS(c->rev_key.src.addr.ipv4),
261 IP_ARGS(c->rev_key.dst.addr.ipv4),
262 ntohs(c->key.src.port), ntohs(c->key.dst.port),
263 ntohs(c->rev_key.src.port), ntohs(c->rev_key.dst.port),
264 c->key.zone, c->rev_key.zone, c->key.nw_proto,
265 c->rev_key.nw_proto);
266 } else {
267 char ip6_s[INET6_ADDRSTRLEN];
268 inet_ntop(AF_INET6, &c->key.src.addr.ipv6, ip6_s, sizeof ip6_s);
269 char ip6_d[INET6_ADDRSTRLEN];
270 inet_ntop(AF_INET6, &c->key.dst.addr.ipv6, ip6_d, sizeof ip6_d);
271 char ip6_rs[INET6_ADDRSTRLEN];
272 inet_ntop(AF_INET6, &c->rev_key.src.addr.ipv6, ip6_rs,
273 sizeof ip6_rs);
274 char ip6_rd[INET6_ADDRSTRLEN];
275 inet_ntop(AF_INET6, &c->rev_key.dst.addr.ipv6, ip6_rd,
276 sizeof ip6_rd);
277
278 CT_VLOG(rl_on, vll, "%s: src ip %s dst ip %s rev src ip %s"
279 " rev dst ip %s src/dst ports %"PRIu16"/%"PRIu16
280 " rev src/dst ports %"PRIu16"/%"PRIu16" zone/rev zone "
281 "%"PRIu16"/%"PRIu16" nw_proto/rev nw_proto "
282 "%"PRIu8"/%"PRIu8, log_msg, ip6_s, ip6_d, ip6_rs,
283 ip6_rd, ntohs(c->key.src.port), ntohs(c->key.dst.port),
284 ntohs(c->rev_key.src.port), ntohs(c->rev_key.dst.port),
285 c->key.zone, c->rev_key.zone, c->key.nw_proto,
286 c->rev_key.nw_proto);
287 }
288 }
289 }
290
291 /* Initializes the connection tracker 'ct'. The caller is responsible for
292 * calling 'conntrack_destroy()', when the instance is not needed anymore */
293 struct conntrack *
294 conntrack_init(void)
295 {
296 struct conntrack *ct = xzalloc(sizeof *ct);
297
298 ovs_rwlock_init(&ct->resources_lock);
299 ovs_rwlock_wrlock(&ct->resources_lock);
300 hmap_init(&ct->alg_expectations);
301 hindex_init(&ct->alg_expectation_refs);
302 ovs_rwlock_unlock(&ct->resources_lock);
303
304 ovs_mutex_init_adaptive(&ct->ct_lock);
305 ovs_mutex_lock(&ct->ct_lock);
306 cmap_init(&ct->conns);
307 for (unsigned i = 0; i < ARRAY_SIZE(ct->exp_lists); i++) {
308 ovs_list_init(&ct->exp_lists[i]);
309 }
310 hmap_init(&ct->zone_limits);
311 ct->zone_limit_seq = 0;
312 timeout_policy_init(ct);
313 ovs_mutex_unlock(&ct->ct_lock);
314
315 ct->hash_basis = random_uint32();
316 atomic_count_init(&ct->n_conn, 0);
317 atomic_init(&ct->n_conn_limit, DEFAULT_N_CONN_LIMIT);
318 atomic_init(&ct->tcp_seq_chk, true);
319 latch_init(&ct->clean_thread_exit);
320 ct->clean_thread = ovs_thread_create("ct_clean", clean_thread_main, ct);
321 ct->ipf = ipf_init();
322
323 return ct;
324 }
325
326 static uint32_t
327 zone_key_hash(int32_t zone, uint32_t basis)
328 {
329 size_t hash = hash_int((OVS_FORCE uint32_t) zone, basis);
330 return hash;
331 }
332
333 static struct zone_limit *
334 zone_limit_lookup(struct conntrack *ct, int32_t zone)
335 OVS_REQUIRES(ct->ct_lock)
336 {
337 uint32_t hash = zone_key_hash(zone, ct->hash_basis);
338 struct zone_limit *zl;
339 HMAP_FOR_EACH_IN_BUCKET (zl, node, hash, &ct->zone_limits) {
340 if (zl->czl.zone == zone) {
341 return zl;
342 }
343 }
344 return NULL;
345 }
346
347 static struct zone_limit *
348 zone_limit_lookup_or_default(struct conntrack *ct, int32_t zone)
349 OVS_REQUIRES(ct->ct_lock)
350 {
351 struct zone_limit *zl = zone_limit_lookup(ct, zone);
352 return zl ? zl : zone_limit_lookup(ct, DEFAULT_ZONE);
353 }
354
355 struct conntrack_zone_limit
356 zone_limit_get(struct conntrack *ct, int32_t zone)
357 {
358 ovs_mutex_lock(&ct->ct_lock);
359 struct conntrack_zone_limit czl = {DEFAULT_ZONE, 0, 0, 0};
360 struct zone_limit *zl = zone_limit_lookup_or_default(ct, zone);
361 if (zl) {
362 czl = zl->czl;
363 }
364 ovs_mutex_unlock(&ct->ct_lock);
365 return czl;
366 }
367
368 static int
369 zone_limit_create(struct conntrack *ct, int32_t zone, uint32_t limit)
370 OVS_REQUIRES(ct->ct_lock)
371 {
372 if (zone >= DEFAULT_ZONE && zone <= MAX_ZONE) {
373 struct zone_limit *zl = xzalloc(sizeof *zl);
374 zl->czl.limit = limit;
375 zl->czl.zone = zone;
376 zl->czl.zone_limit_seq = ct->zone_limit_seq++;
377 uint32_t hash = zone_key_hash(zone, ct->hash_basis);
378 hmap_insert(&ct->zone_limits, &zl->node, hash);
379 return 0;
380 } else {
381 return EINVAL;
382 }
383 }
384
385 int
386 zone_limit_update(struct conntrack *ct, int32_t zone, uint32_t limit)
387 {
388 int err = 0;
389 ovs_mutex_lock(&ct->ct_lock);
390 struct zone_limit *zl = zone_limit_lookup(ct, zone);
391 if (zl) {
392 zl->czl.limit = limit;
393 VLOG_INFO("Changed zone limit of %u for zone %d", limit, zone);
394 } else {
395 err = zone_limit_create(ct, zone, limit);
396 if (!err) {
397 VLOG_INFO("Created zone limit of %u for zone %d", limit, zone);
398 } else {
399 VLOG_WARN("Request to create zone limit for invalid zone %d",
400 zone);
401 }
402 }
403 ovs_mutex_unlock(&ct->ct_lock);
404 return err;
405 }
406
407 static void
408 zone_limit_clean(struct conntrack *ct, struct zone_limit *zl)
409 OVS_REQUIRES(ct->ct_lock)
410 {
411 hmap_remove(&ct->zone_limits, &zl->node);
412 free(zl);
413 }
414
415 int
416 zone_limit_delete(struct conntrack *ct, uint16_t zone)
417 {
418 ovs_mutex_lock(&ct->ct_lock);
419 struct zone_limit *zl = zone_limit_lookup(ct, zone);
420 if (zl) {
421 zone_limit_clean(ct, zl);
422 VLOG_INFO("Deleted zone limit for zone %d", zone);
423 } else {
424 VLOG_INFO("Attempted delete of non-existent zone limit: zone %d",
425 zone);
426 }
427 ovs_mutex_unlock(&ct->ct_lock);
428 return 0;
429 }
430
431 static void
432 conn_clean_cmn(struct conntrack *ct, struct conn *conn)
433 OVS_REQUIRES(ct->ct_lock)
434 {
435 if (conn->alg) {
436 expectation_clean(ct, &conn->key);
437 }
438
439 uint32_t hash = conn_key_hash(&conn->key, ct->hash_basis);
440 cmap_remove(&ct->conns, &conn->cm_node, hash);
441
442 struct zone_limit *zl = zone_limit_lookup(ct, conn->admit_zone);
443 if (zl && zl->czl.zone_limit_seq == conn->zone_limit_seq) {
444 zl->czl.count--;
445 }
446 }
447
448 /* Must be called with 'conn' of 'conn_type' CT_CONN_TYPE_DEFAULT. Also
449 * removes the associated nat 'conn' from the lookup datastructures. */
450 static void
451 conn_clean(struct conntrack *ct, struct conn *conn)
452 OVS_REQUIRES(ct->ct_lock)
453 {
454 ovs_assert(conn->conn_type == CT_CONN_TYPE_DEFAULT);
455
456 conn_clean_cmn(ct, conn);
457 if (conn->nat_conn) {
458 uint32_t hash = conn_key_hash(&conn->nat_conn->key, ct->hash_basis);
459 cmap_remove(&ct->conns, &conn->nat_conn->cm_node, hash);
460 }
461 ovs_list_remove(&conn->exp_node);
462 conn->cleaned = true;
463 ovsrcu_postpone(delete_conn, conn);
464 atomic_count_dec(&ct->n_conn);
465 }
466
467 static void
468 conn_clean_one(struct conntrack *ct, struct conn *conn)
469 OVS_REQUIRES(ct->ct_lock)
470 {
471 conn_clean_cmn(ct, conn);
472 if (conn->conn_type == CT_CONN_TYPE_DEFAULT) {
473 ovs_list_remove(&conn->exp_node);
474 conn->cleaned = true;
475 atomic_count_dec(&ct->n_conn);
476 }
477 ovsrcu_postpone(delete_conn_one, conn);
478 }
479
480 /* Destroys the connection tracker 'ct' and frees all the allocated memory.
481 * The caller of this function must already have shut down packet input
482 * and PMD threads (which would have been quiesced). */
483 void
484 conntrack_destroy(struct conntrack *ct)
485 {
486 struct conn *conn;
487 latch_set(&ct->clean_thread_exit);
488 pthread_join(ct->clean_thread, NULL);
489 latch_destroy(&ct->clean_thread_exit);
490
491 ovs_mutex_lock(&ct->ct_lock);
492 CMAP_FOR_EACH (conn, cm_node, &ct->conns) {
493 conn_clean_one(ct, conn);
494 }
495 cmap_destroy(&ct->conns);
496
497 struct zone_limit *zl;
498 HMAP_FOR_EACH_POP (zl, node, &ct->zone_limits) {
499 free(zl);
500 }
501 hmap_destroy(&ct->zone_limits);
502
503 struct timeout_policy *tp;
504 HMAP_FOR_EACH_POP (tp, node, &ct->timeout_policies) {
505 free(tp);
506 }
507 hmap_destroy(&ct->timeout_policies);
508
509 ovs_mutex_unlock(&ct->ct_lock);
510 ovs_mutex_destroy(&ct->ct_lock);
511
512 ovs_rwlock_wrlock(&ct->resources_lock);
513 struct alg_exp_node *alg_exp_node;
514 HMAP_FOR_EACH_POP (alg_exp_node, node, &ct->alg_expectations) {
515 free(alg_exp_node);
516 }
517 hmap_destroy(&ct->alg_expectations);
518 hindex_destroy(&ct->alg_expectation_refs);
519 ovs_rwlock_unlock(&ct->resources_lock);
520 ovs_rwlock_destroy(&ct->resources_lock);
521
522 ipf_destroy(ct->ipf);
523 free(ct);
524 }
525 \f
526
527 static bool
528 conn_key_lookup(struct conntrack *ct, const struct conn_key *key,
529 uint32_t hash, long long now, struct conn **conn_out,
530 bool *reply)
531 {
532 struct conn *conn;
533 bool found = false;
534
535 CMAP_FOR_EACH_WITH_HASH (conn, cm_node, hash, &ct->conns) {
536 if (!conn_key_cmp(&conn->key, key) && !conn_expired(conn, now)) {
537 found = true;
538 if (reply) {
539 *reply = false;
540 }
541 break;
542 }
543 if (!conn_key_cmp(&conn->rev_key, key) && !conn_expired(conn, now)) {
544 found = true;
545 if (reply) {
546 *reply = true;
547 }
548 break;
549 }
550 }
551
552 if (found && conn_out) {
553 *conn_out = conn;
554 } else if (conn_out) {
555 *conn_out = NULL;
556 }
557 return found;
558 }
559
560 static bool
561 conn_lookup(struct conntrack *ct, const struct conn_key *key,
562 long long now, struct conn **conn_out, bool *reply)
563 {
564 uint32_t hash = conn_key_hash(key, ct->hash_basis);
565 return conn_key_lookup(ct, key, hash, now, conn_out, reply);
566 }
567
568 static void
569 write_ct_md(struct dp_packet *pkt, uint16_t zone, const struct conn *conn,
570 const struct conn_key *key, const struct alg_exp_node *alg_exp)
571 {
572 pkt->md.ct_state |= CS_TRACKED;
573 pkt->md.ct_zone = zone;
574
575 if (conn) {
576 ovs_mutex_lock(&conn->lock);
577 pkt->md.ct_mark = conn->mark;
578 pkt->md.ct_label = conn->label;
579 ovs_mutex_unlock(&conn->lock);
580 } else {
581 pkt->md.ct_mark = 0;
582 pkt->md.ct_label = OVS_U128_ZERO;
583 }
584
585 /* Use the original direction tuple if we have it. */
586 if (conn) {
587 if (conn->alg_related) {
588 key = &conn->parent_key;
589 } else {
590 key = &conn->key;
591 }
592 } else if (alg_exp) {
593 pkt->md.ct_mark = alg_exp->parent_mark;
594 pkt->md.ct_label = alg_exp->parent_label;
595 key = &alg_exp->parent_key;
596 }
597
598 pkt->md.ct_orig_tuple_ipv6 = false;
599
600 if (key) {
601 if (key->dl_type == htons(ETH_TYPE_IP)) {
602 pkt->md.ct_orig_tuple.ipv4 = (struct ovs_key_ct_tuple_ipv4) {
603 key->src.addr.ipv4,
604 key->dst.addr.ipv4,
605 key->nw_proto != IPPROTO_ICMP
606 ? key->src.port : htons(key->src.icmp_type),
607 key->nw_proto != IPPROTO_ICMP
608 ? key->dst.port : htons(key->src.icmp_code),
609 key->nw_proto,
610 };
611 } else {
612 pkt->md.ct_orig_tuple_ipv6 = true;
613 pkt->md.ct_orig_tuple.ipv6 = (struct ovs_key_ct_tuple_ipv6) {
614 key->src.addr.ipv6,
615 key->dst.addr.ipv6,
616 key->nw_proto != IPPROTO_ICMPV6
617 ? key->src.port : htons(key->src.icmp_type),
618 key->nw_proto != IPPROTO_ICMPV6
619 ? key->dst.port : htons(key->src.icmp_code),
620 key->nw_proto,
621 };
622 }
623 } else {
624 memset(&pkt->md.ct_orig_tuple, 0, sizeof pkt->md.ct_orig_tuple);
625 }
626 }
627
628 static uint8_t
629 get_ip_proto(const struct dp_packet *pkt)
630 {
631 uint8_t ip_proto;
632 struct eth_header *l2 = dp_packet_eth(pkt);
633 if (l2->eth_type == htons(ETH_TYPE_IPV6)) {
634 struct ovs_16aligned_ip6_hdr *nh6 = dp_packet_l3(pkt);
635 ip_proto = nh6->ip6_ctlun.ip6_un1.ip6_un1_nxt;
636 } else {
637 struct ip_header *l3_hdr = dp_packet_l3(pkt);
638 ip_proto = l3_hdr->ip_proto;
639 }
640
641 return ip_proto;
642 }
643
644 static bool
645 is_ftp_ctl(const enum ct_alg_ctl_type ct_alg_ctl)
646 {
647 return ct_alg_ctl == CT_ALG_CTL_FTP;
648 }
649
650 static enum ct_alg_ctl_type
651 get_alg_ctl_type(const struct dp_packet *pkt, ovs_be16 tp_src, ovs_be16 tp_dst,
652 const char *helper)
653 {
654 /* CT_IPPORT_FTP/TFTP is used because IPPORT_FTP/TFTP in not defined
655 * in OSX, at least in in.h. Since these values will never change, remove
656 * the external dependency. */
657 enum { CT_IPPORT_FTP = 21 };
658 enum { CT_IPPORT_TFTP = 69 };
659 uint8_t ip_proto = get_ip_proto(pkt);
660 struct udp_header *uh = dp_packet_l4(pkt);
661 struct tcp_header *th = dp_packet_l4(pkt);
662 ovs_be16 ftp_src_port = htons(CT_IPPORT_FTP);
663 ovs_be16 ftp_dst_port = htons(CT_IPPORT_FTP);
664 ovs_be16 tftp_dst_port = htons(CT_IPPORT_TFTP);
665
666 if (OVS_UNLIKELY(tp_dst)) {
667 if (helper && !strncmp(helper, "ftp", strlen("ftp"))) {
668 ftp_dst_port = tp_dst;
669 } else if (helper && !strncmp(helper, "tftp", strlen("tftp"))) {
670 tftp_dst_port = tp_dst;
671 }
672 } else if (OVS_UNLIKELY(tp_src)) {
673 if (helper && !strncmp(helper, "ftp", strlen("ftp"))) {
674 ftp_src_port = tp_src;
675 }
676 }
677
678 if (ip_proto == IPPROTO_UDP && uh->udp_dst == tftp_dst_port) {
679 return CT_ALG_CTL_TFTP;
680 } else if (ip_proto == IPPROTO_TCP &&
681 (th->tcp_src == ftp_src_port || th->tcp_dst == ftp_dst_port)) {
682 return CT_ALG_CTL_FTP;
683 }
684 return CT_ALG_CTL_NONE;
685 }
686
687 static bool
688 alg_src_ip_wc(enum ct_alg_ctl_type alg_ctl_type)
689 {
690 if (alg_ctl_type == CT_ALG_CTL_SIP) {
691 return true;
692 }
693 return false;
694 }
695
696 static void
697 handle_alg_ctl(struct conntrack *ct, const struct conn_lookup_ctx *ctx,
698 struct dp_packet *pkt, enum ct_alg_ctl_type ct_alg_ctl,
699 struct conn *conn, long long now, bool nat)
700 {
701 /* ALG control packet handling with expectation creation. */
702 if (OVS_UNLIKELY(alg_helpers[ct_alg_ctl] && conn && conn->alg)) {
703 ovs_mutex_lock(&conn->lock);
704 alg_helpers[ct_alg_ctl](ct, ctx, pkt, conn, now, CT_FTP_CTL_INTEREST,
705 nat);
706 ovs_mutex_unlock(&conn->lock);
707 }
708 }
709
710 static void
711 pat_packet(struct dp_packet *pkt, const struct conn *conn)
712 {
713 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
714 if (conn->key.nw_proto == IPPROTO_TCP) {
715 struct tcp_header *th = dp_packet_l4(pkt);
716 packet_set_tcp_port(pkt, conn->rev_key.dst.port, th->tcp_dst);
717 } else if (conn->key.nw_proto == IPPROTO_UDP) {
718 struct udp_header *uh = dp_packet_l4(pkt);
719 packet_set_udp_port(pkt, conn->rev_key.dst.port, uh->udp_dst);
720 }
721 } else if (conn->nat_info->nat_action & NAT_ACTION_DST) {
722 if (conn->key.nw_proto == IPPROTO_TCP) {
723 struct tcp_header *th = dp_packet_l4(pkt);
724 packet_set_tcp_port(pkt, th->tcp_src, conn->rev_key.src.port);
725 } else if (conn->key.nw_proto == IPPROTO_UDP) {
726 struct udp_header *uh = dp_packet_l4(pkt);
727 packet_set_udp_port(pkt, uh->udp_src, conn->rev_key.src.port);
728 }
729 }
730 }
731
732 static void
733 nat_packet(struct dp_packet *pkt, const struct conn *conn, bool related)
734 {
735 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
736 pkt->md.ct_state |= CS_SRC_NAT;
737 if (conn->key.dl_type == htons(ETH_TYPE_IP)) {
738 struct ip_header *nh = dp_packet_l3(pkt);
739 packet_set_ipv4_addr(pkt, &nh->ip_src,
740 conn->rev_key.dst.addr.ipv4);
741 } else {
742 struct ovs_16aligned_ip6_hdr *nh6 = dp_packet_l3(pkt);
743 packet_set_ipv6_addr(pkt, conn->key.nw_proto,
744 nh6->ip6_src.be32,
745 &conn->rev_key.dst.addr.ipv6, true);
746 }
747 if (!related) {
748 pat_packet(pkt, conn);
749 }
750 } else if (conn->nat_info->nat_action & NAT_ACTION_DST) {
751 pkt->md.ct_state |= CS_DST_NAT;
752 if (conn->key.dl_type == htons(ETH_TYPE_IP)) {
753 struct ip_header *nh = dp_packet_l3(pkt);
754 packet_set_ipv4_addr(pkt, &nh->ip_dst,
755 conn->rev_key.src.addr.ipv4);
756 } else {
757 struct ovs_16aligned_ip6_hdr *nh6 = dp_packet_l3(pkt);
758 packet_set_ipv6_addr(pkt, conn->key.nw_proto,
759 nh6->ip6_dst.be32,
760 &conn->rev_key.src.addr.ipv6, true);
761 }
762 if (!related) {
763 pat_packet(pkt, conn);
764 }
765 }
766 }
767
768 static void
769 un_pat_packet(struct dp_packet *pkt, const struct conn *conn)
770 {
771 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
772 if (conn->key.nw_proto == IPPROTO_TCP) {
773 struct tcp_header *th = dp_packet_l4(pkt);
774 packet_set_tcp_port(pkt, th->tcp_src, conn->key.src.port);
775 } else if (conn->key.nw_proto == IPPROTO_UDP) {
776 struct udp_header *uh = dp_packet_l4(pkt);
777 packet_set_udp_port(pkt, uh->udp_src, conn->key.src.port);
778 }
779 } else if (conn->nat_info->nat_action & NAT_ACTION_DST) {
780 if (conn->key.nw_proto == IPPROTO_TCP) {
781 struct tcp_header *th = dp_packet_l4(pkt);
782 packet_set_tcp_port(pkt, conn->key.dst.port, th->tcp_dst);
783 } else if (conn->key.nw_proto == IPPROTO_UDP) {
784 struct udp_header *uh = dp_packet_l4(pkt);
785 packet_set_udp_port(pkt, conn->key.dst.port, uh->udp_dst);
786 }
787 }
788 }
789
790 static void
791 reverse_pat_packet(struct dp_packet *pkt, const struct conn *conn)
792 {
793 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
794 if (conn->key.nw_proto == IPPROTO_TCP) {
795 struct tcp_header *th_in = dp_packet_l4(pkt);
796 packet_set_tcp_port(pkt, conn->key.src.port,
797 th_in->tcp_dst);
798 } else if (conn->key.nw_proto == IPPROTO_UDP) {
799 struct udp_header *uh_in = dp_packet_l4(pkt);
800 packet_set_udp_port(pkt, conn->key.src.port,
801 uh_in->udp_dst);
802 }
803 } else if (conn->nat_info->nat_action & NAT_ACTION_DST) {
804 if (conn->key.nw_proto == IPPROTO_TCP) {
805 struct tcp_header *th_in = dp_packet_l4(pkt);
806 packet_set_tcp_port(pkt, th_in->tcp_src,
807 conn->key.dst.port);
808 } else if (conn->key.nw_proto == IPPROTO_UDP) {
809 struct udp_header *uh_in = dp_packet_l4(pkt);
810 packet_set_udp_port(pkt, uh_in->udp_src,
811 conn->key.dst.port);
812 }
813 }
814 }
815
816 static void
817 reverse_nat_packet(struct dp_packet *pkt, const struct conn *conn)
818 {
819 char *tail = dp_packet_tail(pkt);
820 uint8_t pad = dp_packet_l2_pad_size(pkt);
821 struct conn_key inner_key;
822 const char *inner_l4 = NULL;
823 uint16_t orig_l3_ofs = pkt->l3_ofs;
824 uint16_t orig_l4_ofs = pkt->l4_ofs;
825
826 if (conn->key.dl_type == htons(ETH_TYPE_IP)) {
827 struct ip_header *nh = dp_packet_l3(pkt);
828 struct icmp_header *icmp = dp_packet_l4(pkt);
829 struct ip_header *inner_l3 = (struct ip_header *) (icmp + 1);
830 /* This call is already verified to succeed during the code path from
831 * 'conn_key_extract()' which calls 'extract_l4_icmp()'. */
832 extract_l3_ipv4(&inner_key, inner_l3, tail - ((char *)inner_l3) - pad,
833 &inner_l4, false);
834 pkt->l3_ofs += (char *) inner_l3 - (char *) nh;
835 pkt->l4_ofs += inner_l4 - (char *) icmp;
836
837 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
838 packet_set_ipv4_addr(pkt, &inner_l3->ip_src,
839 conn->key.src.addr.ipv4);
840 } else if (conn->nat_info->nat_action & NAT_ACTION_DST) {
841 packet_set_ipv4_addr(pkt, &inner_l3->ip_dst,
842 conn->key.dst.addr.ipv4);
843 }
844
845 reverse_pat_packet(pkt, conn);
846 icmp->icmp_csum = 0;
847 icmp->icmp_csum = csum(icmp, tail - (char *) icmp - pad);
848 } else {
849 struct ovs_16aligned_ip6_hdr *nh6 = dp_packet_l3(pkt);
850 struct icmp6_data_header *icmp6 = dp_packet_l4(pkt);
851 struct ovs_16aligned_ip6_hdr *inner_l3_6 =
852 (struct ovs_16aligned_ip6_hdr *) (icmp6 + 1);
853 /* This call is already verified to succeed during the code path from
854 * 'conn_key_extract()' which calls 'extract_l4_icmp6()'. */
855 extract_l3_ipv6(&inner_key, inner_l3_6,
856 tail - ((char *)inner_l3_6) - pad,
857 &inner_l4);
858 pkt->l3_ofs += (char *) inner_l3_6 - (char *) nh6;
859 pkt->l4_ofs += inner_l4 - (char *) icmp6;
860
861 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
862 packet_set_ipv6_addr(pkt, conn->key.nw_proto,
863 inner_l3_6->ip6_src.be32,
864 &conn->key.src.addr.ipv6, true);
865 } else if (conn->nat_info->nat_action & NAT_ACTION_DST) {
866 packet_set_ipv6_addr(pkt, conn->key.nw_proto,
867 inner_l3_6->ip6_dst.be32,
868 &conn->key.dst.addr.ipv6, true);
869 }
870 reverse_pat_packet(pkt, conn);
871 icmp6->icmp6_base.icmp6_cksum = 0;
872 icmp6->icmp6_base.icmp6_cksum = packet_csum_upperlayer6(nh6, icmp6,
873 IPPROTO_ICMPV6, tail - (char *) icmp6 - pad);
874 }
875 pkt->l3_ofs = orig_l3_ofs;
876 pkt->l4_ofs = orig_l4_ofs;
877 }
878
879 static void
880 un_nat_packet(struct dp_packet *pkt, const struct conn *conn,
881 bool related)
882 {
883 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
884 pkt->md.ct_state |= CS_DST_NAT;
885 if (conn->key.dl_type == htons(ETH_TYPE_IP)) {
886 struct ip_header *nh = dp_packet_l3(pkt);
887 packet_set_ipv4_addr(pkt, &nh->ip_dst,
888 conn->key.src.addr.ipv4);
889 } else {
890 struct ovs_16aligned_ip6_hdr *nh6 = dp_packet_l3(pkt);
891 packet_set_ipv6_addr(pkt, conn->key.nw_proto,
892 nh6->ip6_dst.be32,
893 &conn->key.src.addr.ipv6, true);
894 }
895
896 if (OVS_UNLIKELY(related)) {
897 reverse_nat_packet(pkt, conn);
898 } else {
899 un_pat_packet(pkt, conn);
900 }
901 } else if (conn->nat_info->nat_action & NAT_ACTION_DST) {
902 pkt->md.ct_state |= CS_SRC_NAT;
903 if (conn->key.dl_type == htons(ETH_TYPE_IP)) {
904 struct ip_header *nh = dp_packet_l3(pkt);
905 packet_set_ipv4_addr(pkt, &nh->ip_src,
906 conn->key.dst.addr.ipv4);
907 } else {
908 struct ovs_16aligned_ip6_hdr *nh6 = dp_packet_l3(pkt);
909 packet_set_ipv6_addr(pkt, conn->key.nw_proto,
910 nh6->ip6_src.be32,
911 &conn->key.dst.addr.ipv6, true);
912 }
913
914 if (OVS_UNLIKELY(related)) {
915 reverse_nat_packet(pkt, conn);
916 } else {
917 un_pat_packet(pkt, conn);
918 }
919 }
920 }
921
922 static void
923 conn_seq_skew_set(struct conntrack *ct, const struct conn *conn_in,
924 long long now, int seq_skew, bool seq_skew_dir)
925 OVS_NO_THREAD_SAFETY_ANALYSIS
926 {
927 struct conn *conn;
928 ovs_mutex_unlock(&conn_in->lock);
929 conn_lookup(ct, &conn_in->key, now, &conn, NULL);
930 ovs_mutex_lock(&conn_in->lock);
931
932 if (conn && seq_skew) {
933 conn->seq_skew = seq_skew;
934 conn->seq_skew_dir = seq_skew_dir;
935 }
936 }
937
938 static bool
939 ct_verify_helper(const char *helper, enum ct_alg_ctl_type ct_alg_ctl)
940 {
941 if (ct_alg_ctl == CT_ALG_CTL_NONE) {
942 return true;
943 } else if (helper) {
944 if ((ct_alg_ctl == CT_ALG_CTL_FTP) &&
945 !strncmp(helper, "ftp", strlen("ftp"))) {
946 return true;
947 } else if ((ct_alg_ctl == CT_ALG_CTL_TFTP) &&
948 !strncmp(helper, "tftp", strlen("tftp"))) {
949 return true;
950 } else {
951 return false;
952 }
953 } else {
954 return false;
955 }
956 }
957
958 static struct conn *
959 conn_not_found(struct conntrack *ct, struct dp_packet *pkt,
960 struct conn_lookup_ctx *ctx, bool commit, long long now,
961 const struct nat_action_info_t *nat_action_info,
962 const char *helper, const struct alg_exp_node *alg_exp,
963 enum ct_alg_ctl_type ct_alg_ctl, uint32_t tp_id)
964 OVS_REQUIRES(ct->ct_lock)
965 {
966 struct conn *nc = NULL;
967 struct conn *nat_conn = NULL;
968
969 if (!valid_new(pkt, &ctx->key)) {
970 pkt->md.ct_state = CS_INVALID;
971 return nc;
972 }
973
974 pkt->md.ct_state = CS_NEW;
975
976 if (alg_exp) {
977 pkt->md.ct_state |= CS_RELATED;
978 }
979
980 if (commit) {
981 struct zone_limit *zl = zone_limit_lookup_or_default(ct,
982 ctx->key.zone);
983 if (zl && zl->czl.count >= zl->czl.limit) {
984 return nc;
985 }
986
987 unsigned int n_conn_limit;
988 atomic_read_relaxed(&ct->n_conn_limit, &n_conn_limit);
989 if (atomic_count_get(&ct->n_conn) >= n_conn_limit) {
990 COVERAGE_INC(conntrack_full);
991 return nc;
992 }
993
994 nc = new_conn(ct, pkt, &ctx->key, now, tp_id);
995 memcpy(&nc->key, &ctx->key, sizeof nc->key);
996 memcpy(&nc->rev_key, &nc->key, sizeof nc->rev_key);
997 conn_key_reverse(&nc->rev_key);
998
999 if (ct_verify_helper(helper, ct_alg_ctl)) {
1000 nc->alg = nullable_xstrdup(helper);
1001 }
1002
1003 if (alg_exp) {
1004 nc->alg_related = true;
1005 nc->mark = alg_exp->parent_mark;
1006 nc->label = alg_exp->parent_label;
1007 nc->parent_key = alg_exp->parent_key;
1008 }
1009
1010 if (nat_action_info) {
1011 nc->nat_info = xmemdup(nat_action_info, sizeof *nc->nat_info);
1012 nat_conn = xzalloc(sizeof *nat_conn);
1013
1014 if (alg_exp) {
1015 if (alg_exp->nat_rpl_dst) {
1016 nc->rev_key.dst.addr = alg_exp->alg_nat_repl_addr;
1017 nc->nat_info->nat_action = NAT_ACTION_SRC;
1018 } else {
1019 nc->rev_key.src.addr = alg_exp->alg_nat_repl_addr;
1020 nc->nat_info->nat_action = NAT_ACTION_DST;
1021 }
1022 } else {
1023 memcpy(nat_conn, nc, sizeof *nat_conn);
1024 bool nat_res = nat_select_range_tuple(ct, nc, nat_conn);
1025
1026 if (!nat_res) {
1027 goto nat_res_exhaustion;
1028 }
1029
1030 /* Update nc with nat adjustments made to nat_conn by
1031 * nat_select_range_tuple(). */
1032 memcpy(nc, nat_conn, sizeof *nc);
1033 }
1034
1035 nat_packet(pkt, nc, ctx->icmp_related);
1036 memcpy(&nat_conn->key, &nc->rev_key, sizeof nat_conn->key);
1037 memcpy(&nat_conn->rev_key, &nc->key, sizeof nat_conn->rev_key);
1038 nat_conn->conn_type = CT_CONN_TYPE_UN_NAT;
1039 nat_conn->nat_info = NULL;
1040 nat_conn->alg = NULL;
1041 nat_conn->nat_conn = NULL;
1042 uint32_t nat_hash = conn_key_hash(&nat_conn->key, ct->hash_basis);
1043 cmap_insert(&ct->conns, &nat_conn->cm_node, nat_hash);
1044 }
1045
1046 nc->nat_conn = nat_conn;
1047 ovs_mutex_init_adaptive(&nc->lock);
1048 nc->conn_type = CT_CONN_TYPE_DEFAULT;
1049 cmap_insert(&ct->conns, &nc->cm_node, ctx->hash);
1050 atomic_count_inc(&ct->n_conn);
1051 ctx->conn = nc; /* For completeness. */
1052 if (zl) {
1053 nc->admit_zone = zl->czl.zone;
1054 nc->zone_limit_seq = zl->czl.zone_limit_seq;
1055 zl->czl.count++;
1056 } else {
1057 nc->admit_zone = INVALID_ZONE;
1058 }
1059 }
1060
1061 return nc;
1062
1063 /* This would be a user error or a DOS attack. A user error is prevented
1064 * by allocating enough combinations of NAT addresses when combined with
1065 * ephemeral ports. A DOS attack should be protected against with
1066 * firewall rules or a separate firewall. Also using zone partitioning
1067 * can limit DoS impact. */
1068 nat_res_exhaustion:
1069 free(nat_conn);
1070 ovs_list_remove(&nc->exp_node);
1071 delete_conn_cmn(nc);
1072 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
1073 VLOG_WARN_RL(&rl, "Unable to NAT due to tuple space exhaustion - "
1074 "if DoS attack, use firewalling and/or zone partitioning.");
1075 return NULL;
1076 }
1077
1078 static bool
1079 conn_update_state(struct conntrack *ct, struct dp_packet *pkt,
1080 struct conn_lookup_ctx *ctx, struct conn *conn,
1081 long long now)
1082 {
1083 ovs_assert(conn->conn_type == CT_CONN_TYPE_DEFAULT);
1084 bool create_new_conn = false;
1085
1086 if (ctx->icmp_related) {
1087 pkt->md.ct_state |= CS_RELATED;
1088 if (ctx->reply) {
1089 pkt->md.ct_state |= CS_REPLY_DIR;
1090 }
1091 } else {
1092 if (conn->alg_related) {
1093 pkt->md.ct_state |= CS_RELATED;
1094 }
1095
1096 enum ct_update_res res = conn_update(ct, conn, pkt, ctx, now);
1097
1098 switch (res) {
1099 case CT_UPDATE_VALID:
1100 pkt->md.ct_state |= CS_ESTABLISHED;
1101 pkt->md.ct_state &= ~CS_NEW;
1102 if (ctx->reply) {
1103 pkt->md.ct_state |= CS_REPLY_DIR;
1104 }
1105 break;
1106 case CT_UPDATE_INVALID:
1107 pkt->md.ct_state = CS_INVALID;
1108 break;
1109 case CT_UPDATE_NEW:
1110 ovs_mutex_lock(&ct->ct_lock);
1111 if (conn_lookup(ct, &conn->key, now, NULL, NULL)) {
1112 conn_clean(ct, conn);
1113 }
1114 ovs_mutex_unlock(&ct->ct_lock);
1115 create_new_conn = true;
1116 break;
1117 case CT_UPDATE_VALID_NEW:
1118 pkt->md.ct_state |= CS_NEW;
1119 break;
1120 default:
1121 OVS_NOT_REACHED();
1122 }
1123 }
1124 return create_new_conn;
1125 }
1126
1127 static void
1128 handle_nat(struct dp_packet *pkt, struct conn *conn,
1129 uint16_t zone, bool reply, bool related)
1130 {
1131 if (conn->nat_info &&
1132 (!(pkt->md.ct_state & (CS_SRC_NAT | CS_DST_NAT)) ||
1133 (pkt->md.ct_state & (CS_SRC_NAT | CS_DST_NAT) &&
1134 zone != pkt->md.ct_zone))) {
1135
1136 if (pkt->md.ct_state & (CS_SRC_NAT | CS_DST_NAT)) {
1137 pkt->md.ct_state &= ~(CS_SRC_NAT | CS_DST_NAT);
1138 }
1139 if (reply) {
1140 un_nat_packet(pkt, conn, related);
1141 } else {
1142 nat_packet(pkt, conn, related);
1143 }
1144 }
1145 }
1146
1147 static bool
1148 check_orig_tuple(struct conntrack *ct, struct dp_packet *pkt,
1149 struct conn_lookup_ctx *ctx_in, long long now,
1150 struct conn **conn,
1151 const struct nat_action_info_t *nat_action_info)
1152 {
1153 if (!(pkt->md.ct_state & (CS_SRC_NAT | CS_DST_NAT)) ||
1154 (ctx_in->key.dl_type == htons(ETH_TYPE_IP) &&
1155 !pkt->md.ct_orig_tuple.ipv4.ipv4_proto) ||
1156 (ctx_in->key.dl_type == htons(ETH_TYPE_IPV6) &&
1157 !pkt->md.ct_orig_tuple.ipv6.ipv6_proto) ||
1158 nat_action_info) {
1159 return false;
1160 }
1161
1162 struct conn_key key;
1163 memset(&key, 0 , sizeof key);
1164
1165 if (ctx_in->key.dl_type == htons(ETH_TYPE_IP)) {
1166 key.src.addr.ipv4 = pkt->md.ct_orig_tuple.ipv4.ipv4_src;
1167 key.dst.addr.ipv4 = pkt->md.ct_orig_tuple.ipv4.ipv4_dst;
1168
1169 if (ctx_in->key.nw_proto == IPPROTO_ICMP) {
1170 key.src.icmp_id = ctx_in->key.src.icmp_id;
1171 key.dst.icmp_id = ctx_in->key.dst.icmp_id;
1172 uint16_t src_port = ntohs(pkt->md.ct_orig_tuple.ipv4.src_port);
1173 key.src.icmp_type = (uint8_t) src_port;
1174 key.dst.icmp_type = reverse_icmp_type(key.src.icmp_type);
1175 } else {
1176 key.src.port = pkt->md.ct_orig_tuple.ipv4.src_port;
1177 key.dst.port = pkt->md.ct_orig_tuple.ipv4.dst_port;
1178 }
1179 key.nw_proto = pkt->md.ct_orig_tuple.ipv4.ipv4_proto;
1180 } else {
1181 key.src.addr.ipv6 = pkt->md.ct_orig_tuple.ipv6.ipv6_src;
1182 key.dst.addr.ipv6 = pkt->md.ct_orig_tuple.ipv6.ipv6_dst;
1183
1184 if (ctx_in->key.nw_proto == IPPROTO_ICMPV6) {
1185 key.src.icmp_id = ctx_in->key.src.icmp_id;
1186 key.dst.icmp_id = ctx_in->key.dst.icmp_id;
1187 uint16_t src_port = ntohs(pkt->md.ct_orig_tuple.ipv6.src_port);
1188 key.src.icmp_type = (uint8_t) src_port;
1189 key.dst.icmp_type = reverse_icmp6_type(key.src.icmp_type);
1190 } else {
1191 key.src.port = pkt->md.ct_orig_tuple.ipv6.src_port;
1192 key.dst.port = pkt->md.ct_orig_tuple.ipv6.dst_port;
1193 }
1194 key.nw_proto = pkt->md.ct_orig_tuple.ipv6.ipv6_proto;
1195 }
1196
1197 key.dl_type = ctx_in->key.dl_type;
1198 key.zone = pkt->md.ct_zone;
1199 conn_lookup(ct, &key, now, conn, NULL);
1200 return *conn ? true : false;
1201 }
1202
1203 static bool
1204 conn_update_state_alg(struct conntrack *ct, struct dp_packet *pkt,
1205 struct conn_lookup_ctx *ctx, struct conn *conn,
1206 const struct nat_action_info_t *nat_action_info,
1207 enum ct_alg_ctl_type ct_alg_ctl, long long now,
1208 bool *create_new_conn)
1209 {
1210 if (is_ftp_ctl(ct_alg_ctl)) {
1211 /* Keep sequence tracking in sync with the source of the
1212 * sequence skew. */
1213 ovs_mutex_lock(&conn->lock);
1214 if (ctx->reply != conn->seq_skew_dir) {
1215 handle_ftp_ctl(ct, ctx, pkt, conn, now, CT_FTP_CTL_OTHER,
1216 !!nat_action_info);
1217 /* conn_update_state locks for unrelated fields, so unlock. */
1218 ovs_mutex_unlock(&conn->lock);
1219 *create_new_conn = conn_update_state(ct, pkt, ctx, conn, now);
1220 } else {
1221 /* conn_update_state locks for unrelated fields, so unlock. */
1222 ovs_mutex_unlock(&conn->lock);
1223 *create_new_conn = conn_update_state(ct, pkt, ctx, conn, now);
1224 ovs_mutex_lock(&conn->lock);
1225 if (*create_new_conn == false) {
1226 handle_ftp_ctl(ct, ctx, pkt, conn, now, CT_FTP_CTL_OTHER,
1227 !!nat_action_info);
1228 }
1229 ovs_mutex_unlock(&conn->lock);
1230 }
1231 return true;
1232 }
1233 return false;
1234 }
1235
1236 static void
1237 set_cached_conn(const struct nat_action_info_t *nat_action_info,
1238 const struct conn_lookup_ctx *ctx, struct conn *conn,
1239 struct dp_packet *pkt)
1240 {
1241 if (OVS_LIKELY(!nat_action_info)) {
1242 pkt->md.conn = conn;
1243 pkt->md.reply = ctx->reply;
1244 pkt->md.icmp_related = ctx->icmp_related;
1245 } else {
1246 pkt->md.conn = NULL;
1247 }
1248 }
1249
1250 static void
1251 process_one_fast(uint16_t zone, const uint32_t *setmark,
1252 const struct ovs_key_ct_labels *setlabel,
1253 const struct nat_action_info_t *nat_action_info,
1254 struct conn *conn, struct dp_packet *pkt)
1255 {
1256 if (nat_action_info) {
1257 handle_nat(pkt, conn, zone, pkt->md.reply, pkt->md.icmp_related);
1258 pkt->md.conn = NULL;
1259 }
1260
1261 pkt->md.ct_zone = zone;
1262 ovs_mutex_lock(&conn->lock);
1263 pkt->md.ct_mark = conn->mark;
1264 pkt->md.ct_label = conn->label;
1265 ovs_mutex_unlock(&conn->lock);
1266
1267 if (setmark) {
1268 set_mark(pkt, conn, setmark[0], setmark[1]);
1269 }
1270
1271 if (setlabel) {
1272 set_label(pkt, conn, &setlabel[0], &setlabel[1]);
1273 }
1274 }
1275
1276 static void
1277 process_one(struct conntrack *ct, struct dp_packet *pkt,
1278 struct conn_lookup_ctx *ctx, uint16_t zone,
1279 bool force, bool commit, long long now, const uint32_t *setmark,
1280 const struct ovs_key_ct_labels *setlabel,
1281 const struct nat_action_info_t *nat_action_info,
1282 ovs_be16 tp_src, ovs_be16 tp_dst, const char *helper,
1283 uint32_t tp_id)
1284 {
1285 /* Reset ct_state whenever entering a new zone. */
1286 if (pkt->md.ct_state && pkt->md.ct_zone != zone) {
1287 pkt->md.ct_state = 0;
1288 }
1289
1290 bool create_new_conn = false;
1291 conn_key_lookup(ct, &ctx->key, ctx->hash, now, &ctx->conn, &ctx->reply);
1292 struct conn *conn = ctx->conn;
1293
1294 /* Delete found entry if in wrong direction. 'force' implies commit. */
1295 if (OVS_UNLIKELY(force && ctx->reply && conn)) {
1296 ovs_mutex_lock(&ct->ct_lock);
1297 if (conn_lookup(ct, &conn->key, now, NULL, NULL)) {
1298 conn_clean(ct, conn);
1299 }
1300 ovs_mutex_unlock(&ct->ct_lock);
1301 conn = NULL;
1302 }
1303
1304 if (OVS_LIKELY(conn)) {
1305 if (conn->conn_type == CT_CONN_TYPE_UN_NAT) {
1306
1307 ctx->reply = true;
1308 struct conn *rev_conn = conn; /* Save for debugging. */
1309 uint32_t hash = conn_key_hash(&conn->rev_key, ct->hash_basis);
1310 conn_key_lookup(ct, &ctx->key, hash, now, &conn, &ctx->reply);
1311
1312 if (!conn) {
1313 pkt->md.ct_state |= CS_INVALID;
1314 write_ct_md(pkt, zone, NULL, NULL, NULL);
1315 char *log_msg = xasprintf("Missing parent conn %p", rev_conn);
1316 ct_print_conn_info(rev_conn, log_msg, VLL_INFO, true, true);
1317 free(log_msg);
1318 return;
1319 }
1320 }
1321 }
1322
1323 enum ct_alg_ctl_type ct_alg_ctl = get_alg_ctl_type(pkt, tp_src, tp_dst,
1324 helper);
1325
1326 if (OVS_LIKELY(conn)) {
1327 if (OVS_LIKELY(!conn_update_state_alg(ct, pkt, ctx, conn,
1328 nat_action_info,
1329 ct_alg_ctl, now,
1330 &create_new_conn))) {
1331 create_new_conn = conn_update_state(ct, pkt, ctx, conn, now);
1332 }
1333 if (nat_action_info && !create_new_conn) {
1334 handle_nat(pkt, conn, zone, ctx->reply, ctx->icmp_related);
1335 }
1336
1337 } else if (check_orig_tuple(ct, pkt, ctx, now, &conn, nat_action_info)) {
1338 create_new_conn = conn_update_state(ct, pkt, ctx, conn, now);
1339 } else {
1340 if (ctx->icmp_related) {
1341 /* An icmp related conn should always be found; no new
1342 connection is created based on an icmp related packet. */
1343 pkt->md.ct_state = CS_INVALID;
1344 } else {
1345 create_new_conn = true;
1346 }
1347 }
1348
1349 const struct alg_exp_node *alg_exp = NULL;
1350 struct alg_exp_node alg_exp_entry;
1351
1352 if (OVS_UNLIKELY(create_new_conn)) {
1353
1354 ovs_rwlock_rdlock(&ct->resources_lock);
1355 alg_exp = expectation_lookup(&ct->alg_expectations, &ctx->key,
1356 ct->hash_basis,
1357 alg_src_ip_wc(ct_alg_ctl));
1358 if (alg_exp) {
1359 memcpy(&alg_exp_entry, alg_exp, sizeof alg_exp_entry);
1360 alg_exp = &alg_exp_entry;
1361 }
1362 ovs_rwlock_unlock(&ct->resources_lock);
1363
1364 ovs_mutex_lock(&ct->ct_lock);
1365 if (!conn_lookup(ct, &ctx->key, now, NULL, NULL)) {
1366 conn = conn_not_found(ct, pkt, ctx, commit, now, nat_action_info,
1367 helper, alg_exp, ct_alg_ctl, tp_id);
1368 }
1369 ovs_mutex_unlock(&ct->ct_lock);
1370 }
1371
1372 write_ct_md(pkt, zone, conn, &ctx->key, alg_exp);
1373
1374 if (conn && setmark) {
1375 set_mark(pkt, conn, setmark[0], setmark[1]);
1376 }
1377
1378 if (conn && setlabel) {
1379 set_label(pkt, conn, &setlabel[0], &setlabel[1]);
1380 }
1381
1382 handle_alg_ctl(ct, ctx, pkt, ct_alg_ctl, conn, now, !!nat_action_info);
1383
1384 set_cached_conn(nat_action_info, ctx, conn, pkt);
1385 }
1386
1387 /* Sends the packets in '*pkt_batch' through the connection tracker 'ct'. All
1388 * the packets must have the same 'dl_type' (IPv4 or IPv6) and should have
1389 * the l3 and and l4 offset properly set. Performs fragment reassembly with
1390 * the help of ipf_preprocess_conntrack().
1391 *
1392 * If 'commit' is true, the packets are allowed to create new entries in the
1393 * connection tables. 'setmark', if not NULL, should point to a two
1394 * elements array containing a value and a mask to set the connection mark.
1395 * 'setlabel' behaves similarly for the connection label.*/
1396 int
1397 conntrack_execute(struct conntrack *ct, struct dp_packet_batch *pkt_batch,
1398 ovs_be16 dl_type, bool force, bool commit, uint16_t zone,
1399 const uint32_t *setmark,
1400 const struct ovs_key_ct_labels *setlabel,
1401 ovs_be16 tp_src, ovs_be16 tp_dst, const char *helper,
1402 const struct nat_action_info_t *nat_action_info,
1403 long long now, uint32_t tp_id)
1404 {
1405 ipf_preprocess_conntrack(ct->ipf, pkt_batch, now, dl_type, zone,
1406 ct->hash_basis);
1407
1408 struct dp_packet *packet;
1409 struct conn_lookup_ctx ctx;
1410
1411 DP_PACKET_BATCH_FOR_EACH (i, packet, pkt_batch) {
1412 struct conn *conn = packet->md.conn;
1413 if (OVS_UNLIKELY(packet->md.ct_state == CS_INVALID)) {
1414 write_ct_md(packet, zone, NULL, NULL, NULL);
1415 } else if (conn && conn->key.zone == zone && !force
1416 && !get_alg_ctl_type(packet, tp_src, tp_dst, helper)) {
1417 process_one_fast(zone, setmark, setlabel, nat_action_info,
1418 conn, packet);
1419 } else if (OVS_UNLIKELY(!conn_key_extract(ct, packet, dl_type, &ctx,
1420 zone))) {
1421 packet->md.ct_state = CS_INVALID;
1422 write_ct_md(packet, zone, NULL, NULL, NULL);
1423 } else {
1424 process_one(ct, packet, &ctx, zone, force, commit, now, setmark,
1425 setlabel, nat_action_info, tp_src, tp_dst, helper,
1426 tp_id);
1427 }
1428 }
1429
1430 ipf_postprocess_conntrack(ct->ipf, pkt_batch, now, dl_type);
1431
1432 return 0;
1433 }
1434
1435 void
1436 conntrack_clear(struct dp_packet *packet)
1437 {
1438 /* According to pkt_metadata_init(), ct_state == 0 is enough to make all of
1439 * the conntrack fields invalid. */
1440 packet->md.ct_state = 0;
1441 pkt_metadata_init_conn(&packet->md);
1442 }
1443
1444 static void
1445 set_mark(struct dp_packet *pkt, struct conn *conn, uint32_t val, uint32_t mask)
1446 {
1447 ovs_mutex_lock(&conn->lock);
1448 if (conn->alg_related) {
1449 pkt->md.ct_mark = conn->mark;
1450 } else {
1451 pkt->md.ct_mark = val | (pkt->md.ct_mark & ~(mask));
1452 conn->mark = pkt->md.ct_mark;
1453 }
1454 ovs_mutex_unlock(&conn->lock);
1455 }
1456
1457 static void
1458 set_label(struct dp_packet *pkt, struct conn *conn,
1459 const struct ovs_key_ct_labels *val,
1460 const struct ovs_key_ct_labels *mask)
1461 {
1462 ovs_mutex_lock(&conn->lock);
1463 if (conn->alg_related) {
1464 pkt->md.ct_label = conn->label;
1465 } else {
1466 ovs_u128 v, m;
1467
1468 memcpy(&v, val, sizeof v);
1469 memcpy(&m, mask, sizeof m);
1470
1471 pkt->md.ct_label.u64.lo = v.u64.lo
1472 | (pkt->md.ct_label.u64.lo & ~(m.u64.lo));
1473 pkt->md.ct_label.u64.hi = v.u64.hi
1474 | (pkt->md.ct_label.u64.hi & ~(m.u64.hi));
1475 conn->label = pkt->md.ct_label;
1476 }
1477 ovs_mutex_unlock(&conn->lock);
1478 }
1479
1480 \f
1481 /* Delete the expired connections from 'ctb', up to 'limit'. Returns the
1482 * earliest expiration time among the remaining connections in 'ctb'. Returns
1483 * LLONG_MAX if 'ctb' is empty. The return value might be smaller than 'now',
1484 * if 'limit' is reached */
1485 static long long
1486 ct_sweep(struct conntrack *ct, long long now, size_t limit)
1487 {
1488 struct conn *conn, *next;
1489 long long min_expiration = LLONG_MAX;
1490 size_t count = 0;
1491
1492 ovs_mutex_lock(&ct->ct_lock);
1493
1494 for (unsigned i = 0; i < N_CT_TM; i++) {
1495 LIST_FOR_EACH_SAFE (conn, next, exp_node, &ct->exp_lists[i]) {
1496 ovs_mutex_lock(&conn->lock);
1497 if (now < conn->expiration || count >= limit) {
1498 min_expiration = MIN(min_expiration, conn->expiration);
1499 ovs_mutex_unlock(&conn->lock);
1500 if (count >= limit) {
1501 /* Do not check other lists. */
1502 COVERAGE_INC(conntrack_long_cleanup);
1503 goto out;
1504 }
1505 break;
1506 } else {
1507 ovs_mutex_unlock(&conn->lock);
1508 conn_clean(ct, conn);
1509 }
1510 count++;
1511 }
1512 }
1513
1514 out:
1515 VLOG_DBG("conntrack cleanup %"PRIuSIZE" entries in %lld msec", count,
1516 time_msec() - now);
1517 ovs_mutex_unlock(&ct->ct_lock);
1518 return min_expiration;
1519 }
1520
1521 /* Cleans up old connection entries from 'ct'. Returns the time when the
1522 * next expiration might happen. The return value might be smaller than
1523 * 'now', meaning that an internal limit has been reached, and some expired
1524 * connections have not been deleted. */
1525 static long long
1526 conntrack_clean(struct conntrack *ct, long long now)
1527 {
1528 unsigned int n_conn_limit;
1529 atomic_read_relaxed(&ct->n_conn_limit, &n_conn_limit);
1530 size_t clean_max = n_conn_limit > 10 ? n_conn_limit / 10 : 1;
1531 long long min_exp = ct_sweep(ct, now, clean_max);
1532 long long next_wakeup = MIN(min_exp, now + CT_DPIF_NETDEV_TP_MIN);
1533
1534 return next_wakeup;
1535 }
1536
1537 /* Cleanup:
1538 *
1539 * We must call conntrack_clean() periodically. conntrack_clean() return
1540 * value gives an hint on when the next cleanup must be done (either because
1541 * there is an actual connection that expires, or because a new connection
1542 * might be created with the minimum timeout).
1543 *
1544 * The logic below has two goals:
1545 *
1546 * - We want to reduce the number of wakeups and batch connection cleanup
1547 * when the load is not very high. CT_CLEAN_INTERVAL ensures that if we
1548 * are coping with the current cleanup tasks, then we wait at least
1549 * 5 seconds to do further cleanup.
1550 *
1551 * - We don't want to keep the map locked too long, as we might prevent
1552 * traffic from flowing. CT_CLEAN_MIN_INTERVAL ensures that if cleanup is
1553 * behind, there is at least some 200ms blocks of time when the map will be
1554 * left alone, so the datapath can operate unhindered.
1555 */
1556 #define CT_CLEAN_INTERVAL 5000 /* 5 seconds */
1557 #define CT_CLEAN_MIN_INTERVAL 200 /* 0.2 seconds */
1558
1559 static void *
1560 clean_thread_main(void *f_)
1561 {
1562 struct conntrack *ct = f_;
1563
1564 while (!latch_is_set(&ct->clean_thread_exit)) {
1565 long long next_wake;
1566 long long now = time_msec();
1567 next_wake = conntrack_clean(ct, now);
1568
1569 if (next_wake < now) {
1570 poll_timer_wait_until(now + CT_CLEAN_MIN_INTERVAL);
1571 } else {
1572 poll_timer_wait_until(MAX(next_wake, now + CT_CLEAN_INTERVAL));
1573 }
1574 latch_wait(&ct->clean_thread_exit);
1575 poll_block();
1576 }
1577
1578 return NULL;
1579 }
1580 \f
1581 /* 'Data' is a pointer to the beginning of the L3 header and 'new_data' is
1582 * used to store a pointer to the first byte after the L3 header. 'Size' is
1583 * the size of the packet beyond the data pointer. */
1584 static inline bool
1585 extract_l3_ipv4(struct conn_key *key, const void *data, size_t size,
1586 const char **new_data, bool validate_checksum)
1587 {
1588 if (OVS_UNLIKELY(size < IP_HEADER_LEN)) {
1589 return false;
1590 }
1591
1592 const struct ip_header *ip = data;
1593 size_t ip_len = IP_IHL(ip->ip_ihl_ver) * 4;
1594
1595 if (OVS_UNLIKELY(ip_len < IP_HEADER_LEN)) {
1596 return false;
1597 }
1598
1599 if (OVS_UNLIKELY(size < ip_len)) {
1600 return false;
1601 }
1602
1603 if (IP_IS_FRAGMENT(ip->ip_frag_off)) {
1604 return false;
1605 }
1606
1607 if (validate_checksum && csum(data, ip_len) != 0) {
1608 return false;
1609 }
1610
1611 if (new_data) {
1612 *new_data = (char *) data + ip_len;
1613 }
1614
1615 key->src.addr.ipv4 = get_16aligned_be32(&ip->ip_src);
1616 key->dst.addr.ipv4 = get_16aligned_be32(&ip->ip_dst);
1617 key->nw_proto = ip->ip_proto;
1618
1619 return true;
1620 }
1621
1622 /* 'Data' is a pointer to the beginning of the L3 header and 'new_data' is
1623 * used to store a pointer to the first byte after the L3 header. 'Size' is
1624 * the size of the packet beyond the data pointer. */
1625 static inline bool
1626 extract_l3_ipv6(struct conn_key *key, const void *data, size_t size,
1627 const char **new_data)
1628 {
1629 const struct ovs_16aligned_ip6_hdr *ip6 = data;
1630
1631 if (OVS_UNLIKELY(size < sizeof *ip6)) {
1632 return false;
1633 }
1634
1635 data = ip6 + 1;
1636 size -= sizeof *ip6;
1637 uint8_t nw_proto = ip6->ip6_nxt;
1638 uint8_t nw_frag = 0;
1639
1640 const struct ovs_16aligned_ip6_frag *frag_hdr;
1641 if (!parse_ipv6_ext_hdrs(&data, &size, &nw_proto, &nw_frag, &frag_hdr)) {
1642 return false;
1643 }
1644
1645 if (nw_frag) {
1646 return false;
1647 }
1648
1649 if (new_data) {
1650 *new_data = data;
1651 }
1652
1653 memcpy(&key->src.addr.ipv6, &ip6->ip6_src, sizeof key->src.addr);
1654 memcpy(&key->dst.addr.ipv6, &ip6->ip6_dst, sizeof key->dst.addr);
1655 key->nw_proto = nw_proto;
1656
1657 return true;
1658 }
1659
1660 static inline bool
1661 checksum_valid(const struct conn_key *key, const void *data, size_t size,
1662 const void *l3)
1663 {
1664 if (key->dl_type == htons(ETH_TYPE_IP)) {
1665 uint32_t csum = packet_csum_pseudoheader(l3);
1666 return csum_finish(csum_continue(csum, data, size)) == 0;
1667 } else if (key->dl_type == htons(ETH_TYPE_IPV6)) {
1668 return packet_csum_upperlayer6(l3, data, key->nw_proto, size) == 0;
1669 } else {
1670 COVERAGE_INC(conntrack_l4csum_err);
1671 return false;
1672 }
1673 }
1674
1675 static inline bool
1676 check_l4_tcp(const struct conn_key *key, const void *data, size_t size,
1677 const void *l3, bool validate_checksum)
1678 {
1679 const struct tcp_header *tcp = data;
1680 if (size < sizeof *tcp) {
1681 return false;
1682 }
1683
1684 size_t tcp_len = TCP_OFFSET(tcp->tcp_ctl) * 4;
1685 if (OVS_UNLIKELY(tcp_len < TCP_HEADER_LEN || tcp_len > size)) {
1686 return false;
1687 }
1688
1689 return validate_checksum ? checksum_valid(key, data, size, l3) : true;
1690 }
1691
1692 static inline bool
1693 check_l4_udp(const struct conn_key *key, const void *data, size_t size,
1694 const void *l3, bool validate_checksum)
1695 {
1696 const struct udp_header *udp = data;
1697 if (size < sizeof *udp) {
1698 return false;
1699 }
1700
1701 size_t udp_len = ntohs(udp->udp_len);
1702 if (OVS_UNLIKELY(udp_len < UDP_HEADER_LEN || udp_len > size)) {
1703 return false;
1704 }
1705
1706 /* Validation must be skipped if checksum is 0 on IPv4 packets */
1707 return (udp->udp_csum == 0 && key->dl_type == htons(ETH_TYPE_IP))
1708 || (validate_checksum ? checksum_valid(key, data, size, l3) : true);
1709 }
1710
1711 static inline bool
1712 check_l4_icmp(const void *data, size_t size, bool validate_checksum)
1713 {
1714 if (validate_checksum && csum(data, size) != 0) {
1715 COVERAGE_INC(conntrack_l4csum_err);
1716 return false;
1717 } else {
1718 return true;
1719 }
1720 }
1721
1722 static inline bool
1723 check_l4_icmp6(const struct conn_key *key, const void *data, size_t size,
1724 const void *l3, bool validate_checksum)
1725 {
1726 return validate_checksum ? checksum_valid(key, data, size, l3) : true;
1727 }
1728
1729 static inline bool
1730 extract_l4_tcp(struct conn_key *key, const void *data, size_t size,
1731 size_t *chk_len)
1732 {
1733 if (OVS_UNLIKELY(size < (chk_len ? *chk_len : TCP_HEADER_LEN))) {
1734 return false;
1735 }
1736
1737 const struct tcp_header *tcp = data;
1738 key->src.port = tcp->tcp_src;
1739 key->dst.port = tcp->tcp_dst;
1740
1741 /* Port 0 is invalid */
1742 return key->src.port && key->dst.port;
1743 }
1744
1745 static inline bool
1746 extract_l4_udp(struct conn_key *key, const void *data, size_t size,
1747 size_t *chk_len)
1748 {
1749 if (OVS_UNLIKELY(size < (chk_len ? *chk_len : UDP_HEADER_LEN))) {
1750 return false;
1751 }
1752
1753 const struct udp_header *udp = data;
1754 key->src.port = udp->udp_src;
1755 key->dst.port = udp->udp_dst;
1756
1757 /* Port 0 is invalid */
1758 return key->src.port && key->dst.port;
1759 }
1760
1761 static inline bool extract_l4(struct conn_key *key, const void *data,
1762 size_t size, bool *related, const void *l3,
1763 bool validate_checksum, size_t *chk_len);
1764
1765 static uint8_t
1766 reverse_icmp_type(uint8_t type)
1767 {
1768 switch (type) {
1769 case ICMP4_ECHO_REQUEST:
1770 return ICMP4_ECHO_REPLY;
1771 case ICMP4_ECHO_REPLY:
1772 return ICMP4_ECHO_REQUEST;
1773
1774 case ICMP4_TIMESTAMP:
1775 return ICMP4_TIMESTAMPREPLY;
1776 case ICMP4_TIMESTAMPREPLY:
1777 return ICMP4_TIMESTAMP;
1778
1779 case ICMP4_INFOREQUEST:
1780 return ICMP4_INFOREPLY;
1781 case ICMP4_INFOREPLY:
1782 return ICMP4_INFOREQUEST;
1783 default:
1784 OVS_NOT_REACHED();
1785 }
1786 }
1787
1788 /* If 'related' is not NULL and the function is processing an ICMP
1789 * error packet, extract the l3 and l4 fields from the nested header
1790 * instead and set *related to true. If 'related' is NULL we're
1791 * already processing a nested header and no such recursion is
1792 * possible */
1793 static inline int
1794 extract_l4_icmp(struct conn_key *key, const void *data, size_t size,
1795 bool *related, size_t *chk_len)
1796 {
1797 if (OVS_UNLIKELY(size < (chk_len ? *chk_len : ICMP_HEADER_LEN))) {
1798 return false;
1799 }
1800
1801 const struct icmp_header *icmp = data;
1802
1803 switch (icmp->icmp_type) {
1804 case ICMP4_ECHO_REQUEST:
1805 case ICMP4_ECHO_REPLY:
1806 case ICMP4_TIMESTAMP:
1807 case ICMP4_TIMESTAMPREPLY:
1808 case ICMP4_INFOREQUEST:
1809 case ICMP4_INFOREPLY:
1810 if (icmp->icmp_code != 0) {
1811 return false;
1812 }
1813 /* Separate ICMP connection: identified using id */
1814 key->src.icmp_id = key->dst.icmp_id = icmp->icmp_fields.echo.id;
1815 key->src.icmp_type = icmp->icmp_type;
1816 key->dst.icmp_type = reverse_icmp_type(icmp->icmp_type);
1817 break;
1818 case ICMP4_DST_UNREACH:
1819 case ICMP4_TIME_EXCEEDED:
1820 case ICMP4_PARAM_PROB:
1821 case ICMP4_SOURCEQUENCH:
1822 case ICMP4_REDIRECT: {
1823 /* ICMP packet part of another connection. We should
1824 * extract the key from embedded packet header */
1825 struct conn_key inner_key;
1826 const char *l3 = (const char *) (icmp + 1);
1827 const char *tail = (const char *) data + size;
1828 const char *l4;
1829
1830 if (!related) {
1831 return false;
1832 }
1833
1834 memset(&inner_key, 0, sizeof inner_key);
1835 inner_key.dl_type = htons(ETH_TYPE_IP);
1836 bool ok = extract_l3_ipv4(&inner_key, l3, tail - l3, &l4, false);
1837 if (!ok) {
1838 return false;
1839 }
1840
1841 if (inner_key.src.addr.ipv4 != key->dst.addr.ipv4) {
1842 return false;
1843 }
1844
1845 key->src = inner_key.src;
1846 key->dst = inner_key.dst;
1847 key->nw_proto = inner_key.nw_proto;
1848 size_t check_len = ICMP_ERROR_DATA_L4_LEN;
1849
1850 ok = extract_l4(key, l4, tail - l4, NULL, l3, false, &check_len);
1851 if (ok) {
1852 conn_key_reverse(key);
1853 *related = true;
1854 }
1855 return ok;
1856 }
1857 default:
1858 return false;
1859 }
1860
1861 return true;
1862 }
1863
1864 static uint8_t
1865 reverse_icmp6_type(uint8_t type)
1866 {
1867 switch (type) {
1868 case ICMP6_ECHO_REQUEST:
1869 return ICMP6_ECHO_REPLY;
1870 case ICMP6_ECHO_REPLY:
1871 return ICMP6_ECHO_REQUEST;
1872 default:
1873 OVS_NOT_REACHED();
1874 }
1875 }
1876
1877 /* If 'related' is not NULL and the function is processing an ICMP
1878 * error packet, extract the l3 and l4 fields from the nested header
1879 * instead and set *related to true. If 'related' is NULL we're
1880 * already processing a nested header and no such recursion is
1881 * possible */
1882 static inline bool
1883 extract_l4_icmp6(struct conn_key *key, const void *data, size_t size,
1884 bool *related)
1885 {
1886 const struct icmp6_header *icmp6 = data;
1887
1888 /* All the messages that we support need at least 4 bytes after
1889 * the header */
1890 if (size < sizeof *icmp6 + 4) {
1891 return false;
1892 }
1893
1894 switch (icmp6->icmp6_type) {
1895 case ICMP6_ECHO_REQUEST:
1896 case ICMP6_ECHO_REPLY:
1897 if (icmp6->icmp6_code != 0) {
1898 return false;
1899 }
1900 /* Separate ICMP connection: identified using id */
1901 key->src.icmp_id = key->dst.icmp_id = *(ovs_be16 *) (icmp6 + 1);
1902 key->src.icmp_type = icmp6->icmp6_type;
1903 key->dst.icmp_type = reverse_icmp6_type(icmp6->icmp6_type);
1904 break;
1905 case ICMP6_DST_UNREACH:
1906 case ICMP6_PACKET_TOO_BIG:
1907 case ICMP6_TIME_EXCEEDED:
1908 case ICMP6_PARAM_PROB: {
1909 /* ICMP packet part of another connection. We should
1910 * extract the key from embedded packet header */
1911 struct conn_key inner_key;
1912 const char *l3 = (const char *) icmp6 + 8;
1913 const char *tail = (const char *) data + size;
1914 const char *l4 = NULL;
1915
1916 if (!related) {
1917 return false;
1918 }
1919
1920 memset(&inner_key, 0, sizeof inner_key);
1921 inner_key.dl_type = htons(ETH_TYPE_IPV6);
1922 bool ok = extract_l3_ipv6(&inner_key, l3, tail - l3, &l4);
1923 if (!ok) {
1924 return false;
1925 }
1926
1927 /* pf doesn't do this, but it seems a good idea */
1928 if (!ipv6_addr_equals(&inner_key.src.addr.ipv6,
1929 &key->dst.addr.ipv6)) {
1930 return false;
1931 }
1932
1933 key->src = inner_key.src;
1934 key->dst = inner_key.dst;
1935 key->nw_proto = inner_key.nw_proto;
1936
1937 ok = extract_l4(key, l4, tail - l4, NULL, l3, false, NULL);
1938 if (ok) {
1939 conn_key_reverse(key);
1940 *related = true;
1941 }
1942 return ok;
1943 }
1944 default:
1945 return false;
1946 }
1947
1948 return true;
1949 }
1950
1951 /* Extract l4 fields into 'key', which must already contain valid l3
1952 * members.
1953 *
1954 * If 'related' is not NULL and an ICMP error packet is being
1955 * processed, the function will extract the key from the packet nested
1956 * in the ICMP payload and set '*related' to true.
1957 *
1958 * 'size' here is the layer 4 size, which can be a nested size if parsing
1959 * an ICMP or ICMP6 header.
1960 *
1961 * If 'related' is NULL, it means that we're already parsing a header nested
1962 * in an ICMP error. In this case, we skip the checksum and some length
1963 * validations. */
1964 static inline bool
1965 extract_l4(struct conn_key *key, const void *data, size_t size, bool *related,
1966 const void *l3, bool validate_checksum, size_t *chk_len)
1967 {
1968 if (key->nw_proto == IPPROTO_TCP) {
1969 return (!related || check_l4_tcp(key, data, size, l3,
1970 validate_checksum))
1971 && extract_l4_tcp(key, data, size, chk_len);
1972 } else if (key->nw_proto == IPPROTO_UDP) {
1973 return (!related || check_l4_udp(key, data, size, l3,
1974 validate_checksum))
1975 && extract_l4_udp(key, data, size, chk_len);
1976 } else if (key->dl_type == htons(ETH_TYPE_IP)
1977 && key->nw_proto == IPPROTO_ICMP) {
1978 return (!related || check_l4_icmp(data, size, validate_checksum))
1979 && extract_l4_icmp(key, data, size, related, chk_len);
1980 } else if (key->dl_type == htons(ETH_TYPE_IPV6)
1981 && key->nw_proto == IPPROTO_ICMPV6) {
1982 return (!related || check_l4_icmp6(key, data, size, l3,
1983 validate_checksum))
1984 && extract_l4_icmp6(key, data, size, related);
1985 } else {
1986 return false;
1987 }
1988 }
1989
1990 static bool
1991 conn_key_extract(struct conntrack *ct, struct dp_packet *pkt, ovs_be16 dl_type,
1992 struct conn_lookup_ctx *ctx, uint16_t zone)
1993 {
1994 const struct eth_header *l2 = dp_packet_eth(pkt);
1995 const struct ip_header *l3 = dp_packet_l3(pkt);
1996 const char *l4 = dp_packet_l4(pkt);
1997
1998 memset(ctx, 0, sizeof *ctx);
1999
2000 if (!l2 || !l3 || !l4) {
2001 return false;
2002 }
2003
2004 ctx->key.zone = zone;
2005
2006 /* XXX In this function we parse the packet (again, it has already
2007 * gone through miniflow_extract()) for two reasons:
2008 *
2009 * 1) To extract the l3 addresses and l4 ports.
2010 * We already have the l3 and l4 headers' pointers. Extracting
2011 * the l3 addresses and the l4 ports is really cheap, since they
2012 * can be found at fixed locations.
2013 * 2) To extract the l4 type.
2014 * Extracting the l4 types, for IPv6 can be quite expensive, because
2015 * it's not at a fixed location.
2016 *
2017 * Here's a way to avoid (2) with the help of the datapath.
2018 * The datapath doesn't keep the packet's extracted flow[1], so
2019 * using that is not an option. We could use the packet's matching
2020 * megaflow, but we have to make sure that the l4 type (nw_proto)
2021 * is unwildcarded. This means either:
2022 *
2023 * a) dpif-netdev unwildcards the l4 type when a new flow is installed
2024 * if the actions contains ct().
2025 *
2026 * b) ofproto-dpif-xlate unwildcards the l4 type when translating a ct()
2027 * action. This is already done in different actions, but it's
2028 * unnecessary for the kernel.
2029 *
2030 * ---
2031 * [1] The reasons for this are that keeping the flow increases
2032 * (slightly) the cache footprint and increases computation
2033 * time as we move the packet around. Most importantly, the flow
2034 * should be updated by the actions and this can be slow, as
2035 * we use a sparse representation (miniflow).
2036 *
2037 */
2038 bool ok;
2039 ctx->key.dl_type = dl_type;
2040
2041 if (ctx->key.dl_type == htons(ETH_TYPE_IP)) {
2042 bool hwol_bad_l3_csum = dp_packet_ip_checksum_bad(pkt);
2043 if (hwol_bad_l3_csum) {
2044 ok = false;
2045 } else {
2046 bool hwol_good_l3_csum = dp_packet_ip_checksum_valid(pkt)
2047 || dp_packet_hwol_is_ipv4(pkt);
2048 /* Validate the checksum only when hwol is not supported. */
2049 ok = extract_l3_ipv4(&ctx->key, l3, dp_packet_l3_size(pkt), NULL,
2050 !hwol_good_l3_csum);
2051 }
2052 } else if (ctx->key.dl_type == htons(ETH_TYPE_IPV6)) {
2053 ok = extract_l3_ipv6(&ctx->key, l3, dp_packet_l3_size(pkt), NULL);
2054 } else {
2055 ok = false;
2056 }
2057
2058 if (ok) {
2059 bool hwol_bad_l4_csum = dp_packet_l4_checksum_bad(pkt);
2060 if (!hwol_bad_l4_csum) {
2061 bool hwol_good_l4_csum = dp_packet_l4_checksum_valid(pkt)
2062 || dp_packet_hwol_tx_l4_checksum(pkt);
2063 /* Validate the checksum only when hwol is not supported. */
2064 if (extract_l4(&ctx->key, l4, dp_packet_l4_size(pkt),
2065 &ctx->icmp_related, l3, !hwol_good_l4_csum,
2066 NULL)) {
2067 ctx->hash = conn_key_hash(&ctx->key, ct->hash_basis);
2068 return true;
2069 }
2070 }
2071 }
2072
2073 return false;
2074 }
2075
2076 static uint32_t
2077 ct_addr_hash_add(uint32_t hash, const union ct_addr *addr)
2078 {
2079 BUILD_ASSERT_DECL(sizeof *addr % 4 == 0);
2080 return hash_add_bytes32(hash, (const uint32_t *) addr, sizeof *addr);
2081 }
2082
2083 static uint32_t
2084 ct_endpoint_hash_add(uint32_t hash, const struct ct_endpoint *ep)
2085 {
2086 BUILD_ASSERT_DECL(sizeof *ep % 4 == 0);
2087 return hash_add_bytes32(hash, (const uint32_t *) ep, sizeof *ep);
2088 }
2089 \f
2090 /* Symmetric */
2091 static uint32_t
2092 conn_key_hash(const struct conn_key *key, uint32_t basis)
2093 {
2094 uint32_t hsrc, hdst, hash;
2095 hsrc = hdst = basis;
2096 hsrc = ct_endpoint_hash_add(hsrc, &key->src);
2097 hdst = ct_endpoint_hash_add(hdst, &key->dst);
2098
2099 /* Even if source and destination are swapped the hash will be the same. */
2100 hash = hsrc ^ hdst;
2101
2102 /* Hash the rest of the key(L3 and L4 types and zone). */
2103 return hash_words((uint32_t *) (&key->dst + 1),
2104 (uint32_t *) (key + 1) - (uint32_t *) (&key->dst + 1),
2105 hash);
2106 }
2107
2108 static void
2109 conn_key_reverse(struct conn_key *key)
2110 {
2111 struct ct_endpoint tmp = key->src;
2112 key->src = key->dst;
2113 key->dst = tmp;
2114 }
2115
2116 static uint32_t
2117 nat_ipv6_addrs_delta(struct in6_addr *ipv6_min, struct in6_addr *ipv6_max)
2118 {
2119 uint8_t *ipv6_min_hi = &ipv6_min->s6_addr[0];
2120 uint8_t *ipv6_min_lo = &ipv6_min->s6_addr[0] + sizeof(uint64_t);
2121 uint8_t *ipv6_max_hi = &ipv6_max->s6_addr[0];
2122 uint8_t *ipv6_max_lo = &ipv6_max->s6_addr[0] + sizeof(uint64_t);
2123
2124 ovs_be64 addr6_64_min_hi;
2125 ovs_be64 addr6_64_min_lo;
2126 memcpy(&addr6_64_min_hi, ipv6_min_hi, sizeof addr6_64_min_hi);
2127 memcpy(&addr6_64_min_lo, ipv6_min_lo, sizeof addr6_64_min_lo);
2128
2129 ovs_be64 addr6_64_max_hi;
2130 ovs_be64 addr6_64_max_lo;
2131 memcpy(&addr6_64_max_hi, ipv6_max_hi, sizeof addr6_64_max_hi);
2132 memcpy(&addr6_64_max_lo, ipv6_max_lo, sizeof addr6_64_max_lo);
2133
2134 uint64_t diff;
2135
2136 if (addr6_64_min_hi == addr6_64_max_hi &&
2137 ntohll(addr6_64_min_lo) <= ntohll(addr6_64_max_lo)) {
2138 diff = ntohll(addr6_64_max_lo) - ntohll(addr6_64_min_lo);
2139 } else if (ntohll(addr6_64_min_hi) + 1 == ntohll(addr6_64_max_hi) &&
2140 ntohll(addr6_64_min_lo) > ntohll(addr6_64_max_lo)) {
2141 diff = UINT64_MAX - (ntohll(addr6_64_min_lo) -
2142 ntohll(addr6_64_max_lo) - 1);
2143 } else {
2144 /* Limit address delta supported to 32 bits or 4 billion approximately.
2145 * Possibly, this should be visible to the user through a datapath
2146 * support check, however the practical impact is probably nil. */
2147 diff = 0xfffffffe;
2148 }
2149
2150 if (diff > 0xfffffffe) {
2151 diff = 0xfffffffe;
2152 }
2153 return diff;
2154 }
2155
2156 /* This function must be used in tandem with nat_ipv6_addrs_delta(), which
2157 * restricts the input parameters. */
2158 static void
2159 nat_ipv6_addr_increment(struct in6_addr *ipv6, uint32_t increment)
2160 {
2161 uint8_t *ipv6_hi = &ipv6->s6_addr[0];
2162 uint8_t *ipv6_lo = &ipv6->s6_addr[0] + sizeof(ovs_be64);
2163 ovs_be64 addr6_64_hi;
2164 ovs_be64 addr6_64_lo;
2165 memcpy(&addr6_64_hi, ipv6_hi, sizeof addr6_64_hi);
2166 memcpy(&addr6_64_lo, ipv6_lo, sizeof addr6_64_lo);
2167
2168 if (UINT64_MAX - increment >= ntohll(addr6_64_lo)) {
2169 addr6_64_lo = htonll(increment + ntohll(addr6_64_lo));
2170 } else if (addr6_64_hi != OVS_BE64_MAX) {
2171 addr6_64_hi = htonll(1 + ntohll(addr6_64_hi));
2172 addr6_64_lo = htonll(increment - (UINT64_MAX -
2173 ntohll(addr6_64_lo) + 1));
2174 } else {
2175 OVS_NOT_REACHED();
2176 }
2177
2178 memcpy(ipv6_hi, &addr6_64_hi, sizeof addr6_64_hi);
2179 memcpy(ipv6_lo, &addr6_64_lo, sizeof addr6_64_lo);
2180 }
2181
2182 static uint32_t
2183 nat_range_hash(const struct conn *conn, uint32_t basis)
2184 {
2185 uint32_t hash = basis;
2186
2187 hash = ct_addr_hash_add(hash, &conn->nat_info->min_addr);
2188 hash = ct_addr_hash_add(hash, &conn->nat_info->max_addr);
2189 hash = hash_add(hash,
2190 (conn->nat_info->max_port << 16)
2191 | conn->nat_info->min_port);
2192 hash = ct_endpoint_hash_add(hash, &conn->key.src);
2193 hash = ct_endpoint_hash_add(hash, &conn->key.dst);
2194 hash = hash_add(hash, (OVS_FORCE uint32_t) conn->key.dl_type);
2195 hash = hash_add(hash, conn->key.nw_proto);
2196 hash = hash_add(hash, conn->key.zone);
2197
2198 /* The purpose of the second parameter is to distinguish hashes of data of
2199 * different length; our data always has the same length so there is no
2200 * value in counting. */
2201 return hash_finish(hash, 0);
2202 }
2203
2204 static bool
2205 nat_select_range_tuple(struct conntrack *ct, const struct conn *conn,
2206 struct conn *nat_conn)
2207 {
2208 enum { MIN_NAT_EPHEMERAL_PORT = 1024,
2209 MAX_NAT_EPHEMERAL_PORT = 65535 };
2210
2211 uint16_t min_port;
2212 uint16_t max_port;
2213 uint16_t first_port;
2214 uint32_t hash = nat_range_hash(conn, ct->hash_basis);
2215
2216 if ((conn->nat_info->nat_action & NAT_ACTION_SRC) &&
2217 (!(conn->nat_info->nat_action & NAT_ACTION_SRC_PORT))) {
2218 min_port = ntohs(conn->key.src.port);
2219 max_port = ntohs(conn->key.src.port);
2220 first_port = min_port;
2221 } else if ((conn->nat_info->nat_action & NAT_ACTION_DST) &&
2222 (!(conn->nat_info->nat_action & NAT_ACTION_DST_PORT))) {
2223 min_port = ntohs(conn->key.dst.port);
2224 max_port = ntohs(conn->key.dst.port);
2225 first_port = min_port;
2226 } else {
2227 uint16_t deltap = conn->nat_info->max_port - conn->nat_info->min_port;
2228 uint32_t port_index = hash % (deltap + 1);
2229 first_port = conn->nat_info->min_port + port_index;
2230 min_port = conn->nat_info->min_port;
2231 max_port = conn->nat_info->max_port;
2232 }
2233
2234 uint32_t deltaa = 0;
2235 uint32_t address_index;
2236 union ct_addr ct_addr;
2237 memset(&ct_addr, 0, sizeof ct_addr);
2238 union ct_addr max_ct_addr;
2239 memset(&max_ct_addr, 0, sizeof max_ct_addr);
2240 max_ct_addr = conn->nat_info->max_addr;
2241
2242 if (conn->key.dl_type == htons(ETH_TYPE_IP)) {
2243 deltaa = ntohl(conn->nat_info->max_addr.ipv4) -
2244 ntohl(conn->nat_info->min_addr.ipv4);
2245 address_index = hash % (deltaa + 1);
2246 ct_addr.ipv4 = htonl(
2247 ntohl(conn->nat_info->min_addr.ipv4) + address_index);
2248 } else {
2249 deltaa = nat_ipv6_addrs_delta(&conn->nat_info->min_addr.ipv6,
2250 &conn->nat_info->max_addr.ipv6);
2251 /* deltaa must be within 32 bits for full hash coverage. A 64 or
2252 * 128 bit hash is unnecessary and hence not used here. Most code
2253 * is kept common with V4; nat_ipv6_addrs_delta() will do the
2254 * enforcement via max_ct_addr. */
2255 max_ct_addr = conn->nat_info->min_addr;
2256 nat_ipv6_addr_increment(&max_ct_addr.ipv6, deltaa);
2257 address_index = hash % (deltaa + 1);
2258 ct_addr.ipv6 = conn->nat_info->min_addr.ipv6;
2259 nat_ipv6_addr_increment(&ct_addr.ipv6, address_index);
2260 }
2261
2262 uint16_t port = first_port;
2263 bool all_ports_tried = false;
2264 /* For DNAT or for specified port ranges, we don't use ephemeral ports. */
2265 bool ephemeral_ports_tried
2266 = conn->nat_info->nat_action & NAT_ACTION_DST ||
2267 conn->nat_info->nat_action & NAT_ACTION_SRC_PORT
2268 ? true : false;
2269 union ct_addr first_addr = ct_addr;
2270 bool pat_enabled = conn->key.nw_proto != IPPROTO_ICMP &&
2271 conn->key.nw_proto != IPPROTO_ICMPV6;
2272
2273 while (true) {
2274 if (conn->nat_info->nat_action & NAT_ACTION_SRC) {
2275 nat_conn->rev_key.dst.addr = ct_addr;
2276 if (pat_enabled) {
2277 nat_conn->rev_key.dst.port = htons(port);
2278 }
2279 } else {
2280 nat_conn->rev_key.src.addr = ct_addr;
2281 if (pat_enabled) {
2282 nat_conn->rev_key.src.port = htons(port);
2283 }
2284 }
2285
2286 bool found = conn_lookup(ct, &nat_conn->rev_key, time_msec(), NULL,
2287 NULL);
2288 if (!found) {
2289 return true;
2290 } else if (pat_enabled && !all_ports_tried) {
2291 if (min_port == max_port) {
2292 all_ports_tried = true;
2293 } else if (port == max_port) {
2294 port = min_port;
2295 } else {
2296 port++;
2297 }
2298 if (port == first_port) {
2299 all_ports_tried = true;
2300 }
2301 } else {
2302 if (memcmp(&ct_addr, &max_ct_addr, sizeof ct_addr)) {
2303 if (conn->key.dl_type == htons(ETH_TYPE_IP)) {
2304 ct_addr.ipv4 = htonl(ntohl(ct_addr.ipv4) + 1);
2305 } else {
2306 nat_ipv6_addr_increment(&ct_addr.ipv6, 1);
2307 }
2308 } else {
2309 ct_addr = conn->nat_info->min_addr;
2310 }
2311 if (!memcmp(&ct_addr, &first_addr, sizeof ct_addr)) {
2312 if (pat_enabled && !ephemeral_ports_tried) {
2313 ephemeral_ports_tried = true;
2314 ct_addr = conn->nat_info->min_addr;
2315 first_addr = ct_addr;
2316 min_port = MIN_NAT_EPHEMERAL_PORT;
2317 max_port = MAX_NAT_EPHEMERAL_PORT;
2318 } else {
2319 break;
2320 }
2321 }
2322 first_port = min_port;
2323 port = first_port;
2324 all_ports_tried = false;
2325 }
2326 }
2327 return false;
2328 }
2329
2330 static enum ct_update_res
2331 conn_update(struct conntrack *ct, struct conn *conn, struct dp_packet *pkt,
2332 struct conn_lookup_ctx *ctx, long long now)
2333 {
2334 ovs_mutex_lock(&conn->lock);
2335 enum ct_update_res update_res =
2336 l4_protos[conn->key.nw_proto]->conn_update(ct, conn, pkt, ctx->reply,
2337 now);
2338 ovs_mutex_unlock(&conn->lock);
2339 return update_res;
2340 }
2341
2342 static bool
2343 conn_expired(struct conn *conn, long long now)
2344 {
2345 if (conn->conn_type == CT_CONN_TYPE_DEFAULT) {
2346 ovs_mutex_lock(&conn->lock);
2347 bool expired = now >= conn->expiration ? true : false;
2348 ovs_mutex_unlock(&conn->lock);
2349 return expired;
2350 }
2351 return false;
2352 }
2353
2354 static bool
2355 valid_new(struct dp_packet *pkt, struct conn_key *key)
2356 {
2357 return l4_protos[key->nw_proto]->valid_new(pkt);
2358 }
2359
2360 static struct conn *
2361 new_conn(struct conntrack *ct, struct dp_packet *pkt, struct conn_key *key,
2362 long long now, uint32_t tp_id)
2363 {
2364 return l4_protos[key->nw_proto]->new_conn(ct, pkt, now, tp_id);
2365 }
2366
2367 static void
2368 delete_conn_cmn(struct conn *conn)
2369 {
2370 free(conn->nat_info);
2371 free(conn->alg);
2372 free(conn);
2373 }
2374
2375 static void
2376 delete_conn(struct conn *conn)
2377 {
2378 ovs_assert(conn->conn_type == CT_CONN_TYPE_DEFAULT);
2379 ovs_mutex_destroy(&conn->lock);
2380 free(conn->nat_conn);
2381 delete_conn_cmn(conn);
2382 }
2383
2384 /* Only used by conn_clean_one(). */
2385 static void
2386 delete_conn_one(struct conn *conn)
2387 {
2388 if (conn->conn_type == CT_CONN_TYPE_DEFAULT) {
2389 ovs_mutex_destroy(&conn->lock);
2390 }
2391 delete_conn_cmn(conn);
2392 }
2393 \f
2394 /* Convert a conntrack address 'a' into an IP address 'b' based on 'dl_type'.
2395 *
2396 * Note that 'dl_type' should be either "ETH_TYPE_IP" or "ETH_TYPE_IPv6"
2397 * in network-byte order. */
2398 static void
2399 ct_endpoint_to_ct_dpif_inet_addr(const union ct_addr *a,
2400 union ct_dpif_inet_addr *b,
2401 ovs_be16 dl_type)
2402 {
2403 if (dl_type == htons(ETH_TYPE_IP)) {
2404 b->ip = a->ipv4;
2405 } else if (dl_type == htons(ETH_TYPE_IPV6)){
2406 b->in6 = a->ipv6;
2407 }
2408 }
2409
2410 /* Convert an IP address 'a' into a conntrack address 'b' based on 'dl_type'.
2411 *
2412 * Note that 'dl_type' should be either "ETH_TYPE_IP" or "ETH_TYPE_IPv6"
2413 * in network-byte order. */
2414 static void
2415 ct_dpif_inet_addr_to_ct_endpoint(const union ct_dpif_inet_addr *a,
2416 union ct_addr *b, ovs_be16 dl_type)
2417 {
2418 if (dl_type == htons(ETH_TYPE_IP)) {
2419 b->ipv4 = a->ip;
2420 } else if (dl_type == htons(ETH_TYPE_IPV6)){
2421 b->ipv6 = a->in6;
2422 }
2423 }
2424
2425 static void
2426 conn_key_to_tuple(const struct conn_key *key, struct ct_dpif_tuple *tuple)
2427 {
2428 if (key->dl_type == htons(ETH_TYPE_IP)) {
2429 tuple->l3_type = AF_INET;
2430 } else if (key->dl_type == htons(ETH_TYPE_IPV6)) {
2431 tuple->l3_type = AF_INET6;
2432 }
2433 tuple->ip_proto = key->nw_proto;
2434 ct_endpoint_to_ct_dpif_inet_addr(&key->src.addr, &tuple->src,
2435 key->dl_type);
2436 ct_endpoint_to_ct_dpif_inet_addr(&key->dst.addr, &tuple->dst,
2437 key->dl_type);
2438
2439 if (key->nw_proto == IPPROTO_ICMP || key->nw_proto == IPPROTO_ICMPV6) {
2440 tuple->icmp_id = key->src.icmp_id;
2441 tuple->icmp_type = key->src.icmp_type;
2442 tuple->icmp_code = key->src.icmp_code;
2443 } else {
2444 tuple->src_port = key->src.port;
2445 tuple->dst_port = key->dst.port;
2446 }
2447 }
2448
2449 static void
2450 tuple_to_conn_key(const struct ct_dpif_tuple *tuple, uint16_t zone,
2451 struct conn_key *key)
2452 {
2453 if (tuple->l3_type == AF_INET) {
2454 key->dl_type = htons(ETH_TYPE_IP);
2455 } else if (tuple->l3_type == AF_INET6) {
2456 key->dl_type = htons(ETH_TYPE_IPV6);
2457 }
2458 key->nw_proto = tuple->ip_proto;
2459 ct_dpif_inet_addr_to_ct_endpoint(&tuple->src, &key->src.addr,
2460 key->dl_type);
2461 ct_dpif_inet_addr_to_ct_endpoint(&tuple->dst, &key->dst.addr,
2462 key->dl_type);
2463
2464 if (tuple->ip_proto == IPPROTO_ICMP || tuple->ip_proto == IPPROTO_ICMPV6) {
2465 key->src.icmp_id = tuple->icmp_id;
2466 key->src.icmp_type = tuple->icmp_type;
2467 key->src.icmp_code = tuple->icmp_code;
2468 key->dst.icmp_id = tuple->icmp_id;
2469 key->dst.icmp_type = reverse_icmp_type(tuple->icmp_type);
2470 key->dst.icmp_code = tuple->icmp_code;
2471 } else {
2472 key->src.port = tuple->src_port;
2473 key->dst.port = tuple->dst_port;
2474 }
2475 key->zone = zone;
2476 }
2477
2478 static void
2479 conn_to_ct_dpif_entry(const struct conn *conn, struct ct_dpif_entry *entry,
2480 long long now)
2481 {
2482 memset(entry, 0, sizeof *entry);
2483 conn_key_to_tuple(&conn->key, &entry->tuple_orig);
2484 conn_key_to_tuple(&conn->rev_key, &entry->tuple_reply);
2485
2486 entry->zone = conn->key.zone;
2487
2488 ovs_mutex_lock(&conn->lock);
2489 entry->mark = conn->mark;
2490 memcpy(&entry->labels, &conn->label, sizeof entry->labels);
2491
2492 long long expiration = conn->expiration - now;
2493
2494 struct ct_l4_proto *class = l4_protos[conn->key.nw_proto];
2495 if (class->conn_get_protoinfo) {
2496 class->conn_get_protoinfo(conn, &entry->protoinfo);
2497 }
2498 ovs_mutex_unlock(&conn->lock);
2499
2500 entry->timeout = (expiration > 0) ? expiration / 1000 : 0;
2501
2502 if (conn->alg) {
2503 /* Caller is responsible for freeing. */
2504 entry->helper.name = xstrdup(conn->alg);
2505 }
2506 }
2507
2508 struct ipf *
2509 conntrack_ipf_ctx(struct conntrack *ct)
2510 {
2511 return ct->ipf;
2512 }
2513
2514 int
2515 conntrack_dump_start(struct conntrack *ct, struct conntrack_dump *dump,
2516 const uint16_t *pzone, int *ptot_bkts)
2517 {
2518 memset(dump, 0, sizeof(*dump));
2519
2520 if (pzone) {
2521 dump->zone = *pzone;
2522 dump->filter_zone = true;
2523 }
2524
2525 dump->ct = ct;
2526 *ptot_bkts = 1; /* Need to clean up the callers. */
2527 return 0;
2528 }
2529
2530 int
2531 conntrack_dump_next(struct conntrack_dump *dump, struct ct_dpif_entry *entry)
2532 {
2533 struct conntrack *ct = dump->ct;
2534 long long now = time_msec();
2535
2536 for (;;) {
2537 struct cmap_node *cm_node = cmap_next_position(&ct->conns,
2538 &dump->cm_pos);
2539 if (!cm_node) {
2540 break;
2541 }
2542 struct conn *conn;
2543 INIT_CONTAINER(conn, cm_node, cm_node);
2544 if ((!dump->filter_zone || conn->key.zone == dump->zone) &&
2545 (conn->conn_type != CT_CONN_TYPE_UN_NAT)) {
2546 conn_to_ct_dpif_entry(conn, entry, now);
2547 return 0;
2548 }
2549 }
2550
2551 return EOF;
2552 }
2553
2554 int
2555 conntrack_dump_done(struct conntrack_dump *dump OVS_UNUSED)
2556 {
2557 return 0;
2558 }
2559
2560 int
2561 conntrack_flush(struct conntrack *ct, const uint16_t *zone)
2562 {
2563 struct conn *conn;
2564
2565 ovs_mutex_lock(&ct->ct_lock);
2566 CMAP_FOR_EACH (conn, cm_node, &ct->conns) {
2567 if (!zone || *zone == conn->key.zone) {
2568 conn_clean_one(ct, conn);
2569 }
2570 }
2571 ovs_mutex_unlock(&ct->ct_lock);
2572
2573 return 0;
2574 }
2575
2576 int
2577 conntrack_flush_tuple(struct conntrack *ct, const struct ct_dpif_tuple *tuple,
2578 uint16_t zone)
2579 {
2580 int error = 0;
2581 struct conn_key key;
2582 struct conn *conn;
2583
2584 memset(&key, 0, sizeof(key));
2585 tuple_to_conn_key(tuple, zone, &key);
2586 ovs_mutex_lock(&ct->ct_lock);
2587 conn_lookup(ct, &key, time_msec(), &conn, NULL);
2588
2589 if (conn && conn->conn_type == CT_CONN_TYPE_DEFAULT) {
2590 conn_clean(ct, conn);
2591 } else {
2592 VLOG_WARN("Must flush tuple using the original pre-NATed tuple");
2593 error = ENOENT;
2594 }
2595
2596 ovs_mutex_unlock(&ct->ct_lock);
2597 return error;
2598 }
2599
2600 int
2601 conntrack_set_maxconns(struct conntrack *ct, uint32_t maxconns)
2602 {
2603 atomic_store_relaxed(&ct->n_conn_limit, maxconns);
2604 return 0;
2605 }
2606
2607 int
2608 conntrack_get_maxconns(struct conntrack *ct, uint32_t *maxconns)
2609 {
2610 atomic_read_relaxed(&ct->n_conn_limit, maxconns);
2611 return 0;
2612 }
2613
2614 int
2615 conntrack_get_nconns(struct conntrack *ct, uint32_t *nconns)
2616 {
2617 *nconns = atomic_count_get(&ct->n_conn);
2618 return 0;
2619 }
2620
2621 int
2622 conntrack_set_tcp_seq_chk(struct conntrack *ct, bool enabled)
2623 {
2624 atomic_store_relaxed(&ct->tcp_seq_chk, enabled);
2625 return 0;
2626 }
2627
2628 bool
2629 conntrack_get_tcp_seq_chk(struct conntrack *ct)
2630 {
2631 bool enabled;
2632 atomic_read_relaxed(&ct->tcp_seq_chk, &enabled);
2633 return enabled;
2634 }
2635
2636 /* This function must be called with the ct->resources read lock taken. */
2637 static struct alg_exp_node *
2638 expectation_lookup(struct hmap *alg_expectations, const struct conn_key *key,
2639 uint32_t basis, bool src_ip_wc)
2640 {
2641 struct conn_key check_key;
2642 memcpy(&check_key, key, sizeof check_key);
2643 check_key.src.port = ALG_WC_SRC_PORT;
2644
2645 if (src_ip_wc) {
2646 memset(&check_key.src.addr, 0, sizeof check_key.src.addr);
2647 }
2648
2649 struct alg_exp_node *alg_exp_node;
2650
2651 HMAP_FOR_EACH_WITH_HASH (alg_exp_node, node,
2652 conn_key_hash(&check_key, basis),
2653 alg_expectations) {
2654 if (!conn_key_cmp(&alg_exp_node->key, &check_key)) {
2655 return alg_exp_node;
2656 }
2657 }
2658 return NULL;
2659 }
2660
2661 /* This function must be called with the ct->resources write lock taken. */
2662 static void
2663 expectation_remove(struct hmap *alg_expectations,
2664 const struct conn_key *key, uint32_t basis)
2665 {
2666 struct alg_exp_node *alg_exp_node;
2667
2668 HMAP_FOR_EACH_WITH_HASH (alg_exp_node, node, conn_key_hash(key, basis),
2669 alg_expectations) {
2670 if (!conn_key_cmp(&alg_exp_node->key, key)) {
2671 hmap_remove(alg_expectations, &alg_exp_node->node);
2672 break;
2673 }
2674 }
2675 }
2676
2677 /* This function must be called with the ct->resources read lock taken. */
2678 static struct alg_exp_node *
2679 expectation_ref_lookup_unique(const struct hindex *alg_expectation_refs,
2680 const struct conn_key *parent_key,
2681 const struct conn_key *alg_exp_key,
2682 uint32_t basis)
2683 {
2684 struct alg_exp_node *alg_exp_node;
2685
2686 HINDEX_FOR_EACH_WITH_HASH (alg_exp_node, node_ref,
2687 conn_key_hash(parent_key, basis),
2688 alg_expectation_refs) {
2689 if (!conn_key_cmp(&alg_exp_node->parent_key, parent_key) &&
2690 !conn_key_cmp(&alg_exp_node->key, alg_exp_key)) {
2691 return alg_exp_node;
2692 }
2693 }
2694 return NULL;
2695 }
2696
2697 /* This function must be called with the ct->resources write lock taken. */
2698 static void
2699 expectation_ref_create(struct hindex *alg_expectation_refs,
2700 struct alg_exp_node *alg_exp_node,
2701 uint32_t basis)
2702 {
2703 if (!expectation_ref_lookup_unique(alg_expectation_refs,
2704 &alg_exp_node->parent_key,
2705 &alg_exp_node->key, basis)) {
2706 hindex_insert(alg_expectation_refs, &alg_exp_node->node_ref,
2707 conn_key_hash(&alg_exp_node->parent_key, basis));
2708 }
2709 }
2710
2711 static void
2712 expectation_clean(struct conntrack *ct, const struct conn_key *parent_key)
2713 {
2714 ovs_rwlock_wrlock(&ct->resources_lock);
2715
2716 struct alg_exp_node *node, *next;
2717 HINDEX_FOR_EACH_WITH_HASH_SAFE (node, next, node_ref,
2718 conn_key_hash(parent_key, ct->hash_basis),
2719 &ct->alg_expectation_refs) {
2720 if (!conn_key_cmp(&node->parent_key, parent_key)) {
2721 expectation_remove(&ct->alg_expectations, &node->key,
2722 ct->hash_basis);
2723 hindex_remove(&ct->alg_expectation_refs, &node->node_ref);
2724 free(node);
2725 }
2726 }
2727
2728 ovs_rwlock_unlock(&ct->resources_lock);
2729 }
2730
2731 static void
2732 expectation_create(struct conntrack *ct, ovs_be16 dst_port,
2733 const struct conn *parent_conn, bool reply, bool src_ip_wc,
2734 bool skip_nat)
2735 {
2736 union ct_addr src_addr;
2737 union ct_addr dst_addr;
2738 union ct_addr alg_nat_repl_addr;
2739 struct alg_exp_node *alg_exp_node = xzalloc(sizeof *alg_exp_node);
2740
2741 if (reply) {
2742 src_addr = parent_conn->key.src.addr;
2743 dst_addr = parent_conn->key.dst.addr;
2744 alg_exp_node->nat_rpl_dst = true;
2745 if (skip_nat) {
2746 alg_nat_repl_addr = dst_addr;
2747 } else if (parent_conn->nat_info &&
2748 parent_conn->nat_info->nat_action & NAT_ACTION_DST) {
2749 alg_nat_repl_addr = parent_conn->rev_key.src.addr;
2750 alg_exp_node->nat_rpl_dst = false;
2751 } else {
2752 alg_nat_repl_addr = parent_conn->rev_key.dst.addr;
2753 }
2754 } else {
2755 src_addr = parent_conn->rev_key.src.addr;
2756 dst_addr = parent_conn->rev_key.dst.addr;
2757 alg_exp_node->nat_rpl_dst = false;
2758 if (skip_nat) {
2759 alg_nat_repl_addr = src_addr;
2760 } else if (parent_conn->nat_info &&
2761 parent_conn->nat_info->nat_action & NAT_ACTION_DST) {
2762 alg_nat_repl_addr = parent_conn->key.dst.addr;
2763 alg_exp_node->nat_rpl_dst = true;
2764 } else {
2765 alg_nat_repl_addr = parent_conn->key.src.addr;
2766 }
2767 }
2768 if (src_ip_wc) {
2769 memset(&src_addr, 0, sizeof src_addr);
2770 }
2771
2772 alg_exp_node->key.dl_type = parent_conn->key.dl_type;
2773 alg_exp_node->key.nw_proto = parent_conn->key.nw_proto;
2774 alg_exp_node->key.zone = parent_conn->key.zone;
2775 alg_exp_node->key.src.addr = src_addr;
2776 alg_exp_node->key.dst.addr = dst_addr;
2777 alg_exp_node->key.src.port = ALG_WC_SRC_PORT;
2778 alg_exp_node->key.dst.port = dst_port;
2779 alg_exp_node->parent_mark = parent_conn->mark;
2780 alg_exp_node->parent_label = parent_conn->label;
2781 memcpy(&alg_exp_node->parent_key, &parent_conn->key,
2782 sizeof alg_exp_node->parent_key);
2783 /* Take the write lock here because it is almost 100%
2784 * likely that the lookup will fail and
2785 * expectation_create() will be called below. */
2786 ovs_rwlock_wrlock(&ct->resources_lock);
2787 struct alg_exp_node *alg_exp = expectation_lookup(
2788 &ct->alg_expectations, &alg_exp_node->key, ct->hash_basis, src_ip_wc);
2789 if (alg_exp) {
2790 free(alg_exp_node);
2791 ovs_rwlock_unlock(&ct->resources_lock);
2792 return;
2793 }
2794
2795 alg_exp_node->alg_nat_repl_addr = alg_nat_repl_addr;
2796 hmap_insert(&ct->alg_expectations, &alg_exp_node->node,
2797 conn_key_hash(&alg_exp_node->key, ct->hash_basis));
2798 expectation_ref_create(&ct->alg_expectation_refs, alg_exp_node,
2799 ct->hash_basis);
2800 ovs_rwlock_unlock(&ct->resources_lock);
2801 }
2802
2803 static void
2804 replace_substring(char *substr, uint8_t substr_size,
2805 uint8_t total_size, char *rep_str,
2806 uint8_t rep_str_size)
2807 {
2808 memmove(substr + rep_str_size, substr + substr_size,
2809 total_size - substr_size);
2810 memcpy(substr, rep_str, rep_str_size);
2811 }
2812
2813 static void
2814 repl_bytes(char *str, char c1, char c2)
2815 {
2816 while (*str) {
2817 if (*str == c1) {
2818 *str = c2;
2819 }
2820 str++;
2821 }
2822 }
2823
2824 static void
2825 modify_packet(struct dp_packet *pkt, char *pkt_str, size_t size,
2826 char *repl_str, size_t repl_size,
2827 uint32_t orig_used_size)
2828 {
2829 replace_substring(pkt_str, size,
2830 (const char *) dp_packet_tail(pkt) - pkt_str,
2831 repl_str, repl_size);
2832 dp_packet_set_size(pkt, orig_used_size + (int) repl_size - (int) size);
2833 }
2834
2835 /* Replace IPV4 address in FTP message with NATed address. */
2836 static int
2837 repl_ftp_v4_addr(struct dp_packet *pkt, ovs_be32 v4_addr_rep,
2838 char *ftp_data_start,
2839 size_t addr_offset_from_ftp_data_start,
2840 size_t addr_size OVS_UNUSED)
2841 {
2842 enum { MAX_FTP_V4_NAT_DELTA = 8 };
2843
2844 /* Do conservative check for pathological MTU usage. */
2845 uint32_t orig_used_size = dp_packet_size(pkt);
2846 if (orig_used_size + MAX_FTP_V4_NAT_DELTA >
2847 dp_packet_get_allocated(pkt)) {
2848
2849 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
2850 VLOG_WARN_RL(&rl, "Unsupported effective MTU %u used with FTP V4",
2851 dp_packet_get_allocated(pkt));
2852 return 0;
2853 }
2854
2855 char v4_addr_str[INET_ADDRSTRLEN] = {0};
2856 ovs_assert(inet_ntop(AF_INET, &v4_addr_rep, v4_addr_str,
2857 sizeof v4_addr_str));
2858 repl_bytes(v4_addr_str, '.', ',');
2859 modify_packet(pkt, ftp_data_start + addr_offset_from_ftp_data_start,
2860 addr_size, v4_addr_str, strlen(v4_addr_str),
2861 orig_used_size);
2862 return (int) strlen(v4_addr_str) - (int) addr_size;
2863 }
2864
2865 static char *
2866 skip_non_digits(char *str)
2867 {
2868 while (!isdigit(*str) && *str != 0) {
2869 str++;
2870 }
2871 return str;
2872 }
2873
2874 static char *
2875 terminate_number_str(char *str, uint8_t max_digits)
2876 {
2877 uint8_t digits_found = 0;
2878 while (isdigit(*str) && digits_found <= max_digits) {
2879 str++;
2880 digits_found++;
2881 }
2882
2883 *str = 0;
2884 return str;
2885 }
2886
2887
2888 static void
2889 get_ftp_ctl_msg(struct dp_packet *pkt, char *ftp_msg)
2890 {
2891 struct tcp_header *th = dp_packet_l4(pkt);
2892 char *tcp_hdr = (char *) th;
2893 uint32_t tcp_payload_len = tcp_payload_length(pkt);
2894 size_t tcp_payload_of_interest = MIN(tcp_payload_len,
2895 LARGEST_FTP_MSG_OF_INTEREST);
2896 size_t tcp_hdr_len = TCP_OFFSET(th->tcp_ctl) * 4;
2897
2898 ovs_strlcpy(ftp_msg, tcp_hdr + tcp_hdr_len,
2899 tcp_payload_of_interest);
2900 }
2901
2902 static enum ftp_ctl_pkt
2903 detect_ftp_ctl_type(const struct conn_lookup_ctx *ctx,
2904 struct dp_packet *pkt)
2905 {
2906 char ftp_msg[LARGEST_FTP_MSG_OF_INTEREST + 1] = {0};
2907 get_ftp_ctl_msg(pkt, ftp_msg);
2908
2909 if (ctx->key.dl_type == htons(ETH_TYPE_IPV6)) {
2910 if (strncasecmp(ftp_msg, FTP_EPRT_CMD, strlen(FTP_EPRT_CMD)) &&
2911 !strcasestr(ftp_msg, FTP_EPSV_REPLY)) {
2912 return CT_FTP_CTL_OTHER;
2913 }
2914 } else {
2915 if (strncasecmp(ftp_msg, FTP_PORT_CMD, strlen(FTP_PORT_CMD)) &&
2916 strncasecmp(ftp_msg, FTP_PASV_REPLY_CODE,
2917 strlen(FTP_PASV_REPLY_CODE))) {
2918 return CT_FTP_CTL_OTHER;
2919 }
2920 }
2921
2922 return CT_FTP_CTL_INTEREST;
2923 }
2924
2925 static enum ftp_ctl_pkt
2926 process_ftp_ctl_v4(struct conntrack *ct,
2927 struct dp_packet *pkt,
2928 const struct conn *conn_for_expectation,
2929 ovs_be32 *v4_addr_rep,
2930 char **ftp_data_v4_start,
2931 size_t *addr_offset_from_ftp_data_start,
2932 size_t *addr_size)
2933 {
2934 struct tcp_header *th = dp_packet_l4(pkt);
2935 size_t tcp_hdr_len = TCP_OFFSET(th->tcp_ctl) * 4;
2936 char *tcp_hdr = (char *) th;
2937 *ftp_data_v4_start = tcp_hdr + tcp_hdr_len;
2938 char ftp_msg[LARGEST_FTP_MSG_OF_INTEREST + 1] = {0};
2939 get_ftp_ctl_msg(pkt, ftp_msg);
2940 char *ftp = ftp_msg;
2941 enum ct_alg_mode mode;
2942
2943 if (!strncasecmp(ftp, FTP_PORT_CMD, strlen(FTP_PORT_CMD))) {
2944 ftp = ftp_msg + strlen(FTP_PORT_CMD);
2945 mode = CT_FTP_MODE_ACTIVE;
2946 } else {
2947 ftp = ftp_msg + strlen(FTP_PASV_REPLY_CODE);
2948 mode = CT_FTP_MODE_PASSIVE;
2949 }
2950
2951 /* Find first space. */
2952 ftp = strchr(ftp, ' ');
2953 if (!ftp) {
2954 return CT_FTP_CTL_INVALID;
2955 }
2956
2957 /* Find the first digit, after space. */
2958 ftp = skip_non_digits(ftp);
2959 if (*ftp == 0) {
2960 return CT_FTP_CTL_INVALID;
2961 }
2962
2963 char *ip_addr_start = ftp;
2964 *addr_offset_from_ftp_data_start = ip_addr_start - ftp_msg;
2965
2966 uint8_t comma_count = 0;
2967 while (comma_count < 4 && *ftp) {
2968 if (*ftp == ',') {
2969 comma_count++;
2970 if (comma_count == 4) {
2971 *ftp = 0;
2972 } else {
2973 *ftp = '.';
2974 }
2975 }
2976 ftp++;
2977 }
2978 if (comma_count != 4) {
2979 return CT_FTP_CTL_INVALID;
2980 }
2981
2982 struct in_addr ip_addr;
2983 int rc2 = inet_pton(AF_INET, ip_addr_start, &ip_addr);
2984 if (rc2 != 1) {
2985 return CT_FTP_CTL_INVALID;
2986 }
2987
2988 *addr_size = ftp - ip_addr_start - 1;
2989 char *save_ftp = ftp;
2990 ftp = terminate_number_str(ftp, MAX_FTP_PORT_DGTS);
2991 if (!ftp) {
2992 return CT_FTP_CTL_INVALID;
2993 }
2994 int value;
2995 if (!str_to_int(save_ftp, 10, &value)) {
2996 return CT_FTP_CTL_INVALID;
2997 }
2998
2999 /* This is derived from the L4 port maximum is 65535. */
3000 if (value > 255) {
3001 return CT_FTP_CTL_INVALID;
3002 }
3003
3004 uint16_t port_hs = value;
3005 port_hs <<= 8;
3006
3007 /* Skip over comma. */
3008 ftp++;
3009 save_ftp = ftp;
3010 bool digit_found = false;
3011 while (isdigit(*ftp)) {
3012 ftp++;
3013 digit_found = true;
3014 }
3015 if (!digit_found) {
3016 return CT_FTP_CTL_INVALID;
3017 }
3018 *ftp = 0;
3019 if (!str_to_int(save_ftp, 10, &value)) {
3020 return CT_FTP_CTL_INVALID;
3021 }
3022
3023 if (value > 255) {
3024 return CT_FTP_CTL_INVALID;
3025 }
3026
3027 port_hs |= value;
3028 ovs_be16 port = htons(port_hs);
3029 ovs_be32 conn_ipv4_addr;
3030
3031 switch (mode) {
3032 case CT_FTP_MODE_ACTIVE:
3033 *v4_addr_rep = conn_for_expectation->rev_key.dst.addr.ipv4;
3034 conn_ipv4_addr = conn_for_expectation->key.src.addr.ipv4;
3035 break;
3036 case CT_FTP_MODE_PASSIVE:
3037 *v4_addr_rep = conn_for_expectation->key.dst.addr.ipv4;
3038 conn_ipv4_addr = conn_for_expectation->rev_key.src.addr.ipv4;
3039 break;
3040 case CT_TFTP_MODE:
3041 default:
3042 OVS_NOT_REACHED();
3043 }
3044
3045 ovs_be32 ftp_ipv4_addr;
3046 ftp_ipv4_addr = ip_addr.s_addr;
3047 /* Although most servers will block this exploit, there may be some
3048 * less well managed. */
3049 if (ftp_ipv4_addr != conn_ipv4_addr && ftp_ipv4_addr != *v4_addr_rep) {
3050 return CT_FTP_CTL_INVALID;
3051 }
3052
3053 expectation_create(ct, port, conn_for_expectation,
3054 !!(pkt->md.ct_state & CS_REPLY_DIR), false, false);
3055 return CT_FTP_CTL_INTEREST;
3056 }
3057
3058 static char *
3059 skip_ipv6_digits(char *str)
3060 {
3061 while (isxdigit(*str) || *str == ':' || *str == '.') {
3062 str++;
3063 }
3064 return str;
3065 }
3066
3067 static enum ftp_ctl_pkt
3068 process_ftp_ctl_v6(struct conntrack *ct,
3069 struct dp_packet *pkt,
3070 const struct conn *conn_for_expectation,
3071 union ct_addr *v6_addr_rep, char **ftp_data_start,
3072 size_t *addr_offset_from_ftp_data_start,
3073 size_t *addr_size, enum ct_alg_mode *mode)
3074 {
3075 struct tcp_header *th = dp_packet_l4(pkt);
3076 size_t tcp_hdr_len = TCP_OFFSET(th->tcp_ctl) * 4;
3077 char *tcp_hdr = (char *) th;
3078 char ftp_msg[LARGEST_FTP_MSG_OF_INTEREST + 1] = {0};
3079 get_ftp_ctl_msg(pkt, ftp_msg);
3080 *ftp_data_start = tcp_hdr + tcp_hdr_len;
3081 char *ftp = ftp_msg;
3082 struct in6_addr ip6_addr;
3083
3084 if (!strncasecmp(ftp, FTP_EPRT_CMD, strlen(FTP_EPRT_CMD))) {
3085 ftp = ftp_msg + strlen(FTP_EPRT_CMD);
3086 ftp = skip_non_digits(ftp);
3087 if (*ftp != FTP_AF_V6 || isdigit(ftp[1])) {
3088 return CT_FTP_CTL_INVALID;
3089 }
3090 /* Jump over delimiter. */
3091 ftp += 2;
3092
3093 memset(&ip6_addr, 0, sizeof ip6_addr);
3094 char *ip_addr_start = ftp;
3095 *addr_offset_from_ftp_data_start = ip_addr_start - ftp_msg;
3096 ftp = skip_ipv6_digits(ftp);
3097 *ftp = 0;
3098 *addr_size = ftp - ip_addr_start;
3099 int rc2 = inet_pton(AF_INET6, ip_addr_start, &ip6_addr);
3100 if (rc2 != 1) {
3101 return CT_FTP_CTL_INVALID;
3102 }
3103 ftp++;
3104 *mode = CT_FTP_MODE_ACTIVE;
3105 } else {
3106 ftp = ftp_msg + strcspn(ftp_msg, "(");
3107 ftp = skip_non_digits(ftp);
3108 if (!isdigit(*ftp)) {
3109 return CT_FTP_CTL_INVALID;
3110 }
3111
3112 /* Not used for passive mode. */
3113 *addr_offset_from_ftp_data_start = 0;
3114 *addr_size = 0;
3115
3116 *mode = CT_FTP_MODE_PASSIVE;
3117 }
3118
3119 char *save_ftp = ftp;
3120 ftp = terminate_number_str(ftp, MAX_EXT_FTP_PORT_DGTS);
3121 if (!ftp) {
3122 return CT_FTP_CTL_INVALID;
3123 }
3124
3125 int value;
3126 if (!str_to_int(save_ftp, 10, &value)) {
3127 return CT_FTP_CTL_INVALID;
3128 }
3129 if (value > CT_MAX_L4_PORT) {
3130 return CT_FTP_CTL_INVALID;
3131 }
3132
3133 uint16_t port_hs = value;
3134 ovs_be16 port = htons(port_hs);
3135
3136 switch (*mode) {
3137 case CT_FTP_MODE_ACTIVE:
3138 *v6_addr_rep = conn_for_expectation->rev_key.dst.addr;
3139 /* Although most servers will block this exploit, there may be some
3140 * less well managed. */
3141 if (memcmp(&ip6_addr, &v6_addr_rep->ipv6, sizeof ip6_addr) &&
3142 memcmp(&ip6_addr, &conn_for_expectation->key.src.addr.ipv6,
3143 sizeof ip6_addr)) {
3144 return CT_FTP_CTL_INVALID;
3145 }
3146 break;
3147 case CT_FTP_MODE_PASSIVE:
3148 *v6_addr_rep = conn_for_expectation->key.dst.addr;
3149 break;
3150 case CT_TFTP_MODE:
3151 default:
3152 OVS_NOT_REACHED();
3153 }
3154
3155 expectation_create(ct, port, conn_for_expectation,
3156 !!(pkt->md.ct_state & CS_REPLY_DIR), false, false);
3157 return CT_FTP_CTL_INTEREST;
3158 }
3159
3160 static int
3161 repl_ftp_v6_addr(struct dp_packet *pkt, union ct_addr v6_addr_rep,
3162 char *ftp_data_start,
3163 size_t addr_offset_from_ftp_data_start,
3164 size_t addr_size, enum ct_alg_mode mode)
3165 {
3166 /* This is slightly bigger than really possible. */
3167 enum { MAX_FTP_V6_NAT_DELTA = 45 };
3168
3169 if (mode == CT_FTP_MODE_PASSIVE) {
3170 return 0;
3171 }
3172
3173 /* Do conservative check for pathological MTU usage. */
3174 uint32_t orig_used_size = dp_packet_size(pkt);
3175 if (orig_used_size + MAX_FTP_V6_NAT_DELTA >
3176 dp_packet_get_allocated(pkt)) {
3177
3178 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
3179 VLOG_WARN_RL(&rl, "Unsupported effective MTU %u used with FTP V6",
3180 dp_packet_get_allocated(pkt));
3181 return 0;
3182 }
3183
3184 char v6_addr_str[INET6_ADDRSTRLEN] = {0};
3185 ovs_assert(inet_ntop(AF_INET6, &v6_addr_rep.ipv6, v6_addr_str,
3186 sizeof v6_addr_str));
3187 modify_packet(pkt, ftp_data_start + addr_offset_from_ftp_data_start,
3188 addr_size, v6_addr_str, strlen(v6_addr_str),
3189 orig_used_size);
3190 return (int) strlen(v6_addr_str) - (int) addr_size;
3191 }
3192
3193 /* Increment/decrement a TCP sequence number. */
3194 static void
3195 adj_seqnum(ovs_16aligned_be32 *val, int32_t inc)
3196 {
3197 put_16aligned_be32(val, htonl(ntohl(get_16aligned_be32(val)) + inc));
3198 }
3199
3200 static void
3201 handle_ftp_ctl(struct conntrack *ct, const struct conn_lookup_ctx *ctx,
3202 struct dp_packet *pkt, struct conn *ec, long long now,
3203 enum ftp_ctl_pkt ftp_ctl, bool nat)
3204 {
3205 struct ip_header *l3_hdr = dp_packet_l3(pkt);
3206 ovs_be32 v4_addr_rep = 0;
3207 union ct_addr v6_addr_rep;
3208 size_t addr_offset_from_ftp_data_start = 0;
3209 size_t addr_size = 0;
3210 char *ftp_data_start;
3211 enum ct_alg_mode mode = CT_FTP_MODE_ACTIVE;
3212
3213 if (detect_ftp_ctl_type(ctx, pkt) != ftp_ctl) {
3214 return;
3215 }
3216
3217 struct ovs_16aligned_ip6_hdr *nh6 = dp_packet_l3(pkt);
3218 int64_t seq_skew = 0;
3219
3220 if (ftp_ctl == CT_FTP_CTL_INTEREST) {
3221 enum ftp_ctl_pkt rc;
3222 if (ctx->key.dl_type == htons(ETH_TYPE_IPV6)) {
3223 rc = process_ftp_ctl_v6(ct, pkt, ec,
3224 &v6_addr_rep, &ftp_data_start,
3225 &addr_offset_from_ftp_data_start,
3226 &addr_size, &mode);
3227 } else {
3228 rc = process_ftp_ctl_v4(ct, pkt, ec,
3229 &v4_addr_rep, &ftp_data_start,
3230 &addr_offset_from_ftp_data_start,
3231 &addr_size);
3232 }
3233 if (rc == CT_FTP_CTL_INVALID) {
3234 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
3235 VLOG_WARN_RL(&rl, "Invalid FTP control packet format");
3236 pkt->md.ct_state |= CS_TRACKED | CS_INVALID;
3237 return;
3238 } else if (rc == CT_FTP_CTL_INTEREST) {
3239 uint16_t ip_len;
3240
3241 if (ctx->key.dl_type == htons(ETH_TYPE_IPV6)) {
3242 if (nat) {
3243 seq_skew = repl_ftp_v6_addr(pkt, v6_addr_rep,
3244 ftp_data_start,
3245 addr_offset_from_ftp_data_start,
3246 addr_size, mode);
3247 }
3248
3249 if (seq_skew) {
3250 ip_len = ntohs(nh6->ip6_ctlun.ip6_un1.ip6_un1_plen) +
3251 seq_skew;
3252 nh6->ip6_ctlun.ip6_un1.ip6_un1_plen = htons(ip_len);
3253 }
3254 } else {
3255 if (nat) {
3256 seq_skew = repl_ftp_v4_addr(pkt, v4_addr_rep,
3257 ftp_data_start,
3258 addr_offset_from_ftp_data_start,
3259 addr_size);
3260 }
3261 if (seq_skew) {
3262 ip_len = ntohs(l3_hdr->ip_tot_len) + seq_skew;
3263 if (!dp_packet_hwol_is_ipv4(pkt)) {
3264 l3_hdr->ip_csum = recalc_csum16(l3_hdr->ip_csum,
3265 l3_hdr->ip_tot_len,
3266 htons(ip_len));
3267 }
3268 l3_hdr->ip_tot_len = htons(ip_len);
3269 }
3270 }
3271 } else {
3272 OVS_NOT_REACHED();
3273 }
3274 }
3275
3276 struct tcp_header *th = dp_packet_l4(pkt);
3277
3278 if (nat && ec->seq_skew != 0) {
3279 ctx->reply != ec->seq_skew_dir ?
3280 adj_seqnum(&th->tcp_ack, -ec->seq_skew) :
3281 adj_seqnum(&th->tcp_seq, ec->seq_skew);
3282 }
3283
3284 th->tcp_csum = 0;
3285 if (!dp_packet_hwol_tx_l4_checksum(pkt)) {
3286 if (ctx->key.dl_type == htons(ETH_TYPE_IPV6)) {
3287 th->tcp_csum = packet_csum_upperlayer6(nh6, th, ctx->key.nw_proto,
3288 dp_packet_l4_size(pkt));
3289 } else {
3290 uint32_t tcp_csum = packet_csum_pseudoheader(l3_hdr);
3291 th->tcp_csum = csum_finish(
3292 csum_continue(tcp_csum, th, dp_packet_l4_size(pkt)));
3293 }
3294 }
3295
3296 if (seq_skew) {
3297 conn_seq_skew_set(ct, ec, now, seq_skew + ec->seq_skew,
3298 ctx->reply);
3299 }
3300 }
3301
3302 static void
3303 handle_tftp_ctl(struct conntrack *ct,
3304 const struct conn_lookup_ctx *ctx OVS_UNUSED,
3305 struct dp_packet *pkt, struct conn *conn_for_expectation,
3306 long long now OVS_UNUSED, enum ftp_ctl_pkt ftp_ctl OVS_UNUSED,
3307 bool nat OVS_UNUSED)
3308 {
3309 expectation_create(ct, conn_for_expectation->key.src.port,
3310 conn_for_expectation,
3311 !!(pkt->md.ct_state & CS_REPLY_DIR), false, false);
3312 }