nwfilter_ebiptables_driver.c 124.7 KB
Newer Older
1 2 3
/*
 * nwfilter_ebiptables_driver.c: driver for ebtables/iptables on tap devices
 *
4
 * Copyright (C) 2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * Copyright (C) 2010 IBM Corp.
 * Copyright (C) 2010 Stefan Berger
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Stefan Berger <stefanb@us.ibm.com>
 */

#include <config.h>

27
#include <string.h>
28
#include <sys/stat.h>
29
#include <fcntl.h>
30 31 32 33 34 35 36 37

#include "internal.h"

#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "virterror_internal.h"
#include "domain_conf.h"
38
#include "nwfilter_conf.h"
39 40
#include "nwfilter_gentech_driver.h"
#include "nwfilter_ebiptables_driver.h"
E
Eric Blake 已提交
41
#include "virfile.h"
42
#include "command.h"
43
#include "configmake.h"
44 45 46 47 48 49 50 51 52 53 54 55 56 57


#define VIR_FROM_THIS VIR_FROM_NWFILTER


#define EBTABLES_DEFAULT_TABLE  "nat"
#define EBTABLES_CHAIN_INCOMING "PREROUTING"
#define EBTABLES_CHAIN_OUTGOING "POSTROUTING"

#define CHAINPREFIX_HOST_IN       'I'
#define CHAINPREFIX_HOST_OUT      'O'
#define CHAINPREFIX_HOST_IN_TEMP  'J'
#define CHAINPREFIX_HOST_OUT_TEMP 'P'

58 59 60 61
/* This file generates a temporary shell script.  Since ebiptables is
   Linux-specific, we can be reasonably certain that /bin/sh is more
   or less POSIX-compliant, so we can use $() and $(()).  However, we
   cannot assume that /bin/sh is bash, so stick to POSIX syntax.  */
62 63

#define CMD_SEPARATOR "\n"
64 65
#define CMD_DEF_PRE  "cmd='"
#define CMD_DEF_POST "'"
66
#define CMD_DEF(X) CMD_DEF_PRE X CMD_DEF_POST
67
#define CMD_EXEC   "eval res=\\$\\(\"${cmd}\"\\)" CMD_SEPARATOR
68 69 70 71 72 73 74 75
#define CMD_STOPONERR(X) \
    X ? "if [ $? -ne 0 ]; then" \
        "  echo \"Failure to execute command '${cmd}'.\";" \
        "  exit 1;" \
        "fi" CMD_SEPARATOR \
      : ""


76 77 78 79 80 81 82
#define PROC_BRIDGE_NF_CALL_IPTABLES \
        "/proc/sys/net/bridge/bridge-nf-call-iptables"
#define PROC_BRIDGE_NF_CALL_IP6TABLES \
        "/proc/sys/net/bridge/bridge-nf-call-ip6tables"

#define BRIDGE_NF_CALL_ALERT_INTERVAL  10 /* seconds */

83 84 85 86 87 88
static char *ebtables_cmd_path;
static char *iptables_cmd_path;
static char *ip6tables_cmd_path;
static char *grep_cmd_path;
static char *gawk_cmd_path;

89 90 91 92 93 94

#define PRINT_ROOT_CHAIN(buf, prefix, ifname) \
    snprintf(buf, sizeof(buf), "libvirt-%c-%s", prefix, ifname)
#define PRINT_CHAIN(buf, prefix, ifname, suffix) \
    snprintf(buf, sizeof(buf), "%c-%s-%s", prefix, ifname, suffix)

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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
/* The collect_chains() script recursively determines all names
 * of ebtables (nat) chains that are 'children' of a given 'root' chain.
 * The typical output of an ebtables call is as follows:
 *
 * #> ebtables -t nat -L libvirt-I-tck-test205002
 * Bridge table: nat
 *
 * Bridge chain: libvirt-I-tck-test205002, entries: 5, policy: ACCEPT
 * -p IPv4 -j I-tck-test205002-ipv4
 * -p ARP -j I-tck-test205002-arp
 * -p 0x8035 -j I-tck-test205002-rarp
 * -p 0x835 -j ACCEPT
 * -j DROP
 */
static const char ebtables_script_func_collect_chains[] =
    "collect_chains()\n"
    "{\n"
    "  for tmp2 in $*; do\n"
    "    for tmp in $(%s -t %s -L $tmp2 | \\\n"
    "      sed -n \"/Bridge chain/,\\$ s/.*-j \\\\([%s]-.*\\\\)/\\\\1/p\");\n"
    "    do\n"
    "      echo $tmp\n"
    "      collect_chains $tmp\n"
    "    done\n"
    "  done\n"
    "}\n";

static const char ebiptables_script_func_rm_chains[] =
    "rm_chains()\n"
    "{\n"
    "  for tmp in $*; do %s -t %s -F $tmp; done\n"
    "  for tmp in $*; do %s -t %s -X $tmp; done\n"
    "}\n";

static const char ebiptables_script_func_rename_chains[] =
    "rename_chains()\n"
    "{\n"
    "  for tmp in $*; do\n"
    "    case $tmp in\n"
    "      %c*) %s -t %s -E $tmp %c${tmp#?} ;;\n"
    "      %c*) %s -t %s -E $tmp %c${tmp#?} ;;\n"
    "    esac\n"
    "  done\n"
    "}\n";

static const char ebiptables_script_set_ifs[] =
    "tmp='\n'\n"
    "IFS=' ''\t'$tmp\n";

#define NWFILTER_FUNC_COLLECT_CHAINS ebtables_script_func_collect_chains
#define NWFILTER_FUNC_RM_CHAINS ebiptables_script_func_rm_chains
#define NWFILTER_FUNC_RENAME_CHAINS ebiptables_script_func_rename_chains
#define NWFILTER_FUNC_SET_IFS ebiptables_script_set_ifs
148

S
Stefan Berger 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
#define VIRT_IN_CHAIN      "libvirt-in"
#define VIRT_OUT_CHAIN     "libvirt-out"
#define VIRT_IN_POST_CHAIN "libvirt-in-post"
#define HOST_IN_CHAIN      "libvirt-host-in"

#define PRINT_IPT_ROOT_CHAIN(buf, prefix, ifname) \
    snprintf(buf, sizeof(buf), "%c%c-%s", prefix[0], prefix[1], ifname)

#define PHYSDEV_IN  "--physdev-in"
#define PHYSDEV_OUT "--physdev-out"

static const char *m_state_out_str   = "-m state --state NEW,ESTABLISHED";
static const char *m_state_in_str    = "-m state --state ESTABLISHED";
static const char *m_physdev_in_str  = "-m physdev " PHYSDEV_IN;
static const char *m_physdev_out_str = "-m physdev " PHYSDEV_OUT;

#define MATCH_STATE_OUT    m_state_out_str
#define MATCH_STATE_IN     m_state_in_str
#define MATCH_PHYSDEV_IN   m_physdev_in_str
#define MATCH_PHYSDEV_OUT  m_physdev_out_str

170
#define COMMENT_VARNAME "comment"
S
Stefan Berger 已提交
171

172
static int ebtablesRemoveBasicRules(const char *ifname);
173
static int ebiptablesDriverInit(bool privileged);
174
static void ebiptablesDriverShutdown(void);
175
static int ebtablesCleanAll(const char *ifname);
176
static int ebiptablesAllTeardown(const char *ifname);
177

178
static virMutex execCLIMutex;
179

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
struct ushort_map {
    unsigned short attr;
    const char *val;
};


enum l3_proto_idx {
    L3_PROTO_IPV4_IDX = 0,
    L3_PROTO_IPV6_IDX,
    L3_PROTO_ARP_IDX,
    L3_PROTO_RARP_IDX,
    L3_PROTO_LAST_IDX
};

#define USHORTMAP_ENTRY_IDX(IDX, ATT, VAL) [IDX] = { .attr = ATT, .val = VAL }

196 197 198 199 200
/* A lookup table for translating ethernet protocol IDs to human readable
 * strings. None of the human readable strings must be found as a prefix
 * in another entry here (example 'ab' would be found in 'abc') to allow
 * for prefix matching.
 */
201 202 203 204 205 206
static const struct ushort_map l3_protocols[] = {
    USHORTMAP_ENTRY_IDX(L3_PROTO_IPV4_IDX, ETHERTYPE_IP    , "ipv4"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_IPV6_IDX, ETHERTYPE_IPV6  , "ipv6"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_ARP_IDX , ETHERTYPE_ARP   , "arp"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_RARP_IDX, ETHERTYPE_REVARP, "rarp"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_LAST_IDX, 0               , NULL),
207 208 209 210
};


static int
211
printVar(virNWFilterVarCombIterPtr vars,
212 213 214 215 216 217 218
         char *buf, int bufsize,
         nwItemDescPtr item,
         int *done)
{
    *done = 0;

    if ((item->flags & NWFILTER_ENTRY_ITEM_FLAG_HAS_VAR)) {
219 220
        const char *val;

221
        val = virNWFilterVarCombIterGetVarValue(vars, item->var);
222
        if (!val) {
223
            /* error has been reported */
224 225 226
            return 1;
        }

227
        if (!virStrcpy(buf, val, bufsize)) {
228
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
229 230 231 232 233 234 235 236 237 238 239 240 241
                                   _("Buffer to small to print MAC address "
                                   "'%s' into"),
                                   item->var);
            return 1;
        }

        *done = 1;
    }
    return 0;
}


static int
242
_printDataType(virNWFilterVarCombIterPtr vars,
243 244 245
               char *buf, int bufsize,
               nwItemDescPtr item,
               bool asHex)
246 247
{
    int done;
248
    char *data;
249

250
    if (printVar(vars, buf, bufsize, item, &done))
251 252 253 254 255 256 257
        return 1;

    if (done)
        return 0;

    switch (item->datatype) {
    case DATATYPE_IPADDR:
258
        data = virSocketAddrFormat(&item->u.ipaddr);
259
        if (!data)
260 261
            return 1;
        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
262
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
263 264
                                   _("buffer too small for IP address"));
            VIR_FREE(data);
265 266
            return 1;
        }
267
        VIR_FREE(data);
268 269
    break;

270
    case DATATYPE_IPV6ADDR:
271
        data = virSocketAddrFormat(&item->u.ipaddr);
272
        if (!data)
273 274 275
            return 1;

        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
276
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
277 278 279
                                   _("buffer too small for IPv6 address"));
            VIR_FREE(data);
            return 1;
280
        }
281
        VIR_FREE(data);
282 283
    break;

284
    case DATATYPE_MACADDR:
285
    case DATATYPE_MACMASK:
286
        if (bufsize < VIR_MAC_STRING_BUFLEN) {
287
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
288 289 290 291 292 293 294
                                   _("Buffer too small for MAC address"));
            return 1;
        }

        virFormatMacAddr(item->u.macaddr.addr, buf);
    break;

295 296
    case DATATYPE_IPV6MASK:
    case DATATYPE_IPMASK:
297
        if (snprintf(buf, bufsize, "%d",
298
                     item->u.u8) >= bufsize) {
299
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
300 301 302 303 304 305
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT16:
306
    case DATATYPE_UINT16_HEX:
307
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
308
                     item->u.u16) >= bufsize) {
309
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
310 311 312 313 314 315
                                   _("Buffer too small for uint16 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT8:
316
    case DATATYPE_UINT8_HEX:
317
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
318
                     item->u.u8) >= bufsize) {
319
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
320 321 322 323 324 325
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    default:
326
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
327 328 329 330 331 332 333 334 335
                               _("Unhandled datatype %x"), item->datatype);
        return 1;
    break;
    }

    return 0;
}


336
static int
337
printDataType(virNWFilterVarCombIterPtr vars,
338 339 340
              char *buf, int bufsize,
              nwItemDescPtr item)
{
341
    return _printDataType(vars, buf, bufsize, item, 0);
342 343 344 345
}


static int
346
printDataTypeAsHex(virNWFilterVarCombIterPtr vars,
347 348 349
                   char *buf, int bufsize,
                   nwItemDescPtr item)
{
350
    return _printDataType(vars, buf, bufsize, item, 1);
351 352 353
}


354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
static void
printCommentVar(virBufferPtr dest, const char *buf)
{
    size_t i, len = strlen(buf);

    virBufferAddLit(dest, COMMENT_VARNAME "='");

    if (len > IPTABLES_MAX_COMMENT_LENGTH)
        len = IPTABLES_MAX_COMMENT_LENGTH;

    for (i = 0; i < len; i++) {
        if (buf[i] == '\'')
            virBufferAddLit(dest, "'\\''");
        else
            virBufferAddChar(dest, buf[i]);
    }
    virBufferAddLit(dest,"'" CMD_SEPARATOR);
}


S
Stefan Berger 已提交
374 375 376 377 378 379 380 381 382 383 384 385
static void
ebiptablesRuleInstFree(ebiptablesRuleInstPtr inst)
{
    if (!inst)
        return;

    VIR_FREE(inst->commandTemplate);
    VIR_FREE(inst);
}


static int
386
ebiptablesAddRuleInst(virNWFilterRuleInstPtr res,
S
Stefan Berger 已提交
387
                      char *commandTemplate,
388
                      const char *neededChain,
389
                      virNWFilterChainPriority chainPriority,
S
Stefan Berger 已提交
390
                      char chainprefix,
391
                      virNWFilterRulePriority priority,
S
Stefan Berger 已提交
392 393 394 395 396 397 398 399 400 401 402
                      enum RuleType ruleType)
{
    ebiptablesRuleInstPtr inst;

    if (VIR_ALLOC(inst) < 0) {
        virReportOOMError();
        return 1;
    }

    inst->commandTemplate = commandTemplate;
    inst->neededProtocolChain = neededChain;
403
    inst->chainPriority = chainPriority;
S
Stefan Berger 已提交
404 405 406 407
    inst->chainprefix = chainprefix;
    inst->priority = priority;
    inst->ruleType = ruleType;

408
    return virNWFilterRuleInstAddData(res, inst);
S
Stefan Berger 已提交
409 410 411 412
}


static int
413
ebtablesHandleEthHdr(virBufferPtr buf,
414
                     virNWFilterVarCombIterPtr vars,
415 416
                     ethHdrDataDefPtr ethHdr,
                     bool reverse)
S
Stefan Berger 已提交
417 418 419 420
{
    char macaddr[VIR_MAC_STRING_BUFLEN];

    if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACAddr)) {
421
        if (printDataType(vars,
S
Stefan Berger 已提交
422 423 424 425
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataSrcMACAddr))
            goto err_exit;

426
        virBufferAsprintf(buf,
427 428
                      " %s %s %s",
                      reverse ? "-d" : "-s",
S
Stefan Berger 已提交
429 430 431 432
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataSrcMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACMask)) {
433
            if (printDataType(vars,
S
Stefan Berger 已提交
434 435 436 437
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataSrcMACMask))
                goto err_exit;

438
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
439 440 441 442 443 444
                              "/%s",
                              macaddr);
        }
    }

    if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACAddr)) {
445
        if (printDataType(vars,
S
Stefan Berger 已提交
446 447 448 449
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataDstMACAddr))
            goto err_exit;

450
        virBufferAsprintf(buf,
451 452
                      " %s %s %s",
                      reverse ? "-s" : "-d",
S
Stefan Berger 已提交
453 454 455 456
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataDstMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACMask)) {
457
            if (printDataType(vars,
S
Stefan Berger 已提交
458 459 460 461
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataDstMACMask))
                goto err_exit;

462
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
                              "/%s",
                              macaddr);
        }
    }

    return 0;

 err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


