#include <sys/socket.h>
#include <sys/termios.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/contract/process.h>
#include <sys/ctfs.h>
#include <sys/brand.h>
#include <sys/wait.h>
#include <alloca.h>
#include <assert.h>
#include <ctype.h>
#include <paths.h>
#include <door.h>
#include <errno.h>
#include <nss_dbdefs.h>
#include <poll.h>
#include <priv.h>
#include <pwd.h>
#include <unistd.h>
#include <utmpx.h>
#include <sac.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stropts.h>
#include <wait.h>
#include <zone.h>
#include <fcntl.h>
#include <libdevinfo.h>
#include <libintl.h>
#include <locale.h>
#include <libzonecfg.h>
#include <libcontract.h>
#include <libbrand.h>
#include <auth_list.h>
#include <auth_attr.h>
#include <secdb.h>
static int masterfd;
static struct termios save_termios;
static struct termios effective_termios;
static int save_fd;
static struct winsize winsize;
static volatile int dead;
static volatile pid_t child_pid = -1;
static int interactive = 0;
static priv_set_t *dropprivs;
static int nocmdchar = 0;
static int failsafe = 0;
static int disconnect = 0;
static char cmdchar = '~';
static int quiet = 0;
static int pollerr = 0;
static const char *pname;
static char *username;
static boolean_t forced_login = B_FALSE;
#if !defined(TEXT_DOMAIN)
#define TEXT_DOMAIN "SYS_TEST"
#endif
#define SUPATH "/usr/bin/su"
#define FAILSAFESHELL "/sbin/sh"
#define DEFAULTSHELL "/sbin/sh"
#define DEF_PATH "/usr/sbin:/usr/bin"
#define CLUSTER_BRAND_NAME "cluster"
#define ZLOGIN_BUFSIZ 8192
#define ZLOGIN_RDBUFSIZ 1024
#define HI_WATER 8192
#define CANONIFY_LEN 5
static void
usage(void)
{
(void) fprintf(stderr, gettext("usage: %s [ -dnQCES ] [ -e cmdchar ] "
"[-l user] zonename [command [args ...] ]\n"), pname);
exit(2);
}
static const char *
getpname(const char *arg0)
{
const char *p = strrchr(arg0, '/');
if (p == NULL)
p = arg0;
else
p++;
pname = p;
return (p);
}
static void
zerror(const char *fmt, ...)
{
va_list alist;
(void) fprintf(stderr, "%s: ", pname);
va_start(alist, fmt);
(void) vfprintf(stderr, fmt, alist);
va_end(alist);
(void) fprintf(stderr, "\n");
}
static void
zperror(const char *str)
{
const char *estr;
if ((estr = strerror(errno)) != NULL)
(void) fprintf(stderr, "%s: %s: %s\n", pname, str, estr);
else
(void) fprintf(stderr, "%s: %s: errno %d\n", pname, str, errno);
}
static int
prefork_dropprivs()
{
if ((dropprivs = priv_allocset()) == NULL)
return (1);
priv_basicset(dropprivs);
(void) priv_delset(dropprivs, PRIV_PROC_INFO);
(void) priv_delset(dropprivs, PRIV_PROC_FORK);
(void) priv_delset(dropprivs, PRIV_PROC_EXEC);
(void) priv_delset(dropprivs, PRIV_FILE_LINK_ANY);
if (interactive == 0) {
(void) priv_addset(dropprivs, PRIV_PROC_ZONE);
(void) priv_addset(dropprivs, PRIV_PROC_OWNER);
} else {
(void) priv_delset(dropprivs, PRIV_PROC_SESSION);
}
return (0);
}
static void
postfork_dropprivs()
{
if ((setppriv(PRIV_SET, PRIV_PERMITTED, dropprivs)) == -1) {
zperror(gettext("Warning: could not set permitted privileges"));
}
if ((setppriv(PRIV_SET, PRIV_LIMIT, dropprivs)) == -1) {
zperror(gettext("Warning: could not set limit privileges"));
}
if ((setppriv(PRIV_SET, PRIV_INHERITABLE, dropprivs)) == -1) {
zperror(gettext("Warning: could not set inheritable "
"privileges"));
}
}
static int
get_console_master(const char *zname)
{
int sockfd = -1;
struct sockaddr_un servaddr;
char clientid[MAXPATHLEN];
char handshake[MAXPATHLEN], c;
int msglen;
int i = 0, err = 0;
if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
zperror(gettext("could not create socket"));
return (-1);
}
bzero(&servaddr, sizeof (servaddr));
servaddr.sun_family = AF_UNIX;
(void) snprintf(servaddr.sun_path, sizeof (servaddr.sun_path),
"%s/%s.console_sock", ZONES_TMPDIR, zname);
if (connect(sockfd, (struct sockaddr *)&servaddr,
sizeof (servaddr)) == -1) {
zperror(gettext("Could not connect to zone console"));
goto bad;
}
masterfd = sockfd;
msglen = snprintf(clientid, sizeof (clientid), "IDENT %lu %s %d\n",
getpid(), setlocale(LC_MESSAGES, NULL), disconnect);
if (msglen >= sizeof (clientid) || msglen < 0) {
zerror("protocol error");
goto bad;
}
if (write(masterfd, clientid, msglen) != msglen) {
zerror("protocol error");
goto bad;
}
bzero(handshake, sizeof (handshake));
while ((err = read(masterfd, &c, 1)) == 1) {
if (i >= (sizeof (handshake) - 1))
break;
if (c == '\n')
break;
handshake[i] = c;
i++;
}
if (err == -1) {
zperror(gettext("Could not connect to zone console"));
goto bad;
}
if (strncmp(handshake, "OK", sizeof (handshake)) == 0)
return (0);
zerror(gettext("Console is already in use by process ID %s."),
handshake);
bad:
(void) close(sockfd);
masterfd = -1;
return (-1);
}
static int
get_master_pty()
{
if ((masterfd = open("/dev/ptmx", O_RDWR|O_NONBLOCK)) < 0) {
zperror(gettext("failed to obtain a pseudo-tty"));
return (-1);
}
if (tcgetattr(STDIN_FILENO, &save_termios) == -1) {
zperror(gettext("failed to get terminal settings from stdin"));
return (-1);
}
(void) ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&winsize);
return (0);
}
static int
init_slave_pty(zoneid_t zoneid, char *devroot)
{
int slavefd = -1;
char *slavename, zoneslavename[MAXPATHLEN];
if (grantpt(masterfd) != 0) {
zperror(gettext("grantpt failed"));
return (-1);
}
if (unlockpt(masterfd) != 0) {
zperror(gettext("unlockpt failed"));
return (-1);
}
if ((slavename = ptsname(masterfd)) == NULL) {
zperror(gettext("failed to get name for pseudo-tty"));
return (-1);
}
(void) snprintf(zoneslavename, sizeof (zoneslavename), "%s%s",
devroot, slavename);
if ((slavefd = open(zoneslavename, O_RDWR)) < 0) {
zerror(gettext("failed to open %s: %s"), zoneslavename,
strerror(errno));
return (-1);
}
if (ioctl(slavefd, I_PUSH, "ptem") == -1) {
zperror(gettext("failed to push ptem module"));
if (!failsafe)
goto bad;
}
if (ioctl(slavefd, I_ANCHOR) == -1) {
zperror(gettext("failed to set stream anchor"));
if (!failsafe)
goto bad;
}
if (ioctl(slavefd, I_PUSH, "ldterm") == -1) {
zperror(gettext("failed to push ldterm module"));
if (!failsafe)
goto bad;
}
if (ioctl(slavefd, I_PUSH, "ttcompat") == -1) {
zperror(gettext("failed to push ttcompat module"));
if (!failsafe)
goto bad;
}
if (tcsetattr(slavefd, TCSAFLUSH, &save_termios) == -1) {
zperror(gettext("failed to set terminal settings"));
if (!failsafe)
goto bad;
}
(void) ioctl(slavefd, TIOCSWINSZ, (char *)&winsize);
if (zonept(masterfd, zoneid) != 0) {
zperror(gettext("could not set zoneid of pty"));
goto bad;
}
return (slavefd);
bad:
(void) close(slavefd);
return (-1);
}
static int
set_tty_rawmode(int fd)
{
struct termios term;
if (tcgetattr(fd, &term) < 0) {
zperror(gettext("failed to get user terminal settings"));
return (-1);
}
save_termios = term;
save_fd = fd;
term.c_iflag &= ~(ISTRIP|IXON|IXANY);
term.c_iflag &= ~(INLCR|ICRNL|IGNCR|IUCLC);
term.c_oflag &= ~OPOST;
term.c_lflag &= ~(ICANON|ISIG|ECHO|IEXTEN);
term.c_cc[VMIN] = 1;
term.c_cc[VTIME] = 0;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &term)) {
zperror(gettext("failed to set user terminal to raw mode"));
return (-1);
}
if (tcgetattr(STDIN_FILENO, &effective_termios) < 0) {
zperror(gettext("failed to get user terminal settings"));
return (-1);
}
effective_termios.c_cc[VEOF] = save_termios.c_cc[VEOF];
effective_termios.c_cc[VEOL] = save_termios.c_cc[VEOL];
return (0);
}
static void
sigwinch(int s)
{
struct winsize ws;
if (ioctl(0, TIOCGWINSZ, &ws) == 0)
(void) ioctl(masterfd, TIOCSWINSZ, &ws);
}
static volatile int close_on_sig = -1;
static void
sigcld(int s)
{
int status;
pid_t pid;
if ((pid = waitpid(child_pid, &status, WNOHANG|WNOWAIT)) != -1) {
if (pid == child_pid &&
(WIFEXITED(status) || WIFSIGNALED(status))) {
dead = 1;
if (close_on_sig != -1) {
(void) write(close_on_sig, "a", 1);
(void) close(close_on_sig);
close_on_sig = -1;
}
} else {
(void) waitpid(pid, &status, WNOHANG);
}
}
}
static void
sig_forward(int s)
{
if (child_pid != -1) {
(void) sigsend(P_PGID, child_pid, s);
}
}
static void
reset_tty()
{
(void) tcsetattr(save_fd, TCSADRAIN, &save_termios);
}
static void
canonify(char c, char *cc)
{
if (isprint(c)) {
cc[0] = c;
cc[1] = '\0';
} else if (c >= 0 && c <= 31) {
cc[0] = '^';
cc[1] = c + '@';
cc[2] = '\0';
} else {
cc[0] = '\\';
cc[1] = ((c >> 6) & 7) + '0';
cc[2] = ((c >> 3) & 7) + '0';
cc[3] = (c & 7) + '0';
cc[4] = '\0';
}
}
static int
process_user_input(int outfd, int infd)
{
static boolean_t beginning_of_line = B_TRUE;
static boolean_t local_echo = B_FALSE;
char ibuf[ZLOGIN_BUFSIZ];
int nbytes;
char *buf = ibuf;
nbytes = read(STDIN_FILENO, ibuf, ZLOGIN_RDBUFSIZ);
if (nbytes == -1 && (errno != EINTR || dead))
return (-1);
if (nbytes == -1)
return (0);
if (nbytes == 0)
return (1);
for (char c = *buf; nbytes > 0; c = *buf, --nbytes) {
buf++;
if (beginning_of_line && !nocmdchar) {
beginning_of_line = B_FALSE;
if (c == cmdchar) {
local_echo = B_TRUE;
continue;
}
} else if (local_echo) {
local_echo = B_FALSE;
if (c == '.' || c == effective_termios.c_cc[VEOF]) {
char cc[CANONIFY_LEN];
canonify(c, cc);
(void) write(STDOUT_FILENO, &cmdchar, 1);
(void) write(STDOUT_FILENO, cc, strlen(cc));
return (-1);
}
}
retry:
if (write(outfd, &c, 1) <= 0) {
if (errno == EAGAIN) {
struct timespec rqtp;
int ln;
char obuf[ZLOGIN_BUFSIZ];
if ((ln = read(infd, obuf, ZLOGIN_BUFSIZ)) > 0)
(void) write(STDOUT_FILENO, obuf, ln);
rqtp.tv_sec = 0;
rqtp.tv_nsec = MSEC2NSEC(10);
(void) nanosleep(&rqtp, NULL);
if (!dead)
goto retry;
}
return (-1);
}
beginning_of_line = (c == '\r' || c == '\n' ||
c == effective_termios.c_cc[VKILL] ||
c == effective_termios.c_cc[VEOL] ||
c == effective_termios.c_cc[VSUSP] ||
c == effective_termios.c_cc[VINTR]);
}
return (0);
}
static int
process_raw_input(int stdin_fd, int appin_fd)
{
int cc;
struct stat64 sb;
char ibuf[ZLOGIN_RDBUFSIZ];
if (fstat64(appin_fd, &sb) == -1) {
perror("stat failed");
return (-1);
}
if (dead)
return (-1);
if (sb.st_size >= HI_WATER)
return (0);
cc = read(STDIN_FILENO, ibuf, ZLOGIN_RDBUFSIZ);
if (cc == -1 && (errno != EINTR || dead))
return (-1);
if (cc == -1)
return (0);
if (cc == 0)
return (1);
if (write(stdin_fd, ibuf, cc) == -1)
return (-1);
return (0);
}
static int
process_output(int in_fd, int out_fd)
{
int wrote = 0;
int cc;
char ibuf[ZLOGIN_BUFSIZ];
cc = read(in_fd, ibuf, ZLOGIN_BUFSIZ);
if (cc == -1 && (errno != EINTR || dead))
return (-1);
if (cc == 0)
return (-1);
if (cc == -1)
return (0);
do {
int len;
len = write(out_fd, ibuf + wrote, cc - wrote);
if (len == -1 && errno != EINTR)
return (-1);
if (len != -1)
wrote += len;
} while (wrote < cc);
return (0);
}
static void
doio(int stdin_fd, int appin_fd, int stdout_fd, int stderr_fd, int sig_fd,
boolean_t raw_mode)
{
struct pollfd pollfds[4];
char ibuf[ZLOGIN_BUFSIZ];
int cc, ret;
pollfds[0].fd = stdout_fd;
pollfds[0].events = POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI;
pollfds[1].fd = stderr_fd;
pollfds[1].events = pollfds[0].events;
pollfds[2].fd = STDIN_FILENO;
pollfds[2].events = pollfds[0].events;
pollfds[3].fd = sig_fd;
pollfds[3].events = pollfds[0].events;
for (;;) {
pollfds[0].revents = pollfds[1].revents =
pollfds[2].revents = pollfds[3].revents = 0;
if (dead)
break;
ret = poll(pollfds,
sizeof (pollfds) / sizeof (struct pollfd), -1);
if (ret == -1 && errno != EINTR) {
perror("poll failed");
break;
}
if (errno == EINTR && dead) {
break;
}
if (pollfds[0].revents) {
if (pollfds[0].revents &
(POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) {
if (process_output(stdout_fd, STDOUT_FILENO)
!= 0)
break;
} else {
pollerr = pollfds[0].revents;
break;
}
}
if (pollfds[1].revents) {
if (pollfds[1].revents &
(POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) {
if (process_output(stderr_fd, STDERR_FILENO)
!= 0)
break;
} else {
pollerr = pollfds[1].revents;
break;
}
}
if (pollfds[2].revents) {
if (pollfds[2].revents &
(POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) {
int res;
if (raw_mode)
res = process_raw_input(stdin_fd,
appin_fd);
else
res = process_user_input(stdin_fd,
stdout_fd);
if (res < 0)
break;
if (res > 0) {
pollfds[2].fd = -1;
while ((res = close(stdin_fd)) != 0 &&
errno == EINTR)
;
if (res != 0)
break;
}
} else if (raw_mode && pollfds[2].revents & POLLHUP) {
int res;
pollfds[2].fd = -1;
while ((res = close(stdin_fd)) != 0 &&
errno == EINTR)
;
if (res != 0)
break;
} else {
pollerr = pollfds[2].revents;
break;
}
}
}
retry:
pollfds[0].revents = pollfds[1].revents = 0;
(void) poll(pollfds, 2, 100);
if (pollfds[0].revents &
(POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) {
if ((cc = read(stdout_fd, ibuf, ZLOGIN_BUFSIZ)) > 0) {
(void) write(STDOUT_FILENO, ibuf, cc);
goto retry;
}
}
if (pollfds[1].revents &
(POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) {
if ((cc = read(stderr_fd, ibuf, ZLOGIN_BUFSIZ)) > 0) {
(void) write(STDERR_FILENO, ibuf, cc);
goto retry;
}
}
}
static const char *
zone_get_user_cmd(brand_handle_t bh, const char *login, char *user_cmd,
size_t len)
{
bzero(user_cmd, sizeof (user_cmd));
if (brand_get_user_cmd(bh, login, user_cmd, len) != 0)
return (NULL);
return (user_cmd);
}
extern int str2passwd(const char *, int, void *, char *, int);
static struct passwd *
zone_get_user_pw(const char *user_cmd, struct passwd *pwent, char *pwbuf,
int pwbuflen)
{
char pwline[NSS_BUFLEN_PASSWD];
char *cin = NULL;
FILE *fin;
int status;
assert(getzoneid() != GLOBAL_ZONEID);
if ((fin = popen(user_cmd, "r")) == NULL)
return (NULL);
while (cin == NULL && !feof(fin))
cin = fgets(pwline, sizeof (pwline), fin);
if (cin == NULL) {
(void) pclose(fin);
return (NULL);
}
status = pclose(fin);
if (!WIFEXITED(status))
return (NULL);
if (WEXITSTATUS(status) != 0)
return (NULL);
if (str2passwd(pwline, sizeof (pwline), pwent, pwbuf, pwbuflen) == 0)
return (pwent);
else
return (NULL);
}
static char **
zone_login_cmd(brand_handle_t bh, const char *login)
{
static char result_buf[ARG_MAX];
char **new_argv, *ptr, *lasts;
int n, a;
bzero(result_buf, sizeof (result_buf));
if (forced_login) {
if (brand_get_forcedlogin_cmd(bh, login,
result_buf, sizeof (result_buf)) != 0)
return (NULL);
} else {
if (brand_get_login_cmd(bh, login,
result_buf, sizeof (result_buf)) != 0)
return (NULL);
}
if (strstr(result_buf, " ") != NULL)
return (NULL);
n = strlen(result_buf);
if (result_buf[n - 1] == ' ')
result_buf[n - 1] = '\0';
ptr = result_buf;
for (n = 2; ((ptr = strchr(ptr + 1, (int)' ')) != NULL); n++)
;
if ((new_argv = malloc(sizeof (char *) * n)) == NULL)
return (NULL);
a = 0;
new_argv[a++] = result_buf;
if (n > 2) {
(void) strtok_r(result_buf, " ", &lasts);
while ((new_argv[a++] = strtok_r(NULL, " ", &lasts)) != NULL)
;
} else {
new_argv[a++] = NULL;
}
assert(n == a);
return (new_argv);
}
static char **
prep_args(brand_handle_t bh, const char *login, char **argv)
{
int argc = 0, a = 0, i, n = -1;
char **new_argv;
if (argv != NULL) {
size_t subshell_len = 1;
char *subshell;
while (argv[argc] != NULL)
argc++;
for (i = 0; i < argc; i++) {
subshell_len += strlen(argv[i]) + 1;
}
if ((subshell = calloc(1, subshell_len)) == NULL)
return (NULL);
for (i = 0; i < argc; i++) {
(void) strcat(subshell, argv[i]);
(void) strcat(subshell, " ");
}
if (failsafe) {
n = 4;
if ((new_argv = malloc(sizeof (char *) * n)) == NULL)
return (NULL);
new_argv[a++] = FAILSAFESHELL;
} else {
n = 5;
if ((new_argv = malloc(sizeof (char *) * n)) == NULL)
return (NULL);
new_argv[a++] = SUPATH;
if (strcmp(login, "root") != 0) {
new_argv[a++] = "-";
n++;
}
new_argv[a++] = (char *)login;
}
new_argv[a++] = "-c";
new_argv[a++] = subshell;
new_argv[a++] = NULL;
assert(a == n);
} else {
if (failsafe) {
n = 2;
if ((new_argv = malloc(sizeof (char *) * n)) == NULL)
return (NULL);
new_argv[a++] = FAILSAFESHELL;
new_argv[a++] = NULL;
assert(n == a);
} else {
new_argv = zone_login_cmd(bh, login);
}
}
return (new_argv);
}
static char *
add_env(char *name, char *value)
{
size_t sz = strlen(name) + strlen(value) + 2;
char *str;
if ((str = malloc(sz)) == NULL)
return (NULL);
(void) snprintf(str, sz, "%s=%s", name, value);
return (str);
}
static char **
prep_env()
{
int e = 0, size = 1;
char **new_env, *estr;
char *term = getenv("TERM");
size++;
if (term != NULL)
size++;
if (failsafe)
size += 2;
if ((new_env = malloc(sizeof (char *) * size)) == NULL)
return (NULL);
if ((estr = add_env("PATH", DEF_PATH)) == NULL)
return (NULL);
new_env[e++] = estr;
if (term != NULL) {
if ((estr = add_env("TERM", term)) == NULL)
return (NULL);
new_env[e++] = estr;
}
if (failsafe) {
if ((estr = add_env("HOME", "/")) == NULL)
return (NULL);
new_env[e++] = estr;
if ((estr = add_env("SHELL", FAILSAFESHELL)) == NULL)
return (NULL);
new_env[e++] = estr;
}
new_env[e++] = NULL;
assert(e == size);
return (new_env);
}
static char **
prep_env_noninteractive(const char *user_cmd, char **env)
{
size_t size;
char **new_env;
int e, i;
char *estr;
char varmail[LOGNAME_MAX + 11];
char pwbuf[NSS_BUFLEN_PASSWD + 1];
struct passwd pwent;
struct passwd *pw = NULL;
assert(env != NULL);
assert(failsafe == 0);
pw = zone_get_user_pw(user_cmd, &pwent, pwbuf, sizeof (pwbuf));
for (size = 0; env[size] != NULL; size++)
;
e = size;
if (pw != NULL)
size += 3;
else
size += 1;
size++;
size++;
if ((new_env = malloc(sizeof (char *) * size)) == NULL)
goto malloc_fail;
for (i = 0; env[i] != NULL; i++) {
if ((new_env[i] = strdup(env[i])) == NULL)
goto malloc_fail;
}
assert(e == i);
if (pw != NULL) {
if ((estr = add_env("LOGNAME", pw->pw_name)) == NULL)
goto malloc_fail;
new_env[e++] = estr;
if ((estr = add_env("HOME", pw->pw_dir)) == NULL)
goto malloc_fail;
new_env[e++] = estr;
if (chdir(pw->pw_dir) != 0)
zerror(gettext("Could not chdir to home directory "
"%s: %s"), pw->pw_dir, strerror(errno));
(void) snprintf(varmail, sizeof (varmail), "/var/mail/%s",
pw->pw_name);
if ((estr = add_env("MAIL", varmail)) == NULL)
goto malloc_fail;
new_env[e++] = estr;
} else {
if ((estr = add_env("HOME", "/")) == NULL)
goto malloc_fail;
new_env[e++] = estr;
}
if (pw != NULL && strlen(pw->pw_shell) > 0) {
if ((estr = add_env("SHELL", pw->pw_shell)) == NULL)
goto malloc_fail;
new_env[e++] = estr;
} else {
if ((estr = add_env("SHELL", DEFAULTSHELL)) == NULL)
goto malloc_fail;
new_env[e++] = estr;
}
new_env[e++] = NULL;
assert(e == size);
return (new_env);
malloc_fail:
zperror(gettext("failed to allocate memory for process environment"));
return (NULL);
}
static int
close_func(void *slavefd, int fd)
{
if (fd != *(int *)slavefd)
(void) close(fd);
return (0);
}
static void
set_cmdchar(char *cmdcharstr)
{
char c;
long lc;
if ((c = *cmdcharstr) != '\\') {
cmdchar = c;
return;
}
c = cmdcharstr[1];
if (c == '\0' || c == '\\') {
cmdchar = '\\';
return;
}
if (c < '0' || c > '7') {
zerror(gettext("Unrecognized escape character option %s"),
cmdcharstr);
usage();
}
lc = strtol(cmdcharstr + 1, NULL, 8);
if (lc < 0 || lc > 255) {
zerror(gettext("Octal escape character '%s' too large"),
cmdcharstr);
usage();
}
cmdchar = (char)lc;
}
static int
setup_utmpx(char *slavename)
{
struct utmpx ut;
bzero(&ut, sizeof (ut));
(void) strncpy(ut.ut_user, ".zlogin", sizeof (ut.ut_user));
(void) strncpy(ut.ut_line, slavename, sizeof (ut.ut_line));
ut.ut_pid = getpid();
ut.ut_id[0] = 'z';
ut.ut_id[1] = ut.ut_id[2] = ut.ut_id[3] = (char)SC_WILDC;
ut.ut_type = LOGIN_PROCESS;
(void) time(&ut.ut_tv.tv_sec);
if (makeutx(&ut) == NULL) {
zerror(gettext("makeutx failed"));
return (-1);
}
return (0);
}
static void
release_lock_file(int lockfd)
{
(void) close(lockfd);
}
static int
grab_lock_file(const char *zone_name, int *lockfd)
{
char pathbuf[PATH_MAX];
struct flock flock;
if (mkdir(ZONES_TMPDIR, S_IRWXU) < 0 && errno != EEXIST) {
zerror(gettext("could not mkdir %s: %s"), ZONES_TMPDIR,
strerror(errno));
return (-1);
}
(void) chmod(ZONES_TMPDIR, S_IRWXU);
(void) snprintf(pathbuf, sizeof (pathbuf), "%s/%s.zoneadm.lock",
ZONES_TMPDIR, zone_name);
if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
zerror(gettext("could not open %s: %s"), pathbuf,
strerror(errno));
return (-1);
}
flock.l_type = F_WRLCK;
flock.l_whence = SEEK_SET;
flock.l_start = (off_t)0;
flock.l_len = (off_t)0;
if (fcntl(*lockfd, F_SETLKW, &flock) < 0) {
zerror(gettext("unable to lock %s: %s"), pathbuf,
strerror(errno));
release_lock_file(*lockfd);
return (-1);
}
return (Z_OK);
}
static int
start_zoneadmd(const char *zone_name)
{
pid_t retval;
int pstatus = 0, error = -1, lockfd, doorfd;
struct door_info info;
char doorpath[MAXPATHLEN];
(void) snprintf(doorpath, sizeof (doorpath), ZONE_DOOR_PATH, zone_name);
if (grab_lock_file(zone_name, &lockfd) != Z_OK)
return (-1);
if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
if (errno != ENOENT) {
zerror("failed to open %s: %s", doorpath,
strerror(errno));
goto out;
}
} else {
if (door_info(doorfd, &info) == 0 &&
((info.di_attributes & DOOR_REVOKED) == 0)) {
error = 0;
goto out;
}
}
if ((child_pid = fork()) == -1) {
zperror(gettext("could not fork"));
goto out;
} else if (child_pid == 0) {
(void) execl("/usr/lib/zones/zoneadmd", "zoneadmd", "-z",
zone_name, NULL);
zperror(gettext("could not exec zoneadmd"));
_exit(1);
}
do {
retval = waitpid(child_pid, &pstatus, 0);
} while (retval != child_pid);
if (WIFSIGNALED(pstatus) ||
(WIFEXITED(pstatus) && WEXITSTATUS(pstatus) != 0)) {
zerror(gettext("could not start %s"), "zoneadmd");
goto out;
}
error = 0;
out:
release_lock_file(lockfd);
(void) close(doorfd);
return (error);
}
static int
init_template(void)
{
int fd;
int err = 0;
fd = open64(CTFS_ROOT "/process/template", O_RDWR);
if (fd == -1)
return (-1);
err |= ct_tmpl_set_critical(fd, 0);
err |= ct_tmpl_set_informative(fd, 0);
err |= ct_pr_tmpl_set_fatal(fd, CT_PR_EV_HWERR);
err |= ct_pr_tmpl_set_param(fd, CT_PR_PGRPONLY | CT_PR_REGENT);
if (err || ct_tmpl_activate(fd)) {
(void) close(fd);
return (-1);
}
return (fd);
}
static int
noninteractive_login(char *zonename, const char *user_cmd, zoneid_t zoneid,
char **new_args, char **new_env)
{
pid_t retval;
int stdin_pipe[2], stdout_pipe[2], stderr_pipe[2], dead_child_pipe[2];
int child_status;
int tmpl_fd;
sigset_t block_cld;
if ((tmpl_fd = init_template()) == -1) {
reset_tty();
zperror(gettext("could not create contract"));
return (1);
}
if (pipe(stdin_pipe) != 0) {
zperror(gettext("could not create STDIN pipe"));
return (1);
}
if (ioctl(stdin_pipe[0], I_SWROPT, SNDZERO) != 0) {
zperror(gettext("could not configure STDIN pipe"));
return (1);
}
if (pipe(stdout_pipe) != 0) {
zperror(gettext("could not create STDOUT pipe"));
return (1);
}
if (pipe(stderr_pipe) != 0) {
zperror(gettext("could not create STDERR pipe"));
return (1);
}
if (pipe(dead_child_pipe) != 0) {
zperror(gettext("could not create signalling pipe"));
return (1);
}
close_on_sig = dead_child_pipe[0];
if (stdin_pipe[0] <= STDERR_FILENO ||
stdin_pipe[1] <= STDERR_FILENO ||
stdout_pipe[0] <= STDERR_FILENO ||
stdout_pipe[1] <= STDERR_FILENO ||
stderr_pipe[0] <= STDERR_FILENO ||
stderr_pipe[1] <= STDERR_FILENO ||
dead_child_pipe[0] <= STDERR_FILENO ||
dead_child_pipe[1] <= STDERR_FILENO) {
zperror(gettext("process lacks valid STDIN, STDOUT, STDERR"));
return (1);
}
if (prefork_dropprivs() != 0) {
zperror(gettext("could not allocate privilege set"));
return (1);
}
(void) sigset(SIGCLD, sigcld);
(void) sigemptyset(&block_cld);
(void) sigaddset(&block_cld, SIGCLD);
(void) sigprocmask(SIG_BLOCK, &block_cld, NULL);
if ((child_pid = fork()) == -1) {
(void) ct_tmpl_clear(tmpl_fd);
(void) close(tmpl_fd);
zperror(gettext("could not fork"));
return (1);
} else if (child_pid == 0) {
(void) ct_tmpl_clear(tmpl_fd);
(void) close(STDIN_FILENO);
(void) close(STDOUT_FILENO);
(void) close(STDERR_FILENO);
(void) dup2(stdin_pipe[1], STDIN_FILENO);
(void) dup2(stdout_pipe[1], STDOUT_FILENO);
(void) dup2(stderr_pipe[1], STDERR_FILENO);
(void) closefrom(STDERR_FILENO + 1);
(void) sigset(SIGCLD, SIG_DFL);
(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
(void) ioctl(STDIN_FILENO, I_ANCHOR);
(void) ioctl(STDOUT_FILENO, I_ANCHOR);
(void) ioctl(STDERR_FILENO, I_ANCHOR);
if (zone_enter(zoneid) == -1) {
zerror(gettext("could not enter zone %s: %s"),
zonename, strerror(errno));
_exit(1);
}
if (access("/.SUNWnative/usr/lib/locale", R_OK) == 0)
(void) bindtextdomain(TEXT_DOMAIN,
"/.SUNWnative/usr/lib/locale");
else if (access("/native/usr/lib/locale", R_OK) == 0)
(void) bindtextdomain(TEXT_DOMAIN,
"/native/usr/lib/locale");
if (!failsafe)
new_env = prep_env_noninteractive(user_cmd, new_env);
if (new_env == NULL) {
_exit(1);
}
(void) setpgid(getpid(), getpid());
if (setuid(0) == -1) {
zperror(gettext("insufficient privilege"));
return (1);
}
(void) execve(new_args[0], new_args, new_env);
zperror(gettext("exec failure"));
_exit(1);
}
(void) close(stdout_pipe[1]);
(void) close(stderr_pipe[1]);
(void) sigset(SIGINT, sig_forward);
postfork_dropprivs();
(void) ct_tmpl_clear(tmpl_fd);
(void) close(tmpl_fd);
(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
doio(stdin_pipe[0], stdin_pipe[1], stdout_pipe[0], stderr_pipe[0],
dead_child_pipe[1], B_TRUE);
do {
retval = waitpid(child_pid, &child_status, 0);
if (retval == -1) {
child_status = 0;
}
} while (retval != child_pid && errno != ECHILD);
return (WEXITSTATUS(child_status));
}
static char *
get_username()
{
uid_t uid;
struct passwd *nptr;
uid = getuid();
if ((nptr = getpwuid(uid)) == NULL) {
zerror(gettext("could not get user name."));
_exit(1);
}
return (nptr->pw_name);
}
int
main(int argc, char **argv)
{
int arg, console = 0;
zoneid_t zoneid;
zone_state_t st;
char *login = "root";
int lflag = 0;
int nflag = 0;
char *zonename = NULL;
char **proc_args = NULL;
char **new_args, **new_env;
sigset_t block_cld;
char devroot[MAXPATHLEN];
char *slavename, slaveshortname[MAXPATHLEN];
priv_set_t *privset;
int tmpl_fd;
char zonebrand[MAXNAMELEN];
char default_brand[MAXNAMELEN];
struct stat sb;
char kernzone[ZONENAME_MAX];
brand_handle_t bh;
char user_cmd[MAXPATHLEN];
char authname[MAXAUTHS];
(void) setlocale(LC_ALL, "");
(void) textdomain(TEXT_DOMAIN);
(void) getpname(argv[0]);
username = get_username();
while ((arg = getopt(argc, argv, "dnECR:Se:l:Q")) != EOF) {
switch (arg) {
case 'C':
console = 1;
break;
case 'E':
nocmdchar = 1;
break;
case 'R':
if (*optarg != '/') {
zerror(gettext("root path must be absolute."));
exit(2);
}
if (stat(optarg, &sb) == -1 || !S_ISDIR(sb.st_mode)) {
zerror(
gettext("root path must be a directory."));
exit(2);
}
zonecfg_set_root(optarg);
break;
case 'Q':
quiet = 1;
break;
case 'S':
failsafe = 1;
break;
case 'd':
disconnect = 1;
break;
case 'e':
set_cmdchar(optarg);
break;
case 'l':
login = optarg;
lflag = 1;
break;
case 'n':
nflag = 1;
break;
default:
usage();
}
}
if (console != 0) {
if (lflag != 0) {
zerror(gettext(
"-l may not be specified for console login"));
usage();
}
if (nflag != 0) {
zerror(gettext(
"-n may not be specified for console login"));
usage();
}
if (failsafe != 0) {
zerror(gettext(
"-S may not be specified for console login"));
usage();
}
if (zonecfg_in_alt_root()) {
zerror(gettext(
"-R may not be specified for console login"));
exit(2);
}
}
if (failsafe != 0 && lflag != 0) {
zerror(gettext("-l may not be specified for failsafe login"));
usage();
}
if (!console && disconnect != 0) {
zerror(gettext(
"-d may only be specified with console login"));
usage();
}
if (optind == (argc - 1)) {
if (nflag != 0) {
zerror(gettext(
"-n may not be specified for interactive login"));
usage();
}
if (isatty(STDIN_FILENO))
interactive = 1;
zonename = argv[optind];
} else if (optind < (argc - 1)) {
if (console) {
zerror(gettext("Commands may not be specified for "
"console login."));
usage();
}
zonename = argv[optind];
proc_args = &argv[optind + 1];
interactive = 0;
} else {
usage();
}
if (getzoneid() != GLOBAL_ZONEID) {
zerror(gettext("'%s' may only be used from the global zone"),
pname);
return (1);
}
if (strcmp(zonename, GLOBAL_ZONENAME) == 0) {
zerror(gettext("'%s' not applicable to the global zone"),
pname);
return (1);
}
if (zone_get_state(zonename, &st) != Z_OK) {
zerror(gettext("zone '%s' unknown"), zonename);
return (1);
}
if (st < ZONE_STATE_INSTALLED) {
zerror(gettext("cannot login to a zone which is '%s'"),
zone_state_str(st));
return (1);
}
if ((privset = priv_allocset()) == NULL) {
zperror(gettext("priv_allocset failed"));
return (1);
}
if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
zperror(gettext("getppriv failed"));
priv_freeset(privset);
return (1);
}
if (priv_isfullset(privset) == B_FALSE) {
zerror(gettext("You lack sufficient privilege to run "
"this command (all privs required)"));
priv_freeset(privset);
return (1);
}
priv_freeset(privset);
(void) snprintf(authname, MAXAUTHS, "%s%s%s",
ZONE_MANAGE_AUTH, KV_OBJECT, zonename);
if (chkauthattr(authname, username) == 0) {
if (console) {
zerror(gettext("%s is not authorized for console "
"access to %s zone."),
username, zonename);
return (1);
} else {
(void) snprintf(authname, MAXAUTHS, "%s%s%s",
ZONE_LOGIN_AUTH, KV_OBJECT, zonename);
if (failsafe || !interactive) {
zerror(gettext("%s is not authorized for "
"failsafe or non-interactive login "
"to %s zone."), username, zonename);
return (1);
} else if (chkauthattr(authname, username) == 0) {
zerror(gettext("%s is not authorized "
" to login to %s zone."),
username, zonename);
return (1);
}
}
} else {
forced_login = B_TRUE;
}
if (console) {
if (start_zoneadmd(zonename) == -1)
return (1);
if (get_console_master(zonename) == -1)
return (1);
if (!quiet)
(void) printf(
gettext("[Connected to zone '%s' console]\n"),
zonename);
if (set_tty_rawmode(STDIN_FILENO) == -1) {
reset_tty();
zperror(gettext("failed to set stdin pty to raw mode"));
return (1);
}
(void) sigset(SIGWINCH, sigwinch);
(void) sigwinch(0);
doio(masterfd, -1, masterfd, -1, -1, B_FALSE);
reset_tty();
if (!quiet)
(void) printf(
gettext("\n[Connection to zone '%s' console "
"closed]\n"), zonename);
return (0);
}
if (st != ZONE_STATE_RUNNING && st != ZONE_STATE_MOUNTED) {
zerror(gettext("login allowed only to running zones "
"(%s is '%s')."), zonename, zone_state_str(st));
return (1);
}
(void) strlcpy(kernzone, zonename, sizeof (kernzone));
if (zonecfg_in_alt_root()) {
FILE *fp = zonecfg_open_scratch("", B_FALSE);
if (fp == NULL || zonecfg_find_scratch(fp, zonename,
zonecfg_get_root(), kernzone, sizeof (kernzone)) == -1) {
zerror(gettext("cannot find scratch zone %s"),
zonename);
if (fp != NULL)
zonecfg_close_scratch(fp);
return (1);
}
zonecfg_close_scratch(fp);
}
if ((zoneid = getzoneidbyname(kernzone)) == -1) {
zerror(gettext("failed to get zoneid for zone '%s'"),
zonename);
return (1);
}
if (zone_get_devroot(zonename, devroot, sizeof (devroot)) == -1) {
zerror(gettext("could not get dev path for zone %s"),
zonename);
return (1);
}
if (zone_get_brand(zonename, zonebrand, sizeof (zonebrand)) != Z_OK) {
zerror(gettext("could not get brand for zone %s"), zonename);
return (1);
}
if (zonecfg_default_brand(default_brand,
sizeof (default_brand)) != Z_OK) {
zerror(gettext("unable to determine default brand"));
return (1);
}
if (zonecfg_in_alt_root() &&
strcmp(zonebrand, CLUSTER_BRAND_NAME) == 0) {
(void) strlcpy(zonebrand, default_brand, sizeof (zonebrand));
}
if ((bh = brand_open(zonebrand)) == NULL) {
zerror(gettext("could not open brand for zone %s"), zonename);
return (1);
}
if ((new_args = prep_args(bh, login, proc_args)) == NULL) {
zperror(gettext("could not assemble new arguments"));
brand_close(bh);
return (1);
}
if (!interactive && !failsafe) {
if (zone_get_user_cmd(bh, login, user_cmd,
sizeof (user_cmd)) == NULL) {
zerror(gettext("could not get user_cmd for zone %s"),
zonename);
brand_close(bh);
return (1);
}
}
brand_close(bh);
if ((new_env = prep_env()) == NULL) {
zperror(gettext("could not assemble new environment"));
return (1);
}
if (!interactive) {
if (nflag) {
int nfd;
if ((nfd = open(_PATH_DEVNULL, O_RDONLY)) < 0) {
zperror(gettext("failed to open null device"));
return (1);
}
if (nfd != STDIN_FILENO) {
if (dup2(nfd, STDIN_FILENO) < 0) {
zperror(gettext(
"failed to dup2 null device"));
return (1);
}
(void) close(nfd);
}
}
return (noninteractive_login(zonename, user_cmd, zoneid,
new_args, new_env));
}
if (zonecfg_in_alt_root()) {
zerror(gettext("cannot use interactive login with scratch "
"zone"));
return (1);
}
if (get_master_pty() == -1) {
zerror(gettext("could not setup master pty device"));
return (1);
}
if ((slavename = ptsname(masterfd)) == NULL) {
zperror(gettext("failed to get name for pseudo-tty"));
return (1);
}
if (strncmp(slavename, "/dev/", strlen("/dev/")) == 0)
(void) strlcpy(slaveshortname, slavename + strlen("/dev/"),
sizeof (slaveshortname));
else
(void) strlcpy(slaveshortname, slavename,
sizeof (slaveshortname));
if (!quiet)
(void) printf(gettext("[Connected to zone '%s' %s]\n"),
zonename, slaveshortname);
if (set_tty_rawmode(STDIN_FILENO) == -1) {
reset_tty();
zperror(gettext("failed to set stdin pty to raw mode"));
return (1);
}
if (prefork_dropprivs() != 0) {
reset_tty();
zperror(gettext("could not allocate privilege set"));
return (1);
}
(void) sigset(SIGCLD, sigcld);
(void) sigemptyset(&block_cld);
(void) sigaddset(&block_cld, SIGCLD);
(void) sigprocmask(SIG_BLOCK, &block_cld, NULL);
if ((tmpl_fd = init_template()) == -1) {
reset_tty();
zperror(gettext("could not create contract"));
return (1);
}
if ((child_pid = fork()) == -1) {
(void) ct_tmpl_clear(tmpl_fd);
reset_tty();
zperror(gettext("could not fork"));
return (1);
} else if (child_pid == 0) {
int slavefd, newslave;
(void) ct_tmpl_clear(tmpl_fd);
(void) close(tmpl_fd);
(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
if ((slavefd = init_slave_pty(zoneid, devroot)) == -1)
return (1);
(void) fdwalk(close_func, &slavefd);
if (slavefd != STDERR_FILENO)
(void) dup2(slavefd, STDERR_FILENO);
if (zone_enter(zoneid) == -1) {
zerror(gettext("could not enter zone %s: %s"),
zonename, strerror(errno));
return (1);
}
if (slavefd != STDERR_FILENO)
(void) close(STDERR_FILENO);
(void) setpgrp();
if ((newslave = open(slavename, O_RDWR)) == -1) {
(void) close(slavefd);
return (1);
}
(void) close(slavefd);
slavefd = newslave;
(void) dup2(slavefd, STDIN_FILENO);
(void) dup2(slavefd, STDOUT_FILENO);
(void) dup2(slavefd, STDERR_FILENO);
if (slavefd != STDIN_FILENO && slavefd != STDOUT_FILENO &&
slavefd != STDERR_FILENO) {
(void) close(slavefd);
}
if (!failsafe)
if (setup_utmpx(slaveshortname) == -1)
return (1);
if (setuid(0) == -1) {
zperror(gettext("insufficient privilege"));
return (1);
}
(void) execve(new_args[0], new_args, new_env);
zperror(gettext("exec failure"));
return (1);
}
(void) ct_tmpl_clear(tmpl_fd);
(void) close(tmpl_fd);
(void) sigset(SIGWINCH, sigwinch);
postfork_dropprivs();
(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
doio(masterfd, -1, masterfd, -1, -1, B_FALSE);
reset_tty();
if (!quiet)
(void) fprintf(stderr,
gettext("\n[Connection to zone '%s' %s closed]\n"),
zonename, slaveshortname);
if (pollerr != 0) {
(void) fprintf(stderr, gettext("Error: connection closed due "
"to unexpected pollevents=0x%x.\n"), pollerr);
return (1);
}
return (0);
}