From 9e1d304cac5367c3dbb1ca14700736680bd3a804 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Wed, 11 Nov 2026 08:31:06 +0300 Subject: publish --- 02/src/bruteforce.c | 43 ++ 02/src/common.c | 463 ++++++++++++++++++ 02/src/common.h | 107 +++++ 02/src/cracking.c | 138 ++++++ 02/src/cracking.h | 35 ++ 02/src/dynamic-array.h | 68 +++ 02/src/measure.c | 70 +++ 02/src/passwdctl.c | 493 +++++++++++++++++++ 02/src/shell.c | 1215 +++++++++++++++++++++++++++++++++++++++++++++++ 02/src/string-builder.c | 58 +++ 02/src/string-builder.h | 56 +++ 02/src/string-view.c | 147 ++++++ 02/src/string-view.h | 46 ++ 13 files changed, 2939 insertions(+) create mode 100644 02/src/bruteforce.c create mode 100644 02/src/common.c create mode 100644 02/src/common.h create mode 100644 02/src/cracking.c create mode 100644 02/src/cracking.h create mode 100644 02/src/dynamic-array.h create mode 100644 02/src/measure.c create mode 100644 02/src/passwdctl.c create mode 100644 02/src/shell.c create mode 100644 02/src/string-builder.c create mode 100644 02/src/string-builder.h create mode 100644 02/src/string-view.c create mode 100644 02/src/string-view.h (limited to '02/src') diff --git a/02/src/bruteforce.c b/02/src/bruteforce.c new file mode 100644 index 0000000..38dfd0f --- /dev/null +++ b/02/src/bruteforce.c @@ -0,0 +1,43 @@ +// src/bruteforce.c --- utility to bruteforce shell password +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include + +#include "cracking.h" + +int +main (int argc, char *argv[]) +{ + if (argc != 2) { + fprintf (stderr, "Usage: %s LOGIN\n", argv[0]); + exit (EXIT_FAILURE); + } + + struct shell shell = spawn_shell (); + struct string_view login = SVCSTR (argv[1]); + struct string_builder password = {0}; + STRING_BUILDER_APPEND_STRING_VIEW (password, SVCSTR ("A")); + + for (size_t attmept = 0;; ++attmept) { + if (attmept % 10000 == 0) + printf ("Trying: %.*s\n", SBFMT (password)); + + if (test_credentials (shell, login, SVSB (password))) + break; + + password_bump (&password); + } + + printf ("Found: %.*s\n", SVFMT (SVSB (password))); + + return EXIT_SUCCESS; +} + +// src/bruteforce.c ends here 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 @@ +#include "common.h" + +#include +#include +#include + +#include +#include + +struct string_builder passwd_log = {0}; + +uid_t ruid; +gid_t rgid; +uid_t euid; +gid_t egid; + +char +encode6 (unsigned char b6) +{ + if (b6 < ('9' - '.' + 1) ) return '.' + b6; + if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) ) return 'A' + b6 - ('9' - '.' + 1); + if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) + ('z' - 'a' + 1)) return 'a' + b6 - ('9' - '.' + 1) - ('Z' - 'A' + 1); + printf ("0x%X\n", b6); + assert (!"out of range"); + return -1; +} + +unsigned char +decode6 (char c) +{ + if ('.' <= c && c <= '9') return c - '.'; + if ('A' <= c && c <= 'Z') return c - 'A' + ('9' - '.' + 1); + if ('a' <= c && c <= 'z') return c - 'a' + ('9' - '.' + 1) + ('Z' - 'A' + 1); + assert (!"out of range"); + return -1; +} + +void +encode (char *into, const unsigned char* from, unsigned int size) +{ + for (; size >= 3; size -= 3) { + // 012345670123456701234567 + // 012345012345012345012345 + into[0] = encode6 ( from[0] >> 2); + into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4); + into[2] = encode6 ((from[1] & 0b00001111) << 2 | from[2] >> 6); + into[3] = encode6 ((from[2] & 0b00111111)); + + from += 3; + into += 4; + } + if (size == 2) { + into[0] = encode6 ( from[0] >> 2); + into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4); + into[2] = encode6 ((from[1] & 0b00001111) << 2); + } else if (size == 1) { + into[0] = encode6 ( from[0] >> 2); + into[1] = encode6 ((from[0] & 0b00000011) << 4); + } +} + +void +decode (unsigned char *into, struct string_view from) +{ + size_t len; + + for (len = SVLEN (from); len >= 4; len -= 4) { + // 012345012345012345012345 + // 012345670123456701234567 + + unsigned char d1 = decode6 (from.begin[0]); + unsigned char d2 = decode6 (from.begin[1]); + unsigned char d3 = decode6 (from.begin[2]); + unsigned char d4 = decode6 (from.begin[3]); + + into[0] = d1 << 2 | d2 >> 4; + into[1] = (d2 & 0b001111) << 4 | d3 >> 2; + into[2] = d3 << 6 | d4; + + from.begin += 4; + into += 3; + } + if (len == 3) { + unsigned char d1 = decode6 (from.begin[0]); + unsigned char d2 = decode6 (from.begin[1]); + unsigned char d3 = decode6 (from.begin[2]); + + into[0] = d1 << 2 | d2 >> 4; + into[1] = (d2 & 0b001111) << 4 | d3 >> 2; + } else if (len == 2) { + unsigned char d1 = decode6 (from.begin[0]); + unsigned char d2 = decode6 (from.begin[1]); + + into[0] = d1 << 2 | d2 >> 4; + } else assert ("!unreachable"); +} + +void +generate_salt (unsigned char salt[PASSWORD_SALT_SIZE]) +{ + if (RAND_bytes (salt, PASSWORD_SALT_SIZE) != 1) { + DIE ("error generating salt: RAND_bytes: %s", + ERR_reason_error_string (ERR_get_error ())); + } +} + +unsigned char * +hash_password (unsigned char hash[SHA_DIGEST_LENGTH], + struct string_view password, + const unsigned char salt[PASSWORD_SALT_SIZE]) +{ + EVP_MD_CTX *mdctx = EVP_MD_CTX_new (); + if (mdctx == NULL) { + DIE ("error hashing creating context: EVP_MD_CTX_new: %s", + ERR_reason_error_string (ERR_get_error ())); + } + + if (EVP_DigestInit_ex (mdctx, EVP_sha1 (), NULL) != 1) { + DIE ("error initializing digest: EVP_DigestInit_ex: %s", + ERR_reason_error_string (ERR_get_error ())); + } + + if (EVP_DigestUpdate (mdctx, password.begin, SVLEN (password)) != 1) { + DIE ("error updating digest with password: EVP_DigestUpdate: %s", + ERR_reason_error_string (ERR_get_error ())); + } + + if (EVP_DigestUpdate (mdctx, salt, PASSWORD_SALT_SIZE) != 1) { + DIE ("error updating digest with salt: EVP_DigestUpdate: %s", + ERR_reason_error_string (ERR_get_error ())); + } + + unsigned int hash_len; + if (EVP_DigestFinal_ex(mdctx, hash, &hash_len) != 1) { + DIE ("error finalizing digest: EVP_DigestFinal_ex: %s", + ERR_reason_error_string (ERR_get_error ())); + } + + EVP_MD_CTX_free (mdctx); + + return hash; +} + +struct string_view +encode_password (struct string_view password) +{ + static char encoded[PASSWORD_ENCODED_LENGTH + 1] = { + [0] = '$', + [1] = '1', + [2] = '$', + [3 + PASSWORD_SALT_LENGTH] = '$', + }; + + char *salt_encoded = (void *) &encoded[3]; + char *hash_encoded = (void *) &encoded[3 + PASSWORD_SALT_LENGTH + 1]; + + unsigned char salt[PASSWORD_SALT_SIZE]; + generate_salt (salt); + encode (salt_encoded, salt, sizeof (salt)); + + unsigned char hash[SHA_DIGEST_LENGTH]; + hash_password (hash, password, salt); + encode (hash_encoded, hash, SHA_DIGEST_LENGTH); + + return (struct string_view) { encoded, encoded + PASSWORD_ENCODED_LENGTH }; +} + +bool +check_password (struct string_view password, + struct string_view encoded_password) +{ + if (*encoded_password.begin++ != '$') return false; + if (*encoded_password.begin++ != '1') return false; + if (*encoded_password.begin++ != '$') return false; + + struct string_view encoded_salt = { + .begin = encoded_password.begin, + .end = encoded_password.begin += PASSWORD_SALT_LENGTH, + }; + if (*encoded_password.begin++ != '$') return false; + + struct string_view encoded_hash = { + .begin = encoded_password.begin, + .end = encoded_password.begin + PASSWORD_HASH_LENGTH, + }; + + unsigned char decoded_salt[PASSWORD_SALT_SIZE]; + decode (decoded_salt, encoded_salt); + + unsigned char hash[SHA_DIGEST_LENGTH]; + hash_password (hash, password, decoded_salt); + + unsigned char decoded_hash[SHA_DIGEST_LENGTH]; + decode (decoded_hash, encoded_hash); + + return memcmp (hash, decoded_hash, sizeof (hash)) == 0; +} + +int +fscan_passwd_entry (FILE *stream, struct passwd_entry *entry) +{ + *entry = (struct passwd_entry) {0}; + + int c; + do c = getc (stream); + while (c == '\n'); + if (c == EOF) + return 0; + ungetc (c, stream); + + char buffer[256 + 1]; + + fscanf (stream, "%32[a-zA-Z0-9]", buffer); + if (getc (stream) != ':') return -1; + entry->login = string_view_strdup (buffer); + + fread (buffer, 1, PASSWORD_ENCODED_LENGTH, stream); + if (getc (stream) != ':') return -1; + buffer[PASSWORD_ENCODED_LENGTH] = '\0'; + entry->encoded_password = string_view_strdup (buffer); + + fscanf (stream, "%d", &entry->id); + if (getc (stream) != ':') return -1; + + fscanf (stream, "%d", (int *) &entry->access_rights); + if (entry->access_rights > 0b111) return -1; + if (getc (stream) != ':') return -1; + + int len = 0; + fscanf (stream, "%256[^:\n]%n", buffer, &len); + if (len) + entry->comment = SVDUP0 ((struct string_view) { buffer, buffer + len }); + + return 1; +} + +void +fprint_passwd_entry (FILE *stream, const struct passwd_entry *entry) +{ + if (entry->id < 0) + DIE ("id < 0"); + + struct string_view comment; + if (entry->comment.begin) { + comment.begin = entry->comment.begin; + comment.end = entry->comment.end; + } else { + comment.begin = ""; + comment.end = comment.begin; + } + + fprintf (stream, "%.*s:%.*s:%d:%d:%.*s\n", + SVFMT (entry->login), + SVFMT (entry->encoded_password), + entry->id, + entry->access_rights, + SVFMT (comment)); +} + +void +lock_passwd_file (struct passwd passwd) +{ + if (lockf (fileno (passwd.stream), F_TLOCK, 0) != 0) + DIE ("unable to lock passwd file: %s", strerror (errno)); +} + +void +unlock_passwd_file (struct passwd passwd) +{ + if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0) + DIE ("unable to unlock passwd file: %s", strerror (errno)); +} + +struct passwd +load_passwd_file (void) +{ + elevate (); + struct passwd passwd = { + .stream = fopen (PREFIX"/etc/passwd", "r+"), + }; + drop (); + + if (passwd.stream == NULL) + DIE ("unable to open passwd file: %s", strerror (errno)); + + if (lockf (fileno (passwd.stream), F_TEST, 0) != 0) + DIE ("passwd file is locked: %s", strerror (errno)); + + for (int i = 0;; ++i) { + struct passwd_entry entry; + int ret = fscan_passwd_entry (passwd.stream, &entry); + if (ret == -1) + DIE (PREFIX"/etc/passwd:%d: failed to parse entry", i); + if (ret == 0) + break; + DYNAMIC_ARRAY_APPEND (passwd, entry); + } + + return passwd; +} + +void +save_passwd_file (struct passwd passwd) +{ + ftruncate (fileno (passwd.stream), 0); + rewind (passwd.stream); + for (struct passwd_entry *entry = passwd.items; + entry < passwd.items + passwd.count; ++entry) { + fprint_passwd_entry (passwd.stream, entry); + } fflush (passwd.stream); +} + +void +close_passwd_file (struct passwd passwd) +{ + for (uint32_t i = 0; i < passwd.count; ++i) { + free ((void *) passwd.items[i].login.begin); + free ((void *) passwd.items[i].encoded_password.begin); + free ((void *) passwd.items[i].comment.begin); + } + DYNAMIC_ARRAY_FREE (passwd); + + if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0) + DIE ("unable to unlock passwd file: %s", strerror (errno)); + + fclose (passwd.stream); +} + +struct string_view +read_password () +{ + static char password[PASSWORD_MAX_LENGTH + 2]; + + struct termios term_orig; + tcgetattr (fileno (stdin), &term_orig); + struct termios term_noecho = term_orig; + term_noecho.c_lflag &= ~ECHO; + tcsetattr (fileno (stdin), 0, &term_noecho); + + if (fgets (password, sizeof (password), stdin) == NULL) { + tcsetattr (fileno (stdin), 0, &term_orig); + putchar ('\n'); + exit (0); + } tcsetattr (fileno (stdin), 0, &term_orig); + + putchar ('\n'); + size_t len = strlen (password) - 1; + if (password[len] != '\n') + DIE ("password too long"); + password[len] = '\0'; + + return (struct string_view) { password, password + len }; +} + +struct string_view +read_login () +{ + static char login[LOGIN_MAX_LENGTH + 2]; + + if (fgets (login, sizeof (login), stdin) == NULL) { + putchar ('\n'); + exit (0); + } + + size_t len = strlen (login) - 1; + if (login[len] != '\n') + DIE ("login too long"); + login[len] = '\0'; + + return (struct string_view) { login, login + len }; +} + +struct passwd_entry * +authenticate (struct passwd passwd, + struct string_view login, + struct string_view password) +{ + struct passwd_entry *entry = lookup_login (passwd, login); + + if (!entry) { + fprintf (stderr, "user %.*s not found\n", SVFMT (login)); + return NULL; + } + + if (!check_password (password, entry->encoded_password)) { + fputs ("authentication failure\n", stderr); + string_builder_printf (&passwd_log, "%u user %.*s supplied incorrect password\n", + time (NULL), SVFMT (entry->login)); + return NULL; + } + + string_builder_printf (&passwd_log, "%u authenticated user %.*s %d\n", + time (NULL), SVFMT (entry->login), entry->id); + + return entry; +} + +void +append_passwd_log () +{ + if (passwd_log.count) { + elevate (); + int fd = open (PREFIX"/log/passwd.log", O_CREAT | O_WRONLY | O_APPEND); + drop (); + write (fd, passwd_log.items, passwd_log.count); + close (fd); + DYNAMIC_ARRAY_RESET (passwd_log); + } +} + +struct passwd_entry * +lookup_login (struct passwd passwd, struct string_view login) +{ + for (struct passwd_entry *entry = passwd.items; + entry < passwd.items + passwd.count; ++entry) { + if (SVCMP (login, entry->login) != 0) + continue; + + string_builder_printf (&passwd_log, "%u user '%.*s' (%d) was looked up\n", + time (NULL), SVFMT (entry->login), entry->id); + + return entry; + } + + string_builder_printf (&passwd_log, "%u user '%.*s' lookup failed\n", + time (NULL), SVFMT (login)); + + return NULL; +} + +struct passwd_entry * +lookup_id (struct passwd passwd, int id) +{ + for (struct passwd_entry *entry = passwd.items; + entry < passwd.items + passwd.count; ++entry) { + if (id != entry->id) + continue; + + string_builder_printf (&passwd_log, "%u user %d was looked up\n", + time (NULL), id); + + return entry; + } + + string_builder_printf (&passwd_log, "%u user %d lookup failed\n", + time (NULL), id); + + return NULL; +} + +void +elevate (void) +{ + if (euid != ruid) seteuid (euid); + if (egid != rgid) setegid (egid); +} + +void +drop (void) +{ + if (euid != ruid) seteuid (ruid); + if (egid != rgid) setegid (rgid); +} diff --git a/02/src/common.h b/02/src/common.h new file mode 100644 index 0000000..0edc629 --- /dev/null +++ b/02/src/common.h @@ -0,0 +1,107 @@ +// common.h --- common functions +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#ifndef INCLUDED_COMMON_H +#define INCLUDED_COMMON_H + +#include +#include +#include +#include + +#include + +#include "string-view.h" +#include "string-builder.h" + +#define PREFIX "/usr/local/practice2" + +#define STRINGIFY(ARG) #ARG +#define TO_STRING(ARG) STRINGIFY (ARG) + +#define DIE(FMT, ...) do { \ + fprintf (stderr, "fatal: " FMT "\n" __VA_OPT__ (,) __VA_ARGS__); \ + exit (EXIT_FAILURE); \ + } while (0) + +#define LOGIN_MAX_LENGTH 32 +#define LOGIN_REGEX "[a-zA-Z][-_a-zA-Z0-9]*" + +#define COMMENT_MAX_LENGTH 256 +#define COMMENT_REGEX "[^:\n]*" + +#define PASSWORD_MAX_LENGTH 256 +#define PASSWORD_SALT_SIZE 12 +#define PASSWORD_SALT_LENGTH 16 +#define PASSWORD_HASH_LENGTH 27 +#define PASSWORD_ENCODED_LENGTH (3 + PASSWORD_SALT_LENGTH + 1 + PASSWORD_HASH_LENGTH) +#define PASSWORD_REGEX "[a-zA-Z][a-zA-Z0-9!@#$%^&*()]*" + +extern struct string_builder passwd_log; + +extern uid_t ruid; +extern gid_t rgid; +extern uid_t euid; +extern gid_t egid; + +struct passwd_entry { + struct string_view login; + struct string_view encoded_password; + int id; + enum access_rights { + AR_READ = 1 << 0, + AR_WRITE = 1 << 1, + AR_DELETE = 1 << 2, + } access_rights; + struct string_view comment; +}; + +struct passwd { + struct passwd_entry *items; + uint32_t count; + uint32_t capacity; + FILE *stream; +}; + +char encode6 (unsigned char b6); +unsigned char decode6 (char c); +void encode (char *into, const unsigned char* from, unsigned int size); +void decode (unsigned char *into, struct string_view from); + +void generate_salt (unsigned char salt[PASSWORD_SALT_SIZE]); +unsigned char *hash_password (unsigned char hash[SHA_DIGEST_LENGTH], + struct string_view password, + const unsigned char salt[PASSWORD_SALT_SIZE]); +struct string_view encode_password (struct string_view password); +bool check_password (struct string_view password, + struct string_view encoded_password); + +int fscan_passwd_entry (FILE *, struct passwd_entry *); +void fprint_passwd_entry (FILE *, const struct passwd_entry *); +struct passwd load_passwd_file (void); +void save_passwd_file (struct passwd); +void close_passwd_file (struct passwd); + +struct string_view read_password (void); +struct string_view read_login (void); + +void append_passwd_log (void); + +struct passwd_entry *lookup_login (struct passwd, struct string_view login); +struct passwd_entry *lookup_id (struct passwd, int id); + +struct passwd_entry *authenticate (struct passwd, struct string_view login, struct string_view password); + +void elevate (void); +void drop (void); + +#endif // INCLUDED_COMMON_H + +// common.h ends here diff --git a/02/src/cracking.c b/02/src/cracking.c new file mode 100644 index 0000000..25afcb5 --- /dev/null +++ b/02/src/cracking.c @@ -0,0 +1,138 @@ +#include +#include +#include + +#include "cracking.h" + +void +password_bump (STRING_BUILDER sb) +{ + if ('A' <= sb->string[0] && sb->string[0] < 'Z' || + 'a' <= sb->string[0] && sb->string[0] < 'z') { + sb->string[0] += 1; + return; + } + + if (sb->string[0] == 'Z') { + sb->string[0] = 'a'; + return; + } + + sb->string[0] = 'A'; + + size_t index = 1; + +again: + if (index == sb->length) { + STRING_BUILDER_APPEND_CHAR (*sb, '!'); + return; + } + + if ('0' <= sb->string[index] && sb->string[index] < '9' || + 'A' <= sb->string[index] && sb->string[index] < 'Z' || + 'a' <= sb->string[index] && sb->string[index] < 'z') { + sb->string[index] += 1; + return; + } + + switch (sb->string[index]) { + case '!': sb->string[index] = '@'; return; + case '@': sb->string[index] = '#'; return; + case '#': sb->string[index] = '$'; return; + case '$': sb->string[index] = '%'; return; + case '%': sb->string[index] = '^'; return; + case '^': sb->string[index] = '&'; return; + case '&': sb->string[index] = '*'; return; + case '*': sb->string[index] = '('; return; + case '(': sb->string[index] = ')'; return; + case ')': sb->string[index] = '0'; return; + + case '9': sb->string[index] = 'A'; return; + case 'Z': sb->string[index] = 'a'; return; + } + + sb->string[index] = '!'; + + index += 1; + goto again; +} + +bool +test_credentials (struct shell shell, + struct string_view login, + struct string_view password) +{ + fprintf (shell.out, "%.*s\n%.*s\n", SVFMT (login), SVFMT (password)); + for (;;) { + int c = getc (shell.in); + if (c == '\n') + break; + } + int c = getc (shell.in); + if (c == 'H') + return true; + + ungetc (c, shell.in); + return false; +} + +struct shell +spawn_shell (void) +{ + struct shell shell; + + int fd_master; + int fd_slave; + + if (openpty (&fd_master, &fd_slave, NULL, NULL, NULL) == -1) { + perror ("openpty"); + exit (EXIT_FAILURE); + } + + shell.pid = fork (); + if (shell.pid == -1) { + perror ("fork"); + exit (EXIT_FAILURE); + } + + if (shell.pid == 0) { + close (fd_master); + + if (dup2 (fd_slave, STDIN_FILENO) == -1) { + perror ("dup2 stdin"); + _exit (1); + } + + if (dup2 (fd_slave, STDOUT_FILENO) == -1) { + perror ("dup2 stdout"); + _exit (1); + } + + close (fd_slave); + close (STDERR_FILENO); + + struct termios term; + tcgetattr (STDIN_FILENO, &term); + term.c_lflag &= ~ECHO; + tcsetattr (STDIN_FILENO, 0, &term); + + execlp ("shell", "shell", NULL); + perror ("execlp"); + _exit (1); + } + + close (fd_slave); + + shell.out = fdopen (fd_master, "w"); + shell.in = fdopen (fd_master, "r"); + + return shell; +} + +void +close_shell (struct shell shell) +{ + fclose (shell.in); + fclose (shell.out); + waitpid (shell.pid, NULL, 0); +} diff --git a/02/src/cracking.h b/02/src/cracking.h new file mode 100644 index 0000000..0173dbb --- /dev/null +++ b/02/src/cracking.h @@ -0,0 +1,35 @@ +/// src/cracking.h --- password cracking utilities +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED_CRACKING_H +#define INCLUDED_CRACKING_H + +#include +#include + +#include "string-builder.h" +#include "string-view.h" + +struct shell { + FILE *in; + FILE *out; + pid_t pid; +}; + +void password_bump (STRING_BUILDER); +bool test_credentials (struct shell, + struct string_view login, + struct string_view password); +struct shell spawn_shell (void); +void close_shell (struct shell); + +#endif // INCLUDED_CRACKING_H + +/// src/cracking.h ends here diff --git a/02/src/dynamic-array.h b/02/src/dynamic-array.h new file mode 100644 index 0000000..ed5cb32 --- /dev/null +++ b/02/src/dynamic-array.h @@ -0,0 +1,68 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include +#include + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] + +#define DYNAMIC_ARRAY_POP(DYNAMIC_ARRAY) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count--] + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#endif diff --git a/02/src/measure.c b/02/src/measure.c new file mode 100644 index 0000000..72633bc --- /dev/null +++ b/02/src/measure.c @@ -0,0 +1,70 @@ +// src/measure.c --- utility to measure time to bruteforce +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include +#include +#include + +#include "cracking.h" + +int +main (int argc, char *argv[]) +{ + if (argc != 2) { + fprintf (stderr, "Usage: %s LOGIN\n", argv[0]); + fprintf (stderr, "Note: LOGIN shouldn't have password of length 3 or 4\n"); + exit (EXIT_FAILURE); + } + + struct shell shell = spawn_shell (); + clock_t start, end; + + struct string_view login = SVCSTR (argv[1]); + struct string_builder password = {0}; + STRING_BUILDER_APPEND_STRING_VIEW (password, SVCSTR ("A!!")); + + start = clock(); + while (password.length == 3) { + test_credentials (shell, login, SVSB (password)); + password_bump (&password); + } end = clock(); + double time3 = (end - start) /(double) CLOCKS_PER_SEC; + + double per_try3 = time3/(52*72*72); + double time4_expected = per_try3*(52*pow (72, 3)); + printf ("Tried all 3 letter passwords in: %fs\n", time3); + printf ("Expected time to try all 4 letter passwords: %f min\n", time4_expected/60); + + start = clock(); + while (password.length == 4) { + test_credentials (shell, login, SVSB (password)); + password_bump (&password); + } end = clock(); + double time4 = (end - start) /(double) CLOCKS_PER_SEC; + + double per_try4 = time4/(52*72*72*72); + double per_try = (per_try3 + per_try4)/2; + + double time5 = per_try*(52*pow (72, 4)); + double time6 = per_try*(52*pow (72, 5)); + double time7 = per_try*(52*pow (72, 6)); + double time8 = per_try*(52*pow (72, 7)); + + printf ("Real time to try 3 letter passwords: %fs\n", time3); + printf ("Real time to try 4 letter passwords: %fs\n", time4); + printf ("Estimated time to try 5 letter passwords: %fs\n", time5); + printf ("Estimated time to try 6 letter passwords: %fs\n", time6); + printf ("Estimated time to try 7 letter passwords: %fs\n", time7); + printf ("Estimated time to try 8 letter passwords: %fs\n", time8); + + return EXIT_SUCCESS; +} + +// src/measure.c ends here diff --git a/02/src/passwdctl.c b/02/src/passwdctl.c new file mode 100644 index 0000000..f0ab1a8 --- /dev/null +++ b/02/src/passwdctl.c @@ -0,0 +1,493 @@ +// src/passwdctl.c --- utility to manage access to protected directory +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "dynamic-array.h" +#include "string-builder.h" +#include "string-view.h" +#include "common.h" + +#define SUBCOMMANDS() \ + X (ADD, "add") \ + X (MODIFY, "mod") \ + X (DELETE, "del") + +#define X(SYM, STR) SUBCOMMAND_##SYM, +enum subcommand { + SUBCOMMANDS () +}; +#undef X + +#define X(SYM, STR) [SUBCOMMAND_##SYM] = STR, +char *const subcommand_tokens[] = { + SUBCOMMANDS () + NULL +}; +#undef X + +regex_t login_regex; +regex_t comment_regex; +regex_t password_regex; + +struct string_view +parse_password (struct string_view sv) +{ + if (regexec (&password_regex, sv.begin, 0, NULL, 0) != 0) + DIE ("password doesn't match regex %s", PASSWORD_REGEX); + + return sv; +} + +int +parse_id (const char *cstr) +{ + int id; + size_t read; + sscanf (cstr, "%d%ln", &id, &read); + + if (id < 0) DIE ("invalid id"); + if (read != strlen (cstr)) DIE ("invalid id"); + + return id; +} + +enum access_rights +parse_access_right (const char *cstr) +{ + enum access_rights ar = 0; + + while (*cstr) { + switch (*cstr++) { + case 'r': ar |= AR_READ; break; + case 'w': ar |= AR_WRITE; break; + case 'd': ar |= AR_DELETE; break; + default: DIE ("invalid access right: %c", cstr[-1]); + } + } + + return ar; +} + +struct string_view +parse_comment (const char *cstr) +{ + struct string_view sv = SVCSTR (cstr); + + if (SVLEN (sv) > COMMENT_MAX_LENGTH) + DIE ("comment too long"); + + if (regexec (&comment_regex, cstr, 0, NULL, 0) != 0) + DIE ("comment doesn't match regex " COMMENT_REGEX); + + return sv; +} + +struct string_view +parse_login (const char *cstr) +{ + struct string_view sv = SVCSTR (cstr); + + if (SVLEN (sv) > LOGIN_MAX_LENGTH) + DIE ("login too long"); + + if (regexec (&login_regex, cstr, 0, NULL, 0) != 0) + DIE ("login doesn't match regex " LOGIN_REGEX); + + return sv; +} + +const char * +regex_error (const regex_t *comp, int errcode) +{ + static char *error = NULL; + size_t size = regerror (errcode, comp, NULL, 0); + error = realloc (error, size); + regerror (errcode, comp, error, size); + return error; +} + +void +usage (const char *progname) +{ + printf ("Usage: %s [options] COMMAND [ARGS]\n", progname); + puts (""); + puts ("Options:"); + puts (" -h, --help display this help message and exit"); + puts (""); + puts ("Commands:"); + puts (" add LOGIN add new account"); + puts (" mod LOGIN modify existing account"); + puts (" del LOGIN delete account"); + puts (""); +} + +void +usage_add (const char *progname) +{ + printf ("Usage: %s add [options] LOGIN\n", progname); + puts (""); + puts ("Options:"); + puts (" -h, --help display this help message and exit"); + puts (" -p, --password PASSWORD password of the new account"); + puts (" -i, --id ID ID of the new account"); + puts (" -a, --access-rights {r|w|d}... access right of the new account"); + puts (" -c, --comment COMMENT comment of the new account"); + puts (""); +} + +void +usage_mod (const char *progname) +{ + printf ("Usage: %s mod [options] LOGIN\n", progname); + puts (""); + puts ("Options:"); + puts (" -h, --help display this help message and exit"); + puts (" -l, --login NEW_LOGIN new login for the account"); + puts (" -p, --password PASSWORD new password for the account"); + puts (" -P prompt for new password for the account"); + puts (" -i, --id ID new ID for the account"); + puts (" -a, --access-rights {r|w|d}... new access rights for the account"); + puts (" -c, --comment COMMENT new comment for the account"); + puts (""); +} + +void +usage_del (const char *progname) +{ + printf ("Usage: %s del [options] LOGIN\n", progname); + puts (""); + puts ("Options:"); + puts (" -h, --help display this help message and exit"); + puts (""); +} + +int +main (int argc, char *argv[]) +{ + ruid = getuid (); + euid = geteuid (); + seteuid (ruid); + + ERR_load_crypto_strings (); + + const char *progname = argv[0]; + if (progname == NULL) + DIE ("unable to get program name"); + + char **subcommand = &argv[1]; + if (*subcommand == NULL) { + usage (progname); + exit (1); + } + + int errcode; + errcode = regcomp (&login_regex, "^" LOGIN_REGEX "$", REG_NOSUB); + if (errcode != 0) { + DIE ("unable to compile login regex: %s", + regex_error (&login_regex, errcode)); + } + + errcode = regcomp (&password_regex, "^" PASSWORD_REGEX "$", REG_NOSUB); + if (errcode != 0) { + DIE ("unable to compile password regex: %s", + regex_error (&password_regex, errcode)); + } + + errcode = regcomp (&comment_regex, "^" COMMENT_REGEX "$", REG_NOSUB); + if (errcode != 0) { + DIE ("unable to compile comment regex: %s", + regex_error (&comment_regex, errcode)); + } + + char *value; + switch (getsubopt (subcommand, subcommand_tokens, &value)) { + case SUBCOMMAND_ADD: { + static struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + { "password", required_argument, NULL, 'p' }, + { "id", required_argument, NULL, 'i' }, + { "access-rights", required_argument, NULL, 'a' }, + { "comment", required_argument, NULL, 'c' }, + {0} + }; + char ch; + struct passwd_entry new_entry = { .id = -1 }; + optind = 2; + while ((ch = getopt_long (argc, argv, ":hp:i:a:c:", longopts, NULL)) != -1) { + switch (ch) { + case 'h': + usage_add (progname); + exit (0); + case 'p': + new_entry.encoded_password = + SVDUP (encode_password (parse_password (SVCSTR (optarg)))); + break; + case 'i': new_entry.id = parse_id (optarg); break; + case 'a': new_entry.access_rights = parse_access_right (optarg); break; + case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break; + case '?': DIE ("unknown option -%c", optopt); + case ':': DIE ("missing argument for %s", argv[optind - 1]); + default: DIE ("unexpected opt error"); + } + } + + if (argv[optind] == NULL) { + fprintf (stderr, "error: no login provided\n"); + usage_add (progname); + exit (1); + } + + if (argv[optind + 1] != NULL) + DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); + + if (getuid () != 0) + DIE ("permission denied"); + + new_entry.login = SVDUP (SVCSTR (argv[optind])); + + if (new_entry.encoded_password.begin == NULL) { + fputs ("Password: ", stdout); + struct string_view password = duplicate_string_view_as_cstr (parse_password (read_password ())); + fputs ("Repeat password: ", stdout); + struct string_view repeated = read_password (); + if (string_view_compare (password, repeated) != 0) + DIE ("passwords don't match"); + + new_entry.encoded_password = SVDUP (encode_password (password)); + } + + struct passwd passwd = load_passwd_file (); + + int max_id = -1; + for (struct passwd_entry *entry = passwd.items; + entry < passwd.items + passwd.count; ++entry) { + if (SVCMP (new_entry.login, entry->login) == 0) + DIE ("user %.*s already exists", SVFMT (entry->login)); + if (new_entry.id == entry->id) + DIE ("user with id %d already exists", entry->id); + if (entry->id > max_id) + max_id = entry->id; + } + + if (new_entry.id < 0) + new_entry.id = max_id + 1; + + DYNAMIC_ARRAY_APPEND (passwd, new_entry); + save_passwd_file (passwd); + + string_builder_printf (&passwd_log, "%u added user %.*s %d", + time (NULL), SVFMT (new_entry.login), new_entry.id); + if (new_entry.comment.begin) + string_builder_printf (&passwd_log, " (%.*s)", SVFMT (new_entry.comment)); + string_builder_printf (&passwd_log, " with access rights %c%c%c\n", + new_entry.access_rights & AR_READ ? 'r' : '-', + new_entry.access_rights & AR_WRITE ? 'w' : '-', + new_entry.access_rights & AR_DELETE ? 'd' : '-'); + + close_passwd_file (passwd); + } break; + + case SUBCOMMAND_MODIFY: { // [-p --password=] [-i -id=] [-c --comment=] login + static struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + { "login", required_argument, NULL, 'l' }, + { "password", required_argument, NULL, 'p' }, + { "id", required_argument, NULL, 'i' }, + { "access-rights", required_argument, NULL, 'a' }, + { "comment", required_argument, NULL, 'c' }, + {0} + }; + char ch; + struct passwd_entry new_entry = { .id = -1 }; + bool prompt_for_new_password = false; + optind = 2; + while ((ch = getopt_long (argc, argv, ":hl:p:Pi:a:c:", longopts, NULL)) != -1) { + switch (ch) { + case 'h': + usage_mod (progname); + exit (0); + case 'l': new_entry.login = SVDUP (parse_login (optarg)); break; + case 'p': + new_entry.encoded_password = + SVDUP (encode_password (parse_password (SVCSTR (optarg)))); + break; + case 'P': prompt_for_new_password = true; break; + case 'i': new_entry.id = parse_id (optarg); break; + case 'a': new_entry.access_rights = parse_access_right (optarg); break; + case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break; + case '?': DIE ("unknown option -%c", optopt); + case ':': DIE ("missing argument for %s", argv[optind - 1]); + default: DIE ("unexpected opt error"); + } + } + + if (argv[optind] == NULL) { + fprintf (stderr, "error: no login provided\n"); + usage_mod (progname); + exit (1); + } + + if (argv[optind + 1] != NULL) + DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); + + struct string_view login = SVCSTR (argv[optind]); + struct passwd_entry *entry; + + struct passwd passwd = load_passwd_file (); + + if (getuid () == 0) { + entry = lookup_login (passwd, login); + if (!entry) + DIE ("user %.*s not found", SVFMT (login)); + + string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:", + time (NULL), SVFMT (entry->login), entry->id); + + if (new_entry.id != -1) { + if (lookup_id (passwd, new_entry.id)) + DIE ("user with id %d already exists", new_entry.id); + entry->id = new_entry.id; + string_builder_printf (&passwd_log, " new id %d,", entry->id); + } + + if (new_entry.access_rights != 0) { + entry->access_rights = new_entry.access_rights; + string_builder_printf (&passwd_log, " new access rights %c%c%c,", + entry->access_rights & AR_READ ? 'r' : '-', + entry->access_rights & AR_WRITE ? 'w' : '-', + entry->access_rights & AR_DELETE ? 'd' : '-'); + } + } else { + if (new_entry.id != -1) + DIE ("permission to change id denied"); + if (new_entry.access_rights != 0) + DIE ("permission to change access rights denied"); + + fputs ("Password: ", stdout); + struct string_view password = parse_password (read_password ()); + entry = authenticate (passwd, login, password); + if (!entry) exit (1); + string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:", + time (NULL), SVFMT (entry->login), entry->id); + } + + + if (prompt_for_new_password) { + fputs ("New password: ", stdout); + struct string_view password = SVDUP (parse_password (read_password ())); + fputs ("Repeat password: ", stdout); + struct string_view repeated = read_password (); + if (string_view_compare (password, repeated) != 0) + DIE ("passwords don't match"); + entry->encoded_password = SVDUP (encode_password (password)); + string_builder_printf (&passwd_log, " changed password,"); + } else if (new_entry.encoded_password.begin != NULL) { + entry->encoded_password = new_entry.encoded_password; + string_builder_printf (&passwd_log, " changed password,"); + } + + if (new_entry.comment.begin != NULL) { + entry->comment = new_entry.comment; + string_builder_printf (&passwd_log, " new comment `%.*s',", SVFMT (entry->comment)); + } + + if (new_entry.login.begin != NULL) { + entry->login = new_entry.login; + string_builder_printf (&passwd_log, " new login %.*s,", SVFMT (entry->login)); + } + + if (DYNAMIC_ARRAY_LAST (passwd_log) != ',') + DIE ("no modifications supplied"); + DYNAMIC_ARRAY_LAST (passwd_log) = '\n'; + + save_passwd_file (passwd); + close_passwd_file (passwd); + } break; + + case SUBCOMMAND_DELETE: { // login + static struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + {0} + }; + + char ch; + optind = 2; + while ((ch = getopt_long (argc, argv, ":h", longopts, NULL)) != -1) { + switch (ch) { + case 'h': + usage_del (progname); + exit (0); + case '?': DIE ("unknown option -%c", optopt); + case ':': DIE ("missing argument for %s", argv[optind - 1]); + default: DIE ("unexpected opt error"); + } + } + + if (argv[optind] == NULL) { + fprintf (stderr, "error: no login provided\n"); + usage_del (progname); + exit (1); + } + + if (argv[optind + 1] != NULL) + DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); + + if (getuid () != 0) + DIE ("permission denied"); + + struct string_view login = SVDUP (SVCSTR (argv[optind])); + struct passwd passwd = load_passwd_file (); + + struct passwd_entry *entry; + for (entry = passwd.items; entry < passwd.items + passwd.count; ++entry) { + if (SVCMP (login, entry->login) == 0) + break; + } + + if (entry == passwd.items + passwd.count) + DIE ("user %.*s doesn't exist", SVFMT (login)); + + string_builder_printf (&passwd_log, "%u deleted user %.*s with id %d", + time (NULL), SVFMT (entry->login), entry->id); + if (entry->comment.begin) + string_builder_printf (&passwd_log, " (%.*s)", SVFMT (entry->comment)); + DYNAMIC_ARRAY_APPEND (passwd_log, '\n'); + + if (entry + 1 != passwd.items + passwd.count) { + memmove (entry, entry + 1, + (passwd.count - (entry + 1 - passwd.items))*sizeof (*entry)); + } passwd.count -= 1; + + save_passwd_file (passwd); + close_passwd_file (passwd); + } break; + + default: + usage (progname); + exit (strcmp (value, "-h") != 0 && strcmp (value, "--help") != 0); + } + + append_passwd_log (); + + return EXIT_SUCCESS; +} + +// src/passwdctl.c ends here diff --git a/02/src/shell.c b/02/src/shell.c new file mode 100644 index 0000000..13666d7 --- /dev/null +++ b/02/src/shell.c @@ -0,0 +1,1215 @@ +// src/shell.c --- utility for providing access to protected folder +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common.h" + +#define CONFDATA PREFIX"/confdata" + +int id; + +struct command_line { + struct string_builder expanded; + struct string_view command; + union {struct string_view *items, *args; }; + union {uint32_t count, argc; }; + uint32_t capacity; +}; + +struct string_builder confdata_log = {0}; + +void +append_confdata_log () +{ + if (confdata_log.count) { + elevate (); + int fd = open (PREFIX"/log/confdata.log", O_CREAT | O_WRONLY | O_APPEND); + drop (); + write (fd, confdata_log.items, confdata_log.count); + close (fd); + DYNAMIC_ARRAY_RESET (confdata_log); + } +} + +struct string_view +canonicalize (struct string_view filename) +{ + static struct string_builder sb = {0}; + STRING_BUILDER_RESET (sb); + + static struct { + struct string_view *items; + uint32_t count; + uint32_t capacity; + } parts = {0}; + DYNAMIC_ARRAY_RESET (parts); + + bool ends_with_slash = filename.end[-1] == '/'; + + if (*filename.begin != '/') { + DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 128); + for (;;) { + if (getcwd (sb.string, sb.capacity)) { + sb.length = strlen (sb.string); + break; + } + if (errno != ERANGE) + return SVNULL; + DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 2*sb.capacity); + } + STRING_BUILDER_APPEND_CHAR (sb, '/'); + } + + STRING_BUILDER_APPEND_STRING_VIEW (sb, filename); + filename = SVSB (sb); + + while (++filename.begin < filename.end) { + struct string_view part = string_view_pop_up_to (&filename, '/'); + if (SVLEN (part) == 0) continue; + if (SVCMP (part, SVCSTR (".")) == 0) continue; + if (SVCMP (part, SVCSTR ("..")) == 0) { + if (parts.count == 0) return SVNULL; + parts.count -= 1; + continue; + } + DYNAMIC_ARRAY_APPEND (parts, part); + } + + STRING_BUILDER_RESET (sb); + for (struct string_view *part = parts.items; + part < parts.items + parts.count; ++part) { + STRING_BUILDER_APPEND_CHAR (sb, '/'); + STRING_BUILDER_APPEND_STRING_VIEW (sb, *part); + } + + if (ends_with_slash) + STRING_BUILDER_APPEND_CHAR (sb, '/'); + + return SVSB (sb); +} + +bool +is_conf (struct string_view filename) +{ + elevate (); + char *canonical = realpath (filename.begin, NULL); + if (!canonical) { + struct string_view dirname = SVDUP0 (string_view_dirname (filename)); + canonical = realpath (dirname.begin, NULL); + free ((void *) dirname.begin); + } + drop (); + + if (canonical) { + bool starts_with = string_view_starts_with (SVCSTR (canonical), SVCSTR (CONFDATA)); + free (canonical); + return starts_with; + } + + return false; +} + +bool +authorize_conf (int id, struct string_view filename, enum access_rights ar) +{ + bool ret = true; + struct passwd passwd = load_passwd_file (); + struct passwd_entry *entry = lookup_id (passwd, id); + if (!entry) { + fprintf (stderr, "user no longer exists, switch user"); + ret = false; + goto finish; + } + + if ((ar & entry->access_rights) != ar) { + fprintf (stderr, "access denied '%.*s'\n", SVFMT (filename)); + string_builder_printf (&passwd_log, + "%u user '%.*s' (%d) was denied access %c%c%c to '%.*s'\n", + time (NULL), SVFMT (entry->login), entry->id, + ar & AR_READ ? 'r' : '-', + ar & AR_WRITE ? 'w' : '-', + ar & AR_DELETE ? 'd' : '-', SVFMT (filename)); + ret = false; + goto finish; + } + string_builder_printf (&passwd_log, + "%u user '%.*s' (%d) was granted access %c%c%c to '%.*s'\n", + time (NULL), SVFMT (entry->login), entry->id, + ar & AR_READ ? 'r' : '-', + ar & AR_WRITE ? 'w' : '-', + ar & AR_DELETE ? 'd' : '-', SVFMT (filename)); + + finish: + close_passwd_file (passwd); + return ret; +} + +bool +authorize_reg (struct string_view filename, enum access_rights ar) +{ + if (ar == 0) return true; + + int how = 0; + how |= ar & AR_READ ? R_OK : 0; + how |= ar & (AR_WRITE | AR_DELETE) ? W_OK : 0; + if (access (filename.begin, how) == 0) + return true; + + struct string_view dirname = SVDUP0 (string_view_dirname (filename)); + int ret = access (dirname.begin, how); + free ((void *) dirname.begin); + if (ret == 0) + return true; + + fprintf (stderr, "access denied '%.*s': %s\n", + SVFMT (filename), strerror (errno)); + return false; +} + +bool +authorize (int id, struct string_view filename, enum access_rights ar) +{ + return is_conf (filename) + ? authorize_conf (id, filename, ar) + : authorize_reg (filename, ar); +} + +bool +authorize_known (int id, struct string_view filename, + enum access_rights ar, bool conf) +{ + return conf + ? authorize_conf (id, filename, ar) + : authorize_reg (filename, ar); +} + +bool +copy_file (struct string_view source, struct string_view destination) +{ + bool conf_source = is_conf (source); + bool conf_destination = is_conf (destination); + + if (conf_source && !conf_destination) { + fprintf (stderr, "access denied: no one can copy out of confdata\n"); + return false; + } + + if (!authorize_known (id, source, AR_READ, conf_source )) return false; + if (!authorize_known (id, destination, AR_WRITE, conf_destination)) return false; + + bool ret = true; + if (conf_source) elevate (); + int source_fd = open (source.begin, O_RDONLY); + if (conf_source) drop (); + if (source_fd == -1) { + fprintf (stderr, "error opening file for reading '%.*s': %s\n", + SVFMT (source), strerror (errno)); + return false; + } + + struct stat st; + if (fstat (source_fd, &st) == -1) { + fprintf (stderr, "error getting file stats for '%.*s': %s\n", + SVFMT (source), strerror (errno)); + ret = false; + goto close_source; + } + + if (!S_ISREG (st.st_mode)) { + fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source)); + ret = false; + goto close_source; + } + + if (conf_destination) elevate (); + int destination_fd = open (destination.begin, O_RDWR | O_CREAT | O_EXCL | + O_TRUNC, S_IRUSR | S_IWUSR); + if (conf_destination) drop (); + if (destination_fd == -1) { + fprintf (stderr, "error opening file for writing '%.*s': %s\n", + SVFMT (destination), strerror (errno)); + ret = false; + goto close_source; + } + + if (ftruncate (destination_fd, st.st_size) == -1) { + fprintf (stderr, "error setting file size for '%.*s': %s\n", + SVFMT (destination), strerror (errno)); + ret = false; + goto close_destination; + } + + void *source_map = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, source_fd, 0); + if (source_map == MAP_FAILED) { + fprintf (stderr, "error mapping source file '%.*s': %s\n", + SVFMT (source), strerror (errno)); + ret = false; + goto close_destination; + } + + void *destination_map = mmap (NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, destination_fd, 0); + if (destination_map == MAP_FAILED) { + fprintf (stderr, "error mapping destination file '%.*s': %s\n", + SVFMT (destination), strerror (errno)); + ret = false; + goto munmap_source; + } + + memcpy (destination_map, source_map, st.st_size); + + if (conf_destination) { + elevate (); + char *canonical = realpath (destination.begin, NULL); + drop (); + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + + munmap (destination_map, st.st_size); + munmap_source: + munmap (source_map, st.st_size); + close_destination: + close (destination_fd); + close_source: + close (source_fd); + + elevate (); + if (conf_destination) chown (destination.begin, euid, egid); + else chown (destination.begin, ruid, rgid); + drop (); + + return ret; +} + +bool +rename_file (struct string_view source, struct string_view destination) +{ + bool conf_source = is_conf (source); + bool conf_destination = is_conf (destination); + + if (conf_source && !conf_destination) { + fprintf (stderr, "access denied: no one can rename out of confdata\n"); + return false; + } + + if (!authorize_known (id, source, AR_READ | AR_DELETE, conf_source)) return false; + if (!authorize_known (id, destination, AR_WRITE, conf_destination)) return false; + + struct stat st; + if (stat (source.begin, &st) == -1) { + fprintf (stderr, "error getting file stats for '%.*s': %s\n", + SVFMT (source), strerror (errno)); + return false; + } + + if (!S_ISREG (st.st_mode)) { + fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source)); + return false; + } + + elevate (); + int res = access (destination.begin, F_OK); + drop (); + if (res == 0) { + fprintf (stderr, "destination file already exists '%.*s'\n", SVFMT (destination)); + return false; + } + + char *canonical = NULL; + if (conf_source || conf_destination) elevate (); + if (conf_source) canonical = realpath (source.begin, NULL); + res = rename (source.begin, destination.begin); + if (conf_source || conf_destination) drop (); + if (res == -1) { + fprintf (stderr, "error renaming '%.*s' to '%.*s': %s\n", + SVFMT (source), SVFMT (destination), strerror (errno)); + free (canonical); + return false; + } + + if (conf_destination) { + elevate (); + char *canonical = realpath (destination.begin, NULL); + drop (); + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + + if (conf_source) { + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + + elevate (); + if (conf_destination) chown (destination.begin, euid, egid); + else chown (destination.begin, ruid, rgid); + drop (); + + return true; +} + +int +parse_command_line (struct command_line *cl, struct string_view line) +{ + DYNAMIC_ARRAY_RESET (cl->expanded); + DYNAMIC_ARRAY_RESET (*cl); + cl->command = SVNULL; + + // printf ("line: %.*s\n", SVFMT (line)); + + const char *head = line.begin; + const char *end = line.end; + for (; head < end; ++head) { + if (*head == ' ' || *head == '\t') { + do head += 1; + while (head < end && (*head == ' ' || *head == '\t')); + if (head == end) + break; + if (cl->expanded.length) + STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0'); + } + + if (*head == '\'') { + head += 1; + if (head == end) return 0; + while (head < end && *head != '\'') + STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++); + if (head == end && (head[-1] != '\'' || head - 1 == line.begin)) return 0; + } else if (*head == '"') { + head += 1; + if (head == end) return 0; + if (*head == '!') { + STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA); + head += 1; + } + while (head < end && *head != '"') + STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++); + if (head == end && (head[-1] != '"' || head - 1 == line.begin)) return 0; + } else if (*head == '!' && (cl->expanded.length == 0 || DYNAMIC_ARRAY_LAST (cl->expanded) == '\0')) { + STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA); + } else { + STRING_BUILDER_APPEND_CHAR (cl->expanded, *head); + } + } STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0'); + + head = cl->expanded.string; + end = cl->expanded.string + cl->expanded.length; + cl->command.begin = head; + while (head < end && *head != '\0') + head += 1; + cl->command.end = head++; + + if (SVLEN (cl->command) == 0) return 0; + + while (head < end) { + struct string_view arg; + arg.begin = head; + do head += 1; + while (head < end && *head != '\0'); + arg.end = head++; + + const char *star = strchr (arg.begin, '*'); + struct string_view trimmed = arg; + if (star) { + if (star == arg.begin) { + trimmed = SVCSTR ("."); + } else { + trimmed = SVDUP0 ((struct string_view) { + .begin = arg.begin, + .end = star, + }); + } + } + + bool conf = is_conf (trimmed); + if (conf) elevate (); + glob_t globs; + if (glob (arg.begin, GLOB_MARK | GLOB_NOSORT | GLOB_BRACE | GLOB_TILDE_CHECK, NULL, &globs) != 0) { + DYNAMIC_ARRAY_APPEND (*cl, arg); + } else { + for (size_t i = 0; i < globs.gl_pathc; ++i) { + arg.begin = globs.gl_pathv[i]; + arg.end = arg.begin + strlen (arg.begin); + DYNAMIC_ARRAY_APPEND (*cl, SVDUP0 (arg)); + } + } + if (conf) drop (); + + globfree (&globs); + } + + // printf ("command: %.*s\n", SVFMT (cl->command)); + // for (uint32_t i = 0; i < cl->argc; ++i) + // printf ("arg: %.*s\n", SVFMT (cl->args[i])); + + return 1; +} + +int +command_exit (struct command_line cl) +{ + exit (0); +} + +int +command_help (struct command_line cl) +{ + puts ("Commands:"); + puts (" help display information about builtin commands"); + puts (" su LOGIN change user to LOGIN"); + puts (" pwd print the name of the current working directory "); + puts (" whoami print effective user name"); + puts (" echo [ARG]... write ARG(s) to the standard output"); + puts (" ls [FILE]... list information about the FILE(s)"); + puts (" cd [DIR] change the shell working directory"); + puts (" mv SOURCE DEST rename SOURCE to DEST"); + puts (" mv SOURCE... DIRECTORY move SOURCE(s) to DIRECTORY"); + puts (" cp SOURCE DEST copy SOURCE to DEST"); + puts (" cp SOURCE... DIRECTORY copy SOURCE(s) to DIRECTORY"); + puts (" rm FILE... remove (unlink) the FILE(s)"); + puts (" mkdir DIR... create the DIRECTORY(ies), if they do not already exist"); + puts (" rmdir DIR... remove the DIRECTORY(ies), if they are empty"); + puts (" cat [FILE]... concatenate FILE(s) to standard output"); + puts (" append FILE append text from standard input to FILE"); + puts (""); + puts ("Aliases:"); + puts (" read -> cat"); + puts (" copy -> cp"); + puts (" remove -> rm"); + puts (""); + return 0; +} + +int +command_su (struct command_line cl) +{ + if (cl.argc != 1) { + fprintf (stderr, "usage: %.*s LOGIN\n", SVFMT (cl.command)); + return 1; + } + + struct string_view login = cl.args[0]; + int ret = 0; + struct passwd passwd = load_passwd_file (); + struct passwd_entry *entry; + if (getuid () == 0) { + entry = lookup_login (passwd, login); + if (!entry) { + fprintf (stderr, "user %.*s doesn't exist\n", SVFMT (login)); + ret = 1; + goto close; + } + } else { + fputs ("Password: ", stdout); + struct string_view password = read_password (); + entry = authenticate (passwd, login, password); + if (!entry) { + ret = 1; + goto close; + } + } + id = entry->id; + + close: + close_passwd_file (passwd); + return ret; +} + +int +command_pwd (struct command_line cl) +{ + size_t size = 256; + + for (;;) { + char *buffer = (char *) malloc (size); + if (getcwd (buffer, size) == buffer) { + puts (buffer); + free (buffer); + return 0; + } + free (buffer); + if (errno != ERANGE) + return errno; + size *= 2; + } +} + +int +command_whoami (struct command_line cl) +{ + int ret = 0; + struct passwd passwd = load_passwd_file (); + struct passwd_entry *entry = lookup_id (passwd, id); + if (!entry) { + fprintf (stderr, "user with id %d no longed exists\n", id); + ret = 1; + goto close; + } + + printf ("%d %.*s (%.*s) %c%c%c\n", + id, SVFMT (entry->login), SVFMT (entry->comment), + entry->access_rights & AR_READ ? 'r' : '-', + entry->access_rights & AR_WRITE ? 'w' : '-', + entry->access_rights & AR_DELETE ? 'd' : '-'); + + close: + close_passwd_file (passwd); + return ret; +} + +int +command_echo (struct command_line cl) +{ + if (cl.argc == 0) + return 0; + + fputs (cl.args[0].begin, stdout); + for (uint32_t argind = 1; argind < cl.argc; ++argind) { + putchar (' '); + fputs (cl.args[argind].begin, stdout); + } putchar ('\n'); + + return 0; +} + +int +command_cd (struct command_line cl) +{ + struct string_view dir = cl.argc ? cl.args[0] : SVCSTR (CONFDATA); + bool conf = string_view_starts_with (dir, SVCSTR (CONFDATA)); + + if (conf) elevate (); + if (chdir (dir.begin) == -1) { + fprintf (stderr, "%.*s: cannot change directory to '%s': %s\n", + SVFMT (cl.command), dir.begin, strerror (errno)); + } + if (conf) drop (); + + return 0; +} + +bool +is_dir (struct string_view filename) +{ + struct stat st; + + elevate (); + int res = stat (filename.begin, &st); + drop (); + + if (res == -1) + return false; + + return S_ISDIR (st.st_mode); +} + +int +command_mv (struct command_line cl) +{ + if (cl.argc < 2) { + fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); + fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); + return 1; + } + + int ret = 0; + + if (is_dir (cl.args[cl.argc - 1])) { + struct string_builder sb = {0}; + + struct string_view directory = cl.args[cl.argc - 1]; + STRING_BUILDER_APPEND_STRING_VIEW (sb, directory); + if (DYNAMIC_ARRAY_LAST (sb) != '/') + STRING_BUILDER_APPEND_CHAR (sb, '/'); + + size_t directory_length = sb.length; + for (uint32_t i = 0; i < cl.argc - 1; ++i) { + sb.length = directory_length; + struct string_view source = cl.args[i]; + + struct string_view basename = string_view_basename (source); + STRING_BUILDER_APPEND_STRING_VIEW (sb, basename); + struct string_view destination = SVSB (sb); + STRING_BUILDER_APPEND_NULL (sb); + + if (!rename_file (source, destination)) { + fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n", + SVFMT (source), SVFMT (destination)); + ret = 1; + } + } + + STRING_BUILDER_FREE (sb); + } else { + if (cl.argc != 2) { + fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); + fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); + return 1; + } + + struct string_view source = cl.args[0]; + struct string_view destination = cl.args[1]; + if (!rename_file (source, destination)) { + fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n", + SVFMT (source), SVFMT (destination)); + ret = 1; + } + } + + return ret; +} + +int +command_cp (struct command_line cl) +{ + if (cl.argc < 2) { + fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); + fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); + return 1; + } + + int ret = 0; + + if (is_dir (cl.args[cl.argc - 1])) { + struct string_builder sb = {0}; + + struct string_view directory = cl.args[cl.argc - 1]; + STRING_BUILDER_APPEND_STRING_VIEW (sb, directory); + if (DYNAMIC_ARRAY_LAST (sb) != '/') + STRING_BUILDER_APPEND_CHAR (sb, '/'); + + size_t directory_length = sb.length; + for (uint32_t i = 0; i < cl.argc - 1; ++i) { + sb.length = directory_length; + struct string_view source = cl.args[i]; + + struct string_view basename = string_view_basename (source); + STRING_BUILDER_APPEND_STRING_VIEW (sb, basename); + struct string_view destination = SVSB (sb); + STRING_BUILDER_APPEND_NULL (sb); + + if (!copy_file (source, destination)) { + fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n", + SVFMT (source), SVFMT (destination)); + ret = 1; + } + } + + STRING_BUILDER_FREE (sb); + } else { + if (cl.argc != 2) { + fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); + fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); + return 1; + } + + struct string_view source = cl.args[0]; + struct string_view destination = cl.args[1]; + if (!copy_file (source, destination)) { + fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n", + SVFMT (source), SVFMT (destination)); + ret = 1; + } + } + + return ret; +} + +int +command_rm (struct command_line cl) +{ + if (cl.argc == 0) { + fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); + return 1; + } + + int ret = 0; + for (uint32_t argind = 0; argind < cl.argc; ++argind) { + struct string_view file = cl.args[argind]; + const char *filename = file.begin; + + bool conf = is_conf (file); + if (!authorize_known (id, file, AR_DELETE, conf)) { + ret = 1; + continue; + } + + char *canonical = NULL; + if (conf) { + elevate (); + canonical = realpath (filename, NULL); + } + int res = remove (filename); + if (conf) drop (); + if (res == -1) { + fprintf (stderr, "%.*s: cannot remove file '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + ret = 1; + free (canonical); + } else if (conf) { + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + } + + return ret; +} + +int +command_mkdir (struct command_line cl) +{ + if (cl.argc == 0) { + fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); + return 1; + } + + int ret = 0; + for (uint32_t argind = 0; argind < cl.argc; ++argind) { + const char *filename = cl.args[argind].begin; + + bool conf = is_conf (cl.args[argind]); + if (!authorize_known (id, cl.args[argind], AR_WRITE, conf)) { + ret = 1; + continue; + } + + if (conf) elevate (); + int res = mkdir (filename, S_IRUSR | S_IWUSR | S_IXUSR); + if (conf) drop (); + if (res == -1) { + fprintf (stderr, "%.*s: cannot create directory '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + ret = 1; + } else if (conf) { + elevate (); + char *canonical = realpath (filename, NULL); + drop (); + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d created directory '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + } + + return ret; +} + +int +command_rmdir (struct command_line cl) +{ + if (cl.argc == 0) { + fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); + return 1; + } + + int ret = 0; + for (uint32_t argind = 0; argind < cl.argc; ++argind) { + const char *filename = cl.args[argind].begin; + + bool conf = is_conf (cl.args[argind]); + if (!authorize_known (id, cl.args[argind], AR_DELETE, conf)) { + ret = 1; + continue; + } + char *canonical = NULL; + if (conf) { + elevate (); + canonical = realpath (filename, NULL); + } + int res = rmdir (filename); + if (conf) drop (); + if (res == -1) { + fprintf (stderr, "%.*s: cannot remove directory '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + ret = 1; + free (canonical); + } else if (conf) { + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d removed directory '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + } + + return ret; +} + +int +command_cat (struct command_line cl) +{ + int ret = 0; + for (uint32_t argind = 0; argind < cl.argc; ++argind) { + struct string_view file = cl.args[argind]; + bool conf = is_conf (file); + if (!authorize_known (id, file, AR_READ, conf)) continue; + + const char *filename = file.begin; + if (conf) elevate (); + int fd = open (filename, O_RDONLY); + if (conf) drop (); + if (fd == -1) { + fprintf (stderr, "%.*s: cannot access '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + ret = 1; + continue; + } + + struct stat st; + int res = fstat (fd, &st); + if (res == -1) { + fprintf (stderr, "%.*s: cannot access '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + ret = 2; + goto close; + } + + void *contents = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (contents == NULL) { + ret = 3; + goto close; + } + write (0, contents, st.st_size); + + if (conf) { + elevate (); + char *canonical = realpath (file.begin, NULL); + drop (); + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d read file '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + + munmap (contents, st.st_size); + close: + close (fd); + } + + drop (); + + return ret; +} + +int +command_append (struct command_line cl) +{ + static struct string_builder sb = {0}; + + if (cl.argc != 1) { + fprintf (stderr, "usage: %.*s FILE\n", SVFMT (cl.command)); + return 1; + } + + struct string_view filename = cl.args[0]; + + bool conf = is_conf (filename); + if (!authorize_known (id, filename, AR_WRITE, conf)) + return 1; + + STRING_BUILDER_RESET (sb); + char *line; + while ((line = readline ("append> ")) != NULL) { + STRING_BUILDER_APPEND_CSTR (sb, line); + STRING_BUILDER_APPEND_CHAR (sb, '\n'); + free (line); + } + + int ret = 0; + if (sb.length) { + if (!authorize_known (id, filename, AR_WRITE, conf)) + return 1; + + if (conf) elevate (); + int fd = open (filename.begin, O_WRONLY | O_CREAT | O_APPEND); + if (conf) drop (); + if (fd == -1) { + fprintf (stderr, "failed to open '%.*s' for writing\n", SVFMT (filename)); + return 1; + } + + write (fd, sb.string, sb.length); + + if (conf) { + elevate (); + char *canonical = realpath (filename.begin, NULL); + drop (); + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d appended to file '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + + close (fd); + } + + return 0; +} + +int +command_ls (struct command_line cl) +{ + if (cl.argc == 0) + DYNAMIC_ARRAY_APPEND (cl, SVCSTR (".")); + + for (uint32_t argind = 0; argind < cl.argc; ++argind) { + struct string_view file = cl.args[argind]; + const char *filename = file.begin; + + bool conf = is_conf (file); + if (!authorize_known (id, file, AR_READ, conf)) + continue; + + if (conf) elevate (); + int fd = open (filename, O_RDONLY); + if (conf) drop (); + if (fd == -1) { + fprintf (stderr, "%.*s: cannot access '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + continue; + } + + struct stat st; + if (fstat (fd, &st) == -1) { + fprintf (stderr, "%.*s: cannot access '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + goto close; + } + + if (S_ISREG (st.st_mode)) { + printf ("%s\n", filename); + if (conf) { + elevate (); + char *canonical = realpath (filename, NULL); + drop (); + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d listed file '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + goto close; + } + + DIR *dir = fdopendir (fd); + if (dir == NULL) { + fprintf (stderr, "%.*s: cannot access '%s': %s\n", + SVFMT (cl.command), filename, strerror (errno)); + goto close; + } + + if (argind != 0) putchar ('\n'); + printf ("%s:\n", filename); + struct dirent *entry; + while ((entry = readdir (dir)) != NULL) { + if (strcmp (entry->d_name, ".") == 0 || + strcmp (entry->d_name, "..") == 0) { + continue; + } + + if (entry->d_type == DT_DIR) + printf ("%s/\n", entry->d_name); + else + printf ("%s\n", entry->d_name); + } + + if (conf) { + elevate (); + char *canonical = realpath (filename, NULL); + drop (); + assert (canonical); + string_builder_printf (&confdata_log, "%u user %d listed directory '!%s'\n", + time (NULL), id, canonical + strlen (CONFDATA)); + free (canonical); + } + + closedir (dir); + close: + close (fd); + } + + return 0; +} + +const char * +prompt (int ret) +{ + static struct string_builder sb = {0}; + + STRING_BUILDER_RESET (sb); + STRING_BUILDER_APPEND_CSTR (sb, "\e[36m[\e[34m"); + + struct passwd passwd = load_passwd_file (); + struct passwd_entry *entry = lookup_id (passwd, id); + if (entry) { + STRING_BUILDER_APPEND_STRING_VIEW (sb, entry->login); + +#ifdef MAC + STRING_BUILDER_APPEND_CSTR (sb, "\e[36m@"); + STRING_BUILDER_APPEND_CSTR (sb, entry->security_level == SL_COUNT - 1 + ? "\e[34m" + : "\e[31m"); + STRING_BUILDER_APPEND_CSTR (sb, security_level_names[entry->security_level]); +#endif + } else STRING_BUILDER_APPEND_CHAR (sb, '?'); + close_passwd_file (passwd); + + STRING_BUILDER_APPEND_CSTR (sb, "\e[36m:\e[34m"); + struct string_view canonical = canonicalize (SVCSTR (".")); + if (strncmp (canonical.begin, CONFDATA, strlen (CONFDATA)) == 0) { + STRING_BUILDER_APPEND_CHAR (sb, '!'); + canonical.begin += strlen (CONFDATA); + } STRING_BUILDER_APPEND_STRING_VIEW (sb, canonical); + + STRING_BUILDER_APPEND_CSTR (sb, "\e[36m]\e[34m"); + + if (ret) string_builder_printf (&sb, " \e[31m%d", ret); + + STRING_BUILDER_APPEND_CSTR (sb, ruid == euid ? " \e[31m#" : " \e[95m$"); + STRING_BUILDER_APPEND_CSTR (sb, "\e[0m "); + STRING_BUILDER_TERMINATE (sb); + + return sb.string; +} + +int +main (int argc, char *argv[]) +{ + ruid = getuid (); + rgid = getgid (); + euid = geteuid (); + egid = getegid (); + drop (); + + static struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + { "password", required_argument, NULL, 'p' }, + {0} + }; + char ch; + struct string_view password = {0}; + while ((ch = getopt_long (argc, argv, ":hp:", longopts, NULL)) != -1) { + switch (ch) { + case 'h': + printf ("Usage: %s [options] [LOGIN]\n", argv[0]); + puts (""); + puts ("Options:"); + puts (" -h, --help display this help message and exit"); + puts (" -p, --password PASSWORD password of the account (only if login was provided)"); + puts (""); + exit (0); + case 'p': password = SVCSTR (optarg); break; + case '?': DIE ("unknown option %s", argv[optind - 1]); + case ':': DIE ("missing argument for %s", argv[optind - 1]); + default: DIE ("unexpected opt error"); + } + } + + struct passwd passwd = load_passwd_file (); + struct passwd_entry *entry = NULL; + if (argv[optind] != NULL) { + if (argv[optind + 1] != NULL) + DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); + + struct string_view login = SVCSTR (argv[optind]); + if (ruid == 0) { + entry = lookup_login (passwd, login); + append_passwd_log (); + if (!entry) { + DIE ("user %.*s doesn't exist", SVFMT (login)); + } + } else { + if (password.begin == NULL) { + fputs ("Password: ", stdout); + password = read_password (); + } + entry = authenticate (passwd, login, password); + append_passwd_log (); + if (entry == NULL) exit (1); + } + } else { + do { + fputs ("Login: ", stdout); fflush (stdout); + struct string_view login = read_login (); + fputs ("Password: ", stdout); fflush (stdout); + struct string_view password = read_password (); + entry = authenticate (passwd, login, password); + } while (entry == NULL); + } + + id = entry->id; + printf ("Hello, %.*s! (%d)\n", SVFMT (entry->comment), id); + close_passwd_file (passwd); + printf ("Run 'help', to get a list of available commands.\n"); + + struct command_line cl = {0}; + int ret = 0; + for (;;) { + char *line = readline (prompt (ret)); + if (line == NULL) break; + add_history (line); + switch (parse_command_line (&cl, SVCSTR (line))) { + case 1: + if (SVCMP (cl.command, SVCSTR ("exit" )) == 0) ret = command_exit (cl); + else if (SVCMP (cl.command, SVCSTR ("help" )) == 0) ret = command_help (cl); + else if (SVCMP (cl.command, SVCSTR ("su" )) == 0) ret = command_su (cl); + else if (SVCMP (cl.command, SVCSTR ("pwd" )) == 0) ret = command_pwd (cl); + else if (SVCMP (cl.command, SVCSTR ("whoami")) == 0) ret = command_whoami (cl); + else if (SVCMP (cl.command, SVCSTR ("echo" )) == 0) ret = command_echo (cl); + else if (SVCMP (cl.command, SVCSTR ("ls" )) == 0) ret = command_ls (cl); + else if (SVCMP (cl.command, SVCSTR ("cd" )) == 0) ret = command_cd (cl); + else if (SVCMP (cl.command, SVCSTR ("mv" )) == 0) ret = command_mv (cl); + else if (SVCMP (cl.command, SVCSTR ("cp" )) == 0) ret = command_cp (cl); + else if (SVCMP (cl.command, SVCSTR ("rm" )) == 0) ret = command_rm (cl); + else if (SVCMP (cl.command, SVCSTR ("mkdir" )) == 0) ret = command_mkdir (cl); + else if (SVCMP (cl.command, SVCSTR ("rmdir" )) == 0) ret = command_rmdir (cl); + else if (SVCMP (cl.command, SVCSTR ("cat" )) == 0) ret = command_cat (cl); + else if (SVCMP (cl.command, SVCSTR ("read" )) == 0) ret = command_cat (cl); + else if (SVCMP (cl.command, SVCSTR ("copy" )) == 0) ret = command_cp (cl); + else if (SVCMP (cl.command, SVCSTR ("remove")) == 0) ret = command_rm (cl); + else if (SVCMP (cl.command, SVCSTR ("append")) == 0) ret = command_append (cl); + else puts ("unknown command, run `help' to get the list of available commands"); + break; + case 0: break; + case -1: + putchar ('\n'); + exit (0); + default: + fputs ("invalid command line", stderr); + break; + } free (line); + append_passwd_log (); + append_confdata_log (); + } putchar ('\n'); + + return EXIT_SUCCESS; +} + +// src/shell.c ends here diff --git a/02/src/string-builder.c b/02/src/string-builder.c new file mode 100644 index 0000000..9e70d10 --- /dev/null +++ b/02/src/string-builder.c @@ -0,0 +1,58 @@ +#include "string-builder.h" +#include +#include + +void +string_builder_append_ntimes (STRING_BUILDER sb, char c, size_t n) +{ + DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, n); + memset (sb->items + sb->count, c, n); + sb->count += n; +} + +void +string_builder_append_cstrs (STRING_BUILDER sb, ...) +{ + va_list args; + + va_start (args, sb); + const char *arg = va_arg (args, const char *); + while (arg) { + STRING_BUILDER_APPEND_CSTR(*sb, arg); + arg = va_arg (args, const char *); + } va_end (args); +} + +void +string_builder_printf (STRING_BUILDER sb, const char *format, ...) +{ + va_list args; + + va_start (args, format); + int size = vsnprintf (NULL, 0, format, args); + va_end (args); + ASSERT (size >= 0); + + DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, size + 1); + va_start (args, format); + vsnprintf (&sb->items[sb->count], size + 1, format, args); + va_end (args); + sb->count += size; +} + +bool +string_builder_getline (STRING_BUILDER sb) +{ + for (;;) { + int c = getchar (); + + if (c == EOF) + return false; + if (c == '\n') + break; + + STRING_BUILDER_APPEND_CHAR (*sb, c); + } + + return true; +} diff --git a/02/src/string-builder.h b/02/src/string-builder.h new file mode 100644 index 0000000..18367da --- /dev/null +++ b/02/src/string-builder.h @@ -0,0 +1,56 @@ +#ifndef INCLUDED_STRING_BUILDER_H +#define INCLUDED_STRING_BUILDER_H + +#include +#include +#include +#include "dynamic-array.h" + +struct string_builder { + union { char *items, *string; }; + union { size_t count, length; }; + size_t capacity; +}; +#define STRING_BUILDER struct string_builder * + +#define SBFMT(SB) (int) (SB).length, (SB).string + +#define STRING_BUILDER_APPEND_CHAR(SB, CHAR) \ + DYNAMIC_ARRAY_APPEND (SB, (char) CHAR) + +#define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE) \ + DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE) + +#define STRING_BUILDER_APPEND_CSTR(SB, CSTR) \ + ({ \ + const char *s = (CSTR); \ + size_t n = strlen (s); \ + DYNAMIC_ARRAY_APPEND_MANY(SB, s, n); \ + }) + +#define STRING_BUILDER_APPEND_CSTRS(SB, ...) \ + string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL) + +#define STRING_BUILDER_APPEND_STRING_VIEW(SB, SV) \ + DYNAMIC_ARRAY_APPEND_MANY(SB, (SV).begin, SVLEN (SV)); + +#define STRING_BUILDER_APPEND_NULL(SB) \ + DYNAMIC_ARRAY_APPEND (SB, '\0') + +#define STRING_BUILDER_TERMINATE(SB) ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY (SB, 1); \ + (SB).string[(SB).length] = '\0'; \ + }) + +#define STRING_BUILDER_RESET(SB) \ + DYNAMIC_ARRAY_RESET (SB) + +#define STRING_BUILDER_FREE(SB) \ + DYNAMIC_ARRAY_FREE(SB) + +void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n); +void string_builder_append_cstrs (STRING_BUILDER, ...); +void string_builder_printf (STRING_BUILDER, const char *format, ...); +bool string_builder_getline (STRING_BUILDER); + +#endif diff --git a/02/src/string-view.c b/02/src/string-view.c new file mode 100644 index 0000000..ef84f69 --- /dev/null +++ b/02/src/string-view.c @@ -0,0 +1,147 @@ +#include "string-view.h" +#include +#include + +size_t +string_view_length (struct string_view sv) +{ + return sv.end - sv.begin; +} + +struct string_view +string_view_from_cstr (const char *cstr) +{ + return (struct string_view) { + .begin = cstr, + .end = cstr + strlen (cstr), + }; +} + +struct string_view +duplicate_string_view (struct string_view sv) +{ + size_t len = SVLEN (sv); + + struct string_view result = { + .begin = malloc (len), + }; + result.end = result.begin + len; + + memcpy ((void *) result.begin, sv.begin, len); + + return result; +} + +struct string_view +duplicate_string_view_as_cstr (struct string_view sv) +{ + size_t len = SVLEN (sv); + + struct string_view result = { + .begin = malloc (len + 1), + }; + result.end = result.begin + len; + + memcpy ((void *) result.begin, sv.begin, len); + ((char *) result.begin)[len] = '\0'; + + return result; +} + +struct string_view +string_view_strdup (const char *cstr) +{ + struct string_view sv; + size_t len = strlen (cstr); + sv.begin = malloc (len + 1), + sv.end = sv.begin + len; + + memcpy ((void *) sv.begin, cstr, len); + ((char *) sv.begin)[len] = '\0'; + + return sv; +} + +int +string_view_compare (struct string_view lhs, struct string_view rhs) +{ + if (SVLEN (lhs) != SVLEN (rhs)) + return SVLEN (lhs) - SVLEN (rhs); + + return memcmp (lhs.begin, rhs.begin, SVLEN (lhs)); +} + +bool +string_view_starts_with (struct string_view sv, struct string_view prefix) +{ + if (SVLEN (sv) < SVLEN (prefix)) + return false; + + return memcmp (sv.begin, prefix.begin, SVLEN (prefix)) == 0; +} + +struct string_view +string_view_dirname (struct string_view sv) +{ + while (sv.end != sv.begin && sv.end[-1] == '/') + sv.end -= 1; + + while (sv.end != sv.begin && sv.end[-1] != '/') + sv.end -= 1; + + while (sv.end != sv.begin && sv.end[-1] == '/') + sv.end -= 1; + + if (sv.end == sv.begin) + return SVCSTR ("."); + + return sv; +} + +struct string_view +string_view_basename (struct string_view sv) +{ + const char *head = sv.end; + + while (head > sv.begin && head[-1] == '/') + head -= 1; + + while (head > sv.begin && head[-1] != '/') + head -= 1; + + if (head != sv.begin) + sv.begin = head; + + return sv; +} + +// pops all if c was not found +struct string_view +string_view_pop_up_to (struct string_view *sv, char c) +{ + const char *head = sv->begin; + + while (head < sv->end && *head != c) + head += 1; + + struct string_view result = { .begin = sv->begin }; + result.end = sv->begin = head; + + return result; +} + +struct string_view +string_view_pop_n (struct string_view *sv, size_t n) +{ + struct string_view result = { + .begin = sv->begin, + .end = sv->begin + n, + }; + + if (result.end > sv->end) + result.end = sv->end; + + sv->begin = result.end; + + return result; +} diff --git a/02/src/string-view.h b/02/src/string-view.h new file mode 100644 index 0000000..fa42d77 --- /dev/null +++ b/02/src/string-view.h @@ -0,0 +1,46 @@ +// src/string-view.h +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// Commentary: +// +// Code: + +#ifndef INCLUDED_STRING_VIEW_H +#define INCLUDED_STRING_VIEW_H + +#include +#include + +struct string_view { + const char *begin; + const char *end; +}; + +#define SVNULL ((struct string_view) {0}) +#define SVLEN string_view_length +#define SVFMT(SV) (int) SVLEN (SV), (SV).begin +#define SVCSTR string_view_from_cstr +#define SVDUP duplicate_string_view +#define SVDUP0 duplicate_string_view_as_cstr +#define SVSTRDUP string_view_strdup +#define SVCMP string_view_compare +#define SVSB(SB) ((struct string_view) { (SB).string, (SB).string + (SB).length }) + +size_t string_view_length (struct string_view sv); +struct string_view string_view_from_cstr (const char *cstr); +struct string_view duplicate_string_view (struct string_view sv); +struct string_view duplicate_string_view_as_cstr (struct string_view sv); +struct string_view string_view_strdup (const char *cstr); +int string_view_compare (struct string_view lhs, struct string_view rhs); +bool string_view_starts_with (struct string_view sv, struct string_view prefix); +struct string_view string_view_dirname (struct string_view); +struct string_view string_view_basename (struct string_view); +struct string_view string_view_pop_up_to (struct string_view *, char); +struct string_view string_view_pop_n (struct string_view *, size_t n); + +#endif // INCLUDED_STRING_VIEW_H + +// src/string-view.h ends here -- cgit v1.3.1