nwfilter_ebiptables_driver.c 105.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
 * 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>

#include <sys/stat.h>

#include "internal.h"

#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "virterror_internal.h"
#include "domain_conf.h"
35
#include "nwfilter_conf.h"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#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"
#define CMD_DEF_PRE  "cmd=\""
#define CMD_DEF_POST "\""
#define CMD_DEF(X) CMD_DEF_PRE X CMD_DEF_POST
#define CMD_EXEC   "res=`${cmd}`" CMD_SEPARATOR
#define CMD_STOPONERR(X) \
    X ? "if [ $? -ne 0 ]; then" \
        "  echo \"Failure to execute command '${cmd}'.\";" \
        "  exit 1;" \
        "fi" CMD_SEPARATOR \
      : ""


66 67 68 69 70 71 72
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;

73 74 75 76 77 78 79

#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 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
#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


102
static int ebtablesRemoveBasicRules(const char *ifname);
103 104 105 106
static int ebiptablesDriverInit(void);
static void ebiptablesDriverShutdown(void);


107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
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),
129 130 131 132
};


static int
133
printVar(virNWFilterHashTablePtr vars,
134 135 136 137 138 139 140 141 142
         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) {
143
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
144 145 146 147 148 149
                                   _("cannot find value for '%s'"),
                                   item->var);
            return 1;
        }

        if (!virStrcpy(buf, val, bufsize)) {
150
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
151 152 153 154 155 156 157 158 159 160 161 162 163
                                   _("Buffer to small to print MAC address "
                                   "'%s' into"),
                                   item->var);
            return 1;
        }

        *done = 1;
    }
    return 0;
}


static int
164
_printDataType(virNWFilterHashTablePtr vars,
165 166 167
               char *buf, int bufsize,
               nwItemDescPtr item,
               bool asHex)
168 169
{
    int done;
170
    char *data;
171

172
    if (printVar(vars, buf, bufsize, item, &done))
173 174 175 176 177 178 179
        return 1;

    if (done)
        return 0;

    switch (item->datatype) {
    case DATATYPE_IPADDR:
180 181
        data = virSocketFormatAddr(&item->u.ipaddr.addr);
        if (!data) {
182
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
183 184 185 186 187
                                   _("internal IPv4 address representation "
                                     "is bad"));
            return 1;
        }
        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
188
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
189 190
                                   _("buffer too small for IP address"));
            VIR_FREE(data);
191 192
            return 1;
        }
193
        VIR_FREE(data);
194 195
    break;

196
    case DATATYPE_IPV6ADDR:
197 198
        data = virSocketFormatAddr(&item->u.ipaddr.addr);
        if (!data) {
199
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
200 201 202 203 204 205
                                   _("internal IPv6 address representation "
                                     "is bad"));
            return 1;
        }

        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
206
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
207 208 209
                                   _("buffer too small for IPv6 address"));
            VIR_FREE(data);
            return 1;
210
        }
211
        VIR_FREE(data);
212 213
    break;

214
    case DATATYPE_MACADDR:
215
    case DATATYPE_MACMASK:
216
        if (bufsize < VIR_MAC_STRING_BUFLEN) {
217
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
218 219 220 221 222 223 224
                                   _("Buffer too small for MAC address"));
            return 1;
        }

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

225 226
    case DATATYPE_IPV6MASK:
    case DATATYPE_IPMASK:
227
        if (snprintf(buf, bufsize, "%d",
228
                     item->u.u8) >= bufsize) {
229
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
230 231 232 233 234 235
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT16:
236
    case DATATYPE_UINT16_HEX:
237
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
238
                     item->u.u16) >= bufsize) {
239
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
240 241 242 243 244 245
                                   _("Buffer too small for uint16 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT8:
246
    case DATATYPE_UINT8_HEX:
247
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
248
                     item->u.u8) >= bufsize) {
249
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
250 251 252 253 254 255
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    default:
256
        virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
257 258 259 260 261 262 263 264 265
                               _("Unhandled datatype %x"), item->datatype);
        return 1;
    break;
    }

    return 0;
}


266
static int
267
printDataType(virNWFilterHashTablePtr vars,
268 269 270
              char *buf, int bufsize,
              nwItemDescPtr item)
{
271
    return _printDataType(vars, buf, bufsize, item, 0);
272 273 274 275
}


static int
276
printDataTypeAsHex(virNWFilterHashTablePtr vars,
277 278 279
                   char *buf, int bufsize,
                   nwItemDescPtr item)
{
280
    return _printDataType(vars, buf, bufsize, item, 1);
281 282 283
}


S
Stefan Berger 已提交
284 285 286 287 288 289 290 291 292 293 294 295
static void
ebiptablesRuleInstFree(ebiptablesRuleInstPtr inst)
{
    if (!inst)
        return;

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


static int
296
ebiptablesAddRuleInst(virNWFilterRuleInstPtr res,
S
Stefan Berger 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
                      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;

316
    return virNWFilterRuleInstAddData(res, inst);
S
Stefan Berger 已提交
317 318 319 320
}


static int
321
ebtablesHandleEthHdr(virBufferPtr buf,
S
Stefan Berger 已提交
322
                     virNWFilterHashTablePtr vars,
323 324
                     ethHdrDataDefPtr ethHdr,
                     bool reverse)
S
Stefan Berger 已提交
325 326 327 328
{
    char macaddr[VIR_MAC_STRING_BUFLEN];

    if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACAddr)) {
329
        if (printDataType(vars,
S
Stefan Berger 已提交
330 331 332 333 334
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataSrcMACAddr))
            goto err_exit;

        virBufferVSprintf(buf,
335 336
                      " %s %s %s",
                      reverse ? "-d" : "-s",
S
Stefan Berger 已提交
337 338 339 340
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataSrcMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACMask)) {
341
            if (printDataType(vars,
S
Stefan Berger 已提交
342 343 344 345 346 347 348 349 350 351 352
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataSrcMACMask))
                goto err_exit;

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

    if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACAddr)) {
353
        if (printDataType(vars,
S
Stefan Berger 已提交
354 355 356 357 358
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataDstMACAddr))
            goto err_exit;

        virBufferVSprintf(buf,
359 360
                      " %s %s %s",
                      reverse ? "-s" : "-d",
S
Stefan Berger 已提交
361 362 363 364
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataDstMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACMask)) {
365
            if (printDataType(vars,
S
Stefan Berger 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataDstMACMask))
                goto err_exit;

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

    return 0;

 err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


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

387
static int iptablesLinkIPTablesBaseChain(const char *iptables_cmd,
S
Stefan Berger 已提交
388 389 390 391 392 393 394
                                         virBufferPtr buf,
                                         const char *udchain,
                                         const char *syschain,
                                         unsigned int pos,
                                         int stopOnError)
{
    virBufferVSprintf(buf,
395
                      "res=$(%s -L %s -n --line-number | "
396
                          "%s \" %s \")\n"
S
Stefan Berger 已提交
397
                      "if [ $? -ne 0 ]; then\n"
398
                      "  %s -I %s %d -j %s\n"
S
Stefan Berger 已提交
399
                      "else\n"
400
                      "  r=$(echo $res | %s '{print $1}')\n"
S
Stefan Berger 已提交
401
                      "  if [ \"${r}\" != \"%d\" ]; then\n"
402
                      "    " CMD_DEF("%s -I %s %d -j %s") CMD_SEPARATOR
S
Stefan Berger 已提交
403 404 405
                      "    " CMD_EXEC
                      "    %s"
                      "    let r=r+1\n"
406
                      "    " CMD_DEF("%s -D %s ${r}") CMD_SEPARATOR
S
Stefan Berger 已提交
407 408 409 410 411
                      "    " CMD_EXEC
                      "    %s"
                      "  fi\n"
                      "fi\n",

412
                      iptables_cmd, syschain,
413
                      grep_cmd_path, udchain,
S
Stefan Berger 已提交
414

415
                      iptables_cmd, syschain, pos, udchain,
416
                      gawk_cmd_path,
S
Stefan Berger 已提交
417 418 419

                      pos,

420
                      iptables_cmd, syschain, pos, udchain,
S
Stefan Berger 已提交
421 422
                      CMD_STOPONERR(stopOnError),

423
                      iptables_cmd, syschain,
S
Stefan Berger 已提交
424 425 426 427 428
                      CMD_STOPONERR(stopOnError));
    return 0;
}


429
static int iptablesCreateBaseChains(const char *iptables_cmd,
S
Stefan Berger 已提交
430 431
                                    virBufferPtr buf)
{
432 433 434 435 436 437 438 439
    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);
440
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
441
                                  VIRT_IN_CHAIN     , "FORWARD", 1, 1);
