/*
 * SPDX-FileCopyrightText: 1990 - 1994, Julianne Frances Haugh
 * SPDX-FileCopyrightText: 2006       , Tomasz Kłoczko
 * SPDX-FileCopyrightText: 2006       , Jonas Meurer
 * SPDX-FileCopyrightText: 2007 - 2011, Nicolas François
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "config.h"

#ident "$Id$"

#include <fcntl.h>
#include <getopt.h>
#include <pwd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include "atoi/a2i.h"
#include "defines.h"
#include "groupio.h"
#include "io/fprintf.h"
#include "nscd.h"
#include "sssd.h"
#include "prototypes.h"
#ifdef	SHADOWGRP
#include "sgroupio.h"
#endif
/*@-exitarg@*/
#include "exitcodes.h"
#include "io/fgets/fgets.h"
#include "shadow/gshadow/sgrp.h"
#include "shadowlog.h"
#include "string/strcmp/streq.h"
#include "string/strtok/stpsep.h"

/*
 * Structures
 */
struct option_flags {
	bool chroot;
};

/*
 * Global variables
 */
static const char Prog[] = "chgpasswd";
static bool eflg   = false;
static bool sflg   = false;

static /*@null@*//*@observer@*/const char *crypt_method = NULL;
#define cflg (NULL != crypt_method)
static long sha_rounds = 5000;
#ifdef USE_BCRYPT
static long bcrypt_rounds = 13;
#endif
#ifdef USE_YESCRYPT
static long yescrypt_cost = 5;
#endif

#ifdef SHADOWGRP
static bool is_shadow_grp;
static bool sgr_locked = false;
#endif
static bool gr_locked = false;

/* local function prototypes */
NORETURN static void fail_exit (int code, bool process_selinux);
NORETURN static void usage (int status);
static void process_flags (int argc, char **argv, struct option_flags *flags);
static void check_flags (void);
static void open_files (bool process_selinux);
static void close_files(const struct option_flags *flags);

/*
 * fail_exit - exit with a failure code after unlocking the files
 */
static void fail_exit (int code, bool process_selinux)
{
	if (gr_locked) {
		if (gr_unlock (process_selinux) == 0) {
			eprintf(_("%s: failed to unlock %s\n"), Prog, gr_dbname());
			SYSLOG(LOG_ERR, "failed to unlock %s", gr_dbname());
			/* continue */
		}
	}

#ifdef	SHADOWGRP
	if (sgr_locked) {
		if (sgr_unlock (process_selinux) == 0) {
			eprintf(_("%s: failed to unlock %s\n"), Prog, sgr_dbname());
			SYSLOG(LOG_ERR, "failed to unlock %s", sgr_dbname());
			/* continue */
		}
	}
#endif

	exit (code);
}

/*
 * usage - display usage message and exit
 */
NORETURN
static void
usage (int status)
{
	FILE *usageout = (E_SUCCESS != status) ? stderr : stdout;
	(void) fprintf (usageout,
	                _("Usage: %s [options]\n"
	                  "\n"
	                  "Options:\n"),
	                Prog);
	(void) fprintf (usageout,
	                _("  -c, --crypt-method METHOD     the crypt method (one of %s)\n"),
	                "NONE SHA256 SHA512"
#if defined(USE_BCRYPT)
	                " BCRYPT"
#endif
#if defined(USE_YESCRYPT)
	                " YESCRYPT"
#endif
	               );
	(void) fputs (_("  -e, --encrypted               supplied passwords are encrypted\n"), usageout);
	(void) fputs (_("  -h, --help                    display this help message and exit\n"), usageout);
	(void) fputs (_("  -R, --root CHROOT_DIR         directory to chroot into\n"), usageout);
	(void) fputs (_("  -s, --sha-rounds              number of rounds for the SHA, BCRYPT\n"
	                "                                or YESCRYPT crypt algorithms\n"),
	              usageout);
	(void) fputs ("\n", usageout);

	exit (status);
}

/*
 * process_flags - parse the command line options
 *
 *	It will not return if an error is encountered.
 */
