diff options
| author | 2026-11-11 05:31:06 +0000 | |
|---|---|---|
| committer | 2026-11-11 06:14:42 +0000 | |
| commit | 9e1d304cac5367c3dbb1ca14700736680bd3a804 (patch) | |
| tree | 31f328747acb934d365d423adfda144818ff5ad4 | |
| download | lab-01-05-master.tar.gz | |
60 files changed, 11382 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..49ee6be --- /dev/null +++ b/.gitignore | |||
| @@ -0,0 +1,5 @@ | |||
| 1 | *.html | ||
| 2 | |||
| 3 | *.tex | ||
| 4 | *.dot | ||
| 5 | *.png | ||
diff --git a/02/.envrc b/02/.envrc new file mode 100644 index 0000000..93bd67c --- /dev/null +++ b/02/.envrc | |||
| @@ -0,0 +1,3 @@ | |||
| 1 | export PREFIX=/usr/local/practice2 | ||
| 2 | export CONFDATA=${PREFIX}/confdata | ||
| 3 | export PATH=${PATH}:${PREFIX}/bin | ||
diff --git a/02/.gitignore b/02/.gitignore new file mode 100644 index 0000000..b38c21b --- /dev/null +++ b/02/.gitignore | |||
| @@ -0,0 +1,4 @@ | |||
| 1 | /bruteforce | ||
| 2 | /measure | ||
| 3 | /passwdctl | ||
| 4 | /shell | ||
diff --git a/02/build.sh b/02/build.sh new file mode 100755 index 0000000..ec08c31 --- /dev/null +++ b/02/build.sh | |||
| @@ -0,0 +1,56 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | ## build.sh | ||
| 3 | # | ||
| 4 | # Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 5 | # | ||
| 6 | # SPDX-License-Identifier: MIT | ||
| 7 | # | ||
| 8 | ## Commentary: | ||
| 9 | # | ||
| 10 | ## Code: | ||
| 11 | |||
| 12 | ROOT="$(dirname "$0")" | ||
| 13 | |||
| 14 | CC=cc | ||
| 15 | |||
| 16 | CFLAGS="$CFLAGS -std=gnu99" | ||
| 17 | CFLAGS="$CFLAGS -ggdb3" | ||
| 18 | CFLAGS="$CFLAGS -O3 -march=native" | ||
| 19 | CFLAGS="$CFLAGS -DNDEBUG" | ||
| 20 | CFLAGS="$CFLAGS -Wall -Wextra" | ||
| 21 | CFLAGS="$CFLAGS -Wno-unused-function" | ||
| 22 | CFLAGS="$CFLAGS -Wno-unused-variable" | ||
| 23 | CFLAGS="$CFLAGS -Wno-unused-parameter" | ||
| 24 | CFLAGS="$CFLAGS -Wno-unused-but-set-variable" | ||
| 25 | CFLAGS="$CFLAGS -Wno-parentheses" | ||
| 26 | CFLAGS="$CFLAGS -I$ROOT/src/" | ||
| 27 | |||
| 28 | set -xeu | ||
| 29 | |||
| 30 | $CC $CFLAGS -o $ROOT/src/string-builder.o -c $ROOT/src/string-builder.c | ||
| 31 | $CC $CFLAGS -o $ROOT/src/string-view.o -c $ROOT/src/string-view.c | ||
| 32 | $CC $CFLAGS -o $ROOT/src/common.o -c $ROOT/src/common.c | ||
| 33 | $CC $CFLAGS -o $ROOT/src/cracking.o -c $ROOT/src/cracking.c | ||
| 34 | |||
| 35 | $CC $CFLAGS -lcrypto -o $ROOT/passwdctl \ | ||
| 36 | $ROOT/src/common.o \ | ||
| 37 | $ROOT/src/string-builder.o \ | ||
| 38 | $ROOT/src/string-view.o \ | ||
| 39 | $ROOT/src/passwdctl.c | ||
| 40 | $CC $CFLAGS -lcrypto -lreadline -o $ROOT/shell \ | ||
| 41 | $ROOT/src/common.o \ | ||
| 42 | $ROOT/src/string-builder.o \ | ||
| 43 | $ROOT/src/string-view.o \ | ||
| 44 | $ROOT/src/shell.c | ||
| 45 | $CC $CFLAGS -o $ROOT/bruteforce \ | ||
| 46 | $ROOT/src/string-builder.o \ | ||
| 47 | $ROOT/src/string-view.o \ | ||
| 48 | $ROOT/src/cracking.o \ | ||
| 49 | $ROOT/src/bruteforce.c | ||
| 50 | $CC $CFLAGS -o $ROOT/measure \ | ||
| 51 | $ROOT/src/string-builder.o \ | ||
| 52 | $ROOT/src/string-view.o \ | ||
| 53 | $ROOT/src/cracking.o \ | ||
| 54 | $ROOT/src/measure.c | ||
| 55 | |||
| 56 | ## build.sh ends here | ||
diff --git a/02/install.sh b/02/install.sh new file mode 100755 index 0000000..89feda2 --- /dev/null +++ b/02/install.sh | |||
| @@ -0,0 +1,41 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | ## install.sh | ||
| 3 | # | ||
| 4 | # Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 5 | # | ||
| 6 | # SPDX-License-Identifier: MIT | ||
| 7 | # | ||
| 8 | ## Commentary: | ||
| 9 | # | ||
| 10 | ## Code: | ||
| 11 | |||
| 12 | if [ "$(id -u)" != 0 ]; then | ||
| 13 | echo "$0: permission denied" | ||
| 14 | exit 1 | ||
| 15 | fi | ||
| 16 | |||
| 17 | cd "$(dirname "$0")" | ||
| 18 | |||
| 19 | PREFIX=/usr/local/practice2 | ||
| 20 | |||
| 21 | set -xeu | ||
| 22 | |||
| 23 | install -o root -g root -m 755 -d $PREFIX | ||
| 24 | install -o root -g root -m 755 -d $PREFIX/bin | ||
| 25 | install -o root -g root -m 700 -d $PREFIX/etc | ||
| 26 | install -o root -g root -m 700 -d $PREFIX/confdata | ||
| 27 | install -o root -g root -m 700 -d $PREFIX/log | ||
| 28 | |||
| 29 | install -o root -g root -m 6711 passwdctl $PREFIX/bin/passwdctl | ||
| 30 | install -o root -g root -m 6711 shell $PREFIX/bin/shell | ||
| 31 | install bruteforce $PREFIX/bin/bruteforce | ||
| 32 | install measure $PREFIX/bin/measure | ||
| 33 | |||
| 34 | umask 177 | ||
| 35 | [ ! -f $PREFIX/etc/passwd ] && touch $PREFIX/etc/passwd | ||
| 36 | [ ! -f $PREFIX/log/passwd.log ] && touch $PREFIX/log/passwd.log | ||
| 37 | [ ! -f $PREFIX/log/confdata.log ] && touch $PREFIX/log/confdata.log | ||
| 38 | |||
| 39 | exit 0 | ||
| 40 | |||
| 41 | ## install.sh ends here | ||
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 @@ | |||
| 1 | // src/bruteforce.c --- utility to bruteforce shell password | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <stddef.h> | ||
| 12 | |||
| 13 | #include "cracking.h" | ||
| 14 | |||
| 15 | int | ||
| 16 | main (int argc, char *argv[]) | ||
| 17 | { | ||
| 18 | if (argc != 2) { | ||
| 19 | fprintf (stderr, "Usage: %s LOGIN\n", argv[0]); | ||
| 20 | exit (EXIT_FAILURE); | ||
| 21 | } | ||
| 22 | |||
| 23 | struct shell shell = spawn_shell (); | ||
| 24 | struct string_view login = SVCSTR (argv[1]); | ||
| 25 | struct string_builder password = {0}; | ||
| 26 | STRING_BUILDER_APPEND_STRING_VIEW (password, SVCSTR ("A")); | ||
| 27 | |||
| 28 | for (size_t attmept = 0;; ++attmept) { | ||
| 29 | if (attmept % 10000 == 0) | ||
| 30 | printf ("Trying: %.*s\n", SBFMT (password)); | ||
| 31 | |||
| 32 | if (test_credentials (shell, login, SVSB (password))) | ||
| 33 | break; | ||
| 34 | |||
| 35 | password_bump (&password); | ||
| 36 | } | ||
| 37 | |||
| 38 | printf ("Found: %.*s\n", SVFMT (SVSB (password))); | ||
| 39 | |||
| 40 | return EXIT_SUCCESS; | ||
| 41 | } | ||
| 42 | |||
| 43 | // 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 @@ | |||
| 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 | |||
| 10 | struct string_builder passwd_log = {0}; | ||
| 11 | |||
| 12 | uid_t ruid; | ||
| 13 | gid_t rgid; | ||
| 14 | uid_t euid; | ||
| 15 | gid_t egid; | ||
| 16 | |||
| 17 | char | ||
| 18 | encode6 (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 | |||
| 28 | unsigned char | ||
| 29 | decode6 (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 | |||
| 38 | void | ||
| 39 | encode (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 | |||
| 62 | void | ||
| 63 | decode (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 | |||
| 98 | void | ||
| 99 | generate_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 | |||
| 107 | unsigned char * | ||
| 108 | hash_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 | |||
| 144 | struct string_view | ||
| 145 | encode_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 | |||
| 168 | bool | ||
| 169 | check_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 | |||
| 199 | int | ||
| 200 | fscan_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 | |||
| 237 | void | ||
| 238 | fprint_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 | |||
| 260 | void | ||
| 261 | lock_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 | |||
| 267 | void | ||
| 268 | unlock_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 | |||
| 274 | struct passwd | ||
| 275 | load_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 | |||
| 302 | void | ||
| 303 | save_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 | |||
| 313 | void | ||
| 314 | close_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 | |||
| 329 | struct string_view | ||
| 330 | read_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 | |||
| 355 | struct string_view | ||
| 356 | read_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 | |||
| 373 | struct passwd_entry * | ||
| 374 | authenticate (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 | |||
| 398 | void | ||
| 399 | append_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 | |||
| 411 | struct passwd_entry * | ||
| 412 | lookup_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 | |||
| 431 | struct passwd_entry * | ||
| 432 | lookup_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 | |||
| 451 | void | ||
| 452 | elevate (void) | ||
| 453 | { | ||
| 454 | if (euid != ruid) seteuid (euid); | ||
| 455 | if (egid != rgid) setegid (egid); | ||
| 456 | } | ||
| 457 | |||
| 458 | void | ||
| 459 | drop (void) | ||
| 460 | { | ||
| 461 | if (euid != ruid) seteuid (ruid); | ||
| 462 | if (egid != rgid) setegid (rgid); | ||
| 463 | } | ||
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 @@ | |||
| 1 | // common.h --- common functions | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_COMMON_H | ||
| 12 | #define INCLUDED_COMMON_H | ||
| 13 | |||
| 14 | #include <stddef.h> | ||
| 15 | #include <stdint.h> | ||
| 16 | #include <stdio.h> | ||
| 17 | #include <stdbool.h> | ||
| 18 | |||
| 19 | #include <openssl/sha.h> | ||
| 20 | |||
| 21 | #include "string-view.h" | ||
| 22 | #include "string-builder.h" | ||
| 23 | |||
| 24 | #define PREFIX "/usr/local/practice2" | ||
| 25 | |||
| 26 | #define STRINGIFY(ARG) #ARG | ||
| 27 | #define TO_STRING(ARG) STRINGIFY (ARG) | ||
| 28 | |||
| 29 | #define DIE(FMT, ...) do { \ | ||
| 30 | fprintf (stderr, "fatal: " FMT "\n" __VA_OPT__ (,) __VA_ARGS__); \ | ||
| 31 | exit (EXIT_FAILURE); \ | ||
| 32 | } while (0) | ||
| 33 | |||
| 34 | #define LOGIN_MAX_LENGTH 32 | ||
| 35 | #define LOGIN_REGEX "[a-zA-Z][-_a-zA-Z0-9]*" | ||
| 36 | |||
| 37 | #define COMMENT_MAX_LENGTH 256 | ||
| 38 | #define COMMENT_REGEX "[^:\n]*" | ||
| 39 | |||
| 40 | #define PASSWORD_MAX_LENGTH 256 | ||
| 41 | #define PASSWORD_SALT_SIZE 12 | ||
| 42 | #define PASSWORD_SALT_LENGTH 16 | ||
| 43 | #define PASSWORD_HASH_LENGTH 27 | ||
| 44 | #define PASSWORD_ENCODED_LENGTH (3 + PASSWORD_SALT_LENGTH + 1 + PASSWORD_HASH_LENGTH) | ||
| 45 | #define PASSWORD_REGEX "[a-zA-Z][a-zA-Z0-9!@#$%^&*()]*" | ||
| 46 | |||
| 47 | extern struct string_builder passwd_log; | ||
| 48 | |||
| 49 | extern uid_t ruid; | ||
| 50 | extern gid_t rgid; | ||
| 51 | extern uid_t euid; | ||
| 52 | extern gid_t egid; | ||
| 53 | |||
| 54 | struct passwd_entry { | ||
| 55 | struct string_view login; | ||
| 56 | struct string_view encoded_password; | ||
| 57 | int id; | ||
| 58 | enum access_rights { | ||
| 59 | AR_READ = 1 << 0, | ||
| 60 | AR_WRITE = 1 << 1, | ||
| 61 | AR_DELETE = 1 << 2, | ||
| 62 | } access_rights; | ||
| 63 | struct string_view comment; | ||
| 64 | }; | ||
| 65 | |||
| 66 | struct passwd { | ||
| 67 | struct passwd_entry *items; | ||
| 68 | uint32_t count; | ||
| 69 | uint32_t capacity; | ||
| 70 | FILE *stream; | ||
| 71 | }; | ||
| 72 | |||
| 73 | char encode6 (unsigned char b6); | ||
| 74 | unsigned char decode6 (char c); | ||
| 75 | void encode (char *into, const unsigned char* from, unsigned int size); | ||
| 76 | void decode (unsigned char *into, struct string_view from); | ||
| 77 | |||
| 78 | void generate_salt (unsigned char salt[PASSWORD_SALT_SIZE]); | ||
| 79 | unsigned char *hash_password (unsigned char hash[SHA_DIGEST_LENGTH], | ||
| 80 | struct string_view password, | ||
| 81 | const unsigned char salt[PASSWORD_SALT_SIZE]); | ||
| 82 | struct string_view encode_password (struct string_view password); | ||
| 83 | bool check_password (struct string_view password, | ||
| 84 | struct string_view encoded_password); | ||
| 85 | |||
| 86 | int fscan_passwd_entry (FILE *, struct passwd_entry *); | ||
| 87 | void fprint_passwd_entry (FILE *, const struct passwd_entry *); | ||
| 88 | struct passwd load_passwd_file (void); | ||
| 89 | void save_passwd_file (struct passwd); | ||
| 90 | void close_passwd_file (struct passwd); | ||
| 91 | |||
| 92 | struct string_view read_password (void); | ||
| 93 | struct string_view read_login (void); | ||
| 94 | |||
| 95 | void append_passwd_log (void); | ||
| 96 | |||
| 97 | struct passwd_entry *lookup_login (struct passwd, struct string_view login); | ||
| 98 | struct passwd_entry *lookup_id (struct passwd, int id); | ||
| 99 | |||
| 100 | struct passwd_entry *authenticate (struct passwd, struct string_view login, struct string_view password); | ||
| 101 | |||
| 102 | void elevate (void); | ||
| 103 | void drop (void); | ||
| 104 | |||
| 105 | #endif // INCLUDED_COMMON_H | ||
| 106 | |||
| 107 | // 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 @@ | |||
| 1 | #include <pty.h> | ||
| 2 | #include <termios.h> | ||
| 3 | #include <sys/wait.h> | ||
| 4 | |||
| 5 | #include "cracking.h" | ||
| 6 | |||
| 7 | void | ||
| 8 | password_bump (STRING_BUILDER sb) | ||
| 9 | { | ||
| 10 | if ('A' <= sb->string[0] && sb->string[0] < 'Z' || | ||
| 11 | 'a' <= sb->string[0] && sb->string[0] < 'z') { | ||
| 12 | sb->string[0] += 1; | ||
| 13 | return; | ||
| 14 | } | ||
| 15 | |||
| 16 | if (sb->string[0] == 'Z') { | ||
| 17 | sb->string[0] = 'a'; | ||
| 18 | return; | ||
| 19 | } | ||
| 20 | |||
| 21 | sb->string[0] = 'A'; | ||
| 22 | |||
| 23 | size_t index = 1; | ||
| 24 | |||
| 25 | again: | ||
| 26 | if (index == sb->length) { | ||
| 27 | STRING_BUILDER_APPEND_CHAR (*sb, '!'); | ||
| 28 | return; | ||
| 29 | } | ||
| 30 | |||
| 31 | if ('0' <= sb->string[index] && sb->string[index] < '9' || | ||
| 32 | 'A' <= sb->string[index] && sb->string[index] < 'Z' || | ||
| 33 | 'a' <= sb->string[index] && sb->string[index] < 'z') { | ||
| 34 | sb->string[index] += 1; | ||
| 35 | return; | ||
| 36 | } | ||
| 37 | |||
| 38 | switch (sb->string[index]) { | ||
| 39 | case '!': sb->string[index] = '@'; return; | ||
| 40 | case '@': sb->string[index] = '#'; return; | ||
| 41 | case '#': sb->string[index] = '$'; return; | ||
| 42 | case '$': sb->string[index] = '%'; return; | ||
| 43 | case '%': sb->string[index] = '^'; return; | ||
| 44 | case '^': sb->string[index] = '&'; return; | ||
| 45 | case '&': sb->string[index] = '*'; return; | ||
| 46 | case '*': sb->string[index] = '('; return; | ||
| 47 | case '(': sb->string[index] = ')'; return; | ||
| 48 | case ')': sb->string[index] = '0'; return; | ||
| 49 | |||
| 50 | case '9': sb->string[index] = 'A'; return; | ||
| 51 | case 'Z': sb->string[index] = 'a'; return; | ||
| 52 | } | ||
| 53 | |||
| 54 | sb->string[index] = '!'; | ||
| 55 | |||
| 56 | index += 1; | ||
| 57 | goto again; | ||
| 58 | } | ||
| 59 | |||
| 60 | bool | ||
| 61 | test_credentials (struct shell shell, | ||
| 62 | struct string_view login, | ||
| 63 | struct string_view password) | ||
| 64 | { | ||
| 65 | fprintf (shell.out, "%.*s\n%.*s\n", SVFMT (login), SVFMT (password)); | ||
| 66 | for (;;) { | ||
| 67 | int c = getc (shell.in); | ||
| 68 | if (c == '\n') | ||
| 69 | break; | ||
| 70 | } | ||
| 71 | int c = getc (shell.in); | ||
| 72 | if (c == 'H') | ||
| 73 | return true; | ||
| 74 | |||
| 75 | ungetc (c, shell.in); | ||
| 76 | return false; | ||
| 77 | } | ||
| 78 | |||
| 79 | struct shell | ||
| 80 | spawn_shell (void) | ||
| 81 | { | ||
| 82 | struct shell shell; | ||
| 83 | |||
| 84 | int fd_master; | ||
| 85 | int fd_slave; | ||
| 86 | |||
| 87 | if (openpty (&fd_master, &fd_slave, NULL, NULL, NULL) == -1) { | ||
| 88 | perror ("openpty"); | ||
| 89 | exit (EXIT_FAILURE); | ||
| 90 | } | ||
| 91 | |||
| 92 | shell.pid = fork (); | ||
| 93 | if (shell.pid == -1) { | ||
| 94 | perror ("fork"); | ||
| 95 | exit (EXIT_FAILURE); | ||
| 96 | } | ||
| 97 | |||
| 98 | if (shell.pid == 0) { | ||
| 99 | close (fd_master); | ||
| 100 | |||
| 101 | if (dup2 (fd_slave, STDIN_FILENO) == -1) { | ||
| 102 | perror ("dup2 stdin"); | ||
| 103 | _exit (1); | ||
| 104 | } | ||
| 105 | |||
| 106 | if (dup2 (fd_slave, STDOUT_FILENO) == -1) { | ||
| 107 | perror ("dup2 stdout"); | ||
| 108 | _exit (1); | ||
| 109 | } | ||
| 110 | |||
| 111 | close (fd_slave); | ||
| 112 | close (STDERR_FILENO); | ||
| 113 | |||
| 114 | struct termios term; | ||
| 115 | tcgetattr (STDIN_FILENO, &term); | ||
| 116 | term.c_lflag &= ~ECHO; | ||
| 117 | tcsetattr (STDIN_FILENO, 0, &term); | ||
| 118 | |||
| 119 | execlp ("shell", "shell", NULL); | ||
| 120 | perror ("execlp"); | ||
| 121 | _exit (1); | ||
| 122 | } | ||
| 123 | |||
| 124 | close (fd_slave); | ||
| 125 | |||
| 126 | shell.out = fdopen (fd_master, "w"); | ||
| 127 | shell.in = fdopen (fd_master, "r"); | ||
| 128 | |||
| 129 | return shell; | ||
| 130 | } | ||
| 131 | |||
| 132 | void | ||
| 133 | close_shell (struct shell shell) | ||
| 134 | { | ||
| 135 | fclose (shell.in); | ||
| 136 | fclose (shell.out); | ||
| 137 | waitpid (shell.pid, NULL, 0); | ||
| 138 | } | ||
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 @@ | |||
| 1 | /// src/cracking.h --- password cracking utilities | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_CRACKING_H | ||
| 12 | #define INCLUDED_CRACKING_H | ||
| 13 | |||
| 14 | #include <stdio.h> | ||
| 15 | #include <unistd.h> | ||
| 16 | |||
| 17 | #include "string-builder.h" | ||
| 18 | #include "string-view.h" | ||
| 19 | |||
| 20 | struct shell { | ||
| 21 | FILE *in; | ||
| 22 | FILE *out; | ||
| 23 | pid_t pid; | ||
| 24 | }; | ||
| 25 | |||
| 26 | void password_bump (STRING_BUILDER); | ||
| 27 | bool test_credentials (struct shell, | ||
| 28 | struct string_view login, | ||
| 29 | struct string_view password); | ||
| 30 | struct shell spawn_shell (void); | ||
| 31 | void close_shell (struct shell); | ||
| 32 | |||
| 33 | #endif // INCLUDED_CRACKING_H | ||
| 34 | |||
| 35 | /// 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 @@ | |||
| 1 | #ifndef INCLUDED_DYNAMIC_ARRAY_H | ||
| 2 | #define INCLUDED_DYNAMIC_ARRAY_H | ||
| 3 | |||
| 4 | #include <stdlib.h> | ||
| 5 | #include <assert.h> | ||
| 6 | |||
| 7 | #define MALLOC malloc | ||
| 8 | #define REALLOC realloc | ||
| 9 | #define FREE free | ||
| 10 | #define ASSERT assert | ||
| 11 | |||
| 12 | #ifndef DYNAMIC_ARRAY_INIT_CAP | ||
| 13 | #define DYNAMIC_ARRAY_INIT_CAP 256 | ||
| 14 | #endif | ||
| 15 | |||
| 16 | #define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ | ||
| 17 | ({ \ | ||
| 18 | if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ | ||
| 19 | if ((DYNAMIC_ARRAY).capacity == 0) \ | ||
| 20 | (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ | ||
| 21 | while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ | ||
| 22 | (DYNAMIC_ARRAY).capacity *= 2; \ | ||
| 23 | (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ | ||
| 24 | (DYNAMIC_ARRAY).capacity * \ | ||
| 25 | sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 26 | ASSERT((DYNAMIC_ARRAY).items); \ | ||
| 27 | } \ | ||
| 28 | }) | ||
| 29 | |||
| 30 | #define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ | ||
| 31 | ({ \ | ||
| 32 | (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ | ||
| 33 | (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ | ||
| 34 | (DYNAMIC_ARRAY).capacity * \ | ||
| 35 | sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 36 | ASSERT((DYNAMIC_ARRAY).items); \ | ||
| 37 | \ | ||
| 38 | }) | ||
| 39 | |||
| 40 | #define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ | ||
| 41 | ({ \ | ||
| 42 | DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ | ||
| 43 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ | ||
| 44 | }) | ||
| 45 | |||
| 46 | #define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ | ||
| 47 | ({ \ | ||
| 48 | DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ | ||
| 49 | memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ | ||
| 50 | (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 51 | (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ | ||
| 52 | }) | ||
| 53 | |||
| 54 | #define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \ | ||
| 55 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] | ||
| 56 | |||
| 57 | #define DYNAMIC_ARRAY_POP(DYNAMIC_ARRAY) \ | ||
| 58 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count--] | ||
| 59 | |||
| 60 | #define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) | ||
| 61 | |||
| 62 | #define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) | ||
| 63 | |||
| 64 | #define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ | ||
| 65 | typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ | ||
| 66 | ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) | ||
| 67 | |||
| 68 | #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 @@ | |||
| 1 | // src/measure.c --- utility to measure time to bruteforce | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <stddef.h> | ||
| 12 | #include <time.h> | ||
| 13 | #include <math.h> | ||
| 14 | |||
| 15 | #include "cracking.h" | ||
| 16 | |||
| 17 | int | ||
| 18 | main (int argc, char *argv[]) | ||
| 19 | { | ||
| 20 | if (argc != 2) { | ||
| 21 | fprintf (stderr, "Usage: %s LOGIN\n", argv[0]); | ||
| 22 | fprintf (stderr, "Note: LOGIN shouldn't have password of length 3 or 4\n"); | ||
| 23 | exit (EXIT_FAILURE); | ||
| 24 | } | ||
| 25 | |||
| 26 | struct shell shell = spawn_shell (); | ||
| 27 | clock_t start, end; | ||
| 28 | |||
| 29 | struct string_view login = SVCSTR (argv[1]); | ||
| 30 | struct string_builder password = {0}; | ||
| 31 | STRING_BUILDER_APPEND_STRING_VIEW (password, SVCSTR ("A!!")); | ||
| 32 | |||
| 33 | start = clock(); | ||
| 34 | while (password.length == 3) { | ||
| 35 | test_credentials (shell, login, SVSB (password)); | ||
| 36 | password_bump (&password); | ||
| 37 | } end = clock(); | ||
| 38 | double time3 = (end - start) /(double) CLOCKS_PER_SEC; | ||
| 39 | |||
| 40 | double per_try3 = time3/(52*72*72); | ||
| 41 | double time4_expected = per_try3*(52*pow (72, 3)); | ||
| 42 | printf ("Tried all 3 letter passwords in: %fs\n", time3); | ||
| 43 | printf ("Expected time to try all 4 letter passwords: %f min\n", time4_expected/60); | ||
| 44 | |||
| 45 | start = clock(); | ||
| 46 | while (password.length == 4) { | ||
| 47 | test_credentials (shell, login, SVSB (password)); | ||
| 48 | password_bump (&password); | ||
| 49 | } end = clock(); | ||
| 50 | double time4 = (end - start) /(double) CLOCKS_PER_SEC; | ||
| 51 | |||
| 52 | double per_try4 = time4/(52*72*72*72); | ||
| 53 | double per_try = (per_try3 + per_try4)/2; | ||
| 54 | |||
| 55 | double time5 = per_try*(52*pow (72, 4)); | ||
| 56 | double time6 = per_try*(52*pow (72, 5)); | ||
| 57 | double time7 = per_try*(52*pow (72, 6)); | ||
| 58 | double time8 = per_try*(52*pow (72, 7)); | ||
| 59 | |||
| 60 | printf ("Real time to try 3 letter passwords: %fs\n", time3); | ||
| 61 | printf ("Real time to try 4 letter passwords: %fs\n", time4); | ||
| 62 | printf ("Estimated time to try 5 letter passwords: %fs\n", time5); | ||
| 63 | printf ("Estimated time to try 6 letter passwords: %fs\n", time6); | ||
| 64 | printf ("Estimated time to try 7 letter passwords: %fs\n", time7); | ||
| 65 | printf ("Estimated time to try 8 letter passwords: %fs\n", time8); | ||
| 66 | |||
| 67 | return EXIT_SUCCESS; | ||
| 68 | } | ||
| 69 | |||
| 70 | // 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 @@ | |||
| 1 | // src/passwdctl.c --- utility to manage access to protected directory | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <stdbool.h> | ||
| 12 | #include <stdio.h> | ||
| 13 | #include <stdlib.h> | ||
| 14 | #include <string.h> | ||
| 15 | #include <assert.h> | ||
| 16 | #include <getopt.h> | ||
| 17 | #include <regex.h> | ||
| 18 | #include <unistd.h> | ||
| 19 | |||
| 20 | #include <openssl/evp.h> | ||
| 21 | #include <openssl/err.h> | ||
| 22 | |||
| 23 | #include "dynamic-array.h" | ||
| 24 | #include "string-builder.h" | ||
| 25 | #include "string-view.h" | ||
| 26 | #include "common.h" | ||
| 27 | |||
| 28 | #define SUBCOMMANDS() \ | ||
| 29 | X (ADD, "add") \ | ||
| 30 | X (MODIFY, "mod") \ | ||
| 31 | X (DELETE, "del") | ||
| 32 | |||
| 33 | #define X(SYM, STR) SUBCOMMAND_##SYM, | ||
| 34 | enum subcommand { | ||
| 35 | SUBCOMMANDS () | ||
| 36 | }; | ||
| 37 | #undef X | ||
| 38 | |||
| 39 | #define X(SYM, STR) [SUBCOMMAND_##SYM] = STR, | ||
| 40 | char *const subcommand_tokens[] = { | ||
| 41 | SUBCOMMANDS () | ||
| 42 | NULL | ||
| 43 | }; | ||
| 44 | #undef X | ||
| 45 | |||
| 46 | regex_t login_regex; | ||
| 47 | regex_t comment_regex; | ||
| 48 | regex_t password_regex; | ||
| 49 | |||
| 50 | struct string_view | ||
| 51 | parse_password (struct string_view sv) | ||
| 52 | { | ||
| 53 | if (regexec (&password_regex, sv.begin, 0, NULL, 0) != 0) | ||
| 54 | DIE ("password doesn't match regex %s", PASSWORD_REGEX); | ||
| 55 | |||
| 56 | return sv; | ||
| 57 | } | ||
| 58 | |||
| 59 | int | ||
| 60 | parse_id (const char *cstr) | ||
| 61 | { | ||
| 62 | int id; | ||
| 63 | size_t read; | ||
| 64 | sscanf (cstr, "%d%ln", &id, &read); | ||
| 65 | |||
| 66 | if (id < 0) DIE ("invalid id"); | ||
| 67 | if (read != strlen (cstr)) DIE ("invalid id"); | ||
| 68 | |||
| 69 | return id; | ||
| 70 | } | ||
| 71 | |||
| 72 | enum access_rights | ||
| 73 | parse_access_right (const char *cstr) | ||
| 74 | { | ||
| 75 | enum access_rights ar = 0; | ||
| 76 | |||
| 77 | while (*cstr) { | ||
| 78 | switch (*cstr++) { | ||
| 79 | case 'r': ar |= AR_READ; break; | ||
| 80 | case 'w': ar |= AR_WRITE; break; | ||
| 81 | case 'd': ar |= AR_DELETE; break; | ||
| 82 | default: DIE ("invalid access right: %c", cstr[-1]); | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | return ar; | ||
| 87 | } | ||
| 88 | |||
| 89 | struct string_view | ||
| 90 | parse_comment (const char *cstr) | ||
| 91 | { | ||
| 92 | struct string_view sv = SVCSTR (cstr); | ||
| 93 | |||
| 94 | if (SVLEN (sv) > COMMENT_MAX_LENGTH) | ||
| 95 | DIE ("comment too long"); | ||
| 96 | |||
| 97 | if (regexec (&comment_regex, cstr, 0, NULL, 0) != 0) | ||
| 98 | DIE ("comment doesn't match regex " COMMENT_REGEX); | ||
| 99 | |||
| 100 | return sv; | ||
| 101 | } | ||
| 102 | |||
| 103 | struct string_view | ||
| 104 | parse_login (const char *cstr) | ||
| 105 | { | ||
| 106 | struct string_view sv = SVCSTR (cstr); | ||
| 107 | |||
| 108 | if (SVLEN (sv) > LOGIN_MAX_LENGTH) | ||
| 109 | DIE ("login too long"); | ||
| 110 | |||
| 111 | if (regexec (&login_regex, cstr, 0, NULL, 0) != 0) | ||
| 112 | DIE ("login doesn't match regex " LOGIN_REGEX); | ||
| 113 | |||
| 114 | return sv; | ||
| 115 | } | ||
| 116 | |||
| 117 | const char * | ||
| 118 | regex_error (const regex_t *comp, int errcode) | ||
| 119 | { | ||
| 120 | static char *error = NULL; | ||
| 121 | size_t size = regerror (errcode, comp, NULL, 0); | ||
| 122 | error = realloc (error, size); | ||
| 123 | regerror (errcode, comp, error, size); | ||
| 124 | return error; | ||
| 125 | } | ||
| 126 | |||
| 127 | void | ||
| 128 | usage (const char *progname) | ||
| 129 | { | ||
| 130 | printf ("Usage: %s [options] COMMAND [ARGS]\n", progname); | ||
| 131 | puts (""); | ||
| 132 | puts ("Options:"); | ||
| 133 | puts (" -h, --help display this help message and exit"); | ||
| 134 | puts (""); | ||
| 135 | puts ("Commands:"); | ||
| 136 | puts (" add LOGIN add new account"); | ||
| 137 | puts (" mod LOGIN modify existing account"); | ||
| 138 | puts (" del LOGIN delete account"); | ||
| 139 | puts (""); | ||
| 140 | } | ||
| 141 | |||
| 142 | void | ||
| 143 | usage_add (const char *progname) | ||
| 144 | { | ||
| 145 | printf ("Usage: %s add [options] LOGIN\n", progname); | ||
| 146 | puts (""); | ||
| 147 | puts ("Options:"); | ||
| 148 | puts (" -h, --help display this help message and exit"); | ||
| 149 | puts (" -p, --password PASSWORD password of the new account"); | ||
| 150 | puts (" -i, --id ID ID of the new account"); | ||
| 151 | puts (" -a, --access-rights {r|w|d}... access right of the new account"); | ||
| 152 | puts (" -c, --comment COMMENT comment of the new account"); | ||
| 153 | puts (""); | ||
| 154 | } | ||
| 155 | |||
| 156 | void | ||
| 157 | usage_mod (const char *progname) | ||
| 158 | { | ||
| 159 | printf ("Usage: %s mod [options] LOGIN\n", progname); | ||
| 160 | puts (""); | ||
| 161 | puts ("Options:"); | ||
| 162 | puts (" -h, --help display this help message and exit"); | ||
| 163 | puts (" -l, --login NEW_LOGIN new login for the account"); | ||
| 164 | puts (" -p, --password PASSWORD new password for the account"); | ||
| 165 | puts (" -P prompt for new password for the account"); | ||
| 166 | puts (" -i, --id ID new ID for the account"); | ||
| 167 | puts (" -a, --access-rights {r|w|d}... new access rights for the account"); | ||
| 168 | puts (" -c, --comment COMMENT new comment for the account"); | ||
| 169 | puts (""); | ||
| 170 | } | ||
| 171 | |||
| 172 | void | ||
| 173 | usage_del (const char *progname) | ||
| 174 | { | ||
| 175 | printf ("Usage: %s del [options] LOGIN\n", progname); | ||
| 176 | puts (""); | ||
| 177 | puts ("Options:"); | ||
| 178 | puts (" -h, --help display this help message and exit"); | ||
| 179 | puts (""); | ||
| 180 | } | ||
| 181 | |||
| 182 | int | ||
| 183 | main (int argc, char *argv[]) | ||
| 184 | { | ||
| 185 | ruid = getuid (); | ||
| 186 | euid = geteuid (); | ||
| 187 | seteuid (ruid); | ||
| 188 | |||
| 189 | ERR_load_crypto_strings (); | ||
| 190 | |||
| 191 | const char *progname = argv[0]; | ||
| 192 | if (progname == NULL) | ||
| 193 | DIE ("unable to get program name"); | ||
| 194 | |||
| 195 | char **subcommand = &argv[1]; | ||
| 196 | if (*subcommand == NULL) { | ||
| 197 | usage (progname); | ||
| 198 | exit (1); | ||
| 199 | } | ||
| 200 | |||
| 201 | int errcode; | ||
| 202 | errcode = regcomp (&login_regex, "^" LOGIN_REGEX "$", REG_NOSUB); | ||
| 203 | if (errcode != 0) { | ||
| 204 | DIE ("unable to compile login regex: %s", | ||
| 205 | regex_error (&login_regex, errcode)); | ||
| 206 | } | ||
| 207 | |||
| 208 | errcode = regcomp (&password_regex, "^" PASSWORD_REGEX "$", REG_NOSUB); | ||
| 209 | if (errcode != 0) { | ||
| 210 | DIE ("unable to compile password regex: %s", | ||
| 211 | regex_error (&password_regex, errcode)); | ||
| 212 | } | ||
| 213 | |||
| 214 | errcode = regcomp (&comment_regex, "^" COMMENT_REGEX "$", REG_NOSUB); | ||
| 215 | if (errcode != 0) { | ||
| 216 | DIE ("unable to compile comment regex: %s", | ||
| 217 | regex_error (&comment_regex, errcode)); | ||
| 218 | } | ||
| 219 | |||
| 220 | char *value; | ||
| 221 | switch (getsubopt (subcommand, subcommand_tokens, &value)) { | ||
| 222 | case SUBCOMMAND_ADD: { | ||
| 223 | static struct option longopts[] = { | ||
| 224 | { "help", no_argument, NULL, 'h' }, | ||
| 225 | { "password", required_argument, NULL, 'p' }, | ||
| 226 | { "id", required_argument, NULL, 'i' }, | ||
| 227 | { "access-rights", required_argument, NULL, 'a' }, | ||
| 228 | { "comment", required_argument, NULL, 'c' }, | ||
| 229 | {0} | ||
| 230 | }; | ||
| 231 | char ch; | ||
| 232 | struct passwd_entry new_entry = { .id = -1 }; | ||
| 233 | optind = 2; | ||
| 234 | while ((ch = getopt_long (argc, argv, ":hp:i:a:c:", longopts, NULL)) != -1) { | ||
| 235 | switch (ch) { | ||
| 236 | case 'h': | ||
| 237 | usage_add (progname); | ||
| 238 | exit (0); | ||
| 239 | case 'p': | ||
| 240 | new_entry.encoded_password = | ||
| 241 | SVDUP (encode_password (parse_password (SVCSTR (optarg)))); | ||
| 242 | break; | ||
| 243 | case 'i': new_entry.id = parse_id (optarg); break; | ||
| 244 | case 'a': new_entry.access_rights = parse_access_right (optarg); break; | ||
| 245 | case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break; | ||
| 246 | case '?': DIE ("unknown option -%c", optopt); | ||
| 247 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 248 | default: DIE ("unexpected opt error"); | ||
| 249 | } | ||
| 250 | } | ||
| 251 | |||
| 252 | if (argv[optind] == NULL) { | ||
| 253 | fprintf (stderr, "error: no login provided\n"); | ||
| 254 | usage_add (progname); | ||
| 255 | exit (1); | ||
| 256 | } | ||
| 257 | |||
| 258 | if (argv[optind + 1] != NULL) | ||
| 259 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 260 | |||
| 261 | if (getuid () != 0) | ||
| 262 | DIE ("permission denied"); | ||
| 263 | |||
| 264 | new_entry.login = SVDUP (SVCSTR (argv[optind])); | ||
| 265 | |||
| 266 | if (new_entry.encoded_password.begin == NULL) { | ||
| 267 | fputs ("Password: ", stdout); | ||
| 268 | struct string_view password = duplicate_string_view_as_cstr (parse_password (read_password ())); | ||
| 269 | fputs ("Repeat password: ", stdout); | ||
| 270 | struct string_view repeated = read_password (); | ||
| 271 | if (string_view_compare (password, repeated) != 0) | ||
| 272 | DIE ("passwords don't match"); | ||
| 273 | |||
| 274 | new_entry.encoded_password = SVDUP (encode_password (password)); | ||
| 275 | } | ||
| 276 | |||
| 277 | struct passwd passwd = load_passwd_file (); | ||
| 278 | |||
| 279 | int max_id = -1; | ||
| 280 | for (struct passwd_entry *entry = passwd.items; | ||
| 281 | entry < passwd.items + passwd.count; ++entry) { | ||
| 282 | if (SVCMP (new_entry.login, entry->login) == 0) | ||
| 283 | DIE ("user %.*s already exists", SVFMT (entry->login)); | ||
| 284 | if (new_entry.id == entry->id) | ||
| 285 | DIE ("user with id %d already exists", entry->id); | ||
| 286 | if (entry->id > max_id) | ||
| 287 | max_id = entry->id; | ||
| 288 | } | ||
| 289 | |||
| 290 | if (new_entry.id < 0) | ||
| 291 | new_entry.id = max_id + 1; | ||
| 292 | |||
| 293 | DYNAMIC_ARRAY_APPEND (passwd, new_entry); | ||
| 294 | save_passwd_file (passwd); | ||
| 295 | |||
| 296 | string_builder_printf (&passwd_log, "%u added user %.*s %d", | ||
| 297 | time (NULL), SVFMT (new_entry.login), new_entry.id); | ||
| 298 | if (new_entry.comment.begin) | ||
| 299 | string_builder_printf (&passwd_log, " (%.*s)", SVFMT (new_entry.comment)); | ||
| 300 | string_builder_printf (&passwd_log, " with access rights %c%c%c\n", | ||
| 301 | new_entry.access_rights & AR_READ ? 'r' : '-', | ||
| 302 | new_entry.access_rights & AR_WRITE ? 'w' : '-', | ||
| 303 | new_entry.access_rights & AR_DELETE ? 'd' : '-'); | ||
| 304 | |||
| 305 | close_passwd_file (passwd); | ||
| 306 | } break; | ||
| 307 | |||
| 308 | case SUBCOMMAND_MODIFY: { // [-p --password=] [-i -id=] [-c --comment=] login | ||
| 309 | static struct option longopts[] = { | ||
| 310 | { "help", no_argument, NULL, 'h' }, | ||
| 311 | { "login", required_argument, NULL, 'l' }, | ||
| 312 | { "password", required_argument, NULL, 'p' }, | ||
| 313 | { "id", required_argument, NULL, 'i' }, | ||
| 314 | { "access-rights", required_argument, NULL, 'a' }, | ||
| 315 | { "comment", required_argument, NULL, 'c' }, | ||
| 316 | {0} | ||
| 317 | }; | ||
| 318 | char ch; | ||
| 319 | struct passwd_entry new_entry = { .id = -1 }; | ||
| 320 | bool prompt_for_new_password = false; | ||
| 321 | optind = 2; | ||
| 322 | while ((ch = getopt_long (argc, argv, ":hl:p:Pi:a:c:", longopts, NULL)) != -1) { | ||
| 323 | switch (ch) { | ||
| 324 | case 'h': | ||
| 325 | usage_mod (progname); | ||
| 326 | exit (0); | ||
| 327 | case 'l': new_entry.login = SVDUP (parse_login (optarg)); break; | ||
| 328 | case 'p': | ||
| 329 | new_entry.encoded_password = | ||
| 330 | SVDUP (encode_password (parse_password (SVCSTR (optarg)))); | ||
| 331 | break; | ||
| 332 | case 'P': prompt_for_new_password = true; break; | ||
| 333 | case 'i': new_entry.id = parse_id (optarg); break; | ||
| 334 | case 'a': new_entry.access_rights = parse_access_right (optarg); break; | ||
| 335 | case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break; | ||
| 336 | case '?': DIE ("unknown option -%c", optopt); | ||
| 337 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 338 | default: DIE ("unexpected opt error"); | ||
| 339 | } | ||
| 340 | } | ||
| 341 | |||
| 342 | if (argv[optind] == NULL) { | ||
| 343 | fprintf (stderr, "error: no login provided\n"); | ||
| 344 | usage_mod (progname); | ||
| 345 | exit (1); | ||
| 346 | } | ||
| 347 | |||
| 348 | if (argv[optind + 1] != NULL) | ||
| 349 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 350 | |||
| 351 | struct string_view login = SVCSTR (argv[optind]); | ||
| 352 | struct passwd_entry *entry; | ||
| 353 | |||
| 354 | struct passwd passwd = load_passwd_file (); | ||
| 355 | |||
| 356 | if (getuid () == 0) { | ||
| 357 | entry = lookup_login (passwd, login); | ||
| 358 | if (!entry) | ||
| 359 | DIE ("user %.*s not found", SVFMT (login)); | ||
| 360 | |||
| 361 | string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:", | ||
| 362 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 363 | |||
| 364 | if (new_entry.id != -1) { | ||
| 365 | if (lookup_id (passwd, new_entry.id)) | ||
| 366 | DIE ("user with id %d already exists", new_entry.id); | ||
| 367 | entry->id = new_entry.id; | ||
| 368 | string_builder_printf (&passwd_log, " new id %d,", entry->id); | ||
| 369 | } | ||
| 370 | |||
| 371 | if (new_entry.access_rights != 0) { | ||
| 372 | entry->access_rights = new_entry.access_rights; | ||
| 373 | string_builder_printf (&passwd_log, " new access rights %c%c%c,", | ||
| 374 | entry->access_rights & AR_READ ? 'r' : '-', | ||
| 375 | entry->access_rights & AR_WRITE ? 'w' : '-', | ||
| 376 | entry->access_rights & AR_DELETE ? 'd' : '-'); | ||
| 377 | } | ||
| 378 | } else { | ||
| 379 | if (new_entry.id != -1) | ||
| 380 | DIE ("permission to change id denied"); | ||
| 381 | if (new_entry.access_rights != 0) | ||
| 382 | DIE ("permission to change access rights denied"); | ||
| 383 | |||
| 384 | fputs ("Password: ", stdout); | ||
| 385 | struct string_view password = parse_password (read_password ()); | ||
| 386 | entry = authenticate (passwd, login, password); | ||
| 387 | if (!entry) exit (1); | ||
| 388 | string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:", | ||
| 389 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 390 | } | ||
| 391 | |||
| 392 | |||
| 393 | if (prompt_for_new_password) { | ||
| 394 | fputs ("New password: ", stdout); | ||
| 395 | struct string_view password = SVDUP (parse_password (read_password ())); | ||
| 396 | fputs ("Repeat password: ", stdout); | ||
| 397 | struct string_view repeated = read_password (); | ||
| 398 | if (string_view_compare (password, repeated) != 0) | ||
| 399 | DIE ("passwords don't match"); | ||
| 400 | entry->encoded_password = SVDUP (encode_password (password)); | ||
| 401 | string_builder_printf (&passwd_log, " changed password,"); | ||
| 402 | } else if (new_entry.encoded_password.begin != NULL) { | ||
| 403 | entry->encoded_password = new_entry.encoded_password; | ||
| 404 | string_builder_printf (&passwd_log, " changed password,"); | ||
| 405 | } | ||
| 406 | |||
| 407 | if (new_entry.comment.begin != NULL) { | ||
| 408 | entry->comment = new_entry.comment; | ||
| 409 | string_builder_printf (&passwd_log, " new comment `%.*s',", SVFMT (entry->comment)); | ||
| 410 | } | ||
| 411 | |||
| 412 | if (new_entry.login.begin != NULL) { | ||
| 413 | entry->login = new_entry.login; | ||
| 414 | string_builder_printf (&passwd_log, " new login %.*s,", SVFMT (entry->login)); | ||
| 415 | } | ||
| 416 | |||
| 417 | if (DYNAMIC_ARRAY_LAST (passwd_log) != ',') | ||
| 418 | DIE ("no modifications supplied"); | ||
| 419 | DYNAMIC_ARRAY_LAST (passwd_log) = '\n'; | ||
| 420 | |||
| 421 | save_passwd_file (passwd); | ||
| 422 | close_passwd_file (passwd); | ||
| 423 | } break; | ||
| 424 | |||
| 425 | case SUBCOMMAND_DELETE: { // login | ||
| 426 | static struct option longopts[] = { | ||
| 427 | { "help", no_argument, NULL, 'h' }, | ||
| 428 | {0} | ||
| 429 | }; | ||
| 430 | |||
| 431 | char ch; | ||
| 432 | optind = 2; | ||
| 433 | while ((ch = getopt_long (argc, argv, ":h", longopts, NULL)) != -1) { | ||
| 434 | switch (ch) { | ||
| 435 | case 'h': | ||
| 436 | usage_del (progname); | ||
| 437 | exit (0); | ||
| 438 | case '?': DIE ("unknown option -%c", optopt); | ||
| 439 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 440 | default: DIE ("unexpected opt error"); | ||
| 441 | } | ||
| 442 | } | ||
| 443 | |||
| 444 | if (argv[optind] == NULL) { | ||
| 445 | fprintf (stderr, "error: no login provided\n"); | ||
| 446 | usage_del (progname); | ||
| 447 | exit (1); | ||
| 448 | } | ||
| 449 | |||
| 450 | if (argv[optind + 1] != NULL) | ||
| 451 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 452 | |||
| 453 | if (getuid () != 0) | ||
| 454 | DIE ("permission denied"); | ||
| 455 | |||
| 456 | struct string_view login = SVDUP (SVCSTR (argv[optind])); | ||
| 457 | struct passwd passwd = load_passwd_file (); | ||
| 458 | |||
| 459 | struct passwd_entry *entry; | ||
| 460 | for (entry = passwd.items; entry < passwd.items + passwd.count; ++entry) { | ||
| 461 | if (SVCMP (login, entry->login) == 0) | ||
| 462 | break; | ||
| 463 | } | ||
| 464 | |||
| 465 | if (entry == passwd.items + passwd.count) | ||
| 466 | DIE ("user %.*s doesn't exist", SVFMT (login)); | ||
| 467 | |||
| 468 | string_builder_printf (&passwd_log, "%u deleted user %.*s with id %d", | ||
| 469 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 470 | if (entry->comment.begin) | ||
| 471 | string_builder_printf (&passwd_log, " (%.*s)", SVFMT (entry->comment)); | ||
| 472 | DYNAMIC_ARRAY_APPEND (passwd_log, '\n'); | ||
| 473 | |||
| 474 | if (entry + 1 != passwd.items + passwd.count) { | ||
| 475 | memmove (entry, entry + 1, | ||
| 476 | (passwd.count - (entry + 1 - passwd.items))*sizeof (*entry)); | ||
| 477 | } passwd.count -= 1; | ||
| 478 | |||
| 479 | save_passwd_file (passwd); | ||
| 480 | close_passwd_file (passwd); | ||
| 481 | } break; | ||
| 482 | |||
| 483 | default: | ||
| 484 | usage (progname); | ||
| 485 | exit (strcmp (value, "-h") != 0 && strcmp (value, "--help") != 0); | ||
| 486 | } | ||
| 487 | |||
| 488 | append_passwd_log (); | ||
| 489 | |||
| 490 | return EXIT_SUCCESS; | ||
| 491 | } | ||
| 492 | |||
| 493 | // 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 @@ | |||
| 1 | // src/shell.c --- utility for providing access to protected folder | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <assert.h> | ||
| 12 | #include <getopt.h> | ||
| 13 | #include <stdlib.h> | ||
| 14 | #include <errno.h> | ||
| 15 | #include <unistd.h> | ||
| 16 | #include <fcntl.h> | ||
| 17 | #include <time.h> | ||
| 18 | #include <sys/stat.h> | ||
| 19 | #include <sys/mman.h> | ||
| 20 | #include <glob.h> | ||
| 21 | #include <stdio.h> | ||
| 22 | #include <dirent.h> | ||
| 23 | #include <readline/readline.h> | ||
| 24 | #include <readline/history.h> | ||
| 25 | |||
| 26 | #include "common.h" | ||
| 27 | |||
| 28 | #define CONFDATA PREFIX"/confdata" | ||
| 29 | |||
| 30 | int id; | ||
| 31 | |||
| 32 | struct command_line { | ||
| 33 | struct string_builder expanded; | ||
| 34 | struct string_view command; | ||
| 35 | union {struct string_view *items, *args; }; | ||
| 36 | union {uint32_t count, argc; }; | ||
| 37 | uint32_t capacity; | ||
| 38 | }; | ||
| 39 | |||
| 40 | struct string_builder confdata_log = {0}; | ||
| 41 | |||
| 42 | void | ||
| 43 | append_confdata_log () | ||
| 44 | { | ||
| 45 | if (confdata_log.count) { | ||
| 46 | elevate (); | ||
| 47 | int fd = open (PREFIX"/log/confdata.log", O_CREAT | O_WRONLY | O_APPEND); | ||
| 48 | drop (); | ||
| 49 | write (fd, confdata_log.items, confdata_log.count); | ||
| 50 | close (fd); | ||
| 51 | DYNAMIC_ARRAY_RESET (confdata_log); | ||
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | struct string_view | ||
| 56 | canonicalize (struct string_view filename) | ||
| 57 | { | ||
| 58 | static struct string_builder sb = {0}; | ||
| 59 | STRING_BUILDER_RESET (sb); | ||
| 60 | |||
| 61 | static struct { | ||
| 62 | struct string_view *items; | ||
| 63 | uint32_t count; | ||
| 64 | uint32_t capacity; | ||
| 65 | } parts = {0}; | ||
| 66 | DYNAMIC_ARRAY_RESET (parts); | ||
| 67 | |||
| 68 | bool ends_with_slash = filename.end[-1] == '/'; | ||
| 69 | |||
| 70 | if (*filename.begin != '/') { | ||
| 71 | DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 128); | ||
| 72 | for (;;) { | ||
| 73 | if (getcwd (sb.string, sb.capacity)) { | ||
| 74 | sb.length = strlen (sb.string); | ||
| 75 | break; | ||
| 76 | } | ||
| 77 | if (errno != ERANGE) | ||
| 78 | return SVNULL; | ||
| 79 | DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 2*sb.capacity); | ||
| 80 | } | ||
| 81 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 82 | } | ||
| 83 | |||
| 84 | STRING_BUILDER_APPEND_STRING_VIEW (sb, filename); | ||
| 85 | filename = SVSB (sb); | ||
| 86 | |||
| 87 | while (++filename.begin < filename.end) { | ||
| 88 | struct string_view part = string_view_pop_up_to (&filename, '/'); | ||
| 89 | if (SVLEN (part) == 0) continue; | ||
| 90 | if (SVCMP (part, SVCSTR (".")) == 0) continue; | ||
| 91 | if (SVCMP (part, SVCSTR ("..")) == 0) { | ||
| 92 | if (parts.count == 0) return SVNULL; | ||
| 93 | parts.count -= 1; | ||
| 94 | continue; | ||
| 95 | } | ||
| 96 | DYNAMIC_ARRAY_APPEND (parts, part); | ||
| 97 | } | ||
| 98 | |||
| 99 | STRING_BUILDER_RESET (sb); | ||
| 100 | for (struct string_view *part = parts.items; | ||
| 101 | part < parts.items + parts.count; ++part) { | ||
| 102 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 103 | STRING_BUILDER_APPEND_STRING_VIEW (sb, *part); | ||
| 104 | } | ||
| 105 | |||
| 106 | if (ends_with_slash) | ||
| 107 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 108 | |||
| 109 | return SVSB (sb); | ||
| 110 | } | ||
| 111 | |||
| 112 | bool | ||
| 113 | is_conf (struct string_view filename) | ||
| 114 | { | ||
| 115 | elevate (); | ||
| 116 | char *canonical = realpath (filename.begin, NULL); | ||
| 117 | if (!canonical) { | ||
| 118 | struct string_view dirname = SVDUP0 (string_view_dirname (filename)); | ||
| 119 | canonical = realpath (dirname.begin, NULL); | ||
| 120 | free ((void *) dirname.begin); | ||
| 121 | } | ||
| 122 | drop (); | ||
| 123 | |||
| 124 | if (canonical) { | ||
| 125 | bool starts_with = string_view_starts_with (SVCSTR (canonical), SVCSTR (CONFDATA)); | ||
| 126 | free (canonical); | ||
| 127 | return starts_with; | ||
| 128 | } | ||
| 129 | |||
| 130 | return false; | ||
| 131 | } | ||
| 132 | |||
| 133 | bool | ||
| 134 | authorize_conf (int id, struct string_view filename, enum access_rights ar) | ||
| 135 | { | ||
| 136 | bool ret = true; | ||
| 137 | struct passwd passwd = load_passwd_file (); | ||
| 138 | struct passwd_entry *entry = lookup_id (passwd, id); | ||
| 139 | if (!entry) { | ||
| 140 | fprintf (stderr, "user no longer exists, switch user"); | ||
| 141 | ret = false; | ||
| 142 | goto finish; | ||
| 143 | } | ||
| 144 | |||
| 145 | if ((ar & entry->access_rights) != ar) { | ||
| 146 | fprintf (stderr, "access denied '%.*s'\n", SVFMT (filename)); | ||
| 147 | string_builder_printf (&passwd_log, | ||
| 148 | "%u user '%.*s' (%d) was denied access %c%c%c to '%.*s'\n", | ||
| 149 | time (NULL), SVFMT (entry->login), entry->id, | ||
| 150 | ar & AR_READ ? 'r' : '-', | ||
| 151 | ar & AR_WRITE ? 'w' : '-', | ||
| 152 | ar & AR_DELETE ? 'd' : '-', SVFMT (filename)); | ||
| 153 | ret = false; | ||
| 154 | goto finish; | ||
| 155 | } | ||
| 156 | string_builder_printf (&passwd_log, | ||
| 157 | "%u user '%.*s' (%d) was granted access %c%c%c to '%.*s'\n", | ||
| 158 | time (NULL), SVFMT (entry->login), entry->id, | ||
| 159 | ar & AR_READ ? 'r' : '-', | ||
| 160 | ar & AR_WRITE ? 'w' : '-', | ||
| 161 | ar & AR_DELETE ? 'd' : '-', SVFMT (filename)); | ||
| 162 | |||
| 163 | finish: | ||
| 164 | close_passwd_file (passwd); | ||
| 165 | return ret; | ||
| 166 | } | ||
| 167 | |||
| 168 | bool | ||
| 169 | authorize_reg (struct string_view filename, enum access_rights ar) | ||
| 170 | { | ||
| 171 | if (ar == 0) return true; | ||
| 172 | |||
| 173 | int how = 0; | ||
| 174 | how |= ar & AR_READ ? R_OK : 0; | ||
| 175 | how |= ar & (AR_WRITE | AR_DELETE) ? W_OK : 0; | ||
| 176 | if (access (filename.begin, how) == 0) | ||
| 177 | return true; | ||
| 178 | |||
| 179 | struct string_view dirname = SVDUP0 (string_view_dirname (filename)); | ||
| 180 | int ret = access (dirname.begin, how); | ||
| 181 | free ((void *) dirname.begin); | ||
| 182 | if (ret == 0) | ||
| 183 | return true; | ||
| 184 | |||
| 185 | fprintf (stderr, "access denied '%.*s': %s\n", | ||
| 186 | SVFMT (filename), strerror (errno)); | ||
| 187 | return false; | ||
| 188 | } | ||
| 189 | |||
| 190 | bool | ||
| 191 | authorize (int id, struct string_view filename, enum access_rights ar) | ||
| 192 | { | ||
| 193 | return is_conf (filename) | ||
| 194 | ? authorize_conf (id, filename, ar) | ||
| 195 | : authorize_reg (filename, ar); | ||
| 196 | } | ||
| 197 | |||
| 198 | bool | ||
| 199 | authorize_known (int id, struct string_view filename, | ||
| 200 | enum access_rights ar, bool conf) | ||
| 201 | { | ||
| 202 | return conf | ||
| 203 | ? authorize_conf (id, filename, ar) | ||
| 204 | : authorize_reg (filename, ar); | ||
| 205 | } | ||
| 206 | |||
| 207 | bool | ||
| 208 | copy_file (struct string_view source, struct string_view destination) | ||
| 209 | { | ||
| 210 | bool conf_source = is_conf (source); | ||
| 211 | bool conf_destination = is_conf (destination); | ||
| 212 | |||
| 213 | if (conf_source && !conf_destination) { | ||
| 214 | fprintf (stderr, "access denied: no one can copy out of confdata\n"); | ||
| 215 | return false; | ||
| 216 | } | ||
| 217 | |||
| 218 | if (!authorize_known (id, source, AR_READ, conf_source )) return false; | ||
| 219 | if (!authorize_known (id, destination, AR_WRITE, conf_destination)) return false; | ||
| 220 | |||
| 221 | bool ret = true; | ||
| 222 | if (conf_source) elevate (); | ||
| 223 | int source_fd = open (source.begin, O_RDONLY); | ||
| 224 | if (conf_source) drop (); | ||
| 225 | if (source_fd == -1) { | ||
| 226 | fprintf (stderr, "error opening file for reading '%.*s': %s\n", | ||
| 227 | SVFMT (source), strerror (errno)); | ||
| 228 | return false; | ||
| 229 | } | ||
| 230 | |||
| 231 | struct stat st; | ||
| 232 | if (fstat (source_fd, &st) == -1) { | ||
| 233 | fprintf (stderr, "error getting file stats for '%.*s': %s\n", | ||
| 234 | SVFMT (source), strerror (errno)); | ||
| 235 | ret = false; | ||
| 236 | goto close_source; | ||
| 237 | } | ||
| 238 | |||
| 239 | if (!S_ISREG (st.st_mode)) { | ||
| 240 | fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source)); | ||
| 241 | ret = false; | ||
| 242 | goto close_source; | ||
| 243 | } | ||
| 244 | |||
| 245 | if (conf_destination) elevate (); | ||
| 246 | int destination_fd = open (destination.begin, O_RDWR | O_CREAT | O_EXCL | | ||
| 247 | O_TRUNC, S_IRUSR | S_IWUSR); | ||
| 248 | if (conf_destination) drop (); | ||
| 249 | if (destination_fd == -1) { | ||
| 250 | fprintf (stderr, "error opening file for writing '%.*s': %s\n", | ||
| 251 | SVFMT (destination), strerror (errno)); | ||
| 252 | ret = false; | ||
| 253 | goto close_source; | ||
| 254 | } | ||
| 255 | |||
| 256 | if (ftruncate (destination_fd, st.st_size) == -1) { | ||
| 257 | fprintf (stderr, "error setting file size for '%.*s': %s\n", | ||
| 258 | SVFMT (destination), strerror (errno)); | ||
| 259 | ret = false; | ||
| 260 | goto close_destination; | ||
| 261 | } | ||
| 262 | |||
| 263 | void *source_map = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, source_fd, 0); | ||
| 264 | if (source_map == MAP_FAILED) { | ||
| 265 | fprintf (stderr, "error mapping source file '%.*s': %s\n", | ||
| 266 | SVFMT (source), strerror (errno)); | ||
| 267 | ret = false; | ||
| 268 | goto close_destination; | ||
| 269 | } | ||
| 270 | |||
| 271 | void *destination_map = mmap (NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, destination_fd, 0); | ||
| 272 | if (destination_map == MAP_FAILED) { | ||
| 273 | fprintf (stderr, "error mapping destination file '%.*s': %s\n", | ||
| 274 | SVFMT (destination), strerror (errno)); | ||
| 275 | ret = false; | ||
| 276 | goto munmap_source; | ||
| 277 | } | ||
| 278 | |||
| 279 | memcpy (destination_map, source_map, st.st_size); | ||
| 280 | |||
| 281 | if (conf_destination) { | ||
| 282 | elevate (); | ||
| 283 | char *canonical = realpath (destination.begin, NULL); | ||
| 284 | drop (); | ||
| 285 | assert (canonical); | ||
| 286 | string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n", | ||
| 287 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 288 | free (canonical); | ||
| 289 | } | ||
| 290 | |||
| 291 | munmap (destination_map, st.st_size); | ||
| 292 | munmap_source: | ||
| 293 | munmap (source_map, st.st_size); | ||
| 294 | close_destination: | ||
| 295 | close (destination_fd); | ||
| 296 | close_source: | ||
| 297 | close (source_fd); | ||
| 298 | |||
| 299 | elevate (); | ||
| 300 | if (conf_destination) chown (destination.begin, euid, egid); | ||
| 301 | else chown (destination.begin, ruid, rgid); | ||
| 302 | drop (); | ||
| 303 | |||
| 304 | return ret; | ||
| 305 | } | ||
| 306 | |||
| 307 | bool | ||
| 308 | rename_file (struct string_view source, struct string_view destination) | ||
| 309 | { | ||
| 310 | bool conf_source = is_conf (source); | ||
| 311 | bool conf_destination = is_conf (destination); | ||
| 312 | |||
| 313 | if (conf_source && !conf_destination) { | ||
| 314 | fprintf (stderr, "access denied: no one can rename out of confdata\n"); | ||
| 315 | return false; | ||
| 316 | } | ||
| 317 | |||
| 318 | if (!authorize_known (id, source, AR_READ | AR_DELETE, conf_source)) return false; | ||
| 319 | if (!authorize_known (id, destination, AR_WRITE, conf_destination)) return false; | ||
| 320 | |||
| 321 | struct stat st; | ||
| 322 | if (stat (source.begin, &st) == -1) { | ||
| 323 | fprintf (stderr, "error getting file stats for '%.*s': %s\n", | ||
| 324 | SVFMT (source), strerror (errno)); | ||
| 325 | return false; | ||
| 326 | } | ||
| 327 | |||
| 328 | if (!S_ISREG (st.st_mode)) { | ||
| 329 | fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source)); | ||
| 330 | return false; | ||
| 331 | } | ||
| 332 | |||
| 333 | elevate (); | ||
| 334 | int res = access (destination.begin, F_OK); | ||
| 335 | drop (); | ||
| 336 | if (res == 0) { | ||
| 337 | fprintf (stderr, "destination file already exists '%.*s'\n", SVFMT (destination)); | ||
| 338 | return false; | ||
| 339 | } | ||
| 340 | |||
| 341 | char *canonical = NULL; | ||
| 342 | if (conf_source || conf_destination) elevate (); | ||
| 343 | if (conf_source) canonical = realpath (source.begin, NULL); | ||
| 344 | res = rename (source.begin, destination.begin); | ||
| 345 | if (conf_source || conf_destination) drop (); | ||
| 346 | if (res == -1) { | ||
| 347 | fprintf (stderr, "error renaming '%.*s' to '%.*s': %s\n", | ||
| 348 | SVFMT (source), SVFMT (destination), strerror (errno)); | ||
| 349 | free (canonical); | ||
| 350 | return false; | ||
| 351 | } | ||
| 352 | |||
| 353 | if (conf_destination) { | ||
| 354 | elevate (); | ||
| 355 | char *canonical = realpath (destination.begin, NULL); | ||
| 356 | drop (); | ||
| 357 | assert (canonical); | ||
| 358 | string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n", | ||
| 359 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 360 | free (canonical); | ||
| 361 | } | ||
| 362 | |||
| 363 | if (conf_source) { | ||
| 364 | assert (canonical); | ||
| 365 | string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n", | ||
| 366 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 367 | free (canonical); | ||
| 368 | } | ||
| 369 | |||
| 370 | elevate (); | ||
| 371 | if (conf_destination) chown (destination.begin, euid, egid); | ||
| 372 | else chown (destination.begin, ruid, rgid); | ||
| 373 | drop (); | ||
| 374 | |||
| 375 | return true; | ||
| 376 | } | ||
| 377 | |||
| 378 | int | ||
| 379 | parse_command_line (struct command_line *cl, struct string_view line) | ||
| 380 | { | ||
| 381 | DYNAMIC_ARRAY_RESET (cl->expanded); | ||
| 382 | DYNAMIC_ARRAY_RESET (*cl); | ||
| 383 | cl->command = SVNULL; | ||
| 384 | |||
| 385 | // printf ("line: %.*s\n", SVFMT (line)); | ||
| 386 | |||
| 387 | const char *head = line.begin; | ||
| 388 | const char *end = line.end; | ||
| 389 | for (; head < end; ++head) { | ||
| 390 | if (*head == ' ' || *head == '\t') { | ||
| 391 | do head += 1; | ||
| 392 | while (head < end && (*head == ' ' || *head == '\t')); | ||
| 393 | if (head == end) | ||
| 394 | break; | ||
| 395 | if (cl->expanded.length) | ||
| 396 | STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0'); | ||
| 397 | } | ||
| 398 | |||
| 399 | if (*head == '\'') { | ||
| 400 | head += 1; | ||
| 401 | if (head == end) return 0; | ||
| 402 | while (head < end && *head != '\'') | ||
| 403 | STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++); | ||
| 404 | if (head == end && (head[-1] != '\'' || head - 1 == line.begin)) return 0; | ||
| 405 | } else if (*head == '"') { | ||
| 406 | head += 1; | ||
| 407 | if (head == end) return 0; | ||
| 408 | if (*head == '!') { | ||
| 409 | STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA); | ||
| 410 | head += 1; | ||
| 411 | } | ||
| 412 | while (head < end && *head != '"') | ||
| 413 | STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++); | ||
| 414 | if (head == end && (head[-1] != '"' || head - 1 == line.begin)) return 0; | ||
| 415 | } else if (*head == '!' && (cl->expanded.length == 0 || DYNAMIC_ARRAY_LAST (cl->expanded) == '\0')) { | ||
| 416 | STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA); | ||
| 417 | } else { | ||
| 418 | STRING_BUILDER_APPEND_CHAR (cl->expanded, *head); | ||
| 419 | } | ||
| 420 | } STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0'); | ||
| 421 | |||
| 422 | head = cl->expanded.string; | ||
| 423 | end = cl->expanded.string + cl->expanded.length; | ||
| 424 | cl->command.begin = head; | ||
| 425 | while (head < end && *head != '\0') | ||
| 426 | head += 1; | ||
| 427 | cl->command.end = head++; | ||
| 428 | |||
| 429 | if (SVLEN (cl->command) == 0) return 0; | ||
| 430 | |||
| 431 | while (head < end) { | ||
| 432 | struct string_view arg; | ||
| 433 | arg.begin = head; | ||
| 434 | do head += 1; | ||
| 435 | while (head < end && *head != '\0'); | ||
| 436 | arg.end = head++; | ||
| 437 | |||
| 438 | const char *star = strchr (arg.begin, '*'); | ||
| 439 | struct string_view trimmed = arg; | ||
| 440 | if (star) { | ||
| 441 | if (star == arg.begin) { | ||
| 442 | trimmed = SVCSTR ("."); | ||
| 443 | } else { | ||
| 444 | trimmed = SVDUP0 ((struct string_view) { | ||
| 445 | .begin = arg.begin, | ||
| 446 | .end = star, | ||
| 447 | }); | ||
| 448 | } | ||
| 449 | } | ||
| 450 | |||
| 451 | bool conf = is_conf (trimmed); | ||
| 452 | if (conf) elevate (); | ||
| 453 | glob_t globs; | ||
| 454 | if (glob (arg.begin, GLOB_MARK | GLOB_NOSORT | GLOB_BRACE | GLOB_TILDE_CHECK, NULL, &globs) != 0) { | ||
| 455 | DYNAMIC_ARRAY_APPEND (*cl, arg); | ||
| 456 | } else { | ||
| 457 | for (size_t i = 0; i < globs.gl_pathc; ++i) { | ||
| 458 | arg.begin = globs.gl_pathv[i]; | ||
| 459 | arg.end = arg.begin + strlen (arg.begin); | ||
| 460 | DYNAMIC_ARRAY_APPEND (*cl, SVDUP0 (arg)); | ||
| 461 | } | ||
| 462 | } | ||
| 463 | if (conf) drop (); | ||
| 464 | |||
| 465 | globfree (&globs); | ||
| 466 | } | ||
| 467 | |||
| 468 | // printf ("command: %.*s\n", SVFMT (cl->command)); | ||
| 469 | // for (uint32_t i = 0; i < cl->argc; ++i) | ||
| 470 | // printf ("arg: %.*s\n", SVFMT (cl->args[i])); | ||
| 471 | |||
| 472 | return 1; | ||
| 473 | } | ||
| 474 | |||
| 475 | int | ||
| 476 | command_exit (struct command_line cl) | ||
| 477 | { | ||
| 478 | exit (0); | ||
| 479 | } | ||
| 480 | |||
| 481 | int | ||
| 482 | command_help (struct command_line cl) | ||
| 483 | { | ||
| 484 | puts ("Commands:"); | ||
| 485 | puts (" help display information about builtin commands"); | ||
| 486 | puts (" su LOGIN change user to LOGIN"); | ||
| 487 | puts (" pwd print the name of the current working directory "); | ||
| 488 | puts (" whoami print effective user name"); | ||
| 489 | puts (" echo [ARG]... write ARG(s) to the standard output"); | ||
| 490 | puts (" ls [FILE]... list information about the FILE(s)"); | ||
| 491 | puts (" cd [DIR] change the shell working directory"); | ||
| 492 | puts (" mv SOURCE DEST rename SOURCE to DEST"); | ||
| 493 | puts (" mv SOURCE... DIRECTORY move SOURCE(s) to DIRECTORY"); | ||
| 494 | puts (" cp SOURCE DEST copy SOURCE to DEST"); | ||
| 495 | puts (" cp SOURCE... DIRECTORY copy SOURCE(s) to DIRECTORY"); | ||
| 496 | puts (" rm FILE... remove (unlink) the FILE(s)"); | ||
| 497 | puts (" mkdir DIR... create the DIRECTORY(ies), if they do not already exist"); | ||
| 498 | puts (" rmdir DIR... remove the DIRECTORY(ies), if they are empty"); | ||
| 499 | puts (" cat [FILE]... concatenate FILE(s) to standard output"); | ||
| 500 | puts (" append FILE append text from standard input to FILE"); | ||
| 501 | puts (""); | ||
| 502 | puts ("Aliases:"); | ||
| 503 | puts (" read -> cat"); | ||
| 504 | puts (" copy -> cp"); | ||
| 505 | puts (" remove -> rm"); | ||
| 506 | puts (""); | ||
| 507 | return 0; | ||
| 508 | } | ||
| 509 | |||
| 510 | int | ||
| 511 | command_su (struct command_line cl) | ||
| 512 | { | ||
| 513 | if (cl.argc != 1) { | ||
| 514 | fprintf (stderr, "usage: %.*s LOGIN\n", SVFMT (cl.command)); | ||
| 515 | return 1; | ||
| 516 | } | ||
| 517 | |||
| 518 | struct string_view login = cl.args[0]; | ||
| 519 | int ret = 0; | ||
| 520 | struct passwd passwd = load_passwd_file (); | ||
| 521 | struct passwd_entry *entry; | ||
| 522 | if (getuid () == 0) { | ||
| 523 | entry = lookup_login (passwd, login); | ||
| 524 | if (!entry) { | ||
| 525 | fprintf (stderr, "user %.*s doesn't exist\n", SVFMT (login)); | ||
| 526 | ret = 1; | ||
| 527 | goto close; | ||
| 528 | } | ||
| 529 | } else { | ||
| 530 | fputs ("Password: ", stdout); | ||
| 531 | struct string_view password = read_password (); | ||
| 532 | entry = authenticate (passwd, login, password); | ||
| 533 | if (!entry) { | ||
| 534 | ret = 1; | ||
| 535 | goto close; | ||
| 536 | } | ||
| 537 | } | ||
| 538 | id = entry->id; | ||
| 539 | |||
| 540 | close: | ||
| 541 | close_passwd_file (passwd); | ||
| 542 | return ret; | ||
| 543 | } | ||
| 544 | |||
| 545 | int | ||
| 546 | command_pwd (struct command_line cl) | ||
| 547 | { | ||
| 548 | size_t size = 256; | ||
| 549 | |||
| 550 | for (;;) { | ||
| 551 | char *buffer = (char *) malloc (size); | ||
| 552 | if (getcwd (buffer, size) == buffer) { | ||
| 553 | puts (buffer); | ||
| 554 | free (buffer); | ||
| 555 | return 0; | ||
| 556 | } | ||
| 557 | free (buffer); | ||
| 558 | if (errno != ERANGE) | ||
| 559 | return errno; | ||
| 560 | size *= 2; | ||
| 561 | } | ||
| 562 | } | ||
| 563 | |||
| 564 | int | ||
| 565 | command_whoami (struct command_line cl) | ||
| 566 | { | ||
| 567 | int ret = 0; | ||
| 568 | struct passwd passwd = load_passwd_file (); | ||
| 569 | struct passwd_entry *entry = lookup_id (passwd, id); | ||
| 570 | if (!entry) { | ||
| 571 | fprintf (stderr, "user with id %d no longed exists\n", id); | ||
| 572 | ret = 1; | ||
| 573 | goto close; | ||
| 574 | } | ||
| 575 | |||
| 576 | printf ("%d %.*s (%.*s) %c%c%c\n", | ||
| 577 | id, SVFMT (entry->login), SVFMT (entry->comment), | ||
| 578 | entry->access_rights & AR_READ ? 'r' : '-', | ||
| 579 | entry->access_rights & AR_WRITE ? 'w' : '-', | ||
| 580 | entry->access_rights & AR_DELETE ? 'd' : '-'); | ||
| 581 | |||
| 582 | close: | ||
| 583 | close_passwd_file (passwd); | ||
| 584 | return ret; | ||
| 585 | } | ||
| 586 | |||
| 587 | int | ||
| 588 | command_echo (struct command_line cl) | ||
| 589 | { | ||
| 590 | if (cl.argc == 0) | ||
| 591 | return 0; | ||
| 592 | |||
| 593 | fputs (cl.args[0].begin, stdout); | ||
| 594 | for (uint32_t argind = 1; argind < cl.argc; ++argind) { | ||
| 595 | putchar (' '); | ||
| 596 | fputs (cl.args[argind].begin, stdout); | ||
| 597 | } putchar ('\n'); | ||
| 598 | |||
| 599 | return 0; | ||
| 600 | } | ||
| 601 | |||
| 602 | int | ||
| 603 | command_cd (struct command_line cl) | ||
| 604 | { | ||
| 605 | struct string_view dir = cl.argc ? cl.args[0] : SVCSTR (CONFDATA); | ||
| 606 | bool conf = string_view_starts_with (dir, SVCSTR (CONFDATA)); | ||
| 607 | |||
| 608 | if (conf) elevate (); | ||
| 609 | if (chdir (dir.begin) == -1) { | ||
| 610 | fprintf (stderr, "%.*s: cannot change directory to '%s': %s\n", | ||
| 611 | SVFMT (cl.command), dir.begin, strerror (errno)); | ||
| 612 | } | ||
| 613 | if (conf) drop (); | ||
| 614 | |||
| 615 | return 0; | ||
| 616 | } | ||
| 617 | |||
| 618 | bool | ||
| 619 | is_dir (struct string_view filename) | ||
| 620 | { | ||
| 621 | struct stat st; | ||
| 622 | |||
| 623 | elevate (); | ||
| 624 | int res = stat (filename.begin, &st); | ||
| 625 | drop (); | ||
| 626 | |||
| 627 | if (res == -1) | ||
| 628 | return false; | ||
| 629 | |||
| 630 | return S_ISDIR (st.st_mode); | ||
| 631 | } | ||
| 632 | |||
| 633 | int | ||
| 634 | command_mv (struct command_line cl) | ||
| 635 | { | ||
| 636 | if (cl.argc < 2) { | ||
| 637 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 638 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 639 | return 1; | ||
| 640 | } | ||
| 641 | |||
| 642 | int ret = 0; | ||
| 643 | |||
| 644 | if (is_dir (cl.args[cl.argc - 1])) { | ||
| 645 | struct string_builder sb = {0}; | ||
| 646 | |||
| 647 | struct string_view directory = cl.args[cl.argc - 1]; | ||
| 648 | STRING_BUILDER_APPEND_STRING_VIEW (sb, directory); | ||
| 649 | if (DYNAMIC_ARRAY_LAST (sb) != '/') | ||
| 650 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 651 | |||
| 652 | size_t directory_length = sb.length; | ||
| 653 | for (uint32_t i = 0; i < cl.argc - 1; ++i) { | ||
| 654 | sb.length = directory_length; | ||
| 655 | struct string_view source = cl.args[i]; | ||
| 656 | |||
| 657 | struct string_view basename = string_view_basename (source); | ||
| 658 | STRING_BUILDER_APPEND_STRING_VIEW (sb, basename); | ||
| 659 | struct string_view destination = SVSB (sb); | ||
| 660 | STRING_BUILDER_APPEND_NULL (sb); | ||
| 661 | |||
| 662 | if (!rename_file (source, destination)) { | ||
| 663 | fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n", | ||
| 664 | SVFMT (source), SVFMT (destination)); | ||
| 665 | ret = 1; | ||
| 666 | } | ||
| 667 | } | ||
| 668 | |||
| 669 | STRING_BUILDER_FREE (sb); | ||
| 670 | } else { | ||
| 671 | if (cl.argc != 2) { | ||
| 672 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 673 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 674 | return 1; | ||
| 675 | } | ||
| 676 | |||
| 677 | struct string_view source = cl.args[0]; | ||
| 678 | struct string_view destination = cl.args[1]; | ||
| 679 | if (!rename_file (source, destination)) { | ||
| 680 | fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n", | ||
| 681 | SVFMT (source), SVFMT (destination)); | ||
| 682 | ret = 1; | ||
| 683 | } | ||
| 684 | } | ||
| 685 | |||
| 686 | return ret; | ||
| 687 | } | ||
| 688 | |||
| 689 | int | ||
| 690 | command_cp (struct command_line cl) | ||
| 691 | { | ||
| 692 | if (cl.argc < 2) { | ||
| 693 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 694 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 695 | return 1; | ||
| 696 | } | ||
| 697 | |||
| 698 | int ret = 0; | ||
| 699 | |||
| 700 | if (is_dir (cl.args[cl.argc - 1])) { | ||
| 701 | struct string_builder sb = {0}; | ||
| 702 | |||
| 703 | struct string_view directory = cl.args[cl.argc - 1]; | ||
| 704 | STRING_BUILDER_APPEND_STRING_VIEW (sb, directory); | ||
| 705 | if (DYNAMIC_ARRAY_LAST (sb) != '/') | ||
| 706 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 707 | |||
| 708 | size_t directory_length = sb.length; | ||
| 709 | for (uint32_t i = 0; i < cl.argc - 1; ++i) { | ||
| 710 | sb.length = directory_length; | ||
| 711 | struct string_view source = cl.args[i]; | ||
| 712 | |||
| 713 | struct string_view basename = string_view_basename (source); | ||
| 714 | STRING_BUILDER_APPEND_STRING_VIEW (sb, basename); | ||
| 715 | struct string_view destination = SVSB (sb); | ||
| 716 | STRING_BUILDER_APPEND_NULL (sb); | ||
| 717 | |||
| 718 | if (!copy_file (source, destination)) { | ||
| 719 | fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n", | ||
| 720 | SVFMT (source), SVFMT (destination)); | ||
| 721 | ret = 1; | ||
| 722 | } | ||
| 723 | } | ||
| 724 | |||
| 725 | STRING_BUILDER_FREE (sb); | ||
| 726 | } else { | ||
| 727 | if (cl.argc != 2) { | ||
| 728 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 729 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 730 | return 1; | ||
| 731 | } | ||
| 732 | |||
| 733 | struct string_view source = cl.args[0]; | ||
| 734 | struct string_view destination = cl.args[1]; | ||
| 735 | if (!copy_file (source, destination)) { | ||
| 736 | fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n", | ||
| 737 | SVFMT (source), SVFMT (destination)); | ||
| 738 | ret = 1; | ||
| 739 | } | ||
| 740 | } | ||
| 741 | |||
| 742 | return ret; | ||
| 743 | } | ||
| 744 | |||
| 745 | int | ||
| 746 | command_rm (struct command_line cl) | ||
| 747 | { | ||
| 748 | if (cl.argc == 0) { | ||
| 749 | fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); | ||
| 750 | return 1; | ||
| 751 | } | ||
| 752 | |||
| 753 | int ret = 0; | ||
| 754 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 755 | struct string_view file = cl.args[argind]; | ||
| 756 | const char *filename = file.begin; | ||
| 757 | |||
| 758 | bool conf = is_conf (file); | ||
| 759 | if (!authorize_known (id, file, AR_DELETE, conf)) { | ||
| 760 | ret = 1; | ||
| 761 | continue; | ||
| 762 | } | ||
| 763 | |||
| 764 | char *canonical = NULL; | ||
| 765 | if (conf) { | ||
| 766 | elevate (); | ||
| 767 | canonical = realpath (filename, NULL); | ||
| 768 | } | ||
| 769 | int res = remove (filename); | ||
| 770 | if (conf) drop (); | ||
| 771 | if (res == -1) { | ||
| 772 | fprintf (stderr, "%.*s: cannot remove file '%s': %s\n", | ||
| 773 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 774 | ret = 1; | ||
| 775 | free (canonical); | ||
| 776 | } else if (conf) { | ||
| 777 | assert (canonical); | ||
| 778 | string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n", | ||
| 779 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 780 | free (canonical); | ||
| 781 | } | ||
| 782 | } | ||
| 783 | |||
| 784 | return ret; | ||
| 785 | } | ||
| 786 | |||
| 787 | int | ||
| 788 | command_mkdir (struct command_line cl) | ||
| 789 | { | ||
| 790 | if (cl.argc == 0) { | ||
| 791 | fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); | ||
| 792 | return 1; | ||
| 793 | } | ||
| 794 | |||
| 795 | int ret = 0; | ||
| 796 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 797 | const char *filename = cl.args[argind].begin; | ||
| 798 | |||
| 799 | bool conf = is_conf (cl.args[argind]); | ||
| 800 | if (!authorize_known (id, cl.args[argind], AR_WRITE, conf)) { | ||
| 801 | ret = 1; | ||
| 802 | continue; | ||
| 803 | } | ||
| 804 | |||
| 805 | if (conf) elevate (); | ||
| 806 | int res = mkdir (filename, S_IRUSR | S_IWUSR | S_IXUSR); | ||
| 807 | if (conf) drop (); | ||
| 808 | if (res == -1) { | ||
| 809 | fprintf (stderr, "%.*s: cannot create directory '%s': %s\n", | ||
| 810 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 811 | ret = 1; | ||
| 812 | } else if (conf) { | ||
| 813 | elevate (); | ||
| 814 | char *canonical = realpath (filename, NULL); | ||
| 815 | drop (); | ||
| 816 | assert (canonical); | ||
| 817 | string_builder_printf (&confdata_log, "%u user %d created directory '!%s'\n", | ||
| 818 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 819 | free (canonical); | ||
| 820 | } | ||
| 821 | } | ||
| 822 | |||
| 823 | return ret; | ||
| 824 | } | ||
| 825 | |||
| 826 | int | ||
| 827 | command_rmdir (struct command_line cl) | ||
| 828 | { | ||
| 829 | if (cl.argc == 0) { | ||
| 830 | fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); | ||
| 831 | return 1; | ||
| 832 | } | ||
| 833 | |||
| 834 | int ret = 0; | ||
| 835 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 836 | const char *filename = cl.args[argind].begin; | ||
| 837 | |||
| 838 | bool conf = is_conf (cl.args[argind]); | ||
| 839 | if (!authorize_known (id, cl.args[argind], AR_DELETE, conf)) { | ||
| 840 | ret = 1; | ||
| 841 | continue; | ||
| 842 | } | ||
| 843 | char *canonical = NULL; | ||
| 844 | if (conf) { | ||
| 845 | elevate (); | ||
| 846 | canonical = realpath (filename, NULL); | ||
| 847 | } | ||
| 848 | int res = rmdir (filename); | ||
| 849 | if (conf) drop (); | ||
| 850 | if (res == -1) { | ||
| 851 | fprintf (stderr, "%.*s: cannot remove directory '%s': %s\n", | ||
| 852 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 853 | ret = 1; | ||
| 854 | free (canonical); | ||
| 855 | } else if (conf) { | ||
| 856 | assert (canonical); | ||
| 857 | string_builder_printf (&confdata_log, "%u user %d removed directory '!%s'\n", | ||
| 858 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 859 | free (canonical); | ||
| 860 | } | ||
| 861 | } | ||
| 862 | |||
| 863 | return ret; | ||
| 864 | } | ||
| 865 | |||
| 866 | int | ||
| 867 | command_cat (struct command_line cl) | ||
| 868 | { | ||
| 869 | int ret = 0; | ||
| 870 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 871 | struct string_view file = cl.args[argind]; | ||
| 872 | bool conf = is_conf (file); | ||
| 873 | if (!authorize_known (id, file, AR_READ, conf)) continue; | ||
| 874 | |||
| 875 | const char *filename = file.begin; | ||
| 876 | if (conf) elevate (); | ||
| 877 | int fd = open (filename, O_RDONLY); | ||
| 878 | if (conf) drop (); | ||
| 879 | if (fd == -1) { | ||
| 880 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 881 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 882 | ret = 1; | ||
| 883 | continue; | ||
| 884 | } | ||
| 885 | |||
| 886 | struct stat st; | ||
| 887 | int res = fstat (fd, &st); | ||
| 888 | if (res == -1) { | ||
| 889 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 890 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 891 | ret = 2; | ||
| 892 | goto close; | ||
| 893 | } | ||
| 894 | |||
| 895 | void *contents = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); | ||
| 896 | if (contents == NULL) { | ||
| 897 | ret = 3; | ||
| 898 | goto close; | ||
| 899 | } | ||
| 900 | write (0, contents, st.st_size); | ||
| 901 | |||
| 902 | if (conf) { | ||
| 903 | elevate (); | ||
| 904 | char *canonical = realpath (file.begin, NULL); | ||
| 905 | drop (); | ||
| 906 | assert (canonical); | ||
| 907 | string_builder_printf (&confdata_log, "%u user %d read file '!%s'\n", | ||
| 908 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 909 | free (canonical); | ||
| 910 | } | ||
| 911 | |||
| 912 | munmap (contents, st.st_size); | ||
| 913 | close: | ||
| 914 | close (fd); | ||
| 915 | } | ||
| 916 | |||
| 917 | drop (); | ||
| 918 | |||
| 919 | return ret; | ||
| 920 | } | ||
| 921 | |||
| 922 | int | ||
| 923 | command_append (struct command_line cl) | ||
| 924 | { | ||
| 925 | static struct string_builder sb = {0}; | ||
| 926 | |||
| 927 | if (cl.argc != 1) { | ||
| 928 | fprintf (stderr, "usage: %.*s FILE\n", SVFMT (cl.command)); | ||
| 929 | return 1; | ||
| 930 | } | ||
| 931 | |||
| 932 | struct string_view filename = cl.args[0]; | ||
| 933 | |||
| 934 | bool conf = is_conf (filename); | ||
| 935 | if (!authorize_known (id, filename, AR_WRITE, conf)) | ||
| 936 | return 1; | ||
| 937 | |||
| 938 | STRING_BUILDER_RESET (sb); | ||
| 939 | char *line; | ||
| 940 | while ((line = readline ("append> ")) != NULL) { | ||
| 941 | STRING_BUILDER_APPEND_CSTR (sb, line); | ||
| 942 | STRING_BUILDER_APPEND_CHAR (sb, '\n'); | ||
| 943 | free (line); | ||
| 944 | } | ||
| 945 | |||
| 946 | int ret = 0; | ||
| 947 | if (sb.length) { | ||
| 948 | if (!authorize_known (id, filename, AR_WRITE, conf)) | ||
| 949 | return 1; | ||
| 950 | |||
| 951 | if (conf) elevate (); | ||
| 952 | int fd = open (filename.begin, O_WRONLY | O_CREAT | O_APPEND); | ||
| 953 | if (conf) drop (); | ||
| 954 | if (fd == -1) { | ||
| 955 | fprintf (stderr, "failed to open '%.*s' for writing\n", SVFMT (filename)); | ||
| 956 | return 1; | ||
| 957 | } | ||
| 958 | |||
| 959 | write (fd, sb.string, sb.length); | ||
| 960 | |||
| 961 | if (conf) { | ||
| 962 | elevate (); | ||
| 963 | char *canonical = realpath (filename.begin, NULL); | ||
| 964 | drop (); | ||
| 965 | assert (canonical); | ||
| 966 | string_builder_printf (&confdata_log, "%u user %d appended to file '!%s'\n", | ||
| 967 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 968 | free (canonical); | ||
| 969 | } | ||
| 970 | |||
| 971 | close (fd); | ||
| 972 | } | ||
| 973 | |||
| 974 | return 0; | ||
| 975 | } | ||
| 976 | |||
| 977 | int | ||
| 978 | command_ls (struct command_line cl) | ||
| 979 | { | ||
| 980 | if (cl.argc == 0) | ||
| 981 | DYNAMIC_ARRAY_APPEND (cl, SVCSTR (".")); | ||
| 982 | |||
| 983 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 984 | struct string_view file = cl.args[argind]; | ||
| 985 | const char *filename = file.begin; | ||
| 986 | |||
| 987 | bool conf = is_conf (file); | ||
| 988 | if (!authorize_known (id, file, AR_READ, conf)) | ||
| 989 | continue; | ||
| 990 | |||
| 991 | if (conf) elevate (); | ||
| 992 | int fd = open (filename, O_RDONLY); | ||
| 993 | if (conf) drop (); | ||
| 994 | if (fd == -1) { | ||
| 995 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 996 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 997 | continue; | ||
| 998 | } | ||
| 999 | |||
| 1000 | struct stat st; | ||
| 1001 | if (fstat (fd, &st) == -1) { | ||
| 1002 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 1003 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1004 | goto close; | ||
| 1005 | } | ||
| 1006 | |||
| 1007 | if (S_ISREG (st.st_mode)) { | ||
| 1008 | printf ("%s\n", filename); | ||
| 1009 | if (conf) { | ||
| 1010 | elevate (); | ||
| 1011 | char *canonical = realpath (filename, NULL); | ||
| 1012 | drop (); | ||
| 1013 | assert (canonical); | ||
| 1014 | string_builder_printf (&confdata_log, "%u user %d listed file '!%s'\n", | ||
| 1015 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1016 | free (canonical); | ||
| 1017 | } | ||
| 1018 | goto close; | ||
| 1019 | } | ||
| 1020 | |||
| 1021 | DIR *dir = fdopendir (fd); | ||
| 1022 | if (dir == NULL) { | ||
| 1023 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 1024 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1025 | goto close; | ||
| 1026 | } | ||
| 1027 | |||
| 1028 | if (argind != 0) putchar ('\n'); | ||
| 1029 | printf ("%s:\n", filename); | ||
| 1030 | struct dirent *entry; | ||
| 1031 | while ((entry = readdir (dir)) != NULL) { | ||
| 1032 | if (strcmp (entry->d_name, ".") == 0 || | ||
| 1033 | strcmp (entry->d_name, "..") == 0) { | ||
| 1034 | continue; | ||
| 1035 | } | ||
| 1036 | |||
| 1037 | if (entry->d_type == DT_DIR) | ||
| 1038 | printf ("%s/\n", entry->d_name); | ||
| 1039 | else | ||
| 1040 | printf ("%s\n", entry->d_name); | ||
| 1041 | } | ||
| 1042 | |||
| 1043 | if (conf) { | ||
| 1044 | elevate (); | ||
| 1045 | char *canonical = realpath (filename, NULL); | ||
| 1046 | drop (); | ||
| 1047 | assert (canonical); | ||
| 1048 | string_builder_printf (&confdata_log, "%u user %d listed directory '!%s'\n", | ||
| 1049 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1050 | free (canonical); | ||
| 1051 | } | ||
| 1052 | |||
| 1053 | closedir (dir); | ||
| 1054 | close: | ||
| 1055 | close (fd); | ||
| 1056 | } | ||
| 1057 | |||
| 1058 | return 0; | ||
| 1059 | } | ||
| 1060 | |||
| 1061 | const char * | ||
| 1062 | prompt (int ret) | ||
| 1063 | { | ||
| 1064 | static struct string_builder sb = {0}; | ||
| 1065 | |||
| 1066 | STRING_BUILDER_RESET (sb); | ||
| 1067 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m[\e[34m"); | ||
| 1068 | |||
| 1069 | struct passwd passwd = load_passwd_file (); | ||
| 1070 | struct passwd_entry *entry = lookup_id (passwd, id); | ||
| 1071 | if (entry) { | ||
| 1072 | STRING_BUILDER_APPEND_STRING_VIEW (sb, entry->login); | ||
| 1073 | |||
| 1074 | #ifdef MAC | ||
| 1075 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m@"); | ||
| 1076 | STRING_BUILDER_APPEND_CSTR (sb, entry->security_level == SL_COUNT - 1 | ||
| 1077 | ? "\e[34m" | ||
| 1078 | : "\e[31m"); | ||
| 1079 | STRING_BUILDER_APPEND_CSTR (sb, security_level_names[entry->security_level]); | ||
| 1080 | #endif | ||
| 1081 | } else STRING_BUILDER_APPEND_CHAR (sb, '?'); | ||
| 1082 | close_passwd_file (passwd); | ||
| 1083 | |||
| 1084 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m:\e[34m"); | ||
| 1085 | struct string_view canonical = canonicalize (SVCSTR (".")); | ||
| 1086 | if (strncmp (canonical.begin, CONFDATA, strlen (CONFDATA)) == 0) { | ||
| 1087 | STRING_BUILDER_APPEND_CHAR (sb, '!'); | ||
| 1088 | canonical.begin += strlen (CONFDATA); | ||
| 1089 | } STRING_BUILDER_APPEND_STRING_VIEW (sb, canonical); | ||
| 1090 | |||
| 1091 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m]\e[34m"); | ||
| 1092 | |||
| 1093 | if (ret) string_builder_printf (&sb, " \e[31m%d", ret); | ||
| 1094 | |||
| 1095 | STRING_BUILDER_APPEND_CSTR (sb, ruid == euid ? " \e[31m#" : " \e[95m$"); | ||
| 1096 | STRING_BUILDER_APPEND_CSTR (sb, "\e[0m "); | ||
| 1097 | STRING_BUILDER_TERMINATE (sb); | ||
| 1098 | |||
| 1099 | return sb.string; | ||
| 1100 | } | ||
| 1101 | |||
| 1102 | int | ||
| 1103 | main (int argc, char *argv[]) | ||
| 1104 | { | ||
| 1105 | ruid = getuid (); | ||
| 1106 | rgid = getgid (); | ||
| 1107 | euid = geteuid (); | ||
| 1108 | egid = getegid (); | ||
| 1109 | drop (); | ||
| 1110 | |||
| 1111 | static struct option longopts[] = { | ||
| 1112 | { "help", no_argument, NULL, 'h' }, | ||
| 1113 | { "password", required_argument, NULL, 'p' }, | ||
| 1114 | {0} | ||
| 1115 | }; | ||
| 1116 | char ch; | ||
| 1117 | struct string_view password = {0}; | ||
| 1118 | while ((ch = getopt_long (argc, argv, ":hp:", longopts, NULL)) != -1) { | ||
| 1119 | switch (ch) { | ||
| 1120 | case 'h': | ||
| 1121 | printf ("Usage: %s [options] [LOGIN]\n", argv[0]); | ||
| 1122 | puts (""); | ||
| 1123 | puts ("Options:"); | ||
| 1124 | puts (" -h, --help display this help message and exit"); | ||
| 1125 | puts (" -p, --password PASSWORD password of the account (only if login was provided)"); | ||
| 1126 | puts (""); | ||
| 1127 | exit (0); | ||
| 1128 | case 'p': password = SVCSTR (optarg); break; | ||
| 1129 | case '?': DIE ("unknown option %s", argv[optind - 1]); | ||
| 1130 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 1131 | default: DIE ("unexpected opt error"); | ||
| 1132 | } | ||
| 1133 | } | ||
| 1134 | |||
| 1135 | struct passwd passwd = load_passwd_file (); | ||
| 1136 | struct passwd_entry *entry = NULL; | ||
| 1137 | if (argv[optind] != NULL) { | ||
| 1138 | if (argv[optind + 1] != NULL) | ||
| 1139 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 1140 | |||
| 1141 | struct string_view login = SVCSTR (argv[optind]); | ||
| 1142 | if (ruid == 0) { | ||
| 1143 | entry = lookup_login (passwd, login); | ||
| 1144 | append_passwd_log (); | ||
| 1145 | if (!entry) { | ||
| 1146 | DIE ("user %.*s doesn't exist", SVFMT (login)); | ||
| 1147 | } | ||
| 1148 | } else { | ||
| 1149 | if (password.begin == NULL) { | ||
| 1150 | fputs ("Password: ", stdout); | ||
| 1151 | password = read_password (); | ||
| 1152 | } | ||
| 1153 | entry = authenticate (passwd, login, password); | ||
| 1154 | append_passwd_log (); | ||
| 1155 | if (entry == NULL) exit (1); | ||
| 1156 | } | ||
| 1157 | } else { | ||
| 1158 | do { | ||
| 1159 | fputs ("Login: ", stdout); fflush (stdout); | ||
| 1160 | struct string_view login = read_login (); | ||
| 1161 | fputs ("Password: ", stdout); fflush (stdout); | ||
| 1162 | struct string_view password = read_password (); | ||
| 1163 | entry = authenticate (passwd, login, password); | ||
| 1164 | } while (entry == NULL); | ||
| 1165 | } | ||
| 1166 | |||
| 1167 | id = entry->id; | ||
| 1168 | printf ("Hello, %.*s! (%d)\n", SVFMT (entry->comment), id); | ||
| 1169 | close_passwd_file (passwd); | ||
| 1170 | printf ("Run 'help', to get a list of available commands.\n"); | ||
| 1171 | |||
| 1172 | struct command_line cl = {0}; | ||
| 1173 | int ret = 0; | ||
| 1174 | for (;;) { | ||
| 1175 | char *line = readline (prompt (ret)); | ||
| 1176 | if (line == NULL) break; | ||
| 1177 | add_history (line); | ||
| 1178 | switch (parse_command_line (&cl, SVCSTR (line))) { | ||
| 1179 | case 1: | ||
| 1180 | if (SVCMP (cl.command, SVCSTR ("exit" )) == 0) ret = command_exit (cl); | ||
| 1181 | else if (SVCMP (cl.command, SVCSTR ("help" )) == 0) ret = command_help (cl); | ||
| 1182 | else if (SVCMP (cl.command, SVCSTR ("su" )) == 0) ret = command_su (cl); | ||
| 1183 | else if (SVCMP (cl.command, SVCSTR ("pwd" )) == 0) ret = command_pwd (cl); | ||
| 1184 | else if (SVCMP (cl.command, SVCSTR ("whoami")) == 0) ret = command_whoami (cl); | ||
| 1185 | else if (SVCMP (cl.command, SVCSTR ("echo" )) == 0) ret = command_echo (cl); | ||
| 1186 | else if (SVCMP (cl.command, SVCSTR ("ls" )) == 0) ret = command_ls (cl); | ||
| 1187 | else if (SVCMP (cl.command, SVCSTR ("cd" )) == 0) ret = command_cd (cl); | ||
| 1188 | else if (SVCMP (cl.command, SVCSTR ("mv" )) == 0) ret = command_mv (cl); | ||
| 1189 | else if (SVCMP (cl.command, SVCSTR ("cp" )) == 0) ret = command_cp (cl); | ||
| 1190 | else if (SVCMP (cl.command, SVCSTR ("rm" )) == 0) ret = command_rm (cl); | ||
| 1191 | else if (SVCMP (cl.command, SVCSTR ("mkdir" )) == 0) ret = command_mkdir (cl); | ||
| 1192 | else if (SVCMP (cl.command, SVCSTR ("rmdir" )) == 0) ret = command_rmdir (cl); | ||
| 1193 | else if (SVCMP (cl.command, SVCSTR ("cat" )) == 0) ret = command_cat (cl); | ||
| 1194 | else if (SVCMP (cl.command, SVCSTR ("read" )) == 0) ret = command_cat (cl); | ||
| 1195 | else if (SVCMP (cl.command, SVCSTR ("copy" )) == 0) ret = command_cp (cl); | ||
| 1196 | else if (SVCMP (cl.command, SVCSTR ("remove")) == 0) ret = command_rm (cl); | ||
| 1197 | else if (SVCMP (cl.command, SVCSTR ("append")) == 0) ret = command_append (cl); | ||
| 1198 | else puts ("unknown command, run `help' to get the list of available commands"); | ||
| 1199 | break; | ||
| 1200 | case 0: break; | ||
| 1201 | case -1: | ||
| 1202 | putchar ('\n'); | ||
| 1203 | exit (0); | ||
| 1204 | default: | ||
| 1205 | fputs ("invalid command line", stderr); | ||
| 1206 | break; | ||
| 1207 | } free (line); | ||
| 1208 | append_passwd_log (); | ||
| 1209 | append_confdata_log (); | ||
| 1210 | } putchar ('\n'); | ||
| 1211 | |||
| 1212 | return EXIT_SUCCESS; | ||
| 1213 | } | ||
| 1214 | |||
| 1215 | // 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 @@ | |||
| 1 | #include "string-builder.h" | ||
| 2 | #include <stdarg.h> | ||
| 3 | #include <stdio.h> | ||
| 4 | |||
| 5 | void | ||
| 6 | string_builder_append_ntimes (STRING_BUILDER sb, char c, size_t n) | ||
| 7 | { | ||
| 8 | DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, n); | ||
| 9 | memset (sb->items + sb->count, c, n); | ||
| 10 | sb->count += n; | ||
| 11 | } | ||
| 12 | |||
| 13 | void | ||
| 14 | string_builder_append_cstrs (STRING_BUILDER sb, ...) | ||
| 15 | { | ||
| 16 | va_list args; | ||
| 17 | |||
| 18 | va_start (args, sb); | ||
| 19 | const char *arg = va_arg (args, const char *); | ||
| 20 | while (arg) { | ||
| 21 | STRING_BUILDER_APPEND_CSTR(*sb, arg); | ||
| 22 | arg = va_arg (args, const char *); | ||
| 23 | } va_end (args); | ||
| 24 | } | ||
| 25 | |||
| 26 | void | ||
| 27 | string_builder_printf (STRING_BUILDER sb, const char *format, ...) | ||
| 28 | { | ||
| 29 | va_list args; | ||
| 30 | |||
| 31 | va_start (args, format); | ||
| 32 | int size = vsnprintf (NULL, 0, format, args); | ||
| 33 | va_end (args); | ||
| 34 | ASSERT (size >= 0); | ||
| 35 | |||
| 36 | DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, size + 1); | ||
| 37 | va_start (args, format); | ||
| 38 | vsnprintf (&sb->items[sb->count], size + 1, format, args); | ||
| 39 | va_end (args); | ||
| 40 | sb->count += size; | ||
| 41 | } | ||
| 42 | |||
| 43 | bool | ||
| 44 | string_builder_getline (STRING_BUILDER sb) | ||
| 45 | { | ||
| 46 | for (;;) { | ||
| 47 | int c = getchar (); | ||
| 48 | |||
| 49 | if (c == EOF) | ||
| 50 | return false; | ||
| 51 | if (c == '\n') | ||
| 52 | break; | ||
| 53 | |||
| 54 | STRING_BUILDER_APPEND_CHAR (*sb, c); | ||
| 55 | } | ||
| 56 | |||
| 57 | return true; | ||
| 58 | } | ||
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 @@ | |||
| 1 | #ifndef INCLUDED_STRING_BUILDER_H | ||
| 2 | #define INCLUDED_STRING_BUILDER_H | ||
| 3 | |||
| 4 | #include <stddef.h> | ||
| 5 | #include <string.h> | ||
| 6 | #include <stdbool.h> | ||
| 7 | #include "dynamic-array.h" | ||
| 8 | |||
| 9 | struct string_builder { | ||
| 10 | union { char *items, *string; }; | ||
| 11 | union { size_t count, length; }; | ||
| 12 | size_t capacity; | ||
| 13 | }; | ||
| 14 | #define STRING_BUILDER struct string_builder * | ||
| 15 | |||
| 16 | #define SBFMT(SB) (int) (SB).length, (SB).string | ||
| 17 | |||
| 18 | #define STRING_BUILDER_APPEND_CHAR(SB, CHAR) \ | ||
| 19 | DYNAMIC_ARRAY_APPEND (SB, (char) CHAR) | ||
| 20 | |||
| 21 | #define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE) \ | ||
| 22 | DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE) | ||
| 23 | |||
| 24 | #define STRING_BUILDER_APPEND_CSTR(SB, CSTR) \ | ||
| 25 | ({ \ | ||
| 26 | const char *s = (CSTR); \ | ||
| 27 | size_t n = strlen (s); \ | ||
| 28 | DYNAMIC_ARRAY_APPEND_MANY(SB, s, n); \ | ||
| 29 | }) | ||
| 30 | |||
| 31 | #define STRING_BUILDER_APPEND_CSTRS(SB, ...) \ | ||
| 32 | string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL) | ||
| 33 | |||
| 34 | #define STRING_BUILDER_APPEND_STRING_VIEW(SB, SV) \ | ||
| 35 | DYNAMIC_ARRAY_APPEND_MANY(SB, (SV).begin, SVLEN (SV)); | ||
| 36 | |||
| 37 | #define STRING_BUILDER_APPEND_NULL(SB) \ | ||
| 38 | DYNAMIC_ARRAY_APPEND (SB, '\0') | ||
| 39 | |||
| 40 | #define STRING_BUILDER_TERMINATE(SB) ({ \ | ||
| 41 | DYNAMIC_ARRAY_ENSURE_CAPACITY (SB, 1); \ | ||
| 42 | (SB).string[(SB).length] = '\0'; \ | ||
| 43 | }) | ||
| 44 | |||
| 45 | #define STRING_BUILDER_RESET(SB) \ | ||
| 46 | DYNAMIC_ARRAY_RESET (SB) | ||
| 47 | |||
| 48 | #define STRING_BUILDER_FREE(SB) \ | ||
| 49 | DYNAMIC_ARRAY_FREE(SB) | ||
| 50 | |||
| 51 | void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n); | ||
| 52 | void string_builder_append_cstrs (STRING_BUILDER, ...); | ||
| 53 | void string_builder_printf (STRING_BUILDER, const char *format, ...); | ||
| 54 | bool string_builder_getline (STRING_BUILDER); | ||
| 55 | |||
| 56 | #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 @@ | |||
| 1 | #include "string-view.h" | ||
| 2 | #include <string.h> | ||
| 3 | #include <stdlib.h> | ||
| 4 | |||
| 5 | size_t | ||
| 6 | string_view_length (struct string_view sv) | ||
| 7 | { | ||
| 8 | return sv.end - sv.begin; | ||
| 9 | } | ||
| 10 | |||
| 11 | struct string_view | ||
| 12 | string_view_from_cstr (const char *cstr) | ||
| 13 | { | ||
| 14 | return (struct string_view) { | ||
| 15 | .begin = cstr, | ||
| 16 | .end = cstr + strlen (cstr), | ||
| 17 | }; | ||
| 18 | } | ||
| 19 | |||
| 20 | struct string_view | ||
| 21 | duplicate_string_view (struct string_view sv) | ||
| 22 | { | ||
| 23 | size_t len = SVLEN (sv); | ||
| 24 | |||
| 25 | struct string_view result = { | ||
| 26 | .begin = malloc (len), | ||
| 27 | }; | ||
| 28 | result.end = result.begin + len; | ||
| 29 | |||
| 30 | memcpy ((void *) result.begin, sv.begin, len); | ||
| 31 | |||
| 32 | return result; | ||
| 33 | } | ||
| 34 | |||
| 35 | struct string_view | ||
| 36 | duplicate_string_view_as_cstr (struct string_view sv) | ||
| 37 | { | ||
| 38 | size_t len = SVLEN (sv); | ||
| 39 | |||
| 40 | struct string_view result = { | ||
| 41 | .begin = malloc (len + 1), | ||
| 42 | }; | ||
| 43 | result.end = result.begin + len; | ||
| 44 | |||
| 45 | memcpy ((void *) result.begin, sv.begin, len); | ||
| 46 | ((char *) result.begin)[len] = '\0'; | ||
| 47 | |||
| 48 | return result; | ||
| 49 | } | ||
| 50 | |||
| 51 | struct string_view | ||
| 52 | string_view_strdup (const char *cstr) | ||
| 53 | { | ||
| 54 | struct string_view sv; | ||
| 55 | size_t len = strlen (cstr); | ||
| 56 | sv.begin = malloc (len + 1), | ||
| 57 | sv.end = sv.begin + len; | ||
| 58 | |||
| 59 | memcpy ((void *) sv.begin, cstr, len); | ||
| 60 | ((char *) sv.begin)[len] = '\0'; | ||
| 61 | |||
| 62 | return sv; | ||
| 63 | } | ||
| 64 | |||
| 65 | int | ||
| 66 | string_view_compare (struct string_view lhs, struct string_view rhs) | ||
| 67 | { | ||
| 68 | if (SVLEN (lhs) != SVLEN (rhs)) | ||
| 69 | return SVLEN (lhs) - SVLEN (rhs); | ||
| 70 | |||
| 71 | return memcmp (lhs.begin, rhs.begin, SVLEN (lhs)); | ||
| 72 | } | ||
| 73 | |||
| 74 | bool | ||
| 75 | string_view_starts_with (struct string_view sv, struct string_view prefix) | ||
| 76 | { | ||
| 77 | if (SVLEN (sv) < SVLEN (prefix)) | ||
| 78 | return false; | ||
| 79 | |||
| 80 | return memcmp (sv.begin, prefix.begin, SVLEN (prefix)) == 0; | ||
| 81 | } | ||
| 82 | |||
| 83 | struct string_view | ||
| 84 | string_view_dirname (struct string_view sv) | ||
| 85 | { | ||
| 86 | while (sv.end != sv.begin && sv.end[-1] == '/') | ||
| 87 | sv.end -= 1; | ||
| 88 | |||
| 89 | while (sv.end != sv.begin && sv.end[-1] != '/') | ||
| 90 | sv.end -= 1; | ||
| 91 | |||
| 92 | while (sv.end != sv.begin && sv.end[-1] == '/') | ||
| 93 | sv.end -= 1; | ||
| 94 | |||
| 95 | if (sv.end == sv.begin) | ||
| 96 | return SVCSTR ("."); | ||
| 97 | |||
| 98 | return sv; | ||
| 99 | } | ||
| 100 | |||
| 101 | struct string_view | ||
| 102 | string_view_basename (struct string_view sv) | ||
| 103 | { | ||
| 104 | const char *head = sv.end; | ||
| 105 | |||
| 106 | while (head > sv.begin && head[-1] == '/') | ||
| 107 | head -= 1; | ||
| 108 | |||
| 109 | while (head > sv.begin && head[-1] != '/') | ||
| 110 | head -= 1; | ||
| 111 | |||
| 112 | if (head != sv.begin) | ||
| 113 | sv.begin = head; | ||
| 114 | |||
| 115 | return sv; | ||
| 116 | } | ||
| 117 | |||
| 118 | // pops all if c was not found | ||
| 119 | struct string_view | ||
| 120 | string_view_pop_up_to (struct string_view *sv, char c) | ||
| 121 | { | ||
| 122 | const char *head = sv->begin; | ||
| 123 | |||
| 124 | while (head < sv->end && *head != c) | ||
| 125 | head += 1; | ||
| 126 | |||
| 127 | struct string_view result = { .begin = sv->begin }; | ||
| 128 | result.end = sv->begin = head; | ||
| 129 | |||
| 130 | return result; | ||
| 131 | } | ||
| 132 | |||
| 133 | struct string_view | ||
| 134 | string_view_pop_n (struct string_view *sv, size_t n) | ||
| 135 | { | ||
| 136 | struct string_view result = { | ||
| 137 | .begin = sv->begin, | ||
| 138 | .end = sv->begin + n, | ||
| 139 | }; | ||
| 140 | |||
| 141 | if (result.end > sv->end) | ||
| 142 | result.end = sv->end; | ||
| 143 | |||
| 144 | sv->begin = result.end; | ||
| 145 | |||
| 146 | return result; | ||
| 147 | } | ||
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 @@ | |||
| 1 | // src/string-view.h | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_STRING_VIEW_H | ||
| 12 | #define INCLUDED_STRING_VIEW_H | ||
| 13 | |||
| 14 | #include <stddef.h> | ||
| 15 | #include <stdbool.h> | ||
| 16 | |||
| 17 | struct string_view { | ||
| 18 | const char *begin; | ||
| 19 | const char *end; | ||
| 20 | }; | ||
| 21 | |||
| 22 | #define SVNULL ((struct string_view) {0}) | ||
| 23 | #define SVLEN string_view_length | ||
| 24 | #define SVFMT(SV) (int) SVLEN (SV), (SV).begin | ||
| 25 | #define SVCSTR string_view_from_cstr | ||
| 26 | #define SVDUP duplicate_string_view | ||
| 27 | #define SVDUP0 duplicate_string_view_as_cstr | ||
| 28 | #define SVSTRDUP string_view_strdup | ||
| 29 | #define SVCMP string_view_compare | ||
| 30 | #define SVSB(SB) ((struct string_view) { (SB).string, (SB).string + (SB).length }) | ||
| 31 | |||
| 32 | size_t string_view_length (struct string_view sv); | ||
| 33 | struct string_view string_view_from_cstr (const char *cstr); | ||
| 34 | struct string_view duplicate_string_view (struct string_view sv); | ||
| 35 | struct string_view duplicate_string_view_as_cstr (struct string_view sv); | ||
| 36 | struct string_view string_view_strdup (const char *cstr); | ||
| 37 | int string_view_compare (struct string_view lhs, struct string_view rhs); | ||
| 38 | bool string_view_starts_with (struct string_view sv, struct string_view prefix); | ||
| 39 | struct string_view string_view_dirname (struct string_view); | ||
| 40 | struct string_view string_view_basename (struct string_view); | ||
| 41 | struct string_view string_view_pop_up_to (struct string_view *, char); | ||
| 42 | struct string_view string_view_pop_n (struct string_view *, size_t n); | ||
| 43 | |||
| 44 | #endif // INCLUDED_STRING_VIEW_H | ||
| 45 | |||
| 46 | // src/string-view.h ends here | ||
diff --git a/03/.envrc b/03/.envrc new file mode 100644 index 0000000..ac3d411 --- /dev/null +++ b/03/.envrc | |||
| @@ -0,0 +1,3 @@ | |||
| 1 | export PREFIX=/usr/local/practice3 | ||
| 2 | export CONFDATA=${PREFIX}/confdata | ||
| 3 | export PATH=${PATH}:${PREFIX}/bin | ||
diff --git a/03/.gitignore b/03/.gitignore new file mode 100644 index 0000000..59ef238 --- /dev/null +++ b/03/.gitignore | |||
| @@ -0,0 +1,3 @@ | |||
| 1 | /passwdctl | ||
| 2 | /shell-dac | ||
| 3 | /shell-mac \ No newline at end of file | ||
diff --git a/03/build.sh b/03/build.sh new file mode 100755 index 0000000..1f7f850 --- /dev/null +++ b/03/build.sh | |||
| @@ -0,0 +1,63 @@ | |||
| 1 | #!/usr/bin/env bash | ||
| 2 | ## build.sh | ||
| 3 | # | ||
| 4 | # Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 5 | # | ||
| 6 | # SPDX-License-Identifier: MIT | ||
| 7 | # | ||
| 8 | ## Commentary: | ||
| 9 | # | ||
| 10 | ## Code: | ||
| 11 | |||
| 12 | ROOT="$(dirname "$0")" | ||
| 13 | |||
| 14 | MAX_JOBS="${MAX_JOBS:-$(nproc)}" | ||
| 15 | |||
| 16 | run() { | ||
| 17 | while (( $(jobs -rp | wc -l) >= MAX_JOBS )); do | ||
| 18 | wait -n | ||
| 19 | done | ||
| 20 | echo $@ | ||
| 21 | "$@" & | ||
| 22 | } | ||
| 23 | |||
| 24 | CC="${CC:-cc}" | ||
| 25 | |||
| 26 | CFLAGS="$CFLAGS -std=gnu99" | ||
| 27 | CFLAGS="$CFLAGS -ggdb3 -Og" | ||
| 28 | # CFLAGS="$CFLAGS -O3 -march=native -DNDEBUG" | ||
| 29 | CFLAGS="$CFLAGS -Wall -Wextra" | ||
| 30 | CFLAGS="$CFLAGS -Wno-unused-function" | ||
| 31 | CFLAGS="$CFLAGS -Wno-unused-variable" | ||
| 32 | CFLAGS="$CFLAGS -Wno-unused-parameter" | ||
| 33 | CFLAGS="$CFLAGS -Wno-unused-but-set-variable" | ||
| 34 | CFLAGS="$CFLAGS -Wno-parentheses" | ||
| 35 | CFLAGS="$CFLAGS -Wno-unused-label" | ||
| 36 | CFLAGS="$CFLAGS -Wno-stringop-overflow" | ||
| 37 | CFLAGS="$CFLAGS -I$ROOT/src/" | ||
| 38 | |||
| 39 | set -eu | ||
| 40 | |||
| 41 | run $CC $CFLAGS -o $ROOT/src/string-builder.o -c $ROOT/src/string-builder.c | ||
| 42 | run $CC $CFLAGS -o $ROOT/src/string-view.o -c $ROOT/src/string-view.c | ||
| 43 | run $CC $CFLAGS -o $ROOT/src/common.o -c $ROOT/src/common.c | ||
| 44 | wait | ||
| 45 | |||
| 46 | run $CC $CFLAGS -lcrypto -o $ROOT/passwdctl \ | ||
| 47 | $ROOT/src/common.o \ | ||
| 48 | $ROOT/src/string-builder.o \ | ||
| 49 | $ROOT/src/string-view.o \ | ||
| 50 | $ROOT/src/passwdctl.c | ||
| 51 | run $CC $CFLAGS -lcrypto -lreadline -o $ROOT/shell-dac \ | ||
| 52 | $ROOT/src/common.o \ | ||
| 53 | $ROOT/src/string-builder.o \ | ||
| 54 | $ROOT/src/string-view.o \ | ||
| 55 | $ROOT/src/shell.c | ||
| 56 | run $CC $CFLAGS -lcrypto -lreadline -o $ROOT/shell-mac -DMAC \ | ||
| 57 | $ROOT/src/common.o \ | ||
| 58 | $ROOT/src/string-builder.o \ | ||
| 59 | $ROOT/src/string-view.o \ | ||
| 60 | $ROOT/src/shell.c | ||
| 61 | wait | ||
| 62 | |||
| 63 | ## build.sh ends here | ||
diff --git a/03/install.sh b/03/install.sh new file mode 100755 index 0000000..8cd2aa1 --- /dev/null +++ b/03/install.sh | |||
| @@ -0,0 +1,41 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | ## install.sh | ||
| 3 | # | ||
| 4 | # Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 5 | # | ||
| 6 | # SPDX-License-Identifier: MIT | ||
| 7 | # | ||
| 8 | ## Commentary: | ||
| 9 | # | ||
| 10 | ## Code: | ||
| 11 | |||
| 12 | if [ "$(id -u)" != 0 ]; then | ||
| 13 | echo "$0: permission denied" | ||
| 14 | exit 1 | ||
| 15 | fi | ||
| 16 | |||
| 17 | cd "$(dirname "$0")" | ||
| 18 | |||
| 19 | PREFIX=/usr/local/practice3 | ||
| 20 | |||
| 21 | set -xeu | ||
| 22 | |||
| 23 | install -o root -g root -m 755 -d $PREFIX | ||
| 24 | install -o root -g root -m 755 -d $PREFIX/bin | ||
| 25 | install -o root -g root -m 700 -d $PREFIX/etc | ||
| 26 | install -o root -g root -m 700 -d $PREFIX/etc/acl | ||
| 27 | install -o root -g root -m 700 -d $PREFIX/confdata | ||
| 28 | install -o root -g root -m 700 -d $PREFIX/log | ||
| 29 | |||
| 30 | install -o root -g root -m 6711 passwdctl $PREFIX/bin/passwdctl | ||
| 31 | install -o root -g root -m 6711 shell-dac $PREFIX/bin/shell-dac | ||
| 32 | install -o root -g root -m 6711 shell-mac $PREFIX/bin/shell-mac | ||
| 33 | |||
| 34 | umask 177 | ||
| 35 | [ ! -f $PREFIX/etc/passwd ] && touch $PREFIX/etc/passwd | ||
| 36 | [ ! -f $PREFIX/log/passwd.log ] && touch $PREFIX/log/passwd.log | ||
| 37 | [ ! -f $PREFIX/log/confdata.log ] && touch $PREFIX/log/confdata.log | ||
| 38 | |||
| 39 | exit 0 | ||
| 40 | |||
| 41 | ## install.sh ends here | ||
diff --git a/03/src/common.c b/03/src/common.c new file mode 100644 index 0000000..fd76a3e --- /dev/null +++ b/03/src/common.c | |||
| @@ -0,0 +1,469 @@ | |||
| 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 | |||
| 10 | struct string_builder passwd_log = {0}; | ||
| 11 | |||
| 12 | const char *security_level_names[SL_COUNT] = { | ||
| 13 | [SL_TOP_SECRET ] = "top-secret", | ||
| 14 | [SL_SECRET ] = "secret", | ||
| 15 | [SL_CONFIDENTIAL] = "confidential", | ||
| 16 | [SL_UNCLASSIFIED] = "unclassified", | ||
| 17 | }; | ||
| 18 | |||
| 19 | uid_t ruid; | ||
| 20 | gid_t rgid; | ||
| 21 | uid_t euid; | ||
| 22 | gid_t egid; | ||
| 23 | |||
| 24 | char | ||
| 25 | encode6 (unsigned char b6) | ||
| 26 | { | ||
| 27 | if (b6 < ('9' - '.' + 1) ) return '.' + b6; | ||
| 28 | if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) ) return 'A' + b6 - ('9' - '.' + 1); | ||
| 29 | if (b6 < ('9' - '.' + 1) + ('Z' - 'A' + 1) + ('z' - 'a' + 1)) return 'a' + b6 - ('9' - '.' + 1) - ('Z' - 'A' + 1); | ||
| 30 | printf ("0x%X\n", b6); | ||
| 31 | assert (!"out of range"); | ||
| 32 | return -1; | ||
| 33 | } | ||
| 34 | |||
| 35 | unsigned char | ||
| 36 | decode6 (char c) | ||
| 37 | { | ||
| 38 | if ('.' <= c && c <= '9') return c - '.'; | ||
| 39 | if ('A' <= c && c <= 'Z') return c - 'A' + ('9' - '.' + 1); | ||
| 40 | if ('a' <= c && c <= 'z') return c - 'a' + ('9' - '.' + 1) + ('Z' - 'A' + 1); | ||
| 41 | assert (!"out of range"); | ||
| 42 | return -1; | ||
| 43 | } | ||
| 44 | |||
| 45 | void | ||
| 46 | encode (char *into, const unsigned char* from, unsigned int size) | ||
| 47 | { | ||
| 48 | for (; size >= 3; size -= 3) { | ||
| 49 | // 012345670123456701234567 | ||
| 50 | // 012345012345012345012345 | ||
| 51 | into[0] = encode6 ( from[0] >> 2); | ||
| 52 | into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4); | ||
| 53 | into[2] = encode6 ((from[1] & 0b00001111) << 2 | from[2] >> 6); | ||
| 54 | into[3] = encode6 ((from[2] & 0b00111111)); | ||
| 55 | |||
| 56 | from += 3; | ||
| 57 | into += 4; | ||
| 58 | } | ||
| 59 | if (size == 2) { | ||
| 60 | into[0] = encode6 ( from[0] >> 2); | ||
| 61 | into[1] = encode6 ((from[0] & 0b00000011) << 4 | from[1] >> 4); | ||
| 62 | into[2] = encode6 ((from[1] & 0b00001111) << 2); | ||
| 63 | } else if (size == 1) { | ||
| 64 | into[0] = encode6 ( from[0] >> 2); | ||
| 65 | into[1] = encode6 ((from[0] & 0b00000011) << 4); | ||
| 66 | } | ||
| 67 | } | ||
| 68 | |||
| 69 | void | ||
| 70 | decode (unsigned char *into, struct string_view from) | ||
| 71 | { | ||
| 72 | size_t len; | ||
| 73 | |||
| 74 | for (len = SVLEN (from); len >= 4; len -= 4) { | ||
| 75 | // 012345012345012345012345 | ||
| 76 | // 012345670123456701234567 | ||
| 77 | |||
| 78 | unsigned char d1 = decode6 (from.begin[0]); | ||
| 79 | unsigned char d2 = decode6 (from.begin[1]); | ||
| 80 | unsigned char d3 = decode6 (from.begin[2]); | ||
| 81 | unsigned char d4 = decode6 (from.begin[3]); | ||
| 82 | |||
| 83 | into[0] = d1 << 2 | d2 >> 4; | ||
| 84 | into[1] = (d2 & 0b001111) << 4 | d3 >> 2; | ||
| 85 | into[2] = d3 << 6 | d4; | ||
| 86 | |||
| 87 | from.begin += 4; | ||
| 88 | into += 3; | ||
| 89 | } | ||
| 90 | if (len == 3) { | ||
| 91 | unsigned char d1 = decode6 (from.begin[0]); | ||
| 92 | unsigned char d2 = decode6 (from.begin[1]); | ||
| 93 | unsigned char d3 = decode6 (from.begin[2]); | ||
| 94 | |||
| 95 | into[0] = d1 << 2 | d2 >> 4; | ||
| 96 | into[1] = (d2 & 0b001111) << 4 | d3 >> 2; | ||
| 97 | } else if (len == 2) { | ||
| 98 | unsigned char d1 = decode6 (from.begin[0]); | ||
| 99 | unsigned char d2 = decode6 (from.begin[1]); | ||
| 100 | |||
| 101 | into[0] = d1 << 2 | d2 >> 4; | ||
| 102 | } else assert ("!unreachable"); | ||
| 103 | } | ||
| 104 | |||
| 105 | void | ||
| 106 | generate_salt (unsigned char salt[PASSWORD_SALT_SIZE]) | ||
| 107 | { | ||
| 108 | if (RAND_bytes (salt, PASSWORD_SALT_SIZE) != 1) { | ||
| 109 | DIE ("error generating salt: RAND_bytes: %s", | ||
| 110 | ERR_reason_error_string (ERR_get_error ())); | ||
| 111 | } | ||
| 112 | } | ||
| 113 | |||
| 114 | unsigned char * | ||
| 115 | hash_password (unsigned char hash[SHA_DIGEST_LENGTH], | ||
| 116 | struct string_view password, | ||
| 117 | const unsigned char salt[PASSWORD_SALT_SIZE]) | ||
| 118 | { | ||
| 119 | EVP_MD_CTX *mdctx = EVP_MD_CTX_new (); | ||
| 120 | if (mdctx == NULL) { | ||
| 121 | DIE ("error hashing creating context: EVP_MD_CTX_new: %s", | ||
| 122 | ERR_reason_error_string (ERR_get_error ())); | ||
| 123 | } | ||
| 124 | |||
| 125 | if (EVP_DigestInit_ex (mdctx, EVP_sha1 (), NULL) != 1) { | ||
| 126 | DIE ("error initializing digest: EVP_DigestInit_ex: %s", | ||
| 127 | ERR_reason_error_string (ERR_get_error ())); | ||
| 128 | } | ||
| 129 | |||
| 130 | if (EVP_DigestUpdate (mdctx, password.begin, SVLEN (password)) != 1) { | ||
| 131 | DIE ("error updating digest with password: EVP_DigestUpdate: %s", | ||
| 132 | ERR_reason_error_string (ERR_get_error ())); | ||
| 133 | } | ||
| 134 | |||
| 135 | if (EVP_DigestUpdate (mdctx, salt, PASSWORD_SALT_SIZE) != 1) { | ||
| 136 | DIE ("error updating digest with salt: EVP_DigestUpdate: %s", | ||
| 137 | ERR_reason_error_string (ERR_get_error ())); | ||
| 138 | } | ||
| 139 | |||
| 140 | unsigned int hash_len; | ||
| 141 | if (EVP_DigestFinal_ex(mdctx, hash, &hash_len) != 1) { | ||
| 142 | DIE ("error finalizing digest: EVP_DigestFinal_ex: %s", | ||
| 143 | ERR_reason_error_string (ERR_get_error ())); | ||
| 144 | } | ||
| 145 | |||
| 146 | EVP_MD_CTX_free (mdctx); | ||
| 147 | |||
| 148 | return hash; | ||
| 149 | } | ||
| 150 | |||
| 151 | struct string_view | ||
| 152 | encode_password (struct string_view password) | ||
| 153 | { | ||
| 154 | static char encoded[PASSWORD_ENCODED_LENGTH + 1] = { | ||
| 155 | [0] = '$', | ||
| 156 | [1] = '1', | ||
| 157 | [2] = '$', | ||
| 158 | [3 + PASSWORD_SALT_LENGTH] = '$', | ||
| 159 | }; | ||
| 160 | |||
| 161 | char *salt_encoded = (void *) &encoded[3]; | ||
| 162 | char *hash_encoded = (void *) &encoded[3 + PASSWORD_SALT_LENGTH + 1]; | ||
| 163 | |||
| 164 | unsigned char salt[PASSWORD_SALT_SIZE]; | ||
| 165 | generate_salt (salt); | ||
| 166 | encode (salt_encoded, salt, sizeof (salt)); | ||
| 167 | |||
| 168 | unsigned char hash[SHA_DIGEST_LENGTH]; | ||
| 169 | hash_password (hash, password, salt); | ||
| 170 | encode (hash_encoded, hash, SHA_DIGEST_LENGTH); | ||
| 171 | |||
| 172 | return (struct string_view) { encoded, encoded + PASSWORD_ENCODED_LENGTH }; | ||
| 173 | } | ||
| 174 | |||
| 175 | bool | ||
| 176 | check_password (struct string_view password, | ||
| 177 | struct string_view encoded_password) | ||
| 178 | { | ||
| 179 | if (*encoded_password.begin++ != '$') return false; | ||
| 180 | if (*encoded_password.begin++ != '1') return false; | ||
| 181 | if (*encoded_password.begin++ != '$') return false; | ||
| 182 | |||
| 183 | struct string_view encoded_salt = { | ||
| 184 | .begin = encoded_password.begin, | ||
| 185 | .end = encoded_password.begin += PASSWORD_SALT_LENGTH, | ||
| 186 | }; | ||
| 187 | if (*encoded_password.begin++ != '$') return false; | ||
| 188 | |||
| 189 | struct string_view encoded_hash = { | ||
| 190 | .begin = encoded_password.begin, | ||
| 191 | .end = encoded_password.begin + PASSWORD_HASH_LENGTH, | ||
| 192 | }; | ||
| 193 | |||
| 194 | unsigned char decoded_salt[PASSWORD_SALT_SIZE]; | ||
| 195 | decode (decoded_salt, encoded_salt); | ||
| 196 | |||
| 197 | unsigned char hash[SHA_DIGEST_LENGTH]; | ||
| 198 | hash_password (hash, password, decoded_salt); | ||
| 199 | |||
| 200 | unsigned char decoded_hash[SHA_DIGEST_LENGTH]; | ||
| 201 | decode (decoded_hash, encoded_hash); | ||
| 202 | |||
| 203 | return memcmp (hash, decoded_hash, sizeof (hash)) == 0; | ||
| 204 | } | ||
| 205 | |||
| 206 | int | ||
| 207 | fscan_passwd_entry (FILE *stream, struct passwd_entry *entry) | ||
| 208 | { | ||
| 209 | *entry = (struct passwd_entry) {0}; | ||
| 210 | |||
| 211 | int c; | ||
| 212 | do c = getc (stream); | ||
| 213 | while (c == '\n'); | ||
| 214 | if (c == EOF) | ||
| 215 | return 0; | ||
| 216 | ungetc (c, stream); | ||
| 217 | |||
| 218 | char buffer[256 + 1]; | ||
| 219 | |||
| 220 | fscanf (stream, "%32[-_a-zA-Z0-9]", buffer); | ||
| 221 | if (getc (stream) != ':') return -1; | ||
| 222 | entry->login = string_view_strdup (buffer); | ||
| 223 | |||
| 224 | fread (buffer, 1, PASSWORD_ENCODED_LENGTH, stream); | ||
| 225 | if (getc (stream) != ':') return -1; | ||
| 226 | buffer[PASSWORD_ENCODED_LENGTH] = '\0'; | ||
| 227 | entry->encoded_password = string_view_strdup (buffer); | ||
| 228 | |||
| 229 | fscanf (stream, "%d", &entry->id); | ||
| 230 | if (getc (stream) != ':') return -1; | ||
| 231 | |||
| 232 | fscanf (stream, "%d", (int *) &entry->security_level); | ||
| 233 | if (getc (stream) != ':') return -1; | ||
| 234 | |||
| 235 | int len = 0; | ||
| 236 | fscanf (stream, "%256[^:\n]%n", buffer, &len); | ||
| 237 | if (len) | ||
| 238 | entry->comment = SVDUP0 ((struct string_view) { buffer, buffer + len }); | ||
| 239 | |||
| 240 | return 1; | ||
| 241 | } | ||
| 242 | |||
| 243 | void | ||
| 244 | fprint_passwd_entry (FILE *stream, const struct passwd_entry *entry) | ||
| 245 | { | ||
| 246 | if (entry->id < 0) | ||
| 247 | DIE ("id < 0"); | ||
| 248 | |||
| 249 | struct string_view comment; | ||
| 250 | if (entry->comment.begin) { | ||
| 251 | comment.begin = entry->comment.begin; | ||
| 252 | comment.end = entry->comment.end; | ||
| 253 | } else { | ||
| 254 | comment.begin = ""; | ||
| 255 | comment.end = comment.begin; | ||
| 256 | } | ||
| 257 | |||
| 258 | fprintf (stream, "%.*s:%.*s:%d:%d:%.*s\n", | ||
| 259 | SVFMT (entry->login), | ||
| 260 | SVFMT (entry->encoded_password), | ||
| 261 | entry->id, | ||
| 262 | entry->security_level, | ||
| 263 | SVFMT (comment)); | ||
| 264 | } | ||
| 265 | |||
| 266 | void | ||
| 267 | lock_passwd_file (struct passwd passwd) | ||
| 268 | { | ||
| 269 | if (lockf (fileno (passwd.stream), F_TLOCK, 0) != 0) | ||
| 270 | DIE ("unable to lock passwd file: %s", strerror (errno)); | ||
| 271 | } | ||
| 272 | |||
| 273 | void | ||
| 274 | unlock_passwd_file (struct passwd passwd) | ||
| 275 | { | ||
| 276 | if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0) | ||
| 277 | DIE ("unable to unlock passwd file: %s", strerror (errno)); | ||
| 278 | } | ||
| 279 | |||
| 280 | struct passwd | ||
| 281 | load_passwd_file (void) | ||
| 282 | { | ||
| 283 | elevate (); | ||
| 284 | struct passwd passwd = { | ||
| 285 | .stream = fopen (PREFIX"/etc/passwd", "r+"), | ||
| 286 | }; | ||
| 287 | drop (); | ||
| 288 | |||
| 289 | if (passwd.stream == NULL) | ||
| 290 | DIE ("unable to open passwd file: %s", strerror (errno)); | ||
| 291 | |||
| 292 | if (lockf (fileno (passwd.stream), F_TEST, 0) != 0) | ||
| 293 | DIE ("passwd file is locked: %s", strerror (errno)); | ||
| 294 | |||
| 295 | for (int i = 0;; ++i) { | ||
| 296 | struct passwd_entry entry; | ||
| 297 | int ret = fscan_passwd_entry (passwd.stream, &entry); | ||
| 298 | if (ret == -1) | ||
| 299 | DIE (PREFIX"/etc/passwd:%d: failed to parse entry", i); | ||
| 300 | if (ret == 0) | ||
| 301 | break; | ||
| 302 | DYNAMIC_ARRAY_APPEND (passwd, entry); | ||
| 303 | } | ||
| 304 | |||
| 305 | return passwd; | ||
| 306 | } | ||
| 307 | |||
| 308 | void | ||
| 309 | save_passwd_file (struct passwd passwd) | ||
| 310 | { | ||
| 311 | ftruncate (fileno (passwd.stream), 0); | ||
| 312 | rewind (passwd.stream); | ||
| 313 | for (struct passwd_entry *entry = passwd.items; | ||
| 314 | entry < passwd.items + passwd.count; ++entry) { | ||
| 315 | fprint_passwd_entry (passwd.stream, entry); | ||
| 316 | } fflush (passwd.stream); | ||
| 317 | } | ||
| 318 | |||
| 319 | void | ||
| 320 | close_passwd_file (struct passwd passwd) | ||
| 321 | { | ||
| 322 | for (uint32_t i = 0; i < passwd.count; ++i) { | ||
| 323 | free ((void *) passwd.items[i].login.begin); | ||
| 324 | free ((void *) passwd.items[i].encoded_password.begin); | ||
| 325 | free ((void *) passwd.items[i].comment.begin); | ||
| 326 | } | ||
| 327 | DYNAMIC_ARRAY_FREE (passwd); | ||
| 328 | |||
| 329 | if (lockf (fileno (passwd.stream), F_ULOCK, 0) != 0) | ||
| 330 | DIE ("unable to unlock passwd file: %s", strerror (errno)); | ||
| 331 | |||
| 332 | fclose (passwd.stream); | ||
| 333 | } | ||
| 334 | |||
| 335 | struct string_view | ||
| 336 | read_password () | ||
| 337 | { | ||
| 338 | static char password[PASSWORD_MAX_LENGTH + 2]; | ||
| 339 | |||
| 340 | struct termios term_orig; | ||
| 341 | tcgetattr (fileno (stdin), &term_orig); | ||
| 342 | struct termios term_noecho = term_orig; | ||
| 343 | term_noecho.c_lflag &= ~ECHO; | ||
| 344 | tcsetattr (fileno (stdin), 0, &term_noecho); | ||
| 345 | |||
| 346 | if (fgets (password, sizeof (password), stdin) == NULL) { | ||
| 347 | tcsetattr (fileno (stdin), 0, &term_orig); | ||
| 348 | putchar ('\n'); | ||
| 349 | exit (0); | ||
| 350 | } tcsetattr (fileno (stdin), 0, &term_orig); | ||
| 351 | |||
| 352 | putchar ('\n'); | ||
| 353 | size_t len = strlen (password) - 1; | ||
| 354 | if (password[len] != '\n') | ||
| 355 | DIE ("password too long"); | ||
| 356 | password[len] = '\0'; | ||
| 357 | |||
| 358 | return (struct string_view) { password, password + len }; | ||
| 359 | } | ||
| 360 | |||
| 361 | struct string_view | ||
| 362 | read_login () | ||
| 363 | { | ||
| 364 | static char login[LOGIN_MAX_LENGTH + 2]; | ||
| 365 | |||
| 366 | if (fgets (login, sizeof (login), stdin) == NULL) { | ||
| 367 | putchar ('\n'); | ||
| 368 | exit (0); | ||
| 369 | } | ||
| 370 | |||
| 371 | size_t len = strlen (login) - 1; | ||
| 372 | if (login[len] != '\n') | ||
| 373 | DIE ("login too long"); | ||
| 374 | login[len] = '\0'; | ||
| 375 | |||
| 376 | return (struct string_view) { login, login + len }; | ||
| 377 | } | ||
| 378 | |||
| 379 | struct passwd_entry * | ||
| 380 | authenticate (struct passwd passwd, | ||
| 381 | struct string_view login, | ||
| 382 | struct string_view password) | ||
| 383 | { | ||
| 384 | struct passwd_entry *entry = lookup_login (passwd, login); | ||
| 385 | |||
| 386 | if (!entry) { | ||
| 387 | fprintf (stderr, "user %.*s not found\n", SVFMT (login)); | ||
| 388 | return NULL; | ||
| 389 | } | ||
| 390 | |||
| 391 | if (!check_password (password, entry->encoded_password)) { | ||
| 392 | fputs ("authentication failure\n", stderr); | ||
| 393 | string_builder_printf (&passwd_log, "%u user %.*s supplied incorrect password\n", | ||
| 394 | time (NULL), SVFMT (entry->login)); | ||
| 395 | return NULL; | ||
| 396 | } | ||
| 397 | |||
| 398 | string_builder_printf (&passwd_log, "%u authenticated user %.*s %d\n", | ||
| 399 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 400 | |||
| 401 | return entry; | ||
| 402 | } | ||
| 403 | |||
| 404 | void | ||
| 405 | append_passwd_log () | ||
| 406 | { | ||
| 407 | if (passwd_log.count) { | ||
| 408 | elevate (); | ||
| 409 | int fd = open (PREFIX"/log/passwd.log", O_CREAT | O_WRONLY | O_APPEND); | ||
| 410 | drop (); | ||
| 411 | write (fd, passwd_log.items, passwd_log.count); | ||
| 412 | close (fd); | ||
| 413 | DYNAMIC_ARRAY_RESET (passwd_log); | ||
| 414 | } | ||
| 415 | } | ||
| 416 | |||
| 417 | struct passwd_entry * | ||
| 418 | lookup_login (struct passwd passwd, struct string_view login) | ||
| 419 | { | ||
| 420 | for (struct passwd_entry *entry = passwd.items; | ||
| 421 | entry < passwd.items + passwd.count; ++entry) { | ||
| 422 | if (SVCMP (login, entry->login) != 0) | ||
| 423 | continue; | ||
| 424 | |||
| 425 | string_builder_printf (&passwd_log, "%u user '%.*s' (%d) was looked up\n", | ||
| 426 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 427 | |||
| 428 | return entry; | ||
| 429 | } | ||
| 430 | |||
| 431 | string_builder_printf (&passwd_log, "%u user '%.*s' lookup failed\n", | ||
| 432 | time (NULL), SVFMT (login)); | ||
| 433 | |||
| 434 | return NULL; | ||
| 435 | } | ||
| 436 | |||
| 437 | struct passwd_entry * | ||
| 438 | lookup_id (struct passwd passwd, int id) | ||
| 439 | { | ||
| 440 | for (struct passwd_entry *entry = passwd.items; | ||
| 441 | entry < passwd.items + passwd.count; ++entry) { | ||
| 442 | if (id != entry->id) | ||
| 443 | continue; | ||
| 444 | |||
| 445 | string_builder_printf (&passwd_log, "%u user %d was looked up\n", | ||
| 446 | time (NULL), id); | ||
| 447 | |||
| 448 | return entry; | ||
| 449 | } | ||
| 450 | |||
| 451 | string_builder_printf (&passwd_log, "%u user %d lookup failed\n", | ||
| 452 | time (NULL), id); | ||
| 453 | |||
| 454 | return NULL; | ||
| 455 | } | ||
| 456 | |||
| 457 | void | ||
| 458 | elevate (void) | ||
| 459 | { | ||
| 460 | if (euid != ruid) seteuid (euid); | ||
| 461 | if (egid != rgid) setegid (egid); | ||
| 462 | } | ||
| 463 | |||
| 464 | void | ||
| 465 | drop (void) | ||
| 466 | { | ||
| 467 | if (euid != ruid) seteuid (ruid); | ||
| 468 | if (egid != rgid) setegid (rgid); | ||
| 469 | } | ||
diff --git a/03/src/common.h b/03/src/common.h new file mode 100644 index 0000000..c94763d --- /dev/null +++ b/03/src/common.h | |||
| @@ -0,0 +1,119 @@ | |||
| 1 | // common.h --- common functions | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_COMMON_H | ||
| 12 | #define INCLUDED_COMMON_H | ||
| 13 | |||
| 14 | #include <stddef.h> | ||
| 15 | #include <stdint.h> | ||
| 16 | #include <stdio.h> | ||
| 17 | #include <stdbool.h> | ||
| 18 | |||
| 19 | #include <openssl/sha.h> | ||
| 20 | |||
| 21 | #include "string-view.h" | ||
| 22 | #include "string-builder.h" | ||
| 23 | |||
| 24 | #define PREFIX "/usr/local/practice3" | ||
| 25 | |||
| 26 | #define STRINGIFY(ARG) #ARG | ||
| 27 | #define TO_STRING(ARG) STRINGIFY (ARG) | ||
| 28 | |||
| 29 | #define DIE(FMT, ...) do { \ | ||
| 30 | fprintf (stderr, "fatal: " FMT "\n", ## __VA_ARGS__); \ | ||
| 31 | exit (EXIT_FAILURE); \ | ||
| 32 | } while (0) | ||
| 33 | |||
| 34 | #define LOGIN_MAX_LENGTH 32 | ||
| 35 | #define LOGIN_REGEX "[a-zA-Z][-_a-zA-Z0-9]*" | ||
| 36 | |||
| 37 | #define COMMENT_MAX_LENGTH 256 | ||
| 38 | #define COMMENT_REGEX "[^:\n]*" | ||
| 39 | |||
| 40 | #define PASSWORD_MAX_LENGTH 256 | ||
| 41 | #define PASSWORD_SALT_SIZE 12 | ||
| 42 | #define PASSWORD_SALT_LENGTH 16 | ||
| 43 | #define PASSWORD_HASH_LENGTH 27 | ||
| 44 | #define PASSWORD_ENCODED_LENGTH (3 + PASSWORD_SALT_LENGTH + 1 + PASSWORD_HASH_LENGTH) | ||
| 45 | #define PASSWORD_REGEX "[a-zA-Z][a-zA-Z0-9!@#$%^&*()]*" | ||
| 46 | |||
| 47 | extern struct string_builder passwd_log; | ||
| 48 | |||
| 49 | extern uid_t ruid; | ||
| 50 | extern gid_t rgid; | ||
| 51 | extern uid_t euid; | ||
| 52 | extern gid_t egid; | ||
| 53 | |||
| 54 | enum access_rights { | ||
| 55 | AR_READ = 1 << 0, | ||
| 56 | AR_WRITE = 1 << 1, | ||
| 57 | AR_DELETE = 1 << 2, | ||
| 58 | }; | ||
| 59 | |||
| 60 | enum security_level { | ||
| 61 | SL_TOP_SECRET, | ||
| 62 | SL_SECRET, | ||
| 63 | SL_CONFIDENTIAL, | ||
| 64 | SL_UNCLASSIFIED, | ||
| 65 | SL_COUNT | ||
| 66 | }; | ||
| 67 | |||
| 68 | extern const char *security_level_names[SL_COUNT]; | ||
| 69 | |||
| 70 | struct passwd_entry { | ||
| 71 | struct string_view login; | ||
| 72 | struct string_view encoded_password; | ||
| 73 | enum security_level security_level; | ||
| 74 | int id; | ||
| 75 | struct string_view comment; | ||
| 76 | }; | ||
| 77 | |||
| 78 | struct passwd { | ||
| 79 | struct passwd_entry *items; | ||
| 80 | uint32_t count; | ||
| 81 | uint32_t capacity; | ||
| 82 | FILE *stream; | ||
| 83 | }; | ||
| 84 | |||
| 85 | char encode6 (unsigned char b6); | ||
| 86 | unsigned char decode6 (char c); | ||
| 87 | void encode (char *into, const unsigned char* from, unsigned int size); | ||
| 88 | void decode (unsigned char *into, struct string_view from); | ||
| 89 | |||
| 90 | void generate_salt (unsigned char salt[PASSWORD_SALT_SIZE]); | ||
| 91 | unsigned char *hash_password (unsigned char hash[SHA_DIGEST_LENGTH], | ||
| 92 | struct string_view password, | ||
| 93 | const unsigned char salt[PASSWORD_SALT_SIZE]); | ||
| 94 | struct string_view encode_password (struct string_view password); | ||
| 95 | bool check_password (struct string_view password, | ||
| 96 | struct string_view encoded_password); | ||
| 97 | |||
| 98 | int fscan_passwd_entry (FILE *, struct passwd_entry *); | ||
| 99 | void fprint_passwd_entry (FILE *, const struct passwd_entry *); | ||
| 100 | struct passwd load_passwd_file (void); | ||
| 101 | void save_passwd_file (struct passwd); | ||
| 102 | void close_passwd_file (struct passwd); | ||
| 103 | |||
| 104 | struct string_view read_password (void); | ||
| 105 | struct string_view read_login (void); | ||
| 106 | |||
| 107 | void append_passwd_log (void); | ||
| 108 | |||
| 109 | struct passwd_entry *lookup_login (struct passwd, struct string_view login); | ||
| 110 | struct passwd_entry *lookup_id (struct passwd, int id); | ||
| 111 | |||
| 112 | struct passwd_entry *authenticate (struct passwd, struct string_view login, struct string_view password); | ||
| 113 | |||
| 114 | void elevate (void); | ||
| 115 | void drop (void); | ||
| 116 | |||
| 117 | #endif // INCLUDED_COMMON_H | ||
| 118 | |||
| 119 | // common.h ends here | ||
diff --git a/03/src/dynamic-array.h b/03/src/dynamic-array.h new file mode 100644 index 0000000..ed5cb32 --- /dev/null +++ b/03/src/dynamic-array.h | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | #ifndef INCLUDED_DYNAMIC_ARRAY_H | ||
| 2 | #define INCLUDED_DYNAMIC_ARRAY_H | ||
| 3 | |||
| 4 | #include <stdlib.h> | ||
| 5 | #include <assert.h> | ||
| 6 | |||
| 7 | #define MALLOC malloc | ||
| 8 | #define REALLOC realloc | ||
| 9 | #define FREE free | ||
| 10 | #define ASSERT assert | ||
| 11 | |||
| 12 | #ifndef DYNAMIC_ARRAY_INIT_CAP | ||
| 13 | #define DYNAMIC_ARRAY_INIT_CAP 256 | ||
| 14 | #endif | ||
| 15 | |||
| 16 | #define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ | ||
| 17 | ({ \ | ||
| 18 | if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ | ||
| 19 | if ((DYNAMIC_ARRAY).capacity == 0) \ | ||
| 20 | (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ | ||
| 21 | while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ | ||
| 22 | (DYNAMIC_ARRAY).capacity *= 2; \ | ||
| 23 | (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ | ||
| 24 | (DYNAMIC_ARRAY).capacity * \ | ||
| 25 | sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 26 | ASSERT((DYNAMIC_ARRAY).items); \ | ||
| 27 | } \ | ||
| 28 | }) | ||
| 29 | |||
| 30 | #define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ | ||
| 31 | ({ \ | ||
| 32 | (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ | ||
| 33 | (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ | ||
| 34 | (DYNAMIC_ARRAY).capacity * \ | ||
| 35 | sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 36 | ASSERT((DYNAMIC_ARRAY).items); \ | ||
| 37 | \ | ||
| 38 | }) | ||
| 39 | |||
| 40 | #define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ | ||
| 41 | ({ \ | ||
| 42 | DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ | ||
| 43 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ | ||
| 44 | }) | ||
| 45 | |||
| 46 | #define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ | ||
| 47 | ({ \ | ||
| 48 | DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ | ||
| 49 | memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ | ||
| 50 | (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 51 | (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ | ||
| 52 | }) | ||
| 53 | |||
| 54 | #define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \ | ||
| 55 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] | ||
| 56 | |||
| 57 | #define DYNAMIC_ARRAY_POP(DYNAMIC_ARRAY) \ | ||
| 58 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count--] | ||
| 59 | |||
| 60 | #define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) | ||
| 61 | |||
| 62 | #define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) | ||
| 63 | |||
| 64 | #define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ | ||
| 65 | typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ | ||
| 66 | ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) | ||
| 67 | |||
| 68 | #endif | ||
diff --git a/03/src/passwdctl.c b/03/src/passwdctl.c new file mode 100644 index 0000000..b9e07a7 --- /dev/null +++ b/03/src/passwdctl.c | |||
| @@ -0,0 +1,466 @@ | |||
| 1 | // src/passwdctl.c --- utility to manage access to protected directory | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <stdbool.h> | ||
| 12 | #include <stdio.h> | ||
| 13 | #include <stdlib.h> | ||
| 14 | #include <string.h> | ||
| 15 | #include <assert.h> | ||
| 16 | #include <getopt.h> | ||
| 17 | #include <regex.h> | ||
| 18 | #include <unistd.h> | ||
| 19 | |||
| 20 | #include <openssl/evp.h> | ||
| 21 | #include <openssl/err.h> | ||
| 22 | |||
| 23 | #include "dynamic-array.h" | ||
| 24 | #include "string-builder.h" | ||
| 25 | #include "string-view.h" | ||
| 26 | #include "common.h" | ||
| 27 | |||
| 28 | #define SUBCOMMANDS() \ | ||
| 29 | X (ADD, "add") \ | ||
| 30 | X (MODIFY, "mod") \ | ||
| 31 | X (DELETE, "del") | ||
| 32 | |||
| 33 | #define X(SYM, STR) SUBCOMMAND_##SYM, | ||
| 34 | enum subcommand { | ||
| 35 | SUBCOMMANDS () | ||
| 36 | }; | ||
| 37 | #undef X | ||
| 38 | |||
| 39 | #define X(SYM, STR) [SUBCOMMAND_##SYM] = STR, | ||
| 40 | char *const subcommand_tokens[] = { | ||
| 41 | SUBCOMMANDS () | ||
| 42 | NULL | ||
| 43 | }; | ||
| 44 | #undef X | ||
| 45 | |||
| 46 | regex_t login_regex; | ||
| 47 | regex_t comment_regex; | ||
| 48 | regex_t password_regex; | ||
| 49 | |||
| 50 | struct string_view | ||
| 51 | parse_password (struct string_view sv) | ||
| 52 | { | ||
| 53 | if (regexec (&password_regex, sv.begin, 0, NULL, 0) != 0) | ||
| 54 | DIE ("password doesn't match regex %s", PASSWORD_REGEX); | ||
| 55 | |||
| 56 | return sv; | ||
| 57 | } | ||
| 58 | |||
| 59 | int | ||
| 60 | parse_id (const char *cstr) | ||
| 61 | { | ||
| 62 | int id; | ||
| 63 | size_t read; | ||
| 64 | sscanf (cstr, "%d%ln", &id, &read); | ||
| 65 | |||
| 66 | if (id < 0) DIE ("invalid id"); | ||
| 67 | if (read != strlen (cstr)) DIE ("invalid id"); | ||
| 68 | |||
| 69 | return id; | ||
| 70 | } | ||
| 71 | |||
| 72 | enum security_level | ||
| 73 | parse_security_level (const char *cstr) | ||
| 74 | { | ||
| 75 | for (enum security_level sl = 0; sl < SL_COUNT; ++sl) | ||
| 76 | if (strcmp (cstr, security_level_names[sl]) == 0) return sl; | ||
| 77 | |||
| 78 | DIE ("invalid security level: %s", cstr); | ||
| 79 | } | ||
| 80 | |||
| 81 | struct string_view | ||
| 82 | parse_comment (const char *cstr) | ||
| 83 | { | ||
| 84 | struct string_view sv = SVCSTR (cstr); | ||
| 85 | |||
| 86 | if (SVLEN (sv) > COMMENT_MAX_LENGTH) | ||
| 87 | DIE ("comment too long"); | ||
| 88 | |||
| 89 | if (regexec (&comment_regex, cstr, 0, NULL, 0) != 0) | ||
| 90 | DIE ("comment doesn't match regex " COMMENT_REGEX); | ||
| 91 | |||
| 92 | return sv; | ||
| 93 | } | ||
| 94 | |||
| 95 | struct string_view | ||
| 96 | parse_login (const char *cstr) | ||
| 97 | { | ||
| 98 | struct string_view sv = SVCSTR (cstr); | ||
| 99 | |||
| 100 | if (SVLEN (sv) > LOGIN_MAX_LENGTH) | ||
| 101 | DIE ("login too long"); | ||
| 102 | |||
| 103 | if (regexec (&login_regex, cstr, 0, NULL, 0) != 0) | ||
| 104 | DIE ("login doesn't match regex " LOGIN_REGEX); | ||
| 105 | |||
| 106 | return sv; | ||
| 107 | } | ||
| 108 | |||
| 109 | const char * | ||
| 110 | regex_error (const regex_t *comp, int errcode) | ||
| 111 | { | ||
| 112 | static char *error = NULL; | ||
| 113 | size_t size = regerror (errcode, comp, NULL, 0); | ||
| 114 | error = realloc (error, size); | ||
| 115 | regerror (errcode, comp, error, size); | ||
| 116 | return error; | ||
| 117 | } | ||
| 118 | |||
| 119 | void | ||
| 120 | usage (const char *progname) | ||
| 121 | { | ||
| 122 | printf ("Usage: %s [options] COMMAND [ARGS]\n", progname); | ||
| 123 | puts (""); | ||
| 124 | puts ("Options:"); | ||
| 125 | puts (" -h, --help display this help message and exit"); | ||
| 126 | puts (""); | ||
| 127 | puts ("Commands:"); | ||
| 128 | puts (" add LOGIN add new account"); | ||
| 129 | puts (" mod LOGIN modify existing account"); | ||
| 130 | puts (" del LOGIN delete account"); | ||
| 131 | puts (""); | ||
| 132 | } | ||
| 133 | |||
| 134 | int | ||
| 135 | main (int argc, char *argv[]) | ||
| 136 | { | ||
| 137 | ruid = getuid (); | ||
| 138 | euid = geteuid (); | ||
| 139 | seteuid (ruid); | ||
| 140 | |||
| 141 | ERR_load_crypto_strings (); | ||
| 142 | |||
| 143 | const char *progname = argv[0]; | ||
| 144 | if (progname == NULL) | ||
| 145 | DIE ("unable to get program name"); | ||
| 146 | |||
| 147 | char **subcommand = &argv[1]; | ||
| 148 | if (*subcommand == NULL) { | ||
| 149 | usage (progname); | ||
| 150 | exit (1); | ||
| 151 | } | ||
| 152 | |||
| 153 | int errcode; | ||
| 154 | errcode = regcomp (&login_regex, "^" LOGIN_REGEX "$", REG_NOSUB); | ||
| 155 | if (errcode != 0) { | ||
| 156 | DIE ("unable to compile login regex: %s", | ||
| 157 | regex_error (&login_regex, errcode)); | ||
| 158 | } | ||
| 159 | |||
| 160 | errcode = regcomp (&password_regex, "^" PASSWORD_REGEX "$", REG_NOSUB); | ||
| 161 | if (errcode != 0) { | ||
| 162 | DIE ("unable to compile password regex: %s", | ||
| 163 | regex_error (&password_regex, errcode)); | ||
| 164 | } | ||
| 165 | |||
| 166 | errcode = regcomp (&comment_regex, "^" COMMENT_REGEX "$", REG_NOSUB); | ||
| 167 | if (errcode != 0) { | ||
| 168 | DIE ("unable to compile comment regex: %s", | ||
| 169 | regex_error (&comment_regex, errcode)); | ||
| 170 | } | ||
| 171 | |||
| 172 | char *value; | ||
| 173 | switch (getsubopt (subcommand, subcommand_tokens, &value)) { | ||
| 174 | case SUBCOMMAND_ADD: { | ||
| 175 | static struct option longopts[] = { | ||
| 176 | { "help", no_argument, NULL, 'h' }, | ||
| 177 | { "password", required_argument, NULL, 'p' }, | ||
| 178 | { "id", required_argument, NULL, 'i' }, | ||
| 179 | { "security-level", required_argument, NULL, 's' }, | ||
| 180 | { "comment", required_argument, NULL, 'c' }, | ||
| 181 | {0} | ||
| 182 | }; | ||
| 183 | char ch; | ||
| 184 | struct passwd_entry new_entry = { .id = -1, .security_level = SL_COUNT - 1 }; | ||
| 185 | optind = 2; | ||
| 186 | while ((ch = getopt_long (argc, argv, ":hp:i:s:c:", longopts, NULL)) != -1) { | ||
| 187 | switch (ch) { | ||
| 188 | case 'h': | ||
| 189 | printf ("Usage: %s add [options] LOGIN\n", progname); | ||
| 190 | puts (""); | ||
| 191 | puts ("Options:"); | ||
| 192 | puts (" -h, --help display this help message and exit"); | ||
| 193 | puts (" -p, --password PASSWORD password of the new account"); | ||
| 194 | puts (" -i, --id ID ID of the new account"); | ||
| 195 | puts (" -s, --security-level SECURITY-LEVEL security level of the new account"); | ||
| 196 | puts (" -c, --comment COMMENT comment of the new account"); | ||
| 197 | puts (""); | ||
| 198 | puts ("Security levels:"); | ||
| 199 | puts (" top-secret"); | ||
| 200 | puts (" secret"); | ||
| 201 | puts (" confidential"); | ||
| 202 | puts (" unclassified"); | ||
| 203 | puts (""); | ||
| 204 | exit (0); | ||
| 205 | case 'p': | ||
| 206 | new_entry.encoded_password = | ||
| 207 | SVDUP (encode_password (parse_password (SVCSTR (optarg)))); | ||
| 208 | break; | ||
| 209 | case 'i': new_entry.id = parse_id (optarg); break; | ||
| 210 | case 's': new_entry.security_level = parse_security_level (optarg); break; | ||
| 211 | case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break; | ||
| 212 | case '?': DIE ("unknown option -%c", optopt); | ||
| 213 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 214 | default: DIE ("unexpected opt error"); | ||
| 215 | } | ||
| 216 | } | ||
| 217 | |||
| 218 | if (argv[optind] == NULL) | ||
| 219 | DIE ("no login provided"); | ||
| 220 | |||
| 221 | if (argv[optind + 1] != NULL) | ||
| 222 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 223 | |||
| 224 | if (getuid () != 0) | ||
| 225 | DIE ("permission denied"); | ||
| 226 | |||
| 227 | new_entry.login = SVDUP (SVCSTR (argv[optind])); | ||
| 228 | |||
| 229 | if (new_entry.encoded_password.begin == NULL) { | ||
| 230 | fputs ("Password: ", stdout); | ||
| 231 | struct string_view password = duplicate_string_view_as_cstr (parse_password (read_password ())); | ||
| 232 | fputs ("Repeat password: ", stdout); | ||
| 233 | struct string_view repeated = read_password (); | ||
| 234 | if (string_view_compare (password, repeated) != 0) | ||
| 235 | DIE ("passwords don't match"); | ||
| 236 | |||
| 237 | new_entry.encoded_password = SVDUP (encode_password (password)); | ||
| 238 | } | ||
| 239 | |||
| 240 | struct passwd passwd = load_passwd_file (); | ||
| 241 | |||
| 242 | int max_id = -1; | ||
| 243 | for (struct passwd_entry *entry = passwd.items; | ||
| 244 | entry < passwd.items + passwd.count; ++entry) { | ||
| 245 | if (SVCMP (new_entry.login, entry->login) == 0) | ||
| 246 | DIE ("user %.*s already exists", SVFMT (entry->login)); | ||
| 247 | if (new_entry.id == entry->id) | ||
| 248 | DIE ("user with id %d already exists", entry->id); | ||
| 249 | if (entry->id > max_id) | ||
| 250 | max_id = entry->id; | ||
| 251 | } | ||
| 252 | |||
| 253 | if (new_entry.id < 0) | ||
| 254 | new_entry.id = max_id + 1; | ||
| 255 | |||
| 256 | DYNAMIC_ARRAY_APPEND (passwd, new_entry); | ||
| 257 | save_passwd_file (passwd); | ||
| 258 | |||
| 259 | string_builder_printf (&passwd_log, "%u added user %.*s %d", | ||
| 260 | time (NULL), SVFMT (new_entry.login), new_entry.id); | ||
| 261 | if (new_entry.comment.begin) | ||
| 262 | string_builder_printf (&passwd_log, " (%.*s)", SVFMT (new_entry.comment)); | ||
| 263 | string_builder_printf (&passwd_log, " with security level %s\n", | ||
| 264 | security_level_names[new_entry.security_level]); | ||
| 265 | |||
| 266 | close_passwd_file (passwd); | ||
| 267 | } break; | ||
| 268 | |||
| 269 | case SUBCOMMAND_MODIFY: { // [-p --password=] [-i -id=] [-c --comment=] login | ||
| 270 | static struct option longopts[] = { | ||
| 271 | { "help", no_argument, NULL, 'h' }, | ||
| 272 | { "login", required_argument, NULL, 'l' }, | ||
| 273 | { "password", required_argument, NULL, 'p' }, | ||
| 274 | { "id", required_argument, NULL, 'i' }, | ||
| 275 | { "security-level", required_argument, NULL, 's' }, | ||
| 276 | { "comment", required_argument, NULL, 'c' }, | ||
| 277 | {0} | ||
| 278 | }; | ||
| 279 | char ch; | ||
| 280 | struct passwd_entry new_entry = { .id = -1, .security_level = SL_COUNT }; | ||
| 281 | bool prompt_for_new_password = false; | ||
| 282 | optind = 2; | ||
| 283 | while ((ch = getopt_long (argc, argv, ":hl:p:Pi:s:c:", longopts, NULL)) != -1) { | ||
| 284 | switch (ch) { | ||
| 285 | case 'h': | ||
| 286 | printf ("Usage: %s mod [options] LOGIN\n", progname); | ||
| 287 | puts (""); | ||
| 288 | puts ("Options:"); | ||
| 289 | puts (" -h, --help display this help message and exit"); | ||
| 290 | puts (" -l, --login NEW_LOGIN new login for the account"); | ||
| 291 | puts (" -p, --password PASSWORD new password for the account"); | ||
| 292 | puts (" -P prompt for new password for the account"); | ||
| 293 | puts (" -i, --id ID new ID for the account"); | ||
| 294 | puts (" -s, --security-level SECURITY-LEVEL new access rights for the account"); | ||
| 295 | puts (" -c, --comment COMMENT new comment for the account"); | ||
| 296 | puts (""); | ||
| 297 | puts ("Security levels:"); | ||
| 298 | puts (" top-secret"); | ||
| 299 | puts (" secret"); | ||
| 300 | puts (" confidential"); | ||
| 301 | puts (" unclassified"); | ||
| 302 | puts (""); | ||
| 303 | exit (0); | ||
| 304 | case 'l': new_entry.login = SVDUP (parse_login (optarg)); break; | ||
| 305 | case 'p': | ||
| 306 | new_entry.encoded_password = | ||
| 307 | SVDUP (encode_password (parse_password (SVCSTR (optarg)))); | ||
| 308 | break; | ||
| 309 | case 'P': prompt_for_new_password = true; break; | ||
| 310 | case 'i': new_entry.id = parse_id (optarg); break; | ||
| 311 | case 's': new_entry.security_level = parse_security_level (optarg); break; | ||
| 312 | case 'c': new_entry.comment = SVDUP (parse_comment (optarg)); break; | ||
| 313 | case '?': DIE ("unknown option -%c", optopt); | ||
| 314 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 315 | default: DIE ("unexpected opt error"); | ||
| 316 | } | ||
| 317 | } | ||
| 318 | |||
| 319 | if (argv[optind] == NULL) | ||
| 320 | DIE ("no login provided"); | ||
| 321 | |||
| 322 | if (argv[optind + 1] != NULL) | ||
| 323 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 324 | |||
| 325 | struct string_view login = SVCSTR (argv[optind]); | ||
| 326 | struct passwd_entry *entry; | ||
| 327 | |||
| 328 | struct passwd passwd = load_passwd_file (); | ||
| 329 | |||
| 330 | if (getuid () == 0) { | ||
| 331 | entry = lookup_login (passwd, login); | ||
| 332 | if (!entry) | ||
| 333 | DIE ("user %.*s not found", SVFMT (login)); | ||
| 334 | |||
| 335 | string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:", | ||
| 336 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 337 | |||
| 338 | if (new_entry.id != -1) { | ||
| 339 | if (lookup_id (passwd, new_entry.id)) | ||
| 340 | DIE ("user with id %d already exists", new_entry.id); | ||
| 341 | entry->id = new_entry.id; | ||
| 342 | string_builder_printf (&passwd_log, " new id %d,", entry->id); | ||
| 343 | } | ||
| 344 | |||
| 345 | if (new_entry.security_level != SL_COUNT) { | ||
| 346 | entry->security_level = new_entry.security_level; | ||
| 347 | string_builder_printf (&passwd_log, " new security level %s,", | ||
| 348 | security_level_names[entry->security_level]); | ||
| 349 | } | ||
| 350 | } else { | ||
| 351 | if (new_entry.id != -1) | ||
| 352 | DIE ("permission to change id denied"); | ||
| 353 | if (new_entry.security_level != SL_COUNT) | ||
| 354 | DIE ("permission to change security level denied"); | ||
| 355 | |||
| 356 | fputs ("Password: ", stdout); | ||
| 357 | struct string_view password = parse_password (read_password ()); | ||
| 358 | entry = authenticate (passwd, login, password); | ||
| 359 | if (!entry) exit (1); | ||
| 360 | string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:", | ||
| 361 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 362 | } | ||
| 363 | |||
| 364 | |||
| 365 | if (prompt_for_new_password) { | ||
| 366 | fputs ("New password: ", stdout); | ||
| 367 | struct string_view password = SVDUP (parse_password (read_password ())); | ||
| 368 | fputs ("Repeat password: ", stdout); | ||
| 369 | struct string_view repeated = read_password (); | ||
| 370 | if (string_view_compare (password, repeated) != 0) | ||
| 371 | DIE ("passwords don't match"); | ||
| 372 | entry->encoded_password = SVDUP (encode_password (password)); | ||
| 373 | string_builder_printf (&passwd_log, " changed password,"); | ||
| 374 | } else if (new_entry.encoded_password.begin != NULL) { | ||
| 375 | entry->encoded_password = new_entry.encoded_password; | ||
| 376 | string_builder_printf (&passwd_log, " changed password,"); | ||
| 377 | } | ||
| 378 | |||
| 379 | if (new_entry.comment.begin != NULL) { | ||
| 380 | entry->comment = new_entry.comment; | ||
| 381 | string_builder_printf (&passwd_log, " new comment `%.*s',", SVFMT (entry->comment)); | ||
| 382 | } | ||
| 383 | |||
| 384 | if (new_entry.login.begin != NULL) { | ||
| 385 | entry->login = new_entry.login; | ||
| 386 | string_builder_printf (&passwd_log, " new login %.*s,", SVFMT (entry->login)); | ||
| 387 | } | ||
| 388 | |||
| 389 | if (DYNAMIC_ARRAY_LAST (passwd_log) != ',') | ||
| 390 | DIE ("no modifications supplied"); | ||
| 391 | DYNAMIC_ARRAY_LAST (passwd_log) = '\n'; | ||
| 392 | |||
| 393 | save_passwd_file (passwd); | ||
| 394 | close_passwd_file (passwd); | ||
| 395 | } break; | ||
| 396 | |||
| 397 | case SUBCOMMAND_DELETE: { // login | ||
| 398 | static struct option longopts[] = { | ||
| 399 | { "help", no_argument, NULL, 'h' }, | ||
| 400 | {0} | ||
| 401 | }; | ||
| 402 | |||
| 403 | char ch; | ||
| 404 | optind = 2; | ||
| 405 | while ((ch = getopt_long (argc, argv, ":h", longopts, NULL)) != -1) { | ||
| 406 | switch (ch) { | ||
| 407 | case 'h': | ||
| 408 | printf ("Usage: %s del [options] LOGIN\n", progname); | ||
| 409 | puts (""); | ||
| 410 | puts ("Options:"); | ||
| 411 | puts (" -h, --help display this help message and exit"); | ||
| 412 | puts (""); | ||
| 413 | exit (0); | ||
| 414 | case '?': DIE ("unknown option -%c", optopt); | ||
| 415 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 416 | default: DIE ("unexpected opt error"); | ||
| 417 | } | ||
| 418 | } | ||
| 419 | |||
| 420 | if (argv[optind] == NULL) | ||
| 421 | DIE ("no login"); | ||
| 422 | |||
| 423 | if (argv[optind + 1] != NULL) | ||
| 424 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 425 | |||
| 426 | if (getuid () != 0) | ||
| 427 | DIE ("permission denied"); | ||
| 428 | |||
| 429 | struct string_view login = SVDUP (SVCSTR (argv[optind])); | ||
| 430 | struct passwd passwd = load_passwd_file (); | ||
| 431 | |||
| 432 | struct passwd_entry *entry; | ||
| 433 | for (entry = passwd.items; entry < passwd.items + passwd.count; ++entry) { | ||
| 434 | if (SVCMP (login, entry->login) == 0) | ||
| 435 | break; | ||
| 436 | } | ||
| 437 | |||
| 438 | if (entry == passwd.items + passwd.count) | ||
| 439 | DIE ("user %.*s doesn't exist", SVFMT (login)); | ||
| 440 | |||
| 441 | string_builder_printf (&passwd_log, "%u deleted user %.*s with id %d", | ||
| 442 | time (NULL), SVFMT (entry->login), entry->id); | ||
| 443 | if (entry->comment.begin) | ||
| 444 | string_builder_printf (&passwd_log, " (%.*s)", SVFMT (entry->comment)); | ||
| 445 | DYNAMIC_ARRAY_APPEND (passwd_log, '\n'); | ||
| 446 | |||
| 447 | if (entry + 1 != passwd.items + passwd.count) { | ||
| 448 | memmove (entry, entry + 1, | ||
| 449 | (passwd.count - (entry + 1 - passwd.items))*sizeof (*entry)); | ||
| 450 | } passwd.count -= 1; | ||
| 451 | |||
| 452 | save_passwd_file (passwd); | ||
| 453 | close_passwd_file (passwd); | ||
| 454 | } break; | ||
| 455 | |||
| 456 | default: | ||
| 457 | usage (progname); | ||
| 458 | exit (strcmp (value, "-h") != 0 && strcmp (value, "--help") != 0); | ||
| 459 | } | ||
| 460 | |||
| 461 | append_passwd_log (); | ||
| 462 | |||
| 463 | return EXIT_SUCCESS; | ||
| 464 | } | ||
| 465 | |||
| 466 | // src/passwdctl.c ends here | ||
diff --git a/03/src/shell.c b/03/src/shell.c new file mode 100644 index 0000000..0935ebc --- /dev/null +++ b/03/src/shell.c | |||
| @@ -0,0 +1,1762 @@ | |||
| 1 | // src/shell.c --- utility for providing access to protected folder | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <assert.h> | ||
| 12 | #include <getopt.h> | ||
| 13 | #include <stdlib.h> | ||
| 14 | #include <errno.h> | ||
| 15 | #include <unistd.h> | ||
| 16 | #include <fcntl.h> | ||
| 17 | #include <time.h> | ||
| 18 | #include <sys/stat.h> | ||
| 19 | #include <sys/mman.h> | ||
| 20 | #include <glob.h> | ||
| 21 | #include <stdio.h> | ||
| 22 | #include <dirent.h> | ||
| 23 | #include <readline/readline.h> | ||
| 24 | #include <readline/history.h> | ||
| 25 | |||
| 26 | #include "common.h" | ||
| 27 | |||
| 28 | #define CONFDATA PREFIX"/confdata" | ||
| 29 | #define ACL PREFIX"/etc/acl" | ||
| 30 | |||
| 31 | int id; | ||
| 32 | |||
| 33 | struct string_view | ||
| 34 | canonicalize (struct string_view filename) | ||
| 35 | { | ||
| 36 | static struct string_builder sb = {0}; | ||
| 37 | STRING_BUILDER_RESET (sb); | ||
| 38 | |||
| 39 | static struct { | ||
| 40 | struct string_view *items; | ||
| 41 | uint32_t count; | ||
| 42 | uint32_t capacity; | ||
| 43 | } parts = {0}; | ||
| 44 | DYNAMIC_ARRAY_RESET (parts); | ||
| 45 | |||
| 46 | bool ends_with_slash = filename.end[-1] == '/'; | ||
| 47 | |||
| 48 | if (*filename.begin != '/') { | ||
| 49 | DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 128); | ||
| 50 | for (;;) { | ||
| 51 | if (getcwd (sb.string, sb.capacity)) { | ||
| 52 | sb.length = strlen (sb.string); | ||
| 53 | break; | ||
| 54 | } | ||
| 55 | if (errno != ERANGE) | ||
| 56 | return SVNULL; | ||
| 57 | DYNAMIC_ARRAY_ENSURE_CAPACITY (sb, 2*sb.capacity); | ||
| 58 | } | ||
| 59 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 60 | } | ||
| 61 | |||
| 62 | STRING_BUILDER_APPEND_STRING_VIEW (sb, filename); | ||
| 63 | filename = SVSB (sb); | ||
| 64 | |||
| 65 | while (++filename.begin < filename.end) { | ||
| 66 | struct string_view part = string_view_pop_up_to (&filename, '/'); | ||
| 67 | if (SVLEN (part) == 0) continue; | ||
| 68 | if (SVCMP (part, SVCSTR (".")) == 0) continue; | ||
| 69 | if (SVCMP (part, SVCSTR ("..")) == 0) { | ||
| 70 | if (parts.count == 0) return SVNULL; | ||
| 71 | parts.count -= 1; | ||
| 72 | continue; | ||
| 73 | } | ||
| 74 | DYNAMIC_ARRAY_APPEND (parts, part); | ||
| 75 | } | ||
| 76 | |||
| 77 | STRING_BUILDER_RESET (sb); | ||
| 78 | for (struct string_view *part = parts.items; | ||
| 79 | part < parts.items + parts.count; ++part) { | ||
| 80 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 81 | STRING_BUILDER_APPEND_STRING_VIEW (sb, *part); | ||
| 82 | } | ||
| 83 | |||
| 84 | if (ends_with_slash) | ||
| 85 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 86 | |||
| 87 | return SVSB (sb); | ||
| 88 | } | ||
| 89 | |||
| 90 | struct acl_grant { | ||
| 91 | int id; | ||
| 92 | enum access_rights access_rights; | ||
| 93 | }; | ||
| 94 | |||
| 95 | struct acl { | ||
| 96 | struct string_view filename; | ||
| 97 | const char *path; | ||
| 98 | enum security_level security_level; | ||
| 99 | int owner; | ||
| 100 | int grant_count; | ||
| 101 | struct acl_grant grants[]; | ||
| 102 | }; | ||
| 103 | |||
| 104 | const char * | ||
| 105 | filename_to_acl_path (struct string_view filename) | ||
| 106 | { | ||
| 107 | static struct string_builder acl_path = {0}; | ||
| 108 | |||
| 109 | struct string_view canonical = canonicalize (filename); | ||
| 110 | ASSERT (strncmp (canonical.begin, CONFDATA, strlen (CONFDATA)) == 0); | ||
| 111 | |||
| 112 | STRING_BUILDER_RESET (acl_path); | ||
| 113 | STRING_BUILDER_APPEND_CSTR (acl_path, ACL); | ||
| 114 | STRING_BUILDER_APPEND_CHAR (acl_path, '/'); | ||
| 115 | if (SVLEN (canonical) == strlen (CONFDATA)) { | ||
| 116 | STRING_BUILDER_APPEND_CHAR (acl_path, '!'); | ||
| 117 | goto finish; | ||
| 118 | } | ||
| 119 | |||
| 120 | for (const char *head = canonical.begin + strlen (CONFDATA); head < canonical.end; ++head) { | ||
| 121 | if (*head == '/') STRING_BUILDER_APPEND_CHAR (acl_path, '!'); | ||
| 122 | else STRING_BUILDER_APPEND_CHAR (acl_path, *head); | ||
| 123 | } | ||
| 124 | |||
| 125 | finish: | ||
| 126 | STRING_BUILDER_TERMINATE (acl_path); | ||
| 127 | return acl_path.string; | ||
| 128 | } | ||
| 129 | |||
| 130 | void | ||
| 131 | init_acl_for_file (struct string_view filename, int owner) | ||
| 132 | { | ||
| 133 | struct passwd passwd = load_passwd_file (); | ||
| 134 | struct passwd_entry *entry = lookup_id (passwd, id); | ||
| 135 | close_passwd_file (passwd); | ||
| 136 | ASSERT (entry); | ||
| 137 | |||
| 138 | const char *path = filename_to_acl_path (filename); | ||
| 139 | ASSERT (path); | ||
| 140 | |||
| 141 | elevate (); | ||
| 142 | int fd = open (path, O_WRONLY | O_CREAT | O_EXCL); | ||
| 143 | drop (); | ||
| 144 | ASSERT (fd != -1); | ||
| 145 | |||
| 146 | FILE *stream = fdopen (fd, "w"); | ||
| 147 | ASSERT (stream); | ||
| 148 | fprintf (stream, "%d %d 0\n", entry->security_level, id); | ||
| 149 | fclose (stream); | ||
| 150 | } | ||
| 151 | |||
| 152 | /// File has to be in confdata | ||
| 153 | struct acl * | ||
| 154 | load_acl_for_file (struct string_view filename) | ||
| 155 | { | ||
| 156 | struct acl header = { | ||
| 157 | .filename = filename, | ||
| 158 | .path = filename_to_acl_path (filename), | ||
| 159 | }; | ||
| 160 | ASSERT (header.path); | ||
| 161 | |||
| 162 | elevate (); | ||
| 163 | int fd = open (header.path, O_RDONLY); | ||
| 164 | drop (); | ||
| 165 | if (fd == -1) return NULL; | ||
| 166 | struct stat st; | ||
| 167 | fstat (fd, &st); | ||
| 168 | if (S_ISDIR (st.st_mode)) | ||
| 169 | return NULL; | ||
| 170 | |||
| 171 | FILE *stream = fdopen (fd, "r"); | ||
| 172 | ASSERT (stream); | ||
| 173 | |||
| 174 | fscanf (stream, "%d %d %d", | ||
| 175 | (int *) &header.security_level, &header.owner, &header.grant_count); | ||
| 176 | struct acl *acl = malloc (sizeof (*acl) + | ||
| 177 | (header.grant_count + 1)*sizeof (*acl->grants)); | ||
| 178 | *acl = header; | ||
| 179 | for (int i = 0; i < acl->grant_count; ++i) | ||
| 180 | fscanf (stream, "%d %d", | ||
| 181 | &acl->grants[i].id, (int *) &acl->grants[i].access_rights); | ||
| 182 | fclose (stream); | ||
| 183 | |||
| 184 | return acl; | ||
| 185 | } | ||
| 186 | |||
| 187 | void | ||
| 188 | save_acl (struct acl *acl) | ||
| 189 | { | ||
| 190 | elevate (); | ||
| 191 | int fd = open (acl->path, O_WRONLY); | ||
| 192 | drop (); | ||
| 193 | ASSERT (fd != -1); | ||
| 194 | |||
| 195 | FILE *stream = fdopen (fd, "w"); | ||
| 196 | ASSERT (stream); | ||
| 197 | |||
| 198 | fprintf (stream, "%d %d %d\n", | ||
| 199 | acl->security_level, acl->owner, acl->grant_count); | ||
| 200 | for (int i = 0; i < acl->grant_count; ++i) | ||
| 201 | fprintf (stream, "%d %d\n", | ||
| 202 | acl->grants[i].id, acl->grants[i].access_rights); | ||
| 203 | fclose (stream); | ||
| 204 | } | ||
| 205 | |||
| 206 | struct command_line { | ||
| 207 | struct string_builder expanded; | ||
| 208 | struct string_view command; | ||
| 209 | union {struct string_view *items, *args; }; | ||
| 210 | union {uint32_t count, argc; }; | ||
| 211 | uint32_t capacity; | ||
| 212 | }; | ||
| 213 | |||
| 214 | struct string_builder confdata_log = {0}; | ||
| 215 | |||
| 216 | void | ||
| 217 | flush_confdata_log () | ||
| 218 | { | ||
| 219 | if (confdata_log.count) { | ||
| 220 | elevate (); | ||
| 221 | int fd = open (PREFIX"/log/confdata.log", O_CREAT | O_WRONLY | O_APPEND); | ||
| 222 | drop (); | ||
| 223 | write (fd, confdata_log.items, confdata_log.count); | ||
| 224 | close (fd); | ||
| 225 | DYNAMIC_ARRAY_RESET (confdata_log); | ||
| 226 | } | ||
| 227 | } | ||
| 228 | |||
| 229 | int | ||
| 230 | is_conf (struct string_view filename) | ||
| 231 | { | ||
| 232 | int exists = 1; | ||
| 233 | elevate (); | ||
| 234 | char *canonical = realpath (filename.begin, NULL); | ||
| 235 | if (!canonical) { | ||
| 236 | exists = 0; | ||
| 237 | struct string_view dirname = SVDUP0 (string_view_dirname (filename)); | ||
| 238 | canonical = realpath (dirname.begin, NULL); | ||
| 239 | free ((void *) dirname.begin); | ||
| 240 | } | ||
| 241 | drop (); | ||
| 242 | |||
| 243 | if (canonical) { | ||
| 244 | bool starts_with = string_view_starts_with (SVCSTR (canonical), SVCSTR (CONFDATA)); | ||
| 245 | free (canonical); | ||
| 246 | return starts_with ? 1 + exists : 0; | ||
| 247 | } | ||
| 248 | |||
| 249 | return 0; | ||
| 250 | } | ||
| 251 | |||
| 252 | bool | ||
| 253 | authorize (int id, struct string_view filename, enum access_rights ar) | ||
| 254 | { | ||
| 255 | bool ret = false; | ||
| 256 | struct passwd passwd = load_passwd_file (); | ||
| 257 | struct passwd_entry *entry = lookup_id (passwd, id); | ||
| 258 | if (!entry) { | ||
| 259 | fprintf (stderr, "user no longer exists, switch user"); | ||
| 260 | goto finish; | ||
| 261 | } | ||
| 262 | |||
| 263 | struct acl *acl = load_acl_for_file (filename); | ||
| 264 | if (!acl) { | ||
| 265 | ret = true; | ||
| 266 | goto finish; | ||
| 267 | } | ||
| 268 | |||
| 269 | if (acl->owner == id) goto authorized; | ||
| 270 | for (int i = 0; i < acl->grant_count; ++i) { | ||
| 271 | if (acl->grants[i].id != id) continue; | ||
| 272 | enum access_rights acl_ar = acl->grants[i].access_rights; | ||
| 273 | if ((ar & acl_ar) == ar) goto authorized; | ||
| 274 | else break; | ||
| 275 | } | ||
| 276 | |||
| 277 | denied: | ||
| 278 | fprintf (stderr, "access denied '%.*s'\n", SVFMT (filename)); | ||
| 279 | string_builder_printf (&passwd_log, | ||
| 280 | "%u user '%.*s' (%d) was denied access %c%c%c to '%.*s'\n", | ||
| 281 | time (NULL), SVFMT (entry->login), entry->id, | ||
| 282 | ar & AR_READ ? 'r' : '-', | ||
| 283 | ar & AR_WRITE ? 'w' : '-', | ||
| 284 | ar & AR_DELETE ? 'd' : '-', SVFMT (filename)); | ||
| 285 | goto finish; | ||
| 286 | |||
| 287 | authorized:; | ||
| 288 | #ifdef MAC | ||
| 289 | if ((ar & AR_READ ) && entry->security_level > acl->security_level) goto denied; | ||
| 290 | if ((ar & AR_WRITE) && entry->security_level < acl->security_level) goto denied; | ||
| 291 | #endif | ||
| 292 | |||
| 293 | ret = true; | ||
| 294 | string_builder_printf (&passwd_log, | ||
| 295 | "%u user '%.*s' (%d) was granted access %c%c%c to '%.*s'\n", | ||
| 296 | time (NULL), SVFMT (entry->login), entry->id, | ||
| 297 | ar & AR_READ ? 'r' : '-', | ||
| 298 | ar & AR_WRITE ? 'w' : '-', | ||
| 299 | ar & AR_DELETE ? 'd' : '-', SVFMT (filename)); | ||
| 300 | |||
| 301 | finish: | ||
| 302 | close_passwd_file (passwd); | ||
| 303 | return ret; | ||
| 304 | } | ||
| 305 | |||
| 306 | void | ||
| 307 | created_conf_file (struct string_view filename) | ||
| 308 | { | ||
| 309 | // TODO(cmmm): log | ||
| 310 | init_acl_for_file (filename, id); | ||
| 311 | } | ||
| 312 | |||
| 313 | void | ||
| 314 | deleted_conf_file (struct string_view filename) | ||
| 315 | { | ||
| 316 | const char *path = filename_to_acl_path (filename); | ||
| 317 | elevate (); | ||
| 318 | remove (path); | ||
| 319 | drop (); | ||
| 320 | // TODO(cmmm): log | ||
| 321 | } | ||
| 322 | |||
| 323 | bool | ||
| 324 | copy_file (struct string_view source, struct string_view destination) | ||
| 325 | { | ||
| 326 | int conf_source = is_conf (source); | ||
| 327 | int conf_destination = is_conf (destination); | ||
| 328 | |||
| 329 | if (conf_source && !conf_destination) { | ||
| 330 | fprintf (stderr, "access denied: no one can copy out of confdata\n"); | ||
| 331 | return false; | ||
| 332 | } | ||
| 333 | |||
| 334 | if (conf_source && !authorize (id, source, AR_READ )) return false; | ||
| 335 | if (conf_destination && !authorize (id, destination, AR_WRITE)) return false; | ||
| 336 | |||
| 337 | bool ret = true; | ||
| 338 | if (conf_source) elevate (); | ||
| 339 | int source_fd = open (source.begin, O_RDONLY); | ||
| 340 | if (conf_source) drop (); | ||
| 341 | if (source_fd == -1) { | ||
| 342 | fprintf (stderr, "error opening file for reading '%.*s': %s\n", | ||
| 343 | SVFMT (source), strerror (errno)); | ||
| 344 | return false; | ||
| 345 | } | ||
| 346 | |||
| 347 | struct stat st; | ||
| 348 | if (fstat (source_fd, &st) == -1) { | ||
| 349 | fprintf (stderr, "error getting file stats for '%.*s': %s\n", | ||
| 350 | SVFMT (source), strerror (errno)); | ||
| 351 | ret = false; | ||
| 352 | goto close_source; | ||
| 353 | } | ||
| 354 | |||
| 355 | if (!S_ISREG (st.st_mode)) { | ||
| 356 | fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source)); | ||
| 357 | ret = false; | ||
| 358 | goto close_source; | ||
| 359 | } | ||
| 360 | |||
| 361 | if (conf_destination) elevate (); | ||
| 362 | int destination_fd = open (destination.begin, O_RDWR | O_CREAT | O_EXCL | | ||
| 363 | O_TRUNC, S_IRUSR | S_IWUSR); | ||
| 364 | if (conf_destination) drop (); | ||
| 365 | if (destination_fd == -1) { | ||
| 366 | fprintf (stderr, "error opening file for writing '%.*s': %s\n", | ||
| 367 | SVFMT (destination), strerror (errno)); | ||
| 368 | ret = false; | ||
| 369 | goto close_source; | ||
| 370 | } | ||
| 371 | |||
| 372 | if (ftruncate (destination_fd, st.st_size) == -1) { | ||
| 373 | fprintf (stderr, "error setting file size for '%.*s': %s\n", | ||
| 374 | SVFMT (destination), strerror (errno)); | ||
| 375 | ret = false; | ||
| 376 | goto close_destination; | ||
| 377 | } | ||
| 378 | |||
| 379 | void *source_map = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, source_fd, 0); | ||
| 380 | if (source_map == MAP_FAILED) { | ||
| 381 | fprintf (stderr, "error mapping source file '%.*s': %s\n", | ||
| 382 | SVFMT (source), strerror (errno)); | ||
| 383 | ret = false; | ||
| 384 | goto close_destination; | ||
| 385 | } | ||
| 386 | |||
| 387 | void *destination_map = mmap (NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, destination_fd, 0); | ||
| 388 | if (destination_map == MAP_FAILED) { | ||
| 389 | fprintf (stderr, "error mapping destination file '%.*s': %s\n", | ||
| 390 | SVFMT (destination), strerror (errno)); | ||
| 391 | ret = false; | ||
| 392 | goto munmap_source; | ||
| 393 | } | ||
| 394 | |||
| 395 | memcpy (destination_map, source_map, st.st_size); | ||
| 396 | |||
| 397 | if (conf_destination) { | ||
| 398 | elevate (); | ||
| 399 | char *canonical = realpath (destination.begin, NULL); | ||
| 400 | drop (); | ||
| 401 | assert (canonical); | ||
| 402 | string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n", | ||
| 403 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 404 | free (canonical); | ||
| 405 | |||
| 406 | if (conf_destination != 2) | ||
| 407 | created_conf_file (destination); | ||
| 408 | } | ||
| 409 | |||
| 410 | munmap (destination_map, st.st_size); | ||
| 411 | munmap_source: | ||
| 412 | munmap (source_map, st.st_size); | ||
| 413 | close_destination: | ||
| 414 | close (destination_fd); | ||
| 415 | close_source: | ||
| 416 | close (source_fd); | ||
| 417 | |||
| 418 | elevate (); | ||
| 419 | if (conf_destination) chown (destination.begin, euid, egid); | ||
| 420 | else chown (destination.begin, ruid, rgid); | ||
| 421 | drop (); | ||
| 422 | |||
| 423 | return ret; | ||
| 424 | } | ||
| 425 | |||
| 426 | bool | ||
| 427 | rename_file (struct string_view source, struct string_view destination) | ||
| 428 | { | ||
| 429 | int conf_source = is_conf (source); | ||
| 430 | int conf_destination = is_conf (destination); | ||
| 431 | |||
| 432 | if (conf_source && !conf_destination) { | ||
| 433 | fprintf (stderr, "access denied: no one can rename out of confdata\n"); | ||
| 434 | return false; | ||
| 435 | } | ||
| 436 | |||
| 437 | if (conf_source && !authorize (id, source, AR_READ | AR_DELETE)) return false; | ||
| 438 | if (conf_destination && !authorize (id, destination, AR_WRITE )) return false; | ||
| 439 | |||
| 440 | struct stat st; | ||
| 441 | if (stat (source.begin, &st) == -1) { | ||
| 442 | fprintf (stderr, "error getting file stats for '%.*s': %s\n", | ||
| 443 | SVFMT (source), strerror (errno)); | ||
| 444 | return false; | ||
| 445 | } | ||
| 446 | |||
| 447 | if (!S_ISREG (st.st_mode)) { | ||
| 448 | fprintf (stderr, "source file is not regular '%.*s'\n", SVFMT (source)); | ||
| 449 | return false; | ||
| 450 | } | ||
| 451 | |||
| 452 | elevate (); | ||
| 453 | int res = access (destination.begin, F_OK); | ||
| 454 | drop (); | ||
| 455 | if (res == 0) { | ||
| 456 | fprintf (stderr, "destination file already exists '%.*s'\n", SVFMT (destination)); | ||
| 457 | return false; | ||
| 458 | } | ||
| 459 | |||
| 460 | char *canonical = NULL; | ||
| 461 | if (conf_source || conf_destination) elevate (); | ||
| 462 | if (conf_source) canonical = realpath (source.begin, NULL); | ||
| 463 | res = rename (source.begin, destination.begin); | ||
| 464 | if (conf_source || conf_destination) drop (); | ||
| 465 | if (res == -1) { | ||
| 466 | fprintf (stderr, "error renaming '%.*s' to '%.*s': %s\n", | ||
| 467 | SVFMT (source), SVFMT (destination), strerror (errno)); | ||
| 468 | free (canonical); | ||
| 469 | return false; | ||
| 470 | } | ||
| 471 | |||
| 472 | if (conf_destination) { | ||
| 473 | elevate (); | ||
| 474 | char *canonical = realpath (destination.begin, NULL); | ||
| 475 | drop (); | ||
| 476 | assert (canonical); | ||
| 477 | string_builder_printf (&confdata_log, "%u user %d wrote to file '!%s'\n", | ||
| 478 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 479 | free (canonical); | ||
| 480 | |||
| 481 | if (conf_destination != 2) | ||
| 482 | created_conf_file (destination); | ||
| 483 | } | ||
| 484 | |||
| 485 | if (conf_source) { | ||
| 486 | assert (canonical); | ||
| 487 | string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n", | ||
| 488 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 489 | free (canonical); | ||
| 490 | |||
| 491 | deleted_conf_file (source); | ||
| 492 | } | ||
| 493 | |||
| 494 | elevate (); | ||
| 495 | if (conf_destination) chown (destination.begin, euid, egid); | ||
| 496 | else chown (destination.begin, ruid, rgid); | ||
| 497 | drop (); | ||
| 498 | |||
| 499 | return true; | ||
| 500 | } | ||
| 501 | |||
| 502 | int | ||
| 503 | parse_command_line (struct command_line *cl, struct string_view line) | ||
| 504 | { | ||
| 505 | DYNAMIC_ARRAY_RESET (cl->expanded); | ||
| 506 | DYNAMIC_ARRAY_RESET (*cl); | ||
| 507 | cl->command = SVNULL; | ||
| 508 | |||
| 509 | // printf ("line: %.*s\n", SVFMT (line)); | ||
| 510 | |||
| 511 | const char *head = line.begin; | ||
| 512 | const char *end = line.end; | ||
| 513 | for (; head < end; ++head) { | ||
| 514 | if (*head == ' ' || *head == '\t') { | ||
| 515 | do head += 1; | ||
| 516 | while (head < end && (*head == ' ' || *head == '\t')); | ||
| 517 | if (head == end) | ||
| 518 | break; | ||
| 519 | if (cl->expanded.length) | ||
| 520 | STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0'); | ||
| 521 | } | ||
| 522 | |||
| 523 | if (*head == '\'') { | ||
| 524 | head += 1; | ||
| 525 | if (head == end) return 0; | ||
| 526 | while (head < end && *head != '\'') | ||
| 527 | STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++); | ||
| 528 | if (head == end && (head[-1] != '\'' || head - 1 == line.begin)) return 0; | ||
| 529 | } else if (*head == '"') { | ||
| 530 | head += 1; | ||
| 531 | if (head == end) return 0; | ||
| 532 | if (*head == '!') { | ||
| 533 | STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA); | ||
| 534 | head += 1; | ||
| 535 | } | ||
| 536 | while (head < end && *head != '"') | ||
| 537 | STRING_BUILDER_APPEND_CHAR (cl->expanded, *head++); | ||
| 538 | if (head == end && (head[-1] != '"' || head - 1 == line.begin)) return 0; | ||
| 539 | } else if (*head == '!' && (cl->expanded.length == 0 || DYNAMIC_ARRAY_LAST (cl->expanded) == '\0')) { | ||
| 540 | STRING_BUILDER_APPEND_CSTR (cl->expanded, CONFDATA); | ||
| 541 | } else { | ||
| 542 | STRING_BUILDER_APPEND_CHAR (cl->expanded, *head); | ||
| 543 | } | ||
| 544 | } STRING_BUILDER_APPEND_CHAR (cl->expanded, '\0'); | ||
| 545 | |||
| 546 | head = cl->expanded.string; | ||
| 547 | end = cl->expanded.string + cl->expanded.length; | ||
| 548 | cl->command.begin = head; | ||
| 549 | while (head < end && *head != '\0') | ||
| 550 | head += 1; | ||
| 551 | cl->command.end = head++; | ||
| 552 | |||
| 553 | if (SVLEN (cl->command) == 0) return 0; | ||
| 554 | |||
| 555 | while (head < end) { | ||
| 556 | struct string_view arg; | ||
| 557 | arg.begin = head; | ||
| 558 | do head += 1; | ||
| 559 | while (head < end && *head != '\0'); | ||
| 560 | arg.end = head++; | ||
| 561 | |||
| 562 | const char *star = strchr (arg.begin, '*'); | ||
| 563 | struct string_view trimmed = arg; | ||
| 564 | if (star) { | ||
| 565 | if (star == arg.begin) { | ||
| 566 | trimmed = SVCSTR ("."); | ||
| 567 | } else { | ||
| 568 | trimmed = SVDUP0 ((struct string_view) { | ||
| 569 | .begin = arg.begin, | ||
| 570 | .end = star, | ||
| 571 | }); | ||
| 572 | } | ||
| 573 | } | ||
| 574 | |||
| 575 | bool conf = is_conf (trimmed); | ||
| 576 | glob_t globs; | ||
| 577 | if (conf) elevate (); | ||
| 578 | int ret = glob (arg.begin, GLOB_MARK | GLOB_NOSORT | GLOB_BRACE | GLOB_TILDE_CHECK, NULL, &globs); | ||
| 579 | if (conf) drop (); | ||
| 580 | if (ret != 0) { | ||
| 581 | DYNAMIC_ARRAY_APPEND (*cl, arg); | ||
| 582 | } else { | ||
| 583 | for (size_t i = 0; i < globs.gl_pathc; ++i) { | ||
| 584 | arg.begin = globs.gl_pathv[i]; | ||
| 585 | arg.end = arg.begin + strlen (arg.begin); | ||
| 586 | DYNAMIC_ARRAY_APPEND (*cl, SVDUP0 (arg)); | ||
| 587 | } | ||
| 588 | } | ||
| 589 | |||
| 590 | globfree (&globs); | ||
| 591 | } | ||
| 592 | |||
| 593 | // printf ("command: %.*s\n", SVFMT (cl->command)); | ||
| 594 | // for (uint32_t i = 0; i < cl->argc; ++i) | ||
| 595 | // printf ("arg: %.*s\n", SVFMT (cl->args[i])); | ||
| 596 | |||
| 597 | return 1; | ||
| 598 | } | ||
| 599 | |||
| 600 | int | ||
| 601 | command_exit (struct command_line cl) | ||
| 602 | { | ||
| 603 | exit (0); | ||
| 604 | } | ||
| 605 | |||
| 606 | int | ||
| 607 | command_help (struct command_line cl) | ||
| 608 | { | ||
| 609 | puts ("Commands:"); | ||
| 610 | puts (" help display information about builtin commands"); | ||
| 611 | puts (" su LOGIN change user to LOGIN"); | ||
| 612 | puts (" pwd print the name of the current working directory "); | ||
| 613 | puts (" whoami print effective user name"); | ||
| 614 | puts (" echo [ARG]... write ARG(s) to the standard output"); | ||
| 615 | puts (" ls [FILE]... list information about the FILE(s)"); | ||
| 616 | puts (" cd [DIR] change the shell working directory"); | ||
| 617 | puts (" mv SOURCE DEST rename SOURCE to DEST"); | ||
| 618 | puts (" mv SOURCE... DIRECTORY move SOURCE(s) to DIRECTORY"); | ||
| 619 | puts (" cp SOURCE DEST copy SOURCE to DEST"); | ||
| 620 | puts (" cp SOURCE... DIRECTORY copy SOURCE(s) to DIRECTORY"); | ||
| 621 | puts (" rm FILE... remove (unlink) the FILE(s)"); | ||
| 622 | puts (" mkdir DIR... create the DIRECTORY(ies), if they do not already exist"); | ||
| 623 | puts (" rmdir DIR... remove the DIRECTORY(ies), if they are empty"); | ||
| 624 | puts (" cat [FILE]... concatenate FILE(s) to standard output"); | ||
| 625 | puts (" append FILE append text from standard input to FILE"); | ||
| 626 | puts (" chown LOGIN FILE... change owner of FILE(s) to LOGIN (root only)"); | ||
| 627 | puts (" chsl SECURITY-LEVEL FILE... change security level of FILE(s) to SECURITY-LEVEL (root only)"); | ||
| 628 | puts (" grant LOGIN {r|w|d}... FILE... grant specified access to FILE(s) for LOGIN"); | ||
| 629 | puts (" revoke LOGIN {r|w|d}... FILE... revoke specified access to FILE(s) from LOGIN"); | ||
| 630 | puts (""); | ||
| 631 | puts ("Aliases:"); | ||
| 632 | puts (" read -> cat"); | ||
| 633 | puts (" copy -> cp"); | ||
| 634 | puts (" remove -> rm"); | ||
| 635 | puts (""); | ||
| 636 | puts ("Security levels:"); | ||
| 637 | puts (" top-secret"); | ||
| 638 | puts (" secret"); | ||
| 639 | puts (" confidential"); | ||
| 640 | puts (" unclassified"); | ||
| 641 | puts (""); | ||
| 642 | return 0; | ||
| 643 | } | ||
| 644 | |||
| 645 | int | ||
| 646 | command_su (struct command_line cl) | ||
| 647 | { | ||
| 648 | if (cl.argc != 1) { | ||
| 649 | fprintf (stderr, "usage: %.*s LOGIN\n", SVFMT (cl.command)); | ||
| 650 | return 1; | ||
| 651 | } | ||
| 652 | |||
| 653 | struct string_view login = cl.args[0]; | ||
| 654 | int ret = 0; | ||
| 655 | struct passwd passwd = load_passwd_file (); | ||
| 656 | struct passwd_entry *entry; | ||
| 657 | if (getuid () == 0) { | ||
| 658 | entry = lookup_login (passwd, login); | ||
| 659 | if (!entry) { | ||
| 660 | fprintf (stderr, "user %.*s doesn't exist\n", SVFMT (login)); | ||
| 661 | ret = 1; | ||
| 662 | goto close; | ||
| 663 | } | ||
| 664 | } else { | ||
| 665 | fputs ("Password: ", stdout); | ||
| 666 | struct string_view password = read_password (); | ||
| 667 | entry = authenticate (passwd, login, password); | ||
| 668 | if (!entry) { | ||
| 669 | ret = 1; | ||
| 670 | goto close; | ||
| 671 | } | ||
| 672 | } | ||
| 673 | id = entry->id; | ||
| 674 | |||
| 675 | close: | ||
| 676 | close_passwd_file (passwd); | ||
| 677 | return ret; | ||
| 678 | } | ||
| 679 | |||
| 680 | enum access_rights | ||
| 681 | parse_access_rights (struct string_view sv) | ||
| 682 | { | ||
| 683 | enum access_rights ar = 0; | ||
| 684 | for (const char *head = sv.begin; head < sv.end; ++head) { | ||
| 685 | switch (*head) { | ||
| 686 | case 'r': ar |= AR_READ; continue; | ||
| 687 | case 'w': ar |= AR_WRITE; continue; | ||
| 688 | case 'd': ar |= AR_DELETE; continue; | ||
| 689 | default: return 0; | ||
| 690 | } | ||
| 691 | } | ||
| 692 | return ar; | ||
| 693 | } | ||
| 694 | |||
| 695 | int | ||
| 696 | command_grant (struct command_line cl) | ||
| 697 | { | ||
| 698 | static struct string_builder sb = {0}; | ||
| 699 | |||
| 700 | if (cl.argc < 3) { | ||
| 701 | fprintf (stderr, "usage: %.*s LOGIN {r|w|d}... FILE...\n", SVFMT (cl.command)); | ||
| 702 | return 1; | ||
| 703 | } | ||
| 704 | |||
| 705 | struct string_view login = cl.args[0]; | ||
| 706 | struct passwd passwd = load_passwd_file (); | ||
| 707 | struct passwd_entry *entry = lookup_login (passwd, login); | ||
| 708 | int login_id = entry ? entry->id : -1; | ||
| 709 | close_passwd_file (passwd); | ||
| 710 | |||
| 711 | if (!entry) { | ||
| 712 | fprintf (stderr, "%.*s: user doesn't exist '%.*s'\n", | ||
| 713 | SVFMT (cl.command), SVFMT (login)); | ||
| 714 | return 1; | ||
| 715 | } | ||
| 716 | |||
| 717 | enum access_rights access_rights = parse_access_rights (cl.args[1]); | ||
| 718 | if (!access_rights) { | ||
| 719 | fprintf (stderr, "%.*s: invalid access rights '%.*s'\n", | ||
| 720 | SVFMT (cl.command), SVFMT (cl.args[1])); | ||
| 721 | return 1; | ||
| 722 | } | ||
| 723 | |||
| 724 | int ret = 0; | ||
| 725 | for (uint32_t i = 2; i < cl.argc; ++i) { | ||
| 726 | struct string_view file = cl.args[i]; | ||
| 727 | int conf = is_conf (file); | ||
| 728 | |||
| 729 | if (conf == 0) { | ||
| 730 | fprintf (stderr, "%.*s: warning: skipping file outside of confdata '%.*s'\n", | ||
| 731 | SVFMT (cl.command), SVFMT (file)); | ||
| 732 | continue; | ||
| 733 | } | ||
| 734 | |||
| 735 | if (conf == 1) { | ||
| 736 | fprintf (stderr, "%.*s: warning: skipping nonexistent file '%.*s'\n", | ||
| 737 | SVFMT (cl.command), SVFMT (file)); | ||
| 738 | continue; | ||
| 739 | } | ||
| 740 | |||
| 741 | struct acl *acl = load_acl_for_file (file); | ||
| 742 | ASSERT (acl); | ||
| 743 | if (acl->owner != id && ruid != euid) { | ||
| 744 | fprintf (stderr, "%.*s: error: permission denied: not owner of the file '%.*s'\n", | ||
| 745 | SVFMT (cl.command), SVFMT (file)); | ||
| 746 | ret = 1; | ||
| 747 | continue; | ||
| 748 | } | ||
| 749 | |||
| 750 | for (int i = 0; i < acl->grant_count; ++i) { | ||
| 751 | if (acl->grants[i].id != login_id) | ||
| 752 | continue; | ||
| 753 | |||
| 754 | acl->grants[i].access_rights |= access_rights; | ||
| 755 | goto save; | ||
| 756 | } | ||
| 757 | acl->grants[acl->grant_count++] = (struct acl_grant) { | ||
| 758 | .id = login_id, | ||
| 759 | .access_rights = access_rights, | ||
| 760 | }; | ||
| 761 | |||
| 762 | save: | ||
| 763 | save_acl (acl); | ||
| 764 | free (acl); | ||
| 765 | } | ||
| 766 | |||
| 767 | return ret; | ||
| 768 | } | ||
| 769 | |||
| 770 | int | ||
| 771 | command_revoke (struct command_line cl) | ||
| 772 | { | ||
| 773 | static struct string_builder sb = {0}; | ||
| 774 | |||
| 775 | if (cl.argc < 3) { | ||
| 776 | fprintf (stderr, "usage: %.*s LOGIN {r|w|d}... FILE...\n", SVFMT (cl.command)); | ||
| 777 | return 1; | ||
| 778 | } | ||
| 779 | |||
| 780 | struct string_view login = cl.args[0]; | ||
| 781 | struct passwd passwd = load_passwd_file (); | ||
| 782 | struct passwd_entry *entry = lookup_login (passwd, login); | ||
| 783 | int login_id = entry ? entry->id : -1; | ||
| 784 | close_passwd_file (passwd); | ||
| 785 | |||
| 786 | if (!entry) { | ||
| 787 | fprintf (stderr, "%.*s: user doesn't exist '%.*s'\n", | ||
| 788 | SVFMT (cl.command), SVFMT (login)); | ||
| 789 | return 1; | ||
| 790 | } | ||
| 791 | |||
| 792 | enum access_rights access_rights = parse_access_rights (cl.args[1]); | ||
| 793 | if (!access_rights) { | ||
| 794 | fprintf (stderr, "%.*s: invalid access rights '%.*s'\n", | ||
| 795 | SVFMT (cl.command), SVFMT (cl.args[1])); | ||
| 796 | return 1; | ||
| 797 | } | ||
| 798 | |||
| 799 | int ret = 0; | ||
| 800 | for (uint32_t i = 2; i < cl.argc; ++i) { | ||
| 801 | struct string_view file = cl.args[i]; | ||
| 802 | int conf = is_conf (file); | ||
| 803 | |||
| 804 | if (conf == 0) { | ||
| 805 | fprintf (stderr, "%.*s: warning: skipping file outside of confdata '%.*s'\n", | ||
| 806 | SVFMT (cl.command), SVFMT (file)); | ||
| 807 | continue; | ||
| 808 | } | ||
| 809 | |||
| 810 | if (conf == 1) { | ||
| 811 | fprintf (stderr, "%.*s: warning: skipping nonexistent file '%.*s'\n", | ||
| 812 | SVFMT (cl.command), SVFMT (file)); | ||
| 813 | continue; | ||
| 814 | } | ||
| 815 | |||
| 816 | struct acl *acl = load_acl_for_file (file); | ||
| 817 | ASSERT (acl); | ||
| 818 | if (acl->owner != id && ruid != euid) { | ||
| 819 | fprintf (stderr, "%.*s: error: permission denied: not owner of the file '%.*s'\n", | ||
| 820 | SVFMT (cl.command), SVFMT (file)); | ||
| 821 | ret = 1; | ||
| 822 | continue; | ||
| 823 | } | ||
| 824 | |||
| 825 | for (int i = 0; i < acl->grant_count; ++i) { | ||
| 826 | if (acl->grants[i].id != login_id) | ||
| 827 | continue; | ||
| 828 | |||
| 829 | acl->grants[i].access_rights &= ~access_rights; | ||
| 830 | if (acl->grants[i].access_rights == 0) | ||
| 831 | acl->grants[i] = acl->grants[--acl->grant_count]; | ||
| 832 | |||
| 833 | goto save; | ||
| 834 | } | ||
| 835 | |||
| 836 | save: | ||
| 837 | save_acl (acl); | ||
| 838 | free (acl); | ||
| 839 | } | ||
| 840 | |||
| 841 | return ret; | ||
| 842 | } | ||
| 843 | |||
| 844 | int | ||
| 845 | command_chown (struct command_line cl) | ||
| 846 | { | ||
| 847 | static struct string_builder sb = {0}; | ||
| 848 | |||
| 849 | if (cl.argc < 2) { | ||
| 850 | fprintf (stderr, "usage: %.*s LOGIN FILE...\n", SVFMT (cl.command)); | ||
| 851 | return 1; | ||
| 852 | } | ||
| 853 | |||
| 854 | if (euid != ruid) { | ||
| 855 | fprintf (stderr, "%.*s: error: only superuser can change file ownership\n", | ||
| 856 | SVFMT (cl.command)); | ||
| 857 | return 1; | ||
| 858 | } | ||
| 859 | |||
| 860 | struct string_view login = cl.args[0]; | ||
| 861 | struct passwd passwd = load_passwd_file (); | ||
| 862 | struct passwd_entry *entry = lookup_login (passwd, login); | ||
| 863 | int login_id = entry ? entry->id : -1; | ||
| 864 | close_passwd_file (passwd); | ||
| 865 | |||
| 866 | if (!entry) { | ||
| 867 | fprintf (stderr, "%.*s: user doesn't exist '%.*s'\n", | ||
| 868 | SVFMT (cl.command), SVFMT (login)); | ||
| 869 | return 1; | ||
| 870 | } | ||
| 871 | |||
| 872 | int ret = 0; | ||
| 873 | for (uint32_t i = 1; i < cl.argc; ++i) { | ||
| 874 | struct string_view file = cl.args[i]; | ||
| 875 | int conf = is_conf (file); | ||
| 876 | |||
| 877 | if (conf == 0) { | ||
| 878 | fprintf (stderr, "%.*s: warning: skipping file outside of confdata '%.*s'\n", | ||
| 879 | SVFMT (cl.command), SVFMT (file)); | ||
| 880 | continue; | ||
| 881 | } | ||
| 882 | |||
| 883 | if (conf == 1) { | ||
| 884 | fprintf (stderr, "%.*s: warning: skipping nonexistent file '%.*s'\n", | ||
| 885 | SVFMT (cl.command), SVFMT (file)); | ||
| 886 | continue; | ||
| 887 | } | ||
| 888 | |||
| 889 | struct acl *acl = load_acl_for_file (file); | ||
| 890 | ASSERT (acl); | ||
| 891 | acl->owner = login_id; | ||
| 892 | save_acl (acl); | ||
| 893 | free (acl); | ||
| 894 | } | ||
| 895 | |||
| 896 | return ret; | ||
| 897 | } | ||
| 898 | |||
| 899 | enum security_level | ||
| 900 | parse_security_level (struct string_view sv) | ||
| 901 | { | ||
| 902 | for (enum security_level sl = 0; sl < SL_COUNT; ++sl) { | ||
| 903 | if (SVCMP (sv, SVCSTR (security_level_names[sl])) == 0) | ||
| 904 | return sl; | ||
| 905 | } | ||
| 906 | |||
| 907 | return SL_COUNT; | ||
| 908 | } | ||
| 909 | |||
| 910 | int | ||
| 911 | command_chsl (struct command_line cl) | ||
| 912 | { | ||
| 913 | static struct string_builder sb = {0}; | ||
| 914 | |||
| 915 | if (cl.argc < 2) { | ||
| 916 | fprintf (stderr, "usage: %.*s LOGIN FILE...\n", SVFMT (cl.command)); | ||
| 917 | return 1; | ||
| 918 | } | ||
| 919 | |||
| 920 | if (euid != ruid) { | ||
| 921 | fprintf (stderr, "%.*s: error: only superuser can change file security level\n", | ||
| 922 | SVFMT (cl.command)); | ||
| 923 | return 1; | ||
| 924 | } | ||
| 925 | |||
| 926 | enum security_level security_level = parse_security_level (cl.args[0]); | ||
| 927 | if (security_level == SL_COUNT) { | ||
| 928 | fprintf (stderr, "%.*s: error: invalid security level, use command 'help' to get listing of valid security levels\n", | ||
| 929 | SVFMT (cl.command)); | ||
| 930 | return 1; | ||
| 931 | } | ||
| 932 | |||
| 933 | int ret = 0; | ||
| 934 | for (uint32_t i = 1; i < cl.argc; ++i) { | ||
| 935 | struct string_view file = cl.args[i]; | ||
| 936 | int conf = is_conf (file); | ||
| 937 | |||
| 938 | if (conf == 0) { | ||
| 939 | fprintf (stderr, "%.*s: warning: skipping file outside of confdata '%.*s'\n", | ||
| 940 | SVFMT (cl.command), SVFMT (file)); | ||
| 941 | continue; | ||
| 942 | } | ||
| 943 | |||
| 944 | if (conf == 1) { | ||
| 945 | fprintf (stderr, "%.*s: warning: skipping nonexistent file '%.*s'\n", | ||
| 946 | SVFMT (cl.command), SVFMT (file)); | ||
| 947 | continue; | ||
| 948 | } | ||
| 949 | |||
| 950 | struct acl *acl = load_acl_for_file (file); | ||
| 951 | ASSERT (acl); | ||
| 952 | acl->security_level = security_level; | ||
| 953 | save_acl (acl); | ||
| 954 | free (acl); | ||
| 955 | } | ||
| 956 | |||
| 957 | return ret; | ||
| 958 | } | ||
| 959 | |||
| 960 | int | ||
| 961 | command_pwd (struct command_line cl) | ||
| 962 | { | ||
| 963 | size_t size = 256; | ||
| 964 | |||
| 965 | for (;;) { | ||
| 966 | char *buffer = (char *) malloc (size); | ||
| 967 | if (getcwd (buffer, size) == buffer) { | ||
| 968 | puts (buffer); | ||
| 969 | free (buffer); | ||
| 970 | return 0; | ||
| 971 | } | ||
| 972 | free (buffer); | ||
| 973 | if (errno != ERANGE) | ||
| 974 | return errno; | ||
| 975 | size *= 2; | ||
| 976 | } | ||
| 977 | } | ||
| 978 | |||
| 979 | int | ||
| 980 | command_whoami (struct command_line cl) | ||
| 981 | { | ||
| 982 | int ret = 0; | ||
| 983 | struct passwd passwd = load_passwd_file (); | ||
| 984 | struct passwd_entry *entry = lookup_id (passwd, id); | ||
| 985 | if (!entry) { | ||
| 986 | fprintf (stderr, "user with id %d no longed exists\n", id); | ||
| 987 | ret = 1; | ||
| 988 | goto close; | ||
| 989 | } | ||
| 990 | |||
| 991 | printf ("%.*s", SVFMT (entry->login)); | ||
| 992 | |||
| 993 | #ifdef MAC | ||
| 994 | printf (" (%s)", security_level_names[entry->security_level]); | ||
| 995 | #endif | ||
| 996 | |||
| 997 | putchar ('\n'); | ||
| 998 | |||
| 999 | close: | ||
| 1000 | close_passwd_file (passwd); | ||
| 1001 | return ret; | ||
| 1002 | } | ||
| 1003 | |||
| 1004 | int | ||
| 1005 | command_echo (struct command_line cl) | ||
| 1006 | { | ||
| 1007 | if (cl.argc == 0) | ||
| 1008 | return 0; | ||
| 1009 | |||
| 1010 | fputs (cl.args[0].begin, stdout); | ||
| 1011 | for (uint32_t argind = 1; argind < cl.argc; ++argind) { | ||
| 1012 | putchar (' '); | ||
| 1013 | fputs (cl.args[argind].begin, stdout); | ||
| 1014 | } putchar ('\n'); | ||
| 1015 | |||
| 1016 | return 0; | ||
| 1017 | } | ||
| 1018 | |||
| 1019 | int | ||
| 1020 | command_cd (struct command_line cl) | ||
| 1021 | { | ||
| 1022 | struct string_view dir = cl.argc ? cl.args[0] : SVCSTR (CONFDATA); | ||
| 1023 | bool conf = string_view_starts_with (dir, SVCSTR (CONFDATA)); | ||
| 1024 | |||
| 1025 | if (conf) elevate (); | ||
| 1026 | if (chdir (dir.begin) == -1) { | ||
| 1027 | fprintf (stderr, "%.*s: cannot change directory to '%s': %s\n", | ||
| 1028 | SVFMT (cl.command), dir.begin, strerror (errno)); | ||
| 1029 | } | ||
| 1030 | if (conf) drop (); | ||
| 1031 | |||
| 1032 | return 0; | ||
| 1033 | } | ||
| 1034 | |||
| 1035 | bool | ||
| 1036 | is_dir (struct string_view filename) | ||
| 1037 | { | ||
| 1038 | struct stat st; | ||
| 1039 | |||
| 1040 | elevate (); | ||
| 1041 | int res = stat (filename.begin, &st); | ||
| 1042 | drop (); | ||
| 1043 | |||
| 1044 | if (res == -1) | ||
| 1045 | return false; | ||
| 1046 | |||
| 1047 | return S_ISDIR (st.st_mode); | ||
| 1048 | } | ||
| 1049 | |||
| 1050 | int | ||
| 1051 | command_mv (struct command_line cl) | ||
| 1052 | { | ||
| 1053 | static struct string_builder sb = {0}; | ||
| 1054 | |||
| 1055 | if (cl.argc < 2) { | ||
| 1056 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 1057 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 1058 | return 1; | ||
| 1059 | } | ||
| 1060 | |||
| 1061 | int ret = 0; | ||
| 1062 | |||
| 1063 | if (is_dir (cl.args[cl.argc - 1])) { | ||
| 1064 | STRING_BUILDER_RESET (sb); | ||
| 1065 | |||
| 1066 | struct string_view directory = cl.args[cl.argc - 1]; | ||
| 1067 | STRING_BUILDER_APPEND_STRING_VIEW (sb, directory); | ||
| 1068 | if (DYNAMIC_ARRAY_LAST (sb) != '/') | ||
| 1069 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1070 | |||
| 1071 | size_t directory_length = sb.length; | ||
| 1072 | for (uint32_t i = 0; i < cl.argc - 1; ++i) { | ||
| 1073 | sb.length = directory_length; | ||
| 1074 | struct string_view source = cl.args[i]; | ||
| 1075 | |||
| 1076 | struct string_view basename = string_view_basename (source); | ||
| 1077 | STRING_BUILDER_APPEND_STRING_VIEW (sb, basename); | ||
| 1078 | STRING_BUILDER_TERMINATE (sb); | ||
| 1079 | struct string_view destination = SVSB (sb); | ||
| 1080 | |||
| 1081 | if (!rename_file (source, destination)) { | ||
| 1082 | fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n", | ||
| 1083 | SVFMT (source), SVFMT (destination)); | ||
| 1084 | ret = 1; | ||
| 1085 | } | ||
| 1086 | } | ||
| 1087 | } else { | ||
| 1088 | if (cl.argc != 2) { | ||
| 1089 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 1090 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 1091 | return 1; | ||
| 1092 | } | ||
| 1093 | |||
| 1094 | struct string_view source = cl.args[0]; | ||
| 1095 | struct string_view destination = cl.args[1]; | ||
| 1096 | if (!rename_file (source, destination)) { | ||
| 1097 | fprintf (stderr, "mv: failed to rename '%.*s' -> '%.*s'\n", | ||
| 1098 | SVFMT (source), SVFMT (destination)); | ||
| 1099 | ret = 1; | ||
| 1100 | } | ||
| 1101 | } | ||
| 1102 | |||
| 1103 | return ret; | ||
| 1104 | } | ||
| 1105 | |||
| 1106 | int | ||
| 1107 | command_cp (struct command_line cl) | ||
| 1108 | { | ||
| 1109 | static struct string_builder sb = {0}; | ||
| 1110 | |||
| 1111 | if (cl.argc < 2) { | ||
| 1112 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 1113 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 1114 | return 1; | ||
| 1115 | } | ||
| 1116 | |||
| 1117 | int ret = 0; | ||
| 1118 | |||
| 1119 | if (is_dir (cl.args[cl.argc - 1])) { | ||
| 1120 | STRING_BUILDER_RESET (sb); | ||
| 1121 | |||
| 1122 | struct string_view directory = cl.args[cl.argc - 1]; | ||
| 1123 | STRING_BUILDER_APPEND_STRING_VIEW (sb, directory); | ||
| 1124 | if (DYNAMIC_ARRAY_LAST (sb) != '/') | ||
| 1125 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1126 | |||
| 1127 | size_t directory_length = sb.length; | ||
| 1128 | for (uint32_t i = 0; i < cl.argc - 1; ++i) { | ||
| 1129 | sb.length = directory_length; | ||
| 1130 | struct string_view source = cl.args[i]; | ||
| 1131 | |||
| 1132 | struct string_view basename = string_view_basename (source); | ||
| 1133 | STRING_BUILDER_APPEND_STRING_VIEW (sb, basename); | ||
| 1134 | STRING_BUILDER_TERMINATE (sb); | ||
| 1135 | struct string_view destination = SVSB (sb); | ||
| 1136 | |||
| 1137 | if (!copy_file (source, destination)) { | ||
| 1138 | fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n", | ||
| 1139 | SVFMT (source), SVFMT (destination)); | ||
| 1140 | ret = 1; | ||
| 1141 | } | ||
| 1142 | } | ||
| 1143 | } else { | ||
| 1144 | if (cl.argc != 2) { | ||
| 1145 | fprintf (stderr, "usage: %.*s SOURCE DEST\n", SVFMT (cl.command)); | ||
| 1146 | fprintf (stderr, "or %.*s SOURCE... DIRECTORY\n", SVFMT (cl.command)); | ||
| 1147 | return 1; | ||
| 1148 | } | ||
| 1149 | |||
| 1150 | struct string_view source = cl.args[0]; | ||
| 1151 | struct string_view destination = cl.args[1]; | ||
| 1152 | if (!copy_file (source, destination)) { | ||
| 1153 | fprintf (stderr, "cp: failed to copy '%.*s' -> '%.*s'\n", | ||
| 1154 | SVFMT (source), SVFMT (destination)); | ||
| 1155 | ret = 1; | ||
| 1156 | } | ||
| 1157 | } | ||
| 1158 | |||
| 1159 | return ret; | ||
| 1160 | } | ||
| 1161 | |||
| 1162 | int | ||
| 1163 | command_rm (struct command_line cl) | ||
| 1164 | { | ||
| 1165 | if (cl.argc == 0) { | ||
| 1166 | fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); | ||
| 1167 | return 1; | ||
| 1168 | } | ||
| 1169 | |||
| 1170 | int ret = 0; | ||
| 1171 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 1172 | struct string_view file = cl.args[argind]; | ||
| 1173 | const char *filename = file.begin; | ||
| 1174 | |||
| 1175 | int conf = is_conf (file); | ||
| 1176 | if (conf && !authorize (id, file, AR_DELETE)) { | ||
| 1177 | ret = 1; | ||
| 1178 | continue; | ||
| 1179 | } | ||
| 1180 | |||
| 1181 | char *canonical = NULL; | ||
| 1182 | if (conf) { | ||
| 1183 | elevate (); | ||
| 1184 | canonical = realpath (filename, NULL); | ||
| 1185 | } | ||
| 1186 | int res = remove (filename); | ||
| 1187 | if (conf) drop (); | ||
| 1188 | if (res == -1) { | ||
| 1189 | fprintf (stderr, "%.*s: cannot remove file '%s': %s\n", | ||
| 1190 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1191 | ret = 1; | ||
| 1192 | free (canonical); | ||
| 1193 | } else if (conf) { | ||
| 1194 | assert (canonical); | ||
| 1195 | string_builder_printf (&confdata_log, "%u user %d removed file '!%s'\n", | ||
| 1196 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1197 | free (canonical); | ||
| 1198 | deleted_conf_file (file); | ||
| 1199 | } | ||
| 1200 | } | ||
| 1201 | |||
| 1202 | return ret; | ||
| 1203 | } | ||
| 1204 | |||
| 1205 | int | ||
| 1206 | command_mkdir (struct command_line cl) | ||
| 1207 | { | ||
| 1208 | static struct string_builder sb = {0}; | ||
| 1209 | |||
| 1210 | if (cl.argc == 0) { | ||
| 1211 | fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); | ||
| 1212 | return 1; | ||
| 1213 | } | ||
| 1214 | |||
| 1215 | int ret = 0; | ||
| 1216 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 1217 | struct string_view file = cl.args[argind]; | ||
| 1218 | const char *filename = file.begin; | ||
| 1219 | |||
| 1220 | bool conf = is_conf (file); | ||
| 1221 | if (conf) { | ||
| 1222 | STRING_BUILDER_RESET (sb); | ||
| 1223 | STRING_BUILDER_APPEND_STRING_VIEW (sb, string_view_dirname (canonicalize (file))); | ||
| 1224 | if (sb.string[sb.length - 1] != '/') | ||
| 1225 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1226 | if (!authorize (id, SVSB (sb), AR_WRITE)) { | ||
| 1227 | ret = 1; | ||
| 1228 | continue; | ||
| 1229 | } | ||
| 1230 | } | ||
| 1231 | |||
| 1232 | if (conf) elevate (); | ||
| 1233 | int res = mkdir (filename, S_IRUSR | S_IWUSR | S_IXUSR); | ||
| 1234 | if (conf) drop (); | ||
| 1235 | if (res == -1) { | ||
| 1236 | fprintf (stderr, "%.*s: cannot create directory '%s': %s\n", | ||
| 1237 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1238 | ret = 1; | ||
| 1239 | } else if (conf) { | ||
| 1240 | STRING_BUILDER_RESET (sb); | ||
| 1241 | STRING_BUILDER_APPEND_STRING_VIEW (sb, file); | ||
| 1242 | if (sb.string[sb.length - 1] != '/') | ||
| 1243 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1244 | created_conf_file (SVSB (sb)); | ||
| 1245 | elevate (); | ||
| 1246 | char *canonical = realpath (filename, NULL); | ||
| 1247 | drop (); | ||
| 1248 | assert (canonical); | ||
| 1249 | string_builder_printf (&confdata_log, "%u user %d created directory '!%s'\n", | ||
| 1250 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1251 | free (canonical); | ||
| 1252 | } | ||
| 1253 | } | ||
| 1254 | |||
| 1255 | return ret; | ||
| 1256 | } | ||
| 1257 | |||
| 1258 | int | ||
| 1259 | command_rmdir (struct command_line cl) | ||
| 1260 | { | ||
| 1261 | static struct string_builder sb = {0}; | ||
| 1262 | |||
| 1263 | if (cl.argc == 0) { | ||
| 1264 | fprintf (stderr, "usage: %.*s DIR...\n", SVFMT (cl.command)); | ||
| 1265 | return 1; | ||
| 1266 | } | ||
| 1267 | |||
| 1268 | int ret = 0; | ||
| 1269 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 1270 | struct string_view file = cl.args[argind]; | ||
| 1271 | const char *filename = file.begin; | ||
| 1272 | |||
| 1273 | bool conf = is_conf (file); | ||
| 1274 | if (conf) { | ||
| 1275 | STRING_BUILDER_RESET (sb); | ||
| 1276 | STRING_BUILDER_APPEND_STRING_VIEW (sb, canonicalize (file)); | ||
| 1277 | if (sb.string[sb.length - 1] != '/') | ||
| 1278 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1279 | if (!authorize (id, SVSB (sb), AR_DELETE)) { | ||
| 1280 | ret = 1; | ||
| 1281 | continue; | ||
| 1282 | } | ||
| 1283 | } | ||
| 1284 | char *canonical = NULL; | ||
| 1285 | if (conf) { | ||
| 1286 | elevate (); | ||
| 1287 | canonical = realpath (filename, NULL); | ||
| 1288 | } | ||
| 1289 | int res = rmdir (filename); | ||
| 1290 | if (conf) drop (); | ||
| 1291 | if (res == -1) { | ||
| 1292 | fprintf (stderr, "%.*s: cannot remove directory '%s': %s\n", | ||
| 1293 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1294 | ret = 1; | ||
| 1295 | free (canonical); | ||
| 1296 | } else if (conf) { | ||
| 1297 | assert (canonical); | ||
| 1298 | string_builder_printf (&confdata_log, "%u user %d removed directory '!%s'\n", | ||
| 1299 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1300 | free (canonical); | ||
| 1301 | |||
| 1302 | STRING_BUILDER_RESET (sb); | ||
| 1303 | STRING_BUILDER_APPEND_STRING_VIEW (sb, file); | ||
| 1304 | if (sb.string[sb.length - 1] != '/') | ||
| 1305 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1306 | deleted_conf_file (SVSB (sb)); | ||
| 1307 | } | ||
| 1308 | } | ||
| 1309 | |||
| 1310 | return ret; | ||
| 1311 | } | ||
| 1312 | |||
| 1313 | int | ||
| 1314 | command_cat (struct command_line cl) | ||
| 1315 | { | ||
| 1316 | int ret = 0; | ||
| 1317 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 1318 | struct string_view file = cl.args[argind]; | ||
| 1319 | bool conf = is_conf (file); | ||
| 1320 | if (conf && !authorize (id, file, AR_READ)) continue; | ||
| 1321 | |||
| 1322 | const char *filename = file.begin; | ||
| 1323 | if (conf) elevate (); | ||
| 1324 | int fd = open (filename, O_RDONLY); | ||
| 1325 | if (conf) drop (); | ||
| 1326 | if (fd == -1) { | ||
| 1327 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 1328 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1329 | ret = 1; | ||
| 1330 | continue; | ||
| 1331 | } | ||
| 1332 | |||
| 1333 | struct stat st; | ||
| 1334 | if (fstat (fd, &st) == -1) { | ||
| 1335 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 1336 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1337 | ret = 2; | ||
| 1338 | goto close; | ||
| 1339 | } | ||
| 1340 | |||
| 1341 | void *contents = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); | ||
| 1342 | if (contents == NULL) { | ||
| 1343 | ret = 3; | ||
| 1344 | goto close; | ||
| 1345 | } | ||
| 1346 | write (0, contents, st.st_size); | ||
| 1347 | |||
| 1348 | if (conf) { | ||
| 1349 | elevate (); | ||
| 1350 | char *canonical = realpath (file.begin, NULL); | ||
| 1351 | drop (); | ||
| 1352 | assert (canonical); | ||
| 1353 | string_builder_printf (&confdata_log, "%u user %d read file '!%s'\n", | ||
| 1354 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1355 | free (canonical); | ||
| 1356 | } | ||
| 1357 | |||
| 1358 | munmap (contents, st.st_size); | ||
| 1359 | close: | ||
| 1360 | close (fd); | ||
| 1361 | } | ||
| 1362 | |||
| 1363 | drop (); | ||
| 1364 | |||
| 1365 | return ret; | ||
| 1366 | } | ||
| 1367 | |||
| 1368 | int | ||
| 1369 | command_append (struct command_line cl) | ||
| 1370 | { | ||
| 1371 | static struct string_builder sb = {0}; | ||
| 1372 | |||
| 1373 | if (cl.argc != 1) { | ||
| 1374 | fprintf (stderr, "usage: %.*s FILE\n", SVFMT (cl.command)); | ||
| 1375 | return 1; | ||
| 1376 | } | ||
| 1377 | |||
| 1378 | struct string_view filename = cl.args[0]; | ||
| 1379 | |||
| 1380 | int conf = is_conf (filename); | ||
| 1381 | if (conf && !authorize (id, filename, AR_WRITE)) | ||
| 1382 | return 1; | ||
| 1383 | |||
| 1384 | STRING_BUILDER_RESET (sb); | ||
| 1385 | char *line; | ||
| 1386 | while ((line = readline ("append> ")) != NULL) { | ||
| 1387 | STRING_BUILDER_APPEND_CSTR (sb, line); | ||
| 1388 | STRING_BUILDER_APPEND_CHAR (sb, '\n'); | ||
| 1389 | free (line); | ||
| 1390 | } | ||
| 1391 | |||
| 1392 | int ret = 0; | ||
| 1393 | if (sb.length) { | ||
| 1394 | if (conf && !authorize (id, filename, AR_WRITE)) | ||
| 1395 | return 1; | ||
| 1396 | |||
| 1397 | if (conf) elevate (); | ||
| 1398 | int fd = open (filename.begin, O_WRONLY | O_CREAT | O_APPEND); | ||
| 1399 | if (conf) drop (); | ||
| 1400 | if (fd == -1) { | ||
| 1401 | fprintf (stderr, "failed to open '%.*s' for writing\n", SVFMT (filename)); | ||
| 1402 | return 1; | ||
| 1403 | } | ||
| 1404 | |||
| 1405 | write (fd, sb.string, sb.length); | ||
| 1406 | |||
| 1407 | if (conf) { | ||
| 1408 | elevate (); | ||
| 1409 | char *canonical = realpath (filename.begin, NULL); | ||
| 1410 | drop (); | ||
| 1411 | assert (canonical); | ||
| 1412 | string_builder_printf (&confdata_log, "%u user %d appended to file '!%s'\n", | ||
| 1413 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1414 | free (canonical); | ||
| 1415 | |||
| 1416 | if (conf != 2) created_conf_file (filename); | ||
| 1417 | } | ||
| 1418 | |||
| 1419 | close (fd); | ||
| 1420 | } | ||
| 1421 | |||
| 1422 | return ret; | ||
| 1423 | } | ||
| 1424 | |||
| 1425 | #define COMMAND_LS_ALIGNMENT 30 | ||
| 1426 | |||
| 1427 | int | ||
| 1428 | command_ls (struct command_line cl) | ||
| 1429 | { | ||
| 1430 | static struct string_builder sb = {0}; | ||
| 1431 | |||
| 1432 | if (cl.argc == 0) | ||
| 1433 | DYNAMIC_ARRAY_APPEND (cl, SVCSTR (".")); | ||
| 1434 | |||
| 1435 | struct passwd passwd = load_passwd_file (); | ||
| 1436 | |||
| 1437 | for (uint32_t argind = 0; argind < cl.argc; ++argind) { | ||
| 1438 | struct string_view file = cl.args[argind]; | ||
| 1439 | const char *filename = file.begin; | ||
| 1440 | |||
| 1441 | bool conf = is_conf (file); | ||
| 1442 | |||
| 1443 | if (conf) elevate (); | ||
| 1444 | int fd = open (filename, O_RDONLY); | ||
| 1445 | if (conf) drop (); | ||
| 1446 | if (fd == -1) { | ||
| 1447 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 1448 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1449 | continue; | ||
| 1450 | } | ||
| 1451 | |||
| 1452 | struct stat st; | ||
| 1453 | if (fstat (fd, &st) == -1) { | ||
| 1454 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 1455 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1456 | goto close; | ||
| 1457 | } | ||
| 1458 | |||
| 1459 | if (S_ISREG (st.st_mode)) { | ||
| 1460 | int n = printf ("%s", filename); | ||
| 1461 | if (conf) { | ||
| 1462 | while (n++ < COMMAND_LS_ALIGNMENT) | ||
| 1463 | putchar (' '); | ||
| 1464 | struct acl *acl = load_acl_for_file (file); | ||
| 1465 | |||
| 1466 | #ifdef MAC | ||
| 1467 | fputs (security_level_names[acl->security_level], stdout); | ||
| 1468 | #endif | ||
| 1469 | |||
| 1470 | struct passwd_entry *entry = lookup_id (passwd, acl->owner); | ||
| 1471 | printf (" %.*s", SVFMT (entry->login)); | ||
| 1472 | for (int i = 0; i < acl->grant_count; ++i) { | ||
| 1473 | entry = lookup_id (passwd, acl->grants[i].id); | ||
| 1474 | enum access_rights ar = acl->grants[i].access_rights; | ||
| 1475 | printf (" %.*s:%c%c%c", SVFMT (entry->login), | ||
| 1476 | ar & AR_READ ? 'r' : '-', | ||
| 1477 | ar & AR_WRITE ? 'w' : '-', | ||
| 1478 | ar & AR_DELETE ? 'd' : '-'); | ||
| 1479 | } | ||
| 1480 | free (acl); | ||
| 1481 | |||
| 1482 | elevate (); | ||
| 1483 | char *canonical = realpath (filename, NULL); | ||
| 1484 | drop (); | ||
| 1485 | ASSERT (canonical); | ||
| 1486 | string_builder_printf (&confdata_log, "%u user %d listed file '!%s'\n", | ||
| 1487 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1488 | free (canonical); | ||
| 1489 | } | ||
| 1490 | putchar ('\n'); | ||
| 1491 | goto close; | ||
| 1492 | } | ||
| 1493 | |||
| 1494 | STRING_BUILDER_RESET (sb); | ||
| 1495 | STRING_BUILDER_APPEND_STRING_VIEW (sb, canonicalize (file)); | ||
| 1496 | if (sb.string[sb.length - 1] != '/') | ||
| 1497 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1498 | if (conf && !authorize (id, SVSB (sb), AR_READ)) | ||
| 1499 | continue; | ||
| 1500 | |||
| 1501 | DIR *dir = fdopendir (fd); | ||
| 1502 | if (dir == NULL) { | ||
| 1503 | fprintf (stderr, "%.*s: cannot access '%s': %s\n", | ||
| 1504 | SVFMT (cl.command), filename, strerror (errno)); | ||
| 1505 | goto close; | ||
| 1506 | } | ||
| 1507 | |||
| 1508 | if (argind != 0) putchar ('\n'); | ||
| 1509 | int n = printf ("%s:", filename); | ||
| 1510 | if (conf) { | ||
| 1511 | STRING_BUILDER_RESET (sb); | ||
| 1512 | STRING_BUILDER_APPEND_STRING_VIEW (sb, canonicalize (file)); | ||
| 1513 | if (sb.string[sb.length - 1] != '/') | ||
| 1514 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1515 | struct acl *acl = load_acl_for_file (SVSB (sb)); | ||
| 1516 | if (acl) { | ||
| 1517 | while (n++ < COMMAND_LS_ALIGNMENT) | ||
| 1518 | putchar (' '); | ||
| 1519 | |||
| 1520 | #ifdef MAC | ||
| 1521 | fputs (security_level_names[acl->security_level], stdout); | ||
| 1522 | #endif | ||
| 1523 | |||
| 1524 | struct passwd_entry *entry = lookup_id (passwd, acl->owner); | ||
| 1525 | printf (" %.*s", SVFMT (entry->login)); | ||
| 1526 | for (int i = 0; i < acl->grant_count; ++i) { | ||
| 1527 | entry = lookup_id (passwd, acl->grants[i].id); | ||
| 1528 | enum access_rights ar = acl->grants[i].access_rights; | ||
| 1529 | printf (" %.*s:%c%c%c", SVFMT (entry->login), | ||
| 1530 | ar & AR_READ ? 'r' : '-', | ||
| 1531 | ar & AR_WRITE ? 'w' : '-', | ||
| 1532 | ar & AR_DELETE ? 'd' : '-'); | ||
| 1533 | } | ||
| 1534 | free (acl); | ||
| 1535 | } | ||
| 1536 | } | ||
| 1537 | putchar ('\n'); | ||
| 1538 | struct dirent *entry; | ||
| 1539 | while ((entry = readdir (dir)) != NULL) { | ||
| 1540 | if (strcmp (entry->d_name, ".") == 0 || | ||
| 1541 | strcmp (entry->d_name, "..") == 0) { | ||
| 1542 | continue; | ||
| 1543 | } | ||
| 1544 | |||
| 1545 | if (entry->d_type == DT_DIR) { | ||
| 1546 | n = printf ("%s/", entry->d_name); | ||
| 1547 | } else { | ||
| 1548 | n = printf ("%s", entry->d_name); | ||
| 1549 | } | ||
| 1550 | |||
| 1551 | if (conf) { | ||
| 1552 | STRING_BUILDER_RESET (sb); | ||
| 1553 | STRING_BUILDER_APPEND_STRING_VIEW (sb, file); | ||
| 1554 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1555 | STRING_BUILDER_APPEND_CSTR (sb, entry->d_name); | ||
| 1556 | if (entry->d_type == DT_DIR) | ||
| 1557 | STRING_BUILDER_APPEND_CHAR (sb, '/'); | ||
| 1558 | struct acl *acl = load_acl_for_file (SVSB (sb)); | ||
| 1559 | if (acl) { | ||
| 1560 | while (n++ < COMMAND_LS_ALIGNMENT) | ||
| 1561 | putchar (' '); | ||
| 1562 | |||
| 1563 | #ifdef MAC | ||
| 1564 | fputs (security_level_names[acl->security_level], stdout); | ||
| 1565 | #endif | ||
| 1566 | |||
| 1567 | struct passwd_entry *entry = lookup_id (passwd, acl->owner); | ||
| 1568 | printf (" %.*s", SVFMT (entry->login)); | ||
| 1569 | for (int i = 0; i < acl->grant_count; ++i) { | ||
| 1570 | entry = lookup_id (passwd, acl->grants[i].id); | ||
| 1571 | enum access_rights ar = acl->grants[i].access_rights; | ||
| 1572 | printf (" %.*s:%c%c%c", SVFMT (entry->login), | ||
| 1573 | ar & AR_READ ? 'r' : '-', | ||
| 1574 | ar & AR_WRITE ? 'w' : '-', | ||
| 1575 | ar & AR_DELETE ? 'd' : '-'); | ||
| 1576 | free (acl); | ||
| 1577 | } | ||
| 1578 | } | ||
| 1579 | } | ||
| 1580 | |||
| 1581 | putchar ('\n'); | ||
| 1582 | } | ||
| 1583 | |||
| 1584 | if (conf) { | ||
| 1585 | elevate (); | ||
| 1586 | char *canonical = realpath (filename, NULL); | ||
| 1587 | drop (); | ||
| 1588 | assert (canonical); | ||
| 1589 | string_builder_printf (&confdata_log, "%u user %d listed directory '!%s'\n", | ||
| 1590 | time (NULL), id, canonical + strlen (CONFDATA)); | ||
| 1591 | free (canonical); | ||
| 1592 | } | ||
| 1593 | |||
| 1594 | closedir (dir); | ||
| 1595 | close: | ||
| 1596 | close (fd); | ||
| 1597 | } | ||
| 1598 | |||
| 1599 | close_passwd_file (passwd); | ||
| 1600 | |||
| 1601 | return 0; | ||
| 1602 | } | ||
| 1603 | |||
| 1604 | const char * | ||
| 1605 | prompt (int ret) | ||
| 1606 | { | ||
| 1607 | static struct string_builder sb = {0}; | ||
| 1608 | |||
| 1609 | STRING_BUILDER_RESET (sb); | ||
| 1610 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m[\e[34m"); | ||
| 1611 | |||
| 1612 | struct passwd passwd = load_passwd_file (); | ||
| 1613 | struct passwd_entry *entry = lookup_id (passwd, id); | ||
| 1614 | if (entry) { | ||
| 1615 | STRING_BUILDER_APPEND_STRING_VIEW (sb, entry->login); | ||
| 1616 | |||
| 1617 | #ifdef MAC | ||
| 1618 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m@"); | ||
| 1619 | STRING_BUILDER_APPEND_CSTR (sb, entry->security_level == SL_COUNT - 1 | ||
| 1620 | ? "\e[34m" | ||
| 1621 | : "\e[31m"); | ||
| 1622 | STRING_BUILDER_APPEND_CSTR (sb, security_level_names[entry->security_level]); | ||
| 1623 | #endif | ||
| 1624 | } else STRING_BUILDER_APPEND_CHAR (sb, '?'); | ||
| 1625 | close_passwd_file (passwd); | ||
| 1626 | |||
| 1627 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m:\e[34m"); | ||
| 1628 | struct string_view canonical = canonicalize (SVCSTR (".")); | ||
| 1629 | if (strncmp (canonical.begin, CONFDATA, strlen (CONFDATA)) == 0) { | ||
| 1630 | STRING_BUILDER_APPEND_CHAR (sb, '!'); | ||
| 1631 | canonical.begin += strlen (CONFDATA); | ||
| 1632 | } STRING_BUILDER_APPEND_STRING_VIEW (sb, canonical); | ||
| 1633 | |||
| 1634 | STRING_BUILDER_APPEND_CSTR (sb, "\e[36m]\e[34m"); | ||
| 1635 | |||
| 1636 | if (ret) string_builder_printf (&sb, " \e[31m%d", ret); | ||
| 1637 | |||
| 1638 | STRING_BUILDER_APPEND_CSTR (sb, ruid == euid ? " \e[31m#" : " \e[95m$"); | ||
| 1639 | STRING_BUILDER_APPEND_CSTR (sb, "\e[0m "); | ||
| 1640 | STRING_BUILDER_TERMINATE (sb); | ||
| 1641 | |||
| 1642 | return sb.string; | ||
| 1643 | } | ||
| 1644 | |||
| 1645 | int | ||
| 1646 | main (int argc, char *argv[]) | ||
| 1647 | { | ||
| 1648 | ruid = getuid (); | ||
| 1649 | rgid = getgid (); | ||
| 1650 | euid = geteuid (); | ||
| 1651 | egid = getegid (); | ||
| 1652 | drop (); | ||
| 1653 | |||
| 1654 | static struct option longopts[] = { | ||
| 1655 | { "help", no_argument, NULL, 'h' }, | ||
| 1656 | { "password", required_argument, NULL, 'p' }, | ||
| 1657 | {0} | ||
| 1658 | }; | ||
| 1659 | char ch; | ||
| 1660 | struct string_view password = {0}; | ||
| 1661 | while ((ch = getopt_long (argc, argv, ":hp:", longopts, NULL)) != -1) { | ||
| 1662 | switch (ch) { | ||
| 1663 | case 'h': | ||
| 1664 | printf ("Usage: %s [options] [LOGIN]\n", argv[0]); | ||
| 1665 | puts (""); | ||
| 1666 | puts ("Options:"); | ||
| 1667 | puts (" -h, --help display this help message and exit"); | ||
| 1668 | puts (" -p, --password PASSWORD password of the account (only if login was provided)"); | ||
| 1669 | puts (""); | ||
| 1670 | exit (0); | ||
| 1671 | case 'p': password = SVCSTR (optarg); break; | ||
| 1672 | case '?': DIE ("unknown option %s", argv[optind - 1]); | ||
| 1673 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 1674 | default: DIE ("unexpected opt error"); | ||
| 1675 | } | ||
| 1676 | } | ||
| 1677 | |||
| 1678 | struct passwd passwd = load_passwd_file (); | ||
| 1679 | struct passwd_entry *entry = NULL; | ||
| 1680 | if (argv[optind] != NULL) { | ||
| 1681 | if (argv[optind + 1] != NULL) | ||
| 1682 | DIE ("extra trailing arguments starting with: %s", argv[optind + 1]); | ||
| 1683 | |||
| 1684 | struct string_view login = SVCSTR (argv[optind]); | ||
| 1685 | if (ruid == 0) { | ||
| 1686 | entry = lookup_login (passwd, login); | ||
| 1687 | append_passwd_log (); | ||
| 1688 | if (!entry) { | ||
| 1689 | DIE ("user %.*s doesn't exist", SVFMT (login)); | ||
| 1690 | } | ||
| 1691 | } else { | ||
| 1692 | if (password.begin == NULL) { | ||
| 1693 | fputs ("Password: ", stdout); | ||
| 1694 | password = read_password (); | ||
| 1695 | } | ||
| 1696 | entry = authenticate (passwd, login, password); | ||
| 1697 | append_passwd_log (); | ||
| 1698 | if (entry == NULL) exit (1); | ||
| 1699 | } | ||
| 1700 | } else { | ||
| 1701 | do { | ||
| 1702 | fputs ("Login: ", stdout); fflush (stdout); | ||
| 1703 | struct string_view login = read_login (); | ||
| 1704 | fputs ("Password: ", stdout); fflush (stdout); | ||
| 1705 | struct string_view password = read_password (); | ||
| 1706 | entry = authenticate (passwd, login, password); | ||
| 1707 | } while (entry == NULL); | ||
| 1708 | } | ||
| 1709 | |||
| 1710 | id = entry->id; | ||
| 1711 | printf ("Hello, %.*s! (%d)\n", SVFMT (entry->comment), id); | ||
| 1712 | close_passwd_file (passwd); | ||
| 1713 | printf ("Run 'help', to get a list of available commands.\n"); | ||
| 1714 | |||
| 1715 | struct command_line cl = {0}; | ||
| 1716 | int ret = 0; | ||
| 1717 | for (;;) { | ||
| 1718 | char *line = readline (prompt (ret)); | ||
| 1719 | if (line == NULL) break; | ||
| 1720 | add_history (line); | ||
| 1721 | switch (parse_command_line (&cl, SVCSTR (line))) { | ||
| 1722 | case 1: | ||
| 1723 | if (SVCMP (cl.command, SVCSTR ("exit" )) == 0) ret = command_exit (cl); | ||
| 1724 | else if (SVCMP (cl.command, SVCSTR ("help" )) == 0) ret = command_help (cl); | ||
| 1725 | else if (SVCMP (cl.command, SVCSTR ("su" )) == 0) ret = command_su (cl); | ||
| 1726 | else if (SVCMP (cl.command, SVCSTR ("pwd" )) == 0) ret = command_pwd (cl); | ||
| 1727 | else if (SVCMP (cl.command, SVCSTR ("whoami")) == 0) ret = command_whoami (cl); | ||
| 1728 | else if (SVCMP (cl.command, SVCSTR ("echo" )) == 0) ret = command_echo (cl); | ||
| 1729 | else if (SVCMP (cl.command, SVCSTR ("ls" )) == 0) ret = command_ls (cl); | ||
| 1730 | else if (SVCMP (cl.command, SVCSTR ("cd" )) == 0) ret = command_cd (cl); | ||
| 1731 | else if (SVCMP (cl.command, SVCSTR ("mv" )) == 0) ret = command_mv (cl); | ||
| 1732 | else if (SVCMP (cl.command, SVCSTR ("cp" )) == 0) ret = command_cp (cl); | ||
| 1733 | else if (SVCMP (cl.command, SVCSTR ("rm" )) == 0) ret = command_rm (cl); | ||
| 1734 | else if (SVCMP (cl.command, SVCSTR ("mkdir" )) == 0) ret = command_mkdir (cl); | ||
| 1735 | else if (SVCMP (cl.command, SVCSTR ("rmdir" )) == 0) ret = command_rmdir (cl); | ||
| 1736 | else if (SVCMP (cl.command, SVCSTR ("cat" )) == 0) ret = command_cat (cl); | ||
| 1737 | else if (SVCMP (cl.command, SVCSTR ("read" )) == 0) ret = command_cat (cl); | ||
| 1738 | else if (SVCMP (cl.command, SVCSTR ("copy" )) == 0) ret = command_cp (cl); | ||
| 1739 | else if (SVCMP (cl.command, SVCSTR ("remove")) == 0) ret = command_rm (cl); | ||
| 1740 | else if (SVCMP (cl.command, SVCSTR ("append")) == 0) ret = command_append (cl); | ||
| 1741 | else if (SVCMP (cl.command, SVCSTR ("chown" )) == 0) ret = command_chown (cl); | ||
| 1742 | else if (SVCMP (cl.command, SVCSTR ("chsl" )) == 0) ret = command_chsl (cl); | ||
| 1743 | else if (SVCMP (cl.command, SVCSTR ("grant" )) == 0) ret = command_grant (cl); | ||
| 1744 | else if (SVCMP (cl.command, SVCSTR ("revoke")) == 0) ret = command_revoke (cl); | ||
| 1745 | else puts ("unknown command, run `help' to get the list of available commands"); | ||
| 1746 | break; | ||
| 1747 | case 0: break; | ||
| 1748 | case -1: | ||
| 1749 | putchar ('\n'); | ||
| 1750 | exit (0); | ||
| 1751 | default: | ||
| 1752 | fputs ("invalid command line", stderr); | ||
| 1753 | break; | ||
| 1754 | } free (line); | ||
| 1755 | append_passwd_log (); | ||
| 1756 | flush_confdata_log (); | ||
| 1757 | } putchar ('\n'); | ||
| 1758 | |||
| 1759 | return EXIT_SUCCESS; | ||
| 1760 | } | ||
| 1761 | |||
| 1762 | // src/shell.c ends here | ||
diff --git a/03/src/string-builder.c b/03/src/string-builder.c new file mode 100644 index 0000000..99d066c --- /dev/null +++ b/03/src/string-builder.c | |||
| @@ -0,0 +1,60 @@ | |||
| 1 | #include "string-builder.h" | ||
| 2 | #include <stdarg.h> | ||
| 3 | #include <stdio.h> | ||
| 4 | |||
| 5 | void | ||
| 6 | string_builder_append_ntimes (STRING_BUILDER sb, char c, size_t n) | ||
| 7 | { | ||
| 8 | DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, n); | ||
| 9 | memset (sb->items + sb->count, c, n); | ||
| 10 | sb->count += n; | ||
| 11 | } | ||
| 12 | |||
| 13 | void | ||
| 14 | string_builder_append_cstrs (STRING_BUILDER sb, ...) | ||
| 15 | { | ||
| 16 | va_list args; | ||
| 17 | |||
| 18 | va_start (args, sb); | ||
| 19 | const char *arg = va_arg (args, const char *); | ||
| 20 | while (arg) { | ||
| 21 | STRING_BUILDER_APPEND_CSTR(*sb, arg); | ||
| 22 | arg = va_arg (args, const char *); | ||
| 23 | } va_end (args); | ||
| 24 | } | ||
| 25 | |||
| 26 | void | ||
| 27 | string_builder_printf (STRING_BUILDER sb, const char *format, ...) | ||
| 28 | { | ||
| 29 | va_list args; | ||
| 30 | |||
| 31 | va_start (args, format); | ||
| 32 | int size = vsnprintf (NULL, 0, format, args); | ||
| 33 | va_end (args); | ||
| 34 | ASSERT (size >= 0); | ||
| 35 | |||
| 36 | DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, size + 1); | ||
| 37 | va_start (args, format); | ||
| 38 | vsnprintf (&sb->items[sb->count], size + 1, format, args); | ||
| 39 | va_end (args); | ||
| 40 | sb->count += size; | ||
| 41 | } | ||
| 42 | |||
| 43 | bool | ||
| 44 | string_builder_getline (STRING_BUILDER sb) | ||
| 45 | { | ||
| 46 | for (;;) { | ||
| 47 | int c = getchar (); | ||
| 48 | |||
| 49 | if (c == EOF) { | ||
| 50 | clearerr (stdin); | ||
| 51 | return false; | ||
| 52 | } | ||
| 53 | if (c == '\n') | ||
| 54 | break; | ||
| 55 | |||
| 56 | STRING_BUILDER_APPEND_CHAR (*sb, c); | ||
| 57 | } | ||
| 58 | |||
| 59 | return true; | ||
| 60 | } | ||
diff --git a/03/src/string-builder.h b/03/src/string-builder.h new file mode 100644 index 0000000..6cc6307 --- /dev/null +++ b/03/src/string-builder.h | |||
| @@ -0,0 +1,56 @@ | |||
| 1 | #ifndef INCLUDED_STRING_BUILDER_H | ||
| 2 | #define INCLUDED_STRING_BUILDER_H | ||
| 3 | |||
| 4 | #include <stddef.h> | ||
| 5 | #include <string.h> | ||
| 6 | #include <stdbool.h> | ||
| 7 | #include "dynamic-array.h" | ||
| 8 | |||
| 9 | struct string_builder { | ||
| 10 | union { char *items, *string; }; | ||
| 11 | union { size_t count, length; }; | ||
| 12 | size_t capacity; | ||
| 13 | }; | ||
| 14 | #define STRING_BUILDER struct string_builder * | ||
| 15 | |||
| 16 | #define SBFMT(SB) (int) (SB).length, (SB).string | ||
| 17 | |||
| 18 | #define STRING_BUILDER_APPEND_CHAR(SB, CHAR) \ | ||
| 19 | DYNAMIC_ARRAY_APPEND ((SB), (char) (CHAR)) | ||
| 20 | |||
| 21 | #define STRING_BUILDER_APPEND_BUF(SB, BUF, SIZE) \ | ||
| 22 | DYNAMIC_ARRAY_APPEND_MANY (SB, BUF, SIZE) | ||
| 23 | |||
| 24 | #define STRING_BUILDER_APPEND_CSTR(SB, CSTR) \ | ||
| 25 | ({ \ | ||
| 26 | const char *s = (CSTR); \ | ||
| 27 | size_t n = strlen (s); \ | ||
| 28 | DYNAMIC_ARRAY_APPEND_MANY(SB, s, n); \ | ||
| 29 | }) | ||
| 30 | |||
| 31 | #define STRING_BUILDER_APPEND_CSTRS(SB, ...) \ | ||
| 32 | string_builder_append_cstrs (&(SB), __VA_ARGS__, NULL) | ||
| 33 | |||
| 34 | #define STRING_BUILDER_APPEND_STRING_VIEW(SB, SV) \ | ||
| 35 | DYNAMIC_ARRAY_APPEND_MANY(SB, (SV).begin, SVLEN (SV)); | ||
| 36 | |||
| 37 | #define STRING_BUILDER_APPEND_NULL(SB) \ | ||
| 38 | STRING_BUILDER_APPEND_CHAR (SB, '\0'); | ||
| 39 | |||
| 40 | #define STRING_BUILDER_TERMINATE(SB) ({ \ | ||
| 41 | DYNAMIC_ARRAY_ENSURE_CAPACITY (SB, 1); \ | ||
| 42 | (SB).string[(SB).length] = '\0'; \ | ||
| 43 | }) | ||
| 44 | |||
| 45 | #define STRING_BUILDER_RESET(SB) \ | ||
| 46 | DYNAMIC_ARRAY_RESET (SB) | ||
| 47 | |||
| 48 | #define STRING_BUILDER_FREE(SB) \ | ||
| 49 | DYNAMIC_ARRAY_FREE(SB) | ||
| 50 | |||
| 51 | void string_builder_append_ntimes (STRING_BUILDER, char c, size_t n); | ||
| 52 | void string_builder_append_cstrs (STRING_BUILDER, ...); | ||
| 53 | void string_builder_printf (STRING_BUILDER, const char *format, ...); | ||
| 54 | bool string_builder_getline (STRING_BUILDER); | ||
| 55 | |||
| 56 | #endif | ||
diff --git a/03/src/string-view.c b/03/src/string-view.c new file mode 100644 index 0000000..ef84f69 --- /dev/null +++ b/03/src/string-view.c | |||
| @@ -0,0 +1,147 @@ | |||
| 1 | #include "string-view.h" | ||
| 2 | #include <string.h> | ||
| 3 | #include <stdlib.h> | ||
| 4 | |||
| 5 | size_t | ||
| 6 | string_view_length (struct string_view sv) | ||
| 7 | { | ||
| 8 | return sv.end - sv.begin; | ||
| 9 | } | ||
| 10 | |||
| 11 | struct string_view | ||
| 12 | string_view_from_cstr (const char *cstr) | ||
| 13 | { | ||
| 14 | return (struct string_view) { | ||
| 15 | .begin = cstr, | ||
| 16 | .end = cstr + strlen (cstr), | ||
| 17 | }; | ||
| 18 | } | ||
| 19 | |||
| 20 | struct string_view | ||
| 21 | duplicate_string_view (struct string_view sv) | ||
| 22 | { | ||
| 23 | size_t len = SVLEN (sv); | ||
| 24 | |||
| 25 | struct string_view result = { | ||
| 26 | .begin = malloc (len), | ||
| 27 | }; | ||
| 28 | result.end = result.begin + len; | ||
| 29 | |||
| 30 | memcpy ((void *) result.begin, sv.begin, len); | ||
| 31 | |||
| 32 | return result; | ||
| 33 | } | ||
| 34 | |||
| 35 | struct string_view | ||
| 36 | duplicate_string_view_as_cstr (struct string_view sv) | ||
| 37 | { | ||
| 38 | size_t len = SVLEN (sv); | ||
| 39 | |||
| 40 | struct string_view result = { | ||
| 41 | .begin = malloc (len + 1), | ||
| 42 | }; | ||
| 43 | result.end = result.begin + len; | ||
| 44 | |||
| 45 | memcpy ((void *) result.begin, sv.begin, len); | ||
| 46 | ((char *) result.begin)[len] = '\0'; | ||
| 47 | |||
| 48 | return result; | ||
| 49 | } | ||
| 50 | |||
| 51 | struct string_view | ||
| 52 | string_view_strdup (const char *cstr) | ||
| 53 | { | ||
| 54 | struct string_view sv; | ||
| 55 | size_t len = strlen (cstr); | ||
| 56 | sv.begin = malloc (len + 1), | ||
| 57 | sv.end = sv.begin + len; | ||
| 58 | |||
| 59 | memcpy ((void *) sv.begin, cstr, len); | ||
| 60 | ((char *) sv.begin)[len] = '\0'; | ||
| 61 | |||
| 62 | return sv; | ||
| 63 | } | ||
| 64 | |||
| 65 | int | ||
| 66 | string_view_compare (struct string_view lhs, struct string_view rhs) | ||
| 67 | { | ||
| 68 | if (SVLEN (lhs) != SVLEN (rhs)) | ||
| 69 | return SVLEN (lhs) - SVLEN (rhs); | ||
| 70 | |||
| 71 | return memcmp (lhs.begin, rhs.begin, SVLEN (lhs)); | ||
| 72 | } | ||
| 73 | |||
| 74 | bool | ||
| 75 | string_view_starts_with (struct string_view sv, struct string_view prefix) | ||
| 76 | { | ||
| 77 | if (SVLEN (sv) < SVLEN (prefix)) | ||
| 78 | return false; | ||
| 79 | |||
| 80 | return memcmp (sv.begin, prefix.begin, SVLEN (prefix)) == 0; | ||
| 81 | } | ||
| 82 | |||
| 83 | struct string_view | ||
| 84 | string_view_dirname (struct string_view sv) | ||
| 85 | { | ||
| 86 | while (sv.end != sv.begin && sv.end[-1] == '/') | ||
| 87 | sv.end -= 1; | ||
| 88 | |||
| 89 | while (sv.end != sv.begin && sv.end[-1] != '/') | ||
| 90 | sv.end -= 1; | ||
| 91 | |||
| 92 | while (sv.end != sv.begin && sv.end[-1] == '/') | ||
| 93 | sv.end -= 1; | ||
| 94 | |||
| 95 | if (sv.end == sv.begin) | ||
| 96 | return SVCSTR ("."); | ||
| 97 | |||
| 98 | return sv; | ||
| 99 | } | ||
| 100 | |||
| 101 | struct string_view | ||
| 102 | string_view_basename (struct string_view sv) | ||
| 103 | { | ||
| 104 | const char *head = sv.end; | ||
| 105 | |||
| 106 | while (head > sv.begin && head[-1] == '/') | ||
| 107 | head -= 1; | ||
| 108 | |||
| 109 | while (head > sv.begin && head[-1] != '/') | ||
| 110 | head -= 1; | ||
| 111 | |||
| 112 | if (head != sv.begin) | ||
| 113 | sv.begin = head; | ||
| 114 | |||
| 115 | return sv; | ||
| 116 | } | ||
| 117 | |||
| 118 | // pops all if c was not found | ||
| 119 | struct string_view | ||
| 120 | string_view_pop_up_to (struct string_view *sv, char c) | ||
| 121 | { | ||
| 122 | const char *head = sv->begin; | ||
| 123 | |||
| 124 | while (head < sv->end && *head != c) | ||
| 125 | head += 1; | ||
| 126 | |||
| 127 | struct string_view result = { .begin = sv->begin }; | ||
| 128 | result.end = sv->begin = head; | ||
| 129 | |||
| 130 | return result; | ||
| 131 | } | ||
| 132 | |||
| 133 | struct string_view | ||
| 134 | string_view_pop_n (struct string_view *sv, size_t n) | ||
| 135 | { | ||
| 136 | struct string_view result = { | ||
| 137 | .begin = sv->begin, | ||
| 138 | .end = sv->begin + n, | ||
| 139 | }; | ||
| 140 | |||
| 141 | if (result.end > sv->end) | ||
| 142 | result.end = sv->end; | ||
| 143 | |||
| 144 | sv->begin = result.end; | ||
| 145 | |||
| 146 | return result; | ||
| 147 | } | ||
diff --git a/03/src/string-view.h b/03/src/string-view.h new file mode 100644 index 0000000..fa42d77 --- /dev/null +++ b/03/src/string-view.h | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | // src/string-view.h | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_STRING_VIEW_H | ||
| 12 | #define INCLUDED_STRING_VIEW_H | ||
| 13 | |||
| 14 | #include <stddef.h> | ||
| 15 | #include <stdbool.h> | ||
| 16 | |||
| 17 | struct string_view { | ||
| 18 | const char *begin; | ||
| 19 | const char *end; | ||
| 20 | }; | ||
| 21 | |||
| 22 | #define SVNULL ((struct string_view) {0}) | ||
| 23 | #define SVLEN string_view_length | ||
| 24 | #define SVFMT(SV) (int) SVLEN (SV), (SV).begin | ||
| 25 | #define SVCSTR string_view_from_cstr | ||
| 26 | #define SVDUP duplicate_string_view | ||
| 27 | #define SVDUP0 duplicate_string_view_as_cstr | ||
| 28 | #define SVSTRDUP string_view_strdup | ||
| 29 | #define SVCMP string_view_compare | ||
| 30 | #define SVSB(SB) ((struct string_view) { (SB).string, (SB).string + (SB).length }) | ||
| 31 | |||
| 32 | size_t string_view_length (struct string_view sv); | ||
| 33 | struct string_view string_view_from_cstr (const char *cstr); | ||
| 34 | struct string_view duplicate_string_view (struct string_view sv); | ||
| 35 | struct string_view duplicate_string_view_as_cstr (struct string_view sv); | ||
| 36 | struct string_view string_view_strdup (const char *cstr); | ||
| 37 | int string_view_compare (struct string_view lhs, struct string_view rhs); | ||
| 38 | bool string_view_starts_with (struct string_view sv, struct string_view prefix); | ||
| 39 | struct string_view string_view_dirname (struct string_view); | ||
| 40 | struct string_view string_view_basename (struct string_view); | ||
| 41 | struct string_view string_view_pop_up_to (struct string_view *, char); | ||
| 42 | struct string_view string_view_pop_n (struct string_view *, size_t n); | ||
| 43 | |||
| 44 | #endif // INCLUDED_STRING_VIEW_H | ||
| 45 | |||
| 46 | // src/string-view.h ends here | ||
diff --git a/04/nftables.conf b/04/nftables.conf new file mode 100755 index 0000000..04c30b6 --- /dev/null +++ b/04/nftables.conf | |||
| @@ -0,0 +1,28 @@ | |||
| 1 | #!/usr/bin/nft -f | ||
| 2 | |||
| 3 | flush ruleset | ||
| 4 | |||
| 5 | table inet filter { | ||
| 6 | chain input { | ||
| 7 | type filter hook input priority 0; | ||
| 8 | policy drop; | ||
| 9 | |||
| 10 | iif "lo" counter accept | ||
| 11 | ct state established,related counter accept | ||
| 12 | ip saddr 172.27.203.254 ip protocol icmp icmp type echo-request counter accept | ||
| 13 | } | ||
| 14 | |||
| 15 | chain output { | ||
| 16 | type filter hook output priority 0; | ||
| 17 | policy drop; | ||
| 18 | |||
| 19 | oif "lo" counter accept | ||
| 20 | ct state established,related counter accept | ||
| 21 | udp dport 53 counter accept | ||
| 22 | tcp dport 53 counter accept | ||
| 23 | tcp dport 853 counter accept # DNS over TLS | ||
| 24 | ip protocol icmp icmp type echo-request counter accept | ||
| 25 | tcp dport 80 counter accept | ||
| 26 | tcp dport 443 counter accept | ||
| 27 | } | ||
| 28 | } | ||
diff --git a/05/.gitignore b/05/.gitignore new file mode 100644 index 0000000..3d33a15 --- /dev/null +++ b/05/.gitignore | |||
| @@ -0,0 +1,2 @@ | |||
| 1 | /client | ||
| 2 | /server | ||
diff --git a/05/build.sh b/05/build.sh new file mode 100755 index 0000000..db75cb9 --- /dev/null +++ b/05/build.sh | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | ## build.sh | ||
| 3 | # | ||
| 4 | # Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 5 | # | ||
| 6 | # SPDX-License-Identifier: MIT | ||
| 7 | # | ||
| 8 | ## Commentary: | ||
| 9 | # | ||
| 10 | ## Code: | ||
| 11 | |||
| 12 | ROOT="$(dirname "$0")" | ||
| 13 | |||
| 14 | CC=cc | ||
| 15 | |||
| 16 | CFLAGS="$CFLAGS -std=gnu99" | ||
| 17 | CFLAGS="$CFLAGS -ggdb3" | ||
| 18 | # CFLAGS="$CFLAGS -O3 -march=native" | ||
| 19 | # CFLAGS="$CFLAGS -DNDEBUG" | ||
| 20 | CFLAGS="$CFLAGS -Wall -Wextra" | ||
| 21 | CFLAGS="$CFLAGS -Wno-unused-function" | ||
| 22 | CFLAGS="$CFLAGS -Wno-unused-variable" | ||
| 23 | CFLAGS="$CFLAGS -Wno-unused-parameter" | ||
| 24 | CFLAGS="$CFLAGS -Wno-unused-but-set-variable" | ||
| 25 | CFLAGS="$CFLAGS -Wno-parentheses" | ||
| 26 | CFLAGS="$CFLAGS -Wno-unused-label" | ||
| 27 | CFLAGS="$CFLAGS -Wno-comment" | ||
| 28 | CFLAGS="$CFLAGS -Wno-stringop-overflow" | ||
| 29 | CFLAGS="$CFLAGS -I$ROOT/src/" | ||
| 30 | |||
| 31 | set -xeu | ||
| 32 | |||
| 33 | $CC $CFLAGS -o $ROOT/src/crypto.o -c \ | ||
| 34 | $ROOT/src/crypto.c | ||
| 35 | $CC $CFLAGS -o $ROOT/src/common.o -c \ | ||
| 36 | $ROOT/src/common.c | ||
| 37 | |||
| 38 | $CC $CFLAGS -lcrypto -o $ROOT/server \ | ||
| 39 | $ROOT/src/crypto.o \ | ||
| 40 | $ROOT/src/common.o \ | ||
| 41 | $ROOT/src/server.c | ||
| 42 | |||
| 43 | $CC $CFLAGS -lcrypto -lncurses -o $ROOT/client \ | ||
| 44 | $ROOT/src/crypto.o \ | ||
| 45 | $ROOT/src/common.o \ | ||
| 46 | $ROOT/src/client.c | ||
diff --git a/05/genkey.sh b/05/genkey.sh new file mode 100755 index 0000000..83ad3bb --- /dev/null +++ b/05/genkey.sh | |||
| @@ -0,0 +1,18 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | ## genkey.sh --- generate pseudo-random AES-256 key | ||
| 3 | # | ||
| 4 | # Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 5 | # | ||
| 6 | # SPDX-License-Identifier: MIT | ||
| 7 | # | ||
| 8 | ## Commentary: | ||
| 9 | # | ||
| 10 | ## Code: | ||
| 11 | |||
| 12 | set -xeu | ||
| 13 | |||
| 14 | umask 077 | ||
| 15 | |||
| 16 | openssl rand -hex 32 > aes-256.key | ||
| 17 | |||
| 18 | # genkey.sh ends here | ||
diff --git a/05/src/client.c b/05/src/client.c new file mode 100644 index 0000000..ca3e368 --- /dev/null +++ b/05/src/client.c | |||
| @@ -0,0 +1,684 @@ | |||
| 1 | // client.c --- client component | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <stdlib.h> | ||
| 12 | #include <stdbool.h> | ||
| 13 | #include <stdio.h> | ||
| 14 | #include <string.h> | ||
| 15 | #include <errno.h> | ||
| 16 | #include <ctype.h> | ||
| 17 | #include <getopt.h> | ||
| 18 | #include <unistd.h> | ||
| 19 | #include <fcntl.h> | ||
| 20 | #include <ncurses.h> | ||
| 21 | #include <sys/epoll.h> | ||
| 22 | #include <netinet/in.h> | ||
| 23 | #include <arpa/inet.h> | ||
| 24 | |||
| 25 | #define LOG(PRIORITY, FMT, ...) \ | ||
| 26 | fprintf (stderr, FMT "\n" __VA_OPT__ (,) __VA_ARGS__) | ||
| 27 | |||
| 28 | #include "utils.h" | ||
| 29 | #include "common.h" | ||
| 30 | #include "dynamic-array.h" | ||
| 31 | #include "crypto.h" | ||
| 32 | |||
| 33 | static bool should_stop = false; | ||
| 34 | |||
| 35 | static bool salt = false; | ||
| 36 | static bool check_integrity = false; | ||
| 37 | static bool bad_line = false; | ||
| 38 | static char *key_filename = NULL; | ||
| 39 | static enum key_kind key_kind = KK_PSK; | ||
| 40 | static aes_256_key key; | ||
| 41 | |||
| 42 | static int epoll_fd; | ||
| 43 | static int server; | ||
| 44 | |||
| 45 | enum color { | ||
| 46 | COLOR_NORMAL, | ||
| 47 | COLOR_WARNING, | ||
| 48 | COLOR_ERROR, | ||
| 49 | }; | ||
| 50 | |||
| 51 | struct history_item { | ||
| 52 | char *message; | ||
| 53 | short color_pair; | ||
| 54 | }; | ||
| 55 | |||
| 56 | static struct history { | ||
| 57 | struct history_item *items; | ||
| 58 | int count; | ||
| 59 | int capacity; | ||
| 60 | } history = {0}; | ||
| 61 | |||
| 62 | static struct kill_ring { | ||
| 63 | char *items; | ||
| 64 | int count; | ||
| 65 | int capacity; | ||
| 66 | bool active; | ||
| 67 | bool killed; | ||
| 68 | } kill_ring = {0}; | ||
| 69 | |||
| 70 | void | ||
| 71 | usage (FILE *stream, const char *progname) | ||
| 72 | { | ||
| 73 | fprintf (stream, "Usage: %s [options] ADDR PORT\n", progname); | ||
| 74 | fprintf (stream, "\n"); | ||
| 75 | fprintf (stream, "Options:\n"); | ||
| 76 | fprintf (stream, " -h, --help display this help message and exit\n"); | ||
| 77 | fprintf (stream, " -l, --login LOGIN use LOGIN instead of system login\n"); | ||
| 78 | fprintf (stream, " -p, --plain don't use encryption*\n"); | ||
| 79 | fprintf (stream, " -k, --key FILENAME load symmetric key from FILENAME*\n"); | ||
| 80 | fprintf (stream, " -s, --salt add salt to encrypted messages*\n"); | ||
| 81 | fprintf (stream, " -x, --key-exchange use Diffi-Hellman key exchange*\n"); | ||
| 82 | fprintf (stream, " -c, --check-integrity use message integrity checking*\n"); | ||
| 83 | fprintf (stream, " -b, --bad-line sometimes send message with wrong hash\n"); | ||
| 84 | fprintf (stream, "\n"); | ||
| 85 | fprintf (stream, "Notes:\n"); | ||
| 86 | fprintf (stream, " Options marked with (*) must match the ones use by the server!\n"); | ||
| 87 | fprintf (stream, "\n"); | ||
| 88 | } | ||
| 89 | |||
| 90 | void | ||
| 91 | send_plain (struct memory_view mv) | ||
| 92 | { | ||
| 93 | uint8_t buffer[MAX_PACKET_SIZE]; | ||
| 94 | memcpy (buffer, mv.data, mv.size); | ||
| 95 | size_t size = mv.size; | ||
| 96 | if (check_integrity) { | ||
| 97 | uint8_t hash[SHA_DIGEST_SIZE]; | ||
| 98 | sha1_hash (hash, mv); | ||
| 99 | if (bad_line) { | ||
| 100 | for (int i = 0; i < SHA_DIGEST_SIZE; ++i) | ||
| 101 | hash[i] += i; | ||
| 102 | } | ||
| 103 | memcpy (&buffer[size], hash, sizeof (hash)); | ||
| 104 | size += sizeof (hash); | ||
| 105 | } | ||
| 106 | |||
| 107 | again: | ||
| 108 | ssize_t bytes_written = write (server, buffer, size); | ||
| 109 | if (bytes_written == -1) { | ||
| 110 | switch (errno) { | ||
| 111 | case EAGAIN: goto again; | ||
| 112 | default: ERROR ("write: %s", strerror (errno)); | ||
| 113 | } | ||
| 114 | } | ||
| 115 | |||
| 116 | if (bytes_written == 0) { | ||
| 117 | endwin (); | ||
| 118 | DIE ("Connection to server lost while sending message!"); | ||
| 119 | } | ||
| 120 | |||
| 121 | if ((size_t) bytes_written != size) { | ||
| 122 | endwin (); | ||
| 123 | DIE ("Failed to write whole buffer"); | ||
| 124 | } | ||
| 125 | } | ||
| 126 | |||
| 127 | void | ||
| 128 | send_encrypted (struct memory_view msg_mv) | ||
| 129 | { | ||
| 130 | static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; | ||
| 131 | struct packet *packet = (void *) buffer; | ||
| 132 | struct memory_span packet_ms = { | ||
| 133 | .data = packet->data, | ||
| 134 | .size = MAX_PACKET_SIZE, | ||
| 135 | }; | ||
| 136 | ssize_t size = aes_256_cbc_encrypt (packet_ms, msg_mv, key, salt); | ||
| 137 | if (size == -1) { | ||
| 138 | endwin (); | ||
| 139 | DIE ("Failed to decrypt message"); | ||
| 140 | } | ||
| 141 | packet->size = size; | ||
| 142 | |||
| 143 | struct memory_view packet_mv = { | ||
| 144 | .data = (void *) packet, | ||
| 145 | .size = sizeof (packet->size) + packet->size, | ||
| 146 | }; | ||
| 147 | return send_plain (packet_mv); | ||
| 148 | } | ||
| 149 | |||
| 150 | void | ||
| 151 | send_message (const struct message *msg) | ||
| 152 | { | ||
| 153 | struct history_item item = { | ||
| 154 | .message = malloc (msg->length + 1), | ||
| 155 | }; | ||
| 156 | memcpy (item.message, msg->data, msg->length); | ||
| 157 | item.message[(int) msg->length] = '\0'; | ||
| 158 | DYNAMIC_ARRAY_APPEND (history, item); | ||
| 159 | |||
| 160 | if (key_kind == KK_NONE) { | ||
| 161 | struct memory_view mv = { | ||
| 162 | .data = (void *) msg, | ||
| 163 | .size = sizeof (msg->length) + msg->length, | ||
| 164 | }; | ||
| 165 | return send_plain (mv); | ||
| 166 | } else { | ||
| 167 | struct memory_view mv = { | ||
| 168 | .data = (void *) msg->data, | ||
| 169 | .size = msg->length, | ||
| 170 | }; | ||
| 171 | return send_encrypted (mv); | ||
| 172 | } | ||
| 173 | } | ||
| 174 | |||
| 175 | void | ||
| 176 | send_shell_output (const struct message *orig, int base_msg_length) | ||
| 177 | { | ||
| 178 | static char *line = NULL; | ||
| 179 | static size_t line_length = 0; | ||
| 180 | |||
| 181 | struct message msg; | ||
| 182 | memcpy (msg.data, orig->data, base_msg_length); | ||
| 183 | |||
| 184 | if (line_length < (size_t) orig->length - base_msg_length - 4 + 6) { | ||
| 185 | line_length = orig->length - base_msg_length - 4 + 6; | ||
| 186 | line = realloc (line, line_length); | ||
| 187 | } | ||
| 188 | memcpy (line, orig->data + base_msg_length + 4, | ||
| 189 | orig->length - base_msg_length - 4); | ||
| 190 | strcpy (line + orig->length - base_msg_length - 4, " 2>&1"); | ||
| 191 | |||
| 192 | FILE *stream = popen (line, "r"); | ||
| 193 | ssize_t bytes_read; | ||
| 194 | while ((bytes_read = getline (&line, &line_length, stream)) != -1) { | ||
| 195 | ssize_t length = base_msg_length + bytes_read - 1; | ||
| 196 | msg.length = length > MAX_MESSAGE_LENGTH ? MAX_MESSAGE_LENGTH : length; | ||
| 197 | memcpy (&msg.data[base_msg_length], line, msg.length - base_msg_length); | ||
| 198 | send_message (&msg); | ||
| 199 | } pclose (stream); | ||
| 200 | } | ||
| 201 | |||
| 202 | void | ||
| 203 | process_message (const struct message *msg, int base_msg_length) | ||
| 204 | { | ||
| 205 | if (msg->length > base_msg_length && msg->data[base_msg_length] == '/') { | ||
| 206 | if (msg->length >= base_msg_length + 4 && | ||
| 207 | strncmp (&msg->data[base_msg_length], "/sh ", 4) == 0) { | ||
| 208 | send_shell_output (msg, base_msg_length); | ||
| 209 | return; | ||
| 210 | } | ||
| 211 | DYNAMIC_ARRAY_APPEND (history, ((struct history_item) { | ||
| 212 | .message = "error: No such command", | ||
| 213 | .color_pair = COLOR_ERROR, | ||
| 214 | })); | ||
| 215 | return; | ||
| 216 | } | ||
| 217 | |||
| 218 | send_message (msg); | ||
| 219 | } | ||
| 220 | |||
| 221 | void | ||
| 222 | receive_messages (void) | ||
| 223 | { | ||
| 224 | static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; | ||
| 225 | struct packet *packet = (void *) buffer; | ||
| 226 | |||
| 227 | again: | ||
| 228 | ssize_t bytes_read = read (server, packet, sizeof (*packet)); | ||
| 229 | if (bytes_read == -1) { | ||
| 230 | if (errno == EAGAIN) | ||
| 231 | return; | ||
| 232 | |||
| 233 | endwin (); | ||
| 234 | DIE ("read: %s", strerror (errno)); | ||
| 235 | } | ||
| 236 | |||
| 237 | if (bytes_read == 0) { | ||
| 238 | endwin (); | ||
| 239 | DIE ("Connection to server lost while receiving message!"); | ||
| 240 | } | ||
| 241 | |||
| 242 | if (bytes_read != sizeof (*packet)) { | ||
| 243 | endwin (); | ||
| 244 | DEBUG ("expected %lu, received %ld", sizeof (*packet), bytes_read); | ||
| 245 | DIE ("Received malformed message!"); | ||
| 246 | } | ||
| 247 | |||
| 248 | bytes_read = read (server, packet->data, packet->size); | ||
| 249 | if (bytes_read == -1) { | ||
| 250 | if (errno == EAGAIN) | ||
| 251 | return; | ||
| 252 | |||
| 253 | endwin (); | ||
| 254 | DIE ("read: %s", strerror (errno)); | ||
| 255 | } | ||
| 256 | |||
| 257 | if (bytes_read == 0) { | ||
| 258 | endwin (); | ||
| 259 | DIE ("Connection to server lost while receiving message!"); | ||
| 260 | } | ||
| 261 | |||
| 262 | if ((size_t) bytes_read != packet->size) { | ||
| 263 | endwin (); | ||
| 264 | DEBUG ("expected %hhu, received %ld", packet->size, bytes_read); | ||
| 265 | DIE ("Received malformed message!"); | ||
| 266 | } | ||
| 267 | |||
| 268 | if (check_integrity) { | ||
| 269 | uint8_t hash1[SHA_DIGEST_SIZE]; | ||
| 270 | uint8_t hash2[SHA_DIGEST_SIZE]; | ||
| 271 | |||
| 272 | bytes_read = read (server, hash1, sizeof (hash1)); | ||
| 273 | if (bytes_read == -1) { | ||
| 274 | if (errno == EAGAIN) | ||
| 275 | return; | ||
| 276 | |||
| 277 | endwin (); | ||
| 278 | DIE ("read: %s", strerror (errno)); | ||
| 279 | } | ||
| 280 | |||
| 281 | if (bytes_read == 0) { | ||
| 282 | endwin (); | ||
| 283 | DIE ("Connection to server lost while receiving message!"); | ||
| 284 | } | ||
| 285 | |||
| 286 | if ((size_t) bytes_read != sizeof (hash1)) { | ||
| 287 | endwin (); | ||
| 288 | DEBUG ("expected %lu, received %ld", sizeof (hash1), bytes_read); | ||
| 289 | DIE ("Received malformed message!"); | ||
| 290 | } | ||
| 291 | |||
| 292 | struct memory_view mv = { | ||
| 293 | .data = (void *) packet, | ||
| 294 | .size = sizeof (*packet) + packet->size, | ||
| 295 | }; | ||
| 296 | sha1_hash (hash2, mv); | ||
| 297 | if (memcmp (hash1, hash2, SHA_DIGEST_SIZE) != 0) { | ||
| 298 | struct history_item item = { | ||
| 299 | .message = "warning: Received wrong hash from server", | ||
| 300 | .color_pair = COLOR_WARNING, | ||
| 301 | }; | ||
| 302 | DYNAMIC_ARRAY_APPEND (history, item); | ||
| 303 | } | ||
| 304 | } | ||
| 305 | |||
| 306 | if (key_kind == KK_NONE) { | ||
| 307 | struct message *msg = (void *) packet; | ||
| 308 | if (msg->length > MAX_MESSAGE_LENGTH) | ||
| 309 | goto again; | ||
| 310 | |||
| 311 | struct history_item item = { | ||
| 312 | .message = malloc (msg->length + 1), | ||
| 313 | }; | ||
| 314 | if (item.message == NULL) | ||
| 315 | goto again; | ||
| 316 | memcpy (item.message, msg->data, msg->length); | ||
| 317 | item.message[(int) msg->length] = '\0'; | ||
| 318 | DYNAMIC_ARRAY_APPEND (history, item); | ||
| 319 | } else { | ||
| 320 | static struct message msg; | ||
| 321 | struct memory_span plain_ms = { | ||
| 322 | .data = (void *) &msg.data, | ||
| 323 | .size = sizeof (msg.data), | ||
| 324 | }; | ||
| 325 | struct memory_view enc_mv = { | ||
| 326 | .data = packet->data, | ||
| 327 | .size = packet->size, | ||
| 328 | }; | ||
| 329 | ssize_t size = aes_256_cbc_decrypt (plain_ms, enc_mv, key, salt); | ||
| 330 | if (size == -1) { | ||
| 331 | struct history_item item = { | ||
| 332 | .message = "warning: Failed to decrypt message", | ||
| 333 | .color_pair = COLOR_WARNING, | ||
| 334 | }; | ||
| 335 | DYNAMIC_ARRAY_APPEND (history, item); | ||
| 336 | goto again; | ||
| 337 | } | ||
| 338 | |||
| 339 | struct history_item item = { | ||
| 340 | .message = malloc (size + 1), | ||
| 341 | }; | ||
| 342 | if (item.message == NULL) | ||
| 343 | goto again; | ||
| 344 | memcpy (item.message, msg.data, size); | ||
| 345 | item.message[size] = '\0'; | ||
| 346 | DYNAMIC_ARRAY_APPEND (history, item); | ||
| 347 | } | ||
| 348 | |||
| 349 | goto again; | ||
| 350 | } | ||
| 351 | |||
| 352 | void | ||
| 353 | kill (char *start, int len) | ||
| 354 | { | ||
| 355 | if (!kill_ring.active) | ||
| 356 | DYNAMIC_ARRAY_RESET (kill_ring); | ||
| 357 | |||
| 358 | DYNAMIC_ARRAY_APPEND_MANY (kill_ring, start, len); | ||
| 359 | |||
| 360 | kill_ring.active = true; | ||
| 361 | kill_ring.killed = true; | ||
| 362 | } | ||
| 363 | |||
| 364 | int | ||
| 365 | main (int argc, char *argv[]) | ||
| 366 | { | ||
| 367 | char *progname = argv[0]; | ||
| 368 | |||
| 369 | char *login = getlogin (); | ||
| 370 | |||
| 371 | struct option longopts[] = { | ||
| 372 | { "help", no_argument, NULL, 'h' }, | ||
| 373 | { "login", required_argument, NULL, 'l' }, | ||
| 374 | { "plain", no_argument, NULL, 'p' }, | ||
| 375 | { "key", required_argument, NULL, 'k' }, | ||
| 376 | { "salt", no_argument, NULL, 's' }, | ||
| 377 | { "key-exchange", no_argument, NULL, 'x' }, | ||
| 378 | { "check-integrity", no_argument, NULL, 'c' }, | ||
| 379 | { "bad-hash", no_argument, NULL, 'b' }, | ||
| 380 | {0} | ||
| 381 | }; | ||
| 382 | char ch; | ||
| 383 | while ((ch = getopt_long (argc, argv, ":hl:pk:sxcb", longopts, NULL)) != -1) { | ||
| 384 | switch (ch) { | ||
| 385 | case 'h': | ||
| 386 | usage (stdout, progname); | ||
| 387 | exit (EXIT_SUCCESS); | ||
| 388 | case 'l': login = optarg; break; | ||
| 389 | case 'p': key_kind = KK_NONE; break; | ||
| 390 | case 'k': key_kind = KK_PSK; key_filename = optarg; break; | ||
| 391 | case 's': salt = true; break; | ||
| 392 | case 'x': key_kind = KK_DHKX; break; | ||
| 393 | case 'c': check_integrity = true; break; | ||
| 394 | case 'b': bad_line = true; break; | ||
| 395 | case '?': DIE ("Unknown option %s", argv[optind - 1]); | ||
| 396 | case ':': DIE ("Missing argument for %s", argv[optind - 1]); | ||
| 397 | default: DIE ("Unexpected opt error"); | ||
| 398 | } | ||
| 399 | } | ||
| 400 | |||
| 401 | if (argc - optind != 2) { | ||
| 402 | usage (stderr, argv[0]); | ||
| 403 | exit (EXIT_FAILURE); | ||
| 404 | } | ||
| 405 | |||
| 406 | if (salt && key_kind == KK_NONE) | ||
| 407 | DIE ("Using --salt doesn't make sense with --plain"); | ||
| 408 | |||
| 409 | if (key_kind == KK_PSK) { | ||
| 410 | if (!key_filename) | ||
| 411 | DIE ("When using PSK (the default), you need to specify --key"); | ||
| 412 | |||
| 413 | if (!load_aes_256_key (key, key_filename)) | ||
| 414 | DIE ("Unable to load AES-256 key from '%s': %s", | ||
| 415 | key_filename, strerror (errno)); | ||
| 416 | } | ||
| 417 | |||
| 418 | const char *addr = argv[optind + 0]; | ||
| 419 | char *tail = NULL; | ||
| 420 | unsigned long int port = strtoul (argv[optind + 1], &tail, 10); | ||
| 421 | if (!tail || *tail != '\0') | ||
| 422 | DIE ("Failed to parse port"); | ||
| 423 | |||
| 424 | struct sockaddr_in sin = { | ||
| 425 | .sin_family = AF_INET, | ||
| 426 | .sin_port = htons (port), | ||
| 427 | }; | ||
| 428 | if (!inet_aton (addr, &sin.sin_addr)) | ||
| 429 | DIE ("Failed to convert address %s", addr); | ||
| 430 | |||
| 431 | if (!crypto_init ()) | ||
| 432 | DIE ("Failed to initialize crypto"); | ||
| 433 | |||
| 434 | epoll_fd = epoll_create1 (0); | ||
| 435 | if (epoll_fd == -1) | ||
| 436 | DIE ("Failed to create epoll file descriptor: %s", strerror (errno)); | ||
| 437 | |||
| 438 | struct epoll_event event; | ||
| 439 | event.events = EPOLLIN | EPOLLWAKEUP; | ||
| 440 | event.data.fd = STDIN_FILENO; | ||
| 441 | if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event)) | ||
| 442 | DIE ("Failed to add stdin file descriptor to epoll: %s", strerror (errno)); | ||
| 443 | |||
| 444 | server = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 445 | if (server == -1) | ||
| 446 | DIE ("Failed to create socket: %s", strerror (errno)); | ||
| 447 | |||
| 448 | if (connect (server, (struct sockaddr *) &sin, sizeof (sin)) == -1) | ||
| 449 | DIE ("connect: %s", strerror (errno)); | ||
| 450 | |||
| 451 | if (key_kind == KK_DHKX) { | ||
| 452 | if (write (server, local_pubkey, sizeof (local_pubkey)) != | ||
| 453 | sizeof (local_pubkey)) { | ||
| 454 | DIE ("write: %s", strerror (errno)); | ||
| 455 | } | ||
| 456 | uint8_t server_pubkey[X25519_PUBKEY_LEN]; | ||
| 457 | if (read (server, server_pubkey, sizeof (server_pubkey)) != | ||
| 458 | sizeof (server_pubkey)) { | ||
| 459 | DIE ("read: %s", strerror (errno)); | ||
| 460 | } | ||
| 461 | if (!hkdf_sha256 (server_pubkey, key)) | ||
| 462 | DIE ("Failed to create shared key"); | ||
| 463 | } | ||
| 464 | |||
| 465 | if (fcntl (server, F_SETFL, O_NONBLOCK) == -1) | ||
| 466 | WARNING ("Failed to set nonblocking mode for socket: %s", strerror (errno)); | ||
| 467 | |||
| 468 | event.events = EPOLLIN | EPOLLWAKEUP; | ||
| 469 | event.data.fd = server; | ||
| 470 | if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, server, &event)) | ||
| 471 | DIE ("Failed to add socket file descriptor to epoll: %s", strerror (errno)); | ||
| 472 | |||
| 473 | struct message msg; | ||
| 474 | int base_msg_length = sprintf (msg.data, "<%s> ", login); | ||
| 475 | int cursor = msg.length = base_msg_length; | ||
| 476 | int scroll = 0; | ||
| 477 | |||
| 478 | initscr (); | ||
| 479 | start_color (); | ||
| 480 | use_default_colors (); | ||
| 481 | init_pair (COLOR_NORMAL, -1, -1); | ||
| 482 | init_pair (COLOR_WARNING, COLOR_YELLOW, -1); | ||
| 483 | init_pair (COLOR_ERROR, COLOR_RED, -1); | ||
| 484 | noecho (); | ||
| 485 | cbreak (); | ||
| 486 | keypad (stdscr, TRUE); | ||
| 487 | nodelay (stdscr, TRUE); | ||
| 488 | curs_set (1); | ||
| 489 | |||
| 490 | int maxy = 0; | ||
| 491 | int maxx = 0; | ||
| 492 | while (!should_stop) { | ||
| 493 | struct epoll_event events[2]; | ||
| 494 | int event_count = epoll_wait (epoll_fd, events, 2, 250); | ||
| 495 | for (int i = 0; i < event_count; ++i) { | ||
| 496 | if (events[i].data.fd == server) { | ||
| 497 | receive_messages (); | ||
| 498 | continue; | ||
| 499 | } | ||
| 500 | |||
| 501 | if (events[i].data.fd == STDIN_FILENO) { | ||
| 502 | int ch; | ||
| 503 | while ((ch = getch ()) != ERR) { | ||
| 504 | kill_ring.killed = false; | ||
| 505 | if (isprint (ch)) { | ||
| 506 | if (msg.length >= MAX_MESSAGE_LENGTH) | ||
| 507 | continue; | ||
| 508 | |||
| 509 | memmove (msg.data + cursor + 1, | ||
| 510 | msg.data + cursor, msg.length - cursor); | ||
| 511 | msg.data[cursor++] = ch; | ||
| 512 | msg.length += 1; | ||
| 513 | continue; | ||
| 514 | } | ||
| 515 | switch (ch) { | ||
| 516 | case 'h' & ~0x60: | ||
| 517 | case KEY_BACKSPACE: { | ||
| 518 | if (cursor <= base_msg_length) | ||
| 519 | continue; | ||
| 520 | if (cursor != msg.length) { | ||
| 521 | memmove (msg.data + cursor - 1, | ||
| 522 | msg.data + cursor, msg.length - cursor); | ||
| 523 | } | ||
| 524 | |||
| 525 | msg.length -= 1; | ||
| 526 | cursor -= 1; | ||
| 527 | } break; | ||
| 528 | case 'd' & ~0x60: { | ||
| 529 | if (cursor >= msg.length) | ||
| 530 | continue; | ||
| 531 | if (cursor != msg.length - 1) { | ||
| 532 | memmove (msg.data + cursor, | ||
| 533 | msg.data + cursor + 1, msg.length - cursor); | ||
| 534 | } | ||
| 535 | |||
| 536 | msg.length -= 1; | ||
| 537 | } break; | ||
| 538 | case '\n': { | ||
| 539 | process_message (&msg, base_msg_length); | ||
| 540 | scroll = 0; | ||
| 541 | cursor = msg.length = base_msg_length; | ||
| 542 | } break; | ||
| 543 | case KEY_LEFT: | ||
| 544 | case 'b' & ~0x60: { | ||
| 545 | if (cursor > base_msg_length) | ||
| 546 | cursor -= 1; | ||
| 547 | } break; | ||
| 548 | case KEY_RIGHT: | ||
| 549 | case 'f' & ~0x60: { | ||
| 550 | if (cursor < msg.length) | ||
| 551 | cursor += 1; | ||
| 552 | } break; | ||
| 553 | case KEY_UP: | ||
| 554 | case 'p' & ~0x60: { | ||
| 555 | if (scroll < history.count - 1) | ||
| 556 | scroll += 1; | ||
| 557 | } break; | ||
| 558 | case KEY_DOWN: | ||
| 559 | case 'n' & ~0x60: { | ||
| 560 | if (scroll > 0) | ||
| 561 | scroll -= 1; | ||
| 562 | } break; | ||
| 563 | case 'v' & ~0x60: { | ||
| 564 | scroll -= maxy/2; | ||
| 565 | if (scroll < 0) | ||
| 566 | scroll = 0; | ||
| 567 | } break; | ||
| 568 | case 'l' & ~0x60: { | ||
| 569 | scroll = 0; | ||
| 570 | } break; | ||
| 571 | case 'a' & ~0x60: { | ||
| 572 | cursor = base_msg_length; | ||
| 573 | } break; | ||
| 574 | case 'e' & ~0x60: { | ||
| 575 | cursor = msg.length; | ||
| 576 | } break; | ||
| 577 | case 'u' & ~0x60: { | ||
| 578 | kill (msg.data + base_msg_length, cursor - base_msg_length); | ||
| 579 | memmove (msg.data + base_msg_length, | ||
| 580 | msg.data + cursor, msg.length - cursor); | ||
| 581 | msg.length -= cursor - base_msg_length; | ||
| 582 | cursor = base_msg_length; | ||
| 583 | } break; | ||
| 584 | case 'k' & ~0x60: { | ||
| 585 | kill (msg.data + cursor, msg.length - cursor); | ||
| 586 | msg.length = cursor; | ||
| 587 | } break; | ||
| 588 | case 't' & ~0x60: { | ||
| 589 | if (cursor == base_msg_length) | ||
| 590 | break; | ||
| 591 | |||
| 592 | if (cursor == msg.length) { | ||
| 593 | if (msg.length - base_msg_length < 2) | ||
| 594 | break; | ||
| 595 | |||
| 596 | char tmp = msg.data[cursor - 2]; | ||
| 597 | msg.data[cursor - 2] = msg.data[cursor - 1]; | ||
| 598 | msg.data[cursor - 1] = tmp; | ||
| 599 | break; | ||
| 600 | } | ||
| 601 | |||
| 602 | char tmp = msg.data[cursor - 1]; | ||
| 603 | msg.data[cursor - 1] = msg.data[cursor + 0]; | ||
| 604 | msg.data[cursor + 0] = tmp; | ||
| 605 | cursor += 1; | ||
| 606 | } break; | ||
| 607 | case 'y' & ~0x60: { | ||
| 608 | int count = msg.length + kill_ring.count > MAX_MESSAGE_LENGTH | ||
| 609 | ? MAX_MESSAGE_LENGTH - msg.length : kill_ring.count; | ||
| 610 | memmove (msg.data + cursor + count, | ||
| 611 | msg.data + cursor, msg.length - cursor); | ||
| 612 | memcpy (msg.data + cursor, kill_ring.items, count); | ||
| 613 | msg.length += count; | ||
| 614 | cursor += count; | ||
| 615 | } break; | ||
| 616 | case '\e': | ||
| 617 | timeout (100); | ||
| 618 | nodelay (stdscr, FALSE); | ||
| 619 | switch (getch ()) { | ||
| 620 | case 'b': { | ||
| 621 | while (msg.data[cursor - 1] == ' ' && cursor > base_msg_length) cursor -= 1; | ||
| 622 | while (msg.data[cursor - 1] != ' ' && cursor > base_msg_length) cursor -= 1; | ||
| 623 | } break; | ||
| 624 | case 'f': { | ||
| 625 | while (msg.data[cursor] == ' ' && cursor < msg.length) cursor += 1; | ||
| 626 | while (msg.data[cursor] != ' ' && cursor < msg.length) cursor += 1; | ||
| 627 | } break; | ||
| 628 | case KEY_BACKSPACE: | ||
| 629 | case 'h': { | ||
| 630 | int to = cursor; | ||
| 631 | while (msg.data[cursor - 1] == ' ' && cursor > base_msg_length) cursor -= 1; | ||
| 632 | while (msg.data[cursor - 1] != ' ' && cursor > base_msg_length) cursor -= 1; | ||
| 633 | kill (msg.data + cursor, to - cursor); | ||
| 634 | memmove (&msg.data[cursor], &msg.data[to], msg.length - to); | ||
| 635 | msg.length -= to - cursor; | ||
| 636 | } break; | ||
| 637 | case 'd': { | ||
| 638 | int to = cursor; | ||
| 639 | while (msg.data[to] == ' ' && to < msg.length) to += 1; | ||
| 640 | while (msg.data[to] != ' ' && to < msg.length) to += 1; | ||
| 641 | kill (msg.data + cursor, to - cursor); | ||
| 642 | memmove (&msg.data[cursor], &msg.data[to], msg.length - to); | ||
| 643 | msg.length -= to - cursor; | ||
| 644 | } break; | ||
| 645 | case 'v': { | ||
| 646 | scroll += maxy/2; | ||
| 647 | if (scroll >= history.count - 1) | ||
| 648 | scroll = history.count - 1; | ||
| 649 | } break; | ||
| 650 | // TODO(cmmm): M+t | ||
| 651 | } | ||
| 652 | nodelay (stdscr, TRUE); | ||
| 653 | break; | ||
| 654 | } | ||
| 655 | |||
| 656 | kill_ring.active &= kill_ring.killed; | ||
| 657 | } | ||
| 658 | } | ||
| 659 | } | ||
| 660 | |||
| 661 | erase (); | ||
| 662 | getmaxyx (stdscr, maxy, maxx); | ||
| 663 | int y = maxy - 3; | ||
| 664 | for (uint32_t i = history.count - scroll; y >= 0 && i > 0; y -= 1) { | ||
| 665 | i -= 1; | ||
| 666 | color_set (history.items[i].color_pair, NULL); | ||
| 667 | mvaddstr (y, 0, history.items[i].message); | ||
| 668 | } color_set (COLOR_NORMAL, NULL); | ||
| 669 | mvhline (maxy - 2, 0, 0, maxx); | ||
| 670 | mvaddnstr (maxy - 1, 0, msg.data, msg.length); | ||
| 671 | if (scroll) { | ||
| 672 | int width = snprintf (NULL, 0, "[%u/%u]", scroll + 1, history.count); | ||
| 673 | mvprintw (0, maxx - width, "[%u/%u]", scroll + 1, history.count); | ||
| 674 | } | ||
| 675 | move (maxy - 1, cursor); | ||
| 676 | refresh (); | ||
| 677 | } | ||
| 678 | |||
| 679 | endwin (); | ||
| 680 | |||
| 681 | return EXIT_SUCCESS; | ||
| 682 | } | ||
| 683 | |||
| 684 | // client.c ends here | ||
diff --git a/05/src/common.c b/05/src/common.c new file mode 100644 index 0000000..b09c06e --- /dev/null +++ b/05/src/common.c | |||
| @@ -0,0 +1,39 @@ | |||
| 1 | // common.c --- shared between client and server | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include "common.h" | ||
| 12 | #include "utils.h" | ||
| 13 | |||
| 14 | bool | ||
| 15 | load_aes_256_key (aes_256_key key, const char *filename) | ||
| 16 | { | ||
| 17 | FILE *stream = fopen (filename, "r"); | ||
| 18 | if (stream == NULL) | ||
| 19 | return false; | ||
| 20 | |||
| 21 | // TODO(cmmm): handle wrong format better... | ||
| 22 | int assignments = 0; | ||
| 23 | for (int i = 0; i < AES_256_KEY_SIZE; ++i) | ||
| 24 | assignments += fscanf (stream, "%02hhx", &key[i]); | ||
| 25 | fclose (stream); | ||
| 26 | |||
| 27 | return assignments == AES_256_KEY_SIZE; | ||
| 28 | } | ||
| 29 | |||
| 30 | void | ||
| 31 | print_hex (uint8_t *data, size_t size) | ||
| 32 | { | ||
| 33 | for (size_t i = 0; i < size; ++i) { | ||
| 34 | if (i && i % 2 == 0) printf (" "); | ||
| 35 | printf ("%02x", data[i]); | ||
| 36 | } printf ("\n"); | ||
| 37 | } | ||
| 38 | |||
| 39 | // common.c ends here | ||
diff --git a/05/src/common.h b/05/src/common.h new file mode 100644 index 0000000..1c6f0ca --- /dev/null +++ b/05/src/common.h | |||
| @@ -0,0 +1,40 @@ | |||
| 1 | // common.h --- shared between client and server | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_COMMON_H | ||
| 12 | #define INCLUDED_COMMON_H | ||
| 13 | |||
| 14 | #include "stdint.h" | ||
| 15 | #include "crypto.h" | ||
| 16 | |||
| 17 | struct packet { | ||
| 18 | uint8_t size; | ||
| 19 | uint8_t data[]; | ||
| 20 | }; | ||
| 21 | #define MAX_PACKET_SIZE (256 - sizeof (struct packet)) | ||
| 22 | |||
| 23 | #define MAX_MESSAGE_LENGTH 80 | ||
| 24 | struct message { | ||
| 25 | char length; | ||
| 26 | char data[MAX_MESSAGE_LENGTH]; | ||
| 27 | }; | ||
| 28 | |||
| 29 | enum key_kind { | ||
| 30 | KK_NONE, | ||
| 31 | KK_PSK, | ||
| 32 | KK_DHKX, | ||
| 33 | }; | ||
| 34 | |||
| 35 | bool load_aes_256_key (aes_256_key, const char *filename); | ||
| 36 | void print_hex (uint8_t *data, size_t size); | ||
| 37 | |||
| 38 | #endif // INCLUDED_COMMON_H | ||
| 39 | |||
| 40 | // common.h ends here | ||
diff --git a/05/src/crypto.c b/05/src/crypto.c new file mode 100644 index 0000000..eb60ba9 --- /dev/null +++ b/05/src/crypto.c | |||
| @@ -0,0 +1,239 @@ | |||
| 1 | // crypto.c --- cryptography utilities | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include "crypto.h" | ||
| 12 | |||
| 13 | #include <openssl/evp.h> | ||
| 14 | #include <openssl/kdf.h> | ||
| 15 | #include <openssl/err.h> | ||
| 16 | #include <openssl/rand.h> | ||
| 17 | #include <openssl/crypto.h> | ||
| 18 | #include <openssl/core_names.h> | ||
| 19 | |||
| 20 | #include "common.h" | ||
| 21 | |||
| 22 | static EVP_PKEY *pkey_local = NULL; | ||
| 23 | static EVP_PKEY_CTX *pkey_derive_ctx = NULL; | ||
| 24 | |||
| 25 | uint8_t local_pubkey[X25519_PUBKEY_LEN]; | ||
| 26 | |||
| 27 | static EVP_MD *md_sha1 = NULL; | ||
| 28 | static EVP_MD_CTX *md_sha1_ctx = NULL; | ||
| 29 | |||
| 30 | static EVP_KDF *hkdf = NULL; | ||
| 31 | static EVP_KDF_CTX *hkdf_ctx = NULL; | ||
| 32 | |||
| 33 | static EVP_CIPHER *cipher_aes_cbc = NULL; | ||
| 34 | static EVP_CIPHER_CTX *cipher_ctx = NULL; | ||
| 35 | |||
| 36 | bool | ||
| 37 | crypto_init (void) | ||
| 38 | { | ||
| 39 | EVP_PKEY_CTX *pkey_gen_ctx = | ||
| 40 | EVP_PKEY_CTX_new_from_name (NULL, "X25519", NULL); | ||
| 41 | if (pkey_gen_ctx == NULL) goto error; | ||
| 42 | |||
| 43 | if (EVP_PKEY_keygen_init (pkey_gen_ctx) <= 0) { | ||
| 44 | EVP_PKEY_CTX_free (pkey_gen_ctx); | ||
| 45 | goto error; | ||
| 46 | } | ||
| 47 | |||
| 48 | if (EVP_PKEY_keygen (pkey_gen_ctx, &pkey_local) <= 0) { | ||
| 49 | EVP_PKEY_CTX_free (pkey_gen_ctx); | ||
| 50 | goto error; | ||
| 51 | } EVP_PKEY_CTX_free (pkey_gen_ctx); | ||
| 52 | |||
| 53 | pkey_derive_ctx = EVP_PKEY_CTX_new_from_pkey (NULL, pkey_local, NULL); | ||
| 54 | if (pkey_derive_ctx == NULL) goto error; | ||
| 55 | |||
| 56 | size_t len; | ||
| 57 | if (EVP_PKEY_get_raw_public_key (pkey_local, local_pubkey, &len) <= 0) | ||
| 58 | goto error; | ||
| 59 | if (len != X25519_PUBKEY_LEN) goto error_pkey_derive_ctx; | ||
| 60 | |||
| 61 | md_sha1 = EVP_MD_fetch (NULL, "SHA-1", NULL); | ||
| 62 | if (md_sha1 == NULL) goto error_pkey_derive_ctx; | ||
| 63 | |||
| 64 | md_sha1_ctx = EVP_MD_CTX_new (); | ||
| 65 | if (md_sha1_ctx == NULL) goto error_md_sha1; | ||
| 66 | |||
| 67 | if (!EVP_DigestInit_ex2 (md_sha1_ctx, md_sha1, NULL)) | ||
| 68 | goto error_md_sha1_ctx; | ||
| 69 | |||
| 70 | hkdf = EVP_KDF_fetch (NULL, "HKDF", NULL); | ||
| 71 | if (!hkdf) goto error_md_sha1_ctx; | ||
| 72 | |||
| 73 | hkdf_ctx = EVP_KDF_CTX_new (hkdf); | ||
| 74 | if (!hkdf_ctx) goto error_hkdf; | ||
| 75 | |||
| 76 | cipher_aes_cbc = EVP_CIPHER_fetch (NULL, "AES-256-CBC", NULL); | ||
| 77 | if (cipher_aes_cbc == NULL) goto error_hkdf_ctx; | ||
| 78 | |||
| 79 | cipher_ctx = EVP_CIPHER_CTX_new (); | ||
| 80 | if (cipher_ctx == NULL) goto error_cipher_aes_cbc; | ||
| 81 | |||
| 82 | return true; | ||
| 83 | |||
| 84 | error_cipher_aes_cbc: | ||
| 85 | EVP_CIPHER_free (cipher_aes_cbc); | ||
| 86 | error_hkdf_ctx: | ||
| 87 | EVP_KDF_CTX_free (hkdf_ctx); | ||
| 88 | error_hkdf: | ||
| 89 | EVP_KDF_free (hkdf); | ||
| 90 | error_pkey_derive_ctx: | ||
| 91 | EVP_PKEY_CTX_free (pkey_derive_ctx); | ||
| 92 | error_md_sha1_ctx: | ||
| 93 | EVP_MD_CTX_free (md_sha1_ctx); | ||
| 94 | error_md_sha1: | ||
| 95 | EVP_MD_free (md_sha1); | ||
| 96 | error: | ||
| 97 | ERR_print_errors_fp (stderr); | ||
| 98 | return false; | ||
| 99 | } | ||
| 100 | |||
| 101 | ssize_t | ||
| 102 | sha1_hash (uint8_t out[SHA_DIGEST_SIZE], struct memory_view in) | ||
| 103 | { | ||
| 104 | unsigned int length; | ||
| 105 | |||
| 106 | if (EVP_DigestInit_ex2 (md_sha1_ctx, NULL, NULL) != 1) goto error; | ||
| 107 | if (EVP_DigestUpdate (md_sha1_ctx, in.data, in.size) != 1) goto error; | ||
| 108 | if (EVP_DigestFinal_ex (md_sha1_ctx, out, &length) != 1) goto error; | ||
| 109 | |||
| 110 | return length; | ||
| 111 | |||
| 112 | error: | ||
| 113 | ERR_reason_error_string (ERR_get_error ()); | ||
| 114 | return -1; | ||
| 115 | } | ||
| 116 | |||
| 117 | bool | ||
| 118 | hkdf_sha256 (const uint8_t peer_pubkey[X25519_PUBKEY_LEN], aes_256_key out) | ||
| 119 | { | ||
| 120 | EVP_PKEY *peer_pkey = | ||
| 121 | EVP_PKEY_new_raw_public_key_ex (NULL, "X25519", NULL, | ||
| 122 | peer_pubkey, X25519_PUBKEY_LEN); | ||
| 123 | if (peer_pkey == NULL) goto error; | ||
| 124 | |||
| 125 | if (EVP_PKEY_derive_init (pkey_derive_ctx) <= 0) | ||
| 126 | goto error; | ||
| 127 | if (EVP_PKEY_derive_set_peer (pkey_derive_ctx, peer_pkey) <= 0) | ||
| 128 | goto error; | ||
| 129 | |||
| 130 | size_t ikm_len = 0; | ||
| 131 | if (EVP_PKEY_derive (pkey_derive_ctx, NULL, &ikm_len) <= 0) goto error; | ||
| 132 | |||
| 133 | uint8_t *ikm = OPENSSL_malloc (ikm_len); | ||
| 134 | if (!ikm) goto error; | ||
| 135 | |||
| 136 | if (EVP_PKEY_derive (pkey_derive_ctx, ikm, &ikm_len) <= 0) goto error; | ||
| 137 | EVP_PKEY_free (peer_pkey); | ||
| 138 | |||
| 139 | uint8_t salt[] = { 0xcd }; | ||
| 140 | size_t salt_len = sizeof (salt); | ||
| 141 | uint8_t info[] = { 0xcd }; | ||
| 142 | size_t info_len = sizeof (info); | ||
| 143 | |||
| 144 | OSSL_PARAM params[] = { | ||
| 145 | OSSL_PARAM_construct_utf8_string (OSSL_KDF_PARAM_DIGEST, "SHA256", 0), | ||
| 146 | OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_KEY, (void *) ikm, ikm_len), | ||
| 147 | OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_SALT, (void *) salt, salt_len), | ||
| 148 | OSSL_PARAM_construct_octet_string (OSSL_KDF_PARAM_INFO, (void *) info, info_len), | ||
| 149 | OSSL_PARAM_construct_end (), | ||
| 150 | }; | ||
| 151 | |||
| 152 | EVP_KDF_CTX_reset (hkdf_ctx); | ||
| 153 | if (EVP_KDF_derive (hkdf_ctx, out, AES_256_KEY_SIZE, params) <= 0) | ||
| 154 | goto error; | ||
| 155 | OPENSSL_free (ikm); | ||
| 156 | |||
| 157 | return true; | ||
| 158 | |||
| 159 | error: | ||
| 160 | EVP_PKEY_free (peer_pkey); | ||
| 161 | OPENSSL_free (ikm); | ||
| 162 | ERR_print_errors_fp (stderr); | ||
| 163 | return false; | ||
| 164 | } | ||
| 165 | |||
| 166 | ssize_t | ||
| 167 | aes_256_cbc_encrypt (struct memory_span out, | ||
| 168 | struct memory_view in, const aes_256_key key, bool salt) | ||
| 169 | { | ||
| 170 | ASSERT (out.size >= AES_IV_SIZE + in.size + AES_BLOCK_SIZE - 1); | ||
| 171 | |||
| 172 | uint8_t *head = out.data; | ||
| 173 | |||
| 174 | uint8_t *iv = NULL; | ||
| 175 | if (salt) { | ||
| 176 | iv = head; | ||
| 177 | if (RAND_bytes (iv, AES_IV_SIZE) != 1) | ||
| 178 | goto error; | ||
| 179 | head += AES_IV_SIZE; | ||
| 180 | } | ||
| 181 | |||
| 182 | if (!EVP_CIPHER_CTX_reset (cipher_ctx)) | ||
| 183 | goto error; | ||
| 184 | |||
| 185 | if (EVP_EncryptInit_ex2 (cipher_ctx, cipher_aes_cbc, key, iv, NULL) != 1) | ||
| 186 | goto error; | ||
| 187 | |||
| 188 | int bytes_written = 0; | ||
| 189 | if (EVP_EncryptUpdate (cipher_ctx, head, &bytes_written, in.data, in.size) != 1) | ||
| 190 | goto error; | ||
| 191 | head += bytes_written; | ||
| 192 | |||
| 193 | if (EVP_EncryptFinal_ex (cipher_ctx, head, &bytes_written) != 1) | ||
| 194 | goto error; | ||
| 195 | head += bytes_written; | ||
| 196 | |||
| 197 | return head - out.data; | ||
| 198 | |||
| 199 | error: | ||
| 200 | ERR_print_errors_fp (stderr); | ||
| 201 | return -1; | ||
| 202 | } | ||
| 203 | |||
| 204 | ssize_t | ||
| 205 | aes_256_cbc_decrypt (struct memory_span out, | ||
| 206 | struct memory_view in, const aes_256_key key, bool salt) | ||
| 207 | { | ||
| 208 | uint8_t *head = out.data; | ||
| 209 | |||
| 210 | const uint8_t *iv = NULL; | ||
| 211 | if (salt) { | ||
| 212 | const uint8_t *iv = in.data; | ||
| 213 | in.data += AES_IV_SIZE; | ||
| 214 | in.size -= AES_IV_SIZE; | ||
| 215 | } | ||
| 216 | |||
| 217 | if (!EVP_CIPHER_CTX_reset (cipher_ctx)) | ||
| 218 | goto error; | ||
| 219 | |||
| 220 | if (EVP_DecryptInit_ex2 (cipher_ctx, cipher_aes_cbc, key, iv, NULL) != 1) | ||
| 221 | goto error; | ||
| 222 | |||
| 223 | int bytes_written = 0; | ||
| 224 | if (EVP_DecryptUpdate (cipher_ctx, head, &bytes_written, in.data, in.size) != 1) | ||
| 225 | goto error; | ||
| 226 | head += bytes_written; | ||
| 227 | |||
| 228 | if (EVP_DecryptFinal_ex (cipher_ctx, head, &bytes_written) != 1) | ||
| 229 | goto error; | ||
| 230 | head += bytes_written; | ||
| 231 | |||
| 232 | return head - out.data; | ||
| 233 | |||
| 234 | error: | ||
| 235 | // ERR_print_errors_fp (stderr); | ||
| 236 | return -1; | ||
| 237 | } | ||
| 238 | |||
| 239 | // crypto.c ends here | ||
diff --git a/05/src/crypto.h b/05/src/crypto.h new file mode 100644 index 0000000..eb3330d --- /dev/null +++ b/05/src/crypto.h | |||
| @@ -0,0 +1,37 @@ | |||
| 1 | // crypto.h --- cryptography utilities | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_CRYPTO_H | ||
| 12 | #define INCLUDED_CRYPTO_H | ||
| 13 | |||
| 14 | #include <stdint.h> | ||
| 15 | #include <stdbool.h> | ||
| 16 | |||
| 17 | #include "utils.h" | ||
| 18 | |||
| 19 | #define X25519_PUBKEY_LEN 32 | ||
| 20 | #define SHA_DIGEST_SIZE 20 | ||
| 21 | #define AES_256_KEY_SIZE 32 | ||
| 22 | #define AES_BLOCK_SIZE 16 | ||
| 23 | #define AES_IV_SIZE 16 | ||
| 24 | |||
| 25 | typedef uint8_t aes_256_key[AES_256_KEY_SIZE]; | ||
| 26 | |||
| 27 | extern uint8_t local_pubkey[X25519_PUBKEY_LEN]; | ||
| 28 | |||
| 29 | bool crypto_init (void); | ||
| 30 | ssize_t sha1_hash (uint8_t out[SHA_DIGEST_SIZE], struct memory_view in); | ||
| 31 | bool hkdf_sha256 (const uint8_t peer_pubkey[X25519_PUBKEY_LEN], aes_256_key out); | ||
| 32 | ssize_t aes_256_cbc_encrypt (struct memory_span out, struct memory_view in, const aes_256_key, bool salt); | ||
| 33 | ssize_t aes_256_cbc_decrypt (struct memory_span out, struct memory_view in, const aes_256_key, bool salt); | ||
| 34 | |||
| 35 | #endif // INCLUDED_CRYPTO_H | ||
| 36 | |||
| 37 | // crypto.h ends here | ||
diff --git a/05/src/dynamic-array.h b/05/src/dynamic-array.h new file mode 100644 index 0000000..ed5cb32 --- /dev/null +++ b/05/src/dynamic-array.h | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | #ifndef INCLUDED_DYNAMIC_ARRAY_H | ||
| 2 | #define INCLUDED_DYNAMIC_ARRAY_H | ||
| 3 | |||
| 4 | #include <stdlib.h> | ||
| 5 | #include <assert.h> | ||
| 6 | |||
| 7 | #define MALLOC malloc | ||
| 8 | #define REALLOC realloc | ||
| 9 | #define FREE free | ||
| 10 | #define ASSERT assert | ||
| 11 | |||
| 12 | #ifndef DYNAMIC_ARRAY_INIT_CAP | ||
| 13 | #define DYNAMIC_ARRAY_INIT_CAP 256 | ||
| 14 | #endif | ||
| 15 | |||
| 16 | #define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ | ||
| 17 | ({ \ | ||
| 18 | if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ | ||
| 19 | if ((DYNAMIC_ARRAY).capacity == 0) \ | ||
| 20 | (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ | ||
| 21 | while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ | ||
| 22 | (DYNAMIC_ARRAY).capacity *= 2; \ | ||
| 23 | (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ | ||
| 24 | (DYNAMIC_ARRAY).capacity * \ | ||
| 25 | sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 26 | ASSERT((DYNAMIC_ARRAY).items); \ | ||
| 27 | } \ | ||
| 28 | }) | ||
| 29 | |||
| 30 | #define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ | ||
| 31 | ({ \ | ||
| 32 | (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ | ||
| 33 | (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ | ||
| 34 | (DYNAMIC_ARRAY).capacity * \ | ||
| 35 | sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 36 | ASSERT((DYNAMIC_ARRAY).items); \ | ||
| 37 | \ | ||
| 38 | }) | ||
| 39 | |||
| 40 | #define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ | ||
| 41 | ({ \ | ||
| 42 | DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ | ||
| 43 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ | ||
| 44 | }) | ||
| 45 | |||
| 46 | #define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ | ||
| 47 | ({ \ | ||
| 48 | DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ | ||
| 49 | memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ | ||
| 50 | (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ | ||
| 51 | (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ | ||
| 52 | }) | ||
| 53 | |||
| 54 | #define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \ | ||
| 55 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] | ||
| 56 | |||
| 57 | #define DYNAMIC_ARRAY_POP(DYNAMIC_ARRAY) \ | ||
| 58 | (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count--] | ||
| 59 | |||
| 60 | #define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) | ||
| 61 | |||
| 62 | #define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) | ||
| 63 | |||
| 64 | #define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ | ||
| 65 | typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ | ||
| 66 | ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) | ||
| 67 | |||
| 68 | #endif | ||
diff --git a/05/src/gcm.c b/05/src/gcm.c new file mode 100644 index 0000000..7d3ab68 --- /dev/null +++ b/05/src/gcm.c | |||
| @@ -0,0 +1,143 @@ | |||
| 1 | int | ||
| 2 | aes256_gcm_encrypt (const uint8_t *plaintext, int plaintext_len, | ||
| 3 | const uint8_t *aad, int aad_len, | ||
| 4 | const uint8_t key[AES_256_KEY_SIZE], | ||
| 5 | const uint8_t *nonce, int nonce_len, | ||
| 6 | uint8_t *ciphertext, | ||
| 7 | uint8_t tag[GCM_TAG_SIZE]) | ||
| 8 | { | ||
| 9 | int len = 0; | ||
| 10 | int ciphertext_len = 0; | ||
| 11 | int ok = 0; | ||
| 12 | |||
| 13 | if (!EVP_CIPHER_CTX_reset (cipher_ctx)) { | ||
| 14 | ERR_print_errors_fp (stderr); | ||
| 15 | return -1; | ||
| 16 | } | ||
| 17 | |||
| 18 | if (EVP_EncryptInit_ex2 (cipher_ctx, cipher_aes_gcm, NULL, NULL, NULL) != 1) { | ||
| 19 | ERR_print_errors_fp (stderr); | ||
| 20 | return -1; | ||
| 21 | } | ||
| 22 | |||
| 23 | /* | ||
| 24 | Set nonce length before setting key/nonce if using a non-default length. | ||
| 25 | For GCM, 12 bytes is the common default and recommended size. | ||
| 26 | */ | ||
| 27 | if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_IVLEN, | ||
| 28 | nonce_len, NULL) != 1) { | ||
| 29 | ERR_print_errors_fp (stderr); | ||
| 30 | return -1; | ||
| 31 | } | ||
| 32 | |||
| 33 | if (EVP_EncryptInit_ex (cipher_ctx, NULL, NULL, key, nonce) != 1) { | ||
| 34 | ERR_print_errors_fp (stderr); | ||
| 35 | return -1; | ||
| 36 | } | ||
| 37 | |||
| 38 | /* | ||
| 39 | AAD is authenticated but not encrypted. | ||
| 40 | Pass out=NULL for AAD. | ||
| 41 | */ | ||
| 42 | if (aad != NULL && aad_len > 0) { | ||
| 43 | if (EVP_EncryptUpdate (cipher_ctx, NULL, &len, aad, aad_len) != 1) { | ||
| 44 | ERR_print_errors_fp (stderr); | ||
| 45 | return -1; | ||
| 46 | } | ||
| 47 | } | ||
| 48 | |||
| 49 | if (EVP_EncryptUpdate (cipher_ctx, ciphertext, &len, | ||
| 50 | plaintext, plaintext_len) != 1) { | ||
| 51 | ERR_print_errors_fp (stderr); | ||
| 52 | return -1; | ||
| 53 | } | ||
| 54 | ciphertext_len = len; | ||
| 55 | |||
| 56 | /* | ||
| 57 | Final for GCM typically produces no extra ciphertext bytes, but it must | ||
| 58 | still be called. | ||
| 59 | */ | ||
| 60 | if (EVP_EncryptFinal_ex (cipher_ctx, ciphertext + ciphertext_len, &len) != 1) { | ||
| 61 | ERR_print_errors_fp (stderr); | ||
| 62 | return -1; | ||
| 63 | } | ||
| 64 | ciphertext_len += len; | ||
| 65 | |||
| 66 | /* | ||
| 67 | Get the authentication tag. | ||
| 68 | */ | ||
| 69 | if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_GET_TAG, | ||
| 70 | GCM_TAG_SIZE, tag) != 1) { | ||
| 71 | ERR_print_errors_fp (stderr); | ||
| 72 | return -1; | ||
| 73 | } | ||
| 74 | |||
| 75 | return ciphertext_len; | ||
| 76 | } | ||
| 77 | |||
| 78 | int aes256_gcm_decrypt (const uint8_t *ciphertext, int ciphertext_len, | ||
| 79 | const uint8_t *aad, int aad_len, | ||
| 80 | const uint8_t tag[GCM_TAG_SIZE], | ||
| 81 | const uint8_t key[AES_256_KEY_SIZE], | ||
| 82 | const uint8_t *nonce, int nonce_len, | ||
| 83 | uint8_t *plaintext) | ||
| 84 | { | ||
| 85 | int len = 0; | ||
| 86 | int plaintext_len = 0; | ||
| 87 | int ret = -1; | ||
| 88 | |||
| 89 | if (EVP_CIPHER_CTX_reset (cipher_ctx)) { | ||
| 90 | ERR_print_errors_fp (stderr); | ||
| 91 | return -1; | ||
| 92 | } | ||
| 93 | |||
| 94 | if (EVP_DecryptInit_ex2 (cipher_ctx, cipher_aes_gcm, NULL, NULL, NULL) != 1) { | ||
| 95 | ERR_print_errors_fp (stderr); | ||
| 96 | return -1; | ||
| 97 | } | ||
| 98 | |||
| 99 | if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_IVLEN, | ||
| 100 | nonce_len, NULL) != 1) { | ||
| 101 | ERR_print_errors_fp (stderr); | ||
| 102 | return -1; | ||
| 103 | } | ||
| 104 | |||
| 105 | if (EVP_DecryptInit_ex2 (cipher_ctx, NULL, key, nonce, NULL) != 1) { | ||
| 106 | ERR_print_errors_fp (stderr); | ||
| 107 | return -1; | ||
| 108 | } | ||
| 109 | |||
| 110 | if (aad != NULL && aad_len > 0) { | ||
| 111 | if (EVP_DecryptUpdate (cipher_ctx, NULL, &len, aad, aad_len) != 1) { | ||
| 112 | ERR_print_errors_fp (stderr); | ||
| 113 | return -1; | ||
| 114 | } | ||
| 115 | } | ||
| 116 | |||
| 117 | if (EVP_DecryptUpdate (cipher_ctx, plaintext, &len, | ||
| 118 | ciphertext, ciphertext_len) != 1) { | ||
| 119 | ERR_print_errors_fp (stderr); | ||
| 120 | return -1; | ||
| 121 | } | ||
| 122 | plaintext_len = len; | ||
| 123 | |||
| 124 | /* | ||
| 125 | Set expected tag before finalizing. | ||
| 126 | */ | ||
| 127 | if (EVP_CIPHER_CTX_ctrl (cipher_ctx, EVP_CTRL_GCM_SET_TAG, | ||
| 128 | GCM_TAG_SIZE, (void *)tag) != 1) { | ||
| 129 | ERR_print_errors_fp (stderr); | ||
| 130 | return -1; | ||
| 131 | } | ||
| 132 | |||
| 133 | /* | ||
| 134 | Success only if tag verification passes. | ||
| 135 | */ | ||
| 136 | if (EVP_DecryptFinal_ex (cipher_ctx, plaintext + plaintext_len, &len) != 1) { | ||
| 137 | ERR_print_errors_fp (stderr); | ||
| 138 | return -1; | ||
| 139 | } | ||
| 140 | plaintext_len += len; | ||
| 141 | |||
| 142 | return plaintext_len; | ||
| 143 | } | ||
diff --git a/05/src/server.c b/05/src/server.c new file mode 100644 index 0000000..971117c --- /dev/null +++ b/05/src/server.c | |||
| @@ -0,0 +1,539 @@ | |||
| 1 | // server.c --- server component | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #include <stdlib.h> | ||
| 12 | #include <stdbool.h> | ||
| 13 | #include <stdio.h> | ||
| 14 | #include <string.h> | ||
| 15 | #include <errno.h> | ||
| 16 | #include <getopt.h> | ||
| 17 | #include <libgen.h> | ||
| 18 | #include <unistd.h> | ||
| 19 | #include <fcntl.h> | ||
| 20 | #include <sys/epoll.h> | ||
| 21 | #include <netinet/in.h> | ||
| 22 | #include <arpa/inet.h> | ||
| 23 | |||
| 24 | #define LOG(PRIORITY, FMT, ...) \ | ||
| 25 | syslog (LOG_MAKEPRI (LOG_DAEMON, LOG_##PRIORITY), \ | ||
| 26 | FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 27 | |||
| 28 | #include "utils.h" | ||
| 29 | #include "common.h" | ||
| 30 | #include "crypto.h" | ||
| 31 | #include "dynamic-array.h" | ||
| 32 | |||
| 33 | #define MAX_EVENTS 5 | ||
| 34 | |||
| 35 | static bool should_stop = false; | ||
| 36 | |||
| 37 | static bool salt = false; | ||
| 38 | static bool echo = false; | ||
| 39 | static bool check_integrity = false; | ||
| 40 | static bool bad_line = false; | ||
| 41 | static char *key_filename = NULL; | ||
| 42 | static enum key_kind key_kind = KK_PSK; | ||
| 43 | static aes_256_key key; | ||
| 44 | |||
| 45 | struct client { | ||
| 46 | struct client *prev; | ||
| 47 | struct client *next; | ||
| 48 | struct sockaddr_in sin; | ||
| 49 | aes_256_key key; | ||
| 50 | int fd; | ||
| 51 | enum client_state { | ||
| 52 | CS_READY, | ||
| 53 | CS_WAITING_FOR_PUBKEY, | ||
| 54 | } state; | ||
| 55 | }; | ||
| 56 | |||
| 57 | static struct client *clients = NULL; | ||
| 58 | static struct client *client_free_list = NULL; | ||
| 59 | |||
| 60 | static int epoll_fd; | ||
| 61 | |||
| 62 | void | ||
| 63 | accept_connections (int fd) | ||
| 64 | { | ||
| 65 | again: | ||
| 66 | if (client_free_list == NULL) | ||
| 67 | client_free_list = calloc (1, sizeof (*client_free_list)); | ||
| 68 | struct client *client = client_free_list; | ||
| 69 | |||
| 70 | socklen_t length = sizeof (client->sin); | ||
| 71 | client->fd = accept (fd, (struct sockaddr *) &client->sin, &length); | ||
| 72 | if (client->fd == -1) { | ||
| 73 | if (errno == EWOULDBLOCK) return; | ||
| 74 | ERROR ("Failed to accept connection: %s", strerror (errno)); | ||
| 75 | goto again; | ||
| 76 | } NOTICE ("Accepted connection from " SOCKADDR_IN_FMT, | ||
| 77 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 78 | |||
| 79 | if (fcntl (client->fd, F_SETFL, O_NONBLOCK) == -1) { | ||
| 80 | ERROR ("Failed to set nonblocking mode for client socket: %s", | ||
| 81 | strerror (errno)); | ||
| 82 | } | ||
| 83 | |||
| 84 | struct epoll_event event; | ||
| 85 | event.events = EPOLLIN | EPOLLWAKEUP; | ||
| 86 | event.data.ptr = client; | ||
| 87 | if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, client->fd, &event)) { | ||
| 88 | ERROR ("Failed to add file descriptor to epoll: %s", strerror (errno)); | ||
| 89 | close (client->fd); | ||
| 90 | goto again; | ||
| 91 | } | ||
| 92 | |||
| 93 | client_free_list = client_free_list->next; | ||
| 94 | if (clients) | ||
| 95 | clients->prev = client; | ||
| 96 | client->next = clients; | ||
| 97 | client->prev = NULL; | ||
| 98 | clients = client; | ||
| 99 | |||
| 100 | if (key_kind == KK_DHKX) { | ||
| 101 | write (client->fd, local_pubkey, sizeof (local_pubkey)); | ||
| 102 | client->state = CS_WAITING_FOR_PUBKEY; | ||
| 103 | } else { | ||
| 104 | client->state = CS_READY; | ||
| 105 | } | ||
| 106 | |||
| 107 | goto again; | ||
| 108 | } | ||
| 109 | |||
| 110 | void | ||
| 111 | close_connection (struct client *client) | ||
| 112 | { | ||
| 113 | INFO ("Connection closed " SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (client->sin)); | ||
| 114 | if (epoll_ctl (epoll_fd, EPOLL_CTL_DEL, client->fd, NULL)) | ||
| 115 | ERROR ("Failed to del file descriptor from epoll: %s", strerror (errno)); | ||
| 116 | close (client->fd); | ||
| 117 | |||
| 118 | if (client->prev) client->prev->next = client->next; | ||
| 119 | if (client->next) client->next->prev = client->prev; | ||
| 120 | if (client == clients) clients = client->next; | ||
| 121 | client->next = client_free_list; | ||
| 122 | client_free_list = client; | ||
| 123 | } | ||
| 124 | |||
| 125 | bool | ||
| 126 | send_to_plain (struct memory_view mv, struct client *to) | ||
| 127 | { | ||
| 128 | uint8_t buffer[MAX_PACKET_SIZE]; | ||
| 129 | memcpy (buffer, mv.data, mv.size); | ||
| 130 | size_t size = mv.size; | ||
| 131 | if (check_integrity) { | ||
| 132 | uint8_t hash[SHA_DIGEST_SIZE]; | ||
| 133 | sha1_hash (hash, mv); | ||
| 134 | if (bad_line) { | ||
| 135 | for (int i = 0; i < SHA_DIGEST_SIZE; ++i) | ||
| 136 | hash[i] += i; | ||
| 137 | } | ||
| 138 | memcpy (&buffer[size], hash, sizeof (hash)); | ||
| 139 | size += sizeof (hash); | ||
| 140 | } | ||
| 141 | |||
| 142 | again: | ||
| 143 | ssize_t bytes_written = write (to->fd, buffer, size); | ||
| 144 | if (bytes_written == -1) { | ||
| 145 | switch (errno) { | ||
| 146 | case EAGAIN: goto again; | ||
| 147 | default: | ||
| 148 | ERROR (SOCKADDR_IN_FMT ": write: %s", | ||
| 149 | SOCKADDR_IN_SPLIT (to->sin), strerror (errno)); | ||
| 150 | } return false; | ||
| 151 | } | ||
| 152 | |||
| 153 | if (bytes_written == 0) { | ||
| 154 | return false; | ||
| 155 | } | ||
| 156 | |||
| 157 | if ((size_t) bytes_written != size) { | ||
| 158 | ERROR (SOCKADDR_IN_FMT ": Failed to write whole buffer", | ||
| 159 | SOCKADDR_IN_SPLIT (to->sin)); | ||
| 160 | return false; | ||
| 161 | } | ||
| 162 | |||
| 163 | return true; | ||
| 164 | } | ||
| 165 | |||
| 166 | bool | ||
| 167 | send_to_encrypted (struct memory_view msg_mv, struct client *to) | ||
| 168 | { | ||
| 169 | static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; | ||
| 170 | struct packet *packet = (void *) buffer; | ||
| 171 | struct memory_span packet_ms = { | ||
| 172 | .data = packet->data, | ||
| 173 | .size = MAX_PACKET_SIZE - sizeof (packet->size), | ||
| 174 | }; | ||
| 175 | ssize_t size = | ||
| 176 | aes_256_cbc_encrypt (packet_ms, msg_mv, | ||
| 177 | key_kind == KK_PSK ? key : to->key, salt); | ||
| 178 | if (size == -1) | ||
| 179 | return false; | ||
| 180 | packet->size = size; | ||
| 181 | |||
| 182 | struct memory_view packet_mv = { | ||
| 183 | .data = (void *) packet, | ||
| 184 | .size = sizeof (packet->size) + packet->size, | ||
| 185 | }; | ||
| 186 | return send_to_plain (packet_mv, to); | ||
| 187 | } | ||
| 188 | |||
| 189 | bool | ||
| 190 | send_message_to (const struct message *msg, struct client *to) | ||
| 191 | { | ||
| 192 | INFO ("Sending message to " SOCKADDR_IN_FMT ": %.*s", | ||
| 193 | SOCKADDR_IN_SPLIT (to->sin), (int) msg->length, msg->data); | ||
| 194 | |||
| 195 | bool ret; | ||
| 196 | if (key_kind == KK_NONE) { | ||
| 197 | struct memory_view mv = { | ||
| 198 | .data = (void *) msg, | ||
| 199 | .size = sizeof (msg->length) + msg->length, | ||
| 200 | }; | ||
| 201 | ret = send_to_plain (mv, to); | ||
| 202 | } else { | ||
| 203 | struct memory_view mv = { | ||
| 204 | .data = (void *) msg->data, | ||
| 205 | .size = msg->length, | ||
| 206 | }; | ||
| 207 | ret = send_to_encrypted (mv, to); | ||
| 208 | } | ||
| 209 | |||
| 210 | INFO ("%s message to " SOCKADDR_IN_FMT, | ||
| 211 | ret ? "Sent" : "Failed to send", SOCKADDR_IN_SPLIT (to->sin)); | ||
| 212 | if (!ret) | ||
| 213 | close_connection (to); | ||
| 214 | |||
| 215 | return ret; | ||
| 216 | } | ||
| 217 | |||
| 218 | void | ||
| 219 | broadcast (const struct message *msg, const struct client *except) | ||
| 220 | { | ||
| 221 | struct client *next; | ||
| 222 | for (struct client *client = clients; client; client = next) { | ||
| 223 | if (client == except) | ||
| 224 | continue; | ||
| 225 | |||
| 226 | next = client->next; | ||
| 227 | send_message_to (msg, client); | ||
| 228 | } | ||
| 229 | } | ||
| 230 | |||
| 231 | // FIXME(cmmm): don't expect to read whole (and sole) packet at once... | ||
| 232 | bool | ||
| 233 | handle_client (struct client *client) | ||
| 234 | { | ||
| 235 | static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; | ||
| 236 | struct packet *packet = (void *) buffer; | ||
| 237 | |||
| 238 | again: | ||
| 239 | switch (client->state) { | ||
| 240 | case CS_READY: { | ||
| 241 | ssize_t bytes_read = read (client->fd, packet, sizeof (*packet)); | ||
| 242 | if (bytes_read == -1) { | ||
| 243 | switch (errno) { | ||
| 244 | case EAGAIN: return true; | ||
| 245 | default: | ||
| 246 | ERROR (SOCKADDR_IN_FMT ": read: %s", | ||
| 247 | SOCKADDR_IN_SPLIT (client->sin), strerror (errno)); | ||
| 248 | } return false; | ||
| 249 | } | ||
| 250 | |||
| 251 | if (bytes_read == 0) | ||
| 252 | return false; | ||
| 253 | |||
| 254 | if (bytes_read != sizeof (*packet)) { | ||
| 255 | ERROR ("Received malformed message from " SOCKADDR_IN_FMT, | ||
| 256 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 257 | DEBUG ("expected %lu, received %ld", sizeof (*packet), bytes_read); | ||
| 258 | return false; | ||
| 259 | } | ||
| 260 | |||
| 261 | bytes_read = read (client->fd, packet->data, packet->size); | ||
| 262 | if (bytes_read == -1) { | ||
| 263 | ERROR (SOCKADDR_IN_FMT ": read: %s", | ||
| 264 | SOCKADDR_IN_SPLIT (client->sin), strerror (errno)); | ||
| 265 | return false; | ||
| 266 | } | ||
| 267 | |||
| 268 | if (bytes_read == 0) | ||
| 269 | return false; | ||
| 270 | |||
| 271 | if ((size_t) bytes_read != packet->size) { | ||
| 272 | ERROR ("Received malformed message from " SOCKADDR_IN_FMT, | ||
| 273 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 274 | DEBUG ("expected %hhu, received %ld", packet->size, bytes_read); | ||
| 275 | return false; | ||
| 276 | } | ||
| 277 | |||
| 278 | if (check_integrity) { | ||
| 279 | uint8_t hash1[SHA_DIGEST_SIZE]; | ||
| 280 | uint8_t hash2[SHA_DIGEST_SIZE]; | ||
| 281 | |||
| 282 | bytes_read = read (client->fd, hash1, sizeof (hash1)); | ||
| 283 | if (bytes_read == -1) { | ||
| 284 | ERROR (SOCKADDR_IN_FMT ": read: %s", | ||
| 285 | SOCKADDR_IN_SPLIT (client->sin), strerror (errno)); | ||
| 286 | return false; | ||
| 287 | } | ||
| 288 | |||
| 289 | if (bytes_read == 0) | ||
| 290 | return false; | ||
| 291 | |||
| 292 | if ((size_t) bytes_read != sizeof (hash1)) { | ||
| 293 | ERROR ("Received malformed message from " SOCKADDR_IN_FMT, | ||
| 294 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 295 | DEBUG ("expected %lu, received %ld", sizeof (hash1), bytes_read); | ||
| 296 | return false; | ||
| 297 | } | ||
| 298 | |||
| 299 | struct memory_view mv = { | ||
| 300 | .data = (void *) packet, | ||
| 301 | .size = sizeof (*packet) + packet->size, | ||
| 302 | }; | ||
| 303 | sha1_hash (hash2, mv); | ||
| 304 | if (memcmp (hash1, hash2, SHA_DIGEST_SIZE) != 0) { | ||
| 305 | WARNING ("Received wrong hash from " SOCKADDR_IN_FMT, | ||
| 306 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 307 | goto again; | ||
| 308 | } | ||
| 309 | } | ||
| 310 | |||
| 311 | if (key_kind == KK_NONE) { | ||
| 312 | const struct message *msg = (void *) packet; | ||
| 313 | INFO ("Received plain text message from " SOCKADDR_IN_FMT ": %.*s", | ||
| 314 | SOCKADDR_IN_SPLIT (client->sin), (int) msg->length, msg->data); | ||
| 315 | broadcast (msg, echo ? NULL : client); | ||
| 316 | } else { | ||
| 317 | static struct message msg; | ||
| 318 | struct memory_span plain_ms = { | ||
| 319 | .data = (void *) &msg.data, | ||
| 320 | .size = sizeof (msg.data), | ||
| 321 | }; | ||
| 322 | struct memory_view enc_mv = { | ||
| 323 | .data = packet->data, | ||
| 324 | .size = packet->size, | ||
| 325 | }; | ||
| 326 | ssize_t size = | ||
| 327 | aes_256_cbc_decrypt (plain_ms, enc_mv, | ||
| 328 | key_kind == KK_PSK ? key : client->key, salt); | ||
| 329 | if (size == -1) { | ||
| 330 | ERROR ("Failed to decrypt received message from " SOCKADDR_IN_FMT, | ||
| 331 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 332 | return false; | ||
| 333 | } | ||
| 334 | msg.length = size; | ||
| 335 | INFO ("Received encrypted message from " SOCKADDR_IN_FMT ": %.*s", | ||
| 336 | SOCKADDR_IN_SPLIT (client->sin), (int) msg.length, msg.data); | ||
| 337 | broadcast (&msg, echo ? NULL : client); | ||
| 338 | } | ||
| 339 | |||
| 340 | } break; | ||
| 341 | case CS_WAITING_FOR_PUBKEY: { | ||
| 342 | if (read (client->fd, buffer, X25519_PUBKEY_LEN) != X25519_PUBKEY_LEN) { | ||
| 343 | ERROR ("Received public key of wrong size from " SOCKADDR_IN_FMT, | ||
| 344 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 345 | return false; | ||
| 346 | } | ||
| 347 | |||
| 348 | if (!hkdf_sha256 (buffer, client->key)) { | ||
| 349 | ERROR ("Failed to make shared key for " SOCKADDR_IN_FMT, | ||
| 350 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 351 | return false; | ||
| 352 | } | ||
| 353 | |||
| 354 | NOTICE ("Shared key established with " SOCKADDR_IN_FMT, | ||
| 355 | SOCKADDR_IN_SPLIT (client->sin)); | ||
| 356 | client->state = CS_READY; | ||
| 357 | return true; | ||
| 358 | } break; | ||
| 359 | default: break; | ||
| 360 | } | ||
| 361 | |||
| 362 | goto again; | ||
| 363 | } | ||
| 364 | |||
| 365 | void | ||
| 366 | usage (FILE *stream, const char *progname) | ||
| 367 | { | ||
| 368 | fprintf (stream, "Usage: %s [options] ADDR PORT\n", progname); | ||
| 369 | fprintf (stream, "\n"); | ||
| 370 | fprintf (stream, "Options:\n"); | ||
| 371 | fprintf (stream, " -h, --help display this help message and exit\n"); | ||
| 372 | fprintf (stream, " -e, --echo send messages to sender as well\n"); | ||
| 373 | fprintf (stream, " -k, --key FILENAME load symmetric key from FILENAME*\n"); | ||
| 374 | fprintf (stream, " -p, --plain don't use encryption*\n"); | ||
| 375 | fprintf (stream, " -x, --key-exchange use Diffi-Hellman key exchange*\n"); | ||
| 376 | fprintf (stream, " -c, --check-integrity use message integrity checking*\n"); | ||
| 377 | fprintf (stream, " -b, --bad-line sometimes send message with wrong hash\n"); | ||
| 378 | fprintf (stream, "\n"); | ||
| 379 | fprintf (stream, "Notes:\n"); | ||
| 380 | fprintf (stream, " Options marked with (*) must match the ones use by the clients!\n"); | ||
| 381 | fprintf (stream, "\n"); | ||
| 382 | } | ||
| 383 | |||
| 384 | void | ||
| 385 | test_aes_256_cbc (void) | ||
| 386 | { | ||
| 387 | const char *data = "Hello, World!"; | ||
| 388 | puts (data); | ||
| 389 | struct memory_view mv = { | ||
| 390 | .data = (void *) data, | ||
| 391 | .size = strlen (data), | ||
| 392 | }; | ||
| 393 | |||
| 394 | static uint8_t buffer[sizeof (struct packet) + MAX_PACKET_SIZE]; | ||
| 395 | struct memory_span ms = { | ||
| 396 | .data = buffer, | ||
| 397 | .size = sizeof (buffer), | ||
| 398 | }; | ||
| 399 | |||
| 400 | size_t size; | ||
| 401 | size = aes_256_cbc_encrypt (ms, mv, key, salt); | ||
| 402 | for (size_t i = 0; i < size; ++i) { | ||
| 403 | printf ("%02hhx ", ms.data[i]); | ||
| 404 | if ((i + 1) % 8 == 0) printf ("\n"); | ||
| 405 | } | ||
| 406 | |||
| 407 | mv.data = ms.data; | ||
| 408 | mv.size = ms.size; | ||
| 409 | size = aes_256_cbc_decrypt (ms, mv, key, salt); | ||
| 410 | printf ("%.*s\n", (int) ms.size, ms.data); | ||
| 411 | } | ||
| 412 | |||
| 413 | int | ||
| 414 | main (int argc, char *argv[]) | ||
| 415 | { | ||
| 416 | char *progname = argv[0]; | ||
| 417 | |||
| 418 | struct option longopts[] = { | ||
| 419 | { "help", no_argument, NULL, 'h' }, | ||
| 420 | { "echo", no_argument, NULL, 'e' }, | ||
| 421 | { "plain", no_argument, NULL, 'p' }, | ||
| 422 | { "key", required_argument, NULL, 'k' }, | ||
| 423 | { "salt", no_argument, NULL, 's' }, | ||
| 424 | { "key-exchange", no_argument, NULL, 'x' }, | ||
| 425 | { "check-integrity", no_argument, NULL, 'c' }, | ||
| 426 | { "bad-hash", no_argument, NULL, 'b' }, | ||
| 427 | {0} | ||
| 428 | }; | ||
| 429 | char ch; | ||
| 430 | while ((ch = getopt_long (argc, argv, ":hepk:sxcb", longopts, NULL)) != -1) { | ||
| 431 | switch (ch) { | ||
| 432 | case 'h': | ||
| 433 | usage (stdout, progname); | ||
| 434 | exit (EXIT_SUCCESS); | ||
| 435 | case 'e': echo = true; break; | ||
| 436 | case 'p': key_kind = KK_NONE; break; | ||
| 437 | case 'k': key_kind = KK_PSK; key_filename = optarg; break; | ||
| 438 | case 's': salt = true; break; | ||
| 439 | case 'x': key_kind = KK_DHKX; break; | ||
| 440 | case 'c': check_integrity = true; break; | ||
| 441 | case 'b': bad_line = true; break; | ||
| 442 | case '?': DIE ("unknown option %s", argv[optind - 1]); | ||
| 443 | case ':': DIE ("missing argument for %s", argv[optind - 1]); | ||
| 444 | default: DIE ("unexpected opt error"); | ||
| 445 | } | ||
| 446 | } | ||
| 447 | |||
| 448 | if (argc - optind != 2) { | ||
| 449 | usage (stderr, progname); | ||
| 450 | exit (EXIT_FAILURE); | ||
| 451 | } | ||
| 452 | |||
| 453 | setlogmask (LOG_UPTO (LOG_DEBUG)); | ||
| 454 | // openlog (basename (progname), LOG_PID | LOG_PERROR, LOG_DAEMON); | ||
| 455 | openlog (basename (progname), LOG_PERROR, LOG_DAEMON); | ||
| 456 | |||
| 457 | if (salt && key_kind == KK_NONE) | ||
| 458 | DIE ("Using --salt doesn't make sense with --plain"); | ||
| 459 | |||
| 460 | if (key_kind == KK_PSK) { | ||
| 461 | if (!key_filename) | ||
| 462 | DIE ("When using PSK (the default), you need to specify --key"); | ||
| 463 | |||
| 464 | if (!load_aes_256_key (key, key_filename)) | ||
| 465 | DIE ("Unable to load AES-256 key from '%s': %s", | ||
| 466 | key_filename, strerror (errno)); | ||
| 467 | } | ||
| 468 | |||
| 469 | const char *addr = argv[optind + 0]; | ||
| 470 | char *tail = NULL; | ||
| 471 | unsigned long int port = strtoul (argv[optind + 1], &tail, 10); | ||
| 472 | if (!tail || *tail != '\0') | ||
| 473 | DIE ("Failed to parse port"); | ||
| 474 | |||
| 475 | struct sockaddr_in sin = { | ||
| 476 | .sin_family = AF_INET, | ||
| 477 | .sin_port = htons (port), | ||
| 478 | }; | ||
| 479 | if (!inet_aton (addr, &sin.sin_addr)) | ||
| 480 | DIE ("Failed to convert address %s", addr); | ||
| 481 | |||
| 482 | if (!crypto_init ()) | ||
| 483 | DIE ("Failed to initialize crypto"); | ||
| 484 | |||
| 485 | epoll_fd = epoll_create1 (0); | ||
| 486 | if (epoll_fd == -1) | ||
| 487 | DIE ("Failed to create epoll file descriptor: %s", strerror (errno)); | ||
| 488 | |||
| 489 | int listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 490 | if (listener == -1) | ||
| 491 | DIE ("Failed to create socket: %s", strerror (errno)); | ||
| 492 | |||
| 493 | struct epoll_event event; | ||
| 494 | event.events = EPOLLIN | EPOLLWAKEUP; | ||
| 495 | event.data.ptr = NULL; | ||
| 496 | if (epoll_ctl (epoll_fd, EPOLL_CTL_ADD, listener, &event)) | ||
| 497 | DIE ("Failed to add file descriptor to epoll: %s", strerror (errno)); | ||
| 498 | |||
| 499 | int reuseaddr = 1; | ||
| 500 | setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, | ||
| 501 | &reuseaddr, sizeof (reuseaddr)); | ||
| 502 | |||
| 503 | if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) { | ||
| 504 | ERROR ("Failed to set nonblocking mode for listener socket: %s", | ||
| 505 | strerror (errno)); | ||
| 506 | } | ||
| 507 | |||
| 508 | if (bind (listener, (struct sockaddr *) &sin, sizeof (sin)) == -1) { | ||
| 509 | DIE ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s", | ||
| 510 | SOCKADDR_IN_SPLIT (sin), strerror (errno)); | ||
| 511 | } | ||
| 512 | |||
| 513 | if (listen (listener, 2)) { | ||
| 514 | DIE ("Failed to listen on "SOCKADDR_IN_FMT": %s", | ||
| 515 | SOCKADDR_IN_SPLIT (sin), strerror (errno)); | ||
| 516 | } NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (sin)); | ||
| 517 | |||
| 518 | NOTICE ("Server started..."); | ||
| 519 | while (!should_stop) { | ||
| 520 | DEBUG ("Polling..."); | ||
| 521 | struct epoll_event events[MAX_EVENTS]; | ||
| 522 | int event_count = epoll_wait (epoll_fd, events, MAX_EVENTS, -1); | ||
| 523 | DEBUG ("Got %d event%s", event_count, event_count > 1 ? "s" : ""); | ||
| 524 | for (int i = 0; i < event_count; ++i) { | ||
| 525 | if (events[i].data.ptr == NULL) { | ||
| 526 | accept_connections (listener); | ||
| 527 | continue; | ||
| 528 | } | ||
| 529 | |||
| 530 | if (!handle_client (events[i].data.ptr)) | ||
| 531 | close_connection (events[i].data.ptr); | ||
| 532 | } | ||
| 533 | } | ||
| 534 | |||
| 535 | NOTICE ("Server stopped..."); | ||
| 536 | return EXIT_SUCCESS; | ||
| 537 | } | ||
| 538 | |||
| 539 | // server.c ends here | ||
diff --git a/05/src/utils.h b/05/src/utils.h new file mode 100644 index 0000000..a17eed6 --- /dev/null +++ b/05/src/utils.h | |||
| @@ -0,0 +1,90 @@ | |||
| 1 | // utils.h --- utilities | ||
| 2 | // | ||
| 3 | // Copyright (c) 2026 Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | // Commentary: | ||
| 8 | // | ||
| 9 | // Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_UTILS_H | ||
| 12 | #define INCLUDED_UTILS_H | ||
| 13 | |||
| 14 | #include <stdarg.h> | ||
| 15 | #include <stdlib.h> | ||
| 16 | #include <stdio.h> | ||
| 17 | #include <assert.h> | ||
| 18 | #include <syslog.h> | ||
| 19 | |||
| 20 | #define STRINGIFY(ARG) #ARG | ||
| 21 | #define TO_STRING(ARG) STRINGIFY (ARG) | ||
| 22 | #define DEBUG( FMT, ...) \ | ||
| 23 | LOG (DEBUG, __FILE__ ":" TO_STRING (__LINE__) ": debug: %s: " FMT, __func__ __VA_OPT__ (,) __VA_ARGS__) | ||
| 24 | #define EMERGENCY(FMT, ...) LOG (EMERG, "emergency: " FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 25 | #define ALERT( FMT, ...) LOG (ALERT, "alert: " FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 26 | #define CRITICAL( FMT, ...) LOG (CRIT, "critical: " FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 27 | #define ERROR( FMT, ...) LOG (ERR, "error: " FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 28 | #define WARNING( FMT, ...) LOG (WARNING, "warning: " FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 29 | #define NOTICE( FMT, ...) LOG (NOTICE, "notice: " FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 30 | #define INFO( FMT, ...) LOG (INFO, "info: " FMT __VA_OPT__ (,) __VA_ARGS__) | ||
| 31 | |||
| 32 | #define DIE(FMT, ...) do { \ | ||
| 33 | EMERGENCY (FMT __VA_OPT__ (,) __VA_ARGS__); \ | ||
| 34 | exit (EXIT_FAILURE); \ | ||
| 35 | } while (0) | ||
| 36 | |||
| 37 | #define UNUSED(X) ((void) (X)) | ||
| 38 | #define UNREACHABLE() ASSERT (!"reached the unreachable...") | ||
| 39 | #define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__) | ||
| 40 | // #define TODO(...) | ||
| 41 | #define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__) | ||
| 42 | |||
| 43 | #define MALLOC malloc | ||
| 44 | #define REALLOC realloc | ||
| 45 | #define FREE free | ||
| 46 | #define ASSERT assert | ||
| 47 | |||
| 48 | #define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) | ||
| 49 | |||
| 50 | #define SOCKADDR_IN_FMT "%hhu.%hhu.%hhu.%hhu:%hu" | ||
| 51 | #define SOCKADDR_IN_SPLIT(ADDR) \ | ||
| 52 | ntohl ((ADDR).sin_addr.s_addr) >> 3*8, \ | ||
| 53 | ntohl ((ADDR).sin_addr.s_addr) >> 2*8, \ | ||
| 54 | ntohl ((ADDR).sin_addr.s_addr) >> 1*8, \ | ||
| 55 | ntohl ((ADDR).sin_addr.s_addr) >> 0*8, ntohs ((ADDR).sin_port) | ||
| 56 | |||
| 57 | inline uint8_t | ||
| 58 | log10u8 (uint8_t n) | ||
| 59 | { | ||
| 60 | return (n >= 100 ? 3 : | ||
| 61 | n >= 10 ? 2 : 1); | ||
| 62 | } | ||
| 63 | |||
| 64 | // read-only borrowed | ||
| 65 | struct memory_view { | ||
| 66 | const unsigned char *data; | ||
| 67 | size_t size; | ||
| 68 | }; | ||
| 69 | |||
| 70 | // writable borrowed | ||
| 71 | struct memory_span { | ||
| 72 | unsigned char *data; | ||
| 73 | size_t size; | ||
| 74 | }; | ||
| 75 | |||
| 76 | // writable owning | ||
| 77 | struct memory_buffer { | ||
| 78 | unsigned char *data; | ||
| 79 | size_t size; | ||
| 80 | }; | ||
| 81 | |||
| 82 | #define MEMORY_SPAN_TO_MEMORY_VIEW(MS) \ | ||
| 83 | ((struct memory_view) { \ | ||
| 84 | .data = (MS).data, \ | ||
| 85 | .size = (MS).size, \ | ||
| 86 | }) | ||
| 87 | |||
| 88 | #endif | ||
| 89 | |||
| 90 | // utils.h ends here | ||
diff --git a/README.org b/README.org new file mode 100644 index 0000000..b475872 --- /dev/null +++ b/README.org | |||
| @@ -0,0 +1,48 @@ | |||
| 1 | #+title: CVSS, DAC, MAC, nftables, OpenSSL | ||
| 2 | #+keywords: INFORMATION PROTECTION, THREAT BANK, BASIC VULNERABILITY VECTORS, AUTHENTICATION, AUTHORIZATION, PASSWORD HASHING, PASSWORD BRUTE FORCE, DISCRETIONARY ACCESS CONTROL (DAC), MANDATORY ACCESS CONTROL (MAC), BELL–LAPADULA MODEL, HARRISON–RUZZO–ULLMAN MODEL, FIREWALL, IPTABLES, NETWORK SECURITY, SYMMETRIC ENCRYPTION, CLIENT-SERVER APPLICATIONS, DATA INTEGRITY, HASH FUNCTIONS | ||
| 3 | #+date: 2026H1 | ||
| 4 | #+options: toc:nil | ||
| 5 | |||
| 6 | Keywords: {{{keyword(KEYWORDS)}}} | ||
| 7 | |||
| 8 | #+toc: headlines 2 | ||
| 9 | |||
| 10 | * Labs | ||
| 11 | :PROPERTIES: | ||
| 12 | :CUSTOM_ID: labs | ||
| 13 | :END: | ||
| 14 | ** Software vulnerability Analysis | ||
| 15 | Studying the structure of the "Threats" and "Vulnerabilities" sections | ||
| 16 | of the FSTEC RF database, searching and analyzing vulnerabilities | ||
| 17 | according to specified criteria. | ||
| 18 | |||
| 19 | ** Development and research of an authentication and authorization system | ||
| 20 | Development of access to confidential data, implementation and | ||
| 21 | research of password resistance to brute force attacks, taking into | ||
| 22 | account the length and hashing algorithms. | ||
| 23 | |||
| 24 | ** Implementation of models of discretionary and mandatory access control | ||
| 25 | Study and implementation of discretionary (DAC) and mandatory (MAC) | ||
| 26 | access control based on an authentication system, including models | ||
| 27 | Harrison-Ruzzo-Ullman and Bell-Lapadula. | ||
| 28 | |||
| 29 | ** Firewall | ||
| 30 | Exploration and configuration of the nftables firewall in Linux, | ||
| 31 | implementation of a specified access policy. | ||
| 32 | |||
| 33 | ** Client-server with encryption | ||
| 34 | Development of a client-server application that provides secure | ||
| 35 | messaging between clients and the server using symmetric encryption, | ||
| 36 | as well as data integrity control through hash functions. | ||
| 37 | |||
| 38 | * Documentation | ||
| 39 | :PROPERTIES: | ||
| 40 | :CUSTOM_ID: documentation | ||
| 41 | :END: | ||
| 42 | The exported report can be found at [[https://git.michalec.dev/files/uni/term-08/info-sec/lab-01-05/report.pdf][this link]]. | ||
| 43 | |||
| 44 | * Unlicense | ||
| 45 | :PROPERTIES: | ||
| 46 | :CUSTOM_ID: unlicense | ||
| 47 | :END: | ||
| 48 | #+include: UNLICENSE verse | ||
diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | This is free and unencumbered software released into the public domain. | ||
| 2 | |||
| 3 | Anyone is free to copy, modify, publish, use, compile, sell, or | ||
| 4 | distribute this software, either in source code form or as a compiled | ||
| 5 | binary, for any purpose, commercial or non-commercial, and by any | ||
| 6 | means. | ||
| 7 | |||
| 8 | In jurisdictions that recognize copyright laws, the author or authors | ||
| 9 | of this software dedicate any and all copyright interest in the | ||
| 10 | software to the public domain. We make this dedication for the benefit | ||
| 11 | of the public at large and to the detriment of our heirs and | ||
| 12 | successors. We intend this dedication to be an overt act of | ||
| 13 | relinquishment in perpetuity of all present and future rights to this | ||
| 14 | software under copyright law. | ||
| 15 | |||
| 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
| 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
| 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | ||
| 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | ||
| 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | ||
| 22 | OTHER DEALINGS IN THE SOFTWARE. | ||
| 23 | |||
| 24 | For more information, please refer to <https://unlicense.org/> | ||
diff --git a/doc/02-measurement.plt b/doc/02-measurement.plt new file mode 100644 index 0000000..4f8a61f --- /dev/null +++ b/doc/02-measurement.plt | |||
| @@ -0,0 +1,34 @@ | |||
| 1 | # -*- Gnuplot -*- | ||
| 2 | |||
| 3 | set term cairolatex pdf input \ | ||
| 4 | blacktext notransparent nocrop \ | ||
| 5 | size 15cm,10cm \ | ||
| 6 | noheader | ||
| 7 | |||
| 8 | set size ratio 0.66 | ||
| 9 | set lmargin at screen 0.1 | ||
| 10 | set rmargin at screen 0.9 | ||
| 11 | set bmargin at screen 0.1 | ||
| 12 | set tmargin at screen 0.9 | ||
| 13 | |||
| 14 | # set term x11 | ||
| 15 | |||
| 16 | set xlabel "Длина" | ||
| 17 | set ylabel "Время (с)" | ||
| 18 | set y2label "Кол-во итерации" | ||
| 19 | |||
| 20 | set format y '10^{%T}' | ||
| 21 | set format y2 '10^{%T}' | ||
| 22 | |||
| 23 | set y2tics | ||
| 24 | set ytics nomirror | ||
| 25 | |||
| 26 | set logscale y | ||
| 27 | set logscale y2 | ||
| 28 | set autoscale | ||
| 29 | |||
| 30 | plot '$datafile' using 1:2 with linespoints lw 5 pt 7 title "Время (с)", \ | ||
| 31 | '$datafile' using 1:3 with linespoints lw 5 pt 6 title "Кол-во итерации" axes x1y2 | ||
| 32 | exit | ||
| 33 | |||
| 34 | # script.plt ends here | ||
diff --git a/doc/biblio.bib b/doc/biblio.bib new file mode 100644 index 0000000..30b2edf --- /dev/null +++ b/doc/biblio.bib | |||
| @@ -0,0 +1,51 @@ | |||
| 1 | @online{FSTEC, | ||
| 2 | author = {ФСТЭК России}, | ||
| 3 | title = {Банк данных угроз безопасности информации}, | ||
| 4 | url = {https://bdu.fstec.ru}, | ||
| 5 | note = {Дата обращения: 25.02.2026}, | ||
| 6 | language = {russian}} | ||
| 7 | @manual{openssl, | ||
| 8 | title = {OpenSSL: Cryptography and SSL/TLS Toolkit}, | ||
| 9 | author = {{OpenSSL Project}}, | ||
| 10 | url = {https://www.openssl.org/}, | ||
| 11 | note = {Дата Обращения: 01.04.2026}} | ||
| 12 | @manual{openssl-docs, | ||
| 13 | title = {OpenSSL Documentation}, | ||
| 14 | author = {{OpenSSL Project}}, | ||
| 15 | url = {https://docs.openssl.org/}, | ||
| 16 | note = {Дата Обращения: 01.04.2026}} | ||
| 17 | @manual{readline, | ||
| 18 | title = {GNU Readline Library}, | ||
| 19 | author = {{Free Software Foundation}}, | ||
| 20 | url = {https://tiswww.case.edu/php/chet/readline/rltop.html}, | ||
| 21 | note = {Дата Обращения: 01.04.2026}} | ||
| 22 | @manual{readline-man, | ||
| 23 | title = {readline(3) --- GNU Readline Library Manual}, | ||
| 24 | author = {{GNU Project}}, | ||
| 25 | url = {https://man7.org/linux/man-pages/man3/readline.3.html}, | ||
| 26 | note = {Дата Обращения: 01.04.2026}} | ||
| 27 | @manual{ncurses, | ||
| 28 | title = {ncurses (New Curses Library)}, | ||
| 29 | author = {{Free Software Foundation}}, | ||
| 30 | url = {https://invisible-island.net/ncurses/}, | ||
| 31 | note = {Дата Обращения: 01.04.2026}} | ||
| 32 | @manual{ncurses-man, | ||
| 33 | title = {ncurses(3) --- Library for Text-Based User Interfaces}, | ||
| 34 | author = {{Linux Manual Pages Project}}, | ||
| 35 | url = {https://man7.org/linux/man-pages/man3/ncurses.3x.html}, | ||
| 36 | note = {Дата Обращения: 01.04.2026}} | ||
| 37 | @manual{nftables, | ||
| 38 | title = {nftables: Netfilter Packet Filtering Framework}, | ||
| 39 | author = {{Netfilter Project}}, | ||
| 40 | url = {https://netfilter.org/projects/nftables/}, | ||
| 41 | note = {Дата Обращения: 01.04.2026}} | ||
| 42 | @manual{nft-man, | ||
| 43 | title = {nft(8) --- Netfilter Rule Set Administration Tool}, | ||
| 44 | author = {{Linux Manual Pages Project}}, | ||
| 45 | url = {https://man7.org/linux/man-pages/man8/nft.8.html}, | ||
| 46 | note = {Дата Обращения: 01.04.2026}} | ||
| 47 | @manual{nftables-wiki, | ||
| 48 | title = {nftables Wiki}, | ||
| 49 | author = {{Netfilter Project}}, | ||
| 50 | url = {https://wiki.nftables.org/}, | ||
| 51 | note = {Дата Обращения: 01.04.2026}} \ No newline at end of file | ||
diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty new file mode 100644 index 0000000..dca60fa --- /dev/null +++ b/doc/gost/gost-7-32-bibliography.sty | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \def\UrlBreaks{\do\/\do-} | ||
| 4 | \RequirePackage{url} | ||
| 5 | |||
| 6 | \newdimen\bibindent | ||
| 7 | \renewenvironment{thebibliography}[1]{ | ||
| 8 | \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% | ||
| 9 | \list{\@biblabel{\@arabic\c@enumiv}}% | ||
| 10 | {\settowidth\labelwidth{\@biblabel{#1}}% | ||
| 11 | \leftmargin\labelwidth | ||
| 12 | \advance\leftmargin\labelsep | ||
| 13 | \@openbib@code | ||
| 14 | \usecounter{enumiv}% | ||
| 15 | \let\p@enumiv\@empty | ||
| 16 | \renewcommand\theenumiv{\@arabic\c@enumiv}}% | ||
| 17 | \sloppy\clubpenalty4000\widowpenalty4000% | ||
| 18 | \sfcode`\.\@m | ||
| 19 | }{ | ||
| 20 | \setcounter{totalbib}{\c@enumiv}% | ||
| 21 | \def\@noitemerr | ||
| 22 | {\@latex@warning{Empty `thebibliography' environment}}% | ||
| 23 | \endlist | ||
| 24 | } | ||
| 25 | \renewcommand\@biblabel{}% | ||
| 26 | \setlength\bibindent{1.5em} | ||
| 27 | |||
| 28 | % Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. | ||
| 29 | %\makeatletter | ||
| 30 | \renewcommand*{\@biblabel}[1]{\hfill#1.} | ||
| 31 | |||
| 32 | |||
| 33 | % | ||
| 34 | % Remove References header completely | ||
| 35 | % Stolen from original article.cls | ||
| 36 | % | ||
| 37 | \makeatletter | ||
| 38 | \renewenvironment{thebibliography}[1]{% | ||
| 39 | % \usection{\refname}% | ||
| 40 | % \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% | ||
| 41 | \list{\@biblabel{\@arabic\c@enumiv}}% | ||
| 42 | {\settowidth\labelwidth{\@biblabel{#1}}% | ||
| 43 | \leftmargin\labelwidth | ||
| 44 | \advance\leftmargin\labelsep | ||
| 45 | \@openbib@code | ||
| 46 | \usecounter{enumiv}% | ||
| 47 | \let\p@enumiv\@empty | ||
| 48 | \renewcommand\theenumiv{\@arabic\c@enumiv}}% | ||
| 49 | \sloppy | ||
| 50 | \clubpenalty4000 | ||
| 51 | \@clubpenalty \clubpenalty | ||
| 52 | \widowpenalty4000% | ||
| 53 | \sfcode`\.\@m} | ||
| 54 | {\def\@noitemerr | ||
| 55 | {\@latex@warning{Empty `thebibliography' environment}}% | ||
| 56 | \endlist} | ||
| 57 | \makeatother | ||
diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty new file mode 100644 index 0000000..bffd8e2 --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty | |||
| @@ -0,0 +1,33 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{caption} | ||
| 4 | \RequirePackage{subcaption} | ||
| 5 | \RequirePackage{capt-of} | ||
| 6 | |||
| 7 | % | ||
| 8 | % Table caption aligned to the left with dash as a separator | ||
| 9 | % | ||
| 10 | \captionsetup[table]{labelsep=endash, skip=0.5em, justification=centering, singlelinecheck=off} | ||
| 11 | |||
| 12 | % | ||
| 13 | % Dash as separator in figure caption and centering | ||
| 14 | % | ||
| 15 | \captionsetup[figure]{labelsep=endash, justification=centering} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Listing caption | ||
| 19 | % | ||
| 20 | \captionsetup[listing]{labelsep=endash, skip=0.5em, singlelinecheck=off, position=above} | ||
| 21 | |||
| 22 | \addto\captionsrussian{\renewcommand{\figurename}{Рис.}} | ||
| 23 | \addto\captionsrussian{\renewcommand{\lstlistingname}{Рис.}} | ||
| 24 | %% \addto\captionsrussian{\captionsetup[listing]{name=Рис.}} | ||
| 25 | |||
| 26 | %% NOTE(cmmm): breaks 'figure' counter | ||
| 27 | %% \makeatletter | ||
| 28 | %% \AtBeginDocument{% | ||
| 29 | %% \let\c@figure\c@listing | ||
| 30 | %% \let\thefigure\thelisting | ||
| 31 | %% \let\ftype@listing\ftype@figure | ||
| 32 | %% } | ||
| 33 | %% \makeatother | ||
diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..07c88af --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty | |||
| @@ -0,0 +1,43 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] | ||
| 2 | |||
| 3 | % | ||
| 4 | % Values for capital russian letters counter | ||
| 5 | % | ||
| 6 | \makeatletter | ||
| 7 | \newcommand\AlphRus[1]{% | ||
| 8 | \expandafter \@AlphRus \csname c@#1\endcsname | ||
| 9 | } | ||
| 10 | |||
| 11 | \newcommand\@AlphRus[1]{% | ||
| 12 | \ifcase #1% | ||
| 13 | \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or | ||
| 14 | Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or | ||
| 15 | Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% | ||
| 16 | \else \@ctrerr | ||
| 17 | \fi | ||
| 18 | } | ||
| 19 | \makeatother | ||
| 20 | |||
| 21 | % | ||
| 22 | % Values for lowercase russian letters counter | ||
| 23 | % | ||
| 24 | \makeatletter | ||
| 25 | \newcommand\alphRus[1]{% | ||
| 26 | \expandafter \@alphRus \csname c@#1\endcsname | ||
| 27 | } | ||
| 28 | |||
| 29 | \newcommand\@alphRus[1]{% | ||
| 30 | \ifcase #1% | ||
| 31 | \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or | ||
| 32 | л\or м\or н\or п\or р\or с\or т\or у\or ф\or | ||
| 33 | х\or ц\or ш\or щ\or э\or ю\or я% | ||
| 34 | \else \@ctrerr | ||
| 35 | \fi | ||
| 36 | } | ||
| 37 | \makeatother | ||
| 38 | |||
| 39 | % Increment figure counter when using lstlisting | ||
| 40 | \makeatletter | ||
| 41 | \let\c@lstlisting\c@figure | ||
| 42 | \let\ftype@listings\ftype@figure | ||
| 43 | \makeatother | ||
diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..4787abf --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty | |||
| @@ -0,0 +1,96 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{titlesec} | ||
| 4 | \RequirePackage{titling} | ||
| 5 | \RequirePackage{setspace} | ||
| 6 | |||
| 7 | \RequirePackage{gost-7-32-counters} | ||
| 8 | |||
| 9 | % | ||
| 10 | % Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection | ||
| 11 | % | ||
| 12 | \titleformat{\section}[block]{\centering\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} | ||
| 13 | \titlespacing*{\section}{0cm}{0cm}{0.5cm} | ||
| 14 | \newcommand{\sectionbreak}{\clearpage} | ||
| 15 | |||
| 16 | \titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{} | ||
| 17 | \titlespacing{\subsection}{0cm}{0.5cm}{0.5cm} | ||
| 18 | |||
| 19 | \titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent] | ||
| 20 | \titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm} | ||
| 21 | |||
| 22 | \titleformat{\paragraph}[runin]{\normalsize\bfseries}{\theparagraph}{0.5em}{}[\newline\indent] | ||
| 23 | \titlespacing{\paragraph}{1.25cm}{0.5em}{0cm} | ||
| 24 | |||
| 25 | % | ||
| 26 | % Make special headings, that have their own formatting rules: | ||
| 27 | % - centered | ||
| 28 | % - all-caps | ||
| 29 | % - bold | ||
| 30 | % | ||
| 31 | % Only three of them must appear in TOC: introduction, conclusion and references | ||
| 32 | % | ||
| 33 | \newcommand{\introduction}{ | ||
| 34 | \addcontentsline{toc}{section}{ВВЕДЕНИЕ} | ||
| 35 | \begin{center} | ||
| 36 | \bfseries\large | ||
| 37 | ВВЕДЕНИЕ | ||
| 38 | \end{center} | ||
| 39 | } | ||
| 40 | |||
| 41 | \newcommand{\conclusion}{ | ||
| 42 | \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} | ||
| 43 | \begin{center} | ||
| 44 | \bfseries\large | ||
| 45 | ЗАКЛЮЧЕНИЕ | ||
| 46 | \end{center} | ||
| 47 | } | ||
| 48 | |||
| 49 | \newcommand{\references}{ | ||
| 50 | \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} | ||
| 51 | \begin{center} | ||
| 52 | \bfseries\large | ||
| 53 | СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ | ||
| 54 | \end{center} | ||
| 55 | } | ||
| 56 | |||
| 57 | \newcommand{\essay}{ | ||
| 58 | \begin{center} | ||
| 59 | \bfseries\large | ||
| 60 | РЕФЕРАТ | ||
| 61 | \end{center} | ||
| 62 | } | ||
| 63 | |||
| 64 | \newcommand{\definitions}{ | ||
| 65 | \begin{center} | ||
| 66 | \bfseries\large | ||
| 67 | ОПРЕДЕЛЕНИЯ | ||
| 68 | \end{center} | ||
| 69 | } | ||
| 70 | |||
| 71 | \newcommand{\abbreviations}{ | ||
| 72 | \begin{center} | ||
| 73 | \bfseries\large | ||
| 74 | ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ | ||
| 75 | \end{center} | ||
| 76 | } | ||
| 77 | |||
| 78 | \newcommand{\defsabbrs}{ | ||
| 79 | \begin{center} | ||
| 80 | \bfseries\large | ||
| 81 | ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ | ||
| 82 | \end{center} | ||
| 83 | } | ||
| 84 | |||
| 85 | % | ||
| 86 | % Appendices headings. Appendices have autoincrementing number, | ||
| 87 | % that is represented with russian letter. | ||
| 88 | % This heading must appear in TOC | ||
| 89 | % | ||
| 90 | \newcounter{appendixcnt} | ||
| 91 | \setcounter{appendixcnt}{1} | ||
| 92 | |||
| 93 | \renewcommand{\appendix}[1]{ | ||
| 94 | \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} | ||
| 95 | \stepcounter{appendixcnt} | ||
| 96 | } | ||
diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..3b2a47e --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage[inline]{enumitem} | ||
| 4 | \RequirePackage{gost-7-32-counters} | ||
| 5 | |||
| 6 | \AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} | ||
| 7 | |||
| 8 | %% \setlist{nosep, labelindent=\parindent} | ||
| 9 | \setlist{nosep} | ||
| 10 | |||
| 11 | \setlist[itemize, 1]{label=\textendash} | ||
| 12 | \setlist[itemize, 2]{label=\textbullet} | ||
| 13 | \setlist[itemize, 3]{label=\textbullet} | ||
| 14 | |||
| 15 | \setlist[enumerate, 2]{label=\alphRus*)} | ||
| 16 | |||
| 17 | \newlist{displayitem}{itemize*}{1} | ||
| 18 | \setlist[displayitem]{ | ||
| 19 | before={\unskip:\newline\vspace*{\itemsep}\hspace*{\dimexpr\labelindent+\leftmargin-\labelsep-\labelwidth\relax}}, | ||
| 20 | itemjoin={;\newline\vspace*{\itemsep}\hspace*{\dimexpr\labelindent+\leftmargin-\labelsep-\labelwidth\relax}}, | ||
| 21 | label={\textendash}, | ||
| 22 | after={\unskip.\endgraf\noindent}, | ||
| 23 | } | ||
diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty new file mode 100644 index 0000000..c3954c3 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty | |||
| @@ -0,0 +1,31 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{booktabs} | ||
| 4 | \RequirePackage{xltabular} | ||
| 5 | \renewcommand\tabularxcolumn[1]{m{#1}} % for vertical centering text | ||
| 6 | |||
| 7 | % | ||
| 8 | % Center-aligned column with automatic width | ||
| 9 | % | ||
| 10 | \newcolumntype{C}{>{\centering\arraybackslash}X} | ||
| 11 | |||
| 12 | % | ||
| 13 | % Right-aligned column with automatic width | ||
| 14 | % | ||
| 15 | \newcolumntype{R}{>{\raggedleft\arraybackslash}X} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Table with designations | ||
| 19 | % | ||
| 20 | \newenvironment{designations}{ | ||
| 21 | \noindent | ||
| 22 | \tabularx{\textwidth}{@{} | ||
| 23 | >{\raggedright \arraybackslash \hsize=0.25\hsize}X | ||
| 24 | >{\centering \arraybackslash \hsize=0.05\hsize}X | ||
| 25 | >{\arraybackslash \hsize=0.70\hsize}X | ||
| 26 | } | ||
| 27 | }{ | ||
| 28 | \endtabularx | ||
| 29 | } | ||
| 30 | |||
| 31 | \newcommand{\designation}[2]{#1 &---& #2. \\} | ||
diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty new file mode 100644 index 0000000..328079d --- /dev/null +++ b/doc/gost/gost-7-32-toc.sty | |||
| @@ -0,0 +1,34 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{tocloft} | ||
| 4 | \RequirePackage[ | ||
| 5 | bookmarks=true, | ||
| 6 | colorlinks=true, | ||
| 7 | unicode=true, | ||
| 8 | urlcolor=black, | ||
| 9 | linkcolor=black, | ||
| 10 | anchorcolor=black, | ||
| 11 | citecolor=black, | ||
| 12 | menucolor=black, | ||
| 13 | filecolor=black, | ||
| 14 | hidelinks | ||
| 15 | ]{hyperref} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Set custom font styles | ||
| 19 | % | ||
| 20 | \renewcommand{\cftsecfont}{\normalfont} | ||
| 21 | \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} | ||
| 22 | \renewcommand{\cftsecpagefont}{\normalsize} | ||
| 23 | \renewcommand{\cftaftertoctitle}{\hfill\hfill} | ||
| 24 | \renewcommand{\cfttoctitlefont}{\hfill\normalfont\large\bfseries} | ||
| 25 | \titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} | ||
| 26 | \titlespacing{\tableofcontents}{0cm}{0cm}{1cm} | ||
| 27 | |||
| 28 | % | ||
| 29 | % Set indents and line spacing | ||
| 30 | % | ||
| 31 | \setlength{\cftbeforesecskip}{0cm} | ||
| 32 | \setlength{\cftbeforesubsecskip}{0cm} | ||
| 33 | \setlength{\cftbeforesubsubsecskip}{0cm} | ||
| 34 | \setlength{\cftbeforeparaskip}{0cm} | ||
diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls new file mode 100644 index 0000000..d5e9e2c --- /dev/null +++ b/doc/gost/gost-7-32.cls | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | \NeedsTeXFormat{LaTeX2e} | ||
| 2 | \ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] | ||
| 3 | |||
| 4 | % | ||
| 5 | % Supported font sizes: 12pt, 14pt | ||
| 6 | % | ||
| 7 | \DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 8 | \DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 9 | |||
| 10 | \ProcessOptions\relax | ||
| 11 | |||
| 12 | % | ||
| 13 | % Set A4 paper format | ||
| 14 | % | ||
| 15 | \LoadClass[a4paper]{extarticle} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Use 1.5 line spacing | ||
| 19 | % | ||
| 20 | \RequirePackage{setspace} | ||
| 21 | \singlespacing % or \setstretch{1} | ||
| 22 | |||
| 23 | % | ||
| 24 | % First paragraph indentation | ||
| 25 | % | ||
| 26 | \RequirePackage{indentfirst} | ||
| 27 | \setlength{\parindent}{12.5mm} | ||
| 28 | |||
| 29 | % | ||
| 30 | % Page margin | ||
| 31 | % | ||
| 32 | \RequirePackage[ | ||
| 33 | left=2.5cm, | ||
| 34 | right=2cm, | ||
| 35 | top=2cm, | ||
| 36 | bottom=2cm, | ||
| 37 | footskip=1cm, | ||
| 38 | ]{geometry} | ||
| 39 | |||
| 40 | % | ||
| 41 | % Use TMR-like font | ||
| 42 | % | ||
| 43 | \RequirePackage{fontspec} | ||
| 44 | \RequirePackage{xunicode} | ||
| 45 | \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} | ||
| 46 | \setmainfont{Times New Roman} | ||
| 47 | |||
| 48 | % | ||
| 49 | % Use russian language | ||
| 50 | % | ||
| 51 | \RequirePackage[main=russian, english]{babel} | ||
| 52 | |||
| 53 | % | ||
| 54 | % gost-7-32 packages | ||
| 55 | % | ||
| 56 | \RequirePackage{gost-7-32-headings} | ||
| 57 | \RequirePackage{gost-7-32-toc} | ||
| 58 | \RequirePackage{gost-7-32-lists} | ||
| 59 | \RequirePackage{gost-7-32-bibliography} | ||
| 60 | \RequirePackage{gost-7-32-captions} | ||
| 61 | \RequirePackage{gost-7-32-tables} | ||
diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..3fa36b1 --- /dev/null +++ b/doc/ox-init.el | |||
| @@ -0,0 +1,146 @@ | |||
| 1 | ;;; ox-init.el --- Initialization script for async org exprort session | ||
| 2 | ;;; Commentary: | ||
| 3 | ;;; Code: | ||
| 4 | |||
| 5 | ;; (org-babel-do-load-languages | ||
| 6 | ;; 'org-babel-load-languages | ||
| 7 | ;; '((latex . t))) | ||
| 8 | |||
| 9 | (add-to-list 'load-path "/home/cmmm/.config/emacs/elpaca/builds/org") | ||
| 10 | (add-to-list 'load-path "/home/cmmm/.config/emacs/elpaca/builds/org-contrib") | ||
| 11 | |||
| 12 | (setenv "TEXINPUTS" "./:./gost/:") | ||
| 13 | |||
| 14 | (setq org-latex-remove-logfiles nil) | ||
| 15 | |||
| 16 | (setq org-export-default-language "ru") | ||
| 17 | |||
| 18 | (setq org-latex-default-packages-alist nil) | ||
| 19 | |||
| 20 | (setq org-latex-toc-include-unnumbered t) | ||
| 21 | |||
| 22 | (setq org-latex-tables-booktabs t) | ||
| 23 | |||
| 24 | (setq org-latex-caption-above '(table)) | ||
| 25 | |||
| 26 | (setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" | ||
| 27 | "%bib %b" | ||
| 28 | "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) | ||
| 29 | |||
| 30 | (setq org-latex-classes '(("spbstu-report" "\\documentclass[14pt]{spbstu-report}" | ||
| 31 | ("\\section{%s}" . "\\section*{%s}") | ||
| 32 | ("\\subsection{%s}" . "\\subsection*{%s}") | ||
| 33 | ("\\subsubsection{%s}" . "\\subsubsection*{%s}") | ||
| 34 | ("\\paragraph{%s}" . "\\paragraph*{%s}") | ||
| 35 | ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) | ||
| 36 | |||
| 37 | (require 'ox-extra) | ||
| 38 | (ox-extras-activate '(ignore-headlines)) | ||
| 39 | |||
| 40 | ;; (setq org-latex-src-block-backend 'minted) | ||
| 41 | (setq org-latex-src-block-backend 'listings) | ||
| 42 | (setq org-latex-listings-options '(("numbers" "left"))) | ||
| 43 | |||
| 44 | (require 'oc-bibtex) | ||
| 45 | (setq org-latex-bib-compiler "biber") | ||
| 46 | |||
| 47 | ;; TODO(cmmm): add \addlinespace between rows which don't have 'rule | ||
| 48 | ;; TODO(cmmm): wrap head columns in something like: | ||
| 49 | ;; \multicolumn{1}{c}{\bold head1} | ||
| 50 | (defun cmmm-org-latex-table-row (table-row contents info) | ||
| 51 | "Transcode a TABLE-ROW element from Org to LaTeX. | ||
| 52 | CONTENTS is the contents of the row. INFO is a plist used as | ||
| 53 | a communication channel." | ||
| 54 | (let* ((attr (org-export-read-attribute :attr_latex | ||
| 55 | (org-element-parent table-row))) | ||
| 56 | (booktabsp (if (plist-member attr :booktabs) (plist-get attr :booktabs) | ||
| 57 | (plist-get info :latex-tables-booktabs))) | ||
| 58 | (longtablep | ||
| 59 | (member (or (plist-get attr :environment) | ||
| 60 | (plist-get info :latex-default-table-environment)) | ||
| 61 | ;; adding xltabular is the only change | ||
| 62 | '("longtable" "longtabu" "xltabular")))) | ||
| 63 | (if (eq (org-element-property :type table-row) 'rule) | ||
| 64 | (cond | ||
| 65 | ((not booktabsp) "\\hline") | ||
| 66 | ((not (org-export-get-previous-element table-row info)) "\\toprule") | ||
| 67 | ((not (org-export-get-next-element table-row info)) "\\bottomrule") | ||
| 68 | ((and longtablep | ||
| 69 | (org-export-table-row-ends-header-p | ||
| 70 | (org-export-get-previous-element table-row info) info)) | ||
| 71 | "") | ||
| 72 | (t "\\midrule")) | ||
| 73 | ;; Memorize table header in case it is multiline. We need this | ||
| 74 | ;; information to define contents before "\\endhead" in longtable environments. | ||
| 75 | (when (org-export-table-row-in-header-p table-row info) | ||
| 76 | (let ((table-head-cache (plist-get info :org-latex-table-head-cache))) | ||
| 77 | (unless (hash-table-p table-head-cache) | ||
| 78 | (setq table-head-cache (make-hash-table :test #'eq)) | ||
| 79 | (plist-put info :org-latex-table-head-cache table-head-cache)) | ||
| 80 | (if-let* ((head-contents (gethash (org-element-parent table-row) table-head-cache))) | ||
| 81 | (puthash (org-element-parent table-row) (concat head-contents "\\\\\n" contents) | ||
| 82 | table-head-cache) | ||
| 83 | (puthash (org-element-parent table-row) contents table-head-cache)))) | ||
| 84 | ;; Return LaTeX string as the transcoder. | ||
| 85 | (concat | ||
| 86 | ;; When BOOKTABS are activated enforce top-rule even when no | ||
| 87 | ;; hline was specifically marked. | ||
| 88 | (and booktabsp (not (org-export-get-previous-element table-row info)) | ||
| 89 | "\\toprule\n") | ||
| 90 | contents "\\\\" | ||
| 91 | (and booktabsp (org-export-get-previous-element table-row info) | ||
| 92 | "\\addlinespace") | ||
| 93 | "\n" | ||
| 94 | (cond | ||
| 95 | ;; Special case for long tables. Define header and footers. | ||
| 96 | ((and longtablep (org-export-table-row-ends-header-p table-row info)) | ||
| 97 | (let ((columns (cdr (org-export-table-dimensions | ||
| 98 | (org-element-lineage table-row 'table) info)))) | ||
| 99 | (format "%s | ||
| 100 | \\endfirsthead | ||
| 101 | \\multicolumn{%d}{l}{%s} \\\\ | ||
| 102 | %s | ||
| 103 | %s \\\\\n | ||
| 104 | %s | ||
| 105 | \\endhead | ||
| 106 | %s\\multicolumn{%d}{r}{%s} \\\\ | ||
| 107 | \\endfoot | ||
| 108 | \\endlastfoot" | ||
| 109 | (if booktabsp "\\midrule" "\\hline") | ||
| 110 | columns | ||
| 111 | (org-latex--translate "Continued from previous page" info) | ||
| 112 | (cond | ||
| 113 | ((not (org-export-table-row-starts-header-p table-row info)) | ||
| 114 | "") | ||
| 115 | (booktabsp "\\toprule\n") | ||
| 116 | (t "\\hline\n")) | ||
| 117 | (gethash (org-element-parent table-row) (plist-get info :org-latex-table-head-cache)) | ||
| 118 | (if booktabsp "\\midrule" "\\hline") | ||
| 119 | (if booktabsp "\\midrule" "\\hline") | ||
| 120 | columns | ||
| 121 | (org-latex--translate "Continued on next page" info)))) | ||
| 122 | ;; When BOOKTABS are activated enforce bottom rule even when | ||
| 123 | ;; no hline was specifically marked. | ||
| 124 | ((and booktabsp (not (org-export-get-next-element table-row info))) | ||
| 125 | "\\bottomrule")))))) | ||
| 126 | (advice-add 'org-latex-table-row :override 'cmmm-org-latex-table-row) | ||
| 127 | |||
| 128 | (defun cmmm-org-export-translate (s encoding info) | ||
| 129 | "Translate string S according to language specification. | ||
| 130 | |||
| 131 | ENCODING is a symbol among `:ascii', `:html', `:latex', `:latin1' | ||
| 132 | and `:utf-8'. INFO is a plist used as a communication channel. | ||
| 133 | |||
| 134 | Translation depends on `:language' property. Return the | ||
| 135 | translated string. If no translation is found, try to fall back | ||
| 136 | to `:default' encoding. If it fails, return S." | ||
| 137 | (let* ((lang (plist-get info :language)) | ||
| 138 | (translations (cdr (assoc lang | ||
| 139 | (cdr (assoc s org-export-dictionary)))))) | ||
| 140 | (or (plist-get translations encoding) | ||
| 141 | (plist-get translations :default) | ||
| 142 | (plist-get translations :utf-8) | ||
| 143 | s))) | ||
| 144 | (advice-add 'org-export-translate :override 'cmmm-org-export-translate) | ||
| 145 | |||
| 146 | ;;; ox-init.el ends here | ||
diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..5112749 --- /dev/null +++ b/doc/report.org | |||
| @@ -0,0 +1,2222 @@ | |||
| 1 | #+title: Практические работы | ||
| 2 | #+author: Михалец М. | ||
| 3 | #+date: 2026 | ||
| 4 | #+keywords: ЗАЩИТА ИНФОРМАЦИИ | ||
| 5 | #+keywords: БАНК УГРОЗ | ||
| 6 | #+keywords: БАЗОВЫЕ ВЕКТОРА УЯЗВИМОСТЕЙ | ||
| 7 | #+latex_header: \group{5130201/20101} | ||
| 8 | #+latex_header: \reportof{О ВЫПОЛНЕНИИ ПРАКТИЧЕСКИХ РАБОТ} | ||
| 9 | #+latex_header: \subject{по дисциплине «Защита информации»} | ||
| 10 | #+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}} | ||
| 11 | #+latex_header: \institute{Институт компьютерных наук и кибербезопасности} | ||
| 12 | #+latex_header: \school{Высшая школа технологии искусственного интеллекта} | ||
| 13 | #+latex_header: \direction{02.03.01 Математика и компьютерные науки} | ||
| 14 | #+latex_header: \reviewertitle{}\reviewer{Силиненко А.В.} | ||
| 15 | #+latex_header: \city{Санкт-Петербург} | ||
| 16 | |||
| 17 | #+setupfile: setup.org | ||
| 18 | #+latex: \sloppy | ||
| 19 | |||
| 20 | * РЕФЕРАТ | ||
| 21 | :PROPERTIES: | ||
| 22 | :UNNUMBERED: notoc | ||
| 23 | :END: | ||
| 24 | Михалец М. Практические работы по дисциплине «Защита информации». -- | ||
| 25 | СПб.: СПбГПУ, 2026. -- @@latex:\pageref{LastPage}@@ с, рис. -- | ||
| 26 | @@latex:\totalfigures@@, табл. -- @@latex:\totaltables@@, библиогр. -- | ||
| 27 | @@latex:\totalbibitems@@ назв. | ||
| 28 | |||
| 29 | #+latex: \bigbreak | ||
| 30 | |||
| 31 | ЗАЩИТА ИНФОРМАЦИИ, БАНК УГРОЗ, БАЗОВЫЕ ВЕКТОРА УЯЗВИМОСТЕЙ, | ||
| 32 | АУТЕНТИФИКАЦИЯ, АВТОРИЗАЦИЯ, ХЭШИРОВАНИЕ ПАРОЛЕЙ, ПЕРЕБОР ПАРОЛЕЙ, | ||
| 33 | ДИСКРЕЦИОННОЕ УПРАВЛЕНИЕ ДОСТУПОМ (DAC), МАНДАТНОЕ УПРАВЛЕНИЕ ДОСТУПОМ | ||
| 34 | (MAC), МОДЕЛЬ БЕЛЛА–ЛАПАДУЛЫ, МОДЕЛЬ ХАРРИСОНА–РУЗЗО–УЛЬМАНА, | ||
| 35 | МЕЖСЕТЕВОЕ ЭКРАНИРОВАНИЕ, IPTABLES, СЕТЕВАЯ БЕЗОПАСНОСТЬ, СИММЕТРИЧНОЕ | ||
| 36 | ШИФРОВАНИЕ, КЛИЕНТ-СЕРВЕРНЫЕ ПРИЛОЖЕНИЯ, ЦЕЛОСТНОСТЬ ДАННЫХ, | ||
| 37 | ХЭШ-ФУНКЦИИ | ||
| 38 | |||
| 39 | #+latex: \bigbreak | ||
| 40 | |||
| 41 | Отчет содержит информацию о проделанной работе по дисциплине «защита | ||
| 42 | информации», которая включает в себя следующие задания: | ||
| 43 | 1. Анализ уязвимостей программного обеспечения --- Изучение структуры | ||
| 44 | разделов «Угрозы» и «Уязвимости» банка данных ФСТЭК РФ, поиск и | ||
| 45 | анализ уязвимостей по заданным критериям. | ||
| 46 | 2. Разработка и исследование системы аутентификации и авторизации --- | ||
| 47 | Разработка доступа к конфиденциальным данным, реализация и | ||
| 48 | исследование стойкости паролей к атаке методом грубой силы с учётом | ||
| 49 | длины и алгоритмов хэширования. | ||
| 50 | 3. Реализация моделей дискреционного и мандатного управления доступом | ||
| 51 | --- изучение и реализация дискреционного (DAC) и мандатного (MAC) | ||
| 52 | управления доступом на базе системы аутентификации, включая модели | ||
| 53 | Харрисона-Руззо-Ульмана и Белла-Лападулы. | ||
| 54 | 4. Межсетевое экранирование --- изучение и настройка межсетевого | ||
| 55 | экрана (iptables или аналога) в ОС Linux/MacOS, реализация заданной | ||
| 56 | политики доступа. | ||
| 57 | 5. Клиент-сервер с шифрованием --- Разработка клиент-серверного | ||
| 58 | приложения, обеспечивающего защищённый обмен сообщениями между | ||
| 59 | клиентами и сервером с применением симметричного шифрования, а | ||
| 60 | также контроль целостности данных посредством хэш-функций. | ||
| 61 | |||
| 62 | #+latex: \clearpage | ||
| 63 | #+toc: headlines 3 | ||
| 64 | |||
| 65 | * Термины и определения | ||
| 66 | :PROPERTIES: | ||
| 67 | :UNNUMBERED: toc | ||
| 68 | :END: | ||
| 69 | В настоящем отчете применяют следующие термины с соответствующими | ||
| 70 | определениями: | ||
| 71 | #+name: terms | ||
| 72 | #+caption: Термины и определения | ||
| 73 | #+attr_latex: :placement [H] :float nil :environment xltabular :width \textwidth :align m{4.5cm}X | ||
| 74 | | *Термин* | *Определение* | | ||
| 75 | |------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | ||
| 76 | | Информация | Сведения о лицах, предметах, фактах, событиях, явлениях и процессах независимо от формы их представления. | | ||
| 77 | | Свойства Безопасности информации | Конфиденциальность, Целостность, Доступность. | | ||
| 78 | | Угроза | Потенциально возможное событие, действие или фактор (внешний или внутренний), способный нарушить конфиденциальность, целостность или доступность данных, нанеся ущерб информационным системам или пользователям. | | ||
| 79 | | Риск | Критерий угрозы - вероятность реализации угрозы, использующей уязвимости информационных активов, что приводит к ущербу: нарушению конфиденциальности, целостности или доступности данных. | | ||
| 80 | | Банк угроз | официальный общедоступный ресурс, содержащий систематизированный перечень уязвимостей, угроз, способов их реализации и объектов воздействия в информационных системах. | | ||
| 81 | | ФСТЭК | Федеральная служба по техническому и экспортному контролю. | | ||
| 82 | | Программное обеспечение | Совокупность программ, процедур, правил, документации и данных, необходимых для функционирования систем обработки информации. | | ||
| 83 | | Операционная система | Совокупность программ, обеспечивающих управление ресурсами ЭВМ и взаимодействие пользователя с машиной. | | ||
| 84 | | CWE (Common Weakness Enumeration) | Международная система классификации недостатков, дефектов и уязвимостей в программном и аппаратном обеспечении | | ||
| 85 | | Наличие эксплойта | Специальная программа, фрагмент кода или последовательность команд, использующие уязвимости (ошибки, слабые места) в программном обеспечении (ПО) или операционных системах для проведения атаки. | | ||
| 86 | | CVSS 2.0 (Common Vulnerability Scoring System, v2.0) | Вторая версия открытого стандарта для оценки серьезности уязвимостей IT-систем | | ||
| 87 | | CVSS 3.0 (Common Vulnerability Scoring System, v3.0) | Третья версия открытого стандарта для оценки серьезности уязвимостей IT-систем | | ||
| 88 | | Аутентификация | Процесс установления подлинности пользователя или устройства с помощью пароля, ключа или другого идентификатора. | | ||
| 89 | | Авторизация | Процесс установления доступа пользователя к ресурсам системы с помощью аутентификации. | | ||
| 90 | | Хэширование | Процесс преобразования данных в хеш-значение. | | ||
| 91 | | Слабый пароль | Пароль, который легко угадать или подобрать. | | ||
| 92 | | Дискреционная модель | Модель, в которой доступ к ресурсам определяется правами пользователя. | | ||
| 93 | | Мандатная модель | Модель, в которой доступ к ресурсам определяется уровнем доступа пользователя. | | ||
| 94 | | Уровень доступа | Уровень, определяющий права пользователя на доступ к ресурсам системы. | | ||
| 95 | | Уровень конфиденциальности | Уровень, определяющий степень секретности информации. | | ||
| 96 | | MAC | Mondatory Access Control. | | ||
| 97 | | DAC | Discretionary Access Control. | | ||
| 98 | | DNS | Domain Name System - система преобразования доменных имён в IP-адреса. | | ||
| 99 | | HTTP | HyperText Transfer Protocol - протокол прикладного уровня передачи данных в сети (порт 80). | | ||
| 100 | | HTTPS | HTTP Secure - защищённая версия HTTP с шифрованием TLS/SSL (порт 443). | | ||
| 101 | | ICMP | Internet Control Message Protocol - протокол сетевого уровня для служебных сообщений (ping, уведомления об ошибках). | | ||
| 102 | | TCP | Transmission Control Protocol - транспортный протокол с установлением соединения и надёжной доставкой. | | ||
| 103 | | UDP | User Datagram Protocol - транспортный протокол без установления соединения. | | ||
| 104 | | Мэжсетевой экран (МЭ) | Программное или программно-аппаратное средство фильтрации сетевого трафика между сетями или сегментами. | | ||
| 105 | | tcpdump | Утилита для перехвата и отображения сетевых пакетов, проходящих через сетевые интерфейсы. | | ||
| 106 | | iptables | Механизм ядра Linux для фильтрации пакетов, NAT и управления сетевым трафиком. | | ||
| 107 | | loopback | Виртуальный сетевой интерфейс для локального обмена данными (адрес 127.0.0.1). | | ||
| 108 | | anchors | Якоря в pf - отдельные файлы с правилами, подключаемые к основной конфигурации. | | ||
| 109 | | Симметричное шифрование | Шифрование, в котором используется один и тот же ключ для шифрования и расшифрования данных. | | ||
| 110 | | Асимметричное шифрование | Шифрование, в котором используются два разных ключа для шифрования и расшифрования данных. | | ||
| 111 | | Клиент-серверное приложение | Приложение, в котором клиент и сервер взаимодействуют друг с другом. | | ||
| 112 | |||
| 113 | * Анализ уязвимостей программного обеспечения | ||
| 114 | ** ВВЕДЕНИЕ | ||
| 115 | :PROPERTIES: | ||
| 116 | :UNNUMBERED: toc | ||
| 117 | :END: | ||
| 118 | Анализ уязвимостей программного обеспечения (ПО) — это процесс | ||
| 119 | выявления недостатков в ПО, которые могут привести к угрозам | ||
| 120 | безопасности информационной системы (см. табл. [[terms]]). | ||
| 121 | |||
| 122 | Под уязвимостью понимается «слабое» место в ПО, которое может быть | ||
| 123 | использовано злоумышленником для получения несанкционированного | ||
| 124 | доступа, проведения атак или установления контроля над | ||
| 125 | информацией. Проведение анализа уязвимостей направлено на | ||
| 126 | предупреждение потенциальных угроз и устранение уже существующих | ||
| 127 | проблем в области информационной безопасности. | ||
| 128 | |||
| 129 | Цель данной работы заключается в приобретении практических навыков | ||
| 130 | работы с Банком данных угроз Федеральной службы по техническому и | ||
| 131 | экспортному контролю (ФСТЭК России [cite:@FSTEC]). | ||
| 132 | |||
| 133 | Банк угроз содержит сведения об уязвимостях программного обеспечения, | ||
| 134 | а также о способах их эксплуатации. В рамках данной работы необходимо | ||
| 135 | изучить структуру Банка данных угроз и освоить методы поиска | ||
| 136 | уязвимостей для используемой операционной системы персонального | ||
| 137 | компьютера и мобильного устройства. | ||
| 138 | |||
| 139 | ** Постановка задачи | ||
| 140 | #+latex: \noindent | ||
| 141 | *Цели работы:* получить навыки работы с банком данных ФСТЭК РФ, | ||
| 142 | содержащих сведения об угрозах безопасности и уязвимостях | ||
| 143 | [cite:@FSTEC]. | ||
| 144 | |||
| 145 | #+latex: \bigbreak\noindent | ||
| 146 | *Задачи работы:* | ||
| 147 | - знакомство со структурой раздела «Угрозы» банка данных угроз | ||
| 148 | безопасности информации ФСТЭК РФ (далее – Банк угроз). | ||
| 149 | - знакомство со структурой раздела «Уязвимости» Банка угроз. | ||
| 150 | - поиск информации в разделе Уязвимости Банка угроз по заданным | ||
| 151 | критериям. | ||
| 152 | |||
| 153 | ** Раздел «Угрозы» | ||
| 154 | Раздел «Угрозы» содержит информацию о различных аспектах, связанных с | ||
| 155 | угрозами безопасности информации. В нем представлена классификация | ||
| 156 | угроз по их природе, воздействию и потенциальным последствиям. Каждая | ||
| 157 | угроза сопровождается подробным описанием методов атаки, целей и | ||
| 158 | уязвимостей, которые могут использовать злоумышленники. Для оценки | ||
| 159 | степени серьезности воздействия предусмотрен параметр уровня | ||
| 160 | опасности. Раздел также включает рекомендации по защите, которые | ||
| 161 | помогут определить меры для предотвращения или минимизации угроз. | ||
| 162 | |||
| 163 | В разделе доступна фильтрация данных по: | ||
| 164 | - контекстному поиску; | ||
| 165 | - источнику угрозы; | ||
| 166 | - последствиям реализации угрозы, которые включают: | ||
| 167 | - нарушение конфиденциальности; | ||
| 168 | - нарушение целостности; | ||
| 169 | - нарушение доступности. | ||
| 170 | |||
| 171 | Ниже на рис. [[01-threat]], представлен снимок экрана раздела угроз: | ||
| 172 | #+name: 01-threat | ||
| 173 | #+caption: Раздел угроз | ||
| 174 | #+attr_latex: :placement [H] :width \textwidth | ||
| 175 | [[./res/01/threat.png]] | ||
| 176 | |||
| 177 | ** Раздел «Уязвимости» | ||
| 178 | Раздел «Список уязвимостей» представляет собой перечень потенциальных | ||
| 179 | недостатков или уязвимых точек в ПО, аппаратуре или информационных | ||
| 180 | системах, которые могут быть использованы злоумышленниками для | ||
| 181 | нарушения свойств безопасности информации (см. табл. [[terms]]). | ||
| 182 | |||
| 183 | Основное отличие между уязвимостью и угрозой заключается в том, что | ||
| 184 | уязвимость — это недостаток в ПО (или системе), а угроза — это риск | ||
| 185 | того, что злоумышленники воспользуются этой уязвимостью. | ||
| 186 | |||
| 187 | То есть уязвимость существует независимо, а угроза является условной. | ||
| 188 | |||
| 189 | Уязвимости классифицируются по ряду критериев: | ||
| 190 | - Классификация уязвимости — отнесение уязвимости к конкретному | ||
| 191 | классу, например, в ФСТЭК классы могут быть следующими: уязвимость | ||
| 192 | кода, уязвимость архитектуры и многофакторная уязвимость; | ||
| 193 | - Год добавления — дата, когда уязвимость была обнаружена и добавлена | ||
| 194 | в банк угроз; | ||
| 195 | - Уровень опасности — делится на 4 типа: Низкий, Средний, Высокий, | ||
| 196 | Критический; | ||
| 197 | - Идентификатор типа ошибки — идентификатор, соответствующий общему | ||
| 198 | перечню ошибок CWE (см. табл. [[terms]]); | ||
| 199 | - Наличие эксплойта (см. табл. [[terms]]) — может быть в наличии, в | ||
| 200 | открытом доступе, отсутствовать или уточняться; | ||
| 201 | - Способ эксплуатации — описание угрозы, которая возникает при | ||
| 202 | эксплуатации уязвимости (например, SQL-инъекция); | ||
| 203 | - Способ устранения — меры для устранения уязвимости, например, | ||
| 204 | обновление ПО или организационные мероприятия; | ||
| 205 | - Операционная система — операционная система, в которой обнаружена | ||
| 206 | уязвимость в программном обеспечении. | ||
| 207 | |||
| 208 | Наиболее опасной уязвимостью в ФСТЭК считается возможность выполнения | ||
| 209 | злоумышленником произвольных команд. | ||
| 210 | |||
| 211 | Это можно увидеть, применив сортировку уязвимостей (см. рис. [[01-vul]]) | ||
| 212 | по уровню опасности (критичности), как было описано ранее: | ||
| 213 | #+name: 01-vul | ||
| 214 | #+caption: Сортировка уязвимостей по критичности | ||
| 215 | #+attr_latex: :placement [H] :width \textwidth | ||
| 216 | [[./res/01/vul.png]] | ||
| 217 | |||
| 218 | В разделе «Уязвимости» также есть подраздел «Инфографика», который | ||
| 219 | предоставляет возможность визуально оценить следующие данные: | ||
| 220 | - Количество уязвимостей в ПО различных производителей (см. рис. | ||
| 221 | [[01-info-1]]) | ||
| 222 | - Распределение уязвимостей по уровням опасности (см. рис. [[01-info-2]]) | ||
| 223 | - Распределение уязвимостей по типам ПО (см. рис. [[01-info-3]]) | ||
| 224 | - Количество критических уязвимостей в ПО различных производителей | ||
| 225 | (см. рис. [[01-info-4]]) | ||
| 226 | - Распределение уязвимостей по уровням опасности (см. рис. [[01-info-5]]) | ||
| 227 | - Распределение уязвимостей по типам ошибок (см. рис. [[01-info-6]]) | ||
| 228 | - Количество уязвимостей программного обеспечения различных | ||
| 229 | производителей, связанных с инцидентами информационной безопасности | ||
| 230 | (см. рис. [[01-info-7]]) | ||
| 231 | |||
| 232 | Ниже перечислены все инфографики описанные выше: | ||
| 233 | #+name: 01-info-1 | ||
| 234 | #+caption: Количество уязвимостей в ПО различных производителей | ||
| 235 | #+attr_latex: :placement [H] :width \textwidth | ||
| 236 | [[./res/01/info-1.png]] | ||
| 237 | |||
| 238 | Как видно из рис. [[01-info-1]], количество уязвимостей больше наблюдается | ||
| 239 | у сообщества свободного программного обеспечения. Вероятно это | ||
| 240 | связано с тем, что это не большие компании, где нет отдельных | ||
| 241 | специалистов обеспечивающих должную защиту информации. | ||
| 242 | |||
| 243 | #+name: 01-info-2 | ||
| 244 | #+caption: Распределение уязвимостей по уровням опасности | ||
| 245 | #+attr_latex: :placement [H] :width \textwidth | ||
| 246 | [[./res/01/info-2.png]] | ||
| 247 | |||
| 248 | Из рис. [[01-info-2]], видно что больше всего уязвимостей имеют средний | ||
| 249 | уровень опасности. | ||
| 250 | |||
| 251 | #+name: 01-info-3 | ||
| 252 | #+caption: Распределение уязвимостей по типам ПО | ||
| 253 | #+attr_latex: :placement [H] :width \textwidth | ||
| 254 | [[./res/01/info-3.png]] | ||
| 255 | |||
| 256 | Наиболее уязвимый тип ПО - является операционная система (см. рис. | ||
| 257 | [[01-info-3]]), что обусловлено тем, что ОС - довольно объемное и сложно | ||
| 258 | программное обеспечение. | ||
| 259 | |||
| 260 | #+name: 01-info-4 | ||
| 261 | #+caption: Количество критических уязвимостей в ПО различных производителей | ||
| 262 | #+attr_latex: :placement [H] :width \textwidth | ||
| 263 | [[./res/01/info-4.png]] | ||
| 264 | |||
| 265 | Так же как и в случае с общим количеством уязвимостей (см. рис. | ||
| 266 | [[01-info-1]]), количество критических уязвимостей больше у сообщества | ||
| 267 | свободного программного обеспечение (см. рис. [[01-info-4]]). | ||
| 268 | |||
| 269 | #+name: 01-info-5 | ||
| 270 | #+caption: Распределение уязвимостей по уровням опасности | ||
| 271 | #+attr_latex: :placement [H] :width \textwidth | ||
| 272 | [[./res/01/info-5.png]] | ||
| 273 | |||
| 274 | Наиболее частым уровнем опасности средний-высокий (см. рис. | ||
| 275 | [[01-info-6]]). | ||
| 276 | |||
| 277 | #+name: 01-info-6 | ||
| 278 | #+caption: Распределение уязвимостей по типам ошибок | ||
| 279 | #+attr_latex: :placement [H] :width \textwidth | ||
| 280 | [[./res/01/info-6.png]] | ||
| 281 | |||
| 282 | Наиболее частая уязвимость по типу ошибки - CWE-119 (см. рис. | ||
| 283 | [[01-info-6]]). CWE-119 - это ошибка связанная с неправильным | ||
| 284 | ограничением операций в границах буфера памяти. | ||
| 285 | |||
| 286 | #+name: 01-info-7 | ||
| 287 | #+caption: Количество уязвимостей ПО производителей, связанных с инцидентами ИБ | ||
| 288 | #+attr_latex: :placement [H] :width \textwidth | ||
| 289 | [[./res/01/info-7.png]] | ||
| 290 | |||
| 291 | Из производителей, с наиболее частыми инцидентами в сфере ИБ является | ||
| 292 | Microsoft Corp. На втором месте сообщество свободного программного | ||
| 293 | обеспечения. | ||
| 294 | |||
| 295 | Из крупных производителей стоит так же отметить Google, который | ||
| 296 | расположился на 7-ом месте, Apple inc. расположена на 15 месте. | ||
| 297 | |||
| 298 | В списке так же присутствуют компании занимающиеся в основном | ||
| 299 | разработкой дестрибутивов Linux. (см. рис. [[01-info-7]]). | ||
| 300 | |||
| 301 | ** Проверка собственной операционной системы | ||
| 302 | В практической работе №1, так же необходимо выполнить анализ | ||
| 303 | уязвимостей операционной системы используемого ноутбука и смартфона. | ||
| 304 | |||
| 305 | *** Описание аппаратного обеспечения | ||
| 306 | В качестве используемых аппаратных средств: | ||
| 307 | 1. Ноутбук --- Lenovo ThinkPad x230 16ГБ/1ТБ: | ||
| 308 | - Процессор: Intel(R) Core(TM) i5-3320M CPU @ 2.60GHz; | ||
| 309 | - Архитектура: x86_64; | ||
| 310 | - Архитектура памяти: UMA; | ||
| 311 | - Название дистрибутива GNU/Linux: Void Linux; | ||
| 312 | - Версия ядра Linux: 6.12.68_1; | ||
| 313 | - Статус релиза ядра: LTS. | ||
| 314 | 2. Смартфон --- Pixel 9 Pro 64ГБ/128ГБ: | ||
| 315 | - Архитектура: ARMv9-A; | ||
| 316 | - Имя ОС: GrapheneOS; | ||
| 317 | - Версия Android: 16; | ||
| 318 | - Android security update: Febuary 5, 2026; | ||
| 319 | - Baseband version: g5400c-250908-251105-B-14386369, | ||
| 320 | g5400c-250908-251105-B-14386369; | ||
| 321 | - Kernel version: 6.1.162-android14-11-g4d32cd6f478f #1 Thu Feb 12 | ||
| 322 | 19:19:27 UTC 2026; | ||
| 323 | - Build number: 2026021201; | ||
| 324 | - Статус релиза: Stable. | ||
| 325 | |||
| 326 | *** Поиск уязвимостей ОС ноутбука | ||
| 327 | Для поиска уязвимостей операционной системы ноутбука, необходимо | ||
| 328 | указать в поисковике слудющую информацию: | ||
| 329 | - Тип ПО: Операционная система; | ||
| 330 | - Программное обеспечение: Linux; | ||
| 331 | - Аппаратная платформа: 64-bit; | ||
| 332 | - Уровень опасности: Критический. | ||
| 333 | |||
| 334 | По постановке задачи данной работы, требуется выявить критические | ||
| 335 | уязвимости ПО. Если критические уязвимости не найдены, ищуться | ||
| 336 | уязвимости высокой опасности, если нет высокой опасности, средние | ||
| 337 | иначе низкие. | ||
| 338 | |||
| 339 | Найдено 105 уязвимостей, из которых лишь одна критического уровня. Но | ||
| 340 | все эти уязвимости уже исправлены в моей версии ядра. Самые критичные | ||
| 341 | из них представлены на рис. [[01-notebook]] | ||
| 342 | |||
| 343 | #+name: 01-notebook | ||
| 344 | #+caption: 5 самый критических уязвымостей | ||
| 345 | #+attr_latex: :placement [H] :width \textwidth | ||
| 346 | [[./res/01/notebook.png]] | ||
| 347 | |||
| 348 | Более подробное описание уязвимости критического уровня представлено в | ||
| 349 | [[#BDU:2016-00545][ПРИЛОЖЕНИЙ А]], а одной уязвимости высокого уровня в [[#BDU:2016-00545][ПРИЛОЖЕНИЙ Б]]. | ||
| 350 | |||
| 351 | Ниже представленны табл. [[01-cvss2]] и [[01-cvss3]], где перечислены все | ||
| 352 | метрики векторов уязвимостей для CVSS 2.0 и CVSS 3.0 (см. табл. [[terms]]) | ||
| 353 | соответственно, с пояснением: | ||
| 354 | |||
| 355 | #+name: 01-cvss2 | ||
| 356 | #+caption: Метрики вектора уязвимости CVSS 2.0 | ||
| 357 | #+attr_latex: :placement [H] :environment tabularx :width \textwidth :font \small :align cm{3.5cm}X | ||
| 358 | | *Аббревиатура* | *Расшифровка* | *Значения и смысл* | | ||
| 359 | |--------------+--------------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------| | ||
| 360 | | AV | Access Vector (вектор доступа) | *Local (L)* – локальный доступ; *Adjacent Network (A)* – доступ из смежной сети; *Network (N)* – сетевой доступ. Определяет способ взаимодействия с системой. | | ||
| 361 | | AC | Access Complexity (сложность доступа) | *High (H)* – высокая; *Medium (M)* – средняя; *Low (L)* – низкая. Характеризует условия, необходимые для эксплуатации. | | ||
| 362 | | Au | Authentication (аутентификация) | *Multiple (M)* – множественная; *Single (S)* – единственная; *None (N)* – не требуется. Указывает на необходимость подтверждения подлинности. | | ||
| 363 | | C | Confidentiality Impact (влияние на конфиденциальность) | *None (N)* – отсутствует; *Partial (P)* – частичное; *Complete (C)* – полное. Степень раскрытия информации. | | ||
| 364 | | I | Integrity Impact (влияние на целостность) | *None (N)* – отсутствует; *Partial (P)* – частичное; *Complete (C)* – полное. Возможность искажения данных. | | ||
| 365 | | A | Availability Impact (влияние на доступность) | *None (N)* – отсутствует; *Partial (P)* – частичное; *Complete (C)* – полное. Степень нарушения доступности сервиса. | | ||
| 366 | |||
| 367 | #+name: 01-cvss3 | ||
| 368 | #+caption: Метрики вектора уязвимости CVSS 3.0 | ||
| 369 | #+attr_latex: :placement [H] :environment tabularx :width \textwidth :font \small :align cm{3.5cm}X | ||
| 370 | | *Аббревиатура* | *Расшифровка* | *Значения и смысл* | | ||
| 371 | |--------------+--------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------| | ||
| 372 | | AV | Attack Vector (вектор атаки) | *Network (N)* – сетевой; *Adjacent (A)* – из смежной сети; *Local (L)* – локальный; *Physical (P)* – физический. Отражает удалённость атаки. | | ||
| 373 | | AC | Attack Complexity (сложность атаки) | *Low (L)* – низкая; *High (H)* – высокая. Наличие условий вне контроля атакующего. | | ||
| 374 | | PR | Privileges Required (необходимые привилегии) | *None (N)* – не требуются; *Low (L)* – низкие; *High (H)* – высокие. Уровень прав доступа до атаки. | | ||
| 375 | | UI | User Interaction (взаимодействие с пользователем) | *None (N)* – не требуется; *Required (R)* – требуется. Участие другого лица в успешной атаке. | | ||
| 376 | | S | Scope (область действия) | *Unchanged (U)* – не изменяется; *Changed (C)* – изменяется. Возможность воздействия на другие компоненты. | | ||
| 377 | | C | Confidentiality Impact (влияние на конфиденциальность) | *High (H)* – высокое; *Low (L)* – низкое; *None (N)* – отсутствует. Степень потери конфиденциальности. | | ||
| 378 | | I | Integrity Impact (влияние на целостность) | *High (H)* – высокое; *Low (L)* – низкое; *None (N)* – отсутствует. Возможность модификации данных. | | ||
| 379 | | A | Availability Impact (влияние на доступность) | *High (H)* – высокое; *Low (L)* – низкое; *None (N)* – отсутствует. Степень нарушения доступности. | | ||
| 380 | |||
| 381 | Для более детального анализа, стоит расмотреть базойвый вектор | ||
| 382 | уязвимости каждой уязвимости: | ||
| 383 | - BDU:2016-00545: | ||
| 384 | - CVSS 2.0: AV:N/AC:L/Au:N/C:C/I:C/A:C (Оценка 10) | ||
| 385 | - CVSS 3.0: - | ||
| 386 | - CVSS 4.0: - | ||
| 387 | - BDU:2020-02250: | ||
| 388 | - CVSS 2.0: AV:L/AC:L/Au:N/C:N/I:P/A:C (Оценка 5,6) | ||
| 389 | - CVSS 3.0: AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:H (Оценка 6,1) | ||
| 390 | - CVSS 4.0: - | ||
| 391 | |||
| 392 | Более подробный анализ каждого вектора: | ||
| 393 | - *BDU:2016‑00545* | ||
| 394 | - *CVSS 2.0* | ||
| 395 | - *AV* -- способ получения доступа: *N* -- сетевой | ||
| 396 | - *AC* -- сложность получения доступа: *L* -- низкая | ||
| 397 | - *Au* -- аутентификация: *N* -- не требуется | ||
| 398 | - *C* -- влияние на конфиденциальность: *C* -- полное | ||
| 399 | - *I* -- влияние на целостность: *C* -- полное | ||
| 400 | - *A* -- влияние на доступность: *C* -- полное | ||
| 401 | - /Чтение:/ «Эта уязвимость может быть использована *удалённо через | ||
| 402 | сеть без каких‑либо требований по аутентификации*, её | ||
| 403 | эксплуатация *простая*, и она приводит к *полной потере | ||
| 404 | конфиденциальности, целостности и доступности* системы.» | ||
| 405 | - *BDU:2020‑02250* | ||
| 406 | - *CVSS 2.0* | ||
| 407 | - *AV* -- способ получения доступа: *L* -- локальный | ||
| 408 | - *AC* -- сложность получения доступа: *L* -- низкая | ||
| 409 | - *Au* -- аутентификация: *N* -- не требуется | ||
| 410 | - *C* -- влияние на конфиденциальность: *N* -- нет | ||
| 411 | - *I* -- влияние на целостность: *P* -- частичное | ||
| 412 | - *A* -- влияние на доступность: *C* -- полное | ||
| 413 | - /Чтение:/ «Эта уязвимость требует *локального доступа* и её | ||
| 414 | эксплуатация *простая*; она *не влияет на конфиденциальность*, но | ||
| 415 | может привести к *частичному нарушению целостности* и *полной | ||
| 416 | потере доступности* системы.» | ||
| 417 | - *CVSS 3.0* | ||
| 418 | - *AV* -- способ получения доступа: *L* -- локальный | ||
| 419 | - *AC* -- сложность получения доступа: *L* -- низкая | ||
| 420 | - *PR* -- привилегии: *L* -- низкие | ||
| 421 | - *UI* -- взаимодействие с пользователем: *N* -- не требуется | ||
| 422 | - *S* -- область воздействия: *U* -- без изменения | ||
| 423 | - *C* -- влияние на конфиденциальность: *N* -- нет | ||
| 424 | - *I* -- влияние на целостность: *L* -- низкое | ||
| 425 | - *A* -- влияние на доступность: *H* -- высокое | ||
| 426 | - /Чтение:/ «Для эксплуатации требуется *локальный доступ* и *низкие | ||
| 427 | привилегии*, *не требуется взаимодействие с пользователем*; | ||
| 428 | уязвимость *не влияет на конфиденциальность*, но вызывает | ||
| 429 | *незначительное нарушение целостности* и *серьёзное нарушение | ||
| 430 | доступности* системы.» | ||
| 431 | |||
| 432 | *** Поиск уязвимостей ОС смартфона | ||
| 433 | Для поиска уязвимостей операционной системы смартфона, необходимо | ||
| 434 | указать в поисковике слудющую информацию: | ||
| 435 | - Тип ПО: Операционная система; | ||
| 436 | - Программное обеспечение: Android; | ||
| 437 | - Версия ПО: Android 16; | ||
| 438 | - Уровень опасности: Критический. | ||
| 439 | |||
| 440 | На рисунке [[01-smartphone]], видно что для операционной системы Android | ||
| 441 | 16, существуют уязвимости критического уровня, которых довольно много | ||
| 442 | (113 критических уязвимостей). | ||
| 443 | |||
| 444 | #+name: 01-smartphone | ||
| 445 | #+caption: 5 самый критических уязвымостей | ||
| 446 | #+attr_latex: :placement [H] :width \textwidth | ||
| 447 | [[./res/01/smartphone.png]] | ||
| 448 | |||
| 449 | Возьмем первую и третью из отсортированных по критичности: | ||
| 450 | - BDU:2026-00776; | ||
| 451 | - BDU:2025-15021. | ||
| 452 | |||
| 453 | BDU:2026-00005, позволяет злоумышленнику повысить свои привилегии, а | ||
| 454 | BDU:2025-15412, связанна с недостаточной защитой служебных данных, | ||
| 455 | которая может позволить злоумышленнику вызвать отказ в обслуживании. | ||
| 456 | |||
| 457 | Более подробное описание этих двух уязвимостей представлено в | ||
| 458 | [[#BDU:2026-00776][ПРИЛОЖЕНИЙ В]], и [[#BDU:2025-15021][ПРИЛОЖЕНИЙ Г]]. | ||
| 459 | |||
| 460 | Так же опишем их базовые вектора уязвимостей: | ||
| 461 | - BDU:2026-00776: | ||
| 462 | - CVSS 2.0: AV:N/AC:L/Au:N/C:C/I:C/A:C | ||
| 463 | - CVSS 3.0: AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H | ||
| 464 | - CVSS 4.0: - | ||
| 465 | - BDU:2025-15021: | ||
| 466 | - CVSS 2.0: AV:N/AC:L/Au:N/C:C/I:C/A:C | ||
| 467 | - CVSS 3.0: AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H | ||
| 468 | - CVSS 4.0: - | ||
| 469 | |||
| 470 | Более подробный анализ каждого вектора: | ||
| 471 | - *BDU:2026‑00776* | ||
| 472 | - *CVSS 2.0* | ||
| 473 | - *AV* -- способ получения доступа: *N* -- сетевой | ||
| 474 | - *AC* -- сложность получения доступа: *L* -- низкая | ||
| 475 | - *Au* -- аутентификация: *N* -- не требуется | ||
| 476 | - *C* -- влияние на конфиденциальность: *C* -- полное | ||
| 477 | - *I* -- влияние на целостность: *C* -- полное | ||
| 478 | - *A* -- влияние на доступность: *C* -- полное | ||
| 479 | - /Чтение:/ «Эта уязвимость может быть *эксплуатирована удалённо | ||
| 480 | через сеть без входа*, эксплуатация *простая*, и она приводит к | ||
| 481 | *полной потере конфиденциальности, целостности и доступности* | ||
| 482 | системы.» | ||
| 483 | - *CVSS 3.0* | ||
| 484 | - *AV* -- способ получения доступа: *N* -- сетевой | ||
| 485 | - *AC* -- сложность получения доступа: *L* -- низкая | ||
| 486 | - *PR* -- привилегии: *N* -- не требуются | ||
| 487 | - *UI* -- взаимодействие с пользователем: *N* -- не требуется | ||
| 488 | - *S* -- область воздействия: *U* -- без изменения | ||
| 489 | - *C* -- влияние на конфиденциальность: *H* -- высокое | ||
| 490 | - *I* -- влияние на целостность: *H* -- высокое | ||
| 491 | - *A* -- влияние на доступность: *H* -- высокое | ||
| 492 | - /Чтение:/ «Эта уязвимость может быть *эксплуатирована через сеть | ||
| 493 | без каких‑либо требований к привилегиям и без участия | ||
| 494 | пользователя*, при этом она оказывает *высокое влияние на | ||
| 495 | конфиденциальность, целостность и доступность* системы.» | ||
| 496 | - *BDU:2025‑15021* | ||
| 497 | - *CVSS 2.0* | ||
| 498 | - *AV* -- способ получения доступа: *N* -- сетевой | ||
| 499 | - *AC* -- сложность получения доступа: *L* -- низкая | ||
| 500 | - *Au* -- аутентификация: *N* -- не требуется | ||
| 501 | - *C* -- влияние на конфиденциальность: *C* -- полное | ||
| 502 | - *I* -- влияние на целостность: *C* -- полное | ||
| 503 | - *A* -- влияние на доступность: *C* -- полное | ||
| 504 | - /Чтение:/ «Эта уязвимость может быть *эксплуатирована удалённо по | ||
| 505 | сети без входа*, эксплуатация *простая* и приводит к *полной потере | ||
| 506 | конфиденциальности, целостности и доступности* системы.» | ||
| 507 | - *CVSS 3.0* | ||
| 508 | - *AV* -- способ получения доступа: *N* -- сетевой | ||
| 509 | - *AC* -- сложность получения доступа: *L* -- низкая | ||
| 510 | - *PR* -- привилегии: *N* -- не требуются | ||
| 511 | - *UI* -- взаимодействие с пользователем: *N* -- не требуется | ||
| 512 | - *S* -- область воздействия: *C* -- с изменением | ||
| 513 | - *C* -- влияние на конфиденциальность: *H* -- высокое | ||
| 514 | - *I* -- влияние на целостность: *H* -- высокое | ||
| 515 | - *A* -- влияние на доступность: *H* -- высокое | ||
| 516 | - /Чтение:/ «Эта уязвимость может быть *эксплуатирована через сеть | ||
| 517 | без требований к привилегиям и без участия пользователя*, и она | ||
| 518 | оказывает *высокое влияние на конфиденциальность, целостность и | ||
| 519 | доступность* системы с возможным расширением области | ||
| 520 | воздействия.» | ||
| 521 | |||
| 522 | ** ЗАКЛЮЧЕНИЕ | ||
| 523 | :PROPERTIES: | ||
| 524 | :UNNUMBERED: toc | ||
| 525 | :END: | ||
| 526 | В ходе выполнения практической работы №1, был изучен Банк угроз ФСТЭК, | ||
| 527 | в котором были выявлены уязвимости для имеющихся операционных систем | ||
| 528 | ноутбука (Void Linux) и смартфона (Android 16). В ходе исследования | ||
| 529 | уязвимостей, было выявлено, что операционная система Void Linux, | ||
| 530 | достаточно хорошо защищена, так как были найденные уязвимости только | ||
| 531 | достаточно старых версии ядра Linux. | ||
| 532 | |||
| 533 | Так же было выявлено, что Android довольно уязвима операционная | ||
| 534 | система. Были выявлены критические уязвимости, связанные с полным | ||
| 535 | нарушением безопасности информации, а именно влияние на | ||
| 536 | конфиденциальность, целостность и доступность. Одна из уязвимостей, | ||
| 537 | была в том, что злоумышленник мог получить повысить свои привилегии, | ||
| 538 | другая же, уязвимостей была связана с недостаточной защитой служебных | ||
| 539 | данных, что позволяло злоумышленнику вызвать отказ в обслуживании. | ||
| 540 | |||
| 541 | * Разработка и исследование системы аутентификации и авторизации | ||
| 542 | ** ВВЕДЕНИЕ | ||
| 543 | :PROPERTIES: | ||
| 544 | :UNNUMBERED: toc | ||
| 545 | :END: | ||
| 546 | Одним из базовых инструментов защиты информации от | ||
| 547 | несанкционированного доступа выступает аутентификация --- процедура | ||
| 548 | подтверждения подлинности субъекта на основе предъявленного им | ||
| 549 | идентификатора. В рамках дисциплины «Защита информации» анализ | ||
| 550 | механизмов аутентификации и авторизации формирует системное | ||
| 551 | представление о принципах разграничения доступа к конфиденциальным | ||
| 552 | данным. | ||
| 553 | |||
| 554 | Актуальность исследования определяется необходимостью оценки | ||
| 555 | устойчивости различных методов хэширования паролей с учётом их длины и | ||
| 556 | уровня сложности. Проблема использования слабых паролей по-прежнему | ||
| 557 | остаётся одной из наиболее распространённых уязвимостей как в | ||
| 558 | корпоративных, так и в частных информационных системах. Исследование | ||
| 559 | эффективности атак методом полного перебора (brute force) на пароли, | ||
| 560 | хэшированные с применением алгоритма SHA-1, позволяет установить | ||
| 561 | зависимость времени компрометации от уровня их стойкости. | ||
| 562 | |||
| 563 | В работе также рассматривается реализация системы защиты, включающей | ||
| 564 | модуль аутентификации и авторизации, а также инструмент для | ||
| 565 | моделирования атак на пароли. | ||
| 566 | |||
| 567 | ** Постановка задачи | ||
| 568 | #+latex: \noindent | ||
| 569 | *Цели работы:* | ||
| 570 | - разработать систему доступа пользователей к конфиденциальным данным | ||
| 571 | - исследовать стойкость паролей к атаке методом грубой силы. | ||
| 572 | |||
| 573 | #+latex: \bigbreak\noindent | ||
| 574 | *Задачи работы:* | ||
| 575 | - при необходимости установить на компьютер целевую ОС (Linux или | ||
| 576 | MacOS), в которой производится разработка и использование системы; | ||
| 577 | - разработать систему доступа пользователей к конфиденциальным данным; | ||
| 578 | - разработать программу взлома паролей методом грубой силы и | ||
| 579 | исследовать стойкость паролей в зависимости от длины паролей и | ||
| 580 | алгоритма хэширования. | ||
| 581 | |||
| 582 | ** Требования к разрабатываемой системе | ||
| 583 | *** Работа выполняется в ОС Linux или MacOS | ||
| 584 | Работа выполняется в ОС Linux или MacOS. Для этого необходим доступ к | ||
| 585 | указанным ОС с правами суперпользователя. Если такого доступа нет, то | ||
| 586 | необходимо установить на собственный компьютер гипервизор VirtualBox | ||
| 587 | (https://www.virtualbox.org/) и в качестве гостевой ОС установить одну | ||
| 588 | из указанных ОС любой версии. Допускается установка ОС в качестве | ||
| 589 | второй операционной системы, т.е. без установки VirtualBox. | ||
| 590 | |||
| 591 | *** Структура каталогов | ||
| 592 | Для выполнения работы необходимо создать следующее дерево каталогов: | ||
| 593 | - =/usr/local/practice2/etc= --- каталог для хранения файла с данными | ||
| 594 | аутентификации и авторизации; | ||
| 595 | - =/usr/local/practice2/confdata= --- каталог для хранения файлов с | ||
| 596 | конфиденциальной информацией; | ||
| 597 | - =/usr/local/practice2/bin= --- каталог для хранения разработанных | ||
| 598 | утилит; | ||
| 599 | - =/usr/local/practice2/log= --- каталог для хранения файлов | ||
| 600 | регистрации. | ||
| 601 | |||
| 602 | Права доступа к созданным каталогам: возможность чтения, записи, | ||
| 603 | выполнения только для пользователя root. | ||
| 604 | |||
| 605 | *** Требования к утилите для работы с данными аутентификации и авторизации | ||
| 606 | **** Хранение парольной информации | ||
| 607 | Парольная информация должна храниться в файле | ||
| 608 | =/usr/local/practice2/etc/passwd=. | ||
| 609 | |||
| 610 | Структура содержимого данного файла: | ||
| 611 | #+begin_example | ||
| 612 | <логин_1>:<хэш_пароля_1>:<идентификатор_1>:<права_доступа_1>:<ФИО_1> | ||
| 613 | ... | ||
| 614 | <логин_N>:<хэш_пароля_N>:<идентификатор_N>:<права_доступа_N>:<ФИО_N> | ||
| 615 | #+end_example | ||
| 616 | |||
| 617 | Таким образом, в каждой строке файла должна содержаться информация об | ||
| 618 | одном пользователе. Права доступа для данного файла: чтение и запись | ||
| 619 | только для пользователя root. | ||
| 620 | |||
| 621 | **** Права доступа пользователя | ||
| 622 | Возможные права доступа пользователя к конфиденциальным данным (<права_доступа>): | ||
| 623 | - =r= - чтение; | ||
| 624 | - =w= - запись; | ||
| 625 | - =d= - удаление. | ||
| 626 | |||
| 627 | *** Функциональные требования | ||
| 628 | Утилита должна обеспечивать: | ||
| 629 | - добавление в систему нового пользователя: запрашивать имя | ||
| 630 | пользователя (логин), ФИО, права доступа, пароль, подтверждение | ||
| 631 | пароля. После проверки корректности данные нового пользователя | ||
| 632 | должны сохраняться в файле =/usr/local/practice2/etc/passwd=. Пароль | ||
| 633 | должен храниться в виде хэш-значения. Используемый алгоритм | ||
| 634 | вычисления хэш-значения --- в соответствии с индивидуальным | ||
| 635 | заданием; | ||
| 636 | - алфавит пароля: кодировка ASCII, заглавные и строчные буквы | ||
| 637 | латинского алфавита, цифры =0-9=, спецсимволы =!@#$%^&*()=. Первый | ||
| 638 | символ не может быть цифрой и спецсимволом; | ||
| 639 | - возможность редактирования данных уже существующего пользователя, | ||
| 640 | включая изменение его пароля; | ||
| 641 | - возможность удаления существующего пользователя; | ||
| 642 | - регистрацию всех действий, производимых с файлом passwd. | ||
| 643 | |||
| 644 | *** Требования к утилите доступа к конфиденциальным данным | ||
| 645 | **** Аутентификация пользователя | ||
| 646 | При запуске утилита должна последовательно запрашивать логин и пароль | ||
| 647 | пользователя, проверять корректность введенных данных: | ||
| 648 | - если введены корректные данные, утилита должна выводить приветствие | ||
| 649 | типа "Привет, <ФИО>", краткую справку об утилите и приглашение на | ||
| 650 | ввод команд для работы с файлами; | ||
| 651 | - если введены некорректные данные (логин, пароль), утилита должна | ||
| 652 | повторно запрашивать логин и пароль; | ||
| 653 | - остановка утилиты в случае, если не удалось ввести корректную пару | ||
| 654 | логин/пароль – по сигналу =SIGINT= (комбинация клавиш =Ctrl-C=). | ||
| 655 | |||
| 656 | **** Поддерживаемые команды | ||
| 657 | Утилита должна поддерживать следующие команды: | ||
| 658 | - =read= --- команда вывода содержимого файла на консоль. Разрешена | ||
| 659 | пользователям с правами на чтение; | ||
| 660 | - =append= --- команда добавления данных к уже существующему | ||
| 661 | файлу. Команда должна запрашивать новые данные с | ||
| 662 | клавиатуры. Разрешена пользователям с правами на запись; | ||
| 663 | - =copy= --- команда копирования файла. Допускается копирование из | ||
| 664 | других каталогов в каталог confdata, а также копирование файлов | ||
| 665 | внутри этого каталога. Копирование файлов из каталога confdata в | ||
| 666 | другие каталоги запрещено. Копирование файла внутри каталога | ||
| 667 | confdata в существующие файлы запрещено. Команда разрешена | ||
| 668 | пользователям с правами на чтение и запись; | ||
| 669 | - =remove= --- команда удаления файла. Разрешена пользователям с правами | ||
| 670 | на удаление; | ||
| 671 | - =exit= --- окончание работы утилиты; | ||
| 672 | - =help= --- вывод справочной информации по командам. | ||
| 673 | |||
| 674 | **** Дополнительные требования | ||
| 675 | - утилита должна иметь права на запуск для всех пользователей ОС; | ||
| 676 | - утилита должна обеспечивать регистрацию всех действий, производимых | ||
| 677 | пользователями системы с конфиденциальными данными. | ||
| 678 | |||
| 679 | *** Требования к программе взлома паролей методом грубой силы | ||
| 680 | Программа должна обеспечивать: | ||
| 681 | - последовательный запуск утилиты доступа к конфиденциальной | ||
| 682 | информации и перебор паролей в заданном алфавите с учетом известного | ||
| 683 | алгоритма хэширования; | ||
| 684 | - фиксацию времени выполнения перебора и количества итераций до | ||
| 685 | момента вскрытия пароля. | ||
| 686 | |||
| 687 | *** Общие требования к программам | ||
| 688 | - требования к языку разработки не предъявляются; | ||
| 689 | - исходный код программ должен быть снабжен комментариями. | ||
| 690 | |||
| 691 | *** Требования к исследованию | ||
| 692 | Необходимо: | ||
| 693 | - провести исследование для следующих длин паролей: 3, 4, 5, 6, 7, 8 | ||
| 694 | символов; | ||
| 695 | - рассчитать максимальное количество итераций для указанных длин | ||
| 696 | паролей; | ||
| 697 | - по первым экспериментам с паролями длиной 3–4 символа рассчитать | ||
| 698 | ожидаемое максимальное время взлома для паролей длиной 5–8 символов; | ||
| 699 | - в ходе экспериментов проверить теоретические расчеты; | ||
| 700 | - прервать эксперимент, если длительность перебора составляет более 8 | ||
| 701 | часов; | ||
| 702 | - проводить эксперименты на компьютере без запущенных активных задач. | ||
| 703 | |||
| 704 | ** Сведение об аппаратном и программном обеспечении | ||
| 705 | Работа выполнена в среде GNU/Linux. | ||
| 706 | |||
| 707 | - Аппаратное обеспечение: | ||
| 708 | - Тип --- ноутбук; | ||
| 709 | - Наименование --- ThinkPad X230 (2325SGX); | ||
| 710 | - Процессор --- Intel(R) Core(TM) i5-3320M (4) @ 3.30 ГГц | ||
| 711 | - Оперативная память --- 16 ГБ; | ||
| 712 | - Память --- 1536 ГБ SSD; | ||
| 713 | - Архитектура процессора --- x86_64; | ||
| 714 | - Архитектура памяти --- UMA; | ||
| 715 | - Программное обеспечеине: | ||
| 716 | - Операционная система: | ||
| 717 | - Наименование --- Void Linux x86_64 (glibc); | ||
| 718 | - Ядро --- Linux 6.12.76_1; | ||
| 719 | - Среда разработки: | ||
| 720 | - Наименование --- GNU Emacs; | ||
| 721 | - Версия --- GNU Emacs 30.2 (build 2, x86_64-unknown-linux-gnu, | ||
| 722 | GTK+ Version 3.24.50, cairo version 1.18.4) of 2026-01-19; | ||
| 723 | - Язык программирования: | ||
| 724 | - Наименование --- C; | ||
| 725 | - Стандарт --- C99 (с расширениями GNU); | ||
| 726 | - Дополнительные библиотеки: | ||
| 727 | - OpenSSL (v3.5.5_1) --- SHA-1 хеширование; | ||
| 728 | - Readline (v8.2.010_1) --- повышение интерактивности оболочки. | ||
| 729 | |||
| 730 | ** Сведение об разработке | ||
| 731 | *** Алгоритм хэширования SHA-1 | ||
| 732 | /Secure Hash Algorithm 1/ --- алгоритм криптографического хеширования. | ||
| 733 | Описан в RFC 3174. Для входного сообщения произвольной длины | ||
| 734 | (максимум \(2^{64} − 1\) бит, что примерно равно 2 эксабайта) алгоритм | ||
| 735 | генерирует 160-битное (20 байт) хеш-значение, называемое также | ||
| 736 | дайджестом сообщения, которое обычно отображается как | ||
| 737 | шестнадцатеричное число длиной в 40 цифр. Используется во многих | ||
| 738 | криптографических приложениях и протоколах. | ||
| 739 | |||
| 740 | #+latex: \bigbreak\noindent | ||
| 741 | *Принцип работы:* | ||
| 742 | 1. *Предобработка* | ||
| 743 | - Добавить бит $1$, затем $0$ до длины $\equiv 448 \pmod{512}$. | ||
| 744 | - Добавить 64-битное представление длины исходного сообщения. | ||
| 745 | - Разбить сообщение на блоки по 512 бит. | ||
| 746 | 2. *Инициализация* --- Задать 5 регистров (32 бита каждый): $H_0, H_1, H_2, H_3, H_4$. | ||
| 747 | 3. *Обработка блока* --- Разбить блок на 16 слов по 32 бита и расширить | ||
| 748 | до 80 слов:\[ W_i = (W_{i-3} \oplus W_{i-8} \oplus W_{i-14} \oplus | ||
| 749 | W_{i-16}) \lll 1\] | ||
| 750 | 4. *Основной цикл (80 раундов)* | ||
| 751 | - Инициализировать: $a=H_0,\; b=H_1,\; c=H_2,\; d=H_3,\; e=H_4$ | ||
| 752 | - Для $i=0..79$:\[ \text{temp} = (a \lll 5) + f_i(b,c,d) + e + | ||
| 753 | K_i + W_i\]\[ e=d,\quad d=c,\quad c=b \lll 30,\quad b=a,\quad | ||
| 754 | a=\text{temp} \] где $f_i$ --- логические функции, $K_i$ --- | ||
| 755 | константы. | ||
| 756 | 5. *Обновление хеша* | ||
| 757 | \[ | ||
| 758 | H_0 = H_0 + a,\; | ||
| 759 | H_1 = H_1 + b,\; | ||
| 760 | H_2 = H_2 + c,\; | ||
| 761 | H_3 = H_3 + d,\; | ||
| 762 | H_4 = H_4 + e | ||
| 763 | \] | ||
| 764 | 6. *Результат* | ||
| 765 | - Конкатенация: | ||
| 766 | \[ H = H_0 \parallel H_1 \parallel H_2 \parallel H_3 \parallel H_4 \] | ||
| 767 | - Итог: 160-битный хеш. | ||
| 768 | |||
| 769 | ** Примеры компиляции и установки приложений | ||
| 770 | На рис. [[02-build]] и [[02-install]] представлены примеры компиляции и | ||
| 771 | установки приложений соответственно. | ||
| 772 | |||
| 773 | #+name: 02-build | ||
| 774 | #+caption: Пример компиляции приложения | ||
| 775 | #+begin_src text | ||
| 776 | $ ./build.sh | ||
| 777 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -o ./src/string-builder.o -c ./src/string-builder.c | ||
| 778 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -o ./src/string-view.o -c ./src/string-view.c | ||
| 779 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -o ./src/common.o -c ./src/common.c | ||
| 780 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -o ./src/cracking.o -c ./src/cracking.c | ||
| 781 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -lcrypto -o ./passwdctl ./src/common.o ./src/string-builder.o ./src/string-view.o ./src/passwdctl.c | ||
| 782 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -lcrypto -lreadline -o ./shell ./src/common.o ./src/string-builder.o ./src/string-view.o ./src/shell.c | ||
| 783 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -o ./bruteforce ./src/string-builder.o ./src/string-view.o ./src/cracking.o ./src/bruteforce.c | ||
| 784 | + cc -std=gnu99 -ggdb3 -O3 -march=native -DNDEBUG -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -I./src/ -o ./measure ./src/string-builder.o ./src/string-view.o ./src/cracking.o ./src/measure.c | ||
| 785 | #+end_src | ||
| 786 | |||
| 787 | #+name: 02-install | ||
| 788 | #+caption: Пример установки приложения | ||
| 789 | #+begin_src text | ||
| 790 | $ doas ./install.sh | ||
| 791 | + install -o root -g root -m 755 -d /usr/local/practice2 | ||
| 792 | + install -o root -g root -m 755 -d /usr/local/practice2/bin | ||
| 793 | + install -o root -g root -m 700 -d /usr/local/practice2/etc | ||
| 794 | + install -o root -g root -m 700 -d /usr/local/practice2/confdata | ||
| 795 | + install -o root -g root -m 700 -d /usr/local/practice2/log | ||
| 796 | + install -o root -g root -m 6711 passwdctl /usr/local/practice2/bin/passwdctl | ||
| 797 | + install -o root -g root -m 6711 shell /usr/local/practice2/bin/shell | ||
| 798 | + install bruteforce /usr/local/practice2/bin/bruteforce | ||
| 799 | + install measure /usr/local/practice2/bin/measure | ||
| 800 | + umask 177 | ||
| 801 | + [ ! -f /usr/local/practice2/etc/passwd ] | ||
| 802 | + touch /usr/local/practice2/etc/passwd | ||
| 803 | + [ ! -f /usr/local/practice2/log/passwd.log ] | ||
| 804 | + touch /usr/local/practice2/log/passwd.log | ||
| 805 | + [ ! -f /usr/local/practice2/log/confdata.log ] | ||
| 806 | + touch /usr/local/practice2/log/confdata.log | ||
| 807 | + exit 0 | ||
| 808 | #+end_src | ||
| 809 | |||
| 810 | ** Примеры запуска и работы утилит | ||
| 811 | *** Утилита для работы с данными аутентификации и авторизации | ||
| 812 | Примеры приведены на рис. [[02-passwdctl-first]]-[[02-passwdctl-last]]. | ||
| 813 | |||
| 814 | #+name: 02-passwdctl-first | ||
| 815 | #+caption: Запуск =passwdctl= без аргументов | ||
| 816 | #+begin_src text | ||
| 817 | $ passwdctl | ||
| 818 | Usage: passwdctl [options] COMMAND [ARGS] | ||
| 819 | |||
| 820 | Options: | ||
| 821 | -h, --help display this help message and exit | ||
| 822 | |||
| 823 | Commands: | ||
| 824 | add LOGIN add new account | ||
| 825 | mod LOGIN modify existing account | ||
| 826 | del LOGIN delete account | ||
| 827 | |||
| 828 | #+end_src | ||
| 829 | |||
| 830 | #+caption: Запуск =passwdctl add= без подаргументов | ||
| 831 | #+begin_src text | ||
| 832 | $ passwdctl add | ||
| 833 | error: no login provided | ||
| 834 | Usage: passwdctl add [options] LOGIN | ||
| 835 | |||
| 836 | Options: | ||
| 837 | -h, --help display this help message and exit | ||
| 838 | -p, --password PASSWORD password of the new account | ||
| 839 | -i, --id ID ID of the new account | ||
| 840 | -a, --access-rights {r|w|d}... access right of the new account | ||
| 841 | -c, --comment COMMENT comment of the new account | ||
| 842 | |||
| 843 | #+end_src | ||
| 844 | |||
| 845 | #+caption: Запуск =passwdctl add= как обычный пользователь | ||
| 846 | #+begin_src text | ||
| 847 | $ passwdctl add rdonly | ||
| 848 | fatal: permission denied | ||
| 849 | #+end_src | ||
| 850 | |||
| 851 | #+caption: Запуск =passwdctl add= от имени =root= | ||
| 852 | #+begin_src text | ||
| 853 | # passwdctl add rdonly | ||
| 854 | Password: | ||
| 855 | Repeat password: | ||
| 856 | #+end_src | ||
| 857 | |||
| 858 | #+caption: Запуск =passwdctl mod= с флажком помощи | ||
| 859 | #+begin_src text | ||
| 860 | $ passwdctl mod -h | ||
| 861 | Usage: passwdctl mod [options] LOGIN | ||
| 862 | |||
| 863 | Options: | ||
| 864 | -h, --help display this help message and exit | ||
| 865 | -l, --login NEW_LOGIN new login for the account | ||
| 866 | -p, --password PASSWORD new password for the account | ||
| 867 | -P prompt for new password for the account | ||
| 868 | -i, --id ID new ID for the account | ||
| 869 | -a, --access-rights {r|w|d}... new access rights for the account | ||
| 870 | -c, --comment COMMENT new comment for the account | ||
| 871 | |||
| 872 | #+end_src | ||
| 873 | |||
| 874 | #+caption: Запуск =passwdctl mod= от имени обычного пользователья | ||
| 875 | #+begin_src text | ||
| 876 | $ passwdctl mod rdonly -a r -c 'Read O.' | ||
| 877 | fatal: permission to change access rights denied | ||
| 878 | #+end_src | ||
| 879 | |||
| 880 | #+caption: Запуск =passwdctl mod= для изменения прав доступа и ФИО | ||
| 881 | #+begin_src text | ||
| 882 | # passwdctl mod rdonly -a r -c 'Read O.' | ||
| 883 | #+end_src | ||
| 884 | |||
| 885 | #+caption: Запуск =passwdctl del= с флажком помощи | ||
| 886 | #+begin_src text | ||
| 887 | $ passwdctl del -h | ||
| 888 | Usage: passwdctl del [options] LOGIN | ||
| 889 | |||
| 890 | Options: | ||
| 891 | -h, --help display this help message and exit | ||
| 892 | |||
| 893 | #+end_src | ||
| 894 | |||
| 895 | #+caption: Запуск =passwdctl del= от имени =root= | ||
| 896 | #+begin_src text | ||
| 897 | # passwdctl del rdonly | ||
| 898 | #+end_src | ||
| 899 | |||
| 900 | #+caption: Пример файла =passwd= | ||
| 901 | #+begin_src text | ||
| 902 | rdonly:$1$FU6d/Fcvx40WFrcZ$Wk2T6SuMDyUa681KtWEJQuEPMpM:0:1:Read O. | ||
| 903 | wronly:$1$q0NGI.TjyxGpduam$FbaXzecG9gfAMkjzTf6Iq1ak3Wo:1:2:Write O. | ||
| 904 | dlonly:$1$RuizDB0KMmWV/int$qfdynnanHcOpcLVZLmdbSH9TERc:2:1:Delete O. | ||
| 905 | rdwr:$1$z4RbIwR5p9SS5Bfs$nAJ2zBMJV/FjoaKUrNFk.TM5BxQ:3:3:Read W. | ||
| 906 | all:$1$NaAPi3jMZVDk.i5D$cArn2jGzvYaBrM9nvJCotdQBlNw:4:7:A L.L. | ||
| 907 | #+end_src | ||
| 908 | |||
| 909 | #+name: 02-passwdctl-last | ||
| 910 | #+caption: Пример файла =passwd.log= | ||
| 911 | #+begin_src text | ||
| 912 | 1773888065 added user rdonly 0 with access rights --- | ||
| 913 | 1773888275 user 'rdonly' (0) was looked up | ||
| 914 | 1773888275 modified user rdonly with id 0: new access rights r--, new comment `Read O.' | ||
| 915 | 1773888353 deleted user rdonly with id 0 (Read O.) | ||
| 916 | 1773888585 added user rdonly 0 (Read O.) with access rights r-- | ||
| 917 | 1773888594 added user wronly 1 (Write O.) with access rights r-- | ||
| 918 | 1773888607 added user dlonly 2 (Delete O.) with access rights r-- | ||
| 919 | 1773888624 added user rdwr 3 (Read W.) with access rights r-- | ||
| 920 | 1773888643 added user all 4 (A L.L.) with access rights r-- | ||
| 921 | 1773888697 user 'all' (4) was looked up | ||
| 922 | 1773888697 modified user all with id 4: new access rights rwd | ||
| 923 | 1773888702 user 'rdwr' (3) was looked up | ||
| 924 | 1773888702 modified user rdwr with id 3: new access rights rw- | ||
| 925 | 1773888707 user 'wronly' (1) was looked up | ||
| 926 | 1773888707 modified user wronly with id 1: new access rights -w- | ||
| 927 | #+end_src | ||
| 928 | |||
| 929 | *** Утилита для доступа к конфиденциальным данным | ||
| 930 | Примеры приведены на рис. [[02-shell-first]]-[[02-shell-last]]. | ||
| 931 | |||
| 932 | #+name: 02-shell-first | ||
| 933 | #+caption: Пример запуска =shell= с флажком помощи | ||
| 934 | #+begin_src text | ||
| 935 | $ shell -h | ||
| 936 | Usage: shell [options] [LOGIN] | ||
| 937 | |||
| 938 | Options: | ||
| 939 | -h, --help display this help message and exit | ||
| 940 | -p, --password PASSWORD password of the account (only if login was provided) | ||
| 941 | #+end_src | ||
| 942 | |||
| 943 | #+caption: Пример запуска =shell= без аргументов, авторизации и выхода из программы | ||
| 944 | #+begin_src text | ||
| 945 | $ shell | ||
| 946 | Login: invalid | ||
| 947 | Password: | ||
| 948 | user invalid not found | ||
| 949 | Login: all | ||
| 950 | Password: | ||
| 951 | authentication failure | ||
| 952 | Login: all | ||
| 953 | Password: | ||
| 954 | Hello, A L.L.! (4) | ||
| 955 | Run 'help', to get a list of available commands. | ||
| 956 | [all:/home/cmmm/.../02] $ exit | ||
| 957 | #+end_src | ||
| 958 | |||
| 959 | #+name: 02-shell-last | ||
| 960 | #+caption: Пример запуска встроенной команды =help= | ||
| 961 | #+begin_src text | ||
| 962 | [all:!] $ help | ||
| 963 | Commands: | ||
| 964 | help display information about builtin commands | ||
| 965 | su LOGIN change user to LOGIN | ||
| 966 | pwd print the name of the current working directory | ||
| 967 | whoami print effective user name | ||
| 968 | echo [ARG]... write ARG(s) to the standard output | ||
| 969 | ls [FILE]... list information about the FILE(s) | ||
| 970 | cd [DIR] change the shell working directory | ||
| 971 | mv SOURCE DEST rename SOURCE to DEST | ||
| 972 | mv SOURCE... DIRECTORY move SOURCE(s) to DIRECTORY | ||
| 973 | cp SOURCE DEST copy SOURCE to DEST | ||
| 974 | cp SOURCE... DIRECTORY copy SOURCE(s) to DIRECTORY | ||
| 975 | rm FILE... remove (unlink) the FILE(s) | ||
| 976 | mkdir DIR... create the DIRECTORY(ies), if they do not already exist | ||
| 977 | rmdir DIR... remove the DIRECTORY(ies), if they are empty | ||
| 978 | cat [FILE]... concatenate FILE(s) to standard output | ||
| 979 | append FILE append text from standard input to FILE | ||
| 980 | |||
| 981 | Aliases: | ||
| 982 | read -> cat | ||
| 983 | copy -> cp | ||
| 984 | remove -> rm | ||
| 985 | #+end_src | ||
| 986 | |||
| 987 | #+caption: Пример использования встроенных комманд =append= и =read= | ||
| 988 | #+begin_src text | ||
| 989 | [wronly:!] $ append test.txt | ||
| 990 | append> This is confidential information | ||
| 991 | append> | ||
| 992 | append> For authorized personnel only! | ||
| 993 | append> | ||
| 994 | [wronly:!] $ read test.txt | ||
| 995 | access denied 'test.txt' | ||
| 996 | [wronly:!] 1 $ su rdonly | ||
| 997 | Password: | ||
| 998 | [rdonly:!] $ append test.txt | ||
| 999 | access denied 'test.txt' | ||
| 1000 | [rdonly:!] 1 $ read test.txt | ||
| 1001 | This is confidential information | ||
| 1002 | |||
| 1003 | For authorized personnel only! | ||
| 1004 | [rdonly:!] 1 $ su all | ||
| 1005 | [all:!] $ append test.txt | ||
| 1006 | append> more text... | ||
| 1007 | append> | ||
| 1008 | [all:!] $ read test.txt | ||
| 1009 | This is confidential information | ||
| 1010 | |||
| 1011 | For authorized personnel only! | ||
| 1012 | more text... | ||
| 1013 | [all:!] $ read non-existent | ||
| 1014 | read: cannot access 'non-existent': No such file or directory | ||
| 1015 | [all:!] 1 $ | ||
| 1016 | #+end_src | ||
| 1017 | |||
| 1018 | #+caption: Пример использования встроенной комманды =copy= | ||
| 1019 | #+begin_src text | ||
| 1020 | [all:!] $ copy ~/tmp/a.out . | ||
| 1021 | [all:!] $ copy a.out /tmp/ | ||
| 1022 | access denied: no one can copy out of confdata | ||
| 1023 | cp: failed to copy 'a.out' -> '/tmp/a.out' | ||
| 1024 | [all:!] 1 $ copy a.out b.out | ||
| 1025 | [all:!] $ copy b.out a.out | ||
| 1026 | error opening file for writing 'a.out': File exists | ||
| 1027 | cp: failed to copy 'b.out' -> 'a.out' | ||
| 1028 | [all:!] 1 $ su rdonly | ||
| 1029 | Password: | ||
| 1030 | [rdonly:!] $ copy b.out c.out | ||
| 1031 | access denied 'c.out' | ||
| 1032 | cp: failed to copy 'b.out' -> 'c.out' | ||
| 1033 | [rdonly:!] 1 $ | ||
| 1034 | #+end_src | ||
| 1035 | |||
| 1036 | #+caption: Пример использования встроенной комманды =remove= | ||
| 1037 | #+begin_src text | ||
| 1038 | [rdwr:!] $ whoami | ||
| 1039 | 3 rdwr (Read W.) rw- | ||
| 1040 | [rdwr:!] $ remove test.txt | ||
| 1041 | access denied 'test.txt' | ||
| 1042 | [rdwr:!] 1 $ su dlonly | ||
| 1043 | Password: | ||
| 1044 | [dlonly:!] $ whoami | ||
| 1045 | 2 dlonly (Delete O.) --d | ||
| 1046 | [dlonly:!] $ remove test.txt | ||
| 1047 | [dlonly:!] $ | ||
| 1048 | #+end_src | ||
| 1049 | |||
| 1050 | #+caption: Пример файла =confdata.log= | ||
| 1051 | #+begin_src text | ||
| 1052 | 1773889519 user 4 listed directory '!' | ||
| 1053 | 1773889560 user 4 wrote to file '!/a.out' | ||
| 1054 | 1773889597 user 4 listed directory '!' | ||
| 1055 | 1773889686 user 4 listed directory '!' | ||
| 1056 | 1773889688 user 4 removed file '!/a.out' | ||
| 1057 | 1773889695 user 4 wrote to file '!/a.out' | ||
| 1058 | 1773889794 user 4 listed directory '!' | ||
| 1059 | 1773889796 user 4 removed file '!/a.out' | ||
| 1060 | 1773889801 user 4 wrote to file '!/a.out' | ||
| 1061 | 1773889805 user 4 removed file '!/a.out' | ||
| 1062 | 1773889808 user 4 wrote to file '!/a.out' | ||
| 1063 | 1773889815 user 4 wrote to file '!/b.out' | ||
| 1064 | 1773889967 user 4 listed directory '!' | ||
| 1065 | 1773890008 user 4 appended to file '!/test.txt' | ||
| 1066 | 1773890023 user 4 removed file '!/test.txt' | ||
| 1067 | 1773890190 user 4 listed directory '!' | ||
| 1068 | 1773890194 user 4 removed file '!/a.out' | ||
| 1069 | 1773890194 user 4 removed file '!/b.out' | ||
| 1070 | 1773890194 user 4 listed directory '!' | ||
| 1071 | 1773890448 user 4 appended to file '!/test.txt' | ||
| 1072 | 1773890454 user 4 read file '!/test.txt' | ||
| 1073 | 1773890572 user 0 listed directory '!' | ||
| 1074 | 1773890596 user 0 read file '!/test.txt' | ||
| 1075 | 1773890709 user 1 appended to file '!/test.txt' | ||
| 1076 | 1773890732 user 4 read file '!/test.txt' | ||
| 1077 | 1773890885 user 2 listed directory '!' | ||
| 1078 | 1773891051 user 2 removed file '!/test.txt' | ||
| 1079 | #+end_src | ||
| 1080 | |||
| 1081 | *** Программа взлома паролей методом грубой силы | ||
| 1082 | Примеры приведены на рис. [[02-bruteforce-first]]-[[02-bruteforce-last]]. | ||
| 1083 | |||
| 1084 | #+name: 02-bruteforce-first | ||
| 1085 | #+caption: Запуск =bruteforce= без аргументов | ||
| 1086 | #+begin_src text | ||
| 1087 | $ bruteforce | ||
| 1088 | Usage: bruteforce LOGIN | ||
| 1089 | #+end_src | ||
| 1090 | |||
| 1091 | #+name: 02-bruteforce-last | ||
| 1092 | #+caption: Запуск =bruteforce= | ||
| 1093 | #+begin_src text | ||
| 1094 | $ time bruteforce rdwr | ||
| 1095 | Trying: A | ||
| 1096 | Trying: Qb@ | ||
| 1097 | Trying: gD% | ||
| 1098 | Trying: wz& | ||
| 1099 | Found: C9* | ||
| 1100 | |||
| 1101 | real 0m1.164s | ||
| 1102 | user 0m0.090s | ||
| 1103 | sys 0m0.353s | ||
| 1104 | #+end_src | ||
| 1105 | |||
| 1106 | ** Исследование стойкости паролей | ||
| 1107 | Для данной задачи была разработана программа замера времени на взлом | ||
| 1108 | паролей длиной в 3 и 4 символа, с автоматической экстраполяцией до | ||
| 1109 | длин 5-8. Пример запуска программы приведён на рис. [[02-measure]] | ||
| 1110 | |||
| 1111 | #+name: 02-measure | ||
| 1112 | #+caption: Запуск программы =measure= | ||
| 1113 | #+begin_src text | ||
| 1114 | $ measure user-with-pass-outside-3-and-4 | ||
| 1115 | Tried all 3 letter passwords in: 2.910741s | ||
| 1116 | Expected time to try all 4 letter passwords: 3.492889 min | ||
| 1117 | Real time to try 3 letter passwords: 2.910741s | ||
| 1118 | Real time to try 4 letter passwords: 211.919460s | ||
| 1119 | Estimated time to try 5 letter passwords: 15173.741232s | ||
| 1120 | Estimated time to try 6 letter passwords: 1092509.368704s | ||
| 1121 | Estimated time to try 7 letter passwords: 78660674.546688s | ||
| 1122 | Estimated time to try 8 letter passwords: 5663568567.361536s | ||
| 1123 | #+end_src | ||
| 1124 | |||
| 1125 | Для расчета количества итерации используем формулу: | ||
| 1126 | \[ I = 52 \cdot 72^{L - 1}, \] где \(L\) --- длина пароля. | ||
| 1127 | |||
| 1128 | По предполагаемому и реальному времени для опробования всех паролей | ||
| 1129 | длины 4 видно, что теоретические расчеты достаточно хороши (ошибка | ||
| 1130 | всего 2.3с). | ||
| 1131 | |||
| 1132 | Таким образом, мы получили данные, которые приведены в | ||
| 1133 | табл. [[02-measurements]]. На рис. [[02-plot]] видна экспоненциальная | ||
| 1134 | зависимость времени для взлома пароля от его длины. | ||
| 1135 | |||
| 1136 | #+name: 02-measurements | ||
| 1137 | #+caption: Максимальные времена (итерации) для взлома паролей разных длин | ||
| 1138 | #+plot: script:"02-measurement.plt" file:"res/02/plot.tex" | ||
| 1139 | | Длина | Время (с) | Кол-во итерации | | ||
| 1140 | |-------+-------------------+-----------------| | ||
| 1141 | | 3 | 2.910741 | 269568 | | ||
| 1142 | | 4 | 211.919460 | 19408896 | | ||
| 1143 | | 5 | 15173.741232 | 1397440512 | | ||
| 1144 | | 6 | 1092509.368704 | 100615716864 | | ||
| 1145 | | 7 | 78660674.546688 | 7244331614208 | | ||
| 1146 | | 8 | 5663568567.361536 | 521591876222976 | | ||
| 1147 | |||
| 1148 | #+name: 02-plot | ||
| 1149 | #+caption: Зависимость максимального времени (итерации) взлома от длины паролей | ||
| 1150 | #+attr_latex: :options [H] | ||
| 1151 | #+begin_figure | ||
| 1152 | \centering | ||
| 1153 | \input{res/02/plot} | ||
| 1154 | #+end_figure | ||
| 1155 | |||
| 1156 | ** ЗАКЛЮЧЕНИЕ | ||
| 1157 | :PROPERTIES: | ||
| 1158 | :UNNUMBERED: toc | ||
| 1159 | :END: | ||
| 1160 | В рамках данной практической работы была разработана и | ||
| 1161 | проанализирована простая система управления доступом к | ||
| 1162 | конфиденциальной информации. Для этого были создан отдельный каталог | ||
| 1163 | =/usr/local/practice2/= с фиксированными правами доступа, а также | ||
| 1164 | реализованы утилиты для управления пользователями (=passwdctl=) | ||
| 1165 | аутентификации и контроля доступа (=shell=) и подбора паролей | ||
| 1166 | (=bruteforce=). | ||
| 1167 | |||
| 1168 | Для обеспечения корректной работы с защищёнными файлами =/etc/passwd= и | ||
| 1169 | журналами при сохранении ограничений самой системы GNU/Linux | ||
| 1170 | использовался =SUID=-бит, написанный на языке C, а также применялось | ||
| 1171 | точное управление =EUID=, повышая привилегии только тогда когда это | ||
| 1172 | необходимо (работа с файлами внутри =/usr/local/practice2/=). | ||
| 1173 | |||
| 1174 | В ходе экспериментов была изучена сложность атак методом полного | ||
| 1175 | перебора (brute force) для паролей различной длины, а также проведено | ||
| 1176 | сравнение теоретических оценок с практическими результатами. | ||
| 1177 | |||
| 1178 | Таким образом, поставленные задачи по проектированию системы | ||
| 1179 | защищённого доступа к файлам, организации хранения служебной | ||
| 1180 | информации и моделированию атак были успешно выполнены. | ||
| 1181 | |||
| 1182 | Исходный код данной практической работы, доступен в [[#02-src][ПРИЛОЖЕНИЙ Д]]. | ||
| 1183 | |||
| 1184 | * Реализация моделей дискреционного и мандатного управления доступом | ||
| 1185 | ** ВВЕДЕНИЕ | ||
| 1186 | :PROPERTIES: | ||
| 1187 | :UNNUMBERED: toc | ||
| 1188 | :END: | ||
| 1189 | Помимо базовых механизмов аутентификации и разграничения прав доступа | ||
| 1190 | между субъектами, в защищённых системах широко применяются модели | ||
| 1191 | дискреционного (DAC) и мандатного (MAC) управления доступом. | ||
| 1192 | |||
| 1193 | Дискреционная модель управления доступом предполагает, что владелец | ||
| 1194 | объекта самостоятельно определяет, кому предоставлять или отзывать | ||
| 1195 | права доступа. Это обеспечивает гибкость управления на уровне файловой | ||
| 1196 | системы и отдельных пользователей. | ||
| 1197 | |||
| 1198 | В свою очередь, мандатная модель основывается на использовании меток | ||
| 1199 | конфиденциальности, присваиваемых как субъектам, так и | ||
| 1200 | объектам. Доступ в такой системе регулируется строгими правилами | ||
| 1201 | (например, «не читать выше своего уровня» и «не записывать ниже»), что | ||
| 1202 | существенно снижает вероятность утечки данных даже в случае | ||
| 1203 | компрометации учётной записи. | ||
| 1204 | |||
| 1205 | В данной работе рассматривается реализация обеих моделей в рамках | ||
| 1206 | экспериментального стенда, а также их интеграция с разработанными | ||
| 1207 | утилитами для работы с конфиденциальными данными. | ||
| 1208 | |||
| 1209 | ** Постановка задачи | ||
| 1210 | #+latex: \noindent | ||
| 1211 | *Цели работы:* | ||
| 1212 | - изучить особенности моделей дискреционного (DAC) и мандатного (MAC) | ||
| 1213 | управления доступом; | ||
| 1214 | - на базе разработанной в практической работе 2 системы аутентификации | ||
| 1215 | и авторизации реализовать DAC и MAC. | ||
| 1216 | |||
| 1217 | #+latex: \bigbreak\noindent | ||
| 1218 | *Задачи работы:* | ||
| 1219 | - Изучить особенности дискреционного (произвольного) управления | ||
| 1220 | доступом, а также модель Харрисона-Руззо-Ульмана, основанную на DAC. | ||
| 1221 | - На базе разработанной в практической работе 2 системы аутентификации | ||
| 1222 | и авторизации разработать систему, реализующую DAC. | ||
| 1223 | - Изучить особенности мандатного (принудительного) управления | ||
| 1224 | доступом, а также модель Белла–Лападулы, основанную на MAC. | ||
| 1225 | - На базе разработанной в практической работе 2 системы аутентификации | ||
| 1226 | и авторизации разработать систему, реализующую MAC | ||
| 1227 | |||
| 1228 | ** Требования к работе | ||
| 1229 | 1. Работа выполняется в ОС Linux или MacOS. | ||
| 1230 | 2. Для выполнения работы необходимо создать отдельное дерево каталогов, например: | ||
| 1231 | - =/usr/local/practice3/etc= --- файлы настроек; | ||
| 1232 | - =/usr/local/practice3/confdata= --- файлы с конфиденциальной | ||
| 1233 | информацией, доступ к которым контролируется системами DAC и MAC; | ||
| 1234 | - =/usr/local/practice3/bin= --- исполняемые файлы; | ||
| 1235 | - =/usr/local/practice3/log= --- файлы регистрации. | ||
| 1236 | |||
| 1237 | Права доступа к созданным каталогам: возможность чтения, записи, | ||
| 1238 | выполнение только для пользователя root. | ||
| 1239 | |||
| 1240 | При необходимости возможно создание дополнительных каталогов. | ||
| 1241 | 3. Требования к системе DAC: | ||
| 1242 | - у каждого объекта должен быть владелец, который может произвольно | ||
| 1243 | назначать и передавать права доступа к этому объекту; | ||
| 1244 | - контроль доступа к объектам должен осуществляться на основе | ||
| 1245 | матрицы или списка доступа, в которых хранится информация о | ||
| 1246 | правах доступа субъектов к объектам. | ||
| 1247 | 4. Требования к системе MAC: | ||
| 1248 | - каждому субъекту и объекту должна присваиваться метка | ||
| 1249 | безопасности суперпользователем; | ||
| 1250 | - предусмотреть не менее трех уровней меток безопасности, например: | ||
| 1251 | - «несекретно», | ||
| 1252 | - «для служебного пользования (ДСП)», | ||
| 1253 | - «секретно»; | ||
| 1254 | - субъекты не могут менять метки безопасности; | ||
| 1255 | - контроль доступа к объектам должен осуществляться на основе | ||
| 1256 | свойств безопасности модели Белла–Лападулы: «нет чтения сверху», | ||
| 1257 | «нет записи вниз» и дискреционного свойства. | ||
| 1258 | |||
| 1259 | ** Сведения о DAC и MAC | ||
| 1260 | /Дискреционное управление доступом/ (DAC) --- это модель контроля | ||
| 1261 | доступа, при которой владелец ресурса сам назначает права субъектам на | ||
| 1262 | работу с объектами (чтение, запись, выполнение). Эти права обычно | ||
| 1263 | хранятся в виде матрицы доступа или списков контроля доступа | ||
| 1264 | (ACL). Основное преимущество модели --- высокая гибкость, однако она | ||
| 1265 | может быть уязвима из-за возможности несанкционированной передачи | ||
| 1266 | прав. | ||
| 1267 | |||
| 1268 | /Мандатное управление доступом/ (MAC) --- модель, основанная на | ||
| 1269 | использовании меток безопасности для субъектов и объектов. Доступ | ||
| 1270 | предоставляется только при соблюдении правил сопоставления этих меток, | ||
| 1271 | которые централизованно задаются политикой безопасности. В основе | ||
| 1272 | лежит модель Белла-Лападулы (см. рис. [[blp]]), обеспечивающая | ||
| 1273 | иерархический контроль информационных потоков и предотвращающая | ||
| 1274 | снижение уровня конфиденциальности. В отличие от DAC, пользователи не | ||
| 1275 | имеют возможности изменять правила доступа. | ||
| 1276 | |||
| 1277 | #+name: blp | ||
| 1278 | #+caption: Модель Белла-Лападулы | ||
| 1279 | [[./res/03/blp.png]] | ||
| 1280 | |||
| 1281 | ** Примеры компиляции и установки приложений | ||
| 1282 | На рис. [[03-build]] и [[03-install]] представлены примеры компиляции и | ||
| 1283 | установки приложений соответственно. | ||
| 1284 | |||
| 1285 | #+name: 03-build | ||
| 1286 | #+caption: Пример компиляции приложения | ||
| 1287 | #+begin_src text | ||
| 1288 | $ ./build.sh | ||
| 1289 | + cc -std=gnu99 -ggdb3 -O3 -march=native -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-stringop-overflow -I./src/ -o ./src/string-builder.o -c ./src/string-builder.c | ||
| 1290 | + cc -std=gnu99 -ggdb3 -O3 -march=native -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-stringop-overflow -I./src/ -o ./src/string-view.o -c ./src/string-view.c | ||
| 1291 | + cc -std=gnu99 -ggdb3 -O3 -march=native -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-stringop-overflow -I./src/ -o ./src/common.o -c ./src/common.c | ||
| 1292 | + cc -std=gnu99 -ggdb3 -O3 -march=native -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-stringop-overflow -I./src/ -lcrypto -o ./passwdctl ./src/common.o ./src/string-builder.o ./src/string-view.o ./src/passwdctl.c | ||
| 1293 | + cc -std=gnu99 -ggdb3 -O3 -march=native -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-stringop-overflow -I./src/ -lcrypto -lreadline -o ./shell-dac ./src/common.o ./src/string-builder.o ./src/string-view.o ./src/shell.c | ||
| 1294 | + cc -std=gnu99 -ggdb3 -O3 -march=native -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-stringop-overflow -I./src/ -lcrypto -lreadline -o ./shell-mac -DMAC ./src/common.o ./src/string-builder.o ./src/string-view.o ./src/shell.c | ||
| 1295 | #+end_src | ||
| 1296 | |||
| 1297 | #+name: 03-install | ||
| 1298 | #+caption: Пример установки приложения | ||
| 1299 | #+begin_src text | ||
| 1300 | $ doas ./install.sh | ||
| 1301 | + install -o root -g root -m 755 -d /usr/local/practice3 | ||
| 1302 | + install -o root -g root -m 755 -d /usr/local/practice3/bin | ||
| 1303 | + install -o root -g root -m 700 -d /usr/local/practice3/etc | ||
| 1304 | + install -o root -g root -m 700 -d /usr/local/practice3/etc/acl | ||
| 1305 | + install -o root -g root -m 700 -d /usr/local/practice3/confdata | ||
| 1306 | + install -o root -g root -m 700 -d /usr/local/practice3/log | ||
| 1307 | + install -o root -g root -m 6711 passwdctl /usr/local/practice3/bin/passwdctl | ||
| 1308 | + install -o root -g root -m 6711 shell-dac /usr/local/practice3/bin/shell-dac | ||
| 1309 | + install -o root -g root -m 6711 shell-mac /usr/local/practice3/bin/shell-mac | ||
| 1310 | + umask 177 | ||
| 1311 | + [ ! -f /usr/local/practice3/etc/passwd ] | ||
| 1312 | + touch /usr/local/practice3/etc/passwd | ||
| 1313 | + [ ! -f /usr/local/practice3/log/passwd.log ] | ||
| 1314 | + touch /usr/local/practice3/log/passwd.log | ||
| 1315 | + [ ! -f /usr/local/practice3/log/confdata.log ] | ||
| 1316 | + touch /usr/local/practice3/log/confdata.log | ||
| 1317 | + exit 0 | ||
| 1318 | #+end_src | ||
| 1319 | |||
| 1320 | ** Примеры запуска и работы утилит доступа к конфиденциальной информации | ||
| 1321 | *** Утилита для работы с системой DAC | ||
| 1322 | Примеры запуска и работы приведены на рис. [[03-shell-dac]]. | ||
| 1323 | |||
| 1324 | #+name: 03-shell-dac | ||
| 1325 | #+caption: Запуск и работа =shell-dac= | ||
| 1326 | #+begin_src text | ||
| 1327 | $ shell-dac u1 | ||
| 1328 | Password: | ||
| 1329 | Hello, User 1! (0) | ||
| 1330 | Run 'help', to get a list of available commands. | ||
| 1331 | [u1:/home/cmmm/.../03] $ cd | ||
| 1332 | [u1:!] $ append file1 | ||
| 1333 | append> some text | ||
| 1334 | append> | ||
| 1335 | [u1:!] $ ls | ||
| 1336 | .: | ||
| 1337 | file1 u1 | ||
| 1338 | [u1:!] $ grant u2 r file1 | ||
| 1339 | [u1:!] $ ls | ||
| 1340 | .: | ||
| 1341 | file1 u1 u2:r-- | ||
| 1342 | [u1:!] $ su u2 | ||
| 1343 | Password: | ||
| 1344 | [u2:!] $ read file1 | ||
| 1345 | some text | ||
| 1346 | [u2:!] $ append file1 | ||
| 1347 | access denied 'file1' | ||
| 1348 | [u2:!] 1 $ remove file1 | ||
| 1349 | access denied 'file1' | ||
| 1350 | [u2:!] 1 $ append file2 | ||
| 1351 | append> more text | ||
| 1352 | append> | ||
| 1353 | [u2:!] $ ls | ||
| 1354 | .: | ||
| 1355 | file2 u2 | ||
| 1356 | file1 u1 u2:r-- | ||
| 1357 | [u2:!] $ grant u1 d file2 | ||
| 1358 | [u2:!] $ su u1 | ||
| 1359 | Password: | ||
| 1360 | [u1:!] $ revoke u2 rwd file1 | ||
| 1361 | [u1:!] $ read file2 | ||
| 1362 | access denied 'file2' | ||
| 1363 | [u1:!] $ ls | ||
| 1364 | .: | ||
| 1365 | file2 u2 u1:--d | ||
| 1366 | file1 u1 | ||
| 1367 | [u1:!] $ remove file2 | ||
| 1368 | [u1:!] $ su u2 | ||
| 1369 | Password: | ||
| 1370 | [u2:!] $ read file1 | ||
| 1371 | access denied 'file1' | ||
| 1372 | [u2:!] $ grant u2 r file1 | ||
| 1373 | grant: error: permission denied: not owner of the file 'file1' | ||
| 1374 | [u2:!] 1 $ revoke u2 d file1 | ||
| 1375 | revoke: error: permission denied: not owner of the file 'file1' | ||
| 1376 | [u2:!] 1 $ exit | ||
| 1377 | #+end_src | ||
| 1378 | |||
| 1379 | *** Утилита для работы с системой MAC | ||
| 1380 | Примеры запуска и работы приведены на рис. [[03-shell-mac]]. | ||
| 1381 | |||
| 1382 | #+name: 03-shell-mac | ||
| 1383 | #+caption: Запуск и работа =shell-mac= | ||
| 1384 | #+begin_src text | ||
| 1385 | $ shell-mac secret | ||
| 1386 | Password: | ||
| 1387 | Hello, Secret! (3) | ||
| 1388 | Run 'help', to get a list of available commands. | ||
| 1389 | [secret@secret:/home/cmmm/.../03] $ cd | ||
| 1390 | [secret@secret:!] $ append file1 | ||
| 1391 | append> some text | ||
| 1392 | append> | ||
| 1393 | [secret@secret:!] $ grant top-secret rwd file1 | ||
| 1394 | [secret@secret:!] $ su top-secret | ||
| 1395 | Password: | ||
| 1396 | [top-secret@top-secret:!] $ ls | ||
| 1397 | .: | ||
| 1398 | file1 secret secret top-secret:rwd | ||
| 1399 | [top-secret@top-secret:!] $ append file1 | ||
| 1400 | access denied 'file1' | ||
| 1401 | [top-secret@top-secret:!] 1 $ read file1 | ||
| 1402 | some text | ||
| 1403 | [top-secret@top-secret:!] $ remove file1 | ||
| 1404 | [top-secret@top-secret:!] $ append file2 | ||
| 1405 | append> other text | ||
| 1406 | append> | ||
| 1407 | [top-secret@top-secret:!] $ grant secret rwd file2 | ||
| 1408 | [top-secret@top-secret:!] $ su secret | ||
| 1409 | Password: | ||
| 1410 | [secret@secret:!] $ read file2 | ||
| 1411 | access denied 'file2' | ||
| 1412 | [secret@secret:!] $ ls | ||
| 1413 | .: | ||
| 1414 | file2 top-secret top-secret secret:rwd | ||
| 1415 | [secret@secret:!] $ append file2 | ||
| 1416 | append> some more text | ||
| 1417 | append> | ||
| 1418 | [secret@secret:!] $ su top-secret | ||
| 1419 | Password: | ||
| 1420 | [top-secret@top-secret:!] $ read file2 | ||
| 1421 | other text | ||
| 1422 | some more text | ||
| 1423 | [top-secret@top-secret:!] $ | ||
| 1424 | #+end_src | ||
| 1425 | |||
| 1426 | ** Примеры содержимого служебных файлов, хранящих информацию о списке доступа для DAC и метках конфиденциальности для MAC | ||
| 1427 | На рис. [[03-acl-file1]] приведён пример ACL, определяющий уровень | ||
| 1428 | секретности 1 (=secret=), владельца файла как пользователя с id 3, | ||
| 1429 | количество пользователей, которым присвоены привилегии (1), сами | ||
| 1430 | привилегии 5 (=r-d=), которые присвоены пользователю с id 2. | ||
| 1431 | |||
| 1432 | #+name: 03-acl-file1 | ||
| 1433 | #+caption: ACL =!file1= | ||
| 1434 | #+begin_src text | ||
| 1435 | 1 3 1 | ||
| 1436 | 2 5 | ||
| 1437 | #+end_src | ||
| 1438 | |||
| 1439 | На рис. [[03-acl-file2]] приведён пример ACL, определяющий уровень | ||
| 1440 | секретности 0 (=top-secret=), владельца файла как пользователя с id 2, | ||
| 1441 | количество пользователей, которым присвоены привилегии (1), сами | ||
| 1442 | привилегии 7 (=rwd=), которые присвоены пользователю с id 3. | ||
| 1443 | |||
| 1444 | #+name: 03-acl-file2 | ||
| 1445 | #+caption: ACL =!file2= | ||
| 1446 | #+begin_src text | ||
| 1447 | 0 2 1 | ||
| 1448 | 3 7 | ||
| 1449 | #+end_src | ||
| 1450 | |||
| 1451 | ** ЗАКЛЮЧЕНИЕ | ||
| 1452 | :PROPERTIES: | ||
| 1453 | :UNNUMBERED: toc | ||
| 1454 | :END: | ||
| 1455 | В данной работе были реализованы и проанализированы модели | ||
| 1456 | дискреционного (DAC) и мандатного (MAC) управления доступом, | ||
| 1457 | интегрированные в ранее разработанную систему аутентификации и | ||
| 1458 | разграничения прав. В рамках DAC была организована работа со списками | ||
| 1459 | контроля доступа (ACL), представленными в виде слабо структурированных | ||
| 1460 | текстовых файлов, размещённых в каталоге | ||
| 1461 | =/usr/local/practice3/etc/acl/=. Для каждого файла владелец и набор прав | ||
| 1462 | =rwd= для пользователей. | ||
| 1463 | |||
| 1464 | Для реализации MAC введена иерархия меток конфиденциальности | ||
| 1465 | (=unclassified=, =confidential=, =secret=, =top-secret=), назначаемых как | ||
| 1466 | субъектам, так и объектам, а также предусмотрен их хранение в файлах | ||
| 1467 | =/usr/local/practice3/etc/passwd= и | ||
| 1468 | =/usr/local/practice3/etc/acl/*=. Контроль доступа осуществляется в | ||
| 1469 | соответствии с правилами модели Белла-Лападулы: «не читать вверх» (No | ||
| 1470 | Read Up) и «не записывать вниз» (No Write Down). Итоговое решение о | ||
| 1471 | предоставлении доступа принимается с учётом требований обеих моделей | ||
| 1472 | --- DAC и MAC. | ||
| 1473 | |||
| 1474 | Исходный код данной практической работы, доступен в [[#03-src][ПРИЛОЖЕНИЙ Е]]. | ||
| 1475 | |||
| 1476 | * Межсетевое экранирование | ||
| 1477 | ** ВВЕДЕНИЕ | ||
| 1478 | :PROPERTIES: | ||
| 1479 | :UNNUMBERED: toc | ||
| 1480 | :END: | ||
| 1481 | Межсетевое экранирование является одной из базовых технологий защиты | ||
| 1482 | компьютерных сетей. Оно реализуется с помощью межсетевых экранов (МЭ, | ||
| 1483 | firewall, брандмауэр), представляющих собой программные или | ||
| 1484 | программно-аппаратные средства, контролирующие сетевой трафик между | ||
| 1485 | различными сегментами сети либо отдельными узлами. | ||
| 1486 | |||
| 1487 | Основное назначение межсетевого экрана заключается в фильтрации | ||
| 1488 | потоков данных на основе заданного набора правил. Это позволяет | ||
| 1489 | предотвращать несанкционированный доступ как из внешней сети во | ||
| 1490 | внутреннюю, так и в обратном направлении. | ||
| 1491 | |||
| 1492 | В зависимости от принципа работы межсетевые экраны подразделяются на | ||
| 1493 | несколько типов. Наиболее простыми являются пакетные фильтры (packet | ||
| 1494 | filters), которые анализируют заголовки IP-пакетов и протоколов | ||
| 1495 | транспортного уровня (TCP, UDP, ICMP). Решение о пропуске или | ||
| 1496 | блокировке трафика принимается на основе таких параметров, как адреса | ||
| 1497 | источника и назначения, номера портов и служебные флаги. | ||
| 1498 | |||
| 1499 | Классическим примером пакетного фильтра в операционной системе Linux | ||
| 1500 | является =iptables=, встроенный в ядро системы. | ||
| 1501 | |||
| 1502 | В рамках данной работы рассматривается настройка политики доступа с | ||
| 1503 | использованием =nftables= в среде GNU/Linux, поскольку данный механизм | ||
| 1504 | является более современным и предпочтительным по ряду причин. | ||
| 1505 | |||
| 1506 | Во-первых, nftables использует единую инфраструктуру для фильтрации | ||
| 1507 | пакетов (вместо разрозненных подсистем =iptables=, =ip6tables=, =arptables= | ||
| 1508 | и =ebtables=), что упрощает конфигурацию и администрирование. | ||
| 1509 | |||
| 1510 | Во-вторых, в nftables применяется более компактный и выразительный | ||
| 1511 | синтаксис, позволяющий описывать правила в декларативной форме и | ||
| 1512 | сокращать их количество за счёт использования множеств (sets), | ||
| 1513 | отображений (maps) и диапазонов значений. | ||
| 1514 | |||
| 1515 | В-третьих, nftables обеспечивает более высокую производительность и | ||
| 1516 | масштабируемость благодаря использованию внутреннего представления | ||
| 1517 | правил в виде байткода, что снижает накладные расходы при обработке | ||
| 1518 | большого числа правил. | ||
| 1519 | |||
| 1520 | Кроме того, обновление правил в nftables выполняется атомарно, без | ||
| 1521 | промежуточных состояний, что исключает возникновение кратковременных | ||
| 1522 | уязвимостей в процессе изменения конфигурации. | ||
| 1523 | |||
| 1524 | Наконец, nftables предоставляет более гибкие возможности логирования, | ||
| 1525 | отладки и трассировки пакетов, а также унифицированный интерфейс | ||
| 1526 | управления через утилиту =nft=. | ||
| 1527 | |||
| 1528 | Таким образом, использование nftables является более целесообразным по | ||
| 1529 | сравнению с =iptables= с точки зрения удобства администрирования, | ||
| 1530 | производительности и расширяемости системы фильтрации сетевого | ||
| 1531 | трафика. | ||
| 1532 | |||
| 1533 | На рис. [[04-firewall]] представлен общий принцип работы межсетевого | ||
| 1534 | экрана, где WAN обозначает внешнюю сеть, LAN --- внутреннюю сеть, а | ||
| 1535 | Firewall --- межсетевой экран. | ||
| 1536 | |||
| 1537 | #+name: 04-firewall | ||
| 1538 | #+caption: Межсетевой экран на границе сетевого периметра | ||
| 1539 | [[./res/04/firewall.png]] | ||
| 1540 | |||
| 1541 | ** Постановка задачи | ||
| 1542 | #+latex: \noindent | ||
| 1543 | *Цель работы:* получение базовых знаний по настройке межсетевого экрана | ||
| 1544 | (МЭ) в ОС Linux/MacOS. | ||
| 1545 | |||
| 1546 | #+latex: \bigbreak\noindent | ||
| 1547 | *Задачи практической работы:* | ||
| 1548 | - изучение МЭ iptables или любого другого, обеспечивающего выполнение | ||
| 1549 | задания. | ||
| 1550 | - реализация заданной политики доступа: | ||
| 1551 | - разрешить локальное взаимодействие через интерфейс loopback; | ||
| 1552 | - разрешить взаимодействие с DNS-сервером; | ||
| 1553 | - разрешить использование утилиты ping для проверки достижимости | ||
| 1554 | компьютеров с любыми IP-адресами во внешней сети; | ||
| 1555 | - разрешить использование утилиты ping для проверки достижимости | ||
| 1556 | защищаемого хоста только с конкретного адреса внешней сети; | ||
| 1557 | - разрешить доступ по протоколам HTTP/HTTPS к любым внешним | ||
| 1558 | серверам; | ||
| 1559 | - блокировать все пакеты, не удовлетворяющие указанным выше | ||
| 1560 | условиям. | ||
| 1561 | |||
| 1562 | ** Проектирование системы | ||
| 1563 | Схема сети изображена на рис. [[schema]]. | ||
| 1564 | #+name: schema | ||
| 1565 | #+caption: Схема сети | ||
| 1566 | #+attr_latex: :options [h!] | ||
| 1567 | #+begin_figure | ||
| 1568 | \centering | ||
| 1569 | \begin{tikzpicture} | ||
| 1570 | \node [ | ||
| 1571 | label={[align=center]above:Защищаемый ПК с МЭ\\IP: 192.168.1.10}, | ||
| 1572 | ] (pc) at (0, 3) {\includegraphics[scale=0.5]{res/cisco/laptop}}; | ||
| 1573 | |||
| 1574 | \node [ | ||
| 1575 | label={[align=right]left:SOHO\\Маршрутизатор\\IP: 192.168.1.1}, | ||
| 1576 | ] (router) at (3, 0) {\includegraphics[scale=0.5]{res/cisco/router}}; | ||
| 1577 | |||
| 1578 | \node [ | ||
| 1579 | label={[align=center]below:Другой ПК\\IP: 192.168.1.4}, | ||
| 1580 | ] (pc-other) at (0, -3) {\includegraphics[scale=0.5]{res/cisco/laptop}}; | ||
| 1581 | |||
| 1582 | \node [ | ||
| 1583 | label=below:Интернет, | ||
| 1584 | ] (internet) at (9, 0) {\includegraphics[scale=0.5]{res/cisco/cloud}}; | ||
| 1585 | |||
| 1586 | \node [ | ||
| 1587 | label={[align=center]above:DNS}, | ||
| 1588 | ] (dns) at (5, 4) {\includegraphics[scale=0.5]{res/cisco/ibm-tower}}; | ||
| 1589 | |||
| 1590 | \node [ | ||
| 1591 | label={[align=center]above:web server}, | ||
| 1592 | ] (web) at (9, 4) {\includegraphics[scale=0.5]{res/cisco/ibm-tower}}; | ||
| 1593 | |||
| 1594 | \node [ | ||
| 1595 | label={[align=center]above:other}, | ||
| 1596 | ] (server-other) at (13, 4) {\includegraphics[scale=0.5]{res/cisco/ibm-tower}}; | ||
| 1597 | |||
| 1598 | \draw (pc) -- (router); | ||
| 1599 | \draw (pc-other) -- (router); | ||
| 1600 | \draw (router) -- (internet); | ||
| 1601 | \draw (internet) -- (dns); | ||
| 1602 | \draw (internet) -- (web); | ||
| 1603 | \draw (internet) -- (server-other); | ||
| 1604 | \end{tikzpicture} | ||
| 1605 | #+end_figure | ||
| 1606 | |||
| 1607 | #+caption: Входная таблица | ||
| 1608 | | *Паттерн* | *Действие* | | ||
| 1609 | |------------------------------------------------------------+----------| | ||
| 1610 | | loopback | accept | | ||
| 1611 | | SADDR = 203.0.113.10 \(\land\) ICMP \(\land\) echo-request | accept | | ||
| 1612 | |------------------------------------------------------------+----------| | ||
| 1613 | | | drop | | ||
| 1614 | |||
| 1615 | #+caption: Выходная таблица | ||
| 1616 | | *Пттерн* | *Действие* | | ||
| 1617 | |-----------------------------+----------| | ||
| 1618 | | loopback | accept | | ||
| 1619 | | UDP \(\land\) port = 53 | accept | | ||
| 1620 | | TCP \(\land\) port = 53 | accept | | ||
| 1621 | | TCP \(\land\) port = 853 | accept | | ||
| 1622 | | TCP \(\land\) port = 80 | accept | | ||
| 1623 | | TCP \(\land\) port = 443 | accept | | ||
| 1624 | | ICMP \(\land\) echo-request | accept | | ||
| 1625 | |-----------------------------+----------| | ||
| 1626 | | | drop | | ||
| 1627 | |||
| 1628 | ** Принцип обработки пакетов в nftables | ||
| 1629 | В nftables правила организуются так: | ||
| 1630 | - =table= --- таблица; | ||
| 1631 | - =chain= --- цепочка; | ||
| 1632 | - =rule= --- правило. | ||
| 1633 | |||
| 1634 | Для фильтрации обычно используется таблица inet, потому что она | ||
| 1635 | подходит и для IPv4, и для IPv6. | ||
| 1636 | |||
| 1637 | Основные цепочки: | ||
| 1638 | - =input= --- пакеты, адресованные самому хосту; | ||
| 1639 | - =output= --- пакеты, отправляемые с хоста; | ||
| 1640 | - =forward= --- транзитные пакеты через хост. | ||
| 1641 | |||
| 1642 | В нашем задании достаточно input и output. Действие по умолчанию | ||
| 1643 | задаётся через policy drop или policy accept. В этой работе логично | ||
| 1644 | использовать запрет по умолчанию. Это соответствует требованию | ||
| 1645 | блокировать весь неразрешённый трафик. | ||
| 1646 | |||
| 1647 | #+begin_src conf | ||
| 1648 | #!/usr/bin/nft -f | ||
| 1649 | |||
| 1650 | flush ruleset # remove all active rules | ||
| 1651 | |||
| 1652 | table inet filter { | ||
| 1653 | chain input { | ||
| 1654 | type filter hook input priority 0; | ||
| 1655 | policy drop; # drop by default | ||
| 1656 | |||
| 1657 | iif "lo" accept # allow input on loopback | ||
| 1658 | ct state established,related accept # keep active connections | ||
| 1659 | |||
| 1660 | # allow ping from specific ip | ||
| 1661 | ip saddr 192.168.1.4 ip protocol icmp icmp type echo-request accept | ||
| 1662 | } | ||
| 1663 | |||
| 1664 | chain output { | ||
| 1665 | type filter hook output priority 0; | ||
| 1666 | policy drop; # drop by default | ||
| 1667 | |||
| 1668 | oif "lo" accept # allow output on loopback | ||
| 1669 | ct state established,related accept # keep active connections | ||
| 1670 | |||
| 1671 | # DNS | ||
| 1672 | udp dport 53 accept | ||
| 1673 | tcp dport 53 accept | ||
| 1674 | tcp dport 853 accept # DNS over TLS | ||
| 1675 | |||
| 1676 | # ping | ||
| 1677 | ip protocol icmp icmp type echo-request accept | ||
| 1678 | |||
| 1679 | # HTTP[S] | ||
| 1680 | tcp dport 80 accept | ||
| 1681 | tcp dport 443 accept | ||
| 1682 | } | ||
| 1683 | } | ||
| 1684 | #+end_src | ||
| 1685 | |||
| 1686 | #+begin_src sh | ||
| 1687 | doas sv start nftables | ||
| 1688 | #+end_src | ||
| 1689 | |||
| 1690 | #+name: 04-ruleset | ||
| 1691 | #+begin_src sh :results verbatim | ||
| 1692 | doas nft list ruleset | ||
| 1693 | #+end_src | ||
| 1694 | |||
| 1695 | #+RESULTS: 04-ruleset | ||
| 1696 | #+begin_example | ||
| 1697 | table inet filter { | ||
| 1698 | chain input { | ||
| 1699 | type filter hook input priority filter; policy drop; | ||
| 1700 | iif "lo" accept | ||
| 1701 | ct state established,related accept | ||
| 1702 | ip saddr 192.168.1.4 ip protocol icmp icmp type echo-request accept | ||
| 1703 | } | ||
| 1704 | |||
| 1705 | chain output { | ||
| 1706 | type filter hook output priority filter; policy drop; | ||
| 1707 | oif "lo" accept | ||
| 1708 | ct state established,related accept | ||
| 1709 | udp dport 53 accept | ||
| 1710 | tcp dport 53 accept | ||
| 1711 | tcp dport 853 accept | ||
| 1712 | ip protocol icmp icmp type echo-request accept | ||
| 1713 | tcp dport 80 accept | ||
| 1714 | tcp dport 443 accept | ||
| 1715 | } | ||
| 1716 | } | ||
| 1717 | #+end_example | ||
| 1718 | |||
| 1719 | ** Проверка | ||
| 1720 | Команды проверки приведены на рис. [[04-test-first]]-[[04-test-last]]. | ||
| 1721 | |||
| 1722 | #+name: 04-test-first | ||
| 1723 | #+caption: ICMP out | ||
| 1724 | #+begin_src sh | ||
| 1725 | ping michalec.dev | ||
| 1726 | #+end_src | ||
| 1727 | |||
| 1728 | #+caption: DNS | ||
| 1729 | #+begin_src sh | ||
| 1730 | dig michalec.dev | ||
| 1731 | #+end_src | ||
| 1732 | |||
| 1733 | #+caption: HTTP | ||
| 1734 | #+begin_src sh | ||
| 1735 | curl http://michalec.dev | ||
| 1736 | #+end_src | ||
| 1737 | |||
| 1738 | #+caption: HTTPS | ||
| 1739 | #+begin_src sh | ||
| 1740 | curl https://michalec.dev | ||
| 1741 | #+end_src | ||
| 1742 | |||
| 1743 | #+name: 04-test-last | ||
| 1744 | #+caption: SSH | ||
| 1745 | #+begin_src sh | ||
| 1746 | ssh michalec.dev | ||
| 1747 | #+end_src | ||
| 1748 | |||
| 1749 | ** ЗАКЛЮЧЕНИЕ | ||
| 1750 | :PROPERTIES: | ||
| 1751 | :UNNUMBERED: toc | ||
| 1752 | :END: | ||
| 1753 | В данной главе выполнено проектирование и реализация политики | ||
| 1754 | межсетевого экранирования с использованием подсистемы nftables в среде | ||
| 1755 | GNU/Linux. Рассмотрены архитектура nftables, принципы обработки | ||
| 1756 | сетевых пакетов, а также организация таблиц, цепочек и правил, | ||
| 1757 | обеспечивающих гибкое и централизованное управление фильтрацией | ||
| 1758 | трафика. Особое внимание уделено конфигурации правил через файл | ||
| 1759 | =/etc/nftables.conf=, что позволяет сохранять настройки и автоматически | ||
| 1760 | применять их при загрузке системы. | ||
| 1761 | |||
| 1762 | Реализованная политика доступа предусматривает: разрешение трафика | ||
| 1763 | через интерфейс loopback, исходящих DNS-запросов (UDP/TCP, порт 53, | ||
| 1764 | DNS over TLS порт 853), исходящего ICMP (ping), входящего ICMP с | ||
| 1765 | доверенного узла 192.168.1.4, а также HTTP/HTTPS-трафика (порты 80 и | ||
| 1766 | 443). Остальной трафик блокируется по умолчанию. | ||
| 1767 | |||
| 1768 | Проведённое тестирование подтвердило корректность работы настроенной | ||
| 1769 | политики: разрешённый трафик успешно проходит, тогда как запрещённые | ||
| 1770 | соединения блокируются. Контроль и анализ сетевого трафика | ||
| 1771 | осуществлялись с использованием утилит tcpdump и nft, что позволило | ||
| 1772 | верифицировать соответствие фактического поведения заданной политике | ||
| 1773 | безопасности. | ||
| 1774 | |||
| 1775 | * Клиент-сервер с шифрованием | ||
| 1776 | ** ВВЕДЕНИЕ | ||
| 1777 | :PROPERTIES: | ||
| 1778 | :UNNUMBERED: toc | ||
| 1779 | :END: | ||
| 1780 | В данной работе разработано клиент-серверное приложение, | ||
| 1781 | предназначенное для защищённого обмена короткими сообщениями (до 80 | ||
| 1782 | символов) по протоколу TCP. В процессе выполнения решались задачи | ||
| 1783 | освоения криптографических возможностей библиотеки OpenSSL | ||
| 1784 | (libcrypto), реализации механизма обмена сообщениями между клиентами, | ||
| 1785 | а также проверки корректности функционирования системы посредством | ||
| 1786 | анализа сетевого трафика. | ||
| 1787 | |||
| 1788 | В соответствии с индивидуальным заданием в системе применяется | ||
| 1789 | симметричное шифрование AES-256 и хэш-функция SHA-1. Ключ шифрования | ||
| 1790 | длиной 32 байта хранится в отдельном файле с ограниченными правами | ||
| 1791 | доступа, что обеспечивает дополнительный уровень защиты. | ||
| 1792 | |||
| 1793 | Помимо базовой функциональности, реализованы дополнительные механизмы | ||
| 1794 | безопасности и взаимодействия: шифрование с затравкой (IV/nonce) и | ||
| 1795 | генерация сессионного ключа с использованием протокола Диффи-Хеллмана. | ||
| 1796 | |||
| 1797 | Актуальность рассматриваемой темы обусловлена необходимостью | ||
| 1798 | обеспечения конфиденциальности и целостности данных, передаваемых в | ||
| 1799 | сетевых приложениях, особенно при работе в условиях открытых и | ||
| 1800 | потенциально небезопасных сетей, где существует риск перехвата и | ||
| 1801 | несанкционированной модификации информации. | ||
| 1802 | |||
| 1803 | ** Постановка задачи | ||
| 1804 | #+latex: \noindent | ||
| 1805 | *Цель работы:* Разработка клиент-серверного приложения для | ||
| 1806 | конфиденциального обмена сообщениями с использованием шифрования и | ||
| 1807 | контроля целостности. | ||
| 1808 | |||
| 1809 | #+latex: \bigbreak\noindent | ||
| 1810 | *Задачи работы:* | ||
| 1811 | - получение базовых знаний по использованию криптографических функций | ||
| 1812 | библиотеки crypto в ОС Linux или другой библиотеки, обеспечивающей | ||
| 1813 | реализацию требований задания; | ||
| 1814 | - разработка клиент-серверного приложения для обмена шифрованными | ||
| 1815 | сообщениями с контролем целостности; | ||
| 1816 | - проверка работы приложения в различных режимах использования с | ||
| 1817 | помощью программы анализа трафика. | ||
| 1818 | |||
| 1819 | ** Алгоритм AES-256 | ||
| 1820 | AES-256 (/Advanced Encryption Standard/) --- это симметричный блочный | ||
| 1821 | алгоритм шифрования, использующий ключ длиной 256 бит. Алгоритм | ||
| 1822 | работает с блоками данных размером 128 бит и применяется для | ||
| 1823 | обеспечения конфиденциальности информации. | ||
| 1824 | |||
| 1825 | В основе AES-256 лежит сеть подстановок и перестановок | ||
| 1826 | (/Substitution-Permutation Network/). Исходный блок данных | ||
| 1827 | представляется в виде матрицы байтов размером \(4 \times 4\), над | ||
| 1828 | которой последовательно выполняются раунды преобразований. Для | ||
| 1829 | AES-256 используется 14 раундов шифрования. | ||
| 1830 | |||
| 1831 | Каждый раунд, за исключением последнего, включает следующие операции: | ||
| 1832 | 1. *SubBytes* --- нелинейная замена каждого байта по таблице | ||
| 1833 | подстановок; | ||
| 1834 | 2. *ShiftRows* --- циклический сдвиг строк матрицы состояния; | ||
| 1835 | 3. *MixColumns* --- преобразование столбцов матрицы в поле \(GF(2^8)\); | ||
| 1836 | 4. *AddRoundKey* --- побитовое сложение состояния с раундовым ключом по | ||
| 1837 | модулю 2. | ||
| 1838 | |||
| 1839 | Последний раунд не содержит операцию *MixColumns*. Перед началом | ||
| 1840 | основных раундов выполняется начальное преобразование | ||
| 1841 | *AddRoundKey*. Раундовые ключи генерируются из исходного 256-битного | ||
| 1842 | ключа с помощью процедуры расширения ключа (/Key Expansion/). | ||
| 1843 | |||
| 1844 | Высокая криптографическая стойкость AES-256 достигается за счёт | ||
| 1845 | большой длины ключа, многократных раундов преобразований и сочетания | ||
| 1846 | линейных и нелинейных операций. Алгоритм широко применяется в | ||
| 1847 | современных системах защиты информации. | ||
| 1848 | |||
| 1849 | ** Шифрование с затравкой | ||
| 1850 | Шифрование «с затравкой» предполагает использование дополнительного | ||
| 1851 | параметра --- затравки (/salt/ / /IV/ / /nonce/), представляющей собой | ||
| 1852 | случайную или псевдослучайную последовательность байтов, которая | ||
| 1853 | добавляется к исходным данным или ключу перед выполнением | ||
| 1854 | криптографических преобразований. | ||
| 1855 | |||
| 1856 | Основная цель использования затравки заключается в предотвращении атак, | ||
| 1857 | связанных с предвычислением (например, радужных таблиц), а также в | ||
| 1858 | обеспечении уникальности результатов шифрования или хэширования даже | ||
| 1859 | для одинаковых входных данных. | ||
| 1860 | |||
| 1861 | Как правило, затравка генерируется отдельно для каждого сеанса или | ||
| 1862 | сообщения и передаётся вместе с зашифрованными данными либо хранится | ||
| 1863 | отдельно. При этом она не является секретной, однако должна обладать | ||
| 1864 | достаточной случайностью. | ||
| 1865 | |||
| 1866 | Таким образом, применение затравки повышает криптографическую стойкость | ||
| 1867 | системы за счёт усложнения анализа и сопоставления зашифрованных данных. | ||
| 1868 | |||
| 1869 | В данной работе используется 20 байт затравки, которые генерируются | ||
| 1870 | псевдослучайным образом для каждого сообщения перед его шифрованием. | ||
| 1871 | Сама затравка располагается непосредственно перед зашифрованными | ||
| 1872 | данными, для поддержки их потоко-ориентированного дешифрования. | ||
| 1873 | |||
| 1874 | ** Пример компиляции и сборки исполняемых модулей приложения | ||
| 1875 | На рис. [[05-build]] представлен пример компиляции и сборки исполняемых | ||
| 1876 | модулей приложения. | ||
| 1877 | |||
| 1878 | #+name: 05-build | ||
| 1879 | #+caption: Пример компиляции и сборки исполняемых модулей приложения | ||
| 1880 | #+begin_src text | ||
| 1881 | $ ./build.sh+ cc -std=gnu99 -ggdb3 -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-comment -Wno-stringop-overflow -I./src/ -o ./src/crypto.o -c ./src/crypto.c | ||
| 1882 | + cc -std=gnu99 -ggdb3 -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-comment -Wno-stringop-overflow -I./src/ -o ./src/common.o -c ./src/common.c | ||
| 1883 | + cc -std=gnu99 -ggdb3 -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-comment -Wno-stringop-overflow -I./src/ -lcrypto -o ./server ./src/crypto.o ./src/common.o ./src/server.c | ||
| 1884 | + cc -std=gnu99 -ggdb3 -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter -Wno-unused-but-set-variable -Wno-parentheses -Wno-unused-label -Wno-comment -Wno-stringop-overflow -I./src/ -lcrypto -lncurses -o ./client ./src/crypto.o ./src/common.o ./src/client.c | ||
| 1885 | #+end_src | ||
| 1886 | |||
| 1887 | ** Процедура проверки работы приложения | ||
| 1888 | На рис. [[05-test-plain-server]]-[[05-test-edc-tcpdump]] представлены примеры | ||
| 1889 | проверки работы приложения, где цветом выделены наши данные. Описание | ||
| 1890 | цветов: | ||
| 1891 | - желтый --- размер сообщения (1 Б); | ||
| 1892 | - синий --- затравка (16 Б); | ||
| 1893 | - зелёный --- данные сообщения; | ||
| 1894 | - красный --- контрольный хеш (16 Б); | ||
| 1895 | - розовый --- публичная часть ключа (20 Б); | ||
| 1896 | |||
| 1897 | *** Проверка работы без шифрования | ||
| 1898 | На рис. [[05-test-plain-server]]-[[05-test-plain-tcpdump]] представлен пример | ||
| 1899 | проверка работы без шифрования. | ||
| 1900 | |||
| 1901 | #+name: 05-test-plain-server | ||
| 1902 | #+caption: Запуск сервера без шифрования | ||
| 1903 | #+begin_src text | ||
| 1904 | $ ./server --plain --echo 0.0.0.0 1234 | ||
| 1905 | #+end_src | ||
| 1906 | |||
| 1907 | #+name: 05-test-plain-client | ||
| 1908 | #+caption: Запуск клиента без шифрования | ||
| 1909 | #+begin_src text | ||
| 1910 | $ ./client --plain 127.0.0.1 1234 | ||
| 1911 | #+end_src | ||
| 1912 | |||
| 1913 | #+name: 05-test-plain-tcpdump | ||
| 1914 | #+caption: Вывод =tcpdump= без шифрования | ||
| 1915 | #+begin_src text | ||
| 1916 | $ doas tcpdump -i lo -nn -X -A 'tcp port 1234 and (tcp[tcpflags] & tcp-push != 0)' 2>/dev/null | ||
| 1917 | 04:26:23.640654 IP 127.0.0.1.35744 > 127.0.0.1.1234: Flags [P.], seq 2631017051:2631017063, ack 3179503841, win 512, options [nop,nop,TS val 3499244821 ecr 3499237490], length 12 | ||
| 1918 | 0x0000: 4500 0040 cf95 4000 4006 6d20 7f00 0001 E..@..@.@.m..... | ||
| 1919 | 0x0010: 7f00 0001 8ba0 04d2 9cd2 225b bd83 60e1 .........."[..`. | ||
| 1920 | 0x0020: 8018 0200 fe34 0000 0101 080a d092 3d15 .....4........=. | ||
| 1921 | 0x0030: d092 2072 (*@\hlc[yellow!70]{0b}@*)(*@\hlc[green!50]{3c 636d 6d6d 3e20 7465 7374}@*) ...r(*@\hlc[yellow!70]{.}@*)(*@\hlc[green!50]{<cmmm>.test}@*) | ||
| 1922 | 04:26:23.640881 IP 127.0.0.1.1234 > 127.0.0.1.35744: Flags [P.], seq 1:13, ack 12, win 512, options [nop,nop,TS val 3499244822 ecr 3499244821], length 12 | ||
| 1923 | 0x0000: 4500 0040 9edc 4000 4006 9dd9 7f00 0001 E..@..@.@....... | ||
| 1924 | 0x0010: 7f00 0001 04d2 8ba0 bd83 60e1 9cd2 2267 ..........`..."g | ||
| 1925 | 0x0020: 8018 0200 fe34 0000 0101 080a d092 3d16 .....4........=. | ||
| 1926 | 0x0030: d092 3d15 (*@\hlc[yellow!70]{0b}@*)(*@\hlc[green!50]{3c 636d 6d6d 3e20 7465 7374}@*) ...r(*@\hlc[yellow!70]{.}@*)(*@\hlc[green!50]{<cmmm>.test}@*) | ||
| 1927 | #+end_src | ||
| 1928 | |||
| 1929 | *** Проверка работы с шифрованием | ||
| 1930 | На рис. [[05-test-ed-server]]-[[05-test-ed-tcpdump]] представлен пример | ||
| 1931 | проверка работы с шифрованием. | ||
| 1932 | |||
| 1933 | #+name: 05-test-ed-server | ||
| 1934 | #+caption: Запуск сервера с шифрованием | ||
| 1935 | #+begin_src text | ||
| 1936 | $ ./server --key aes-256.key --echo 0.0.0.0 1234 | ||
| 1937 | #+end_src | ||
| 1938 | |||
| 1939 | #+name: 05-test-ed-client | ||
| 1940 | #+caption: Запуск клиента с шифрованием | ||
| 1941 | #+begin_src text | ||
| 1942 | $ ./client --key aes-256.key 127.0.0.1 1234 | ||
| 1943 | #+end_src | ||
| 1944 | |||
| 1945 | #+name: 05-test-ed-tcpdump | ||
| 1946 | #+caption: Вывод =tcpdump= с шифрованием | ||
| 1947 | #+begin_src text | ||
| 1948 | $ doas tcpdump -i lo -nn -X -A 'tcp port 1234 and (tcp[tcpflags] & tcp-push != 0)' 2>/dev/null | ||
| 1949 | 09:10:43.556509 IP 127.0.0.1.58304 > 127.0.0.1.1234: Flags [P.], seq 1561868211:1561868228, ack 3124673098, win 512, options [nop,nop,TS val 3516111009 ecr 3516105015], length 17 | ||
| 1950 | 0x0000: 4500 0045 4f90 4000 4006 ed20 7f00 0001 E..EO.@.@....... | ||
| 1951 | 0x0010: 7f00 0001 e3c0 04d2 5d18 37b3 ba3e ba4a ........].7..>.J | ||
| 1952 | 0x0020: 8018 0200 fe39 0000 0101 080a d193 98a1 .....9.......... | ||
| 1953 | 0x0030: d193 8137 (*@\hlc[yellow!70]{10}@*)(*@\hlc[green!50]{0b 494f 4dcc c01f f4b3 7dc5}@*) ...7(*@\hlc[yellow!70]{.}@*)(*@\hlc[green!50]{.IOM.....\}.}@*) | ||
| 1954 | 0x0040: (*@\hlc[green!50]{790f 594b f3}@*) (*@\hlc[green!50]{y.YK.}@*) | ||
| 1955 | 09:10:43.556732 IP 127.0.0.1.1234 > 127.0.0.1.58304: Flags [P.], seq 1:18, ack 17, win 512, options [nop,nop,TS val 3516111009 ecr 3516111009], length 17 | ||
| 1956 | 0x0000: 4500 0045 1ddc 4000 4006 1ed5 7f00 0001 E..E..@.@....... | ||
| 1957 | 0x0010: 7f00 0001 04d2 e3c0 ba3e ba4a 5d18 37c4 .........>.J].7. | ||
| 1958 | 0x0020: 8018 0200 fe39 0000 0101 080a d193 98a1 .....9.......... | ||
| 1959 | 0x0030: d193 98a1 (*@\hlc[yellow!70]{10}@*)(*@\hlc[green!50]{0b 494f 4dcc c01f f4b3 7dc5}@*) ...7(*@\hlc[yellow!70]{.}@*)(*@\hlc[green!50]{.IOM.....\}.}@*) | ||
| 1960 | 0x0040: (*@\hlc[green!50]{790f 594b f3}@*) (*@\hlc[green!50]{y.YK.}@*) | ||
| 1961 | #+end_src | ||
| 1962 | *** Проверка работы с шифрованием и контролем целостности | ||
| 1963 | На рис. [[05-test-edc-server]]-[[05-test-edc-tcpdump]] представлен пример | ||
| 1964 | проверка работы с шифрованием и контролем целостности. | ||
| 1965 | |||
| 1966 | #+name: 05-test-edc-server | ||
| 1967 | #+caption: Запуск сервера с шифрованием и контролем целостности | ||
| 1968 | #+begin_src text | ||
| 1969 | $ ./server --key aes-256.key --check-integrity --echo 0.0.0.0 1234 | ||
| 1970 | #+end_src | ||
| 1971 | |||
| 1972 | #+name: 05-test-edc-client | ||
| 1973 | #+caption: Запуск клиента с шифрованием и контролем целостности | ||
| 1974 | #+begin_src text | ||
| 1975 | $ ./client --key aes-256.key --check-integrity 127.0.0.1 1234 | ||
| 1976 | #+end_src | ||
| 1977 | |||
| 1978 | #+name: 05-test-edc-tcpdump | ||
| 1979 | #+caption: Вывод =tcpdump= с шифрованием и контролем целостности | ||
| 1980 | #+begin_src text | ||
| 1981 | $ doas tcpdump -i lo -nn -X -A 'tcp port 1234 and (tcp[tcpflags] & tcp-push != 0)' 2>/dev/null | ||
| 1982 | 08:58:12.825762 IP 127.0.0.1.54108 > 127.0.0.1.1234: Flags [P.], seq 3200705430:3200705467, ack 2913569223, win 512, options [nop,nop,TS val 3515360278 ecr 3515358428], length 37 | ||
| 1983 | 0x0000: 4500 0059 c876 4000 4006 7426 7f00 0001 E..Y.v@.@.t&.... | ||
| 1984 | 0x0010: 7f00 0001 d35c 04d2 bec6 e396 ada9 89c7 .....\.......... | ||
| 1985 | 0x0020: 8018 0200 fe4d 0000 0101 080a d188 2416 .....M........$. | ||
| 1986 | 0x0030: d188 1cdc (*@\hlc[yellow!70]{10}@*)(*@\hlc[green!50]{0b 494f 4dcc c01f f4b3 7dc5}@*) ....(*@\hlc[yellow!70]{.}@*)(*@\hlc[green!50]{.IOM.....\}.}@*) | ||
| 1987 | 0x0040: (*@\hlc[green!50]{790f 594b f3}@*)(*@\hlc[red!50]{3e 7c17 a783 876e 3024 6041}@*) (*@\hlc[green!50]{y.YK.}@*)(*@\hlc[red!50]{>|....n0\$`A}@*) | ||
| 1988 | 0x0050: (*@\hlc[red!50]{3b30 1c89 ab9a a0a6 75}@*) (*@\hlc[red!50]{;0......u}@*) | ||
| 1989 | 08:58:12.825925 IP 127.0.0.1.1234 > 127.0.0.1.54108: Flags [P.], seq 1:38, ack 37, win 512, options [nop,nop,TS val 3515360278 ecr 3515360278], length 37 | ||
| 1990 | 0x0000: 4500 0059 e19e 4000 4006 5afe 7f00 0001 E..Y..@.@.Z..... | ||
| 1991 | 0x0010: 7f00 0001 04d2 d35c ada9 89c7 bec6 e3bb .......\........ | ||
| 1992 | 0x0020: 8018 0200 fe4d 0000 0101 080a d188 2416 .....M........$. | ||
| 1993 | 0x0030: d188 2416 (*@\hlc[yellow!70]{10}@*)(*@\hlc[green!50]{0b 494f 4dcc c01f f4b3 7dc5}@*) ..$.(*@\hlc[yellow!70]{.}@*)(*@\hlc[green!50]{.IOM.....\}.}@*) | ||
| 1994 | 0x0040: (*@\hlc[green!50]{790f 594b f3}@*)(*@\hlc[red!50]{3e 7c17 a783 876e 3024 6041}@*) (*@\hlc[green!50]{y.YK.}@*)(*@\hlc[red!50]{>|....n0\$`A}@*) | ||
| 1995 | 0x0050: (*@\hlc[red!50]{3b30 1c89 ab9a a0a6 75}@*) (*@\hlc[red!50]{;0......u}@*) | ||
| 1996 | #+end_src | ||
| 1997 | |||
| 1998 | *** Проверка работы с шифрованием с затравкой | ||
| 1999 | На рис. [[05-test-eds-server]]-[[05-test-eds-tcpdump]] представлен пример | ||
| 2000 | проверка работы с шифрованием с затравкой. | ||
| 2001 | |||
| 2002 | #+name: 05-test-eds-server | ||
| 2003 | #+caption: Запуск сервера с шифрованием с затравкой | ||
| 2004 | #+begin_src text | ||
| 2005 | $ ./server --key aes-256.key --salt --echo 0.0.0.0 1234 | ||
| 2006 | #+end_src | ||
| 2007 | |||
| 2008 | #+name: 05-test-eds-client | ||
| 2009 | #+caption: Запуск клиента с шифрованием с затравкой | ||
| 2010 | #+begin_src text | ||
| 2011 | $ ./client --key aes-256.key --salt 127.0.0.1 1234 | ||
| 2012 | #+end_src | ||
| 2013 | |||
| 2014 | #+name: 05-test-eds-tcpdump | ||
| 2015 | #+caption: Вывод =tcpdump= с шифрованием с затравкой | ||
| 2016 | #+begin_src text | ||
| 2017 | $ doas tcpdump -i lo -nn -X -A 'tcp port 1234 and (tcp[tcpflags] & tcp-push != 0)' 2>/dev/null | ||
| 2018 | 07:55:48.003886 IP 127.0.0.1.52790 > 127.0.0.1.1234: Flags [P.], seq 3340264500:3340264533, ack 2416979481, win 512, options [nop,nop,TS val 3511615456 ecr 3511614686], length 33 | ||
| 2019 | 0x0000: 4500 0055 88b3 4000 4006 b3ed 7f00 0001 E..U..@.@....... | ||
| 2020 | 0x0010: 7f00 0001 ce36 04d2 c718 6434 9010 2e19 .....6....d4.... | ||
| 2021 | 0x0020: 8018 0200 fe49 0000 0101 080a d14e ffe0 .....I.......N.. | ||
| 2022 | 0x0030: d14e fcde (*@\hlc[yellow!70]{20}@*)(*@\hlc[blue!50]{58 c54d 7b3a 9499 4737 236d}@*) .N..(*@\hlc[yellow!70]{.}@*)(*@\hlc[blue!50]{X.M\{:..G7#m}@*) | ||
| 2023 | 0x0040: (*@\hlc[blue!50]{89e8 1441 d8}@*)(*@\hlc[green!50]{8d 57d5 3866 d5d7 dbfe abd9}@*) (*@\hlc[blue!50]{...A.}@*)(*@\hlc[green!50]{.W.8f......}@*) | ||
| 2024 | 0x0050: (*@\hlc[green!50]{2c58 0e5a 98}@*) (*@\hlc[green!50]{,X.Z.}@*) | ||
| 2025 | 07:55:48.004180 IP 127.0.0.1.1234 > 127.0.0.1.52790: Flags [P.], seq 1:34, ack 33, win 512, options [nop,nop,TS val 3511615457 ecr 3511615456], length 33 | ||
| 2026 | 0x0000: 4500 0055 e921 4000 4006 537f 7f00 0001 E..U.!@.@.S..... | ||
| 2027 | 0x0010: 7f00 0001 04d2 ce36 9010 2e19 c718 6455 .......6......dU | ||
| 2028 | 0x0020: 8018 0200 fe49 0000 0101 080a d14e ffe1 .....I.......N.. | ||
| 2029 | 0x0030: d14e ffe0 (*@\hlc[yellow!70]{20}@*)(*@\hlc[blue!50]{16 5dae 57e6 2a10 0b99 5496}@*) .N..(*@\hlc[yellow!70]{.}@*)(*@\hlc[blue!50]{.].W.*...T.}@*) | ||
| 2030 | 0x0040: (*@\hlc[blue!50]{7e0f 55cd 82}@*)(*@\hlc[green!50]{9f 8c36 b83c bf16 32f0 d1c1}@*) (*@\hlc[blue!50]{~.U..}@*)(*@\hlc[green!50]{..6.<..2...}@*) | ||
| 2031 | 0x0050: (*@\hlc[green!50]{4f1a 8781 c8}@*) (*@\hlc[green!50]{O....}@*) | ||
| 2032 | #+end_src | ||
| 2033 | |||
| 2034 | *** Проверка работы алгоритма Диффи-Хелмана | ||
| 2035 | На рис. [[05-test-dh-server]]-[[05-test-dh-tcpdump]] представлен пример | ||
| 2036 | проверка работы с шифрованием с затравкой. | ||
| 2037 | |||
| 2038 | #+name: 05-test-dh-server | ||
| 2039 | #+caption: Запуск сервера с использованием алгоритма Диффи-Хелмана | ||
| 2040 | #+begin_src text | ||
| 2041 | $ ./server --dhkx --echo 0.0.0.0 1234 | ||
| 2042 | #+end_src | ||
| 2043 | |||
| 2044 | #+name: 05-test-dh-client | ||
| 2045 | #+caption: Запуск клиента с использованием алгоритма Диффи-Хелмана | ||
| 2046 | #+begin_src text | ||
| 2047 | $ ./client --dhkx --salt 127.0.0.1 1234 | ||
| 2048 | #+end_src | ||
| 2049 | |||
| 2050 | #+name: 05-test-dh-tcpdump | ||
| 2051 | #+caption: Вывод =tcpdump= с использованием алгоритма Диффи-Хелмана | ||
| 2052 | #+begin_src text | ||
| 2053 | $ doas tcpdump -i lo -nn -X -A 'tcp port 1234 and (tcp[tcpflags] & tcp-push != 0)' 2>/dev/null | ||
| 2054 | 09:21:30.598486 IP 127.0.0.1.53964 > 127.0.0.1.1234: Flags [P.], seq 816271690:816271722, ack 3763122886, win 512, options [nop,nop,TS val 3516758051 ecr 3516758051], length 32 | ||
| 2055 | 0x0000: 4500 0054 8da1 4000 4006 af00 7f00 0001 E..T..@.@....... | ||
| 2056 | 0x0010: 7f00 0001 d2cc 04d2 30a7 514a e04c b2c6 ........0.QJ.L.. | ||
| 2057 | 0x0020: 8018 0200 fe48 0000 0101 080a d19d 7823 .....H........x# | ||
| 2058 | 0x0030: d19d 7823 (*@\hlc[magenta!70]{62d8 f776 280f bac6 87c2 7033}@*) ..x#(*@\hlc[magenta!70]{b..v(.....p3}@*) | ||
| 2059 | 0x0040: (*@\hlc[magenta!70]{36a9 0563 2130 03b6 ec2d ee84 1e72 451e}@*) (*@\hlc[magenta!70]{6..c!0...-...rE.}@*) | ||
| 2060 | 0x0050: (*@\hlc[magenta!70]{a1ac da26}@*) (*@\hlc[magenta!70]{...\&}@*) | ||
| 2061 | 09:21:30.598609 IP 127.0.0.1.1234 > 127.0.0.1.53964: Flags [P.], seq 1:33, ack 32, win 512, options [nop,nop,TS val 3516758051 ecr 3516758051], length 32 | ||
| 2062 | 0x0000: 4500 0054 8ed5 4000 4006 adcc 7f00 0001 E..T..@.@....... | ||
| 2063 | 0x0010: 7f00 0001 04d2 d2cc e04c b2c6 30a7 516a .........L..0.Qj | ||
| 2064 | 0x0020: 8018 0200 fe48 0000 0101 080a d19d 7823 .....H........x# | ||
| 2065 | 0x0030: d19d 7823 (*@\hlc[magenta!70]{a17d 18cb fa9e 7b8b 47c6 eb75}@*) ..x#(*@\hlc[magenta!70]{.\}....\{.G..u}@*) | ||
| 2066 | 0x0040: (*@\hlc[magenta!70]{e4a0 226d 73ef 4d99 ceab be3c d1ac be1a}@*) (*@\hlc[magenta!70]{..\textquotedbl ms.M....<....}@*) | ||
| 2067 | 0x0050: (*@\hlc[magenta!70]{4ecf 0576}@*) (*@\hlc[magenta!70]{N..v}@*) | ||
| 2068 | #+end_src | ||
| 2069 | |||
| 2070 | ** ЗАКЛЮЧЕНИЕ | ||
| 2071 | :PROPERTIES: | ||
| 2072 | :UNNUMBERED: toc | ||
| 2073 | :END: | ||
| 2074 | В ходе выполнения работы было разработано клиент-серверное приложение, | ||
| 2075 | предназначенное для защищённого обмена сообщениями с обеспечением | ||
| 2076 | конфиденциальности и целостности передаваемых данных. Реализована | ||
| 2077 | базовая функциональность, включающая шифрование с использованием | ||
| 2078 | алгоритма AES-256, контроль целостности на основе хэш-функции SHA-1 | ||
| 2079 | и передачу данных по протоколу TCP. | ||
| 2080 | |||
| 2081 | В дополнение к основным требованиям реализованы расширенные механизмы | ||
| 2082 | безопасности: использование затравки при шифрований и генерация | ||
| 2083 | сессионного ключа по протоколу Диффи–Хеллмана на эллиптической кривой | ||
| 2084 | X25519. | ||
| 2085 | |||
| 2086 | Результаты тестирования с применением анализа сетевого трафика | ||
| 2087 | подтвердили корректность функционирования всех реализованных | ||
| 2088 | компонентов системы. | ||
| 2089 | |||
| 2090 | Исходный код приложения и скриптов запуска приведён в приложении | ||
| 2091 | [[#05-src][ПРИЛОЖЕНИЙ Ж]]. | ||
| 2092 | |||
| 2093 | * СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ | ||
| 2094 | :PROPERTIES: | ||
| 2095 | :UNNUMBERED: toc | ||
| 2096 | :END: | ||
| 2097 | #+latex: \nocite{openssl} | ||
| 2098 | #+latex: \nocite{openssl-docs} | ||
| 2099 | #+latex: \nocite{readline} | ||
| 2100 | #+latex: \nocite{readline-man} | ||
| 2101 | #+latex: \nocite{ncurses} | ||
| 2102 | #+latex: \nocite{ncurses-man} | ||
| 2103 | #+latex: \nocite{nftables} | ||
| 2104 | #+latex: \nocite{nft-man} | ||
| 2105 | #+latex: \nocite{nftables-wiki} | ||
| 2106 | #+print_bibliography: :heading none | ||
| 2107 | |||
| 2108 | * ПРИЛОЖЕНИЕ @@latex:\AlphRus{appendixcnt}\\@@ BDU:2016-00545 | ||
| 2109 | :PROPERTIES: | ||
| 2110 | :UNNUMBERED: notoc | ||
| 2111 | :CUSTOM_ID: BDU:2016-00545 | ||
| 2112 | :END: | ||
| 2113 | #+latex: \appendix{BDU:2016-00545} | ||
| 2114 | #+latex: \vspace*{\fill} | ||
| 2115 | #+attr_latex: :options [page=1] :width \textwidth | ||
| 2116 | [[./res/01/2016-00545.pdf]] | ||
| 2117 | #+latex: \vspace*{\fill} | ||
| 2118 | #+latex: \clearpage | ||
| 2119 | #+latex: \vspace*{\fill} | ||
| 2120 | #+attr_latex: :options [page=2] :width \textwidth | ||
| 2121 | [[./res/01/2016-00545.pdf]] | ||
| 2122 | #+latex: \vspace*{\fill} | ||
| 2123 | |||
| 2124 | * ПРИЛОЖЕНИЕ @@latex:\AlphRus{appendixcnt}\\@@ BDU:2020-02250 | ||
| 2125 | :PROPERTIES: | ||
| 2126 | :UNNUMBERED: notoc | ||
| 2127 | :CUSTOM_ID: BDU:2020-02250 | ||
| 2128 | :END: | ||
| 2129 | #+latex: \appendix{BDU:2020-02250} | ||
| 2130 | #+latex: \vspace*{\fill} | ||
| 2131 | #+attr_latex: :options [page=1] :width \textwidth | ||
| 2132 | [[./res/01/2020-02250.pdf]] | ||
| 2133 | #+latex: \vspace*{\fill} | ||
| 2134 | #+latex: \clearpage | ||
| 2135 | #+latex: \vspace*{\fill} | ||
| 2136 | #+attr_latex: :options [page=2] :width \textwidth | ||
| 2137 | [[./res/01/2020-02250.pdf]] | ||
| 2138 | #+latex: \vspace*{\fill} | ||
| 2139 | |||
| 2140 | * ПРИЛОЖЕНИЕ @@latex:\AlphRus{appendixcnt}\\@@ BDU:2026-00776 | ||
| 2141 | :PROPERTIES: | ||
| 2142 | :UNNUMBERED: notoc | ||
| 2143 | :CUSTOM_ID: BDU:2026-00776 | ||
| 2144 | :END: | ||
| 2145 | #+latex: \appendix{BDU:2026-00776} | ||
| 2146 | #+latex: \vspace*{\fill} | ||
| 2147 | #+attr_latex: :options [page=1] :width \textwidth | ||
| 2148 | [[./res/01/2026-00776.pdf]] | ||
| 2149 | #+latex: \vspace*{\fill} | ||
| 2150 | #+latex: \clearpage | ||
| 2151 | #+latex: \vspace*{\fill} | ||
| 2152 | #+attr_latex: :options [page=2] :width \textwidth | ||
| 2153 | [[./res/01/2026-00776.pdf]] | ||
| 2154 | #+latex: \vspace*{\fill} | ||
| 2155 | |||
| 2156 | * ПРИЛОЖЕНИЕ @@latex:\AlphRus{appendixcnt}\\@@ BDU:2025-15021 | ||
| 2157 | :PROPERTIES: | ||
| 2158 | :UNNUMBERED: notoc | ||
| 2159 | :CUSTOM_ID: BDU:2025-15021 | ||
| 2160 | :END: | ||
| 2161 | #+latex: \appendix{BDU:2025-15021} | ||
| 2162 | #+latex: \vspace*{\fill} | ||
| 2163 | #+attr_latex: :options [page=1] :width \textwidth | ||
| 2164 | [[./res/01/2025-15021.pdf]] | ||
| 2165 | #+latex: \vspace*{\fill} | ||
| 2166 | #+latex: \clearpage | ||
| 2167 | #+latex: \vspace*{\fill} | ||
| 2168 | #+attr_latex: :options [page=2] :width \textwidth | ||
| 2169 | [[./res/01/2025-15021.pdf]] | ||
| 2170 | #+latex: \vspace*{\fill} | ||
| 2171 | |||
| 2172 | * ПРИЛОЖЕНИЕ @@latex:\AlphRus{appendixcnt}\\@@ Исходный код системы аутентификации и авторизации | ||
| 2173 | :PROPERTIES: | ||
| 2174 | :UNNUMBERED: notoc | ||
| 2175 | :CUSTOM_ID: 02-src | ||
| 2176 | :END: | ||
| 2177 | #+latex: \appendix{Исходный код системы аутентификации и авторизации} | ||
| 2178 | #+include: "../02/build.sh" src sh | ||
| 2179 | #+include: "../02/install.sh" src sh | ||
| 2180 | #+include: "../02/src/passwdctl.c" src c | ||
| 2181 | #+include: "../02/src/shell.c" src c | ||
| 2182 | #+include: "../02/src/common.c" src c | ||
| 2183 | #+include: "../02/src/common.h" src c | ||
| 2184 | #+include: "../02/src/bruteforce.c" src c | ||
| 2185 | #+include: "../02/src/measure.c" src c | ||
| 2186 | #+include: "../02/src/cracking.c" src c | ||
| 2187 | #+include: "../02/src/cracking.h" src c | ||
| 2188 | |||
| 2189 | * ПРИЛОЖЕНИЕ @@latex:\AlphRus{appendixcnt}\\@@ Исходный код системы авторизации с DAC и MAC | ||
| 2190 | :PROPERTIES: | ||
| 2191 | :UNNUMBERED: notoc | ||
| 2192 | :CUSTOM_ID: 03-src | ||
| 2193 | :END: | ||
| 2194 | #+latex: \appendix{Исходный код системы авторизации с DAC и MAC} | ||
| 2195 | #+include: "../03/build.sh" src sh | ||
| 2196 | #+include: "../03/install.sh" src sh | ||
| 2197 | #+include: "../03/src/passwdctl.c" src c | ||
| 2198 | #+include: "../03/src/shell.c" src c | ||
| 2199 | #+include: "../03/src/common.c" src c | ||
| 2200 | #+include: "../03/src/common.h" src c | ||
| 2201 | |||
| 2202 | * ПРИЛОЖЕНИЕ @@latex:\AlphRus{appendixcnt}\\@@ Исходный код клиент-серверного приложения с шифрованием | ||
| 2203 | :PROPERTIES: | ||
| 2204 | :UNNUMBERED: notoc | ||
| 2205 | :CUSTOM_ID: 05-src | ||
| 2206 | :END: | ||
| 2207 | #+latex: \appendix{Исходный код клиент-серверного приложения с шифрованием} | ||
| 2208 | #+include: "../05/build.sh" src sh | ||
| 2209 | #+include: "../05/genkey.sh" src sh | ||
| 2210 | #+include: "../05/src/crypto.h" src c | ||
| 2211 | #+include: "../05/src/crypto.c" src c | ||
| 2212 | #+include: "../05/src/client.c" src c | ||
| 2213 | #+include: "../05/src/server.c" src c | ||
| 2214 | #+include: "../05/src/utils.h" src c | ||
| 2215 | #+include: "../05/src/common.h" src c | ||
| 2216 | #+include: "../05/src/common.c" src c | ||
| 2217 | |||
| 2218 | # Local Variables: | ||
| 2219 | # org-confirm-babel-evaluate: nil | ||
| 2220 | # org-export-async-init-file: "ox-init.el" | ||
| 2221 | # org-export-in-background: t | ||
| 2222 | # End: | ||
diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..3749904 --- /dev/null +++ b/doc/setup.org | |||
| @@ -0,0 +1,77 @@ | |||
| 1 | #+options: ':nil *:t -:t ::t <:t H:4 \n:nil ^:{} arch:headline | ||
| 2 | #+options: author:t broken-links:nil c:nil creator:nil | ||
| 3 | #+options: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t | ||
| 4 | #+options: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t | ||
| 5 | #+options: timestamp:nil title:t toc:nil todo:t |:t | ||
| 6 | #+creator: Emacs 30.2 (Org mode 9.8-pre) | ||
| 7 | |||
| 8 | #+select_tags: export | ||
| 9 | #+exclude_tags: noexport | ||
| 10 | |||
| 11 | #+bibliography: biblio.bib | ||
| 12 | #+cite_export: biblatex | ||
| 13 | |||
| 14 | #+latex_compiler: xelatex | ||
| 15 | #+latex_class: spbstu-report | ||
| 16 | # #+latex_class_options: [draft] | ||
| 17 | |||
| 18 | #+latex_header: \usepackage{float} | ||
| 19 | #+latex_header: \usepackage{soul} | ||
| 20 | #+latex_header: \usepackage{makecell} | ||
| 21 | # #+latex_header: \usepackage{cellspace} | ||
| 22 | # #+latex_header: \setlength\cellspacetoplimit{2ex} | ||
| 23 | # #+latex_header: \setlength\cellspacebottomlimit{2ex} | ||
| 24 | |||
| 25 | # #+latex_header: \usepackage[newfloat]{minted} | ||
| 26 | # #+latex_header: \usemintedstyle{bw} | ||
| 27 | # #+latex_header: \setminted{baselinestretch=1, linenos, breaklines, escapeinside=@@, ignorelexererrors=1} | ||
| 28 | |||
| 29 | #+latex_header: \usepackage{listings} | ||
| 30 | #+latex_header: \lstdefinelanguage{text}{ | ||
| 31 | #+latex_header: morekeywords={}, | ||
| 32 | #+latex_header: sensitive=false, | ||
| 33 | #+latex_header: morecomment=[l]{}, | ||
| 34 | #+latex_header: morestring=[b]{}, | ||
| 35 | #+latex_header: } | ||
| 36 | #+latex_header: \usepackage{xcolor} | ||
| 37 | |||
| 38 | #+latex_header: \lstset{ | ||
| 39 | #+latex_header: basicstyle=\ttfamily, | ||
| 40 | #+latex_header: numberstyle=\ttfamily, | ||
| 41 | #+latex_header: lineskip=-2pt, | ||
| 42 | #+latex_header: keywordstyle=\bfseries, | ||
| 43 | #+latex_header: identifierstyle=, | ||
| 44 | #+latex_header: commentstyle=\itshape, | ||
| 45 | #+latex_header: stringstyle=\itshape, | ||
| 46 | #+latex_header: frame=lines, | ||
| 47 | #+latex_header: numbers=left, | ||
| 48 | #+latex_header: breaklines=true, | ||
| 49 | #+latex_header: postbreak=⮡, | ||
| 50 | #+latex_header: columns=fullflexible, | ||
| 51 | #+latex_header: keepspaces=true, | ||
| 52 | #+latex_header: showstringspaces=false, | ||
| 53 | #+latex_header: tabsize=2, | ||
| 54 | #+latex_header: upquote=true, | ||
| 55 | #+latex_header: literate=, | ||
| 56 | #+latex_header: escapeinside={(*@}{@*)}, | ||
| 57 | #+latex_header: } | ||
| 58 | |||
| 59 | # #+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} | ||
| 60 | |||
| 61 | #+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} | ||
| 62 | #+latex_header: \setmainfont{Times New Roman} | ||
| 63 | #+latex_header: \setmonofont{Aporetic Serif Mono}[Ligatures=TeXOff, Contextuals=AlternateOff] | ||
| 64 | |||
| 65 | # #+latex_header: \usepackage{parskip} | ||
| 66 | #+latex_header: \usepackage{lastpage} | ||
| 67 | #+latex_header: \newcounter{bibitem} | ||
| 68 | #+latex_header: \usepackage[figure,table,bibitem,xspace]{totalcount} | ||
| 69 | #+latex_header_extra: \AtEveryBibitem{\stepcounter{bibitem}} | ||
| 70 | |||
| 71 | #+latex_header: \usepackage{tikz} | ||
| 72 | #+latex_header: \usepackage{pgfplots} | ||
| 73 | |||
| 74 | #+latex_header: \newcommand{\hlc}[2][yellow]{{% | ||
| 75 | #+latex_header: \colorlet{foo}{#1}% | ||
| 76 | #+latex_header: \sethlcolor{foo}\hl{#2}}% | ||
| 77 | #+latex_header: } | ||
diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..cba6c1e --- /dev/null +++ b/doc/spbstu-report.cls | |||
| @@ -0,0 +1,78 @@ | |||
| 1 | \NeedsTeXFormat{LaTeX2e} | ||
| 2 | \ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] | ||
| 3 | |||
| 4 | % | ||
| 5 | % Support font sizes: 12pt, 14pt | ||
| 6 | % | ||
| 7 | \DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 8 | \DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 9 | |||
| 10 | \ProcessOptions\relax | ||
| 11 | |||
| 12 | \LoadClass[a4paper]{gost-7-32} | ||
| 13 | |||
| 14 | \RequirePackage{csquotes} | ||
| 15 | \RequirePackage{amsmath} | ||
| 16 | \RequirePackage{amssymb} | ||
| 17 | \RequirePackage{adjustbox} | ||
| 18 | \RequirePackage{graphicx} | ||
| 19 | \RequirePackage{wrapfig} | ||
| 20 | \RequirePackage{rotating} | ||
| 21 | |||
| 22 | \newcommand{\@group}{}\newcommand{\group}[1]{\renewcommand{\@group}{#1}} | ||
| 23 | \newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} | ||
| 24 | \newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}} | ||
| 25 | \newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}} | ||
| 26 | \newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}} | ||
| 27 | \newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}} | ||
| 28 | \newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} | ||
| 29 | \newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} | ||
| 30 | \newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} | ||
| 31 | \newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} | ||
| 32 | \newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}} | ||
| 33 | \renewcommand{\maketitle}{ | ||
| 34 | \begin{titlepage} | ||
| 35 | \begin{center} | ||
| 36 | \vspace{2cm} | ||
| 37 | \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} | ||
| 38 | |||
| 39 | \normalsize{\@university} | ||
| 40 | |||
| 41 | \vspace{0.5cm} | ||
| 42 | \normalsize{\@institute} | ||
| 43 | |||
| 44 | \normalsize{\@school} | ||
| 45 | |||
| 46 | \normalsize{Направление \@direction} | ||
| 47 | |||
| 48 | \vspace{2cm} | ||
| 49 | \LARGE{ОТЧЁТ} | ||
| 50 | |||
| 51 | \normalsize{\@reportof} | ||
| 52 | |||
| 53 | \large{\@subject} | ||
| 54 | |||
| 55 | %% \large{\textit{\@title}} | ||
| 56 | \end{center} | ||
| 57 | |||
| 58 | \vspace{3cm} | ||
| 59 | \small{ | ||
| 60 | \begin{tabular}{lrrl} | ||
| 61 | \!\!\!Студент, & \hspace{2cm} & & \\ | ||
| 62 | \!\!\!группы \@group & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ | ||
| 63 | \!\!\!Преподаватель, & \hspace{2cm} & \\ | ||
| 64 | \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ | ||
| 65 | &&\hspace{5cm} | ||
| 66 | \end{tabular} | ||
| 67 | \begin{flushright} | ||
| 68 | \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. | ||
| 69 | \end{flushright} | ||
| 70 | } | ||
| 71 | |||
| 72 | \vspace*{\fill} | ||
| 73 | \begin{center} | ||
| 74 | \small{\@city, \@date} | ||
| 75 | \end{center} | ||
| 76 | \end{titlepage} | ||
| 77 | \setcounter{page}{2} | ||
| 78 | } | ||