442
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
443
                                  VIRT_OUT_CHAIN    , "FORWARD", 2, 1);
444
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
445
                                  VIRT_IN_POST_CHAIN, "FORWARD", 3, 1);
446
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
447 448 449 450 451 452 453
                                  HOST_IN_CHAIN     , "INPUT"  , 1, 1);

    return 0;
}


static int
454
iptablesCreateTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                           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,
470
                      CMD_DEF("%s -N %s") CMD_SEPARATOR
S
Stefan Berger 已提交
471 472
                      CMD_EXEC
                      "%s",
473
                      iptables_cmd,
S
Stefan Berger 已提交
474 475 476 477 478 479 480 481
                      chain,
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
482
iptablesCreateTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
483 484 485
                            virBufferPtr buf,
                            const char *ifname)
{
486 487 488
    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 已提交
489 490 491 492 493
    return 0;
}


static int
494
_iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
                         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,
515 516 517 518
                      "%s -F %s" CMD_SEPARATOR
                      "%s -X %s" CMD_SEPARATOR,
                      iptables_cmd, chain,
                      iptables_cmd, chain);
S
Stefan Berger 已提交
519 520 521 522 523 524

    return 0;
}


static int
525
iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
526 527 528 529 530
                        virBufferPtr buf,
                        char prefix,
                        int incoming,
                        const char *ifname)
{
531
    return _iptablesRemoveRootChain(iptables_cmd,
532
                                    buf, prefix, incoming, ifname, 0);
S
Stefan Berger 已提交
533 534 535 536
}


static int
537
iptablesRemoveTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
538 539 540 541 542
                           virBufferPtr buf,
                           char prefix,
                           int incoming,
                           const char *ifname)
{
543
    return _iptablesRemoveRootChain(iptables_cmd, buf, prefix,
544
                                    incoming, ifname, 1);
S
Stefan Berger 已提交
545 546 547 548
}


static int
549
iptablesRemoveTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
550 551 552
                            virBufferPtr buf,
                            const char *ifname)
{
553 554 555
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
556 557 558 559 560
    return 0;
}


static int
561
iptablesRemoveRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
562 563 564
                         virBufferPtr buf,
                         const char *ifname)
{
565 566 567
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
568 569 570 571 572
    return 0;
}


static int
573
iptablesLinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
                         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,
592
                      CMD_DEF("%s -A %s "
S
Stefan Berger 已提交
593 594 595
                              "%s %s -g %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",
596
                      iptables_cmd,
S
Stefan Berger 已提交
597 598 599 600 601 602 603 604 605 606
                      basechain,
                      match, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
607
iptablesLinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
608 609 610
                          virBufferPtr buf,
                          const char *ifname)
{
611 612 613
    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 已提交
614 615 616 617 618 619

    return 0;
}


static int
620
iptablesSetupVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
621 622 623 624 625
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
    virBufferVSprintf(buf,
626
                      "res=$(%s -L " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
627 628
                      " | grep \"\\%s %s\")\n"
                      "if [ \"${res}\" == \"\" ]; then "
629
                        CMD_DEF("%s"
S
Stefan Berger 已提交
630 631 632 633 634
                        " -A " VIRT_IN_POST_CHAIN
                        " %s %s -j ACCEPT") CMD_SEPARATOR
                        CMD_EXEC
                        "%s"
                      "fi\n",
635
                      iptables_cmd,
S
Stefan Berger 已提交
636
                      PHYSDEV_IN, ifname,
637
                      iptables_cmd,
S
Stefan Berger 已提交
638 639 640 641 642 643 644
                      match, ifname,
                      CMD_STOPONERR(1));
    return 0;
}


static int
645
iptablesClearVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
646 647 648 649 650
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
    virBufferVSprintf(buf,
651
                      "%s -D " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
652
                      " %s %s -j ACCEPT" CMD_SEPARATOR,
653
                      iptables_cmd,
S
Stefan Berger 已提交
654 655 656 657 658
                      match, ifname);
    return 0;
}

static int
659 660 661 662 663 664
_iptablesUnlinkRootChain(const char *iptables_cmd,
                         virBufferPtr buf,
                         const char *basechain,
                         char prefix,
                         int incoming, const char *ifname,
                         int isTempChain)
S
Stefan Berger 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
{
    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,
682
                      "%s -D %s "
S
Stefan Berger 已提交
683
                      "%s %s -g %s" CMD_SEPARATOR,
684
                      iptables_cmd,
S
Stefan Berger 已提交
685 686 687 688 689 690 691 692
                      basechain,
                      match, ifname, chain);

    return 0;
}


static int
693
iptablesUnlinkRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
694 695 696 697 698
                        virBufferPtr buf,
                        const char *basechain,
                        char prefix,
                        int incoming, const char *ifname)
{
699
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
700 701 702 703 704
                                    basechain, prefix, incoming, ifname, 0);
}


static int
705
iptablesUnlinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
706 707 708 709 710
                           virBufferPtr buf,
                           const char *basechain,
                           char prefix,
                           int incoming, const char *ifname)
{
711
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
712 713 714 715 716
                                    basechain, prefix, incoming, ifname, 1);
}


static int
717
iptablesUnlinkRootChains(const char *cmd,
S
Stefan Berger 已提交
718 719 720
                         virBufferPtr buf,
                         const char *ifname)
{
721 722 723
    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 已提交
724 725 726 727 728 729

    return 0;
}


static int
730
iptablesUnlinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
731 732 733
                            virBufferPtr buf,
                            const char *ifname)
{
734 735 736
    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 已提交
737 738 739 740 741
    return 0;
}


static int
742
iptablesRenameTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
                           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,
764 765
                      "%s -E %s %s" CMD_SEPARATOR,
                      iptables_cmd,
S
Stefan Berger 已提交
766 767 768 769 770 771 772
                      tmpchain,
                      chain);
    return 0;
}


static int
773
iptablesRenameTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
774 775 776
                            virBufferPtr buf,
                            const char *ifname)
{
777 778 779
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
780 781 782 783 784
    return 0;
}


