nwfilter_ebiptables_driver.c 128.4 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"
S
Stefan Berger 已提交
44
#include "intprops.h"
45 46 47 48 49 50 51 52 53 54 55 56 57


#define VIR_FROM_THIS VIR_FROM_NWFILTER


#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} 2>&1\"\\)" CMD_SEPARATOR
68 69
#define CMD_STOPONERR(X) \
    X ? "if [ $? -ne 0 ]; then" \
70
        "  echo \"Failure to execute command '${cmd}' : '${res}'.\";" \
71 72 73 74 75
        "  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
#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)

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
/* 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"
112
    "    for tmp in $($EBT -t nat -L $tmp2 | \\\n"
113 114 115 116 117 118 119 120 121 122 123
    "      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"
124 125
    "  for tmp in $*; do $EBT -t nat -F $tmp; done\n"
    "  for tmp in $*; do $EBT -t nat -X $tmp; done\n"
126 127 128 129 130 131 132
    "}\n";

static const char ebiptables_script_func_rename_chains[] =
    "rename_chains()\n"
    "{\n"
    "  for tmp in $*; do\n"
    "    case $tmp in\n"
133 134
    "      %c*) $EBT -t nat -E $tmp %c${tmp#?} ;;\n"
    "      %c*) $EBT -t nat -E $tmp %c${tmp#?} ;;\n"
135 136 137 138 139 140 141 142 143 144 145 146
    "    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
147

148 149
#define NWFILTER_SET_EBTABLES_SHELLVAR(BUFPTR) \
    virBufferAsprintf(BUFPTR, "EBT=%s\n", ebtables_cmd_path);
150 151 152 153
#define NWFILTER_SET_IPTABLES_SHELLVAR(BUFPTR) \
    virBufferAsprintf(BUFPTR, "IPT=%s\n", iptables_cmd_path);
#define NWFILTER_SET_IP6TABLES_SHELLVAR(BUFPTR) \
    virBufferAsprintf(BUFPTR, "IPT=%s\n", ip6tables_cmd_path);
154

S
Stefan Berger 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
#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

176
#define COMMENT_VARNAME "comment"
S
Stefan Berger 已提交
177

178
static int ebtablesRemoveBasicRules(const char *ifname);
179
static int ebiptablesDriverInit(bool privileged);
180
static void ebiptablesDriverShutdown(void);
181
static int ebtablesCleanAll(const char *ifname);
182
static int ebiptablesAllTeardown(const char *ifname);
183

184
static virMutex execCLIMutex;
185

186 187 188 189 190 191 192 193 194 195 196
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,
S
Stefan Berger 已提交
197
    L2_PROTO_MAC_IDX,
S
Stefan Berger 已提交
198
    L2_PROTO_VLAN_IDX,
S
Stefan Berger 已提交
199
    L2_PROTO_STP_IDX,
200 201 202 203 204
    L3_PROTO_LAST_IDX
};

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

205 206 207 208 209
/* 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.
 */
210 211 212 213 214
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"),
S
Stefan Berger 已提交
215
    USHORTMAP_ENTRY_IDX(L2_PROTO_VLAN_IDX, ETHERTYPE_VLAN  , "vlan"),
S
Stefan Berger 已提交
216
    USHORTMAP_ENTRY_IDX(L2_PROTO_STP_IDX,  0               , "stp"),
S
Stefan Berger 已提交
217
    USHORTMAP_ENTRY_IDX(L2_PROTO_MAC_IDX,  0               , "mac"),
218
    USHORTMAP_ENTRY_IDX(L3_PROTO_LAST_IDX, 0               , NULL),
219 220 221 222
};


static int
223
printVar(virNWFilterVarCombIterPtr vars,
224 225 226 227 228 229 230
         char *buf, int bufsize,
         nwItemDescPtr item,
         int *done)
{
    *done = 0;

    if ((item->flags & NWFILTER_ENTRY_ITEM_FLAG_HAS_VAR)) {
231 232
        const char *val;

233
        val = virNWFilterVarCombIterGetVarValue(vars, item->var);
234
        if (!val) {
235
            /* error has been reported */
236 237 238
            return 1;
        }

239
        if (!virStrcpy(buf, val, bufsize)) {
240
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
241 242 243 244 245 246 247 248 249 250 251 252 253
                                   _("Buffer to small to print MAC address "
                                   "'%s' into"),
                                   item->var);
            return 1;
        }

        *done = 1;
    }
    return 0;
}


static int
254
_printDataType(virNWFilterVarCombIterPtr vars,
255 256 257
               char *buf, int bufsize,
               nwItemDescPtr item,
               bool asHex)
258 259
{
    int done;
260
    char *data;
261

262
    if (printVar(vars, buf, bufsize, item, &done))
263 264 265 266 267 268 269
        return 1;

    if (done)
        return 0;

    switch (item->datatype) {
    case DATATYPE_IPADDR:
270
        data = virSocketAddrFormat(&item->u.ipaddr);
271
        if (!data)
272 273
            return 1;
        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
274
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
275 276
                                   _("buffer too small for IP address"));
            VIR_FREE(data);
277 278
            return 1;
        }
279
        VIR_FREE(data);
280 281
    break;

282
    case DATATYPE_IPV6ADDR:
283
        data = virSocketAddrFormat(&item->u.ipaddr);
284
        if (!data)
285 286 287
            return 1;

        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
288
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
289 290 291
                                   _("buffer too small for IPv6 address"));
            VIR_FREE(data);
            return 1;
292
        }
293
        VIR_FREE(data);
294 295
    break;

296
    case DATATYPE_MACADDR:
297
    case DATATYPE_MACMASK:
298
        if (bufsize < VIR_MAC_STRING_BUFLEN) {
299
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
300 301 302 303 304 305 306
                                   _("Buffer too small for MAC address"));
            return 1;
        }

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

307 308
    case DATATYPE_IPV6MASK:
    case DATATYPE_IPMASK:
309
        if (snprintf(buf, bufsize, "%d",
310
                     item->u.u8) >= bufsize) {
311
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
312 313 314 315 316
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

S
Stefan Berger 已提交
317 318 319 320 321 322 323 324 325 326
    case DATATYPE_UINT32:
    case DATATYPE_UINT32_HEX:
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%u",
                     item->u.u32) >= bufsize) {
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Buffer too small for uint32 type"));
            return 1;
        }
    break;

327
    case DATATYPE_UINT16:
328
    case DATATYPE_UINT16_HEX:
329
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
330
                     item->u.u16) >= bufsize) {
331
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
332 333 334 335 336 337
                                   _("Buffer too small for uint16 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT8:
338
    case DATATYPE_UINT8_HEX:
339
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
340
                     item->u.u8) >= bufsize) {
341
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
342 343 344 345 346 347
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    default:
348
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
349 350 351 352 353 354 355 356 357
                               _("Unhandled datatype %x"), item->datatype);
        return 1;
    break;
    }

    return 0;
}


358
static int
359
printDataType(virNWFilterVarCombIterPtr vars,
360 361 362
              char *buf, int bufsize,
              nwItemDescPtr item)
{
363
    return _printDataType(vars, buf, bufsize, item, 0);
364 365 366 367
}


static int
368
printDataTypeAsHex(virNWFilterVarCombIterPtr vars,
369 370 371
                   char *buf, int bufsize,
                   nwItemDescPtr item)
{
372
    return _printDataType(vars, buf, bufsize, item, 1);
373 374 375
}


376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
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 已提交
396 397 398 399 400 401 402 403 404 405 406 407
static void
ebiptablesRuleInstFree(ebiptablesRuleInstPtr inst)
{
    if (!inst)
        return;

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


static int
408
ebiptablesAddRuleInst(virNWFilterRuleInstPtr res,
S
Stefan Berger 已提交
409
                      char *commandTemplate,
410
                      const char *neededChain,
411
                      virNWFilterChainPriority chainPriority,
S
Stefan Berger 已提交
412
                      char chainprefix,
413
                      virNWFilterRulePriority priority,
S
Stefan Berger 已提交
414 415 416 417 418 419 420 421 422 423 424
                      enum RuleType ruleType)
{
    ebiptablesRuleInstPtr inst;

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

    inst->commandTemplate = commandTemplate;
    inst->neededProtocolChain = neededChain;
425
    inst->chainPriority = chainPriority;
S
Stefan Berger 已提交
426 427 428 429
    inst->chainprefix = chainprefix;
    inst->priority = priority;
    inst->ruleType = ruleType;

430
    return virNWFilterRuleInstAddData(res, inst);
S
Stefan Berger 已提交
431 432 433 434
}


static int
435
ebtablesHandleEthHdr(virBufferPtr buf,
436
                     virNWFilterVarCombIterPtr vars,
437 438
                     ethHdrDataDefPtr ethHdr,
                     bool reverse)
S
Stefan Berger 已提交
439 440 441 442
{
    char macaddr[VIR_MAC_STRING_BUFLEN];

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

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

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

460
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
461 462 463 464 465 466
                              "/%s",
                              macaddr);
        }
    }

    if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACAddr)) {
467
        if (printDataType(vars,
S
Stefan Berger 已提交
468 469 470 471
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataDstMACAddr))
            goto err_exit;

472
        virBufferAsprintf(buf,
473 474
                      " %s %s %s",
                      reverse ? "-s" : "-d",
S
Stefan Berger 已提交
475 476 477 478
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataDstMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACMask)) {
479
            if (printDataType(vars,
S
Stefan Berger 已提交
480 481 482 483
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataDstMACMask))
                goto err_exit;

484
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
                              "/%s",
                              macaddr);
        }
    }

    return 0;

 err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


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

501
static int iptablesLinkIPTablesBaseChain(virBufferPtr buf,
S
Stefan Berger 已提交
502 503 504 505 506
                                         const char *udchain,
                                         const char *syschain,
                                         unsigned int pos,
                                         int stopOnError)
{
507
    virBufferAsprintf(buf,
508
                      "res=$($IPT -L %s -n --line-number | "
509
                          "%s \" %s \")\n"
S
Stefan Berger 已提交
510
                      "if [ $? -ne 0 ]; then\n"
511
                      "  $IPT -I %s %d -j %s\n"
S
Stefan Berger 已提交
512
                      "else\n"
513
                      "  r=$(echo $res | %s '{print $1}')\n"
S
Stefan Berger 已提交
514
                      "  if [ \"${r}\" != \"%d\" ]; then\n"
515
                      "    " CMD_DEF("$IPT -I %s %d -j %s") CMD_SEPARATOR
S
Stefan Berger 已提交
516 517
                      "    " CMD_EXEC
                      "    %s"
518
                      "    r=$(( $r + 1 ))\n"
519
                      "    " CMD_DEF("$IPT -D %s ${r}") CMD_SEPARATOR
S
Stefan Berger 已提交
520 521 522 523 524
                      "    " CMD_EXEC
                      "    %s"
                      "  fi\n"
                      "fi\n",

525
                      syschain,
526
                      grep_cmd_path, udchain,
S
Stefan Berger 已提交
527

528
                      syschain, pos, udchain,
529
                      gawk_cmd_path,
S
Stefan Berger 已提交
530 531 532

                      pos,

533
                      syschain, pos, udchain,
S
Stefan Berger 已提交
534 535
                      CMD_STOPONERR(stopOnError),

536
                      syschain,
S
Stefan Berger 已提交
537 538 539 540 541
                      CMD_STOPONERR(stopOnError));
    return 0;
}


542
static int iptablesCreateBaseChains(virBufferPtr buf)
S
Stefan Berger 已提交
543
{
544 545 546 547 548
    virBufferAddLit(buf, "$IPT -N " VIRT_IN_CHAIN      CMD_SEPARATOR
                         "$IPT -N " VIRT_OUT_CHAIN     CMD_SEPARATOR
                         "$IPT -N " VIRT_IN_POST_CHAIN CMD_SEPARATOR
                         "$IPT -N " HOST_IN_CHAIN      CMD_SEPARATOR);
    iptablesLinkIPTablesBaseChain(buf,
S
Stefan Berger 已提交
549
                                  VIRT_IN_CHAIN     , "FORWARD", 1, 1);
550
    iptablesLinkIPTablesBaseChain(buf,
S
Stefan Berger 已提交
551
                                  VIRT_OUT_CHAIN    , "FORWARD", 2, 1);
552
    iptablesLinkIPTablesBaseChain(buf,
S
Stefan Berger 已提交
553
                                  VIRT_IN_POST_CHAIN, "FORWARD", 3, 1);
554
    iptablesLinkIPTablesBaseChain(buf,
S
Stefan Berger 已提交
555 556 557 558 559 560 561
                                  HOST_IN_CHAIN     , "INPUT"  , 1, 1);

    return 0;
}


static int
562
iptablesCreateTmpRootChain(virBufferPtr buf,
S
Stefan Berger 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575
                           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);

