nwfilter_ebiptables_driver.c 116.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * nwfilter_ebiptables_driver.c: driver for ebtables/iptables on tap devices
 *
 * 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>

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

#include "internal.h"

#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "virterror_internal.h"
#include "domain_conf.h"
37
#include "nwfilter_conf.h"
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include "nwfilter_gentech_driver.h"
#include "nwfilter_ebiptables_driver.h"


#define VIR_FROM_THIS VIR_FROM_NWFILTER


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

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


#define CMD_SEPARATOR "\n"
56 57
#define CMD_DEF_PRE  "cmd='"
#define CMD_DEF_POST "'"
58
#define CMD_DEF(X) CMD_DEF_PRE X CMD_DEF_POST
59
#define CMD_EXEC   "eval res=\\`\"${cmd}\"\\`" CMD_SEPARATOR
60 61 62 63 64 65 66 67
#define CMD_STOPONERR(X) \
    X ? "if [ $? -ne 0 ]; then" \
        "  echo \"Failure to execute command '${cmd}'.\";" \
        "  exit 1;" \
        "fi" CMD_SEPARATOR \
      : ""


68 69 70 71 72 73 74
#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 */

75 76 77 78 79 80 81
static char *ebtables_cmd_path;
static char *iptables_cmd_path;
static char *ip6tables_cmd_path;
static char *bash_cmd_path;
static char *grep_cmd_path;
static char *gawk_cmd_path;

82 83 84 85 86 87 88

#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)


S
Stefan Berger 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
#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

110
#define COMMENT_VARNAME "comment"
S
Stefan Berger 已提交
111

112
static int ebtablesRemoveBasicRules(const char *ifname);
113 114
static int ebiptablesDriverInit(void);
static void ebiptablesDriverShutdown(void);
115
static int ebtablesCleanAll(const char *ifname);
116

117
static virMutex execCLIMutex;
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
struct ushort_map {
    unsigned short attr;
    const char *val;
};


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

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

static const struct ushort_map l3_protocols[] = {
    USHORTMAP_ENTRY_IDX(L3_PROTO_IPV4_IDX, ETHERTYPE_IP    , "ipv4"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_IPV6_IDX, ETHERTYPE_IPV6  , "ipv6"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_ARP_IDX , ETHERTYPE_ARP   , "arp"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_RARP_IDX, ETHERTYPE_REVARP, "rarp"),
    USHORTMAP_ENTRY_IDX(L3_PROTO_LAST_IDX, 0               , NULL),
141 142 143 144
};


static int
145
printVar(virNWFilterHashTablePtr vars,
146 147 148 149 150 151 152 153 154
         char *buf, int bufsize,
         nwItemDescPtr item,
         int *done)
{
    *done = 0;

    if ((item->flags & NWFILTER_ENTRY_ITEM_FLAG_HAS_VAR)) {
        char *val = (char *)virHashLookup(vars->hashTable, item->var);
        if (!val) {
155
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
156 157 158 159 160 161
                                   _("cannot find value for '%s'"),
                                   item->var);
            return 1;
        }

        if (!virStrcpy(buf, val, bufsize)) {
162
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
163 164 165 166 167 168 169 170 171 172 173 174 175
                                   _("Buffer to small to print MAC address "
                                   "'%s' into"),
                                   item->var);
            return 1;
        }

        *done = 1;
    }
    return 0;
}


static int
176
_printDataType(virNWFilterHashTablePtr vars,
177 178 179
               char *buf, int bufsize,
               nwItemDescPtr item,
               bool asHex)
180 181
{
    int done;
182
    char *data;
183

184
    if (printVar(vars, buf, bufsize, item, &done))
185 186 187 188 189 190 191
        return 1;

    if (done)
        return 0;

    switch (item->datatype) {
    case DATATYPE_IPADDR:
192 193
        data = virSocketFormatAddr(&item->u.ipaddr.addr);
        if (!data) {
194
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
195 196 197 198 199
                                   _("internal IPv4 address representation "
                                     "is bad"));
            return 1;
        }
        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
200
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
201 202
                                   _("buffer too small for IP address"));
            VIR_FREE(data);
203 204
            return 1;
        }
205
        VIR_FREE(data);
206 207
    break;

208
    case DATATYPE_IPV6ADDR:
209 210
        data = virSocketFormatAddr(&item->u.ipaddr.addr);
        if (!data) {
211
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
212 213 214 215 216 217
                                   _("internal IPv6 address representation "
                                     "is bad"));
            return 1;
        }

        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
218
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
219 220 221
                                   _("buffer too small for IPv6 address"));
            VIR_FREE(data);
            return 1;
222
        }
223
        VIR_FREE(data);
224 225
    break;

226
    case DATATYPE_MACADDR:
227
    case DATATYPE_MACMASK:
228
        if (bufsize < VIR_MAC_STRING_BUFLEN) {
229
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
230 231 232 233 234 235 236
                                   _("Buffer too small for MAC address"));
            return 1;
        }

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

237 238
    case DATATYPE_IPV6MASK:
    case DATATYPE_IPMASK:
239
        if (snprintf(buf, bufsize, "%d",
240
                     item->u.u8) >= bufsize) {
241
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
242 243 244 245 246 247
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT16:
248
    case DATATYPE_UINT16_HEX:
249
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
250
                     item->u.u16) >= bufsize) {
251
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
252 253 254 255 256 257
                                   _("Buffer too small for uint16 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT8:
258
    case DATATYPE_UINT8_HEX:
259
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
260
                     item->u.u8) >= bufsize) {
261
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
262 263 264 265 266 267
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    default:
268
        virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
269 270 271 272 273 274 275 276 277
                               _("Unhandled datatype %x"), item->datatype);
        return 1;
    break;
    }

    return 0;
}


278
static int
279
printDataType(virNWFilterHashTablePtr vars,
280 281 282
              char *buf, int bufsize,
              nwItemDescPtr item)
{
283
    return _printDataType(vars, buf, bufsize, item, 0);
284 285 286 287
}


static int
288
printDataTypeAsHex(virNWFilterHashTablePtr vars,
289 290 291
                   char *buf, int bufsize,
                   nwItemDescPtr item)
{
292
    return _printDataType(vars, buf, bufsize, item, 1);
293 294 295
}


296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
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 已提交
316 317 318 319 320 321 322 323 324 325 326 327
static void
ebiptablesRuleInstFree(ebiptablesRuleInstPtr inst)
{
    if (!inst)
        return;

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


static int
328
ebiptablesAddRuleInst(virNWFilterRuleInstPtr res,
S
Stefan Berger 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
                      char *commandTemplate,
                      enum virNWFilterChainSuffixType neededChain,
                      char chainprefix,
                      unsigned int priority,
                      enum RuleType ruleType)
{
    ebiptablesRuleInstPtr inst;

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

    inst->commandTemplate = commandTemplate;
    inst->neededProtocolChain = neededChain;
    inst->chainprefix = chainprefix;
    inst->priority = priority;
    inst->ruleType = ruleType;

348
    return virNWFilterRuleInstAddData(res, inst);
S
Stefan Berger 已提交
349 350 351 352
}


static int
353
ebtablesHandleEthHdr(virBufferPtr buf,
S
Stefan Berger 已提交
354
                     virNWFilterHashTablePtr vars,
355 356
                     ethHdrDataDefPtr ethHdr,
                     bool reverse)
S
Stefan Berger 已提交
357 358 359 360
{
    char macaddr[VIR_MAC_STRING_BUFLEN];

    if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACAddr)) {
361
        if (printDataType(vars,
S
Stefan Berger 已提交
362 363 364 365 366
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataSrcMACAddr))
            goto err_exit;

        virBufferVSprintf(buf,
367 368
                      " %s %s %s",
                      reverse ? "-d" : "-s",
S
Stefan Berger 已提交
369 370 371 372
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataSrcMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACMask)) {
373
            if (printDataType(vars,
S
Stefan Berger 已提交
374 375 376 377 378 379 380 381 382 383 384
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataSrcMACMask))
                goto err_exit;

            virBufferVSprintf(buf,
                              "/%s",
                              macaddr);
        }
    }

    if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACAddr)) {
385
        if (printDataType(vars,
S
Stefan Berger 已提交
386 387 388 389 390
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataDstMACAddr))
            goto err_exit;

        virBufferVSprintf(buf,
391 392
                      " %s %s %s",
                      reverse ? "-s" : "-d",
S
Stefan Berger 已提交
393 394 395 396
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataDstMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACMask)) {
397
            if (printDataType(vars,
S
Stefan Berger 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataDstMACMask))
                goto err_exit;

            virBufferVSprintf(buf,
                              "/%s",
                              macaddr);
        }
    }

    return 0;

 err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


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

419
static int iptablesLinkIPTablesBaseChain(const char *iptables_cmd,
S
Stefan Berger 已提交
420 421 422 423 424 425 426
                                         virBufferPtr buf,
                                         const char *udchain,
                                         const char *syschain,
                                         unsigned int pos,
                                         int stopOnError)
{
    virBufferVSprintf(buf,
427
                      "res=$(%s -L %s -n --line-number | "
428
                          "%s \" %s \")\n"
S
Stefan Berger 已提交
429
                      "if [ $? -ne 0 ]; then\n"
430
                      "  %s -I %s %d -j %s\n"
S
Stefan Berger 已提交
431
                      "else\n"
432
                      "  r=$(echo $res | %s '{print $1}')\n"
S
Stefan Berger 已提交
433
                      "  if [ \"${r}\" != \"%d\" ]; then\n"
434
                      "    " CMD_DEF("%s -I %s %d -j %s") CMD_SEPARATOR
S
Stefan Berger 已提交
435 436 437
                      "    " CMD_EXEC
                      "    %s"
                      "    let r=r+1\n"
438
                      "    " CMD_DEF("%s -D %s ${r}") CMD_SEPARATOR
S
Stefan Berger 已提交
439 440 441 442 443
                      "    " CMD_EXEC
                      "    %s"
                      "  fi\n"
                      "fi\n",

444
                      iptables_cmd, syschain,
445
                      grep_cmd_path, udchain,
S
Stefan Berger 已提交
446

447
                      iptables_cmd, syschain, pos, udchain,
448
                      gawk_cmd_path,
S
Stefan Berger 已提交
449 450 451

                      pos,

452
                      iptables_cmd, syschain, pos, udchain,
S
Stefan Berger 已提交
453 454
                      CMD_STOPONERR(stopOnError),

455
                      iptables_cmd, syschain,
S
Stefan Berger 已提交
456 457 458 459 460
                      CMD_STOPONERR(stopOnError));
    return 0;
}


461
static int iptablesCreateBaseChains(const char *iptables_cmd,
S
Stefan Berger 已提交
462 463
                                    virBufferPtr buf)
{
464 465 466 467 468 469 470 471
    virBufferVSprintf(buf,"%s -N " VIRT_IN_CHAIN      CMD_SEPARATOR
                          "%s -N " VIRT_OUT_CHAIN     CMD_SEPARATOR
                          "%s -N " VIRT_IN_POST_CHAIN CMD_SEPARATOR
                          "%s -N " HOST_IN_CHAIN      CMD_SEPARATOR,
                          iptables_cmd,
                          iptables_cmd,
                          iptables_cmd,
                          iptables_cmd);
472
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
473
                                  VIRT_IN_CHAIN     , "FORWARD", 1, 1);
