package main

// SSH logins and sudo use from the system's auth log (/var/log/auth.log on Debian and Ubuntu,
// /var/log/secure on RHEL and its relatives). The agent reads only what was appended since its
// previous look (it remembers where it stopped across restarts), at most authLogMaxRead bytes at a
// time, and keeps:
//   - counters: failed and invalid-user attempts, accepted logins, the source addresses that tried
//     most (with the time of their last try and the names of EXISTING accounts they tried: the
//     names an attacker guesses are never sent, they may be someone's mistyped password);
//   - successful SSH logins: time, account, source address and port, method (publickey, password…);
//   - sudo use: time, account, allowed or refused (never the command).
// The first look after install also reads the last part of the file (authLogMaxRead) for the
// logins and sudo history (not the counters). On systems that log only to journald the file does
// not exist and the check is skipped. The file is readable by root and the adm group only: the
// detailed install (CAP_DAC_READ_SEARCH), --root or --auth-log (adm group) read it.

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

const authLogMaxRead = 2 << 20

// SSHAuthOut is what the rollup carries: counts since the previous rollup.
type SSHAuthOut struct {
	Source    string    `json:"source"`
	Failed    int       `json:"failed"`   // failed password / key / keyboard-interactive attempts
	Invalid   int       `json:"invalid"`  // connections naming a user that does not exist
	Accepted  int       `json:"accepted"` // successful logins
	IPs       int       `json:"ips"`      // distinct source addresses of failures
	Top       []IPCount `json:"top"`      // the 5 addresses with the most failures
	WindowS   int64     `json:"window_s"`
	Truncated bool      `json:"truncated,omitempty"` // more was written than the agent reads at once
}

type IPCount struct {
	IP string `json:"ip"`
	N  int    `json:"n"`
}

// AuthCounts accumulates between two rollups.
type AuthCounts struct {
	Failed, Invalid, Accepted int
	ByIP                      map[string]int
	Truncated                 bool
	Fail                      map[string]*IPFail // 0.3.0: per source address
	Logins                    []AcceptedRec
	Sudo                      []SudoRec
}

// IPFail: the failures of one source address.
type IPFail struct {
	Invalid int
	Last    int64
	Users   map[string]int // account names tried (filtered to existing accounts before sending)
}

// AcceptedRec: "Accepted <method> for <user> from <ip> port <port>".
type AcceptedRec struct {
	At     int64  `json:"at"`
	User   string `json:"user"`
	IP     string `json:"ip"`
	Method string `json:"method"`
	Port   int    `json:"port,omitempty"`
}

// SudoRec: someone ran sudo (allowed or refused). The command is never kept.
type SudoRec struct {
	At   int64  `json:"at"`
	User string `json:"user"`
	OK   bool   `json:"ok"`
}

const maxAuthEvents = 200

func (a *AuthCounts) add(b AuthCounts) {
	a.Failed += b.Failed
	a.Invalid += b.Invalid
	a.Accepted += b.Accepted
	a.Truncated = a.Truncated || b.Truncated
	a.Logins = lastN(append(a.Logins, b.Logins...), maxAuthEvents)
	a.Sudo = lastN(append(a.Sudo, b.Sudo...), maxAuthEvents)
	for ip, f := range b.Fail {
		if a.Fail == nil {
			a.Fail = map[string]*IPFail{}
		}
		g := a.Fail[ip]
		if g == nil {
			if len(a.Fail) >= 10000 {
				continue
			}
			g = &IPFail{}
			a.Fail[ip] = g
		}
		g.Invalid += f.Invalid
		g.Last = max(g.Last, f.Last)
		for u, n := range f.Users {
			if g.Users == nil {
				g.Users = map[string]int{}
			}
			if _, ok := g.Users[u]; ok || len(g.Users) < 20 {
				g.Users[u] += n
			}
		}
	}
	for ip, n := range b.ByIP {
		if a.ByIP == nil {
			a.ByIP = map[string]int{}
		}
		if _, ok := a.ByIP[ip]; ok || len(a.ByIP) < 10000 {
			a.ByIP[ip] += n
		}
	}
}

