-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmypassword.c
More file actions
75 lines (64 loc) · 2.21 KB
/
Copy pathmypassword.c
File metadata and controls
75 lines (64 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <crypt.h>
void change_password(char *user) {
// Check EUID to ensure the program has Root privileges (SetUID)
if (geteuid() != 0) {
fprintf(stderr, "Error: SetUID root required to write /etc/shadow\n");
return;
}
FILE *fs = fopen("/etc/shadow", "r");
FILE *ft = fopen("/etc/shadow.tmp", "w");
if (!fs || !ft) { perror("File error"); return; }
char line[512], tmp_line[512], stored_hash[256];
int found = 0;
// Verify Old Password
while (fgets(line, sizeof(line), fs)) {
strcpy(tmp_line, line);
char *name = strtok(tmp_line, ":");
if (name && strcmp(name, user) == 0) {
strcpy(stored_hash, strtok(NULL, ":"));
found = 1; break;
}
}
if (!found) { printf("User not found.\n"); fclose(fs); fclose(ft); return; }
char *old_pw = getpass("Old password: ");
if (strcmp(crypt(old_pw, stored_hash), stored_hash) != 0) {
printf("Incorrect password.\n"); fclose(fs); fclose(ft); return;
}
// Generate New Hash
char *new_pw = getpass("New password: ");
char *new_hash = crypt(new_pw, "$6$saltsalt"); // Using SHA-512 with a salt
// Rewrite shadow file
rewind(fs);
while (fgets(line, sizeof(line), fs)) {
strcpy(tmp_line, line);
char *name = strtok(tmp_line, ":");
if (name && strcmp(name, user) == 0) {
// Reconstruct the shadow line: name:new_hash:rest_of_fields
char *rest = strtok(NULL, ""); // Get everything after username
rest = strchr(rest, ':'); // Move pointer to the first ':' after hash
fprintf(ft, "%s:%s%s", user, new_hash, rest ? rest : ":::");
} else {
fputs(line, ft);
}
}
fclose(fs); fclose(ft);
// Swap files and set permissions
if (rename("/etc/shadow.tmp", "/etc/shadow") == 0) {
chmod("/etc/shadow", 0640);
printf("Password updated successfully.\n");
} else {
perror("Rename failed");
}
}
int main() {
char user[50];
printf("Username: ");
scanf("%49s", user);
change_password(user);
return 0;
}