bridge_driver_linux.c 28.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * bridge_driver_linux.c: Linux implementation of bridge driver
 *
 * Copyright (C) 2006-2013 Red Hat, Inc.
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include "viralloc.h"
#include "virfile.h"
#include "viriptables.h"
#include "virstring.h"
28
#include "virlog.h"
29
#include "virfirewall.h"
30
#include "virfirewalld.h"
31 32 33

#define VIR_FROM_THIS VIR_FROM_NONE

34 35
VIR_LOG_INIT("network.bridge_driver_linux");

36 37
#define PROC_NET_ROUTE "/proc/net/route"

38 39
static virErrorPtr errInitV4;
static virErrorPtr errInitV6;
40 41

void networkPreReloadFirewallRules(bool startup)
42
{
43
    bool created = false;
44 45 46 47 48 49 50 51 52 53
    int rc;

    /* We create global rules upfront as we don't want
     * the perf hit of conditionally figuring out whether
     * to create them each time a network is started.
     *
     * Any errors here are saved to be reported at time
     * of starting the network though as that makes them
     * more likely to be seen by a human
     */
54
    rc = iptablesSetupPrivateChains(VIR_FIREWALL_LAYER_IPV4);
55
    if (rc < 0) {
56
        errInitV4 = virSaveLastError();
57
        virResetLastError();
58 59 60
    } else {
        virFreeError(errInitV4);
        errInitV4 = NULL;
61
    }
62 63 64 65 66 67 68
    if (rc)
        created = true;

    rc = iptablesSetupPrivateChains(VIR_FIREWALL_LAYER_IPV6);
    if (rc < 0) {
        errInitV6 = virSaveLastError();
        virResetLastError();
69 70 71
    } else {
        virFreeError(errInitV6);
        errInitV6 = NULL;
72 73 74
    }
    if (rc)
        created = true;
75 76 77 78 79 80 81 82 83 84 85 86 87 88

    /*
     * If this is initial startup, and we just created the
     * top level private chains we either
     *
     *   - upgraded from old libvirt
     *   - freshly booted from clean state
     *
     * In the first case we must delete the old rules from
     * the built-in chains, instead of our new private chains.
     * In the second case it doesn't matter, since no existing
     * rules will be present. Thus we can safely just tell it
     * to always delete from the builin chain
     */
89
    if (startup && created)
90
        iptablesSetDeletePrivate(false);
91 92 93 94 95
}


void networkPostReloadFirewallRules(bool startup ATTRIBUTE_UNUSED)
{
96
    iptablesSetDeletePrivate(true);
97 98 99
}


100 101 102 103
/* XXX: This function can be a lot more exhaustive, there are certainly
 *      other scenarios where we can ruin host network connectivity.
 * XXX: Using a proper library is preferred over parsing /proc
 */
