viriptables.c 36.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
/**
 * 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
 */
315 316 317
void
iptablesAddUdpOutput(virFirewallPtr fw,
                     virFirewallLayer layer,
318 319 320
                     const char *iface,
                     int port)
{
321
    iptablesOutput(fw, layer, true, iface, port, ADD, 0);
322 323 324 325 326 327 328 329 330 331 332
}

/**
 * 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
 */
333 334 335
void
iptablesRemoveUdpOutput(virFirewallPtr fw,
                        virFirewallLayer layer,
336 337 338
                        const char *iface,
                        int port)
{
339
    iptablesOutput(fw, layer, deletePrivate, iface, port, REMOVE, 0);
340 341
}

342

343
static char *iptablesFormatNetwork(virSocketAddr *netaddr,
344
                                   unsigned int prefix)
345 346
{
    virSocketAddr network;
347
    g_autofree char *netstr = NULL;
348 349
    char *ret;

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

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

363
    netstr = virSocketAddrFormat(&network);
364 365 366 367

    if (!netstr)
        return NULL;

368
    ignore_value(virAsprintf(&ret, "%s/%d", netstr, prefix));
369 370 371 372 373

    return ret;
}


374 375 376
/* Allow all traffic coming from the bridge, with a valid network address
 * to proceed to WAN
 */
377
static int
378
iptablesForwardAllowOut(virFirewallPtr fw,
379
                        bool pvt,
380
                        virSocketAddr *netaddr,
381
                        unsigned int prefix,
382 383 384
                        const char *iface,
                        const char *physdev,
                        int action)
385
{
386
    g_autofree char *networkstr = NULL;
387 388
    virFirewallLayer layer = VIR_SOCKET_ADDR_FAMILY(netaddr) == AF_INET ?
        VIR_FIREWALL_LAYER_IPV4 : VIR_FIREWALL_LAYER_IPV6;
389

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

393
    if (physdev && physdev[0])
394 395
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
396 397
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWO" : "FORWARD",
398 399 400 401 402 403 404 405
                           "--source", networkstr,
                           "--in-interface", iface,
                           "--out-interface", physdev,
                           "--jump", "ACCEPT",
                           NULL);
    else
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
406 407
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWO" : "FORWARD",
408 409 410 411
                           "--source", networkstr,
                           "--in-interface", iface,
                           "--jump", "ACCEPT",
                           NULL);
412

413
    return 0;
414 415
}

416 417 418 419 420 421
/**
 * iptablesAddForwardAllowOut:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the source interface name
 * @physdev: the physical output device
422
 *
423 424 425 426 427 428
 * 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
 */
429
int
430 431
iptablesAddForwardAllowOut(virFirewallPtr fw,
                           virSocketAddr *netaddr,
432
                           unsigned int prefix,
433 434
                           const char *iface,
                           const char *physdev)
435
{
436
    return iptablesForwardAllowOut(fw, true, netaddr, prefix, iface, physdev, ADD);
437 438
}

439 440 441 442 443 444
/**
 * iptablesRemoveForwardAllowOut:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @iface: the source interface name
 * @physdev: the physical output device
445
 *
446 447 448 449 450 451
 * 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
 */
452
int
453 454
iptablesRemoveForwardAllowOut(virFirewallPtr fw,
                              virSocketAddr *netaddr,
455
                              unsigned int prefix,
456 457
                              const char *iface,
                              const char *physdev)
458
{
459
    return iptablesForwardAllowOut(fw, deletePrivate, netaddr, prefix, iface, physdev, REMOVE);
460 461
}

462 463 464 465

/* Allow all traffic destined to the bridge, with a valid network address
 * and associated with an existing connection
 */
466
static int
467
iptablesForwardAllowRelatedIn(virFirewallPtr fw,
468
                              bool pvt,
469
                              virSocketAddr *netaddr,
470
                              unsigned int prefix,
471 472 473
                              const char *iface,
                              const char *physdev,
                              int action)
