swaylock/shadow.c

104 lines
2.3 KiB
C
Raw Normal View History

#define _XOPEN_SOURCE // for crypt
#include <pwd.h>
#include <shadow.h>
2019-01-23 14:16:44 -06:00
#include <stdlib.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#ifdef __GLIBC__
// GNU, you damn slimy bastard
#include <crypt.h>
#endif
2019-01-16 16:35:14 -06:00
#include "comm.h"
#include "log.h"
2022-05-30 04:50:30 -05:00
#include "password-buffer.h"
2019-01-16 16:35:14 -06:00
#include "swaylock.h"
2019-01-18 07:52:17 -06:00
void initialize_pw_backend(int argc, char **argv) {
if (geteuid() != 0) {
swaylock_log(LOG_ERROR,
"swaylock needs to be setuid to read /etc/shadow");
exit(EXIT_FAILURE);
}
if (!spawn_comm_child()) {
exit(EXIT_FAILURE);
}
if (setgid(getgid()) != 0) {
swaylock_log_errno(LOG_ERROR, "Unable to drop root");
exit(EXIT_FAILURE);
}
if (setuid(getuid()) != 0) {
swaylock_log_errno(LOG_ERROR, "Unable to drop root");
exit(EXIT_FAILURE);
}
if (setuid(0) != -1) {
swaylock_log_errno(LOG_ERROR, "Unable to drop root (we shouldn't be "
"able to restore it after setuid)");
exit(EXIT_FAILURE);
}
}
2019-01-16 16:35:14 -06:00
void run_pw_backend_child(void) {
/* This code runs as root */
struct passwd *pwent = getpwuid(getuid());
if (!pwent) {
swaylock_log_errno(LOG_ERROR, "failed to getpwuid");
exit(EXIT_FAILURE);
}
char *encpw = pwent->pw_passwd;
if (strcmp(encpw, "x") == 0) {
struct spwd *swent = getspnam(pwent->pw_name);
if (!swent) {
swaylock_log_errno(LOG_ERROR, "failed to getspnam");
exit(EXIT_FAILURE);
}
encpw = swent->sp_pwdp;
}
/* We don't need any additional logging here because the parent process will
* also fail here and will handle logging for us. */
if (setgid(getgid()) != 0) {
exit(EXIT_FAILURE);
}
if (setuid(getuid()) != 0) {
exit(EXIT_FAILURE);
}
if (setuid(0) != -1) {
exit(EXIT_FAILURE);
}
/* This code does not run as root */
2019-01-16 16:35:14 -06:00
swaylock_log(LOG_DEBUG, "Prepared to authorize user %s", pwent->pw_name);
while (1) {
2019-01-16 16:35:14 -06:00
char *buf;
ssize_t size = read_comm_request(&buf);
if (size < 0) {
exit(EXIT_FAILURE);
2019-01-16 16:35:14 -06:00
} else if (size == 0) {
break;
}
2019-01-16 16:35:14 -06:00
const char *c = crypt(buf, encpw);
2022-05-30 04:50:30 -05:00
password_buffer_destroy(buf, size);
buf = NULL;
if (c == NULL) {
2019-01-16 16:35:14 -06:00
swaylock_log_errno(LOG_ERROR, "crypt failed");
exit(EXIT_FAILURE);
}
2019-01-16 16:35:14 -06:00
bool success = strcmp(c, encpw) == 0;
if (!write_comm_reply(success)) {
exit(EXIT_FAILURE);
}
2019-01-16 16:35:14 -06:00
sleep(2);
}
clear_buffer(encpw, strlen(encpw));
exit(EXIT_SUCCESS);
}