package main

// Security posture: a handful of settings that make a server easy to break into or leave it
// unpatched, read once an hour from configuration files and from what the agent already knows
// (listening ports, accounts, systemd units, processes). Only verdict-sized facts leave the
// machine: the effective value of a few sshd options, which host firewall was found, whether
// automatic updates are on, the names of extra UID 0 accounts, the number of sudoers NOPASSWD
// rules and the users or groups they name, the database ports reachable from the network,
// whether a reboot is pending and how many updates wait. Never the content of a file.

import (
	"bufio"
	"bytes"
	"errors"
	"io/fs"
	"net"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strconv"
	"strings"
)

type PostureOut struct {
	At       int64        `json:"at"`
	SSH      *SSHPosture  `json:"ssh,omitempty"` // nil: no sshd configuration on this machine
	Firewall FirewallOut  `json:"firewall"`
	AutoUpd  AutoUpdOut   `json:"auto_updates"`
	UID0     []string     `json:"uid0"` // accounts other than root with UID 0
	Sudo     SudoOut      `json:"sudo_nopasswd"`
	PublicDB []PublicPort `json:"public_db"`
	Reboot   RebootOut    `json:"reboot"`
	Updates  *UpdatesOut  `json:"updates,omitempty"` // nil: this system keeps no update count the agent can read
	// 0.3.0
	Fail2ban *Fail2banOut `json:"fail2ban,omitempty"` // nil: fail2ban is not installed
	Users    []UserOut    `json:"users,omitempty"`
	FW       *FWOut       `json:"fw,omitempty"`
	Pkg      *PkgOut      `json:"pkg,omitempty"`
}

// ---------------------------------------------------------------------------
// sshd
// ---------------------------------------------------------------------------

type SSHPosture struct {
	Readable        bool   `json:"readable"`
	PermitRootLogin string `json:"permit_root_login,omitempty"` // effective values (defaults applied)
	PasswordAuth    string `json:"password_auth,omitempty"`
	KbdInteractive  string `json:"kbd_interactive,omitempty"`
	UsePAM          string `json:"use_pam,omitempty"`
	PermitEmpty     string `json:"permit_empty,omitempty"`
	AuthMethods     string `json:"auth_methods,omitempty"`
	PasswordLogin   bool   `json:"password_login"` // a password can log in, by the values above
	Ports           []int  `json:"ports,omitempty"`
	Running         bool   `json:"running"` // an sshd process runs
	// 0.3.0
	PubkeyAuth    string     `json:"pubkey_auth,omitempty"`
	MaxAuthTries  int        `json:"max_auth_tries,omitempty"`
	AllowUsers    []string   `json:"allow_users,omitempty"`
	AllowGroups   []string   `json:"allow_groups,omitempty"`
	DenyUsers     []string   `json:"deny_users,omitempty"`
	DenyGroups    []string   `json:"deny_groups,omitempty"`
	MatchBlocks   int        `json:"match_blocks,omitempty"`
	MatchPassword bool       `json:"match_password,omitempty"` // a Match block turns password logins on
	MatchRoot     bool       `json:"match_root,omitempty"`     // a Match block sets PermitRootLogin yes
	Keys          []KeyCount `json:"keys,omitempty"`           // authorized_keys per account: count and key types
}

// KeyCount: how many keys an account's authorized_keys holds, and of which types (no fingerprints).
type KeyCount struct {
	User  string   `json:"user"`
	Count int      `json:"count"`
	Types []string `json:"types"`
}

type sshdParse struct {
	root       string
	vals       map[string]string
	lists      map[string][]string // allowusers & co. accumulate over lines (sshd appends them)
	ports      []int
	files      int
	unreadable bool
	matches    int
	matchPw    bool
	matchRoot  bool
}

