: nply/authelia-fcgi-authz

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 
#define _POSIX_C_SOURCE 200809L
#include "http_client.h"
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#define FCGI_VERSION_1 1
#define FCGI_BEGIN_REQUEST 1
#define FCGI_ABORT_REQUEST 2
#define FCGI_END_REQUEST 3
#define FCGI_PARAMS 4
#define FCGI_STDOUT 6
#define FCGI_RESPONDER 1
#define FCGI_AUTHORIZER 2
#define FCGI_REQUEST_COMPLETE 0

typedef struct { unsigned char version, type, requestIdB1, requestIdB0, contentLengthB1, contentLengthB0, paddingLength, reserved; } fcgi_header;
typedef struct { char *name, *value; } param;
typedef struct { char *data; size_t len, cap; } buf;

static void *xrealloc(void *p, size_t n) { void *q = realloc(p, n); if (!q) exit(111); return q; }
static char *xstrndup(const char *s, size_t n) { char *p = malloc(n + 1); if (!p) exit(111); memcpy(p, s, n); p[n] = 0; return p; }
static void badd(buf *b, const char *p, size_t n) { if (b->len + n + 1 > b->cap) { b->cap = (b->len + n + 1) * 2 + 256; b->data = xrealloc(b->data, b->cap); } memcpy(b->data + b->len, p, n); b->len += n; b->data[b->len] = 0; }
static int read_full(int fd, void *bufp, size_t n) { char *p = bufp; while (n) { ssize_t r = read(fd, p, n); if (r == 0) return 0; if (r < 0 && errno == EINTR) continue; if (r < 0) return -1; p += r; n -= (size_t)r; } return 1; }
static int write_full(int fd, const void *bufp, size_t n) { const char *p = bufp; while (n) { ssize_t r = write(fd, p, n); if (r < 0 && errno == EINTR) continue; if (r < 0) return -1; p += r; n -= (size_t)r; } return 0; }
static int g_in = 0, g_out = 1;
static int fcgi_write(uint16_t id, uint8_t type, const char *p, size_t n) { while (n || type == FCGI_STDOUT) { uint16_t chunk = n > 65535 ? 65535 : (uint16_t)n; fcgi_header h = { FCGI_VERSION_1, type, id >> 8, id & 255, chunk >> 8, chunk & 255, 0, 0 }; if (write_full(g_out, &h, sizeof h) || (chunk && write_full(g_out, p, chunk))) return -1; if (n <= chunk) break; p += chunk; n -= chunk; } return 0; }
static void fcgi_end(uint16_t id) { unsigned char body[8] = {0,0,0,0, FCGI_REQUEST_COMPLETE,0,0,0}; fcgi_write(id, FCGI_STDOUT, "", 0); fcgi_header h = { FCGI_VERSION_1, FCGI_END_REQUEST, id >> 8, id & 255, 0, sizeof body, 0, 0 }; write_full(g_out, &h, sizeof h); write_full(g_out, body, sizeof body); }
static const char *getp(param *ps, size_t n, const char *name) { for (size_t i = 0; i < n; i++) if (!strcmp(ps[i].name, name)) return ps[i].value; return ""; }
static size_t dec_len(const unsigned char **p) { if (!(**p & 0x80)) return *(*p)++; size_t n = (((*p)[0] & 0x7f) << 24) | ((*p)[1] << 16) | ((*p)[2] << 8) | (*p)[3]; *p += 4; return n; }
static void add_params(param **ps, size_t *n, const unsigned char *p, size_t len) { const unsigned char *end = p + len; while (p < end) { size_t nl = dec_len(&p), vl = dec_len(&p); if (p + nl + vl > end) return; *ps = xrealloc(*ps, (*n + 1) * sizeof **ps); (*ps)[*n].name = xstrndup((const char *)p, nl); p += nl; (*ps)[*n].value = xstrndup((const char *)p, vl); p += vl; (*n)++; } }
static int is_auth_user_uri(const char *uri) { return !strncmp(uri, "/auth/user", 10) && (uri[10] == '\0' || uri[10] == '?'); }
static void addh(buf *h, const char *name, const char *value) { if (!value || !*value) return; badd(h, name, strlen(name)); badd(h, ": ", 2); badd(h, value, strlen(value)); badd(h, "\r\n", 2); }
static void copy_response_headers(buf *out, const char *hdrs) { const char *p = hdrs; while (p && *p) { const char *e = strstr(p, "\r\n"); if (!e) break; if (e == p) { p += 2; continue; } if (!strncasecmp(p, "HTTP/", 5) || !strncasecmp(p, "Connection:", 11) || !strncasecmp(p, "Content-Length:", 15) || !strncasecmp(p, "Transfer-Encoding:", 18)) { p = e + 2; continue; } badd(out, p, (size_t)(e - p)); badd(out, "\r\n", 2); p = e + 2; } }
static void add_variable(buf *out, const char *name, const char *value) { if (!value || !*value) return; badd(out, "Variable-", 9); badd(out, name, strlen(name)); badd(out, ": ", 2); badd(out, value, strlen(value)); badd(out, "\r\n", 2); }

