CMLAB-Docker-Builder/tool/setup_uid.c

104 lines
3.0 KiB
C

#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
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) {
/*
* Insert the user into uid file
* It will setup the next start uid automatically
* == it will change /etc/subuid or /etc/subgid ==
*
* 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 value, means the next start uid
* Return:
* No
*/
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, 65536);
fputs(new_line, fp);
fclose(fp);
printf("[SUCCESS] %s has been inserted in %s\n", username, filename);
}
int main() {
int ret;
char *username = getlogin();
uid_t ruid, euid, suid;
getresuid(&ruid, &euid, &suid);
printf("ruid=%d, euid=%d, suid=%d\n", ruid, euid, suid);
ret = setuid(0);
printf("ret=%d\n", ret);
if (ret != 0) {
perror("Error:");
exit(1);
}
getresuid(&ruid, &euid, &suid);
printf("ruid=%d, euid=%d, suid=%d\n", ruid, euid, suid);
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;
}