// ReadSSHD reads /etc/ssh/sshd_config and the files it includes the way sshd does: keywords are
// case-insensitive, the first value of a keyword wins, Include is followed (globs, in order) and
// Match blocks (settings for some users or addresses only) are left out.
func ReadSSHD(root string) *SSHPosture {
	main := filepath.Join(root, "etc/ssh/sshd_config")
	if _, err := os.Lstat(main); err != nil {
		alt := filepath.Join(root, "usr/etc/ssh/sshd_config") // openSUSE keeps the vendor file here
		if _, err2 := os.Lstat(alt); err2 != nil {
			return nil
		}
		main = alt
	}
	p := &sshdParse{root: root, vals: map[string]string{}, lists: map[string][]string{}}
	p.file(main, 0)
	out := &SSHPosture{Readable: p.files > 0 && !p.unreadable}
	if !out.Readable {
		return out
	}
	get := func(k, def string) string {
		if v, ok := p.vals[k]; ok {
			return v
		}
		return def
	}
	out.PermitRootLogin = get("permitrootlogin", "prohibit-password")
	if out.PermitRootLogin == "without-password" {
		out.PermitRootLogin = "prohibit-password"
	}
	out.PasswordAuth = get("passwordauthentication", "yes")
	out.KbdInteractive = get("kbdinteractiveauthentication", get("challengeresponseauthentication", "yes"))
	out.UsePAM = get("usepam", "no")
	out.PermitEmpty = get("permitemptypasswords", "no")
	out.AuthMethods = truncate(get("authenticationmethods", "any"), 120)
	methodsAllow := out.AuthMethods == "any" || strings.Contains(out.AuthMethods, "password") || strings.Contains(out.AuthMethods, "keyboard-interactive")
	out.PasswordLogin = methodsAllow && (out.PasswordAuth == "yes" || (out.KbdInteractive == "yes" && out.UsePAM == "yes"))
	out.Ports = p.ports
	if len(out.Ports) == 0 {
		out.Ports = []int{22}
	}
	out.PubkeyAuth = get("pubkeyauthentication", "yes")
	out.MaxAuthTries = 6
	if n, err := strconv.Atoi(get("maxauthtries", "6")); err == nil && n > 0 && n < 10000 {
		out.MaxAuthTries = n
	}
	out.AllowUsers, out.AllowGroups = p.lists["allowusers"], p.lists["allowgroups"]
	out.DenyUsers, out.DenyGroups = p.lists["denyusers"], p.lists["denygroups"]
	out.MatchBlocks, out.MatchPassword, out.MatchRoot = p.matches, p.matchPw, p.matchRoot
	return out
}

func (p *sshdParse) file(path string, depth int) {
	if depth > 8 || p.files >= 64 {
		return
	}
	b, err := readSmall(path, 256*1024)
	if err != nil {
		if errors.Is(err, fs.ErrPermission) {
			p.unreadable = true
		}
		return
	}
	p.files++
	inMatch := false
	sc := bufio.NewScanner(bytes.NewReader(b))
	sc.Buffer(make([]byte, 16*1024), 64*1024)
	for sc.Scan() {
		line := strings.TrimSpace(sc.Text())
		if line == "" || line[0] == '#' {
			continue
		}
		key, rest := splitSSHDLine(line)
		if key == "match" {
			inMatch = strings.ToLower(rest) != "all"
			if inMatch {
				p.matches++
			}
			continue
		}
		if inMatch {
			v := strings.ToLower(unquote(firstField(rest)))
			switch {
			case (key == "passwordauthentication" || key == "kbdinteractiveauthentication") && v == "yes":
				p.matchPw = true
			case key == "permitrootlogin" && v == "yes":
				p.matchRoot = true
			}
			continue
		}
		switch key {
		case "include":
			for _, pat := range strings.Fields(rest) {
				pat = unquote(pat)
				if !strings.HasPrefix(pat, "/") {
					pat = "/etc/ssh/" + pat
				}
				matches, _ := filepath.Glob(filepath.Join(p.root, pat))
				sort.Strings(matches)
				for _, m := range matches {
					p.file(m, depth+1)
				}
			}
		case "port":
			if n, err := strconv.Atoi(firstField(rest)); err == nil && n > 0 && n < 65536 && len(p.ports) < 16 {
				p.ports = append(p.ports, n)
			}
		case "allowusers", "allowgroups", "denyusers", "denygroups":
			for _, w := range strings.Fields(rest) {
				if len(p.lists[key]) < 30 {
					p.lists[key] = append(p.lists[key], truncate(unquote(w), 64))
				}
			}
		default:
			if _, set := p.vals[key]; !set && rest != "" {
				if key == "authenticationmethods" {
					p.vals[key] = strings.ToLower(rest)
				} else {
					p.vals[key] = strings.ToLower(unquote(firstField(rest)))
				}
			}
		}
	}
}

// splitSSHDLine: "Keyword value", "Keyword=value" or "Keyword = value".
func splitSSHDLine(line string) (string, string) {
	i := strings.IndexAny(line, " \t=")
	if i < 0 {
		return strings.ToLower(line), ""
	}
	key := strings.ToLower(line[:i])
	rest := strings.TrimLeft(line[i:], " \t")
	rest = strings.TrimSpace(strings.TrimPrefix(rest, "="))
	return key, rest
}