static void user_info(uint16_t id, param *ps, size_t pn) {
    const char *url = getenv("AUTHELIA_USERINFO_URL"); if (!url) url = "http://127.0.0.1:9091/api/user/info";
    const char *sock = getenv("AUTHELIA_SOCKET");
    buf hs = {0}, out = {0}; addh(&hs, "Cookie", getp(ps,pn,"HTTP_COOKIE")); addh(&hs, "Accept", "application/json");
    http_response r; int ok = http_request("GET", url, sock, hs.data, NULL, &r); free(hs.data);
    char st[80]; snprintf(st, sizeof st, "Status: %ld\r\n", ok ? 500L : r.status); badd(&out, st, strlen(st)); if (!ok) { copy_response_headers(&out, r.headers); badd(&out, "Cache-Control: no-store\r\n\r\n", 27); if (r.body) badd(&out, r.body, strlen(r.body)); http_response_free(&r); } else badd(&out, "\r\n", 2);
    fcgi_write(id, FCGI_STDOUT, out.data, out.len); fcgi_end(id); free(out.data);
}

static void authorize(uint16_t id, param *ps, size_t pn) {
    const char *host = *getp(ps,pn,"HTTP_HOST") ? getp(ps,pn,"HTTP_HOST") : getp(ps,pn,"SERVER_NAME");
    const char *uri = *getp(ps,pn,"REQUEST_URI") ? getp(ps,pn,"REQUEST_URI") : getp(ps,pn,"SCRIPT_NAME");
    if (is_auth_user_uri(uri)) { user_info(id, ps, pn); return; }
    const char *url = getenv("AUTHELIA_AUTHZ_URL"); if (!url) url = "http://127.0.0.1:9091/api/authz/forward-auth";
    const char *sock = getenv("AUTHELIA_SOCKET");
    const char *https = getp(ps,pn,"HTTPS"); const char *proto = (!strcmp(https,"on") || !strcmp(https,"1")) ? "https" : "http";
    char original[4096]; snprintf(original, sizeof original, "%s://%s%s", proto, host, uri);
    buf hs = {0}, out = {0};
    addh(&hs, "X-Forwarded-Method", getp(ps,pn,"REQUEST_METHOD")); addh(&hs, "X-Forwarded-Proto", proto); addh(&hs, "X-Forwarded-Host", host); addh(&hs, "X-Forwarded-Uri", uri); addh(&hs, "X-Forwarded-For", getp(ps,pn,"REMOTE_ADDR")); addh(&hs, "X-Original-URL", original); addh(&hs, "Cookie", getp(ps,pn,"HTTP_COOKIE")); addh(&hs, "Authorization", getp(ps,pn,"HTTP_AUTHORIZATION")); addh(&hs, "Accept", getp(ps,pn,"HTTP_ACCEPT"));
    http_response r; int ok = http_request("HEAD", url, sock, hs.data, NULL, &r); free(hs.data);
    if (!ok && r.status >= 200 && r.status < 300) {
        char *u = http_header_value(r.headers, "Remote-User"), *n = http_header_value(r.headers, "Remote-Name"), *e = http_header_value(r.headers, "Remote-Email");
        badd(&out, "Status: 200 OK\r\n", 16); add_variable(&out, "REMOTE_USER", u); add_variable(&out, "AUTH_TYPE", "authelia"); add_variable(&out, "HTTP_REMOTE_USER", u); add_variable(&out, "HTTP_REMOTE_NAME", n); add_variable(&out, "HTTP_REMOTE_EMAIL", e); badd(&out, "\r\n", 2); free(u); free(n); free(e);
    } else {
        char st[80]; snprintf(st, sizeof st, "Status: %ld\r\n", ok ? 500L : r.status); badd(&out, st, strlen(st)); if (!ok) copy_response_headers(&out, r.headers); badd(&out, "\r\n", 2); if (!ok && r.body) badd(&out, r.body, strlen(r.body));
    }
    if (!ok) http_response_free(&r);
    fcgi_write(id, FCGI_STDOUT, out.data, out.len);
    fcgi_end(id);
    free(out.data);
}

static int serve_connection(int in, int out) { g_in = in; g_out = out; param *ps = NULL; size_t pn = 0; uint16_t cur = 0; for (;;) { fcgi_header h; int r = read_full(g_in, &h, sizeof h); if (r <= 0) break; uint16_t id = ((uint16_t)h.requestIdB1 << 8) | h.requestIdB0; uint16_t len = ((uint16_t)h.contentLengthB1 << 8) | h.contentLengthB0; unsigned char *content = len ? malloc(len) : NULL; if (len && !content) return 111; if (len && read_full(g_in, content, len) <= 0) return 1; if (h.paddingLength) { char pad[255]; if (read_full(g_in, pad, h.paddingLength) <= 0) return 1; } if (h.type == FCGI_BEGIN_REQUEST) { cur = id; for (size_t i=0;i<pn;i++){free(ps[i].name);free(ps[i].value);} free(ps); ps=NULL; pn=0; } else if (h.type == FCGI_PARAMS && id == cur) { if (len) add_params(&ps, &pn, content, len); else authorize(id, ps, pn); } else if (h.type == FCGI_ABORT_REQUEST) fcgi_end(id); free(content); } for (size_t i=0;i<pn;i++){free(ps[i].name);free(ps[i].value);} free(ps); return 0; }
int main(void) { for (;;) { int c = accept(0, NULL, NULL); if (c >= 0) { serve_connection(c, c); close(c); continue; } if (errno == EINTR) continue; if (errno == ENOTSOCK || errno == EINVAL) serve_connection(0, 1); break; } return 0; }