/*
 *	$Source: /mit/kerberos/src/appl/bsd/RCS/rshd.c,v $
 *	$Author: jtkohl $
 *	$Header: rshd.c,v 4.13 89/05/17 10:57:22 jtkohl Exp $
 */

#ifndef lint
static char rcsid_rshd_c[] =
"$Header: rshd.c,v 4.13 89/05/17 10:57:22 jtkohl Exp $";
#endif lint

/*
 * Copyright (c) 1983 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that the above copyright notice and this paragraph are
 * duplicated in all such forms and that any documentation,
 * advertising materials, and other materials related to such
 * distribution and use acknowledge that the software was developed
 * by the University of California, Berkeley.  The name of the
 * University may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1983 The Regents of the University of California.\n\
 All rights reserved.\n";
#endif /* not lint */

#ifndef lint
static char sccsid[] = "@(#)rshd.c	5.12 (Berkeley) 9/12/88";
#endif /* not lint */

/*
 * remote shell server:
 *	remuser\0
 *	locuser\0
 *	command\0
 *	data
 */
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/time.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <stdio.h>
#include <errno.h>
#include <pwd.h>
#include <signal.h>
#include <netdb.h>
#include <syslog.h>

#ifdef KERBEROS
#include <krb.h>

int ksh = 0;
char *strsave();
#endif KERBEROS

#ifdef ATHENA
#define DEFAULT "default"     /* account name for default network usage */
#endif ATHENA

int	errno;
char	*index(), *rindex(), *strncat();
/*VARARGS1*/
int	error();

/*ARGSUSED*/
main(argc, argv)
	int argc;
	char **argv;
{
#if defined(BSD) && BSD >= 43
	struct linger linger;
#endif
	int on = 1, fromlen;
	struct sockaddr_in from;

#ifdef KERBEROS
	ksh = (strcmp(*argv,"kshd")==0);
#endif KERBEROS
#ifndef LOG_ODELAY /* 4.2 syslog */
	openlog("rsh", LOG_PID);
#else
	openlog("rsh", LOG_PID | LOG_ODELAY, LOG_DAEMON);
#endif /* 4.2 syslog */
	fromlen = sizeof (from);
	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
		fprintf(stderr, "%s: ", argv[0]);
		perror("getpeername");
		_exit(1);
	}
	if (setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
	    sizeof (on)) < 0)
		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
#if defined(BSD) && BSD >= 43
	linger.l_onoff = 1;
	linger.l_linger = 60;			/* XXX */
	if (setsockopt(0, SOL_SOCKET, SO_LINGER, (char *)&linger,
	    sizeof (linger)) < 0)
		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
#endif
	doit(dup(0), &from);
}

char	username[20] = "USER=";
char	homedir[64] = "HOME=";
char	shell[64] = "SHELL=";
char	*envinit[] =
	    {homedir, shell, "PATH=:/usr/ucb:/bin:/usr/bin", username, 0};
char	**environ;

doit(f, fromp)
	int f;
	struct sockaddr_in *fromp;
{
	char cmdbuf[NCARGS+1], *cp;
	char locuser[16], remuser[16];
	struct passwd *pwd;
	int s;
	struct hostent *hp;
	char *hostname;
	short port;
	int pv[2], pid, cc;
	long ready, readfrom;
	char buf[BUFSIZ], sig;
	int one = 1;
#ifdef ATHENA
	int def = 0;
#endif ATHENA
#ifdef KERBEROS
	AUTH_DAT *kdata = (AUTH_DAT *)NULL;
	KTEXT ticket = (KTEXT)NULL;
	char instance[INST_SZ], version[9], *h_name;
	/* need to save the sockaddr_in for krb_recvauth; *fromp is reused
	   before then */
	struct sockaddr_in fromaddr;
	int rc;
	long authoptions;

	fromaddr = *fromp; 
#endif KERBEROS