474
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
475
                                  VIRT_OUT_CHAIN    , "FORWARD", 2, 1);
476
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
477
                                  VIRT_IN_POST_CHAIN, "FORWARD", 3, 1);
478
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
479 480 481 482 483 484 485
                                  HOST_IN_CHAIN     , "INPUT"  , 1, 1);

    return 0;
}


static int
486
iptablesCreateTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
                           virBufferPtr buf,
                           char prefix,
                           int incoming, const char *ifname,
                           int stopOnError)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix[2] = {
       prefix,
       (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                  : CHAINPREFIX_HOST_OUT_TEMP
    };

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    virBufferVSprintf(buf,
502
                      CMD_DEF("%s -N %s") CMD_SEPARATOR
S
Stefan Berger 已提交
503 504
                      CMD_EXEC
                      "%s",
505
                      iptables_cmd,
S
Stefan Berger 已提交
506 507 508 509 510 511 512 513
                      chain,
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
514
iptablesCreateTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
515 516 517
                            virBufferPtr buf,
                            const char *ifname)
{
518 519 520
    iptablesCreateTmpRootChain(iptables_cmd, buf, 'F', 0, ifname, 1);
    iptablesCreateTmpRootChain(iptables_cmd, buf, 'F', 1, ifname, 1);
    iptablesCreateTmpRootChain(iptables_cmd, buf, 'H', 1, ifname, 1);
S
Stefan Berger 已提交
521 522 523 524 525
    return 0;
}


static int
526
_iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
                         virBufferPtr buf,
                         char prefix,
                         int incoming, const char *ifname,
                         int isTempChain)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix[2] = {
        prefix,
    };

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

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    virBufferVSprintf(buf,
547 548 549 550
                      "%s -F %s" CMD_SEPARATOR
                      "%s -X %s" CMD_SEPARATOR,
                      iptables_cmd, chain,
                      iptables_cmd, chain);
S
Stefan Berger 已提交
551 552 553 554 555 556

    return 0;
}


static int
557
iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
558 559 560 561 562
                        virBufferPtr buf,
                        char prefix,
                        int incoming,
                        const char *ifname)
{
563
    return _iptablesRemoveRootChain(iptables_cmd,
564
                                    buf, prefix, incoming, ifname, 0);
S
Stefan Berger 已提交
565 566 567 568
}


static int
569
iptablesRemoveTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
570 571 572 573 574
                           virBufferPtr buf,
                           char prefix,
                           int incoming,
                           const char *ifname)
{
575
    return _iptablesRemoveRootChain(iptables_cmd, buf, prefix,
576
                                    incoming, ifname, 1);
S
Stefan Berger 已提交
577 578 579 580
}


static int
581
iptablesRemoveTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
582 583 584
                            virBufferPtr buf,
                            const char *ifname)
{
585 586 587
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
588 589 590 591 592
    return 0;
}


static int
593
iptablesRemoveRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
594 595 596
                         virBufferPtr buf,
                         const char *ifname)
{
597 598 599
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
600 601 602 603 604
    return 0;
}


static int
605
iptablesLinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
                         virBufferPtr buf,
                         const char *basechain,
                         char prefix,
                         int incoming, const char *ifname,
                         int stopOnError)
{
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix[2] = {
        prefix,
        (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                   : CHAINPREFIX_HOST_OUT_TEMP
    };
    const char *match = (incoming) ? MATCH_PHYSDEV_IN
                                   : MATCH_PHYSDEV_OUT;

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    virBufferVSprintf(buf,
624
                      CMD_DEF("%s -A %s "
S
Stefan Berger 已提交
625 626 627
                              "%s %s -g %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",
628
                      iptables_cmd,
S
Stefan Berger 已提交
629 630 631 632 633 634 635 636 637 638
                      basechain,
                      match, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
639
iptablesLinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
640 641 642
                          virBufferPtr buf,
                          const char *ifname)
{
643 644 645
    iptablesLinkTmpRootChain(cmd, buf, VIRT_OUT_CHAIN, 'F', 0, ifname, 1);
    iptablesLinkTmpRootChain(cmd, buf, VIRT_IN_CHAIN , 'F', 1, ifname, 1);
    iptablesLinkTmpRootChain(cmd, buf, HOST_IN_CHAIN , 'H', 1, ifname, 1);
S
Stefan Berger 已提交
646 647 648 649 650 651

    return 0;
}


static int
652
iptablesSetupVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
653 654 655 656 657
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
    virBufferVSprintf(buf,
658
                      "res=$(%s -L " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
659 660
                      " | grep \"\\%s %s\")\n"
                      "if [ \"${res}\" == \"\" ]; then "
661
                        CMD_DEF("%s"
S
Stefan Berger 已提交
662 663 664 665 666
                        " -A " VIRT_IN_POST_CHAIN
                        " %s %s -j ACCEPT") CMD_SEPARATOR
                        CMD_EXEC
                        "%s"
                      "fi\n",
667
                      iptables_cmd,
S
Stefan Berger 已提交
668
                      PHYSDEV_IN, ifname,
669
                      iptables_cmd,
S
Stefan Berger 已提交
670 671 672 673 674 675 676
                      match, ifname,
                      CMD_STOPONERR(1));
    return 0;
}


static int
677
iptablesClearVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
678 679 680 681 682
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
    virBufferVSprintf(buf,
683
                      "%s -D " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
684
                      " %s %s -j ACCEPT" CMD_SEPARATOR,
685
                      iptables_cmd,
S
Stefan Berger 已提交
686 687 688 689 690
                      match, ifname);
    return 0;
}

static int
691 692 693 694 695 696
_iptablesUnlinkRootChain(const char *iptables_cmd,
                         virBufferPtr buf,
                         const char *basechain,
                         char prefix,
                         int incoming, const char *ifname,
                         int isTempChain)
S
Stefan Berger 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
{
    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);

    virBufferVSprintf(buf,
714
                      "%s -D %s "
S
Stefan Berger 已提交
715
                      "%s %s -g %s" CMD_SEPARATOR,
716
                      iptables_cmd,
S
Stefan Berger 已提交
717 718 719 720 721 722 723 724
                      basechain,
                      match, ifname, chain);

    return 0;
}


static int
725
iptablesUnlinkRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
726 727 728 729 730
                        virBufferPtr buf,
                        const char *basechain,
                        char prefix,
                        int incoming, const char *ifname)
{
731
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
732 733 734 735 736
                                    basechain, prefix, incoming, ifname, 0);
}


static int
737
iptablesUnlinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
738 739 740 741 742
                           virBufferPtr buf,
                           const char *basechain,
                           char prefix,
                           int incoming, const char *ifname)
{
743
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
744 745 746 747 748
                                    basechain, prefix, incoming, ifname, 1);
}


static int
749
iptablesUnlinkRootChains(const char *cmd,
S
Stefan Berger 已提交
750 751 752
                         virBufferPtr buf,
                         const char *ifname)
{
753 754 755
    iptablesUnlinkRootChain(cmd, buf, VIRT_OUT_CHAIN, 'F', 0, ifname);
    iptablesUnlinkRootChain(cmd, buf, VIRT_IN_CHAIN , 'F', 1, ifname);
    iptablesUnlinkRootChain(cmd, buf, HOST_IN_CHAIN , 'H', 1, ifname);
S
Stefan Berger 已提交
756 757 758 759 760 761

    return 0;
}


static int
762
iptablesUnlinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
763 764 765
                            virBufferPtr buf,
                            const char *ifname)
{
766 767 768
    iptablesUnlinkTmpRootChain(cmd, buf, VIRT_OUT_CHAIN, 'F', 0, ifname);
    iptablesUnlinkTmpRootChain(cmd, buf, VIRT_IN_CHAIN , 'F', 1, ifname);
    iptablesUnlinkTmpRootChain(cmd, buf, HOST_IN_CHAIN , 'H', 1, ifname);
S
Stefan Berger 已提交
769 770 771 772 773
    return 0;
}


static int
774
iptablesRenameTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
                           virBufferPtr buf,
                           char prefix,
                           int incoming,
                           const char *ifname)
{
    char tmpchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char tmpChainPrefix[2] = {
        prefix,
        (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                   : CHAINPREFIX_HOST_OUT_TEMP
    };
    char chainPrefix[2] = {
        prefix,
        (incoming) ? CHAINPREFIX_HOST_IN
                   : CHAINPREFIX_HOST_OUT
    };

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

    virBufferVSprintf(buf,
796 797
                      "%s -E %s %s" CMD_SEPARATOR,
                      iptables_cmd,
S
Stefan Berger 已提交
798 799 800 801 802 803 804
                      tmpchain,
                      chain);
    return 0;
}


static int
805
iptablesRenameTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
806 807 808
                            virBufferPtr buf,
                            const char *ifname)
{
809 810 811
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
812 813 814 815 816
    return 0;
}


static void
817
iptablesInstCommand(virBufferPtr buf,
S
Stefan Berger 已提交
818 819 820 821 822 823 824 825 826 827 828 829 830
                    const char *templ, char cmd, int pos,
                    int stopOnError)
{
    char position[10] = { 0 };
    if (pos >= 0)
        snprintf(position, sizeof(position), "%d", pos);
    virBufferVSprintf(buf, templ, cmd, position);
    virBufferVSprintf(buf, CMD_SEPARATOR "%s",
                      CMD_STOPONERR(stopOnError));
}


static int
831
iptablesHandleSrcMacAddr(virBufferPtr buf,
S
Stefan Berger 已提交
832 833
                         virNWFilterHashTablePtr vars,
                         nwItemDescPtr srcMacAddr,
834 835
                         int directionIn,
                         bool *srcmacskipped)