func firstField(s string) string {
	if f := strings.Fields(s); len(f) > 0 {
		return f[0]
	}
	return ""
}

// ---------------------------------------------------------------------------
// host firewall
// ---------------------------------------------------------------------------

type FirewallOut struct {
	Found []string `json:"found"` // ufw | firewalld | nftables | iptables | csf | shorewall
	Known bool     `json:"known"` // false: the agent could not tell (no unit list and nothing found)
}

func unitActive(units map[string]UnitInfo, name string) bool {
	u, ok := units[name]
	return ok && u.ActiveState == "active"
}

var dropRe = regexp.MustCompile(`(?i)\b(drop|reject)\b`)

// rulesFileFilters: a ruleset file that drops or rejects something (Debian ships an
// /etc/nftables.conf that accepts everything). Unreadable or with includes: assumed to filter.
func rulesFileFilters(path string) bool {
	b, err := readSmall(path, 256*1024)
	if err != nil {
		return !errors.Is(err, fs.ErrNotExist)
	}
	var kept []string
	for _, l := range strings.Split(string(b), "\n") {
		l = strings.TrimSpace(l)
		if l == "" || l[0] == '#' {
			continue
		}
		kept = append(kept, l)
	}
	s := strings.Join(kept, "\n")
	return dropRe.MatchString(s) || strings.Contains(s, "include")
}

// DetectFirewall looks for an active host firewall. Cloud firewalls (security groups) are outside
// the machine and cannot be seen from it.
func DetectFirewall(root string, units map[string]UnitInfo, procNames map[string]bool) FirewallOut {
	var found []string
	if b, err := readSmall(filepath.Join(root, "etc/ufw/ufw.conf"), 64*1024); err == nil {
		for _, l := range strings.Split(string(b), "\n") {
			if strings.EqualFold(strings.ReplaceAll(strings.TrimSpace(l), " ", ""), "ENABLED=yes") {
				found = append(found, "ufw")
				break
			}
		}
	}
	if unitActive(units, "firewalld.service") || procNames["firewalld"] {
		found = append(found, "firewalld")
	}
	if unitActive(units, "nftables.service") &&
		(rulesFileFilters(filepath.Join(root, "etc/nftables.conf")) || rulesFileFilters(filepath.Join(root, "etc/sysconfig/nftables.conf"))) {
		found = append(found, "nftables")
	}
	if unitActive(units, "netfilter-persistent.service") || unitActive(units, "iptables.service") || unitActive(units, "ip6tables.service") {
		found = append(found, "iptables")
	}
	if unitActive(units, "csf.service") || procNames["lfd"] {
		found = append(found, "csf")
	}
	if unitActive(units, "shorewall.service") {
		found = append(found, "shorewall")
	}
	if found == nil {
		found = []string{}
	}
	return FirewallOut{Found: found, Known: units != nil || len(found) > 0}
}

// ---------------------------------------------------------------------------
// automatic security updates
// ---------------------------------------------------------------------------

type AutoUpdOut struct {
	Kind    string `json:"kind"` // unattended-upgrades | dnf-automatic | "" (a system the agent does not know)
	Enabled bool   `json:"enabled"`
	Detail  string `json:"detail,omitempty"` // not_installed | disabled | timer_inactive
}

var aptUnattendedRe = regexp.MustCompile(`(?i)^\s*APT::Periodic::Unattended-Upgrade\s+"([^"]*)"`)