static void
785
iptablesInstCommand(virBufferPtr buf,
S
Stefan Berger 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798
                    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
799
iptablesHandleSrcMacAddr(virBufferPtr buf,
S
Stefan Berger 已提交
800 801
                         virNWFilterHashTablePtr vars,
                         nwItemDescPtr srcMacAddr,
802 803
                         int directionIn,
                         bool *srcmacskipped)
S
Stefan Berger 已提交
804 805
{
    char macaddr[VIR_MAC_STRING_BUFLEN];
806
    *srcmacskipped = false;
S
Stefan Berger 已提交
807 808

    if (HAS_ENTRY_ITEM(srcMacAddr)) {
809 810 811 812 813
        if (directionIn) {
            *srcmacskipped = true;
            return 0;
        }

814
        if (printDataType(vars,
S
Stefan Berger 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
                          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
835
iptablesHandleIpHdr(virBufferPtr buf,
S
Stefan Berger 已提交
836 837
                    virNWFilterHashTablePtr vars,
                    ipHdrDataDefPtr ipHdr,
838 839
                    int directionIn,
                    bool *skipRule, bool *skipMatch)
S
Stefan Berger 已提交
840
{
841
    char ipaddr[INET6_ADDRSTRLEN],
S
Stefan Berger 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855
         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)) {

856
        if (printDataType(vars,
S
Stefan Berger 已提交
857 858 859 860 861 862 863 864 865 866 867 868
                          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)) {

869
            if (printDataType(vars,
S
Stefan Berger 已提交
870 871 872 873 874 875 876 877 878 879
                              number, sizeof(number),
                              &ipHdr->dataSrcIPMask))
                goto err_exit;

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

880
        if (printDataType(vars,
S
Stefan Berger 已提交
881 882 883 884 885 886 887 888 889 890 891 892
                          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)) {

893
            if (printDataType(vars,
S
Stefan Berger 已提交
894 895 896 897 898 899 900 901 902 903 904 905
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataSrcIPTo))
                goto err_exit;

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

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

906
        if (printDataType(vars,
S
Stefan Berger 已提交
907 908 909 910 911 912 913 914 915 916 917 918
                          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)) {

919
            if (printDataType(vars,
S
Stefan Berger 已提交
920 921 922 923 924 925 926 927 928 929 930
                              number, sizeof(number),
                              &ipHdr->dataDstIPMask))
                goto err_exit;

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

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

931
        if (printDataType(vars,
S
Stefan Berger 已提交
932 933 934 935 936 937 938 939 940 941 942 943
                          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)) {

944
            if (printDataType(vars,
S
Stefan Berger 已提交
945 946 947
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataDstIPTo))
                goto err_exit;
948

S
Stefan Berger 已提交
949 950 951 952 953
            virBufferVSprintf(buf,
                              "-%s",
                              ipaddr);
        }
    }
954

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

957
        if (printDataType(vars,
S
Stefan Berger 已提交
958 959 960
                          number, sizeof(number),
                          &ipHdr->dataDSCP))
           goto err_exit;
961

S
Stefan Berger 已提交
962 963 964 965
        virBufferVSprintf(buf,
                          " -m dscp %s --dscp %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDSCP),
                          number);
966 967
    }

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
    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;
        }
    }

S
Stefan Berger 已提交
986
    return 0;
987

S
Stefan Berger 已提交
988 989 990 991
err_exit:
    virBufferFreeAndReset(buf);

    return 1;
992 993 994 995
}


static int
996
iptablesHandlePortData(virBufferPtr buf,
S
Stefan Berger 已提交
997 998 999
                       virNWFilterHashTablePtr vars,
                       portDataDefPtr portData,
                       int directionIn)
1000
{
S
Stefan Berger 已提交
1001 1002 1003 1004 1005 1006 1007
    char portstr[20];
    const char *sport = "--sport";
    const char *dport = "--dport";
    if (directionIn) {
        sport = "--dport";
        dport = "--sport";
    }
1008

S
Stefan Berger 已提交
1009
    if (HAS_ENTRY_ITEM(&portData->dataSrcPortStart)) {
1010
        if (printDataType(vars,
S
Stefan Berger 已提交
1011 1012
                          portstr, sizeof(portstr),
                          &portData->dataSrcPortStart))
1013 1014 1015
            goto err_exit;

        virBufferVSprintf(buf,
S
Stefan Berger 已提交
1016 1017 1018 1019
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataSrcPortStart),
                          sport,
                          portstr);
1020

S
Stefan Berger 已提交
1021
        if (HAS_ENTRY_ITEM(&portData->dataSrcPortEnd)) {
1022
            if (printDataType(vars,
S
Stefan Berger 已提交
1023 1024
                              portstr, sizeof(portstr),
                              &portData->dataSrcPortEnd))
1025 1026
                goto err_exit;

S
Stefan Berger 已提交
1027 1028 1029
             virBufferVSprintf(buf,
                               ":%s",
                               portstr);
1030 1031 1032
        }
    }

S
Stefan Berger 已提交
1033
    if (HAS_ENTRY_ITEM(&portData->dataDstPortStart)) {
1034
        if (printDataType(vars,
S
Stefan Berger 已提交
1035 1036
                          portstr, sizeof(portstr),
                          &portData->dataDstPortStart))
1037 1038 1039
            goto err_exit;

        virBufferVSprintf(buf,
S
Stefan Berger 已提交
1040 1041 1042 1043
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataDstPortStart),
                          dport,
                          portstr);
1044

S
Stefan Berger 已提交
1045
        if (HAS_ENTRY_ITEM(&portData->dataDstPortEnd)) {
1046
            if (printDataType(vars,
S
Stefan Berger 已提交
1047 1048
                              portstr, sizeof(portstr),
                              &portData->dataDstPortEnd))
1049 1050
                goto err_exit;

S
Stefan Berger 已提交
1051 1052 1053
             virBufferVSprintf(buf,
                               ":%s",
                               portstr);
1054 1055 1056 1057 1058
        }
    }

    return 0;

S
Stefan Berger 已提交
1059
err_exit:
1060 1061 1062
    return 1;
}

S
Stefan Berger 已提交
1063 1064 1065 1066 1067 1068 1069 1070
/*
 * _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
1071 1072 1073 1074 1075 1076
 * @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 已提交
1077 1078 1079 1080 1081 1082 1083 1084
 *
 * 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
1085
_iptablesCreateRuleInstance(int directionIn,
S
Stefan Berger 已提交
1086 1087 1088 1089 1090 1091 1092
                            const char *chainPrefix,
                            virNWFilterDefPtr nwfilter,
                            virNWFilterRuleDefPtr rule,
                            const char *ifname,
                            virNWFilterHashTablePtr vars,
                            virNWFilterRuleInstPtr res,
                            const char *match,
1093
                            const char *accept_target,
1094 1095
                            bool isIPv6,
                            bool maySkipICMP)
S
Stefan Berger 已提交
1096 1097 1098 1099 1100
{
    char chain[MAX_CHAINNAME_LENGTH];
    char number[20];
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    const char *target;
1101 1102
    const char *iptables_cmd = (isIPv6) ? ip6tables_cmd_path
                                        : iptables_cmd_path;
1103 1104
    unsigned int bufUsed;
    bool srcMacSkipped = false;
1105 1106
    bool skipRule = false;
    bool skipMatch = false;
S
Stefan Berger 已提交
1107

1108 1109 1110 1111 1112 1113 1114 1115
    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 已提交
1116 1117 1118 1119
    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
1120
    case VIR_NWFILTER_RULE_PROTOCOL_TCPoIPV6:
S
Stefan Berger 已提交
1121
        virBufferVSprintf(&buf,
1122 1123
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1124 1125 1126 1127
                          chain);

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

1128 1129
        bufUsed = virBufferUse(&buf);

1130
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1131 1132
                                     vars,
                                     &rule->p.tcpHdrFilter.dataSrcMACAddr,
1133 1134
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1135 1136
            goto err_exit;

1137
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1138 1139
                                vars,
                                &rule->p.tcpHdrFilter.ipHdr,
1140 1141
                                directionIn,
                                &skipRule, &skipMatch))
S
Stefan Berger 已提交
1142 1143
            goto err_exit;

1144
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1145 1146 1147 1148 1149 1150
                                   vars,
                                   &rule->p.tcpHdrFilter.portData,
                                   directionIn))
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.tcpHdrFilter.dataTCPOption)) {
1151
            if (printDataType(vars,
S
Stefan Berger 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
                              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:
1165
    case VIR_NWFILTER_RULE_PROTOCOL_UDPoIPV6:
S
Stefan Berger 已提交
1166
        virBufferVSprintf(&buf,
1167 1168
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1169 1170 1171 1172
                          chain);

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

1173 1174
        bufUsed = virBufferUse(&buf);

1175
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1176 1177
                                     vars,
                                     &rule->p.udpHdrFilter.dataSrcMACAddr,
1178 1179
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1180 1181
            goto err_exit;

1182
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1183 1184
                                vars,
                                &rule->p.udpHdrFilter.ipHdr,
1185 1186
                                directionIn,
                                &skipRule, &skipMatch))
S
Stefan Berger 已提交
1187 1188
            goto err_exit;

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

1196
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
1197
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITEoIPV6:
1198
        virBufferVSprintf(&buf,
1199 1200
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1201 1202 1203 1204
                          chain);

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

1205 1206
        bufUsed = virBufferUse(&buf);

1207
        if (iptablesHandleSrcMacAddr(&buf,
1208 1209
                                     vars,
                                     &rule->p.udpliteHdrFilter.dataSrcMACAddr,
1210 1211
                                     directionIn,
                                     &srcMacSkipped))
1212 1213
            goto err_exit;

1214
        if (iptablesHandleIpHdr(&buf,
1215 1216
                                vars,
                                &rule->p.udpliteHdrFilter.ipHdr,
1217 1218
                                directionIn,
                                &skipRule, &skipMatch))
1219 1220 1221 1222 1223
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
1224
    case VIR_NWFILTER_RULE_PROTOCOL_ESPoIPV6:
1225
        virBufferVSprintf(&buf,
1226 1227
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1228 1229 1230 1231
                          chain);

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

1232 1233
        bufUsed = virBufferUse(&buf);

1234
        if (iptablesHandleSrcMacAddr(&buf,
1235 1236
                                     vars,
                                     &rule->p.espHdrFilter.dataSrcMACAddr,
1237 1238
                                     directionIn,
                                     &srcMacSkipped))
1239 1240
            goto err_exit;

1241
        if (iptablesHandleIpHdr(&buf,
1242 1243
                                vars,
                                &rule->p.espHdrFilter.ipHdr,
1244 1245
                                directionIn,
                                &skipRule, &skipMatch))
1246 1247 1248 1249 1250
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_AH:
1251
    case VIR_NWFILTER_RULE_PROTOCOL_AHoIPV6:
1252
        virBufferVSprintf(&buf,
1253 1254
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1255 1256 1257 1258
                          chain);

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

1259 1260
        bufUsed = virBufferUse(&buf);

1261
        if (iptablesHandleSrcMacAddr(&buf,
1262 1263
                                     vars,
                                     &rule->p.ahHdrFilter.dataSrcMACAddr,
1264 1265
                                     directionIn,
                                     &srcMacSkipped))
1266 1267
            goto err_exit;

1268
        if (iptablesHandleIpHdr(&buf,
1269 1270
                                vars,
                                &rule->p.ahHdrFilter.ipHdr,
1271 1272
                                directionIn,
                                &skipRule, &skipMatch))
1273 1274 1275 1276
            goto err_exit;

    break;

S
Stefan Berger 已提交
1277
    case VIR_NWFILTER_RULE_PROTOCOL_SCTP:
1278
    case VIR_NWFILTER_RULE_PROTOCOL_SCTPoIPV6:
S
Stefan Berger 已提交
1279
        virBufferVSprintf(&buf,
1280 1281
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1282 1283 1284 1285
                          chain);

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

1286 1287
        bufUsed = virBufferUse(&buf);

1288
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1289 1290
                                     vars,
                                     &rule->p.sctpHdrFilter.dataSrcMACAddr,
1291 1292
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1293 1294
            goto err_exit;

1295
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1296 1297
                                vars,
                                &rule->p.sctpHdrFilter.ipHdr,
1298 1299
                                directionIn,
                                &skipRule, &skipMatch))
S
Stefan Berger 已提交
1300 1301
            goto err_exit;

1302
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1303 1304 1305 1306 1307 1308 1309
                                   vars,
                                   &rule->p.sctpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
1310
    case VIR_NWFILTER_RULE_PROTOCOL_ICMPV6:
S
Stefan Berger 已提交
1311
        virBufferVSprintf(&buf,
1312 1313
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1314 1315
                          chain);

1316 1317 1318 1319
        if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
            virBufferAddLit(&buf, " -p icmp");
        else
            virBufferAddLit(&buf, " -p icmpv6");
S
Stefan Berger 已提交
1320

1321 1322
        bufUsed = virBufferUse(&buf);

1323
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1324 1325
                                     vars,
                                     &rule->p.icmpHdrFilter.dataSrcMACAddr,
1326 1327
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1328 1329
            goto err_exit;

1330
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1331 1332
                                vars,
                                &rule->p.icmpHdrFilter.ipHdr,
1333 1334
                                directionIn,
                                &skipRule, &skipMatch))
S
Stefan Berger 已提交
1335 1336 1337
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPType)) {
1338
            const char *parm;
1339 1340 1341 1342

            if (maySkipICMP)
                goto exit_no_error;

1343 1344 1345 1346 1347
            if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
                parm = "--icmp-type";
            else
                parm = "--icmpv6-type";

1348
            if (printDataType(vars,
S
Stefan Berger 已提交
1349 1350 1351 1352 1353
                              number, sizeof(number),
                              &rule->p.icmpHdrFilter.dataICMPType))
                goto err_exit;

            virBufferVSprintf(&buf,
1354
                      " %s %s %s",
S
Stefan Berger 已提交
1355
                      ENTRY_GET_NEG_SIGN(&rule->p.icmpHdrFilter.dataICMPType),
1356
                      parm,
S
Stefan Berger 已提交
1357 1358 1359
                      number);

            if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPCode)) {
1360
                if (printDataType(vars,
S
Stefan Berger 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
                                  number, sizeof(number),
                                  &rule->p.icmpHdrFilter.dataICMPCode))
                    goto err_exit;

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

1372 1373 1374 1375 1376 1377 1378 1379
    case VIR_NWFILTER_RULE_PROTOCOL_IGMP:
        virBufferVSprintf(&buf,
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
                          chain);

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

1380 1381
        bufUsed = virBufferUse(&buf);

1382
        if (iptablesHandleSrcMacAddr(&buf,
1383 1384
                                     vars,
                                     &rule->p.igmpHdrFilter.dataSrcMACAddr,
1385 1386
                                     directionIn,
                                     &srcMacSkipped))
1387 1388
            goto err_exit;

1389
        if (iptablesHandleIpHdr(&buf,
1390 1391
                                vars,
                                &rule->p.igmpHdrFilter.ipHdr,
1392 1393
                                directionIn,
                                &skipRule, &skipMatch))
1394 1395 1396 1397
            goto err_exit;

    break;

S
Stefan Berger 已提交
1398
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
1399
    case VIR_NWFILTER_RULE_PROTOCOL_ALLoIPV6:
S
Stefan Berger 已提交
1400
        virBufferVSprintf(&buf,
1401 1402
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1403 1404 1405 1406
                          chain);

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

1407 1408
        bufUsed = virBufferUse(&buf);

1409
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1410 1411
                                     vars,
                                     &rule->p.allHdrFilter.dataSrcMACAddr,
1412 1413
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1414 1415
            goto err_exit;

1416
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1417 1418
                                vars,
                                &rule->p.allHdrFilter.ipHdr,
1419 1420
                                directionIn,
                                &skipRule, &skipMatch))
S
Stefan Berger 已提交
1421 1422 1423 1424 1425 1426 1427 1428
            goto err_exit;

    break;

    default:
        return -1;
    }

1429 1430
    if ((srcMacSkipped && bufUsed == virBufferUse(&buf)) ||
         skipRule) {
1431 1432 1433 1434
        virBufferFreeAndReset(&buf);
        return 0;
    }

S
Stefan Berger 已提交
1435 1436
    if (rule->action == VIR_NWFILTER_RULE_ACTION_ACCEPT)
        target = accept_target;
1437
    else {
S
Stefan Berger 已提交
1438
        target = "DROP";
1439
        skipMatch = true;
1440 1441
    }

1442
    if (match && !skipMatch)
1443 1444
        virBufferVSprintf(&buf, " %s", match);

S
Stefan Berger 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

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

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

1457
    return ebiptablesAddRuleInst(res,
S
Stefan Berger 已提交
1458 1459 1460 1461
                                 virBufferContentAndReset(&buf),
                                 nwfilter->chainsuffix,
                                 '\0',
                                 rule->priority,
1462
                                 (isIPv6) ? RT_IP6TABLES : RT_IPTABLES);
S
Stefan Berger 已提交
1463 1464 1465 1466 1467 1468 1469


err_exit:
    virBufferFreeAndReset(&buf);

    return -1;

1470 1471 1472 1473
exit_no_error:
    virBufferFreeAndReset(&buf);

    return 0;
S
Stefan Berger 已提交
1474 1475 1476 1477
}


static int
1478
iptablesCreateRuleInstance(virNWFilterDefPtr nwfilter,
S
Stefan Berger 已提交
1479 1480 1481
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
                           virNWFilterHashTablePtr vars,
1482 1483
                           virNWFilterRuleInstPtr res,
                           bool isIPv6)
S
Stefan Berger 已提交
1484 1485 1486 1487 1488
{
    int rc;
    int directionIn = 0;
    char chainPrefix[2];
    int needState = 1;
1489
    bool maySkipICMP, inout = false;
S
Stefan Berger 已提交
1490 1491 1492 1493 1494

    if ((rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN) ||
        (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT)) {
        directionIn = 1;
        needState = 0;
1495
        inout = (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
S
Stefan Berger 已提交
1496 1497 1498 1499
    }

    chainPrefix[0] = 'F';

1500 1501
    maySkipICMP = directionIn || inout;

S
Stefan Berger 已提交
1502
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1503
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1504 1505 1506 1507 1508 1509 1510 1511
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
                                     needState ? MATCH_STATE_OUT
                                               : NULL,
1512
                                     "RETURN",
1513 1514
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1515 1516 1517
    if (rc)
        return rc;

1518 1519 1520

    maySkipICMP = !directionIn || inout;

S
Stefan Berger 已提交
1521
    chainPrefix[1] = CHAINPREFIX_HOST_OUT_TEMP;
1522
    rc = _iptablesCreateRuleInstance(!directionIn,
S
Stefan Berger 已提交
1523 1524 1525 1526 1527 1528 1529 1530
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
                                     needState ? MATCH_STATE_IN
                                               : NULL,
1531
                                     "ACCEPT",
1532 1533
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1534 1535 1536
    if (rc)
        return rc;

1537 1538
    maySkipICMP = directionIn;

S
Stefan Berger 已提交
1539 1540
    chainPrefix[0] = 'H';
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1541
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1542 1543 1544 1545 1546 1547 1548
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
                                     NULL,
1549
                                     "ACCEPT",
1550 1551
                                     isIPv6,
                                     maySkipICMP);
S
Stefan Berger 已提交
1552 1553 1554 1555 1556 1557 1558

    return rc;
}




1559 1560 1561 1562 1563 1564 1565 1566
/*
 * 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
1567
 * @reverse : Whether to reverse src and dst attributes
1568 1569 1570 1571 1572 1573 1574 1575
 *
 * 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
1576
ebtablesCreateRuleInstance(char chainPrefix,
1577 1578 1579 1580
                           virNWFilterDefPtr nwfilter,
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
                           virNWFilterHashTablePtr vars,
1581 1582
                           virNWFilterRuleInstPtr res,
                           bool reverse)
1583 1584 1585
{
    char macaddr[VIR_MAC_STRING_BUFLEN],
         ipaddr[INET_ADDRSTRLEN],
1586
         ipv6addr[INET6_ADDRSTRLEN],
1587 1588 1589 1590
         number[20];
    char chain[MAX_CHAINNAME_LENGTH];
    virBuffer buf = VIR_BUFFER_INITIALIZER;

1591 1592 1593 1594 1595 1596 1597
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rule since ebtables tool is "
                                 "missing."));
        goto err_exit;
    }

1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
    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,
1609 1610
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1611 1612


1613
        if (ebtablesHandleEthHdr(&buf,
1614
                                 vars,
1615 1616
                                 &rule->p.ethHdrFilter.ethHdr,
                                 reverse))
1617 1618 1619
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.ethHdrFilter.dataProtocolID)) {
1620
            if (printDataTypeAsHex(vars,
1621 1622
                                   number, sizeof(number),
                                   &rule->p.ethHdrFilter.dataProtocolID))
1623 1624 1625 1626 1627 1628 1629 1630 1631
                goto err_exit;
            virBufferVSprintf(&buf,
                          " -p %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.ethHdrFilter.dataProtocolID),
                          number);
        }
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
1632
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
1633 1634

        virBufferVSprintf(&buf,
1635 1636
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1637

1638
        if (ebtablesHandleEthHdr(&buf,
1639
                                 vars,
1640 1641
                                 &rule->p.arpHdrFilter.ethHdr,
                                 reverse))
1642 1643
            goto err_exit;

1644 1645 1646 1647
        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);
1648 1649

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataHWType)) {
1650 1651 1652
             if (printDataType(vars,
                               number, sizeof(number),
                               &rule->p.arpHdrFilter.dataHWType))
1653 1654 1655 1656 1657 1658 1659 1660
                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)) {
1661
            if (printDataType(vars,
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
                              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)) {
1672
            if (printDataTypeAsHex(vars,
1673 1674
                                   number, sizeof(number),
                                   &rule->p.arpHdrFilter.dataProtocolType))
1675 1676 1677 1678 1679 1680 1681 1682
                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)) {
1683
            if (printDataType(vars,
1684 1685 1686 1687 1688
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1689 1690
                          " %s %s %s",
                          reverse ? "--arp-ip-dst" : "--arp-ip-src",
1691 1692 1693 1694 1695
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstIPAddr)) {
1696
            if (printDataType(vars,
1697 1698 1699 1700 1701
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1702 1703
                          " %s %s %s",
                          reverse ? "--arp-ip-src" : "--arp-ip-dst",
1704 1705 1706 1707 1708
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcMACAddr)) {
1709
            if (printDataType(vars,
1710 1711 1712 1713 1714
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPSrcMACAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1715 1716
                          " %s %s %s",
                          reverse ? "--arp-mac-dst" : "--arp-mac-src",
1717 1718 1719 1720 1721
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcMACAddr),
                          macaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstMACAddr)) {
1722
            if (printDataType(vars,
1723 1724 1725 1726 1727
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPDstMACAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1728 1729
                          " %s %s %s",
                          reverse ? "--arp-mac-src" : "--arp-mac-dst",
1730 1731 1732 1733 1734 1735 1736
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstMACAddr),
                          macaddr);
        }
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_IP:
        virBufferVSprintf(&buf,
1737 1738
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1739

1740
        if (ebtablesHandleEthHdr(&buf,
1741
                                 vars,
1742 1743
                                 &rule->p.ipHdrFilter.ethHdr,
                                 reverse))
1744 1745 1746 1747 1748 1749
            goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr)) {
1750
            if (printDataType(vars,
1751 1752 1753 1754 1755
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1756 1757
                          " %s %s %s",
                          reverse ? "--ip-destination" : "--ip-source",
1758 1759 1760 1761
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPMask)) {
1762
                if (printDataType(vars,
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                             "/%s",
                             number);
            }
        }

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

1774
            if (printDataType(vars,
1775 1776 1777 1778 1779
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1780 1781
                          " %s %s %s",
                          reverse ? "--ip-source" : "--ip-destination",
1782 1783 1784 1785
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDstIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDstIPMask)) {
1786
                if (printDataType(vars,
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataProtocolID)) {
1797
            if (printDataType(vars,
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
                              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)) {

1810
            if (printDataType(vars,
1811 1812 1813 1814 1815
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataSrcPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1816 1817
                          " %s %s %s",
                          reverse ? "--ip-destination-port" : "--ip-source-port",
1818 1819 1820 1821
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataSrcPortEnd)) {
1822
                if (printDataType(vars,
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

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

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

1835
            if (printDataType(vars,
1836 1837 1838 1839 1840
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataDstPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1841 1842
                          " %s %s %s",
                          reverse ? "--ip-source-port" : "--ip-destination-port",
1843 1844 1845 1846
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataDstPortEnd)) {
1847
                if (printDataType(vars,
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
                                number, sizeof(number),
                                &rule->p.ipHdrFilter.portData.dataDstPortEnd))
                    goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDSCP)) {
1859 1860 1861
            if (printDataTypeAsHex(vars,
                                   number, sizeof(number),
                                   &rule->p.ipHdrFilter.ipHdr.dataDSCP))
1862 1863 1864 1865 1866 1867 1868 1869 1870
                goto err_exit;

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

1871 1872
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
        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.ipv6HdrFilter.ethHdr,
                                 reverse))
1880 1881 1882 1883 1884 1885
            goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr)) {
1886
            if (printDataType(vars,
1887 1888 1889 1890 1891
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1892 1893
                          " %s %s %s",
                          reverse ? "--ip6-destination" : "--ip6-source",
1894 1895 1896 1897
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask)) {
1898
                if (printDataType(vars,
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                             "/%s",
                             number);
            }
        }

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

1910
            if (printDataType(vars,
1911 1912 1913 1914 1915
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1916 1917
                          " %s %s %s",
                          reverse ? "--ip6-source" : "--ip6-destination",
1918 1919 1920 1921
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask)) {
1922
                if (printDataType(vars,
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID)) {
1933
            if (printDataType(vars,
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
                              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)) {

1946
            if (printDataType(vars,
1947 1948 1949 1950 1951
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataSrcPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1952 1953
                          " %s %s %s",
                          reverse ? "--ip6-destination-port" : "--ip6-source-port",
1954 1955 1956 1957
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataSrcPortEnd)) {
1958
                if (printDataType(vars,
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

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

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

1971
            if (printDataType(vars,
1972 1973 1974 1975 1976
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataDstPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1977 1978
                          " %s %s %s",
                          reverse ? "--ip6-source-port" : "--ip6-destination-port",
1979 1980 1981 1982
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataDstPortEnd)) {
1983 1984 1985
                if (printDataType(vars,
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataDstPortEnd))
1986 1987 1988 1989 1990 1991 1992 1993 1994
                    goto err_exit;

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

1995 1996
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
        virBufferVSprintf(&buf,
1997 1998
                          CMD_DEF_PRE "%s -t %s -%%c %s %%s",
                          ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
1999
    break;
S
Stefan Berger 已提交
2000 2001 2002

    default:
        return -1;
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
    }

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

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

2016
    return ebiptablesAddRuleInst(res,
2017 2018 2019
                                 virBufferContentAndReset(&buf),
                                 nwfilter->chainsuffix,
                                 chainPrefix,
S
Stefan Berger 已提交
2020 2021
                                 rule->priority,
                                 RT_EBTABLES);
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045

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
2046
ebiptablesCreateRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
S
Stefan Berger 已提交
2047
                             enum virDomainNetType nettype,
2048 2049 2050 2051 2052 2053 2054
                             virNWFilterDefPtr nwfilter,
                             virNWFilterRuleDefPtr rule,
                             const char *ifname,
                             virNWFilterHashTablePtr vars,
                             virNWFilterRuleInstPtr res)
{
    int rc = 0;
2055
    bool isIPv6;
2056 2057 2058 2059 2060

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_IP:
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:
    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
2061
    case VIR_NWFILTER_RULE_PROTOCOL_RARP:
2062
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
2063
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
2064 2065 2066

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_OUT ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2067
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_IN_TEMP,
2068 2069 2070 2071
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2072 2073
                                            res,
                                            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
2074 2075 2076 2077 2078 2079
            if (rc)
                return rc;
        }

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
2080
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_OUT_TEMP,
2081 2082 2083 2084
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
2085 2086
                                            res,
                                            false);
2087 2088
        }
    break;
S
Stefan Berger 已提交
2089 2090 2091

    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
2092 2093 2094
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
    case VIR_NWFILTER_RULE_PROTOCOL_AH:
S
Stefan Berger 已提交
2095 2096 2097 2098 2099
    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) {
2100
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
S
Stefan Berger 已提交
2101 2102 2103 2104 2105
                          _("'%s' protocol not support for net type '%s'"),
                          virNWFilterRuleProtocolTypeToString(rule->prtclType),
                          virDomainNetTypeToString(nettype));
            return 1;
        }
2106
        isIPv6 = 0;
2107
        rc = iptablesCreateRuleInstance(nwfilter,
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
                                        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) {
2124
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
2125 2126 2127 2128 2129 2130
                          _("'%s' protocol not support for net type '%s'"),
                          virNWFilterRuleProtocolTypeToString(rule->prtclType),
                          virDomainNetTypeToString(nettype));
            return 1;
        }
        isIPv6 = 1;
2131
        rc = iptablesCreateRuleInstance(nwfilter,
S
Stefan Berger 已提交
2132 2133 2134
                                        rule,
                                        ifname,
                                        vars,
2135 2136
                                        res,
                                        isIPv6);
S
Stefan Berger 已提交
2137 2138 2139
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_LAST:
2140
        virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
S
Stefan Berger 已提交
2141 2142 2143
                               "%s", _("illegal protocol type"));
        rc = 1;
    break;
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
    }

    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;
2163 2164 2165
    VIR_INFO("Command Template: '%s', Needed protocol: '%s'",
             inst->commandTemplate,
             virNWFilterChainSuffixTypeToString(inst->neededProtocolChain));
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
    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 *
2184
ebiptablesWriteToTempFile(const char *string) {
2185 2186 2187
    char filename[] = "/tmp/virtdXXXXXX";
    int len;
    char *filnam;
2188 2189
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *header;
2190 2191
    size_t written;

2192 2193 2194 2195 2196 2197 2198 2199 2200
    virBufferVSprintf(&buf, "#!%s\n", bash_cmd_path);

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

2201 2202 2203
    int fd = mkstemp(filename);

    if (fd < 0) {
2204
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2205 2206
                               "%s",
                               _("cannot create temporary file"));
2207
        goto err_exit;
2208 2209 2210
    }

    if (fchmod(fd, S_IXUSR| S_IRUSR | S_IWUSR) < 0) {
2211
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2212 2213 2214 2215 2216 2217 2218 2219
                               "%s",
                               _("cannot change permissions on temp. file"));
        goto err_exit;
    }

    len = strlen(header);
    written = safewrite(fd, header, len);
    if (written != len) {
2220
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2221 2222 2223 2224 2225 2226 2227 2228
                               "%s",
                               _("cannot write string to file"));
        goto err_exit;
    }

    len = strlen(string);
    written = safewrite(fd, string, len);
    if (written != len) {
2229
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
                               "%s",
                               _("cannot write string to file"));
        goto err_exit;
    }

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

2241
    VIR_FREE(header);
2242 2243 2244 2245
    close(fd);
    return filnam;

err_exit:
2246
    VIR_FREE(header);
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
    close(fd);
    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
2268
ebiptablesExecCLI(virBufferPtr buf,
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
                  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;

2291
    filename = ebiptablesWriteToTempFile(cmds);
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
    VIR_FREE(cmds);

    if (!filename)
        return 1;

    argv[0] = filename;
    rc = virRun(argv, status);

    *status >>= 8;

2302
    VIR_DEBUG("rc = %d, status = %d",rc, *status);
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312

    unlink(filename);

    VIR_FREE(filename);

    return rc;
}


static int
2313
ebtablesCreateTmpRootChain(virBufferPtr buf,
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
                           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,
2324
                      CMD_DEF("%s -t %s -N %s") CMD_SEPARATOR
2325 2326
                      CMD_EXEC
                      "%s",
2327
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2328 2329 2330 2331 2332 2333 2334
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2335
ebtablesLinkTmpRootChain(virBufferPtr buf,
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
                         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,
2347
                      CMD_DEF("%s -t %s -A %s -%c %s -j %s") CMD_SEPARATOR
2348 2349
                      CMD_EXEC
                      "%s",
2350
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2362
_ebtablesRemoveRootChain(virBufferPtr buf,
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
                         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,
2378 2379 2380 2381
                      "%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);
2382 2383 2384 2385 2386 2387

    return 0;
}


static int
2388
ebtablesRemoveRootChain(virBufferPtr buf,
2389 2390
                        int incoming, const char *ifname)
{
2391
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 0);
2392 2393 2394 2395
}


static int
2396
ebtablesRemoveTmpRootChain(virBufferPtr buf,
2397 2398
                           int incoming, const char *ifname)
{
2399
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 1);
2400 2401 2402 2403
}


static int
2404
_ebtablesUnlinkRootChain(virBufferPtr buf,
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
                         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,
2423 2424
                      "%s -t %s -D %s -%c %s -j %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2425 2426 2427 2428 2429 2430 2431 2432 2433
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain);

    return 0;
}


static int
2434
ebtablesUnlinkRootChain(virBufferPtr buf,
2435 2436
                        int incoming, const char *ifname)
{
2437
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 0);
2438 2439 2440 2441
}


static int
2442
ebtablesUnlinkTmpRootChain(virBufferPtr buf,
2443 2444
                           int incoming, const char *ifname)
{
2445
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 1);
2446 2447 2448 2449
}


static int
2450
ebtablesCreateTmpSubChain(virBufferPtr buf,
2451 2452
                          int incoming,
                          const char *ifname,
2453
                          enum l3_proto_idx protoidx,
2454 2455 2456 2457 2458 2459 2460
                          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);
2461
    PRINT_CHAIN(chain, chainPrefix, ifname, l3_protocols[protoidx].val);
2462 2463

    virBufferVSprintf(buf,
2464
                      CMD_DEF("%s -t %s -N %s") CMD_SEPARATOR
2465 2466
                      CMD_EXEC
                      "%s"
2467
                      CMD_DEF("%s -t %s -A %s -p 0x%x -j %s") CMD_SEPARATOR
2468 2469 2470
                      CMD_EXEC
                      "%s",

2471
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2472 2473 2474

                      CMD_STOPONERR(stopOnError),

2475
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2476
                      rootchain, l3_protocols[protoidx].attr, chain,
2477 2478 2479 2480 2481 2482 2483 2484

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2485
_ebtablesRemoveSubChain(virBufferPtr buf,
2486 2487
                        int incoming,
                        const char *ifname,
2488
                        enum l3_proto_idx protoidx,
2489 2490 2491 2492
                        int isTempChain)
{
    char rootchain[MAX_CHAINNAME_LENGTH], chain[MAX_CHAINNAME_LENGTH];
    char chainPrefix;
2493

2494 2495 2496 2497 2498 2499 2500 2501 2502
    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);
2503
    PRINT_CHAIN(chain, chainPrefix, ifname, l3_protocols[protoidx].val);
2504 2505

    virBufferVSprintf(buf,
2506
                      "%s -t %s -D %s -p 0x%x -j %s" CMD_SEPARATOR
2507 2508 2509
                      "%s -t %s -F %s" CMD_SEPARATOR
                      "%s -t %s -X %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
2510
                      rootchain, l3_protocols[protoidx].attr, chain,
2511

2512
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2513

2514
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain);
2515 2516 2517 2518 2519 2520

    return 0;
}


static int
2521
ebtablesRemoveSubChain(virBufferPtr buf,
2522 2523
                       int incoming,
                       const char *ifname,
2524
                       enum l3_proto_idx protoidx)
2525
{
2526
    return _ebtablesRemoveSubChain(buf,
2527
                                   incoming, ifname, protoidx, 0);
2528 2529 2530 2531
}


static int
2532 2533
ebtablesRemoveSubChains(virBufferPtr buf,
                        const char *ifname)
2534
{
2535 2536 2537 2538 2539
    enum l3_proto_idx i;

    for (i = 0; i < L3_PROTO_LAST_IDX; i++) {
        ebtablesRemoveSubChain(buf, 1, ifname, i);
        ebtablesRemoveSubChain(buf, 0, ifname, i);
2540 2541 2542 2543 2544 2545 2546
    }

    return 0;
}


static int
2547
ebtablesRemoveTmpSubChain(virBufferPtr buf,
2548 2549
                          int incoming,
                          const char *ifname,
2550
                          enum l3_proto_idx protoidx)
2551
{
2552
    return _ebtablesRemoveSubChain(buf,
2553
                                   incoming, ifname, protoidx, 1);
2554 2555 2556 2557
}


static int
2558
ebtablesRemoveTmpSubChains(virBufferPtr buf,
2559 2560
                           const char *ifname)
{
2561 2562 2563 2564 2565
    enum l3_proto_idx i;

    for (i = 0; i < L3_PROTO_LAST_IDX; i++) {
        ebtablesRemoveTmpSubChain(buf, 1, ifname, i);
        ebtablesRemoveTmpSubChain(buf, 0, ifname, i);
2566 2567 2568 2569 2570 2571 2572
    }

    return 0;
}


static int
2573
ebtablesRenameTmpSubChain(virBufferPtr buf,
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
                          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,
2593 2594
                      "%s -t %s -E %s %s" CMD_SEPARATOR,
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, tmpchain, chain);
2595 2596 2597 2598 2599
    return 0;
}


static int
2600
ebtablesRenameTmpSubChains(virBufferPtr buf,
2601 2602
                           const char *ifname)
{
2603 2604 2605 2606 2607
    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);
2608 2609 2610 2611 2612 2613 2614
    }

    return 0;
}


static int
2615
ebtablesRenameTmpRootChain(virBufferPtr buf,
2616 2617 2618
                           int incoming,
                           const char *ifname)
{
2619
    return ebtablesRenameTmpSubChain(buf, incoming, ifname, NULL);
2620 2621 2622 2623
}


static void
2624
ebiptablesInstCommand(virBufferPtr buf,
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
                      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));
}


2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
/**
 * 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);
}

2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
/**
 * 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
 */
2663
static int
2664 2665 2666 2667 2668 2669 2670 2671 2672
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];

