[comp.sources.misc] Setgrp - spawn a process into a new group

jfh@killer.UUCP (John Haugh) (06/29/87)

I wrote this to handle a problem that a poster asked about in
comp.unix.questions.  Hope you like it as much as we do.  Must
be run set-uid (boo) and probably is only useful on System V.

Basically, the program checks the /etc/group file and sees
if you are in the group.  Probably not totally sexure, mostly
because it ignores passwords!  But then its free ...

- john.
------------------------- cut here ----------------------

#include <grp.h>
#include <pwd.h>
#include <stdio.h>

struct	passwd	*getpwuid ();
struct	group	*getgrnam ();

main  (argc, argv)
int	argc;
char	**argv;
{
	char	username[20];
	char	groupname[20];
	struct	passwd	*ppwd;
	struct	group	*pgrp;
	int	i;

	if (argc < 3) {
		fprintf (stderr, "usage: %s group command [ args ... ]\n", arg[0]);
		exit (1);
	}
	if (! (ppwd = getpwuid (getuid ()))) {
		fprintf (stderr, "Error reading password file\n");
		exit (1);
	}
	strncpy (username, ppwd->pw_name, sizeof (username));
	strncpy (groupname, argv[1], sizeof (groupname));
	if (! (pgrp = getgrnam (groupname))) {
		fprintf (stderr, "Nonexistent group: %s\n", groupname);
		exit (1);
	}
	for (i = 0;pgrp->gr_mem[i] != (char *) 0;i++) {
		if (strncmp (username, pgrp->gr_mem[i], sizeof (username)))
			continue;
		else
			break;
	}
	if (pgrp->gr_mem[i] == (char *) 0) {
		fprintf (stderr, "Permission denied\n");
		exit (1);
	}
	setgid (pgrp->gr_gid);
	setuid (getuid ());

	execvp (argv[2], &argv[2]);

	perror (argv[2]);
	exit (1);
}