#include #include #include #include #include #include #include #define POLICY_INTERACTIVE 0 #define POLICY_ALLOW 1 #define POLICY_DENY 2 static int check_policy_file(const char *path, uid_t uid) { FILE *f = fopen(path, "r"); if (!f) return -1; char line[256]; int action = -1; time_t now = time(NULL); while (fgets(line, sizeof(line), f)) { if (line[0] == '#' || line[0] == '\n' || line[0] == '\r') continue; long f_uid = 0; int f_action = 0; long long f_until = 0; if (sscanf(line, "%ld %d %lld", &f_uid, &f_action, &f_until) >= 2) { if ((uid_t)f_uid == uid) { if (f_until == 0 || f_until > (long long)now) { action = f_action; } break; } } } fclose(f); return action; } int main(void) { const char *test_file = "/tmp/test_policy.conf"; FILE *f = fopen(test_file, "w"); assert(f != NULL); time_t now = time(NULL); /* Write test policy entries */ fprintf(f, "# Comment line\n"); fprintf(f, "\n"); fprintf(f, " \n"); fprintf(f, "invalid garbage line\n"); fprintf(f, "10050 1 0 org.test.allow_forever\n"); fprintf(f, "10051 2 0 org.test.deny_forever\n"); fprintf(f, "10052 1 %lld org.test.expired\n", (long long)(now - 100)); fprintf(f, "10053 1 %lld org.test.valid_future\n", (long long)(now + 1000)); fprintf(f, "# Another comment\n"); fprintf(f, "10054 2 %lld org.test.deny_future\n", (long long)(now + 500)); fclose(f); /* Test 1: Allow forever */ int act = check_policy_file(test_file, 10050); assert(act == POLICY_ALLOW); printf("PASS: uid 10050 allow forever\n"); /* Test 2: Deny forever */ act = check_policy_file(test_file, 10051); assert(act == POLICY_DENY); printf("PASS: uid 10051 deny forever\n"); /* Test 3: Expired policy should return -1 (interactive prompt) */ act = check_policy_file(test_file, 10052); assert(act == -1); printf("PASS: uid 10052 expired -> interactive\n"); /* Test 4: Future expiry should be allowed */ act = check_policy_file(test_file, 10053); assert(act == POLICY_ALLOW); printf("PASS: uid 10053 valid future timestamp\n"); /* Test 5: Future deny */ act = check_policy_file(test_file, 10054); assert(act == POLICY_DENY); printf("PASS: uid 10054 deny future timestamp\n"); /* Test 6: Unknown UID */ act = check_policy_file(test_file, 99999); assert(act == -1); printf("PASS: uid 99999 not in policy file -> -1\n"); /* Test 7: Nonexistent file */ act = check_policy_file("/tmp/nonexistent_policy_file.conf", 10050); assert(act == -1); printf("PASS: nonexistent file -> -1\n"); unlink(test_file); printf("All policy file parser tests passed successfully.\n"); return 0; }