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