nwfilter_ebiptables_driver.c 90.1 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 35 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
/*
 * 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"
#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 \
      : ""


65 66 67 68 69 70
#define EBTABLES_CMD  EBTABLES_PATH
#define IPTABLES_CMD  IPTABLES_PATH
#define IP6TABLES_CMD IP6TABLES_PATH
#define BASH_CMD      BASH_PATH
#define GREP_CMD      GREP_PATH
#define GAWK_CMD      GAWK_PATH
71 72 73 74 75 76 77

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


100 101
static const char *supported_protocols[] = {
    "ipv4",
102
    "ipv6",
103 104 105 106 107 108
    "arp",
    NULL,
};


static int
109
printVar(virNWFilterHashTablePtr vars,
110 111 112 113 114 115 116 117 118
         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) {
119
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
120 121 122 123 124 125
                                   _("cannot find value for '%s'"),
                                   item->var);
            return 1;
        }

        if (!virStrcpy(buf, val, bufsize)) {
126
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
127 128 129 130 131 132 133 134 135 136 137 138 139
                                   _("Buffer to small to print MAC address "
                                   "'%s' into"),
                                   item->var);
            return 1;
        }

        *done = 1;
    }
    return 0;
}


static int
140
_printDataType(virNWFilterHashTablePtr vars,
141 142 143
               char *buf, int bufsize,
               nwItemDescPtr item,
               bool asHex)
144 145
{
    int done;
146
    char *data;
147

148
    if (printVar(vars, buf, bufsize, item, &done))
149 150 151 152 153 154 155
        return 1;

    if (done)
        return 0;

    switch (item->datatype) {
    case DATATYPE_IPADDR:
156 157
        data = virSocketFormatAddr(&item->u.ipaddr.addr);
        if (!data) {
158
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
159 160 161 162 163
                                   _("internal IPv4 address representation "
                                     "is bad"));
            return 1;
        }
        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
164
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
165 166
                                   _("buffer too small for IP address"));
            VIR_FREE(data);
167 168
            return 1;
        }
169
        VIR_FREE(data);
170 171
    break;

172
    case DATATYPE_IPV6ADDR:
173 174
        data = virSocketFormatAddr(&item->u.ipaddr.addr);
        if (!data) {
175
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
176 177 178 179 180 181
                                   _("internal IPv6 address representation "
                                     "is bad"));
            return 1;
        }

        if (snprintf(buf, bufsize, "%s", data) >= bufsize) {
182
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR, "%s",
183 184 185
                                   _("buffer too small for IPv6 address"));
            VIR_FREE(data);
            return 1;
186
        }
187
        VIR_FREE(data);
188 189
    break;

190
    case DATATYPE_MACADDR:
191
    case DATATYPE_MACMASK:
192
        if (bufsize < VIR_MAC_STRING_BUFLEN) {
193
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
194 195 196 197 198 199 200
                                   _("Buffer too small for MAC address"));
            return 1;
        }

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

201 202
    case DATATYPE_IPV6MASK:
    case DATATYPE_IPMASK:
203
        if (snprintf(buf, bufsize, "%d",
204
                     item->u.u8) >= bufsize) {
205
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
206 207 208 209 210 211 212
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT16:
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
213
                     item->u.u16) >= bufsize) {
214
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
215 216 217 218 219 220
                                   _("Buffer too small for uint16 type"));
            return 1;
        }
    break;

    case DATATYPE_UINT8:
221
        if (snprintf(buf, bufsize, asHex ? "0x%x" : "%d",
222
                     item->u.u8) >= bufsize) {
223
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER, "%s",
224 225 226 227 228 229
                                   _("Buffer too small for uint8 type"));
            return 1;
        }
    break;

    default:
230
        virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
231 232 233 234 235 236 237 238 239
                               _("Unhandled datatype %x"), item->datatype);
        return 1;
    break;
    }

    return 0;
}


240
static int
241
printDataType(virNWFilterHashTablePtr vars,
242 243 244
              char *buf, int bufsize,
              nwItemDescPtr item)
{
245
    return _printDataType(vars, buf, bufsize, item, 0);
246 247 248 249
}


static int
250
printDataTypeAsHex(virNWFilterHashTablePtr vars,
251 252 253
                   char *buf, int bufsize,
                   nwItemDescPtr item)
{
254
    return _printDataType(vars, buf, bufsize, item, 1);
255 256 257
}


S
Stefan Berger 已提交
258 259 260 261 262 263 264 265 266 267 268 269
static void
ebiptablesRuleInstFree(ebiptablesRuleInstPtr inst)
{
    if (!inst)
        return;

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


static int
270
ebiptablesAddRuleInst(virNWFilterRuleInstPtr res,
S
Stefan Berger 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
                      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;

290
    return virNWFilterRuleInstAddData(res, inst);
S
Stefan Berger 已提交
291 292 293 294
}


static int
295
ebtablesHandleEthHdr(virBufferPtr buf,
S
Stefan Berger 已提交
296
                     virNWFilterHashTablePtr vars,
297 298
                     ethHdrDataDefPtr ethHdr,
                     bool reverse)
S
Stefan Berger 已提交
299 300 301 302
{
    char macaddr[VIR_MAC_STRING_BUFLEN];

    if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACAddr)) {
303
        if (printDataType(vars,
S
Stefan Berger 已提交
304 305 306 307 308
                          macaddr, sizeof(macaddr),
                          &ethHdr->dataSrcMACAddr))
            goto err_exit;

        virBufferVSprintf(buf,
309 310
                      " %s %s %s",
                      reverse ? "-d" : "-s",
S
Stefan Berger 已提交
311 312 313 314
                      ENTRY_GET_NEG_SIGN(&ethHdr->dataSrcMACAddr),
                      macaddr);

        if (HAS_ENTRY_ITEM(&ethHdr->dataSrcMACMask)) {
315
            if (printDataType(vars,
S
Stefan Berger 已提交
316 317 318 319 320 321 322 323 324 325 326
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataSrcMACMask))
                goto err_exit;

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

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

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

        if (HAS_ENTRY_ITEM(&ethHdr->dataDstMACMask)) {
339
            if (printDataType(vars,
S
Stefan Berger 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                              macaddr, sizeof(macaddr),
                              &ethHdr->dataDstMACMask))
                goto err_exit;

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

    return 0;

 err_exit:
    virBufferFreeAndReset(buf);

    return 1;
}


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

361
static int iptablesLinkIPTablesBaseChain(const char *iptables_cmd,
S
Stefan Berger 已提交
362 363 364 365 366 367 368
                                         virBufferPtr buf,
                                         const char *udchain,
                                         const char *syschain,
                                         unsigned int pos,
                                         int stopOnError)
{
    virBufferVSprintf(buf,
369
                      "res=$(%s -L %s -n --line-number | "
S
Stefan Berger 已提交
370 371
                          GREP_CMD " \" %s \")\n"
                      "if [ $? -ne 0 ]; then\n"
372
                      "  %s -I %s %d -j %s\n"
S
Stefan Berger 已提交
373 374 375
                      "else\n"
                      "  r=$(echo $res | " GAWK_CMD " '{print $1}')\n"
                      "  if [ \"${r}\" != \"%d\" ]; then\n"
376
                      "    " CMD_DEF("%s -I %s %d -j %s") CMD_SEPARATOR
S
Stefan Berger 已提交
377 378 379
                      "    " CMD_EXEC
                      "    %s"
                      "    let r=r+1\n"
380
                      "    " CMD_DEF("%s -D %s ${r}") CMD_SEPARATOR
S
Stefan Berger 已提交
381 382 383 384 385
                      "    " CMD_EXEC
                      "    %s"
                      "  fi\n"
                      "fi\n",

386 387
                      iptables_cmd, syschain,
                      udchain,
S
Stefan Berger 已提交
388

389
                      iptables_cmd, syschain, pos, udchain,
S
Stefan Berger 已提交
390 391 392

                      pos,

393
                      iptables_cmd, syschain, pos, udchain,
S
Stefan Berger 已提交
394 395
                      CMD_STOPONERR(stopOnError),

396
                      iptables_cmd, syschain,
S
Stefan Berger 已提交
397 398 399 400 401
                      CMD_STOPONERR(stopOnError));
    return 0;
}


402
static int iptablesCreateBaseChains(const char *iptables_cmd,
S
Stefan Berger 已提交
403 404
                                    virBufferPtr buf)
{
405 406 407 408 409 410 411 412
    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);
413
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
414
                                  VIRT_IN_CHAIN     , "FORWARD", 1, 1);
415
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
416
                                  VIRT_OUT_CHAIN    , "FORWARD", 2, 1);
417
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
418
                                  VIRT_IN_POST_CHAIN, "FORWARD", 3, 1);
419
    iptablesLinkIPTablesBaseChain(iptables_cmd, buf,
S
Stefan Berger 已提交
420 421 422 423 424 425 426
                                  HOST_IN_CHAIN     , "INPUT"  , 1, 1);

    return 0;
}


static int
427
iptablesCreateTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
                           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,
443
                      CMD_DEF("%s -N %s") CMD_SEPARATOR
S
Stefan Berger 已提交
444 445
                      CMD_EXEC
                      "%s",
446
                      iptables_cmd,
S
Stefan Berger 已提交
447 448 449 450 451 452 453 454
                      chain,
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
455
iptablesCreateTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
456 457 458
                            virBufferPtr buf,
                            const char *ifname)
{
459 460 461
    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 已提交
462 463 464 465 466
    return 0;
}


static int
467
_iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
                         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,
488 489 490 491
                      "%s -F %s" CMD_SEPARATOR
                      "%s -X %s" CMD_SEPARATOR,
                      iptables_cmd, chain,
                      iptables_cmd, chain);
S
Stefan Berger 已提交
492 493 494 495 496 497

    return 0;
}


static int
498
iptablesRemoveRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
499 500 501 502 503
                        virBufferPtr buf,
                        char prefix,
                        int incoming,
                        const char *ifname)
{
504
    return _iptablesRemoveRootChain(iptables_cmd,
505
                                    buf, prefix, incoming, ifname, 0);
S
Stefan Berger 已提交
506 507 508 509
}


static int
510
iptablesRemoveTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
511 512 513 514 515
                           virBufferPtr buf,
                           char prefix,
                           int incoming,
                           const char *ifname)
{
516
    return _iptablesRemoveRootChain(iptables_cmd, buf, prefix,
517
                                    incoming, ifname, 1);
S
Stefan Berger 已提交
518 519 520 521
}


static int
522
iptablesRemoveTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
523 524 525
                            virBufferPtr buf,
                            const char *ifname)
{
526 527 528
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
529 530 531 532 533
    return 0;
}


static int
534
iptablesRemoveRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
535 536 537
                         virBufferPtr buf,
                         const char *ifname)
{
538 539 540
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRemoveRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
541 542 543 544 545
    return 0;
}


static int
546
iptablesLinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
                         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,
565
                      CMD_DEF("%s -A %s "
S
Stefan Berger 已提交
566 567 568
                              "%s %s -g %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",
569
                      iptables_cmd,
S
Stefan Berger 已提交
570 571 572 573 574 575 576 577 578 579
                      basechain,
                      match, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
580
iptablesLinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
581 582 583
                          virBufferPtr buf,
                          const char *ifname)
{
584 585 586
    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 已提交
587 588 589 590 591 592

    return 0;
}


static int
593
iptablesSetupVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
594 595 596 597 598
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
    virBufferVSprintf(buf,
599
                      "res=$(%s -L " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
600 601
                      " | grep \"\\%s %s\")\n"
                      "if [ \"${res}\" == \"\" ]; then "
602
                        CMD_DEF("%s"
S
Stefan Berger 已提交
603 604 605 606 607
                        " -A " VIRT_IN_POST_CHAIN
                        " %s %s -j ACCEPT") CMD_SEPARATOR
                        CMD_EXEC
                        "%s"
                      "fi\n",
608
                      iptables_cmd,
S
Stefan Berger 已提交
609
                      PHYSDEV_IN, ifname,
610
                      iptables_cmd,
S
Stefan Berger 已提交
611 612 613 614 615 616 617
                      match, ifname,
                      CMD_STOPONERR(1));
    return 0;
}


static int
618
iptablesClearVirtInPost(const char *iptables_cmd,
S
Stefan Berger 已提交
619 620 621 622 623
                        virBufferPtr buf,
                        const char *ifname)
{
    const char *match = MATCH_PHYSDEV_IN;
    virBufferVSprintf(buf,
624
                      "%s -D " VIRT_IN_POST_CHAIN
S
Stefan Berger 已提交
625
                      " %s %s -j ACCEPT" CMD_SEPARATOR,
626
                      iptables_cmd,
S
Stefan Berger 已提交
627 628 629 630 631
                      match, ifname);
    return 0;
}

static int
632 633 634 635 636 637
_iptablesUnlinkRootChain(const char *iptables_cmd,
                         virBufferPtr buf,
                         const char *basechain,
                         char prefix,
                         int incoming, const char *ifname,
                         int isTempChain)
S
Stefan Berger 已提交
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
{
    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,
655
                      "%s -D %s "
S
Stefan Berger 已提交
656
                      "%s %s -g %s" CMD_SEPARATOR,
657
                      iptables_cmd,
S
Stefan Berger 已提交
658 659 660 661 662 663 664 665
                      basechain,
                      match, ifname, chain);

    return 0;
}


static int
666
iptablesUnlinkRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
667 668 669 670 671
                        virBufferPtr buf,
                        const char *basechain,
                        char prefix,
                        int incoming, const char *ifname)
{
672
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
673 674 675 676 677
                                    basechain, prefix, incoming, ifname, 0);
}


static int
678
iptablesUnlinkTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
679 680 681 682 683
                           virBufferPtr buf,
                           const char *basechain,
                           char prefix,
                           int incoming, const char *ifname)
{
684
    return _iptablesUnlinkRootChain(iptables_cmd, buf,
S
Stefan Berger 已提交
685 686 687 688 689
                                    basechain, prefix, incoming, ifname, 1);
}


static int
690
iptablesUnlinkRootChains(const char *cmd,
S
Stefan Berger 已提交
691 692 693
                         virBufferPtr buf,
                         const char *ifname)
{
694 695 696
    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 已提交
697 698 699 700 701 702

    return 0;
}


static int
703
iptablesUnlinkTmpRootChains(const char *cmd,
S
Stefan Berger 已提交
704 705 706
                            virBufferPtr buf,
                            const char *ifname)
{
707 708 709
    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 已提交
710 711 712 713 714
    return 0;
}


static int
715
iptablesRenameTmpRootChain(const char *iptables_cmd,
S
Stefan Berger 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
                           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,
737 738
                      "%s -E %s %s" CMD_SEPARATOR,
                      iptables_cmd,
S
Stefan Berger 已提交
739 740 741 742 743 744 745
                      tmpchain,
                      chain);
    return 0;
}


static int
746
iptablesRenameTmpRootChains(const char *iptables_cmd,
S
Stefan Berger 已提交
747 748 749
                            virBufferPtr buf,
                            const char *ifname)
{
750 751 752
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 0, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'F', 1, ifname);
    iptablesRenameTmpRootChain(iptables_cmd, buf, 'H', 1, ifname);
S
Stefan Berger 已提交
753 754 755 756 757
    return 0;
}


static void
758
iptablesInstCommand(virBufferPtr buf,
S
Stefan Berger 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771
                    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
772
iptablesHandleSrcMacAddr(virBufferPtr buf,
S
Stefan Berger 已提交
773 774
                         virNWFilterHashTablePtr vars,
                         nwItemDescPtr srcMacAddr,
775 776
                         int directionIn,
                         bool *srcmacskipped)
S
Stefan Berger 已提交
777 778
{
    char macaddr[VIR_MAC_STRING_BUFLEN];
779
    *srcmacskipped = false;
S
Stefan Berger 已提交
780 781

    if (HAS_ENTRY_ITEM(srcMacAddr)) {
782 783 784 785 786
        if (directionIn) {
            *srcmacskipped = true;
            return 0;
        }

787
        if (printDataType(vars,
S
Stefan Berger 已提交
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
                          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
808
iptablesHandleIpHdr(virBufferPtr buf,
S
Stefan Berger 已提交
809 810 811 812
                    virNWFilterHashTablePtr vars,
                    ipHdrDataDefPtr ipHdr,
                    int directionIn)
{
813
    char ipaddr[INET6_ADDRSTRLEN],
S
Stefan Berger 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826 827
         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)) {

828
        if (printDataType(vars,
S
Stefan Berger 已提交
829 830 831 832 833 834 835 836 837 838 839 840
                          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)) {

841
            if (printDataType(vars,
S
Stefan Berger 已提交
842 843 844 845 846 847 848 849 850 851
                              number, sizeof(number),
                              &ipHdr->dataSrcIPMask))
                goto err_exit;

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

852
        if (printDataType(vars,
S
Stefan Berger 已提交
853 854 855 856 857 858 859 860 861 862 863 864
                          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)) {

865
            if (printDataType(vars,
S
Stefan Berger 已提交
866 867 868 869 870 871 872 873 874 875 876 877
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataSrcIPTo))
                goto err_exit;

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

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

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

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

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

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

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

916
            if (printDataType(vars,
S
Stefan Berger 已提交
917 918 919
                              ipaddr, sizeof(ipaddr),
                              &ipHdr->dataDstIPTo))
                goto err_exit;
920

S
Stefan Berger 已提交
921 922 923 924 925
            virBufferVSprintf(buf,
                              "-%s",
                              ipaddr);
        }
    }
926

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

929
        if (printDataType(vars,
S
Stefan Berger 已提交
930 931 932
                          number, sizeof(number),
                          &ipHdr->dataDSCP))
           goto err_exit;
933

S
Stefan Berger 已提交
934 935 936 937
        virBufferVSprintf(buf,
                          " -m dscp %s --dscp %s",
                          ENTRY_GET_NEG_SIGN(&ipHdr->dataDSCP),
                          number);
938 939
    }

S
Stefan Berger 已提交
940
    return 0;
941

S
Stefan Berger 已提交
942 943 944 945
err_exit:
    virBufferFreeAndReset(buf);

    return 1;
946 947 948 949
}


static int
950
iptablesHandlePortData(virBufferPtr buf,
S
Stefan Berger 已提交
951 952 953
                       virNWFilterHashTablePtr vars,
                       portDataDefPtr portData,
                       int directionIn)
954
{
S
Stefan Berger 已提交
955 956 957 958 959 960 961
    char portstr[20];
    const char *sport = "--sport";
    const char *dport = "--dport";
    if (directionIn) {
        sport = "--dport";
        dport = "--sport";
    }
962

S
Stefan Berger 已提交
963
    if (HAS_ENTRY_ITEM(&portData->dataSrcPortStart)) {
964
        if (printDataType(vars,
S
Stefan Berger 已提交
965 966
                          portstr, sizeof(portstr),
                          &portData->dataSrcPortStart))
967 968 969
            goto err_exit;

        virBufferVSprintf(buf,
S
Stefan Berger 已提交
970 971 972 973
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataSrcPortStart),
                          sport,
                          portstr);
974

S
Stefan Berger 已提交
975
        if (HAS_ENTRY_ITEM(&portData->dataSrcPortEnd)) {
976
            if (printDataType(vars,
S
Stefan Berger 已提交
977 978
                              portstr, sizeof(portstr),
                              &portData->dataSrcPortEnd))
979 980
                goto err_exit;

S
Stefan Berger 已提交
981 982 983
             virBufferVSprintf(buf,
                               ":%s",
                               portstr);
984 985 986
        }
    }

S
Stefan Berger 已提交
987
    if (HAS_ENTRY_ITEM(&portData->dataDstPortStart)) {
988
        if (printDataType(vars,
S
Stefan Berger 已提交
989 990
                          portstr, sizeof(portstr),
                          &portData->dataDstPortStart))
991 992 993
            goto err_exit;

        virBufferVSprintf(buf,
S
Stefan Berger 已提交
994 995 996 997
                          " %s %s %s",
                          ENTRY_GET_NEG_SIGN(&portData->dataDstPortStart),
                          dport,
                          portstr);
998

S
Stefan Berger 已提交
999
        if (HAS_ENTRY_ITEM(&portData->dataDstPortEnd)) {
1000
            if (printDataType(vars,
S
Stefan Berger 已提交
1001 1002
                              portstr, sizeof(portstr),
                              &portData->dataDstPortEnd))
1003 1004
                goto err_exit;

S
Stefan Berger 已提交
1005 1006 1007
             virBufferVSprintf(buf,
                               ":%s",
                               portstr);
1008 1009 1010 1011 1012
        }
    }

    return 0;

S
Stefan Berger 已提交
1013
err_exit:
1014 1015 1016
    return 1;
}

S
Stefan Berger 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
/*
 * _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
 *
 * 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
1033
_iptablesCreateRuleInstance(int directionIn,
S
Stefan Berger 已提交
1034 1035 1036 1037 1038 1039 1040
                            const char *chainPrefix,
                            virNWFilterDefPtr nwfilter,
                            virNWFilterRuleDefPtr rule,
                            const char *ifname,
                            virNWFilterHashTablePtr vars,
                            virNWFilterRuleInstPtr res,
                            const char *match,
1041 1042
                            const char *accept_target,
                            bool isIPv6)
S
Stefan Berger 已提交
1043 1044 1045 1046 1047
{
    char chain[MAX_CHAINNAME_LENGTH];
    char number[20];
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    const char *target;
1048
    const char *iptables_cmd = (isIPv6) ? IP6TABLES_CMD : IPTABLES_CMD;
1049 1050
    unsigned int bufUsed;
    bool srcMacSkipped = false;
S
Stefan Berger 已提交
1051 1052 1053 1054 1055

    PRINT_IPT_ROOT_CHAIN(chain, chainPrefix, ifname);

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
1056
    case VIR_NWFILTER_RULE_PROTOCOL_TCPoIPV6:
S
Stefan Berger 已提交
1057
        virBufferVSprintf(&buf,
1058 1059
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1060 1061 1062 1063
                          chain);

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

1064 1065
        bufUsed = virBufferUse(&buf);

1066
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1067 1068
                                     vars,
                                     &rule->p.tcpHdrFilter.dataSrcMACAddr,
1069 1070
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1071 1072
            goto err_exit;

1073
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1074 1075 1076 1077 1078
                                vars,
                                &rule->p.tcpHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

1079
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1080 1081 1082 1083 1084 1085
                                   vars,
                                   &rule->p.tcpHdrFilter.portData,
                                   directionIn))
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.tcpHdrFilter.dataTCPOption)) {
1086
            if (printDataType(vars,
S
Stefan Berger 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
                              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:
1100
    case VIR_NWFILTER_RULE_PROTOCOL_UDPoIPV6:
S
Stefan Berger 已提交
1101
        virBufferVSprintf(&buf,
1102 1103
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1104 1105 1106 1107
                          chain);

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

1108 1109
        bufUsed = virBufferUse(&buf);

1110
        if (iptablesHandleSrcMacAddr(&buf,
S
Stefan Berger 已提交
1111 1112
                                     vars,
                                     &rule->p.udpHdrFilter.dataSrcMACAddr,
1113 1114
                                     directionIn,
                                     &srcMacSkipped))
S
Stefan Berger 已提交
1115 1116
            goto err_exit;

1117
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1118 1119 1120 1121 1122
                                vars,
                                &rule->p.udpHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

1123
        if (iptablesHandlePortData(&buf,
S
Stefan Berger 已提交
1124 1125 1126 1127 1128 1129
                                   vars,
                                   &rule->p.udpHdrFilter.portData,
                                   directionIn))
            goto err_exit;
    break;

1130
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
1131
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITEoIPV6:
1132
        virBufferVSprintf(&buf,
1133 1134
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1135 1136 1137 1138
                          chain);

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

1139 1140
        bufUsed = virBufferUse(&buf);

1141
        if (iptablesHandleSrcMacAddr(&buf,
1142 1143
                                     vars,
                                     &rule->p.udpliteHdrFilter.dataSrcMACAddr,
1144 1145
                                     directionIn,
                                     &srcMacSkipped))
1146 1147
            goto err_exit;

1148
        if (iptablesHandleIpHdr(&buf,
1149 1150 1151 1152 1153 1154 1155 1156
                                vars,
                                &rule->p.udpliteHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
1157
    case VIR_NWFILTER_RULE_PROTOCOL_ESPoIPV6:
1158
        virBufferVSprintf(&buf,
1159 1160
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1161 1162 1163 1164
                          chain);

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

1165 1166
        bufUsed = virBufferUse(&buf);

1167
        if (iptablesHandleSrcMacAddr(&buf,
1168 1169
                                     vars,
                                     &rule->p.espHdrFilter.dataSrcMACAddr,
1170 1171
                                     directionIn,
                                     &srcMacSkipped))
1172 1173
            goto err_exit;

1174
        if (iptablesHandleIpHdr(&buf,
1175 1176 1177 1178 1179 1180 1181 1182
                                vars,
                                &rule->p.espHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

    break;

    case VIR_NWFILTER_RULE_PROTOCOL_AH:
1183
    case VIR_NWFILTER_RULE_PROTOCOL_AHoIPV6:
1184
        virBufferVSprintf(&buf,
1185 1186
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
1187 1188 1189 1190
                          chain);

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

1191 1192
        bufUsed = virBufferUse(&buf);

1193
        if (iptablesHandleSrcMacAddr(&buf,
1194 1195
                                     vars,
                                     &rule->p.ahHdrFilter.dataSrcMACAddr,
1196 1197
                                     directionIn,
                                     &srcMacSkipped))
1198 1199
            goto err_exit;

1200
        if (iptablesHandleIpHdr(&buf,
1201 1202 1203 1204 1205 1206 1207
                                vars,
                                &rule->p.ahHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

    break;

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

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

1217 1218
        bufUsed = virBufferUse(&buf);

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

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

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

    case VIR_NWFILTER_RULE_PROTOCOL_ICMP:
1240
    case VIR_NWFILTER_RULE_PROTOCOL_ICMPV6:
S
Stefan Berger 已提交
1241
        virBufferVSprintf(&buf,
1242 1243
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1244 1245
                          chain);

1246 1247 1248 1249
        if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
            virBufferAddLit(&buf, " -p icmp");
        else
            virBufferAddLit(&buf, " -p icmpv6");
S
Stefan Berger 已提交
1250

1251 1252
        bufUsed = virBufferUse(&buf);

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

1260
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1261 1262 1263 1264 1265 1266
                                vars,
                                &rule->p.icmpHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPType)) {
1267 1268 1269 1270 1271 1272
            const char *parm;
            if (rule->prtclType == VIR_NWFILTER_RULE_PROTOCOL_ICMP)
                parm = "--icmp-type";
            else
                parm = "--icmpv6-type";

1273
            if (printDataType(vars,
S
Stefan Berger 已提交
1274 1275 1276 1277 1278
                              number, sizeof(number),
                              &rule->p.icmpHdrFilter.dataICMPType))
                goto err_exit;

            virBufferVSprintf(&buf,
1279
                      " %s %s %s",
S
Stefan Berger 已提交
1280
                      ENTRY_GET_NEG_SIGN(&rule->p.icmpHdrFilter.dataICMPType),
1281
                      parm,
S
Stefan Berger 已提交
1282 1283 1284
                      number);

            if (HAS_ENTRY_ITEM(&rule->p.icmpHdrFilter.dataICMPCode)) {
1285
                if (printDataType(vars,
S
Stefan Berger 已提交
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
                                  number, sizeof(number),
                                  &rule->p.icmpHdrFilter.dataICMPCode))
                    goto err_exit;

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

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

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

1305 1306
        bufUsed = virBufferUse(&buf);

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

1314
        if (iptablesHandleIpHdr(&buf,
1315 1316 1317 1318 1319 1320 1321
                                vars,
                                &rule->p.igmpHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

    break;

S
Stefan Berger 已提交
1322
    case VIR_NWFILTER_RULE_PROTOCOL_ALL:
1323
    case VIR_NWFILTER_RULE_PROTOCOL_ALLoIPV6:
S
Stefan Berger 已提交
1324
        virBufferVSprintf(&buf,
1325 1326
                          CMD_DEF_PRE "%s -%%c %s %%s",
                          iptables_cmd,
S
Stefan Berger 已提交
1327 1328 1329 1330
                          chain);

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

1331 1332
        bufUsed = virBufferUse(&buf);

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

1340
        if (iptablesHandleIpHdr(&buf,
S
Stefan Berger 已提交
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
                                vars,
                                &rule->p.allHdrFilter.ipHdr,
                                directionIn))
            goto err_exit;

    break;

    default:
        return -1;
    }

1352 1353 1354 1355 1356
    if (srcMacSkipped && bufUsed == virBufferUse(&buf)) {
        virBufferFreeAndReset(&buf);
        return 0;
    }

S
Stefan Berger 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
    if (match)
        virBufferVSprintf(&buf, " %s", match);

    if (rule->action == VIR_NWFILTER_RULE_ACTION_ACCEPT)
        target = accept_target;
    else
        target = "DROP";

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

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

1376
    return ebiptablesAddRuleInst(res,
S
Stefan Berger 已提交
1377 1378 1379 1380
                                 virBufferContentAndReset(&buf),
                                 nwfilter->chainsuffix,
                                 '\0',
                                 rule->priority,
1381
                                 (isIPv6) ? RT_IP6TABLES : RT_IPTABLES);
S
Stefan Berger 已提交
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392


err_exit:
    virBufferFreeAndReset(&buf);

    return -1;

}


static int
1393
iptablesCreateRuleInstance(virNWFilterDefPtr nwfilter,
S
Stefan Berger 已提交
1394 1395 1396
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
                           virNWFilterHashTablePtr vars,
1397 1398
                           virNWFilterRuleInstPtr res,
                           bool isIPv6)
S
Stefan Berger 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
{
    int rc;
    int directionIn = 0;
    char chainPrefix[2];
    int needState = 1;

    if ((rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN) ||
        (rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT)) {
        directionIn = 1;
        needState = 0;
    }

    chainPrefix[0] = 'F';

    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1414
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1415 1416 1417 1418 1419 1420 1421 1422
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
                                     needState ? MATCH_STATE_OUT
                                               : NULL,
1423 1424
                                     "RETURN",
                                     isIPv6);
S
Stefan Berger 已提交
1425 1426 1427 1428
    if (rc)
        return rc;

    chainPrefix[1] = CHAINPREFIX_HOST_OUT_TEMP;
1429
    rc = _iptablesCreateRuleInstance(!directionIn,
S
Stefan Berger 已提交
1430 1431 1432 1433 1434 1435 1436 1437
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
                                     needState ? MATCH_STATE_IN
                                               : NULL,
1438 1439
                                     "ACCEPT",
                                     isIPv6);
S
Stefan Berger 已提交
1440 1441 1442 1443 1444
    if (rc)
        return rc;

    chainPrefix[0] = 'H';
    chainPrefix[1] = CHAINPREFIX_HOST_IN_TEMP;
1445
    rc = _iptablesCreateRuleInstance(directionIn,
S
Stefan Berger 已提交
1446 1447 1448 1449 1450 1451 1452
                                     chainPrefix,
                                     nwfilter,
                                     rule,
                                     ifname,
                                     vars,
                                     res,
                                     NULL,
1453 1454
                                     "ACCEPT",
                                     isIPv6);
S
Stefan Berger 已提交
1455 1456 1457 1458 1459 1460 1461 1462 1463
    if (rc)
        return rc;

    return rc;
}




1464 1465 1466 1467 1468 1469 1470 1471
/*
 * 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
1472
 * @reverse : Whether to reverse src and dst attributes
1473 1474 1475 1476 1477 1478 1479 1480
 *
 * 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
1481
ebtablesCreateRuleInstance(char chainPrefix,
1482 1483 1484 1485
                           virNWFilterDefPtr nwfilter,
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
                           virNWFilterHashTablePtr vars,
1486 1487
                           virNWFilterRuleInstPtr res,
                           bool reverse)
1488 1489 1490
{
    char macaddr[VIR_MAC_STRING_BUFLEN],
         ipaddr[INET_ADDRSTRLEN],
1491
         ipv6addr[INET6_ADDRSTRLEN],
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
         number[20];
    char chain[MAX_CHAINNAME_LENGTH];
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    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,
                          CMD_DEF_PRE EBTABLES_CMD " -t %s -%%c %s %%s",
                          EBTABLES_DEFAULT_TABLE, chain);


1511
        if (ebtablesHandleEthHdr(&buf,
1512
                                 vars,
1513 1514
                                 &rule->p.ethHdrFilter.ethHdr,
                                 reverse))
1515 1516 1517
            goto err_exit;

        if (HAS_ENTRY_ITEM(&rule->p.ethHdrFilter.dataProtocolID)) {
1518
            if (printDataTypeAsHex(vars,
1519 1520
                                   number, sizeof(number),
                                   &rule->p.ethHdrFilter.dataProtocolID))
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
                goto err_exit;
            virBufferVSprintf(&buf,
                          " -p %s %s",
                          ENTRY_GET_NEG_SIGN(&rule->p.ethHdrFilter.dataProtocolID),
                          number);
        }
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_ARP:

        virBufferVSprintf(&buf,
                          CMD_DEF_PRE EBTABLES_CMD " -t %s -%%c %s %%s",
                          EBTABLES_DEFAULT_TABLE, chain);

1535
        if (ebtablesHandleEthHdr(&buf,
1536
                                 vars,
1537 1538
                                 &rule->p.arpHdrFilter.ethHdr,
                                 reverse))
1539 1540 1541 1542 1543
            goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataHWType)) {
1544 1545 1546
             if (printDataType(vars,
                               number, sizeof(number),
                               &rule->p.arpHdrFilter.dataHWType))
1547 1548 1549 1550 1551 1552 1553 1554
                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)) {
1555
            if (printDataType(vars,
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
                              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)) {
1566
            if (printDataTypeAsHex(vars,
1567 1568
                                   number, sizeof(number),
                                   &rule->p.arpHdrFilter.dataProtocolType))
1569 1570 1571 1572 1573 1574 1575 1576
                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)) {
1577
            if (printDataType(vars,
1578 1579 1580 1581 1582
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1583 1584
                          " %s %s %s",
                          reverse ? "--arp-ip-dst" : "--arp-ip-src",
1585 1586 1587 1588 1589
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstIPAddr)) {
1590
            if (printDataType(vars,
1591 1592 1593 1594 1595
                              ipaddr, sizeof(ipaddr),
                              &rule->p.arpHdrFilter.dataARPDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1596 1597
                          " %s %s %s",
                          reverse ? "--arp-ip-src" : "--arp-ip-dst",
1598 1599 1600 1601 1602
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstIPAddr),
                          ipaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPSrcMACAddr)) {
1603
            if (printDataType(vars,
1604 1605 1606 1607 1608
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPSrcMACAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1609 1610
                          " %s %s %s",
                          reverse ? "--arp-mac-dst" : "--arp-mac-src",
1611 1612 1613 1614 1615
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPSrcMACAddr),
                          macaddr);
        }

        if (HAS_ENTRY_ITEM(&rule->p.arpHdrFilter.dataARPDstMACAddr)) {
1616
            if (printDataType(vars,
1617 1618 1619 1620 1621
                              macaddr, sizeof(macaddr),
                              &rule->p.arpHdrFilter.dataARPDstMACAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1622 1623
                          " %s %s %s",
                          reverse ? "--arp-mac-src" : "--arp-mac-dst",
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
                          ENTRY_GET_NEG_SIGN(&rule->p.arpHdrFilter.dataARPDstMACAddr),
                          macaddr);
        }
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_IP:
        virBufferVSprintf(&buf,
                          CMD_DEF_PRE EBTABLES_CMD " -t %s -%%c %s %%s",
                          EBTABLES_DEFAULT_TABLE, chain);

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

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

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr)) {
1644
            if (printDataType(vars,
1645 1646 1647 1648 1649
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1650 1651
                          " %s %s %s",
                          reverse ? "--ip-destination" : "--ip-source",
1652 1653 1654 1655
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataSrcIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataSrcIPMask)) {
1656
                if (printDataType(vars,
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                             "/%s",
                             number);
            }
        }

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

1668
            if (printDataType(vars,
1669 1670 1671 1672 1673
                              ipaddr, sizeof(ipaddr),
                              &rule->p.ipHdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1674 1675
                          " %s %s %s",
                          reverse ? "--ip-source" : "--ip-destination",
1676 1677 1678 1679
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.ipHdr.dataDstIPAddr),
                          ipaddr);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDstIPMask)) {
1680
                if (printDataType(vars,
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataProtocolID)) {
1691
            if (printDataType(vars,
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
                              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)) {

1704
            if (printDataType(vars,
1705 1706 1707 1708 1709
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataSrcPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1710 1711
                          " %s %s %s",
                          reverse ? "--ip-destination-port" : "--ip-source-port",
1712 1713 1714 1715
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataSrcPortEnd)) {
1716
                if (printDataType(vars,
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
                                  number, sizeof(number),
                                  &rule->p.ipHdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

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

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

1729
            if (printDataType(vars,
1730 1731 1732 1733 1734
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.portData.dataDstPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1735 1736
                          " %s %s %s",
                          reverse ? "--ip-source-port" : "--ip-destination-port",
1737 1738 1739 1740
                          ENTRY_GET_NEG_SIGN(&rule->p.ipHdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.portData.dataDstPortEnd)) {
1741
                if (printDataType(vars,
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
                                number, sizeof(number),
                                &rule->p.ipHdrFilter.portData.dataDstPortEnd))
                    goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.ipHdrFilter.ipHdr.dataDSCP)) {
1753
            if (printDataType(vars,
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
                              number, sizeof(number),
                              &rule->p.ipHdrFilter.ipHdr.dataDSCP))
                goto err_exit;

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

1765 1766 1767 1768 1769
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
        virBufferVSprintf(&buf,
                          CMD_DEF_PRE EBTABLES_CMD " -t %s -%%c %s %%s",
                          EBTABLES_DEFAULT_TABLE, chain);

1770
        if (ebtablesHandleEthHdr(&buf,
1771
                                 vars,
1772 1773
                                 &rule->p.ipv6HdrFilter.ethHdr,
                                 reverse))
1774 1775 1776 1777 1778 1779
            goto err_exit;

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

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr)) {
1780
            if (printDataType(vars,
1781 1782 1783 1784 1785
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1786 1787
                          " %s %s %s",
                          reverse ? "--ip6-destination" : "--ip6-source",
1788 1789 1790 1791
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask)) {
1792
                if (printDataType(vars,
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataSrcIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                             "/%s",
                             number);
            }
        }

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

1804
            if (printDataType(vars,
1805 1806 1807 1808 1809
                              ipv6addr, sizeof(ipv6addr),
                              &rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr))
                goto err_exit;

            virBufferVSprintf(&buf,
1810 1811
                          " %s %s %s",
                          reverse ? "--ip6-source" : "--ip6-destination",
1812 1813 1814 1815
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPAddr),
                          ipv6addr);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask)) {
1816
                if (printDataType(vars,
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.ipHdr.dataDstIPMask))
                    goto err_exit;
                virBufferVSprintf(&buf,
                                  "/%s",
                                  number);
            }
        }

        if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.ipHdr.dataProtocolID)) {
1827
            if (printDataType(vars,
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
                              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)) {

1840
            if (printDataType(vars,
1841 1842 1843 1844 1845
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataSrcPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1846 1847
                          " %s %s %s",
                          reverse ? "--ip6-destination-port" : "--ip6-source-port",
1848 1849 1850 1851
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataSrcPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataSrcPortEnd)) {
1852
                if (printDataType(vars,
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataSrcPortEnd))
                    goto err_exit;

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

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

1865
            if (printDataType(vars,
1866 1867 1868 1869 1870
                              number, sizeof(number),
                              &rule->p.ipv6HdrFilter.portData.dataDstPortStart))
                goto err_exit;

            virBufferVSprintf(&buf,
1871 1872
                          " %s %s %s",
                          reverse ? "--ip6-source-port" : "--ip6-destination-port",
1873 1874 1875 1876
                          ENTRY_GET_NEG_SIGN(&rule->p.ipv6HdrFilter.portData.dataDstPortStart),
                          number);

            if (HAS_ENTRY_ITEM(&rule->p.ipv6HdrFilter.portData.dataDstPortEnd)) {
1877 1878 1879
                if (printDataType(vars,
                                  number, sizeof(number),
                                  &rule->p.ipv6HdrFilter.portData.dataDstPortEnd))
1880 1881 1882 1883 1884 1885 1886 1887 1888
                    goto err_exit;

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

1889 1890 1891 1892 1893
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
        virBufferVSprintf(&buf,
                          CMD_DEF_PRE EBTABLES_CMD " -t %s -%%c %s %%s",
                          EBTABLES_DEFAULT_TABLE, chain);
    break;
S
Stefan Berger 已提交
1894 1895 1896

    default:
        return -1;
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
    }

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

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

1910
    return ebiptablesAddRuleInst(res,
1911 1912 1913
                                 virBufferContentAndReset(&buf),
                                 nwfilter->chainsuffix,
                                 chainPrefix,
S
Stefan Berger 已提交
1914 1915
                                 rule->priority,
                                 RT_EBTABLES);
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939

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
1940
ebiptablesCreateRuleInstance(virConnectPtr conn ATTRIBUTE_UNUSED,
S
Stefan Berger 已提交
1941
                             enum virDomainNetType nettype,
1942 1943 1944 1945 1946 1947 1948
                             virNWFilterDefPtr nwfilter,
                             virNWFilterRuleDefPtr rule,
                             const char *ifname,
                             virNWFilterHashTablePtr vars,
                             virNWFilterRuleInstPtr res)
{
    int rc = 0;
1949
    bool isIPv6;
1950 1951 1952 1953 1954 1955

    switch (rule->prtclType) {
    case VIR_NWFILTER_RULE_PROTOCOL_IP:
    case VIR_NWFILTER_RULE_PROTOCOL_MAC:
    case VIR_NWFILTER_RULE_PROTOCOL_ARP:
    case VIR_NWFILTER_RULE_PROTOCOL_NONE:
1956
    case VIR_NWFILTER_RULE_PROTOCOL_IPV6:
1957 1958 1959

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_OUT ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
1960
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_IN_TEMP,
1961 1962 1963 1964
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
1965 1966
                                            res,
                                            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT);
1967 1968 1969 1970 1971 1972
            if (rc)
                return rc;
        }

        if (rule->tt == VIR_NWFILTER_RULE_DIRECTION_IN ||
            rule->tt == VIR_NWFILTER_RULE_DIRECTION_INOUT) {
1973
            rc = ebtablesCreateRuleInstance(CHAINPREFIX_HOST_OUT_TEMP,
1974 1975 1976 1977
                                            nwfilter,
                                            rule,
                                            ifname,
                                            vars,
1978 1979
                                            res,
                                            false);
1980 1981
        }
    break;
S
Stefan Berger 已提交
1982 1983 1984

    case VIR_NWFILTER_RULE_PROTOCOL_TCP:
    case VIR_NWFILTER_RULE_PROTOCOL_UDP:
1985 1986 1987
    case VIR_NWFILTER_RULE_PROTOCOL_UDPLITE:
    case VIR_NWFILTER_RULE_PROTOCOL_ESP:
    case VIR_NWFILTER_RULE_PROTOCOL_AH:
S
Stefan Berger 已提交
1988 1989 1990 1991 1992
    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) {
1993
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
S
Stefan Berger 已提交
1994 1995 1996 1997 1998
                          _("'%s' protocol not support for net type '%s'"),
                          virNWFilterRuleProtocolTypeToString(rule->prtclType),
                          virDomainNetTypeToString(nettype));
            return 1;
        }
1999
        isIPv6 = 0;
2000
        rc = iptablesCreateRuleInstance(nwfilter,
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
                                        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) {
2017
            virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
2018 2019 2020 2021 2022 2023
                          _("'%s' protocol not support for net type '%s'"),
                          virNWFilterRuleProtocolTypeToString(rule->prtclType),
                          virDomainNetTypeToString(nettype));
            return 1;
        }
        isIPv6 = 1;
2024
        rc = iptablesCreateRuleInstance(nwfilter,
S
Stefan Berger 已提交
2025 2026 2027
                                        rule,
                                        ifname,
                                        vars,
2028 2029
                                        res,
                                        isIPv6);
S
Stefan Berger 已提交
2030 2031 2032
    break;

    case VIR_NWFILTER_RULE_PROTOCOL_LAST:
2033
        virNWFilterReportError(VIR_ERR_INVALID_NWFILTER,
S
Stefan Berger 已提交
2034 2035 2036
                               "%s", _("illegal protocol type"));
        rc = 1;
    break;
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
    }

    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;
    printf("Command Template: %s\nNeeded protocol: %s\n\n",
           inst->commandTemplate,
           virNWFilterChainSuffixTypeToString(inst->neededProtocolChain));
    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 *
2077
ebiptablesWriteToTempFile(const char *string) {
2078 2079 2080 2081 2082 2083 2084 2085 2086
    char filename[] = "/tmp/virtdXXXXXX";
    int len;
    char *filnam;
    const char header[] = "#!" BASH_CMD "\n";
    size_t written;

    int fd = mkstemp(filename);

    if (fd < 0) {
2087
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2088 2089 2090 2091 2092 2093
                               "%s",
                               _("cannot create temporary file"));
        return NULL;
    }

    if (fchmod(fd, S_IXUSR| S_IRUSR | S_IWUSR) < 0) {
2094
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2095 2096 2097 2098 2099 2100 2101 2102
                               "%s",
                               _("cannot change permissions on temp. file"));
        goto err_exit;
    }

    len = strlen(header);
    written = safewrite(fd, header, len);
    if (written != len) {
2103
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2104 2105 2106 2107 2108 2109 2110 2111
                               "%s",
                               _("cannot write string to file"));
        goto err_exit;
    }

    len = strlen(string);
    written = safewrite(fd, string, len);
    if (written != len) {
2112
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
                               "%s",
                               _("cannot write string to file"));
        goto err_exit;
    }

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

    close(fd);
    return filnam;

err_exit:
    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
2149
ebiptablesExecCLI(virBufferPtr buf,
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
                  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;

2172
    filename = ebiptablesWriteToTempFile(cmds);
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
    VIR_FREE(cmds);

    if (!filename)
        return 1;

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

    *status >>= 8;

2183
    VIR_DEBUG("rc = %d, status = %d",rc, *status);
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193

    unlink(filename);

    VIR_FREE(filename);

    return rc;
}


static int
2194
ebtablesCreateTmpRootChain(virBufferPtr buf,
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
                           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,
                      CMD_DEF(EBTABLES_CMD " -t %s -N %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",
                      EBTABLES_DEFAULT_TABLE, chain,
                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2216
ebtablesLinkTmpRootChain(virBufferPtr buf,
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
                         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,
                      CMD_DEF(EBTABLES_CMD " -t %s -A %s -%c %s -j %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",
                      EBTABLES_DEFAULT_TABLE,
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2243
_ebtablesRemoveRootChain(virBufferPtr buf,
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
                         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,
                      EBTABLES_CMD " -t %s -F %s" CMD_SEPARATOR
                      EBTABLES_CMD " -t %s -X %s" CMD_SEPARATOR,
                      EBTABLES_DEFAULT_TABLE, chain,
                      EBTABLES_DEFAULT_TABLE, chain);

    return 0;
}


static int
2269
ebtablesRemoveRootChain(virBufferPtr buf,
2270 2271
                        int incoming, const char *ifname)
{
2272
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 0);
2273 2274 2275 2276
}


static int
2277
ebtablesRemoveTmpRootChain(virBufferPtr buf,
2278 2279
                           int incoming, const char *ifname)
{
2280
    return _ebtablesRemoveRootChain(buf, incoming, ifname, 1);
2281 2282 2283 2284
}


static int
2285
_ebtablesUnlinkRootChain(virBufferPtr buf,
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
                         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,
                      EBTABLES_CMD " -t %s -D %s -%c %s -j %s" CMD_SEPARATOR,
                      EBTABLES_DEFAULT_TABLE,
                      (incoming) ? EBTABLES_CHAIN_INCOMING
                                 : EBTABLES_CHAIN_OUTGOING,
                      iodev, ifname, chain);

    return 0;
}


static int
2315
ebtablesUnlinkRootChain(virBufferPtr buf,
2316 2317
                        int incoming, const char *ifname)
{
2318
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 0);
2319 2320 2321 2322
}


static int
2323
ebtablesUnlinkTmpRootChain(virBufferPtr buf,
2324 2325
                           int incoming, const char *ifname)
{
2326
    return _ebtablesUnlinkRootChain(buf, incoming, ifname, 1);
2327 2328 2329 2330
}


static int
2331
ebtablesCreateTmpSubChain(virBufferPtr buf,
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
                          int incoming,
                          const char *ifname,
                          const char *protocol,
                          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);
    PRINT_CHAIN(chain, chainPrefix, ifname, protocol);

    virBufferVSprintf(buf,
                      CMD_DEF(EBTABLES_CMD " -t %s -N %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s"
                      CMD_DEF(EBTABLES_CMD " -t %s -A %s -p %s -j %s") CMD_SEPARATOR
                      CMD_EXEC
                      "%s",

                      EBTABLES_DEFAULT_TABLE, chain,

                      CMD_STOPONERR(stopOnError),

                      EBTABLES_DEFAULT_TABLE,
                      rootchain,
                      protocol, chain,

                      CMD_STOPONERR(stopOnError));

    return 0;
}


static int
2367
_ebtablesRemoveSubChain(virBufferPtr buf,
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
                        int incoming,
                        const char *ifname,
                        const char *protocol,
                        int isTempChain)
{
    char rootchain[MAX_CHAINNAME_LENGTH], 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(rootchain, chainPrefix, ifname);
    PRINT_CHAIN(chain, chainPrefix, ifname, protocol);

    virBufferVSprintf(buf,
                      EBTABLES_CMD " -t %s -D %s -p %s -j %s" CMD_SEPARATOR
                      EBTABLES_CMD " -t %s -F %s" CMD_SEPARATOR
                      EBTABLES_CMD " -t %s -X %s" CMD_SEPARATOR,
                      EBTABLES_DEFAULT_TABLE,
                      rootchain,
                      protocol, chain,

                      EBTABLES_DEFAULT_TABLE, chain,

                      EBTABLES_DEFAULT_TABLE, chain);

    return 0;
}


static int
2403
ebtablesRemoveSubChain(virBufferPtr buf,
2404 2405 2406 2407
                       int incoming,
                       const char *ifname,
                       const char *protocol)
{
2408
    return _ebtablesRemoveSubChain(buf,
2409 2410 2411 2412 2413
                                   incoming, ifname, protocol, 0);
}


static int
2414 2415
ebtablesRemoveSubChains(virBufferPtr buf,
                        const char *ifname)
2416 2417 2418
{
    int i;
    for (i = 0; supported_protocols[i]; i++) {
2419 2420
        ebtablesRemoveSubChain(buf, 1, ifname, supported_protocols[i]);
        ebtablesRemoveSubChain(buf, 0, ifname, supported_protocols[i]);
2421 2422 2423 2424 2425 2426 2427
    }

    return 0;
}


static int
2428
ebtablesRemoveTmpSubChain(virBufferPtr buf,
2429 2430 2431 2432
                          int incoming,
                          const char *ifname,
                          const char *protocol)
{
2433
    return _ebtablesRemoveSubChain(buf,
2434 2435 2436 2437 2438
                                   incoming, ifname, protocol, 1);
}


static int
2439
ebtablesRemoveTmpSubChains(virBufferPtr buf,
2440 2441 2442 2443
                           const char *ifname)
{
    int i;
    for (i = 0; supported_protocols[i]; i++) {
2444
        ebtablesRemoveTmpSubChain(buf, 1, ifname,
2445
                                  supported_protocols[i]);
2446
        ebtablesRemoveTmpSubChain(buf, 0, ifname,
2447 2448 2449 2450 2451 2452 2453 2454
                                  supported_protocols[i]);
    }

    return 0;
}


static int
2455
ebtablesRenameTmpSubChain(virBufferPtr buf,
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
                          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,
                      EBTABLES_CMD " -t %s -E %s %s" CMD_SEPARATOR,
                      EBTABLES_DEFAULT_TABLE,
                      tmpchain,
                      chain);
    return 0;
}


static int
2484
ebtablesRenameTmpSubChains(virBufferPtr buf,
2485 2486 2487 2488
                           const char *ifname)
{
    int i;
    for (i = 0; supported_protocols[i]; i++) {
2489
        ebtablesRenameTmpSubChain (buf, 1, ifname,
2490
                                   supported_protocols[i]);
2491
        ebtablesRenameTmpSubChain (buf, 0, ifname,
2492 2493 2494 2495 2496 2497 2498 2499
                                   supported_protocols[i]);
    }

    return 0;
}


static int
2500
ebtablesRenameTmpRootChain(virBufferPtr buf,
2501 2502 2503
                           int incoming,
                           const char *ifname)
{
2504
    return ebtablesRenameTmpSubChain(buf, incoming, ifname, NULL);
2505 2506 2507 2508
}


static void
2509
ebiptablesInstCommand(virBufferPtr buf,
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
                      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
ebiptablesRuleOrderSort(const void *a, const void *b)
{
    const ebiptablesRuleInstPtr *insta = a;
    const ebiptablesRuleInstPtr *instb = b;
    return ((*insta)->priority - (*instb)->priority);
}


static int
2532
ebiptablesApplyNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
2533 2534 2535 2536 2537 2538 2539 2540 2541
                        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;
S
Stefan Berger 已提交
2542
    int haveIptables = 0;
2543
    int haveIp6tables = 0;
2544 2545 2546 2547 2548 2549

    if (inst)
        qsort(inst, nruleInstances, sizeof(inst[0]),
              ebiptablesRuleOrderSort);

    for (i = 0; i < nruleInstances; i++) {
S
Stefan Berger 已提交
2550 2551 2552 2553 2554 2555
        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);
        }
2556 2557
    }

2558 2559 2560 2561 2562 2563
    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);
    ebiptablesExecCLI(&buf, &cli_status);
2564 2565

    if (chains_in != 0)
2566
        ebtablesCreateTmpRootChain(&buf, 1, ifname, 1);
2567
    if (chains_out != 0)
2568
        ebtablesCreateTmpRootChain(&buf, 0, ifname, 1);
2569 2570

    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv4))
2571
        ebtablesCreateTmpSubChain(&buf, 1, ifname, "ipv4", 1);
2572
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv4))
2573
        ebtablesCreateTmpSubChain(&buf, 0, ifname, "ipv4", 1);
2574

2575
    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv6))
2576
        ebtablesCreateTmpSubChain(&buf, 1, ifname, "ipv6", 1);
2577
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_IPv6))
2578
        ebtablesCreateTmpSubChain(&buf, 0, ifname, "ipv6", 1);
2579

2580 2581
    // keep arp as last
    if (chains_in  & (1 << VIR_NWFILTER_CHAINSUFFIX_ARP))
2582
        ebtablesCreateTmpSubChain(&buf, 1, ifname, "arp", 1);
2583
    if (chains_out & (1 << VIR_NWFILTER_CHAINSUFFIX_ARP))
2584
        ebtablesCreateTmpSubChain(&buf, 0, ifname, "arp", 1);
2585

2586
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
2587 2588 2589
        goto tear_down_tmpebchains;

    for (i = 0; i < nruleInstances; i++)
S
Stefan Berger 已提交
2590 2591
        switch (inst[i]->ruleType) {
        case RT_EBTABLES:
2592
            ebiptablesInstCommand(&buf,
S
Stefan Berger 已提交
2593 2594 2595 2596 2597 2598
                                  inst[i]->commandTemplate,
                                  'A', -1, 1);
        break;
        case RT_IPTABLES:
            haveIptables = 1;
        break;
2599 2600 2601
        case RT_IP6TABLES:
            haveIp6tables = 1;
        break;
S
Stefan Berger 已提交
2602
        }
2603

2604
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
2605 2606 2607 2608
        goto tear_down_tmpebchains;

    // FIXME: establishment of iptables user define table tree goes here

S
Stefan Berger 已提交
2609
    if (haveIptables) {
2610 2611
        iptablesUnlinkTmpRootChains(IPTABLES_CMD, &buf, ifname);
        iptablesRemoveTmpRootChains(IPTABLES_CMD, &buf, ifname);
S
Stefan Berger 已提交
2612

2613
        iptablesCreateBaseChains(IPTABLES_CMD, &buf);
S
Stefan Berger 已提交
2614

2615
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
2616 2617
            goto tear_down_tmpebchains;

2618
        iptablesCreateTmpRootChains(IPTABLES_CMD, &buf, ifname);
S
Stefan Berger 已提交
2619

2620
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
2621 2622
           goto tear_down_tmpiptchains;

2623 2624 2625
        iptablesLinkTmpRootChains(IPTABLES_CMD, &buf, ifname);
        iptablesSetupVirtInPost(IPTABLES_CMD, &buf, ifname);
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
2626 2627 2628 2629
           goto tear_down_tmpiptchains;

        for (i = 0; i < nruleInstances; i++) {
            if (inst[i]->ruleType == RT_IPTABLES)
2630
                iptablesInstCommand(&buf,
S
Stefan Berger 已提交
2631 2632 2633 2634
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

2635
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
S
Stefan Berger 已提交
2636 2637 2638
           goto tear_down_tmpiptchains;
    }

2639
    if (haveIp6tables) {
2640 2641
        iptablesUnlinkTmpRootChains(IP6TABLES_CMD, &buf, ifname);
        iptablesRemoveTmpRootChains(IP6TABLES_CMD, &buf, ifname);
2642

2643
        iptablesCreateBaseChains(IP6TABLES_CMD, &buf);
2644

2645
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
2646 2647
            goto tear_down_tmpiptchains;

2648
        iptablesCreateTmpRootChains(IP6TABLES_CMD, &buf, ifname);
2649

2650
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
2651 2652
           goto tear_down_tmpip6tchains;

2653 2654 2655
        iptablesLinkTmpRootChains(IP6TABLES_CMD, &buf, ifname);
        iptablesSetupVirtInPost(IP6TABLES_CMD, &buf, ifname);
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
2656 2657 2658 2659
           goto tear_down_tmpip6tchains;

        for (i = 0; i < nruleInstances; i++) {
            if (inst[i]->ruleType == RT_IP6TABLES)
2660
                iptablesInstCommand(&buf,
2661 2662 2663 2664
                                    inst[i]->commandTemplate,
                                    'A', -1, 1);
        }

2665
        if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
2666 2667 2668
           goto tear_down_tmpip6tchains;
    }

S
Stefan Berger 已提交
2669

2670 2671 2672
    // END IPTABLES stuff

    if (chains_in != 0)
2673
        ebtablesLinkTmpRootChain(&buf, 1, ifname, 1);
2674
    if (chains_out != 0)
2675
        ebtablesLinkTmpRootChain(&buf, 0, ifname, 1);
2676

2677
    if (ebiptablesExecCLI(&buf, &cli_status) || cli_status != 0)
2678 2679 2680 2681 2682
        goto tear_down_ebsubchains_and_unlink;

    return 0;

tear_down_ebsubchains_and_unlink:
2683 2684
    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
2685

2686 2687
tear_down_tmpip6tchains:
    if (haveIp6tables) {
2688 2689
        iptablesUnlinkTmpRootChains(IP6TABLES_CMD, &buf, ifname);
        iptablesRemoveTmpRootChains(IP6TABLES_CMD, &buf, ifname);
2690 2691
    }

S
Stefan Berger 已提交
2692 2693
tear_down_tmpiptchains:
    if (haveIptables) {
2694 2695
        iptablesUnlinkTmpRootChains(IPTABLES_CMD, &buf, ifname);
        iptablesRemoveTmpRootChains(IPTABLES_CMD, &buf, ifname);
S
Stefan Berger 已提交
2696 2697
    }

2698
tear_down_tmpebchains:
2699 2700 2701
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);
2702

2703
    ebiptablesExecCLI(&buf, &cli_status);
2704

2705
    virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
2706 2707 2708 2709 2710 2711 2712 2713
                           "%s",
                           _("Some rules could not be created."));

    return 1;
}


static int
2714
ebiptablesTearNewRules(virConnectPtr conn ATTRIBUTE_UNUSED,
2715 2716 2717 2718 2719
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

2720 2721
    iptablesUnlinkTmpRootChains(IPTABLES_CMD, &buf, ifname);
    iptablesRemoveTmpRootChains(IPTABLES_CMD, &buf, ifname);
2722

2723 2724
    iptablesUnlinkTmpRootChains(IP6TABLES_CMD, &buf, ifname);
    iptablesRemoveTmpRootChains(IP6TABLES_CMD, &buf, ifname);
S
Stefan Berger 已提交
2725

2726 2727
    ebtablesUnlinkTmpRootChain(&buf, 1, ifname);
    ebtablesUnlinkTmpRootChain(&buf, 0, ifname);
2728

2729 2730 2731
    ebtablesRemoveTmpSubChains(&buf, ifname);
    ebtablesRemoveTmpRootChain(&buf, 1, ifname);
    ebtablesRemoveTmpRootChain(&buf, 0, ifname);
2732

2733
    ebiptablesExecCLI(&buf, &cli_status);
2734 2735 2736 2737 2738 2739

    return 0;
}


static int
2740
ebiptablesTearOldRules(virConnectPtr conn ATTRIBUTE_UNUSED,
2741 2742 2743 2744 2745
                       const char *ifname)
{
    int cli_status;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

S
Stefan Berger 已提交
2746
    // switch to new iptables user defined chains
2747 2748
    iptablesUnlinkRootChains(IPTABLES_CMD, &buf, ifname);
    iptablesRemoveRootChains(IPTABLES_CMD, &buf, ifname);
S
Stefan Berger 已提交
2749

2750 2751
    iptablesRenameTmpRootChains(IPTABLES_CMD, &buf, ifname);
    ebiptablesExecCLI(&buf, &cli_status);
2752

2753 2754
    iptablesUnlinkRootChains(IP6TABLES_CMD, &buf, ifname);
    iptablesRemoveRootChains(IP6TABLES_CMD, &buf, ifname);
2755

2756 2757
    iptablesRenameTmpRootChains(IP6TABLES_CMD, &buf, ifname);
    ebiptablesExecCLI(&buf, &cli_status);
S
Stefan Berger 已提交
2758

2759 2760
    ebtablesUnlinkRootChain(&buf, 1, ifname);
    ebtablesUnlinkRootChain(&buf, 0, ifname);
2761

2762
    ebtablesRemoveSubChains(&buf, ifname);
2763

2764 2765
    ebtablesRemoveRootChain(&buf, 1, ifname);
    ebtablesRemoveRootChain(&buf, 0, ifname);
2766

2767 2768 2769
    ebtablesRenameTmpSubChains(&buf, ifname);
    ebtablesRenameTmpRootChain(&buf, 1, ifname);
    ebtablesRenameTmpRootChain(&buf, 0, ifname);
2770

2771
    ebiptablesExecCLI(&buf, &cli_status);
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789

    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
2790
ebiptablesRemoveRules(virConnectPtr conn ATTRIBUTE_UNUSED,
2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
                      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++)
2802
        ebiptablesInstCommand(&buf,
2803 2804 2805 2806
                              inst[i]->commandTemplate,
                              'D', -1,
                              0);

2807
    if (ebiptablesExecCLI(&buf, &cli_status))
2808 2809 2810
        goto err_exit;

    if (cli_status) {
2811
        virNWFilterReportError(VIR_ERR_BUILD_FIREWALL,
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
                               "%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;

2837 2838 2839
    iptablesUnlinkRootChains(IPTABLES_CMD, &buf, ifname);
    iptablesClearVirtInPost (IPTABLES_CMD, &buf, ifname);
    iptablesRemoveRootChains(IPTABLES_CMD, &buf, ifname);
2840

2841 2842 2843
    iptablesUnlinkRootChains(IP6TABLES_CMD, &buf, ifname);
    iptablesClearVirtInPost (IP6TABLES_CMD, &buf, ifname);
    iptablesRemoveRootChains(IP6TABLES_CMD, &buf, ifname);
S
Stefan Berger 已提交
2844

2845 2846
    ebtablesUnlinkRootChain(&buf, 1, ifname);
    ebtablesUnlinkRootChain(&buf, 0, ifname);
2847

2848 2849
    ebtablesRemoveRootChain(&buf, 1, ifname);
    ebtablesRemoveRootChain(&buf, 0, ifname);
2850

2851
    ebtablesRemoveSubChains(&buf, ifname);
2852

2853
    ebiptablesExecCLI(&buf, &cli_status);
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870

    return 0;
}


virNWFilterTechDriver ebiptables_driver = {
    .name = EBIPTABLES_DRIVER_ID,

    .createRuleInstance  = ebiptablesCreateRuleInstance,
    .applyNewRules       = ebiptablesApplyNewRules,
    .tearNewRules        = ebiptablesTearNewRules,
    .tearOldRules        = ebiptablesTearOldRules,
    .allTeardown         = ebiptablesAllTeardown,
    .removeRules         = ebiptablesRemoveRules,
    .freeRuleInstance    = ebiptablesFreeRuleInstance,
    .displayRuleInstance = ebiptablesDisplayRuleInstance,
};