func (a AuthCounts) Out(source string, window int64) *SSHAuthOut {
	o := &SSHAuthOut{Source: source, Failed: a.Failed, Invalid: a.Invalid, Accepted: a.Accepted, IPs: len(a.ByIP), WindowS: window,
		Truncated: a.Truncated, Top: []IPCount{}}
	for ip, n := range a.ByIP {
		o.Top = append(o.Top, IPCount{ip, n})
	}
	sort.Slice(o.Top, func(i, j int) bool {
		if o.Top[i].N != o.Top[j].N {
			return o.Top[i].N > o.Top[j].N
		}
		return o.Top[i].IP < o.Top[j].IP
	})
	if len(o.Top) > 5 {
		o.Top = o.Top[:5]
	}
	return o
}

// ParseAuthLines counts the sshd lines of a chunk of the auth log and collects the successful
// logins and the sudo use, with their times (now: the reference for syslog dates without a year).
func ParseAuthLines(b []byte) AuthCounts { return parseAuth(b, time.Now(), false) }

func parseAuth(b []byte, now time.Time, eventsOnly bool) AuthCounts {
	c := AuthCounts{ByIP: map[string]int{}, Fail: map[string]*IPFail{}}
	for len(b) > 0 {
		var line []byte
		if i := bytes.IndexByte(b, '\n'); i >= 0 {
			line, b = b[:i], b[i+1:]
		} else {
			line, b = b, nil
		}
		if bytes.Contains(line, []byte(" sudo")) {
			if r, ok := parseSudo(line, now); ok && len(c.Sudo) < 10*maxAuthEvents {
				c.Sudo = append(c.Sudo, r)
			}
			continue
		}
		if !bytes.Contains(line, []byte("sshd")) { // sshd[123] and, since OpenSSH 9.8, sshd-session[123]
			continue
		}
		s := string(line)
		switch {
		case strings.Contains(s, "]: Failed password for ") || strings.Contains(s, "]: Failed publickey for ") ||
			strings.Contains(s, "]: Failed keyboard-interactive/pam for ") || strings.Contains(s, "]: Failed none for "):
			if eventsOnly {
				continue
			}
			c.Failed++
			// "for invalid user x": its "Invalid user x from IP" line came first and counted the address.
			if !strings.Contains(s, " for invalid user ") {
				ip := c.countIP(s)
				if f := c.fail(ip); f != nil {
					f.Last = max(f.Last, syslogTime(line, now))
					if u := wordAfter(s, " for "); u != "" && len(f.Users) < 20 {
						f.Users[truncate(u, 32)]++
					}
				}
			}
		case strings.Contains(s, "]: Invalid user "):
			if eventsOnly {
				continue
			}
			c.Invalid++
			ip := c.countIP(s)
			if f := c.fail(ip); f != nil {
				f.Invalid++
				f.Last = max(f.Last, syslogTime(line, now))
			}
		case strings.Contains(s, "]: Accepted "):
			if !eventsOnly {
				c.Accepted++
			}
			if r, ok := parseAccepted(s, line, now); ok && len(c.Logins) < 10*maxAuthEvents {
				c.Logins = append(c.Logins, r)
			}
		}
	}
	c.Logins = lastN(c.Logins, maxAuthEvents)
	c.Sudo = lastN(c.Sudo, maxAuthEvents)
	return c
}

func (c *AuthCounts) fail(ip string) *IPFail {
	if ip == "" {
		return nil
	}
	f := c.Fail[ip]
	if f == nil {
		if len(c.Fail) >= 10000 {
			return nil
		}
		f = &IPFail{Users: map[string]int{}}
		c.Fail[ip] = f
	}
	return f
}

func (c *AuthCounts) countIP(s string) string {
	i := strings.LastIndex(s, " from ")
	if i < 0 {
		return ""
	}
	f := strings.Fields(s[i+6:])
	if len(f) == 0 || net.ParseIP(f[0]) == nil {
		return ""
	}
	if _, ok := c.ByIP[f[0]]; ok || len(c.ByIP) < 10000 {
		c.ByIP[f[0]]++
	}
	return f[0]
}

// wordAfter returns the word that follows the first occurrence of marker.
func wordAfter(s, marker string) string {
	i := strings.Index(s, marker)
	if i < 0 {
		return ""
	}
	return firstField(s[i+len(marker):])
}

