Compare commits

...

11 Commits

Author SHA1 Message Date
cb81eafe74 Try Dualstack Update
All checks were successful
release-tag / release-image (push) Successful in 1m34s
2025-06-26 21:00:56 +02:00
a5f3fd110a update FTP + Message on Slave-Mode
All checks were successful
release-tag / release-image (push) Successful in 2m21s
2025-06-25 21:20:11 +02:00
742d727802 Ports "143", "993", "1723" ergänzt
All checks were successful
release-tag / release-image (push) Successful in 1m55s
2025-06-23 18:54:30 +02:00
7aa77d9560 fix metrics
All checks were successful
release-tag / release-image (push) Successful in 1m38s
2025-06-23 18:41:31 +02:00
d0d6154bec bugfix3
All checks were successful
release-tag / release-image (push) Successful in 1m47s
2025-06-21 22:43:43 +02:00
28d724ed20 bugfix
All checks were successful
release-tag / release-image (push) Successful in 1m38s
2025-06-21 22:12:31 +02:00
cf6a812004 debug
All checks were successful
release-tag / release-image (push) Successful in 1m52s
2025-06-18 12:37:32 +02:00
8ae64e5619 Release 0.3.0
All checks were successful
release-tag / release-image (push) Successful in 1m57s
2025-06-17 22:11:26 +02:00
203af2a46b Release-Candidate with Dynamic TCP and UDP-Ports 2025-06-17 22:03:33 +02:00
46bb3adf76 Release 0.2.0
All checks were successful
release-tag / release-image (push) Successful in 1m51s
2025-06-17 00:19:28 +02:00
b3a2bafb80 Release 0.1.0
All checks were successful
release-tag / release-image (push) Successful in 1m31s
2025-06-15 17:02:55 +02:00
5 changed files with 359 additions and 39 deletions

View File

