You need to sign in or sign up before continuing.
viriptables.c 30.3 KB
Newer Older
1
/*
2 3
 * viriptables.c: helper APIs for managing iptables
 *
4
 * Copyright (C) 2007-2013 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23
 *
 * Authors:
 *     Mark McLoughlin <markmc@redhat.com>
 */

24
#include <config.h>
25 26 27 28 29 30 31 32 33 34 35

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
E
Eric Blake 已提交
36
#include <sys/wait.h>
37 38

#ifdef HAVE_PATHS_H
39
# include <paths.h>
40
#endif
41

42
#include "internal.h"
43
#include "viriptables.h"
44
#include "vircommand.h"
45
#include "viralloc.h"
46
#include "virerror.h"
47
#include "virlog.h"
48
#include "virthread.h"
49 50
#include "virstring.h"
#include "virutil.h"
51 52 53 54 55 56 57 58 59

#if HAVE_FIREWALLD
static char *firewall_cmd_path = NULL;

static int
virIpTablesOnceInit(void)
{
    firewall_cmd_path = virFindFileInPath("firewall-cmd");
    if (!firewall_cmd_path) {
60
        VIR_INFO("firewall-cmd not found on system. "
61 62 63 64 65 66 67
                 "firewalld support disabled for iptables.");
    } else {
        virCommandPtr cmd = virCommandNew(firewall_cmd_path);
        int status;

        virCommandAddArgList(cmd, "--state", NULL);
        if (virCommandRun(cmd, &status) < 0 || status != 0) {
68
            VIR_INFO("firewall-cmd found but disabled for iptables");
69 70 71
            VIR_FREE(firewall_cmd_path);
            firewall_cmd_path = NULL;
        } else {
72
            VIR_INFO("using firewalld for iptables commands");
73 74 75 76 77 78 79 80 81
        }
        virCommandFree(cmd);
    }
    return 0;
}

VIR_ONCE_GLOBAL_INIT(virIpTables)

#endif
82

83
#define VIR_FROM_THIS VIR_FROM_NONE
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
enum {
    ADD = 0,
    REMOVE
};

typedef struct
{
    char  *table;
    char  *chain;
} iptRules;

struct _iptablesContext
{
    iptRules *input_filter;
    iptRules *forward_filter;
    iptRules *nat_postrouting;
101
    iptRules *mangle_postrouting;
102 103 104 105 106
};

static void
iptRulesFree(iptRules *rules)
{
107 108
    VIR_FREE(rules->table);
    VIR_FREE(rules->chain);
109
    VIR_FREE(rules);
110 111 112 113 114 115 116 117
}

static iptRules *
iptRulesNew(const char *table,
            const char *chain)
{
    iptRules *rules;

118
    if (VIR_ALLOC(rules) < 0)
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        return NULL;

    if (!(rules->table = strdup(table)))
        goto error;

    if (!(rules->chain = strdup(chain)))
        goto error;

    return rules;

 error:
    iptRulesFree(rules);
    return NULL;
}

134 135
static virCommandPtr
iptablesCommandNew(iptRules *rules, int family, int action)
136
{
137 138 139 140 141 142 143 144 145 146 147 148
    virCommandPtr cmd = NULL;
#if HAVE_FIREWALLD
    virIpTablesInitialize();
    if (firewall_cmd_path) {
        cmd = virCommandNew(firewall_cmd_path);
        virCommandAddArgList(cmd, "--direct", "--passthrough",
                             (family == AF_INET6) ? "ipv6" : "ipv4", NULL);
    }
#endif

    if (cmd == NULL) {
        cmd = virCommandNew((family == AF_INET6)
149
                        ? IP6TABLES_PATH : IPTABLES_PATH);
150
    }
151

152 153
    virCommandAddArgList(cmd, "--table", rules->table,
                         action == ADD ? "--insert" : "--delete",
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
                         rules->chain, NULL);
    return cmd;
}

static int
iptablesCommandRunAndFree(virCommandPtr cmd)
{
    int ret;
    ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
}

