qemu/qemu-bridge-helper.c
<<
>>
Prefs
   1/*
   2 * QEMU Bridge Helper
   3 *
   4 * Copyright IBM, Corp. 2011
   5 *
   6 * Authors:
   7 * Anthony Liguori   <aliguori@us.ibm.com>
   8 * Richa Marwaha     <rmarwah@linux.vnet.ibm.com>
   9 * Corey Bryant      <coreyb@linux.vnet.ibm.com>
  10 *
  11 * This work is licensed under the terms of the GNU GPL, version 2.  See
  12 * the COPYING file in the top-level directory.
  13 *
  14 */
  15
  16#include "qemu/osdep.h"
  17
  18
  19#include <sys/ioctl.h>
  20#include <sys/socket.h>
  21#include <sys/un.h>
  22#include <sys/prctl.h>
  23
  24#include <net/if.h>
  25
  26#include <linux/sockios.h>
  27
  28#ifndef SIOCBRADDIF
  29#include <linux/if_bridge.h>
  30#endif
  31
  32#include "qemu/queue.h"
  33
  34#include "net/tap-linux.h"
  35
  36#ifdef CONFIG_LIBCAP
  37#include <cap-ng.h>
  38#endif
  39
  40#define DEFAULT_ACL_FILE CONFIG_QEMU_CONFDIR "/bridge.conf"
  41
  42enum {
  43    ACL_ALLOW = 0,
  44    ACL_ALLOW_ALL,
  45    ACL_DENY,
  46    ACL_DENY_ALL,
  47};
  48
  49typedef struct ACLRule {
  50    int type;
  51    char iface[IFNAMSIZ];
  52    QSIMPLEQ_ENTRY(ACLRule) entry;
  53} ACLRule;
  54
  55typedef QSIMPLEQ_HEAD(ACLList, ACLRule) ACLList;
  56
  57static void usage(void)
  58{
  59    fprintf(stderr,
  60            "Usage: qemu-bridge-helper [--use-vnet] --br=bridge --fd=unixfd\n");
  61}
  62
  63static int parse_acl_file(const char *filename, ACLList *acl_list)
  64{
  65    FILE *f;
  66    char line[4096];
  67    ACLRule *acl_rule;
  68
  69    f = fopen(filename, "r");
  70    if (f == NULL) {
  71        return -1;
  72    }
  73
  74    while (fgets(line, sizeof(line), f) != NULL) {
  75        char *ptr = line;
  76        char *cmd, *arg, *argend;
  77
  78        while (isspace(*ptr)) {
  79            ptr++;
  80        }
  81
  82        /* skip comments and empty lines */
  83        if (*ptr == '#' || *ptr == 0) {
  84            continue;
  85        }
  86
  87        cmd = ptr;
  88        arg = strchr(cmd, ' ');
  89        if (arg == NULL) {
  90            arg = strchr(cmd, '\t');
  91        }
  92
  93        if (arg == NULL) {
  94            fprintf(stderr, "Invalid config line:\n  %s\n", line);
  95            fclose(f);
  96            errno = EINVAL;
  97            return -1;
  98        }
  99
 100        *arg = 0;
 101        arg++;
 102        while (isspace(*arg)) {
 103            arg++;
 104        }
 105
 106        argend = arg + strlen(arg);
 107        while (arg != argend && isspace(*(argend - 1))) {
 108            argend--;
 109        }
 110        *argend = 0;
 111
 112        if (!g_str_equal(cmd, "include") && strlen(arg) >= IFNAMSIZ) {
 113            fprintf(stderr, "name `%s' too long: %zu\n", arg, strlen(arg));
 114            fclose(f);
 115            errno = EINVAL;
 116            return -1;
 117        }
 118
 119        if (strcmp(cmd, "deny") == 0) {
 120            acl_rule = g_malloc(sizeof(*acl_rule));
 121            if (strcmp(arg, "all") == 0) {
 122                acl_rule->type = ACL_DENY_ALL;
 123            } else {
 124                acl_rule->type = ACL_DENY;
 125                snprintf(acl_rule->iface, IFNAMSIZ, "%s", arg);
 126            }
 127            QSIMPLEQ_INSERT_TAIL(acl_list, acl_rule, entry);
 128        } else if (strcmp(cmd, "allow") == 0) {
 129            acl_rule = g_malloc(sizeof(*acl_rule));
 130            if (strcmp(arg, "all") == 0) {
 131                acl_rule->type = ACL_ALLOW_ALL;
 132            } else {
 133                acl_rule->type = ACL_ALLOW;
 134                snprintf(acl_rule->iface, IFNAMSIZ, "%s", arg);
 135            }
 136            QSIMPLEQ_INSERT_TAIL(acl_list, acl_rule, entry);
 137        } else if (strcmp(cmd, "include") == 0) {
 138            /* ignore errors */
 139            parse_acl_file(arg, acl_list);
 140        } else {
 141            fprintf(stderr, "Unknown command `%s'\n", cmd);
 142            fclose(f);
 143            errno = EINVAL;
 144            return -1;
 145        }
 146    }
 147
 148    fclose(f);
 149
 150    return 0;
 151}
 152
 153static bool has_vnet_hdr(int fd)
 154{
 155    unsigned int features = 0;
 156
 157    if (ioctl(fd, TUNGETFEATURES, &features) == -1) {
 158        return false;
 159    }
 160
 161    if (!(features & IFF_VNET_HDR)) {
 162        return false;
 163    }
 164
 165    return true;
 166}
 167
 168static void prep_ifreq(struct ifreq *ifr, const char *ifname)
 169{
 170    memset(ifr, 0, sizeof(*ifr));
 171    snprintf(ifr->ifr_name, IFNAMSIZ, "%s", ifname);
 172}
 173
 174static int send_fd(int c, int fd)
 175{
 176    char msgbuf[CMSG_SPACE(sizeof(fd))];
 177    struct msghdr msg = {
 178        .msg_control = msgbuf,
 179        .msg_controllen = sizeof(msgbuf),
 180    };
 181    struct cmsghdr *cmsg;
 182    struct iovec iov;
 183    char req[1] = { 0x00 };
 184
 185    cmsg = CMSG_FIRSTHDR(&msg);
 186    cmsg->cmsg_level = SOL_SOCKET;
 187    cmsg->cmsg_type = SCM_RIGHTS;
 188    cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
 189    msg.msg_controllen = cmsg->cmsg_len;
 190
 191    iov.iov_base = req;
 192    iov.iov_len = sizeof(req);
 193
 194    msg.msg_iov = &iov;
 195    msg.msg_iovlen = 1;
 196    memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
 197
 198    return sendmsg(c, &msg, 0);
 199}
 200
 201#ifdef CONFIG_LIBCAP
 202static int drop_privileges(void)
 203{
 204    /* clear all capabilities */
 205    capng_clear(CAPNG_SELECT_BOTH);
 206
 207    if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
 208                     CAP_NET_ADMIN) < 0) {
 209        return -1;
 210    }
 211
 212    /* change to calling user's real uid and gid, retaining supplemental
 213     * groups and CAP_NET_ADMIN */
 214    if (capng_change_id(getuid(), getgid(), CAPNG_CLEAR_BOUNDING)) {
 215        return -1;
 216    }
 217
 218    return 0;
 219}
 220#endif
 221
 222int main(int argc, char **argv)
 223{
 224    struct ifreq ifr;
 225#ifndef SIOCBRADDIF
 226    unsigned long ifargs[4];
 227#endif
 228    int ifindex;
 229    int fd = -1, ctlfd = -1, unixfd = -1;
 230    int use_vnet = 0;
 231    int mtu;
 232    const char *bridge = NULL;
 233    char iface[IFNAMSIZ];
 234    int index;
 235    ACLRule *acl_rule;
 236    ACLList acl_list;
 237    int access_allowed, access_denied;
 238    int ret = EXIT_SUCCESS;
 239
 240#ifdef CONFIG_LIBCAP
 241    /* if we're run from an suid binary, immediately drop privileges preserving
 242     * cap_net_admin */
 243    if (geteuid() == 0 && getuid() != geteuid()) {
 244        if (drop_privileges() == -1) {
 245            fprintf(stderr, "failed to drop privileges\n");
 246            return 1;
 247        }
 248    }
 249#endif
 250
 251    /* parse arguments */
 252    for (index = 1; index < argc; index++) {
 253        if (strcmp(argv[index], "--use-vnet") == 0) {
 254            use_vnet = 1;
 255        } else if (strncmp(argv[index], "--br=", 5) == 0) {
 256            bridge = &argv[index][5];
 257        } else if (strncmp(argv[index], "--fd=", 5) == 0) {
 258            unixfd = atoi(&argv[index][5]);
 259        } else {
 260            usage();
 261            return EXIT_FAILURE;
 262        }
 263    }
 264
 265    if (bridge == NULL || unixfd == -1) {
 266        usage();
 267        return EXIT_FAILURE;
 268    }
 269    if (strlen(bridge) >= IFNAMSIZ) {
 270        fprintf(stderr, "name `%s' too long: %zu\n", bridge, strlen(bridge));
 271        return EXIT_FAILURE;
 272    }
 273
 274    /* parse default acl file */
 275    QSIMPLEQ_INIT(&acl_list);
 276    if (parse_acl_file(DEFAULT_ACL_FILE, &acl_list) == -1) {
 277        fprintf(stderr, "failed to parse default acl file `%s'\n",
 278                DEFAULT_ACL_FILE);
 279        ret = EXIT_FAILURE;
 280        goto cleanup;
 281    }
 282
 283    /* validate bridge against acl -- default policy is to deny
 284     * according acl policy if we have a deny and allow both
 285     * then deny should always win over allow
 286     */
 287    access_allowed = 0;
 288    access_denied = 0;
 289    QSIMPLEQ_FOREACH(acl_rule, &acl_list, entry) {
 290        switch (acl_rule->type) {
 291        case ACL_ALLOW_ALL:
 292            access_allowed = 1;
 293            break;
 294        case ACL_ALLOW:
 295            if (strcmp(bridge, acl_rule->iface) == 0) {
 296                access_allowed = 1;
 297            }
 298            break;
 299        case ACL_DENY_ALL:
 300            access_denied = 1;
 301            break;
 302        case ACL_DENY:
 303            if (strcmp(bridge, acl_rule->iface) == 0) {
 304                access_denied = 1;
 305            }
 306            break;
 307        }
 308    }
 309
 310    if ((access_allowed == 0) || (access_denied == 1)) {
 311        fprintf(stderr, "access denied by acl file\n");
 312        ret = EXIT_FAILURE;
 313        goto cleanup;
 314    }
 315
 316    /* open a socket to use to control the network interfaces */
 317    ctlfd = socket(AF_INET, SOCK_STREAM, 0);
 318    if (ctlfd == -1) {
 319        fprintf(stderr, "failed to open control socket: %s\n", strerror(errno));
 320        ret = EXIT_FAILURE;
 321        goto cleanup;
 322    }
 323
 324    /* open the tap device */
 325    fd = open("/dev/net/tun", O_RDWR);
 326    if (fd == -1) {
 327        fprintf(stderr, "failed to open /dev/net/tun: %s\n", strerror(errno));
 328        ret = EXIT_FAILURE;
 329        goto cleanup;
 330    }
 331
 332    /* request a tap device, disable PI, and add vnet header support if
 333     * requested and it's available. */
 334    prep_ifreq(&ifr, "tap%d");
 335    ifr.ifr_flags = IFF_TAP|IFF_NO_PI;
 336    if (use_vnet && has_vnet_hdr(fd)) {
 337        ifr.ifr_flags |= IFF_VNET_HDR;
 338    }
 339
 340    if (ioctl(fd, TUNSETIFF, &ifr) == -1) {
 341        fprintf(stderr, "failed to create tun device: %s\n", strerror(errno));
 342        ret = EXIT_FAILURE;
 343        goto cleanup;
 344    }
 345
 346    /* save tap device name */
 347    snprintf(iface, sizeof(iface), "%s", ifr.ifr_name);
 348
 349    /* get the mtu of the bridge */
 350    prep_ifreq(&ifr, bridge);
 351    if (ioctl(ctlfd, SIOCGIFMTU, &ifr) == -1) {
 352        fprintf(stderr, "failed to get mtu of bridge `%s': %s\n",
 353                bridge, strerror(errno));
 354        ret = EXIT_FAILURE;
 355        goto cleanup;
 356    }
 357
 358    /* save mtu */
 359    mtu = ifr.ifr_mtu;
 360
 361    /* set the mtu of the interface based on the bridge */
 362    prep_ifreq(&ifr, iface);
 363    ifr.ifr_mtu = mtu;
 364    if (ioctl(ctlfd, SIOCSIFMTU, &ifr) == -1) {
 365        fprintf(stderr, "failed to set mtu of device `%s' to %d: %s\n",
 366                iface, mtu, strerror(errno));
 367        ret = EXIT_FAILURE;
 368        goto cleanup;
 369    }
 370
 371    /* Linux uses the lowest enslaved MAC address as the MAC address of
 372     * the bridge.  Set MAC address to a high value so that it doesn't
 373     * affect the MAC address of the bridge.
 374     */
 375    if (ioctl(ctlfd, SIOCGIFHWADDR, &ifr) < 0) {
 376        fprintf(stderr, "failed to get MAC address of device `%s': %s\n",
 377                iface, strerror(errno));
 378        ret = EXIT_FAILURE;
 379        goto cleanup;
 380    }
 381    ifr.ifr_hwaddr.sa_data[0] = 0xFE;
 382    if (ioctl(ctlfd, SIOCSIFHWADDR, &ifr) < 0) {
 383        fprintf(stderr, "failed to set MAC address of device `%s': %s\n",
 384                iface, strerror(errno));
 385        ret = EXIT_FAILURE;
 386        goto cleanup;
 387    }
 388
 389    /* add the interface to the bridge */
 390    prep_ifreq(&ifr, bridge);
 391    ifindex = if_nametoindex(iface);
 392#ifndef SIOCBRADDIF
 393    ifargs[0] = BRCTL_ADD_IF;
 394    ifargs[1] = ifindex;
 395    ifargs[2] = 0;
 396    ifargs[3] = 0;
 397    ifr.ifr_data = (void *)ifargs;
 398    ret = ioctl(ctlfd, SIOCDEVPRIVATE, &ifr);
 399#else
 400    ifr.ifr_ifindex = ifindex;
 401    ret = ioctl(ctlfd, SIOCBRADDIF, &ifr);
 402#endif
 403    if (ret == -1) {
 404        fprintf(stderr, "failed to add interface `%s' to bridge `%s': %s\n",
 405                iface, bridge, strerror(errno));
 406        ret = EXIT_FAILURE;
 407        goto cleanup;
 408    }
 409
 410    /* bring the interface up */
 411    prep_ifreq(&ifr, iface);
 412    if (ioctl(ctlfd, SIOCGIFFLAGS, &ifr) == -1) {
 413        fprintf(stderr, "failed to get interface flags for `%s': %s\n",
 414                iface, strerror(errno));
 415        ret = EXIT_FAILURE;
 416        goto cleanup;
 417    }
 418
 419    ifr.ifr_flags |= IFF_UP;
 420    if (ioctl(ctlfd, SIOCSIFFLAGS, &ifr) == -1) {
 421        fprintf(stderr, "failed to bring up interface `%s': %s\n",
 422                iface, strerror(errno));
 423        ret = EXIT_FAILURE;
 424        goto cleanup;
 425    }
 426
 427    /* write fd to the domain socket */
 428    if (send_fd(unixfd, fd) == -1) {
 429        fprintf(stderr, "failed to write fd to unix socket: %s\n",
 430                strerror(errno));
 431        ret = EXIT_FAILURE;
 432        goto cleanup;
 433    }
 434
 435    /* ... */
 436
 437    /* profit! */
 438
 439cleanup:
 440    if (fd >= 0) {
 441        close(fd);
 442    }
 443    if (ctlfd >= 0) {
 444        close(ctlfd);
 445    }
 446    while ((acl_rule = QSIMPLEQ_FIRST(&acl_list)) != NULL) {
 447        QSIMPLEQ_REMOVE_HEAD(&acl_list, entry);
 448        g_free(acl_rule);
 449    }
 450
 451    return ret;
 452}
 453