/************************ iptables support ************************/

479
static int iptablesLinkIPTablesBaseChain(const char *iptables_cmd,
S
Stefan Berger 已提交
480 481 482 483 484 485
                                         virBufferPtr buf,
                                         const char *udchain,
                                         const char *syschain,
                                         unsigned int pos,
                                         int stopOnError)
{
486
    virBufferAsprintf(buf,
487
                      "res=$(%s -L %s -n --line-number | "
488
                          "%s \" %s \")\n"
S
Stefan Berger 已提交
489
                      "if [ $? -ne 0 ]; then\n"
490
                      "  %s -I %s %d -j %s\n"
S
Stefan Berger 已提交
491
                      "else\n"
492
                      "  r=$(echo $res | %s '{print $1}')\n"
S
Stefan Berger 已提交
493
                      "  if [ \"${r}\" != \"%d\" ]; then\n"
494
                      "    " CMD_DEF("%s -I %s %d -j %s") CMD_SEPARATOR
S
Stefan Berger 已提交
495 496
                      "    " CMD_EXEC
                      "    %s"
497
                      "    r=$(( $r + 1 ))\n"
498
                      "    " CMD_DEF("%s -D %s ${r}") CMD_SEPARATOR
S
Stefan Berger 已提交
499 500 501 502 503
                      "    " CMD_EXEC
                      "    %s"
                      "  fi\n"
                      "fi\n",

504
                      iptables_cmd, syschain,
505
                      grep_cmd_path, udchain,
S
Stefan Berger 已提交
506

507
                      iptables_cmd, syschain, pos, udchain,
508
                      gawk_cmd_path,
S
Stefan Berger 已提交
509 510 511

                      pos,

512
                      iptables_cmd, syschain, pos, udchain,
S
Stefan Berger 已提交
513 514
                      CMD_STOPONERR(stopOnError),

515
                      iptables_cmd, syschain,
S
Stefan Berger 已提交
516 517 518 519 520
                      CMD_STOPONERR(stopOnError));
    return 0;
}


521
static int iptablesCreateBaseChains(const char *iptables_cmd,
S
Stefan Berger 已提交
522 523
                                    virBufferPtr buf)
{
524
    virBufferAsprintf(buf,"%s -N " VIRT_IN_CHAIN      CMD_SEPARATOR
525 526 527 528 529 530 531
                          "%s -N " VIRT_OUT_CHAIN     CMD_SEPARATOR
                          "%s -N " VIRT_IN_POST_CHAIN CMD_SEPARATOR
                          "%s -N " HOST_IN_CHAIN      CMD_SEPARATOR,
                          iptables_cmd,
                          iptables_cmd,
                          iptables_cmd,
                          iptables_cmd);
532
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
533
                                  VIRT_IN_CHAIN     , "FORWARD", 1, 1);
534
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
535
                                  VIRT_OUT_CHAIN    , "FORWARD", 2, 1);
536
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
537
                                  VIRT_IN_POST_CHAIN, "FORWARD", 3, 1);
538
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
539 540 541 542 543 544 545
                                  HOST_IN_CHAIN     , "INPUT"  , 1, 1);

    return 0;
}


static int
546
iptablesCreateTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560
                           virBufferPtr buf,
                           char prefix,
                           int incoming, const char *ifname,
                           int stopOnError)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix[2] = {
       prefix,
       (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                  : CHAINPREFIX_HOST_OUT_TEMP
    };

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

561
    virBufferAsprintf(buf,
562
                      CMD_DEF("%s -N %s") CMD_SEPARATOR
S
Stefan Berger 已提交
563 564
                      CMD_EXEC
                      "%s",
565
                      iptables_cmd,
S
Stefan Berger 已提交
566 567 568 569 570 571 572 573
                      chain,
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
574
iptablesCreateTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
575 576 577
                            virBufferPtr buf,
                            const char *ifname)
{
578 579 580
    iptablesCreateTmpRootChain(iptables_cmd, buf, 'F', 0, ifname, 1);
    iptablesCreateTmpRootChain(iptables_cmd, buf, 'F', 1, ifname, 1);
    iptablesCreateTmpRootChain(iptables_cmd, buf, 'H', 1, ifname, 1);
S
Stefan Berger 已提交
581 582 583 584 585
    return 0;
}


static int
586
_iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
                         virBufferPtr buf,
                         char prefix,
                         int incoming, const char *ifname,
                         int isTempChain)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix[2] = {
        prefix,
    };

    if (isTempChain)
        chainPrefix[1] = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                    : CHAINPREFIX_HOST_OUT_TEMP;
    else
        chainPrefix[1] = (incoming) ? CHAINPREFIX_HOST_IN
                                    : CHAINPREFIX_HOST_OUT;

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

606
    virBufferAsprintf(buf,
607 608 609 610
                      "%s -F %s" CMD_SEPARATOR
                      "%s -X %s" CMD_SEPARATOR,
                      iptables_cmd, chain,
                      iptables_cmd, chain);
S
Stefan Berger 已提交
611 612 613 614 615 616

    return 0;
}


static int
617
iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
618 619 620 621 622
                        virBufferPtr buf,
                        char prefix,
                        int incoming,
                        const char *ifname)
{
623
    return _iptablesRemoveRootChain(iptables_cmd,
624
                                    buf, prefix, incoming, ifname, 0);
S
Stefan Berger 已提交
625 626 627 628
}


static int
629
iptablesRemoveTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
630 631 632 633 634
                           virBufferPtr buf,
                           char prefix,
                           int incoming,
                           const char *ifname)
{
635
    return _iptablesRemoveRootChain(iptables_cmd, buf, prefix,
636
                                    incoming, ifname, 1);
S
Stefan Berger 已提交
637 638 639 640
}


static int
641
iptablesRemoveTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
642 643 644
                            virBufferPtr buf,
                            const char *ifname)
{
645 646 647
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
648 649 650 651 652
    return 0;
}


static int
653
iptablesRemoveRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
654 655 656
                         virBufferPtr buf,
                         const char *ifname)
{
657 658 659
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
660 661 662 663 664
    return 0;
}


static int
665
iptablesLinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
                         virBufferPtr buf,
                         const char *basechain,
                         char prefix,
                         int incoming, const char *ifname,
                         int stopOnError)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix[2] = {
        prefix,
        (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                   : CHAINPREFIX_HOST_OUT_TEMP
    };
    const char *match = (incoming) ? MATCH_PHYSDEV_IN
                                   : MATCH_PHYSDEV_OUT;

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

683
    virBufferAsprintf(buf,
684
                      CMD_DEF("%s -A %s "
S
Stefan Berger 已提交
685 686 687
                              "%s %s -g %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",
688
                      iptables_cmd,
S
Stefan Berger 已提交
689 690 691 692 693 694 695 696 697 698
                      basechain,
                      match, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
699
iptablesLinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
700 701 702
                          virBufferPtr buf,
                          const char *ifname)
{
703 704 705
    iptablesLinkTmpRootChain(cmd, buf, VIRT_OUT_CHAIN, 'F', 0, ifname, 1);
    iptablesLinkTmpRootChain(cmd, buf, VIRT_IN_CHAIN , 'F', 1, ifname, 1);
    iptablesLinkTmpRootChain(cmd, buf, HOST_IN_CHAIN , 'H', 1, ifname, 1);
S
Stefan Berger 已提交
706 707 708 709 710 711

    return 0;
}


static int
712
iptablesSetupVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
713 714 715 716
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
717
    virBufferAsprintf(buf,
G
Guido Günther 已提交
718
                      "res=$(%s -n -L " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
719
                      " | grep \"\\%s %s\")\n"
720
                      "if [ \"${res}\" = \"\" ]; then "
721
                        CMD_DEF("%s"
S
Stefan Berger 已提交
722 723 724 725 726
                        " -A " VIRT_IN_POST_CHAIN
                        " %s %s -j ACCEPT") CMD_SEPARATOR
                        CMD_EXEC
                        "%s"
                      "fi\n",
727
                      iptables_cmd,
S
Stefan Berger 已提交
728
                      PHYSDEV_IN, ifname,
729
                      iptables_cmd,
S
Stefan Berger 已提交
730 731 732 733 734 735 736
                      match, ifname,
                      CMD_STOPONERR(1));
    return 0;
}


static int
737
iptablesClearVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
738 739 740 741
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
742
    virBufferAsprintf(buf,
743
                      "%s -D " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
744
                      " %s %s -j ACCEPT" CMD_SEPARATOR,
745
                      iptables_cmd,
S
Stefan Berger 已提交
746 747 748 749 750
                      match, ifname);
    return 0;
}

static int
751 752 753 754 755 756
_iptablesUnlinkRootChain(const char *iptables_cmd,
                         virBufferPtr buf,
                         const char *basechain,
                         char prefix,
                         int incoming, const char *ifname,
                         int isTempChain)
S
Stefan Berger 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix[2] = {
        prefix,
    };
    if (isTempChain)
        chainPrefix[1] = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                    : CHAINPREFIX_HOST_OUT_TEMP;
    else
        chainPrefix[1] = (incoming) ? CHAINPREFIX_HOST_IN
                                    : CHAINPREFIX_HOST_OUT;
    const char *match = (incoming) ? MATCH_PHYSDEV_IN
                                   : MATCH_PHYSDEV_OUT;

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

773
    virBufferAsprintf(buf,
774
                      "%s -D %s "
S
Stefan Berger 已提交
775
                      "%s %s -g %s" CMD_SEPARATOR,
776
                      iptables_cmd,
S
Stefan Berger 已提交
777 778 779 780 781 782 783 784
                      basechain,
                      match, ifname, chain);

    return 0;
}


static int
785
iptablesUnlinkRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
786 787 788 789 790
                        virBufferPtr buf,
                        const char *basechain,
                        char prefix,
                        int incoming, const char *ifname)
{
791
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
792 793 794 795 796
                                    basechain, prefix, incoming, ifname, 0);
}


static int
797
iptablesUnlinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
798 799 800 801 802
                           virBufferPtr buf,
                           const char *basechain,
                           char prefix,
                           int incoming, const char *ifname)
{
803
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
804 805 806 807 808
                                    basechain, prefix, incoming, ifname, 1);
}


static int
809
iptablesUnlinkRootChains(const char *cmd,
S
Stefan Berger 已提交
810 811 812
                         virBufferPtr buf,
                         const char *ifname)
{
813 814 815
    iptablesUnlinkRootChain(cmd, buf, VIRT_OUT_CHAIN, 'F', 0, ifname);
    iptablesUnlinkRootChain(cmd, buf, VIRT_IN_CHAIN , 'F', 1, ifname);
    iptablesUnlinkRootChain(cmd, buf, HOST_IN_CHAIN , 'H', 1, ifname);
S
Stefan Berger 已提交
816 817 818 819 820 821

    return 0;
}


static int
822
iptablesUnlinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
823 824 825
                            virBufferPtr buf,
                            const char *ifname)
{
826 827 828
    iptablesUnlinkTmpRootChain(cmd, buf, VIRT_OUT_CHAIN, 'F', 0, ifname);
    iptablesUnlinkTmpRootChain(cmd, buf, VIRT_IN_CHAIN , 'F', 1, ifname);
    iptablesUnlinkTmpRootChain(cmd, buf, HOST_IN_CHAIN , 'H', 1, ifname);
S
Stefan Berger 已提交
829 830 831 832 833
    return 0;
}


static int
834
iptablesRenameTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
                           virBufferPtr buf,
                           char prefix,
                           int incoming,
                           const char *ifname)
{
    char tmpchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char tmpChainPrefix[2] = {
        prefix,
        (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                   : CHAINPREFIX_HOST_OUT_TEMP
    };
    char chainPrefix[2] = {
        prefix,
        (incoming) ? CHAINPREFIX_HOST_IN
                   : CHAINPREFIX_HOST_OUT
    };

    PRINT_IPT_ROOT_CHAIN(tmpchain, tmpChainPrefix, ifname);
    PRINT_IPT_ROOT_CHAIN(   chain,    chainPrefix, ifname);

855
    virBufferAsprintf(buf,
856 857
                      "%s -E %s %s" CMD_SEPARATOR,
                      iptables_cmd,
S
Stefan Berger 已提交
858 859 860 861 862 863 864
                      tmpchain,
                      chain);
    return 0;
}


static int
865
iptablesRenameTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
866 867 868
                            virBufferPtr buf,
                            const char *ifname)
{
869 870 871
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
872 873 874 875 876
    return 0;
}


static void
877
iptablesInstCommand(virBufferPtr buf,
S
Stefan Berger 已提交
878 879 880 881 882 883
                    const char *templ, char cmd, int pos,
                    int stopOnError)
{
    char position[10] = { 0 };
    if (pos >= 0)
        snprintf(position, sizeof(position), "%d", pos);
884 885
    virBufferAsprintf(buf, templ, cmd, position);
    virBufferAsprintf(buf, CMD_SEPARATOR "%s",
S
Stefan Berger 已提交
886 887 888 889 890
                      CMD_STOPONERR(stopOnError));
}


static int
891
iptablesHandleSrcMacAddr(virBufferPtr buf,
892
                         virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
893
                         nwItemDescPtr srcMacAddr,
894 895
                         int directionIn,
                         bool *srcmacskipped)
S
Stefan Berger 已提交
896 897
{
    char macaddr[VIR_MAC_STRING_BUFLEN];
898
    *srcmacskipped = false;
S
Stefan Berger 已提交
899 900

    if (HAS_ENTRY_ITEM(srcMacAddr)) {
901 902 903 904 905
        if (directionIn) {
            *srcmacskipped = true;
            return 0;
        }

906
        if (printDataType(vars,
S
Stefan Berger 已提交
907 908 909 910
                          macaddr, sizeof(macaddr),
                          srcMacAddr))
            goto err_exit;

911
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
                          " -m mac %s --mac-source %s",
                          ENTRY_GET_NEG_SIGN(srcMacAddr),
                          macaddr);
    }

    return 0;

err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


static int
927
iptablesHandleIpHdr(virBufferPtr buf,
928
                    virBufferPtr afterStateMatch,
929
                    virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
930
                    ipHdrDataDefPtr ipHdr,
931
                    int directionIn,
932 933
                    bool *skipRule, bool *skipMatch,
                    virBufferPtr prefix)
