commit 91d9a3e66b0dda77270dcd8513f038ccb27572e2 Author: Ting-Jun Wang Date: Sat May 25 18:31:10 2024 +0800 feat: setuid & setgid script diff --git a/tool/Makefile b/tool/Makefile new file mode 100644 index 0000000..95afa3e --- /dev/null +++ b/tool/Makefile @@ -0,0 +1,12 @@ +CC = gcc +CFLAGS = -Wall -Wextra -std=c99 + +all: setup_uid + +setup_uid: setup_uid.c + $(CC) $(CFLAGS) -o setup_uid setup_uid.c + sudo chown root:root setup_uid + sudo chmod +s setup_uid + +clean: + sudo rm setup_uid diff --git a/tool/setup_uid.c b/tool/setup_uid.c new file mode 100644 index 0000000..d9f32e9 --- /dev/null +++ b/tool/setup_uid.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include + +bool check_user(char *filename, char *username, unsigned long *new_start) { + /* + * Check whether the user exists in the uid file (subuid, subgid). + * Return exists or not, and set the new_start if need it. + * + * Args: + * filename (char *): means the uid file (subuid or subgid). + * username (char *): the user who run this excutable file. + * new_start (unsigned long *): it's a pointer, save the new start point. + * Return: + * exist (bool): exist or not + */ + FILE *fp = fopen(filename, "r"); + + if (fp == NULL) { + printf("[ERROR] Please contact Unix Manager.\n"); + exit(1); + } + + // read data from subuid, subgid + char line[100]; + char user[30]; + unsigned long start, size; // 0~2^32-1, equal to subuid + bool exist = false; + while (fgets(line, sizeof(line), fp)) { + sscanf(line, "%[^:]:%lu:%lu", user, &start, &size); + *new_start = start + size; + if (strcmp(username, user) == 0) exist = true; + } + fclose(fp); + return exist; +} + +void insert_user(char *filename, char *username, unsigned long start) { + FILE *fp = fopen(filename, "a"); + + if (fp == NULL) { + printf("[ERROR] Please contact Unix Manager.\n"); + exit(1); + } + char new_line[100]; + sprintf(new_line, "%s:%lu:%d\n", username, start, 65535); + fputs(new_line, fp); + fclose(fp); + printf("[SUCCESS] %s has been inserted in %s\n", username, filename); +} + + +int main() { + char *username = getlogin(); + + char filenames[2][20] = { + "/etc/subuid", "/etc/subgid" + }; + + bool exist; + unsigned long new_start; // 0~2^32-1, equal to subuid + for (int i=0; i<2; i++) { + new_start = 100000; // subuid, subgid default from 100000~165535 + exist = check_user(filenames[i], username, &new_start); + if (exist) { + printf("[WARNING] %s has been in %s, no change\n", username, filenames[i]); + } else { + insert_user(filenames[i], username, new_start); + } + } + return 0; +}