576
    virBufferAsprintf(buf,
577
                      CMD_DEF("$IPT -N %s") CMD_SEPARATOR
S
Stefan Berger 已提交
578 579 580 581 582 583 584 585 586 587
                      CMD_EXEC
                      "%s",
                      chain,
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
588
iptablesCreateTmpRootChains(virBufferPtr buf,
S
Stefan Berger 已提交
589 590
                            const char *ifname)
{
591 592 593
    iptablesCreateTmpRootChain(buf, 'F', 0, ifname, 1);
    iptablesCreateTmpRootChain(buf, 'F', 1, ifname, 1);
    iptablesCreateTmpRootChain(buf, 'H', 1, ifname, 1);
S
Stefan Berger 已提交
594 595 596 597 598
    return 0;
}


static int
599
_iptablesRemoveRootChain(virBufferPtr buf,
S
Stefan Berger 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
                         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);

618
    virBufferAsprintf(buf,
619 620 621 622
                      "$IPT -F %s" CMD_SEPARATOR
                      "$IPT -X %s" CMD_SEPARATOR,
                      chain,
                      chain);
S
Stefan Berger 已提交
623 624 625 626 627 628

    return 0;
}


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


static int
639
iptablesRemoveTmpRootChain(virBufferPtr buf,
S
Stefan Berger 已提交
640 641 642 643
                           char prefix,
                           int incoming,
                           const char *ifname)
{
644
    return _iptablesRemoveRootChain(buf, prefix,
645
                                    incoming, ifname, 1);
S
Stefan Berger 已提交
646 647 648 649
}


static int
650
iptablesRemoveTmpRootChains(virBufferPtr buf,
S
Stefan Berger 已提交
651 652
                            const char *ifname)
{
653 654 655
    iptablesRemoveTmpRootChain(buf, 'F', 0, ifname);
    iptablesRemoveTmpRootChain(buf, 'F', 1, ifname);
    iptablesRemoveTmpRootChain(buf, 'H', 1, ifname);
S
Stefan Berger 已提交
656 657 658 659 660
    return 0;
}


static int
661
iptablesRemoveRootChains(virBufferPtr buf,
S
Stefan Berger 已提交
662 663
                         const char *ifname)
{
664 665 666
    iptablesRemoveRootChain(buf, 'F', 0, ifname);
    iptablesRemoveRootChain(buf, 'F', 1, ifname);
    iptablesRemoveRootChain(buf, 'H', 1, ifname);
S
Stefan Berger 已提交
667 668 669 670 671
    return 0;
}


static int
672
iptablesLinkTmpRootChain(virBufferPtr buf,
S
Stefan Berger 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
                         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);

689
    virBufferAsprintf(buf,
690
                      CMD_DEF("$IPT -A %s "
S
Stefan Berger 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703
                              "%s %s -g %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",
                      basechain,
                      match, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
704
iptablesLinkTmpRootChains(virBufferPtr buf,
S
Stefan Berger 已提交
705 706
                          const char *ifname)
{
707 708 709
    iptablesLinkTmpRootChain(buf, VIRT_OUT_CHAIN, 'F', 0, ifname, 1);
    iptablesLinkTmpRootChain(buf, VIRT_IN_CHAIN , 'F', 1, ifname, 1);
    iptablesLinkTmpRootChain(buf, HOST_IN_CHAIN , 'H', 1, ifname, 1);
S
Stefan Berger 已提交
710 711 712 713 714 715

    return 0;
}


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


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

static int
750
_iptablesUnlinkRootChain(virBufferPtr buf,
751 752 753 754
                         const char *basechain,
                         char prefix,
                         int incoming, const char *ifname,
                         int isTempChain)
S
Stefan Berger 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
{
    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);

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

    return 0;
}


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


static int
793
iptablesUnlinkTmpRootChain(virBufferPtr buf,
S
Stefan Berger 已提交
794 795 796 797
                           const char *basechain,
                           char prefix,
                           int incoming, const char *ifname)
{
798
    return _iptablesUnlinkRootChain(buf,
S
Stefan Berger 已提交
799 800 801 802 803
                                    basechain, prefix, incoming, ifname, 1);
}


static int
804
iptablesUnlinkRootChains(virBufferPtr buf,
S
Stefan Berger 已提交
805 806
                         const char *ifname)
{
807 808 809
    iptablesUnlinkRootChain(buf, VIRT_OUT_CHAIN, 'F', 0, ifname);
    iptablesUnlinkRootChain(buf, VIRT_IN_CHAIN , 'F', 1, ifname);
    iptablesUnlinkRootChain(buf, HOST_IN_CHAIN , 'H', 1, ifname);
S
Stefan Berger 已提交
810 811 812 813 814 815

    return 0;
}


static int
816
iptablesUnlinkTmpRootChains(virBufferPtr buf,
S
Stefan Berger 已提交
817 818
                            const char *ifname)
{
819 820 821
    iptablesUnlinkTmpRootChain(buf, VIRT_OUT_CHAIN, 'F', 0, ifname);
    iptablesUnlinkTmpRootChain(buf, VIRT_IN_CHAIN , 'F', 1, ifname);
    iptablesUnlinkTmpRootChain(buf, HOST_IN_CHAIN , 'H', 1, ifname);
S
Stefan Berger 已提交
822 823 824 825 826
    return 0;
}


static int
827
iptablesRenameTmpRootChain(virBufferPtr buf,
S
Stefan Berger 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
                           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);

847
    virBufferAsprintf(buf,
848
                      "$IPT -E %s %s" CMD_SEPARATOR,
S
Stefan Berger 已提交
849 850 851 852 853 854 855
                      tmpchain,
                      chain);
    return 0;
}


static int
856
iptablesRenameTmpRootChains(virBufferPtr buf,
S
Stefan Berger 已提交
857 858
                            const char *ifname)
{
859 860 861
    iptablesRenameTmpRootChain(buf, 'F', 0, ifname);
    iptablesRenameTmpRootChain(buf, 'F', 1, ifname);
    iptablesRenameTmpRootChain(buf, 'H', 1, ifname);
S
Stefan Berger 已提交
862 863 864 865 866
    return 0;
}


static void
867
iptablesInstCommand(virBufferPtr buf,
S
Stefan Berger 已提交
868 869 870 871 872 873
                    const char *templ, char cmd, int pos,
                    int stopOnError)
{
    char position[10] = { 0 };
    if (pos >= 0)
        snprintf(position, sizeof(position), "%d", pos);
874 875
    virBufferAsprintf(buf, templ, cmd, position);
    virBufferAsprintf(buf, CMD_SEPARATOR "%s",
S
Stefan Berger 已提交
876 877 878 879 880
                      CMD_STOPONERR(stopOnError));
}


static int
881
iptablesHandleSrcMacAddr(virBufferPtr buf,
882
                         virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
883
                         nwItemDescPtr srcMacAddr,
884 885
                         int directionIn,
                         bool *srcmacskipped)
S
Stefan Berger 已提交
886 887
{
    char macaddr[VIR_MAC_STRING_BUFLEN];
888
    *srcmacskipped = false;
S
Stefan Berger 已提交
889 890

    if (HAS_ENTRY_ITEM(srcMacAddr)) {
891 892 893 894 895
        if (directionIn) {
            *srcmacskipped = true;
            return 0;
        }

896
        if (printDataType(vars,
S
Stefan Berger 已提交
897 898 899 900
                          macaddr, sizeof(macaddr),
                          srcMacAddr))
            goto err_exit;

901
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
                          " -m mac %s --mac-source %s",
                          ENTRY_GET_NEG_SIGN(srcMacAddr),
                          macaddr);
    }

    return 0;

err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


static int
917
iptablesHandleIpHdr(virBufferPtr buf,
918
                    virBufferPtr afterStateMatch,
919
                    virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
920
                    ipHdrDataDefPtr ipHdr,
921
                    int directionIn,
922 923
                    bool *skipRule, bool *skipMatch,
                    virBufferPtr prefix)
S
Stefan Berger 已提交
924
{
925
    char ipaddr[INET6_ADDRSTRLEN],
S
Stefan Berger 已提交
926 927
         number[MAX(INT_BUFSIZE_BOUND(uint32_t),
                    INT_BUFSIZE_BOUND(int))];
S
Stefan Berger 已提交
928 929 930 931 932 933 934 935 936 937 938 939 940
    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)) {

941
        if (printDataType(vars,
S
Stefan Berger 已提交
942 943 944 945
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataSrcIPAddr))
            goto err_exit;

946
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
947 948 949 950 951 952 953
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataSrcIPAddr),
                          src,
                          ipaddr);

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

954
            if (printDataType(vars,
S
Stefan Berger 已提交
955 956 957 958
                              number, sizeof(number),
                              &ipHdr->dataSrcIPMask))
                goto err_exit;

959
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
960 961 962 963 964
                              "/%s",
                              number);
        }
    } else if (HAS_ENTRY_ITEM(&ipHdr->dataSrcIPFrom)) {

965
        if (printDataType(vars,
S
Stefan Berger 已提交
966 967 968 969
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataSrcIPFrom))
            goto err_exit;

970
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
971 972 973 974 975 976 977
                          " -m iprange %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataSrcIPFrom),
                          srcrange,
                          ipaddr);

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

978
            if (printDataType(vars,
S
Stefan Berger 已提交
979 980 981 982
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataSrcIPTo))
                goto err_exit;

983
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
984 985 986 987 988 989 990
                              "-%s",
                              ipaddr);
        }
    }

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

991
        if (printDataType(vars,
S
Stefan Berger 已提交
992 993 994 995
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataDstIPAddr))
           goto err_exit;

996
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
997 998 999 1000 1001 1002 1003
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDstIPAddr),
                          dst,
                          ipaddr);

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

1004
            if (printDataType(vars,
S
Stefan Berger 已提交
1005 1006 1007 1008
                              number, sizeof(number),
                              &ipHdr->dataDstIPMask))
                goto err_exit;

1009
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
1010 1011 1012 1013 1014 1015
                              "/%s",
                              number);

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

1016
        if (printDataType(vars,
S
Stefan Berger 已提交
1017 1018 1019 1020
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataDstIPFrom))
            goto err_exit;

1021
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1022 1023 1024 1025 1026 1027 1028
                          " -m iprange %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDstIPFrom),
                          dstrange,
                          ipaddr);

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

1029
            if (printDataType(vars,
S
Stefan Berger 已提交
1030 1031 1032
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataDstIPTo))
                goto err_exit;
1033

1034
            virBufferAsprintf(buf,
S
Stefan Berger 已提交
1035 1036 1037 1038
                              "-%s",
                              ipaddr);
        }
    }
1039

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

1042
        if (printDataType(vars,
S
Stefan Berger 已提交
1043 1044 1045
                          number, sizeof(number),
                          &ipHdr->dataDSCP))
           goto err_exit;
1046

1047
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1048 1049 1050
                          " -m dscp %s --dscp %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDSCP),
                          number);
1051 1052
    }

1053 1054
    if (HAS_ENTRY_ITEM(&ipHdr->dataConnlimitAbove)) {
        if (directionIn) {
1055
            /* only support for limit in outgoing dir. */
1056 1057 1058 1059 1060 1061 1062
            *skipRule = true;
        } else {
            if (printDataType(vars,
                              number, sizeof(number),
                              &ipHdr->dataConnlimitAbove))
               goto err_exit;

1063 1064
            /* place connlimit after potential -m state --state ...
               since this is the most useful order */
1065
            virBufferAsprintf(afterStateMatch,
1066 1067 1068 1069 1070 1071 1072
                              " -m connlimit %s --connlimit-above %s",
                              ENTRY_GET_NEG_SIGN(&ipHdr->dataConnlimitAbove),
                              number);
            *skipMatch = true;
        }
    }

1073 1074 1075
    if (HAS_ENTRY_ITEM(&ipHdr->dataComment)) {
        printCommentVar(prefix, ipHdr->dataComment.u.string);

1076 1077 1078
        /* keep comments behind everything else -- they are packet eval.
           no-ops */
        virBufferAddLit(afterStateMatch,
1079 1080 1081
                        " -m comment --comment \"$" COMMENT_VARNAME "\"");
    }

S
Stefan Berger 已提交
1082
    return 0;
1083

S
Stefan Berger 已提交
1084 1085
err_exit:
    virBufferFreeAndReset(buf);
1086
    virBufferFreeAndReset(afterStateMatch);
S
Stefan Berger 已提交
1087 1088

    return 1;
1089 1090 1091 1092
}


static int
1093
iptablesHandlePortData(virBufferPtr buf,
1094
                       virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
1095 1096
                       portDataDefPtr portData,
                       int directionIn)
1097
{
S
Stefan Berger 已提交
1098 1099 1100 1101 1102 1103 1104
    char portstr[20];
    const char *sport = "--sport";
    const char *dport = "--dport";
    if (directionIn) {
        sport = "--dport";
        dport = "--sport";
    }
1105

S
Stefan Berger 已提交
1106
    if (HAS_ENTRY_ITEM(&portData->dataSrcPortStart)) {
1107
        if (printDataType(vars,
S
Stefan Berger 已提交
1108 1109
                          portstr, sizeof(portstr),
                          &portData->dataSrcPortStart))
1110 1111
            goto err_exit;

1112
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1113 1114 1115 1116
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataSrcPortStart),
                          sport,
                          portstr);
