/*
 * 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[] = "@(#)rexecd.c	5.7 (Berkeley) 1/4/89";
#endif /* not lint */

#include "sys_defs.h"

#ifdef SYSV4
#define BSD_COMP        /* for sys/ioctl.h */
#endif

#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/time.h>

#include <netinet/in.h>

#include <unistd.h>
#include <stdlib.h>

#include <stdio.h>
#include <errno.h>
#include <pwd.h>
#include <signal.h>
#include <netdb.h>
#include <arpa/inet.h>

#include <string.h>

extern	errno;
struct	passwd *getpwnam();
/*VARARGS1*/
int	error();

#ifdef NO_SETSID
#define setsid()	setpgrp(0,0)
#endif

#if !defined(NCARGS)
#define NCARGS 10240
#endif

#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 256
#endif

#include <syslog.h>

#define _PATH_FTPUSERS        "/etc/ftpusers"	/* not in 44bsd paths.h */

#ifdef SYSV_SHADOW
#include "sysv4-shadow.h"
#endif

char	remote[MAXHOSTNAMELEN];

/*
 * remote execute server:
 *	username\0
 *	password\0
 *	command\0
 *	data
 */
/*ARGSUSED*/
main(argc, argv)
	int argc;
	char **argv;
{
	struct sockaddr_in from;
	int fromlen;
	struct hostent *hp;

	fromlen = sizeof (from);
	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
		fprintf(stderr, "%s: ", argv[0]);
		perror("getpeername");
		exit(1);
	}
#ifdef LOG_AUTH
	(void) openlog(argv[0], LOG_PID, FACILITY);	/* BSD43 syslog */
#else
	(void) openlog(argv[0], LOG_PID);		/* old syslog */
#endif
	hp = gethostbyaddr((char *) &from.sin_addr, sizeof(from.sin_addr),
			   from.sin_family);
	strncpy(remote, hp != 0 ? hp->h_name : inet_ntoa(from.sin_addr),
		sizeof(remote) - 1);

	doit(0, &from);
}

char	username[100] = "USER=";
char	homedir[MAXPATHLEN + sizeof("HOME=")] = "HOME=";
char	shell[MAXPATHLEN + sizeof("SHELL=")] = "SHELL=";
#ifdef SYSV_ENV
char	path[] = "PATH=/bin:/usr/bin:";
#else /* SYSV_ENV */
char	path[] = "PATH=/usr/ucb:/bin:/usr/bin:";
char	**environ;
#endif /* SYSV_ENV */

doit(f, fromp)
	int f;
	struct sockaddr_in *fromp;
{
	char cmdbuf[NCARGS+1], *cp, *namep;
#ifdef SKEY
	char *skey_crypt();
	int permit_passwd;
#endif /* SKEY */
	char user[100], pass[100];
	struct passwd *pwd;
	int s;
	u_short port;
	int pv[2], pid, nfd, cc;
	fd_set ready, readfrom;
	char buf[BUFSIZ], sig;
	int one = 1;
#ifdef RESTRICT_FTP
	FILE* fp;
#endif

