virt-login-shell.c 10.3 KB
Newer Older
D
Dan Walsh 已提交
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
/*
 * virt-login-shell.c: a shell to connect to a container
 *
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * 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, see
 * <http://www.gnu.org/licenses/>.
 *
 * Daniel Walsh <dwalsh@redhat.com>
 */
#include <config.h>

#include <stdarg.h>
#include <getopt.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <fnmatch.h>
30
#include <locale.h>
D
Dan Walsh 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43

#include "internal.h"
#include "virerror.h"
#include "virconf.h"
#include "virutil.h"
#include "virfile.h"
#include "virprocess.h"
#include "configmake.h"
#include "virstring.h"
#include "viralloc.h"
#include "vircommand.h"
#define VIR_FROM_THIS VIR_FROM_NONE

44 45
static ssize_t nfdlist;
static int *fdlist;
D
Dan Walsh 已提交
46 47
static const char *conf_file = SYSCONFDIR "/libvirt/virt-login-shell.conf";

48
static void virLoginShellFini(virConnectPtr conn, virDomainPtr dom)
D
Dan Walsh 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
{
    size_t i;

    for (i = 0; i < nfdlist; i++)
        VIR_FORCE_CLOSE(fdlist[i]);
    VIR_FREE(fdlist);
    nfdlist = 0;
    if (dom)
        virDomainFree(dom);
    if (conn)
        virConnectClose(conn);
}

static int virLoginShellAllowedUser(virConfPtr conf,
                                    const char *name,
                                    gid_t *groups)
{
    virConfValuePtr p;
    int ret = -1;
    char *ptr = NULL;
    size_t i;
    char *gname = NULL;

    p = virConfGetValue(conf, "allowed_users");
    if (p && p->type == VIR_CONF_LIST) {
        virConfValuePtr pp;

        /* Calc length and check items */
        for (pp = p->list; pp; pp = pp->next) {
            if (pp->type != VIR_CONF_STRING) {
79 80
                virReportSystemError(EINVAL, "%s",
                                     _("shell must be a list of strings"));
D
Dan Walsh 已提交
81 82 83 84 85 86 87 88
                goto cleanup;
            } else {
                /*
                  If string begins with a % this indicates a linux group.
                  Check to see if the user is in the Linux Group.
                */
                if (pp->str[0] == '%') {
                    ptr = &pp->str[1];
89
                    if (!*ptr)
D
Dan Walsh 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
                        continue;
                    for (i = 0; groups[i]; i++) {
                        if (!(gname = virGetGroupName(groups[i])))
                            continue;
                        if (fnmatch(ptr, gname, 0) == 0) {
                            ret = 0;
                            goto cleanup;
                        }
                        VIR_FREE(gname);
                    }
                    continue;
                }
                if (fnmatch(pp->str, name, 0) == 0) {
                    ret = 0;
                    goto cleanup;
                }
            }
        }
    }
109 110 111
    virReportSystemError(EPERM,
                         _("%s not matched against 'allowed_users' in %s"),
                         name, conf_file);
D
Dan Walsh 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
cleanup:
    VIR_FREE(gname);
    return ret;
}

static char **virLoginShellGetShellArgv(virConfPtr conf)
{
    size_t i;
    char **shargv=NULL;
    virConfValuePtr p;

    p = virConfGetValue(conf, "shell");
    if (!p)
        return virStringSplit("/bin/sh -l", " ", 3);

127
    if (p->type == VIR_CONF_LIST) {
D
Dan Walsh 已提交
128 129 130 131 132 133
        size_t len;
        virConfValuePtr pp;

        /* Calc length and check items */
        for (len = 0, pp = p->list; pp; len++, pp = pp->next) {
            if (pp->type != VIR_CONF_STRING) {
134 135
                virReportSystemError(EINVAL, "%s",
                                     _("shell must be a list of strings"));
D
Dan Walsh 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
                goto error;
            }
        }

        if (VIR_ALLOC_N(shargv, len + 1) < 0)
            goto error;
        for (i = 0, pp = p->list; pp; i++, pp = pp->next) {
            if (VIR_STRDUP(shargv[i], pp->str) < 0)
                goto error;
        }
    }
    return shargv;
error:
    virStringFreeList(shargv);
    return NULL;
}

static char *progname;

/*
 * Print usage
 */
static void
usage(void)
{
161 162 163 164 165 166 167 168 169 170
    fprintf(stdout,
            _("\n"
              "Usage:\n"
              "  %s [options]\n\n"
              "Options:\n"
              "  -h | --help            Display program help:\n"
              "  -V | --version         Display program version:\n"
              "\n"
              "libvirt login shell\n"),
            progname);
D
Dan Walsh 已提交
171 172 173
    return;
}

174 175 176 177 178 179 180 181
/* Display version information. */
static void
show_version(void)
{
    printf("%s (%s) %s\n", progname, PACKAGE_NAME, PACKAGE_VERSION);
}


D
Dan Walsh 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
int
main(int argc, char **argv)
{
    virConfPtr conf = NULL;
    const char *login_shell_path = conf_file;
    pid_t cpid;
    int ret = EXIT_FAILURE;
    int status;
    int status2;
    uid_t uid = getuid();
    gid_t gid = getgid();
    char *name = NULL;
    char **shargv = NULL;
    virSecurityModelPtr secmodel = NULL;
    virSecurityLabelPtr seclabel = NULL;
    virDomainPtr dom = NULL;
    virConnectPtr conn = NULL;
    char *homedir = NULL;
    int arg;
    int longindex = -1;
    int ngroups;
    gid_t *groups = NULL;

    struct option opt[] = {
        {"help", no_argument, NULL, 'h'},
207
        {"version", optional_argument, NULL, 'V'},
D
Dan Walsh 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
        {NULL, 0, NULL, 0}
    };
    if (virInitialize() < 0) {
        fprintf(stderr, _("Failed to initialize libvirt Error Handling"));
        return EXIT_FAILURE;
    }

    virSetErrorFunc(NULL, NULL);
    virSetErrorLogPriorityFunc(NULL);

    progname = argv[0];
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
        /* failure to setup locale is not fatal */
    }
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
        perror("bindtextdomain");
        return ret;
    }
    if (!textdomain(PACKAGE)) {
        perror("textdomain");
        return ret;
    }