2673 2674 2675 2676 2677 2678 2679
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
    virFormatMacAddr(macaddr, macaddr_str);

    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    ebiptablesExecCLI(&buf, &cli_status);

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

    PRINT_ROOT_CHAIN(chain, chainPrefix, ifname);
    virBufferVSprintf(&buf,
2693
                      CMD_DEF("%s -t %s -A %s -s ! %s -j DROP") CMD_SEPARATOR
2694 2695 2696
                      CMD_EXEC
                      "%s",

2697 2698
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE,
                      chain, macaddr_str,
2699 2700 2701
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
2702
                      CMD_DEF("%s -t %s -A %s -p IPv4 -j ACCEPT") CMD_SEPARATOR
2703 2704 2705
                      CMD_EXEC
                      "%s",

2706
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2707 2708 2709
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
2710
                      CMD_DEF("%s -t %s -A %s -p ARP -j ACCEPT") CMD_SEPARATOR
2711 2712 2713
                      CMD_EXEC
                      "%s",

2714
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2715 2716 2717
                      CMD_STOPONERR(1));

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

2722
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain,
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
                      CMD_STOPONERR(1));

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

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

    return 0;

tear_down_tmpebchains:
    ebtablesRemoveBasicRules(ifname);

    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.
 */
2757
static int
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
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;