104
int networkCheckRouteCollision(virNetworkDefPtr def)
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 130 131
{
    int ret = 0, len;
    char *cur, *buf = NULL;
    /* allow for up to 100000 routes (each line is 128 bytes) */
    enum {MAX_ROUTE_SIZE = 128*100000};

    /* Read whole routing table into memory */
    if ((len = virFileReadAll(PROC_NET_ROUTE, MAX_ROUTE_SIZE, &buf)) < 0)
        goto out;

    /* Dropping the last character shouldn't hurt */
    if (len > 0)
        buf[len-1] = '\0';

    VIR_DEBUG("%s output:\n%s", PROC_NET_ROUTE, buf);

    if (!STRPREFIX(buf, "Iface"))
        goto out;

    /* First line is just headings, skip it */
    cur = strchr(buf, '\n');
    if (cur)
        cur++;

    while (cur) {
        char iface[17], dest[128], mask[128];
        unsigned int addr_val, mask_val;
132
        virNetworkIPDefPtr ipdef;
133
        virNetDevIPRoutePtr routedef;
134 135 136 137 138
        int num;
        size_t i;

        /* NUL-terminate the line, so sscanf doesn't go beyond a newline.  */
        char *nl = strchr(cur, '\n');
139
        if (nl)
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
            *nl++ = '\0';

        num = sscanf(cur, "%16s %127s %*s %*s %*s %*s %*s %127s",
                     iface, dest, mask);
        cur = nl;

        if (num != 3) {
            VIR_DEBUG("Failed to parse %s", PROC_NET_ROUTE);
            continue;
        }

        if (virStrToLong_ui(dest, NULL, 16, &addr_val) < 0) {
            VIR_DEBUG("Failed to convert network address %s to uint", dest);
            continue;
        }

        if (virStrToLong_ui(mask, NULL, 16, &mask_val) < 0) {
            VIR_DEBUG("Failed to convert network mask %s to uint", mask);
            continue;
        }

        addr_val &= mask_val;

        for (i = 0;
164
             (ipdef = virNetworkDefGetIPByIndex(def, AF_INET, i));
165 166 167 168 169
             i++) {

            unsigned int net_dest;
            virSocketAddr netmask;

170
            if (virNetworkIPDefNetmask(ipdef, &netmask) < 0) {
171
                VIR_WARN("Failed to get netmask of '%s'",
172
                         def->bridge);
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
                continue;
            }

            net_dest = (ipdef->address.data.inet4.sin_addr.s_addr &
                        netmask.data.inet4.sin_addr.s_addr);

            if ((net_dest == addr_val) &&
                (netmask.data.inet4.sin_addr.s_addr == mask_val)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Network is already in use by interface %s"),
                               iface);
                ret = -1;
                goto out;
            }
        }
188 189 190 191 192 193

        for (i = 0;
             (routedef = virNetworkDefGetRouteByIndex(def, AF_INET, i));
             i++) {

            virSocketAddr r_mask, r_addr;
194 195
            virSocketAddrPtr tmp_addr = virNetDevIPRouteGetAddress(routedef);
            int r_prefix = virNetDevIPRouteGetPrefix(routedef);
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

            if (!tmp_addr ||
                virSocketAddrMaskByPrefix(tmp_addr, r_prefix, &r_addr) < 0 ||
                virSocketAddrPrefixToNetmask(r_prefix, &r_mask, AF_INET) < 0)
                continue;

            if ((r_addr.data.inet4.sin_addr.s_addr == addr_val) &&
                (r_mask.data.inet4.sin_addr.s_addr == mask_val)) {
                char *addr_str = virSocketAddrFormat(&r_addr);
                if (!addr_str)
                    virResetLastError();
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Route address '%s' conflicts "
                                 "with IP address for '%s'"),
                               NULLSTR(addr_str), iface);
                VIR_FREE(addr_str);
                ret = -1;
                goto out;
            }
        }
216 217
    }

218
 out:
219 220 221 222
    VIR_FREE(buf);
    return ret;
}

223 224 225
static const char networkLocalMulticast[] = "224.0.0.0/24";
static const char networkLocalBroadcast[] = "255.255.255.255/32";

226
static int
227
networkAddMasqueradingFirewallRules(virFirewallPtr fw,
228
                                    virNetworkDefPtr def,
229
                                    virNetworkIPDefPtr ipdef)
230
{
231
    int prefix = virNetworkIPDefPrefix(ipdef);
232
    const char *forwardIf = virNetworkDefForwardIf(def, 0);
233 234 235 236

    if (prefix < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid prefix or netmask for '%s'"),
237
                       def->bridge);
238
        return -1;
239 240 241
    }

    /* allow forwarding packets from the bridge interface */
242 243
    if (iptablesAddForwardAllowOut(fw,
                                   &ipdef->address,
244
                                   prefix,
245
                                   def->bridge,
246 247
                                   forwardIf) < 0)
        return -1;
248 249 250 251

    /* allow forwarding packets to the bridge interface if they are
     * part of an existing connection
     */
252 253
    if (iptablesAddForwardAllowRelatedIn(fw,
                                         &ipdef->address,
254
                                         prefix,
255
                                         def->bridge,
256 257
                                         forwardIf) < 0)
        return -1;