1117

S
Stefan Berger 已提交
1118
        if (HAS_ENTRY_ITEM(&portData->dataSrcPortEnd)) {
1119
            if (printDataType(vars,
S
Stefan Berger 已提交
1120 1121
                              portstr, sizeof(portstr),
                              &portData->dataSrcPortEnd))
1122 1123
                goto err_exit;

1124
             virBufferAsprintf(buf,
S
Stefan Berger 已提交
1125 1126
                               ":%s",
                               portstr);
1127 1128 1129
        }
    }

S
Stefan Berger 已提交
1130
    if (HAS_ENTRY_ITEM(&portData->dataDstPortStart)) {
1131
        if (printDataType(vars,
S
Stefan Berger 已提交
1132 1133
                          portstr, sizeof(portstr),
                          &portData->dataDstPortStart))
1134 1135
            goto err_exit;

1136
        virBufferAsprintf(buf,
S
Stefan Berger 已提交
1137 1138 1139 1140
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataDstPortStart),
                          dport,
                          portstr);
1141

S
Stefan Berger 已提交
1142
        if (HAS_ENTRY_ITEM(&portData->dataDstPortEnd)) {
1143
            if (printDataType(vars,
S
Stefan Berger 已提交
1144 1145
                              portstr, sizeof(portstr),
                              &portData->dataDstPortEnd))
1146 1147
                goto err_exit;

1148
             virBufferAsprintf(buf,
S
Stefan Berger 已提交
1149 1150
                               ":%s",
                               portstr);
1151 1152 1153 1154 1155
        }
    }

    return 0;

S
Stefan Berger 已提交
1156
err_exit:
1157 1158 1159
    return 1;
}

1160 1161 1162 1163 1164 1165 1166

static void
iptablesEnforceDirection(int directionIn,
                         virNWFilterRuleDefPtr rule,
                         virBufferPtr buf)
{
    if (rule->tt != VIR_NWFILTER_RULE_DIRECTION_INOUT)
1167
        virBufferAsprintf(buf, " -m conntrack --ctdir %s",
1168 1169 1170 1171 1172
                          (directionIn) ? "Original"
                                        : "Reply");
}