// parseAccepted: "sshd[812]: Accepted publickey for kaan from 203.0.113.5 port 52144 ssh2: ED25519 SHA256:…"
func parseAccepted(s string, line []byte, now time.Time) (AcceptedRec, bool) {
	i := strings.Index(s, "]: Accepted ")
	if i < 0 {
		return AcceptedRec{}, false
	}
	rest := s[i+len("]: Accepted "):]
	f := strings.Fields(rest)
	// method for user from ip port n
	if len(f) < 5 || f[1] != "for" {
		return AcceptedRec{}, false
	}
	r := AcceptedRec{At: syslogTime(line, now), Method: authMethod(f[0]), User: truncate(f[2], 32)}
	for k := 3; k+1 < len(f); k++ {
		switch f[k] {
		case "from":
			if net.ParseIP(f[k+1]) != nil {
				r.IP = f[k+1]
			}
		case "port":
			r.Port, _ = strconv.Atoi(f[k+1])
		}
	}
	return r, r.User != "" && r.At > 0
}

func authMethod(m string) string {
	switch m {
	case "publickey", "password", "keyboard-interactive/pam", "keyboard-interactive", "hostbased", "gssapi-with-mic", "gssapi-keyex", "none":
		return strings.TrimSuffix(m, "/pam")
	}
	return "other"
}

// parseSudo: "sudo:     kaan : TTY=pts/0 ; PWD=/home/kaan ; USER=root ; COMMAND=/usr/bin/apt update" (allowed),
// "sudo:     kaan : 3 incorrect password attempts ; TTY=…", "sudo:      bob : user NOT in sudoers ; …" (refused).
// The command is never kept.
func parseSudo(line []byte, now time.Time) (SudoRec, bool) {
	s := string(line)
	i := strings.Index(s, " sudo: ")
	if i < 0 {
		i = strings.Index(s, " sudo[")
		if i < 0 {
			return SudoRec{}, false
		}
		j := strings.Index(s[i:], "]: ")
		if j < 0 {
			return SudoRec{}, false
		}
		i += j + 2
	} else {
		i += len(" sudo:")
	}
	rest := strings.TrimLeft(s[i:], " ")
	if strings.HasPrefix(rest, "pam_unix") || strings.HasPrefix(rest, "pam_") {
		return SudoRec{}, false
	}
	k := strings.Index(rest, " : ")
	if k <= 0 {
		return SudoRec{}, false
	}
	user := strings.TrimSpace(rest[:k])
	what := rest[k+3:]
	if user == "" || strings.ContainsAny(user, " ;=") {
		return SudoRec{}, false
	}
	ok := strings.Contains(what, "COMMAND=")
	if strings.Contains(what, "incorrect password") || strings.Contains(what, "NOT in sudoers") || strings.Contains(what, "command not allowed") ||
		strings.Contains(what, "authentication failure") || strings.Contains(what, "a password is required") {
		ok = false
	} else if !ok {
		return SudoRec{}, false
	}
	at := syslogTime(line, now)
	if at == 0 {
		return SudoRec{}, false
	}
	return SudoRec{At: at, User: truncate(user, 32), OK: ok}, true
}

