]> andersk Git - test.git/blame - shellinabox/launcher.c
Avoid compiler warnings with some versions of GCC.
[test.git] / shellinabox / launcher.c
CommitLineData
7460295f 1// launcher.c -- Launch services from a privileged process
e0bb8a33 2// Copyright (C) 2008-2009 Markus Gutschke <markus@shellinabox.com>
7460295f
MG
3//
4// This program is free software; you can redistribute it and/or modify
5// it under the terms of the GNU General Public License version 2 as
6// published by the Free Software Foundation.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License along
14// with this program; if not, write to the Free Software Foundation, Inc.,
15// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16//
17// In addition to these license terms, the author grants the following
18// additional rights:
19//
20// If you modify this program, or any covered work, by linking or
21// combining it with the OpenSSL project's OpenSSL library (or a
22// modified version of that library), containing parts covered by the
23// terms of the OpenSSL or SSLeay licenses, the author
24// grants you additional permission to convey the resulting work.
25// Corresponding Source for a non-source form of such a combination
26// shall include the source code for the parts of OpenSSL used as well
27// as that of the covered work.
28//
29// You may at your option choose to remove this additional permission from
30// the work, or from any part of it.
31//
32// It is possible to build this program in a way that it loads OpenSSL
33// libraries at run-time. If doing so, the following notices are required
34// by the OpenSSL and SSLeay licenses:
35//
36// This product includes software developed by the OpenSSL Project
37// for use in the OpenSSL Toolkit. (http://www.openssl.org/)
38//
39// This product includes cryptographic software written by Eric Young
40// (eay@cryptsoft.com)
41//
42//
43// The most up-to-date version of this program is always available from
44// http://shellinabox.com
45
46#define _GNU_SOURCE
bdd01e84 47#include "config.h"
7460295f 48
c593cf68 49#define pthread_once x_pthread_once
572ac014 50#define execle x_execle
c593cf68 51
7460295f
MG
52#include <dirent.h>
53#include <dlfcn.h>
54#include <fcntl.h>
55#include <grp.h>
bf1ec4d2 56#include <limits.h>
7460295f 57#include <pwd.h>
47e62a9c 58#include <signal.h>
5e56158a 59#include <stdio.h>
7460295f
MG
60#include <stdlib.h>
61#include <string.h>
62#include <sys/ioctl.h>
63#include <sys/socket.h>
64#include <sys/stat.h>
65#include <sys/time.h>
66#include <sys/types.h>
67#include <sys/wait.h>
68#include <sys/utsname.h>
69#include <termios.h>
70#include <unistd.h>
47e62a9c 71
a3876a41
MG
72#ifdef HAVE_LIBUTIL_H
73#include <libutil.h>
74#endif
75
572ac014
MG
76#ifdef HAVE_PTY_H
77#include <pty.h>
78#endif
79
80#ifdef HAVE_SYS_UIO_H
81#include <sys/uio.h>
82#endif
83
84#ifdef HAVE_UTIL_H
85#include <util.h>
86#endif
87
a3876a41
MG
88#ifdef HAVE_UTMP_H
89#include <utmp.h>
90#endif
91
47e62a9c 92#ifdef HAVE_UTMPX_H
7460295f 93#include <utmpx.h>
47e62a9c 94#endif
7460295f 95
a3876a41 96#if defined(HAVE_SECURITY_PAM_APPL_H)
7460295f 97#include <security/pam_appl.h>
a3876a41
MG
98
99#if defined(HAVE_SECURITY_PAM_MISC_H)
7460295f 100#include <security/pam_misc.h>
a3876a41 101#endif
7460295f
MG
102#else
103struct pam_message;
104struct pam_response;
105struct pam_conv;
106typedef struct pam_handle pam_handle_t;
107#endif
108
572ac014
MG
109#ifdef HAVE_STRLCAT
110#define strncat(a,b,c) ({ char *_a = (a); strlcat(_a, (b), (c)+1); _a; })
111#endif
112
7460295f
MG
113#include "shellinabox/launcher.h"
114#include "shellinabox/privileges.h"
115#include "shellinabox/service.h"
116#include "libhttp/hashmap.h"
117#include "logging/logging.h"
118
c593cf68 119#undef pthread_once
572ac014
MG
120#undef execle
121int execle(const char *, const char *, ...);
c593cf68
MG
122
123#if defined(HAVE_PTHREAD_H) && defined(__linux__)
124#include <pthread.h>
125extern int pthread_once(pthread_once_t *, void (*)(void))__attribute__((weak));
126#endif
127
7460295f
MG
128// If PAM support is available, take advantage of it. Otherwise, silently fall
129// back on legacy operations for session management.
bf1ec4d2 130#if defined(HAVE_SECURITY_PAM_APPL_H) && defined(HAVE_DLOPEN)
7460295f
MG
131static int (*x_pam_acct_mgmt)(pam_handle_t *, int);
132static int (*x_pam_authenticate)(pam_handle_t *, int);
a3876a41
MG
133#if defined(HAVE_SECURITY_PAM_CLIENT_H)
134static int (**x_pam_binary_handler_fn)(void *, pamc_bp_t *);
135#endif
7460295f
MG
136static int (*x_pam_close_session)(pam_handle_t *, int);
137static int (*x_pam_end)(pam_handle_t *, int);
138static int (*x_pam_get_item)(const pam_handle_t *, int, const void **);
139static int (*x_pam_open_session)(pam_handle_t *, int);
140static int (*x_pam_set_item)(pam_handle_t *, int, const void *);
141static int (*x_pam_start)(const char *, const char *, const struct pam_conv *,
142 pam_handle_t **);
143static int (*x_misc_conv)(int, const struct pam_message **,
144 struct pam_response **, void *);
bf1ec4d2
MG
145
146#define pam_acct_mgmt x_pam_acct_mgmt
147#define pam_authenticate x_pam_authenticate
148#define pam_binary_handler_fn x_pam_binary_handler_fn
149#define pam_close_session x_pam_close_session
150#define pam_end x_pam_end
151#define pam_get_item x_pam_get_item
152#define pam_open_session x_pam_open_session
153#define pam_set_item x_pam_set_item
154#define pam_start x_pam_start
155#define misc_conv x_misc_conv
5e56158a 156#endif
7460295f 157
7460295f 158static int launcher = -1;
d1edcc0e 159static uid_t restricted;
7460295f
MG
160
161
a3876a41
MG
162// If the PAM misc library cannot be found, we have to provide our own basic
163// conversation function. As we know that this code is only ever called from
164// ShellInABox, it can be kept significantly simpler than the more generic
165// code that the PAM library implements.
166
167static int read_string(int echo, const char *prompt, char **retstr) {
168 *retstr = NULL;
169 struct termios term_before, term_tmp;
170 if (tcgetattr(0, &term_before) != 0) {
171 return -1;
172 }
173 memcpy(&term_tmp, &term_before, sizeof(term_tmp));
174 if (!echo) {
175 term_tmp.c_lflag &= ~ECHO;
176 }
177 int nc;
178 for (;;) {
179 tcsetattr(0, TCSAFLUSH, &term_tmp);
180 fprintf(stderr, "%s", prompt);
181 char *line;
182 const int lineLength = 512;
183 check(line = calloc(1, lineLength));
184 nc = read(0, line, lineLength - 1);
185 tcsetattr(0, TCSADRAIN, &term_before);
186 if (!echo) {
187 fprintf(stderr, "\n");
188 }
189 if (nc > 0) {
190 if (line[nc-1] == '\n') {
191 nc--;
192 } else if (echo) {
193 fprintf(stderr, "\n");
194 }
195 line[nc] = '\000';
196 check(*retstr = line);
197 break;
198 } else {
199 memset(line, 0, lineLength);
200 free(line);
201 if (echo) {
202 fprintf(stderr, "\n");
203 }
204 break;
205 }
206 }
207 tcsetattr(0, TCSADRAIN, &term_before);
208 return nc;
209}
210
78016c46 211#if defined(HAVE_SECURITY_PAM_APPL_H) && defined(HAVE_DLOPEN)
ecafba9c 212#if defined(HAVE_SECURITY_PAM_CLIENT_H)
a3876a41
MG
213static pamc_bp_t *p(pamc_bp_t *p) {
214 // GCC is too smart for its own good, and triggers a warning in
215 // PAM_BP_RENEW, unless we pass the first argument through a function.
216 return p;
217}
ecafba9c 218#endif
a3876a41
MG
219
220static int my_misc_conv(int num_msg, const struct pam_message **msgm,
221 struct pam_response **response, void *appdata_ptr) {
222 if (num_msg <= 0) {
223 return PAM_CONV_ERR;
224 }
225 struct pam_response *reply;
226 check(reply = (struct pam_response *)calloc(num_msg,
227 sizeof(struct pam_response)));
228 for (int count = 0; count < num_msg; count++) {
229 char *string = NULL;
230 switch(msgm[count]->msg_style) {
231 case PAM_PROMPT_ECHO_OFF:
232 if (read_string(0, msgm[count]->msg, &string) < 0) {
233 goto failed_conversation;
234 }
235 break;
236 case PAM_PROMPT_ECHO_ON:
237 if (read_string(1, msgm[count]->msg, &string) < 0) {
238 goto failed_conversation;
239 }
240 break;
241 case PAM_ERROR_MSG:
242 if (fprintf(stderr, "%s\n", msgm[count]->msg) < 0) {
243 goto failed_conversation;
244 }
245 break;
246 case PAM_TEXT_INFO:
247 if (fprintf(stdout, "%s\n", msgm[count]->msg) < 0) {
248 goto failed_conversation;
249 }
250 break;
251#if defined(HAVE_SECURITY_PAM_CLIENT_H)
252 case PAM_BINARY_PROMPT: {
253 pamc_bp_t binary_prompt = NULL;
bf1ec4d2 254 if (!msgm[count]->msg || !*pam_binary_handler_fn) {
a3876a41
MG
255 goto failed_conversation;
256 }
257 PAM_BP_RENEW(p(&binary_prompt), PAM_BP_RCONTROL(msgm[count]->msg),
258 PAM_BP_LENGTH(msgm[count]->msg));
259 PAM_BP_FILL(binary_prompt, 0, PAM_BP_LENGTH(msgm[count]->msg),
260 PAM_BP_RDATA(msgm[count]->msg));
bf1ec4d2 261 if ((*pam_binary_handler_fn)(appdata_ptr, &binary_prompt) !=
a3876a41
MG
262 PAM_SUCCESS || !binary_prompt) {
263 goto failed_conversation;
264 }
265 string = (char *)binary_prompt;
266 break; }
267#endif
268 default:
269 goto failed_conversation;
270 }
271 if (string) {
272 reply[count].resp_retcode = 0;
273 reply[count].resp = string;
274 }
275 }
276failed_conversation:
277 *response = reply;
278 return PAM_SUCCESS;
279}
280
7460295f
MG
281static void *loadSymbol(const char *lib, const char *fn) {
282 void *dl = RTLD_DEFAULT;
283 void *rc = dlsym(dl, fn);
284 if (!rc) {
a3876a41 285#ifdef RTLD_NOLOAD
7460295f 286 dl = dlopen(lib, RTLD_LAZY|RTLD_GLOBAL|RTLD_NOLOAD);
a3876a41
MG
287#else
288 dl = NULL;
289#endif
7460295f
MG
290 if (dl == NULL) {
291 dl = dlopen(lib, RTLD_LAZY|RTLD_GLOBAL);
292 }
293 if (dl != NULL) {
294 rc = dlsym(dl, fn);
295 }
296 }
297 return rc;
298}
299
300static void loadPAM(void) {
bf1ec4d2
MG
301 check(!pam_start);
302 check(!misc_conv);
7460295f 303 struct {
88b579e2
MG
304 union {
305 void *avoid_gcc_warning_about_type_punning;
306 void **var;
307 };
7460295f
MG
308 const char *lib;
309 const char *fn;
310 } symbols[] = {
bf1ec4d2
MG
311 { { &pam_acct_mgmt }, "libpam.so", "pam_acct_mgmt" },
312 { { &pam_authenticate }, "libpam.so", "pam_authenticate" },
a3876a41 313#if defined(HAVE_SECURITY_PAM_CLIENT_H)
bf1ec4d2 314 { { &pam_binary_handler_fn }, "libpam_misc.so", "pam_binary_handler_fn" },
a3876a41 315#endif
bf1ec4d2
MG
316 { { &pam_close_session }, "libpam.so", "pam_close_session" },
317 { { &pam_end }, "libpam.so", "pam_end" },
318 { { &pam_get_item }, "libpam.so", "pam_get_item" },
319 { { &pam_open_session }, "libpam.so", "pam_open_session" },
320 { { &pam_set_item }, "libpam.so", "pam_set_item" },
321 { { &pam_start }, "libpam.so", "pam_start" },
322 { { &misc_conv }, "libpam_misc.so", "misc_conv" }
7460295f
MG
323 };
324 for (int i = 0; i < sizeof(symbols)/sizeof(symbols[0]); i++) {
325 if (!(*symbols[i].var = loadSymbol(symbols[i].lib, symbols[i].fn))) {
a3876a41
MG
326#if defined(HAVE_SECURITY_PAM_CLIENT_H)
327 if (!strcmp(symbols[i].fn, "pam_binary_handler_fn")) {
328 // Binary conversation support is optional
329 continue;
330 } else
331#endif
332 if (!strcmp(symbols[i].fn, "misc_conv")) {
333 // PAM misc is optional
334 *symbols[i].var = (void *)my_misc_conv;
335 continue;
336 }
7460295f
MG
337 debug("Failed to load PAM support. Could not find \"%s\"",
338 symbols[i].fn);
339 for (int j = 0; j < sizeof(symbols)/sizeof(symbols[0]); j++) {
340 *symbols[j].var = NULL;
341 }
342 break;
343 }
344 }
345 debug("Loaded PAM suppport");
346}
5e56158a 347#endif
7460295f
MG
348
349int supportsPAM(void) {
bf1ec4d2
MG
350#if defined(HAVE_SECURITY_PAM_APPL_H) && !defined(HAVE_DLOPEN)
351 return 1;
352#else
a3876a41 353#if defined(HAVE_SECURITY_PAM_APPL_H)
7460295f
MG
354
355 // We want to call loadPAM() exactly once. For single-threaded applications,
356 // this is straight-forward. For threaded applications, we need to call
357 // pthread_once(), instead. We perform run-time checks for whether we are
358 // single- or multi-threaded, so that the same code can be used.
a3876a41 359 // This currently only works on Linux.
9d758d39 360#if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
7460295f
MG
361 if (!!&pthread_once) {
362 static pthread_once_t once = PTHREAD_ONCE_INIT;
363 pthread_once(&once, loadPAM);
364 } else
365#endif
366 {
367 static int initialized;
368 if (!initialized) {
369 initialized = 1;
370 loadPAM();
371 }
372 }
bf1ec4d2 373 return misc_conv && pam_start;
7460295f
MG
374#else
375 return 0;
376#endif
bf1ec4d2 377#endif
7460295f
MG
378}
379
572ac014
MG
380#ifndef HAVE_GETPWUID_R
381// This is a not-thread-safe replacement for getpwuid_r()
382#define getpwuid_r x_getpwuid_r
383static int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf, size_t buflen,
384 struct passwd **result) {
385 if (result) {
386 *result = NULL;
387 }
388 if (!pwd) {
389 return -1;
390 }
391 errno = 0;
392 struct passwd *p = getpwuid(uid);
393 if (!p) {
394 return errno ? -1 : 0;
395 }
396 *pwd = *p;
397 if (result) {
398 *result = pwd;
399 }
400 return 0;
401}
402#endif
403
1ef7f27f 404int launchChild(int service, struct Session *session, const char *url) {
3240f75b
MG
405 if (launcher < 0) {
406 errno = EINVAL;
407 return -1;
408 }
409
e2232b9f
MG
410 char *u;
411 check(u = strdup(url));
412 for (int i; u[i = strcspn(u, "\\\"'`${};() \r\n\t\v\f")]; ) {
413 static const char hex[] = "0123456789ABCDEF";
414 check(u = realloc(u, strlen(u) + 4));
415 memmove(u + i + 3, u + i + 1, strlen(u + i));
416 u[i + 2] = hex[ u[i] & 0xF];
417 u[i + 1] = hex[(u[i] >> 4) & 0xF];
418 u[i] = '%';
419 }
420
1ef7f27f 421 struct LaunchRequest *request;
e2232b9f 422 size_t len = sizeof(struct LaunchRequest) + strlen(u) + 1;
1ef7f27f
MG
423 check(request = calloc(len, 1));
424 request->service = service;
425 request->width = session->width;
426 request->height = session->height;
427 strncat(request->peerName, httpGetPeerName(session->http),
428 sizeof(request->peerName) - 1);
e2232b9f
MG
429 request->urlLength = strlen(u);
430 memcpy(&request->url, u, request->urlLength);
431 free(u);
1ef7f27f
MG
432 if (NOINTR(write(launcher, request, len)) != len) {
433 free(request);
7460295f
MG
434 return -1;
435 }
1ef7f27f 436 free(request);
7460295f
MG
437 pid_t pid;
438 char cmsg_buf[CMSG_SPACE(sizeof(int))];
439 struct iovec iov = { 0 };
440 struct msghdr msg = { 0 };
441 iov.iov_base = &pid;
442 iov.iov_len = sizeof(pid);
443 msg.msg_iov = &iov;
444 msg.msg_iovlen = 1;
445 msg.msg_control = &cmsg_buf;
446 msg.msg_controllen = sizeof(cmsg_buf);
447 int bytes = NOINTR(recvmsg(launcher, &msg, 0));
448 if (bytes < 0) {
449 return -1;
450 }
451 check(bytes == sizeof(pid));
452 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
453 check(cmsg);
454 check(cmsg->cmsg_level == SOL_SOCKET);
455 check(cmsg->cmsg_type == SCM_RIGHTS);
ac96c090 456 memcpy(&session->pty, CMSG_DATA(cmsg), sizeof(int));
7460295f
MG
457 return pid;
458}
459
460struct Utmp {
461 const char pid[32];
462 int pty;
463 int useLogin;
47e62a9c 464#ifdef HAVE_UTMPX_H
7460295f 465 struct utmpx utmpx;
47e62a9c 466#endif
7460295f
MG
467};
468
469static HashMap *childProcesses;
470
471void initUtmp(struct Utmp *utmp, int useLogin, const char *ptyPath,
472 const char *peerName) {
473 memset(utmp, 0, sizeof(struct Utmp));
474 utmp->pty = -1;
475 utmp->useLogin = useLogin;
47e62a9c 476#ifdef HAVE_UTMPX_H
7460295f
MG
477 utmp->utmpx.ut_type = useLogin ? LOGIN_PROCESS : USER_PROCESS;
478 dcheck(!strncmp(ptyPath, "/dev/pts", 8));
479 strncat(&utmp->utmpx.ut_line[0], ptyPath + 5, sizeof(utmp->utmpx.ut_line));
480 strncat(&utmp->utmpx.ut_id[0], ptyPath + 8, sizeof(utmp->utmpx.ut_id));
481 strncat(&utmp->utmpx.ut_user[0], "SHELLINABOX", sizeof(utmp->utmpx.ut_user));
482 strncat(&utmp->utmpx.ut_host[0], peerName, sizeof(utmp->utmpx.ut_host));
483 struct timeval tv;
484 check(!gettimeofday(&tv, NULL));
485 utmp->utmpx.ut_tv.tv_sec = tv.tv_sec;
486 utmp->utmpx.ut_tv.tv_usec = tv.tv_usec;
47e62a9c 487#endif
7460295f
MG
488}
489
490struct Utmp *newUtmp(int useLogin, const char *ptyPath,
491 const char *peerName) {
492 struct Utmp *utmp;
493 check(utmp = malloc(sizeof(struct Utmp)));
494 initUtmp(utmp, useLogin, ptyPath, peerName);
495 return utmp;
496}
497
498void destroyUtmp(struct Utmp *utmp) {
499 if (utmp) {
500 if (utmp->pty >= 0) {
47e62a9c 501#ifdef HAVE_UTMPX_H
7460295f
MG
502 utmp->utmpx.ut_type = DEAD_PROCESS;
503 memset(&utmp->utmpx.ut_user, 0, sizeof(utmp->utmpx.ut_user));
504 memset(&utmp->utmpx.ut_host, 0, sizeof(utmp->utmpx.ut_host));
505 struct timeval tv;
506 check(!gettimeofday(&tv, NULL));
507 utmp->utmpx.ut_tv.tv_sec = tv.tv_sec;
508 utmp->utmpx.ut_tv.tv_usec = tv.tv_usec;
509
510 // Temporarily regain privileges to update the utmp database
511 uid_t r_uid, e_uid, s_uid;
512 uid_t r_gid, e_gid, s_gid;
513 check(!getresuid(&r_uid, &e_uid, &s_uid));
514 check(!getresgid(&r_gid, &e_gid, &s_gid));
515 setresuid(0, 0, 0);
516 setresgid(0, 0, 0);
517
518 setutxent();
519 pututxline(&utmp->utmpx);
520 endutxent();
521 if (!utmp->useLogin) {
522 updwtmpx("/var/log/wtmp", &utmp->utmpx);
523 }
524
525 // Switch back to the lower privileges
526 check(!setresgid(r_gid, e_gid, s_gid));
527 check(!setresuid(r_uid, e_uid, s_uid));
47e62a9c 528#endif
7460295f
MG
529
530 NOINTR(close(utmp->pty));
531 }
532 }
533}
534
535void deleteUtmp(struct Utmp *utmp) {
536 destroyUtmp(utmp);
537 free(utmp);
538}
539
540static void destroyUtmpHashEntry(void *arg, char *key, char *value) {
541 deleteUtmp((struct Utmp *)value);
542}
543
d1edcc0e
MG
544void closeAllFds(int *exceptFds, int num) {
545 // Close all file handles. If possible, scan through "/proc/self/fd" as
546 // that is faster than calling close() on all possible file handles.
547 int nullFd = open("/dev/null", O_RDWR);
f4a48088
MG
548 DIR *dir = opendir("/proc/self/fd");
549 if (dir == 0) {
d1edcc0e
MG
550 for (int i = sysconf(_SC_OPEN_MAX); --i > 0; ) {
551 if (i != nullFd) {
552 for (int j = 0; j < num; j++) {
553 if (i == exceptFds[j]) {
554 goto no_close_1;
555 }
556 }
557 // Closing handles 0..2 is never a good idea. Instead, redirect them
558 // to /dev/null
559 if (i <= 2) {
560 NOINTR(dup2(nullFd, i));
561 } else {
562 NOINTR(close(i));
563 }
564 }
565 no_close_1:;
566 }
567 } else {
d1edcc0e
MG
568 struct dirent de, *res;
569 while (!readdir_r(dir, &de, &res) && res) {
570 if (res->d_name[0] < '0')
571 continue;
572 int fd = atoi(res->d_name);
f4a48088 573 if (fd != nullFd && fd != dirfd(dir)) {
d1edcc0e
MG
574 for (int j = 0; j < num; j++) {
575 if (fd == exceptFds[j]) {
576 goto no_close_2;
577 }
578 }
579 // Closing handles 0..2 is never a good idea. Instead, redirect them
580 // to /dev/null
581 if (fd <= 2) {
582 NOINTR(dup2(nullFd, fd));
583 } else {
584 NOINTR(close(fd));
585 }
586 }
587 no_close_2:;
588 }
589 check(!closedir(dir));
590 }
591 if (nullFd > 2) {
592 check(!close(nullFd));
593 }
594}
595
a49eb7aa 596#if !defined(HAVE_OPENPTY) && !defined(HAVE_PTSNAME_R)
29135474
MG
597static int ptsname_r(int fd, char *buf, size_t buflen) {
598 // It is unfortunate that ptsname_r is not universally available.
599 // For the time being, this is not a big problem, as ShellInABox is
600 // single-threaded (and so is the launcher process). But if this
601 // code gets re-used in a multi-threaded application, that could
602 // lead to problems.
603 if (buf == NULL) {
604 errno = EINVAL;
605 return -1;
606 }
607 char *p = ptsname(fd);
608 if (p == NULL) {
609 return -1;
610 }
611 if (buflen < strlen(p) + 1) {
612 errno = ERANGE;
613 return -1;
614 }
615 strcpy(buf, p);
616 return 0;
bf1ec4d2 617}
29135474
MG
618#endif
619
7460295f
MG
620static int forkPty(int *pty, int useLogin, struct Utmp **utmp,
621 const char *peerName) {
622 int slave;
623 char ptyPath[PATH_MAX];
572ac014
MG
624 #ifdef HAVE_OPENPTY
625 if (openpty(pty, &slave, ptyPath, NULL, NULL) < 0) {
626 *pty = -1;
627 *utmp = NULL;
628 return -1;
629 }
630 #else
9c2eb40e
MG
631 if ((*pty = posix_openpt(O_RDWR|O_NOCTTY)) < 0 ||
632 grantpt(*pty) < 0 ||
633 unlockpt(*pty) < 0 ||
634 ptsname_r(*pty, ptyPath, sizeof(ptyPath)) < 0 ||
635 (slave = NOINTR(open(ptyPath, O_RDWR|O_NOCTTY))) < 0) {
7460295f
MG
636 if (*pty >= 0) {
637 NOINTR(close(*pty));
638 }
9c2eb40e
MG
639
640 // Try old-style pty handling
641 char fname[40] = "/dev/ptyXX";
642 for (const char *ptr1 = "pqrstuvwxyzabcde"; *ptr1; ptr1++) {
643 fname[8] = *ptr1;
644 for (const char *ptr2 = "0123456789abcdef"; *ptr2; ptr2++) {
645 fname[9] = *ptr2;
646 if ((*pty = NOINTR(open(fname, O_RDWR, 0))) < 0) {
647 if (errno == ENOENT) {
8249fd91 648 continue;
9c2eb40e
MG
649 }
650 }
651 grantpt(*pty);
652 unlockpt(*pty);
653 if (ptsname_r(*pty, ptyPath, sizeof(ptyPath)) < 0) {
654 strcpy(ptyPath, fname);
655 ptyPath[5] = 't';
656 }
657 if ((slave = NOINTR(open(ptyPath, O_RDWR|O_NOCTTY))) >= 0) {
658 debug("Opened old-style pty: %s", ptyPath);
659 goto success;
660 }
661 NOINTR(close(*pty));
662 }
663 }
9c2eb40e
MG
664 *pty = -1;
665 *utmp = NULL;
7460295f
MG
666 return -1;
667 }
9c2eb40e 668 success:
572ac014 669 #endif
7460295f
MG
670
671 // Fill in utmp entry
9c2eb40e 672 *utmp = newUtmp(useLogin, ptyPath, peerName);
7460295f
MG
673
674 // Now, fork off the child process
675 pid_t pid;
9c2eb40e 676 if ((pid = fork()) < 0) {
7460295f
MG
677 NOINTR(close(slave));
678 NOINTR(close(*pty));
9c2eb40e 679 *pty = -1;
7460295f 680 deleteUtmp(*utmp);
9c2eb40e 681 *utmp = NULL;
7460295f
MG
682 return -1;
683 } else if (pid == 0) {
9c2eb40e 684 pid = getpid();
7460295f 685 snprintf((char *)&(*utmp)->pid[0], sizeof((*utmp)->pid), "%d", pid);
47e62a9c 686#ifdef HAVE_UTMPX_H
9c2eb40e 687 (*utmp)->utmpx.ut_pid = pid;
47e62a9c 688#endif
9c2eb40e 689 (*utmp)->pty = slave;
7460295f 690
d1edcc0e 691 closeAllFds((int []){ slave }, 1);
7460295f 692
a3876a41
MG
693#ifdef HAVE_LOGIN_TTY
694 login_tty(slave);
695#else
7460295f
MG
696 // Become the session/process-group leader
697 setsid();
698 setpgid(0, 0);
e6bea11c 699
7460295f
MG
700 // Redirect standard I/O to the pty
701 dup2(slave, 0);
702 dup2(slave, 1);
703 dup2(slave, 2);
704 if (slave > 2) {
705 NOINTR(close(slave));
706 }
a3876a41 707#endif
9c2eb40e 708 *pty = 0;
7460295f
MG
709
710 // Force the pty to be our control terminal
711 NOINTR(close(NOINTR(open(ptyPath, O_RDWR))));
712
713 return 0;
714 } else {
715 snprintf((char *)&(*utmp)->pid[0], sizeof((*utmp)->pid), "%d", pid);
47e62a9c 716#ifdef HAVE_UTMPX_H
9c2eb40e 717 (*utmp)->utmpx.ut_pid = pid;
47e62a9c 718#endif
9c2eb40e 719 (*utmp)->pty = *pty;
7460295f
MG
720 fcntl(*pty, F_SETFL, O_NONBLOCK|O_RDWR);
721 NOINTR(close(slave));
722 return pid;
723 }
724}
725
726static const struct passwd *getPWEnt(uid_t uid) {
727 struct passwd pwbuf, *pw;
728 char *buf;
572ac014 729 #ifdef _SC_GETPW_R_SIZE_MAX
2eb60237 730 int len = sysconf(_SC_GETPW_R_SIZE_MAX);
29135474 731 if (len <= 0) {
2eb60237 732 len = 4096;
29135474 733 }
572ac014 734 #else
2eb60237 735 int len = 4096;
572ac014 736 #endif
2eb60237 737 check(buf = malloc(len));
7460295f 738 check(!getpwuid_r(uid, &pwbuf, buf, len, &pw) && pw);
e6bea11c
MG
739 if (!pw->pw_name ) pw->pw_name = (char *)"";
740 if (!pw->pw_passwd) pw->pw_passwd = (char *)"";
741 if (!pw->pw_gecos ) pw->pw_gecos = (char *)"";
742 if (!pw->pw_dir ) pw->pw_dir = (char *)"";
743 if (!pw->pw_shell ) pw->pw_shell = (char *)"";
7460295f 744 struct passwd *passwd;
2eb60237
MG
745 check(passwd = calloc(sizeof(struct passwd) +
746 strlen(pw->pw_name) +
747 strlen(pw->pw_passwd) +
748 strlen(pw->pw_gecos) +
749 strlen(pw->pw_dir) +
750 strlen(pw->pw_shell) + 5, 1));
751 passwd->pw_uid = pw->pw_uid;
752 passwd->pw_gid = pw->pw_gid;
753 strncat(passwd->pw_shell = strrchr(
754 strncat(passwd->pw_dir = strrchr(
755 strncat(passwd->pw_gecos = strrchr(
756 strncat(passwd->pw_passwd = strrchr(
757 strncat(passwd->pw_name = (char *)(passwd + 1),
572ac014
MG
758 pw->pw_name, strlen(pw->pw_name)), '\000') + 1,
759 pw->pw_passwd, strlen(pw->pw_passwd)), '\000') + 1,
760 pw->pw_gecos, strlen(pw->pw_gecos)), '\000') + 1,
761 pw->pw_dir, strlen(pw->pw_dir)), '\000') + 1,
762 pw->pw_shell, strlen(pw->pw_shell));
7460295f
MG
763 free(buf);
764 return passwd;
765}
766
767static void sigAlrmHandler(int sig, siginfo_t *info, void *unused) {
768 puts("\nLogin timed out after 60 seconds.");
769 _exit(1);
770}
771
772static pam_handle_t *internalLogin(struct Service *service, struct Utmp *utmp,
773 char ***environment) {
774 // Time out after 60 seconds
775 struct sigaction sa;
776 memset(&sa, 0, sizeof(sa));
777 sa.sa_flags = SA_SIGINFO;
778 sa.sa_sigaction = sigAlrmHandler;
779 check(!sigaction(SIGALRM, &sa, NULL));
780 alarm(60);
781
78016c46
MG
782 // Change the prompt to include the host name
783 const char *hostname = NULL;
784 if (service->authUser == 2 /* SSH */) {
785 // If connecting to a remote host, include that hostname
786 hostname = strrchr(service->cmdline, '@');
787 if (!hostname || !strcmp(++hostname, "localhost")) {
788 hostname = NULL;
789 }
790 }
791 struct utsname uts;
792 memset(&uts, 0, sizeof(uts));
793 if (!hostname) {
794 // Find our local hostname
795 check(!uname(&uts));
796 hostname = uts.nodename;
797 }
8ac38fe6
MG
798 const char *fqdn;
799 check(fqdn = strdup(hostname));
1f771613
MG
800 check(hostname = strdup(hostname));
801 char *dot = strchr(hostname, '.');
802 if (dot) {
803 *dot = '\000';
804 }
78016c46 805
7460295f
MG
806 const struct passwd *pw;
807 pam_handle_t *pam = NULL;
78016c46
MG
808 if (service->authUser == 2 /* SSH */) {
809 // Just ask for the user name. SSH will negotiate the password
810 char *user = NULL;
7460295f 811 char *prompt;
78016c46 812 check(prompt = stringPrintf(NULL, "%s login: ", hostname));
8ac38fe6
MG
813 for (;;) {
814 if (read_string(1, prompt, &user) <= 0) {
815 free(user);
816 free(prompt);
817 _exit(1);
818 }
819 if (*user) {
820 for (char *u = user; *u; u++) {
821 char ch = *u;
822 if (!((ch >= '0' && ch <= '9') ||
823 (ch >= 'A' && ch <= 'Z') ||
824 (ch >= 'a' && ch <= 'z') ||
825 ch == '-' || ch == '_' || ch == '.')) {
826 goto invalid_user_name;
827 }
828 }
829 break;
830 }
831 invalid_user_name:
78016c46 832 free(user);
8ac38fe6 833 user = NULL;
78016c46
MG
834 }
835 free(prompt);
1f771613 836 char *cmdline = stringPrintf(NULL, service->cmdline, user);
78016c46 837 free(user);
8ac38fe6
MG
838
839 // Replace '@localhost' with the actual host name. This results in a nicer
840 // prompt when SSH asks for the password.
841 char *ptr = strrchr(cmdline, '@');
842 if (!strcmp(ptr + 1, "localhost")) {
843 int offset = ptr + 1 - cmdline;
844 check(cmdline = realloc(cmdline,
845 strlen(cmdline) + strlen(fqdn) -
846 strlen("localhost") + 1));
847 ptr = cmdline + offset;
848 *ptr = '\000';
849 strncat(ptr, fqdn, strlen(fqdn));
850 }
851
78016c46
MG
852 free((void *)service->cmdline);
853 service->cmdline = cmdline;
854
855 // Run SSH as an unprivileged user
856 if ((service->uid = restricted) == 0) {
857 if (runAsUser >= 0) {
858 service->uid = runAsUser;
859 } else {
860 service->uid = getUserId("nobody");
7460295f 861 }
78016c46
MG
862 if (runAsGroup >= 0) {
863 service->gid = runAsGroup;
7460295f 864 } else {
78016c46 865 service->gid = getGroupId("nogroup");
7460295f
MG
866 }
867 }
78016c46
MG
868 pw = getPWEnt(service->uid);
869 if (restricted) {
870 service->gid = pw->pw_gid;
871 }
872 service->user = getUserName(service->uid);
873 service->group = getGroupName(service->gid);
7460295f 874 } else {
78016c46
MG
875 // Use PAM to negotiate user authentication and authorization
876#if defined(HAVE_SECURITY_PAM_APPL_H)
877 struct pam_conv conv = { .conv = misc_conv };
878 if (service->authUser) {
879 check(supportsPAM());
880 check(pam_start("shellinabox", NULL, &conv, &pam) == PAM_SUCCESS);
881
882 const char *origPrompt;
883 check(pam_get_item(pam, PAM_USER_PROMPT, (void *)&origPrompt) ==
7460295f 884 PAM_SUCCESS);
78016c46
MG
885 char *prompt;
886 check(prompt = stringPrintf(NULL, "%s %s", hostname,
887 origPrompt ? origPrompt : "login: "));
888 check(pam_set_item(pam, PAM_USER_PROMPT, prompt) == PAM_SUCCESS);
889
890 // Up to three attempts to enter the user id and password
891 for (int i = 0;;) {
892 check(pam_set_item(pam, PAM_USER, NULL) == PAM_SUCCESS);
893 int rc;
894 if ((rc = pam_authenticate(pam, PAM_SILENT)) ==
895 PAM_SUCCESS &&
896 (geteuid() ||
897 (rc = pam_acct_mgmt(pam, PAM_SILENT)) ==
898 PAM_SUCCESS)) {
899 break;
900 }
901 if (++i == 3) {
902 // Quit if login failed.
903 puts("\nMaximum number of tries exceeded (3)");
904 pam_end(pam, rc);
905 _exit(1);
906 } else {
907 puts("\nLogin incorrect");
908 }
7460295f 909 }
78016c46
MG
910 check(pam_set_item(pam, PAM_USER_PROMPT, "login: ") == PAM_SUCCESS);
911 free(prompt);
912
913 // Retrieve user id, and group id.
914 const char *name;
915 check(pam_get_item(pam, PAM_USER, (void *)&name) == PAM_SUCCESS);
916 pw = getPWEnt(getUserId(name));
917 check(service->uid < 0);
918 check(service->gid < 0);
919 check(!service->user);
920 check(!service->group);
921 service->uid = pw->pw_uid;
922 service->gid = pw->pw_gid;
923 check(service->user = strdup(pw->pw_name));
924 service->group = getGroupName(pw->pw_gid);
925 } else {
926 check(service->uid >= 0);
927 check(service->gid >= 0);
928 check(service->user);
929 check(service->group);
930 if (supportsPAM()) {
931 check(pam_start("shellinabox", service->user, &conv, &pam) ==
932 PAM_SUCCESS);
933 int rc;
934
935 // PAM account management requires root access. Just skip it, if we
936 // are running with lower privileges.
937 if (!geteuid() &&
938 (rc = pam_acct_mgmt(pam, PAM_SILENT)) !=
939 PAM_SUCCESS) {
940 pam_end(pam, rc);
941 _exit(1);
942 }
943 }
944 pw = getPWEnt(service->uid);
7460295f 945 }
5e56158a 946#else
78016c46
MG
947 check(!supportsPAM());
948 pw = getPWEnt(service->uid);
5e56158a 949#endif
78016c46 950 }
8ac38fe6 951 free((void *)fqdn);
1f771613 952 free((void *)hostname);
7460295f 953
2eb60237
MG
954 if (service->useDefaultShell) {
955 check(!service->cmdline);
956 service->cmdline = strdup(*pw->pw_shell ?
957 pw->pw_shell : "/bin/sh");
958 }
959
7460295f
MG
960 if (restricted &&
961 (service->uid != restricted || service->gid != pw->pw_gid)) {
962 puts("\nAccess denied!");
a3876a41 963#if defined(HAVE_SECURITY_PAM_APPL_H)
78016c46
MG
964 if (service->authUser != 2 /* SSH */) {
965 pam_end(pam, PAM_SUCCESS);
966 }
5e56158a 967#endif
7460295f
MG
968 _exit(1);
969 }
970
78016c46 971 if (service->authUser != 2 /* SSH */) {
a3876a41 972#if defined(HAVE_SECURITY_PAM_APPL_H)
78016c46 973 if (pam) {
47e62a9c 974#ifdef HAVE_UTMPX_H
78016c46
MG
975 check(pam_set_item(pam, PAM_TTY, (const void **)utmp->utmpx.ut_line) ==
976 PAM_SUCCESS);
47e62a9c 977#endif
78016c46 978 }
5e56158a 979#else
78016c46 980 check(!pam);
5e56158a 981#endif
78016c46 982 }
7460295f
MG
983
984 // Retrieve supplementary group ids.
a3876a41
MG
985 int ngroups;
986#if defined(__linux__)
987 // On Linux, we can query the number of supplementary groups. On all other
988 // platforms, we play it safe and just assume a fixed upper bound.
989 ngroups = 0;
7460295f 990 getgrouplist(service->user, pw->pw_gid, NULL, &ngroups);
a3876a41
MG
991#else
992 ngroups = 128;
993#endif
7460295f
MG
994 check(ngroups >= 0);
995 if (ngroups > 0) {
996 // Set supplementary group ids
997 gid_t *groups;
998 check(groups = malloc((ngroups + 1) * sizeof(gid_t)));
a3876a41 999 check(getgrouplist(service->user, pw->pw_gid, groups, &ngroups) >= 0);
7460295f
MG
1000
1001 // Make sure that any group that was requested on the command line is
1002 // included, if it is not one of the normal groups for this user.
1003 for (int i = 0; ; i++) {
1004 if (i == ngroups) {
a3876a41 1005 groups[ngroups++] = service->gid;
7460295f
MG
1006 break;
1007 } else if (groups[i] == service->gid) {
1008 break;
1009 }
1010 }
1011 setgroups(ngroups, groups);
1012 free(groups);
1013 }
1014
1015 // Add standard environment variables
1016 int numEnvVars = 0;
1017 for (char **e = *environment; *e; numEnvVars++, e++) {
1018 }
1019 check(*environment = realloc(*environment,
1020 (numEnvVars + 6)*sizeof(char *)));
1021 (*environment)[numEnvVars++] = stringPrintf(NULL, "HOME=%s", pw->pw_dir);
1022 (*environment)[numEnvVars++] = stringPrintf(NULL, "SHELL=%s", pw->pw_shell);
1023 check(
1024 (*environment)[numEnvVars++] = strdup(
1025 "PATH=/usr/local/bin:/usr/bin:/bin:/usr/games"));
1026 (*environment)[numEnvVars++] = stringPrintf(NULL, "LOGNAME=%s",
1027 service->user);
1028 (*environment)[numEnvVars++] = stringPrintf(NULL, "USER=%s", service->user);
1029 (*environment)[numEnvVars++] = NULL;
1030 free((void *)pw);
1031
1032 // Update utmp/wtmp entries
47e62a9c 1033#ifdef HAVE_UTMPX_H
78016c46
MG
1034 if (service->authUser != 2 /* SSH */) {
1035 memset(&utmp->utmpx.ut_user, 0, sizeof(utmp->utmpx.ut_user));
1036 strncat(&utmp->utmpx.ut_user[0], service->user,
1037 sizeof(utmp->utmpx.ut_user));
1038 setutxent();
1039 pututxline(&utmp->utmpx);
1040 endutxent();
1041 updwtmpx("/var/log/wtmp", &utmp->utmpx);
1042 }
47e62a9c 1043#endif
7460295f
MG
1044
1045 alarm(0);
1046 return pam;
1047}
1048
1049static void destroyVariableHashEntry(void *arg, char *key, char *value) {
1050 free(key);
1051 free(value);
1052}
1053
1054static void execService(int width, int height, struct Service *service,
1ef7f27f
MG
1055 const char *peerName, char **environment,
1056 const char *url) {
7460295f
MG
1057 // Create a hash table with all the variables that we can expand. This
1058 // includes all environment variables being passed to the child.
1059 HashMap *vars;
1060 check(vars = newHashMap(destroyVariableHashEntry, NULL));
1061 for (char **e = environment; *e; e++) {
1062 char *ptr = strchr(*e, '=');
1063 char *key, *value;
1064 if (!ptr) {
1065 check(key = strdup(*e));
1066 check(value = strdup(""));
1067 } else {
1068 check(key = malloc(ptr - *e + 1));
1069 memcpy(key, *e, ptr - *e);
1070 key[ptr - *e] = '\000';
1071 check(value = strdup(ptr + 1));
1072 }
1073 // All of our variables are lower-case
1074 for (ptr = key; *ptr; ptr++) {
1075 if (*ptr >= 'A' && *ptr <= 'Z') {
1076 *ptr += 'a' - 'A';
1077 }
1078 }
1079 addToHashMap(vars, key, value);
1080 }
1081 char *key, *value;
1082 check(key = strdup("gid"));
1083 addToHashMap(vars, key, stringPrintf(NULL, "%d", service->gid));
1084 check(key = strdup("group"));
1085 check(value = strdup(service->group));
1086 addToHashMap(vars, key, value);
1087 check(key = strdup("peer"));
1088 check(value = strdup(peerName));
1089 addToHashMap(vars, key, value);
1090 check(key = strdup("uid"));
1091 addToHashMap(vars, key, stringPrintf(NULL, "%d", service->uid));
1ef7f27f
MG
1092 check(key = strdup("url"));
1093 addToHashMap(vars, key, strdup(url));
7460295f
MG
1094
1095 enum { ENV, ARGS } state = ENV;
1096 enum { NONE, SINGLE, DOUBLE
1097 } quote = NONE;
1098 char *cmdline;
1099 check(cmdline = strdup(service->cmdline));
1100 int argc = 0;
1101 char **argv;
1102 check(argv = malloc(sizeof(char *)));
1103 key = NULL;
1104 value = NULL;
1105 for (char *ptr = cmdline; ; ptr++) {
1106 if (!key && *ptr && *ptr != ' ') {
1107 key = ptr;
1108 }
1109 switch (*ptr) {
1110 case '\'':
1111 if (quote == SINGLE || quote == NONE) {
1112 memmove(ptr, ptr + 1, strlen(ptr));
1113 ptr--;
1114 quote = quote == SINGLE ? NONE : SINGLE;
1115 } else {
1116 dcheck(quote == DOUBLE);
1117 }
1118 break;
1119 case '\"':
1120 if (quote == DOUBLE || quote == NONE) {
1121 memmove(ptr, ptr + 1, strlen(ptr));
1122 ptr--;
1123 quote = quote == DOUBLE ? NONE : DOUBLE;
1124 } else {
1125 dcheck(quote == SINGLE);
1126 }
1127 break;
1128 case '$':
1129 if ((quote == NONE || quote == DOUBLE) && ptr[1] == '{') {
1130 // Always treat environment variables as if they were quoted. There
da3d13a3 1131 // is no good reason for us to try to look for spaces within
7460295f
MG
1132 // expanded environment variables. This just leads to subtle bugs.
1133 char *end = ptr + 2;
1134 while (*end && *end != '}') {
1135 end++;
1136 }
1137 char ch = *end;
1138 *end = '\000';
da3d13a3 1139 const char *repl = getFromHashMap(vars, ptr + 2);
7460295f
MG
1140 int replLen = repl ? strlen(repl) : 0;
1141 *end = ch;
1142 if (ch) {
1143 end++;
1144 }
1ef7f27f
MG
1145 int incr = replLen - (end - ptr);
1146 if (incr > 0) {
1147 char *oldCmdline = cmdline;
1148 check(cmdline = realloc(cmdline,
1149 (end - cmdline) + strlen(end) +
1150 incr + 1));
1151 ptr += cmdline - oldCmdline;
1152 end += cmdline - oldCmdline;
1153 if (key) {
1154 key += cmdline - oldCmdline;
1155 }
1156 if (value) {
1157 value += cmdline - oldCmdline;
1158 }
1159 }
7460295f
MG
1160 memmove(ptr + replLen, end, strlen(end) + 1);
1161 if (repl) {
1162 memcpy(ptr, repl, replLen);
1163 }
1ef7f27f 1164 ptr += replLen - 1;
7460295f
MG
1165 }
1166 break;
1167 case '\\':
1168 if (!ptr[1]) {
1169 *ptr-- = '\000';
1170 } else {
1171 memmove(ptr, ptr + 1, strlen(ptr));
1172 }
1173 break;
1174 case '=':
1175 // This is the seperator between keys and values of any environment
1176 // variable that we are asked to set.
1177 if (state == ENV && quote == NONE && !value) {
1178 *ptr = '\000';
1179 value = ptr + 1;
1180 }
1181 break;
1182 case ' ':
1183 // If this space character is not quoted, this is the start of a new
1184 // command line argument.
1185 if (quote != NONE) {
1186 break;
1187 }
1188 // Fall thru
1189 case '\000':;
1190 char ch = *ptr;
1191 if (key) {
1192 *ptr = '\000';
1193 if (state == ENV && value) {
1194 // Override an existing environment variable.
1195 int numEnvVars = 0;
1196 int len = strlen(key);
1197 for (char **e = environment; *e; e++, numEnvVars++) {
1198 if (!strncmp(*e, key, len) && (*e)[len] == '=') {
572ac014
MG
1199 int s_size = len + strlen(value) + 1;
1200 check(*e = realloc(*e, s_size + 1));
1201 (*e)[len + 1] = '\000';
1202 strncat(*e, value, s_size);
7460295f
MG
1203 numEnvVars = -1;
1204 break;
1205 }
1206 }
1207 // Add a new environment variable
1208 if (numEnvVars >= 0) {
1209 check(environment = realloc(environment,
1210 (numEnvVars + 2)*sizeof(char *)));
1211 value[-1] = '=';
1212 environment[numEnvVars++] = strdup(key);
1213 environment[numEnvVars] = NULL;
1214 }
1215 } else {
1216 // Add entry to argv.
1217 state = ARGS;
1ef7f27f 1218 argv[argc++] = strdup(key);
7460295f
MG
1219 check(argv = realloc(argv, (argc + 1)*sizeof(char *)));
1220 }
1221 }
1222 key = NULL;
1223 value = NULL;
1224 if (!ch) {
1225 goto done;
1226 }
1227 break;
1228 default:
1229 break;
1230 }
1231 }
1232 done:
1ef7f27f 1233 free(cmdline);
7460295f
MG
1234 argv[argc] = NULL;
1235 deleteHashMap(vars);
1236 check(argc);
1237
1238 extern char **environ;
1239 environ = environment;
2eb60237
MG
1240 char *cmd = strdup(argv[0]);
1241 char *slash = strrchr(argv[0], '/');
1242 if (slash) {
1243 memmove(argv[0], slash + 1, strlen(slash));
1244 }
1245 if (service->useDefaultShell) {
1246 int len = strlen(argv[0]);
1247 check(argv[0] = realloc(argv[0], len + 2));
1248 memmove(argv[0] + 1, argv[0], len);
1249 argv[0][0] = '-';
1250 argv[0][len + 1] = '\000';
1251 }
1252 execvp(cmd, argv);
7460295f
MG
1253}
1254
1255void setWindowSize(int pty, int width, int height) {
1256 if (width > 0 && height > 0) {
08db8657
MG
1257 #ifdef TIOCSSIZE
1258 {
1259 struct ttysize win;
1260 ioctl(pty, TIOCGSIZE, &win);
1261 win.ts_lines = height;
1262 win.ts_cols = width;
1263 ioctl(pty, TIOCSSIZE, &win);
1264 }
1265 #endif
1266 #ifdef TIOCGWINSZ
1267 {
1268 struct winsize win;
1269 ioctl(pty, TIOCGWINSZ, &win);
1270 win.ws_row = height;
1271 win.ws_col = width;
1272 ioctl(pty, TIOCSWINSZ, &win);
1273 }
1274 #endif
7460295f
MG
1275 }
1276}
1277
1278static void childProcess(struct Service *service, int width, int height,
1ef7f27f
MG
1279 struct Utmp *utmp, const char *peerName,
1280 const char *url) {
7460295f
MG
1281 // Set initial window size
1282 setWindowSize(0, width, height);
1283
1284 // Set up environment variables
1285 static const char *legalEnv[] = { "TZ", "HZ", NULL };
1286 char **environment;
1287 check(environment = malloc(2*sizeof(char *)));
1288 int numEnvVars = 1;
5e56158a 1289 check(environment[0] = strdup("TERM=xterm"));
7460295f
MG
1290 if (width > 0 && height > 0) {
1291 numEnvVars += 2;
1292 check(environment = realloc(environment,
1293 (numEnvVars + 1)*sizeof(char *)));
1294 environment[numEnvVars-2] = stringPrintf(NULL, "COLUMNS=%d", width);
1295 environment[numEnvVars-1] = stringPrintf(NULL, "LINES=%d", height);
1296 }
1297 for (int i = 0; legalEnv[i]; i++) {
1298 char *value = getenv(legalEnv[i]);
1299 if (value) {
1300 numEnvVars++;
1301 check(environment = realloc(environment,
1302 (numEnvVars + 1)*sizeof(char *)));
1303 environment[numEnvVars-1] = stringPrintf(NULL, "%s=%s",
1304 legalEnv[i], value);
1305 }
1306 }
1307 environment[numEnvVars] = NULL;
1308
1309 // Set initial terminal settings
30046882 1310 struct termios tt = { 0 };
7460295f
MG
1311 tcgetattr(0, &tt);
1312 cfsetispeed(&tt, 38400);
1313 cfsetospeed(&tt, 38400);
1314 tt.c_iflag = TTYDEF_IFLAG & ~ISTRIP;
1315 tt.c_oflag = TTYDEF_OFLAG;
1316 tt.c_lflag = TTYDEF_LFLAG;
1317 tt.c_cflag = (TTYDEF_CFLAG & ~(CS7|PARENB|HUPCL)) | CS8;
1318 tt.c_cc[VERASE] = '\x7F';
1319 tcsetattr(0, TCSAFLUSH, &tt);
1320
1321 // Assert root privileges in order to update utmp entry.
1322 setresuid(0, 0, 0);
1323 setresgid(0, 0, 0);
47e62a9c 1324#ifdef HAVE_UTMPX_H
7460295f
MG
1325 setutxent();
1326 struct utmpx utmpx = utmp->utmpx;
1327 if (service->useLogin || service->authUser) {
1328 utmpx.ut_type = LOGIN_PROCESS;
1329 memset(utmpx.ut_host, 0, sizeof(utmpx.ut_host));
1330 }
1331 pututxline(&utmpx);
1332 endutxent();
1333 if (!utmp->useLogin) {
1334 memset(&utmpx.ut_user, 0, sizeof(utmpx.ut_user));
1335 strncat(&utmpx.ut_user[0], "LOGIN", sizeof(utmpx.ut_user));
1336 updwtmpx("/var/log/wtmp", &utmpx);
1337 }
47e62a9c 1338#endif
7460295f
MG
1339
1340 // Create session. We might have to fork another process as PAM wants us
1341 // to close the session when the child terminates. And we must retain
1342 // permissions, as session closure could require root permissions.
1343 // None of this really applies if we are running as an unprivileged user.
1344 // In that case, we do not bother about session management.
1345 if (!service->useLogin) {
1346 pam_handle_t *pam = internalLogin(service, utmp, &environment);
a3876a41 1347#if defined(HAVE_SECURITY_PAM_APPL_H)
7460295f 1348 if (pam && !geteuid()) {
bf1ec4d2 1349 check(pam_open_session(pam, PAM_SILENT) == PAM_SUCCESS);
7460295f
MG
1350 pid_t pid = fork();
1351 switch (pid) {
1352 case -1:
1353 _exit(1);
1354 case 0:
1355 break;
1356 default:;
1357 // Finish all pending PAM operations.
1358 int status, rc;
a3876a41 1359 check(NOINTR(waitpid(pid, &status, 0)) == pid);
bf1ec4d2 1360 check((rc = pam_close_session(pam, PAM_SILENT)) ==
7460295f 1361 PAM_SUCCESS);
bf1ec4d2 1362 check(pam_end(pam, rc) == PAM_SUCCESS);
7460295f
MG
1363 _exit(WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status));
1364 }
1365 }
5e56158a
MG
1366#else
1367 check(!pam);
1368#endif
7460295f
MG
1369 }
1370
1371 // Change user and group ids
1372 check(!setresgid(service->gid, service->gid, service->gid));
1373 check(!setresuid(service->uid, service->uid, service->uid));
1374
1375 // Change working directory
1376 if (service->useHomeDir) {
1377 check(!service->useLogin);
1378 const struct passwd *pw = getPWEnt(getuid());
1379 check(!service->cwd);
1380 check(service->cwd = strdup(pw->pw_dir));
1381 free((void *)pw);
1382 }
1383 check(service->cwd);
1384 if (!*service->cwd || *service->cwd != '/' || chdir(service->cwd)) {
1385 check(service->cwd = realloc((char *)service->cwd, 2));
572ac014
MG
1386 *(char *)service->cwd = '\000';
1387 strncat((char *)service->cwd, "/", 1);
7460295f
MG
1388 puts("No directory, logging in with HOME=/");
1389 check(!chdir("/"));
1390 for (int i = 0; environment[i]; i++) {
1391 if (!strncmp(environment[i], "HOME=", 5)) {
1392 free(environment[i]);
1393 check(environment[i] = strdup("HOME=/"));
1394 break;
1395 }
1396 }
1397 }
1398
1399 // Finally, launch the child process.
78016c46 1400 if (service->useLogin == 1) {
572ac014
MG
1401 execle("/bin/login", "login", "-p", "-h", peerName,
1402 (void *)0, environment);
1403 execle("/usr/bin/login", "login", "-p", "-h", peerName,
1404 (void *)0, environment);
7460295f 1405 } else {
1ef7f27f 1406 execService(width, height, service, peerName, environment, url);
7460295f
MG
1407 }
1408 _exit(1);
1409}
1410
1411static void sigChildHandler(int sig, siginfo_t *info, void *unused) {
1412}
1413
1414static void launcherDaemon(int fd) {
1415 struct sigaction sa;
1416 memset(&sa, 0, sizeof(sa));
1417 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
1418 sa.sa_sigaction = sigChildHandler;
1419 check(!sigaction(SIGCHLD, &sa, NULL));
1420
1421 struct LaunchRequest request;
1422 for (;;) {
1423 errno = 0;
1424 int len = read(fd, &request, sizeof(request));
1425 if (len != sizeof(request) && errno != EINTR) {
1ef7f27f
MG
1426 if (len) {
1427 debug("Failed to read launch request");
1428 }
7460295f
MG
1429 break;
1430 }
1431
1432 // Check whether our read operation got interrupted, because a child
1433 // has died.
1434 int status;
1435 pid_t pid;
1436 while (NOINTR(pid = waitpid(-1, &status, WNOHANG)) > 0) {
1437 if (WIFEXITED(pid) || WIFSIGNALED(pid)) {
1438 char key[32];
1439 snprintf(&key[0], sizeof(key), "%d", pid);
1440 deleteFromHashMap(childProcesses, key);
1441 }
1442 }
1443 if (len != sizeof(request)) {
1444 continue;
1445 }
1446
1ef7f27f
MG
1447 char *url;
1448 check(url = calloc(request.urlLength + 1, 1));
1449 readURL:
1450 len = read(fd, url, request.urlLength + 1);
1451 if (len != request.urlLength + 1 && errno != EINTR) {
1452 debug("Failed to read URL");
1453 free(url);
1454 break;
1455 }
1456 while (NOINTR(pid = waitpid(-1, &status, WNOHANG)) > 0) {
1457 if (WIFEXITED(pid) || WIFSIGNALED(pid)) {
1458 char key[32];
1459 snprintf(&key[0], sizeof(key), "%d", pid);
1460 deleteFromHashMap(childProcesses, key);
1461 }
1462 }
1463 if (len != request.urlLength + 1) {
1464 goto readURL;
1465 }
1466
7460295f
MG
1467 check(request.service >= 0);
1468 check(request.service < numServices);
1469
1470 // Sanitize the host name, so that we do not pass any unexpected characters
1471 // to our child process.
1472 request.peerName[sizeof(request.peerName)-1] = '\000';
1473 for (char *s = request.peerName; *s; s++) {
1474 if (!((*s >= '0' && *s <= '9') ||
1475 (*s >= 'A' && *s <= 'Z') ||
1476 (*s >= 'a' && *s <= 'z') ||
1477 *s == '.' || *s == '-')) {
1478 *s = '-';
1479 }
1480 }
1481
1482 // Fork and exec the child process.
1483 int pty;
1484 struct Utmp *utmp;
1485 if ((pid = forkPty(&pty,
1486 services[request.service]->useLogin,
8249fd91 1487 &utmp, request.peerName)) == 0) {
7460295f 1488 childProcess(services[request.service], request.width, request.height,
1ef7f27f
MG
1489 utmp, request.peerName, url);
1490 free(url);
7460295f
MG
1491 _exit(1);
1492 } else {
1493 // Remember the utmp entry so that we can clean up when the child
1494 // terminates.
1ef7f27f 1495 free(url);
8249fd91
MG
1496 if (pid > 0) {
1497 if (!childProcesses) {
1498 childProcesses = newHashMap(destroyUtmpHashEntry, NULL);
1499 }
1500 addToHashMap(childProcesses, utmp->pid, (char *)utmp);
1501 } else {
1502 int fds[2];
1503 if (!pipe(fds)) {
0f21d7cb 1504 NOINTR(write(fds[1], "forkpty() failed\r\n", 18));
8249fd91
MG
1505 NOINTR(close(fds[1]));
1506 pty = fds[0];
1507 pid = 0;
1508 }
7460295f 1509 }
7460295f
MG
1510
1511 // Send file handle and process id back to parent
0fae962f 1512 char cmsg_buf[CMSG_SPACE(sizeof(int))] = { 0 };
7460295f
MG
1513 struct iovec iov = { 0 };
1514 struct msghdr msg = { 0 };
1515 iov.iov_base = &pid;
1516 iov.iov_len = sizeof(pid);
1517 msg.msg_iov = &iov;
1518 msg.msg_iovlen = 1;
1519 msg.msg_control = &cmsg_buf;
1520 msg.msg_controllen = sizeof(cmsg_buf);
1521 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
1522 check(cmsg);
1523 cmsg->cmsg_level = SOL_SOCKET;
1524 cmsg->cmsg_type = SCM_RIGHTS;
1525 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
ac96c090 1526 memcpy(CMSG_DATA(cmsg), &pty, sizeof(int));
7460295f
MG
1527 if (NOINTR(sendmsg(fd, &msg, 0)) != sizeof(pid)) {
1528 break;
1529 }
9ae45f2d 1530 NOINTR(close(pty));
7460295f
MG
1531 }
1532 }
1533 deleteHashMap(childProcesses);
1534 _exit(0);
1535}
1536
d1edcc0e 1537int forkLauncher(void) {
7460295f
MG
1538 int pair[2];
1539 check(!socketpair(AF_UNIX, SOCK_STREAM, 0, pair));
1540
1541 switch (fork()) {
1542 case 0:;
1543 // If our real-uid is not "root", then we should not allow anybody to
1544 // login unauthenticated users as anyone other than their own.
1545 uid_t tmp;
1546 check(!getresuid(&restricted, &tmp, &tmp));
1547
1548 // Temporarily drop most permissions. We still retain the ability to
1549 // switch back to root, which is necessary for launching "login".
1550 lowerPrivileges();
d1edcc0e 1551 closeAllFds((int []){ pair[1] }, 1);
7460295f
MG
1552 launcherDaemon(pair[1]);
1553 fatal("exit() failed!");
1554 case -1:
1555 fatal("fork() failed!");
7460295f
MG
1556 default:
1557 NOINTR(close(pair[1]));
1558 launcher = pair[0];
d1edcc0e 1559 return launcher;
7460295f
MG
1560 }
1561}
3240f75b
MG
1562
1563void terminateLauncher(void) {
1564 if (launcher >= 0) {
1565 NOINTR(close(launcher));
1566 launcher = -1;
1567 }
1568}
This page took 4.282614 seconds and 5 git commands to generate.