viriptables.c 37.0 KB
Newer Older
1
/*
2 3
 * viriptables.c: helper APIs for managing iptables
 *
4
 * Copyright (C) 2007-2014 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
#include <config.h>
22 23 24 25 26 27

#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
E
Eric Blake 已提交
28
#include <sys/wait.h>
29

30
#include "internal.h"
31
#include "viriptables.h"
32
#include "vircommand.h"
33
#include "viralloc.h"
34
#include "virerror.h"
35
#include "virfile.h"
36
#include "virlog.h"
37
#include "virthread.h"
38 39
#include "virstring.h"
#include "virutil.h"
40
#include "virhash.h"
41

42 43
VIR_LOG_INIT("util.iptables");

44
#define VIR_FROM_THIS VIR_FROM_NONE
45

46 47 48 49 50
enum {
    ADD = 0,
    REMOVE
};

51
static bool deletePrivate = true;
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
typedef struct {
    const char *parent;
    const char *child;
} iptablesGlobalChain;

typedef struct {
    virFirewallLayer layer;
    const char *table;
    iptablesGlobalChain *chains;
    size_t nchains;
    bool *changed;
} iptablesGlobalChainData;


static int
iptablesPrivateChainCreate(virFirewallPtr fw,
                           virFirewallLayer layer,
                           const char *const *lines,
                           void *opaque)
{
    iptablesGlobalChainData *data = opaque;
    virHashTablePtr chains = NULL;
    virHashTablePtr links = NULL;
    const char *const *tmp;
    int ret = -1;
    size_t i;

    if (!(chains = virHashCreate(50, NULL)))
        goto cleanup;
    if (!(links = virHashCreate(50, NULL)))
        goto cleanup;

    tmp = lines;
    while (tmp && *tmp) {
        if (STRPREFIX(*tmp, "-N ")) { /* eg "-N LIBVIRT_INP" */
            if (virHashUpdateEntry(chains, *tmp + 3, (void *)0x1) < 0)
                goto cleanup;
        } else if (STRPREFIX(*tmp, "-A ")) { /* eg "-A INPUT -j LIBVIRT_INP" */
            char *sep = strchr(*tmp + 3, ' ');
            if (sep) {
                *sep = '\0';
                if (STRPREFIX(sep + 1, "-j ")) {
                    if (virHashUpdateEntry(links, sep + 4,
                                           (char *)*tmp + 3) < 0)
                        goto cleanup;
                }
            }
        }
        tmp++;
    }

    for (i = 0; i < data->nchains; i++) {
        const char *from;
        if (!virHashLookup(chains, data->chains[i].child)) {
            virFirewallAddRule(fw, layer,
                               "--table", data->table,
                               "--new-chain", data->chains[i].child, NULL);
            *data->changed = true;
        }

        from = virHashLookup(links, data->chains[i].child);
        if (!from || STRNEQ(from, data->chains[i].parent))
            virFirewallAddRule(fw, layer,
                               "--table", data->table,
                               "--insert", data->chains[i].parent,
                               "--jump", data->chains[i].child, NULL);
    }

    ret = 0;
 cleanup:
    virHashFree(chains);
    virHashFree(links);
    return ret;
}