2769 2770 2771 2772 2773 2774 2775
    if (!ebtables_cmd_path) {
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot create rules since ebtables tool is "
                                 "missing."));
        return 1;
    }

2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
    if (dhcpserver) {
        virBufferVSprintf(&buf, " --ip-src %s", dhcpserver);
        if (virBufferError(&buf))
            return 1;
        srcIPParam = virBufferContentAndReset(&buf);
    }

    virFormatMacAddr(macaddr, macaddr_str);

    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    ebiptablesExecCLI(&buf, &cli_status);

    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,
2799
                      CMD_DEF("%s -t %s -A %s"
2800 2801 2802 2803 2804 2805 2806 2807
                              " -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",

2808
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_in,
2809 2810 2811 2812
                      macaddr_str,
                      CMD_STOPONERR(1));

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

2817
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_in,
2818 2819 2820
                      CMD_STOPONERR(1));

    virBufferVSprintf(&buf,
2821
                      CMD_DEF("%s -t %s -A %s"
2822 2823 2824 2825 2826 2827 2828 2829
                              " -d %s"
                              " -p ipv4 --ip-protocol udp"
                              " %s"
                              " --ip-sport 67 --ip-dport 68"
                              " -j ACCEPT") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

2830
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_out,
2831 2832 2833 2834 2835
                      macaddr_str,
                      srcIPParam != NULL ? srcIPParam : "",
                      CMD_STOPONERR(1));

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