S
Stefan Berger 已提交
934
{
935
    char ipaddr[INET6_ADDRSTRLEN],
S
Stefan Berger 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949
         number[20];
    const char *src = "--source";
    const char *dst = "--destination";
    const char *srcrange = "--src-range";
    const char *dstrange = "--dst-range";
    if (directionIn) {
        src = "--destination";
        dst = "--source";
        srcrange = "--dst-range";
        dstrange = "--src-range";
    }

    if (HAS_ENTRY_ITEM(&ipHdr->dataSrcIPAddr)) {

950
        if (printDataType(vars,
S
Stefan Berger 已提交
951 952 953 954
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataSrcIPAddr))
            goto err_exit;

955
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
956 957 958 959 960 961 962
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataSrcIPAddr),
                          src,
                          ipaddr);

        if (HAS_ENTRY_ITEM(&ipHdr->dataSrcIPMask)) {

963
            if (printDataType(vars,
S
Stefan Berger 已提交
964 965 966 967
                              number, sizeof(number),
                              &ipHdr->dataSrcIPMask))
                goto err_exit;

968
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
969 970 971 972 973
                              "/%s",
                              number);
        }
    } else if (HAS_ENTRY_ITEM(&ipHdr->dataSrcIPFrom)) {

974
        if (printDataType(vars,
S
Stefan Berger 已提交
975 976 977 978
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataSrcIPFrom))
            goto err_exit;

979
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
980 981 982 983 984 985 986
                          " -m iprange %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataSrcIPFrom),
                          srcrange,
                          ipaddr);

        if (HAS_ENTRY_ITEM(&ipHdr->dataSrcIPTo)) {

987
            if (printDataType(vars,
S
Stefan Berger 已提交
988 989 990 991
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataSrcIPTo))
                goto err_exit;

992
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
993 994 995 996 997 998 999
                              "-%s",
                              ipaddr);
        }
    }

    if (HAS_ENTRY_ITEM(&ipHdr->dataDstIPAddr)) {

1000
        if (printDataType(vars,
S
Stefan Berger 已提交
1001 1002 1003 1004
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataDstIPAddr))
           goto err_exit;

1005
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1006 1007 1008 1009 1010 1011 1012
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDstIPAddr),
                          dst,
                          ipaddr);

        if (HAS_ENTRY_ITEM(&ipHdr->dataDstIPMask)) {

1013
            if (printDataType(vars,
S
Stefan Berger 已提交
1014 1015 1016 1017
                              number, sizeof(number),
                              &ipHdr->dataDstIPMask))
                goto err_exit;

1018
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
1019 1020 1021 1022 1023 1024
                              "/%s",
                              number);

        }
    } else if (HAS_ENTRY_ITEM(&ipHdr->dataDstIPFrom)) {

1025
        if (printDataType(vars,
S
Stefan Berger 已提交
1026 1027 1028 1029
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataDstIPFrom))
            goto err_exit;

1030
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1031 1032 1033 1034 1035 1036 1037
                          " -m iprange %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDstIPFrom),
                          dstrange,
                          ipaddr);

        if (HAS_ENTRY_ITEM(&ipHdr->dataDstIPTo)) {

1038
            if (printDataType(vars,
S
Stefan Berger 已提交
1039 1040 1041
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataDstIPTo))
                goto err_exit;
1042

1043
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
1044 1045 1046 1047
                              "-%s",
                              ipaddr);
        }
    }
1048

S
Stefan Berger 已提交
1049
    if (HAS_ENTRY_ITEM(&ipHdr->dataDSCP)) {
1050

1051
        if (printDataType(vars,
S
Stefan Berger 已提交
1052 1053 1054
                          number, sizeof(number),
                          &ipHdr->dataDSCP))
           goto err_exit;
1055

1056
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1057 1058 1059
                          " -m dscp %s --dscp %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDSCP),
                          number);
1060 1061
    }

1062 1063
    if (HAS_ENTRY_ITEM(&ipHdr->dataConnlimitAbove)) {
        if (directionIn) {
1064
            /* only support for limit in outgoing dir. */
1065 1066 1067 1068 1069 1070 1071
            *skipRule = true;
        } else {
            if (printDataType(vars,
                              number, sizeof(number),
                              &ipHdr->dataConnlimitAbove))
               goto err_exit;

1072 1073
            /* place connlimit after potential -m state --state ...
               since this is the most useful order */
1074
            virBufferAsprintf(afterStateMatch,
1075 1076 1077 1078 1079 1080 1081
                              " -m connlimit %s --connlimit-above %s",
                              ENTRY_GET_NEG_SIGN(&ipHdr->dataConnlimitAbove),
                              number);
            *skipMatch = true;
        }
    }

1082 1083 1084
    if (HAS_ENTRY_ITEM(&ipHdr->dataComment)) {
        printCommentVar(prefix, ipHdr->dataComment.u.string);

1085 1086 1087
        /* keep comments behind everything else -- they are packet eval.
           no-ops */
        virBufferAddLit(afterStateMatch,
1088 1089 1090
                        " -m comment --comment \"$" COMMENT_VARNAME "\"");
    }

S
Stefan Berger 已提交
1091
    return 0;
1092

S
Stefan Berger 已提交
1093 1094
err_exit:
    virBufferFreeAndReset(buf);
1095
    virBufferFreeAndReset(afterStateMatch);
S
Stefan Berger 已提交
1096 1097

    return 1;
1098 1099 1100 1101
}


static int
1102
iptablesHandlePortData(virBufferPtr buf,
1103
                       virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
1104 1105
                       portDataDefPtr portData,
                       int directionIn)
1106
{
S
Stefan Berger 已提交
1107 1108 1109 1110 1111 1112 1113
    char portstr[20];
    const char *sport = "--sport";
    const char *dport = "--dport";
    if (directionIn) {
        sport = "--dport";
        dport = "--sport";
    }
1114

S
Stefan Berger 已提交
1115
    if (HAS_ENTRY_ITEM(&portData->dataSrcPortStart)) {
1116
        if (printDataType(vars,
S
Stefan Berger 已提交
1117 1118
                          portstr, sizeof(portstr),
                          &portData->dataSrcPortStart))
1119 1120
            goto err_exit;

1121
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1122 1123 1124 1125
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataSrcPortStart),
                          sport,
                          portstr);
1126

S
Stefan Berger 已提交
1127
        if (HAS_ENTRY_ITEM(&portData->dataSrcPortEnd)) {
1128
            if (printDataType(vars,
S
Stefan Berger 已提交
1129 1130
                              portstr, sizeof(portstr),
                              &portData->dataSrcPortEnd))
1131 1132
                goto err_exit;

1133
             virBufferAsprintf(buf,
S
Stefan Berger 已提交
1134 1135
                               ":%s",
                               portstr);
1136 1137 1138
        }
    }

S
Stefan Berger 已提交
1139
    if (HAS_ENTRY_ITEM(&portData->dataDstPortStart)) {
1140
        if (printDataType(vars,
S
Stefan Berger 已提交
1141 1142
                          portstr, sizeof(portstr),
                          &portData->dataDstPortStart))
1143 1144
            goto err_exit;

1145
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1146 1147 1148 1149
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataDstPortStart),
                          dport,
                          portstr);
1150

S
Stefan Berger 已提交
1151
        if (HAS_ENTRY_ITEM(&portData->dataDstPortEnd)) {
1152
            if (printDataType(vars,
S
Stefan Berger 已提交
1153 1154
                              portstr, sizeof(portstr),
                              &portData->dataDstPortEnd))
1155 1156
                goto err_exit;

1157
             virBufferAsprintf(buf,
S
Stefan Berger 已提交
1158 1159
                               ":%s",
                               portstr);
1160 1161 1162 1163 1164
        }
    }

    return 0;

S
Stefan Berger 已提交
1165
err_exit:
1166 1167 1168
    return 1;
}

1169 1170 1171 1172 1173 1174 1175

static void
iptablesEnforceDirection(int directionIn,
                         virNWFilterRuleDefPtr rule,
                         virBufferPtr buf)
{
    if (rule->tt != VIR_NWFILTER_RULE_DIRECTION_INOUT)
1176
        virBufferAsprintf(buf, " -m conntrack --ctdir %s",
1177 1178 1179 1180 1181
                          (directionIn) ? "Original"
                                        : "Reply");
}


S
Stefan Berger 已提交
1182 1183 1184 1185 1186 1187 1188 1189
/*
 * _iptablesCreateRuleInstance:
 * @chainPrefix : The prefix to put in front of the name of the chain
 * @nwfilter : The filter
 * @rule: The rule of the filter to convert
 * @ifname : The name of the interface to apply the rule to
 * @vars : A map containing the variables to resolve
 * @res : The data structure to store the result(s) into
1190 1191 1192 1193 1194 1195
 * @match : optional string for state match
 * @accept_target : where to jump to on accepted traffic, i.e., "RETURN"
 *    "ACCEPT"
 * @isIPv6 : Whether this is an IPv6 rule
 * @maySkipICMP : whether this rule may under certain circumstances skip
 *           the ICMP rule from being created
S
Stefan Berger 已提交
1196 1197 1198 1199 1200 1201 1202 1203
 *
 * Convert a single rule into its representation for later instantiation
 *
 * Returns 0 in case of success with the result stored in the data structure
 * pointed to by res, != 0 otherwise with the error message stored in the
 * virConnect object.
 */
static int
1204
_iptablesCreateRuleInstance(int directionIn,
S
Stefan Berger 已提交
1205 1206 1207 1208
                            const char *chainPrefix,
                            virNWFilterDefPtr nwfilter,
                            virNWFilterRuleDefPtr rule,
                            const char *ifname,
1209
                            virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
1210
                            virNWFilterRuleInstPtr res,
1211
                            const char *match, bool defMatch,
1212
                            const char *accept_target,
1213 1214
                            bool isIPv6,
                            bool maySkipICMP)
S
Stefan Berger 已提交
1215 1216 1217
{
    char chain[MAX_CHAINNAME_LENGTH];
    char number[20];
1218
    virBuffer prefix = VIR_BUFFER_INITIALIZER;
S
Stefan Berger 已提交
1219
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1220
    virBuffer afterStateMatch = VIR_BUFFER_INITIALIZER;
1221
    virBufferPtr final = NULL;
S
Stefan Berger 已提交
1222
    const char *target;
1223 1224
    const char *iptables_cmd = (isIPv6) ? ip6tables_cmd_path
                                        : iptables_cmd_path;
1225 1226
    unsigned int bufUsed;
    bool srcMacSkipped = false;
1227 1228
    bool skipRule = false;
    bool skipMatch = false;
1229
    bool hasICMPType = false;
S
Stefan Berger 已提交
1230

1231 1232 1233 1234 1235 1236 1237 1238
    if (!iptables_cmd) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
                               _("cannot create rule since %s tool is "
                                 "missing."),
                               isIPv6 ? "ip6tables" : "iptables");
        goto err_exit;
    }

S
Stefan Berger 已提交
1239 1240 1241 1242
    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
1243
    case VIR_NWFILTER_RULE_PROTOCOL_TCPoIPV6:
1244
        virBufferAsprintf(&buf,
1245 1246
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1247 1248 1249 1250
                          chain);

        virBufferAddLit(&buf, " -p tcp");

1251 1252
        bufUsed = virBufferUse(&buf);

1253
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1254 1255
                                     vars,
                                     &rule->p.tcpHdrFilter.dataSrcMACAddr,
1256 1257
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1258 1259
            goto err_exit;

1260
        if (iptablesHandleIpHdr(&buf,
1261
                                &afterStateMatch,
S
Stefan Berger 已提交
1262 1263
                                vars,
                                &rule->p.tcpHdrFilter.ipHdr,
1264
                                directionIn,
1265 1266
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1267 1268
            goto err_exit;

1269
        if (HAS_ENTRY_ITEM(&rule->p.tcpHdrFilter.dataTCPFlags)) {
1270
            virBufferAsprintf(&buf, " %s --tcp-flags ",
1271 1272 1273 1274 1275 1276 1277
                      ENTRY_GET_NEG_SIGN(&rule->p.tcpHdrFilter.dataTCPFlags));
            virNWFilterPrintTCPFlags(&buf,
                      rule->p.tcpHdrFilter.dataTCPFlags.u.tcpFlags.mask,
                      ' ',
                      rule->p.tcpHdrFilter.dataTCPFlags.u.tcpFlags.flags);
        }

1278
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1279 1280 1281 1282 1283 1284
                                   vars,
                                   &rule->p.tcpHdrFilter.portData,
                                   directionIn))
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.tcpHdrFilter.dataTCPOption)) {
1285
            if (printDataType(vars,
S
Stefan Berger 已提交
1286 1287 1288 1289
                              number, sizeof(number),
                              &rule->p.tcpHdrFilter.dataTCPOption))
                goto err_exit;

1290
            virBufferAsprintf(&buf,
S
Stefan Berger 已提交
1291 1292 1293 1294 1295 1296 1297 1298
                              " %s --tcp-option %s",
                              ENTRY_GET_NEG_SIGN(&rule->p.tcpHdrFilter.dataTCPOption),
                              number);
        }

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
1299
    case VIR_NWFILTER_RULE_PROTOCOL_UDPoIPV6:
1300
        virBufferAsprintf(&buf,
1301 1302
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1303 1304 1305 1306
                          chain);

        virBufferAddLit(&buf, " -p udp");

1307 1308
        bufUsed = virBufferUse(&buf);

1309
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1310 1311
                                     vars,
                                     &rule->p.udpHdrFilter.dataSrcMACAddr,
1312 1313
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1314 1315
            goto err_exit;