	(void) signal(SIGINT, SIG_DFL);
	(void) signal(SIGQUIT, SIG_DFL);
	(void) signal(SIGTERM, SIG_DFL);
#ifdef DEBUG
	{ int t = open("/dev/tty", 2);
	  if (t >= 0) {
		ioctl(t, TIOCNOTTY, (char *)0);
		(void) close(t);
	  }
	}
#endif
	fromp->sin_port = ntohs((u_short)fromp->sin_port);
	if (fromp->sin_family != AF_INET) {
		syslog(LOG_ERR, "malformed from address\n");
		exit(1);
	}
#ifdef KERBEROS
	if (!ksh && (fromp->sin_port >= IPPORT_RESERVED ||
	    fromp->sin_port < IPPORT_RESERVED/2)) {
#else
	if (fromp->sin_port >= IPPORT_RESERVED ||
	    fromp->sin_port < IPPORT_RESERVED/2) {
#endif KERBEROS
		syslog(LOG_NOTICE, "connection from bad port\n");
		exit(1);
	}
	(void) alarm(60);
	port = 0;
	for (;;) {
		char c;
		if ((cc = read(f, &c, 1)) != 1) {
			if (cc < 0)
				syslog(LOG_NOTICE, "read: %m");
			shutdown(f, 1+1);
			exit(1);
		}
		if (c == 0)
			break;
		port = port * 10 + c - '0';
	}
	(void) alarm(0);
	if (port != 0) {
		int lport = IPPORT_RESERVED - 1;
		s = rresvport(&lport);
		if (s < 0) {
			syslog(LOG_ERR, "can't get stderr port: %m");
			exit(1);
		}
#ifdef KERBEROS
		if (!ksh && port >= IPPORT_RESERVED) {
#else
		if (port >= IPPORT_RESERVED) {
#endif KERBEROS
			syslog(LOG_ERR, "2nd port not reserved\n");
			exit(1);
		}
		fromp->sin_port = htons((u_short)port);
		if (connect(s, (struct sockaddr *)fromp, sizeof (*fromp)) < 0) {
			syslog(LOG_INFO, "connect second port: %m");
			exit(1);
		}
	}
	dup2(f, 0);
	dup2(f, 1);
	dup2(f, 2);
	hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof (struct in_addr),
		fromp->sin_family);
	if (hp)
		hostname = hp->h_name;
	else
		hostname = inet_ntoa(fromp->sin_addr);
#ifdef KERBEROS
	if (ksh) {
		h_name = strsave( hp->h_name );
		kdata = (AUTH_DAT *)malloc(sizeof(AUTH_DAT));
		ticket = (KTEXT) malloc(sizeof(KTEXT_ST));
		authoptions = 0L;
		strcpy(instance, "*");
		version[8] = '\0';
		if (rc=krb_recvauth(authoptions, f, ticket, "rcmd",
				    instance, &fromaddr,
				    (struct sockaddr_in *) 0,
				    kdata,"", (bit_64 *) 0, version)) {
			error("Kerberos rsh or rcp failed: %s\n",
				krb_err_txt[rc]);
			exit(1);
		}
		free(h_name);
		h_name = (char *)NULL;
	} else {
		getstr(remuser, sizeof(remuser), "remuser");
	}
#else
	getstr(remuser, sizeof(remuser), "remuser");
#endif KERBEROS
	getstr(locuser, sizeof(locuser), "locuser");
	getstr(cmdbuf, sizeof(cmdbuf), "command");
	setpwent();
	pwd = getpwnam(locuser);
	if (pwd == NULL) {
#ifdef ATHENA
		strcpy (locuser, DEFAULT);
		pwd = getpwnam(locuser);
		if (pwd == NULL) {
			error("Login incorrect.\n");
			exit(1);
		} else {
			def = 1;
			sprintf(buf,"Remote user %s@%s logged in as default\n",
				remuser, hp->h_name);
			syslog (LOG_INFO, buf);
		}
#else
		error("Login incorrect.\n");
		exit(1);
#endif ATHENA
	}
	endpwent();
	if (chdir(pwd->pw_dir) < 0) {
		(void) chdir("/");
#ifdef notdef
		error("No remote directory.\n");
		exit(1);
#endif
	}
#ifdef KERBEROS
	if (pwd->pw_passwd != 0 && *pwd->pw_passwd != '\0') {
		if (ksh) {
			if ( kuserok(kdata,locuser) ) {
				error("Permission denied.\r\n");
				exit(1);
			}
		} else {
			if (ruserok(hp->h_name, pwd->pw_uid == 0,
#ifdef ATHENA
				def ? locuser : remuser, locuser) < 0)
#else
				remuser, locuser) < 0)
#endif
			       {
				error("Permission denied.\n");
				exit(1);
			}
		}
	}
