/*
 * Copyright (c) 1988 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "bsd_locl.h"

RCSID("$Header: /afs/nada.kth.se/src/packages/kth-krb/SourceRepository/krb4/appl/bsd/su.c,v 1.22 1995/10/24 14:03:11 bg Exp $");

#ifndef HAVE_SETENV
static int
setenv(const char *var, const char *val, int rewrite)
{
  char *t;

  if (!rewrite && getenv(var) != 0)
    return 0;
  
  if ((t = malloc(strlen(var) + strlen(val) + 2)) == 0)
    return -1;

  strcpy(t, var);
  strcat(t, "=");
  strcat(t, val);
  if (putenv(t) == 0)
    return 0;
  else
    return -1;
}
#endif

#ifndef HAVE_SETPRIORITY
int
setpriority(int which, int who, int niceval)
{
  return 0;			/* Bloody Psoriasis */
}
#endif

#ifndef HAVE_GETPRIORITY
int
getpriority(int which, int who)
{
  return 0;			/* Bloody Psoriasis */
}
#endif

/* Handle '-' option after all the getopt options */
#define	ARGSTR	"Kflm"

int use_kerberos = 1;

static int chshell();
static char *ontty();

int
main(argc, argv)
	int argc;
	char **argv;
{
	extern char **environ;
	extern int errno, optind;
	register struct passwd *pwd;
	register char *p, **g;
	struct group *gr;
	uid_t ruid;
	int asme, ch, asthem, fastlogin, prio;
	enum { UNSET, YES, NO } iscsh = UNSET;
	char *user, *shell, *avshell, *username, *cleanenv[10], **np;
	char shellbuf[MaxPathLen], avshellbuf[MaxPathLen];

	asme = asthem = fastlogin = 0;
	while ((ch = getopt(argc, argv, ARGSTR)) != EOF)
		switch((char)ch) {
		case 'K':
			use_kerberos = 0;
			break;
		case 'f':
			fastlogin = 1;
			break;
		case 'l':
			asme = 0;
			asthem = 1;
			break;
		case 'm':
			asme = 1;
			asthem = 0;
			break;
		case '?':
		default:
			(void)fprintf(stderr, "usage: ksu [%s] [-] [login]\n",
			    ARGSTR);
			exit(1);
		}
	/* Don't handle '-' option with getopt */
	if (optind < argc && strcmp (argv[optind], "-") == 0) {
		asme = 0;
		asthem = 1;
		optind++;
	}
	argv += optind;

	errno = 0;
	prio = getpriority(PRIO_PROCESS, 0);
	if (errno)
		prio = 0;
	(void)setpriority(PRIO_PROCESS, 0, -2);
	openlog("ksu", LOG_CONS, 0);

	/* get current login name and shell */
	ruid = getuid();
	username = getlogin();
	if (username == NULL || (pwd = getpwnam(username)) == NULL ||
	    pwd->pw_uid != ruid)
		pwd = getpwuid(ruid);
	if (pwd == NULL) {
		fprintf(stderr, "ksu: who are you?\n");
		exit(1);
	}
	username = strdup(pwd->pw_name);
	if (asme)
		if (pwd->pw_shell && *pwd->pw_shell)
			shell = strcpy(shellbuf,  pwd->pw_shell);
		else {
			shell = _PATH_BSHELL;
			iscsh = NO;
		}

	/* get target login information, default to root */
	user = *argv ? *argv : "root";
	np = *argv ? argv : argv-1;

	pwd = getpwnam(user);
	if (pwd == NULL){
		fprintf(stderr, "ksu: unknown login %s\n", user);
		exit(1);
	}

	if (!use_kerberos || kerberos(username, user, pwd->pw_uid)) {
#ifndef PASSWD_FALLBACK
	  fprintf(stderr, "ksu: won't use /etc/passwd authentication\n");
	  exit(1);
#endif
	  /* only allow those in group zero to su to root. */
	  if (pwd->pw_uid == 0 && (gr = getgrgid((gid_t)0)))
	    for (g = gr->gr_mem;; ++g) {
	      if (!*g) {
#if 1
		/* if group 0 is empty or only contains root su is still ok. */
		if (gr->gr_mem[0] == 0)
		  break;		/* group 0 is empty */
		if (gr->gr_mem[1] == 0 && strcmp(gr->gr_mem[0], "root") == 0)
		  break;		/* only root in group 0 */
#endif
		fprintf(stderr,
			"ksu: you are not in the correct group to su %s.\n",
			user);
		exit(1);
	      }
	      if (!strcmp(username, *g))
		break;
	    }
	  /* if target requires a password, verify it */
	  if (*pwd->pw_passwd) {
	    p = getpass("Password:");
	    if (strcmp(pwd->pw_passwd, crypt(p, pwd->pw_passwd))) {
	      fprintf(stderr, "Sorry\n");
	      syslog(LOG_AUTH|LOG_WARNING,
		     "BAD SU %s to %s%s", username,
		     user, ontty());
	      exit(1);
	    }
	  }
	}
	if (asme) {
		/* if asme and non-standard target shell, must be root */
		if (!chshell(pwd->pw_shell) && ruid) {
			(void)fprintf(stderr,
				"ksu: permission denied (shell '%s'not in /etc/shells).\n", pwd->pw_shell);
			exit(1);
		}
	} else if (pwd->pw_shell && *pwd->pw_shell) {
		shell = pwd->pw_shell;
		iscsh = UNSET;
	} else {
		shell = _PATH_BSHELL;
		iscsh = NO;
	}

	if ((p = strrchr(shell, '/')) != 0)
		avshell = p+1;
	else
		avshell = shell;

	/* if we're forking a csh, we want to slightly muck the args */
	if (iscsh == UNSET)
		iscsh = strcmp(avshell, "csh") ? NO : YES;

	/* set permissions */
	

	if (setgid(pwd->pw_gid) < 0) {
		perror("ksu: setgid");
		exit(1);
	}
	if (initgroups(user, pwd->pw_gid)) {
		(void)fprintf(stderr, "ksu: initgroups failed.\n");
		exit(1);
	}

	if (setuid(pwd->pw_uid) < 0) {
		perror("ksu: setuid");
		exit(1);
	}

	if (!asme) {
		if (asthem) {
		  char *k=getenv("KRBTKFILE");
		  char *t = getenv("TERM");
		  cleanenv[0] = NULL;
		  environ = cleanenv;
		  setenv("PATH", _PATH_DEFPATH, 1);
		  if(t)
		    setenv("TERM", t, 1);
		  if(k)
		    setenv("KRBTKFILE", k, 1);
		  if (chdir(pwd->pw_dir) < 0) {
		    fprintf(stderr, "ksu: no directory\n");
		    exit(1);
		  }
		}
		if (asthem || pwd->pw_uid)
			(void)setenv("USER", pwd->pw_name, 1);
		(void)setenv("HOME", pwd->pw_dir, 1);
		(void)setenv("SHELL", shell, 1);
	}

	if (iscsh == YES) {
		if (fastlogin)
			*np-- = "-f";
		if (asme)
			*np-- = "-m";
	}

	if (asthem) {
		avshellbuf[0] = '-';
		strcpy(avshellbuf+1, avshell);
		avshell = avshellbuf;
	} else if (iscsh == YES) {
		/* csh strips the first character... */
		avshellbuf[0] = '_';
		strcpy(avshellbuf+1, avshell);
		avshell = avshellbuf;
	}
			
	*np = avshell;

	if (ruid != 0)
		syslog(LOG_NOTICE|LOG_AUTH, "%s to %s%s",
		    username, user, ontty());

	(void)setpriority(PRIO_PROCESS, 0, prio);

	if (k_hasafs()) {
		int code;
		if (k_setpag() != 0)
			perror("ksu: setpag");
		code = k_afsklog(0, 0);
		if (code != KSUCCESS)
		    fprintf(stderr, "ksu: afsklog: %s\n", krb_err_txt[code]);
	}

	execv(shell, np);
	(void)fprintf(stderr, "ksu: %s not found.\n", shell);
	if (getuid() == 0) {
		execv(_PATH_BSHELL, np);
		(void)fprintf(stderr, "ksu: %s not found.\n", _PATH_BSHELL);
	}
	exit(1);
}