S
Stefan Berger 已提交
1173 1174 1175 1176 1177 1178 1179 1180
/*
 * _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
1181 1182 1183 1184 1185 1186
 * @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 已提交
1187 1188 1189 1190 1191 1192 1193 1194
 *
 * 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
1195
_iptablesCreateRuleInstance(int directionIn,
S
Stefan Berger 已提交
1196 1197 1198 1199
                            const char *chainPrefix,
                            virNWFilterDefPtr nwfilter,
                            virNWFilterRuleDefPtr rule,
                            const char *ifname,
1200
                            virNWFilterVarCombIterPtr vars,
S
Stefan Berger 已提交
1201
                            virNWFilterRuleInstPtr res,
1202
                            const char *match, bool defMatch,
1203
                            const char *accept_target,
1204 1205
                            bool isIPv6,
                            bool maySkipICMP)
S
Stefan Berger 已提交
1206 1207
{
    char chain[MAX_CHAINNAME_LENGTH];
S
Stefan Berger 已提交
1208 1209
    char number[MAX(INT_BUFSIZE_BOUND(uint32_t),
                    INT_BUFSIZE_BOUND(int))];
1210
    virBuffer prefix = VIR_BUFFER_INITIALIZER;
S
Stefan Berger 已提交
1211
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1212
    virBuffer afterStateMatch = VIR_BUFFER_INITIALIZER;
1213
    virBufferPtr final = NULL;
S
Stefan Berger 已提交
1214
    const char *target;
1215 1216
    const char *iptables_cmd = (isIPv6) ? ip6tables_cmd_path
                                        : iptables_cmd_path;
1217 1218
    unsigned int bufUsed;
    bool srcMacSkipped = false;
1219 1220
    bool skipRule = false;
    bool skipMatch = false;
1221
    bool hasICMPType = false;
S
Stefan Berger 已提交
1222

1223 1224 1225 1226 1227 1228 1229 1230
    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 已提交
1231 1232 1233 1234
    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
1235
    case VIR_NWFILTER_RULE_PROTOCOL_TCPoIPV6:
1236
        virBufferAsprintf(&buf,
1237
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
S
Stefan Berger 已提交
1238 1239 1240 1241
                          chain);

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

1242 1243
        bufUsed = virBufferUse(&buf);

1244
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1245 1246
                                     vars,
                                     &rule->p.tcpHdrFilter.dataSrcMACAddr,
1247 1248
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1249 1250
            goto err_exit;

1251
        if (iptablesHandleIpHdr(&buf,
1252
                                &afterStateMatch,
S
Stefan Berger 已提交
1253 1254
                                vars,
                                &rule->p.tcpHdrFilter.ipHdr,
1255
                                directionIn,
1256 1257
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1258 1259
            goto err_exit;

1260
        if (HAS_ENTRY_ITEM(&rule->p.tcpHdrFilter.dataTCPFlags)) {
1261
            virBufferAsprintf(&buf, " %s --tcp-flags ",
1262 1263 1264 1265 1266 1267 1268
                      ENTRY_GET_NEG_SIGN(&rule->p.tcpHdrFilter.dataTCPFlags));
            virNWFilterPrintTCPFlags(&buf,
                      rule->p.tcpHdrFilter.dataTCPFlags.u.tcpFlags.mask,
                      ' ',
                      rule->p.tcpHdrFilter.dataTCPFlags.u.tcpFlags.flags);
        }

1269
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1270 1271 1272 1273 1274 1275
                                   vars,
                                   &rule->p.tcpHdrFilter.portData,
                                   directionIn))
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.tcpHdrFilter.dataTCPOption)) {
1276
            if (printDataType(vars,
S
Stefan Berger 已提交
1277 1278 1279 1280
                              number, sizeof(number),
                              &rule->p.tcpHdrFilter.dataTCPOption))
                goto err_exit;

1281
            virBufferAsprintf(&buf,
S
Stefan Berger 已提交
1282 1283 1284 1285 1286 1287 1288 1289
                              " %s --tcp-option %s",
                              ENTRY_GET_NEG_SIGN(&rule->p.tcpHdrFilter.dataTCPOption),
                              number);
        }

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
1290
    case VIR_NWFILTER_RULE_PROTOCOL_UDPoIPV6:
1291
        virBufferAsprintf(&buf,
1292
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
S
Stefan Berger 已提交
1293 1294 1295 1296
                          chain);

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

1297 1298
        bufUsed = virBufferUse(&buf);

1299
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1300 1301
                                     vars,
                                     &rule->p.udpHdrFilter.dataSrcMACAddr,
1302 1303
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1304 1305
            goto err_exit;

1306
        if (iptablesHandleIpHdr(&buf,
1307
                                &afterStateMatch,
S
Stefan Berger 已提交
1308 1309
                                vars,
                                &rule->p.udpHdrFilter.ipHdr,
1310
                                directionIn,
1311 1312
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1313 1314
            goto err_exit;

1315
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1316 1317 1318 1319 1320 1321
                                   vars,
                                   &rule->p.udpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

1322
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
1323
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITEoIPV6:
1324
        virBufferAsprintf(&buf,
1325
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
1326 1327 1328 1329
                          chain);

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

1330 1331
        bufUsed = virBufferUse(&buf);

1332
        if (iptablesHandleSrcMacAddr(&buf,
1333 1334
                                     vars,
                                     &rule->p.udpliteHdrFilter.dataSrcMACAddr,
1335 1336
                                     directionIn,
                                     &srcMacSkipped))
1337 1338
            goto err_exit;

1339
        if (iptablesHandleIpHdr(&buf,
1340
                                &afterStateMatch,
1341 1342
                                vars,
                                &rule->p.udpliteHdrFilter.ipHdr,
1343
                                directionIn,
1344 1345
                                &skipRule, &skipMatch,
                                &prefix))
1346 1347 1348 1349 1350
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
1351
    case VIR_NWFILTER_RULE_PROTOCOL_ESPoIPV6:
1352
        virBufferAsprintf(&buf,
1353
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
1354 1355 1356 1357
                          chain);

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

1358 1359
        bufUsed = virBufferUse(&buf);

1360
        if (iptablesHandleSrcMacAddr(&buf,
1361 1362
                                     vars,
                                     &rule->p.espHdrFilter.dataSrcMACAddr,
1363 1364
                                     directionIn,
                                     &srcMacSkipped))
1365 1366
            goto err_exit;

1367
        if (iptablesHandleIpHdr(&buf,
1368
                                &afterStateMatch,
1369 1370
                                vars,
                                &rule->p.espHdrFilter.ipHdr,
1371
                                directionIn,
1372 1373
                                &skipRule, &skipMatch,
                                &prefix))
1374 1375 1376 1377 1378
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_AH:
1379
    case VIR_NWFILTER_RULE_PROTOCOL_AHoIPV6:
1380
        virBufferAsprintf(&buf,
1381
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
1382 1383 1384 1385
                          chain);

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

1386 1387
        bufUsed = virBufferUse(&buf);

1388
        if (iptablesHandleSrcMacAddr(&buf,
1389 1390
                                     vars,
                                     &rule->p.ahHdrFilter.dataSrcMACAddr,
1391 1392
                                     directionIn,
                                     &srcMacSkipped))
1393 1394
            goto err_exit;

1395
        if (iptablesHandleIpHdr(&buf,
1396
                                &afterStateMatch,
1397 1398
                                vars,
                                &rule->p.ahHdrFilter.ipHdr,
1399
                                directionIn,
1400 1401
                                &skipRule, &skipMatch,
                                &prefix))
1402 1403 1404 1405
            goto err_exit;

    break;

S
Stefan Berger 已提交
1406
    case VIR_NWFILTER_RULE_PROTOCOL_SCTP:
1407
    case VIR_NWFILTER_RULE_PROTOCOL_SCTPoIPV6:
1408
        virBufferAsprintf(&buf,
1409
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
S
Stefan Berger 已提交
1410 1411 1412 1413
                          chain);

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

1414 1415
        bufUsed = virBufferUse(&buf);

1416
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1417 1418
                                     vars,
                                     &rule->p.sctpHdrFilter.dataSrcMACAddr,
1419 1420
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1421 1422
            goto err_exit;

1423
        if (iptablesHandleIpHdr(&buf,
1424
                                &afterStateMatch,
S
Stefan Berger 已提交
1425 1426
                                vars,
                                &rule->p.sctpHdrFilter.ipHdr,
1427
                                directionIn,
1428 1429
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1430 1431
            goto err_exit;

1432
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1433 1434 1435 1436 1437 1438 1439
                                   vars,
                                   &rule->p.sctpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
1440
    case VIR_NWFILTER_RULE_PROTOCOL_ICMPV6:
1441
        virBufferAsprintf(&buf,
1442
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
S
Stefan Berger 已提交
1443 1444
                          chain);

1445 1446 1447 1448
        if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
            virBufferAddLit(&buf, " -p icmp");
        else
            virBufferAddLit(&buf, " -p icmpv6");
S
Stefan Berger 已提交
1449

1450 1451
        bufUsed = virBufferUse(&buf);

1452
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1453 1454
                                     vars,
                                     &rule->p.icmpHdrFilter.dataSrcMACAddr,
1455 1456
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1457 1458
            goto err_exit;

1459
        if (iptablesHandleIpHdr(&buf,
1460
                                &afterStateMatch,
S
Stefan Berger 已提交
1461 1462
                                vars,
                                &rule->p.icmpHdrFilter.ipHdr,
1463
                                directionIn,
1464 1465
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1466 1467 1468
            goto err_exit;

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

1471 1472
            hasICMPType = true;

1473 1474 1475
            if (maySkipICMP)
                goto exit_no_error;

1476 1477 1478 1479 1480
            if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
                parm = "--icmp-type";
            else
                parm = "--icmpv6-type";

1481
            if (printDataType(vars,
S
Stefan Berger 已提交
1482 1483 1484 1485
                              number, sizeof(number),
                              &rule->p.icmpHdrFilter.dataICMPType))
                goto err_exit;

1486
            virBufferAsprintf(&buf,
1487
                      " %s %s %s",
S
Stefan Berger 已提交
1488
                      ENTRY_GET_NEG_SIGN(&rule->p.icmpHdrFilter.dataICMPType),
1489
                      parm,
S
Stefan Berger 已提交
1490 1491 1492
                      number);

            if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPCode)) {
1493
                if (printDataType(vars,
S
Stefan Berger 已提交
1494 1495 1496 1497
                                  number, sizeof(number),
                                  &rule->p.icmpHdrFilter.dataICMPCode))
                    goto err_exit;

1498
                 virBufferAsprintf(&buf,
S
Stefan Berger 已提交
1499 1500 1501 1502 1503 1504
                                   "/%s",
                                   number);
            }
        }
    break;

1505
    case VIR_NWFILTER_RULE_PROTOCOL_IGMP:
1506
        virBufferAsprintf(&buf,
1507
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
1508 1509 1510 1511
                          chain);

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

1512 1513
        bufUsed = virBufferUse(&buf);

1514
        if (iptablesHandleSrcMacAddr(&buf,
1515 1516
                                     vars,
                                     &rule->p.igmpHdrFilter.dataSrcMACAddr,
1517 1518
                                     directionIn,
                                     &srcMacSkipped))
1519 1520
            goto err_exit;

1521
        if (iptablesHandleIpHdr(&buf,
1522
                                &afterStateMatch,
1523 1524
                                vars,
                                &rule->p.igmpHdrFilter.ipHdr,
1525
                                directionIn,
1526 1527
                                &skipRule, &skipMatch,
                                &prefix))
1528 1529 1530 1531
            goto err_exit;

    break;

S
Stefan Berger 已提交
1532
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
1533
    case VIR_NWFILTER_RULE_PROTOCOL_ALLoIPV6:
1534
        virBufferAsprintf(&buf,
1535
                          CMD_DEF_PRE "$IPT -%%c %s %%s",
S
Stefan Berger 已提交
1536 1537 1538 1539
                          chain);

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

1540 1541
        bufUsed = virBufferUse(&buf);

1542
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1543 1544
                                     vars,
                                     &rule->p.allHdrFilter.dataSrcMACAddr,
1545 1546
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1547 1548
            goto err_exit;

1549
        if (iptablesHandleIpHdr(&buf,
1550
                                &afterStateMatch,
S
Stefan Berger 已提交
1551 1552
                                vars,
                                &rule->p.allHdrFilter.ipHdr,
1553
                                directionIn,
1554 1555
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1556 1557 1558 1559 1560 1561 1562 1563
            goto err_exit;

    break;

    default:
        return -1;
    }

1564 1565
    if ((srcMacSkipped && bufUsed == virBufferUse(&buf)) ||
         skipRule) {
1566
        virBufferFreeAndReset(&buf);
1567
        virBufferFreeAndReset(&prefix);
1568 1569 1570
        return 0;
    }

S
Stefan Berger 已提交
1571 1572
    if (rule->action == VIR_NWFILTER_RULE_ACTION_ACCEPT)
        target = accept_target;
1573
    else {
1574
        target = virNWFilterJumpTargetTypeToString(rule->action);
1575
        skipMatch = defMatch;
1576 1577
    }

1578
    if (match && !skipMatch)
1579
        virBufferAsprintf(&buf, " %s", match);
1580

1581
    if (defMatch && match != NULL && !skipMatch && !hasICMPType)
1582 1583 1584
        iptablesEnforceDirection(directionIn,
                                 rule,
                                 &buf);
S
Stefan Berger 已提交
1585

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
    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);
    }

1602
    virBufferAsprintf(&buf,
S
Stefan Berger 已提交
1603 1604 1605 1606
                      " -j %s" CMD_DEF_POST CMD_SEPARATOR
                      CMD_EXEC,
                      target);

1607
    if (virBufferError(&buf) || virBufferError(&prefix)) {
S
Stefan Berger 已提交
1608
        virBufferFreeAndReset(&buf);
1609
        virBufferFreeAndReset(&prefix);
S
Stefan Berger 已提交
1610 1611 1612 1613
        virReportOOMError();
        return -1;
    }

1614
    if (virBufferUse(&prefix)) {
S
Stefan Berger 已提交
1615 1616 1617 1618 1619
        char *s = virBufferContentAndReset(&buf);

        virBufferAdd(&prefix, s, -1);

        VIR_FREE(s);
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631

        final = &prefix;

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


1632
    return ebiptablesAddRuleInst(res,
1633
                                 virBufferContentAndReset(final),
S
Stefan Berger 已提交
1634
                                 nwfilter->chainsuffix,
1635
                                 nwfilter->chainPriority,
S
Stefan Berger 已提交
1636 1637
                                 '\0',
                                 rule->priority,
1638
                                 (isIPv6) ? RT_IP6TABLES : RT_IPTABLES);
S
Stefan Berger 已提交
1639 1640 1641 1642


err_exit:
    virBufferFreeAndReset(&buf);
S
Stefan Berger 已提交
1643
    virBufferFreeAndReset(&prefix);
1644
    virBufferFreeAndReset(&afterStateMatch);
S
Stefan Berger 已提交
1645 1646 1647

    return -1;

1648 1649
exit_no_error:
    virBufferFreeAndReset(&buf);
S
Stefan Berger 已提交
1650
    virBufferFreeAndReset(&prefix);
1651
    virBufferFreeAndReset(&afterStateMatch);
1652 1653

    return 0;
S
Stefan Berger 已提交
1654 1655 1656
}


1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
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,
1678
                                    virNWFilterVarCombIterPtr vars,
1679 1680 1681 1682
                                    virNWFilterRuleInstPtr res,
                                    bool isIPv6)
{
    int rc;
C
Christophe Fergeau 已提交
1683
    int directionIn = 0;
1684 1685 1686 1687 1688 1689 1690 1691
    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 已提交
1692 1693
        inout = (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
    }
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 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

    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 已提交
1799
static int
1800
iptablesCreateRuleInstance(virNWFilterDefPtr nwfilter,
S
Stefan Berger 已提交
1801 1802
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
1803
                           virNWFilterVarCombIterPtr vars,
1804 1805
                           virNWFilterRuleInstPtr res,
                           bool isIPv6)
S
Stefan Berger 已提交
1806 1807 1808 1809 1810
{
    int rc;
    int directionIn = 0;
    char chainPrefix[2];
    int needState = 1;
1811
    bool maySkipICMP, inout = false;
1812
    const char *matchState;
S
Stefan Berger 已提交
1813

1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    if (!(rule->flags & RULE_FLAG_NO_STATEMATCH) &&
         (rule->flags & IPTABLES_STATE_FLAGS)) {
        return iptablesCreateRuleInstanceStateCtrl(nwfilter,
                                                   rule,
                                                   ifname,
                                                   vars,
                                                   res,
                                                   isIPv6);
    }

S
Stefan Berger 已提交
1824 1825 1826
    if ((rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN) ||
        (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT)) {
        directionIn = 1;
1827
        inout = (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
1828 1829
        if (inout)
            needState = 0;
S
Stefan Berger 已提交
1830 1831
    }

1832 1833 1834
    if ((rule->flags & RULE_FLAG_NO_STATEMATCH))
        needState = 0;

S
Stefan Berger 已提交
1835 1836
    chainPrefix[0] = 'F';

1837 1838
    maySkipICMP = directionIn || inout;

1839 1840 1841 1842 1843
    if (needState)
        matchState = directionIn ? MATCH_STATE_IN : MATCH_STATE_OUT;
    else
        matchState = NULL;

S
Stefan Berger 已提交
1844
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1845
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1846 1847 1848 1849 1850 1851
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1852
                                     matchState, true,
1853
                                     "RETURN",
1854 1855
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1856 1857 1858
    if (rc)
        return rc;

1859 1860

    maySkipICMP = !directionIn || inout;
1861 1862 1863 1864
    if (needState)
        matchState = directionIn ? MATCH_STATE_OUT : MATCH_STATE_IN;
    else
        matchState = NULL;
1865

S
Stefan Berger 已提交
1866
    chainPrefix[1] = CHAINPREFIX_HOST_OUT_TEMP;
1867
    rc = _iptablesCreateRuleInstance(!directionIn,
S
Stefan Berger 已提交
1868 1869 1870 1871 1872 1873
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1874
                                     matchState, true,
1875
                                     "ACCEPT",
1876 1877
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1878 1879 1880
    if (rc)
        return rc;

1881
    maySkipICMP = directionIn;
1882 1883 1884 1885
    if (needState)
        matchState = directionIn ? MATCH_STATE_IN : MATCH_STATE_OUT;
    else
        matchState = NULL;
1886

S
Stefan Berger 已提交
1887 1888
    chainPrefix[0] = 'H';
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1889
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1890 1891 1892 1893 1894 1895
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1896 1897
                                     matchState, true,
                                     "RETURN",
1898 1899
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1900 1901 1902 1903 1904 1905 1906

    return rc;
}




1907 1908 1909 1910 1911 1912 1913 1914
/*
 * 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
1915
 * @reverse : Whether to reverse src and dst attributes
1916 1917 1918 1919 1920 1921 1922 1923
 *
 * 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
1924
ebtablesCreateRuleInstance(char chainPrefix,
1925 1926 1927
                           virNWFilterDefPtr nwfilter,
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
1928
                           virNWFilterVarCombIterPtr vars,
1929 1930
                           virNWFilterRuleInstPtr res,
                           bool reverse)
1931 1932 1933
{
    char macaddr[VIR_MAC_STRING_BUFLEN],
         ipaddr[INET_ADDRSTRLEN],
1934
         ipv6addr[INET6_ADDRSTRLEN],
S
Stefan Berger 已提交
1935 1936 1937
         number[MAX(INT_BUFSIZE_BOUND(uint32_t),
                    INT_BUFSIZE_BOUND(int))],
         field[MAX(VIR_MAC_STRING_BUFLEN, INET6_ADDRSTRLEN)];
1938 1939
    char chain[MAX_CHAINNAME_LENGTH];
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1940
    const char *target;
1941

1942 1943 1944 1945 1946 1947 1948
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rule since ebtables tool is "
                                 "missing."));
        goto err_exit;
    }

1949 1950 1951
    if (STREQ(nwfilter->chainsuffix,
              virNWFilterChainSuffixTypeToString(
                  VIR_NWFILTER_CHAINSUFFIX_ROOT)))
1952 1953 1954
        PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);
    else
        PRINT_CHAIN(chain, chainPrefix, ifname,
1955
                    nwfilter->chainsuffix);
1956 1957 1958 1959 1960


    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:

1961
        virBufferAsprintf(&buf,
1962 1963
                          CMD_DEF_PRE "$EBT -t nat -%%c %s %%s",
                          chain);
1964

1965
        if (ebtablesHandleEthHdr(&buf,
1966
                                 vars,
1967 1968
                                 &rule->p.ethHdrFilter.ethHdr,
                                 reverse))
1969 1970 1971
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.ethHdrFilter.dataProtocolID)) {
1972
            if (printDataTypeAsHex(vars,
1973 1974
                                   number, sizeof(number),
                                   &rule->p.ethHdrFilter.dataProtocolID))
1975
                goto err_exit;
1976
            virBufferAsprintf(&buf,
1977 1978 1979 1980 1981 1982
                          " -p %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.ethHdrFilter.dataProtocolID),
                          number);
        }
    break;

S
Stefan Berger 已提交
1983 1984 1985
    case VIR_NWFILTER_RULE_PROTOCOL_VLAN:

        virBufferAsprintf(&buf,
1986 1987
                          CMD_DEF_PRE "$EBT -t nat -%%c %s %%s",
                          chain);
S
Stefan Berger 已提交
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001


        if (ebtablesHandleEthHdr(&buf,
                                 vars,
                                 &rule->p.vlanHdrFilter.ethHdr,
                                 reverse))
            goto err_exit;

        virBufferAddLit(&buf,
                        " -p 0x8100");

#define INST_ITEM(STRUCT, ITEM, CLI) \
        if (HAS_ENTRY_ITEM(&rule->p.STRUCT.ITEM)) { \
            if (printDataType(vars, \
S
Stefan Berger 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
                              field, sizeof(field), \
                              &rule->p.STRUCT.ITEM)) \
                goto err_exit; \
            virBufferAsprintf(&buf, \
                          " " CLI " %s %s", \
                          ENTRY_GET_NEG_SIGN(&rule->p.STRUCT.ITEM), \
                          field); \
        }

#define INST_ITEM_2PARMS(STRUCT, ITEM, ITEM_HI, CLI, SEP) \
        if (HAS_ENTRY_ITEM(&rule->p.STRUCT.ITEM)) { \
            if (printDataType(vars, \
                              field, sizeof(field), \
S
Stefan Berger 已提交
2015 2016 2017 2018 2019
                              &rule->p.STRUCT.ITEM)) \
                goto err_exit; \
            virBufferAsprintf(&buf, \
                          " " CLI " %s %s", \
                          ENTRY_GET_NEG_SIGN(&rule->p.STRUCT.ITEM), \
S
Stefan Berger 已提交
2020 2021 2022 2023 2024 2025 2026 2027
                          field); \
            if (HAS_ENTRY_ITEM(&rule->p.STRUCT.ITEM_HI)) { \
                if (printDataType(vars, \
                                  field, sizeof(field), \
                                  &rule->p.STRUCT.ITEM_HI)) \
                    goto err_exit; \
                virBufferAsprintf(&buf, SEP "%s", field); \
            } \
S
Stefan Berger 已提交
2028
        }
S
Stefan Berger 已提交
2029 2030 2031 2032
#define INST_ITEM_RANGE(S, I, I_HI, C) \
    INST_ITEM_2PARMS(S, I, I_HI, C, ":")
#define INST_ITEM_MASK(S, I, MASK, C) \
    INST_ITEM_2PARMS(S, I, MASK, C, "/")
S
Stefan Berger 已提交
2033 2034 2035 2036 2037

        INST_ITEM(vlanHdrFilter, dataVlanID, "--vlan-id")
        INST_ITEM(vlanHdrFilter, dataVlanEncap, "--vlan-encap")
    break;

S
Stefan Berger 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
    case VIR_NWFILTER_RULE_PROTOCOL_STP:

        /* cannot handle inout direction with srcmask set in reverse dir.
           since this clashes with -d below... */
        if (reverse &&
            HAS_ENTRY_ITEM(&rule->p.stpHdrFilter.ethHdr.dataSrcMACAddr)) {
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("STP filtering in %s direction with "
                                   "source MAC address set is not supported"),
                                   virNWFilterRuleDirectionTypeToString(
                                       VIR_NWFILTER_RULE_DIRECTION_INOUT));
            return -1;
        }

        virBufferAsprintf(&buf,
2053 2054
                          CMD_DEF_PRE "$EBT -t nat -%%c %s %%s",
                          chain);