258 259 260 261

    /*
     * Enable masquerading.
     *
262 263 264 265 266 267 268
     * We need to end up with 5 rules in the table in this order
     *
     *  1. do not masquerade packets targeting 224.0.0.0/24
     *  2. do not masquerade packets targeting 255.255.255.255/32
     *  3. masquerade protocol=tcp with sport mapping restriction
     *  4. masquerade protocol=udp with sport mapping restriction
     *  5. generic, masquerade any protocol
269
     *
270 271 272 273 274 275
     * 224.0.0.0/24 is the local network multicast range. Packets are not
     * forwarded outside.
     *
     * 255.255.255.255/32 is the broadcast address of any local network. Again,
     * such packets are never forwarded, but strict DHCP clients don't accept
     * DHCP replies with changed source ports.
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
     *
     * The sport mappings are required, because default IPtables
     * MASQUERADE maintain port numbers unchanged where possible.
     *
     * NFS can be configured to only "trust" port numbers < 1023.
     *
     * Guests using NAT thus need to be prevented from having port
     * numbers < 1023, otherwise they can bypass the NFS "security"
     * check on the source port number.
     *
     * Since we use '--insert' to add rules to the header of the
     * chain, we actually need to add them in the reverse of the
     * order just mentioned !
     */

    /* First the generic masquerade rule for other protocols */
292 293
    if (iptablesAddForwardMasquerade(fw,
                                     &ipdef->address,
294 295
                                     prefix,
                                     forwardIf,
296 297
                                     &def->forward.addr,
                                     &def->forward.port,
298 299
                                     NULL) < 0)
        return -1;
300 301

    /* UDP with a source port restriction */
302 303
    if (iptablesAddForwardMasquerade(fw,
                                     &ipdef->address,
304 305
                                     prefix,
                                     forwardIf,
306 307
                                     &def->forward.addr,
                                     &def->forward.port,
308 309
                                     "udp") < 0)
        return -1;
310 311

    /* TCP with a source port restriction */
312 313
    if (iptablesAddForwardMasquerade(fw,
                                     &ipdef->address,
314 315
                                     prefix,
                                     forwardIf,
316 317
                                     &def->forward.addr,
                                     &def->forward.port,
318 319
                                     "tcp") < 0)
        return -1;
320

321
    /* exempt local network broadcast address as destination */
322 323
    if (iptablesAddDontMasquerade(fw,
                                  &ipdef->address,
324 325
                                  prefix,
                                  forwardIf,
326 327
                                  networkLocalBroadcast) < 0)
        return -1;
328 329

    /* exempt local multicast range as destination */
330 331
    if (iptablesAddDontMasquerade(fw,
                                  &ipdef->address,
332 333
                                  prefix,
                                  forwardIf,
334 335
                                  networkLocalMulticast) < 0)
        return -1;
336

337 338 339
    return 0;
}

340 341
static int
networkRemoveMasqueradingFirewallRules(virFirewallPtr fw,
342
                                       virNetworkDefPtr def,
343
                                       virNetworkIPDefPtr ipdef)
344
{
345
    int prefix = virNetworkIPDefPrefix(ipdef);
346
    const char *forwardIf = virNetworkDefForwardIf(def, 0);
347

348 349 350 351 352
    if (prefix < 0)
        return 0;

    if (iptablesRemoveDontMasquerade(fw,
                                     &ipdef->address,
353 354
                                     prefix,
                                     forwardIf,
355 356 357 358 359
                                     networkLocalMulticast) < 0)
        return -1;

    if (iptablesRemoveDontMasquerade(fw,
                                     &ipdef->address,
360 361
                                     prefix,
                                     forwardIf,
362 363 364 365 366
                                     networkLocalBroadcast) < 0)
        return -1;

    if (iptablesRemoveForwardMasquerade(fw,
                                        &ipdef->address,
367 368
                                        prefix,
                                        forwardIf,
369 370
                                        &def->forward.addr,
                                        &def->forward.port,
371 372 373 374 375
                                        "tcp") < 0)
        return -1;

    if (iptablesRemoveForwardMasquerade(fw,
                                        &ipdef->address,
376 377
                                        prefix,
                                        forwardIf,
378 379
                                        &def->forward.addr,
                                        &def->forward.port,
380 381 382 383 384
                                        "udp") < 0)
        return -1;

    if (iptablesRemoveForwardMasquerade(fw,
                                        &ipdef->address,
385 386
                                        prefix,
                                        forwardIf,
387 388
                                        &def->forward.addr,
                                        &def->forward.port,
389 390
                                        NULL) < 0)
        return -1;
391

392 393
    if (iptablesRemoveForwardAllowRelatedIn(fw,
                                            &ipdef->address,
394
                                            prefix,
395
                                            def->bridge,
396 397 398 399 400
                                            forwardIf) < 0)
        return -1;

    if (iptablesRemoveForwardAllowOut(fw,
                                      &ipdef->address,
401
                                      prefix,
402
                                      def->bridge,
403 404 405 406
                                      forwardIf) < 0)
        return -1;

    return 0;
407 408
}