int
130
iptablesSetupPrivateChains(virFirewallLayer layer)
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
{
    virFirewallPtr fw = NULL;
    int ret = -1;
    iptablesGlobalChain filter_chains[] = {
        {"INPUT", "LIBVIRT_INP"},
        {"OUTPUT", "LIBVIRT_OUT"},
        {"FORWARD", "LIBVIRT_FWO"},
        {"FORWARD", "LIBVIRT_FWI"},
        {"FORWARD", "LIBVIRT_FWX"},
    };
    iptablesGlobalChain natmangle_chains[] = {
        {"POSTROUTING",  "LIBVIRT_PRT"},
    };
    bool changed = false;
    iptablesGlobalChainData data[] = {
146
        { layer, "filter",
147
          filter_chains, G_N_ELEMENTS(filter_chains), &changed },
148
        { layer, "nat",
149
          natmangle_chains, G_N_ELEMENTS(natmangle_chains), &changed },
150
        { layer, "mangle",
151
          natmangle_chains, G_N_ELEMENTS(natmangle_chains), &changed },
152 153 154 155 156 157 158
    };
    size_t i;

    fw = virFirewallNew();

    virFirewallStartTransaction(fw, 0);

159
    for (i = 0; i < G_N_ELEMENTS(data); i++)
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        virFirewallAddRuleFull(fw, data[i].layer,
                               false, iptablesPrivateChainCreate,
                               &(data[i]), "--table", data[i].table,
                               "--list-rules", NULL);

    if (virFirewallApply(fw) < 0)
        goto cleanup;

    ret = changed ? 1 : 0;

 cleanup:

    virFirewallFree(fw);
    return ret;
}


177 178 179 180 181 182 183
void
iptablesSetDeletePrivate(bool pvt)
{
    deletePrivate = pvt;
}


184 185 186
static void
iptablesInput(virFirewallPtr fw,
              virFirewallLayer layer,
187
              bool pvt,
188 189 190 191 192 193 194 195 196 197
              const char *iface,
              int port,
              int action,
              int tcp)
{
    char portstr[32];

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

198 199
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
200 201
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_INP" : "INPUT",
202 203 204 205 206
                       "--in-interface", iface,
                       "--protocol", tcp ? "tcp" : "udp",
                       "--destination-port", portstr,
                       "--jump", "ACCEPT",
                       NULL);
207 208
}

209 210 211
static void
iptablesOutput(virFirewallPtr fw,
               virFirewallLayer layer,
212
               bool pvt,
213 214 215 216 217 218 219 220 221 222
               const char *iface,
               int port,
               int action,
               int tcp)
{
    char portstr[32];

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

223 224
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
225 226
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_OUT" : "OUTPUT",
227 228 229 230 231
                       "--out-interface", iface,
                       "--protocol", tcp ? "tcp" : "udp",
                       "--destination-port", portstr,
                       "--jump", "ACCEPT",
                       NULL);
232 233
}

234 235 236 237 238 239 240 241 242
/**
 * 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
 */
243 244 245
void
iptablesAddTcpInput(virFirewallPtr fw,
                    virFirewallLayer layer,
246 247 248
                    const char *iface,
                    int port)
{
249
    iptablesInput(fw, layer, true, iface, port, ADD, 1);
250 251
}

252 253 254 255 256 257
/**
 * iptablesRemoveTcpInput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the TCP port to remove
 *
R
Richard W.M. Jones 已提交
258
 * Removes an input from the IP table, hence forbidding access to the given
259 260
 * @port on the given @iface interface for TCP packets
 */
261 262 263
void
iptablesRemoveTcpInput(virFirewallPtr fw,
                       virFirewallLayer layer,
264 265 266
                       const char *iface,
                       int port)
{
267
    iptablesInput(fw, layer, deletePrivate, iface, port, REMOVE, 1);
268 269
}

270 271 272 273 274 275 276 277 278
/**
 * 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
 */
279 280 281
void
iptablesAddUdpInput(virFirewallPtr fw,
                    virFirewallLayer layer,
282 283 284
                    const char *iface,
                    int port)
{
285
    iptablesInput(fw, layer, true, iface, port, ADD, 0);
286 287
}

288 289 290 291 292 293
/**
 * iptablesRemoveUdpInput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to remove
 *
R
Richard W.M. Jones 已提交
294
 * Removes an input from the IP table, hence forbidding access to the given
295 296
 * @port on the given @iface interface for UDP packets
 */
297 298 299
void
iptablesRemoveUdpInput(virFirewallPtr fw,
                       virFirewallLayer layer,
300 301 302
                       const char *iface,
                       int port)
{
303
    iptablesInput(fw, layer, deletePrivate, iface, port, REMOVE, 0);
304 305
}

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
/**
 * iptablesAddTcpOutput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the TCP port to add
 *
 * Add an output to the IP table allowing access to the given @port from
 * the given @iface interface for TCP packets
 */