S
Stefan Berger 已提交
836 837
{
    char macaddr[VIR_MAC_STRING_BUFLEN];
838
    *srcmacskipped = false;
S
Stefan Berger 已提交
839 840

    if (HAS_ENTRY_ITEM(srcMacAddr)) {
841 842 843 844 845
        if (directionIn) {
            *srcmacskipped = true;
            return 0;
        }

846
        if (printDataType(vars,
S
Stefan Berger 已提交
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
                          macaddr, sizeof(macaddr),
                          srcMacAddr))
            goto err_exit;

        virBufferVSprintf(buf,
                          " -m mac %s --mac-source %s",
                          ENTRY_GET_NEG_SIGN(srcMacAddr),
                          macaddr);
    }

    return 0;

err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


static int
867
iptablesHandleIpHdr(virBufferPtr buf,
S
Stefan Berger 已提交
868 869
                    virNWFilterHashTablePtr vars,
                    ipHdrDataDefPtr ipHdr,
870
                    int directionIn,
871 872
                    bool *skipRule, bool *skipMatch,
                    virBufferPtr prefix)
S
Stefan Berger 已提交
873
{
874
    char ipaddr[INET6_ADDRSTRLEN],
S
Stefan Berger 已提交
875 876 877 878 879 880 881 882 883 884 885 886 887 888
         number[20];
    const char *src = "--source";
    const char *dst = "--destination";
    const char *srcrange = "--src-range";
    const char *dstrange = "--dst-range";
    if (directionIn) {
        src = "--destination";
        dst = "--source";
        srcrange = "--dst-range";
        dstrange = "--src-range";
    }

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

889
        if (printDataType(vars,
S
Stefan Berger 已提交
890 891 892 893 894 895 896 897 898 899 900 901
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataSrcIPAddr))
            goto err_exit;

        virBufferVSprintf(buf,
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataSrcIPAddr),
                          src,
                          ipaddr);

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

902
            if (printDataType(vars,
S
Stefan Berger 已提交
903 904 905 906 907 908 909 910 911 912
                              number, sizeof(number),
                              &ipHdr->dataSrcIPMask))
                goto err_exit;

            virBufferVSprintf(buf,
                              "/%s",
                              number);
        }
    } else if (HAS_ENTRY_ITEM(&ipHdr->dataSrcIPFrom)) {

913
        if (printDataType(vars,
S
Stefan Berger 已提交
914 915 916 917 918 919 920 921 922 923 924 925
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataSrcIPFrom))
            goto err_exit;

        virBufferVSprintf(buf,
                          " -m iprange %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataSrcIPFrom),
                          srcrange,
                          ipaddr);

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

926
            if (printDataType(vars,
S
Stefan Berger 已提交
927 928 929 930 931 932 933 934 935 936 937 938
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataSrcIPTo))
                goto err_exit;

            virBufferVSprintf(buf,
                              "-%s",
                              ipaddr);
        }
    }

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

939
        if (printDataType(vars,
S
Stefan Berger 已提交
940 941 942 943 944 945 946 947 948 949 950 951
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataDstIPAddr))
           goto err_exit;

        virBufferVSprintf(buf,
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDstIPAddr),
                          dst,
                          ipaddr);

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

952
            if (printDataType(vars,
S
Stefan Berger 已提交
953 954 955 956 957 958 959 960 961 962 963
                              number, sizeof(number),
                              &ipHdr->dataDstIPMask))
                goto err_exit;

            virBufferVSprintf(buf,
                              "/%s",
                              number);

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

964
        if (printDataType(vars,
S
Stefan Berger 已提交
965 966 967 968 969 970 971 972 973 974 975 976
                          ipaddr, sizeof(ipaddr),
                          &ipHdr->dataDstIPFrom))
            goto err_exit;

        virBufferVSprintf(buf,
                          " -m iprange %s %s %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDstIPFrom),
                          dstrange,
                          ipaddr);

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

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

S
Stefan Berger 已提交
982 983 984 985 986
            virBufferVSprintf(buf,
                              "-%s",
                              ipaddr);
        }
    }
987

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

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

S
Stefan Berger 已提交
995 996 997 998
        virBufferVSprintf(buf,
                          " -m dscp %s --dscp %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDSCP),
                          number);
999 1000
    }

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    if (HAS_ENTRY_ITEM(&ipHdr->dataConnlimitAbove)) {
        if (directionIn) {
            // only support for limit in outgoing dir.
            *skipRule = true;
        } else {
            if (printDataType(vars,
                              number, sizeof(number),
                              &ipHdr->dataConnlimitAbove))
               goto err_exit;

            virBufferVSprintf(buf,
                              " -m connlimit %s --connlimit-above %s",
                              ENTRY_GET_NEG_SIGN(&ipHdr->dataConnlimitAbove),
                              number);
            *skipMatch = true;
        }
    }

1019 1020 1021 1022 1023 1024 1025
    if (HAS_ENTRY_ITEM(&ipHdr->dataComment)) {
        printCommentVar(prefix, ipHdr->dataComment.u.string);

        virBufferAddLit(buf,
                        " -m comment --comment \"$" COMMENT_VARNAME "\"");
    }

S
Stefan Berger 已提交
1026
    return 0;
1027

S
Stefan Berger 已提交
1028 1029 1030 1031
err_exit:
    virBufferFreeAndReset(buf);

    return 1;
1032 1033 1034 1035
}


static int
1036
iptablesHandlePortData(virBufferPtr buf,
S
Stefan Berger 已提交
1037 1038 1039
                       virNWFilterHashTablePtr vars,
                       portDataDefPtr portData,
                       int directionIn)
1040
{
S
Stefan Berger 已提交
1041 1042 1043 1044 1045 1046 1047
    char portstr[20];
    const char *sport = "--sport";
    const char *dport = "--dport";
    if (directionIn) {
        sport = "--dport";
        dport = "--sport";
    }
1048

S
Stefan Berger 已提交
1049
    if (HAS_ENTRY_ITEM(&portData->dataSrcPortStart)) {
1050
        if (printDataType(vars,
S
Stefan Berger 已提交
1051 1052
                          portstr, sizeof(portstr),
                          &portData->dataSrcPortStart))
1053 1054 1055
            goto err_exit;

        virBufferVSprintf(buf,
S
Stefan Berger 已提交
1056 1057 1058 1059
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataSrcPortStart),
                          sport,
                          portstr);
1060

S
Stefan Berger 已提交
1061
        if (HAS_ENTRY_ITEM(&portData->dataSrcPortEnd)) {
1062
            if (printDataType(vars,
S
Stefan Berger 已提交
1063 1064
                              portstr, sizeof(portstr),
                              &portData->dataSrcPortEnd))
1065 1066
                goto err_exit;

S
Stefan Berger 已提交
1067 1068 1069
             virBufferVSprintf(buf,
                               ":%s",
                               portstr);
1070 1071 1072
        }
    }

S
Stefan Berger 已提交
1073
    if (HAS_ENTRY_ITEM(&portData->dataDstPortStart)) {
1074
        if (printDataType(vars,
S
Stefan Berger 已提交
1075 1076
                          portstr, sizeof(portstr),
                          &portData->dataDstPortStart))
1077 1078 1079
            goto err_exit;

        virBufferVSprintf(buf,
S
Stefan Berger 已提交
1080 1081 1082 1083
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataDstPortStart),
                          dport,
                          portstr);
1084

S
Stefan Berger 已提交
1085
        if (HAS_ENTRY_ITEM(&portData->dataDstPortEnd)) {
1086
            if (printDataType(vars,
S
Stefan Berger 已提交
1087 1088
                              portstr, sizeof(portstr),
                              &portData->dataDstPortEnd))
1089 1090
                goto err_exit;

S
Stefan Berger 已提交
1091 1092 1093
             virBufferVSprintf(buf,
                               ":%s",
                               portstr);
1094 1095 1096 1097 1098
        }
    }

    return 0;

S
Stefan Berger 已提交
1099
err_exit:
1100 1101 1102
    return 1;
}