S
Stefan Berger 已提交
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086


        if (ebtablesHandleEthHdr(&buf,
                                 vars,
                                 &rule->p.stpHdrFilter.ethHdr,
                                 reverse))
            goto err_exit;

        virBufferAddLit(&buf, " -d " NWFILTER_MAC_BGA);

        INST_ITEM(stpHdrFilter, dataType, "--stp-type")
        INST_ITEM(stpHdrFilter, dataFlags, "--stp-flags")
        INST_ITEM_RANGE(stpHdrFilter, dataRootPri, dataRootPriHi,
                        "--stp-root-pri");
        INST_ITEM_MASK( stpHdrFilter, dataRootAddr, dataRootAddrMask,
                       "--stp-root-addr");
        INST_ITEM_RANGE(stpHdrFilter, dataRootCost, dataRootCostHi,
                        "--stp-root-cost");
        INST_ITEM_RANGE(stpHdrFilter, dataSndrPrio, dataSndrPrioHi,
                        "--stp-sender-prio");
        INST_ITEM_MASK( stpHdrFilter, dataSndrAddr, dataSndrAddrMask,
                        "--stp-sender-addr");
        INST_ITEM_RANGE(stpHdrFilter, dataPort, dataPortHi, "--stp-port");
        INST_ITEM_RANGE(stpHdrFilter, dataAge, dataAgeHi, "--stp-msg-age");
        INST_ITEM_RANGE(stpHdrFilter, dataMaxAge, dataMaxAgeHi,
                        "--stp-max-age");
        INST_ITEM_RANGE(stpHdrFilter, dataHelloTime, dataHelloTimeHi,
                        "--stp-hello-time");
        INST_ITEM_RANGE(stpHdrFilter, dataFwdDelay, dataFwdDelayHi,
                        "--stp-forward-delay");
    break;

2087
    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
2088
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
2089

2090
        virBufferAsprintf(&buf,
2091 2092
                          CMD_DEF_PRE "$EBT -t nat -%%c %s %%s",
                          chain);
2093

2094
        if (ebtablesHandleEthHdr(&buf,
2095
                                 vars,
2096 2097
                                 &rule->p.arpHdrFilter.ethHdr,
                                 reverse))
2098 2099
            goto err_exit;

2100
        virBufferAsprintf(&buf, " -p 0x%x",
2101 2102 2103
                          (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ARP)
                           ? l3_protocols[L3_PROTO_ARP_IDX].attr
                           : l3_protocols[L3_PROTO_RARP_IDX].attr);
2104 2105

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataHWType)) {
2106 2107 2108
             if (printDataType(vars,
                               number, sizeof(number),
                               &rule->p.arpHdrFilter.dataHWType))
2109
                goto err_exit;
2110
           virBufferAsprintf(&buf,
2111 2112 2113 2114 2115 2116
                          " --arp-htype %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataHWType),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataOpcode)) {
2117
            if (printDataType(vars,
2118 2119 2120
                              number, sizeof(number),
                              &rule->p.arpHdrFilter.dataOpcode))
                goto err_exit;
2121
            virBufferAsprintf(&buf,
2122 2123 2124 2125 2126 2127
                          " --arp-opcode %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataOpcode),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataProtocolType)) {
2128
            if (printDataTypeAsHex(vars,
2129 2130
                                   number, sizeof(number),
                                   &rule->p.arpHdrFilter.dataProtocolType))
2131
                goto err_exit;
2132
            virBufferAsprintf(&buf,
2133 2134 2135 2136 2137 2138
                          " --arp-ptype %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataProtocolType),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcIPAddr)) {
2139
            if (printDataType(vars,
2140 2141 2142 2143
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPSrcIPAddr))
                goto err_exit;

2144
            virBufferAsprintf(&buf,
2145 2146
                          " %s %s %s",
                          reverse ? "--arp-ip-dst" : "--arp-ip-src",
2147 2148 2149 2150 2151
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstIPAddr)) {
2152
            if (printDataType(vars,
2153 2154 2155 2156
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPDstIPAddr))
                goto err_exit;

2157
            virBufferAsprintf(&buf,
2158 2159
                          " %s %s %s",
                          reverse ? "--arp-ip-src" : "--arp-ip-dst",
2160 2161 2162 2163 2164
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcMACAddr)) {
2165
            if (printDataType(vars,
2166 2167 2168 2169
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPSrcMACAddr))
                goto err_exit;

2170
            virBufferAsprintf(&buf,
2171 2172
                          " %s %s %s",
                          reverse ? "--arp-mac-dst" : "--arp-mac-src",
2173 2174 2175 2176 2177
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcMACAddr),
                          macaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstMACAddr)) {
2178
            if (printDataType(vars,
2179 2180 2181 2182
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPDstMACAddr))
                goto err_exit;

2183
            virBufferAsprintf(&buf,
2184 2185
                          " %s %s %s",
                          reverse ? "--arp-mac-src" : "--arp-mac-dst",
2186 2187 2188
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstMACAddr),
                          macaddr);
        }
2189 2190 2191 2192 2193 2194 2195

        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));
        }
2196 2197 2198
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_IP:
2199
        virBufferAsprintf(&buf,
2200 2201
                          CMD_DEF_PRE "$EBT -t nat -%%c %s %%s",
                          chain);
2202

2203
        if (ebtablesHandleEthHdr(&buf,
2204
                                 vars,
2205 2206
                                 &rule->p.ipHdrFilter.ethHdr,
                                 reverse))
2207 2208 2209 2210 2211 2212
            goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr)) {
2213
            if (printDataType(vars,
2214 2215 2216 2217
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

2218
            virBufferAsprintf(&buf,
2219 2220
                          " %s %s %s",
                          reverse ? "--ip-destination" : "--ip-source",
2221 2222 2223 2224
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPMask)) {
2225
                if (printDataType(vars,
2226 2227 2228
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
2229
                virBufferAsprintf(&buf,
2230 2231 2232 2233 2234 2235 2236
                             "/%s",
                             number);
            }
        }

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

2237
            if (printDataType(vars,
2238 2239 2240 2241
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

2242
            virBufferAsprintf(&buf,
2243 2244
                          " %s %s %s",
                          reverse ? "--ip-source" : "--ip-destination",
2245 2246 2247 2248
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDstIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDstIPMask)) {
2249
                if (printDataType(vars,
2250 2251 2252
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
2253
                virBufferAsprintf(&buf,
2254 2255 2256 2257 2258 2259
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataProtocolID)) {
2260
            if (printDataType(vars,
2261 2262 2263 2264
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.ipHdr.dataProtocolID))
                goto err_exit;

2265
            virBufferAsprintf(&buf,
2266 2267 2268 2269 2270 2271 2272
                 " --ip-protocol %s %s",
                 ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataProtocolID),
                 number);
        }

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

2273
            if (printDataType(vars,
2274 2275 2276 2277
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataSrcPortStart))
                goto err_exit;

2278
            virBufferAsprintf(&buf,
2279 2280
                          " %s %s %s",
                          reverse ? "--ip-destination-port" : "--ip-source-port",
2281 2282 2283 2284
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataSrcPortEnd)) {
2285
                if (printDataType(vars,
2286 2287 2288 2289
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

2290
                virBufferAsprintf(&buf,
2291 2292 2293 2294 2295 2296 2297
                                  ":%s",
                                  number);
            }
        }

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

2298
            if (printDataType(vars,
2299 2300 2301 2302
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataDstPortStart))
                goto err_exit;

2303
            virBufferAsprintf(&buf,
2304 2305
                          " %s %s %s",
                          reverse ? "--ip-source-port" : "--ip-destination-port",
2306 2307 2308 2309
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataDstPortEnd)) {
2310
                if (printDataType(vars,
2311 2312 2313 2314
                                number, sizeof(number),
                                &rule->p.ipHdrFilter.portData.dataDstPortEnd))
                    goto err_exit;

2315
                virBufferAsprintf(&buf,
2316 2317 2318 2319 2320 2321
                                  ":%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDSCP)) {
2322 2323 2324
            if (printDataTypeAsHex(vars,
                                   number, sizeof(number),
                                   &rule->p.ipHdrFilter.ipHdr.dataDSCP))
2325 2326
                goto err_exit;

2327
            virBufferAsprintf(&buf,
2328 2329 2330 2331 2332 2333
                       " --ip-tos %s %s",
                       ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDSCP),
                       number);
        }
    break;

2334
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
2335
        virBufferAsprintf(&buf,
2336 2337
                          CMD_DEF_PRE "$EBT -t nat -%%c %s %%s",
                          chain);
2338

2339
        if (ebtablesHandleEthHdr(&buf,
2340
                                 vars,
2341 2342
                                 &rule->p.ipv6HdrFilter.ethHdr,
                                 reverse))
2343 2344 2345 2346 2347 2348
            goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr)) {
2349
            if (printDataType(vars,
2350 2351 2352 2353
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

2354
            virBufferAsprintf(&buf,
2355 2356
                          " %s %s %s",
                          reverse ? "--ip6-destination" : "--ip6-source",
2357 2358 2359 2360
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask)) {
2361
                if (printDataType(vars,
2362 2363 2364
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
2365
                virBufferAsprintf(&buf,
2366 2367 2368 2369 2370 2371 2372
                             "/%s",
                             number);
            }
        }

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

2373
            if (printDataType(vars,
2374 2375 2376 2377
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

2378
            virBufferAsprintf(&buf,
2379 2380
                          " %s %s %s",
                          reverse ? "--ip6-source" : "--ip6-destination",
2381 2382 2383 2384
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask)) {
2385
                if (printDataType(vars,
2386 2387 2388
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
2389
                virBufferAsprintf(&buf,
2390 2391 2392 2393 2394 2395
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID)) {
2396
            if (printDataType(vars,
2397 2398 2399 2400
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.ipHdr.dataProtocolID))
                goto err_exit;

2401
            virBufferAsprintf(&buf,
2402 2403 2404 2405 2406 2407 2408
                 " --ip6-protocol %s %s",
                 ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID),
                 number);
        }

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

2409
            if (printDataType(vars,
2410 2411 2412 2413
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataSrcPortStart))
                goto err_exit;

2414
            virBufferAsprintf(&buf,
2415 2416
                          " %s %s %s",
                          reverse ? "--ip6-destination-port" : "--ip6-source-port",
2417 2418 2419 2420
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataSrcPortEnd)) {
2421
                if (printDataType(vars,
2422 2423 2424 2425
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

2426
                virBufferAsprintf(&buf,
2427 2428 2429 2430 2431 2432 2433
                                  ":%s",
                                  number);
            }
        }

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

2434
            if (printDataType(vars,
2435 2436 2437 2438
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataDstPortStart))
                goto err_exit;

2439
            virBufferAsprintf(&buf,
2440 2441
                          " %s %s %s",
                          reverse ? "--ip6-source-port" : "--ip6-destination-port",
2442 2443 2444 2445
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataDstPortEnd)) {
2446 2447 2448
                if (printDataType(vars,
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataDstPortEnd))
2449 2450
                    goto err_exit;

2451
                virBufferAsprintf(&buf,
2452 2453 2454 2455 2456 2457
                                  ":%s",
                                  number);
            }
        }
    break;

2458
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
2459
        virBufferAsprintf(&buf,
2460 2461
                          CMD_DEF_PRE "$EBT -t nat -%%c %s %%s",
                          chain);
2462
    break;
S
Stefan Berger 已提交
2463 2464 2465

    default:
        return -1;
2466 2467
    }

2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
    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);
    }

2478
    virBufferAsprintf(&buf,
2479 2480
                      " -j %s" CMD_DEF_POST CMD_SEPARATOR
                      CMD_EXEC,
2481
                      target);
2482 2483 2484 2485 2486 2487 2488

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

2489
    return ebiptablesAddRuleInst(res,
2490 2491
                                 virBufferContentAndReset(&buf),
                                 nwfilter->chainsuffix,
2492
                                 nwfilter->chainPriority,
2493
                                 chainPrefix,
S
Stefan Berger 已提交
2494 2495
                                 rule->priority,
                                 RT_EBTABLES);
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519

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
2520
ebiptablesCreateRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
2521
                             enum virDomainNetType nettype ATTRIBUTE_UNUSED,
2522 2523 2524
                             virNWFilterDefPtr nwfilter,
                             virNWFilterRuleDefPtr rule,
                             const char *ifname,
2525
                             virNWFilterVarCombIterPtr vars,
2526 2527 2528
                             virNWFilterRuleInstPtr res)
{
    int rc = 0;
2529
    bool isIPv6;
2530 2531 2532 2533

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_IP:
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:
S
Stefan Berger 已提交
2534
    case VIR_NWFILTER_RULE_PROTOCOL_VLAN:
S
Stefan Berger 已提交
2535
    case VIR_NWFILTER_RULE_PROTOCOL_STP:
2536
    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
2537
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
2538
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
2539
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
2540 2541 2542

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_OUT ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2543
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_IN_TEMP,
2544 2545 2546 2547
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2548 2549
                                            res,
                                            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
2550 2551 2552 2553 2554 2555
            if (rc)
                return rc;
        }

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2556
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_OUT_TEMP,
2557 2558 2559 2560
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2561 2562
                                            res,
                                            false);
