/* chat_login: see chat_login.h. */ #include "chat_login.h" /* ---- small string helpers (no libc: also built on the host) ---- */ static unsigned int c_len(const char *s) { unsigned int n = 0; while (s && s[n]) n++; return n; } static void c_copy(char *d, const char *s, unsigned int cap) { unsigned int i = 0; if (!cap) return; while (s && s[i] && i + 1 < cap) { d[i] = s[i]; i++; } d[i] = '\0'; } static int c_prefix(const char *s, const char *p) { while (*p) { if (*s != *p) return 0; s++; p++; } return 1; } static int __attribute__((unused)) c_suffix(const char *s, const char *suf) { unsigned int a = c_len(s), b = c_len(suf), i; if (b > a) return 0; for (i = 0; i < b; i++) if (s[a - b + i] != suf[i]) return 0; return 1; } /* Find needle in hay[0..len); index or -1. */ static int c_find(const char *hay, unsigned int len, const char *needle, unsigned int from) { unsigned int n = c_len(needle), i, j; if (!n || n > len) return -1; for (i = from; i + n <= len; i++) { for (j = 0; j < n; j++) if (hay[i + j] != needle[j]) break; if (j == n) return (int)i; } return -1; } /* Cloudron's consent interaction page is a bare auto-submit form, not the * login SPA:
* Return the action of such an interaction form (relative to the page). */ static int c_form_action(const char *html, unsigned int len, char *out, unsigned int cap) { unsigned int at = 0; while (at < len) { int f = c_find(html, len, "", (unsigned int)f); if (end < 0) return 0; a = c_find(html, (unsigned int)end, "action", (unsigned int)f); if (a >= 0) { unsigned int i = (unsigned int)a + 6, k = 0; char q; while (i < (unsigned int)end && (html[i] == ' ' || html[i] == '\t' || html[i] == '\r' || html[i] == '\n')) i++; if (i < (unsigned int)end && html[i] == '=') { i++; while (i < (unsigned int)end && (html[i] == ' ' || html[i] == '\t' || html[i] == '\r' || html[i] == '\n')) i++; if (i < (unsigned int)end && (html[i] == '"' || html[i] == '\'')) { q = html[i++]; while (i < (unsigned int)end && html[i] != q) { if (k + 1 >= cap) return 0; out[k++] = html[i++]; } out[k] = '\0'; if (i < (unsigned int)end && html[i] == q && c_find(out, k, "/openid/interaction/", 0) >= 0 && (c_suffix(out, "/confirm") || c_suffix(out, "/abort"))) return 1; } } } at = (unsigned int)end + 1; } return 0; } /* ---- server URL / config file ---- */ int chat_server_normalize(const char *in, char *out, unsigned int cap) { unsigned int n = 0, i = 0, len; while (in[i] == ' ' || in[i] == '\t') i++; if (!c_prefix(in + i, "https://") && !c_prefix(in + i, "http://")) { const char *pre = "https://"; while (*pre && n + 1 < cap) out[n++] = *pre++; } while (in[i] && in[i] != ' ' && in[i] != '\t' && n + 1 < cap) out[n++] = in[i++]; out[n] = '\0'; if (in[i] && in[i] != ' ' && in[i] != '\t') return -1; /* did not fit */ while (in[i] == ' ' || in[i] == '\t') i++; if (in[i]) return -1; /* embedded space */ while (n > 0 && out[n - 1] == '/') out[--n] = '\0'; len = n; /* need a host after the scheme */ if (c_prefix(out, "https://")) return len > 8 ? 0 : -1; return len > 7 ? 0 : -1; } int chat_config_parse(const char *text, unsigned int len, char *server, unsigned int scap, char *cookie, unsigned int ccap) { unsigned int i = 0; int found = 0; if (scap) server[0] = '\0'; if (ccap) cookie[0] = '\0'; while (i < len) { unsigned int s = i, e, k; char *dst = 0; unsigned int cap = 0; while (i < len && text[i] != '\n') i++; e = i; if (i < len) i++; while (e > s && (text[e - 1] == '\r' || text[e - 1] == ' ')) e--; while (s < e && (text[s] == ' ' || text[s] == '\t')) s++; if (s == e || text[s] == '#') continue; if (e - s > 7 && c_prefix(text + s, "server=")) { dst = server; cap = scap; s += 7; } else if (e - s > 7 && c_prefix(text + s, "cookie=")) { dst = cookie; cap = ccap; s += 7; } if (!dst || !cap) continue; for (k = 0; s + k < e && k + 1 < cap; k++) dst[k] = text[s + k]; dst[k] = '\0'; found = 1; } return found ? 0 : -1; } int chat_config_format(char *out, unsigned int cap, const char *server, const char *cookie) { unsigned int n = 0; #define APP(s) do { const char *ap = (s); \ while (*ap) { if (n + 1 >= cap) return -1; out[n++] = *ap++; } } while (0) APP("# NebOS chat session (the cookie is a bearer credential)\n"); APP("server="); APP(server); APP("\n"); if (cookie && cookie[0]) { APP("cookie="); APP(cookie); APP("\n"); } #undef APP out[n] = '\0'; return (int)n; } int chat_login_body(char *out, unsigned int cap, const char *user, const char *pass, const char *totp) { unsigned int n = 0; int r; #define LIT(s) do { const char *ap = (s); \ while (*ap) { if (n + 1 >= cap) return -1; out[n++] = *ap++; } } while (0) #define STR(s) do { \ r = ujson_escape(out + n, cap - n, (s)); \ if (r < 0) \ return -1; \ n += (unsigned int)r; \ } while (0) LIT("{\"username\":"); STR(user); LIT(",\"password\":"); STR(pass); LIT(",\"totpToken\":"); STR(totp ? totp : ""); LIT("}"); #undef LIT #undef STR out[n] = '\0'; return (int)n; } /* ---- page / reply parsing ---- */ static struct ujson_node pnodes[512]; static char psbuf[8192]; /* Resolve href against an absolute base URL. Handles absolute URLs, * scheme-relative, absolute-path and directory-relative references. */ static int resolve(const char *base, const char *href, char *out, unsigned int cap) { unsigned int n = 0, i, origin_end, dir_end; if (c_prefix(href, "http://") || c_prefix(href, "https://")) { if (c_len(href) + 1 > cap) return -1; c_copy(out, href, cap); return 0; } /* origin = scheme://host[:port] */ i = 0; while (base[i] && base[i] != ':') i++; if (base[i] != ':' || base[i + 1] != '/' || base[i + 2] != '/') return -1; if (href[0] == '/' && href[1] == '/') { if (i + 1 + c_len(href) + 1 > cap) return -1; for (n = 0; n <= i; n++) out[n] = base[n]; c_copy(out + n, href, cap - n); return 0; } i += 3; while (base[i] && base[i] != '/' && base[i] != '?' && base[i] != '#') i++; origin_end = i; dir_end = origin_end; while (base[i] && base[i] != '?' && base[i] != '#') { if (base[i] == '/') dir_end = i; i++; } if (href[0] == '/') { if (origin_end + c_len(href) + 1 > cap) return -1; for (n = 0; n < origin_end; n++) out[n] = base[n]; c_copy(out + n, href, cap - n); return 0; } if (dir_end + 1 + c_len(href) + 1 > cap) return -1; for (n = 0; n < dir_end; n++) out[n] = base[n]; out[n++] = '/'; c_copy(out + n, href, cap - n); return 0; } int chat_login_parse_page(const char *html, unsigned int len, const char *base_url, char *submit_url, unsigned int cap, char *app_name, unsigned int name_cap) { struct ujson j; char raw[1024]; int at, s, e, root; submit_url[0] = '\0'; if (name_cap) app_name[0] = '\0'; raw[0] = '\0'; at = c_find(html, len, "id=\"cloudron-config\"", 0); if (at >= 0) { s = c_find(html, len, ">", (unsigned int)at); e = s >= 0 ? c_find(html, len, "= 0 && e > s) { ujson_init(&j, pnodes, sizeof(pnodes) / sizeof(pnodes[0]), psbuf, sizeof(psbuf)); root = ujson_parse(&j, html + s + 1, (unsigned int)(e - s - 1)); if (root >= 0) { c_copy(raw, ujson_get_str(&j, root, "submitUrl"), sizeof(raw)); if (name_cap) c_copy(app_name, ujson_get_str(&j, root, "name"), name_cap); } } } if (!raw[0]) { /* Fallback: a plain scan, unescaping \/ only. */ at = c_find(html, len, "\"submitUrl\":\"", 0); if (at >= 0) { unsigned int i = (unsigned int)at + 13, k = 0; while (i < len && html[i] != '"' && k + 1 < sizeof(raw)) { if (html[i] == '\\' && i + 1 < len) i++; raw[k++] = html[i++]; } raw[k] = '\0'; if (i >= len || html[i] != '"') raw[0] = '\0'; } } if (!raw[0]) { if (!c_form_action(html, len, raw, sizeof(raw))) raw[0] = '\0'; } if (!raw[0]) return -1; return resolve(base_url, raw, submit_url, cap); } int chat_login_parse_reply(int status, const char *body, unsigned int len, char *redirect, unsigned int rcap, char *msg, unsigned int mcap) { struct ujson j; int root; if (rcap) redirect[0] = '\0'; if (mcap) msg[0] = '\0'; ujson_init(&j, pnodes, sizeof(pnodes) / sizeof(pnodes[0]), psbuf, sizeof(psbuf)); root = ujson_parse(&j, body, len); if (root >= 0 && ujson_type(&j, root) == UJSON_OBJECT) { const char *m = ujson_get_str(&j, root, "message"); if (!m[0]) m = ujson_get_str(&j, root, "error"); c_copy(msg, m, mcap); } if (status == 401 || status == 403) return CHAT_REPLY_DENIED; if (status != 200 || root < 0 || ujson_type(&j, root) != UJSON_OBJECT) return CHAT_REPLY_ERROR; if (ujson_truthy(&j, ujson_get(&j, root, "twoFactorRequired"))) { if (ujson_truthy(&j, ujson_get(&j, root, "totpRequired"))) return CHAT_REPLY_TOTP; return CHAT_REPLY_PASSKEY; } c_copy(redirect, ujson_get_str(&j, root, "redirectTo"), rcap); if (!redirect[0]) return CHAT_REPLY_ERROR; return CHAT_REPLY_REDIRECT; } #ifndef CHAT_LOGIN_PURE /* ---- HTTP helpers ---- */ int chat_http_body(struct uhttp *h, char *buf, unsigned int cap) { unsigned int n = 0; for (;;) { int r; if (n + 1 >= cap) { char scratch[1]; /* Full: is there more? */ r = uhttp_read(h, scratch, 1, UHTTP_IDLE_TIMEOUT_MS); buf[n] = '\0'; if (r > 0) { h->keepalive = 0; uhttp_close(h); return UHTTP_ERR_TOOLONG; } break; } r = uhttp_read(h, buf + n, cap - 1 - n, UHTTP_IDLE_TIMEOUT_MS); if (r < 0) { buf[n] = '\0'; h->keepalive = 0; uhttp_close(h); return r; } if (r == 0) break; n += (unsigned int)r; } buf[n] = '\0'; uhttp_close(h); return (int)n; } int chat_http(struct uhttp *h, const char *method, const char *url, const char *json, char *buf, unsigned int cap, unsigned int *blen) { int r; if (blen) *blen = 0; h->keepalive = 1; if (method && json) uhttp_set_method(h, method, json, c_len(json), "application/json"); else if (method) /* uhttp only sends Content-Length with a body, so a bodyless * POST carries an empty JSON object instead. */ uhttp_set_method(h, method, "{}", 2, "application/json"); else uhttp_set_method(h, 0, 0, 0, 0); r = uhttp_open(h, url, 0, 0); if (r != 0) return r; r = chat_http_body(h, buf, cap); if (r < 0) return r; if (blen) *blen = (unsigned int)r; return h->resp.status; } int chat_server_host(const char *server, char *host, unsigned int cap, int *secure) { struct uhttp_url u; if (uhttp_parse_url(server, &u) != 0) return -1; c_copy(host, u.host, cap); if (secure) *secure = u.secure; return 0; } static void set_err(struct chat_login *l, const char *a, const char *b) { unsigned int n = 0; while (a && *a && n + 1 < sizeof(l->error)) l->error[n++] = *a++; while (b && *b && n + 1 < sizeof(l->error)) l->error[n++] = *b++; l->error[n] = '\0'; } /* 1 when the response that ended at final_url is back on the Chat host. */ static int on_server(const struct chat_login *l, const char *final_url) { unsigned int n = c_len(l->server); unsigned int i; for (i = 0; i < n; i++) if (final_url[i] != l->server[i]) return 0; return final_url[n] == '\0' || final_url[n] == '/' || final_url[n] == '?'; } int chat_session_check(struct uhttp *h, struct uhttp_jar *jar, const char *server, char *buf, unsigned int cap, unsigned int *blen) { char url[CHAT_SERVER_MAX + 16]; int st; c_copy(url, server, sizeof(url)); c_copy(url + c_len(url), "/api/me", sizeof(url) - c_len(url)); h->jar = jar; h->accept = "application/json"; st = chat_http(h, 0, url, 0, buf, cap, blen); if (st == 200) return 0; if (st == 401 || st == 403) return 1; if (st > 0) return -100 - st; return st; } /* After a successful submit (or an existing provider session) the page may * still be an interaction: a consent prompt (auto-confirmed, like the web * UI does) or an abort page (no access to the app). */ static int finish(struct chat_login *l, struct uhttp *h, struct uhttp_jar *jar, const char *url, char *buf, unsigned int cap) { unsigned int len; int st, round; const char *method = 0; c_copy(l->redirect, url, sizeof(l->redirect)); for (round = 0; round < 3; round++) { h->jar = jar; h->accept = "text/html,application/json,*/*"; st = chat_http(h, method, l->redirect, 0, buf, cap, &len); if (st < 0) { set_err(l, "Login redirect failed: ", uhttp_error_string(st)); return CHAT_LOGIN_ERROR; } if (on_server(l, h->resp.final_url)) { unsigned int me_len; if (c_find(h->resp.final_url, c_len(h->resp.final_url), "error=auth_failed", 0) >= 0) { set_err(l, "The Chat server rejected the login " "(auth_failed)", 0); return CHAT_LOGIN_ERROR; } st = chat_session_check(h, jar, l->server, buf, cap, &me_len); if (st == 0) return CHAT_LOGIN_OK; set_err(l, st == 1 ? "Signed in, but the Chat session " "was not accepted" : "Session check failed", 0); return CHAT_LOGIN_ERROR; } if (chat_login_parse_page(buf, len, h->resp.final_url, l->submit_url, sizeof(l->submit_url), l->app_name, sizeof(l->app_name)) != 0) { set_err(l, "Login did not return to the Chat server", 0); return CHAT_LOGIN_ERROR; } if (c_suffix(l->submit_url, "/confirm")) { c_copy(l->redirect, l->submit_url, sizeof(l->redirect)); method = "POST"; continue; } if (c_suffix(l->submit_url, "/abort")) { set_err(l, "This account has no access to the Chat app", 0); return CHAT_LOGIN_ERROR; } /* Back at a login form: the provider wants credentials. */ return CHAT_LOGIN_FORM; } set_err(l, "Too many login interaction steps", 0); return CHAT_LOGIN_ERROR; } int chat_login_start(struct chat_login *l, struct uhttp *h, struct uhttp_jar *jar, const char *server, char *buf, unsigned int cap) { char url[CHAT_SERVER_MAX + 16]; unsigned int len; int st; l->error[0] = '\0'; l->submit_url[0] = '\0'; l->app_name[0] = '\0'; l->totp_required = 0; if (chat_server_normalize(server, l->server, sizeof(l->server)) != 0) { set_err(l, "Invalid server address", 0); return CHAT_LOGIN_ERROR; } c_copy(url, l->server, sizeof(url)); c_copy(url + c_len(url), "/auth/login", sizeof(url) - c_len(url)); h->jar = jar; h->accept = "text/html,*/*"; st = chat_http(h, 0, url, 0, buf, cap, &len); if (st < 0) { set_err(l, "Cannot reach the server: ", uhttp_error_string(st)); return CHAT_LOGIN_ERROR; } if (on_server(l, h->resp.final_url) && st == 200) { /* The provider already knew us and sent us straight back. */ unsigned int me_len; if (chat_session_check(h, jar, l->server, buf, cap, &me_len) == 0) return CHAT_LOGIN_OK; } if (st != 200) { char code[8]; unsigned int v = (unsigned int)st, k = 0, i; char tmp[8]; while (v && k < sizeof(tmp)) { tmp[k++] = (char)('0' + v % 10); v /= 10; } for (i = 0; i < k; i++) code[i] = tmp[k - 1 - i]; code[k] = '\0'; set_err(l, "Login page returned HTTP ", code); return CHAT_LOGIN_ERROR; } if (chat_login_parse_page(buf, len, h->resp.final_url, l->submit_url, sizeof(l->submit_url), l->app_name, sizeof(l->app_name)) != 0) { set_err(l, "No Cloudron login form (external SSO or passkey " "login?) - use the cookie option", 0); return CHAT_LOGIN_NOFORM; } if (c_suffix(l->submit_url, "/confirm") || c_suffix(l->submit_url, "/abort")) return finish(l, h, jar, h->resp.final_url, buf, cap); return CHAT_LOGIN_FORM; } int chat_login_submit(struct chat_login *l, struct uhttp *h, struct uhttp_jar *jar, const char *user, const char *pass, const char *totp, char *buf, unsigned int cap) { static char body[1600]; char msg[128]; unsigned int len; int st, kind; l->error[0] = '\0'; if (!l->submit_url[0]) { set_err(l, "No login form", 0); return CHAT_LOGIN_ERROR; } if (chat_login_body(body, sizeof(body), user, pass, totp) < 0) { set_err(l, "Username or password too long", 0); return CHAT_LOGIN_ERROR; } h->jar = jar; h->accept = "application/json"; st = chat_http(h, "POST", l->submit_url, body, buf, cap, &len); /* The body held the password: wipe it right away. */ { unsigned int i; for (i = 0; i < sizeof(body); i++) body[i] = 0; } if (st < 0) { set_err(l, "Login request failed: ", uhttp_error_string(st)); return CHAT_LOGIN_ERROR; } kind = chat_login_parse_reply(st, buf, len, l->redirect, sizeof(l->redirect), msg, sizeof(msg)); switch (kind) { case CHAT_REPLY_DENIED: set_err(l, msg[0] ? msg : "Username and password do not match", 0); return CHAT_LOGIN_DENIED; case CHAT_REPLY_TOTP: l->totp_required = 1; return CHAT_LOGIN_TOTP; case CHAT_REPLY_PASSKEY: set_err(l, "This account signs in with a passkey; use the " "cookie option", 0); return CHAT_LOGIN_PASSKEY; case CHAT_REPLY_REDIRECT: break; default: set_err(l, msg[0] ? msg : "Unexpected reply from the login " "server", 0); return CHAT_LOGIN_ERROR; } { char next[CHAT_URL_MAX]; /* redirectTo may be relative to the submit URL. */ if (resolve(l->submit_url, l->redirect, next, sizeof(next)) != 0) { set_err(l, "Bad login redirect", 0); return CHAT_LOGIN_ERROR; } st = finish(l, h, jar, next, buf, cap); } if (st == CHAT_LOGIN_FORM) { set_err(l, "The login server asked for the password again", 0); return CHAT_LOGIN_ERROR; } return st; } #endif