static void process_flags (int argc, char **argv, struct option_flags *flags)
{
	int c;
	int bad_s;
	static struct option long_options[] = {
		{"crypt-method", required_argument, NULL, 'c'},
		{"encrypted",    no_argument,       NULL, 'e'},
		{"help",         no_argument,       NULL, 'h'},
		{"root",         required_argument, NULL, 'R'},
		{"sha-rounds",   required_argument, NULL, 's'},
		{NULL, 0, NULL, '\0'}
	};
	while (-1 != (c = getopt_long(argc, argv, "c:ehR:s:", long_options, NULL)))
	{
		switch (c) {
		case 'c':
			crypt_method = optarg;
			break;
		case 'e':
			eflg = true;
			break;
		case 'h':
			usage (E_SUCCESS);
			/*@notreached@*/break;
		case 'R': /* no-op, handled in process_root_flag () */
			flags->chroot = true;
			break;
		case 's':
			sflg = true;
			bad_s = 0;

			if (!crypt_method) {
				eprintf(_("%s: no crypt method defined\n"),
				         Prog);
				usage (E_USAGE);
			}
			if (  (   (streq(crypt_method, "SHA256") || streq(crypt_method, "SHA512"))
			       && (-1 == str2sl(&sha_rounds, optarg)))) {
				bad_s = 1;
			}
#if defined(USE_BCRYPT)
			if (  (   streq(crypt_method, "BCRYPT")
			       && (-1 == str2sl(&bcrypt_rounds, optarg)))) {
				bad_s = 1;
			}
#endif				/* USE_BCRYPT */
#if defined(USE_YESCRYPT)
			if (  (   streq(crypt_method, "YESCRYPT")
			       && (-1 == str2sl(&yescrypt_cost, optarg)))) {
				bad_s = 1;
			}
#endif				/* USE_YESCRYPT */
			if (bad_s != 0) {
				eprintf(_("%s: invalid numeric argument '%s'\n"),
				         Prog, optarg);
				usage (E_USAGE);
			}
			break;
		default:
			usage (E_USAGE);
			/*@notreached@*/break;
		}
	}

	/* validate options */
	check_flags ();
}

/*
 * check_flags - check flags and parameters consistency
 *
 *	It will not return if an error is encountered.
 */
static void check_flags (void)
{
	if (sflg && !cflg) {
		eprintf(_("%s: %s flag is only allowed with the %s flag\n"),
		         Prog, "-s", "-c");
		usage (E_USAGE);
	}

	if (eflg && cflg) {
		eprintf(_("%s: the -c and -e flags are exclusive\n"), Prog);
		usage (E_USAGE);
	}

	if (cflg) {
		if (   !streq(crypt_method, "NONE")
		    && !streq(crypt_method, "SHA256")
		    && !streq(crypt_method, "SHA512")
#ifdef USE_BCRYPT
		    && !streq(crypt_method, "BCRYPT")
#endif				/* USE_BCRYPT */
#ifdef USE_YESCRYPT
		    && !streq(crypt_method, "YESCRYPT")
#endif				/* USE_YESCRYPT */
		    ) {
			eprintf(_("%s: unsupported crypt method: %s\n"),
			         Prog, crypt_method);
			usage (E_USAGE);
		}
	}
}

/*
 * open_files - lock and open the group databases
 */
static void open_files (bool process_selinux)
{
	/*
	 * Lock the group file and open it for reading and writing. This will
	 * bring all of the entries into memory where they may be updated.
	 */
	if (gr_lock () == 0) {
		eprintf(_("%s: cannot lock %s; try again later.\n"),
		         Prog, gr_dbname ());
		fail_exit (1, process_selinux);
	}
	gr_locked = true;
	if (gr_open (O_CREAT | O_RDWR) == 0) {
		eprintf(_("%s: cannot open %s\n"), Prog, gr_dbname());
		fail_exit (1, process_selinux);
	}

#ifdef SHADOWGRP
	/* Do the same for the shadowed database, if it exist */
	if (is_shadow_grp) {
		if (sgr_lock () == 0) {
			eprintf(_("%s: cannot lock %s; try again later.\n"),
			         Prog, sgr_dbname ());
			fail_exit (1, process_selinux);
		}
		sgr_locked = true;
		if (sgr_open (O_CREAT | O_RDWR) == 0) {
			eprintf(_("%s: cannot open %s\n"), Prog, sgr_dbname());
			fail_exit (1, process_selinux);
		}
	}
#endif
}