S
Stefan Berger 已提交
1103 1104 1105 1106 1107 1108 1109 1110
/*
 * _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
1111 1112 1113 1114 1115 1116
 * @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 已提交
1117 1118 1119 1120 1121 1122 1123 1124
 *
 * 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
1125
_iptablesCreateRuleInstance(int directionIn,
S
Stefan Berger 已提交
1126 1127 1128 1129 1130 1131
                            const char *chainPrefix,
                            virNWFilterDefPtr nwfilter,
                            virNWFilterRuleDefPtr rule,
                            const char *ifname,
                            virNWFilterHashTablePtr vars,
                            virNWFilterRuleInstPtr res,
1132
                            const char *match, bool defMatch,
1133
                            const char *accept_target,
1134 1135
                            bool isIPv6,
                            bool maySkipICMP)
S
Stefan Berger 已提交
1136 1137 1138
{
    char chain[MAX_CHAINNAME_LENGTH];
    char number[20];
1139
    virBuffer prefix = VIR_BUFFER_INITIALIZER;
S
Stefan Berger 已提交
1140
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1141
    virBufferPtr final = NULL;
S
Stefan Berger 已提交
1142
    const char *target;
1143 1144
    const char *iptables_cmd = (isIPv6) ? ip6tables_cmd_path
                                        : iptables_cmd_path;
1145 1146
    unsigned int bufUsed;
    bool srcMacSkipped = false;
1147 1148
    bool skipRule = false;
    bool skipMatch = false;
S
Stefan Berger 已提交
1149

1150 1151 1152 1153 1154 1155 1156 1157
    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 已提交
1158 1159 1160 1161
    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
1162
    case VIR_NWFILTER_RULE_PROTOCOL_TCPoIPV6:
S
Stefan Berger 已提交
1163
        virBufferVSprintf(&buf,
1164 1165
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1166 1167 1168 1169
                          chain);

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

1170 1171
        bufUsed = virBufferUse(&buf);

1172
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1173 1174
                                     vars,
                                     &rule->p.tcpHdrFilter.dataSrcMACAddr,
1175 1176
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1177 1178
            goto err_exit;

1179
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1180 1181
                                vars,
                                &rule->p.tcpHdrFilter.ipHdr,
1182
                                directionIn,
1183 1184
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1185 1186
            goto err_exit;

1187
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1188 1189 1190 1191 1192 1193
                                   vars,
                                   &rule->p.tcpHdrFilter.portData,
                                   directionIn))
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.tcpHdrFilter.dataTCPOption)) {
1194
            if (printDataType(vars,
S
Stefan Berger 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
                              number, sizeof(number),
                              &rule->p.tcpHdrFilter.dataTCPOption))
                goto err_exit;

            virBufferVSprintf(&buf,
                              " %s --tcp-option %s",
                              ENTRY_GET_NEG_SIGN(&rule->p.tcpHdrFilter.dataTCPOption),
                              number);
        }

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
1208
    case VIR_NWFILTER_RULE_PROTOCOL_UDPoIPV6:
S
Stefan Berger 已提交
1209
        virBufferVSprintf(&buf,
1210 1211
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1212 1213 1214 1215
                          chain);

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

1216 1217
        bufUsed = virBufferUse(&buf);

1218
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1219 1220
                                     vars,
                                     &rule->p.udpHdrFilter.dataSrcMACAddr,
1221 1222
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1223 1224
            goto err_exit;

1225
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1226 1227
                                vars,
                                &rule->p.udpHdrFilter.ipHdr,
1228
                                directionIn,
1229 1230
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1231 1232
            goto err_exit;

1233
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1234 1235 1236 1237 1238 1239
                                   vars,
                                   &rule->p.udpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

1240
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
1241
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITEoIPV6:
1242
        virBufferVSprintf(&buf,
1243 1244
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1245 1246 1247 1248
                          chain);

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

1249 1250
        bufUsed = virBufferUse(&buf);

1251
        if (iptablesHandleSrcMacAddr(&buf,
1252 1253
                                     vars,
                                     &rule->p.udpliteHdrFilter.dataSrcMACAddr,
1254 1255
                                     directionIn,
                                     &srcMacSkipped))
1256 1257
            goto err_exit;

1258
        if (iptablesHandleIpHdr(&buf,
1259 1260
                                vars,
                                &rule->p.udpliteHdrFilter.ipHdr,
1261
                                directionIn,
1262 1263
                                &skipRule, &skipMatch,
                                &prefix))
1264 1265 1266 1267 1268
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
1269
    case VIR_NWFILTER_RULE_PROTOCOL_ESPoIPV6:
1270
        virBufferVSprintf(&buf,
1271 1272
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1273 1274 1275 1276
                          chain);

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

1277 1278
        bufUsed = virBufferUse(&buf);

1279
        if (iptablesHandleSrcMacAddr(&buf,
1280 1281
                                     vars,
                                     &rule->p.espHdrFilter.dataSrcMACAddr,
1282 1283
                                     directionIn,
                                     &srcMacSkipped))
1284 1285
            goto err_exit;

1286
        if (iptablesHandleIpHdr(&buf,
1287 1288
                                vars,
                                &rule->p.espHdrFilter.ipHdr,
1289
                                directionIn,
1290 1291
                                &skipRule, &skipMatch,
                                &prefix))
1292 1293 1294 1295 1296
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_AH:
1297
    case VIR_NWFILTER_RULE_PROTOCOL_AHoIPV6:
1298
        virBufferVSprintf(&buf,
1299 1300
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1301 1302 1303 1304
                          chain);

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

1305 1306
        bufUsed = virBufferUse(&buf);

1307
        if (iptablesHandleSrcMacAddr(&buf,
1308 1309
                                     vars,
                                     &rule->p.ahHdrFilter.dataSrcMACAddr,
1310 1311
                                     directionIn,
                                     &srcMacSkipped))
1312 1313
            goto err_exit;

1314
        if (iptablesHandleIpHdr(&buf,
1315 1316
                                vars,
                                &rule->p.ahHdrFilter.ipHdr,
1317
                                directionIn,
1318 1319
                                &skipRule, &skipMatch,
                                &prefix))
1320 1321 1322 1323
            goto err_exit;

    break;

S
Stefan Berger 已提交
1324
    case VIR_NWFILTER_RULE_PROTOCOL_SCTP:
1325
    case VIR_NWFILTER_RULE_PROTOCOL_SCTPoIPV6:
S
Stefan Berger 已提交
1326
        virBufferVSprintf(&buf,
1327 1328
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1329 1330 1331 1332
                          chain);

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

1333 1334
        bufUsed = virBufferUse(&buf);

1335
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1336 1337
                                     vars,
                                     &rule->p.sctpHdrFilter.dataSrcMACAddr,
1338 1339
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1340 1341
            goto err_exit;

1342
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1343 1344
                                vars,
                                &rule->p.sctpHdrFilter.ipHdr,
1345
                                directionIn,
1346 1347
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1348 1349
            goto err_exit;

1350
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1351 1352 1353 1354 1355 1356 1357
                                   vars,
                                   &rule->p.sctpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
1358
    case VIR_NWFILTER_RULE_PROTOCOL_ICMPV6:
S
Stefan Berger 已提交
1359
        virBufferVSprintf(&buf,
1360 1361
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1362 1363
                          chain);

1364 1365 1366 1367
        if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
            virBufferAddLit(&buf, " -p icmp");
        else
            virBufferAddLit(&buf, " -p icmpv6");
S
Stefan Berger 已提交
1368

1369 1370
        bufUsed = virBufferUse(&buf);

1371
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1372 1373
                                     vars,
                                     &rule->p.icmpHdrFilter.dataSrcMACAddr,
1374 1375
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1376 1377
            goto err_exit;

1378
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1379 1380
                                vars,
                                &rule->p.icmpHdrFilter.ipHdr,
1381
                                directionIn,
1382 1383
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1384 1385 1386
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPType)) {
1387
            const char *parm;
1388 1389 1390 1391

            if (maySkipICMP)
                goto exit_no_error;

1392 1393 1394 1395 1396
            if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
                parm = "--icmp-type";
            else
                parm = "--icmpv6-type";

1397
            if (printDataType(vars,
S
Stefan Berger 已提交
1398 1399 1400 1401 1402
                              number, sizeof(number),
                              &rule->p.icmpHdrFilter.dataICMPType))
                goto err_exit;

            virBufferVSprintf(&buf,
1403
                      " %s %s %s",
S
Stefan Berger 已提交
1404
                      ENTRY_GET_NEG_SIGN(&rule->p.icmpHdrFilter.dataICMPType),
1405
                      parm,
S
Stefan Berger 已提交
1406 1407 1408
                      number);

            if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPCode)) {
1409
                if (printDataType(vars,
S
Stefan Berger 已提交
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
                                  number, sizeof(number),
                                  &rule->p.icmpHdrFilter.dataICMPCode))
                    goto err_exit;

                 virBufferVSprintf(&buf,
                                   "/%s",
                                   number);
            }
        }
    break;

1421 1422 1423 1424 1425 1426 1427 1428
    case VIR_NWFILTER_RULE_PROTOCOL_IGMP:
        virBufferVSprintf(&buf,
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
                          chain);

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

1429 1430
        bufUsed = virBufferUse(&buf);

1431
        if (iptablesHandleSrcMacAddr(&buf,
1432 1433
                                     vars,
                                     &rule->p.igmpHdrFilter.dataSrcMACAddr,
1434 1435
                                     directionIn,
                                     &srcMacSkipped))
1436 1437
            goto err_exit;

1438
        if (iptablesHandleIpHdr(&buf,
1439 1440
                                vars,
                                &rule->p.igmpHdrFilter.ipHdr,
1441
                                directionIn,
1442 1443
                                &skipRule, &skipMatch,
                                &prefix))
1444 1445 1446 1447
            goto err_exit;

    break;

S
Stefan Berger 已提交
1448
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
1449
    case VIR_NWFILTER_RULE_PROTOCOL_ALLoIPV6:
S
Stefan Berger 已提交
1450
        virBufferVSprintf(&buf,
1451 1452
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1453 1454 1455 1456
                          chain);

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

1457 1458
        bufUsed = virBufferUse(&buf);

1459
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1460 1461
                                     vars,
                                     &rule->p.allHdrFilter.dataSrcMACAddr,
1462 1463
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1464 1465
            goto err_exit;

1466
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1467 1468
                                vars,
                                &rule->p.allHdrFilter.ipHdr,
1469
                                directionIn,
1470 1471
                                &skipRule, &skipMatch,
                                &prefix))
S
Stefan Berger 已提交
1472 1473 1474 1475 1476 1477 1478 1479
            goto err_exit;

    break;

    default:
        return -1;
    }

1480 1481
    if ((srcMacSkipped && bufUsed == virBufferUse(&buf)) ||
         skipRule) {
1482
        virBufferFreeAndReset(&buf);
1483
        virBufferFreeAndReset(&prefix);
1484 1485 1486
        return 0;
    }

S
Stefan Berger 已提交
1487 1488
    if (rule->action == VIR_NWFILTER_RULE_ACTION_ACCEPT)
        target = accept_target;
1489
    else {
S
Stefan Berger 已提交
1490
        target = "DROP";
1491
        skipMatch = defMatch;
1492 1493
    }

1494
    if (match && !skipMatch)
1495 1496
        virBufferVSprintf(&buf, " %s", match);

S
Stefan Berger 已提交
1497 1498 1499 1500 1501 1502

    virBufferVSprintf(&buf,
                      " -j %s" CMD_DEF_POST CMD_SEPARATOR
                      CMD_EXEC,
                      target);

1503
    if (virBufferError(&buf) || virBufferError(&prefix)) {
S
Stefan Berger 已提交
1504
        virBufferFreeAndReset(&buf);
1505
        virBufferFreeAndReset(&prefix);
S
Stefan Berger 已提交
1506 1507 1508 1509
        virReportOOMError();
        return -1;
    }

1510
    if (virBufferUse(&prefix)) {
S
Stefan Berger 已提交
1511 1512 1513 1514 1515
        char *s = virBufferContentAndReset(&buf);

        virBufferAdd(&prefix, s, -1);

        VIR_FREE(s);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527

        final = &prefix;

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


1528
    return ebiptablesAddRuleInst(res,
1529
                                 virBufferContentAndReset(final),
S
Stefan Berger 已提交
1530 1531 1532
                                 nwfilter->chainsuffix,
                                 '\0',
                                 rule->priority,
1533
                                 (isIPv6) ? RT_IP6TABLES : RT_IPTABLES);
S
Stefan Berger 已提交
1534 1535 1536 1537


err_exit:
    virBufferFreeAndReset(&buf);
S
Stefan Berger 已提交
1538
    virBufferFreeAndReset(&prefix);
S
Stefan Berger 已提交
1539 1540 1541

    return -1;

1542 1543
exit_no_error:
    virBufferFreeAndReset(&buf);
S
Stefan Berger 已提交
1544
    virBufferFreeAndReset(&prefix);
1545 1546

    return 0;
S
Stefan Berger 已提交
1547 1548 1549
}


1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
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,
                                    virNWFilterHashTablePtr vars,
                                    virNWFilterRuleInstPtr res,
                                    bool isIPv6)
{
    int rc;
    int directionIn = 0, directionOut = 0;
    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;
        directionOut = inout = (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
    } else
        directionOut = 1;

    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 已提交
1693
static int
1694
iptablesCreateRuleInstance(virNWFilterDefPtr nwfilter,
S
Stefan Berger 已提交
1695 1696 1697
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
                           virNWFilterHashTablePtr vars,
1698 1699
                           virNWFilterRuleInstPtr res,
                           bool isIPv6)
S
Stefan Berger 已提交
1700 1701 1702 1703 1704
{
    int rc;
    int directionIn = 0;
    char chainPrefix[2];
    int needState = 1;
1705
    bool maySkipICMP, inout = false;
1706
    const char *matchState;
S
Stefan Berger 已提交
1707

1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
    if (!(rule->flags & RULE_FLAG_NO_STATEMATCH) &&
         (rule->flags & IPTABLES_STATE_FLAGS)) {
        return iptablesCreateRuleInstanceStateCtrl(nwfilter,
                                                   rule,
                                                   ifname,
                                                   vars,
                                                   res,
                                                   isIPv6);
    }

S
Stefan Berger 已提交
1718 1719 1720
    if ((rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN) ||
        (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT)) {
        directionIn = 1;
1721
        inout = (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
1722 1723
        if (inout)
            needState = 0;
S
Stefan Berger 已提交
1724 1725
    }

1726 1727 1728
    if ((rule->flags & RULE_FLAG_NO_STATEMATCH))
        needState = 0;

S
Stefan Berger 已提交
1729 1730
    chainPrefix[0] = 'F';

1731 1732
    maySkipICMP = directionIn || inout;

1733 1734 1735 1736 1737
    if (needState)
        matchState = directionIn ? MATCH_STATE_IN : MATCH_STATE_OUT;
    else
        matchState = NULL;

S
Stefan Berger 已提交
1738
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1739
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1740 1741 1742 1743 1744 1745
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1746
                                     matchState, true,
1747
                                     "RETURN",
1748 1749
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1750 1751 1752
    if (rc)
        return rc;

1753 1754

    maySkipICMP = !directionIn || inout;
1755 1756 1757 1758
    if (needState)
        matchState = directionIn ? MATCH_STATE_OUT : MATCH_STATE_IN;
    else
        matchState = NULL;
1759

S
Stefan Berger 已提交
1760
    chainPrefix[1] = CHAINPREFIX_HOST_OUT_TEMP;
1761
    rc = _iptablesCreateRuleInstance(!directionIn,
S
Stefan Berger 已提交
1762 1763 1764 1765 1766 1767
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1768
                                     matchState, true,
1769
                                     "ACCEPT",
1770 1771
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1772 1773 1774
    if (rc)
        return rc;

1775 1776
    maySkipICMP = directionIn;

S
Stefan Berger 已提交
1777 1778
    chainPrefix[0] = 'H';
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1779
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1780 1781 1782 1783 1784 1785
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
1786
                                     NULL, true,
1787
                                     "ACCEPT",
1788 1789
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1790 1791 1792 1793 1794 1795 1796

    return rc;
}




1797 1798 1799 1800 1801 1802 1803 1804
/*
 * 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
1805
 * @reverse : Whether to reverse src and dst attributes
1806 1807 1808 1809 1810 1811 1812 1813
 *
 * 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
1814
ebtablesCreateRuleInstance(char chainPrefix,
1815 1816 1817 1818
                           virNWFilterDefPtr nwfilter,
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
                           virNWFilterHashTablePtr vars,
1819 1820
                           virNWFilterRuleInstPtr res,
                           bool reverse)
1821 1822 1823
{
    char macaddr[VIR_MAC_STRING_BUFLEN],
         ipaddr[INET_ADDRSTRLEN],
1824
         ipv6addr[INET6_ADDRSTRLEN],
1825 1826 1827 1828
         number[20];
    char chain[MAX_CHAINNAME_LENGTH];
    virBuffer buf = VIR_BUFFER_INITIALIZER;

1829 1830 1831 1832 1833 1834 1835
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rule since ebtables tool is "
                                 "missing."));
        goto err_exit;
    }

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
    if (nwfilter->chainsuffix == VIR_NWFILTER_CHAINSUFFIX_ROOT)
        PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);
    else
        PRINT_CHAIN(chain, chainPrefix, ifname,
                    virNWFilterChainSuffixTypeToString(nwfilter->chainsuffix));


    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:

        virBufferVSprintf(&buf,
1847 1848
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1849 1850


1851
        if (ebtablesHandleEthHdr(&buf,
1852
                                 vars,
1853 1854
                                 &rule->p.ethHdrFilter.ethHdr,
                                 reverse))
1855 1856 1857
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.ethHdrFilter.dataProtocolID)) {
1858
            if (printDataTypeAsHex(vars,
1859 1860
                                   number, sizeof(number),
                                   &rule->p.ethHdrFilter.dataProtocolID))
1861 1862 1863 1864 1865 1866 1867 1868 1869
                goto err_exit;
            virBufferVSprintf(&buf,
                          " -p %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.ethHdrFilter.dataProtocolID),
                          number);
        }
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
1870
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
1871 1872

        virBufferVSprintf(&buf,
1873 1874
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1875

1876
        if (ebtablesHandleEthHdr(&buf,
1877
                                 vars,
1878 1879
                                 &rule->p.arpHdrFilter.ethHdr,
                                 reverse))
1880 1881
            goto err_exit;

1882 1883 1884 1885
        virBufferVSprintf(&buf, " -p 0x%x",
                          (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ARP)
                           ? l3_protocols[L3_PROTO_ARP_IDX].attr
                           : l3_protocols[L3_PROTO_RARP_IDX].attr);
1886 1887

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataHWType)) {
1888 1889 1890
             if (printDataType(vars,
                               number, sizeof(number),
                               &rule->p.arpHdrFilter.dataHWType))
1891 1892 1893 1894 1895 1896 1897 1898
                goto err_exit;
           virBufferVSprintf(&buf,
                          " --arp-htype %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataHWType),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataOpcode)) {
1899
            if (printDataType(vars,
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
                              number, sizeof(number),
                              &rule->p.arpHdrFilter.dataOpcode))
                goto err_exit;
            virBufferVSprintf(&buf,
                          " --arp-opcode %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataOpcode),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataProtocolType)) {
1910
            if (printDataTypeAsHex(vars,
1911 1912
                                   number, sizeof(number),
                                   &rule->p.arpHdrFilter.dataProtocolType))
1913 1914 1915 1916 1917 1918 1919 1920
                goto err_exit;
            virBufferVSprintf(&buf,
                          " --arp-ptype %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataProtocolType),
                          number);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcIPAddr)) {
1921
            if (printDataType(vars,
1922 1923 1924 1925 1926
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1927 1928
                          " %s %s %s",
                          reverse ? "--arp-ip-dst" : "--arp-ip-src",
1929 1930 1931 1932 1933
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstIPAddr)) {
1934
            if (printDataType(vars,
1935 1936 1937 1938 1939
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1940 1941
                          " %s %s %s",
                          reverse ? "--arp-ip-src" : "--arp-ip-dst",
1942 1943 1944 1945 1946
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcMACAddr)) {
1947
            if (printDataType(vars,
1948 1949 1950 1951 1952
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPSrcMACAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1953 1954
                          " %s %s %s",
                          reverse ? "--arp-mac-dst" : "--arp-mac-src",
1955 1956 1957 1958 1959
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcMACAddr),
                          macaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstMACAddr)) {
1960
            if (printDataType(vars,
1961 1962 1963 1964 1965
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPDstMACAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1966 1967
                          " %s %s %s",
                          reverse ? "--arp-mac-src" : "--arp-mac-dst",
1968 1969 1970 1971 1972 1973 1974
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstMACAddr),
                          macaddr);
        }
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_IP:
        virBufferVSprintf(&buf,
1975 1976
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1977

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

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

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr)) {
1988
            if (printDataType(vars,
1989 1990 1991 1992 1993
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1994 1995
                          " %s %s %s",
                          reverse ? "--ip-destination" : "--ip-source",
1996 1997 1998 1999
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPMask)) {
2000
                if (printDataType(vars,
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                             "/%s",
                             number);
            }
        }

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

2012
            if (printDataType(vars,
2013 2014 2015 2016 2017
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
2018 2019
                          " %s %s %s",
                          reverse ? "--ip-source" : "--ip-destination",
2020 2021 2022 2023
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDstIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDstIPMask)) {
2024
                if (printDataType(vars,
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataProtocolID)) {
2035
            if (printDataType(vars,
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.ipHdr.dataProtocolID))
                goto err_exit;

            virBufferVSprintf(&buf,
                 " --ip-protocol %s %s",
                 ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataProtocolID),
                 number);
        }

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

2048
            if (printDataType(vars,
2049 2050 2051 2052 2053
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataSrcPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
2054 2055
                          " %s %s %s",
                          reverse ? "--ip-destination-port" : "--ip-source-port",
2056 2057 2058 2059
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataSrcPortEnd)) {
2060
                if (printDataType(vars,
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

                virBufferVSprintf(&buf,
                                  ":%s",
                                  number);
            }
        }

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

2073
            if (printDataType(vars,
2074 2075 2076 2077 2078
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataDstPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
2079 2080
                          " %s %s %s",
                          reverse ? "--ip-source-port" : "--ip-destination-port",
2081 2082 2083 2084
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataDstPortEnd)) {
2085
                if (printDataType(vars,
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
                                number, sizeof(number),
                                &rule->p.ipHdrFilter.portData.dataDstPortEnd))
                    goto err_exit;

                virBufferVSprintf(&buf,
                                  ":%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDSCP)) {
2097 2098 2099
            if (printDataTypeAsHex(vars,
                                   number, sizeof(number),
                                   &rule->p.ipHdrFilter.ipHdr.dataDSCP))
2100 2101 2102 2103 2104 2105 2106 2107 2108
                goto err_exit;

            virBufferVSprintf(&buf,
                       " --ip-tos %s %s",
                       ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDSCP),
                       number);
        }
    break;

2109 2110
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
        virBufferVSprintf(&buf,
2111 2112
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2113

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

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

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

            virBufferVSprintf(&buf,
2130 2131
                          " %s %s %s",
                          reverse ? "--ip6-destination" : "--ip6-source",
2132 2133 2134 2135
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr),
                          ipv6addr);

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

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

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

            virBufferVSprintf(&buf,
2154 2155
                          " %s %s %s",
                          reverse ? "--ip6-source" : "--ip6-destination",
2156 2157 2158 2159
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr),
                          ipv6addr);

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

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID)) {
2171
            if (printDataType(vars,
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.ipHdr.dataProtocolID))
                goto err_exit;

            virBufferVSprintf(&buf,
                 " --ip6-protocol %s %s",
                 ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID),
                 number);
        }

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

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

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

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataSrcPortEnd)) {
2196
                if (printDataType(vars,
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

                virBufferVSprintf(&buf,
                                  ":%s",
                                  number);
            }
        }

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

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

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

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataDstPortEnd)) {
2221 2222 2223
                if (printDataType(vars,
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataDstPortEnd))
2224 2225 2226 2227 2228 2229 2230 2231 2232
                    goto err_exit;

                virBufferVSprintf(&buf,
                                  ":%s",
                                  number);
            }
        }
    break;

2233 2234
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
        virBufferVSprintf(&buf,
2235 2236
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2237
    break;
S
Stefan Berger 已提交
2238 2239 2240

    default:
        return -1;
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
    }

    virBufferVSprintf(&buf,
                      " -j %s" CMD_DEF_POST CMD_SEPARATOR
                      CMD_EXEC,
                      virNWFilterJumpTargetTypeToString(rule->action));

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

2254
    return ebiptablesAddRuleInst(res,
2255 2256 2257
                                 virBufferContentAndReset(&buf),
                                 nwfilter->chainsuffix,
                                 chainPrefix,
S
Stefan Berger 已提交
2258 2259
                                 rule->priority,
                                 RT_EBTABLES);
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283

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
2284
ebiptablesCreateRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
S
Stefan Berger 已提交
2285
                             enum virDomainNetType nettype,
2286 2287 2288 2289 2290 2291 2292
                             virNWFilterDefPtr nwfilter,
                             virNWFilterRuleDefPtr rule,
                             const char *ifname,
                             virNWFilterHashTablePtr vars,
                             virNWFilterRuleInstPtr res)
{
    int rc = 0;
2293
    bool isIPv6;
2294 2295 2296 2297 2298

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_IP:
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:
    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
2299
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
2300
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
2301
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
2302 2303 2304

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_OUT ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2305
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_IN_TEMP,
2306 2307 2308 2309
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2310 2311
                                            res,
                                            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
2312 2313 2314 2315 2316 2317
            if (rc)
                return rc;
        }

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2318
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_OUT_TEMP,
2319 2320 2321 2322
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2323 2324
                                            res,
                                            false);
2325 2326
        }
    break;
S
Stefan Berger 已提交
2327 2328 2329

    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
2330 2331 2332
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
    case VIR_NWFILTER_RULE_PROTOCOL_AH:
S
Stefan Berger 已提交
2333 2334 2335 2336 2337
    case VIR_NWFILTER_RULE_PROTOCOL_SCTP:
    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
    case VIR_NWFILTER_RULE_PROTOCOL_IGMP:
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
        if (nettype == VIR_DOMAIN_NET_TYPE_DIRECT) {
2338
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
S
Stefan Berger 已提交
2339 2340 2341 2342 2343
                          _("'%s' protocol not support for net type '%s'"),
                          virNWFilterRuleProtocolTypeToString(rule->prtclType),
                          virDomainNetTypeToString(nettype));
            return 1;
        }
2344
        isIPv6 = 0;
2345
        rc = iptablesCreateRuleInstance(nwfilter,
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
                                        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:
        if (nettype == VIR_DOMAIN_NET_TYPE_DIRECT) {
2362
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
2363 2364 2365 2366 2367 2368
                          _("'%s' protocol not support for net type '%s'"),
                          virNWFilterRuleProtocolTypeToString(rule->prtclType),
                          virDomainNetTypeToString(nettype));
            return 1;
        }
        isIPv6 = 1;
2369
        rc = iptablesCreateRuleInstance(nwfilter,
S
Stefan Berger 已提交
2370 2371 2372
                                        rule,
                                        ifname,
                                        vars,
2373 2374
                                        res,
                                        isIPv6);
S
Stefan Berger 已提交
2375 2376 2377
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_LAST:
2378
        virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
S
Stefan Berger 已提交
2379 2380 2381
                               "%s", _("illegal protocol type"));
        rc = 1;
    break;
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
    }

    return rc;
}


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


static int
ebiptablesDisplayRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
                              void *_inst)
{
    ebiptablesRuleInstPtr inst = (ebiptablesRuleInstPtr)_inst;
2401 2402 2403
    VIR_INFO("Command Template: '%s', Needed protocol: '%s'",
             inst->commandTemplate,
             virNWFilterChainSuffixTypeToString(inst->neededProtocolChain));
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    return 0;
}


/**
 * ebiptablesWriteToTempFile:
 * @string : the string to write into the file
 *
 * Returns the tempory filename where the string was written into,
 * NULL in case of error with the error reported.
 *
 * Write the string into a temporary file and return the name of
 * the temporary file. The string is assumed to contain executable
 * commands. A line '#!/bin/bash' will automatically be written
 * as the first line in the file. The permissions of the file are
 * set so that the file can be run as an executable script.
 */