474
{
475 476
    virFirewallLayer layer = VIR_SOCKET_ADDR_FAMILY(netaddr) == AF_INET ?
        VIR_FIREWALL_LAYER_IPV4 : VIR_FIREWALL_LAYER_IPV6;
477
    g_autofree char *networkstr = NULL;
478

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

482 483 484
    if (physdev && physdev[0])
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
485 486
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
487 488 489 490 491 492 493 494 495 496
                           "--destination", networkstr,
                           "--in-interface", physdev,
                           "--out-interface", iface,
                           "--match", "conntrack",
                           "--ctstate", "ESTABLISHED,RELATED",
                           "--jump", "ACCEPT",
                           NULL);
    else
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
497 498
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
499 500 501 502 503 504 505 506
                           "--destination", networkstr,
                           "--out-interface", iface,
                           "--match", "conntrack",
                           "--ctstate", "ESTABLISHED,RELATED",
                           "--jump", "ACCEPT",
                           NULL);

    return 0;
507 508
}

509 510 511 512 513 514 515 516 517 518 519 520 521 522
/**
 * 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
523 524
iptablesAddForwardAllowRelatedIn(virFirewallPtr fw,
                                 virSocketAddr *netaddr,
525
                                 unsigned int prefix,
526 527
                                 const char *iface,
                                 const char *physdev)
528
{
529
    return iptablesForwardAllowRelatedIn(fw, true, netaddr, prefix, iface, physdev, ADD);
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
}

/**
 * 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
546 547
iptablesRemoveForwardAllowRelatedIn(virFirewallPtr fw,
                                    virSocketAddr *netaddr,
548
                                    unsigned int prefix,
549 550
                                    const char *iface,
                                    const char *physdev)
551
{
552
    return iptablesForwardAllowRelatedIn(fw, deletePrivate, netaddr, prefix, iface, physdev, REMOVE);
553 554 555 556 557
}

/* Allow all traffic destined to the bridge, with a valid network address
 */
static int
558
iptablesForwardAllowIn(virFirewallPtr fw,
559
                       bool pvt,
560
                       virSocketAddr *netaddr,
561
                       unsigned int prefix,
562 563 564 565
                       const char *iface,
                       const char *physdev,
                       int action)
{
566 567
    virFirewallLayer layer = VIR_SOCKET_ADDR_FAMILY(netaddr) == AF_INET ?
        VIR_FIREWALL_LAYER_IPV4 : VIR_FIREWALL_LAYER_IPV6;
568
    g_autofree char *networkstr = NULL;
569

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

573 574 575
    if (physdev && physdev[0])
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
576 577
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
578 579 580 581 582 583 584 585
                           "--destination", networkstr,
                           "--in-interface", physdev,
                           "--out-interface", iface,
                           "--jump", "ACCEPT",
                           NULL);
    else
        virFirewallAddRule(fw, layer,
                           "--table", "filter",
586 587
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_FWI" : "FORWARD",
588 589 590 591 592
                           "--destination", networkstr,
                           "--out-interface", iface,
                           "--jump", "ACCEPT",
                           NULL);
    return 0;
593 594
}

595 596 597 598 599 600
/**
 * 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
601
 *
602 603 604 605 606 607
 * 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
 */
608
int
609 610
iptablesAddForwardAllowIn(virFirewallPtr fw,
                          virSocketAddr *netaddr,
611
                          unsigned int prefix,
612 613 614
                          const char *iface,
                          const char *physdev)
{
615
    return iptablesForwardAllowIn(fw, true, netaddr, prefix, iface, physdev, ADD);
616 617
}

618 619 620 621 622 623
/**
 * 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
624
 *
625 626 627 628 629 630
 * 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
 */
631
int
632 633
iptablesRemoveForwardAllowIn(virFirewallPtr fw,
                             virSocketAddr *netaddr,
634
                             unsigned int prefix,
635 636 637
                             const char *iface,
                             const char *physdev)
{
638
    return iptablesForwardAllowIn(fw, deletePrivate, netaddr, prefix, iface, physdev, REMOVE);
639 640
}