/*
 * close_files - close and unlock the group databases
 */
static void close_files(const struct option_flags *flags)
{
	bool process_selinux;

	process_selinux = !flags->chroot;
#ifdef SHADOWGRP
	if (is_shadow_grp) {
		if (sgr_close (process_selinux) == 0) {
			eprintf(_("%s: failure while writing changes to %s\n"),
			         Prog, sgr_dbname ());
			SYSLOG(LOG_ERR, "failure while writing changes to %s", sgr_dbname());
			fail_exit (1, process_selinux);
		}
		if (sgr_unlock (process_selinux) == 0) {
			eprintf(_("%s: failed to unlock %s\n"), Prog, sgr_dbname());
			SYSLOG(LOG_ERR, "failed to unlock %s", sgr_dbname());
			/* continue */
		}
		sgr_locked = false;
	}
#endif

	if (gr_close (process_selinux) == 0) {
		eprintf(_("%s: failure while writing changes to %s\n"),
		         Prog, gr_dbname ());
		SYSLOG(LOG_ERR, "failure while writing changes to %s", gr_dbname());
		fail_exit (1, process_selinux);
	}
	if (gr_unlock (process_selinux) == 0) {
		eprintf(_("%s: failed to unlock %s\n"), Prog, gr_dbname());
		SYSLOG(LOG_ERR, "failed to unlock %s", gr_dbname());
		/* continue */
	}
	gr_locked = false;
}