1316
        if (iptablesHandleIpHdr(&buf,
1317
                                &afterStateMatch,
S
Stefan Berger 已提交
1318 1319
                                vars,
                                &rule->p.udpHdrFilter.ipHdr,
1320
                                directionIn,
1321 1322
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1323 1324
            goto err_exit;

1325
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1326 1327 1328 1329 1330 1331
                                   vars,
                                   &rule->p.udpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

1332
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
1333
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITEoIPV6:
1334
        virBufferAsprintf(&buf,
1335 1336
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1337 1338 1339 1340
                          chain);

        virBufferAddLit(&buf, " -p udplite");

1341 1342
        bufUsed = virBufferUse(&buf);

1343
        if (iptablesHandleSrcMacAddr(&buf,
1344 1345
                                     vars,
                                     &rule->p.udpliteHdrFilter.dataSrcMACAddr,
1346 1347
                                     directionIn,
                                     &srcMacSkipped))
1348 1349
            goto err_exit;

1350
        if (iptablesHandleIpHdr(&buf,
1351
                                &afterStateMatch,
1352 1353
                                vars,
                                &rule->p.udpliteHdrFilter.ipHdr,
1354
                                directionIn,
1355 1356
                                &skipRule, &skipMatch,
                                &prefix))
1357 1358 1359 1360 1361
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
1362
    case VIR_NWFILTER_RULE_PROTOCOL_ESPoIPV6:
1363
        virBufferAsprintf(&buf,
1364 1365
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1366 1367 1368 1369
                          chain);

        virBufferAddLit(&buf, " -p esp");

1370 1371
        bufUsed = virBufferUse(&buf);

1372
        if (iptablesHandleSrcMacAddr(&buf,
1373 1374
                                     vars,
                                     &rule->p.espHdrFilter.dataSrcMACAddr,
1375 1376
                                     directionIn,
                                     &srcMacSkipped))
1377 1378
            goto err_exit;

1379
        if (iptablesHandleIpHdr(&buf,
1380
                                &afterStateMatch,
1381 1382
                                vars,
                                &rule->p.espHdrFilter.ipHdr,
1383
                                directionIn,
1384 1385
                                &skipRule, &skipMatch,
                                &prefix))
1386 1387 1388 1389 1390
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_AH:
1391
    case VIR_NWFILTER_RULE_PROTOCOL_AHoIPV6:
1392
        virBufferAsprintf(&buf,
1393 1394
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1395 1396 1397 1398
                          chain);

        virBufferAddLit(&buf, " -p ah");

1399 1400
        bufUsed = virBufferUse(&buf);

1401
        if (iptablesHandleSrcMacAddr(&buf,
1402 1403
                                     vars,
                                     &rule->p.ahHdrFilter.dataSrcMACAddr,
1404 1405
                                     directionIn,
                                     &srcMacSkipped))
1406 1407
            goto err_exit;

1408
        if (iptablesHandleIpHdr(&buf,
1409
                                &afterStateMatch,
1410 1411
                                vars,
                                &rule->p.ahHdrFilter.ipHdr,
1412
                                directionIn,
1413 1414
                                &skipRule, &skipMatch,
                                &prefix))
1415 1416 1417 1418
            goto err_exit;

    break;

S
Stefan Berger 已提交
1419
    case VIR_NWFILTER_RULE_PROTOCOL_SCTP:
1420
    case VIR_NWFILTER_RULE_PROTOCOL_SCTPoIPV6:
1421
        virBufferAsprintf(&buf,
1422 1423
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1424 1425 1426 1427
                          chain);

        virBufferAddLit(&buf, " -p sctp");

1428 1429
        bufUsed = virBufferUse(&buf);

1430
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1431 1432
                                     vars,
                                     &rule->p.sctpHdrFilter.dataSrcMACAddr,
1433 1434
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1435 1436
            goto err_exit;

1437
        if (iptablesHandleIpHdr(&buf,
1438
                                &afterStateMatch,
S
Stefan Berger 已提交
1439 1440
                                vars,
                                &rule->p.sctpHdrFilter.ipHdr,
1441
                                directionIn,
1442 1443
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1444 1445
            goto err_exit;

1446
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1447 1448 1449 1450 1451 1452 1453
                                   vars,
                                   &rule->p.sctpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
1454
    case VIR_NWFILTER_RULE_PROTOCOL_ICMPV6:
1455
        virBufferAsprintf(&buf,
1456 1457
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1458 1459
                          chain);

1460 1461 1462 1463
        if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
            virBufferAddLit(&buf, " -p icmp");
        else
            virBufferAddLit(&buf, " -p icmpv6");
S
Stefan Berger 已提交
1464

1465 1466
        bufUsed = virBufferUse(&buf);

1467
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1468 1469
                                     vars,
                                     &rule->p.icmpHdrFilter.dataSrcMACAddr,
1470 1471
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1472 1473
            goto err_exit;

1474
        if (iptablesHandleIpHdr(&buf,
1475
                                &afterStateMatch,
S
Stefan Berger 已提交
1476 1477
                                vars,
                                &rule->p.icmpHdrFilter.ipHdr,
1478
                                directionIn,
1479 1480
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1481 1482 1483
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPType)) {
1484
            const char *parm;
1485

1486 1487
            hasICMPType = true;

1488 1489 1490
            if (maySkipICMP)
                goto exit_no_error;

1491 1492 1493 1494 1495
            if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
                parm = "--icmp-type";
            else
                parm = "--icmpv6-type";

1496
            if (printDataType(vars,
S
Stefan Berger 已提交
1497 1498 1499 1500
                              number, sizeof(number),
                              &rule->p.icmpHdrFilter.dataICMPType))
                goto err_exit;

1501
            virBufferAsprintf(&buf,
1502
                      " %s %s %s",
S
Stefan Berger 已提交
1503
                      ENTRY_GET_NEG_SIGN(&rule->p.icmpHdrFilter.dataICMPType),
1504
                      parm,
S
Stefan Berger 已提交
1505 1506 1507
                      number);

            if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPCode)) {
1508
                if (printDataType(vars,
S
Stefan Berger 已提交
1509 1510 1511 1512
                                  number, sizeof(number),
                                  &rule->p.icmpHdrFilter.dataICMPCode))
                    goto err_exit;

1513
                 virBufferAsprintf(&buf,
S
Stefan Berger 已提交
1514 1515 1516 1517 1518 1519
                                   "/%s",
                                   number);
            }
        }
    break;

1520
    case VIR_NWFILTER_RULE_PROTOCOL_IGMP:
1521
        virBufferAsprintf(&buf,
1522 1523 1524 1525 1526 1527
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
                          chain);

        virBufferAddLit(&buf, " -p igmp");

1528 1529
        bufUsed = virBufferUse(&buf);

1530
        if (iptablesHandleSrcMacAddr(&buf,
1531 1532
                                     vars,
                                     &rule->p.igmpHdrFilter.dataSrcMACAddr,
1533 1534
                                     directionIn,
                                     &srcMacSkipped))
1535 1536
            goto err_exit;

1537
        if (iptablesHandleIpHdr(&buf,
1538
                                &afterStateMatch,
1539 1540
                                vars,
                                &rule->p.igmpHdrFilter.ipHdr,
1541
                                directionIn,
1542 1543
                                &skipRule, &skipMatch,
                                &prefix))
1544 1545 1546 1547
            goto err_exit;

    break;

S
Stefan Berger 已提交
1548
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
1549
    case VIR_NWFILTER_RULE_PROTOCOL_ALLoIPV6:
1550
        virBufferAsprintf(&buf,
1551 1552
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1553 1554 1555 1556
                          chain);

        virBufferAddLit(&buf, " -p all");

1557 1558
        bufUsed = virBufferUse(&buf);

1559
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1560 1561
                                     vars,
                                     &rule->p.allHdrFilter.dataSrcMACAddr,
1562 1563
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1564 1565
            goto err_exit;

1566
        if (iptablesHandleIpHdr(&buf,
1567
                                &afterStateMatch,
S
Stefan Berger 已提交
1568 1569
                                vars,
                                &rule->p.allHdrFilter.ipHdr,
1570
                                directionIn,
1571 1572
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1573 1574 1575 1576 1577 1578 1579 1580
            goto err_exit;

    break;

    default:
        return -1;
    }

1581 1582
    if ((srcMacSkipped && bufUsed == virBufferUse(&buf)) ||
         skipRule) {
1583
        virBufferFreeAndReset(&buf);
1584
        virBufferFreeAndReset(&prefix);
1585 1586 1587
        return 0;
    }

S
Stefan Berger 已提交
1588 1589
    if (rule->action == VIR_NWFILTER_RULE_ACTION_ACCEPT)
        target = accept_target;
1590
    else {
1591
        target = virNWFilterJumpTargetTypeToString(rule->action);
1592
        skipMatch = defMatch;
1593 1594
    }

1595
    if (match && !skipMatch)
1596
        virBufferAsprintf(&buf, " %s", match);
1597

1598
    if (defMatch && match != NULL && !skipMatch && !hasICMPType)
1599 1600 1601
        iptablesEnforceDirection(directionIn,
                                 rule,
                                 &buf);
S
Stefan Berger 已提交
1602

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
    if (virBufferError(&afterStateMatch)) {
        virBufferFreeAndReset(&buf);
        virBufferFreeAndReset(&prefix);
        virBufferFreeAndReset(&afterStateMatch);
        virReportOOMError();
        return -1;
    }

    if (virBufferUse(&afterStateMatch)) {
        char *s = virBufferContentAndReset(&afterStateMatch);

        virBufferAdd(&buf, s, -1);

        VIR_FREE(s);
    }

1619
    virBufferAsprintf(&buf,
S
Stefan Berger 已提交
1620 1621 1622 1623
                      " -j %s" CMD_DEF_POST CMD_SEPARATOR
                      CMD_EXEC,
                      target);

1624
    if (virBufferError(&buf) || virBufferError(&prefix)) {
S
Stefan Berger 已提交
1625
        virBufferFreeAndReset(&buf);
1626
        virBufferFreeAndReset(&prefix);
S
Stefan Berger 已提交
1627 1628 1629 1630
        virReportOOMError();
        return -1;
    }

1631
    if (virBufferUse(&prefix)) {
S
Stefan Berger 已提交
1632 1633 1634 1635 1636
        char *s = virBufferContentAndReset(&buf);

        virBufferAdd(&prefix, s, -1);

        VIR_FREE(s);
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648

        final = &prefix;

        if (virBufferError(&prefix)) {
            virBufferFreeAndReset(&prefix);
            virReportOOMError();
            return -1;
        }
    } else
        final = &buf;


1649
    return ebiptablesAddRuleInst(res,
1650
                                 virBufferContentAndReset(final),
S
Stefan Berger 已提交
1651
                                 nwfilter->chainsuffix,
1652
                                 nwfilter->chainPriority,
S
Stefan Berger 已提交
1653 1654
                                 '\0',
                                 rule->priority,
1655
                                 (isIPv6) ? RT_IP6TABLES : RT_IPTABLES);
S
Stefan Berger 已提交
1656 1657 1658 1659


err_exit:
    virBufferFreeAndReset(&buf);
S
Stefan Berger 已提交
1660
    virBufferFreeAndReset(&prefix);
1661
    virBufferFreeAndReset(&afterStateMatch);
S
Stefan Berger 已提交
1662 1663 1664

    return -1;

1665 1666
exit_no_error:
    virBufferFreeAndReset(&buf);
S
Stefan Berger 已提交
1667
    virBufferFreeAndReset(&prefix);
1668
    virBufferFreeAndReset(&afterStateMatch);
1669 1670

    return 0;
S
Stefan Berger 已提交
1671 1672 1673
}


1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
static int
printStateMatchFlags(int32_t flags, char **bufptr)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    virNWFilterPrintStateMatchFlags(&buf,
                                    "-m state --state ",
                                    flags,
                                    false);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        virReportOOMError();
        return 1;
    }
    *bufptr = virBufferContentAndReset(&buf);
    return 0;
}

static int
iptablesCreateRuleInstanceStateCtrl(virNWFilterDefPtr nwfilter,
                                    virNWFilterRuleDefPtr rule,
                                    const char *ifname,
1695
                                    virNWFilterVarCombIterPtr vars,
1696 1697 1698 1699
                                    virNWFilterRuleInstPtr res,
                                    bool isIPv6)
{
    int rc;
C
Christophe Fergeau 已提交
1700
    int directionIn = 0;
1701 1702 1703 1704 1705 1706 1707 1708
    char chainPrefix[2];
    bool maySkipICMP, inout = false;
    char *matchState = NULL;
    bool create;

    if ((rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN) ||
        (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT)) {
        directionIn = 1;
C
Christophe Fergeau 已提交
1709 1710
        inout = (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
    }
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815

    chainPrefix[0] = 'F';

    maySkipICMP = directionIn || inout;

    create = true;
    matchState = NULL;

    if (directionIn && !inout) {
        if ((rule->flags & IPTABLES_STATE_FLAGS))
            create = false;
    }

    if (create && (rule->flags & IPTABLES_STATE_FLAGS)) {
        if (printStateMatchFlags(rule->flags, &matchState))
            return 1;
    }

    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
    if (create) {
        rc = _iptablesCreateRuleInstance(directionIn,
                                         chainPrefix,
                                         nwfilter,
                                         rule,
                                         ifname,
                                         vars,
                                         res,
                                         matchState, false,
                                         "RETURN",
                                         isIPv6,
                                         maySkipICMP);

        VIR_FREE(matchState);
        if (rc)
            return rc;
    }

    maySkipICMP = !directionIn || inout;
    create = true;

    if (!directionIn) {
        if ((rule->flags & IPTABLES_STATE_FLAGS))
            create = false;
    }

    if (create && (rule->flags & IPTABLES_STATE_FLAGS)) {
        if (printStateMatchFlags(rule->flags, &matchState))
            return 1;
    }

    chainPrefix[1] = CHAINPREFIX_HOST_OUT_TEMP;
    if (create) {
        rc = _iptablesCreateRuleInstance(!directionIn,
                                         chainPrefix,
                                         nwfilter,
                                         rule,
                                         ifname,
                                         vars,
                                         res,
                                         matchState, false,
                                         "ACCEPT",
                                         isIPv6,
                                         maySkipICMP);

        VIR_FREE(matchState);

        if (rc)
            return rc;
    }

    maySkipICMP = directionIn;

    create = true;

    if (directionIn && !inout) {
        if ((rule->flags & IPTABLES_STATE_FLAGS))
            create = false;
    } else {
        if ((rule->flags & IPTABLES_STATE_FLAGS)) {
            if (printStateMatchFlags(rule->flags, &matchState))
                return 1;
        }
    }

    if (create) {
        chainPrefix[0] = 'H';
        chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
        rc = _iptablesCreateRuleInstance(directionIn,
                                         chainPrefix,
                                         nwfilter,
                                         rule,
                                         ifname,
                                         vars,
                                         res,
                                         matchState, false,
                                         "RETURN",
                                         isIPv6,
                                         maySkipICMP);
        VIR_FREE(matchState);
    }

    return rc;
}


S
Stefan Berger 已提交
1816
static int
1817
iptablesCreateRuleInstance(virNWFilterDefPtr nwfilter,
S
Stefan Berger 已提交
1818 1819
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
1820
                           virNWFilterVarCombIterPtr vars,
1821 1822
                           virNWFilterRuleInstPtr res,
                           bool isIPv6)
S
Stefan Berger 已提交
1823 1824 1825 1826 1827
{
    int rc;
    int directionIn = 0;
    char chainPrefix[2];
    int needState = 1;
1828
    bool maySkipICMP, inout = false;
1829
    const char *matchState;
S
Stefan Berger 已提交
1830

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
    if (!(rule->flags & RULE_FLAG_NO_STATEMATCH) &&
         (rule->flags & IPTABLES_STATE_FLAGS)) {
        return iptablesCreateRuleInstanceStateCtrl(nwfilter,
                                                   rule,
                                                   ifname,
                                                   vars,
                                                   res,
                                                   isIPv6);
    }

S
Stefan Berger 已提交
1841 1842 1843
    if ((rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN) ||
        (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT)) {
        directionIn = 1;
1844
        inout = (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
1845 1846
        if (inout)
            needState = 0;
S
Stefan Berger 已提交
1847 1848
    }

1849 1850 1851
    if ((rule->flags & RULE_FLAG_NO_STATEMATCH))
        needState = 0;

S
Stefan Berger 已提交
1852 1853
    chainPrefix[0] = 'F';

1854 1855
    maySkipICMP = directionIn || inout;

1856 1857 1858 1859 1860
    if (needState)
        matchState = directionIn ? MATCH_STATE_IN : MATCH_STATE_OUT;
    else
        matchState = NULL;

S
Stefan Berger 已提交
1861
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1862
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1863 1864 1865 1866 1867 1868
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1869
                                     matchState, true,
1870
                                     "RETURN",
1871 1872
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1873 1874 1875
    if (rc)
        return rc;

1876 1877

    maySkipICMP = !directionIn || inout;
1878 1879 1880 1881
    if (needState)
        matchState = directionIn ? MATCH_STATE_OUT : MATCH_STATE_IN;
    else
        matchState = NULL;
1882

S
Stefan Berger 已提交
1883
    chainPrefix[1] = CHAINPREFIX_HOST_OUT_TEMP;
1884
    rc = _iptablesCreateRuleInstance(!directionIn,
S
Stefan Berger 已提交
1885 1886 1887 1888 1889 1890
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1891
                                     matchState, true,
1892
                                     "ACCEPT",
1893 1894
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1895 1896 1897
    if (rc)
        return rc;

1898
    maySkipICMP = directionIn;
1899 1900 1901 1902
    if (needState)
        matchState = directionIn ? MATCH_STATE_IN : MATCH_STATE_OUT;
    else
        matchState = NULL;
1903

S
Stefan Berger 已提交
1904 1905
    chainPrefix[0] = 'H';
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1906
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1907 1908 1909 1910 1911 1912
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1913 1914
                                     matchState, true,
                                     "RETURN",
1915 1916
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1917 1918 1919 1920 1921 1922 1923

    return rc;
}




1924 1925 1926 1927 1928 1929 1930 1931
/*
 * ebtablesCreateRuleInstance:
 * @chainPrefix : The prefix to put in front of the name of the chain
 * @nwfilter : The filter
 * @rule: The rule of the filter to convert
 * @ifname : The name of the interface to apply the rule to
 * @vars : A map containing the variables to resolve
 * @res : The data structure to store the result(s) into
1932
 * @reverse : Whether to reverse src and dst attributes
1933 1934 1935 1936 1937 1938 1939 1940
 *
 * Convert a single rule into its representation for later instantiation
 *
 * Returns 0 in case of success with the result stored in the data structure
 * pointed to by res, != 0 otherwise with the error message stored in the
 * virConnect object.
 */
static int
1941
ebtablesCreateRuleInstance(char chainPrefix,
1942 1943 1944
                           virNWFilterDefPtr nwfilter,
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
1945
                           virNWFilterVarCombIterPtr vars,
1946 1947
                           virNWFilterRuleInstPtr res,
                           bool reverse)
1948 1949 1950
{
    char macaddr[VIR_MAC_STRING_BUFLEN],
         ipaddr[INET_ADDRSTRLEN],
1951
         ipv6addr[INET6_ADDRSTRLEN],
1952 1953 1954
         number[20];
    char chain[MAX_CHAINNAME_LENGTH];
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1955
    const char *target;
1956

1957 1958 1959 1960 1961 1962 1963
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rule since ebtables tool is "
                                 "missing."));
        goto err_exit;
    }

1964 1965 1966
    if (STREQ(nwfilter->chainsuffix,
              virNWFilterChainSuffixTypeToString(
                  VIR_NWFILTER_CHAINSUFFIX_ROOT)))
1967 1968 1969
        PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);
    else
        PRINT_CHAIN(chain, chainPrefix, ifname,
1970
                    nwfilter->chainsuffix);