static int
chshell(sh)
	char *sh;
{
	register char *cp;

	while ((cp = getusershell()) != NULL)
		if (!strcmp(cp, sh))
			return (1);
	return (0);
}

static char *
ontty()
{
	char *p;
	static char buf[MaxPathLen + 4];

	buf[0] = 0;
	if ((p = ttyname(STDERR_FILENO)) != 0)
		sprintf(buf, " on %s", p);
	return (buf);
}

int
kerberos(username, user, uid)
	char *username, *user;
	int uid;
{
	KTEXT_ST ticket;
	AUTH_DAT authdata;
	struct hostent *hp;
	int kerno;
	u_long faddr;
	char lrealm[REALM_SZ], krbtkfile[MaxPathLen];
	char hostname[MaxHostNameLen], savehost[MaxHostNameLen];

	if (krb_get_lrealm(lrealm, 1) != KSUCCESS)
		return (1);
	if (koktologin(username, lrealm, user) && !uid) {
		(void)fprintf(stderr, "ksu: not in %s's ACL.\n", user);
		return (1);
	}
	sprintf(krbtkfile, "%s_%s_to_%s", TKT_ROOT, username, user);

	setenv("KRBTKFILE", krbtkfile, 1);
	krb_set_tkt_string(krbtkfile);
	/*
	 * Set real as well as effective ID to 0 for the moment,
	 * to make the kerberos library do the right thing.
	 */
#if 1
	if (k_setreuid(uid, 0) < 0) {
		perror("ksu: setuid");
		return (1);
	}
#else
	if (setuid(0) < 0) {
		perror("ksu: setuid");
		return (1);
	}
#endif
	/*
	 * Little trick here -- if we are su'ing to root,
	 * we need to get a ticket for "xxx.root", where xxx represents
	 * the name of the person su'ing.  Otherwise (non-root case),
	 * we need to get a ticket for "yyy.", where yyy represents
	 * the name of the person being su'd to, and the instance is null
	 *
	 * We should have a way to set the ticket lifetime,
	 * with a system default for root.
	 */
	printf("User's %s%s%s@%s ",
	       (uid == 0 ? username : user),
	       (uid == 0 ? "." : ""),
	       (uid == 0 ? "root" : ""),
	       lrealm);
	fflush(stdout);
	kerno = krb_get_pw_in_tkt((uid == 0 ? username : user),
		(uid == 0 ? "root" : ""), lrealm,
	    	"krbtgt", lrealm, DEFAULT_TKT_LIFE, 0);

	if (kerno != KSUCCESS) {
		if (kerno == KDC_PR_UNKNOWN) {
			fprintf(stderr, "principal unknown: %s.%s@%s\n",
				(uid == 0 ? username : user),
				(uid == 0 ? "root" : ""), lrealm);
			return (1);
		}
		(void)fprintf(stderr, "ksu: unable to su: %s\n",
		    krb_err_txt[kerno]);
		syslog(LOG_NOTICE|LOG_AUTH,
		    "BAD KSU: %s to %s%s: %s",
		    username, user, ontty(), krb_err_txt[kerno]);
		return (1);
	}

	if (chown(krbtkfile, uid, -1) < 0) {
		perror("ksu: chown:");
		(void)unlink(krbtkfile);
		return (1);
	}

	(void)setpriority(PRIO_PROCESS, 0, -2);

	if (gethostname(hostname, sizeof(hostname)) == -1) {
		perror("ksu: gethostname");
		dest_tkt();
		return (1);
	}

	(void)strncpy(savehost, krb_get_phost(hostname), sizeof(savehost));
	savehost[sizeof(savehost) - 1] = '\0';

	kerno = krb_mk_req(&ticket, "rcmd", savehost, lrealm, 33);

	if (kerno == KDC_PR_UNKNOWN) {
		(void)fprintf(stderr, "Warning: TGT not verified.\n");
		syslog(LOG_NOTICE|LOG_AUTH,
		    "%s to %s%s, TGT not verified (%s); %s.%s not registered?",
		    username, user, ontty(), krb_err_txt[kerno],
		    "rcmd", savehost);
#ifdef KLOGIN_PARANOID
		/*
		 * if the "VERIFY_SERVICE" doesn't exist in the KDC
		 * for this host, * don't allow kerberos login, also
		 * log the error condition.
		 */
		(void)fprintf(stderr, "Trying local password!\n");
		return (1);
#endif
	} else if (kerno != KSUCCESS) {
		(void)fprintf(stderr, "Unable to use TGT: %s\n",
		    krb_err_txt[kerno]);
		syslog(LOG_NOTICE|LOG_AUTH, "failed ksu: %s to %s%s: %s",
		    username, user, ontty(), krb_err_txt[kerno]);
		dest_tkt();
		return (1);
	} else {
		if (!(hp = gethostbyname(hostname))) {
			(void)fprintf(stderr, "ksu: can't get addr of %s\n",
			    hostname);
			dest_tkt();
			return (1);
		}
		(void)bcopy((char *)hp->h_addr, (char *)&faddr, sizeof(faddr));

		if ((kerno = krb_rd_req(&ticket, "rcmd", savehost, faddr,
		    &authdata, "")) != KSUCCESS) {
			(void)fprintf(stderr,
			    "ksu: unable to verify rcmd ticket: %s\n",
			    krb_err_txt[kerno]);
			syslog(LOG_NOTICE|LOG_AUTH,
			    "failed ksu: %s to %s%s: %s", username,
			     user, ontty(), krb_err_txt[kerno]);
			dest_tkt();
			return (1);
		}
	}
	fprintf(stderr, "Don't forget to kdestroy before exiting the shell.\n");
	return (0);
}

int
koktologin(name, realm, toname)
	char *name, *realm, *toname;
{
	register AUTH_DAT *kdata;
	AUTH_DAT kdata_st;

	kdata = &kdata_st;
	bzero((caddr_t) kdata, sizeof(*kdata));
	(void)strcpy(kdata->pname, name);
	(void)strcpy(kdata->pinst,
	    ((strcmp(toname, "root") == 0) ? "root" : ""));
	(void)strcpy(kdata->prealm, realm);
	return (kuserok(kdata, toname));
}