2563 2564
        }
    break;
S
Stefan Berger 已提交
2565 2566 2567

    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
2568 2569 2570
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
    case VIR_NWFILTER_RULE_PROTOCOL_AH:
S
Stefan Berger 已提交
2571 2572 2573 2574
    case VIR_NWFILTER_RULE_PROTOCOL_SCTP:
    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
    case VIR_NWFILTER_RULE_PROTOCOL_IGMP:
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
2575
        isIPv6 = 0;
2576
        rc = iptablesCreateRuleInstance(nwfilter,
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
                                        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;
2593
        rc = iptablesCreateRuleInstance(nwfilter,
S
Stefan Berger 已提交
2594 2595 2596
                                        rule,
                                        ifname,
                                        vars,
2597 2598
                                        res,
                                        isIPv6);
S
Stefan Berger 已提交
2599 2600 2601
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_LAST:
2602
        virNWFilterReportError(VIR_ERR_OPERATION_FAILED,
S
Stefan Berger 已提交
2603 2604 2605
                               "%s", _("illegal protocol type"));
        rc = 1;
    break;
2606 2607 2608 2609 2610
    }

    return rc;
}

2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
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;
}
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662

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


static int
ebiptablesDisplayRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
                              void *_inst)
{
    ebiptablesRuleInstPtr inst = (ebiptablesRuleInstPtr)_inst;
2663 2664
    VIR_INFO("Command Template: '%s', Needed protocol: '%s'",
             inst->commandTemplate,
2665
             inst->neededProtocolChain);
2666 2667 2668 2669 2670 2671 2672 2673
    return 0;
}


/**
 * ebiptablesExecCLI:
 * @buf : pointer to virBuffer containing the string with the commands to
 *        execute.
2674
 * @status: Pointer to an integer for returning the WEXITSTATUS of the
2675
 *        commands executed via the script the was run.
2676 2677 2678 2679
 * @outbuf: Optional pointer to a string that will hold the buffer with
 *          output of the executed command. The actual buffer holding
 *          the message will be newly allocated by this function and
 *          any passed in buffer freed first.
2680
 *
2681
 * Returns 0 in case of success, < 0 in case of an error. The returned
2682
 * value is NOT the result of running the commands inside the shell
2683 2684
 * script.
 *
2685
 * Execute a sequence of commands (held in the given buffer) as a /bin/sh
2686 2687
 * script and return the status of the execution in *status (if status is
 * NULL, then the script must exit with status 0).
2688 2689
 */
static int
2690
ebiptablesExecCLI(virBufferPtr buf,
2691
                  int *status, char **outbuf)
2692
{
2693 2694
    int rc = -1;
    virCommandPtr cmd;
2695

2696 2697 2698
    if (status)
         *status = 0;

2699
    if (!virBufferError(buf) && !virBufferUse(buf))
2700 2701
        return 0;

2702 2703 2704
    if (outbuf)
        VIR_FREE(*outbuf);

2705 2706
    cmd = virCommandNewArgList("/bin/sh", "-c", NULL);
    virCommandAddArgBuffer(cmd, buf);
2707 2708
    if (outbuf)
        virCommandSetOutputBuffer(cmd, outbuf);
2709 2710 2711

    virMutexLock(&execCLIMutex);

2712
    rc = virCommandRun(cmd, status);
2713

2714 2715
    virMutexUnlock(&execCLIMutex);

2716 2717
    virCommandFree(cmd);

2718 2719 2720 2721 2722
    return rc;
}


static int
2723
ebtablesCreateTmpRootChain(virBufferPtr buf,
2724 2725 2726 2727 2728 2729 2730 2731 2732
                           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);

2733
    virBufferAsprintf(buf,
2734
                      CMD_DEF("$EBT -t nat -N %s") CMD_SEPARATOR
2735 2736
                      CMD_EXEC
                      "%s",
2737
                      chain,
2738 2739 2740 2741 2742 2743 2744
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2745
ebtablesLinkTmpRootChain(virBufferPtr buf,
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
                         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);

2756
    virBufferAsprintf(buf,
2757
                      CMD_DEF("$EBT -t nat -A %s -%c %s -j %s") CMD_SEPARATOR
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770
                      CMD_EXEC
                      "%s",
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2771
_ebtablesRemoveRootChain(virBufferPtr buf,
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
                         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);

2786
    virBufferAsprintf(buf,
2787 2788 2789 2790
                      "$EBT -t nat -F %s" CMD_SEPARATOR
                      "$EBT -t nat -X %s" CMD_SEPARATOR,
                      chain,
                      chain);
2791 2792 2793 2794 2795 2796

    return 0;
}


static int
2797
ebtablesRemoveRootChain(virBufferPtr buf,
2798 2799
                        int incoming, const char *ifname)
{
2800
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 0);
2801 2802 2803 2804
}


static int
2805
ebtablesRemoveTmpRootChain(virBufferPtr buf,
2806 2807
                           int incoming, const char *ifname)
{
2808
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 1);
2809 2810 2811 2812
}


static int
2813
_ebtablesUnlinkRootChain(virBufferPtr buf,
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
                         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);

2831
    virBufferAsprintf(buf,
2832
                      "$EBT -t nat -D %s -%c %s -j %s" CMD_SEPARATOR,
2833 2834 2835 2836 2837 2838 2839 2840 2841
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain);

    return 0;
}


static int
2842
ebtablesUnlinkRootChain(virBufferPtr buf,
2843 2844
                        int incoming, const char *ifname)
{
2845
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 0);
2846 2847 2848 2849
}


static int
2850
ebtablesUnlinkTmpRootChain(virBufferPtr buf,
2851 2852
                           int incoming, const char *ifname)
{
2853
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 1);
2854 2855 2856 2857
}


static int
2858 2859
ebtablesCreateTmpSubChain(ebiptablesRuleInstPtr *inst,
                          int *nRuleInstances,
2860 2861
                          int incoming,
                          const char *ifname,
2862
                          enum l3_proto_idx protoidx,
2863
                          const char *filtername,
2864 2865
                          int stopOnError,
                          virNWFilterChainPriority priority)
2866
{
2867 2868 2869
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    ebiptablesRuleInstPtr tmp = *inst;
    size_t count = *nRuleInstances;
2870 2871 2872
    char rootchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                  : CHAINPREFIX_HOST_OUT_TEMP;
S
Stefan Berger 已提交
2873
    char *protostr = NULL;
2874 2875

    PRINT_ROOT_CHAIN(rootchain, chainPrefix, ifname);
2876 2877
    PRINT_CHAIN(chain, chainPrefix, ifname,
                (filtername) ? filtername : l3_protocols[protoidx].val);
2878

S
Stefan Berger 已提交
2879 2880 2881 2882
    switch (protoidx) {
    case L2_PROTO_MAC_IDX:
        protostr = strdup("");
        break;
S
Stefan Berger 已提交
2883 2884 2885
    case L2_PROTO_STP_IDX:
        virAsprintf(&protostr, "-d " NWFILTER_MAC_BGA " ");
        break;
S
Stefan Berger 已提交
2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
    default:
        virAsprintf(&protostr, "-p 0x%04x ", l3_protocols[protoidx].attr);
        break;
    }

    if (!protostr) {
        virReportOOMError();
        return -1;
    }

2896
    virBufferAsprintf(&buf,
2897
                      CMD_DEF("$EBT -t nat -F %s") CMD_SEPARATOR
2898
                      CMD_EXEC
2899
                      CMD_DEF("$EBT -t nat -X %s") CMD_SEPARATOR
2900
                      CMD_EXEC
2901
                      CMD_DEF("$EBT -t nat -N %s") CMD_SEPARATOR
2902 2903
                      CMD_EXEC
                      "%s"
2904
                      CMD_DEF("$EBT -t nat -%%c %s %%s %s-j %s")
2905
                          CMD_SEPARATOR
2906 2907 2908
                      CMD_EXEC
                      "%s",

2909 2910 2911
                      chain,
                      chain,
                      chain,
2912 2913 2914

                      CMD_STOPONERR(stopOnError),

S
Stefan Berger 已提交
2915
                      rootchain, protostr, chain,
2916 2917 2918

                      CMD_STOPONERR(stopOnError));

S
Stefan Berger 已提交
2919 2920
    VIR_FREE(protostr);

2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
    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);

2937 2938 2939 2940
    return 0;
}

static int
2941 2942 2943
_ebtablesRemoveSubChains(virBufferPtr buf,
                         const char *ifname,
                         const char *chains)
2944
{
2945 2946
    char rootchain[MAX_CHAINNAME_LENGTH];
    unsigned i;
2947

2948 2949
    NWFILTER_SET_EBTABLES_SHELLVAR(buf);

2950
    virBufferAsprintf(buf, NWFILTER_FUNC_COLLECT_CHAINS,
2951 2952
                      chains);
    virBufferAdd(buf, NWFILTER_FUNC_RM_CHAINS, -1);
2953

2954 2955 2956 2957 2958 2959 2960
    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");
2961

2962 2963 2964
    for (i = 0; chains[i] != 0; i++) {
        PRINT_ROOT_CHAIN(rootchain, chains[i], ifname);
        virBufferAsprintf(buf,
2965
                          "$EBT -t nat -F %s\n",
2966 2967 2968
                          rootchain);
    }
    virBufferAddLit(buf, "rm_chains $chains\n");
2969 2970 2971 2972 2973

    return 0;
}

static int
2974 2975
ebtablesRemoveSubChains(virBufferPtr buf,
                        const char *ifname)
2976
{
2977 2978 2979 2980 2981
    char chains[3] = {
        CHAINPREFIX_HOST_IN,
        CHAINPREFIX_HOST_OUT,
        0
    };
2982

2983
    return _ebtablesRemoveSubChains(buf, ifname, chains);
2984 2985 2986
}

static int
2987
ebtablesRemoveTmpSubChains(virBufferPtr buf,
2988 2989
                           const char *ifname)
{
2990 2991 2992 2993 2994
    char chains[3] = {
        CHAINPREFIX_HOST_IN_TEMP,
        CHAINPREFIX_HOST_OUT_TEMP,
        0
    };
2995

2996
    return _ebtablesRemoveSubChains(buf, ifname, chains);
2997 2998 2999
}

static int
3000
ebtablesRenameTmpSubChain(virBufferPtr buf,
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
                          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);
    }

3019
    virBufferAsprintf(buf,
3020 3021
                      "$EBT -t nat -E %s %s" CMD_SEPARATOR,
                      tmpchain, chain);
3022 3023 3024 3025
    return 0;
}

static int
3026 3027
ebtablesRenameTmpRootChain(virBufferPtr buf,
                           int incoming,
3028 3029
                           const char *ifname)
{
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
    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};
3043

3044 3045
    NWFILTER_SET_EBTABLES_SHELLVAR(buf);

3046
    virBufferAsprintf(buf, NWFILTER_FUNC_COLLECT_CHAINS,
3047
                      chains);
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058
    virBufferAsprintf(buf, NWFILTER_FUNC_RENAME_CHAINS,
                      CHAINPREFIX_HOST_IN_TEMP,
                      CHAINPREFIX_HOST_IN,
                      CHAINPREFIX_HOST_OUT_TEMP,
                      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);
3059
    }
3060
    virBufferAddLit(buf, ")\"\n");
3061

3062
    virBufferAddLit(buf, "rename_chains $chains\n");
3063

3064 3065
    ebtablesRenameTmpRootChain(buf, 1, ifname);
    ebtablesRenameTmpRootChain(buf, 0, ifname);
3066

3067
    return 0;
3068 3069 3070
}