409

410
static int
411
networkAddRoutingFirewallRules(virFirewallPtr fw,
412
                               virNetworkDefPtr def,
413
                               virNetworkIPDefPtr ipdef)
414
{
415
    int prefix = virNetworkIPDefPrefix(ipdef);
416
    const char *forwardIf = virNetworkDefForwardIf(def, 0);
417 418 419 420

    if (prefix < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid prefix or netmask for '%s'"),
421
                       def->bridge);
422
        return -1;
423 424 425
    }

    /* allow routing packets from the bridge interface */
426 427
    if (iptablesAddForwardAllowOut(fw,
                                   &ipdef->address,
428
                                   prefix,
429
                                   def->bridge,
430 431
                                   forwardIf) < 0)
        return -1;
432 433

    /* allow routing packets to the bridge interface */
434 435
    if (iptablesAddForwardAllowIn(fw,
                                  &ipdef->address,
436
                                  prefix,
437
                                  def->bridge,
438 439
                                  forwardIf) < 0)
        return -1;
440 441 442 443

    return 0;
}

444

445 446
static int
networkRemoveRoutingFirewallRules(virFirewallPtr fw,
447
                                  virNetworkDefPtr def,
448
                                  virNetworkIPDefPtr ipdef)
449
{
450
    int prefix = virNetworkIPDefPrefix(ipdef);
451
    const char *forwardIf = virNetworkDefForwardIf(def, 0);
452

453 454 455 456 457
    if (prefix < 0)
        return 0;

    if (iptablesRemoveForwardAllowIn(fw,
                                     &ipdef->address,
458
                                     prefix,
459
                                     def->bridge,
460 461
                                     forwardIf) < 0)
        return -1;
462

463 464
    if (iptablesRemoveForwardAllowOut(fw,
                                      &ipdef->address,
465
                                      prefix,
466
                                      def->bridge,
467 468 469 470 471 472 473 474 475
                                      forwardIf) < 0)
        return -1;

    return 0;
}


static void
networkAddGeneralIPv4FirewallRules(virFirewallPtr fw,
476
                                   virNetworkDefPtr def)
477 478
{
    size_t i;
479
    virNetworkIPDefPtr ipv4def;
480 481 482 483

    /* First look for first IPv4 address that has dhcp or tftpboot defined. */
    /* We support dhcp config on 1 IPv4 interface only. */
    for (i = 0;
484
         (ipv4def = virNetworkDefGetIPByIndex(def, AF_INET, i));
485 486 487 488 489 490
         i++) {
        if (ipv4def->nranges || ipv4def->nhosts || ipv4def->tftproot)
            break;
    }

    /* allow DHCP requests through to dnsmasq */
491 492 493
    iptablesAddTcpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 67);
    iptablesAddUdpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 67);
    iptablesAddUdpOutput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 68);
494 495

    /* allow DNS requests through to dnsmasq */
496 497
    iptablesAddTcpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 53);
    iptablesAddUdpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 53);
498 499 500

    /* allow TFTP requests through to dnsmasq if necessary */
    if (ipv4def && ipv4def->tftproot)
501
        iptablesAddUdpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 69);
502 503

    /* Catch all rules to block forwarding to/from bridges */
504 505
    iptablesAddForwardRejectOut(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge);
    iptablesAddForwardRejectIn(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge);
506 507

    /* Allow traffic between guests on the same bridge */
508
    iptablesAddForwardAllowCross(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge);
509 510 511 512
}

static void
networkRemoveGeneralIPv4FirewallRules(virFirewallPtr fw,
513
                                      virNetworkDefPtr def)
