summaryrefslogtreecommitdiffstats
path: root/src/hook.c
blob: d581bc82dcca407af8539281749169094191866e (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
/* hook.c - the mode git calls, and the only one a push depends on.
 *
 * This is what `core.hooksPath` points at.  The shape is git's: an identity in
 * the environment, one "old new ref" line per ref on stdin, and a non-zero exit
 * to stop the whole push.  Nothing is asked of the client and nothing is
 * inferred from the transport, because ref names travel inside a compressed
 * request body - the hook is the first place they exist as data.
 *
 * Two facts are not in the hook's input, and only the object store has them:
 * whether "old -> new" is a fast-forward, and which branch HEAD points at.
 * Those are asked of git, and an answer that cannot be had is taken the
 * expensive way: a rewrite until proven a fast-forward, and any deletion of a
 * branch treated as the default one while HEAD itself is unknown.  Guessing the
 * cheap way would be 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.
 *
 * stdin is shut off from /dev/null: a child left holding the hook's stdin eats
 * the ref lines that have not been read yet, and a push that loses refs from
 * its own list is a push that skips checks.  stderr goes to /dev/null too, so
 * that 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;
}

/* Object ids are 40 or 64 hex digits, or all zeroes for "does not exist".
 * Anything else is a protocol oddity, and an oddity gets 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)
{
    /* Terminated by hand, and by name: execvp walks this array until it finds
     * the NULL, and an array that runs off the end takes whatever is on the
     * stack next as an argument - which is not a crash you can read, and made
     * every deletion cost admin because the answer was never received. */
    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 way */

    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;
}

/* Is old an ancestor of new? */
static int fast_forward(hook_opts o, const char *old, const char *new)
{
    /* Same as head_ref: the NULL is part of the contract, not padding. */
    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 = "/var/lib/git";
    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;
}

static int flag(const char *arg, const char *name, const char **slot)
{
    size_t n = strlen(name);

    if (strncmp(arg, name, n) != 0 || arg[n] != '=')
        return 0;
    *slot = arg + n + 1;
    return 1;
}

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;
    const char *head;
    int head_unknown;
    int seen = 0;
    int i;

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

    for (i = 0; i < argc; i++) {
        if (flag(argv[i], "--user", &o.user))
            continue;
        if (flag(argv[i], "--repo", &o.repo))
            continue;
        if (flag(argv[i], "--ff", &o.ff))
            continue;
        if (flag(argv[i], "--head", &o.head))
            continue;
        if (strcmp(argv[i], "--no-git") == 0) {
            o.use_git = 0;
            continue;
        }
        if (strcmp(argv[i], "--explain") == 0) {
            o.explain = 1;
            continue;
        }
        fprintf(stderr, "%s: authorize: unknown argument %s\n", progname, argv[i]);
        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[4];
        int nf = 0;
        char *ref;
        char *old;
        char *new;
        level_t need;
        decision_t d;

        /* Split on whitespace by hand: the object ids and refnames in this line
         * never contain it, and it keeps the reader's index the same as the
         * writer's. */
        {
            char *q = line;

            while (*q != '\0') {
                while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')
                    q++;
                if (*q == '\0')
                    break;
                fields[nf++] = q;
                while (*q != '\0' && *q != ' ' && *q != '\t' && *q != '\n' && *q != '\r')
                    q++;
                if (*q != '\0')
                    *q++ = '\0';
                if (nf == 4)
                    break;
            }
        }
        if (nf == 0)
            continue;
        if (nf != 3) {
            fprintf(stderr, "%s: deny: expected \"old new ref\", got %d field(s)\n",
                    progname, nf);
            free(line);
            free(repo);
            free((char *)head);
            return 1;
        }

        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);
            free(line);
            free(repo);
            free((char *)head);
            return 1;
        }

        if (is_zero(new)) {
            /* A deletion.  Branches cost force; the one HEAD points at costs
             * an admin, because a repository without a default branch is a
             * repository whose clones check out nothing. */
            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);
            free(line);
            free(repo);
            free((char *)head);
            return 1;
        }
        if (o.explain)
            printf("%s: allow: %s\n", progname, d.why);
    }
    free(line);
    free(repo);
    free((char *)head);

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