2840
                      ebtables_cmd_path, EBTABLES_DEFAULT_TABLE, chain_out,
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
                      CMD_STOPONERR(1));

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

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

    VIR_FREE(srcIPParam);

    return 0;

tear_down_tmpebchains:
    ebtablesRemoveBasicRules(ifname);

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

    VIR_FREE(srcIPParam);

    return 1;
}


2866
static int
2867 2868 2869 2870 2871
ebtablesRemoveBasicRules(const char *ifname)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int cli_status;

2872 2873 2874
    if (!ebtables_cmd_path)
        return 0;

2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
    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;
}


2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
static int
ebiptablesRuleOrderSort(const void *a, const void *b)
{
    const ebiptablesRuleInstPtr *insta = a;
    const ebiptablesRuleInstPtr *instb = b;
    return ((*insta)->priority - (*instb)->priority);
}


static int
2896
ebiptablesApplyNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
2897 2898 2899 2900 2901 2902 2903 2904 2905
                        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;
2906 2907
    bool haveIptables = false;
    bool haveIp6tables = false;
2908

2909 2910
    if (nruleInstances > 1 && inst)
        qsort(inst, nruleInstances, sizeof(inst[0]), ebiptablesRuleOrderSort);
2911 2912

    for (i = 0; i < nruleInstances; i++) {
2913
        sa_assert (inst);
S
Stefan Berger 已提交
2914 2915 2916 2917 2918 2919
        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);
        }