641 642 643
static void
iptablesForwardAllowCross(virFirewallPtr fw,
                          virFirewallLayer layer,
644
                          bool pvt,
645 646 647 648 649
                          const char *iface,
                          int action)
{
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
650 651
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_FWX" : "FORWARD",
652 653 654 655 656 657
                       "--in-interface", iface,
                       "--out-interface", iface,
                       "--jump", "ACCEPT",
                       NULL);
}

658 659 660 661 662 663 664 665 666 667 668
/**
 * 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
 */
669 670 671
void
iptablesAddForwardAllowCross(virFirewallPtr fw,
                             virFirewallLayer layer,
672 673
                             const char *iface)
{
674
    iptablesForwardAllowCross(fw, layer, true, iface, ADD);
675 676
}

677 678 679 680 681 682 683 684 685 686 687
/**
 * 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
 */
688 689 690
void
iptablesRemoveForwardAllowCross(virFirewallPtr fw,
                                virFirewallLayer layer,
691
                                const char *iface)
692
{
693
    iptablesForwardAllowCross(fw, layer, deletePrivate, iface, REMOVE);
694 695 696 697 698
}

static void
iptablesForwardRejectOut(virFirewallPtr fw,
                         virFirewallLayer layer,
699
                         bool pvt,
700 701
                         const char *iface,
                         int action)
702
{
703 704
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
705 706
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_FWO" : "FORWARD",
707
                       "--in-interface", iface,
708
                       "--jump", "REJECT",
709
                       NULL);
710 711
}

712 713 714 715 716 717 718 719 720 721
/**
 * 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
 */
722 723 724
void
iptablesAddForwardRejectOut(virFirewallPtr fw,
                            virFirewallLayer layer,
725 726
                            const char *iface)
{
727
    iptablesForwardRejectOut(fw, layer, true, iface, ADD);
728 729
}

730 731 732 733 734 735 736 737 738 739
/**
 * 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
 */
740 741 742
void
iptablesRemoveForwardRejectOut(virFirewallPtr fw,
                               virFirewallLayer layer,
743
                               const char *iface)
744
{
745
    iptablesForwardRejectOut(fw, layer, deletePrivate, iface, REMOVE);
746 747 748 749 750 751
}


static void
iptablesForwardRejectIn(virFirewallPtr fw,
                        virFirewallLayer layer,
752
                        bool pvt,
753 754
                        const char *iface,
                        int action)
755
{
756 757
    virFirewallAddRule(fw, layer,
                       "--table", "filter",
758 759
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_FWI" : "FORWARD",
760
                       "--out-interface", iface,
761 762
                       "--jump", "REJECT",
                       NULL);
763 764
}

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 777
void
iptablesAddForwardRejectIn(virFirewallPtr fw,
                           virFirewallLayer layer,
778
                           const char *iface)
779
{
780
    iptablesForwardRejectIn(fw, layer, true, 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 794 795
void
iptablesRemoveForwardRejectIn(virFirewallPtr fw,
                              virFirewallLayer layer,
796
                              const char *iface)
797
{
798
    iptablesForwardRejectIn(fw, layer, deletePrivate, iface, REMOVE);
799 800
}

801 802 803 804

/* Masquerade all traffic coming from the network associated
 * with the bridge
 */
805
static int
806
iptablesForwardMasquerade(virFirewallPtr fw,
807
                          bool pvt,
808
                          virSocketAddr *netaddr,
809
                          unsigned int prefix,
810
                          const char *physdev,
811 812
                          virSocketAddrRangePtr addr,
                          virPortRangePtr port,
813 814
                          const char *protocol,
                          int action)
815
{
816 817 818 819 820
    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;
821
    virFirewallRulePtr rule;
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
        return -1;
832 833
    }

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

843 844 845
    if (protocol && protocol[0]) {
        rule = virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                                  "--table", "nat",
846 847
                                  action == ADD ? "--insert" : "--delete",
                                  pvt ? "LIBVIRT_PRT" : "POSTROUTING",
848 849 850 851 852 853 854
                                  "--source", networkstr,
                                  "-p", protocol,
                                  "!", "--destination", networkstr,
                                  NULL);
    } else {
        rule = virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                                  "--table", "nat",
855 856
                                  action == ADD ? "--insert" : "--delete",
                                  pvt ? "LIBVIRT_PRT" : "POSTROUTING",
857 858 859 860
                                  "--source", networkstr,
                                  "!", "--destination", networkstr,
                                  NULL);
    }
