aboutsummaryrefslogtreecommitdiff
path: root/usergen.c
blob: 5a0cf3c41d43829f49adc440d1aee7ec409e36c8 (plain) (blame)
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
#define _POSIX_C_SOURCE 200809L

#include "hex.h"
#include <dynstr.h>
#include <cjson/cJSON.h>
#include <sodium.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static cJSON *dump_db(const char *const dir)
{
    int fd = -1;
    cJSON *ret = NULL, *c = NULL;
    char *buf = NULL;
    struct dynstr d;
    struct stat sb;

    dynstr_init(&d);

    if (dynstr_append(&d, "%s/db.json", dir))
    {
        fprintf(stderr, "%s: dynstr_append failed\n", __func__);
        goto end;
    }
    else if ((fd = open(d.str, O_RDONLY)) < 0)
    {
        fprintf(stderr, "%s: open(2) %s: %s\n", __func__, d.str,
            strerror(errno));
        goto end;
    }
    else if (fstat(fd, &sb))
    {
        fprintf(stderr, "%s: fstat(2) %s: %s\n", __func__, d.str,
            strerror(errno));
        goto end;
    }
    else if (sb.st_size > SIZE_MAX - 1)
    {
        fprintf(stderr, "%s: size for %s (%ju) exceeds maximum size (%zu)\n",
            __func__, d.str, (uintmax_t)sb.st_size, SIZE_MAX);
        goto end;
    }
    else if (!(buf = malloc(sb.st_size + 1)))
    {
        fprintf(stderr, "%s: malloc(3): %s\n", __func__, strerror(errno));
        goto end;
    }

    size_t rem = sb.st_size;
    char *p = buf;

    while (rem)
    {
        const ssize_t r = read(fd, p, rem);

        if (r < 0)
        {
            fprintf(stderr, "%s: read(2): %s\n", __func__, strerror(errno));
            goto end;
        }

        rem -= r;
        p += r;
    }

    buf[sb.st_size] = '\0';

    if (!(c = cJSON_Parse(buf)))
    {
        fprintf(stderr, "%s: cJSON_Parse failed\n", __func__);
        goto end;
    }

    ret = c;

end:

    if (fd >= 0 && close(fd))
    {
        fprintf(stderr, "%s: close(2): %s\n", __func__, strerror(errno));
        ret = NULL;
    }

    if (!ret)
        cJSON_Delete(c);

    dynstr_free(&d);
    free(buf);
    return ret;
}

static int getuser(char *const username, const size_t n)
{
    fputs("Username:\n", stderr);

    if (!fgets(username, n, stdin))
    {
        fputs("Failed to obtain username\n", stderr);
        return -1;
    }
    else if (strcspn(username, " \t") != strlen(username))
    {
        fputs("Username cannot contain whitespaces\n", stderr);
        return -1;
    }

    *strchr(username, '\n') = '\0';
    return 0;
}

static int checkuser(const char *const username, const cJSON *const c)
{
    const cJSON *entry, *const users = cJSON_GetObjectItem(c, "users");

    if (!users)
    {
        fputs("Could not find users in database\n", stderr);
        return -1;
    }
    else if (!cJSON_IsArray(users))
    {
        fputs("Expected JSON array for users\n", stderr);
        return -1;
    }

    cJSON_ArrayForEach(entry, users)
    {
        const cJSON *const u = cJSON_GetObjectItem(entry, "name");
        const char *dbuser;

        if (!u || !(dbuser = cJSON_GetStringValue(u)))
        {
            fputs("Missing username field in database\n", stderr);
            return -1;
        }
        else if (!strcmp(username, dbuser))
        {
            fprintf(stderr, "User %s already in database\n", username);
            return -1;
        }
    }

    return 0;
}

static int getpass(char *const password, const size_t n)
{
    int ret = -1;
    struct termios t, ne;

    fputs("Password:\n", stderr);

    if (tcgetattr(STDIN_FILENO, &t))
    {
        fprintf(stderr, "%s: tcgetattr(3): %s\n", __func__, strerror(errno));
        return -1;
    }

    ne = t;
    ne.c_lflag ^= ECHO;

    if (tcsetattr(STDIN_FILENO, TCSANOW, &ne))
    {
        fprintf(stderr, "%s: tcgetattr(3): %s\n", __func__, strerror(errno));
        return -1;
    }
    else if (!fgets(password, n, stdin))
    {
        fputs("Failed to obtain username\n", stderr);
        goto restore;
    }

    *strchr(password, '\n') = '\0';
    putchar('\n');
    ret = 0;

restore:

    if (tcsetattr(STDIN_FILENO, TCSANOW, &t))
    {
        fprintf(stderr, "%s: tcgetattr(3): %s\n", __func__, strerror(errno));
        ret = -1;
    }

    return ret;
}