void
iptablesAddTcpOutput(virFirewallPtr fw,
                     virFirewallLayer layer,
                     const char *iface,
                     int port)
{
    iptablesOutput(fw, layer, true, iface, port, ADD, 1);
}

/**
 * iptablesRemoveTcpOutput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to remove
 *
 * Removes an output from the IP table, hence forbidding access to the given
 * @port from the given @iface interface for TCP packets
 */
void
iptablesRemoveTcpOutput(virFirewallPtr fw,
                        virFirewallLayer layer,
                        const char *iface,
                        int port)
{
    iptablesOutput(fw, layer, deletePrivate, iface, port, REMOVE, 1);
}

342 343 344 345 346 347 348 349 350
/**
 * iptablesAddUdpOutput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to add
 *
 * Add an output to the IP table allowing access to the given @port from
 * the given @iface interface for UDP packets
 */
351 352 353
void
iptablesAddUdpOutput(virFirewallPtr fw,
                     virFirewallLayer layer,
354 355 356
                     const char *iface,
                     int port)
{
357
    iptablesOutput(fw, layer, true, iface, port, ADD, 0);
358 359 360 361 362 363 364 365 366 367 368
}

/**
 * iptablesRemoveUdpOutput:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to remove
 *
 * Removes an output from the IP table, hence forbidding access to the given
 * @port from the given @iface interface for UDP packets
 */
369 370 371
void
iptablesRemoveUdpOutput(virFirewallPtr fw,
                        virFirewallLayer layer,
372 373 374
                        const char *iface,
                        int port)
{
375
    iptablesOutput(fw, layer, deletePrivate, iface, port, REMOVE, 0);
376 377
}

378

379
static char *iptablesFormatNetwork(virSocketAddr *netaddr,
380
                                   unsigned int prefix)
381 382
{
    virSocketAddr network;
383
    g_autofree char *netstr = NULL;
384 385
    char *ret;

386 387
    if (!(VIR_SOCKET_ADDR_IS_FAMILY(netaddr, AF_INET) ||
          VIR_SOCKET_ADDR_IS_FAMILY(netaddr, AF_INET6))) {
388 389
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Only IPv4 or IPv6 addresses can be used with iptables"));
390 391 392
        return NULL;
    }

393
    if (virSocketAddrMaskByPrefix(netaddr, prefix, &network) < 0) {
394 395
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failure to mask address"));
396 397
        return NULL;
    }
398

399
    netstr = virSocketAddrFormat(&network);
400 401 402 403

    if (!netstr)
        return NULL;

404
    ignore_value(virAsprintf(&ret, "%s/%d", netstr, prefix));
405 406 407 408 409

    return ret;
}


410 411 412
/* Allow all traffic coming from the bridge, with a valid network address
 * to proceed to WAN
 */
413
static int
414
iptablesForwardAllowOut(virFirewallPtr fw,
415
                        bool pvt,
416
                        virSocketAddr *netaddr,
417
                        unsigned int prefix,
418 419 420
                        const char *iface,
                        const char *physdev,
                        int action)
421
{
422
    g_autofree char *networkstr = NULL;
423 424
    virFirewallLayer layer = VIR_SOCKET_ADDR_FAMILY(netaddr) == AF_INET ?
        VIR_FIREWALL_LAYER_IPV4 : VIR_FIREWALL_LAYER_IPV6;
425

426
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
427 428
        return -1;

429
    if (physdev && physdev[0])
430 431
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
432 433
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWO" : "FORWARD",
434 435 436 437 438 439 440 441
                           "--source", networkstr,
                           "--in-interface", iface,
                           "--out-interface", physdev,
                           "--jump", "ACCEPT",
                           NULL);
    else
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
442 443
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWO" : "FORWARD",
444 445 446 447
                           "--source", networkstr,
                           "--in-interface", iface,
                           "--jump", "ACCEPT",
                           NULL);