#else
	if (pwd->pw_passwd != 0 && *pwd->pw_passwd != '\0' &&
	    ruserok(hostname, pwd->pw_uid == 0, remuser, locuser) < 0) {
		error("Permission denied.\n");
		exit(1);
	}
#endif KERBEROS
	if (pwd->pw_uid && !access("/etc/nologin", F_OK)) {
		error("Logins currently disabled.\n");
		exit(1);
	}
	(void) write(2, "\0", 1);
	if (port) {
		if (pipe(pv) < 0) {
			error("Can't make pipe.\n");
			exit(1);
		}
		pid = fork();
		if (pid == -1)  {
			error("Try again.\n");
			exit(1);
		}
		if (pid) {
			(void) close(0); (void) close(1); (void) close(2);
			(void) close(f); (void) close(pv[1]);
			readfrom = (1L<<s) | (1L<<pv[0]);
			ioctl(pv[0], FIONBIO, (char *)&one);
			/* should set s nbio! */
			do {
				ready = readfrom;
				if (select(16, &ready, (fd_set *)0,
				    (fd_set *)0, (struct timeval *)0) < 0)
					break;
				if (ready & (1L<<s)) {
					if (read(s, &sig, 1) <= 0)
						readfrom &= ~(1L<<s);
					else
						killpg(pid, sig);
				}
				if (ready & (1L<<pv[0])) {
					errno = 0;
					cc = read(pv[0], buf, sizeof (buf));
					if (cc <= 0) {
						shutdown(s, 1+1);
						readfrom &= ~(1L<<pv[0]);
					} else
						(void) write(s, buf, cc);
				}
			} while (readfrom);
			exit(0);
		}
		setpgrp(0, getpid());
		(void) close(s); (void) close(pv[0]);
		dup2(pv[1], 2);
		(void) close(pv[1]);
	}
	if (*pwd->pw_shell == '\0')
		pwd->pw_shell = "/bin/sh";
	(void) close(f);
	(void) setgid((gid_t)pwd->pw_gid);
	initgroups(pwd->pw_name, pwd->pw_gid);
	(void) setuid((uid_t)pwd->pw_uid);
	environ = envinit;
	strncat(homedir, pwd->pw_dir, sizeof(homedir)-6);
	strncat(shell, pwd->pw_shell, sizeof(shell)-7);
	strncat(username, pwd->pw_name, sizeof(username)-6);
	cp = rindex(pwd->pw_shell, '/');
	if (cp)
		cp++;
	else
		cp = pwd->pw_shell;
	execl(pwd->pw_shell, cp, "-c", cmdbuf, 0);
	perror(pwd->pw_shell);
	exit(1);
}

/*VARARGS1*/
error(fmt, a1, a2, a3)
	char *fmt;
	int a1, a2, a3;
{
	char buf[BUFSIZ];

	buf[0] = 1;
	(void) sprintf(buf+1, fmt, a1, a2, a3);
	(void) write(2, buf, strlen(buf));
}

getstr(buf, cnt, err)
	char *buf;
	int cnt;
	char *err;
{
	char c;

	do {
		if (read(0, &c, 1) != 1)
			exit(1);
		*buf++ = c;
		if (--cnt == 0) {
			error("%s too long\n", err);
			exit(1);
		}
	} while (c != 0);
}