1971 1972 1973 1974 1975


    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:

1976
        virBufferAsprintf(&buf,
1977 1978
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1979 1980


1981
        if (ebtablesHandleEthHdr(&buf,
1982
                                 vars,
1983 1984
                                 &rule->p.ethHdrFilter.ethHdr,
                                 reverse))
1985 1986 1987
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.ethHdrFilter.dataProtocolID)) {
1988
            if (printDataTypeAsHex(vars,
1989 1990
                                   number, sizeof(number),
                                   &rule->p.ethHdrFilter.dataProtocolID))
1991
                goto err_exit;
1992
            virBufferAsprintf(&buf,
1993 1994 1995 1996 1997 1998 1999
                          " -p %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.ethHdrFilter.dataProtocolID),
                          number);
        }
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
2000
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
2001

2002
        virBufferAsprintf(&buf,
2003 2004
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2005

2006
        if (ebtablesHandleEthHdr(&buf,
2007
                                 vars,
2008 2009
                                 &rule->p.arpHdrFilter.ethHdr,
                                 reverse))
2010 2011
            goto err_exit;

2012
        virBufferAsprintf(&buf, " -p 0x%x",
2013 2014 2015
                          (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ARP)
                           ? l3_protocols[L3_PROTO_ARP_IDX].attr
                           : l3_protocols[L3_PROTO_RARP_IDX].attr);
2016 2017

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataHWType)) {
2018 2019 2020
             if (printDataType(vars,
                               number, sizeof(number),
                               &rule->p.arpHdrFilter.dataHWType))
2021
                goto err_exit;
2022
           virBufferAsprintf(&buf,
2023 2024 2025 2026 2027 2028
                          " --arp-htype %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataHWType),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataOpcode)) {
2029
            if (printDataType(vars,
2030 2031 2032
                              number, sizeof(number),
                              &rule->p.arpHdrFilter.dataOpcode))
                goto err_exit;
2033
            virBufferAsprintf(&buf,
2034 2035 2036 2037 2038 2039
                          " --arp-opcode %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataOpcode),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataProtocolType)) {
2040
            if (printDataTypeAsHex(vars,
2041 2042
                                   number, sizeof(number),
                                   &rule->p.arpHdrFilter.dataProtocolType))
2043
                goto err_exit;
2044
            virBufferAsprintf(&buf,
2045 2046 2047 2048 2049 2050
                          " --arp-ptype %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataProtocolType),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcIPAddr)) {
2051
            if (printDataType(vars,
2052 2053 2054 2055
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPSrcIPAddr))
                goto err_exit;

2056
            virBufferAsprintf(&buf,
2057 2058
                          " %s %s %s",
                          reverse ? "--arp-ip-dst" : "--arp-ip-src",
2059 2060 2061 2062 2063
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstIPAddr)) {
2064
            if (printDataType(vars,
2065 2066 2067 2068
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPDstIPAddr))
                goto err_exit;

2069
            virBufferAsprintf(&buf,
2070 2071
                          " %s %s %s",
                          reverse ? "--arp-ip-src" : "--arp-ip-dst",
2072 2073 2074 2075 2076
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcMACAddr)) {
2077
            if (printDataType(vars,
2078 2079 2080 2081
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPSrcMACAddr))
                goto err_exit;

2082
            virBufferAsprintf(&buf,
2083 2084
                          " %s %s %s",
                          reverse ? "--arp-mac-dst" : "--arp-mac-src",
2085 2086 2087 2088 2089
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcMACAddr),
                          macaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstMACAddr)) {
2090
            if (printDataType(vars,
2091 2092 2093 2094
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPDstMACAddr))
                goto err_exit;

2095
            virBufferAsprintf(&buf,
2096 2097
                          " %s %s %s",
                          reverse ? "--arp-mac-src" : "--arp-mac-dst",
2098 2099 2100
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstMACAddr),
                          macaddr);
        }
2101 2102 2103 2104 2105 2106 2107

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataGratuitousARP) &&
            rule->p.arpHdrFilter.dataGratuitousARP.u.boolean) {
            virBufferAsprintf(&buf,
                          " %s --arp-gratuitous",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataGratuitousARP));
        }