448

449
    return 0;
450 451
}

452 453 454 455 456 457
/**
 * iptablesAddForwardAllowOut:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the source interface name
 * @physdev: the physical output device
458
 *
459 460 461 462 463 464
 * 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
 */
465
int
466 467
iptablesAddForwardAllowOut(virFirewallPtr fw,
                           virSocketAddr *netaddr,
468
                           unsigned int prefix,
469 470
                           const char *iface,
                           const char *physdev)
471
{
472
    return iptablesForwardAllowOut(fw, true, netaddr, prefix, iface, physdev, ADD);
473 474
}

475 476 477 478 479 480
/**
 * iptablesRemoveForwardAllowOut:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the source interface name
 * @physdev: the physical output device
481
 *
482 483 484 485 486 487
 * 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
 */
488
int
489 490
iptablesRemoveForwardAllowOut(virFirewallPtr fw,
                              virSocketAddr *netaddr,
491
                              unsigned int prefix,
492 493
                              const char *iface,
                              const char *physdev)
494
{
495
    return iptablesForwardAllowOut(fw, deletePrivate, netaddr, prefix, iface, physdev, REMOVE);
496 497
}

498 499 500 501

/* Allow all traffic destined to the bridge, with a valid network address
 * and associated with an existing connection
 */
502
static int
503
iptablesForwardAllowRelatedIn(virFirewallPtr fw,
504
                              bool pvt,
505
                              virSocketAddr *netaddr,
506
                              unsigned int prefix,
507 508 509
                              const char *iface,
                              const char *physdev,
                              int action)
510
{
511 512
    virFirewallLayer layer = VIR_SOCKET_ADDR_FAMILY(netaddr) == AF_INET ?
        VIR_FIREWALL_LAYER_IPV4 : VIR_FIREWALL_LAYER_IPV6;
513
    g_autofree char *networkstr = NULL;
514

515
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
516 517
        return -1;

518 519 520
    if (physdev && physdev[0])
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
521 522
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
523 524 525 526 527 528 529 530 531 532
                           "--destination", networkstr,
                           "--in-interface", physdev,
                           "--out-interface", iface,
                           "--match", "conntrack",
                           "--ctstate", "ESTABLISHED,RELATED",
                           "--jump", "ACCEPT",
                           NULL);
    else
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
533 534
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
535 536 537 538 539 540 541 542
                           "--destination", networkstr,
                           "--out-interface", iface,
                           "--match", "conntrack",
                           "--ctstate", "ESTABLISHED,RELATED",
                           "--jump", "ACCEPT",
                           NULL);

    return 0;
543 544
}

545 546 547 548 549 550 551 552 553 554 555 556 557 558
/**
 * 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
559 560
iptablesAddForwardAllowRelatedIn(virFirewallPtr fw,
                                 virSocketAddr *netaddr,
561
                                 unsigned int prefix,
562 563
                                 const char *iface,
                                 const char *physdev)
564
{
565
    return iptablesForwardAllowRelatedIn(fw, true, netaddr, prefix, iface, physdev, ADD);
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
}

/**
 * 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
582 583
iptablesRemoveForwardAllowRelatedIn(virFirewallPtr fw,
                                    virSocketAddr *netaddr,
584
                                    unsigned int prefix,
585 586
                                    const char *iface,
                                    const char *physdev)
587
{
588
    return iptablesForwardAllowRelatedIn(fw, deletePrivate, netaddr, prefix, iface, physdev, REMOVE);
589 590 591 592 593
}

/* Allow all traffic destined to the bridge, with a valid network address
 */