static int getquota(unsigned long long *const q)
{
    char s[256], *end;

    fputs("Quota, in MiB (leave empty for unlimited quota):\n", stderr);

    if (!fgets(s, sizeof s, stdin))
    {
        fprintf(stderr, "%s: fgets(3): %s\n", __func__, strerror(errno));
        return -1;
    }

    *strchr(s, '\n') = '\0';

    if (!*s)
    {
        *q = 0;
        return 0;
    }

    errno = 0;
    *q = strtoull(s, &end, 10);

    if (errno)
    {
        fprintf(stderr, "%s: strtoull(3): %s\n", __func__, strerror(errno));
        return -1;
    }
    else if (*end)
    {
        fprintf(stderr, "Invalid quota: %s\n", s);
        return -1;
    }

    return 0;
}

static int getmethod(char *const method, const size_t n)
{
    fputs("Password hashing (sha256 [deprecated], argon2id): "
        "[argon2id]\n", stderr);

    if (!fgets(method, n, stdin))
    {
        fprintf(stderr, "%s: fgets(3): %s\n", __func__, strerror(errno));
        return -1;
    }

    *strchr(method, '\n') = '\0';

    if (!*method)
        strcpy(method, "argon2id");

    return 0;
}

static cJSON *createobj(cJSON *const c, const char *const username,
    const char *const key, const char *const method,
    const unsigned long long quota)
{
    cJSON *const ret = cJSON_CreateObject();
    char sq[sizeof "18446744073709551615"];
    const int n = snprintf(sq, sizeof sq, "%llu", quota);

    if (!ret)
    {
        fprintf(stderr, "%s: cJSON_CreateObject failed\n", __func__);
        goto failure;
    }
    else if (n < 0 || n >= sizeof sq)
    {
        fprintf(stderr, "%s: snprintf(3) failed with %d\n", __func__, n);
        goto failure;
    }
    else if (!cJSON_AddStringToObject(ret, "name", username)
        || !cJSON_AddStringToObject(ret, "key", key)
        || !cJSON_AddStringToObject(ret, "method", method)
        || (quota && !cJSON_AddStringToObject(ret, "quota", sq)))
    {
        fprintf(stderr, "%s: cJSON_AddStringToObject failed\n", __func__);
        goto failure;
    }

    return ret;

failure:
    cJSON_Delete(ret);
    return NULL;
}

static int runsha256(const char *const password, cJSON *const o)
{
    int ret = -1;
    enum {ROUNDS = 1000};
    unsigned char salt[32], sha256[crypto_hash_sha256_BYTES];
    const size_t plen = strlen(password), bufsz = sizeof salt + plen;
    char hexsha256[sizeof sha256 * 2 + 1], hexsalt[sizeof salt * 2 + 1];
    unsigned char *const buf = malloc(bufsz);

    randombytes_buf(salt, sizeof salt);

    if (!buf)
    {
        fprintf(stderr, "%s: malloc(3): %s\n", __func__, strerror(errno));
        goto end;
    }

    memcpy(buf, salt, sizeof salt);
    memcpy(buf + sizeof salt, password, plen);

    if (crypto_hash_sha256(sha256, buf, bufsz))
    {
        fprintf(stderr, "%s: crypto_hash_sha256 failed\n", __func__);
        goto end;
    }

    fprintf(stderr, "1/%d", ROUNDS);

    for (int i = 1; i < ROUNDS; i++)
    {
        if (crypto_hash_sha256(sha256, sha256, sizeof sha256))
        {
            fprintf(stderr, "%s: crypto_hash_sha256 failed\n", __func__);
            goto end;
        }

        fprintf(stderr, "\r%d/%d", i + 1, ROUNDS);
    }

    fputc('\n', stderr);

    if (hex_encode(salt, hexsalt, sizeof salt, sizeof hexsalt)
        || hex_encode(sha256, hexsha256, sizeof sha256, sizeof hexsha256))
    {
        fprintf(stderr, "%s: hex_encode failed\n", __func__);
        goto end;
    }
    else if (!cJSON_AddStringToObject(o, "salt", hexsalt)
        || !cJSON_AddStringToObject(o, "password", hexsha256))
    {
        fprintf(stderr, "%s: cJSON_AddStringToObject failed\n", __func__);
        goto end;
    }

    ret = 0;

end:
    free(buf);
    return ret;
}

static int runargon2id(const char *const password, cJSON *const o)
{
    char hashpwd[crypto_pwhash_STRBYTES];

    if (crypto_pwhash_str(hashpwd, password, strlen(password),
        crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE))
    {
        fprintf(stderr, "%s: crypto_pwhash_str failed\n", __func__);
        return -1;
    }
    else if (!cJSON_AddStringToObject(o, "password", hashpwd))
    {
        fprintf(stderr, "%s: cJSON_AddStringToObject failed\n", __func__);
        return -1;
    }

    return 0;
}

