package enforce import ( "errors" "fmt" "net/netip" "os" "path/filepath" "strings" "sync" "time" ) // MaxLogBytes is the size at which the decision file is rotated (one .1 kept). const MaxLogBytes = 20 << 20 // token reduces s to [A-Za-z0-9._-] (at most 32 bytes); fallback if nothing is left. func token(s, fallback string) string { var b strings.Builder for i := 0; i < len(s) && b.Len() < 32; i++ { c := s[i] if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-' { b.WriteByte(c) } } if b.Len() == 0 { return fallback } return b.String() } // FormatLine renders one decision. Nothing the attacker controls enters it: // the address is re-formatted by netip, the reason must be a fixed slug and the // host and source names are reduced to a safe alphabet. func FormatLine(t time.Time, ip netip.Addr, reason string, score int, ttl time.Duration, host, src string) (string, error) { ip = ip.Unmap().WithZone("") if !ip.IsValid() { return "", errors.New("invalid ip") } if !ValidReason(reason) { return "", errors.New("invalid reason") } score = max(0, min(100, score)) secs := max(1, int64(ttl/time.Second)) if src != "local" { src = "peer:" + token(strings.TrimPrefix(src, "peer:"), "peer") } return fmt.Sprintf("%s urutau decision=ban ip=%s reason=%s score=%d ttl=%d host=%s src=%s\n", t.UTC().Format("2006-01-02T15:04:05Z"), ip.String(), reason, score, secs, token(host, "urutau"), src), nil } // logFile appends to the decision file, rotating by size. type logFile struct { mu sync.Mutex path string f *os.File size int64 } func (l *logFile) open() error { if err := os.MkdirAll(filepath.Dir(l.path), 0o750); err != nil { return err } f, err := os.OpenFile(l.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640) if err != nil { return err } fi, err := f.Stat() if err != nil { f.Close() return err } l.f, l.size = f, fi.Size() return nil } func (l *logFile) write(line string) error { l.mu.Lock() defer l.mu.Unlock() if l.f == nil { if err := l.open(); err != nil { return err } } if l.size+int64(len(line)) > MaxLogBytes { l.f.Close() l.f = nil if err := os.Rename(l.path, l.path+".1"); err != nil { return err } if err := l.open(); err != nil { return err } } n, err := l.f.WriteString(line) l.size += int64(n) if err != nil { l.f.Close() l.f = nil } return err } func (l *logFile) close() { l.mu.Lock() defer l.mu.Unlock() if l.f != nil { l.f.Close() l.f = nil } } // Writable reports whether the decision file can be appended to, without // creating anything: an existing file is opened for writing, otherwise a // temporary file is created next to where it would live. func Writable(path string) bool { if path == "" { return false } if _, err := os.Stat(path); err == nil { f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0) if err != nil { return false } f.Close() return true } dir := filepath.Dir(path) if _, err := os.Stat(dir); err != nil { // the directory is created on first write: check the nearest parent for dir != "/" && dir != "." { dir = filepath.Dir(dir) if _, err := os.Stat(dir); err == nil { break } } } f, err := os.CreateTemp(dir, ".urutau-w-*") if err != nil { return false } f.Close() os.Remove(f.Name()) return true }