package main

// Accounts, SSH key counts, fail2ban and package-manager activity, for the hourly settings check.
// Read from /etc/passwd, /etc/group (never /etc/shadow), ~/.ssh/authorized_keys (counted, the
// keys themselves stay on the server), fail2ban's configuration files, and the time stamps apt and
// dnf leave behind.

import (
	"bufio"
	"bytes"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
)

// UserOut is one account that can log in, has UID 0, or may use sudo.
type UserOut struct {
	Name      string   `json:"name"`
	UID       int      `json:"uid"`
	Shell     string   `json:"shell"`
	Login     bool     `json:"login"`
	Sudo      bool     `json:"sudo"`               // member of sudo, wheel or admin (or root)
	Groups    []string `json:"groups,omitempty"`   // its groups (at most 12)
	NoPasswd  bool     `json:"nopasswd,omitempty"` // a sudoers NOPASSWD rule names it (or one of its groups)
	LastLogin int64    `json:"last_login,omitempty"`
	Keys      int      `json:"keys"` // authorized_keys entries (-1: unreadable)
}

// GroupEntry from /etc/group.
type GroupEntry struct {
	Name    string
	GID     int
	Members []string
}

func ParseGroup(b []byte) []GroupEntry {
	var out []GroupEntry
	sc := bufio.NewScanner(bytes.NewReader(b))
	sc.Buffer(make([]byte, 64*1024), 1024*1024)
	for sc.Scan() {
		f := strings.Split(sc.Text(), ":")
		if len(f) < 4 || strings.HasPrefix(f[0], "#") {
			continue
		}
		gid, err := strconv.Atoi(f[2])
		if err != nil {
			continue
		}
		g := GroupEntry{Name: f[0], GID: gid}
		for _, m := range strings.Split(f[3], ",") {
			if m = strings.TrimSpace(m); m != "" {
				g.Members = append(g.Members, m)
			}
		}
		out = append(out, g)
	}
	return out
}

// passwdGIDs: /etc/passwd's primary group of each user (ParsePasswd drops it).
func passwdGIDs(b []byte) map[string]int {
	out := map[string]int{}
	sc := bufio.NewScanner(bytes.NewReader(b))
	for sc.Scan() {
		f := strings.Split(sc.Text(), ":")
		if len(f) < 7 {
			continue
		}
		if gid, err := strconv.Atoi(f[3]); err == nil {
			out[f[0]] = gid
		}
	}
	return out
}

var sudoGroups = map[string]bool{"sudo": true, "wheel": true, "admin": true}

// BuildUsers lists the accounts worth showing: login shell, UID 0, or a sudo group.
func BuildUsers(root string, users []PasswdEntry, sudo SudoOut, last map[string]int64, keys map[string]KeyCount, keysRead bool) []UserOut {
	var groups []GroupEntry
	if b, err := readSmall(filepath.Join(root, "etc/group"), 4<<20); err == nil {
		groups = ParseGroup(b)
	}
	var gids map[string]int
	if b, err := readSmall(filepath.Join(root, "etc/passwd"), 4<<20); err == nil {
		gids = passwdGIDs(b)
	}
	byGID := map[int]string{}
	member := map[string][]string{}
	for _, g := range groups {
		byGID[g.GID] = g.Name
		for _, m := range g.Members {
			member[m] = append(member[m], g.Name)
		}
	}
	nopw := map[string]bool{}
	for _, n := range sudo.Names {
		nopw[n] = true
	}
	var out []UserOut
	for _, u := range users {
		gs := append([]string(nil), member[u.Name]...)
		if g, ok := byGID[gids[u.Name]]; ok {
			gs = append(gs, g)
		}
		sort.Strings(gs)
		gs = dedupSorted(gs)
		inSudo := u.UID == 0
		np := nopw[u.Name]
		for _, g := range gs {
			if sudoGroups[g] {
				inSudo = true
			}
			if nopw["%"+g] {
				np = true
			}
		}
		login := LoginShell(u.Shell)
		if !login && u.UID != 0 && !inSudo {
			continue
		}
		o := UserOut{Name: truncate(u.Name, 32), UID: u.UID, Shell: truncate(u.Shell, 64), Login: login, Sudo: inSudo, NoPasswd: np,
			LastLogin: last[u.Name], Keys: -1}
		if len(gs) > 12 {
			gs = gs[:12]
		}
		o.Groups = gs
		if keysRead {
			o.Keys = keys[u.Name].Count
		}
		out = append(out, o)
		if len(out) >= 50 {
			break
		}
	}
	return out
}