static void
3071
ebiptablesInstCommand(virBufferPtr buf,
3072 3073 3074 3075 3076 3077
                      const char *templ, char cmd, int pos,
                      int stopOnError)
{
    char position[10] = { 0 };
    if (pos >= 0)
        snprintf(position, sizeof(position), "%d", pos);
3078 3079
    virBufferAsprintf(buf, templ, cmd, position);
    virBufferAsprintf(buf, CMD_SEPARATOR "%s",
3080 3081 3082 3083
                      CMD_STOPONERR(stopOnError));
}


3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
/**
 * 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);
}

3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109
/**
 * 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
 */
3110
static int
3111 3112 3113 3114 3115 3116 3117 3118
ebtablesApplyBasicRules(const char *ifname,
                        const unsigned char *macaddr)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = CHAINPREFIX_HOST_IN_TEMP;
    char macaddr_str[VIR_MAC_STRING_BUFLEN];

3119 3120 3121 3122 3123 3124 3125
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

3126 3127
    virFormatMacAddr(macaddr, macaddr_str);

3128
    ebiptablesAllTeardown(ifname);
3129

3130 3131
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3132 3133 3134
    ebtablesCreateTmpRootChain(&buf, 1, ifname, 1);

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);
3135
    virBufferAsprintf(&buf,
3136
                      CMD_DEF("$EBT -t nat -A %s -s ! %s -j DROP") CMD_SEPARATOR
3137 3138 3139
                      CMD_EXEC
                      "%s",

3140
                      chain, macaddr_str,
3141 3142
                      CMD_STOPONERR(1));

3143
    virBufferAsprintf(&buf,
3144
                      CMD_DEF("$EBT -t nat -A %s -p IPv4 -j ACCEPT") CMD_SEPARATOR
3145 3146 3147
                      CMD_EXEC
                      "%s",

3148
                      chain,
3149 3150
                      CMD_STOPONERR(1));

3151
    virBufferAsprintf(&buf,
3152
                      CMD_DEF("$EBT -t nat -A %s -p ARP -j ACCEPT") CMD_SEPARATOR
3153 3154 3155
                      CMD_EXEC
                      "%s",

3156
                      chain,
3157 3158
                      CMD_STOPONERR(1));

3159
    virBufferAsprintf(&buf,
3160
                      CMD_DEF("$EBT -t nat -A %s -j DROP") CMD_SEPARATOR
3161 3162 3163
                      CMD_EXEC
                      "%s",

3164
                      chain,
3165 3166 3167
                      CMD_STOPONERR(1));

    ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
3168
    ebtablesRenameTmpRootChain(&buf, 1, ifname);
3169

3170
    if (ebiptablesExecCLI(&buf, NULL, NULL) < 0)
3171 3172 3173 3174 3175
        goto tear_down_tmpebchains;

    return 0;

tear_down_tmpebchains:
3176
    ebtablesCleanAll(ifname);
3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193

    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
3194 3195 3196
 * @leaveTemporary: Whether to leave the table names with their temporary
 *    names (true) or also perform the renaming to their final names as
 *    part of this call (false)
3197 3198 3199 3200 3201 3202
 *
 * 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.
 */
3203
static int
3204 3205
ebtablesApplyDHCPOnlyRules(const char *ifname,
                           const unsigned char *macaddr,
3206 3207
                           const char *dhcpserver,
                           bool leaveTemporary)
3208 3209 3210 3211 3212 3213 3214
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char chain_in [MAX_CHAINNAME_LENGTH],
         chain_out[MAX_CHAINNAME_LENGTH];
    char macaddr_str[VIR_MAC_STRING_BUFLEN];
    char *srcIPParam = NULL;

3215 3216 3217 3218 3219 3220 3221
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

3222
    if (dhcpserver) {
3223
        virBufferAsprintf(&buf, " --ip-src %s", dhcpserver);
3224 3225 3226 3227 3228 3229 3230
        if (virBufferError(&buf))
            return 1;
        srcIPParam = virBufferContentAndReset(&buf);
    }

    virFormatMacAddr(macaddr, macaddr_str);

3231
    ebiptablesAllTeardown(ifname);
3232

3233 3234
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3235 3236 3237 3238 3239 3240
    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);

3241
    virBufferAsprintf(&buf,
3242
                      CMD_DEF("$EBT -t nat -A %s"
3243 3244 3245 3246 3247 3248 3249 3250
                              " -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",

3251
                      chain_in,
3252 3253 3254
                      macaddr_str,
                      CMD_STOPONERR(1));

3255
    virBufferAsprintf(&buf,
3256
                      CMD_DEF("$EBT -t nat -A %s -j DROP") CMD_SEPARATOR
3257 3258 3259
                      CMD_EXEC
                      "%s",

3260
                      chain_in,
3261 3262
                      CMD_STOPONERR(1));

3263
    virBufferAsprintf(&buf,
3264
                      CMD_DEF("$EBT -t nat -A %s"
3265 3266 3267 3268 3269 3270 3271 3272
                              " -d %s"
                              " -p ipv4 --ip-protocol udp"
                              " %s"
                              " --ip-sport 67 --ip-dport 68"
                              " -j ACCEPT") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

3273
                      chain_out,
3274 3275 3276 3277
                      macaddr_str,
                      srcIPParam != NULL ? srcIPParam : "",
                      CMD_STOPONERR(1));

3278
    virBufferAsprintf(&buf,
3279
                      CMD_DEF("$EBT -t nat -A %s -j DROP") CMD_SEPARATOR
3280 3281 3282
                      CMD_EXEC
                      "%s",

3283
                      chain_out,
3284 3285 3286 3287
                      CMD_STOPONERR(1));

    ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
    ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
3288 3289 3290 3291 3292

    if (!leaveTemporary) {
        ebtablesRenameTmpRootChain(&buf, 1, ifname);
        ebtablesRenameTmpRootChain(&buf, 0, ifname);
    }
3293

3294
    if (ebiptablesExecCLI(&buf, NULL, NULL) < 0)
3295 3296 3297 3298 3299 3300 3301
        goto tear_down_tmpebchains;

    VIR_FREE(srcIPParam);

    return 0;

tear_down_tmpebchains:
3302
    ebtablesCleanAll(ifname);
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313

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

    VIR_FREE(srcIPParam);

    return 1;
}


3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336
/**
 * 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;
    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;
    }

3337
    ebiptablesAllTeardown(ifname);
3338

3339 3340
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3341 3342 3343 3344 3345 3346
    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);

3347
    virBufferAsprintf(&buf,
3348
                      CMD_DEF("$EBT -t nat -A %s -j DROP") CMD_SEPARATOR
3349 3350 3351
                      CMD_EXEC
                      "%s",

3352
                      chain_in,
3353 3354
                      CMD_STOPONERR(1));

3355
    virBufferAsprintf(&buf,
3356
                      CMD_DEF("$EBT -t nat -A %s -j DROP") CMD_SEPARATOR
3357 3358 3359
                      CMD_EXEC
                      "%s",

3360
                      chain_out,
3361 3362 3363 3364 3365 3366 3367
                      CMD_STOPONERR(1));

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

3368
    if (ebiptablesExecCLI(&buf, NULL, NULL) < 0)
3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
        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;
}


3384
static int
3385
ebtablesRemoveBasicRules(const char *ifname)
3386 3387 3388 3389 3390 3391
{
    return ebtablesCleanAll(ifname);
}


static int ebtablesCleanAll(const char *ifname)
3392 3393 3394 3395
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;

3396 3397 3398
    if (!ebtables_cmd_path)
        return 0;

3399 3400
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3401 3402 3403 3404 3405 3406
    ebtablesUnlinkRootChain(&buf, 1, ifname);
    ebtablesUnlinkRootChain(&buf, 0, ifname);
    ebtablesRemoveSubChains(&buf, ifname);
    ebtablesRemoveRootChain(&buf, 1, ifname);
    ebtablesRemoveRootChain(&buf, 0, ifname);

3407 3408 3409 3410 3411 3412
    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);

3413
    ebiptablesExecCLI(&buf, &cli_status, NULL);
3414 3415 3416 3417
    return 0;
}


3418 3419
static int
ebiptablesRuleOrderSort(const void *a, const void *b)
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445
{
    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)
3446 3447 3448
{
    const ebiptablesRuleInstPtr *insta = a;
    const ebiptablesRuleInstPtr *instb = b;
3449
    return ebiptablesRuleOrderSort(*insta, *instb);
3450 3451
}

3452 3453 3454 3455 3456 3457 3458 3459
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;
}
3460

3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
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);
3487
                    VIR_WARN("%s", msg);
3488 3489 3490 3491 3492 3493
                    if (isIPv6)
                        lastReportIPv6 = now;
                    else
                        lastReport = now;
                }
            }
3494
            VIR_FORCE_CLOSE(fd);
3495 3496 3497 3498
        }
    }
}

3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
/*
 * 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,
3520 3521 3522
                                  virHashTablePtr chains, int direction,
                                  ebiptablesRuleInstPtr *inst,
                                  int *nRuleInstances)
3523 3524 3525
{
    int rc = 0, i;
    virHashKeyValuePairPtr filter_names;
3526
    const virNWFilterChainPriority *priority;
3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540

    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;
3541 3542 3543 3544 3545
        priority = (const virNWFilterChainPriority *)filter_names[i].value;
        rc = ebtablesCreateTmpSubChain(inst, nRuleInstances,
                                       direction, ifname, idx,
                                       filter_names[i].key, 1,
                                       *priority);
3546 3547 3548 3549 3550 3551 3552
        if (rc < 0)
            break;
    }

    VIR_FREE(filter_names);
    return rc;
}
3553

3554
static int
3555
ebiptablesApplyNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3556 3557 3558 3559
                        const char *ifname,
                        int nruleInstances,
                        void **_inst)
{
3560
    int i, j;
3561 3562 3563
    int cli_status;
    ebiptablesRuleInstPtr *inst = (ebiptablesRuleInstPtr *)_inst;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
3564 3565
    virHashTablePtr chains_in_set  = virHashCreate(10, NULL);
    virHashTablePtr chains_out_set = virHashCreate(10, NULL);
3566 3567
    bool haveIptables = false;
    bool haveIp6tables = false;
3568 3569
    ebiptablesRuleInstPtr ebtChains = NULL;
    int nEbtChains = 0;
3570
    char *errmsg = NULL;
3571

3572 3573 3574 3575 3576
    if (!chains_in_set || !chains_out_set) {
        virReportOOMError();
        goto exit_free_sets;
    }

3577
    if (nruleInstances > 1 && inst)
3578 3579
        qsort(inst, nruleInstances, sizeof(inst[0]),
              ebiptablesRuleOrderSortPtr);
3580

3581
    /* scan the rules to see which chains need to be created */
3582
    for (i = 0; i < nruleInstances; i++) {
3583
        sa_assert (inst);
S
Stefan Berger 已提交
3584
        if (inst[i]->ruleType == RT_EBTABLES) {
3585
            const char *name = inst[i]->neededProtocolChain;
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
            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 已提交
3599
        }
3600 3601
    }

3602

3603
    /* cleanup whatever may exist */
3604
    if (ebtables_cmd_path) {
3605 3606
        NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3607 3608 3609 3610 3611
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
3612
        ebiptablesExecCLI(&buf, &cli_status, NULL);
3613
    }
3614

3615 3616
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3617
    /* create needed chains */
3618 3619 3620 3621
    if (ebtablesCreateTmpRootAndSubChains(&buf, ifname, chains_in_set , 1,
                                          &ebtChains, &nEbtChains) ||
        ebtablesCreateTmpRootAndSubChains(&buf, ifname, chains_out_set, 0,
                                          &ebtChains, &nEbtChains)) {
3622 3623
        goto tear_down_tmpebchains;
    }
3624

3625 3626 3627 3628
    if (nEbtChains > 0)
        qsort(&ebtChains[0], nEbtChains, sizeof(ebtChains[0]),
              ebiptablesRuleOrderSort);

3629
    if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
3630 3631
        goto tear_down_tmpebchains;

3632 3633
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3634 3635 3636
    /* process ebtables commands; interleave commands from filters with
       commands for creating and connecting ebtables chains */
    j = 0;
3637
    for (i = 0; i < nruleInstances; i++) {
3638
        sa_assert (inst);
S
Stefan Berger 已提交
3639 3640
        switch (inst[i]->ruleType) {
        case RT_EBTABLES:
3641 3642 3643 3644 3645 3646
            while (j < nEbtChains &&
                   ebtChains[j].priority <= inst[i]->priority) {
                ebiptablesInstCommand(&buf,
                                      ebtChains[j++].commandTemplate,
                                      'A', -1, 1);
            }
3647
            ebiptablesInstCommand(&buf,
S
Stefan Berger 已提交
3648 3649 3650 3651
                                  inst[i]->commandTemplate,
                                  'A', -1, 1);
        break;
        case RT_IPTABLES:
3652
            haveIptables = true;
S
Stefan Berger 已提交
3653
        break;
3654
        case RT_IP6TABLES:
3655
            haveIp6tables = true;
3656
        break;
S
Stefan Berger 已提交
3657
        }
3658
    }