int main (int argc, char **argv)
{
	char buf[BUFSIZ];
	char *name;
	char *newpwd;
	char *cp;

#ifdef	SHADOWGRP
	const struct sgrp *sg;
	struct sgrp newsg;
#endif

	const struct group *gr;
	struct group newgr;
	bool errors = false;
	intmax_t line = 0;
	struct option_flags  flags = {.chroot = false};
	bool process_selinux;

	log_set_progname(Prog);
	log_set_logfd(stderr);

	(void) setlocale (LC_ALL, "");
	(void) bindtextdomain (PACKAGE, LOCALEDIR);
	(void) textdomain (PACKAGE);

#ifdef WITH_SELINUX
	if (check_selinux_permit ("passwd") != 0) {
		return (E_NOPERM);
	}
#endif				/* WITH_SELINUX */

	process_root_flag ("-R", argc, argv);

	process_flags (argc, argv, &flags);
	process_selinux = !flags.chroot;

	OPENLOG (Prog);

#ifdef SHADOWGRP
	is_shadow_grp = sgr_file_present ();
#endif

	open_files (process_selinux);

	/*
	 * Read each line, separating the group name from the password. The
	 * group entry for each group will be looked up in the appropriate
	 * file (gshadow or group) and the password changed.
	 */
	while (fgets_a(buf, stdin) != NULL) {
		line++;
		if (stpsep(buf, "\n") == NULL) {
			eprintf(_("%s: line %jd: line too long\n"), Prog, line);
			errors = true;
			continue;
		}

		/*
		 * The group's name is the first field. It is separated from
		 * the password with a ":" character which is replaced with a
		 * NUL to give the new password. The new password will then
		 * be encrypted in the normal fashion with a new salt
		 * generated, unless the '-e' is given, in which case it is
		 * assumed to already be encrypted.
		 */

		name = buf;
		cp = stpsep(name, ":");
		if (cp == NULL) {
			eprintf(_("%s: line %jd: missing new password\n"),
			         Prog, line);
			errors = true;
			continue;
		}
		newpwd = cp;
		if (   (!eflg)
		    && (   (NULL == crypt_method)
		        || !streq(crypt_method, "NONE"))) {
			void *arg = NULL;
			const char *salt;
			if (sflg) {
				if (   streq(crypt_method, "SHA256")
					|| streq(crypt_method, "SHA512")) {
					arg = &sha_rounds;
				}
#if defined(USE_BCRYPT)
				if (streq(crypt_method, "BCRYPT")) {
					arg = &bcrypt_rounds;
				}
#endif				/* USE_BCRYPT */
#if defined(USE_YESCRYPT)
				if (streq(crypt_method, "YESCRYPT")) {
					arg = &yescrypt_cost;
				}
#endif				/* USE_YESCRYPT */
			}
			salt = crypt_make_salt (crypt_method, arg);
			cp = pw_encrypt (newpwd, salt);
			if (NULL == cp) {
				eprinte(_("%s: failed to crypt password with salt '%s'"),
				        Prog, salt);
				fail_exit (1, process_selinux);
			}
		}

		/*
		 * Get the group file entry for this group. The group must
		 * already exist.
		 */
		gr = gr_locate (name);
		if (NULL == gr) {
			eprintf(_("%s: line %jd: group '%s' does not exist\n"), Prog,
			         line, name);
			errors = true;
			continue;
		}
#ifdef SHADOWGRP
		if (is_shadow_grp) {
			/* The gshadow entry should be updated if the
			 * group entry has a password set to 'x'.
			 * But on the other hand, if there is already both
			 * a group and a gshadow password, it's preferable
			 * to update both.
			 */
			sg = sgr_locate (name);

			if (   (NULL == sg)
			    && streq(gr->gr_passwd, SHADOW_PASSWD_STRING))
			{
				static char *empty = NULL;
				/* If the password is set to 'x' in
				 * group, but there are no entries in
				 * gshadow, create one.
				 */
				newsg.sg_namp   = name;
				/* newsg.sg_passwd = NULL; will be set later */
				newsg.sg_adm    = &empty;
				newsg.sg_mem    = dup_list (gr->gr_mem);
				sg = &newsg;
			}
		} else {
			sg = NULL;
		}
#endif

		/*
		 * The freshly encrypted new password is merged into the
		 * group's entry.
		 */
#ifdef SHADOWGRP
		if (NULL != sg) {
			newsg = *sg;
			newsg.sg_passwd = cp;
		}
		if (   (NULL == sg)
		    || !streq(gr->gr_passwd, SHADOW_PASSWD_STRING))
#endif
		{
			newgr = *gr;
			newgr.gr_passwd = cp;
		}

		/*
		 * The updated group file entry is then put back and will
		 * be written to the group file later, after all the
		 * other entries have been updated as well.
		 */
#ifdef SHADOWGRP
		if (NULL != sg) {
			if (sgr_update (&newsg) == 0) {
				eprintf(_("%s: line %jd: failed to prepare the new %s entry '%s'\n"),
				         Prog, line, sgr_dbname (), newsg.sg_namp);
				errors = true;
				continue;
			}
		}
		if (   (NULL == sg)
		    || !streq(gr->gr_passwd, SHADOW_PASSWD_STRING))
#endif
		{
			if (gr_update (&newgr) == 0) {
				eprintf(_("%s: line %jd: failed to prepare the new %s entry '%s'\n"),
				         Prog, line, gr_dbname (), newgr.gr_name);
				errors = true;
				continue;
			}
		}
	}

	/*
	 * Any detected errors will cause the entire set of changes to be
	 * aborted. Unlocking the group file will cause all of the
	 * changes to be ignored. Otherwise the file is closed, causing the
	 * changes to be written out all at once, and then unlocked
	 * afterwards.
	 */
	if (errors) {
		eprintf(_("%s: error detected, changes ignored\n"), Prog);
		fail_exit (1, process_selinux);
	}

	close_files (&flags);

	nscd_flush_cache ("group");
	sssd_flush_cache (SSSD_DB_GROUP);

	return (0);
}