static char *
2422
ebiptablesWriteToTempFile(const char *string) {
2423 2424 2425
    char filename[] = "/tmp/virtdXXXXXX";
    int len;
    char *filnam;
2426 2427
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *header;
2428 2429
    size_t written;

2430 2431 2432 2433 2434 2435 2436 2437 2438
    virBufferVSprintf(&buf, "#!%s\n", bash_cmd_path);

    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        virReportOOMError();
        return NULL;
    }
    header = virBufferContentAndReset(&buf);

2439 2440 2441
    int fd = mkstemp(filename);

    if (fd < 0) {
2442
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2443 2444
                               "%s",
                               _("cannot create temporary file"));
2445
        goto err_exit;
2446 2447 2448
    }

    if (fchmod(fd, S_IXUSR| S_IRUSR | S_IWUSR) < 0) {
2449
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2450 2451 2452 2453 2454 2455 2456 2457
                               "%s",
                               _("cannot change permissions on temp. file"));
        goto err_exit;
    }

    len = strlen(header);
    written = safewrite(fd, header, len);
    if (written != len) {
2458
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2459 2460 2461 2462 2463 2464 2465 2466
                               "%s",
                               _("cannot write string to file"));
        goto err_exit;
    }

    len = strlen(string);
    written = safewrite(fd, string, len);
    if (written != len) {
2467
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
                               "%s",
                               _("cannot write string to file"));
        goto err_exit;
    }

    filnam = strdup(filename);
    if (!filnam) {
        virReportOOMError();
        goto err_exit;
    }

