commit e891693f6f1d939a7d7f744e152f8e3949c3a2b9 Author: Alessandro Mauri Date: Mon Mar 22 14:06:08 2021 +0100 initial commie diff --git a/README.md b/README.md new file mode 100644 index 0000000..f2e841f --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# US - User Switcher diff --git a/makefile b/makefile new file mode 100644 index 0000000..418299e --- /dev/null +++ b/makefile @@ -0,0 +1,25 @@ +CC ?= gcc +CFLAGS = -Wall -pedantic --std=c99 -O2 +PREFIX = /usr/local +MANPREFIX = ${PREFIX}/share/man + +us: us.c + +dbg: + gcc -O0 -g us.c -o us + +install: us + mkdir -p ${DESTDIR}${PREFIX}/bin + cp -f us ${DESTDIR}${PREFIX}/bin/us + chown root:root ${DESTDIR}${PREFIX}/bin/us + chmod 4755 ${DESTDIR}${PREFIX}/bin/us +# mkdir -p ${DESTDIR}${MANPREFIX}/man1 +# cp -f us.1 ${DESTDIR}${MANPREFIX}/man1/us.1 +# chmod 644 ${DESTDIR}${MANPREFIX}/man1/us.1 + +uninstall: + rm -f ${DESTDIR}${PREFIX}/bin/us +# ${DESTDIR}${MANPREFIX}/man1/us.1 + +clean: + rm -f us us-dbg diff --git a/us.c b/us.c new file mode 100644 index 0000000..342debc --- /dev/null +++ b/us.c @@ -0,0 +1,57 @@ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include + +static void usage (void); +static int perm_set (uid_t); + +int main (int argc, char *argv[]) +{ + if (argc < 2) { + usage(); + exit(1); + } + + uid_t ruid = getuid(); + + // Copy argv and argc + int c_argc = argc - 1; + char **c_argv = malloc((c_argc + 1) * sizeof(char *)); + if (!c_argv) { + fprintf(stderr, "malloc: %s\n", strerror(errno)); + goto fail_end; + } + for (int i = 0; i < c_argc; i++) + c_argv[i] = strdup(argv[i+1]); + c_argc[c_argv] = NULL; + + if (perm_set(0) == -1) { // 0 = root + fprintf(stderr, "perm_set: %s\n", strerror(errno)); + goto fail_end; + } + if (execvp(*c_argv, c_argv) == -1) // execvp searches in path + fprintf(stderr, "execv: %s\n", strerror(errno)); + // if exec fails reset the permissions + if (perm_set(ruid) == -1) { // 0 = root + fprintf(stderr, "perm_set: %s\n", strerror(errno)); + goto fail_end; + } + + fail_end: + return 0; +} + +static inline void usage (void) +{ + printf("usage: us [command]\n"); +} + +static inline int perm_set (uid_t id) +{ + return seteuid(id); +}