514 515
{
    size_t i;
516
    virNetworkIPDefPtr ipv4def;
517 518

    for (i = 0;
519
         (ipv4def = virNetworkDefGetIPByIndex(def, AF_INET, i));
520 521 522
         i++) {
        if (ipv4def->nranges || ipv4def->nhosts || ipv4def->tftproot)
            break;
523
    }
524

525 526 527
    iptablesRemoveForwardAllowCross(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge);
    iptablesRemoveForwardRejectIn(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge);
    iptablesRemoveForwardRejectOut(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge);
528 529

    if (ipv4def && ipv4def->tftproot)
530
        iptablesRemoveUdpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 69);
531

532 533
    iptablesRemoveUdpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 53);
    iptablesRemoveTcpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 53);
534

535 536 537
    iptablesRemoveUdpOutput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 68);
    iptablesRemoveUdpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 67);
    iptablesRemoveTcpInput(fw, VIR_FIREWALL_LAYER_IPV4, def->bridge, 67);
538 539
}

540

541 542
/* Add all once/network rules required for IPv6.
 * If no IPv6 addresses are defined and <network ipv6='yes'> is
M
Martin Kletzander 已提交
543
 * specified, then allow IPv6 communications between virtual systems.
544 545
 * If any IPv6 addresses are defined, then add the rules for regular operation.
 */
546 547
static void
networkAddGeneralIPv6FirewallRules(virFirewallPtr fw,
548
                                   virNetworkDefPtr def)
549
{
550
    if (!virNetworkDefGetIPByIndex(def, AF_INET6, 0) &&
551
        !def->ipv6nogw) {
552
        return;
553 554 555
    }

    /* Catch all rules to block forwarding to/from bridges */
556 557
    iptablesAddForwardRejectOut(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge);
    iptablesAddForwardRejectIn(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge);
558 559

    /* Allow traffic between guests on the same bridge */
560
    iptablesAddForwardAllowCross(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge);
561

562
    if (virNetworkDefGetIPByIndex(def, AF_INET6, 0)) {
563
        /* allow DNS over IPv6 */
564 565 566
        iptablesAddTcpInput(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge, 53);
        iptablesAddUdpInput(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge, 53);
        iptablesAddUdpInput(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge, 547);
567 568 569 570
    }
}

static void
571
networkRemoveGeneralIPv6FirewallRules(virFirewallPtr fw,
572
                                      virNetworkDefPtr def)
573
{
574
    if (!virNetworkDefGetIPByIndex(def, AF_INET6, 0) &&
575
        !def->ipv6nogw) {
576 577
        return;
    }
578

579
    if (virNetworkDefGetIPByIndex(def, AF_INET6, 0)) {
580 581 582
        iptablesRemoveUdpInput(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge, 547);
        iptablesRemoveUdpInput(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge, 53);
        iptablesRemoveTcpInput(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge, 53);
583 584 585
    }

    /* the following rules are there if no IPv6 address has been defined
586
     * but def->ipv6nogw == true
587
     */
588 589 590
    iptablesRemoveForwardAllowCross(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge);
    iptablesRemoveForwardRejectIn(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge);
    iptablesRemoveForwardRejectOut(fw, VIR_FIREWALL_LAYER_IPV6, def->bridge);
591 592
}

593

594 595
static void
networkAddGeneralFirewallRules(virFirewallPtr fw,
596
                               virNetworkDefPtr def)
597
{
598 599
    networkAddGeneralIPv4FirewallRules(fw, def);
    networkAddGeneralIPv6FirewallRules(fw, def);
600 601 602 603 604
}


static void
networkRemoveGeneralFirewallRules(virFirewallPtr fw,
605
                                  virNetworkDefPtr def)
606
{
607 608
    networkRemoveGeneralIPv4FirewallRules(fw, def);
    networkRemoveGeneralIPv6FirewallRules(fw, def);
609 610 611 612
}

static void
networkAddChecksumFirewallRules(virFirewallPtr fw,
613
                                virNetworkDefPtr def)