2479
    VIR_FREE(header);
2480 2481 2482 2483
    close(fd);
    return filnam;

err_exit:
2484
    VIR_FREE(header);
2485 2486
    if (fd >= 0)
        close(fd);
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
    unlink(filename);
    return NULL;
}


/**
 * ebiptablesExecCLI:
 * @buf : pointer to virBuffer containing the string with the commands to
 *        execute.
 * @status: Pointer to an integer for returning the status of the
 *        commands executed via the script the was run.
 *
 * Returns 0 in case of success, != 0 in case of an error. The returned
 * value is NOT the result of running the commands inside the bash
 * script.
 *
 * Execute a sequence of commands (held in the given buffer) as a bash
 * script and return the status of the execution.
 */
static int
2507
ebiptablesExecCLI(virBufferPtr buf,
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
                  int *status)
{
    char *cmds;
    char *filename;
    int rc;
    const char *argv[] = {NULL, NULL};

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

    *status = 0;

    cmds = virBufferContentAndReset(buf);

    VIR_DEBUG("%s", cmds);

    if (!cmds)
        return 0;

2530
    filename = ebiptablesWriteToTempFile(cmds);
2531 2532 2533 2534 2535 2536
    VIR_FREE(cmds);

    if (!filename)
        return 1;

    argv[0] = filename;
2537 2538 2539

    virMutexLock(&execCLIMutex);

2540 2541
    rc = virRun(argv, status);

2542 2543
    virMutexUnlock(&execCLIMutex);

2544 2545
    *status >>= 8;

2546
    VIR_DEBUG("rc = %d, status = %d",rc, *status);
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556

    unlink(filename);

    VIR_FREE(filename);

    return rc;
}


static int
2557
ebtablesCreateTmpRootChain(virBufferPtr buf,
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
                           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);

    virBufferVSprintf(buf,
2568
                      CMD_DEF("%s -t %s -N %s") CMD_SEPARATOR
2569 2570
                      CMD_EXEC
                      "%s",
2571
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2572 2573 2574 2575 2576 2577 2578
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2579
ebtablesLinkTmpRootChain(virBufferPtr buf,
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
                         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);

    virBufferVSprintf(buf,
2591
                      CMD_DEF("%s -t %s -A %s -%c %s -j %s") CMD_SEPARATOR
2592 2593
                      CMD_EXEC
                      "%s",
2594
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2606
_ebtablesRemoveRootChain(virBufferPtr buf,
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
                         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);

    virBufferVSprintf(buf,
2622 2623 2624 2625
                      "%s -t %s -F %s" CMD_SEPARATOR
                      "%s -t %s -X %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2626 2627 2628 2629 2630 2631

    return 0;
}


static int
2632
ebtablesRemoveRootChain(virBufferPtr buf,
2633 2634
                        int incoming, const char *ifname)
{
2635
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 0);
2636 2637 2638 2639
}


static int
2640
ebtablesRemoveTmpRootChain(virBufferPtr buf,
2641 2642
                           int incoming, const char *ifname)
{
2643
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 1);
2644 2645 2646 2647
}


static int
2648
_ebtablesUnlinkRootChain(virBufferPtr buf,
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
                         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);

    virBufferVSprintf(buf,
2667 2668
                      "%s -t %s -D %s -%c %s -j %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2669 2670 2671 2672 2673 2674 2675 2676 2677
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain);

    return 0;
}


static int
2678
ebtablesUnlinkRootChain(virBufferPtr buf,
2679 2680
                        int incoming, const char *ifname)
{
2681
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 0);
2682 2683 2684 2685
}


static int
2686
ebtablesUnlinkTmpRootChain(virBufferPtr buf,
2687 2688
                           int incoming, const char *ifname)
{
2689
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 1);
2690 2691 2692 2693
}


