aboutsummaryrefslogtreecommitdiff
path: root/03/src/passwdctl.c
blob: b9e07a799545c9d1fa816ab6e6a6f6dda78903c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// src/passwdctl.c --- utility to manage access to protected directory
//
// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
//
// SPDX-License-Identifier: MIT
//
// Commentary:
//
// Code:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include <regex.h>
#include <unistd.h>

#include <openssl/evp.h>
#include <openssl/err.h>

#include "dynamic-array.h"
#include "string-builder.h"
#include "string-view.h"
#include "common.h"

#define SUBCOMMANDS()   \
  X (ADD,    "add")     \
  X (MODIFY, "mod")     \
  X (DELETE, "del")

#define X(SYM, STR) SUBCOMMAND_##SYM,
enum subcommand {
  SUBCOMMANDS ()
};
#undef X

#define X(SYM, STR) [SUBCOMMAND_##SYM] = STR,
char *const subcommand_tokens[] = {
  SUBCOMMANDS ()
  NULL
};
#undef X

regex_t login_regex;
regex_t comment_regex;
regex_t password_regex;

struct string_view
parse_password (struct string_view sv)
{
  if (regexec (&password_regex, sv.begin, 0, NULL, 0) != 0)
    DIE ("password doesn't match regex %s", PASSWORD_REGEX);

  return sv;
}

int
parse_id (const char *cstr)
{
  int id;
  size_t read;
  sscanf (cstr, "%d%ln", &id, &read);

  if (id < 0) DIE ("invalid id");
  if (read != strlen (cstr)) DIE ("invalid id");

  return id;
}

enum security_level
parse_security_level (const char *cstr)
{
  for (enum security_level sl = 0; sl < SL_COUNT; ++sl)
    if (strcmp (cstr, security_level_names[sl]) == 0) return sl;

  DIE ("invalid security level: %s", cstr);
}

struct string_view
parse_comment (const char *cstr)
{
  struct string_view sv = SVCSTR (cstr);

  if (SVLEN (sv) > COMMENT_MAX_LENGTH)
    DIE ("comment too long");

  if (regexec (&comment_regex, cstr, 0, NULL, 0) != 0)
    DIE ("comment doesn't match regex " COMMENT_REGEX);

  return sv;
}

struct string_view
parse_login (const char *cstr)
{
  struct string_view sv = SVCSTR (cstr);

  if (SVLEN (sv) > LOGIN_MAX_LENGTH)
    DIE ("login too long");

  if (regexec (&login_regex, cstr, 0, NULL, 0) != 0)
    DIE ("login doesn't match regex " LOGIN_REGEX);

  return sv;
}

const char *
regex_error (const regex_t *comp, int errcode)
{
  static char *error = NULL;
  size_t size = regerror (errcode, comp, NULL, 0);
  error = realloc (error, size);
  regerror (errcode, comp, error, size);
  return error;
}

void
usage (const char *progname)
{
    printf ("Usage: %s [options] COMMAND [ARGS]\n", progname);
    puts ("");
    puts ("Options:");
    puts ("  -h, --help                     display this help message and exit");
    puts ("");
    puts ("Commands:");
    puts ("  add LOGIN                      add new account");
    puts ("  mod LOGIN                      modify existing account");
    puts ("  del LOGIN                      delete account");
    puts ("");
}