2108 2109 2110
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_IP:
2111
        virBufferAsprintf(&buf,
2112 2113
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2114

2115
        if (ebtablesHandleEthHdr(&buf,
2116
                                 vars,
2117 2118
                                 &rule->p.ipHdrFilter.ethHdr,
                                 reverse))
2119 2120 2121 2122 2123 2124
            goto err_exit;

        virBufferAddLit(&buf,
                        " -p ipv4");

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr)) {
2125
            if (printDataType(vars,
2126 2127 2128 2129
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

2130
            virBufferAsprintf(&buf,
2131 2132
                          " %s %s %s",
                          reverse ? "--ip-destination" : "--ip-source",
2133 2134 2135 2136
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPMask)) {
2137
                if (printDataType(vars,
2138 2139 2140
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
2141
                virBufferAsprintf(&buf,
2142 2143 2144 2145 2146 2147 2148
                             "/%s",
                             number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDstIPAddr)) {

2149
            if (printDataType(vars,
2150 2151 2152 2153
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

2154
            virBufferAsprintf(&buf,
2155 2156
                          " %s %s %s",
                          reverse ? "--ip-source" : "--ip-destination",
2157 2158 2159 2160
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDstIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDstIPMask)) {
2161
                if (printDataType(vars,
2162 2163 2164
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
2165
                virBufferAsprintf(&buf,
2166 2167 2168 2169 2170 2171
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataProtocolID)) {
2172
            if (printDataType(vars,
2173 2174 2175 2176
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.ipHdr.dataProtocolID))
                goto err_exit;

2177
            virBufferAsprintf(&buf,
2178 2179 2180 2181 2182 2183 2184
                 " --ip-protocol %s %s",
                 ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataProtocolID),
                 number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataSrcPortStart)) {

2185
            if (printDataType(vars,
2186 2187 2188 2189
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataSrcPortStart))
                goto err_exit;

2190
            virBufferAsprintf(&buf,
2191 2192
                          " %s %s %s",
                          reverse ? "--ip-destination-port" : "--ip-source-port",
2193 2194 2195 2196
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataSrcPortEnd)) {
2197
                if (printDataType(vars,
2198 2199 2200 2201
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

2202
                virBufferAsprintf(&buf,
2203 2204 2205 2206 2207 2208 2209
                                  ":%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataDstPortStart)) {

2210
            if (printDataType(vars,
2211 2212 2213 2214
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataDstPortStart))
                goto err_exit;

2215
            virBufferAsprintf(&buf,
2216 2217
                          " %s %s %s",
                          reverse ? "--ip-source-port" : "--ip-destination-port",
2218 2219 2220 2221
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataDstPortEnd)) {
2222
                if (printDataType(vars,
2223 2224 2225 2226
                                number, sizeof(number),
                                &rule->p.ipHdrFilter.portData.dataDstPortEnd))
                    goto err_exit;

2227
                virBufferAsprintf(&buf,
2228 2229 2230 2231 2232 2233
                                  ":%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDSCP)) {
2234 2235 2236
            if (printDataTypeAsHex(vars,
                                   number, sizeof(number),
                                   &rule->p.ipHdrFilter.ipHdr.dataDSCP))
2237 2238
                goto err_exit;

2239
            virBufferAsprintf(&buf,
2240 2241 2242 2243 2244 2245
                       " --ip-tos %s %s",
                       ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDSCP),
                       number);
        }
    break;

2246
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
2247
        virBufferAsprintf(&buf,
2248 2249
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2250

2251
        if (ebtablesHandleEthHdr(&buf,
2252
                                 vars,
2253 2254
                                 &rule->p.ipv6HdrFilter.ethHdr,
                                 reverse))
2255 2256 2257 2258 2259 2260
            goto err_exit;

        virBufferAddLit(&buf,
                        " -p ipv6");

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr)) {
2261
            if (printDataType(vars,
2262 2263 2264 2265
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

2266
            virBufferAsprintf(&buf,
2267 2268
                          " %s %s %s",
                          reverse ? "--ip6-destination" : "--ip6-source",
2269 2270 2271 2272
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask)) {
2273
                if (printDataType(vars,
2274 2275 2276
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
2277
                virBufferAsprintf(&buf,
2278 2279 2280 2281 2282 2283 2284
                             "/%s",
                             number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr)) {

2285
            if (printDataType(vars,
2286 2287 2288 2289
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

2290
            virBufferAsprintf(&buf,
2291 2292
                          " %s %s %s",
                          reverse ? "--ip6-source" : "--ip6-destination",
2293 2294 2295 2296
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask)) {
2297
                if (printDataType(vars,
2298 2299 2300
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
2301
                virBufferAsprintf(&buf,
2302 2303 2304 2305 2306 2307
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID)) {
2308
            if (printDataType(vars,
2309 2310 2311 2312
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.ipHdr.dataProtocolID))
                goto err_exit;

2313
            virBufferAsprintf(&buf,
2314 2315 2316 2317 2318 2319 2320
                 " --ip6-protocol %s %s",
                 ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID),
                 number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataSrcPortStart)) {

2321
            if (printDataType(vars,
2322 2323 2324 2325
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataSrcPortStart))
                goto err_exit;

2326
            virBufferAsprintf(&buf,
2327 2328
                          " %s %s %s",
                          reverse ? "--ip6-destination-port" : "--ip6-source-port",
2329 2330 2331 2332
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataSrcPortEnd)) {
2333
                if (printDataType(vars,
2334 2335 2336 2337
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

2338
                virBufferAsprintf(&buf,
2339 2340 2341 2342 2343 2344 2345
                                  ":%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataDstPortStart)) {

2346
            if (printDataType(vars,
2347 2348 2349 2350
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataDstPortStart))
                goto err_exit;

2351
            virBufferAsprintf(&buf,
2352 2353
                          " %s %s %s",
                          reverse ? "--ip6-source-port" : "--ip6-destination-port",
2354 2355 2356 2357
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataDstPortEnd)) {
2358 2359 2360
                if (printDataType(vars,
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataDstPortEnd))
2361 2362
                    goto err_exit;

2363
                virBufferAsprintf(&buf,
2364 2365 2366 2367 2368 2369
                                  ":%s",
                                  number);
            }
        }
    break;

2370
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
2371
        virBufferAsprintf(&buf,
2372 2373
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2374
    break;
S
Stefan Berger 已提交
2375 2376 2377

    default:
        return -1;
2378 2379
    }

2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
    switch (rule->action) {
    case VIR_NWFILTER_RULE_ACTION_REJECT:
        /* REJECT not supported */
        target = virNWFilterJumpTargetTypeToString(
                                     VIR_NWFILTER_RULE_ACTION_DROP);
    break;
    default:
        target = virNWFilterJumpTargetTypeToString(rule->action);
    }

2390
    virBufferAsprintf(&buf,
2391 2392
                      " -j %s" CMD_DEF_POST CMD_SEPARATOR
                      CMD_EXEC,
2393
                      target);
2394 2395 2396 2397 2398 2399 2400

    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        virReportOOMError();
        return -1;
    }

2401
    return ebiptablesAddRuleInst(res,
2402 2403
                                 virBufferContentAndReset(&buf),
                                 nwfilter->chainsuffix,
2404
                                 nwfilter->chainPriority,
2405
                                 chainPrefix,
S
Stefan Berger 已提交
2406 2407
                                 rule->priority,
                                 RT_EBTABLES);
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431

err_exit:
    virBufferFreeAndReset(&buf);

    return -1;
}


/*
 * ebiptablesCreateRuleInstance:
 * @conn : Pointer to a virConnect object
 * @nwfilter : The filter
 * @rule: The rule of the filter to convert
 * @ifname : The name of the interface to apply the rule to
 * @vars : A map containing the variables to resolve
 * @res : The data structure to store the result(s) into
 *
 * Convert a single rule into its representation for later instantiation
 *
 * Returns 0 in case of success with the result stored in the data structure
 * pointed to by res, != 0 otherwise with the error message stored in the
 * virConnect object.
 */
static int
2432
ebiptablesCreateRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
2433
                             enum virDomainNetType nettype ATTRIBUTE_UNUSED,
2434 2435 2436
                             virNWFilterDefPtr nwfilter,
                             virNWFilterRuleDefPtr rule,
                             const char *ifname,
2437
                             virNWFilterVarCombIterPtr vars,
2438 2439 2440
                             virNWFilterRuleInstPtr res)
{
    int rc = 0;
2441
    bool isIPv6;
2442 2443 2444 2445 2446

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_IP:
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:
    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
2447
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
2448
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
2449
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
2450 2451 2452

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_OUT ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2453
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_IN_TEMP,
2454 2455 2456 2457
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2458 2459
                                            res,
                                            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
2460 2461 2462 2463 2464 2465
            if (rc)
                return rc;
        }

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2466
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_OUT_TEMP,
2467 2468 2469 2470
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2471 2472
                                            res,
                                            false);
2473 2474
        }
    break;
S
Stefan Berger 已提交
2475 2476 2477

    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
2478 2479 2480
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
    case VIR_NWFILTER_RULE_PROTOCOL_AH:
S
Stefan Berger 已提交
2481 2482 2483 2484
    case VIR_NWFILTER_RULE_PROTOCOL_SCTP:
    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
    case VIR_NWFILTER_RULE_PROTOCOL_IGMP:
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
2485
        isIPv6 = 0;
2486
        rc = iptablesCreateRuleInstance(nwfilter,
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
                                        rule,
                                        ifname,
                                        vars,
                                        res,
                                        isIPv6);
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_TCPoIPV6:
    case VIR_NWFILTER_RULE_PROTOCOL_UDPoIPV6:
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITEoIPV6:
    case VIR_NWFILTER_RULE_PROTOCOL_ESPoIPV6:
    case VIR_NWFILTER_RULE_PROTOCOL_AHoIPV6:
    case VIR_NWFILTER_RULE_PROTOCOL_SCTPoIPV6:
    case VIR_NWFILTER_RULE_PROTOCOL_ICMPV6:
    case VIR_NWFILTER_RULE_PROTOCOL_ALLoIPV6:
        isIPv6 = 1;
2503
        rc = iptablesCreateRuleInstance(nwfilter,
S
Stefan Berger 已提交
2504 2505 2506
                                        rule,
                                        ifname,
                                        vars,
2507 2508
                                        res,
                                        isIPv6);
S
Stefan Berger 已提交
2509 2510 2511
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_LAST:
2512
        virNWFilterReportError(VIR_ERR_OPERATION_FAILED,
S
Stefan Berger 已提交
2513 2514 2515
                               "%s", _("illegal protocol type"));
        rc = 1;
    break;
2516 2517 2518 2519 2520
    }

    return rc;
}

2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
static int
ebiptablesCreateRuleInstanceIterate(
                             virConnectPtr conn ATTRIBUTE_UNUSED,
                             enum virDomainNetType nettype ATTRIBUTE_UNUSED,
                             virNWFilterDefPtr nwfilter,
                             virNWFilterRuleDefPtr rule,
                             const char *ifname,
                             virNWFilterHashTablePtr vars,
                             virNWFilterRuleInstPtr res)
{
    int rc = 0;
    virNWFilterVarCombIterPtr vciter;

    /* rule->vars holds all the variables names that this rule will access.
     * iterate over all combinations of the variables' values and instantiate
     * the filtering rule with each combination.
     */
    vciter = virNWFilterVarCombIterCreate(vars, rule->vars, rule->nvars);
    if (!vciter)
        return 1;

    do {
        rc = ebiptablesCreateRuleInstance(conn,
                                          nettype,
                                          nwfilter,
                                          rule,
                                          ifname,
                                          vciter,
                                          res);
        if (rc)
            break;
        vciter = virNWFilterVarCombIterNext(vciter);
    } while (vciter != NULL);

    virNWFilterVarCombIterFree(vciter);

    return rc;
}
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572

static int
ebiptablesFreeRuleInstance(void *_inst)
{
    ebiptablesRuleInstFree((ebiptablesRuleInstPtr)_inst);
    return 0;
}


static int
ebiptablesDisplayRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
                              void *_inst)
{
    ebiptablesRuleInstPtr inst = (ebiptablesRuleInstPtr)_inst;
2573 2574
    VIR_INFO("Command Template: '%s', Needed protocol: '%s'",
             inst->commandTemplate,
2575
             inst->neededProtocolChain);
2576 2577 2578 2579 2580 2581 2582 2583
    return 0;
}


/**
 * ebiptablesExecCLI:
 * @buf : pointer to virBuffer containing the string with the commands to
 *        execute.
2584
 * @status: Pointer to an integer for returning the WEXITSTATUS of the
2585 2586
 *        commands executed via the script the was run.
 *
2587
 * Returns 0 in case of success, < 0 in case of an error. The returned
2588
 * value is NOT the result of running the commands inside the shell
2589 2590
 * script.
 *
2591
 * Execute a sequence of commands (held in the given buffer) as a /bin/sh
2592 2593
 * script and return the status of the execution in *status (if status is
 * NULL, then the script must exit with status 0).
2594 2595
 */
static int
2596
ebiptablesExecCLI(virBufferPtr buf,
2597 2598
                  int *status)
{
2599 2600
    int rc = -1;
    virCommandPtr cmd;
2601 2602

    *status = 0;
2603
    if (!virBufferError(buf) && !virBufferUse(buf))
2604 2605
        return 0;

2606 2607
    cmd = virCommandNewArgList("/bin/sh", "-c", NULL);
    virCommandAddArgBuffer(cmd, buf);
2608 2609 2610

    virMutexLock(&execCLIMutex);

2611
    rc = virCommandRun(cmd, status);
2612

2613 2614
    virMutexUnlock(&execCLIMutex);

2615 2616
    virCommandFree(cmd);

2617 2618 2619 2620 2621
    return rc;
}


static int
2622
ebtablesCreateTmpRootChain(virBufferPtr buf,
2623 2624 2625 2626 2627 2628 2629 2630 2631
                           int incoming, const char *ifname,
                           int stopOnError)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                  : CHAINPREFIX_HOST_OUT_TEMP;

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);

2632
    virBufferAsprintf(buf,
2633
                      CMD_DEF("%s -t %s -N %s") CMD_SEPARATOR
2634 2635
                      CMD_EXEC
                      "%s",
2636
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2637 2638 2639 2640 2641 2642 2643
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2644
ebtablesLinkTmpRootChain(virBufferPtr buf,
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
                         int incoming, const char *ifname,
                         int stopOnError)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                  : CHAINPREFIX_HOST_OUT_TEMP;
    char iodev = (incoming) ? 'i' : 'o';

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);

2655
    virBufferAsprintf(buf,
2656
                      CMD_DEF("%s -t %s -A %s -%c %s -j %s") CMD_SEPARATOR
2657 2658
                      CMD_EXEC
                      "%s",
2659
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2671
_ebtablesRemoveRootChain(virBufferPtr buf,
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
                         int incoming, const char *ifname,
                         int isTempChain)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix;
    if (isTempChain)
        chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                 : CHAINPREFIX_HOST_OUT_TEMP;
    else
        chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN
                                 : CHAINPREFIX_HOST_OUT;

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);

2686
    virBufferAsprintf(buf,
2687 2688 2689 2690
                      "%s -t %s -F %s" CMD_SEPARATOR
                      "%s -t %s -X %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2691 2692 2693 2694 2695 2696

    return 0;
}


static int
2697
ebtablesRemoveRootChain(virBufferPtr buf,
2698 2699
                        int incoming, const char *ifname)
{
2700
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 0);
2701 2702 2703 2704
}


static int
2705
ebtablesRemoveTmpRootChain(virBufferPtr buf,
2706 2707
                           int incoming, const char *ifname)
{
2708
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 1);
2709 2710 2711 2712
}


static int
2713
_ebtablesUnlinkRootChain(virBufferPtr buf,
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
                         int incoming, const char *ifname,
                         int isTempChain)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char iodev = (incoming) ? 'i' : 'o';
    char chainPrefix;

    if (isTempChain) {
        chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                 : CHAINPREFIX_HOST_OUT_TEMP;
    } else {
        chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN
                                 : CHAINPREFIX_HOST_OUT;
    }

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);

2731
    virBufferAsprintf(buf,
2732 2733
                      "%s -t %s -D %s -%c %s -j %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2734 2735 2736 2737 2738 2739 2740 2741 2742
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain);

    return 0;
}


static int
2743
ebtablesUnlinkRootChain(virBufferPtr buf,
2744 2745
                        int incoming, const char *ifname)
{
2746
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 0);
2747 2748 2749 2750
}


static int
2751
ebtablesUnlinkTmpRootChain(virBufferPtr buf,
2752 2753
                           int incoming, const char *ifname)
{
2754
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 1);
2755 2756 2757 2758
}


static int
2759 2760
ebtablesCreateTmpSubChain(ebiptablesRuleInstPtr *inst,
                          int *nRuleInstances,
2761 2762
                          int incoming,
                          const char *ifname,
2763
                          enum l3_proto_idx protoidx,
2764
                          const char *filtername,
2765 2766
                          int stopOnError,
                          virNWFilterChainPriority priority)
2767
{
2768 2769 2770
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    ebiptablesRuleInstPtr tmp = *inst;
    size_t count = *nRuleInstances;
2771 2772 2773 2774 2775
    char rootchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                  : CHAINPREFIX_HOST_OUT_TEMP;

    PRINT_ROOT_CHAIN(rootchain, chainPrefix, ifname);
2776 2777
    PRINT_CHAIN(chain, chainPrefix, ifname,
                (filtername) ? filtername : l3_protocols[protoidx].val);
2778

2779 2780 2781 2782 2783
    virBufferAsprintf(&buf,
                      CMD_DEF("%s -t %s -F %s") CMD_SEPARATOR
                      CMD_EXEC
                      CMD_DEF("%s -t %s -X %s") CMD_SEPARATOR
                      CMD_EXEC
2784
                      CMD_DEF("%s -t %s -N %s") CMD_SEPARATOR
2785 2786
                      CMD_EXEC
                      "%s"
2787 2788
                      CMD_DEF("%s -t %s -%%c %s %%s -p 0x%x -j %s")
                          CMD_SEPARATOR
2789 2790 2791
                      CMD_EXEC
                      "%s",

2792 2793
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2794
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2795 2796 2797

                      CMD_STOPONERR(stopOnError),

2798
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2799
                      rootchain, l3_protocols[protoidx].attr, chain,
2800 2801 2802

                      CMD_STOPONERR(stopOnError));

2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
    if (virBufferError(&buf) ||
        VIR_EXPAND_N(tmp, count, 1) < 0) {
        virReportOOMError();
        virBufferFreeAndReset(&buf);
        return -1;
    }

    *nRuleInstances = count;
    *inst = tmp;

    tmp[*nRuleInstances - 1].priority = priority;
    tmp[*nRuleInstances - 1].commandTemplate =
        virBufferContentAndReset(&buf);
    tmp[*nRuleInstances - 1].neededProtocolChain =
        virNWFilterChainSuffixTypeToString(VIR_NWFILTER_CHAINSUFFIX_ROOT);

2819 2820 2821 2822
    return 0;
}

static int
2823 2824 2825
_ebtablesRemoveSubChains(virBufferPtr buf,
                         const char *ifname,
                         const char *chains)
2826
{
2827 2828
    char rootchain[MAX_CHAINNAME_LENGTH];
    unsigned i;
2829

2830 2831 2832
    virBufferAsprintf(buf, NWFILTER_FUNC_COLLECT_CHAINS,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chains);
    virBufferAsprintf(buf, NWFILTER_FUNC_RM_CHAINS,
2833
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2834
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE);
2835

2836 2837 2838 2839 2840 2841 2842
    virBufferAsprintf(buf, NWFILTER_FUNC_SET_IFS);
    virBufferAddLit(buf, "chains=\"$(collect_chains");
    for (i = 0; chains[i] != 0; i++) {
        PRINT_ROOT_CHAIN(rootchain, chains[i], ifname);
        virBufferAsprintf(buf, " %s", rootchain);
    }
    virBufferAddLit(buf, ")\"\n");
2843

2844 2845 2846 2847 2848 2849 2850 2851
    for (i = 0; chains[i] != 0; i++) {
        PRINT_ROOT_CHAIN(rootchain, chains[i], ifname);
        virBufferAsprintf(buf,
                          "%s -t %s -F %s\n",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                          rootchain);
    }
    virBufferAddLit(buf, "rm_chains $chains\n");
2852 2853 2854 2855 2856

    return 0;
}

static int
2857 2858
ebtablesRemoveSubChains(virBufferPtr buf,
                        const char *ifname)
2859
{
2860 2861 2862 2863 2864
    char chains[3] = {
        CHAINPREFIX_HOST_IN,
        CHAINPREFIX_HOST_OUT,
        0
    };
2865

2866
    return _ebtablesRemoveSubChains(buf, ifname, chains);
2867 2868 2869
}

static int
2870
ebtablesRemoveTmpSubChains(virBufferPtr buf,
2871 2872
                           const char *ifname)
{
2873 2874 2875 2876 2877
    char chains[3] = {
        CHAINPREFIX_HOST_IN_TEMP,
        CHAINPREFIX_HOST_OUT_TEMP,
        0
    };
2878

2879
    return _ebtablesRemoveSubChains(buf, ifname, chains);
2880 2881 2882
}

static int
2883
ebtablesRenameTmpSubChain(virBufferPtr buf,
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
                          int incoming,
                          const char *ifname,
                          const char *protocol)
{
    char tmpchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char tmpChainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                     : CHAINPREFIX_HOST_OUT_TEMP;
    char chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN
                                  : CHAINPREFIX_HOST_OUT;

    if (protocol) {
        PRINT_CHAIN(tmpchain, tmpChainPrefix, ifname, protocol);
        PRINT_CHAIN(   chain,    chainPrefix, ifname, protocol);
    } else {
        PRINT_ROOT_CHAIN(tmpchain, tmpChainPrefix, ifname);
        PRINT_ROOT_CHAIN(   chain,    chainPrefix, ifname);
    }

2902
    virBufferAsprintf(buf,
2903 2904
                      "%s -t %s -E %s %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, tmpchain, chain);
2905 2906 2907 2908
    return 0;
}

static int
2909 2910
ebtablesRenameTmpRootChain(virBufferPtr buf,
                           int incoming,
2911 2912
                           const char *ifname)
{
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
    return ebtablesRenameTmpSubChain(buf, incoming, ifname, NULL);
}

static int
ebtablesRenameTmpSubAndRootChains(virBufferPtr buf,
                                  const char *ifname)
{
    char rootchain[MAX_CHAINNAME_LENGTH];
    unsigned i;
    char chains[3] = {
        CHAINPREFIX_HOST_IN_TEMP,
        CHAINPREFIX_HOST_OUT_TEMP,
        0};
2926

2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
    virBufferAsprintf(buf, NWFILTER_FUNC_COLLECT_CHAINS,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chains);
    virBufferAsprintf(buf, NWFILTER_FUNC_RENAME_CHAINS,
                      CHAINPREFIX_HOST_IN_TEMP,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                      CHAINPREFIX_HOST_IN,
                      CHAINPREFIX_HOST_OUT_TEMP,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                      CHAINPREFIX_HOST_OUT);

    virBufferAsprintf(buf, NWFILTER_FUNC_SET_IFS);
    virBufferAddLit(buf, "chains=\"$(collect_chains");
    for (i = 0; chains[i] != 0; i++) {
        PRINT_ROOT_CHAIN(rootchain, chains[i], ifname);
        virBufferAsprintf(buf, " %s", rootchain);
2942
    }
2943
    virBufferAddLit(buf, ")\"\n");
2944

2945
    virBufferAddLit(buf, "rename_chains $chains\n");
2946

2947 2948
    ebtablesRenameTmpRootChain(buf, 1, ifname);
    ebtablesRenameTmpRootChain(buf, 0, ifname);
2949

2950
    return 0;
2951 2952 2953
}

static void
2954
ebiptablesInstCommand(virBufferPtr buf,
2955 2956 2957 2958 2959 2960
                      const char *templ, char cmd, int pos,
                      int stopOnError)
{
    char position[10] = { 0 };
    if (pos >= 0)
        snprintf(position, sizeof(position), "%d", pos);
2961 2962
    virBufferAsprintf(buf, templ, cmd, position);
    virBufferAsprintf(buf, CMD_SEPARATOR "%s",
2963 2964 2965 2966
                      CMD_STOPONERR(stopOnError));
}


2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
/**
 * ebiptablesCanApplyBasicRules
 *
 * Determine whether this driver can apply the basic rules, meaning
 * run ebtablesApplyBasicRules and ebtablesApplyDHCPOnlyRules.
 * In case of this driver we need the ebtables tool available.
 */
static int
ebiptablesCanApplyBasicRules(void) {
    return (ebtables_cmd_path != NULL);
}

2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
/**
 * ebtablesApplyBasicRules
 *
 * @conn: virConnect object
 * @ifname: name of the backend-interface to which to apply the rules
 * @macaddr: MAC address the VM is using in packets sent through the
 *    interface
 *
 * Returns 0 on success, 1 on failure with the rules removed
 *
 * Apply basic filtering rules on the given interface
 * - filtering for MAC address spoofing
 * - allowing IPv4 & ARP traffic
 */
2993
static int
2994 2995 2996 2997 2998 2999 3000 3001 3002
ebtablesApplyBasicRules(const char *ifname,
                        const unsigned char *macaddr)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = CHAINPREFIX_HOST_IN_TEMP;
    char macaddr_str[VIR_MAC_STRING_BUFLEN];

3003 3004 3005 3006 3007 3008 3009
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

3010 3011
    virFormatMacAddr(macaddr, macaddr_str);

3012
    ebiptablesAllTeardown(ifname);
3013 3014 3015 3016

    ebtablesCreateTmpRootChain(&buf, 1, ifname, 1);

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);
3017
    virBufferAsprintf(&buf,
3018
                      CMD_DEF("%s -t %s -A %s -s ! %s -j DROP") CMD_SEPARATOR
3019 3020 3021
                      CMD_EXEC
                      "%s",

3022 3023
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                      chain, macaddr_str,
3024 3025
                      CMD_STOPONERR(1));

3026
    virBufferAsprintf(&buf,
3027
                      CMD_DEF("%s -t %s -A %s -p IPv4 -j ACCEPT") CMD_SEPARATOR
3028 3029 3030
                      CMD_EXEC
                      "%s",

3031
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
3032 3033
                      CMD_STOPONERR(1));

3034
    virBufferAsprintf(&buf,
3035
                      CMD_DEF("%s -t %s -A %s -p ARP -j ACCEPT") CMD_SEPARATOR
3036 3037 3038
                      CMD_EXEC
                      "%s",

3039
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
3040 3041
                      CMD_STOPONERR(1));

3042
    virBufferAsprintf(&buf,
3043
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
3044 3045 3046
                      CMD_EXEC
                      "%s",

3047
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
3048 3049 3050
                      CMD_STOPONERR(1));

    ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
3051
    ebtablesRenameTmpRootChain(&buf, 1, ifname);
3052 3053 3054 3055 3056 3057 3058

    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
        goto tear_down_tmpebchains;

    return 0;

tear_down_tmpebchains:
3059
    ebtablesCleanAll(ifname);
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082

    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
                           "%s",
                           _("Some rules could not be created."));

    return 1;
}


/**
 * ebtablesApplyDHCPOnlyRules
 *
 * @ifname: name of the backend-interface to which to apply the rules
 * @macaddr: MAC address the VM is using in packets sent through the
 *    interface
 * @dhcpserver: The DHCP server from which the VM may receive traffic
 *    from; may be NULL
 *
 * Returns 0 on success, 1 on failure with the rules removed
 *
 * Apply filtering rules so that the VM can only send and receive
 * DHCP traffic and nothing else.
 */
3083
static int
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
ebtablesApplyDHCPOnlyRules(const char *ifname,
                           const unsigned char *macaddr,
                           const char *dhcpserver)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;
    char chain_in [MAX_CHAINNAME_LENGTH],
         chain_out[MAX_CHAINNAME_LENGTH];
    char macaddr_str[VIR_MAC_STRING_BUFLEN];
    char *srcIPParam = NULL;

3095 3096 3097 3098 3099 3100 3101
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

3102
    if (dhcpserver) {
3103
        virBufferAsprintf(&buf, " --ip-src %s", dhcpserver);
3104 3105 3106 3107 3108 3109 3110
        if (virBufferError(&buf))
            return 1;
        srcIPParam = virBufferContentAndReset(&buf);
    }

    virFormatMacAddr(macaddr, macaddr_str);

3111
    ebiptablesAllTeardown(ifname);
3112 3113 3114 3115 3116 3117 3118

    ebtablesCreateTmpRootChain(&buf, 1, ifname, 1);
    ebtablesCreateTmpRootChain(&buf, 0, ifname, 1);

    PRINT_ROOT_CHAIN(chain_in , CHAINPREFIX_HOST_IN_TEMP , ifname);
    PRINT_ROOT_CHAIN(chain_out, CHAINPREFIX_HOST_OUT_TEMP, ifname);

3119
    virBufferAsprintf(&buf,
3120
                      CMD_DEF("%s -t %s -A %s"
3121 3122 3123 3124 3125 3126 3127 3128
                              " -s %s -d Broadcast "
                              " -p ipv4 --ip-protocol udp"
                              " --ip-src 0.0.0.0 --ip-dst 255.255.255.255"
                              " --ip-sport 68 --ip-dport 67"
                              " -j ACCEPT") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

3129
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_in,
3130 3131 3132
                      macaddr_str,
                      CMD_STOPONERR(1));

3133
    virBufferAsprintf(&buf,
3134
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
3135 3136 3137
                      CMD_EXEC
                      "%s",

3138
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_in,
3139 3140
                      CMD_STOPONERR(1));

3141
    virBufferAsprintf(&buf,
3142
                      CMD_DEF("%s -t %s -A %s"
3143 3144 3145 3146 3147 3148 3149 3150
                              " -d %s"
                              " -p ipv4 --ip-protocol udp"
                              " %s"
                              " --ip-sport 67 --ip-dport 68"
                              " -j ACCEPT") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

3151
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_out,
3152 3153 3154 3155
                      macaddr_str,
                      srcIPParam != NULL ? srcIPParam : "",
                      CMD_STOPONERR(1));

3156
    virBufferAsprintf(&buf,
3157
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
3158 3159 3160
                      CMD_EXEC
                      "%s",

3161
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_out,
3162 3163 3164 3165
                      CMD_STOPONERR(1));

    ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
    ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
3166 3167
    ebtablesRenameTmpRootChain(&buf, 1, ifname);
    ebtablesRenameTmpRootChain(&buf, 0, ifname);
3168 3169 3170 3171 3172 3173 3174 3175 3176

    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
        goto tear_down_tmpebchains;

    VIR_FREE(srcIPParam);

    return 0;

tear_down_tmpebchains:
3177
    ebtablesCleanAll(ifname);
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188

    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
                           "%s",
                           _("Some rules could not be created."));

    VIR_FREE(srcIPParam);

    return 1;
}