static int ATTRIBUTE_SENTINEL
iptablesAddRemoveRule(iptRules *rules, int family, int action,
                      const char *arg, ...)
{
    va_list args;
    virCommandPtr cmd = NULL;
    const char *s;

    cmd = iptablesCommandNew(rules, family, action);
    virCommandAddArg(cmd, arg);
177 178

    va_start(args, arg);
179 180
    while ((s = va_arg(args, const char *)))
        virCommandAddArg(cmd, s);
181 182
    va_end(args);

183
    return iptablesCommandRunAndFree(cmd);
184 185
}

186 187 188 189 190 191 192
/**
 * iptablesContextNew:
 *
 * Create a new IPtable context
 *
 * Returns a pointer to the new structure or NULL in case of error
 */
193 194 195 196 197
iptablesContext *
iptablesContextNew(void)
{
    iptablesContext *ctx;

198
    if (VIR_ALLOC(ctx) < 0)
199 200
        return NULL;

201
    if (!(ctx->input_filter = iptRulesNew("filter", "INPUT")))
202 203
        goto error;

204
    if (!(ctx->forward_filter = iptRulesNew("filter", "FORWARD")))
205 206
        goto error;

207
    if (!(ctx->nat_postrouting = iptRulesNew("nat", "POSTROUTING")))
208 209
        goto error;

210 211 212
    if (!(ctx->mangle_postrouting = iptRulesNew("mangle", "POSTROUTING")))
        goto error;

213 214 215 216 217 218 219
    return ctx;

 error:
    iptablesContextFree(ctx);
    return NULL;
}

220 221 222 223
/**
 * iptablesContextFree:
 * @ctx: pointer to the IP table context
 *
R
Richard W.M. Jones 已提交
224
 * Free the resources associated with an IP table context
225
 */
226 227 228
void
iptablesContextFree(iptablesContext *ctx)
{
229 230 231 232 233 234
    if (ctx->input_filter)
        iptRulesFree(ctx->input_filter);
    if (ctx->forward_filter)
        iptRulesFree(ctx->forward_filter);
    if (ctx->nat_postrouting)
        iptRulesFree(ctx->nat_postrouting);
235 236
    if (ctx->mangle_postrouting)
        iptRulesFree(ctx->mangle_postrouting);
237
    VIR_FREE(ctx);
238 239 240 241
}

static int
iptablesInput(iptablesContext *ctx,
242
              int family,
243 244 245 246 247 248 249 250 251 252
              const char *iface,
              int port,
              int action,
              int tcp)
{
    char portstr[32];

    snprintf(portstr, sizeof(portstr), "%d", port);
    portstr[sizeof(portstr) - 1] = '\0';

253
    return iptablesAddRemoveRule(ctx->input_filter,
254
                                 family,
255 256 257 258 259 260
                                 action,
                                 "--in-interface", iface,
                                 "--protocol", tcp ? "tcp" : "udp",
                                 "--destination-port", portstr,
                                 "--jump", "ACCEPT",
                                 NULL);
261 262
}

263 264 265 266 267 268 269 270 271 272 273 274
/**
 * iptablesAddTcpInput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the TCP port to add
 *
 * Add an input to the IP table allowing access to the given @port on
 * the given @iface interface for TCP packets
 *
 * Returns 0 in case of success or an error code in case of error
 */

275 276
int
iptablesAddTcpInput(iptablesContext *ctx,
277
                    int family,
278 279 280
                    const char *iface,
                    int port)
{
281
    return iptablesInput(ctx, family, iface, port, ADD, 1);
282 283
}

284 285 286 287 288 289
/**
 * iptablesRemoveTcpInput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the TCP port to remove
 *
R
Richard W.M. Jones 已提交
290
 * Removes an input from the IP table, hence forbidding access to the given
291 292 293 294
 * @port on the given @iface interface for TCP packets
 *
 * Returns 0 in case of success or an error code in case of error
 */