static int
2694
ebtablesCreateTmpSubChain(virBufferPtr buf,
2695 2696
                          int incoming,
                          const char *ifname,
2697
                          enum l3_proto_idx protoidx,
2698 2699 2700 2701 2702 2703 2704
                          int stopOnError)
{
    char rootchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = (incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                  : CHAINPREFIX_HOST_OUT_TEMP;

    PRINT_ROOT_CHAIN(rootchain, chainPrefix, ifname);
2705
    PRINT_CHAIN(chain, chainPrefix, ifname, l3_protocols[protoidx].val);
2706 2707

    virBufferVSprintf(buf,
2708
                      CMD_DEF("%s -t %s -N %s") CMD_SEPARATOR
2709 2710
                      CMD_EXEC
                      "%s"
2711
                      CMD_DEF("%s -t %s -A %s -p 0x%x -j %s") CMD_SEPARATOR
2712 2713 2714
                      CMD_EXEC
                      "%s",

2715
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2716 2717 2718

                      CMD_STOPONERR(stopOnError),

2719
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2720
                      rootchain, l3_protocols[protoidx].attr, chain,
2721 2722 2723 2724 2725 2726 2727 2728

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2729
_ebtablesRemoveSubChain(virBufferPtr buf,
2730 2731
                        int incoming,
                        const char *ifname,
2732
                        enum l3_proto_idx protoidx,
2733 2734 2735 2736
                        int isTempChain)
{
    char rootchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix;
2737

2738 2739 2740 2741 2742 2743 2744 2745 2746
    if (isTempChain) {
        chainPrefix =(incoming) ? CHAINPREFIX_HOST_IN_TEMP
                                : CHAINPREFIX_HOST_OUT_TEMP;
    } else {
        chainPrefix =(incoming) ? CHAINPREFIX_HOST_IN
                                : CHAINPREFIX_HOST_OUT;
    }

    PRINT_ROOT_CHAIN(rootchain, chainPrefix, ifname);
2747
    PRINT_CHAIN(chain, chainPrefix, ifname, l3_protocols[protoidx].val);
2748 2749

    virBufferVSprintf(buf,
2750
                      "%s -t %s -D %s -p 0x%x -j %s" CMD_SEPARATOR
2751 2752 2753
                      "%s -t %s -F %s" CMD_SEPARATOR
                      "%s -t %s -X %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2754
                      rootchain, l3_protocols[protoidx].attr, chain,
2755

2756
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2757

2758
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2759 2760 2761 2762 2763 2764

    return 0;
}


static int
2765
ebtablesRemoveSubChain(virBufferPtr buf,
2766 2767
                       int incoming,
                       const char *ifname,
2768
                       enum l3_proto_idx protoidx)
2769
{
2770
    return _ebtablesRemoveSubChain(buf,
2771
                                   incoming, ifname, protoidx, 0);
2772 2773 2774 2775
}


static int
2776 2777
ebtablesRemoveSubChains(virBufferPtr buf,
                        const char *ifname)
2778
{
2779 2780 2781 2782 2783
    enum l3_proto_idx i;

    for (i = 0; i < L3_PROTO_LAST_IDX; i++) {
        ebtablesRemoveSubChain(buf, 1, ifname, i);
        ebtablesRemoveSubChain(buf, 0, ifname, i);
2784 2785 2786 2787 2788 2789 2790
    }

    return 0;
}


static int
2791
ebtablesRemoveTmpSubChain(virBufferPtr buf,
2792 2793
                          int incoming,
                          const char *ifname,
2794
                          enum l3_proto_idx protoidx)
2795
{
2796
    return _ebtablesRemoveSubChain(buf,
2797
                                   incoming, ifname, protoidx, 1);
2798 2799 2800 2801
}


static int
2802
ebtablesRemoveTmpSubChains(virBufferPtr buf,
2803 2804
                           const char *ifname)
{
2805 2806 2807 2808 2809
    enum l3_proto_idx i;

    for (i = 0; i < L3_PROTO_LAST_IDX; i++) {
        ebtablesRemoveTmpSubChain(buf, 1, ifname, i);
        ebtablesRemoveTmpSubChain(buf, 0, ifname, i);
2810 2811 2812 2813 2814 2815 2816
    }

    return 0;
}


static int
2817
ebtablesRenameTmpSubChain(virBufferPtr buf,
2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
                          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);
    }

    virBufferVSprintf(buf,
2837 2838
                      "%s -t %s -E %s %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, tmpchain, chain);
2839 2840 2841 2842 2843
    return 0;
}


static int
2844
ebtablesRenameTmpSubChains(virBufferPtr buf,
2845 2846
                           const char *ifname)
{
2847 2848 2849 2850 2851
    enum l3_proto_idx i;

    for (i = 0; i < L3_PROTO_LAST_IDX; i++) {
        ebtablesRenameTmpSubChain (buf, 1, ifname, l3_protocols[i].val);
        ebtablesRenameTmpSubChain (buf, 0, ifname, l3_protocols[i].val);
2852 2853 2854 2855 2856 2857 2858
    }

    return 0;
}


static int
2859
ebtablesRenameTmpRootChain(virBufferPtr buf,
2860 2861 2862
                           int incoming,
                           const char *ifname)
{
2863
    return ebtablesRenameTmpSubChain(buf, incoming, ifname, NULL);
2864 2865 2866 2867
}


static void
2868
ebiptablesInstCommand(virBufferPtr buf,
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
                      const char *templ, char cmd, int pos,
                      int stopOnError)
{
    char position[10] = { 0 };
    if (pos >= 0)
        snprintf(position, sizeof(position), "%d", pos);
    virBufferVSprintf(buf, templ, cmd, position);
    virBufferVSprintf(buf, CMD_SEPARATOR "%s",
                      CMD_STOPONERR(stopOnError));
}


2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
/**
 * 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);
}

2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
/**
 * 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
 */
2907
static int
2908 2909 2910 2911 2912 2913 2914 2915 2916
ebtablesApplyBasicRules(const char *ifname,
                        const unsigned char *macaddr)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;
    char chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix = CHAINPREFIX_HOST_IN_TEMP;
    char macaddr_str[VIR_MAC_STRING_BUFLEN];

2917 2918 2919 2920 2921 2922 2923
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

2924 2925
    virFormatMacAddr(macaddr, macaddr_str);

2926
    ebtablesCleanAll(ifname);
2927 2928 2929 2930 2931

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

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);
    virBufferVSprintf(&buf,
2932
                      CMD_DEF("%s -t %s -A %s -s ! %s -j DROP") CMD_SEPARATOR
2933 2934 2935
                      CMD_EXEC
                      "%s",

2936 2937
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                      chain, macaddr_str,
2938 2939 2940
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
2941
                      CMD_DEF("%s -t %s -A %s -p IPv4 -j ACCEPT") CMD_SEPARATOR
2942 2943 2944
                      CMD_EXEC
                      "%s",

2945
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2946 2947 2948
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
2949
                      CMD_DEF("%s -t %s -A %s -p ARP -j ACCEPT") CMD_SEPARATOR
2950 2951 2952
                      CMD_EXEC
                      "%s",

2953
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2954 2955 2956
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
2957
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
2958 2959 2960
                      CMD_EXEC
                      "%s",

2961
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2962 2963 2964
                      CMD_STOPONERR(1));

    ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
2965
    ebtablesRenameTmpRootChain(&buf, 1, ifname);
2966 2967 2968 2969 2970 2971 2972

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

    return 0;

tear_down_tmpebchains:
2973
    ebtablesCleanAll(ifname);
2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996

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

    return 1;
}


/**
 * ebtablesApplyDHCPOnlyRules
 *
 * @ifname: name of the backend-interface to which to apply the rules
 * @macaddr: MAC address the VM is using in packets sent through the
 *    interface
 * @dhcpserver: The DHCP server from which the VM may receive traffic
 *    from; may be NULL
 *
 * Returns 0 on success, 1 on failure with the rules removed
 *
 * Apply filtering rules so that the VM can only send and receive
 * DHCP traffic and nothing else.
 */
2997
static int
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
ebtablesApplyDHCPOnlyRules(const char *ifname,
                           const unsigned char *macaddr,
                           const char *dhcpserver)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;
    char chain_in [MAX_CHAINNAME_LENGTH],
         chain_out[MAX_CHAINNAME_LENGTH];
    char macaddr_str[VIR_MAC_STRING_BUFLEN];
    char *srcIPParam = NULL;

3009 3010 3011 3012 3013 3014 3015
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

3016 3017 3018 3019 3020 3021 3022 3023 3024
    if (dhcpserver) {
        virBufferVSprintf(&buf, " --ip-src %s", dhcpserver);
        if (virBufferError(&buf))
            return 1;
        srcIPParam = virBufferContentAndReset(&buf);
    }

    virFormatMacAddr(macaddr, macaddr_str);

3025
    ebtablesCleanAll(ifname);
3026 3027 3028 3029 3030 3031 3032 3033

    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);

    virBufferVSprintf(&buf,
3034
                      CMD_DEF("%s -t %s -A %s"
3035 3036 3037 3038 3039 3040 3041 3042
                              " -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",

3043
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_in,
3044 3045 3046 3047
                      macaddr_str,
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
3048
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
3049 3050 3051
                      CMD_EXEC
                      "%s",

3052
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_in,
3053 3054 3055
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
3056
                      CMD_DEF("%s -t %s -A %s"
3057 3058 3059 3060 3061 3062 3063 3064
                              " -d %s"
                              " -p ipv4 --ip-protocol udp"
                              " %s"
                              " --ip-sport 67 --ip-dport 68"
                              " -j ACCEPT") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

3065
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_out,
3066 3067 3068 3069 3070
                      macaddr_str,
                      srcIPParam != NULL ? srcIPParam : "",
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
3071
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
3072 3073 3074
                      CMD_EXEC
                      "%s",

3075
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_out,
3076 3077 3078 3079
                      CMD_STOPONERR(1));

    ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
    ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
3080 3081
    ebtablesRenameTmpRootChain(&buf, 1, ifname);
    ebtablesRenameTmpRootChain(&buf, 0, ifname);
3082 3083 3084 3085 3086 3087 3088 3089 3090

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

    VIR_FREE(srcIPParam);

    return 0;

tear_down_tmpebchains:
3091
    ebtablesCleanAll(ifname);
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102

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

    VIR_FREE(srcIPParam);

    return 1;
}


3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
/**
 * ebtablesApplyDropAllRules
 *
 * @ifname: name of the backend-interface to which to apply the rules
 *
 * Returns 0 on success, 1 on failure with the rules removed
 *
 * Apply filtering rules so that the VM cannot receive or send traffic.
 */
static int
ebtablesApplyDropAllRules(const char *ifname)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;
    char chain_in [MAX_CHAINNAME_LENGTH],
         chain_out[MAX_CHAINNAME_LENGTH];

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

    ebtablesCleanAll(ifname);

    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);

    virBufferVSprintf(&buf,
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

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

    virBufferVSprintf(&buf,
                      CMD_DEF("%s -t %s -A %s -j DROP") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

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

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

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

    return 0;

tear_down_tmpebchains:
    ebtablesCleanAll(ifname);

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

    return 1;
}


3172
static int
3173
ebtablesRemoveBasicRules(const char *ifname)
3174 3175 3176 3177 3178 3179
{
    return ebtablesCleanAll(ifname);
}


static int ebtablesCleanAll(const char *ifname)
3180 3181 3182 3183
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;

3184 3185 3186
    if (!ebtables_cmd_path)
        return 0;

3187 3188 3189 3190 3191 3192
    ebtablesUnlinkRootChain(&buf, 1, ifname);
    ebtablesUnlinkRootChain(&buf, 0, ifname);
    ebtablesRemoveSubChains(&buf, ifname);
    ebtablesRemoveRootChain(&buf, 1, ifname);
    ebtablesRemoveRootChain(&buf, 0, ifname);

3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);

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


3204 3205 3206 3207 3208 3209 3210 3211 3212
static int
ebiptablesRuleOrderSort(const void *a, const void *b)
{
    const ebiptablesRuleInstPtr *insta = a;
    const ebiptablesRuleInstPtr *instb = b;
    return ((*insta)->priority - (*instb)->priority);
}


3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
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);
                    VIR_WARN0(msg);
                    if (isIPv6)
                        lastReportIPv6 = now;
                    else
                        lastReport = now;
                }
            }
            close(fd);
        }
    }
}


3252
static int
3253
ebiptablesApplyNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3254 3255 3256 3257 3258 3259 3260 3261 3262
                        const char *ifname,
                        int nruleInstances,
                        void **_inst)
{
    int i;
    int cli_status;
    ebiptablesRuleInstPtr *inst = (ebiptablesRuleInstPtr *)_inst;
    int chains_in = 0, chains_out = 0;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
3263 3264
    bool haveIptables = false;
    bool haveIp6tables = false;
3265

3266 3267
    if (nruleInstances > 1 && inst)
        qsort(inst, nruleInstances, sizeof(inst[0]), ebiptablesRuleOrderSort);
3268 3269

    for (i = 0; i < nruleInstances; i++) {
3270
        sa_assert (inst);
S
Stefan Berger 已提交
3271 3272 3273 3274 3275 3276
        if (inst[i]->ruleType == RT_EBTABLES) {
            if (inst[i]->chainprefix == CHAINPREFIX_HOST_IN_TEMP)
                chains_in  |= (1 << inst[i]->neededProtocolChain);
            else
                chains_out |= (1 << inst[i]->neededProtocolChain);
        }
3277 3278
    }

3279 3280 3281 3282 3283 3284 3285 3286
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
3287 3288

    if (chains_in != 0)
3289
        ebtablesCreateTmpRootChain(&buf, 1, ifname, 1);
3290
    if (chains_out != 0)
3291
        ebtablesCreateTmpRootChain(&buf, 0, ifname, 1);
3292 3293

    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv4))
3294
        ebtablesCreateTmpSubChain(&buf, 1, ifname, L3_PROTO_IPV4_IDX, 1);