static int
594
iptablesForwardAllowIn(virFirewallPtr fw,
595
                       bool pvt,
596
                       virSocketAddr *netaddr,
597
                       unsigned int prefix,
598 599 600 601
                       const char *iface,
                       const char *physdev,
                       int action)
{
602 603
    virFirewallLayer layer = VIR_SOCKET_ADDR_FAMILY(netaddr) == AF_INET ?
        VIR_FIREWALL_LAYER_IPV4 : VIR_FIREWALL_LAYER_IPV6;
604
    g_autofree char *networkstr = NULL;
605

606
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
607 608
        return -1;

609 610 611
    if (physdev && physdev[0])
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
612 613
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
614 615 616 617 618 619 620 621
                           "--destination", networkstr,
                           "--in-interface", physdev,
                           "--out-interface", iface,
                           "--jump", "ACCEPT",
                           NULL);
    else
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
622 623
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
624 625 626 627 628
                           "--destination", networkstr,
                           "--out-interface", iface,
                           "--jump", "ACCEPT",
                           NULL);
    return 0;
629 630
}

631 632 633 634 635 636
/**
 * 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
637
 *
638 639 640 641 642 643
 * 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
 */
644
int
645 646
iptablesAddForwardAllowIn(virFirewallPtr fw,
                          virSocketAddr *netaddr,
647
                          unsigned int prefix,
648 649 650
                          const char *iface,
                          const char *physdev)
{
651
    return iptablesForwardAllowIn(fw, true, netaddr, prefix, iface, physdev, ADD);
652 653
}

654 655 656 657 658 659
/**
 * 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
660
 *
661 662 663 664 665 666
 * 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
 */
667
int
668 669
iptablesRemoveForwardAllowIn(virFirewallPtr fw,
                             virSocketAddr *netaddr,
670
                             unsigned int prefix,
671 672 673
                             const char *iface,
                             const char *physdev)
{
674
    return iptablesForwardAllowIn(fw, deletePrivate, netaddr, prefix, iface, physdev, REMOVE);
675 676
}

677 678 679
static void
iptablesForwardAllowCross(virFirewallPtr fw,
                          virFirewallLayer layer,
680
                          bool pvt,
681 682 683 684 685
                          const char *iface,
                          int action)
{
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
686 687
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_FWX" : "FORWARD",
688 689 690 691 692 693
                       "--in-interface", iface,
                       "--out-interface", iface,
                       "--jump", "ACCEPT",
                       NULL);
}

694 695 696 697 698 699 700 701 702 703 704
/**
 * 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
 */
705 706 707
void
iptablesAddForwardAllowCross(virFirewallPtr fw,
                             virFirewallLayer layer,
708 709
                             const char *iface)
{
710
    iptablesForwardAllowCross(fw, layer, true, iface, ADD);
711 712
}

713 714 715 716 717 718 719 720 721 722 723
/**
 * 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
 */
724 725 726
void
iptablesRemoveForwardAllowCross(virFirewallPtr fw,
                                virFirewallLayer layer,
727
                                const char *iface)
728
{
729
    iptablesForwardAllowCross(fw, layer, deletePrivate, iface, REMOVE);
730 731 732 733 734
}

static void
iptablesForwardRejectOut(virFirewallPtr fw,
                         virFirewallLayer layer,
735
                         bool pvt,
736 737
                         const char *iface,
                         int action)
738
{
739 740
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
741 742
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_FWO" : "FORWARD",
743
                       "--in-interface", iface,
744
                       "--jump", "REJECT",
745
                       NULL);
746 747
}

748 749 750 751 752 753 754 755 756 757
/**
 * 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
 */
758 759 760
void
iptablesAddForwardRejectOut(virFirewallPtr fw,
                            virFirewallLayer layer,
761 762
                            const char *iface)
{
763
    iptablesForwardRejectOut(fw, layer, true, iface, ADD);
764 765
}

766 767 768 769 770 771 772 773 774 775
/**
 * 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
 */
776 777 778
void
iptablesRemoveForwardRejectOut(virFirewallPtr fw,
                               virFirewallLayer layer,
779
                               const char *iface)
780
{
781
    iptablesForwardRejectOut(fw, layer, deletePrivate, iface, REMOVE);
782 783 784 785 786 787
}


