Initial commit — migrated from GitHub (account suspended)
This commit is contained in:
commit
09d0ee68c8
65 files changed
+23255
No files matched your search
@@ -0,0 +1,401 @@
|
||||
// Dashboard panel (v0.4): kartu sistem dari data nyata, ringkasan jumlah
|
||||
// dari store, dan bagian keamanan (login gagal 24 jam terakhir + risiko
|
||||
// yang benar-benar diperiksa). Tidak ada angka yang dikarang: yang tidak
|
||||
// dapat dideteksi dilaporkan sebagai "tidak dapat dideteksi" / level
|
||||
// "tidak_diketahui", bukan "aman".
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/maspend/hostora/internal/store"
|
||||
)
|
||||
|
||||
// handleDashboard — GET /api/dashboard (admin saja; parent mendaftarkan
|
||||
// rute dengan requireAuth). Mengembalikan sistem, ringkasan, keamanan,
|
||||
// dan ringkasan pemindaian terakhir.
|
||||
func (s *Server) handleDashboard(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 d store.Data
|
||||
s.store.View(func(dd *store.Data) { d = *dd })
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"system": s.dashboardSystem(),
|
||||
"summary": dashboardSummary(&d),
|
||||
"security": map[string]any{
|
||||
"failed_logins_24h": failedLogins24h(&d),
|
||||
"failed_logins_by_actor": failedLoginsByActor(&d),
|
||||
"risks": s.dashboardRisks(&d),
|
||||
},
|
||||
"last_scan": lastScanSummary(d.LastScan),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- kartu sistem ----------
|
||||
|
||||
func (s *Server) dashboardSystem() map[string]any {
|
||||
memTotal, memFree := memInfo()
|
||||
diskTotal, diskFree := diskInfo("/")
|
||||
hn, _ := os.Hostname()
|
||||
load1, load5, load15 := loadAvg()
|
||||
return map[string]any{
|
||||
"cpu_percent": cpuPercent(),
|
||||
"mem_percent": percentUsed(memTotal, memFree),
|
||||
"mem_used_gb": gb(memTotal - memFree),
|
||||
"mem_total_gb": gb(memTotal),
|
||||
"disk_used_gb": gb(diskTotal - diskFree),
|
||||
"disk_total_gb": gb(diskTotal),
|
||||
"load1": load1,
|
||||
"load5": load5,
|
||||
"load15": load15,
|
||||
"processes": processCount(),
|
||||
"uptime_seconds": uptimeSeconds(),
|
||||
"hostname": hn,
|
||||
"os": readOSPretty(),
|
||||
}
|
||||
}
|
||||
|
||||
func gb(bytes uint64) float64 {
|
||||
return math.Round(float64(bytes)/1e9*100) / 100
|
||||
}
|
||||
|
||||
func percentUsed(total, free uint64) float64 {
|
||||
if total == 0 {
|
||||
return 0
|
||||
}
|
||||
return math.Round(float64(total-free)/float64(total)*1000) / 10
|
||||
}
|
||||
|
||||
// cpuPercent menghitung pemakaian CPU dari /proc/stat (dua sampel
|
||||
// berjarak 200 ms). Mengembalikan 0 bila /proc/stat tidak terbaca.
|
||||
func cpuPercent() float64 {
|
||||
idle1, total1, ok1 := readCPUStat()
|
||||
if !ok1 {
|
||||
return 0
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
idle2, total2, ok2 := readCPUStat()
|
||||
if !ok2 || total2 <= total1 {
|
||||
return 0
|
||||
}
|
||||
busy := (total2 - total1) - (idle2 - idle1)
|
||||
return math.Round(float64(busy)/float64(total2-total1)*1000) / 10
|
||||
}
|
||||
|
||||
func readCPUStat() (idle, total uint64, ok bool) {
|
||||
raw, err := os.ReadFile("/proc/stat")
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
if !strings.HasPrefix(line, "cpu ") {
|
||||
continue
|
||||
}
|
||||
f := strings.Fields(line)[1:]
|
||||
var sum uint64
|
||||
var idleVal uint64
|
||||
for i, s := range f {
|
||||
v, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
sum += v
|
||||
if i == 3 || i == 4 { // idle + iowait
|
||||
idleVal += v
|
||||
}
|
||||
}
|
||||
return idleVal, sum, true
|
||||
}
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
// loadAvg membaca /proc/loadavg (rata-rata beban 1/5/15 menit).
|
||||
func loadAvg() (float64, float64, float64) {
|
||||
raw, err := os.ReadFile("/proc/loadavg")
|
||||
if err != nil {
|
||||
return 0, 0, 0
|
||||
}
|
||||
f := strings.Fields(string(raw))
|
||||
if len(f) < 3 {
|
||||
return 0, 0, 0
|
||||
}
|
||||
l1, _ := strconv.ParseFloat(f[0], 64)
|
||||
l5, _ := strconv.ParseFloat(f[1], 64)
|
||||
l15, _ := strconv.ParseFloat(f[2], 64)
|
||||
return l1, l5, l15
|
||||
}
|
||||
|
||||
// processCount menghitung entri numerik di /proc (= jumlah proses).
|
||||
func processCount() int {
|
||||
entries, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
n := 0
|
||||
for _, e := range entries {
|
||||
if _, err := strconv.Atoi(e.Name()); err == nil {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// ---------- ringkasan ----------
|
||||
|
||||
type summaryItem struct {
|
||||
Label string `json:"label"`
|
||||
Count int `json:"count"`
|
||||
Tab string `json:"tab"`
|
||||
Note string `json:"note,omitempty"`
|
||||
}
|
||||
|
||||
func dashboardSummary(d *store.Data) []summaryItem {
|
||||
return []summaryItem{
|
||||
{Label: "Akun hosting", Count: len(d.Users), Tab: "users"},
|
||||
{Label: "Situs web", Count: len(d.Sites), Tab: "sites"},
|
||||
{Label: "Aplikasi terpasang", Count: len(d.InstalledApps), Tab: "apps"},
|
||||
{Label: "Database", Count: len(d.Databases), Tab: "databases"},
|
||||
{Label: "Mailbox", Count: len(d.Mailboxes), Tab: "mailboxes"},
|
||||
// FTP belum diimplementasikan di panel — laporkan 0 secara jujur.
|
||||
{Label: "Akun FTP", Count: 0, Tab: "ftp", Note: "ftp_belum_tersedia"},
|
||||
{Label: "Zona DNS", Count: len(d.DNSZones), Tab: "dns"},
|
||||
{Label: "Cron job", Count: len(d.CronJobs), Tab: "cron"},
|
||||
{Label: "Pengguna panel", Count: len(d.Users), Tab: "users"},
|
||||
// Panel belum melacak paket sistem — laporkan 0 secara jujur.
|
||||
{Label: "Paket", Count: 0, Tab: "packages", Note: "belum_dilacak"},
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- keamanan ----------
|
||||
|
||||
type failedLoginGroup struct {
|
||||
Actor string `json:"actor"`
|
||||
IP string `json:"ip"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// failedLogins24h menghitung entri log aktivitas "login" + "gagal" dalam
|
||||
// 24 jam terakhir.
|
||||
func failedLogins24h(d *store.Data) int {
|
||||
cutoff := time.Now().Add(-24 * time.Hour)
|
||||
n := 0
|
||||
for _, e := range d.Activity {
|
||||
if e.Action == "login" && e.Result == "gagal" && e.Time.After(cutoff) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// failedLoginsByActor merinci login gagal 24 jam terakhir per aktor/IP,
|
||||
// terbanyak dulu.
|
||||
func failedLoginsByActor(d *store.Data) []failedLoginGroup {
|
||||
cutoff := time.Now().Add(-24 * time.Hour)
|
||||
groups := map[string]*failedLoginGroup{}
|
||||
for _, e := range d.Activity {
|
||||
if e.Action != "login" || e.Result != "gagal" || !e.Time.After(cutoff) {
|
||||
continue
|
||||
}
|
||||
actor := e.Actor
|
||||
if actor == "" {
|
||||
actor = "(tidak diketahui)"
|
||||
}
|
||||
key := actor + "\x00" + e.IP
|
||||
g, ok := groups[key]
|
||||
if !ok {
|
||||
g = &failedLoginGroup{Actor: actor, IP: e.IP}
|
||||
groups[key] = g
|
||||
}
|
||||
g.Count++
|
||||
}
|
||||
out := make([]failedLoginGroup, 0, len(groups))
|
||||
for _, g := range groups {
|
||||
out = append(out, *g)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Count > out[j].Count })
|
||||
return out
|
||||
}
|
||||
|
||||
type dashboardRisk struct {
|
||||
ID string `json:"id"`
|
||||
Level string `json:"level"` // "kritis" | "tinggi" | "sedang" | "rendah" | "tidak_diketahui"
|
||||
Title string `json:"title"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// dashboardRisks memeriksa risiko nyata. Risiko hanya muncul bila
|
||||
// pemeriksaannya berhasil menemukan masalah, atau bila statusnya tidak
|
||||
// dapat diperiksa sama sekali (level "tidak_diketahui" — tidak pernah
|
||||
// dilaporkan "aman" tanpa bukti).
|
||||
func (s *Server) dashboardRisks(d *store.Data) []dashboardRisk {
|
||||
risks := []dashboardRisk{}
|
||||
if r, ok := firewallRisk(); ok {
|
||||
risks = append(risks, r)
|
||||
}
|
||||
if r, ok := s.panelCertRisk(d); ok {
|
||||
risks = append(risks, r)
|
||||
}
|
||||
var no2fa []string
|
||||
for _, u := range d.Users {
|
||||
if u.Role == "admin" && !u.TwoFAEnabled {
|
||||
no2fa = append(no2fa, u.Username)
|
||||
}
|
||||
}
|
||||
if len(no2fa) > 0 {
|
||||
risks = append(risks, dashboardRisk{
|
||||
ID: "admin-tanpa-2fa",
|
||||
Level: "tinggi",
|
||||
Title: "Admin tanpa 2FA",
|
||||
Detail: fmt.Sprintf("%d akun admin belum mengaktifkan 2FA: %s. Aktifkan TOTP di menu Keamanan.", len(no2fa), strings.Join(no2fa, ", ")),
|
||||
})
|
||||
}
|
||||
if r, ok := sshRootRisk(); ok {
|
||||
risks = append(risks, r)
|
||||
}
|
||||
return risks
|
||||
}
|
||||
|
||||
// firewallRisk memeriksa UFW, lalu firewalld, lalu aturan iptables.
|
||||
// Mengembalikan ok=false bila firewall terdeteksi aktif (bukan risiko).
|
||||
func firewallRisk() (dashboardRisk, bool) {
|
||||
run := func(name string, args ...string) (string, bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, name, args...).Output()
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return string(out), true
|
||||
}
|
||||
if out, ok := run("ufw", "status"); ok {
|
||||
if strings.Contains(out, "Status: active") {
|
||||
return dashboardRisk{}, false
|
||||
}
|
||||
if strings.Contains(out, "Status: inactive") {
|
||||
return dashboardRisk{ID: "firewall-nonaktif", Level: "tinggi", Title: "Firewall (UFW) tidak aktif",
|
||||
Detail: "ufw status melaporkan 'inactive'. Aktifkan dengan 'ufw enable'."}, true
|
||||
}
|
||||
}
|
||||
if out, ok := run("firewall-cmd", "--state"); ok {
|
||||
if strings.TrimSpace(out) == "running" {
|
||||
return dashboardRisk{}, false
|
||||
}
|
||||
return dashboardRisk{ID: "firewall-nonaktif", Level: "tinggi", Title: "Firewall (firewalld) tidak berjalan",
|
||||
Detail: "firewall-cmd --state tidak melaporkan 'running'. Jalankan firewalld."}, true
|
||||
}
|
||||
if out, ok := run("iptables", "-S"); ok {
|
||||
rules := 0
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if strings.HasPrefix(line, "-A ") || strings.HasPrefix(line, "-I ") {
|
||||
rules++
|
||||
}
|
||||
}
|
||||
if rules > 0 {
|
||||
return dashboardRisk{}, false
|
||||
}
|
||||
return dashboardRisk{ID: "firewall-tanpa-aturan", Level: "sedang", Title: "iptables tanpa aturan",
|
||||
Detail: "iptables terpasang tapi tidak ada aturan (-A/-I) yang terdaftar."}, true
|
||||
}
|
||||
return dashboardRisk{ID: "firewall-tidak-terdeteksi", Level: "tidak_diketahui",
|
||||
Title: "Status firewall tidak dapat dideteksi",
|
||||
Detail: "ufw, firewalld, dan iptables tidak tersedia atau tidak dapat dibaca di server ini; status firewall tidak diketahui — ini bukan berarti aman."}, true
|
||||
}
|
||||
|
||||
// panelCertRisk memeriksa apakah panel memakai self-signed atau sudah
|
||||
// Let's Encrypt. ok=false bila sertifikat LE terdeteksi.
|
||||
func (s *Server) panelCertRisk(d *store.Data) (dashboardRisk, bool) {
|
||||
if s.letsEncrypt && d.Settings.LetsEncrypt {
|
||||
acmeDir := filepath.Join(s.certDir, "acme")
|
||||
if entries, err := os.ReadDir(acmeDir); err == nil && len(entries) > 0 {
|
||||
return dashboardRisk{}, false // sertifikat LE tersimpan di cache ACME
|
||||
}
|
||||
return dashboardRisk{ID: "letsencrypt-belum-ada", Level: "sedang",
|
||||
Title: "Let's Encrypt diminta tapi belum ada sertifikat",
|
||||
Detail: "Pengaturan Let's Encrypt aktif tapi cache ACME masih kosong — panel kemungkinan masih memakai sertifikat self-signed."}, true
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(s.certDir, "cert.pem")); err == nil {
|
||||
return dashboardRisk{ID: "panel-self-signed", Level: "sedang",
|
||||
Title: "Panel memakai sertifikat self-signed",
|
||||
Detail: "Browser menampilkan peringatan keamanan. Aktifkan Let's Encrypt dengan hostname FQDN untuk sertifikat tepercaya."}, true
|
||||
}
|
||||
return dashboardRisk{ID: "sertifikat-tidak-terbaca", Level: "tidak_diketahui",
|
||||
Title: "Status sertifikat panel tidak dapat dibaca",
|
||||
Detail: "Direktori sertifikat panel tidak dapat dibaca; tidak dapat dipastikan apakah panel memakai self-signed atau Let's Encrypt."}, true
|
||||
}
|
||||
|
||||
// sshRootRisk membaca /etc/ssh/sshd_config bila bisa dibaca.
|
||||
// ok=false bila PermitRootLogin eksplisit "no" / "forced-commands-only".
|
||||
func sshRootRisk() (dashboardRisk, bool) {
|
||||
raw, err := os.ReadFile("/etc/ssh/sshd_config")
|
||||
if err != nil {
|
||||
return dashboardRisk{ID: "ssh-tidak-terbaca", Level: "tidak_diketahui",
|
||||
Title: "Konfigurasi SSH tidak dapat dibaca",
|
||||
Detail: fmt.Sprintf("/etc/ssh/sshd_config tidak dapat dibaca (%v); status login root SSH tidak diketahui.", err)}, true
|
||||
}
|
||||
value := ""
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
f := strings.Fields(line)
|
||||
if len(f) >= 2 && strings.EqualFold(f[0], "PermitRootLogin") {
|
||||
value = strings.ToLower(f[1]) // kemunculan terakhir menang
|
||||
}
|
||||
}
|
||||
switch value {
|
||||
case "":
|
||||
return dashboardRisk{ID: "ssh-root-tidak-pasti", Level: "tidak_diketahui",
|
||||
Title: "Pengaturan login root SSH tidak eksplisit",
|
||||
Detail: "Tidak ada pengaturan PermitRootLogin eksplisit di sshd_config — server memakai default sistem, yang tidak dapat dipastikan dari file ini."}, true
|
||||
case "yes":
|
||||
return dashboardRisk{ID: "ssh-root-login", Level: "tinggi",
|
||||
Title: "Login SSH root dengan password diizinkan",
|
||||
Detail: "PermitRootLogin yes di /etc/ssh/sshd_config. Ubah ke 'prohibit-password' atau 'no'."}, true
|
||||
case "prohibit-password", "without-password":
|
||||
return dashboardRisk{ID: "ssh-root-kunci", Level: "sedang",
|
||||
Title: "Login SSH root diizinkan dengan kunci",
|
||||
Detail: "PermitRootLogin prohibit-password: root hanya bisa login dengan kunci SSH, bukan password. Pertimbangkan 'no' bila root tidak perlu login langsung."}, true
|
||||
default: // "no", "forced-commands-only"
|
||||
return dashboardRisk{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// lastScanSummary merangkum pemindaian terakhir untuk dashboard.
|
||||
func lastScanSummary(last *store.ScanResult) map[string]any {
|
||||
if last == nil {
|
||||
return map[string]any{"scanned": false}
|
||||
}
|
||||
byLevel := map[string]int{}
|
||||
for _, f := range last.Findings {
|
||||
byLevel[f.Level]++
|
||||
}
|
||||
return map[string]any{
|
||||
"scanned": true,
|
||||
"id": last.ID,
|
||||
"started_at": last.StartedAt,
|
||||
"finished_at": last.FinishedAt,
|
||||
"files_scanned": last.FilesScanned,
|
||||
"skipped": last.Skipped,
|
||||
"findings": len(last.Findings),
|
||||
"by_level": byLevel,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user