func DetectAutoUpdates(root string, units map[string]UnitInfo) AutoUpdOut {
	aptDir := filepath.Join(root, "etc/apt/apt.conf.d")
	if ents, err := os.ReadDir(aptDir); err == nil {
		out := AutoUpdOut{Kind: "unattended-upgrades"}
		installed := exists(filepath.Join(root, "usr/bin/unattended-upgrade")) || exists(filepath.Join(root, "usr/bin/unattended-upgrades"))
		value := ""
		names := make([]string, 0, len(ents))
		for _, e := range ents {
			names = append(names, e.Name())
		}
		sort.Strings(names) // apt reads them in this order; a later file overrides an earlier one
		for _, n := range names {
			b, err := readSmall(filepath.Join(aptDir, n), 64*1024)
			if err != nil {
				continue
			}
			for _, l := range strings.Split(string(b), "\n") {
				if m := aptUnattendedRe.FindStringSubmatch(l); m != nil {
					value = m[1]
				}
			}
		}
		switch {
		case !installed:
			out.Detail = "not_installed"
		case value == "" || value == "0":
			out.Detail = "disabled"
		case units != nil && !unitActive(units, "apt-daily-upgrade.timer"):
			out.Detail = "timer_inactive"
		default:
			out.Enabled = true
		}
		return out
	}
	if exists(filepath.Join(root, "etc/dnf")) || exists(filepath.Join(root, "etc/yum.conf")) {
		out := AutoUpdOut{Kind: "dnf-automatic"}
		apply := false
		if b, err := readSmall(filepath.Join(root, "etc/dnf/automatic.conf"), 64*1024); err == nil {
			for _, l := range strings.Split(string(b), "\n") {
				k, v, ok := strings.Cut(strings.TrimSpace(l), "=")
				if ok && strings.TrimSpace(k) == "apply_updates" {
					v = strings.ToLower(strings.TrimSpace(v))
					apply = v == "yes" || v == "true" || v == "1"
				}
			}
		}
		timer := unitActive(units, "dnf-automatic.timer") || unitActive(units, "dnf5-automatic.timer")
		switch {
		case unitActive(units, "dnf-automatic-install.timer"):
			out.Enabled = true
		case units == nil && apply:
			out.Enabled = true // no unit list to check the timer against
		case !apply:
			out.Detail = "disabled"
		case !timer:
			out.Detail = "timer_inactive"
		default:
			out.Enabled = true
		}
		return out
	}
	return AutoUpdOut{}
}

func exists(p string) bool {
	_, err := os.Stat(p)
	return err == nil
}

// ---------------------------------------------------------------------------
// accounts: extra UID 0, sudoers NOPASSWD
// ---------------------------------------------------------------------------

func ExtraUID0(users []PasswdEntry) []string {
	out := []string{}
	for _, u := range users {
		if u.UID == 0 && u.Name != "root" && len(out) < 20 {
			out = append(out, truncate(u.Name, 64))
		}
	}
	sort.Strings(out)
	return dedupSorted(out)
}

type SudoOut struct {
	Readable bool     `json:"readable"`
	Count    int      `json:"count"` // rules with NOPASSWD
	Names    []string `json:"names"` // the users and %groups they name
}

// ReadSudoers counts the NOPASSWD rules of /etc/sudoers and /etc/sudoers.d. Only the first word of
// a rule (who it applies to) is kept; the commands are not.
func ReadSudoers(root string) SudoOut {
	out := SudoOut{Names: []string{}}
	main := filepath.Join(root, "etc/sudoers")
	files := []string{main}
	if ents, err := os.ReadDir(filepath.Join(root, "etc/sudoers.d")); err == nil {
		for _, e := range ents {
			n := e.Name()
			if strings.Contains(n, ".") || strings.HasSuffix(n, "~") || !e.Type().IsRegular() { // sudo skips these too
				continue
			}
			files = append(files, filepath.Join(root, "etc/sudoers.d", n))
		}
	} else if errors.Is(err, fs.ErrPermission) {
		return out
	}
	readAny := false
	for _, f := range files {
		b, err := readSmall(f, 256*1024)
		if err != nil {
			if errors.Is(err, fs.ErrPermission) {
				return SudoOut{Names: []string{}}
			}
			continue
		}
		readAny = true
		text := strings.ReplaceAll(string(b), "\\\n", " ")
		for _, l := range strings.Split(text, "\n") {
			l = strings.TrimSpace(l)
			if l == "" || l[0] == '#' || l[0] == '@' || !strings.Contains(l, "NOPASSWD") {
				continue
			}
			who := firstField(l)
			switch who {
			case "Defaults", "Cmnd_Alias", "User_Alias", "Runas_Alias", "Host_Alias":
				continue
			}
			if strings.HasPrefix(who, "Defaults") {
				continue
			}
			out.Count++
			if len(out.Names) < 20 {
				out.Names = append(out.Names, truncate(who, 64))
			}
		}
	}
	out.Readable = readAny || !exists(main)
	sort.Strings(out.Names)
	out.Names = dedupSorted(out.Names)
	return out
}

// ---------------------------------------------------------------------------
// databases reachable from the network
// ---------------------------------------------------------------------------