static void
iptablesForwardRejectIn(virFirewallPtr fw,
                        virFirewallLayer layer,
788
                        bool pvt,
789 790
                        const char *iface,
                        int action)
791
{
792 793
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
794 795
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_FWI" : "FORWARD",
796
                       "--out-interface", iface,
797 798
                       "--jump", "REJECT",
                       NULL);
799 800
}

801 802 803 804 805 806 807 808 809 810
/**
 * 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
 */
811 812 813
void
iptablesAddForwardRejectIn(virFirewallPtr fw,
                           virFirewallLayer layer,
814
                           const char *iface)
815
{
816
    iptablesForwardRejectIn(fw, layer, true, iface, ADD);
817 818
}

819 820 821 822 823 824 825 826 827 828
/**
 * 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
 */
829 830 831
void
iptablesRemoveForwardRejectIn(virFirewallPtr fw,
                              virFirewallLayer layer,
832
                              const char *iface)
833
{
834
    iptablesForwardRejectIn(fw, layer, deletePrivate, iface, REMOVE);
835 836
}

837 838 839 840

/* Masquerade all traffic coming from the network associated
 * with the bridge
 */
841
static int
842
iptablesForwardMasquerade(virFirewallPtr fw,
843
                          bool pvt,
844
                          virSocketAddr *netaddr,
845
                          unsigned int prefix,
846
                          const char *physdev,
847 848
                          virSocketAddrRangePtr addr,
                          virPortRangePtr port,
849 850
                          const char *protocol,
                          int action)
851
{
852 853 854 855 856
    g_autofree char *networkstr = NULL;
    g_autofree char *addrStartStr = NULL;
    g_autofree char *addrEndStr = NULL;
    g_autofree char *portRangeStr = NULL;
    g_autofree char *natRangeStr = NULL;
857
    virFirewallRulePtr rule;
858

859
    if (!(networkstr = iptablesFormatNetwork(netaddr, prefix)))
860 861
        return -1;

862
    if (!VIR_SOCKET_ADDR_IS_FAMILY(netaddr, AF_INET)) {
863
        /* Higher level code *should* guaranteee it's impossible to get here. */
864 865 866
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Attempted to NAT '%s'. NAT is only supported for IPv4."),
                       networkstr);
867
        return -1;
868 869
    }

870 871
    if (VIR_SOCKET_ADDR_IS_FAMILY(&addr->start, AF_INET)) {
        if (!(addrStartStr = virSocketAddrFormat(&addr->start)))
872
            return -1;
873 874
        if (VIR_SOCKET_ADDR_IS_FAMILY(&addr->end, AF_INET)) {
            if (!(addrEndStr = virSocketAddrFormat(&addr->end)))
875
                return -1;
876
        }
877 878
    }

879 880 881
    if (protocol && protocol[0]) {
        rule = virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                                  "--table", "nat",
882 883
                                  action == ADD ? "--insert" : "--delete",
                                  pvt ? "LIBVIRT_PRT" : "POSTROUTING",
884 885 886 887 888 889 890
                                  "--source", networkstr,
                                  "-p", protocol,
                                  "!", "--destination", networkstr,
                                  NULL);
    } else {
        rule = virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                                  "--table", "nat",
891 892
                                  action == ADD ? "--insert" : "--delete",
                                  pvt ? "LIBVIRT_PRT" : "POSTROUTING",
893 894 895 896
                                  "--source", networkstr,
                                  "!", "--destination", networkstr,
                                  NULL);
    }
897 898

    if (physdev && physdev[0])
899
        virFirewallRuleAddArgList(fw, rule, "--out-interface", physdev, NULL);
900

901
    if (protocol && protocol[0]) {
902 903 904
        if (port->start == 0 && port->end == 0) {
            port->start = 1024;
            port->end = 65535;
905 906
        }

907 908
        if (port->start < port->end && port->end < 65536) {
            if (virAsprintf(&portRangeStr, ":%u-%u",
909
                            port->start, port->end) < 0)
910
                return -1;
911 912 913
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid port range '%u-%u'."),
914
                           port->start, port->end);
915 916 917
        }
    }

