1 mike 1.1.2.1 #define _XOPEN_SOURCE
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include "Defines.h"
6 #include "Strlcpy.h"
7 #include "PasswordFile.h"
8
9 /*
10 **==============================================================================
11 **
12 ** CheckPasswordFile()
13 **
14 ** Checks whether the *password* is correct for the given *username*,
15 ** according to the password file referred to by *path*. The file has
16 ** the following format.
17 **
18 ** <usrname>:<encrypted-password>
19 **
20 ** For example (smith's password is "changeme"):
21 **
22 mike 1.1.2.1 ** smith:AB5bZ.JX9fQzA
23 ** jones:XMllrzJ80fd.A
24 ** williams:lM80ffj.jiOiO
25 **
26 ** Returns zero if the password matches or if password is null and the
27 ** user exists.
28 **
29 **==============================================================================
30 */
31
32 int CheckPasswordFile(
33 const char* path,
34 const char* username,
35 const char* password)
36 {
37 FILE* is;
38 char line[EXECUTOR_BUFFER_SIZE];
39
40 // Open file.
41
42 if ((is = fopen(path, "r")) == NULL)
43 mike 1.1.2.1 return -1;
44
45 // Lookup encrypted password for this user.
46
47 while (fgets(line, sizeof(line), is) != NULL)
48 {
49 char* p;
50 char encryptedPassword[14];
51 char buffer[EXECUTOR_BUFFER_SIZE];
52 char salt[3];
53
54 /* Skip lines starting with '#'. */
55
56 if (line[0] == '#')
57 continue;
58
59 /* Replace colon with null-terminator. */
60
61 if ((p = strchr(line, ':')) == NULL)
62 continue;
63
64 mike 1.1.2.1 *p++ = '\0';
65
66 /* Skip this line, if username does not match. */
67
68 if (strcmp(line, username) != 0)
69 continue;
70
71 /* If password is null, we are done. */
72
73 if (password == NULL)
74 return 0;
75
76 /* Get encrypted password. */
77
78 Strlcpy(encryptedPassword, p, sizeof(encryptedPassword));
79
80 /* Get salt from encrypted password. */
81
82 salt[0] = encryptedPassword[0];
83 salt[1] = encryptedPassword[1];
84 salt[2] = '\0';
85 mike 1.1.2.1
86 /* Check password. */
87
88 Strlcpy(buffer, crypt(password, salt), sizeof(buffer));
89
90 if (strcmp(buffer, encryptedPassword) == 0)
91 {
92 fclose(is);
93 return 0;
94 }
95 else
96 {
97 fclose(is);
98 return -1;
99 }
100 }
101
102 // User entry not found.
103
104 fclose(is);
105 return -1;
106 mike 1.1.2.1 }
|