3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
/**
 * ebtablesApplyDropAllRules
 *
 * @ifname: name of the backend-interface to which to apply the rules
 *
 * Returns 0 on success, 1 on failure with the rules removed
 *
 * Apply filtering rules so that the VM cannot receive or send traffic.
 */
static int
ebtablesApplyDropAllRules(const char *ifname)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;
    char chain_in [MAX_CHAINNAME_LENGTH],
         chain_out[MAX_CHAINNAME_LENGTH];

    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

3213
    ebiptablesAllTeardown(ifname);
3214 3215 3216 3217 3218 3219 3220

    ebtablesCreateTmpRootChain(&buf, 1, ifname, 1);
    ebtablesCreateTmpRootChain(&buf, 0, ifname, 1);

    PRINT_ROOT_CHAIN(chain_in , CHAINPREFIX_HOST_IN_TEMP , ifname);
    PRINT_ROOT_CHAIN(chain_out, CHAINPREFIX_HOST_OUT_TEMP, ifname);

3221
    virBufferAsprintf(&buf,
3222 3223 3224 3225 3226 3227 3228
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_in,
                      CMD_STOPONERR(1));

3229
    virBufferAsprintf(&buf,
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_out,
                      CMD_STOPONERR(1));

    ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
    ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
    ebtablesRenameTmpRootChain(&buf, 1, ifname);
    ebtablesRenameTmpRootChain(&buf, 0, ifname);

    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
        goto tear_down_tmpebchains;

    return 0;

tear_down_tmpebchains:
    ebtablesCleanAll(ifname);

    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
                           "%s",
                           _("Some rules could not be created."));

    return 1;
}


3258
static int
3259
ebtablesRemoveBasicRules(const char *ifname)
3260 3261 3262 3263 3264 3265
{
    return ebtablesCleanAll(ifname);
}


static int ebtablesCleanAll(const char *ifname)
3266 3267 3268 3269
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;

3270 3271 3272
    if (!ebtables_cmd_path)
        return 0;

3273 3274 3275 3276 3277 3278
    ebtablesUnlinkRootChain(&buf, 1, ifname);
    ebtablesUnlinkRootChain(&buf, 0, ifname);
    ebtablesRemoveSubChains(&buf, ifname);
    ebtablesRemoveRootChain(&buf, 1, ifname);
    ebtablesRemoveRootChain(&buf, 0, ifname);

3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);

    ebiptablesExecCLI(&buf, &cli_status);
    return 0;
}


3290 3291
static int
ebiptablesRuleOrderSort(const void *a, const void *b)
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
{
    const ebiptablesRuleInstPtr insta = (const ebiptablesRuleInstPtr)a;
    const ebiptablesRuleInstPtr instb = (const ebiptablesRuleInstPtr)b;
    const char *root = virNWFilterChainSuffixTypeToString(
                                     VIR_NWFILTER_CHAINSUFFIX_ROOT);
    bool root_a = STREQ(insta->neededProtocolChain, root);
    bool root_b = STREQ(instb->neededProtocolChain, root);

    /* ensure root chain commands appear before all others since
       we will need them to create the child chains */
    if (root_a) {
        if (root_b) {
            goto normal;
        }
        return -1; /* a before b */
    }
    if (root_b) {
        return 1; /* b before a */
    }
normal:
    /* priorities are limited to range [-1000, 1000] */
    return (insta->priority - instb->priority);
}

static int
ebiptablesRuleOrderSortPtr(const void *a, const void *b)
3318 3319 3320
{
    const ebiptablesRuleInstPtr *insta = a;
    const ebiptablesRuleInstPtr *instb = b;
3321
    return ebiptablesRuleOrderSort(*insta, *instb);
3322 3323
}

3324 3325 3326 3327 3328 3329 3330 3331
static int
ebiptablesFilterOrderSort(const virHashKeyValuePairPtr a,
                          const virHashKeyValuePairPtr b)
{
    /* elements' values has been limited to range [-1000, 1000] */
    return *(virNWFilterChainPriority *)a->value -
           *(virNWFilterChainPriority *)b->value;
}
3332

3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
static void
iptablesCheckBridgeNFCallEnabled(bool isIPv6)
{
    static time_t lastReport, lastReportIPv6;
    const char *pathname = NULL;
    char buffer[1];
    time_t now = time(NULL);

    if (isIPv6 &&
        (now - lastReportIPv6) > BRIDGE_NF_CALL_ALERT_INTERVAL ) {
        pathname = PROC_BRIDGE_NF_CALL_IP6TABLES;
    } else if (now - lastReport > BRIDGE_NF_CALL_ALERT_INTERVAL) {
        pathname = PROC_BRIDGE_NF_CALL_IPTABLES;
    }

    if (pathname) {
        int fd = open(pathname, O_RDONLY);
        if (fd >= 0) {
            if (read(fd, buffer, 1) == 1) {
                if (buffer[0] == '0') {
                    char msg[256];
                    snprintf(msg, sizeof(msg),
                             _("To enable ip%stables filtering for the VM do "
                              "'echo 1 > %s'"),
                             isIPv6 ? "6" : "",
                             pathname);
3359
                    VIR_WARN("%s", msg);
3360 3361 3362 3363 3364 3365
                    if (isIPv6)
                        lastReportIPv6 = now;
                    else
                        lastReport = now;
                }
            }
3366
            VIR_FORCE_CLOSE(fd);
3367 3368 3369 3370
        }
    }
}

3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
/*
 * Given a filtername determine the protocol it is used for evaluating
 * We do prefix-matching to determine the protocol.
 */
static enum l3_proto_idx
ebtablesGetProtoIdxByFiltername(const char *filtername)
{
    enum l3_proto_idx idx;

    for (idx = 0; idx < L3_PROTO_LAST_IDX; idx++) {
        if (STRPREFIX(filtername, l3_protocols[idx].val)) {
            return idx;
        }
    }

    return -1;
}

static int
ebtablesCreateTmpRootAndSubChains(virBufferPtr buf,
                                  const char *ifname,
3392 3393 3394
                                  virHashTablePtr chains, int direction,
                                  ebiptablesRuleInstPtr *inst,
                                  int *nRuleInstances)
3395 3396 3397
{
    int rc = 0, i;
    virHashKeyValuePairPtr filter_names;
3398
    const virNWFilterChainPriority *priority;
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412

    if (ebtablesCreateTmpRootChain(buf, direction, ifname, 1) < 0)
        return -1;

    filter_names = virHashGetItems(chains,
                                   ebiptablesFilterOrderSort);
    if (filter_names == NULL)
        return -1;

    for (i = 0; filter_names[i].key; i++) {
        enum l3_proto_idx idx = ebtablesGetProtoIdxByFiltername(
                                  filter_names[i].key);
        if ((int)idx < 0)
            continue;
3413 3414 3415 3416 3417
        priority = (const virNWFilterChainPriority *)filter_names[i].value;
        rc = ebtablesCreateTmpSubChain(inst, nRuleInstances,
                                       direction, ifname, idx,
                                       filter_names[i].key, 1,
                                       *priority);
3418 3419 3420 3421 3422 3423 3424
        if (rc < 0)
            break;
    }

    VIR_FREE(filter_names);
    return rc;
}
3425

