#!/usr/bin/env python3 """Sign in to an app on the Core as a browser would, with the test account. Used by `coreapp signin`; the password comes on stdin. signin.py [--cookies FILE] [--form ACTION] Open start-url (the app's page that starts sign-in), follow the redirects to the Core's Authelia, sign in, follow them back to the app, and say where it ended. If start-url is a page whose form starts sign-in (a button, with hidden fields only, e.g. a CSRF token), submit it, as a person pressing the button would: the only such form, or the one whose action is ACTION. Without such a form, follow its one link whose text names Core SSO or Authelia. When it doesn't end signed in, it prints the error or notice the app's page shows. signin.py --code [--pkce] For apps whose sign-in starts in the browser's JavaScript: start at Authelia's authorization with the app's client, sign in, and stop at the app's callback: print it, with the code (and the PKCE verifier). Each step is printed; values of codes, states and such are left out. Exits 0 when signed in, 1 when not. """ import base64 import hashlib import html.parser import http.cookiejar import json import re import secrets import sys import urllib.error import urllib.parse import urllib.request MAX_STEPS = 25 # Query values worth showing (the rest are secrets or noise) SHOWN = {"client_id", "redirect_uri", "scope", "response_type", "response_mode", "code_challenge_method", "error", "error_description", "error_hint", "flow"} class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None def shown(url): """url without the values that aren't for printing.""" parts = urllib.parse.urlsplit(url) query = [f"{k}={v}" if k in SHOWN else f"{k}=…" for k, v in urllib.parse.parse_qsl(parts.query, keep_blank_values=True)] return urllib.parse.urlunsplit(parts._replace(query="&".join(query))) def errors(url): q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query)) return {k: q[k] for k in ("error", "error_description", "error_hint") if k in q} class Browser: def __init__(self, jar): self.jar = jar # Where sign-in started (the path, and a pressed form's action) self.signin_urls = [] self.opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(jar), NoRedirect) def request(self, url, data=None, headers=None): """(status, Location or "", body) for one request, no redirects.""" req = urllib.request.Request(url, data=data, headers={ "User-Agent": "coreapp-signin", "Accept": "text/html,application/json,*/*", **{k: v for k, v in (headers or {}).items() if v}}) try: with self.opener.open(req, timeout=30) as r: return r.status, "", r.read(200_000) except urllib.error.HTTPError as e: location = e.headers.get("Location", "") return e.code, urllib.parse.urljoin(url, location) if location else "", e.read(200_000) class Forms(html.parser.HTMLParser): """The forms on a page: method, action, hidden values, whether a person has to fill something in, and the button's text.""" FILLED = {"hidden", "submit", "button", "image", "reset"} def __init__(self): super().__init__() self.forms = [] self.form = None self.in_button = False def handle_starttag(self, tag, attrs): a = dict(attrs) if tag == "form": self.form = {"method": (a.get("method") or "get").lower(), "action": a.get("action") or "", "fields": [], "to_fill": False, "button": ""} self.forms.append(self.form) elif self.form is None: return elif tag == "input": kind = (a.get("type") or "text").lower() if kind == "hidden" and a.get("name"): self.form["fields"].append((a["name"], a.get("value") or "")) elif kind not in self.FILLED: self.form["to_fill"] = True elif kind == "submit" and not self.form["button"]: self.form["button"] = a.get("value") or "" elif tag in ("textarea", "select"): self.form["to_fill"] = True elif tag == "button": self.in_button = True def handle_endtag(self, tag): if tag == "form": self.form = None elif tag == "button": self.in_button = False def handle_data(self, data): if self.form is not None and self.in_button and data.strip(): self.form["button"] = (self.form["button"] + " " + data.strip()).strip() class Links(html.parser.HTMLParser): """The page's links that start sign-in with the Core: their text (or title or aria-label) names Core SSO or Authelia, as Coreapps label it.""" NAMES = re.compile(r"core\s*sso|authelia", re.I) def __init__(self): super().__init__() self.found, self.href, self.text = [], None, "" def handle_starttag(self, tag, attrs): if tag == "a": a = dict(attrs) self.href = a.get("href") self.text = " ".join(filter(None, [a.get("title"), a.get("aria-label")])) def handle_data(self, data): if self.href is not None: self.text += " " + data def handle_endtag(self, tag): if tag == "a" and self.href is not None: text = " ".join(self.text.split()) if self.NAMES.search(text) and not self.href.startswith(("#", "javascript:")): self.found.append((self.href, text)) self.href = None def pick_link(page_url, body): """(url, label) for the page's one Core SSO link, or None.""" parser = Links() parser.feed(body.decode(errors="replace")) urls = {} for href, text in parser.found: urls.setdefault(urllib.parse.urljoin(page_url, href), text) if len(urls) != 1: return None url, text = next(iter(urls.items())) return url, f"the link \"{text[:60]}\"" class Messages(html.parser.HTMLParser): """Text the page shows as an error or notice: elements whose class, id or role says alert, error, notice, flash or the like.""" KINDS = re.compile(r"alert|error|danger|warning|notice|notification|flash|toast|invalid", re.I) VOID = {"br", "img", "input", "meta", "link", "hr", "wbr", "source"} def __init__(self): super().__init__() self.depth, self.parts, self.found = 0, [], [] def handle_starttag(self, tag, attrs): if tag in self.VOID: return if self.depth: self.depth += 1 return a = dict(attrs) marks = " ".join(filter(None, [a.get("class"), a.get("id"), a.get("role")])) if tag not in ("script", "style", "template") and self.KINDS.search(marks): self.depth, self.parts = 1, [] def handle_endtag(self, tag): if tag in self.VOID or not self.depth: return self.depth -= 1 if not self.depth: text = " ".join(" ".join(self.parts).split()) if text and text not in self.found: self.found.append(text) def handle_data(self, data): if self.depth: self.parts.append(data) def page_says(body): """' The page says: "..."' with its visible error or notice, or ''.""" parser = Messages() try: parser.feed(body.decode(errors="replace")) except Exception: return "" text = "; ".join(parser.found)[:300] return f' The page says: "{text}".' if text else "" def pick_form(page_url, body, wanted): """(url, data, label) for the form that starts sign-in, or None.""" parser = Forms() parser.feed(body.decode(errors="replace")) for f in parser.forms: f["url"] = urllib.parse.urljoin(page_url, f["action"]) if wanted: target = urllib.parse.urljoin(page_url, wanted) forms = [f for f in parser.forms if f["url"].split("?")[0] == target.split("?")[0]] if not forms: actions = ", ".join(sorted({urllib.parse.urlsplit(f["url"]).path for f in parser.forms})) raise SystemExit(f"Not signed in: {shown(page_url)} has no form with action {wanted}" f" (its forms: {actions or 'none'}).") else: forms = [f for f in parser.forms if not f["to_fill"]] if len(forms) > 1: actions = ", ".join(urllib.parse.urlsplit(f["url"]).path for f in forms) raise SystemExit(f"Not signed in: {shown(page_url)} has several forms that could start " f"sign-in ({actions}): pick one with --form .") if not forms: return None f = forms[0] data = urllib.parse.urlencode(f["fields"]) if f["method"] == "post": return f["url"], data.encode(), f"the form's button \"{f['button']}\"" return f["url"].split("?")[0] + ("?" + data if data else ""), None, f"the form's button \"{f['button']}\"" def sign_in(browser, portal_url, username, password): """Authelia's login page reached: sign in with its API, as its page does. Returns where Authelia sends the browser next.""" parts = urllib.parse.urlsplit(portal_url) q = dict(urllib.parse.parse_qsl(parts.query)) body = {"username": username, "password": password, "keepMeLoggedIn": False} if q.get("flow"): body.update(flow=q["flow"], flowID=q.get("flow_id", "")) if q.get("subflow"): body["subflow"] = q["subflow"] elif q.get("rd"): body.update(targetURL=q["rd"], requestMethod=q.get("rm", "GET")) origin = f"{parts.scheme}://{parts.netloc}" status, _, raw = browser.request(origin + "/api/firstfactor", json.dumps(body).encode(), { "Content-Type": "application/json", "Origin": origin}) try: reply = json.loads(raw) except ValueError: reply = {} print(f" POST {origin}/api/firstfactor (as {username}) -> {status} {reply.get('status', '')}") if status != 200 or reply.get("status") != "OK": message = reply.get("message") or raw[:200].decode(errors="replace") raise SystemExit(f"Not signed in: Authelia refused the test account: {message}") return urllib.parse.urljoin(origin, (reply.get("data") or {}).get("redirect", "") or "/") def follow(browser, url, username, password, stop_at=None, form=None): """Follow a browser's way from url. Returns (last url, status, body, whether it signed in at Authelia).""" auth_host = None signed_in = False submitted = False data, label, referer = None, "", None for _ in range(MAX_STEPS): if stop_at and url.startswith(stop_at): return url, None, b"", signed_in if data is not None: parts = urllib.parse.urlsplit(url) status, location, body = browser.request(url, data, { "Content-Type": "application/x-www-form-urlencoded", "Origin": f"{parts.scheme}://{parts.netloc}", "Referer": referer}) print(f" POST {shown(url)} ({label}) -> {status}") data = None else: status, location, body = browser.request(url) print(f" GET {shown(url)}{f' ({label})' if label else ''} -> {status}") label = "" err = errors(location or url) if err: raise SystemExit("Not signed in: " + ", ".join(f"{k}: {v}" for k, v in err.items())) host = urllib.parse.urlsplit(url).netloc if "/api/oidc/authorization" in url: auth_host = host if location: url = location continue if host == auth_host and status == 200 and b" picks a form); if the app starts it in the browser's JavaScript, " "use --code.") if urllib.parse.urlsplit(last).netloc != app.netloc: raise SystemExit(f"Not signed in: it ended at {shown(last)} (HTTP {status}), not at the app.") if status >= 400: raise SystemExit(f"Not signed in: Authelia accepted the test account, but the app answered " f"HTTP {status} at {shown(last)}.{page_says(body)} (coreapp logs may say " "more.)") text = re.sub(rb"<[^>]+>", b" ", body).decode(errors="replace") mentions = username.split("@")[0] in text # Back at the app isn't signed in if the app's page offers sign-in again # (its callback failed quietly and sent the browser to its sign-in page) page = body.decode(errors="replace") starts = {urllib.parse.urlsplit(u).path for u in [start] + browser.signin_urls} targets = {urllib.parse.urlsplit(urllib.parse.urljoin(last, t)).path for t in re.findall(r"""(?:href|action)\s*=\s*["']([^"'#]+)""", page)} offers = (urllib.parse.urlsplit(last).path in starts or starts & targets or re.search(r"""]*type\s*=\s*["']?password""", page, re.I)) if offers and not mentions: raise SystemExit( f"Not signed in: Authelia accepted the test account, but the app ended at " f"{shown(last)}, which offers sign-in again: its callback didn't sign the person " f"in.{page_says(body)} (coreapp logs may say more.)") if cookies: jar.save(ignore_discard=True, ignore_expires=True) print(f"Signed in: back at the app, {shown(last)} answered HTTP {status}.") who = username.split("@")[0] print(f"Its page shows {who}." if mentions else f"Its page doesn't show {who}, but doesn't offer sign-in again either; to be sure, " "look at a page only signed-in people get, with --cookies.") if cookies: print(f"Cookies saved in {cookies} (curl -b {cookies} https://{app.netloc}/...).") return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))