918 919 920
    /* Use --jump SNAT if public addr is specified */
    if (addrStartStr && addrStartStr[0]) {
        int r = 0;
921

922 923
        if (addrEndStr && addrEndStr[0]) {
            r = virAsprintf(&natRangeStr, "%s-%s%s", addrStartStr, addrEndStr,
924
                            portRangeStr ? portRangeStr : "");
925
        } else {
926 927
            r = virAsprintf(&natRangeStr, "%s%s", addrStartStr,
                            portRangeStr ? portRangeStr : "");
928 929
        }

930
        if (r < 0)
931
            return -1;
932

933 934
        virFirewallRuleAddArgList(fw, rule,
                                  "--jump", "SNAT",
935
                                  "--to-source", natRangeStr, NULL);
936 937 938
    } else {
        virFirewallRuleAddArgList(fw, rule,
                                  "--jump", "MASQUERADE", NULL);
939

940 941 942 943
        if (portRangeStr && portRangeStr[0])
            virFirewallRuleAddArgList(fw, rule,
                                      "--to-ports", &portRangeStr[1], NULL);
    }
944

945
    return 0;
946 947
}

948 949 950 951 952
/**
 * iptablesAddForwardMasquerade:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @physdev: the physical input device or NULL
953
 * @protocol: the network protocol or NULL
954
 *
955 956 957 958 959 960
 * 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
 */
961
int
962 963
iptablesAddForwardMasquerade(virFirewallPtr fw,
                             virSocketAddr *netaddr,
964
                             unsigned int prefix,
965
                             const char *physdev,
966 967
                             virSocketAddrRangePtr addr,
                             virPortRangePtr port,
968
                             const char *protocol)
969
{
970 971
    return iptablesForwardMasquerade(fw, true, netaddr, prefix,
                                     physdev, addr, port, protocol, ADD);
972 973
}

974 975 976 977 978
/**
 * iptablesRemoveForwardMasquerade:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @physdev: the physical input device or NULL
979
 * @protocol: the network protocol or NULL
980
 *
981 982 983 984 985 986
 * 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
 */
987
int
988 989
iptablesRemoveForwardMasquerade(virFirewallPtr fw,
                                virSocketAddr *netaddr,
990
                                unsigned int prefix,
991
                                const char *physdev,
992 993
                                virSocketAddrRangePtr addr,
                                virPortRangePtr port,
994
                                const char *protocol)
995
{
996 997
    return iptablesForwardMasquerade(fw, deletePrivate, netaddr, prefix,
                                     physdev, addr, port, protocol, REMOVE);
998
}
999 1000


1001 1002 1003 1004
/* Don't masquerade traffic coming from the network associated with the bridge
 * if said traffic targets @destaddr.
 */
static int
1005
iptablesForwardDontMasquerade(virFirewallPtr fw,
1006
                              bool pvt,
1007
                              virSocketAddr *netaddr,
1008 1009 1010 1011 1012
                              unsigned int prefix,
                              const char *physdev,
                              const char *destaddr,
                              int action)
{
1013
    g_autofree char *networkstr = NULL;
1014 1015 1016 1017 1018 1019 1020 1021 1022

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

    if (!VIR_SOCKET_ADDR_IS_FAMILY(netaddr, AF_INET)) {
        /* Higher level code *should* guaranteee it's impossible to get here. */
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Attempted to NAT '%s'. NAT is only supported for IPv4."),
                       networkstr);
1023
        return -1;
1024 1025 1026
    }

    if (physdev && physdev[0])
1027 1028
        virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                           "--table", "nat",