int
main (int argc, char *argv[])
{
  ruid = getuid ();
  euid = geteuid ();
  seteuid (ruid);

  ERR_load_crypto_strings ();

  const char *progname = argv[0];
  if (progname == NULL)
    DIE ("unable to get program name");

  char **subcommand = &argv[1];
  if (*subcommand == NULL) {
    usage (progname);
    exit (1);
  }

  int errcode;
  errcode = regcomp (&login_regex, "^" LOGIN_REGEX "$", REG_NOSUB);
  if (errcode != 0) {
    DIE ("unable to compile login regex: %s",
         regex_error (&login_regex, errcode));
  }

  errcode = regcomp (&password_regex, "^" PASSWORD_REGEX "$", REG_NOSUB);
  if (errcode != 0) {
    DIE ("unable to compile password regex: %s",
         regex_error (&password_regex, errcode));
  }

  errcode = regcomp (&comment_regex, "^" COMMENT_REGEX "$", REG_NOSUB);
  if (errcode != 0) {
    DIE ("unable to compile comment regex: %s",
         regex_error (&comment_regex, errcode));
  }

  char *value;
  switch (getsubopt (subcommand, subcommand_tokens, &value)) {
  case SUBCOMMAND_ADD: {
    static struct option longopts[] = {
        { "help",           no_argument,       NULL, 'h' },
        { "password",       required_argument, NULL, 'p' },
        { "id",             required_argument, NULL, 'i' },
        { "security-level", required_argument, NULL, 's' },
        { "comment",        required_argument, NULL, 'c' },
        {0}
      };
    char ch;
    struct passwd_entry new_entry = { .id = -1, .security_level = SL_COUNT - 1 };
    optind = 2;
    while ((ch = getopt_long (argc, argv, ":hp:i:s:c:", longopts, NULL)) != -1) {
      switch (ch) {
      case 'h':
        printf ("Usage: %s add [options] LOGIN\n", progname);
        puts ("");
        puts ("Options:");
        puts ("  -h, --help                          display this help message and exit");
        puts ("  -p, --password PASSWORD             password of the new account");
        puts ("  -i, --id ID                         ID of the new account");
        puts ("  -s, --security-level SECURITY-LEVEL security level of the new account");
        puts ("  -c, --comment COMMENT               comment of the new account");
        puts ("");
        puts ("Security levels:");
        puts ("  top-secret");
        puts ("  secret");
        puts ("  confidential");
        puts ("  unclassified");
        puts ("");
        exit (0);
      case 'p':
        new_entry.encoded_password =
          SVDUP (encode_password (parse_password (SVCSTR (optarg))));
        break;
      case 'i': new_entry.id             = parse_id             (optarg); break;
      case 's': new_entry.security_level = parse_security_level (optarg); break;
      case 'c': new_entry.comment        = SVDUP (parse_comment (optarg)); break;
      case '?': DIE ("unknown option -%c", optopt);
      case ':': DIE ("missing argument for %s", argv[optind - 1]);
      default: DIE ("unexpected opt error");
      }
    }

    if (argv[optind] == NULL)
      DIE ("no login provided");

    if (argv[optind + 1] != NULL)
      DIE ("extra trailing arguments starting with: %s", argv[optind + 1]);

    if (getuid () != 0)
      DIE ("permission denied");

    new_entry.login = SVDUP (SVCSTR (argv[optind]));

    if (new_entry.encoded_password.begin == NULL) {
      fputs ("Password: ", stdout);
      struct string_view password = duplicate_string_view_as_cstr (parse_password (read_password ()));
      fputs ("Repeat password: ", stdout);
      struct string_view repeated = read_password ();
      if (string_view_compare (password, repeated) != 0)
        DIE ("passwords don't match");

      new_entry.encoded_password = SVDUP (encode_password (password));
    }

    struct passwd passwd = load_passwd_file ();

    int max_id = -1;
    for (struct passwd_entry *entry = passwd.items;
         entry < passwd.items + passwd.count; ++entry) {
      if (SVCMP (new_entry.login, entry->login) == 0)
        DIE ("user %.*s already exists", SVFMT (entry->login));
      if (new_entry.id == entry->id)
        DIE ("user with id %d already exists", entry->id);
      if (entry->id > max_id)
        max_id = entry->id;
    }

    if (new_entry.id < 0)
      new_entry.id = max_id + 1;

    DYNAMIC_ARRAY_APPEND (passwd, new_entry);
    save_passwd_file  (passwd);

    string_builder_printf (&passwd_log, "%u added user %.*s %d",
                           time (NULL), SVFMT (new_entry.login), new_entry.id);
    if (new_entry.comment.begin)
      string_builder_printf (&passwd_log, " (%.*s)", SVFMT (new_entry.comment));
    string_builder_printf (&passwd_log, " with security level %s\n",
                           security_level_names[new_entry.security_level]);

    close_passwd_file (passwd);
  } break;

  case SUBCOMMAND_MODIFY: {       // [-p --password=] [-i -id=] [-c --comment=] login
    static struct option longopts[] = {
        { "help",           no_argument,       NULL, 'h' },
        { "login",          required_argument, NULL, 'l' },
        { "password",       required_argument, NULL, 'p' },
        { "id",             required_argument, NULL, 'i' },
        { "security-level", required_argument, NULL, 's' },
        { "comment",        required_argument, NULL, 'c' },
        {0}
      };
    char ch;
    struct passwd_entry new_entry = { .id = -1, .security_level = SL_COUNT };
    bool prompt_for_new_password = false;
    optind = 2;
    while ((ch = getopt_long (argc, argv, ":hl:p:Pi:s:c:", longopts, NULL)) != -1) {
      switch (ch) {
      case 'h':
        printf ("Usage: %s mod [options] LOGIN\n", progname);
        puts ("");
        puts ("Options:");
        puts ("  -h, --help                          display this help message and exit");
        puts ("  -l, --login NEW_LOGIN               new login for the account");
        puts ("  -p, --password PASSWORD             new password for the account");
        puts ("  -P                                  prompt for new password for the account");
        puts ("  -i, --id ID                         new ID for the account");
        puts ("  -s, --security-level SECURITY-LEVEL new access rights for the account");
        puts ("  -c, --comment COMMENT               new comment for the account");
        puts ("");
        puts ("Security levels:");
        puts ("  top-secret");
        puts ("  secret");
        puts ("  confidential");
        puts ("  unclassified");
        puts ("");
        exit (0);
      case 'l': new_entry.login = SVDUP (parse_login (optarg)); break;
      case 'p':
        new_entry.encoded_password =
          SVDUP (encode_password (parse_password (SVCSTR (optarg))));
        break;
      case 'P': prompt_for_new_password = true; break;
      case 'i': new_entry.id             = parse_id             (optarg); break;
      case 's': new_entry.security_level = parse_security_level (optarg); break;
      case 'c': new_entry.comment        = SVDUP (parse_comment (optarg)); break;
      case '?': DIE ("unknown option -%c", optopt);
      case ':': DIE ("missing argument for %s", argv[optind - 1]);
      default: DIE ("unexpected opt error");
      }
    }

    if (argv[optind] == NULL)
      DIE ("no login provided");

    if (argv[optind + 1] != NULL)
      DIE ("extra trailing arguments starting with: %s", argv[optind + 1]);

    struct string_view login = SVCSTR (argv[optind]);
    struct passwd_entry *entry;

    struct passwd passwd = load_passwd_file ();

    if (getuid () == 0) {
      entry = lookup_login (passwd, login);
      if (!entry)
        DIE ("user %.*s not found", SVFMT (login));

      string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:",
                             time (NULL), SVFMT (entry->login), entry->id);

      if (new_entry.id != -1) {
        if (lookup_id (passwd, new_entry.id))
          DIE ("user with id %d already exists", new_entry.id);
        entry->id = new_entry.id;
        string_builder_printf (&passwd_log, " new id %d,", entry->id);
      }

      if (new_entry.security_level != SL_COUNT) {
        entry->security_level = new_entry.security_level;
        string_builder_printf (&passwd_log, " new security level %s,",
                               security_level_names[entry->security_level]);
      }
    } else {
      if (new_entry.id != -1)
        DIE ("permission to change id denied");
      if (new_entry.security_level != SL_COUNT)
        DIE ("permission to change security level denied");

      fputs ("Password: ", stdout);
      struct string_view password = parse_password (read_password ());
      entry = authenticate (passwd, login, password);
      if (!entry) exit (1);
      string_builder_printf (&passwd_log, "%u modified user %.*s with id %d:",
                             time (NULL), SVFMT (entry->login), entry->id);
    }


    if (prompt_for_new_password) {
      fputs ("New password: ", stdout);
      struct string_view password = SVDUP (parse_password (read_password ()));
      fputs ("Repeat password: ", stdout);
      struct string_view repeated = read_password ();
      if (string_view_compare (password, repeated) != 0)
        DIE ("passwords don't match");
      entry->encoded_password = SVDUP (encode_password (password));
      string_builder_printf (&passwd_log, " changed password,");
    } else if (new_entry.encoded_password.begin != NULL) {
      entry->encoded_password = new_entry.encoded_password;
      string_builder_printf (&passwd_log, " changed password,");
    }

    if (new_entry.comment.begin != NULL) {
      entry->comment = new_entry.comment;
      string_builder_printf (&passwd_log, " new comment `%.*s',", SVFMT (entry->comment));
    }

    if (new_entry.login.begin != NULL) {
      entry->login = new_entry.login;
      string_builder_printf (&passwd_log, " new login %.*s,", SVFMT (entry->login));
    }

    if (DYNAMIC_ARRAY_LAST (passwd_log) != ',')
      DIE ("no modifications supplied");
    DYNAMIC_ARRAY_LAST (passwd_log) = '\n';

    save_passwd_file  (passwd);
    close_passwd_file (passwd);
  } break;

  case SUBCOMMAND_DELETE: {       // login
    static struct option longopts[] = {
      { "help", no_argument, NULL, 'h' },
      {0}
    };

    char ch;
    optind = 2;
    while ((ch = getopt_long (argc, argv, ":h", longopts, NULL)) != -1) {
      switch (ch) {
      case 'h':
        printf ("Usage: %s del [options] LOGIN\n", progname);
        puts ("");
        puts ("Options:");
        puts ("  -h, --help                     display this help message and exit");
        puts ("");
        exit (0);
      case '?': DIE ("unknown option -%c", optopt);
      case ':': DIE ("missing argument for %s", argv[optind - 1]);
      default: DIE ("unexpected opt error");
      }
    }

    if (argv[optind] == NULL)
      DIE ("no login");

    if (argv[optind + 1] != NULL)
      DIE ("extra trailing arguments starting with: %s", argv[optind + 1]);

    if (getuid () != 0)
      DIE ("permission denied");

    struct string_view login = SVDUP (SVCSTR (argv[optind]));
    struct passwd passwd = load_passwd_file ();

    struct passwd_entry *entry;
    for (entry = passwd.items; entry < passwd.items + passwd.count; ++entry) {
      if (SVCMP (login, entry->login) == 0)
        break;
    }

    if (entry == passwd.items + passwd.count)
      DIE ("user %.*s doesn't exist", SVFMT (login));

    string_builder_printf (&passwd_log, "%u deleted user %.*s with id %d",
                           time (NULL), SVFMT (entry->login), entry->id);
    if (entry->comment.begin)
      string_builder_printf (&passwd_log, " (%.*s)", SVFMT (entry->comment));
    DYNAMIC_ARRAY_APPEND (passwd_log, '\n');

    if (entry + 1 != passwd.items + passwd.count) {
      memmove (entry, entry + 1,
               (passwd.count - (entry + 1 - passwd.items))*sizeof (*entry));
    } passwd.count -= 1;

    save_passwd_file  (passwd);
    close_passwd_file (passwd);
  } break;

  default:
    usage (progname);
    exit (strcmp (value, "-h") != 0 && strcmp (value, "--help") != 0);
  }

  append_passwd_log ();

  return EXIT_SUCCESS;
}

// src/passwdctl.c ends here