aboutsummaryrefslogtreecommitdiff
path: root/02/src/common.c
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 05:31:06 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-11 06:14:42 +0000
commit9e1d304cac5367c3dbb1ca14700736680bd3a804 (patch)
tree31f328747acb934d365d423adfda144818ff5ad4 /02/src/common.c
downloadlab-01-05-9e1d304cac5367c3dbb1ca14700736680bd3a804.tar.gz
publishHEADmaster
Diffstat (limited to '02/src/common.c')
-rw-r--r--02/src/common.c463
1 files changed, 463 insertions, 0 deletions
diff --git a/02/src/common.c b/02/src/common.c
new file mode 100644
index 0000000..05a0e49
--- /dev/null
+++ b/02/src/common.c
@@ -0,0 +1,463 @@
1#include "common.h"
2
3#include <termios.h>
4#include <fcntl.h>
5#include <unistd.h>
6
7#include <openssl/rand.h>
8#include <openssl/err.h>
9
10struct string_builder passwd_log = {0};
11
12uid_t ruid;
13gid_t rgid;
14uid_t euid;
15gid_t egid;
16
17char
18encode6 (unsigned char b6)
19{
20 if (b6 < ('9' - '.' + 1) ) return '.' + b6;
21 if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) ) return 'A' + b6 - ('9' - '.' + 1);
22 if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) + ('z' - 'a' + 1)) return 'a' + b6 - ('9' - '.' + 1) - ('Z' - 'A' + 1);
23 printf ("0x%X\n", b6);
24 assert (!"out of range");
25 return -1;
26}
27
28unsigned char
29decode6 (char c)
30{
31 if ('.' <= c && c <= '9') return c - '.';
32 if ('A' <= c && c <= 'Z') return c - 'A' + ('9' - '.' + 1);
33 if ('a' <= c && c <= 'z') return c - 'a' + ('9' - '.' + 1) + ('Z' - 'A' + 1);
34 assert (!"out of range");
35 return -1;
36}
37
38void
39encode (char *into, const unsigned char* from, unsigned int size)
40{
41 for (; size >= 3; size -= 3) {
42 // 012345670123456701234567
43 // 012345012345012345012345
44 into[0] = encode6 ( from[0] >> 2);
45 into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4);
46 into[2] = encode6 ((from[1] & 0b00001111) << 2 | from[2] >> 6);
47 into[3] = encode6 ((from[2] & 0b00111111));
48
49 from += 3;
50 into += 4;
51 }
52 if (size == 2) {
53 into[0] = encode6 ( from[0] >> 2);
54 into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4);
55 into[2] = encode6 ((from[1] & 0b00001111) << 2);
56 } else if (size == 1) {
57 into[0] = encode6 ( from[0] >> 2);
58 into[1] = encode6 ((from[0] & 0b00000011) << 4);
59 }
60}
61
62void
63decode (unsigned char *into, struct string_view from)
64{
65 size_t len;
66
67 for (len = SVLEN (from); len >= 4; len -= 4) {
68 // 012345012345012345012345
69 // 012345670123456701234567
70
71 unsigned char d1 = decode6 (from.begin[0]);
72 unsigned char d2 = decode6 (from.begin[1]);
73 unsigned char d3 = decode6 (from.begin[2]);
74 unsigned char d4 = decode6 (from.begin[3]);
75
76 into[0] = d1 << 2 | d2 >> 4;
77 into[1] = (d2 & 0b001111) << 4 | d3 >> 2;
78 into[2] = d3 << 6 | d4;
79
80 from.begin += 4;
81 into += 3;
82 }
83 if (len == 3) {
84 unsigned char d1 = decode6 (from.begin[0]);
85 unsigned char d2 = decode6 (from.begin[1]);
86 unsigned char d3 = decode6 (from.begin[2]);
87
88 into[0] = d1 << 2 | d2 >> 4;
89 into[1] = (d2 & 0b001111) << 4 | d3 >> 2;
90 } else if (len == 2) {
91 unsigned char d1 = decode6 (from.begin[0]);
92 unsigned char d2 = decode6 (from.begin[1]);
93
94 into[0] = d1 << 2 | d2 >> 4;
95 } else assert ("!unreachable");
96}
97
98void
99generate_salt (unsigned char salt[PASSWORD_SALT_SIZE])
100{
101 if (RAND_bytes (salt, PASSWORD_SALT_SIZE) != 1) {
102 DIE ("error generating salt: RAND_bytes: %s",
103 ERR_reason_error_string (ERR_get_error ()));
104 }
105}
106
107unsigned char *
108hash_password (unsigned char hash[SHA_DIGEST_LENGTH],
109 struct string_view password,
110 const unsigned char salt[PASSWORD_SALT_SIZE])
111{
112 EVP_MD_CTX *mdctx = EVP_MD_CTX_new ();
113 if (mdctx == NULL) {
114 DIE ("error hashing creating context: EVP_MD_CTX_new: %s",
115 ERR_reason_error_string (ERR_get_error ()));
116 }
117
118 if (EVP_DigestInit_ex (mdctx, EVP_sha1 (), NULL) != 1) {
119 DIE ("error initializing digest: EVP_DigestInit_ex: %s",
120 ERR_reason_error_string (ERR_get_error ()));
121 }
122
123 if (EVP_DigestUpdate (mdctx, password.begin, SVLEN (password)) != 1) {
124 DIE ("error updating digest with password: EVP_DigestUpdate: %s",
125 ERR_reason_error_string (ERR_get_error ()));
126 }
127
128 if (EVP_DigestUpdate (mdctx, salt, PASSWORD_SALT_SIZE) != 1) {
129 DIE ("error updating digest with salt: EVP_DigestUpdate: %s",
130 ERR_reason_error_string (ERR_get_error ()));
131 }
132
133 unsigned int hash_len;
134 if (EVP_DigestFinal_ex(mdctx, hash, &hash_len) != 1) {
135 DIE ("error finalizing digest: EVP_DigestFinal_ex: %s",
136 ERR_reason_error_string (ERR_get_error ()));
137 }
138
139 EVP_MD_CTX_free (mdctx);
140
141 return hash;
142}
143
144struct string_view
145encode_password (struct string_view password)
146{
147 static char encoded[PASSWORD_ENCODED_LENGTH + 1] = {
148 [0] = '$',
149 [1] = '1',
150 [2] = '$',
151 [3 + PASSWORD_SALT_LENGTH] = '$',
152 };
153
154 char *salt_encoded = (void *) &encoded[3];
155 char *hash_encoded = (void *) &encoded[3 + PASSWORD_SALT_LENGTH + 1];
156
157 unsigned char salt[PASSWORD_SALT_SIZE];
158 generate_salt (salt);
159 encode (salt_encoded, salt, sizeof (salt));
160
161 unsigned char hash[SHA_DIGEST_LENGTH];
162 hash_password (hash, password, salt);
163 encode (hash_encoded, hash, SHA_DIGEST_LENGTH);
164
165 return (struct string_view) { encoded, encoded + PASSWORD_ENCODED_LENGTH };
166}
167
168bool
169check_password (struct string_view password,
170 struct string_view encoded_password)
171{
172 if (*encoded_password.begin++ != '$') return false;
173 if (*encoded_password.begin++ != '1') return false;
174 if (*encoded_password.begin++ != '$') return false;
175
176 struct string_view encoded_salt = {
177 .begin = encoded_password.begin,
178 .end = encoded_password.begin += PASSWORD_SALT_LENGTH,
179 };
180 if (*encoded_password.begin++ != '$') return false;
181
182 struct string_view encoded_hash = {
183 .begin = encoded_password.begin,
184 .end = encoded_password.begin + PASSWORD_HASH_LENGTH,
185 };
186
187 unsigned char decoded_salt[PASSWORD_SALT_SIZE];
188 decode (decoded_salt, encoded_salt);
189
190 unsigned char hash[SHA_DIGEST_LENGTH];
191 hash_password (hash, password, decoded_salt);
192
193 unsigned char decoded_hash[SHA_DIGEST_LENGTH];
194 decode (decoded_hash, encoded_hash);
195
196 return memcmp (hash, decoded_hash, sizeof (hash)) == 0;
197}
198
199int
200fscan_passwd_entry (FILE *stream, struct passwd_entry *entry)
201{
202 *entry = (struct passwd_entry) {0};
203
204 int c;
205 do c = getc (stream);
206 while (c == '\n');
207 if (c == EOF)
208 return 0;
209 ungetc (c, stream);
210
211 char buffer[256 + 1];
212
213 fscanf (stream, "%32[a-zA-Z0-9]", buffer);
214 if (getc (stream) != ':') return -1;
215 entry->login = string_view_strdup (buffer);
216
217 fread (buffer, 1, PASSWORD_ENCODED_LENGTH, stream);
218 if (getc (stream) != ':') return -1;
219 buffer[PASSWORD_ENCODED_LENGTH] = '\0';
220 entry->encoded_password = string_view_strdup (buffer);
221
222 fscanf (stream, "%d", &entry->id);
223 if (getc (stream) != ':') return -1;
224
225 fscanf (stream, "%d", (int *) &entry->access_rights);
226 if (entry->access_rights > 0b111) return -1;
227 if (getc (stream) != ':') return -1;
228
229 int len = 0;
230 fscanf (stream, "%256[^:\n]%n", buffer, &len);
231 if (len)
232 entry->comment = SVDUP0 ((struct string_view) { buffer, buffer + len });
233
234 return 1;
235}
236
237void
238fprint_passwd_entry (FILE *stream, const struct passwd_entry *entry)
239{
240 if (entry->id < 0)
241 DIE ("id < 0");
242
243 struct string_view comment;
244 if (entry->comment.begin) {
245 comment.begin = entry->comment.begin;
246 comment.end = entry->comment.end;
247 } else {
248 comment.begin = "";
249 comment.end = comment.begin;
250 }
251
252 fprintf (stream, "%.*s:%.*s:%d:%d:%.*s\n",
253 SVFMT (entry->login),
254 SVFMT (entry->encoded_password),
255 entry->id,
256 entry->access_rights,
257 SVFMT (comment));
258}
259
260void
261lock_passwd_file (struct passwd passwd)
262{
263 if (lockf (fileno (passwd.stream), F_TLOCK, 0) != 0)
264 DIE ("unable to lock passwd file: %s", strerror (errno));
265}
266
267void
268unlock_passwd_file (struct passwd passwd)
269{
270 if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0)
271 DIE ("unable to unlock passwd file: %s", strerror (errno));
272}
273
274struct passwd
275load_passwd_file (void)
276{
277 elevate ();
278 struct passwd passwd = {
279 .stream = fopen (PREFIX"/etc/passwd", "r+"),
280 };
281 drop ();
282
283 if (passwd.stream == NULL)
284 DIE ("unable to open passwd file: %s", strerror (errno));
285
286 if (lockf (fileno (passwd.stream), F_TEST, 0) != 0)
287 DIE ("passwd file is locked: %s", strerror (errno));
288
289 for (int i = 0;; ++i) {
290 struct passwd_entry entry;
291 int ret = fscan_passwd_entry (passwd.stream, &entry);
292 if (ret == -1)
293 DIE (PREFIX"/etc/passwd:%d: failed to parse entry", i);
294 if (ret == 0)
295 break;
296 DYNAMIC_ARRAY_APPEND (passwd, entry);
297 }
298
299 return passwd;
300}
301
302void
303save_passwd_file (struct passwd passwd)
304{
305 ftruncate (fileno (passwd.stream), 0);
306 rewind (passwd.stream);
307 for (struct passwd_entry *entry = passwd.items;
308 entry < passwd.items + passwd.count; ++entry) {
309 fprint_passwd_entry (passwd.stream, entry);
310 } fflush (passwd.stream);
311}
312
313void
314close_passwd_file (struct passwd passwd)
315{
316 for (uint32_t i = 0; i < passwd.count; ++i) {
317 free ((void *) passwd.items[i].login.begin);
318 free ((void *) passwd.items[i].encoded_password.begin);
319 free ((void *) passwd.items[i].comment.begin);
320 }
321 DYNAMIC_ARRAY_FREE (passwd);
322
323 if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0)
324 DIE ("unable to unlock passwd file: %s", strerror (errno));
325
326 fclose (passwd.stream);
327}
328
329struct string_view
330read_password ()
331{
332 static char password[PASSWORD_MAX_LENGTH + 2];
333
334 struct termios term_orig;
335 tcgetattr (fileno (stdin), &term_orig);
336 struct termios term_noecho = term_orig;
337 term_noecho.c_lflag &= ~ECHO;
338 tcsetattr (fileno (stdin), 0, &term_noecho);
339
340 if (fgets (password, sizeof (password), stdin) == NULL) {
341 tcsetattr (fileno (stdin), 0, &term_orig);
342 putchar ('\n');
343 exit (0);
344 } tcsetattr (fileno (stdin), 0, &term_orig);
345
346 putchar ('\n');
347 size_t len = strlen (password) - 1;
348 if (password[len] != '\n')
349 DIE ("password too long");
350 password[len] = '\0';
351
352 return (struct string_view) { password, password + len };
353}
354
355struct string_view
356read_login ()
357{
358 static char login[LOGIN_MAX_LENGTH + 2];
359
360 if (fgets (login, sizeof (login), stdin) == NULL) {
361 putchar ('\n');
362 exit (0);
363 }
364
365 size_t len = strlen (login) - 1;
366 if (login[len] != '\n')
367 DIE ("login too long");
368 login[len] = '\0';
369
370 return (struct string_view) { login, login + len };
371}
372
373struct passwd_entry *
374authenticate (struct passwd passwd,
375 struct string_view login,
376 struct string_view password)
377{
378 struct passwd_entry *entry = lookup_login (passwd, login);
379
380 if (!entry) {
381 fprintf (stderr, "user %.*s not found\n", SVFMT (login));
382 return NULL;
383 }
384
385 if (!check_password (password, entry->encoded_password)) {
386 fputs ("authentication failure\n", stderr);
387 string_builder_printf (&passwd_log, "%u user %.*s supplied incorrect password\n",
388 time (NULL), SVFMT (entry->login));
389 return NULL;
390 }
391
392 string_builder_printf (&passwd_log, "%u authenticated user %.*s %d\n",
393 time (NULL), SVFMT (entry->login), entry->id);
394
395 return entry;
396}
397
398void
399append_passwd_log ()
400{
401 if (passwd_log.count) {
402 elevate ();
403 int fd = open (PREFIX"/log/passwd.log", O_CREAT | O_WRONLY | O_APPEND);
404 drop ();
405 write (fd, passwd_log.items, passwd_log.count);
406 close (fd);
407 DYNAMIC_ARRAY_RESET (passwd_log);
408 }
409}
410
411struct passwd_entry *
412lookup_login (struct passwd passwd, struct string_view login)
413{
414 for (struct passwd_entry *entry = passwd.items;
415 entry < passwd.items + passwd.count; ++entry) {
416 if (SVCMP (login, entry->login) != 0)
417 continue;
418
419 string_builder_printf (&passwd_log, "%u user '%.*s' (%d) was looked up\n",
420 time (NULL), SVFMT (entry->login), entry->id);
421
422 return entry;
423 }
424
425 string_builder_printf (&passwd_log, "%u user '%.*s' lookup failed\n",
426 time (NULL), SVFMT (login));
427
428 return NULL;
429}
430
431struct passwd_entry *
432lookup_id (struct passwd passwd, int id)
433{
434 for (struct passwd_entry *entry = passwd.items;
435 entry < passwd.items + passwd.count; ++entry) {
436 if (id != entry->id)
437 continue;
438
439 string_builder_printf (&passwd_log, "%u user %d was looked up\n",
440 time (NULL), id);
441
442 return entry;
443 }
444
445 string_builder_printf (&passwd_log, "%u user %d lookup failed\n",
446 time (NULL), id);
447
448 return NULL;
449}
450
451void
452elevate (void)
453{
454 if (euid != ruid) seteuid (euid);
455 if (egid != rgid) setegid (egid);
456}
457
458void
459drop (void)
460{
461 if (euid != ruid) seteuid (ruid);
462 if (egid != rgid) setegid (rgid);
463}