1029 1030
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_PRT" : "POSTROUTING",
1031 1032 1033 1034 1035 1036 1037 1038
                           "--out-interface", physdev,
                           "--source", networkstr,
                           "--destination", destaddr,
                           "--jump", "RETURN",
                           NULL);
    else
        virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                           "--table", "nat",
1039 1040
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_PRT" : "POSTROUTING",
1041 1042 1043 1044 1045
                           "--source", networkstr,
                           "--destination", destaddr,
                           "--jump", "RETURN",
                           NULL);

1046
    return 0;
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
}

/**
 * iptablesAddDontMasquerade:
 * @netaddr: the source network name
 * @prefix: prefix (# of 1 bits) of netmask to apply to @netaddr
 * @physdev: the physical output device or NULL
 * @destaddr: the destination network not to masquerade for
 *
 * Add rules to the IP table context to avoid masquerading from
 * @netaddr/@prefix to @destaddr on @physdev. @destaddr must be in a format
 * directly consumable by iptables, it must not depend on user input or
 * configuration.
 *
 * Returns 0 in case of success or an error code otherwise.
 */
int
1064 1065
iptablesAddDontMasquerade(virFirewallPtr fw,
                          virSocketAddr *netaddr,
1066 1067 1068 1069
                          unsigned int prefix,
                          const char *physdev,
                          const char *destaddr)
{
1070 1071
    return iptablesForwardDontMasquerade(fw, true, netaddr, prefix,
                                         physdev, destaddr, ADD);
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
}

/**
 * iptablesRemoveDontMasquerade:
 * @netaddr: the source network name
 * @prefix: prefix (# of 1 bits) of netmask to apply to @netaddr
 * @physdev: the physical output device or NULL
 * @destaddr: the destination network not to masquerade for
 *
 * Remove rules from the IP table context that prevent masquerading from
 * @netaddr/@prefix to @destaddr on @physdev. @destaddr must be in a format
 * directly consumable by iptables, it must not depend on user input or
 * configuration.
 *
 * Returns 0 in case of success or an error code otherwise.
 */
int
1089 1090
iptablesRemoveDontMasquerade(virFirewallPtr fw,
                             virSocketAddr *netaddr,
1091 1092 1093 1094
                             unsigned int prefix,
                             const char *physdev,
                             const char *destaddr)
{
1095 1096
    return iptablesForwardDontMasquerade(fw, deletePrivate, netaddr, prefix,
                                         physdev, destaddr, REMOVE);
1097 1098 1099
}


1100 1101
static void
iptablesOutputFixUdpChecksum(virFirewallPtr fw,
1102
                             bool pvt,
1103
                             const char *iface,
1104 1105 1106 1107 1108 1109 1110 1111
                             int port,
                             int action)
{
    char portstr[32];

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

1112 1113
    virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                       "--table", "mangle",
1114 1115
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_PRT" : "POSTROUTING",
1116 1117 1118 1119 1120
                       "--out-interface", iface,
                       "--protocol", "udp",
                       "--destination-port", portstr,
                       "--jump", "CHECKSUM", "--checksum-fill",
                       NULL);
1121 1122 1123 1124 1125 1126 1127 1128
}

/**
 * iptablesAddOutputFixUdpChecksum:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to match
 *
E
Eric Blake 已提交
1129
 * Add a rule to the mangle table's POSTROUTING chain that fixes up the
1130 1131 1132 1133
 * checksum of packets with the given destination @port.
 * the given @iface interface for TCP packets.
 *
 */
1134 1135 1136
void
iptablesAddOutputFixUdpChecksum(virFirewallPtr fw,
                                const char *iface,
1137 1138
                                int port)
{
1139
    iptablesOutputFixUdpChecksum(fw, true, iface, port, ADD);
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
}

/**
 * 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.
 */
1151 1152 1153
void
iptablesRemoveOutputFixUdpChecksum(virFirewallPtr fw,
                                   const char *iface,
1154 1155
                                   int port)
{
1156
    iptablesOutputFixUdpChecksum(fw, deletePrivate, iface, port, REMOVE);
1157
}