3295
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv4))
3296
        ebtablesCreateTmpSubChain(&buf, 0, ifname, L3_PROTO_IPV4_IDX, 1);
3297

3298
    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv6))
3299
        ebtablesCreateTmpSubChain(&buf, 1, ifname, L3_PROTO_IPV6_IDX, 1);
3300
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv6))
3301
        ebtablesCreateTmpSubChain(&buf, 0, ifname, L3_PROTO_IPV6_IDX, 1);
3302

3303
    // keep arp,rarp as last
3304
    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_ARP))
3305
        ebtablesCreateTmpSubChain(&buf, 1, ifname, L3_PROTO_ARP_IDX, 1);
3306
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_ARP))
3307 3308 3309 3310 3311
        ebtablesCreateTmpSubChain(&buf, 0, ifname, L3_PROTO_ARP_IDX, 1);
    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_RARP))
        ebtablesCreateTmpSubChain(&buf, 1, ifname, L3_PROTO_RARP_IDX, 1);
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_RARP))
        ebtablesCreateTmpSubChain(&buf, 0, ifname, L3_PROTO_RARP_IDX, 1);
3312

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

3316
    for (i = 0; i < nruleInstances; i++) {
3317
        sa_assert (inst);
S
Stefan Berger 已提交
3318 3319
        switch (inst[i]->ruleType) {
        case RT_EBTABLES:
3320
            ebiptablesInstCommand(&buf,
S
Stefan Berger 已提交
3321 3322 3323 3324
                                  inst[i]->commandTemplate,
                                  'A', -1, 1);
        break;
        case RT_IPTABLES:
3325
            haveIptables = true;
S
Stefan Berger 已提交
3326
        break;
3327
        case RT_IP6TABLES:
3328
            haveIp6tables = true;
3329
        break;
S
Stefan Berger 已提交
3330
        }
3331
    }
3332

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

S
Stefan Berger 已提交
3336
    if (haveIptables) {
3337 3338
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3339

3340
        iptablesCreateBaseChains(iptables_cmd_path, &buf);
S
Stefan Berger 已提交
3341

3342
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3343 3344
            goto tear_down_tmpebchains;

3345
        iptablesCreateTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3346

3347
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3348 3349
           goto tear_down_tmpiptchains;

3350 3351
        iptablesLinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesSetupVirtInPost(iptables_cmd_path, &buf, ifname);
3352
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3353 3354 3355
           goto tear_down_tmpiptchains;

        for (i = 0; i < nruleInstances; i++) {
3356
            sa_assert (inst);
S
Stefan Berger 已提交
3357
            if (inst[i]->ruleType == RT_IPTABLES)
3358
                iptablesInstCommand(&buf,
S
Stefan Berger 已提交
3359 3360 3361 3362
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3363
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3364
           goto tear_down_tmpiptchains;
3365 3366

        iptablesCheckBridgeNFCallEnabled(false);
S
Stefan Berger 已提交
3367 3368
    }

3369
    if (haveIp6tables) {
3370 3371
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3372

3373
        iptablesCreateBaseChains(ip6tables_cmd_path, &buf);
3374

3375
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3376 3377
            goto tear_down_tmpiptchains;

3378
        iptablesCreateTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3379

3380
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3381 3382
           goto tear_down_tmpip6tchains;

3383 3384
        iptablesLinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesSetupVirtInPost(ip6tables_cmd_path, &buf, ifname);
3385
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3386 3387 3388 3389
           goto tear_down_tmpip6tchains;

        for (i = 0; i < nruleInstances; i++) {
            if (inst[i]->ruleType == RT_IP6TABLES)
3390
                iptablesInstCommand(&buf,
3391 3392 3393 3394
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3395
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3396
           goto tear_down_tmpip6tchains;
3397 3398

        iptablesCheckBridgeNFCallEnabled(true);
3399 3400
    }

3401
    if (chains_in != 0)
3402
        ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
3403
    if (chains_out != 0)
3404
        ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
3405

3406
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3407 3408 3409 3410 3411
        goto tear_down_ebsubchains_and_unlink;

    return 0;

tear_down_ebsubchains_and_unlink:
3412 3413 3414 3415
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    }
3416

3417 3418
tear_down_tmpip6tchains:
    if (haveIp6tables) {
3419 3420
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3421 3422
    }

S
Stefan Berger 已提交
3423 3424
tear_down_tmpiptchains:
    if (haveIptables) {
3425 3426
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3427 3428
    }

3429
tear_down_tmpebchains:
3430 3431 3432 3433 3434
    if (ebtables_cmd_path) {
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3435

3436
    ebiptablesExecCLI(&buf, &cli_status);
3437

3438
    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3439 3440 3441
                           _("Some rules could not be created for "
                             "interface %s."),
                           ifname);
3442 3443 3444 3445 3446 3447

    return 1;
}


static int
3448
ebiptablesTearNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3449 3450 3451 3452 3453
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

3454 3455 3456 3457
    if (iptables_cmd_path) {
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
    }
3458

3459 3460 3461 3462
    if (ip6tables_cmd_path) {
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
    }
S
Stefan Berger 已提交
3463

3464 3465 3466
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
3467

3468 3469 3470 3471
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3472

3473
    ebiptablesExecCLI(&buf, &cli_status);
3474 3475 3476 3477 3478 3479

    return 0;
}


static int
3480
ebiptablesTearOldRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3481 3482 3483 3484 3485
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

S
Stefan Berger 已提交
3486
    // switch to new iptables user defined chains
3487 3488 3489
    if (iptables_cmd_path) {
        iptablesUnlinkRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3490

3491 3492 3493
        iptablesRenameTmpRootChains(iptables_cmd_path, &buf, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
3494

3495 3496 3497
    if (ip6tables_cmd_path) {
        iptablesUnlinkRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(ip6tables_cmd_path, &buf, ifname);
3498

3499 3500 3501
        iptablesRenameTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
S
Stefan Berger 已提交
3502

3503 3504 3505
    if (ebtables_cmd_path) {
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3506

3507
        ebtablesRemoveSubChains(&buf, ifname);
3508

3509 3510
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
3511

3512 3513 3514
        ebtablesRenameTmpSubChains(&buf, ifname);
        ebtablesRenameTmpRootChain(&buf, 1, ifname);
        ebtablesRenameTmpRootChain(&buf, 0, ifname);
3515

3516 3517
        ebiptablesExecCLI(&buf, &cli_status);
    }
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535

    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
3536
ebiptablesRemoveRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
                      const char *ifname ATTRIBUTE_UNUSED,
                      int nruleInstances,
                      void **_inst)
{
    int rc = 0;
    int cli_status;
    int i;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    ebiptablesRuleInstPtr *inst = (ebiptablesRuleInstPtr *)_inst;

    for (i = 0; i < nruleInstances; i++)
3548
        ebiptablesInstCommand(&buf,
3549 3550 3551 3552
                              inst[i]->commandTemplate,
                              'D', -1,
                              0);

3553
    if (ebiptablesExecCLI(&buf, &cli_status))
3554 3555 3556
        goto err_exit;

    if (cli_status) {
3557
        virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582
                               "%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;

3583 3584 3585 3586 3587
    if (iptables_cmd_path) {
        iptablesUnlinkRootChains(iptables_cmd_path, &buf, ifname);
        iptablesClearVirtInPost (iptables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(iptables_cmd_path, &buf, ifname);
    }
3588

3589 3590 3591 3592 3593
    if (ip6tables_cmd_path) {
        iptablesUnlinkRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesClearVirtInPost (ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(ip6tables_cmd_path, &buf, ifname);
    }
S
Stefan Berger 已提交
3594

3595 3596 3597
    if (ebtables_cmd_path) {
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3598

3599 3600
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
3601

3602 3603
        ebtablesRemoveSubChains(&buf, ifname);
    }
3604

3605
    ebiptablesExecCLI(&buf, &cli_status);
3606 3607 3608 3609 3610 3611 3612

    return 0;
}


virNWFilterTechDriver ebiptables_driver = {
    .name = EBIPTABLES_DRIVER_ID,
3613 3614 3615 3616
    .flags = 0,

    .init     = ebiptablesDriverInit,
    .shutdown = ebiptablesDriverShutdown,
3617 3618 3619 3620 3621 3622 3623 3624 3625

    .createRuleInstance  = ebiptablesCreateRuleInstance,
    .applyNewRules       = ebiptablesApplyNewRules,
    .tearNewRules        = ebiptablesTearNewRules,
    .tearOldRules        = ebiptablesTearOldRules,
    .allTeardown         = ebiptablesAllTeardown,
    .removeRules         = ebiptablesRemoveRules,
    .freeRuleInstance    = ebiptablesFreeRuleInstance,
    .displayRuleInstance = ebiptablesDisplayRuleInstance,
3626 3627 3628 3629

    .canApplyBasicRules  = ebiptablesCanApplyBasicRules,
    .applyBasicRules     = ebtablesApplyBasicRules,
    .applyDHCPOnlyRules  = ebtablesApplyDHCPOnlyRules,
3630
    .applyDropAllRules   = ebtablesApplyDropAllRules,
3631
    .removeBasicRules    = ebtablesRemoveBasicRules,
3632
};
3633 3634 3635 3636 3637 3638 3639 3640


static int
ebiptablesDriverInit(void)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;

3641 3642 3643
    if (virMutexInit(&execCLIMutex))
        return EINVAL;

3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
    bash_cmd_path = virFindFileInPath("bash");
    gawk_cmd_path = virFindFileInPath("gawk");
    grep_cmd_path = virFindFileInPath("grep");

    ebtables_cmd_path = virFindFileInPath("ebtables");
    if (ebtables_cmd_path) {
        /* basic probing */
        virBufferVSprintf(&buf,
                          CMD_DEF("%s -t %s -L") CMD_SEPARATOR
                          CMD_EXEC
                          "%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                          CMD_STOPONERR(1));

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

    iptables_cmd_path = virFindFileInPath("iptables");
    if (iptables_cmd_path) {
        virBufferVSprintf(&buf,
                          CMD_DEF("%s -L FORWARD") CMD_SEPARATOR
                          CMD_EXEC
                          "%s",
                          iptables_cmd_path,
                          CMD_STOPONERR(1));

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

    ip6tables_cmd_path = virFindFileInPath("ip6tables");
    if (ip6tables_cmd_path) {
        virBufferVSprintf(&buf,
                          CMD_DEF("%s -L FORWARD") CMD_SEPARATOR
                          CMD_EXEC
                          "%s",
                          ip6tables_cmd_path,
                          CMD_STOPONERR(1));

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

    /* ip(6)tables support needs bash, gawk & grep, ebtables doesn't */
    if ((iptables_cmd_path != NULL || ip6tables_cmd_path != NULL) &&
        (!grep_cmd_path || !bash_cmd_path || !gawk_cmd_path)) {
        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
ebiptablesDriverShutdown()
{
    VIR_FREE(gawk_cmd_path);
    VIR_FREE(bash_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;
}