summaryrefslogtreecommitdiffstats
path: root/src/hook.c
blob: 1dc4445637b548055a15f27938c0879124769f63 (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
// What core.hooksPath points at.  Nothing is inferred from the transport: ref
// names travel inside a compressed request body, and this is the first place
// they exist as data.
//
// Two facts are not in the input and only git has them - is old an ancestor of
// new, and which branch is HEAD.  An answer that cannot be had is taken the
// expensive way, because guessing the cheap way is the hole.

#include "authz.h"

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#define DEV_NULL "/dev/null"

// Run a program, optionally keeping the first line of its stdout.
//
// The child gets /dev/null on stdin: one left holding the hook's stdin eats the
// ref lines not yet read, and a push that loses refs from its own list is a push
// that skips checks.  stderr is /dev/null too, so a failed lookup does not shout
// "fatal:" at the person pushing about machinery they cannot touch.

static int spawn(const char *const argv[], int capture, char **out)
{
    int fds[2] = { -1, -1 };
    int status = -1;
    pid_t pid;

    if (out != NULL)
        *out = NULL;
    if (capture && pipe(fds) != 0)
        return -1;

    pid = fork();
    if (pid < 0) {
        if (capture) {
            close(fds[0]);
            close(fds[1]);
        }
        return -1;
    }
    if (pid == 0) {
        int devnull = open(DEV_NULL, O_RDWR);

        if (devnull >= 0) {
            dup2(devnull, STDIN_FILENO);
            if (!capture)
                dup2(devnull, STDOUT_FILENO);
            dup2(devnull, STDERR_FILENO);
            if (devnull > 2)
                close(devnull);
        }
        if (capture) {
            dup2(fds[1], STDOUT_FILENO);
            close(fds[0]);
            close(fds[1]);
        }
        execvp(argv[0], (char *const *)argv);
        _exit(127);
    }

    if (capture) {
        FILE *f;

        close(fds[1]);
        f = fdopen(fds[0], "r");
        if (f != NULL) {
            char *line = NULL;
            size_t cap = 0;

            if (getline(&line, &cap, f) != -1) {
                size_t n = strlen(line);

                while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r'))
                    line[--n] = '\0';
                *out = line;
            } else {
                free(line);
            }
            fclose(f);
        } else {
            close(fds[0]);
        }
    }

    while (waitpid(pid, &status, 0) == -1)
        ;
    if (WIFEXITED(status))
        return WEXITSTATUS(status);
    return -1;
}

static int is_zero(const char *s)
{
    int i;

    if (s == NULL || s[0] == '\0')
        return 0;
    for (i = 0; s[i] != '\0'; i++) {
        if (s[i] != '0')
            return 0;
    }
    return 1;
}

// 40 or 64 hex digits, or all zeroes.  Anything else is denied rather than
// interpreted.

static int object_id_ok(const char *s)
{
    size_t i;
    int hex = 0;

    for (i = 0; s[i] != '\0'; i++) {
        char c = s[i];

        if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
              (c >= 'A' && c <= 'F')))
            return 0;
        hex++;
    }
    return hex == 40 || hex == 64;
}

static char *head_ref(hook_opts o, int *unknown)
{
    // The NULL is load-bearing: execvp walks until it finds one, and an array
    // that runs off the end passes stack garbage as an argument.  That bug was
    // silent, and every deletion cost admin.

    const char *argv[5] = { "git", "symbolic-ref", "-q", "HEAD", NULL };
    char *out = NULL;
    int rc;

    *unknown = 0;
    if (strcmp(o.head, "none") == 0)
        return NULL;
    if (strcmp(o.head, "auto") != 0)
        return xstrdup(o.head);
    if (!o.use_git)
        return NULL;            // told not to ask; so do not guess either

    rc = spawn(argv, 1, &out);
    if (rc == 0 && out != NULL && out[0] != '\0')
        return out;
    free(out);
    *unknown = 1;               // cannot tell: charge deletions the most
    return NULL;
}

static int fast_forward(hook_opts o, const char *old, const char *new)
{
    const char *argv[6] = { "git", "merge-base", "--is-ancestor",
                            NULL, NULL, NULL };
    int rc;

    if (strcmp(o.ff, "yes") == 0)
        return 1;
    if (strcmp(o.ff, "no") == 0)
        return 0;
    if (!o.use_git)
        return 0;

    argv[3] = old;
    argv[4] = new;
    rc = spawn(argv, 0, NULL);
    return rc == 0;
}

static char *derive_repo(hook_opts o)
{
    const char *e;
    const char *root;
    size_t rootlen;
    char *cwd;
    char *name;

    if (o.repo != NULL)
        return authz_norm_repo(o.repo);
    e = getenv("GIT_HOST_REPO");
    if (e != NULL && e[0] != '\0')
        return authz_norm_repo(e);

    cwd = getcwd(NULL, 0);
    if (cwd == NULL)
        return xstrdup("");
    root = getenv("GIT_REPO_ROOT");
    if (root == NULL || root[0] == '\0')
        root = DEFAULT_ROOT;        // the documented home of the repositories
    rootlen = strlen(root);
    while (rootlen > 1 && root[rootlen - 1] == '/')
        rootlen--;                       // "/var/lib/git/" is "/var/lib/git"

    if (strncmp(cwd, root, rootlen) == 0 && cwd[rootlen] == '/')
        name = cwd + rootlen + 1;
    else {
        char *slash = strrchr(cwd, '/');

        name = (slash != NULL && slash[1] != '\0') ? slash + 1 : cwd;
    }
    {
        char *out = authz_norm_repo(name);

        free(cwd);
        return out;
    }
}

