-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalert_consumer.go
More file actions
191 lines (167 loc) · 5.08 KB
/
alert_consumer.go
File metadata and controls
191 lines (167 loc) · 5.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/confluentinc/confluent-kafka-go/v2/kafka"
)
// AlertData struct để parse JSON từ Kafka
type AlertData struct {
AlertID string `json:"alert_id"`
Timestamp string `json:"timestamp"`
DetectionTime string `json:"detection_time"`
Severity string `json:"severity"`
Type string `json:"type"`
Source struct {
IP string `json:"ip"`
Port int `json:"port"`
} `json:"source"`
Destination struct {
IP string `json:"ip"`
Port int `json:"port"`
} `json:"destination"`
Protocol int `json:"protocol"`
Prediction struct {
Label string `json:"label"`
Confidence float64 `json:"confidence"`
Threshold float64 `json:"threshold"`
} `json:"prediction"`
FlowStats struct {
Duration float64 `json:"duration"`
TotalFwdPackets int `json:"total_fwd_packets"`
TotalBwdPackets int `json:"total_bwd_packets"`
TotalFwdBytes int `json:"total_fwd_bytes"`
TotalBwdBytes int `json:"total_bwd_bytes"`
} `json:"flow_stats"`
}
// getProtocolName converts protocol number to name
func getProtocolName(protocol int) string {
protocolMap := map[int]string{
1: "ICMP",
6: "TCP",
17: "UDP",
}
if name, ok := protocolMap[protocol]; ok {
return name
}
return fmt.Sprintf("Protocol-%d", protocol)
}
// escapeHTML escapes special characters for Telegram HTML parse mode
func escapeHTML(s string) string {
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
return s
}
func sendTelegramAlert(message string) error {
credentials := []string{
"8322060808:AAFeGSVmuhGceQyJVkSKc746odROERyL0A0",
"5833402318",
}
botToken := credentials[0]
chatID := credentials[1]
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
// Escape message for JSON
escapedMsg := strings.ReplaceAll(message, `"`, `\"`)
escapedMsg = strings.ReplaceAll(escapedMsg, "\n", "\\n")
bodyJSON := fmt.Sprintf(
`{"chat_id":"%s","text":"%s","parse_mode":"HTML"}`,
chatID, escapedMsg,
)
resp, err := http.Post(url, "application/json", bytes.NewBuffer([]byte(bodyJSON)))
if err != nil {
return fmt.Errorf("failed to send POST request: %w", err)
}
defer resp.Body.Close()
// Check if response status is a success (2xx)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// Read the error body
bodyBytes, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return fmt.Errorf("status %s; error reading body: %w", resp.Status, readErr)
}
return fmt.Errorf("telegram API error: status %s; body: %s", resp.Status, string(bodyBytes))
}
// All good; success
return nil
}
func main() {
c, err := kafka.NewConsumer(&kafka.ConfigMap{
"bootstrap.servers": "localhost:9092",
"group.id": "myGroup",
"auto.offset.reset": "earliest",
})
if err != nil {
panic(err)
}
err = c.SubscribeTopics([]string{"alert"}, nil)
if err != nil {
panic(err)
}
// A signal handler or similar could be used to set this to false to break the loop.
run := true
for run {
msg, err := c.ReadMessage(time.Second)
if err == nil {
fmt.Printf("Message on %s: %s\n", msg.TopicPartition, string(msg.Value))
// Parse JSON alert
var alert AlertData
if err := json.Unmarshal(msg.Value, &alert); err != nil {
fmt.Printf("❌ Failed to parse alert JSON: %v\n", err)
continue
}
// Format message với thông tin chi tiết
telegramMsg := fmt.Sprintf(
"🚨 <b>BOTNET ALERT</b> 🚨\n\n"+
"<b>Alert ID:</b> %s\n"+
"<b>Time:</b> %s\n"+
"<b>Severity:</b> %s\n\n"+
"<b>🔴 Detection:</b>\n"+
" • Label: %s\n"+
" • Confidence: %.2f%%\n"+
" • Threshold: %.4f\n\n"+
"<b>📡 Network Info:</b>\n"+
" • Source: %s:%d\n"+
" • Destination: %s:%d\n"+
" • Protocol: %s\n\n"+
"<b>📊 Flow Statistics:</b>\n"+
" • Duration: %.2f sec\n"+
" • Forward: %d packets (%d bytes)\n"+
" • Backward: %d packets (%d bytes)",
escapeHTML(alert.AlertID),
escapeHTML(alert.Timestamp),
escapeHTML(alert.Severity),
escapeHTML(alert.Prediction.Label),
alert.Prediction.Confidence*100,
alert.Prediction.Threshold,
escapeHTML(alert.Source.IP),
alert.Source.Port,
escapeHTML(alert.Destination.IP),
alert.Destination.Port,
getProtocolName(alert.Protocol),
alert.FlowStats.Duration,
alert.FlowStats.TotalFwdPackets,
alert.FlowStats.TotalFwdBytes,
alert.FlowStats.TotalBwdPackets,
alert.FlowStats.TotalBwdBytes,
)
// Gửi alert đến Telegram
err := sendTelegramAlert(telegramMsg)
if err != nil {
fmt.Printf("❌ Failed to send Telegram alert: %v\n", err)
} else {
fmt.Println("✅ Alert sent to Telegram successfully")
}
} else if !err.(kafka.Error).IsTimeout() {
// The client will automatically try to recover from all errors.
// Timeout is not considered an error because it is raised by
// ReadMessage in absence of messages.
fmt.Printf("Consumer error: %v (%v)\n", err, msg)
}
}
c.Close()
}