// syslogTime reads the time at the start of a syslog line: RFC 3339 ("2026-10-07T10:12:01.123456+03:00",
// Ubuntu 24.04 and rsyslog's high-precision format) or the traditional "Oct  7 10:12:01" (local time,
// no year: the year that puts it in the past). 0 when neither.
func syslogTime(line []byte, now time.Time) int64 {
	if len(line) >= 19 && line[4] == '-' && line[10] == 'T' {
		end := bytes.IndexByte(line, ' ')
		if end < 0 {
			end = len(line)
		}
		if t, err := time.Parse(time.RFC3339Nano, string(line[:end])); err == nil {
			return t.Unix()
		}
		return 0
	}
	if len(line) < 15 {
		return 0
	}
	t, err := time.ParseInLocation("Jan _2 15:04:05", string(line[:15]), time.Local)
	if err != nil {
		return 0
	}
	t = time.Date(now.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
	if t.After(now.Add(48 * time.Hour)) {
		t = t.AddDate(-1, 0, 0)
	}
	return t.Unix()
}

func lastN[T any](xs []T, n int) []T {
	if len(xs) > n {
		return append([]T(nil), xs[len(xs)-n:]...)
	}
	return xs
}

// AuthLog follows one log file across rotations.
type AuthLog struct {
	Path     string
	dev, ino uint64
	off      int64
	tail     []byte // the bytes just before off: if they changed, the file was truncated and rewritten (copytruncate)
	started  bool
	Backfill bool // the first Read also returns the logins and sudo use of the file's last authLogMaxRead bytes
}

// AuthPos is the reader's position, kept in the state directory across restarts.
type AuthPos struct {
	Path string `json:"path"`
	Dev  uint64 `json:"dev"`
	Ino  uint64 `json:"ino"`
	Off  int64  `json:"off"`
	Tail []byte `json:"tail"`
}

func (a *AuthLog) Pos() *AuthPos {
	if !a.started {
		return nil
	}
	return &AuthPos{Path: a.Path, Dev: a.dev, Ino: a.ino, Off: a.off, Tail: a.tail}
}

// Resume continues from a saved position (same path): what was written while the agent was
// stopped is counted too.
func (a *AuthLog) Resume(p *AuthPos) {
	if p == nil || p.Path != a.Path || a.Path == "" {
		return
	}
	a.dev, a.ino, a.off, a.tail, a.started = p.Dev, p.Ino, p.Off, p.Tail, true
}

var errNoAuthLog = errors.New("no auth log")

// FindAuthLog returns the configured path, or the first of /var/log/auth.log and /var/log/secure that exists.
func FindAuthLog(root, configured string) string {
	if configured != "" {
		return configured
	}
	for _, p := range []string{"var/log/auth.log", "var/log/secure"} {
		if _, err := os.Stat(filepath.Join(root, p)); err == nil {
			return filepath.Join(root, p)
		}
	}
	return ""
}

// Read returns the counts in what was appended since the previous call. The first call only
// positions at the end of the file (history before the agent started is not counted).
func (a *AuthLog) Read() (AuthCounts, error) {
	if a.Path == "" {
		return AuthCounts{}, errNoAuthLog
	}
	f, err := os.Open(a.Path)
	if err != nil {
		return AuthCounts{}, err
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return AuthCounts{}, err
	}
	if !fi.Mode().IsRegular() {
		return AuthCounts{}, &fs.PathError{Op: "read", Path: a.Path, Err: errors.New("not a regular file")}
	}
	var dev, ino uint64
	if st, ok := fi.Sys().(*syscall.Stat_t); ok {
		dev, ino = uint64(st.Dev), uint64(st.Ino)
	}
	size := fi.Size()
	if !a.started {
		a.started, a.dev, a.ino, a.off = true, dev, ino, size
		a.tail = readTail(f, size)
		if !a.Backfill || size == 0 {
			return AuthCounts{}, nil
		}
		// History for the login and sudo lists (counters start from now).
		from := max(0, size-authLogMaxRead)
		buf := make([]byte, size-from)
		n, err := f.ReadAt(buf, from)
		if err != nil && !errors.Is(err, io.EOF) {
			return AuthCounts{}, nil
		}
		buf = buf[:n]
		if from > 0 {
			if i := bytes.IndexByte(buf, '\n'); i >= 0 {
				buf = buf[i+1:]
			}
		}
		return parseAuth(buf, time.Now(), true), nil
	}
	if dev != a.dev || ino != a.ino || size < a.off || !bytes.Equal(readTail(f, a.off), a.tail) {
		a.dev, a.ino, a.off = dev, ino, 0 // rotated, or truncated in place: the file from its start
	}
	var out AuthCounts
	if size-a.off > authLogMaxRead { // a flood: count the latest part only
		a.off = size - authLogMaxRead
		out.Truncated = true
	}
	if size == a.off {
		return out, nil
	}
	buf := make([]byte, size-a.off)
	n, err := f.ReadAt(buf, a.off)
	if err != nil && !errors.Is(err, io.EOF) {
		return out, err
	}
	buf = buf[:n]
	last := bytes.LastIndexByte(buf, '\n')
	if last < 0 { // no complete line yet
		return out, nil
	}
	a.off += int64(last + 1)
	a.tail = readTail(f, a.off)
	c := parseAuth(buf[:last+1], time.Now(), false)
	c.Truncated = c.Truncated || out.Truncated
	return c, nil
}

// readTail returns up to 64 bytes ending at off.
func readTail(f *os.File, off int64) []byte {
	n := min(off, 64)
	if n <= 0 {
		return nil
	}
	b := make([]byte, n)
	if _, err := f.ReadAt(b, off-n); err != nil {
		return nil
	}
	return b
}