3659

3660 3661 3662 3663 3664
    while (j < nEbtChains)
        ebiptablesInstCommand(&buf,
                              ebtChains[j++].commandTemplate,
                              'A', -1, 1);

3665
    if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
3666 3667
        goto tear_down_tmpebchains;

S
Stefan Berger 已提交
3668
    if (haveIptables) {
3669 3670 3671 3672
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

        iptablesUnlinkTmpRootChains(&buf, ifname);
        iptablesRemoveTmpRootChains(&buf, ifname);
S
Stefan Berger 已提交
3673

3674
        iptablesCreateBaseChains(&buf);
S
Stefan Berger 已提交
3675

3676
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
S
Stefan Berger 已提交
3677 3678
            goto tear_down_tmpebchains;

3679 3680 3681
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

        iptablesCreateTmpRootChains(&buf, ifname);
S
Stefan Berger 已提交
3682

3683
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
S
Stefan Berger 已提交
3684 3685
           goto tear_down_tmpiptchains;

3686 3687 3688 3689
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

        iptablesLinkTmpRootChains(&buf, ifname);
        iptablesSetupVirtInPost(&buf, ifname);
3690
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
S
Stefan Berger 已提交
3691 3692
           goto tear_down_tmpiptchains;

3693 3694
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

S
Stefan Berger 已提交
3695
        for (i = 0; i < nruleInstances; i++) {
3696
            sa_assert (inst);
S
Stefan Berger 已提交
3697
            if (inst[i]->ruleType == RT_IPTABLES)
3698
                iptablesInstCommand(&buf,
S
Stefan Berger 已提交
3699 3700 3701 3702
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3703
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
S
Stefan Berger 已提交
3704
           goto tear_down_tmpiptchains;
3705 3706

        iptablesCheckBridgeNFCallEnabled(false);
S
Stefan Berger 已提交
3707 3708
    }

3709
    if (haveIp6tables) {
3710 3711 3712 3713
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

        iptablesUnlinkTmpRootChains(&buf, ifname);
        iptablesRemoveTmpRootChains(&buf, ifname);
3714

3715
        iptablesCreateBaseChains(&buf);
3716

3717
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
3718 3719
            goto tear_down_tmpiptchains;

3720 3721 3722
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

        iptablesCreateTmpRootChains(&buf, ifname);
3723

3724
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
3725 3726
           goto tear_down_tmpip6tchains;

3727 3728 3729 3730
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

        iptablesLinkTmpRootChains(&buf, ifname);
        iptablesSetupVirtInPost(&buf, ifname);
3731
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
3732 3733
           goto tear_down_tmpip6tchains;

3734 3735
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

3736 3737
        for (i = 0; i < nruleInstances; i++) {
            if (inst[i]->ruleType == RT_IP6TABLES)
3738
                iptablesInstCommand(&buf,
3739 3740 3741 3742
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3743
        if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
3744
           goto tear_down_tmpip6tchains;
3745 3746

        iptablesCheckBridgeNFCallEnabled(true);
3747 3748
    }

3749 3750
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3751
    if (virHashSize(chains_in_set) != 0)
3752
        ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
3753
    if (virHashSize(chains_out_set) != 0)
3754
        ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
3755

3756
    if (ebiptablesExecCLI(&buf, NULL, &errmsg) < 0)
3757 3758
        goto tear_down_ebsubchains_and_unlink;

3759 3760 3761
    virHashFree(chains_in_set);
    virHashFree(chains_out_set);

3762 3763 3764 3765
    for (i = 0; i < nEbtChains; i++)
        VIR_FREE(ebtChains[i].commandTemplate);
    VIR_FREE(ebtChains);

3766 3767
    VIR_FREE(errmsg);

3768 3769 3770
    return 0;

tear_down_ebsubchains_and_unlink:
3771
    if (ebtables_cmd_path) {
3772 3773
        NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3774 3775 3776
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    }
3777

3778 3779
tear_down_tmpip6tchains:
    if (haveIp6tables) {
3780 3781 3782 3783
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

        iptablesUnlinkTmpRootChains(&buf, ifname);
        iptablesRemoveTmpRootChains(&buf, ifname);
3784 3785
    }

S
Stefan Berger 已提交
3786 3787
tear_down_tmpiptchains:
    if (haveIptables) {
3788 3789 3790 3791
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

        iptablesUnlinkTmpRootChains(&buf, ifname);
        iptablesRemoveTmpRootChains(&buf, ifname);
S
Stefan Berger 已提交
3792 3793
    }

3794
tear_down_tmpebchains:
3795
    if (ebtables_cmd_path) {
3796 3797
        NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3798 3799 3800 3801
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3802

3803
    ebiptablesExecCLI(&buf, &cli_status, NULL);
3804

3805
    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3806
                           _("Some rules could not be created for "
3807 3808 3809 3810
                             "interface %s%s%s"),
                           ifname,
                           errmsg ? ": " : "",
                           errmsg ? errmsg : "");
3811

3812 3813 3814 3815
exit_free_sets:
    virHashFree(chains_in_set);
    virHashFree(chains_out_set);

3816 3817 3818 3819
    for (i = 0; i < nEbtChains; i++)
        VIR_FREE(ebtChains[i].commandTemplate);
    VIR_FREE(ebtChains);

3820 3821
    VIR_FREE(errmsg);

3822 3823 3824 3825 3826
    return 1;
}


static int
3827
ebiptablesTearNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3828 3829 3830 3831 3832
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

3833
    if (iptables_cmd_path) {
3834 3835 3836 3837
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

        iptablesUnlinkTmpRootChains(&buf, ifname);
        iptablesRemoveTmpRootChains(&buf, ifname);
3838
    }
3839

3840
    if (ip6tables_cmd_path) {
3841 3842 3843 3844
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

        iptablesUnlinkTmpRootChains(&buf, ifname);
        iptablesRemoveTmpRootChains(&buf, ifname);
3845
    }
S
Stefan Berger 已提交
3846

3847
    if (ebtables_cmd_path) {
3848 3849
        NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3850 3851
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
3852

3853 3854 3855 3856
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3857

3858
    ebiptablesExecCLI(&buf, &cli_status, NULL);
3859 3860 3861 3862 3863 3864

    return 0;
}


static int
3865
ebiptablesTearOldRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3866 3867 3868 3869 3870
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

3871
    /* switch to new iptables user defined chains */
3872
    if (iptables_cmd_path) {
3873 3874 3875 3876
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

        iptablesUnlinkRootChains(&buf, ifname);
        iptablesRemoveRootChains(&buf, ifname);
S
Stefan Berger 已提交
3877

3878
        iptablesRenameTmpRootChains(&buf, ifname);
3879
        ebiptablesExecCLI(&buf, &cli_status, NULL);
3880
    }
3881

3882
    if (ip6tables_cmd_path) {
3883
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);
3884

3885 3886 3887 3888
        iptablesUnlinkRootChains(&buf, ifname);
        iptablesRemoveRootChains(&buf, ifname);

        iptablesRenameTmpRootChains(&buf, ifname);
3889
        ebiptablesExecCLI(&buf, &cli_status, NULL);
3890
    }
S
Stefan Berger 已提交
3891

3892
    if (ebtables_cmd_path) {
3893 3894
        NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3895 3896
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3897

3898
        ebtablesRemoveSubChains(&buf, ifname);
3899

3900 3901
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
3902

3903
        ebtablesRenameTmpSubAndRootChains(&buf, ifname);
3904

3905
        ebiptablesExecCLI(&buf, &cli_status, NULL);
3906
    }
3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924

    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
3925
ebiptablesRemoveRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3926 3927 3928 3929 3930 3931 3932 3933 3934 3935
                      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;

3936 3937
    NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3938
    for (i = 0; i < nruleInstances; i++)
3939
        ebiptablesInstCommand(&buf,
3940 3941 3942 3943
                              inst[i]->commandTemplate,
                              'D', -1,
                              0);

3944
    if (ebiptablesExecCLI(&buf, &cli_status, NULL))
3945 3946 3947
        goto err_exit;

    if (cli_status) {
3948
        virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973
                               "%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;

3974
    if (iptables_cmd_path) {
3975 3976 3977 3978 3979
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

        iptablesUnlinkRootChains(&buf, ifname);
        iptablesClearVirtInPost (&buf, ifname);
        iptablesRemoveRootChains(&buf, ifname);
3980
    }
3981

3982
    if (ip6tables_cmd_path) {
3983 3984 3985 3986 3987
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

        iptablesUnlinkRootChains(&buf, ifname);
        iptablesClearVirtInPost (&buf, ifname);
        iptablesRemoveRootChains(&buf, ifname);
3988
    }
S
Stefan Berger 已提交
3989

3990
    if (ebtables_cmd_path) {
3991 3992
        NWFILTER_SET_EBTABLES_SHELLVAR(&buf);

3993 3994
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3995

3996 3997
        ebtablesRemoveSubChains(&buf, ifname);

3998 3999 4000
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
    }
4001
    ebiptablesExecCLI(&buf, &cli_status, NULL);
4002 4003 4004 4005 4006 4007 4008

    return 0;
}


virNWFilterTechDriver ebiptables_driver = {
    .name = EBIPTABLES_DRIVER_ID,
4009 4010 4011 4012
    .flags = 0,

    .init     = ebiptablesDriverInit,
    .shutdown = ebiptablesDriverShutdown,
4013

4014
    .createRuleInstance  = ebiptablesCreateRuleInstanceIterate,
4015 4016 4017 4018 4019 4020 4021
    .applyNewRules       = ebiptablesApplyNewRules,
    .tearNewRules        = ebiptablesTearNewRules,
    .tearOldRules        = ebiptablesTearOldRules,
    .allTeardown         = ebiptablesAllTeardown,
    .removeRules         = ebiptablesRemoveRules,
    .freeRuleInstance    = ebiptablesFreeRuleInstance,
    .displayRuleInstance = ebiptablesDisplayRuleInstance,
4022 4023 4024 4025

    .canApplyBasicRules  = ebiptablesCanApplyBasicRules,
    .applyBasicRules     = ebtablesApplyBasicRules,
    .applyDHCPOnlyRules  = ebtablesApplyDHCPOnlyRules,
4026
    .applyDropAllRules   = ebtablesApplyDropAllRules,
4027
    .removeBasicRules    = ebtablesRemoveBasicRules,
4028
};
4029 4030 4031


static int
4032
ebiptablesDriverInit(bool privileged)
4033 4034 4035
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

4036 4037 4038
    if (!privileged)
        return 0;

4039 4040 4041
    if (virMutexInit(&execCLIMutex))
        return EINVAL;

4042 4043 4044 4045 4046
    gawk_cmd_path = virFindFileInPath("gawk");
    grep_cmd_path = virFindFileInPath("grep");

    ebtables_cmd_path = virFindFileInPath("ebtables");
    if (ebtables_cmd_path) {
4047
        NWFILTER_SET_EBTABLES_SHELLVAR(&buf);
4048
        /* basic probing */
4049
        virBufferAsprintf(&buf,
4050
                          CMD_DEF("$EBT -t nat -L") CMD_SEPARATOR
4051 4052 4053 4054
                          CMD_EXEC
                          "%s",
                          CMD_STOPONERR(1));

4055
        if (ebiptablesExecCLI(&buf, NULL, NULL) < 0)
4056 4057 4058 4059 4060
             VIR_FREE(ebtables_cmd_path);
    }

    iptables_cmd_path = virFindFileInPath("iptables");
    if (iptables_cmd_path) {
4061 4062
        NWFILTER_SET_IPTABLES_SHELLVAR(&buf);

4063
        virBufferAsprintf(&buf,
4064
                          CMD_DEF("$IPT -n -L FORWARD") CMD_SEPARATOR
4065 4066 4067 4068
                          CMD_EXEC
                          "%s",
                          CMD_STOPONERR(1));

4069
        if (ebiptablesExecCLI(&buf, NULL, NULL) < 0)
4070 4071 4072 4073 4074
             VIR_FREE(iptables_cmd_path);
    }

    ip6tables_cmd_path = virFindFileInPath("ip6tables");
    if (ip6tables_cmd_path) {
4075 4076
        NWFILTER_SET_IP6TABLES_SHELLVAR(&buf);

4077
        virBufferAsprintf(&buf,
4078
                          CMD_DEF("$IPT -n -L FORWARD") CMD_SEPARATOR
4079 4080 4081 4082
                          CMD_EXEC
                          "%s",
                          CMD_STOPONERR(1));

4083
        if (ebiptablesExecCLI(&buf, NULL, NULL) < 0)
4084 4085 4086
             VIR_FREE(ip6tables_cmd_path);
    }

4087
    /* ip(6)tables support needs gawk & grep, ebtables doesn't */
4088
    if ((iptables_cmd_path != NULL || ip6tables_cmd_path != NULL) &&
4089
        (!grep_cmd_path || !gawk_cmd_path)) {
4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
        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
4113
ebiptablesDriverShutdown(void)
4114 4115 4116 4117 4118 4119 4120 4121
{
    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;
}