summaryrefslogtreecommitdiffstats
path: root/modules/slock/validate.c
blob: aabec058242b139406fee27fd9bb340efdfe6a13 (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
// enstate's validator for text/x-crypt-hash (enstate's docs/design.md,
// 5.2): objects to each slot under IN/channels that preload.c couldn't
// use, i.e. that isn't one line of at most 4095 bytes that crypt accepts
// as a setting.
//
// usage: validate IN OUT

#include <crypt.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

static void object(const char *channel, const char *slot, const char *message) {
  printf("{\"address\": \"%s/%s\", \"message\": \"%s\"}\n", channel, slot, message);
}

static void check(const char *path, const char *channel, const char *slot) {
  char hash[4096];
  FILE *f = fopen(path, "r");
  if (f == NULL) {
    object(channel, slot, "cannot be read");
    return;
  }
  size_t n = fread(hash, 1, sizeof hash, f);
  fclose(f);
  if (n == sizeof hash) {
    object(channel, slot, "is longer than 4095 bytes");
    return;
  }
  if (n > 0 && hash[n - 1] == '\n') {
    n--;
  }
  hash[n] = '\0';
  if (n == 0) {
    object(channel, slot, "is empty");
    return;
  }
  if (strlen(hash) != n || strchr(hash, '\n') != NULL) {
    object(channel, slot, "is not one line");
    return;
  }
  const char *result = crypt("", hash);
  if (result == NULL || result[0] == '*' || strlen(result) != n) {
    object(channel, slot, "is not a password hash that crypt accepts");
  }
}

int main(int argc, char **argv) {
  if (argc != 3) {
    fprintf(stderr, "usage: validate IN OUT\n");
    return 1;
  }
  char path[4096];
  snprintf(path, sizeof path, "%s/channels", argv[1]);
  DIR *channels = opendir(path);
  if (channels == NULL) {
    return 0;
  }
  struct dirent *channel;
  while ((channel = readdir(channels)) != NULL) {
    if (channel->d_name[0] == '.') {
      continue;
    }
    snprintf(path, sizeof path, "%s/channels/%s", argv[1], channel->d_name);
    DIR *slots = opendir(path);
    if (slots == NULL) {
      continue;
    }
    struct dirent *slot;
    while ((slot = readdir(slots)) != NULL) {
      if (slot->d_name[0] == '.') {
        continue;
      }
      snprintf(path, sizeof path, "%s/channels/%s/%s",
               argv[1], channel->d_name, slot->d_name);
      check(path, channel->d_name, slot->d_name);
    }
    closedir(slots);
  }
  closedir(channels);
  return 0;
}