type PublicPort struct {
	Proto   string `json:"proto"`
	Port    int    `json:"port"`
	Addr    string `json:"addr"`
	Service string `json:"service"`
	Process string `json:"process,omitempty"`
}

var riskyPorts = map[int]string{
	3306: "MySQL/MariaDB", 33060: "MySQL X", 5432: "PostgreSQL", 6379: "Redis", 27017: "MongoDB", 27018: "MongoDB",
	9200: "Elasticsearch/OpenSearch", 9300: "Elasticsearch transport", 11211: "Memcached", 5984: "CouchDB", 9042: "Cassandra",
	8086: "InfluxDB", 2379: "etcd", 1433: "SQL Server", 1521: "Oracle", 28015: "RethinkDB", 2375: "Docker API (no TLS)",
}

var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}

// exposedAddr: an address other machines on the internet can reach: all interfaces, or a
// public address (not loopback, private, link-local or carrier-grade NAT).
func exposedAddr(addr string) bool {
	ip := net.ParseIP(addr)
	if ip == nil || ip.IsLoopback() {
		return false
	}
	if ip.IsUnspecified() {
		return true
	}
	return !(ip.IsPrivate() || ip.IsLinkLocalUnicast() || cgnat.Contains(ip))
}

// PublicDBPorts: database and similar ports listening on an address reachable from the network.
// A firewall may still block them; the agent cannot tell.
func PublicDBPorts(ports []PortOut) []PublicPort {
	out := []PublicPort{}
	seen := map[string]bool{}
	for _, p := range ports {
		svc, risky := riskyPorts[p.Port]
		if !risky || p.Local || !exposedAddr(p.Addr) || (p.Proto == "udp" && p.Port != 11211) {
			continue
		}
		k := p.Proto + "/" + strconv.Itoa(p.Port)
		if seen[k] {
			continue
		}
		seen[k] = true
		out = append(out, PublicPort{Proto: p.Proto, Port: p.Port, Addr: p.Addr, Service: svc, Process: p.Name})
	}
	sort.Slice(out, func(i, j int) bool {
		return out[i].Proto+strconv.Itoa(out[i].Port) < out[j].Proto+strconv.Itoa(out[j].Port)
	})
	return out
}

// ---------------------------------------------------------------------------
// pending reboot, waiting updates
// ---------------------------------------------------------------------------

type RebootOut struct {
	Required bool     `json:"required"`
	Reason   string   `json:"reason,omitempty"` // reboot-required (Debian, Ubuntu) | new-kernel
	Since    int64    `json:"since,omitempty"`
	Pkgs     []string `json:"pkgs,omitempty"`   // from /run/reboot-required.pkgs
	Kernel   string   `json:"kernel,omitempty"` // the newer kernel installed after boot
}

// CheckReboot: Debian and Ubuntu flag a needed reboot in /run/reboot-required. Elsewhere (and as a
// second opinion) a kernel newer than the running one, installed after the last boot, means a reboot.
func CheckReboot(root, running string, bootTime int64) RebootOut {
	for _, p := range []string{"run/reboot-required", "var/run/reboot-required"} {
		fi, err := os.Stat(filepath.Join(root, p))
		if err != nil {
			continue
		}
		out := RebootOut{Required: true, Reason: "reboot-required", Since: fi.ModTime().Unix()}
		if b, err := readSmall(filepath.Join(root, p+".pkgs"), 64*1024); err == nil {
			for _, l := range strings.Split(string(b), "\n") {
				if l = strings.TrimSpace(l); l != "" && len(out.Pkgs) < 20 {
					out.Pkgs = append(out.Pkgs, truncate(l, 80))
				}
			}
			sort.Strings(out.Pkgs)
			out.Pkgs = dedupSorted(out.Pkgs)
		}
		return out
	}
	if running == "" {
		return RebootOut{}
	}
	for _, dir := range []string{"lib/modules", "usr/lib/modules"} {
		ents, err := os.ReadDir(filepath.Join(root, dir))
		if err != nil || len(ents) == 0 {
			continue
		}
		newest := ""
		var newestAt int64
		for _, e := range ents {
			if !e.IsDir() {
				continue
			}
			if newest == "" || kernelCmp(e.Name(), newest) > 0 {
				if fi, err := e.Info(); err == nil {
					newest, newestAt = e.Name(), fi.ModTime().Unix()
				}
			}
		}
		if newest != "" && newest != running && kernelCmp(newest, running) > 0 && (bootTime == 0 || newestAt > bootTime+60) {
			return RebootOut{Required: true, Reason: "new-kernel", Since: newestAt, Kernel: truncate(newest, 80)}
		}
		return RebootOut{}
	}
	return RebootOut{}
}

