#!/usr/bin/env bash # GHOST Connect 2.2 — current-boot browser terminal for the CPX-owned HP. # Adapted from the reviewed GHOSTremote ONE v1.3 runtime service design. # This is not GHOSTos, desktop sharing, enterprise enrollment, or complete SSO. # Version 2.2 preserves version 2 runtime ownership for status and cleanup. set +x set -Eeuo pipefail umask 077 readonly VERSION=GHOST_CONNECT_2 readonly STATE=/run/ghost-connect readonly TERM_UNIT=/run/systemd/system/ghost-connect-terminal.service readonly CF_UNIT=/run/systemd/system/ghost-connect-tunnel.service readonly SOCKET_UNIT=/run/systemd/system/ghost-connect-proxy.socket readonly PROXY_UNIT=/run/systemd/system/ghost-connect-proxy.service readonly PROXY_BIN=/usr/lib/systemd/systemd-socket-proxyd readonly REMOTE_USER=ghost readonly REMOTE_HOME=/run/ghost-terminal readonly TERMINAL_URL=https://hp-terminal.cpx.agency/ readonly TUNNEL_ID=d33e8b9c-5e5a-470e-ab7d-fa97192232d4 readonly ACCOUNT_ID=fc7b4b9a3a43f4c2130ea638378de850 readonly REPO=/etc/apt/sources.list.d/ghost-connect-cloudflare.list readonly KEY=/usr/share/keyrings/ghost-connect-cloudflare.gpg CONFIG_TMP= CF_BIN= LOGIN_DIR_ID= say() { printf '[GHOST] %s\n' "$*"; } die() { say "STOP: $*" >&2; exit 1; } has() { command -v "$1" >/dev/null 2>&1; } exists() { [[ -e $1 || -L $1 ]]; } mark() { printf '%s\n' "${2:-yes}" | sudo tee "$STATE/$1" >/dev/null; } readmark() { sudo cat "$STATE/$1"; } have_mark() { sudo test -f "$STATE/$1"; } unit_active() { systemctl is-active --quiet "$1"; } listeners() { ss -H -lnt | awk -v p=":$1" '$4 ~ p"$" {print $4}'; } owned_digest() { sudo sha256sum "$2" | awk '{print $1}' | sudo tee "$STATE/$1" >/dev/null; } digest_matches() { [[ $(sudo sha256sum "$2" | awk '{print $1}') == "$(readmark "$1")" ]]; } unit_file() { case "$1" in terminal) printf '%s\n' "$TERM_UNIT" ;; tunnel) printf '%s\n' "$CF_UNIT" ;; socket) printf '%s\n' "$SOCKET_UNIT" ;; proxy) printf '%s\n' "$PROXY_UNIT" ;; esac } usage() { cat <<'HELP' GHOST Connect 2.2 — CURRENT BOOT ONLY bash GHOST-Connect.sh Connect the GHOST browser terminal bash GHOST-Connect.sh --check Read-only prerequisites bash GHOST-Connect.sh --status Show local and cloud connection status bash GHOST-Connect.sh --stop Remove this script's owned session Run in the HP's local terminal, WITHOUT sudo before bash. Setup installs the terminal and Cloudflare connector in the live overlay. Authorize the CPX domain in the browser that Cloudflare opens. GHOST then opens its protected browser terminal. No separate terminal password is required. The terminal runs as the non-administrator account ghost. Cloudflare Access protects the route and the connector validates the application JWT. The local server requires the authenticated-user header and a matching WebSocket origin. That header alone is not a replacement for Cloudflare's JWT validation. Browser authorization issues a tunnel-management account certificate. Only this setup's new local copy is removed; that does not revoke the Cloudflare account authorization. Existing Cloudflare credential directories are preserved and cause setup to stop for review. Tokens are never printed or sent to chat. Reboot ends this installation. The standard SSH service is not changed. The terminal cannot run sudo, change system files or access private home folders. This does not install native GHOSTos, desktop control, or a persistent OS. No disk formatting, partitioning, mounting, or boot changes are performed. HELP } check_host() { [[ $(uname -s) == Linux ]] || die 'This adapter requires Linux.' [[ $(awk -F= '$1=="ID" {gsub(/"/,"",$2);print $2}' /etc/os-release) == ubuntu ]] || die 'This adapter requires Ubuntu Live.' for c in findmnt ss systemctl awk grep stat getent python3 sha256sum readlink pgrep df cut id; do has "$c" || die "Missing required command: $c"; done [[ $(findmnt -n -o FSTYPE /) == overlay ]] || die 'Root is not a live overlay; no changes made.' grep -Eq '(^|[[:space:]])(boot=casper|BOOT_IMAGE=[^[:space:]]*/casper/)' /proc/cmdline || die 'Ubuntu Live boot marker not found.' ! grep -Eqi '(^|[[:space:]])(persistent|persistence|casper-rw|cowfile)(=|[[:space:]]|$)' /proc/cmdline || die 'Persistence marker found; this adapter is temporary only.' [[ $(findmnt -n -o FSTYPE -T /run) == tmpfs ]] || die '/run is not RAM-backed.' [[ $(findmnt -n -o FSTYPE -T "$HOME") == overlay ]] || die 'Home is not in the live overlay.' [[ -d /run/systemd/system ]] || die 'Systemd is unavailable.' [[ -r /sys/class/dmi/id/product_name ]] || die 'HP model cannot be confirmed.' grep -Eqi 'Spectre.*13-aw' /sys/class/dmi/id/product_name || die 'This adapter is scoped to the reported HP Spectre 13-aw.' say 'HP Ubuntu Live prerequisites confirmed; persistence after reboot is not provided.' } preflight() { [[ $EUID -ne 0 && -t 0 && -t 1 ]] || die 'Use a local interactive terminal, without sudo before bash.' [[ -z ${SSH_CONNECTION:-}${SSH_TTY:-} ]] || die 'Start GHOST Connect from the physical HP desktop terminal.' check_host for c in sudo apt-get apt-cache useradd; do has "$c" || die "Missing required command: $c"; done [[ -n ${DISPLAY:-}${WAYLAND_DISPLAY:-} && -n ${DBUS_SESSION_BUS_ADDRESS:-} ]] || die 'A local graphical login is required for Cloudflare browser authorization.' [[ -n ${XDG_RUNTIME_DIR:-} && -d $XDG_RUNTIME_DIR && ! -L $XDG_RUNTIME_DIR ]] || die 'Desktop runtime directory is unavailable.' [[ $(stat -c %u "$XDG_RUNTIME_DIR") == "$EUID" && $(stat -c %a "$XDG_RUNTIME_DIR") == 700 ]] || die 'Desktop runtime directory is not private.' [[ $(findmnt -n -o FSTYPE -T "$XDG_RUNTIME_DIR") == tmpfs ]] || die 'Desktop runtime directory is not RAM-backed.' for p in "$STATE" "$REMOTE_HOME" "$TERM_UNIT" "$CF_UNIT" "$SOCKET_UNIT" "$PROXY_UNIT" "$REPO" "$KEY"; do ! exists "$p" || die "Existing setup path requires review: $p"; done ! getent passwd "$REMOTE_USER" >/dev/null || die 'The ghost account already exists; it will not be reused.' ! getent group "$REMOTE_USER" >/dev/null || die 'The ghost group already exists; it will not be reused.' for u in ttyd.service ghost-connect-terminal.service ghost-connect-tunnel.service ghost-connect-proxy.socket ghost-connect-proxy.service ghostremote-one-tunnel.service cloudflared.service; do ! unit_active "$u" || die "An existing service is active: $u" done local loadstate for u in ghost-connect-terminal.service ghost-connect-tunnel.service ghost-connect-proxy.socket ghost-connect-proxy.service; do loadstate=$(systemctl show --property=LoadState --value "$u" 2>/dev/null || true) [[ $loadstate == not-found ]] || die "A GHOST unit already exists or cannot be inspected: $u" done ! pgrep -x cloudflared >/dev/null || die 'A Cloudflare connector is already running.' ! pgrep -x ttyd >/dev/null || die 'A terminal server is already running.' for port in 7681 9090 20315; do [[ -z $(listeners "$port") ]] || die "Port $port is already in use."; done [[ $(df -Pk / | awk 'NR==2 {print $4}') -ge 1048576 ]] || die 'At least 1 GiB free live-overlay capacity is required.' ! exists "$HOME/.cloudflared" || die 'A Cloudflare credential directory already exists. It is preserved; do not delete it to bypass this check.' sudo -n /usr/bin/true 2>/dev/null || sudo -v } cleanup() { sudo test -d "$STATE" && have_mark release && [[ $(readmark release) == "$VERSION" ]] || { say 'No recognized owned session to remove.'; return 1; } local unit file marker for unit in tunnel socket proxy terminal; do file=$(unit_file "$unit") if sudo test -e "$file"; then have_mark "$unit-unit-sha256" && digest_matches "$unit-unit-sha256" "$file" || { say 'A service file is changed or unverified; cleanup stopped.'; return 1; } fi done for unit in tunnel socket proxy terminal; do file=$(unit_file "$unit") if sudo test -e "$file"; then sudo systemctl stop "$(basename "$file")" || return 1 sudo rm -- "$file" || return 1 fi done if have_mark account-uid; then local expected current expected=$(readmark account-uid) current=$(id -u "$REMOTE_USER" 2>/dev/null || true) if [[ -n $current ]]; then [[ $current == "$expected" && $(getent passwd "$REMOTE_USER" | cut -d: -f6) == "$REMOTE_HOME" ]] || { say 'Owned account identity changed; preserved.'; return 1; } sudo loginctl terminate-user "$REMOTE_USER" >/dev/null 2>&1 || true sudo pkill -TERM -u "$current" >/dev/null 2>&1 || true sudo userdel --remove "$REMOTE_USER" || return 1 fi elif getent passwd "$REMOTE_USER" >/dev/null; then say 'Account creation outcome is uncertain; account and evidence preserved.'; return 1 fi for marker in repo key; do if [[ $marker == repo ]]; then file=$REPO; else file=$KEY; fi if have_mark "$marker-sha256" && sudo test -f "$file"; then digest_matches "$marker-sha256" "$file" || { say 'Package repository file changed; preserved.'; return 1; } sudo rm -- "$file" || return 1 fi done sudo rm -rf -- "$STATE" || return 1 ! sudo test -e "$STATE" || return 1 sudo systemctl daemon-reload || return 1 say 'Owned remote session removed. Installed packages and the default-terminal runtime mask remain until reboot.' } cleanup_login_certificate() { [[ -n $LOGIN_DIR_ID ]] || return 0 python3 - "$HOME/.cloudflared" "$LOGIN_DIR_ID" "$EUID" <<'PY' import os,stat,sys path,identity,uid=sys.argv[1:] try: ds=os.lstat(path) if not stat.S_ISDIR(ds.st_mode) or ds.st_uid!=int(uid) or stat.S_IMODE(ds.st_mode)!=0o700 or f'{ds.st_dev}:{ds.st_ino}'!=identity: raise ValueError() names=os.listdir(path) if set(names)-{'cert.pem'}: raise ValueError() cert=os.path.join(path,'cert.pem') if 'cert.pem' in names: cs=os.lstat(cert) if not stat.S_ISREG(cs.st_mode) or cs.st_uid!=int(uid) or stat.S_IMODE(cs.st_mode)!=0o600: raise ValueError() current=os.lstat(cert) if (current.st_dev,current.st_ino)!=(cs.st_dev,cs.st_ino): raise ValueError() os.unlink(cert) os.rmdir(path) except FileNotFoundError: pass except Exception: print('The newly created Cloudflare login directory changed; preserved for local review. Do not share its contents.',file=sys.stderr) raise SystemExit(1) PY } finish() { local rc=$? trap - EXIT INT HUP TERM if [[ -n $CONFIG_TMP && -f $CONFIG_TMP && ! -L $CONFIG_TMP ]]; then rm -f -- "$CONFIG_TMP"; fi cleanup_login_certificate || { say 'New local account certificate cleanup requires review.'; rc=1; } if (( rc != 0 )); then say 'Setup did not complete. Removing only this installer’s owned runtime changes.' cleanup || say 'Cleanup is incomplete; do not rerun blindly. Report this message, without credentials.' fi exit "$rc" } install_dependencies() { # Prevent a package-supplied default terminal service from opening another port. ! unit_active ttyd.service || die 'A terminal service became active; it is preserved.' ! pgrep -x ttyd >/dev/null || die 'A terminal server appeared during setup.' sudo systemctl mask --runtime ttyd.service local maskstate maskstate=$(systemctl is-enabled ttyd.service 2>/dev/null || true) [[ $maskstate == masked || $maskstate == masked-runtime ]] || die 'The default-terminal runtime mask is not effective. No terminal package will be installed.' if [[ ! -x /usr/bin/ttyd || ! -x /usr/bin/curl || ! -s /etc/ssl/certs/ca-certificates.crt ]]; then sudo apt-get update if ! apt-cache show ttyd >/dev/null 2>&1; then has add-apt-repository || die 'The signed Ubuntu universe repository is unavailable. No terminal has been started.' sudo add-apt-repository --yes universe sudo apt-get update fi sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ttyd curl ca-certificates else say 'Using the terminal and HTTPS tools already installed for this boot.' fi ! unit_active ttyd.service || die 'The default terminal service unexpectedly started.' [[ -z $(listeners 7681) && -z $(listeners 9090) ]] || die 'An unexpected terminal listener opened during package installation.' if [[ ! -x /usr/bin/cloudflared ]]; then curl --proto '=https' --proto-redir '=https' --fail --silent --show-error --location --max-time 45 --retry 2 https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee "$STATE/cloudflare-key.gpg" >/dev/null sudo test -s "$STATE/cloudflare-key.gpg" || die 'Cloudflare package key download was empty.' sudo install -m 0644 "$STATE/cloudflare-key.gpg" "$KEY" owned_digest key-sha256 "$KEY" printf 'deb [signed-by=%s] https://pkg.cloudflare.com/cloudflared any main\n' "$KEY" | sudo tee "$REPO" >/dev/null owned_digest repo-sha256 "$REPO" sudo apt-get update sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends cloudflared fi CF_BIN=/usr/bin/cloudflared local perms helptext component for component in /usr /usr/bin /usr/lib /usr/lib/systemd "$CF_BIN" /usr/bin/ttyd /usr/bin/bash "$PROXY_BIN"; do [[ ! -L $component && $(stat -c %u "$component") == 0 ]] || die 'Executables must be in their standard root-owned Apt locations.' perms=$(stat -c %a "$component") (( (8#$perms & 0022) == 0 )) || die 'An executable path component is writable by another user.' done [[ -x $CF_BIN && -x /usr/bin/ttyd && -x /usr/bin/bash && -x $PROXY_BIN ]] || die 'Required executables are unavailable after package installation.' helptext=$("$CF_BIN" tunnel run --help) [[ $helptext == *--token-file* ]] || die 'Cloudflare connector lacks token-file support.' helptext=$(/usr/bin/ttyd --help 2>&1) for option in --interface --writable --check-origin --auth-header --max-clients; do [[ $helptext == *"$option"* ]] || die "The terminal package lacks required option $option." done } authorize_tunnel() { local cert="$HOME/.cloudflared/cert.pem" ! exists "$HOME/.cloudflared" || die 'A Cloudflare directory appeared during setup; it has been preserved.' mkdir -m 0700 -- "$HOME/.cloudflared" LOGIN_DIR_ID=$(stat -c '%d:%i' "$HOME/.cloudflared") CONFIG_TMP=$(mktemp "$XDG_RUNTIME_DIR/ghost-connect-config.XXXXXXXX") printf '{}\n' > "$CONFIG_TMP" say 'Keep this terminal open. Sign in to the Cloudflare dashboard with the CPX owner account, select cpx.agency, and choose Authorize.' say 'If no browser opens, copy the complete https://dash.cloudflare.com/argotunnel?... link printed below into Firefox on this HP.' say 'Use the link from this run, including everything after the question mark. Keep the link and any certificate private.' say 'Return here after approval. Press Ctrl+C here to cancel and clean up this attempt.' if ! "$CF_BIN" tunnel --config "$CONFIG_TMP" login; then die 'Cloudflare ended sign-in before confirming authorization. If Firefox downloaded a certificate, keep it private. The next attempt will use a fresh sign-in link.' fi if [[ ! -s $cert || -L $cert ]]; then die 'Cloudflare has not delivered the account certificate to this terminal. Leave any browser-downloaded certificate private. A fresh attempt issues a new sign-in link.' fi # Login always writes the default cert.pem; --origincert does NOT redirect login. # Validate the NEW file without following links; copy it to root-only RAM and # remove that exact new inode only. Existing certificates are never used. sudo python3 - "$cert" "$STATE/origin-cert.pem" "$EUID" "$ACCOUNT_ID" <<'PY' import base64,json,os,re,stat,sys src,dst,uid,account=sys.argv[1:] try: fd=os.open(src,os.O_RDONLY|os.O_NOFOLLOW) with os.fdopen(fd,'rb') as f: st=os.fstat(f.fileno()) if not stat.S_ISREG(st.st_mode) or st.st_uid!=int(uid) or stat.S_IMODE(st.st_mode)!=0o600 or not 0/dev/null sudo bash -c 'umask 077; "$1" tunnel --config "$2" --origincert "$3" token "$4" > "$5" 2> "$6"' \ bash "$CF_BIN" "$STATE/config.yml" "$STATE/origin-cert.pem" "$TUNNEL_ID" "$STATE/tunnel.token" "$STATE/token-fetch.log" || die 'The authorized account could not retrieve the HP tunnel token.' # Validate identity binding locally. Never display token contents or secret fields. sudo python3 - "$STATE/tunnel.token" "$ACCOUNT_ID" "$TUNNEL_ID" <<'PY' import base64,json,os,stat,sys path,account,tunnel=sys.argv[1:] try: fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW) with os.fdopen(fd,'rb') as f: st=os.fstat(f.fileno()) if not stat.S_ISREG(st.st_mode) or st.st_uid!=0 or stat.S_IMODE(st.st_mode)!=0o600 or not 0/dev/null <<'RC' export PS1='GHOST \w \$ ' printf '\nGHOST terminal — current boot, standard access\n' printf 'Temporary workspace: /run/ghost-terminal\n\n' RC sudo chown "$REMOTE_USER:$REMOTE_USER" "$REMOTE_HOME/.bashrc" sudo chmod 0600 "$REMOTE_HOME/.bashrc" sudo tee "$TERM_UNIT" >/dev/null </dev/null </dev/null </dev/null </dev/null || die 'The local terminal HTTP check failed.' sudo systemctl start ghost-connect-tunnel.service for attempt in {1..20}; do if curl --noproxy '*' -fsS --max-time 2 http://127.0.0.1:20315/ready >/dev/null 2>&1; then return 0; fi sleep 2 done die 'Cloudflare did not report an edge connection; rolling back owned runtime services.' } status() { say 'CURRENT BOOT ONLY — these checks do not prove an owner browser session.' for unit in ghost-connect-terminal.service ghost-connect-proxy.socket ghost-connect-proxy.service ghost-connect-tunnel.service; do printf '%s: ' "$unit"; systemctl is-active "$unit" 2>/dev/null || true done printf 'GHOST local terminal: '; if [[ $(listeners 9090) == 127.0.0.1:9090 ]]; then printf 'ready\n'; else printf 'not ready\n'; fi printf 'GHOST cloud connection: '; if has curl && curl --noproxy '*' -fsS --max-time 3 http://127.0.0.1:20315/ready >/dev/null 2>&1; then printf 'ready\n'; else printf 'not ready\n'; fi say "Open GHOST: $TERMINAL_URL" say 'Complete the existing CPX owner sign-in if prompted. The terminal account is ghost.' say 'This is a temporary non-administrator terminal; desktop control and native GHOSTos installation remain separate.' local script_path script_path=$(readlink -f -- "$0") printf '[GHOST] Check status: bash %q --status\n' "$script_path" printf '[GHOST] Disconnect: bash %q --stop\n' "$script_path" } connect() { preflight say 'Connecting GHOST for the current boot. Browser authorization is the only account step.' sudo mkdir -m 0700 -- "$STATE" mark release "$VERSION" trap finish EXIT trap 'exit 130' INT HUP TERM install_dependencies authorize_tunnel start_services say 'GHOST local terminal and cloud connection are ready. Owner browser access still needs verification.' status if has xdg-open; then xdg-open "$TERMINAL_URL" >/dev/null 2>&1 || true; fi } [[ ${BASH_SOURCE[0]} == "$0" ]] || { printf 'Run this file with bash; do not source it.\n' >&2; return 1; } case "${1:-connect}" in connect|--connect) connect ;; --check) check_host ;; --status) status ;; --stop) [[ $EUID -ne 0 && -t 0 ]] || die 'Use your local terminal without sudo before bash.'; sudo -n /usr/bin/true 2>/dev/null || sudo -v; cleanup ;; --help|-h) usage ;; *) usage; exit 2 ;; esac