// CountSSHKeys counts the keys in authorized_keys(2) of root and of every account with a login
// shell, by type. ok is false when a file could not be read (permissions).
func CountSSHKeys(root string, users []PasswdEntry) (map[string]KeyCount, bool) {
	out := map[string]KeyCount{}
	ok := true
	seen := map[string]bool{}
	for _, u := range users {
		if u.UID != 0 && !LoginShell(u.Shell) {
			continue
		}
		if u.Home == "" || u.Home == "/" || seen[u.Home] {
			continue
		}
		seen[u.Home] = true
		kc := KeyCount{User: truncate(u.Name, 32)}
		for _, name := range []string{"authorized_keys", "authorized_keys2"} {
			b, err := readSmall(filepath.Join(root, u.Home, ".ssh", name), 512*1024)
			if err != nil {
				if os.IsPermission(err) {
					ok = false
				}
				continue
			}
			sc := bufio.NewScanner(bytes.NewReader(b))
			sc.Buffer(make([]byte, 64*1024), 1024*1024)
			for sc.Scan() {
				line := strings.TrimSpace(sc.Text())
				if line == "" || line[0] == '#' {
					continue
				}
				for _, f := range strings.Fields(line) {
					if keyType(f) {
						kc.Count++
						if !hasStr(kc.Types, f) && len(kc.Types) < 8 {
							kc.Types = append(kc.Types, f)
						}
						break
					}
				}
			}
		}
		if kc.Count > 0 {
			sort.Strings(kc.Types)
			out[u.Name] = kc
		}
	}
	return out, ok
}

func hasStr(xs []string, x string) bool {
	for _, y := range xs {
		if y == x {
			return true
		}
	}
	return false
}

func keyList(m map[string]KeyCount) []KeyCount {
	out := make([]KeyCount, 0, len(m))
	for _, k := range m {
		out = append(out, k)
	}
	sort.Slice(out, func(i, j int) bool { return out[i].User < out[j].User })
	if len(out) > 50 {
		out = out[:50]
	}
	return out
}

// ---------------------------------------------------------------------------
// fail2ban
// ---------------------------------------------------------------------------

type Fail2banOut struct {
	Installed bool     `json:"installed"`
	Running   bool     `json:"running"`
	Jails     []string `json:"jails"`  // enabled jails, from the configuration files
	Banned    *int     `json:"banned"` // not read (it lives in fail2ban's database): null
}