295 296
int
iptablesRemoveTcpInput(iptablesContext *ctx,
297
                       int family,
298 299 300
                       const char *iface,
                       int port)
{
301
    return iptablesInput(ctx, family, iface, port, REMOVE, 1);
302 303
}

304 305 306 307 308 309 310 311 312 313 314 315
/**
 * iptablesAddUdpInput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to add
 *
 * Add an input to the IP table allowing access to the given @port on
 * the given @iface interface for UDP packets
 *
 * Returns 0 in case of success or an error code in case of error
 */

316 317
int
iptablesAddUdpInput(iptablesContext *ctx,
318
                    int family,
319 320 321
                    const char *iface,
                    int port)
{
322
    return iptablesInput(ctx, family, iface, port, ADD, 0);
323 324
}

325 326 327 328 329 330
/**
 * iptablesRemoveUdpInput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to remove
 *
R
Richard W.M. Jones 已提交
331
 * Removes an input from the IP table, hence forbidding access to the given
332 333 334 335
 * @port on the given @iface interface for UDP packets
 *
 * Returns 0 in case of success or an error code in case of error
 */
336 337
int
iptablesRemoveUdpInput(iptablesContext *ctx,
338
                       int family,
339 340 341
                       const char *iface,
                       int port)
{
342
    return iptablesInput(ctx, family, iface, port, REMOVE, 0);
343 344 345
}


346
static char *iptablesFormatNetwork(virSocketAddr *netaddr,
347
                                   unsigned int prefix)
348 349 350 351 352
{
    virSocketAddr network;
    char *netstr;
    char *ret;

353 354
    if (!(VIR_SOCKET_ADDR_IS_FAMILY(netaddr, AF_INET) ||
          VIR_SOCKET_ADDR_IS_FAMILY(netaddr, AF_INET6))) {
355 356
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Only IPv4 or IPv6 addresses can be used with iptables"));
357 358 359
        return NULL;
    }

360
    if (virSocketAddrMaskByPrefix(netaddr, prefix, &network) < 0) {
361 362
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failure to mask address"));
363 364
        return NULL;
    }
365

366
    netstr = virSocketAddrFormat(&network);
367 368 369 370 371 372 373 374 375 376 377 378

    if (!netstr)
        return NULL;

    if (virAsprintf(&ret, "%s/%d", netstr, prefix) < 0)
        virReportOOMError();

    VIR_FREE(netstr);
    return ret;
}


379 380 381
/* Allow all traffic coming from the bridge, with a valid network address
 * to proceed to WAN
 */
382
static int
383
iptablesForwardAllowOut(iptablesContext *ctx,
384
                        virSocketAddr *netaddr,
385
                        unsigned int prefix,
386 387 388
                        const char *iface,
                        const char *physdev,
                        int action)
389
{
390 391
    int ret;
    char *networkstr;
392
    virCommandPtr cmd = NULL;
393

394
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
395 396
        return -1;

397 398 399 400 401 402 403 404 405 406 407 408 409
    cmd = iptablesCommandNew(ctx->forward_filter,
                             VIR_SOCKET_ADDR_FAMILY(netaddr),
                             action);
    virCommandAddArgList(cmd,
                         "--source", networkstr,
                         "--in-interface", iface, NULL);

    if (physdev && physdev[0])
        virCommandAddArgList(cmd, "--out-interface", physdev, NULL);

    virCommandAddArgList(cmd, "--jump", "ACCEPT", NULL);

    ret = iptablesCommandRunAndFree(cmd);
410 411
    VIR_FREE(networkstr);
    return ret;
412 413
}

414 415 416 417 418 419
/**
 * iptablesAddForwardAllowOut:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the source interface name
 * @physdev: the physical output device
420
 *
421 422 423 424 425 426
 * Add a rule to the IP table context to allow the traffic for the
 * network @network via interface @iface to be forwarded to
 * @physdev device. This allow the outbound traffic on a bridge.
 *
 * Returns 0 in case of success or an error code otherwise
 */
427
int
428
iptablesAddForwardAllowOut(iptablesContext *ctx,
429
                           virSocketAddr *netaddr,
430
                           unsigned int prefix,
431 432
                           const char *iface,
                           const char *physdev)