2920 2921
    }

2922 2923 2924 2925 2926 2927 2928 2929
    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);
    }
2930 2931

    if (chains_in != 0)
2932
        ebtablesCreateTmpRootChain(&buf, 1, ifname, 1);
2933
    if (chains_out != 0)
2934
        ebtablesCreateTmpRootChain(&buf, 0, ifname, 1);
2935 2936

    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv4))
2937
        ebtablesCreateTmpSubChain(&buf, 1, ifname, L3_PROTO_IPV4_IDX, 1);
2938
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv4))
2939
        ebtablesCreateTmpSubChain(&buf, 0, ifname, L3_PROTO_IPV4_IDX, 1);
2940

2941
    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv6))
2942
        ebtablesCreateTmpSubChain(&buf, 1, ifname, L3_PROTO_IPV6_IDX, 1);
2943
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv6))
2944
        ebtablesCreateTmpSubChain(&buf, 0, ifname, L3_PROTO_IPV6_IDX, 1);
2945

2946
    // keep arp,rarp as last
2947
    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_ARP))
2948
        ebtablesCreateTmpSubChain(&buf, 1, ifname, L3_PROTO_ARP_IDX, 1);
2949
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_ARP))
2950 2951 2952 2953 2954
        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);
2955

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

2959
    for (i = 0; i < nruleInstances; i++) {
2960
        sa_assert (inst);
S
Stefan Berger 已提交
2961 2962
        switch (inst[i]->ruleType) {
        case RT_EBTABLES:
2963
            ebiptablesInstCommand(&buf,
S
Stefan Berger 已提交
2964 2965 2966 2967
                                  inst[i]->commandTemplate,
                                  'A', -1, 1);
        break;
        case RT_IPTABLES:
2968
            haveIptables = true;
S
Stefan Berger 已提交
2969
        break;
2970
        case RT_IP6TABLES:
2971
            haveIp6tables = true;
2972
        break;
S
Stefan Berger 已提交
2973
        }
2974
    }