	(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
	dup2(f, 0);
	dup2(f, 1);
	dup2(f, 2);
	(void) alarm(60);
	port = 0;
	for (;;) {
		char c;
		if (read(f, &c, 1) != 1)
			exit(1);
		if (c == 0)
			break;
		port = port * 10 + c - '0';
	}
	(void) alarm(0);
	if (port != 0) {
		s = socket(AF_INET, SOCK_STREAM, 0);
		if (s < 0)
			exit(1);
		(void) alarm(60);
		fromp->sin_port = htons(port);
		if (connect(s, (struct sockaddr *)fromp, sizeof (*fromp)) < 0)
			exit(1);
		(void) alarm(0);
	}
	getstr(user, sizeof(user), "username");
	getstr(pass, sizeof(pass), "password");
	getstr(cmdbuf, sizeof(cmdbuf), "command");
	setpwent();
	pwd = getpwnam(user);
	if (pwd == NULL) {
		/* Log failed attempts. */
		log(LOG_ERR, "LOGIN FAILURE from %h, %u",
		       remote, user, cmdbuf);
		error("Login incorrect.\n");
		exit(1);
	}
	endpwent();
	if (*pwd->pw_passwd != '\0') {
#ifdef SKEY
		permit_passwd = skeyaccess(pwd, (char *) 0, remote,
					   inet_ntoa(fromp->sin_addr));
		namep = skey_crypt(pass, pwd->pw_passwd, pwd, permit_passwd);
#else /* SKEY */
		namep = crypt(pass, pwd->pw_passwd);
#endif /* SKEY */
		if (strcmp(namep, pwd->pw_passwd)) {
			/* Log failed attempts. */
			log(LOG_ERR, "LOGIN FAILURE from %h, %u",
			       remote, user, cmdbuf);
			error("Login incorrect.\n");
			exit(1);
		}
	}
	/* Disallow access to privileged accounts. */
	if (pwd->pw_uid == 0) {
		error("Login incorrect.\n");
		log(LOG_ERR, "%u LOGIN REFUSED from %h",
		       remote, user, cmdbuf);
		exit(1);
	}
#ifdef RESTRICT_FTP
	/* Disallow access to accounts in /etc/ftpusers. */
	if ((fp = fopen(_PATH_FTPUSERS, "r")) != NULL) {
	    while (fgets(buf, sizeof (buf), fp) != NULL) {
		if ((cp = strchr(buf, '\n')) != NULL)
			*cp = '\0';
		if (strcmp(buf, pwd->pw_name) == 0) {
			error("Login incorrect.\n");
			log(LOG_ERR, "%u LOGIN REFUSED from %h",
			       remote, user, cmdbuf);
			exit(1);
		}
	    }
	}
	(void) fclose(fp);
#endif /* RESTRICT_FTP */
	/* Log successfull attempts. */
	log(LOG_INFO, "login from %h as %u", remote, user, cmdbuf);
	if (chdir(pwd->pw_dir) < 0) {
		error("No remote directory.\n");
		exit(1);
	}
	(void) write(2, "\0", 1);
	if (port) {
		(void) pipe(pv);
		pid = fork();
		if (pid == -1)  {
			error("Try again.\n");
			exit(1);
		}
		if (pv[0] > s)
			nfd = pv[0];
		else
			nfd = s;
		nfd++;
		if (pid) {
			(void) close(0); (void) close(1); (void) close(2);
			(void) close(f); (void) close(pv[1]);
			FD_ZERO(&readfrom);
			FD_SET(s, &readfrom);
			FD_SET(pv[0], &readfrom);
			ioctl(pv[1], FIONBIO, (char *)&one);
			/* should set s nbio! */
			do {
				ready = readfrom;
				(void) select(nfd, &ready, (fd_set *)0,
				    (fd_set *)0, (struct timeval *)0);
				if (FD_ISSET(s, &ready)) {
					if (read(s, &sig, 1) <= 0)
						FD_CLR(s, &readfrom);
					else
						kill(-pid, sig);
				}
				if (FD_ISSET(pv[0], &ready)) {
					cc = read(pv[0], buf, sizeof (buf));
					if (cc <= 0) {
						shutdown(s, 1+1);
						FD_CLR(pv[0], &readfrom);
					} else
						(void) write(s, buf, cc);
				}
			} while (FD_ISSET(s, &readfrom) || FD_ISSET(pv[0], &readfrom));
			exit(0);
		}
		setsid();
		(void) close(s); (void)close(pv[0]);
		dup2(pv[1], 2);
		close(pv[1]);
	}
	if (*pwd->pw_shell == '\0')
		pwd->pw_shell = "/bin/sh";
	if (f > 2)
		(void) close(f);
	if (setgid((gid_t)pwd->pw_gid)) {
		perror("setgid");
		exit(1);
	}
	initgroups(pwd->pw_name, pwd->pw_gid);
	if (setuid((uid_t)pwd->pw_uid)) {
		perror("setuid");
		exit(1);
	}
#ifndef SYSV_ENV /* Preserve TZ etc. */
	if (environ)
		environ[0] = 0;
#endif
	strncat(homedir, pwd->pw_dir, sizeof(homedir)-sizeof("HOME="));
	strncat(shell, pwd->pw_shell, sizeof(shell)-sizeof("SHELL="));
	strncat(username, pwd->pw_name, sizeof(username)-sizeof("USER="));
	putenv(homedir);
	putenv(shell);
	putenv(username);
	putenv(path);
	cp = strrchr(pwd->pw_shell, '/');
	if (cp)
		cp++;
	else
		cp = pwd->pw_shell;
	execl(pwd->pw_shell, cp, "-c", cmdbuf, (char *) 0);
	perror(pwd->pw_shell);
	exit(1);
}

/*VARARGS1*/
error(fmt, a1, a2, a3)
	char *fmt;
	char *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);
}

log(level, what, host, user, command)
	int             level;
	char           *what;
	char           *host;
	char           *user;
	char           *command;
{
	char            buf[BUFSIZ];
	char           *op = buf;
	char           *cp;

	for (cp = what; *cp; cp++) {
		if (*cp == '%') {
			if (cp[1] == 'h') {
				sprintf(op, "%.100s", host);
				op += strlen(op);
				cp++;
			} else if (cp[1] == 'u') {
				sprintf(op, "%.100s", user);
				op += strlen(op);
				cp++;
			} else if (cp[1] == '%') {
				*op++ = *cp++;
			}
		} else {
			*op++ = *cp;
		}
	}
#ifdef LOG_COMMANDS
	sprintf(op, " (%.100s)", command);
#else
	*op = 0;
#endif
	syslog(level, "%s", buf);
}