433
{
434
    return iptablesForwardAllowOut(ctx, netaddr, prefix, iface, physdev, ADD);
435 436
}

437 438 439 440 441 442
/**
 * iptablesRemoveForwardAllowOut:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the source interface name
 * @physdev: the physical output device
443
 *
444 445 446 447 448 449
 * Remove a rule from the IP table context hence forbidding forwarding
 * of the traffic for the network @network via interface @iface
 * to the @physdev device output. This stops the outbound traffic on a bridge.
 *
 * Returns 0 in case of success or an error code otherwise
 */
450
int
451
iptablesRemoveForwardAllowOut(iptablesContext *ctx,
452
                              virSocketAddr *netaddr,
453
                              unsigned int prefix,
454 455
                              const char *iface,
                              const char *physdev)
456
{
457
    return iptablesForwardAllowOut(ctx, netaddr, prefix, iface, physdev, REMOVE);
458 459
}

460 461 462 463

/* Allow all traffic destined to the bridge, with a valid network address
 * and associated with an existing connection
 */
464
static int
465
iptablesForwardAllowRelatedIn(iptablesContext *ctx,
466
                              virSocketAddr *netaddr,
467
                              unsigned int prefix,
468 469 470
                              const char *iface,
                              const char *physdev,
                              int action)
471
{
472 473 474
    int ret;
    char *networkstr;

475
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
476 477
        return -1;

478
    if (physdev && physdev[0]) {
479
        ret = iptablesAddRemoveRule(ctx->forward_filter,
480
                                    VIR_SOCKET_ADDR_FAMILY(netaddr),
481 482 483 484
                                    action,
                                    "--destination", networkstr,
                                    "--in-interface", physdev,
                                    "--out-interface", iface,
S
Stefan Seyfried 已提交
485 486
                                    "--match", "conntrack",
                                    "--ctstate", "ESTABLISHED,RELATED",
487 488
                                    "--jump", "ACCEPT",
                                    NULL);
489
    } else {
490
        ret = iptablesAddRemoveRule(ctx->forward_filter,
491
                                    VIR_SOCKET_ADDR_FAMILY(netaddr),
492 493 494
                                    action,
                                    "--destination", networkstr,
                                    "--out-interface", iface,
S
Stefan Seyfried 已提交
495 496
                                    "--match", "conntrack",
                                    "--ctstate", "ESTABLISHED,RELATED",
497 498
                                    "--jump", "ACCEPT",
                                    NULL);
499
    }
500 501
    VIR_FREE(networkstr);
    return ret;
502 503
}

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
/**
 * iptablesAddForwardAllowRelatedIn:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the output interface name
 * @physdev: the physical input device or NULL
 *
 * Add rules to the IP table context to allow the traffic for the
 * network @network on @physdev device to be forwarded to
 * interface @iface, if it is part of an existing connection.
 *
 * Returns 0 in case of success or an error code otherwise
 */
int
iptablesAddForwardAllowRelatedIn(iptablesContext *ctx,
519
                                 virSocketAddr *netaddr,
520
                                 unsigned int prefix,
521 522
                                 const char *iface,
                                 const char *physdev)
523
{
524
    return iptablesForwardAllowRelatedIn(ctx, netaddr, prefix, iface, physdev, ADD);
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
}

/**
 * iptablesRemoveForwardAllowRelatedIn:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the output interface name
 * @physdev: the physical input device or NULL
 *
 * Remove rules from the IP table context hence forbidding the traffic for
 * network @network on @physdev device to be forwarded to
 * interface @iface, if it is part of an existing connection.
 *
 * Returns 0 in case of success or an error code otherwise
 */
int
iptablesRemoveForwardAllowRelatedIn(iptablesContext *ctx,
542
                                    virSocketAddr *netaddr,
543
                                    unsigned int prefix,
544 545
                                    const char *iface,
                                    const char *physdev)
546
{
547
    return iptablesForwardAllowRelatedIn(ctx, netaddr, prefix, iface, physdev, REMOVE);
548 549 550 551 552 553
}

