summaryrefslogtreecommitdiffstats
path: root/cmd/main.c
blob: 852f131569b5511142fc30e0eb613f910a35cb50 (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
// One program, because check and the hook have to agree exactly about what a
// rule means: a check that answers differently from the hook is a program that
// lies.  Exit status is the interface: 0 allowed, 1 denied, 3 the host is
// broken rather than this person (no usable policy, or input that was never a
// push), 64 usage.

#include "authz.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define POLICY_ENV "GIT_HOST_AUTHZ"
#define DEFAULT_POLICY "/etc/git-host/authz.conf"

enum { OPT_POLICY = 128, OPT_HELP };

static void usage(FILE *f)
{
    fprintf(f,
"usage: git-authz [--policy PATH] <command> [arguments]\n"
"\n"
"  check <user> <repo> <write|force|admin> [ref]\n"
"        one question: allow or deny on stdout, the reason with it.  This is\n"
"        where the reason for a refusal is read out; the hook does not give it.\n"
"        Without a ref it asks about the repository as a whole.\n"
"\n"
"  authorize    read a push exactly as git's receive hook does - identity from\n"
"        GIT_HOST_USER (ssh) or REMOTE_USER (http), one \"old new ref\" line per\n"
"        ref on stdin - and deny the push on the first ref it may not allow.\n"
"        This also runs as 'pre-receive', which is how core.hooksPath finds it.\n"
"        A denial is one line naming the input it refused, and nothing else:\n"
"        the reason is what check is for.\n"
"          --user U --repo R     override the identity and the repository\n"
"          --ff auto|yes|no      whether to ask git if old is an ancestor of new\n"
"          --head auto|none|REF  the default branch, or how to treat deletions\n"
"          --no-git              ask git nothing (an unknown HEAD is not guessed)\n"
"          --explain             print the reason, and the allows too\n"
"\n"
"  validate     is the policy parseable, and is it sane?\n"
"          --strict              warnings are failures too\n"
"\n"
"Levels are monotone: admin implies force implies write.  '@all' means everyone\n"
"the policy already names.  \"main\", \"heads/main\" and \"refs/heads/main\" are the\n"
"same branch; a bare name is always a branch and never a tag.  A rule says what\n"
"it says: nothing else in the file can raise the price of a ref.\n"
"\n"
"Exit status: 0 allowed, 1 denied, 64 for usage, and 3 when the host is broken\n"
"rather than this person: nothing is allowed on a policy that cannot be read\n"
"('invalid policy file'), and a hook handed something that is not a push says\n"
"'invalid operation' - a real git never sends that.\n");
}

// 3 and not 1: a push refused because the host is broken has to sound different
// from one refused because the person is not allowed.  Every 3 is one line, and
// which of them it is is all a monitor has to tell; what is wrong with the policy
// is `validate`'s job, and it says so with line numbers.

static int deny_policy(void)
{
    fprintf(stderr, "%s: invalid policy file\n", progname);
    return 3;
}

// Split out of main so the policy is freed on every exit path: a short-lived
// process can leave the heap to the kernel, but then the sanitizer reports
// forty leaks and stops showing the one that matters.

enum {
    OPT_STRICT = 128
};

static int parse_validate(int argc, char **argv, validate_opts *vo)
{
    static const struct option longopts[] = {
        { "strict", no_argument, NULL, OPT_STRICT },
        { NULL, 0, NULL, 0 }
    };
    int c;

    authz_opt_reset();
    while ((c = getopt_long(argc, argv, "+:", longopts, NULL)) != -1) {
        switch (c) {
        case OPT_STRICT: vo->strict = 1; break;
        case ':':
            authz_opt_need_value(longopts);
            return -1;
        default:
            authz_opt_unknown("validate", argv[optind - 1]);
            return -1;
        }
    }
    if (optind < argc) {
        authz_opt_unknown("validate", argv[optind]);
        return -1;
    }
    return 0;
}

static int dispatch(policy_t *p, int rc, const char *cmd, int argc, char **argv,
                    hook_opts ho, validate_opts vo)
{
    // argv[0] is the command name, which is where getopt_long expects argv[0]
    // to be.  A command's own positional arguments therefore start at argv[1].

    if (strcmp(cmd, "validate") == 0) {
        if (parse_validate(argc, argv, &vo) != 0)
            return 64;
        // A policy that does not parse is the finding, so it is passed down
        // rather than exiting 3 here.

        return cmd_validate(p, vo);
    }

    if (strcmp(cmd, "authorize") == 0) {
        if (rc != 0)
            return deny_policy();
        return cmd_authorize(p, ho, argc, argv);
    }

    if (strcmp(cmd, "check") == 0) {
        decision_t d;
        char msg[AUTHZ_MSGSZ];
        int level;

        argc--;
        argv++;
        if (argc < 3 || argc > 4) {
            fprintf(stderr, "%s: check wants <user> <repo> <level> [ref]\n", progname);
            return 64;
        }
        // Only the level: check answers a question about names as written, so a
        // user or repository it would not recognise is an answer, not a usage error.
        if (authz_rule_validate(NULL, NULL, argv[2], NULL, 0,
                                msg, sizeof(msg)) != 0) {
            fprintf(stderr, "%s: %s\n", progname, msg);
            return 64;
        }
        level = authz_level_of(argv[2]);
        if (rc != 0)
            return deny_policy();
        authz_check(p, argv[0], argv[1], (level_t)level, argc > 3 ? argv[3] : NULL, &d);
        printf("%s: %s\n", d.allowed ? "allow" : "deny", d.why);
        return d.allowed ? 0 : 1;
    }

    fprintf(stderr, "%s: unknown command \"%s\"\n", progname, cmd);
    usage(stderr);
    return 64;
}

int main(int argc, char **argv)
{
    static const struct option longopts[] = {
        { "policy", required_argument, NULL, OPT_POLICY },
        { "help",   no_argument,       NULL, OPT_HELP   },
        { NULL, 0, NULL, 0 }
    };
    const char *path;
    const char *base;
    const char *cmd;
    policy_t p;
    hook_opts ho;
    validate_opts vo;
    int c;
    int rc;
    int status;

    base = strrchr(argv[0], '/');
    progname = base != NULL ? base + 1 : argv[0];

    path = getenv(POLICY_ENV);
    if (path == NULL || path[0] == '\0')
        path = DEFAULT_POLICY;

    memset(&ho, 0, sizeof(ho));
    ho.use_git = 1;
    memset(&vo, 0, sizeof(vo));

    // Reached through the hook symlink: git's arguments are not this program's,
    // so they are dropped, and the policy comes from the environment.  The one
    // element is the command-name slot getopt_long expects at argv[0].

    if (strcmp(progname, "pre-receive") == 0) {
        char *hook_argv[] = { (char *)"pre-receive", NULL };

        policy_init(&p, path);

        // Reached by the name git calls, so everything it prints is read by the
        // person pushing.  The policy's own complaints - line number, errno -
        // are for whoever owns the file, and are not in this output.

        p.log = NULL;
        rc = policy_load(&p);
        if (rc != 0) {
            policy_free(&p);
            return deny_policy();
        }
        status = cmd_authorize(&p, ho, 1, hook_argv);
        policy_free(&p);
        return status;
    }

    // Options before the command are the program's own.  The '+' in the optstring
    // is what stops getopt at the command name rather than permuting past it.

    authz_opt_reset();
    while ((c = getopt_long(argc, argv, "+:h", longopts, NULL)) != -1) {
        switch (c) {
        case OPT_POLICY:
            path = optarg;
            break;
        case OPT_HELP:
        case 'h':
            usage(stdout);
            return 0;
        case ':':
            authz_opt_need_value(longopts);
            return 64;
        default:
            fprintf(stderr, "%s: unknown option before the command: %s\n",
                    progname, argv[optind - 1]);
            usage(stderr);
            return 64;
        }
    }
    if (optind >= argc) {
        usage(stderr);
        return 64;
    }

    // argv[0] is the command from here on - which is where getopt_long expects
    // argv[0] to be, so validate and authorize parse it as it stands, and the
    // commands that take names step over it.

    cmd = argv[optind];
    argc -= optind;
    argv += optind;

    if (strcmp(cmd, "help") == 0 || strcmp(cmd, "-h") == 0 ||
        strcmp(cmd, "--help") == 0) {
        usage(stdout);
        return 0;
    }

    policy_init(&p, path);

    // authorize mode answers a person pushing, whoever invoked it: the mode is
    // the audience, so the file's line numbers stay out of its output.

    if (strcmp(cmd, "authorize") == 0)
        p.log = NULL;
    rc = policy_load(&p);
    status = dispatch(&p, rc, cmd, argc, argv, ho, vo);
    policy_free(&p);
    return status;
}