861 862

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

865
    if (protocol && protocol[0]) {
866 867 868
        if (port->start == 0 && port->end == 0) {
            port->start = 1024;
            port->end = 65535;
869 870
        }

871 872
        if (port->start < port->end && port->end < 65536) {
            if (virAsprintf(&portRangeStr, ":%u-%u",
873
                            port->start, port->end) < 0)
874
                return -1;
875 876 877
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid port range '%u-%u'."),
878
                           port->start, port->end);
879 880 881
        }
    }

882 883 884
    /* Use --jump SNAT if public addr is specified */
    if (addrStartStr && addrStartStr[0]) {
        int r = 0;
885

886 887
        if (addrEndStr && addrEndStr[0]) {
            r = virAsprintf(&natRangeStr, "%s-%s%s", addrStartStr, addrEndStr,
888
                            portRangeStr ? portRangeStr : "");
889
        } else {
890 891
            r = virAsprintf(&natRangeStr, "%s%s", addrStartStr,
                            portRangeStr ? portRangeStr : "");
892 893
        }

894
        if (r < 0)
895
            return -1;
896

897 898
        virFirewallRuleAddArgList(fw, rule,
                                  "--jump", "SNAT",
899
                                  "--to-source", natRangeStr, NULL);
900 901 902
    } else {
        virFirewallRuleAddArgList(fw, rule,
                                  "--jump", "MASQUERADE", NULL);
903

904 905 906 907
        if (portRangeStr && portRangeStr[0])
            virFirewallRuleAddArgList(fw, rule,
                                      "--to-ports", &portRangeStr[1], NULL);
    }
908

909
    return 0;
910 911
}

912 913 914 915 916
/**
 * iptablesAddForwardMasquerade:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @physdev: the physical input device or NULL
917
 * @protocol: the network protocol or NULL
918
 *
919 920 921 922 923 924
 * 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
 */
925
int
926 927
iptablesAddForwardMasquerade(virFirewallPtr fw,
                             virSocketAddr *netaddr,
928
                             unsigned int prefix,
929
                             const char *physdev,
930 931
                             virSocketAddrRangePtr addr,
                             virPortRangePtr port,
932
                             const char *protocol)
933
{
934 935
    return iptablesForwardMasquerade(fw, true, netaddr, prefix,
                                     physdev, addr, port, protocol, ADD);
936 937
}

938 939 940 941 942
/**
 * iptablesRemoveForwardMasquerade:
 * @ctx: pointer to the IP table context
 * @network: the source network name
 * @physdev: the physical input device or NULL
943
 * @protocol: the network protocol or NULL
944
 *
945 946 947 948 949 950
 * 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
 */
951
int
952 953
iptablesRemoveForwardMasquerade(virFirewallPtr fw,
                                virSocketAddr *netaddr,
954
                                unsigned int prefix,
955
                                const char *physdev,
956 957
                                virSocketAddrRangePtr addr,
                                virPortRangePtr port,
958
                                const char *protocol)
959
{
960 961
    return iptablesForwardMasquerade(fw, deletePrivate, netaddr, prefix,
                                     physdev, addr, port, protocol, REMOVE);
962
}
963 964