static const char *identity(hook_opts o)
{
    const char *e;

    if (o.user != NULL)
        return o.user;
    e = getenv("GIT_HOST_USER");
    if (e != NULL && e[0] != '\0')
        return e;
    e = getenv("REMOTE_USER");
    if (e != NULL && e[0] != '\0')
        return e;
    return NULL;
}

// "--ff=yes" and "--ff yes" mean the same thing.  The usage text writes the
// two-word form and validate accepts both, so authorize accepts both: an option
// the help offers must not come back as "unknown argument".  getopt_long does
// both spellings, so there is nothing here but the table and what each one sets.

enum {
    OPT_USER = 128, OPT_REPO, OPT_FF, OPT_HEAD, OPT_NOGIT, OPT_EXPLAIN
};

static int parse_options(int argc, char **argv, hook_opts *o)
{
    static const struct option longopts[] = {
        { "user",    required_argument, NULL, OPT_USER    },
        { "repo",    required_argument, NULL, OPT_REPO    },
        { "ff",      required_argument, NULL, OPT_FF      },
        { "head",    required_argument, NULL, OPT_HEAD    },
        { "no-git",  no_argument,       NULL, OPT_NOGIT   },
        { "explain", no_argument,       NULL, OPT_EXPLAIN },
        { NULL, 0, NULL, 0 }
    };
    int c;

    // The leading '+' stops at the first non-option: authorize takes no
    // positional arguments, so anything that is not an option is a mistake
    // either way, and this way it is reported as the one the person typed
    // rather than as everything that followed it.

    authz_opt_reset();
    while ((c = getopt_long(argc, argv, "+:", longopts, NULL)) != -1) {
        switch (c) {
        case OPT_USER:    o->user = optarg;        break;
        case OPT_REPO:    o->repo = optarg;        break;
        case OPT_FF:      o->ff = optarg;         break;
        case OPT_HEAD:    o->head = optarg;        break;
        case OPT_NOGIT:   o->use_git = 0;          break;
        case OPT_EXPLAIN: o->explain = 1;          break;
        case ':':
            authz_opt_need_value(longopts);
            return -1;
        default:
            // getopt_long gives back no name for an option it does not know,
            // but optind has already stepped past it.
            authz_opt_unknown("authorize", argv[optind - 1]);
            return -1;
        }
    }
    if (optind < argc) {
        authz_opt_unknown("authorize", argv[optind]);
        return -1;
    }
    return 0;
}

int cmd_authorize(const policy_t *p, hook_opts o, int argc, char **argv)
{
    char *line = NULL;
    size_t cap = 0;
    ssize_t len;
    char *repo;
    const char *user;
    char *head;
    int head_unknown;
    int seen = 0;
    int status = 0;

    if (o.ff == NULL)
        o.ff = "auto";
    if (o.head == NULL)
        o.head = "auto";

    // argv[0] is the command name, which is where getopt_long expects it; the
    // options are what follows.

    if (parse_options(argc, argv, &o) != 0)
        return 64;
    if (strcmp(o.ff, "auto") != 0 && strcmp(o.ff, "yes") != 0 &&
        strcmp(o.ff, "no") != 0) {
        fprintf(stderr, "%s: --ff wants auto, yes or no\n", progname);
        return 64;
    }

    user = identity(o);
    repo = derive_repo(o);
    head = head_ref(o, &head_unknown);

    while ((len = getline(&line, &cap, stdin)) != -1) {
        char *fields[3];
        int nf;
        char *ref;
        char *old;
        char *new;
        level_t need;
        decision_t d;

        // Object ids and refnames never contain whitespace, so the same splitter
        // that reads a rule line reads one of these.  More than three fields
        // comes back as 4, which the check below refuses rather than reading
        // past the array.

        nf = authz_split_ws(line, fields, 3);
        if (nf == 0)
            continue;
        if (nf != 3) {
            fprintf(stderr, "%s: deny: expected \"old new ref\", got %d field(s)\n",
                    progname, nf);
            status = 1;
            break;
        }

        old = fields[0];
        new = fields[1];
        ref = fields[2];
        seen++;

        if (!object_id_ok(old) || !object_id_ok(new) ||
            strncmp(ref, "refs/", 5) != 0) {
            fprintf(stderr, "%s: deny: \"%s %s %s\" is not an update git would send\n",
                    progname, old, new, ref);
            status = 1;
            break;
        }

        if (is_zero(new)) {
            // The branch HEAD points at costs admin: a repository whose
            // clones check out nothing is a broken repository.

            need = LV_FORCE;
            if (head_unknown || (head != NULL && strcmp(ref, head) == 0))
                need = LV_ADMIN;
        } else if (is_zero(old)) {
            need = LV_WRITE;                     // a creation
        } else {
            need = fast_forward(o, old, new) ? LV_WRITE : LV_FORCE;
        }

        authz_check(p, user, repo, need, ref, &d);
        if (!d.allowed) {
            fprintf(stderr, "%s: deny: %s\n", progname, d.why);
            status = 1;
            break;
        }
        if (o.explain)
            printf("%s: allow: %s\n", progname, d.why);
    }

    // One exit path, so nothing added later can forget one of these.

    free(line);
    free(repo);
    free(head);

    if (seen == 0 && o.explain && status == 0)
        printf("%s: nothing to check\n", progname);
    return status;
}