/* Allow all traffic destined to the bridge, with a valid network address
 */
static int
iptablesForwardAllowIn(iptablesContext *ctx,
554
                       virSocketAddr *netaddr,
555
                       unsigned int prefix,
556 557 558 559
                       const char *iface,
                       const char *physdev,
                       int action)
{
560 561 562
    int ret;
    char *networkstr;

563
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
564 565
        return -1;

566
    if (physdev && physdev[0]) {
567
        ret = iptablesAddRemoveRule(ctx->forward_filter,
568
                                    VIR_SOCKET_ADDR_FAMILY(netaddr),
569 570 571 572 573 574
                                    action,
                                    "--destination", networkstr,
                                    "--in-interface", physdev,
                                    "--out-interface", iface,
                                    "--jump", "ACCEPT",
                                    NULL);
575
    } else {
576
        ret = iptablesAddRemoveRule(ctx->forward_filter,
577
                                    VIR_SOCKET_ADDR_FAMILY(netaddr),
578 579 580 581 582
                                    action,
                                    "--destination", networkstr,
                                    "--out-interface", iface,
                                    "--jump", "ACCEPT",
                                    NULL);
583
    }
584 585
    VIR_FREE(networkstr);
    return ret;
586 587
}

588 589 590 591 592 593
/**
 * iptablesAddForwardAllowIn:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the output interface name
 * @physdev: the physical input device or NULL
594
 *
595 596 597 598 599 600
 * Add rules to the IP table context to allow the traffic for the
 * network @network on @physdev device to be forwarded to
 * interface @iface. This allow the inbound traffic on a bridge.
 *
 * Returns 0 in case of success or an error code otherwise
 */
601
int
602
iptablesAddForwardAllowIn(iptablesContext *ctx,
603
                          virSocketAddr *netaddr,
604
                          unsigned int prefix,
605 606 607
                          const char *iface,
                          const char *physdev)
{
608
    return iptablesForwardAllowIn(ctx, netaddr, prefix, iface, physdev, ADD);
609 610
}

611 612 613 614 615 616
/**
 * iptablesRemoveForwardAllowIn:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the output interface name
 * @physdev: the physical input device or NULL
617
 *
618 619 620 621 622 623
 * Remove rules from the IP table context hence forbidding the traffic for
 * network @network on @physdev device to be forwarded to
 * interface @iface. This stops the inbound traffic on a bridge.
 *
 * Returns 0 in case of success or an error code otherwise
 */
624 625
int
iptablesRemoveForwardAllowIn(iptablesContext *ctx,
626
                             virSocketAddr *netaddr,
627
                             unsigned int prefix,
628 629 630
                             const char *iface,
                             const char *physdev)
{
631
    return iptablesForwardAllowIn(ctx, netaddr, prefix, iface, physdev, REMOVE);
632 633 634 635 636 637 638 639
}


/* Allow all traffic between guests on the same bridge,
 * with a valid network address
 */
static int
iptablesForwardAllowCross(iptablesContext *ctx,
640
                          int family,
641 642 643 644
                          const char *iface,
                          int action)
{
    return iptablesAddRemoveRule(ctx->forward_filter,
645
                                 family,
646 647 648 649 650 651 652
                                 action,
                                 "--in-interface", iface,
                                 "--out-interface", iface,
                                 "--jump", "ACCEPT",
                                 NULL);
}

653 654 655 656 657 658 659 660 661 662 663
/**
 * iptablesAddForwardAllowCross:
 * @ctx: pointer to the IP table context
 * @iface: the input/output interface name
 *
 * Add rules to the IP table context to allow traffic to cross that
 * interface. It allows all traffic between guests on the same bridge
 * represented by that interface.
 *
 * Returns 0 in case of success or an error code otherwise
 */
664 665
int
iptablesAddForwardAllowCross(iptablesContext *ctx,
666 667 668 669
                             int family,
                             const char *iface)
{
    return iptablesForwardAllowCross(ctx, family, iface, ADD);
670 671
}