232
    while ((arg = getopt_long(argc, argv, "hV", opt, &longindex)) != -1) {
D
Dan Walsh 已提交
233 234 235 236
        switch (arg) {
        case 'h':
            usage();
            exit(EXIT_SUCCESS);
237 238 239 240 241 242 243 244 245

        case 'V':
            show_version();
            exit(EXIT_SUCCESS);

        case '?':
        default:
            usage();
            exit(EXIT_FAILURE);
D
Dan Walsh 已提交
246 247 248 249 250 251 252 253 254
        }
    }

    if (argc > optind) {
        virReportSystemError(EINVAL, _("%s takes no options"), progname);
        goto cleanup;
    }

    if (uid == 0) {
255 256
        virReportSystemError(EPERM, _("%s must be run by non root users"),
                             progname);
D
Dan Walsh 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        goto cleanup;
    }

    name = virGetUserName(uid);
    if (!name)
        goto cleanup;

    homedir = virGetUserDirectoryByUID(uid);
    if (!homedir)
        goto cleanup;

    if (!(conf = virConfReadFile(login_shell_path, 0)))
        goto cleanup;

    if ((ngroups = virGetGroupList(uid, gid, &groups)) < 0)
        goto cleanup;

    if (virLoginShellAllowedUser(conf, name, groups) < 0)
        goto cleanup;

    if (!(shargv = virLoginShellGetShellArgv(conf)))
        goto cleanup;

    conn = virConnectOpen("lxc:///");
    if (!conn)
        goto cleanup;

    dom = virDomainLookupByName(conn, name);
    if (!dom)
        goto cleanup;

    if (!virDomainIsActive(dom) && virDomainCreate(dom)) {
        virErrorPtr last_error;
        last_error = virGetLastError();
        if (last_error->code != VIR_ERR_OPERATION_INVALID) {
292 293 294
            virReportSystemError(last_error->code,
                                 _("Can't create %s container: %s"),
                                 name, last_error->message);
D
Dan Walsh 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
            goto cleanup;
        }
    }

    if ((nfdlist = virDomainLxcOpenNamespace(dom, &fdlist, 0)) < 0)
        goto cleanup;
    if (VIR_ALLOC(secmodel) < 0)
        goto cleanup;
    if (VIR_ALLOC(seclabel) < 0)
        goto cleanup;
    if (virNodeGetSecurityModel(conn, secmodel) < 0)
        goto cleanup;
    if (virDomainGetSecurityLabel(dom, seclabel) < 0)
        goto cleanup;

    if (virFork(&cpid) < 0)
        goto cleanup;

    if (cpid == 0) {
        pid_t ccpid;

316 317 318 319 320 321 322 323 324 325 326 327
        int openmax = sysconf(_SC_OPEN_MAX);
        int fd;
        if (openmax < 0) {
            virReportSystemError(errno,  "%s",
                                 _("sysconf(_SC_OPEN_MAX) failed"));
            return EXIT_FAILURE;
        }
        for (fd = 3; fd < openmax; fd++) {
            int tmpfd = fd;
            VIR_MASS_CLOSE(tmpfd);
        }

D
Dan Walsh 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        /* Fork once because we don't want to affect
         * virt-login-shell's namespace itself
         */
        if (virSetUIDGID(0, 0, NULL, 0) < 0)
            return EXIT_FAILURE;

        if (virDomainLxcEnterSecurityLabel(secmodel,
                                           seclabel,
                                           NULL,
                                           0) < 0)
            return EXIT_FAILURE;

        if (nfdlist > 0) {
            if (virDomainLxcEnterNamespace(dom,
                                           nfdlist,
                                           fdlist,
                                           NULL,
                                           NULL,
                                           0) < 0)
                return EXIT_FAILURE;
        }

        ret = virSetUIDGID(uid, gid, groups, ngroups);
        VIR_FREE(groups);
        if (ret < 0)
            return EXIT_FAILURE;

        if (virFork(&ccpid) < 0)
            return EXIT_FAILURE;

        if (ccpid == 0) {
            if (chdir(homedir) < 0) {
360
                virReportSystemError(errno, _("Unable to chdir(%s)"), homedir);
D
Dan Walsh 已提交
361 362 363
                return EXIT_FAILURE;
            }
            if (execv(shargv[0], (char *const*) shargv) < 0) {
364 365
                virReportSystemError(errno, _("Unable to exec shell %s"),
                                     shargv[0]);
366
                return EXIT_FAILURE;
D
Dan Walsh 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
            }
        }
        return virProcessWait(ccpid, &status2);
    }
    ret = virProcessWait(cpid, &status);

cleanup:
    virConfFree(conf);
    virLoginShellFini(conn, dom);
    virStringFreeList(shargv);
    VIR_FREE(name);
    VIR_FREE(homedir);
    VIR_FREE(seclabel);
    VIR_FREE(secmodel);
    VIR_FREE(groups);
    if (ret)
        virDispatchError(NULL);
    return ret;
}