3426
static int
3427
ebiptablesApplyNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3428 3429 3430 3431
                        const char *ifname,
                        int nruleInstances,
                        void **_inst)
{
3432
    int i, j;
3433 3434 3435
    int cli_status;
    ebiptablesRuleInstPtr *inst = (ebiptablesRuleInstPtr *)_inst;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
3436 3437
    virHashTablePtr chains_in_set  = virHashCreate(10, NULL);
    virHashTablePtr chains_out_set = virHashCreate(10, NULL);
3438 3439
    bool haveIptables = false;
    bool haveIp6tables = false;
3440 3441
    ebiptablesRuleInstPtr ebtChains = NULL;
    int nEbtChains = 0;
3442

3443 3444 3445 3446 3447
    if (!chains_in_set || !chains_out_set) {
        virReportOOMError();
        goto exit_free_sets;
    }

3448
    if (nruleInstances > 1 && inst)
3449 3450
        qsort(inst, nruleInstances, sizeof(inst[0]),
              ebiptablesRuleOrderSortPtr);
3451

3452
    /* scan the rules to see which chains need to be created */
3453
    for (i = 0; i < nruleInstances; i++) {
3454
        sa_assert (inst);
S
Stefan Berger 已提交
3455
        if (inst[i]->ruleType == RT_EBTABLES) {
3456
            const char *name = inst[i]->neededProtocolChain;
3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
            if (inst[i]->chainprefix == CHAINPREFIX_HOST_IN_TEMP) {
                if (virHashUpdateEntry(chains_in_set, name,
                                       &inst[i]->chainPriority)) {
                    virReportOOMError();
                    goto exit_free_sets;
                }
            } else {
                if (virHashUpdateEntry(chains_out_set, name,
                                       &inst[i]->chainPriority)) {
                    virReportOOMError();
                    goto exit_free_sets;
                }
            }
S
Stefan Berger 已提交
3470
        }
3471 3472
    }

3473
    /* cleanup whatever may exist */
3474 3475 3476 3477 3478 3479 3480 3481
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
3482

3483
    /* create needed chains */
3484 3485 3486 3487
    if (ebtablesCreateTmpRootAndSubChains(&buf, ifname, chains_in_set , 1,
                                          &ebtChains, &nEbtChains) ||
        ebtablesCreateTmpRootAndSubChains(&buf, ifname, chains_out_set, 0,
                                          &ebtChains, &nEbtChains)) {
3488 3489
        goto tear_down_tmpebchains;
    }
3490

3491 3492 3493 3494
    if (nEbtChains > 0)
        qsort(&ebtChains[0], nEbtChains, sizeof(ebtChains[0]),
              ebiptablesRuleOrderSort);

3495
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3496 3497
        goto tear_down_tmpebchains;

3498 3499 3500
    /* process ebtables commands; interleave commands from filters with
       commands for creating and connecting ebtables chains */
    j = 0;
3501
    for (i = 0; i < nruleInstances; i++) {
3502
        sa_assert (inst);
S
Stefan Berger 已提交
3503 3504
        switch (inst[i]->ruleType) {
        case RT_EBTABLES:
3505 3506 3507 3508 3509 3510
            while (j < nEbtChains &&
                   ebtChains[j].priority <= inst[i]->priority) {
                ebiptablesInstCommand(&buf,
                                      ebtChains[j++].commandTemplate,
                                      'A', -1, 1);
            }
3511
            ebiptablesInstCommand(&buf,
S
Stefan Berger 已提交
3512 3513 3514 3515
                                  inst[i]->commandTemplate,
                                  'A', -1, 1);
        break;
        case RT_IPTABLES:
3516
            haveIptables = true;
S
Stefan Berger 已提交
3517
        break;
3518
        case RT_IP6TABLES:
3519
            haveIp6tables = true;
3520
        break;
S
Stefan Berger 已提交
3521
        }
3522
    }
3523

3524 3525 3526 3527 3528
    while (j < nEbtChains)
        ebiptablesInstCommand(&buf,
                              ebtChains[j++].commandTemplate,
                              'A', -1, 1);

3529
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3530 3531
        goto tear_down_tmpebchains;

S
Stefan Berger 已提交
3532
    if (haveIptables) {
3533 3534
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3535

3536
        iptablesCreateBaseChains(iptables_cmd_path, &buf);
S
Stefan Berger 已提交
3537

3538
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3539 3540
            goto tear_down_tmpebchains;

3541
        iptablesCreateTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3542

3543
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3544 3545
           goto tear_down_tmpiptchains;

3546 3547
        iptablesLinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesSetupVirtInPost(iptables_cmd_path, &buf, ifname);
3548
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3549 3550 3551
           goto tear_down_tmpiptchains;

        for (i = 0; i < nruleInstances; i++) {
3552
            sa_assert (inst);
S
Stefan Berger 已提交
3553
            if (inst[i]->ruleType == RT_IPTABLES)
3554
                iptablesInstCommand(&buf,
S
Stefan Berger 已提交
3555 3556 3557 3558
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3559
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3560
           goto tear_down_tmpiptchains;
3561 3562

        iptablesCheckBridgeNFCallEnabled(false);
S
Stefan Berger 已提交
3563 3564
    }

3565
    if (haveIp6tables) {
3566 3567
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3568

3569
        iptablesCreateBaseChains(ip6tables_cmd_path, &buf);
3570

3571
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3572 3573
            goto tear_down_tmpiptchains;

3574
        iptablesCreateTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3575

3576
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3577 3578
           goto tear_down_tmpip6tchains;

3579 3580
        iptablesLinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesSetupVirtInPost(ip6tables_cmd_path, &buf, ifname);
3581
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3582 3583 3584 3585
           goto tear_down_tmpip6tchains;

        for (i = 0; i < nruleInstances; i++) {
            if (inst[i]->ruleType == RT_IP6TABLES)
3586
                iptablesInstCommand(&buf,
3587 3588 3589 3590
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3591
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3592
           goto tear_down_tmpip6tchains;
3593 3594

        iptablesCheckBridgeNFCallEnabled(true);
3595 3596
    }

3597
    if (virHashSize(chains_in_set) != 0)
3598
        ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
3599
    if (virHashSize(chains_out_set) != 0)
3600
        ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
3601

3602
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3603 3604
        goto tear_down_ebsubchains_and_unlink;

3605 3606 3607
    virHashFree(chains_in_set);
    virHashFree(chains_out_set);

3608 3609 3610 3611
    for (i = 0; i < nEbtChains; i++)
        VIR_FREE(ebtChains[i].commandTemplate);
    VIR_FREE(ebtChains);

3612 3613 3614
    return 0;

tear_down_ebsubchains_and_unlink:
3615 3616 3617 3618
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    }
3619

3620 3621
tear_down_tmpip6tchains:
    if (haveIp6tables) {
3622 3623
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3624 3625
    }

S
Stefan Berger 已提交
3626 3627
tear_down_tmpiptchains:
    if (haveIptables) {
3628 3629
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3630 3631
    }

3632
tear_down_tmpebchains:
3633 3634 3635 3636 3637
    if (ebtables_cmd_path) {
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3638

3639
    ebiptablesExecCLI(&buf, &cli_status);
3640

3641
    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3642 3643 3644
                           _("Some rules could not be created for "
                             "interface %s."),
                           ifname);
3645

3646 3647 3648 3649
exit_free_sets:
    virHashFree(chains_in_set);
    virHashFree(chains_out_set);

3650 3651 3652 3653
    for (i = 0; i < nEbtChains; i++)
        VIR_FREE(ebtChains[i].commandTemplate);
    VIR_FREE(ebtChains);

3654 3655 3656 3657 3658
    return 1;
}


static int
3659
ebiptablesTearNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3660 3661 3662 3663 3664
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

3665 3666 3667 3668
    if (iptables_cmd_path) {
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
    }
3669

3670 3671 3672 3673
    if (ip6tables_cmd_path) {
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
    }
S
Stefan Berger 已提交
3674

3675 3676 3677
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
3678

3679 3680 3681 3682
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3683

3684
    ebiptablesExecCLI(&buf, &cli_status);
3685 3686 3687 3688 3689 3690

    return 0;
}


static int
3691
ebiptablesTearOldRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3692 3693 3694 3695 3696
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

3697
    /* switch to new iptables user defined chains */
3698 3699 3700
    if (iptables_cmd_path) {
        iptablesUnlinkRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3701

3702 3703 3704
        iptablesRenameTmpRootChains(iptables_cmd_path, &buf, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
3705

3706 3707 3708
    if (ip6tables_cmd_path) {
        iptablesUnlinkRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(ip6tables_cmd_path, &buf, ifname);
3709

3710 3711 3712
        iptablesRenameTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
S
Stefan Berger 已提交
3713

3714 3715 3716
    if (ebtables_cmd_path) {
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3717

3718
        ebtablesRemoveSubChains(&buf, ifname);
3719

3720 3721
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
3722

3723
        ebtablesRenameTmpSubAndRootChains(&buf, ifname);
3724

3725 3726
        ebiptablesExecCLI(&buf, &cli_status);
    }
3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744

    return 0;
}


/**
 * ebiptablesRemoveRules:
 * @conn : pointer to virConnect object
 * @ifname : the name of the interface to which the rules apply
 * @nRuleInstance : the number of given rules
 * @_inst : array of rule instantiation data
 *
 * Remove all rules one after the other
 *
 * Return 0 on success, 1 if execution of one or more cleanup
 * commands failed.
 */
static int
3745
ebiptablesRemoveRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756
                      const char *ifname ATTRIBUTE_UNUSED,
                      int nruleInstances,
                      void **_inst)
{
    int rc = 0;
    int cli_status;
    int i;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    ebiptablesRuleInstPtr *inst = (ebiptablesRuleInstPtr *)_inst;

    for (i = 0; i < nruleInstances; i++)
3757
        ebiptablesInstCommand(&buf,
3758 3759 3760 3761
                              inst[i]->commandTemplate,
                              'D', -1,
                              0);

3762
    if (ebiptablesExecCLI(&buf, &cli_status))
3763 3764 3765
        goto err_exit;

    if (cli_status) {
3766
        virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791
                               "%s",
                               _("error while executing CLI commands"));
        rc = 1;
    }

err_exit:
    return rc;
}


/**
 * ebiptablesAllTeardown:
 * @ifname : the name of the interface to which the rules apply
 *
 * Unconditionally remove all possible user defined tables and rules
 * that were created for the given interface (ifname).
 *
 * Always returns 0.
 */
static int
ebiptablesAllTeardown(const char *ifname)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;

3792 3793 3794 3795 3796
    if (iptables_cmd_path) {
        iptablesUnlinkRootChains(iptables_cmd_path, &buf, ifname);
        iptablesClearVirtInPost (iptables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(iptables_cmd_path, &buf, ifname);
    }
3797

3798 3799 3800 3801 3802
    if (ip6tables_cmd_path) {
        iptablesUnlinkRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesClearVirtInPost (ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(ip6tables_cmd_path, &buf, ifname);
    }
S
Stefan Berger 已提交
3803

3804 3805 3806
    if (ebtables_cmd_path) {
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3807

3808 3809
        ebtablesRemoveSubChains(&buf, ifname);

3810 3811 3812
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
    }
3813
    ebiptablesExecCLI(&buf, &cli_status);
3814 3815 3816 3817 3818 3819 3820

    return 0;
}


virNWFilterTechDriver ebiptables_driver = {
    .name = EBIPTABLES_DRIVER_ID,
3821 3822 3823 3824
    .flags = 0,

    .init     = ebiptablesDriverInit,
    .shutdown = ebiptablesDriverShutdown,
3825

3826
    .createRuleInstance  = ebiptablesCreateRuleInstanceIterate,
3827 3828 3829 3830 3831 3832 3833
    .applyNewRules       = ebiptablesApplyNewRules,
    .tearNewRules        = ebiptablesTearNewRules,
    .tearOldRules        = ebiptablesTearOldRules,
    .allTeardown         = ebiptablesAllTeardown,
    .removeRules         = ebiptablesRemoveRules,
    .freeRuleInstance    = ebiptablesFreeRuleInstance,
    .displayRuleInstance = ebiptablesDisplayRuleInstance,
3834 3835 3836 3837

    .canApplyBasicRules  = ebiptablesCanApplyBasicRules,
    .applyBasicRules     = ebtablesApplyBasicRules,
    .applyDHCPOnlyRules  = ebtablesApplyDHCPOnlyRules,
3838
    .applyDropAllRules   = ebtablesApplyDropAllRules,
3839
    .removeBasicRules    = ebtablesRemoveBasicRules,
3840
};
3841 3842 3843


static int
3844
ebiptablesDriverInit(bool privileged)
3845 3846 3847 3848
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;

3849 3850 3851
    if (!privileged)
        return 0;

3852 3853 3854
    if (virMutexInit(&execCLIMutex))
        return EINVAL;

3855 3856 3857 3858 3859 3860
    gawk_cmd_path = virFindFileInPath("gawk");
    grep_cmd_path = virFindFileInPath("grep");

    ebtables_cmd_path = virFindFileInPath("ebtables");
    if (ebtables_cmd_path) {
        /* basic probing */
3861
        virBufferAsprintf(&buf,
3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
                          CMD_DEF("%s -t %s -L") CMD_SEPARATOR
                          CMD_EXEC
                          "%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                          CMD_STOPONERR(1));

        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status)
             VIR_FREE(ebtables_cmd_path);
    }

    iptables_cmd_path = virFindFileInPath("iptables");
    if (iptables_cmd_path) {
3874
        virBufferAsprintf(&buf,
G
Guido Günther 已提交
3875
                          CMD_DEF("%s -n -L FORWARD") CMD_SEPARATOR
3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
                          CMD_EXEC
                          "%s",
                          iptables_cmd_path,
                          CMD_STOPONERR(1));

        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status)
             VIR_FREE(iptables_cmd_path);
    }

    ip6tables_cmd_path = virFindFileInPath("ip6tables");
    if (ip6tables_cmd_path) {
3887
        virBufferAsprintf(&buf,
G
Guido Günther 已提交
3888
                          CMD_DEF("%s -n -L FORWARD") CMD_SEPARATOR
3889 3890 3891 3892 3893 3894 3895 3896 3897
                          CMD_EXEC
                          "%s",
                          ip6tables_cmd_path,
                          CMD_STOPONERR(1));

        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status)
             VIR_FREE(ip6tables_cmd_path);
    }

3898
    /* ip(6)tables support needs gawk & grep, ebtables doesn't */
3899
    if ((iptables_cmd_path != NULL || ip6tables_cmd_path != NULL) &&
3900
        (!grep_cmd_path || !gawk_cmd_path)) {
3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("essential tools to support ip(6)tables "
                                 "firewalls could not be located"));
        VIR_FREE(iptables_cmd_path);
        VIR_FREE(ip6tables_cmd_path);
    }


    if (!ebtables_cmd_path && !iptables_cmd_path && !ip6tables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("firewall tools were not found or "
                                 "cannot be used"));
        ebiptablesDriverShutdown();
        return ENOTSUP;
    }

    ebiptables_driver.flags = TECHDRV_FLAG_INITIALIZED;

    return 0;
}


static void
3924
ebiptablesDriverShutdown(void)
3925 3926 3927 3928 3929 3930 3931 3932
{
    VIR_FREE(gawk_cmd_path);
    VIR_FREE(grep_cmd_path);
    VIR_FREE(ebtables_cmd_path);
    VIR_FREE(iptables_cmd_path);
    VIR_FREE(ip6tables_cmd_path);
    ebiptables_driver.flags = 0;
}