672 673 674 675 676 677 678 679 680 681 682
/**
 * iptablesRemoveForwardAllowCross:
 * @ctx: pointer to the IP table context
 * @iface: the input/output interface name
 *
 * Remove rules to the IP table context to block traffic to cross that
 * interface. It forbids traffic between guests on the same bridge
 * represented by that interface.
 *
 * Returns 0 in case of success or an error code otherwise
 */
683 684
int
iptablesRemoveForwardAllowCross(iptablesContext *ctx,
685 686 687 688
                                int family,
                                const char *iface)
{
    return iptablesForwardAllowCross(ctx, family, iface, REMOVE);
689 690 691 692 693 694 695 696
}


/* Drop all traffic trying to forward from the bridge.
 * ie the bridge is the in interface
 */
static int
iptablesForwardRejectOut(iptablesContext *ctx,
697
                         int family,
698 699 700 701
                         const char *iface,
                         int action)
{
    return iptablesAddRemoveRule(ctx->forward_filter,
702 703 704 705 706
                                 family,
                                 action,
                                 "--in-interface", iface,
                                 "--jump", "REJECT",
                                 NULL);
707 708
}

709 710 711 712 713 714 715 716 717 718
/**
 * iptablesAddForwardRejectOut:
 * @ctx: pointer to the IP table context
 * @iface: the output interface name
 *
 * Add rules to the IP table context to forbid all traffic to that
 * interface. It forbids forwarding from the bridge to that interface.
 *
 * Returns 0 in case of success or an error code otherwise
 */
719 720
int
iptablesAddForwardRejectOut(iptablesContext *ctx,
721
                            int family,
722 723
                            const char *iface)
{
724
    return iptablesForwardRejectOut(ctx, family, iface, ADD);
725 726
}

727 728 729 730 731 732 733 734 735 736
/**
 * iptablesRemoveForwardRejectOut:
 * @ctx: pointer to the IP table context
 * @iface: the output interface name
 *
 * Remove rules from the IP table context forbidding all traffic to that
 * interface. It reallow forwarding from the bridge to that interface.
 *
 * Returns 0 in case of success or an error code otherwise
 */
737 738
int
iptablesRemoveForwardRejectOut(iptablesContext *ctx,
739
                               int family,
740 741
                               const char *iface)
{
742
    return iptablesForwardRejectOut(ctx, family, iface, REMOVE);
743 744 745 746 747 748 749 750 751 752
}




/* Drop all traffic trying to forward to the bridge.
 * ie the bridge is the out interface
 */
static int
iptablesForwardRejectIn(iptablesContext *ctx,
753
                        int family,
754
                        const char *iface,
755 756 757
                        int action)
{
    return iptablesAddRemoveRule(ctx->forward_filter,
758
                                 family,
759 760 761 762 763 764
                                 action,
                                 "--out-interface", iface,
                                 "--jump", "REJECT",
                                 NULL);
}

765 766 767 768 769 770 771 772 773 774
/**
 * iptablesAddForwardRejectIn:
 * @ctx: pointer to the IP table context
 * @iface: the input interface name
 *
 * Add rules to the IP table context to forbid all traffic from that
 * interface. It forbids forwarding from that interface to the bridge.
 *
 * Returns 0 in case of success or an error code otherwise
 */
775 776
int
iptablesAddForwardRejectIn(iptablesContext *ctx,
777
                           int family,
778
                           const char *iface)
779
{
780
    return iptablesForwardRejectIn(ctx, family, iface, ADD);
781 782
}

783 784 785 786 787 788 789 790 791 792
/**
 * iptablesRemoveForwardRejectIn:
 * @ctx: pointer to the IP table context
 * @iface: the input interface name
 *
 * Remove rules from the IP table context forbidding all traffic from that
 * interface. It allows forwarding from that interface to the bridge.
 *
 * Returns 0 in case of success or an error code otherwise
 */
793
int
794
iptablesRemoveForwardRejectIn(iptablesContext *ctx,
795
                              int family,
796
                              const char *iface)