static int runmethod(const char *const method, const char *const password,
    cJSON *const o)
{
    static const struct m
    {
        const char *s;
        int (*fn)(const char *, cJSON *);
    } methods[] =
    {
        {.s = "sha256", .fn = runsha256},
        {.s = "argon2id", .fn = runargon2id}
    };

    for (size_t i = 0; i < sizeof methods / sizeof *methods; i++)
    {
        const struct m *const m = &methods[i];

        if (!strcmp(m->s, method))
            return m->fn(password, o);
    }

    fprintf(stderr, "Invalid password hashing method: %s\n", method);
    return -1;
}

static int save_db(const cJSON *const c, const char *const dir)
{
    int ret = -1;
    FILE *f = NULL;
    char *s = NULL;
    struct dynstr d;

    dynstr_init(&d);

    if (dynstr_append(&d, "%s/db.json", dir))
    {
        fprintf(stderr, "%s: dynstr_append failed\n", __func__);
        goto end;
    }
    else if (!(f = fopen(d.str, "wb")))
    {
        fprintf(stderr, "%s: fopen(3) %s: %s\n", __func__, d.str,
            strerror(errno));
        goto end;
    }
    else if (!(s = cJSON_Print(c)))
    {
        fprintf(stderr, "%s: cJSON_Print failed\n", __func__);
        goto end;
    }
    else if (fprintf(f, "%s", s) < 0)
    {
        fprintf(stderr, "%s: fprintf(3) failed\n", __func__);
        goto end;
    }

    ret = 0;

end:

    if (f && fclose(f))
    {
        fprintf(stderr, "%s: fclose(3) %s: %s\n", __func__, d.str ? d.str : "",
            strerror(errno));
        ret = -1;
    }

    cJSON_free(s);
    dynstr_free(&d);
    return ret;
}

static int mkuserdir(const char *const dir, const char *const username)
{
    int ret = -1;
    struct dynstr d;

    dynstr_init(&d);

    if (dynstr_append(&d, "%s/user", dir))
    {
        fprintf(stderr, "%s: dynstr_append failed\n", __func__);
        goto end;
    }
    else if (mkdir(d.str, 0700) && errno != EEXIST)
    {
        fprintf(stderr, "%s: mkdir(2) %s: %s\n", __func__, d.str,
            strerror(errno));
        goto end;
    }
    else if (dynstr_append(&d, "/%s", username))
    {
        fprintf(stderr, "%s: dynstr_append failed\n", __func__);
        goto end;
    }
    else if (mkdir(d.str, 0700) && errno != EEXIST)
    {
        fprintf(stderr, "%s: mkdir(2) %s: %s\n", __func__, d.str,
            strerror(errno));
        goto end;
    }

    ret = 0;

end:
    dynstr_free(&d);
    return ret;
}

int main(int argc, char *argv[])
{
    int ret = EXIT_FAILURE;
    cJSON *c = NULL, *o, *users;
    unsigned long long quota;
    unsigned char key[32];
    char username[256], password[sizeof username], method[sizeof username],
        hexkey[sizeof key * 2 + 1];
    const char *dir;

    if (argc != 2)
    {
        fprintf(stderr, "%s <dir>\n", *argv);
        goto end;
    }
    else if (sodium_init())
    {
        fprintf(stderr, "%s: sodium_init failed\n", __func__);
        goto end;
    }
    else if (!(c = dump_db((dir = argv[1]))))
    {
        fprintf(stderr, "%s: dump_db failed\n", __func__);
        goto end;
    }

    randombytes_buf(key, sizeof key);

    if (hex_encode(key, hexkey, sizeof key, sizeof hexkey))
    {
        fprintf(stderr, "%s: hex_encode failed\n", __func__);
        goto end;
    }

    if (getuser(username, sizeof username)
        || checkuser(username, c)
        || getpass(password, sizeof password)
        || getquota(&quota)
        || getmethod(method, sizeof method)
        || !(o = createobj(c, username, hexkey, method, quota)))
        goto end;
    else if (runmethod(method, password, o))
    {
        cJSON_Delete(o);
        goto end;
    }
    else if (!(users = cJSON_GetObjectItem(c, "users")))
    {
        fputs("Missing \"users\" array in database\n", stderr);
        goto end;
    }
    else if (!cJSON_IsArray(users))
    {
        fputs("Database item \"users\" not an array\n", stderr);
        goto end;
    }
    else if (!cJSON_AddItemToArray(users, o))
    {
        fprintf(stderr, "%s: cJSON_AddItemToArray failed\n", __func__);
        cJSON_Delete(o);
        goto end;
    }
    else if (mkuserdir(dir, username)
        || save_db(c, dir))
        goto end;

    ret = EXIT_SUCCESS;

end:
    cJSON_Delete(c);
    return ret;
}