360 lines
9.9 KiB
Go
360 lines
9.9 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/maspend/hostora/internal/store"
|
|
"github.com/maspend/hostora/internal/waf"
|
|
)
|
|
|
|
// ---------- WAF per situs (v0.4) ----------
|
|
//
|
|
// Rute (didaftarkan oleh parent di routes() — file ini TIDAK mengubah
|
|
// server.go):
|
|
//
|
|
// PUT/GET /api/sites/{id}/waf -> handleWAFMode
|
|
// POST /api/sites/{id}/waf/disable -> handleWAFDisable
|
|
// GET /api/waf/log -> handleWAFLog
|
|
//
|
|
// Middleware WAF sendiri dipasang oleh parent dengan membungkus mux
|
|
// (lihat potongan wiring di laporan v0.4.0).
|
|
|
|
// validWAFMode melaporkan apakah mode WAF dikenal.
|
|
func validWAFMode(mode string) bool {
|
|
switch mode {
|
|
case waf.ModeOff, waf.ModeDetect, waf.ModeBlock:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// wafModeForSite adalah resolver mode untuk waf.Middleware: mencari
|
|
// situs berdasarkan header Host (buang port dan "www.") dan
|
|
// mengembalikan Site.WAFMode-nya, atau "off" bila tidak ditemukan.
|
|
// Dipakai parent pada wiring middleware.
|
|
func (s *Server) wafModeForSite(r *http.Request) string {
|
|
if r == nil {
|
|
return waf.ModeOff
|
|
}
|
|
host := waf.SiteFromHost(r.Host)
|
|
if host == "" {
|
|
return waf.ModeOff
|
|
}
|
|
mode := waf.ModeOff
|
|
s.store.View(func(d *store.Data) {
|
|
for _, site := range d.Sites {
|
|
if site.Domain == host {
|
|
if site.WAFMode != "" {
|
|
mode = site.WAFMode
|
|
}
|
|
return
|
|
}
|
|
}
|
|
})
|
|
return mode
|
|
}
|
|
|
|
// logWAFRequest adalah callback log untuk waf.Middleware: mengubah
|
|
// waf.LogEntry menjadi store.WAFLogEntry, menambahkannya ke store,
|
|
// dan memangkas log ke 100 entri terbaru (waf.TrimLog). Best effort:
|
|
// galat penyimpanan diabaikan supaya request situs tidak gagal hanya
|
|
// karena log gagal ditulis.
|
|
func (s *Server) logWAFRequest(entry waf.LogEntry) {
|
|
_ = s.store.Update(func(d *store.Data) error {
|
|
d.WAFLog = append(d.WAFLog, store.WAFLogEntry{
|
|
Time: entry.Time,
|
|
Site: entry.Site,
|
|
IP: entry.IP,
|
|
Score: entry.Score,
|
|
RuleID: entry.RuleID,
|
|
Matched: entry.Matched,
|
|
Action: entry.Action,
|
|
})
|
|
d.WAFLog = waf.TrimLog(d.WAFLog)
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// wafRulesView adalah representasi aturan WAF yang bisa di-JSON-kan
|
|
// (Pattern *regexp.Regexp tidak bisa di-marshal, jadi dipakai string).
|
|
type wafRuleView struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Pattern string `json:"pattern"`
|
|
Score int `json:"score"`
|
|
OWASP string `json:"owasp"`
|
|
}
|
|
|
|
func wafRulesList() []wafRuleView {
|
|
rules := waf.Rules()
|
|
out := make([]wafRuleView, 0, len(rules))
|
|
for _, r := range rules {
|
|
out = append(out, wafRuleView{
|
|
ID: r.ID, Name: r.Name, Pattern: r.PatternString(),
|
|
Score: r.Score, OWASP: r.OWASP,
|
|
})
|
|
}
|
|
return out
|
|
}
|
|
|
|
// handleWAFMode menangani GET dan PUT /api/sites/{id}/waf.
|
|
//
|
|
// GET -> mode saat ini + daftar aturan.
|
|
// PUT -> {mode: "off"|"detect"|"block"}; memvalidasi, menyimpan
|
|
//
|
|
// Site.WAFMode, menyinkronkan snippet nginx di vhost situs
|
|
// (bila ada), dan mencatat "waf.mode" di log aktivitas.
|
|
func (s *Server) handleWAFMode(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
actor, ip := s.actorIP(r)
|
|
site, found := s.findSite(id)
|
|
if !found {
|
|
writeErr(w, http.StatusNotFound, errNotFound.Error())
|
|
return
|
|
}
|
|
// WAF hanya untuk situs milik pengguna sendiri (v0.5).
|
|
if !s.canAccessSite(r, site) {
|
|
writeErr(w, http.StatusForbidden, "situs ini bukan milikmu")
|
|
return
|
|
}
|
|
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
var site store.Site
|
|
found := false
|
|
s.store.View(func(d *store.Data) {
|
|
for _, st := range d.Sites {
|
|
if st.ID == id {
|
|
site, found = st, true
|
|
return
|
|
}
|
|
}
|
|
})
|
|
if !found {
|
|
writeErr(w, http.StatusNotFound, errNotFound.Error())
|
|
return
|
|
}
|
|
mode := site.WAFMode
|
|
if mode == "" {
|
|
mode = waf.ModeOff
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"site_id": site.ID,
|
|
"domain": site.Domain,
|
|
"mode": mode,
|
|
"rules": wafRulesList(),
|
|
})
|
|
case http.MethodPut:
|
|
var in struct {
|
|
Mode string `json:"mode"`
|
|
}
|
|
if err := readJSON(r, &in); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "JSON tidak valid")
|
|
return
|
|
}
|
|
mode := strings.ToLower(strings.TrimSpace(in.Mode))
|
|
if !validWAFMode(mode) {
|
|
writeErr(w, http.StatusBadRequest, `mode harus "off", "detect", atau "block"`)
|
|
return
|
|
}
|
|
var updated store.Site
|
|
err := s.store.Update(func(d *store.Data) error {
|
|
for i := range d.Sites {
|
|
if d.Sites[i].ID == id {
|
|
d.Sites[i].WAFMode = mode
|
|
d.Sites[i].UpdatedAt = time.Now()
|
|
updated = d.Sites[i]
|
|
return nil
|
|
}
|
|
}
|
|
return errNotFound
|
|
})
|
|
if err != nil {
|
|
writeErr(w, http.StatusNotFound, err.Error())
|
|
return
|
|
}
|
|
nginxUpdated, nginxErr := syncWAFVhost(updated)
|
|
s.log(actor, "waf.mode", updated.Domain, ip, "ok", "mode "+mode)
|
|
resp := map[string]any{
|
|
"ok": true, "site_id": updated.ID, "domain": updated.Domain,
|
|
"mode": mode, "nginx_updated": nginxUpdated,
|
|
}
|
|
if nginxErr != nil {
|
|
resp["nginx_error"] = nginxErr.Error()
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
default:
|
|
writeErr(w, http.StatusMethodNotAllowed, "metode tidak diizinkan")
|
|
}
|
|
}
|
|
|
|
// handleWAFDisable menangani POST /api/sites/{id}/waf/disable:
|
|
// mode menjadi "off" dan snippet nginx dihapus dari vhost (bila ada).
|
|
func (s *Server) handleWAFDisable(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeErr(w, http.StatusMethodNotAllowed, "metode tidak diizinkan")
|
|
return
|
|
}
|
|
id := r.PathValue("id")
|
|
actor, ip := s.actorIP(r)
|
|
site, found := s.findSite(id)
|
|
if !found {
|
|
writeErr(w, http.StatusNotFound, errNotFound.Error())
|
|
return
|
|
}
|
|
// WAF hanya untuk situs milik pengguna sendiri (v0.5).
|
|
if !s.canAccessSite(r, site) {
|
|
writeErr(w, http.StatusForbidden, "situs ini bukan milikmu")
|
|
return
|
|
}
|
|
var updated store.Site
|
|
err := s.store.Update(func(d *store.Data) error {
|
|
for i := range d.Sites {
|
|
if d.Sites[i].ID == id {
|
|
d.Sites[i].WAFMode = waf.ModeOff
|
|
d.Sites[i].UpdatedAt = time.Now()
|
|
updated = d.Sites[i]
|
|
return nil
|
|
}
|
|
}
|
|
return errNotFound
|
|
})
|
|
if err != nil {
|
|
writeErr(w, http.StatusNotFound, err.Error())
|
|
return
|
|
}
|
|
nginxUpdated, nginxErr := syncWAFVhost(updated)
|
|
s.log(actor, "waf.mode", updated.Domain, ip, "ok", "mode off (dinonaktifkan)")
|
|
resp := map[string]any{
|
|
"ok": true, "site_id": updated.ID, "domain": updated.Domain,
|
|
"mode": waf.ModeOff, "nginx_updated": nginxUpdated,
|
|
}
|
|
if nginxErr != nil {
|
|
resp["nginx_error"] = nginxErr.Error()
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// handleWAFLog menangani GET /api/waf/log (admin saja, seperti
|
|
// /api/activity): 100 entri WAF terakhir, terbaru dulu.
|
|
func (s *Server) handleWAFLog(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
writeErr(w, http.StatusMethodNotAllowed, "metode tidak diizinkan")
|
|
return
|
|
}
|
|
if !s.isAdmin(r) {
|
|
writeErr(w, http.StatusForbidden, "hanya admin")
|
|
return
|
|
}
|
|
var all []store.WAFLogEntry
|
|
s.store.View(func(d *store.Data) { all = d.WAFLog })
|
|
if all == nil {
|
|
all = []store.WAFLogEntry{}
|
|
}
|
|
// Terbaru dulu, maks 100.
|
|
out := make([]store.WAFLogEntry, 0, len(all))
|
|
for i := len(all) - 1; i >= 0; i-- {
|
|
out = append(out, all[i])
|
|
if len(out) >= waf.MaxLogEntries {
|
|
break
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"total": len(all),
|
|
"entries": out,
|
|
})
|
|
}
|
|
|
|
// ---------- Sinkronisasi snippet nginx ----------
|
|
|
|
// syncWAFVhost menulis/mengganti/menghapus blok WAF di file vhost
|
|
// nginx situs. Mengembalikan (diperbarui, galat):
|
|
//
|
|
// - VhostPath kosong atau file tidak ada -> (false, nil): situs
|
|
// belum punya vhost nginx (status "planned"), tidak ada yang
|
|
// ditulis dan itu bukan galat.
|
|
// - mode "off" -> blok dihapus bila ada.
|
|
// - mode "detect"/"block" -> blok diganti (bila sudah ada) atau
|
|
// disisipkan sebelum kurung tutup terakhir blok server.
|
|
//
|
|
// Operasi idempotent: blok lama selalu dihapus dulu sebelum blok baru
|
|
// ditulis, jadi blok tidak pernah terduplikasi. Nginx TIDAK di-reload
|
|
// di sini (konsisten dengan pembuatan vhost di handleSites) — admin
|
|
// me-reload nginx sendiri (`nginx -t && systemctl reload nginx`).
|
|
func syncWAFVhost(site store.Site) (bool, error) {
|
|
if site.VhostPath == "" {
|
|
return false, nil
|
|
}
|
|
raw, err := os.ReadFile(site.VhostPath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
content := removeWAFBlock(string(raw))
|
|
if site.WAFMode != waf.ModeOff && site.WAFMode != "" {
|
|
snippet := waf.NginxRules(site.Domain, site.WAFMode)
|
|
if snippet != "" {
|
|
content = insertWAFBlock(content, snippet)
|
|
}
|
|
}
|
|
if content == string(raw) {
|
|
return false, nil
|
|
}
|
|
if err := os.WriteFile(site.VhostPath, []byte(content), 0o644); err != nil {
|
|
return false, err
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// removeWAFBlock menghapus blok dari MarkerStart sampai MarkerEnd
|
|
// (termasuk kedua baris marker). Bila tidak ada blok, isi dikembalikan
|
|
// apa adanya.
|
|
func removeWAFBlock(content string) string {
|
|
start := strings.Index(content, waf.MarkerStart)
|
|
if start < 0 {
|
|
return content
|
|
}
|
|
end := strings.Index(content[start:], waf.MarkerEnd)
|
|
if end < 0 {
|
|
return content
|
|
}
|
|
end += start + len(waf.MarkerEnd)
|
|
// Sertakan baris marker sampai akhir baris (termasuk newline).
|
|
if nl := strings.Index(content[end:], "\n"); nl >= 0 {
|
|
end += nl + 1
|
|
}
|
|
// Baris sebelum marker: bila marker berada di awal barisnya
|
|
// sendiri, buang juga newline sebelumnya agar tidak tersisa
|
|
// baris kosong ganda.
|
|
head := content[:start]
|
|
if strings.HasSuffix(head, "\n") {
|
|
// Pertahankan satu newline pemisah dengan konten sebelumnya.
|
|
head = strings.TrimSuffix(head, "\n")
|
|
if head != "" {
|
|
head += "\n"
|
|
}
|
|
}
|
|
return head + content[end:]
|
|
}
|
|
|
|
// insertWAFBlock menyisipkan snippet sebelum kurung tutup terakhir
|
|
// ("}") file vhost — yaitu penutup blok server — supaya location/if
|
|
// berada di dalam blok server. Bila tidak ada "}", snippet ditambahkan
|
|
// di akhir file.
|
|
func insertWAFBlock(content, snippet string) string {
|
|
if !strings.HasSuffix(content, "\n") && content != "" {
|
|
content += "\n"
|
|
}
|
|
idx := strings.LastIndex(content, "}")
|
|
if idx < 0 {
|
|
return content + snippet
|
|
}
|
|
return content[:idx] + snippet + content[idx:]
|
|
}
|