// ReadFail2ban: installed (its configuration or server exists), running (its process or socket),
// and the jails its configuration enables, read the way fail2ban does: jail.conf, jail.d/*.conf,
// jail.local, jail.d/*.local, later files overriding earlier ones, [DEFAULT] enabled applying to
// jails that do not set it.
func ReadFail2ban(root string, procNames map[string]bool) *Fail2banOut {
	dir := filepath.Join(root, "etc/fail2ban")
	installed := exists(filepath.Join(dir, "jail.conf")) || exists(filepath.Join(root, "usr/bin/fail2ban-server"))
	if !installed {
		return nil
	}
	out := &Fail2banOut{Installed: true, Jails: []string{}}
	out.Running = procNames["fail2ban-server"] || procNames["fail2ban-serve"] ||
		exists(filepath.Join(root, "run/fail2ban/fail2ban.sock")) || exists(filepath.Join(root, "var/run/fail2ban/fail2ban.sock"))
	files := []string{filepath.Join(dir, "jail.conf")}
	globD := func(ext string) []string {
		m, _ := filepath.Glob(filepath.Join(dir, "jail.d", "*"+ext))
		sort.Strings(m)
		return m
	}
	files = append(files, globD(".conf")...)
	files = append(files, filepath.Join(dir, "jail.local"))
	files = append(files, globD(".local")...)
	enabled := map[string]string{} // jail -> "true"/"false"/"" (unset)
	defEnabled := "false"
	for _, f := range files {
		b, err := readSmall(f, 1<<20)
		if err != nil {
			continue
		}
		sec := ""
		for _, l := range strings.Split(string(b), "\n") {
			l = strings.TrimSpace(l)
			if l == "" || l[0] == '#' || l[0] == ';' {
				continue
			}
			if l[0] == '[' && strings.HasSuffix(l, "]") {
				sec = strings.TrimSpace(l[1 : len(l)-1])
				if sec != "DEFAULT" && sec != "INCLUDES" && sec != "Definition" {
					if _, ok := enabled[sec]; !ok && len(enabled) < 500 {
						enabled[sec] = ""
					}
				}
				continue
			}
			k, v, ok := strings.Cut(l, "=")
			if !ok || strings.TrimSpace(strings.ToLower(k)) != "enabled" {
				continue
			}
			v = strings.ToLower(strings.TrimSpace(v))
			on := "false"
			if v == "true" || v == "yes" || v == "1" || v == "on" {
				on = "true"
			}
			if sec == "DEFAULT" {
				defEnabled = on
			} else if sec != "" && sec != "INCLUDES" {
				enabled[sec] = on
			}
		}
	}
	for j, e := range enabled {
		if e == "true" || (e == "" && defEnabled == "true") {
			out.Jails = append(out.Jails, truncate(j, 64))
		}
	}
	sort.Strings(out.Jails)
	if len(out.Jails) > 30 {
		out.Jails = out.Jails[:30]
	}
	return out
}

// ---------------------------------------------------------------------------
// package manager activity
// ---------------------------------------------------------------------------

type PkgOut struct {
	Manager     string `json:"manager"`                // apt | dnf | yum | zypper | apk
	LastUpdate  int64  `json:"last_update,omitempty"`  // the package lists were last refreshed
	LastUpgrade int64  `json:"last_upgrade,omitempty"` // an automatic upgrade last ran
	LastChange  int64  `json:"last_change,omitempty"`  // packages were last installed / upgraded / removed
}

func mtimeOf(paths ...string) int64 {
	var best int64
	for _, p := range paths {
		if fi, err := os.Stat(p); err == nil && fi.ModTime().Unix() > best {
			best = fi.ModTime().Unix()
		}
	}
	return best
}

// ReadPkg: apt's periodic stamps (/var/lib/apt/periodic), unattended-upgrades' log and apt's
// history; dnf's makecache stamp and history database; only their modification times.
func ReadPkg(root string) *PkgOut {
	j := func(p string) string { return filepath.Join(root, p) }
	switch {
	case exists(j("var/lib/dpkg/status")):
		return &PkgOut{Manager: "apt",
			LastUpdate:  mtimeOf(j("var/lib/apt/periodic/update-success-stamp"), j("var/lib/apt/periodic/update-stamp")),
			LastUpgrade: mtimeOf(j("var/lib/apt/periodic/upgrade-stamp"), j("var/log/unattended-upgrades/unattended-upgrades.log")),
			LastChange:  mtimeOf(j("var/log/apt/history.log"), j("var/log/dpkg.log"))}
	case exists(j("etc/dnf")) || exists(j("usr/bin/dnf")):
		return &PkgOut{Manager: "dnf", LastUpdate: mtimeOf(j("var/cache/dnf/last_makecache"), j("var/cache/dnf/expired_repos.json")),
			LastChange: mtimeOf(j("var/lib/dnf/history.sqlite"), j("var/log/dnf.rpm.log"))}
	case exists(j("etc/yum.conf")):
		return &PkgOut{Manager: "yum", LastChange: mtimeOf(j("var/log/yum.log"))}
	case exists(j("etc/zypp")):
		return &PkgOut{Manager: "zypper", LastChange: mtimeOf(j("var/log/zypp/history"))}
	case exists(j("etc/apk")):
		return &PkgOut{Manager: "apk", LastChange: mtimeOf(j("lib/apk/db/installed"))}
	}
	return nil
}
