-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
83 lines (69 loc) · 2.07 KB
/
main.c
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
76
77
78
79
80
81
82
//
// Copyright (c) 2023 Brian Sullender
// All rights reserved.
//
// This source code is licensed under the terms provided in the README file.
//
// https://github.com/b-sullender/linux-auth
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <crypt.h>
#define USER_ENTRY_FILE "/etc/shadow"
// Function to check if two hashed passwords match
int passwordsMatch(const char* storedHashedPassword, const char* inputPassword) {
return strcmp(storedHashedPassword, crypt(inputPassword, storedHashedPassword)) == 0;
}
// Function to authenticate a user
int authenticateUser(const char* username, const char* password)
{
FILE* file = fopen(USER_ENTRY_FILE, "r");
if (file == NULL) {
perror("Error opening shadow file");
return -1;
}
char line[256];
while (fgets(line, sizeof(line), file))
{
char *token = strtok(line, ":");
if (token != NULL && strcmp(token, username) == 0)
{
token = strtok(NULL, ":"); // Get the stored hashed password
if (token != NULL && passwordsMatch(token, password)) {
fclose(file);
return 1; // Authentication successful
} else {
fclose(file);
return 0; // Authentication failed (wrong password)
}
}
}
fclose(file);
return 0; // Authentication failed (user not found)
}
int main()
{
char username[100];
char password[100];
printf("Enter username: ");
if (scanf("%99s", username) != 1) {
fprintf(stderr, "Error reading username\n");
return 1;
}
printf("Enter password: ");
if (scanf("%99s", password) != 1) {
fprintf(stderr, "Error reading password\n");
return 1;
}
int result = authenticateUser(username, password);
if (result == 1) {
printf("Authentication successful!\n");
} else if (result == 0) {
printf("Authentication failed: Incorrect username or password.\n");
} else {
printf("Error authenticating user.\n");
}
return 0;
}