var digitsRe = regexp.MustCompile(`\d+`)

// kernelCmp compares two kernel release strings by their numbers in order (6.8.0-47 > 6.8.0-45).
func kernelCmp(a, b string) int {
	x, y := digitsRe.FindAllString(a, 12), digitsRe.FindAllString(b, 12)
	for i := 0; i < len(x) && i < len(y); i++ {
		p, _ := strconv.ParseUint(x[i], 10, 64)
		q, _ := strconv.ParseUint(y[i], 10, 64)
		if p != q {
			if p > q {
				return 1
			}
			return -1
		}
	}
	switch {
	case len(x) > len(y):
		return 1
	case len(x) < len(y):
		return -1
	}
	return strings.Compare(a, b)
}

type UpdatesOut struct {
	Source   string `json:"source"` // update-notifier (Ubuntu)
	Total    int    `json:"total"`
	Security int    `json:"security"`
	At       int64  `json:"at"` // when the counts were computed (the file's time)
}

var (
	updTotalRe = regexp.MustCompile(`(?m)^\s*(\d+)\s+(?:updates?|packages?)\s+can\s+be\s+(?:applied\s+immediately|updated)`)
	updSecRe   = regexp.MustCompile(`(?m)^\s*(\d+)\s+(?:of\s+these\s+)?updates?\s+(?:is\s+a\s+|are\s+|is\s+)?(?:standard\s+)?security\s+updates?`)
)

// ParseUpdatesAvailable reads Ubuntu's /var/lib/update-notifier/updates-available (the text of the
// login banner, refreshed by apt). ok=false when the text is in a form it does not know.
func ParseUpdatesAvailable(b []byte) (total, security int, ok bool) {
	s := string(b)
	if strings.TrimSpace(s) == "" {
		return 0, 0, true // older releases leave it empty when nothing is pending
	}
	m := updTotalRe.FindStringSubmatch(s)
	if m == nil {
		return 0, 0, false
	}
	total, _ = strconv.Atoi(m[1])
	if m := updSecRe.FindStringSubmatch(s); m != nil {
		security, _ = strconv.Atoi(m[1])
	}
	return total, security, true
}

func ReadUpdates(root string) *UpdatesOut {
	p := filepath.Join(root, "var/lib/update-notifier/updates-available")
	fi, err := os.Stat(p)
	if err != nil {
		return nil
	}
	b, err := readSmall(p, 64*1024)
	if err != nil {
		return nil
	}
	total, sec, ok := ParseUpdatesAvailable(b)
	if !ok {
		return nil
	}
	return &UpdatesOut{Source: "update-notifier", Total: total, Security: sec, At: fi.ModTime().Unix()}
}

// ---------------------------------------------------------------------------
// time synchronisation
// ---------------------------------------------------------------------------

type TimeOut struct {
	Daemon string `json:"daemon"` // chronyd | ntpd | systemd-timesyncd | ptp4l | "" (none found)
	Synced *bool  `json:"synced"` // true when the daemon says so in a file the agent can read; null: cannot tell
	Jumps  int    `json:"jumps"`  // wall clock steps of more than 30 s seen since the agent started
}

// TimeSync names the time daemon that runs (from the process list, or the unit list) and, for
// systemd-timesyncd, whether it has synchronised (/run/systemd/timesync/synchronized).
func TimeSync(root string, units map[string]UnitInfo, procNames map[string]bool) TimeOut {
	var out TimeOut
	switch {
	case procNames["chronyd"] || unitActive(units, "chrony.service") || unitActive(units, "chronyd.service"):
		out.Daemon = "chronyd"
	case procNames["ntpd"] || unitActive(units, "ntp.service") || unitActive(units, "ntpd.service") || unitActive(units, "ntpsec.service"):
		out.Daemon = "ntpd"
	case procNames["systemd-timesyn"] || unitActive(units, "systemd-timesyncd.service"):
		out.Daemon = "systemd-timesyncd"
		if exists(filepath.Join(root, "run/systemd/timesync/synchronized")) {
			t := true
			out.Synced = &t
		}
	case procNames["ptp4l"] || procNames["phc2sys"]:
		out.Daemon = "ptp4l"
	}
	return out
}