614 615
{
    size_t i;
616
    virNetworkIPDefPtr ipv4def;
617 618 619 620

    /* First look for first IPv4 address that has dhcp or tftpboot defined. */
    /* We support dhcp config on 1 IPv4 interface only. */
    for (i = 0;
621
         (ipv4def = virNetworkDefGetIPByIndex(def, AF_INET, i));
622
         i++) {
623
        if (ipv4def->nranges || ipv4def->nhosts)
624 625 626 627 628 629 630 631
            break;
    }

    /* If we are doing local DHCP service on this network, attempt to
     * add a rule that will fixup the checksum of DHCP response
     * packets back to the guests (but report failure without
     * aborting, since not all iptables implementations support it).
     */
632
    if (ipv4def)
633
        iptablesAddOutputFixUdpChecksum(fw, def->bridge, 68);
634 635
}

636 637

static void
638
networkRemoveChecksumFirewallRules(virFirewallPtr fw,
639
                                   virNetworkDefPtr def)
640 641
{
    size_t i;
642
    virNetworkIPDefPtr ipv4def;
643

644 645
    /* First look for first IPv4 address that has dhcp or tftpboot defined. */
    /* We support dhcp config on 1 IPv4 interface only. */
646
    for (i = 0;
647
         (ipv4def = virNetworkDefGetIPByIndex(def, AF_INET, i));
648
         i++) {
649
        if (ipv4def->nranges || ipv4def->nhosts)
650 651 652
            break;
    }

653
    if (ipv4def)
654
        iptablesRemoveOutputFixUdpChecksum(fw, def->bridge, 68);
655 656
}

657 658

static int
659
networkAddIPSpecificFirewallRules(virFirewallPtr fw,
660
                                  virNetworkDefPtr def,
661
                                  virNetworkIPDefPtr ipdef)
662 663 664 665 666
{
    /* NB: in the case of IPv6, routing rules are added when the
     * forward mode is NAT. This is because IPv6 has no NAT.
     */

667
    if (def->forward.type == VIR_NETWORK_FORWARD_NAT) {
668
        if (VIR_SOCKET_ADDR_IS_FAMILY(&ipdef->address, AF_INET))
669
            return networkAddMasqueradingFirewallRules(fw, def, ipdef);
670
        else if (VIR_SOCKET_ADDR_IS_FAMILY(&ipdef->address, AF_INET6))
671 672 673
            return networkAddRoutingFirewallRules(fw, def, ipdef);
    } else if (def->forward.type == VIR_NETWORK_FORWARD_ROUTE) {
        return networkAddRoutingFirewallRules(fw, def, ipdef);
674 675 676 677
    }
    return 0;
}

678

679
static int
680
networkRemoveIPSpecificFirewallRules(virFirewallPtr fw,
681
                                     virNetworkDefPtr def,
682
                                     virNetworkIPDefPtr ipdef)
683
{
684
    if (def->forward.type == VIR_NETWORK_FORWARD_NAT) {
685
        if (VIR_SOCKET_ADDR_IS_FAMILY(&ipdef->address, AF_INET))
686
            return networkRemoveMasqueradingFirewallRules(fw, def, ipdef);
687
        else if (VIR_SOCKET_ADDR_IS_FAMILY(&ipdef->address, AF_INET6))
688 689 690
            return networkRemoveRoutingFirewallRules(fw, def, ipdef);
    } else if (def->forward.type == VIR_NETWORK_FORWARD_ROUTE) {
        return networkRemoveRoutingFirewallRules(fw, def, ipdef);
691
    }
692
    return 0;
693 694
}

695