797
{
798
    return iptablesForwardRejectIn(ctx, family, iface, REMOVE);
799 800
}

801 802 803 804

/* Masquerade all traffic coming from the network associated
 * with the bridge
 */
805
static int
806
iptablesForwardMasquerade(iptablesContext *ctx,
807
                          virSocketAddr *netaddr,
808
                          unsigned int prefix,
809
                          const char *physdev,
810 811
                          virSocketAddrRangePtr addr,
                          virPortRangePtr port,
812 813
                          const char *protocol,
                          int action)
814
{
815 816 817 818
    int ret = -1;
    char *networkstr = NULL;
    char *addrStartStr = NULL;
    char *addrEndStr = NULL;
819
    char *portRangeStr = NULL;
820
    char *natRangeStr = NULL;
821
    virCommandPtr cmd = NULL;
822

823
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
824 825
        return -1;

826
    if (!VIR_SOCKET_ADDR_IS_FAMILY(netaddr, AF_INET)) {
827
        /* Higher level code *should* guaranteee it's impossible to get here. */
828 829 830
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Attempted to NAT '%s'. NAT is only supported for IPv4."),
                       networkstr);
831 832 833
        goto cleanup;
    }

834 835
    if (VIR_SOCKET_ADDR_IS_FAMILY(&addr->start, AF_INET)) {
        if (!(addrStartStr = virSocketAddrFormat(&addr->start)))
836
            goto cleanup;
837 838
        if (VIR_SOCKET_ADDR_IS_FAMILY(&addr->end, AF_INET)) {
            if (!(addrEndStr = virSocketAddrFormat(&addr->end)))
839 840
                goto cleanup;
        }
841 842
    }

843 844 845 846 847 848 849 850 851 852 853
    cmd = iptablesCommandNew(ctx->nat_postrouting, AF_INET, action);
    virCommandAddArgList(cmd, "--source", networkstr, NULL);

    if (protocol && protocol[0])
        virCommandAddArgList(cmd, "-p", protocol, NULL);

    virCommandAddArgList(cmd, "!", "--destination", networkstr, NULL);

    if (physdev && physdev[0])
        virCommandAddArgList(cmd, "--out-interface", physdev, NULL);

854
    if (protocol && protocol[0]) {
855 856 857
        if (port->start == 0 && port->end == 0) {
            port->start = 1024;
            port->end = 65535;
858 859
        }

860 861 862
        if (port->start < port->end && port->end < 65536) {
            if (virAsprintf(&portRangeStr, ":%u-%u",
                            port->start, port->end) < 0) {
863 864 865 866 867 868
                virReportOOMError();
                goto cleanup;
            }
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid port range '%u-%u'."),
869
                           port->start, port->end);
870 871 872
        }
    }

873 874 875
    /* Use --jump SNAT if public addr is specified */
    if (addrStartStr && addrStartStr[0]) {
        int r = 0;
876

877 878
        if (addrEndStr && addrEndStr[0]) {
            r = virAsprintf(&natRangeStr, "%s-%s%s", addrStartStr, addrEndStr,
879
                            portRangeStr ? portRangeStr : "");
880
        } else {
881 882
            r = virAsprintf(&natRangeStr, "%s%s", addrStartStr,
                            portRangeStr ? portRangeStr : "");
883 884 885 886 887 888 889 890 891 892 893 894
        }

        if (r < 0) {
            virReportOOMError();
            goto cleanup;
        }

        virCommandAddArgList(cmd, "--jump", "SNAT",
                                  "--to-source", natRangeStr, NULL);
     } else {
         virCommandAddArgList(cmd, "--jump", "MASQUERADE", NULL);

895 896
         if (portRangeStr && portRangeStr[0])
             virCommandAddArgList(cmd, "--to-ports", &portRangeStr[1], NULL);
897 898 899 900 901
     }

    ret = virCommandRun(cmd, NULL);
cleanup:
    virCommandFree(cmd);
902
    VIR_FREE(networkstr);