965 966 967 968
/* Don't masquerade traffic coming from the network associated with the bridge
 * if said traffic targets @destaddr.
 */
static int
969
iptablesForwardDontMasquerade(virFirewallPtr fw,
970
                              bool pvt,
971
                              virSocketAddr *netaddr,
972 973 974 975 976
                              unsigned int prefix,
                              const char *physdev,
                              const char *destaddr,
                              int action)
{
977
    g_autofree char *networkstr = NULL;
978 979 980 981 982 983 984 985 986

    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);
987
        return -1;
988 989 990
    }

    if (physdev && physdev[0])
991 992
        virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                           "--table", "nat",
993 994
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_PRT" : "POSTROUTING",
995 996 997 998 999 1000 1001 1002
                           "--out-interface", physdev,
                           "--source", networkstr,
                           "--destination", destaddr,
                           "--jump", "RETURN",
                           NULL);
    else
        virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                           "--table", "nat",
1003 1004
                           action == ADD ? "--insert" : "--delete",
                           pvt ? "LIBVIRT_PRT" : "POSTROUTING",
1005 1006 1007 1008 1009
                           "--source", networkstr,
                           "--destination", destaddr,
                           "--jump", "RETURN",
                           NULL);

1010
    return 0;
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
}

/**
 * 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
1028 1029
iptablesAddDontMasquerade(virFirewallPtr fw,
                          virSocketAddr *netaddr,
1030 1031 1032 1033
                          unsigned int prefix,
                          const char *physdev,
                          const char *destaddr)
{
1034 1035
    return iptablesForwardDontMasquerade(fw, true, netaddr, prefix,
                                         physdev, destaddr, ADD);
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
}

/**
 * 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
1053 1054
iptablesRemoveDontMasquerade(virFirewallPtr fw,
                             virSocketAddr *netaddr,
1055 1056 1057 1058
                             unsigned int prefix,
                             const char *physdev,
                             const char *destaddr)
{
1059 1060
    return iptablesForwardDontMasquerade(fw, deletePrivate, netaddr, prefix,
                                         physdev, destaddr, REMOVE);
1061 1062 1063
}


1064 1065
static void
iptablesOutputFixUdpChecksum(virFirewallPtr fw,
1066
                             bool pvt,
1067
                             const char *iface,
1068 1069 1070 1071 1072 1073 1074 1075
                             int port,
                             int action)
{
    char portstr[32];

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

1076 1077
    virFirewallAddRule(fw, VIR_FIREWALL_LAYER_IPV4,
                       "--table", "mangle",
1078 1079
                       action == ADD ? "--insert" : "--delete",
                       pvt ? "LIBVIRT_PRT" : "POSTROUTING",
1080 1081 1082 1083 1084
                       "--out-interface", iface,
                       "--protocol", "udp",
                       "--destination-port", portstr,
                       "--jump", "CHECKSUM", "--checksum-fill",
                       NULL);
1085 1086 1087 1088 1089 1090 1091 1092
}

/**
 * iptablesAddOutputFixUdpChecksum:
 * @ctx: pointer to the IP table context
 * @iface: the interface name
 * @port: the UDP port to match
 *
E
Eric Blake 已提交
1093
 * Add a rule to the mangle table's POSTROUTING chain that fixes up the
1094 1095 1096 1097
 * checksum of packets with the given destination @port.
 * the given @iface interface for TCP packets.
 *
 */
1098 1099 1100
void
iptablesAddOutputFixUdpChecksum(virFirewallPtr fw,
                                const char *iface,
1101 1102
                                int port)
{
1103
    iptablesOutputFixUdpChecksum(fw, true, iface, port, ADD);
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
}

/**
 * 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.
 */
1115 1116 1117
void
iptablesRemoveOutputFixUdpChecksum(virFirewallPtr fw,
                                   const char *iface,
1118 1119
                                   int port)
{
1120
    iptablesOutputFixUdpChecksum(fw, deletePrivate, iface, port, REMOVE);
1121
}