#!/bin/bash # olduo endpoint agent for macOS and Linux (bash 3.2+, curl). # # Only calls out to the desk over HTTPS: a heartbeat with health metrics every minute and a long poll for jobs. # Runs nothing but the allow-listed jobs below; anything else the desk might ask for is refused here too. # The token is kept in a file only root can read; it never appears on a command line. # # Install (as root; the desk shows this line, with the token, when an admin enrols the device): # curl -fsSL https://desk.olduo.com/agent/olduo-agent.sh -o /tmp/olduo-agent.sh # sudo bash /tmp/olduo-agent.sh install --desk https://desk.olduo.com --token mda_... # Uninstall: # sudo bash /usr/local/lib/olduo-agent/olduo-agent.sh uninstall set -u umask 077 VERSION="1.0.0" PLATFORM="linux" [ "$(uname -s)" = "Darwin" ] && PLATFORM="macos" LIB="/usr/local/lib/olduo-agent" ETC="${OLDUO_ETC:-/etc/olduo-agent}" # OLDUO_ETC / OLDUO_STATE: only for testing the agent CONF="$ETC/config" STATE="/var/lib/olduo-agent" [ "$PLATFORM" = "macos" ] && STATE="/Library/Application Support/olduo-agent" STATE="${OLDUO_STATE:-$STATE}" LOG="$STATE/agent.log" PLIST="/Library/LaunchDaemons/com.olduo.agent.plist" UNIT="/etc/systemd/system/olduo-agent.service" PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" export PATH log() { mkdir -p "$STATE" 2>/dev/null; printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"$LOG" 2>/dev/null; } die() { echo "olduo agent: $*" >&2; exit 1; } # ---- install / uninstall -------------------------------------------------------------------------- install_agent() { local desk="" token="" while [ $# -gt 0 ]; do case "$1" in --desk) desk="${2:-}"; shift 2 ;; --token) token="${2:-}"; shift 2 ;; *) die "unknown option $1" ;; esac done [ "$(id -u)" = "0" ] || die "run the installer as root (sudo)" desk="${desk%/}" case "$desk" in https://*) ;; http://127.0.0.1*|http://localhost*) ;; *) die "--desk must be the desk's https:// address" ;; esac case "$token" in mda_*) ;; *) die "--token must be the device token the desk showed (mda_...)" ;; esac command -v curl >/dev/null 2>&1 || die "curl is needed" mkdir -p "$LIB" "$ETC" "$STATE" cp "$0" "$LIB/olduo-agent.sh" && chmod 755 "$LIB/olduo-agent.sh" printf 'DESK=%s\nTOKEN=%s\n' "$desk" "$token" >"$CONF" chown -R 0:0 "$ETC" 2>/dev/null; chmod 700 "$ETC"; chmod 600 "$CONF" if [ "$PLATFORM" = "macos" ]; then cat >"$PLIST" < Labelcom.olduo.agent ProgramArguments/bin/bash$LIB/olduo-agent.shrun RunAtLoad KeepAlive ThrottleInterval60 EOF chmod 644 "$PLIST" launchctl bootout system "$PLIST" >/dev/null 2>&1 launchctl bootstrap system "$PLIST" || die "launchd did not take the agent" else command -v systemctl >/dev/null 2>&1 || die "systemd is needed" cat >"$UNIT" </dev/null 2>&1 || die "systemd did not start the agent" fi echo "olduo agent $VERSION installed on $(hostname) ($PLATFORM); reporting to $desk" } uninstall_agent() { [ "$(id -u)" = "0" ] || die "run as root (sudo)" if [ "$PLATFORM" = "macos" ]; then launchctl bootout system "$PLIST" >/dev/null 2>&1; rm -f "$PLIST" else systemctl disable --now olduo-agent.service >/dev/null 2>&1; rm -f "$UNIT"; systemctl daemon-reload >/dev/null 2>&1 fi rm -rf "$LIB" "$ETC" "$STATE" echo "olduo agent removed" } # ---- talking to the desk ------------------------------------------------------------------------ load_config() { [ -r "$CONF" ] || die "not installed (no $CONF)" DESK="$(sed -n 's/^DESK=//p' "$CONF" | head -n1)" TOKEN="$(sed -n 's/^TOKEN=//p' "$CONF" | head -n1)" [ -n "$DESK" ] && [ -n "$TOKEN" ] || die "config is incomplete" AUTH_FILE="$STATE/.auth" mkdir -p "$STATE" printf 'header = "Authorization: Bearer %s"\n' "$TOKEN" >"$AUTH_FILE" # curl reads it; the token stays off the command line chmod 600 "$AUTH_FILE" } call() { # call METHOD PATH [JSON] [TIMEOUT] -> body on stdout; non-zero on failure local method="$1" path="$2" body="${3:-}" timeout="${4:-40}" local proto="=https" case "$DESK" in http://127.0.0.1*|http://localhost*) proto="=http,https" ;; esac if [ -n "$body" ]; then printf '%s' "$body" | curl -fsS --proto "$proto" --max-time "$timeout" -K "$AUTH_FILE" -X "$method" \ -H "Content-Type: application/json; charset=utf-8" --data-binary @- "$DESK$path" else curl -fsS --proto "$proto" --max-time "$timeout" -K "$AUTH_FILE" -X "$method" "$DESK$path" fi } json() { # a JSON string, escaped printf '"%s"' "$(printf '%s' "$1" | LC_ALL=C sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/\t/\\t/g' -e 's/\r//g' \ | LC_ALL=C tr -d '\000-\010\013\014\016-\037' | awk 'BEGIN{ORS=""} NR>1{print "\\n"} {print}')" } num() { case "$1" in ''|*[!0-9-]*) printf '%s' "${2:-0}" ;; *) printf '%s' "$1" ;; esac; } fnum() { case "$1" in ''|*[!0-9.]*) printf '0' ;; *) printf '%s' "$1" ;; esac; } # ---- health --------------------------------------------------------------------------------------- os_name() { if [ "$PLATFORM" = "macos" ]; then printf 'macOS %s' "$(sw_vers -productVersion 2>/dev/null)" elif [ -r /etc/os-release ]; then ( . /etc/os-release; printf '%s' "${PRETTY_NAME:-Linux}" ) else uname -sr fi } mem_used_pct() { if [ "$PLATFORM" = "macos" ]; then local total pagesize free inactive total=$(sysctl -n hw.memsize 2>/dev/null); pagesize=$(sysctl -n hw.pagesize 2>/dev/null) free=$(vm_stat 2>/dev/null | awk '/Pages free/ {gsub("\\.","",$3); print $3}') inactive=$(vm_stat 2>/dev/null | awk '/Pages inactive/ {gsub("\\.","",$3); print $3}') [ -n "$total" ] && [ -n "$pagesize" ] && [ -n "$free" ] || { echo 0; return; } awk -v t="$total" -v p="$pagesize" -v f="$free" -v i="${inactive:-0}" 'BEGIN{printf "%d", 100 - ((f+i)*p*100/t)}' else awk '/MemTotal/ {t=$2} /MemAvailable/ {a=$2} END{ if (t>0) printf "%d", 100 - a*100/t; else print 0 }' /proc/meminfo 2>/dev/null fi } cpu_pct() { if [ "$PLATFORM" = "macos" ]; then top -l 2 -n 0 -s 1 2>/dev/null | awk '/CPU usage/ {u=$3; s=$5} END{gsub("%","",u); gsub("%","",s); printf "%d", u+s}' else local a b a=$(awk '/^cpu / {print $2+$3+$4+$6+$7+$8, $2+$3+$4+$5+$6+$7+$8}' /proc/stat); sleep 1 b=$(awk '/^cpu / {print $2+$3+$4+$6+$7+$8, $2+$3+$4+$5+$6+$7+$8}' /proc/stat) echo "$a $b" | awk '{ d=$4-$2; if (d>0) printf "%d", ($3-$1)*100/d; else print 0 }' fi } uptime_hours() { if [ "$PLATFORM" = "macos" ]; then local boot; boot=$(sysctl -n kern.boottime 2>/dev/null | sed -n 's/.*sec = \([0-9]*\).*/\1/p') [ -n "$boot" ] && echo $(( ( $(date +%s) - boot ) / 3600 )) || echo 0 else awk '{printf "%d", $1/3600}' /proc/uptime 2>/dev/null fi } last_patch_days() { local t="" if [ "$PLATFORM" = "macos" ]; then t=$(stat -f %m /Library/Receipts/InstallHistory.plist 2>/dev/null) elif [ -r /var/log/apt/history.log ]; then t=$(stat -c %Y /var/log/apt/history.log 2>/dev/null) elif [ -d /var/lib/dnf ]; then t=$(stat -c %Y /var/lib/dnf/history.sqlite 2>/dev/null) fi [ -n "$t" ] && echo $(( ( $(date +%s) - t ) / 86400 )) || echo -1 } pending_reboot() { [ -e /var/run/reboot-required ] && echo true || echo false; } dns_ok() { if [ "$PLATFORM" = "macos" ]; then dscacheutil -q host -a name www.apple.com 2>/dev/null | grep -q ip_address && echo true || echo false else getent hosts www.microsoft.com >/dev/null 2>&1 && echo true || echo false fi } ip_addr() { if [ "$PLATFORM" = "macos" ]; then ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null else hostname -I 2>/dev/null | awk '{print $1}' fi } software() { # installed applications as a JSON array (at most 300) local first=1 name ver printf '[' if [ "$PLATFORM" = "macos" ]; then for app in /Applications/*.app; do [ -d "$app" ] || continue ver=$(defaults read "$app/Contents/Info" CFBundleShortVersionString 2>/dev/null) || continue name=$(basename "$app" .app) [ $first = 1 ] || printf ','; first=0 printf '{"name":%s,"version":%s}' "$(json "$name")" "$(json "$ver")" done elif command -v dpkg-query >/dev/null 2>&1; then dpkg-query -W -f='${Package}\t${Version}\n' 2>/dev/null | head -n 300 | while IFS="$(printf '\t')" read -r name ver; do [ -n "$name" ] || continue printf '{"name":%s,"version":%s},' "$(json "$name")" "$(json "$ver")" done | sed 's/,$//' elif command -v rpm >/dev/null 2>&1; then rpm -qa --qf '%{NAME}\t%{VERSION}-%{RELEASE}\n' 2>/dev/null | head -n 300 | while IFS="$(printf '\t')" read -r name ver; do [ -n "$name" ] || continue printf '{"name":%s,"version":%s},' "$(json "$name")" "$(json "$ver")" done | sed 's/,$//' fi printf ']' } disk_used_pct() { df -P / 2>/dev/null | awk 'NR==2 {gsub("%","",$5); print $5}'; } disk_free_gb() { df -Pk / 2>/dev/null | awk 'NR==2 {printf "%.1f", $4/1048576}'; } result_of() { [ -r "$STATE/$1" ] && head -c 1500 "$STATE/$1" || printf ''; } metrics() { printf '{"platform":%s,"disk_used_pct":%s,"disk_free_gb":%s,"cpu_pct":%s,"mem_used_pct":%s,"uptime_hours":%s,' \ "$(json "$PLATFORM")" "$(num "$(disk_used_pct)")" "$(fnum "$(disk_free_gb)")" "$(num "$(cpu_pct)")" "$(num "$(mem_used_pct)")" "$(num "$(uptime_hours)")" printf '"last_patch_days":%s,"pending_reboot":%s,"dns_ok":%s,"ip":%s,"updates_run":%s,"software":%s}' \ "$(num "$(last_patch_days)" -1)" "$(pending_reboot)" "$(dns_ok)" "$(json "$(ip_addr)")" "$(json "$(result_of updates-result.txt)")" "$(software)" } # ---- the allow-listed jobs --------------------------------------------------------------------------- run_updates() { # in the background: the result reaches the desk with a later heartbeat local out="$STATE/updates-result.txt" printf 'running since %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$out" ( if [ "$PLATFORM" = "macos" ]; then r=$(softwareupdate -i -a 2>&1); c=$? elif command -v apt-get >/dev/null 2>&1; then r=$(DEBIAN_FRONTEND=noninteractive apt-get update -q 2>&1 && DEBIAN_FRONTEND=noninteractive apt-get -y -q upgrade 2>&1); c=$? elif command -v dnf >/dev/null 2>&1; then r=$(dnf -y -q upgrade 2>&1); c=$? else r="no package manager this agent knows (apt, dnf)"; c=1 fi if [ $c -eq 0 ]; then s=finished; else s=failed; fi printf '%s %s\n%s\n' "$s" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$(printf '%s' "$r" | tail -n 15)" >"$out" ) >/dev/null 2>&1 & echo "Updates started in the background; the result arrives with the next heartbeats (this can take 10-30 minutes; a restart may be needed)." } run_job() { # run_job SCRIPT -> output on stdout; non-zero when it failed case "$1" in dns-reset) if [ "$PLATFORM" = "macos" ]; then dscacheutil -flushcache && killall -HUP mDNSResponder 2>/dev/null elif command -v resolvectl >/dev/null 2>&1; then resolvectl flush-caches elif command -v systemd-resolve >/dev/null 2>&1; then systemd-resolve --flush-caches elif command -v nscd >/dev/null 2>&1; then nscd -i hosts fi echo "DNS cache flushed. Lookup works now: $(dns_ok)." ;; printer-fix) command -v cancel >/dev/null 2>&1 || { echo "CUPS printing is not installed on this device"; return 1; } cancel -a 2>/dev/null if [ "$PLATFORM" = "macos" ]; then launchctl kickstart -k system/org.cups.cupsd 2>/dev/null; else systemctl restart cups 2>/dev/null; fi echo "Print queue cleared and the print service (CUPS) restarted. Printers: $(lpstat -p 2>/dev/null | awk '{print $2}' | tr '\n' ' ')" ;; perf-report) echo "cpu $(cpu_pct)%, memory $(mem_used_pct)% used, disk / $(disk_used_pct)% used ($(disk_free_gb) GB free), up $(uptime_hours) h" echo "busiest processes (cpu%, mem%, command):" ps -A -o pcpu=,pmem=,comm= 2>/dev/null | sort -rn | head -n 8 ;; disk-cleanup) local before after before=$(df -Pk / | awk 'NR==2 {print $4}') find /tmp /var/tmp -xdev -type f -mtime +7 -delete 2>/dev/null if [ "$PLATFORM" = "linux" ]; then command -v apt-get >/dev/null 2>&1 && apt-get clean -q 2>/dev/null command -v dnf >/dev/null 2>&1 && dnf clean all -q 2>/dev/null command -v journalctl >/dev/null 2>&1 && journalctl --vacuum-time=14d -q 2>/dev/null else find /Library/Caches -xdev -type f -mtime +14 -delete 2>/dev/null fi after=$(df -Pk / | awk 'NR==2 {print $4}') awk -v a="$before" -v b="$after" 'BEGIN{printf "Removed temporary files older than a week and old package caches; freed %.1f GB.\n", (b-a)/1048576}' ;; lock-screen) if [ "$PLATFORM" = "macos" ]; then pmset displaysleepnow && echo "Display put to sleep: the screen locks if the Mac asks for the password after sleep (System Settings → Lock Screen)." elif command -v loginctl >/dev/null 2>&1; then loginctl lock-sessions && echo "Every session on this machine is locked." else echo "no way to lock the screen here (loginctl missing)"; return 1 fi ;; patch-status) echo "last change to installed software: $(last_patch_days) days ago; restart pending: $(pending_reboot)" if [ "$PLATFORM" = "macos" ]; then softwareupdate -l 2>&1 | tail -n 20 elif command -v apt >/dev/null 2>&1; then echo "upgradable packages: $(apt list --upgradable 2>/dev/null | grep -c upgradable)"; apt list --upgradable 2>/dev/null | head -n 15 elif command -v dnf >/dev/null 2>&1; then dnf -q check-update 2>/dev/null | head -n 15 fi printf 'last update run: %s\n' "$(result_of updates-result.txt | head -n 1)" ;; install-updates) run_updates ;; crash-report) if [ "$PLATFORM" = "macos" ]; then echo "kernel panics in the last 30 days:" find /Library/Logs/DiagnosticReports -name '*.panic' -mtime -30 2>/dev/null | head -n 10 echo "app crashes in the last 30 days:" find /Library/Logs/DiagnosticReports "/Users" -path '*DiagnosticReports*' \( -name '*.ips' -o -name '*.crash' \) -mtime -30 2>/dev/null \ | sed 's#.*/##; s/-[0-9].*//' | sort | uniq -c | sort -rn | head -n 10 else echo "kernel errors in the last 30 days:" journalctl -k -p err --since "30 days ago" --no-pager -q 2>/dev/null | tail -n 15 echo "saved crash dumps: $(ls /var/crash 2>/dev/null | wc -l | tr -d ' ')" fi echo "disk / $(disk_used_pct)% used; up $(uptime_hours) h" ;; *) echo "job '$1' is not allow-listed on this device ($PLATFORM)"; return 1 ;; esac } # ---- main loop ---------------------------------------------------------------------------------- self_update() { # the desk ships a newer agent: fetch it, check it is ours and the version the desk named, swap, restart local want="$1" new="$STATE/olduo-agent.new.sh" call GET /agent/olduo-agent.sh "" 60 >"$new" || { rm -f "$new"; return; } if grep -q '^run_job()' "$new" && grep -q "^VERSION=\"$want\"\$" "$new" && bash -n "$new"; then mv -f "$new" "$LIB/olduo-agent.sh" && chmod 755 "$LIB/olduo-agent.sh" log "updating $VERSION -> $want" exit 0 # launchd / systemd start the new one fi rm -f "$new" } post_result() { # post_result JOB_ID OK OUTPUT call POST "/agent/jobs/$1/result" "{\"ok\":$2,\"output\":$(json "$(printf '%s' "$3" | head -c 8000)")}" >/dev/null 2>&1 } loop() { local once="${1:-}" last=0 now hb want lines id script out load_config log "agent $VERSION starting on $(hostname) ($PLATFORM)" while :; do now=$(date +%s) if [ $((now - last)) -ge 60 ]; then if hb=$(call POST /agent/heartbeat "{\"version\":$(json "$VERSION"),\"platform\":$(json "$PLATFORM"),\"os\":$(json "$(os_name)"),\"metrics\":$(metrics)}" 40); then last=$now want=$(printf '%s' "$hb" | sed -n 's/.*"agent_version":"\([0-9][0-9.]*\)".*/\1/p') [ -n "$want" ] && [ "$want" != "$VERSION" ] && [ -z "$once" ] && self_update "$want" else log "heartbeat failed"; sleep 10; [ -n "$once" ] && return 1; continue fi fi lines=$(call GET "/agent/jobs?wait=${OLDUO_WAIT:-20}&format=tsv" "" 35) || { log "job poll failed"; sleep 10; [ -n "$once" ] && return 1; continue; } if [ -n "$lines" ]; then while IFS="$(printf '\t')" read -r id script _args; do case "$id" in ''|*[!0-9]*) continue ;; esac log "job $id: $script" if out=$(run_job "$script" 2>&1); then post_result "$id" true "$out"; else post_result "$id" false "$out"; fi last=0 # report fresh metrics right after a change done <&2; exit 2 ;; esac