decorate.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package firewall
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "strings"
  6. )
  7. func decorateRuleLines(kind string, rule any, lines []string) []string {
  8. v := values(rule)
  9. id := text(v, "id")
  10. var out []string
  11. for i, line := range lines {
  12. marker := "-m comment --comment " + quote("id:"+id)
  13. at := strings.LastIndex(line, marker)
  14. if at < 0 {
  15. out = append(out, line)
  16. continue
  17. }
  18. end := at + len(marker)
  19. match, target := line[:end], strings.TrimSpace(line[end:])
  20. if log, _ := v["log"].(bool); log && text(v, "action") != "log" {
  21. prefix := text(v, "log_prefix")
  22. logMatch := strings.Replace(match, marker, "-m comment --comment "+quote("id:"+id+":log"), 1)
  23. out = append(out, logMatch+" -j LOG --log-prefix "+quote(prefix))
  24. }
  25. pass, _ := v["passthrough"].(bool)
  26. action := text(v, "action")
  27. if kind == "mangle" && !pass && action != "accept" && action != "drop" && action != "return" && action != "jump" {
  28. h := sha256.Sum256([]byte(fmt.Sprintf("%s:%d", id, i)))
  29. chain := fmt.Sprintf("R_%x", h[:6])
  30. out = append(out, ":"+chain+" - [0:0]", match+" -g "+chain)
  31. if target != "" {
  32. out = append(out, "-A "+chain+" "+target)
  33. }
  34. out = append(out, "-A "+chain+" -j RETURN")
  35. } else {
  36. out = append(out, line)
  37. }
  38. }
  39. return out
  40. }