@@ -0,0 +1,51 @@
name: release-tag
on:
push:
branches:
- 'main'
jobs:
release-image:
runs-on: ubuntu-fast
env:
DOCKER_ORG: ${{ vars.DOCKER_ORG }}
DOCKER_LATEST: latest
RUNNER_TOOL_CACHE: /toolcache
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker BuildX
uses: docker/setup-buildx-action@v2
with: # replace it with your local IP
config-inline: |
[registry."${{ vars.DOCKER_REGISTRY }}"]
http = true
insecure = true
- name: Login to DockerHub
uses: docker/login-action@v2
with:
registry: ${{ vars.DOCKER_REGISTRY }} # replace it with your local IP
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Get Meta
id: meta
run: |
echo REPO_NAME=$(echo ${GITHUB_REPOSITORY} | awk -F"/" '{print $2}') >> $GITHUB_OUTPUT
echo REPO_VERSION=$(git describe --tags --always | sed 's/^v//') >> $GITHUB_OUTPUT
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
file: ./Dockerfile
platforms: |
linux/amd64
push: true
tags: | # replace it with your local IP and tags
${{ vars.DOCKER_REGISTRY }}/${{ env.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}:${{ steps.meta.outputs.REPO_VERSION }}
${{ vars.DOCKER_REGISTRY }}/${{ env.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}:${{ env.DOCKER_LATEST }}

28
Dockerfile Normal file
View File

@@ -0,0 +1,28 @@
# -------- Dockerfile (Multi-Stage Build) --------
# 1. Builder-Stage
FROM golang:1.24-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /bin/ipblock-api
# 2. Runtime-Stage
FROM alpine:3.20
# HTTPS-Callouts in Alpine brauchen ca-certificates
RUN apk add --no-cache ca-certificates
COPY --from=builder /bin/ipblock-api /bin/ipblock-api
# Default listens on :8080 siehe main.go
EXPOSE 8080
# Environment defaults; können per compose überschrieben werden
ENV REDIS_ADDR=redis:6379 \
BLOCKLIST_MODE=slave \
HASH_NAME=bl:manual \
MASTER_URL=https://flod-proxy.send.nrw
ENTRYPOINT ["/bin/ipblock-api"]

View File

@@ -1,2 +1 @@
# flod-pod

25
compose.yml Normal file
View File

@@ -0,0 +1,25 @@
services:
api:
image: git.send.nrw/sendnrw/flod-pod:latest
container_name: ipblock-slave
networks:
- flod_nw
environment:
# Beispiel mehrere Listen in einer Kategorie „spam“
BLOCKLIST_MODE: slave
MASTER_URL: https://flod-proxy.send.nrw
#ports:
#- "8080:8080" # <host>:<container>
restart: unless-stopped
newt:
image: fosrl/newt
container_name: newt
networks:
- flod_nw
restart: unless-stopped
environment:
- PANGOLIN_ENDPOINT=
- NEWT_ID=
- NEWT_SECRET=
networks:
flod_nw:

293
main.go
View File

@@ -3,11 +3,14 @@ package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
"github.com/redis/go-redis/v9"
@@ -16,106 +19,317 @@ import (
var (
ctx = context.Background()
redisClient *redis.Client
hashName = "bl:cat"
hashName = "bl:manual"
blocklistMode string
masterURL string
)
func main() {
// Modus und Master-URL aus ENV
blocklistMode = os.Getenv("BLOCKLIST_MODE")
hashName = os.Getenv("HASH_NAME")
if hashName == "" {
hashName = "bl:manual"
}
//DEBUG
//blocklistMode = "master"
//DEBUG
if blocklistMode != "master" && blocklistMode != "slave" {
log.Fatal("BLOCKLIST_MODE muss 'master' oder 'slave' sein")
log.Fatal("BLOCKLIST_MODE has to be 'master' or 'slave'")
} else {
log.Println("✅ BLOCKLIST_MODE set to:", blocklistMode)
}
if blocklistMode == "slave" {
masterURL = os.Getenv("MASTER_URL")
//DEBUG
//masterURL = "http://127.0.0.1:8081"
//DEBUG
if masterURL == "" {
log.Fatal("MASTER_URL muss gesetzt sein im slave Modus")
log.Fatal("MASTER_URL has to be set in slave mode")
}
log.Println("✅ MASTER_URL set to:", masterURL)
}
if blocklistMode == "master" {
// Redis initialisieren
redisAddr := os.Getenv("REDIS_ADDR")
redisPass := os.Getenv("REDIS_PASS")
if redisAddr == "" {
redisAddr = "localhost:6379"
}
log.Println("✅ Redis Connection set to:", redisAddr)
redisClient = redis.NewClient(&redis.Options{
Addr: redisAddr,
Password: "",
DB: 0,
Username: os.Getenv("REDIS_USER"),
Password: redisPass,
})
if err := redisClient.Ping(ctx).Err(); err != nil {
log.Fatalf("Keine Verbindung zu Redis: %v", err)
log.Fatalf("❌ No connection to redis-server: %v", err)
}
}
// Endpunkte registrieren
portsTCP := []string{"135", "139", "445", "389", "636", "3268", "3269", "88", "3389", "3306", "27017", "5432", "25", "123", "5900", "143", "993", "1723", "21"}
for _, port := range portsTCP {
//go startTCPListener(port)
go startTCPListenerWithNet("tcp4", port)
go startTCPListenerWithNet("tcp6", port)
}
portsUDP := []string{"135", "137", "138", "389", "3389", "88"}
for _, port := range portsUDP {
go startUDPListener("udp4", port)
go startUDPListener("udp6", port)
}
http.HandleFunc("/", handleRoot)
http.HandleFunc("/add", handleAdd)
http.HandleFunc("/dashboard", handleDashboard)
http.HandleFunc("/dashboard.json", handleDashboardJSON)
http.HandleFunc("/metrics", handleMetrics)
log.Println("Server läuft im Modus:", blocklistMode)
log.Println("Server startet auf :8080")
log.Println("🚀 Server listening at :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
log.Fatal("⚠️ ListenAndServe: ", err)
}
}
/*func startTCPListener(port string) {
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatalf("❌ Could not listen on TCP port %s: %v", port, err)
}
log.Printf("🚀 TCP Honeypod listening on port %s", port)
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("⚠️ Error accepting TCP connection: %v", err)
continue
}
ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
processIP(ip, port, "TCP", nil)
conn.Close()
}
}*/
func startTCPListenerWithNet(network, port string) {
ln, err := net.Listen(network, ":"+port)
if err != nil {
log.Fatalf("❌ Could not listen on %s port %s: %v", network, port, err)
}
log.Printf("🚀 TCP Honeypot listening on %s port %s", network, port)
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("⚠️ Error accepting TCP connection: %v", err)
continue
}
ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
processIP(ip, port, "TCP", nil)
conn.Close()
}
}
func startUDPListener(network, port string) {
addr := net.UDPAddr{
Port: portInt(port),
IP: nil, // nil bedeutet: alle Interfaces (IPv4 oder IPv6 je nach Netzwerktyp)
}
conn, err := net.ListenUDP(network, &addr)
if err != nil {
log.Fatalf("❌ Could not listen on %s port %s: %v", network, port, err)
}
log.Printf("🚀 UDP Honeypot listening on %s port %s", network, port)
buf := make([]byte, 1024)
for {
n, remoteAddr, err := conn.ReadFromUDP(buf)
if err != nil {
log.Printf("⚠️ Error reading UDP packet: %v", err)
continue
}
if n > 0 {
ip := remoteAddr.IP.String()
processIP(ip, port, "UDP", nil)
}
}
}
/*func startUDPListener(port string) {
addr := net.UDPAddr{
Port: portInt(port),
IP: net.ParseIP("0.0.0.0"),
}
conn, err := net.ListenUDP("udp", &addr)
if err != nil {
log.Fatalf("❌ Could not listen on UDP port %s: %v", port, err)
}
log.Printf("🚀 UDP Honeypod listening on port %s", port)
buf := make([]byte, 1024)
for {
n, remoteAddr, err := conn.ReadFromUDP(buf)
if err != nil {
log.Printf("⚠️ Error reading UDP packet: %v", err)
continue
}
if n > 0 {
ip := remoteAddr.IP.String()
processIP(ip, port, "UDP", nil)
}
}
}
func startUDP6Listener(port string) {
addr := net.UDPAddr{
Port: portInt(port),
IP: net.ParseIP("::"),
}
conn, err := net.ListenUDP("udp", &addr)
if err != nil {
log.Fatalf("❌ Could not listen on UDP port %s: %v", port, err)
}
log.Printf("🚀 UDP Honeypod listening on port %s", port)
buf := make([]byte, 1024)
for {
n, remoteAddr, err := conn.ReadFromUDP(buf)
if err != nil {
log.Printf("⚠️ Error reading UDP packet: %v", err)
continue
}
if n > 0 {
ip := remoteAddr.IP.String()
processIP(ip, port, "UDP", nil)
}
}
}*/
func handleRoot(w http.ResponseWriter, r *http.Request) {
ip := getClientIP(r)
if ip == "" {
http.Error(w, "Ungültige IP", http.StatusBadRequest)
http.Error(w, "Wrong IP", http.StatusBadRequest)
return
}
processIP(ip, w)
processIP(ip, "80", "HTTP", w)
}
func handleAdd(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil || len(body) == 0 {
http.Error(w, "Ungültiger Body", http.StatusBadRequest)
http.Error(w, "Wrong Body", http.StatusBadRequest)
return
}
ip := strings.TrimSpace(string(body))
if !isValidIP(ip) {
http.Error(w, "Ungültige IP", http.StatusBadRequest)
parts := strings.Split(string(body), "|")
if len(parts) != 3 {
http.Error(w, "Wrong Body", http.StatusBadRequest)
return
}
processIP(ip, w)
ip, port, proto := parts[0], parts[1], parts[2]
processIP(ip, port, proto, w)
}
func processIP(ip string, w http.ResponseWriter) {
func processIP(ip, port, proto string, w http.ResponseWriter) {
ipKey := ip + "/32"
if blocklistMode == "master" {
err := redisClient.HSet(ctx, hashName, ipKey, 1).Err()
if err != nil {
log.Printf("Fehler beim Schreiben in Redis: %v", err)
http.Error(w, "Interner Fehler", http.StatusInternalServerError)
return
_ = redisClient.HSet(ctx, hashName, ipKey, 1).Err()
_ = redisClient.SAdd(ctx, "bl:manual:"+ipKey, port+"/"+proto).Err()
log.Printf("✅ IP %s saved with port %s/%s", ipKey, port, proto)
if w != nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("Temporary unavailable"))
}
log.Printf("IP %s in Redis gespeichert", ipKey)
w.WriteHeader(http.StatusOK)
w.Write([]byte("IP gespeichert: " + ipKey + "\n"))
} else {
// Slave: an Master weiterleiten
resp, err := http.Post(masterURL+"/add", "text/plain", bytes.NewBuffer([]byte(ip)))
payload := ip + "|" + port + "|" + proto
resp, err := http.Post(masterURL+"/add", "text/plain", bytes.NewBuffer([]byte(payload)))
if err != nil {
log.Printf("Fehler beim Weiterleiten an Master: %v", err)
http.Error(w, "Fehler beim Weiterleiten", http.StatusBadGateway)
log.Printf("❌ Error relaying to Master: %v", err)
if w != nil {
http.Error(w, "Error relaying", http.StatusBadGateway)
}
return
}
log.Printf("✅ IP %s relayed with port %s/%s", ipKey, port, proto)
defer resp.Body.Close()
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
if w != nil {
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
}
}
func handleMetrics(w http.ResponseWriter, r *http.Request) {
keys, _ := redisClient.HKeys(ctx, hashName).Result()
totalIPs := len(keys)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(fmt.Sprintf("honeypod_blocked_ips_total %d\n", totalIPs)))
// Map zum Zählen
portHitCounter := make(map[string]int)
for _, ip := range keys {
ports, _ := redisClient.SMembers(ctx, "bl:manual:"+ip).Result()
for _, p := range ports {
portHitCounter[p]++
}
}
// Jetzt pro Port+Proto Metriken ausgeben
for p, count := range portHitCounter {
parts := strings.Split(p, "/")
if len(parts) == 2 {
port, proto := parts[0], parts[1]
metricName := fmt.Sprintf("honeypod_port_hits{port=\"%s\",protocol=\"%s\"} %d\n", port, proto, count)
w.Write([]byte(metricName))
}
}
}
func handleDashboard(w http.ResponseWriter, r *http.Request) {
keys, _ := redisClient.HKeys(ctx, hashName).Result()
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Honeypod Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-dark text-light">
<div class="container mt-4">
<h1 class="mb-4">Honeypod Dashboard</h1>
<table class="table table-dark table-striped">
<thead><tr><th>IP</th><th>Ports / Protocols</th></tr></thead>
<tbody>
`))
for _, ip := range keys {
ports, _ := redisClient.SMembers(ctx, "bl:manual:"+ip).Result()
w.Write([]byte("<tr><td>" + ip + "</td><td>" + strings.Join(ports, ", ") + "</td></tr>"))
}
w.Write([]byte(`
</tbody>
</table>
</div>
</body>
</html>
`))
}
func handleDashboardJSON(w http.ResponseWriter, r *http.Request) {
keys, _ := redisClient.HKeys(ctx, hashName).Result()
result := make(map[string][]string)
for _, ip := range keys {
ports, _ := redisClient.SMembers(ctx, "bl:manual:"+ip).Result()
result[ip] = ports
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
}
func getClientIP(r *http.Request) string {
xff := r.Header.Get("X-Forwarded-For")
xrip := r.Header.Get("X-Real-Ip")
log.Printf("X-Forwarded-For: %s, X-Real-Ip: %s, RemoteAddr: %s", xff, xrip, r.RemoteAddr)
if xff != "" {
parts := strings.Split(xff, ",")
ip := strings.TrimSpace(parts[0])
@@ -124,11 +338,9 @@ func getClientIP(r *http.Request) string {
}
}
xrip := r.Header.Get("X-Real-Ip")
if xrip != "" && isValidIP(xrip) {
return xrip
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return ""
@@ -142,3 +354,8 @@ func getClientIP(r *http.Request) string {
func isValidIP(ip string) bool {
return net.ParseIP(ip) != nil
}
func portInt(port string) int {
p, _ := strconv.Atoi(port)
return p
}