903 904
    VIR_FREE(addrStartStr);
    VIR_FREE(addrEndStr);
905
    VIR_FREE(portRangeStr);
906
    VIR_FREE(natRangeStr);
907
    return ret;
908 909
}

910 911 912 913 914
/**
 * iptablesAddForwardMasquerade:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @physdev: the physical input device or NULL
915
 * @protocol: the network protocol or NULL
916
 *
917 918 919 920 921 922
 * Add rules to the IP table context to allow masquerading
 * network @network on @physdev. This allow the bridge to
 * masquerade for that network (on @physdev).
 *
 * Returns 0 in case of success or an error code otherwise
 */
923
int
924
iptablesAddForwardMasquerade(iptablesContext *ctx,
925
                             virSocketAddr *netaddr,
926
                             unsigned int prefix,
927
                             const char *physdev,
928 929
                             virSocketAddrRangePtr addr,
                             virPortRangePtr port,
930
                             const char *protocol)
931
{
932
    return iptablesForwardMasquerade(ctx, netaddr, prefix, physdev, addr, port,
933
                                     protocol, ADD);
934 935
}

936 937 938 939 940
/**
 * iptablesRemoveForwardMasquerade:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @physdev: the physical input device or NULL
941
 * @protocol: the network protocol or NULL
942
 *
943 944 945 946 947 948
 * Remove rules from the IP table context to stop masquerading
 * network @network on @physdev. This stops the bridge from
 * masquerading for that network (on @physdev).
 *
 * Returns 0 in case of success or an error code otherwise
 */
949
int
950
iptablesRemoveForwardMasquerade(iptablesContext *ctx,
951
                                virSocketAddr *netaddr,
952
                                unsigned int prefix,
953
                                const char *physdev,
954 955
                                virSocketAddrRangePtr addr,
                                virPortRangePtr port,
956
                                const char *protocol)
957
{
958
    return iptablesForwardMasquerade(ctx, netaddr, prefix, physdev, addr, port,
959
                                     protocol, REMOVE);
960
}
961 962 963 964 965 966 967 968 969 970 971 972 973 974


static int
iptablesOutputFixUdpChecksum(iptablesContext *ctx,
                             const char *iface,
                             int port,
                             int action)
{
    char portstr[32];

    snprintf(portstr, sizeof(portstr), "%d", port);
    portstr[sizeof(portstr) - 1] = '\0';

    return iptablesAddRemoveRule(ctx->mangle_postrouting,
975
                                 AF_INET,
976 977 978 979 980 981 982 983 984 985 986 987 988 989
                                 action,
                                 "--out-interface", iface,
                                 "--protocol", "udp",
                                 "--destination-port", portstr,
                                 "--jump", "CHECKSUM", "--checksum-fill",
                                 NULL);
}

/**
 * iptablesAddOutputFixUdpChecksum:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to match
 *
E
Eric Blake 已提交
990
 * Add a rule to the mangle table's POSTROUTING chain that fixes up the
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
 * checksum of packets with the given destination @port.
 * the given @iface interface for TCP packets.
 *
 * Returns 0 in case of success or an error code in case of error.
 * (NB: if the system's iptables does not support checksum mangling,
 * this will return an error, which should be ignored.)
 */

int
iptablesAddOutputFixUdpChecksum(iptablesContext *ctx,
                                const char *iface,
                                int port)
{
    return iptablesOutputFixUdpChecksum(ctx, iface, port, ADD);
}

/**
 * iptablesRemoveOutputFixUdpChecksum:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port of the rule to remove
 *
 * Removes the checksum fixup rule that was previous added with
 * iptablesAddOutputFixUdpChecksum.
 *
 * Returns 0 in case of success or an error code in case of error
 * (again, if iptables doesn't support checksum fixup, this will
 * return an error, which should be ignored)
 */
int
iptablesRemoveOutputFixUdpChecksum(iptablesContext *ctx,
                                   const char *iface,
                                   int port)
{
    return iptablesOutputFixUdpChecksum(ctx, iface, port, REMOVE);
}