2975

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

S
Stefan Berger 已提交
2979
    if (haveIptables) {
2980 2981
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
2982

2983
        iptablesCreateBaseChains(iptables_cmd_path, &buf);
S
Stefan Berger 已提交
2984

2985
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
2986 2987
            goto tear_down_tmpebchains;

2988
        iptablesCreateTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
2989

2990
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
2991 2992
           goto tear_down_tmpiptchains;

2993 2994
        iptablesLinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesSetupVirtInPost(iptables_cmd_path, &buf, ifname);
2995
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
2996 2997 2998
           goto tear_down_tmpiptchains;

        for (i = 0; i < nruleInstances; i++) {
2999
            sa_assert (inst);
S
Stefan Berger 已提交
3000
            if (inst[i]->ruleType == RT_IPTABLES)
3001
                iptablesInstCommand(&buf,
S
Stefan Berger 已提交
3002 3003 3004 3005
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3006
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
3007 3008 3009
           goto tear_down_tmpiptchains;
    }

3010
    if (haveIp6tables) {
3011 3012
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3013

3014
        iptablesCreateBaseChains(ip6tables_cmd_path, &buf);
3015

3016
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3017 3018
            goto tear_down_tmpiptchains;

3019
        iptablesCreateTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3020

3021
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3022 3023
           goto tear_down_tmpip6tchains;

3024 3025
        iptablesLinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesSetupVirtInPost(ip6tables_cmd_path, &buf, ifname);
3026
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3027 3028 3029 3030
           goto tear_down_tmpip6tchains;

        for (i = 0; i < nruleInstances; i++) {
            if (inst[i]->ruleType == RT_IP6TABLES)
3031
                iptablesInstCommand(&buf,
3032 3033 3034 3035
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

3036
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3037 3038 3039
           goto tear_down_tmpip6tchains;
    }

3040
    if (chains_in != 0)
3041
        ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
3042
    if (chains_out != 0)
3043
        ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
3044

3045
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
3046 3047 3048 3049 3050
        goto tear_down_ebsubchains_and_unlink;

    return 0;

tear_down_ebsubchains_and_unlink:
3051 3052 3053 3054
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    }
3055

3056 3057
tear_down_tmpip6tchains:
    if (haveIp6tables) {
3058 3059
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
3060 3061
    }

S
Stefan Berger 已提交
3062 3063
tear_down_tmpiptchains:
    if (haveIptables) {
3064 3065
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3066 3067
    }

3068
tear_down_tmpebchains:
3069 3070 3071 3072 3073
    if (ebtables_cmd_path) {
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3074

3075
    ebiptablesExecCLI(&buf, &cli_status);
3076

3077
    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3078 3079 3080 3081 3082 3083 3084 3085
                           "%s",
                           _("Some rules could not be created."));

    return 1;
}


static int
3086
ebiptablesTearNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3087 3088 3089 3090 3091
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

3092 3093 3094 3095
    if (iptables_cmd_path) {
        iptablesUnlinkTmpRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(iptables_cmd_path, &buf, ifname);
    }
3096

3097 3098 3099 3100
    if (ip6tables_cmd_path) {
        iptablesUnlinkTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveTmpRootChains(ip6tables_cmd_path, &buf, ifname);
    }
S
Stefan Berger 已提交
3101

3102 3103 3104
    if (ebtables_cmd_path) {
        ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
        ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
3105

3106 3107 3108 3109
        ebtablesRemoveTmpSubChains(&buf, ifname);
        ebtablesRemoveTmpRootChain(&buf, 1, ifname);
        ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    }
3110

3111
    ebiptablesExecCLI(&buf, &cli_status);
3112 3113 3114 3115 3116 3117

    return 0;
}


static int
3118
ebiptablesTearOldRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3119 3120 3121 3122 3123
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

S
Stefan Berger 已提交
3124
    // switch to new iptables user defined chains
3125 3126 3127
    if (iptables_cmd_path) {
        iptablesUnlinkRootChains(iptables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(iptables_cmd_path, &buf, ifname);
S
Stefan Berger 已提交
3128

3129 3130 3131
        iptablesRenameTmpRootChains(iptables_cmd_path, &buf, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
3132

3133 3134 3135
    if (ip6tables_cmd_path) {
        iptablesUnlinkRootChains(ip6tables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(ip6tables_cmd_path, &buf, ifname);
3136

3137 3138 3139
        iptablesRenameTmpRootChains(ip6tables_cmd_path, &buf, ifname);
        ebiptablesExecCLI(&buf, &cli_status);
    }
S
Stefan Berger 已提交
3140

3141 3142 3143
    if (ebtables_cmd_path) {
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3144

3145
        ebtablesRemoveSubChains(&buf, ifname);
3146

3147 3148
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
3149

3150 3151 3152
        ebtablesRenameTmpSubChains(&buf, ifname);
        ebtablesRenameTmpRootChain(&buf, 1, ifname);
        ebtablesRenameTmpRootChain(&buf, 0, ifname);
3153

3154 3155
        ebiptablesExecCLI(&buf, &cli_status);
    }
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173

    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
3174
ebiptablesRemoveRules(virConnectPtr conn ATTRIBUTE_UNUSED,
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
                      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++)
3186
        ebiptablesInstCommand(&buf,
3187 3188 3189 3190
                              inst[i]->commandTemplate,
                              'D', -1,
                              0);

3191
    if (ebiptablesExecCLI(&buf, &cli_status))
3192 3193 3194
        goto err_exit;

    if (cli_status) {
3195
        virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
                               "%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;

3221 3222 3223 3224 3225
    if (iptables_cmd_path) {
        iptablesUnlinkRootChains(iptables_cmd_path, &buf, ifname);
        iptablesClearVirtInPost (iptables_cmd_path, &buf, ifname);
        iptablesRemoveRootChains(iptables_cmd_path, &buf, ifname);
    }
3226

3227 3228 3229 3230 3231
    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 已提交
3232

3233 3234 3235
    if (ebtables_cmd_path) {
        ebtablesUnlinkRootChain(&buf, 1, ifname);
        ebtablesUnlinkRootChain(&buf, 0, ifname);
3236

3237 3238
        ebtablesRemoveRootChain(&buf, 1, ifname);
        ebtablesRemoveRootChain(&buf, 0, ifname);
3239

3240 3241
        ebtablesRemoveSubChains(&buf, ifname);
    }
3242

3243
    ebiptablesExecCLI(&buf, &cli_status);
3244 3245 3246 3247 3248 3249 3250

    return 0;
}


virNWFilterTechDriver ebiptables_driver = {
    .name = EBIPTABLES_DRIVER_ID,
3251 3252 3253 3254
    .flags = 0,

    .init     = ebiptablesDriverInit,
    .shutdown = ebiptablesDriverShutdown,
3255 3256 3257 3258 3259 3260 3261 3262 3263

    .createRuleInstance  = ebiptablesCreateRuleInstance,
    .applyNewRules       = ebiptablesApplyNewRules,
    .tearNewRules        = ebiptablesTearNewRules,
    .tearOldRules        = ebiptablesTearOldRules,
    .allTeardown         = ebiptablesAllTeardown,
    .removeRules         = ebiptablesRemoveRules,
    .freeRuleInstance    = ebiptablesFreeRuleInstance,
    .displayRuleInstance = ebiptablesDisplayRuleInstance,
3264 3265 3266 3267 3268

    .canApplyBasicRules  = ebiptablesCanApplyBasicRules,
    .applyBasicRules     = ebtablesApplyBasicRules,
    .applyDHCPOnlyRules  = ebtablesApplyDHCPOnlyRules,
    .removeBasicRules    = ebtablesRemoveBasicRules,
3269
};
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357


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

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