/*
 * pam_c8wallet: opens the wallet with the password typed at login, as
 * pam_kwallet does for KWallet.
 *
 * auth (after pam_unix, so only a password that worked) keeps a copy of
 * it; open_session hands it to c8-wallet-keeper, running as the user,
 * which gives it once to c8-wallet over a socket in the runtime dir and
 * then forgets it (or after two minutes, in a session without c8-wallet).
 * chauthtok (passwd and the like) tells a running wallet (oo7-daemon's
 * PAM socket) about the new password, so it keeps opening by itself; one
 * that isn't running is changed by c8-wallet at the next login instead.
 * Nothing here can fail a login or a password change: every problem is
 * PAM_IGNORE.
 */
#define _DEFAULT_SOURCE
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#include <security/pam_ext.h>
#include <security/pam_modules.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <syslog.h>
#include <unistd.h>

#define KEEP "c8wallet_authtok"

#include "oo7-pam.h"

#ifndef C8_WALLET_KEEPER
#define C8_WALLET_KEEPER "/usr/libexec/c8-wallet-keeper"
#endif

static void forget(pam_handle_t *pamh, void *data, int status) {
	if (data) {
		explicit_bzero(data, strlen(data));
		free(data);
	}
}

PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc,
		const char **argv) {
	const void *tok = NULL;
	if (pam_get_item(pamh, PAM_AUTHTOK, &tok) != PAM_SUCCESS || tok == NULL ||
			((const char *)tok)[0] == '\0') {
		return PAM_IGNORE;
	}
	char *copy = strdup(tok);
	if (copy == NULL || pam_set_data(pamh, KEEP, copy, forget) != PAM_SUCCESS) {
		forget(pamh, copy, 0);
	}
	return PAM_IGNORE;
}

PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc,
		const char **argv) {
	return PAM_IGNORE;
}

/* The runtime dir pam_systemd made for the user (it runs before us) */
static int runtime_dir(pam_handle_t *pamh, const struct passwd *pw,
		char *out, size_t size) {
	const char *env = pam_getenv(pamh, "XDG_RUNTIME_DIR");
	if (env) {
		snprintf(out, size, "%s", env);
	} else {
		snprintf(out, size, "/run/user/%u", (unsigned)pw->pw_uid);
	}
	struct stat st;
	if (stat(out, &st) < 0 || !S_ISDIR(st.st_mode) ||
			st.st_uid != pw->pw_uid || (st.st_mode & 077)) {
		return -1;
	}
	return 0;
}

PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc,
		const char **argv) {
	const void *data = NULL;
	if (pam_get_data(pamh, KEEP, &data) != PAM_SUCCESS || data == NULL) {
		return PAM_IGNORE; // autologin, fingerprint: nothing to give
	}
	const char *pass = data;
	const char *user = NULL;
	if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || user == NULL) {
		return PAM_IGNORE;
	}
	struct passwd *pw = getpwnam(user);
	char dir[256];
	if (pw == NULL || pw->pw_uid == 0 ||
			runtime_dir(pamh, pw, dir, sizeof(dir)) < 0) {
		pam_syslog(pamh, LOG_NOTICE, "no runtime dir; wallet not opened");
		return PAM_IGNORE;
	}
	int fds[2];
	if (pipe(fds) < 0) {
		return PAM_IGNORE;
	}
	pid_t child = fork();
	if (child < 0) {
		close(fds[0]);
		close(fds[1]);
		return PAM_IGNORE;
	}
	if (child == 0) {
		/* Become the user, then let go of the login process entirely */
		close(fds[1]);
		if (dup2(fds[0], STDIN_FILENO) < 0) {
			_exit(1);
		}
		/* A stack already running as the user (a locker) has nothing to drop */
		if (geteuid() == 0 && (initgroups(pw->pw_name, pw->pw_gid) < 0 ||
				setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0 ||
				setuid(0) == 0)) {
			_exit(1);
		}
		if (getuid() != pw->pw_uid) {
			_exit(1);
		}
		if (fork() != 0) {
			_exit(0);
		}
		setsid();
		/* Not the login manager's output: it may be waiting on it */
		int null = open("/dev/null", O_RDWR | O_CLOEXEC);
		if (null >= 0) {
			dup2(null, STDOUT_FILENO);
			dup2(null, STDERR_FILENO);
		}
		for (int fd = 3; fd < 1024; fd++) {
			close(fd);
		}
		char *env[] = {NULL};
		execle(C8_WALLET_KEEPER, C8_WALLET_KEEPER, dir, (char *)NULL, env);
		_exit(127);
	}
	close(fds[0]);
	size_t len = strlen(pass);
	ssize_t n = write(fds[1], pass, len);
	close(fds[1]);
	waitpid(child, NULL, 0);
	if (n != (ssize_t)len) {
		pam_syslog(pamh, LOG_NOTICE, "couldn't hand over the password");
	}
	return PAM_IGNORE;
}

PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc,
		const char **argv) {
	return PAM_IGNORE;
}

PAM_EXTERN int pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc,
		const char **argv) {
	if (!(flags & PAM_UPDATE_AUTHTOK)) {
		return PAM_IGNORE;
	}
	const void *old = NULL, *new = NULL;
	const char *user = NULL;
	if (pam_get_item(pamh, PAM_OLDAUTHTOK, &old) != PAM_SUCCESS ||
			pam_get_item(pamh, PAM_AUTHTOK, &new) != PAM_SUCCESS ||
			old == NULL || new == NULL ||
			pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || user == NULL) {
		return PAM_IGNORE;
	}
	struct passwd *pw = getpwnam(user);
	if (pw == NULL) {
		return PAM_IGNORE;
	}
	/* The daemon's socket, if it runs: the user's own, in their dir */
	char sock[128];
	snprintf(sock, sizeof(sock), "/run/user/%u/oo7-pam.sock",
		(unsigned)pw->pw_uid);
	struct stat st;
	if (lstat(sock, &st) < 0 || !S_ISSOCK(st.st_mode) ||
			st.st_uid != pw->pw_uid) {
		return PAM_IGNORE;
	}
	if (oo7_pam_send(sock, OO7_PAM_CHANGE_PASSWORD, user, old, new) == 0) {
		pam_syslog(pamh, LOG_INFO, "wallet password changed too");
	}
	return PAM_IGNORE;
}