696
/* Add all rules for all ip addresses (and general rules) on a network */
697
int networkAddFirewallRules(virNetworkDefPtr def)
698
{
699
    size_t i;
700
    virNetworkIPDefPtr ipdef;
701 702
    virFirewallPtr fw = NULL;
    int ret = -1;
703

704 705 706 707 708 709 710 711 712 713 714 715
    if (errInitV4 &&
        (virNetworkDefGetIPByIndex(def, AF_INET, 0) ||
         virNetworkDefGetRouteByIndex(def, AF_INET, 0))) {
        virSetError(errInitV4);
        return -1;
    }

    if (errInitV6 &&
        (virNetworkDefGetIPByIndex(def, AF_INET6, 0) ||
         virNetworkDefGetRouteByIndex(def, AF_INET6, 0) ||
         def->ipv6nogw)) {
        virSetError(errInitV6);
716 717 718
        return -1;
    }

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
    if (def->bridgeZone) {

        /* if a firewalld zone has been specified, fail/log an error
         * if we can't honor it
         */
        if (virFirewallDIsRegistered() < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("zone %s requested for network %s "
                             "but firewalld is not active"),
                           def->bridgeZone, def->name);
            goto cleanup;
        }

        if (virFirewallDInterfaceSetZone(def->bridge, def->bridgeZone) < 0)
            goto cleanup;

    } else {

        /* if firewalld is active, try to set the "libvirt" zone. This is
         * desirable (for consistency) if firewalld is using the iptables
         * backend, but is necessary (for basic network connectivity) if
         * firewalld is using the nftables backend
741
         */
742 743 744 745 746 747 748 749
        if (virFirewallDIsRegistered() == 0) {

            /* if the "libvirt" zone exists, then set it. If not, and
             * if firewalld is using the nftables backend, then we
             * need to log an error because the combination of
             * nftables + default zone means that traffic cannot be
             * forwarded (and even DHCP and DNS from guest to host
             * will probably no be permitted by the default zone
750
             */
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
            if (virFirewallDZoneExists("libvirt")) {
                if (virFirewallDInterfaceSetZone(def->bridge, "libvirt") < 0)
                    goto cleanup;
            } else {
                unsigned long version;
                int vresult = virFirewallDGetVersion(&version);

                if (vresult < 0)
                    goto cleanup;

                /* Support for nftables backend was added in firewalld
                 * 0.6.0. Support for rule priorities (required by the
                 * 'libvirt' zone, which should be installed by a
                 * libvirt package, *not* by firewalld) was not added
                 * until firewalld 0.7.0 (unless it was backported).
                 */
                if (version >= 6000 &&
                    virFirewallDGetBackend() == VIR_FIREWALLD_BACKEND_NFTABLES) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("firewalld is set to use the nftables "
                                     "backend, but the required firewalld "
                                     "'libvirt' zone is missing. Either set "
                                     "the firewalld backend to 'iptables', or "
                                     "ensure that firewalld has a 'libvirt' "
                                     "zone by upgrading firewalld to a "
                                     "version supporting rule priorities "
                                     "(0.7.0+) and/or rebuilding "
                                     "libvirt with --with-firewalld-zone"));
                    goto cleanup;
                }
781 782 783 784
            }
        }
    }

785 786 787 788
    fw = virFirewallNew();

    virFirewallStartTransaction(fw, 0);

789
    networkAddGeneralFirewallRules(fw, def);
790 791

    for (i = 0;
792
         (ipdef = virNetworkDefGetIPByIndex(def, AF_UNSPEC, i));
793
         i++) {
794
        if (networkAddIPSpecificFirewallRules(fw, def, ipdef) < 0)
795
            goto cleanup;
796 797
    }

798
    virFirewallStartRollback(fw, 0);
799

800
    for (i = 0;
801
         (ipdef = virNetworkDefGetIPByIndex(def, AF_UNSPEC, i));
802
         i++) {
803
        if (networkRemoveIPSpecificFirewallRules(fw, def, ipdef) < 0)
804
            goto cleanup;
805
    }
806
    networkRemoveGeneralFirewallRules(fw, def);
807 808

    virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
809
    networkAddChecksumFirewallRules(fw, def);
810 811 812

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

814 815 816 817
    ret = 0;
 cleanup:
    virFirewallFree(fw);
    return ret;
818 819 820
}

/* Remove all rules for all ip addresses (and general rules) on a network */
821
void networkRemoveFirewallRules(virNetworkDefPtr def)
822 823
{
    size_t i;
824
    virNetworkIPDefPtr ipdef;
825 826 827 828 829
    virFirewallPtr fw = NULL;

    fw = virFirewallNew();

    virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
830
    networkRemoveChecksumFirewallRules(fw, def);
831 832

    virFirewallStartTransaction(fw, VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
833 834

    for (i = 0;
835
         (ipdef = virNetworkDefGetIPByIndex(def, AF_UNSPEC, i));
836
         i++) {
837
        if (networkRemoveIPSpecificFirewallRules(fw, def, ipdef) < 0)
838
            goto cleanup;
839
    }
840
    networkRemoveGeneralFirewallRules(fw, def);
841 842 843 844 845

    virFirewallApply(fw);

 cleanup:
    virFirewallFree(fw);
846
}