-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase.go
603 lines (529 loc) · 18.8 KB
/
database.go
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
package main
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
_ "github.com/mattn/go-sqlite3"
"net/http"
"strconv"
)
var db *sql.DB
type HoneypotConfig struct {
ID int `yaml:"id"`
Name string `yaml:"name"`
CVE string `yaml:"cve"`
Application string `yaml:"application"`
Port int `yaml:"port"`
TemplateHTMLFile string `yaml:"template_html_file"`
DetectionEndpoint string `yaml:"detection_endpoint"`
RequestRegex string `yaml:"request_regex"`
Responders []ResponderConfig `yaml:"responders"`
DateCreated string `yaml:"date_created"`
DateUpdated string `yaml:"date_updated"`
RedirectURL string `yaml:"redirect_url"`
Enabled bool `yaml:"enabled"`
}
type ResponderConfig struct {
Engine string `yaml:"engine"`
Script string `yaml:"script"`
Parameters []string `yaml:"parameters"`
}
func InitDB(filepath string) {
var err error
db, err = sql.Open("sqlite3", filepath)
if err != nil {
logError("Failed to open database: " + err.Error())
return
}
logInfo("Database opened successfully")
createTable := `
CREATE TABLE IF NOT EXISTS honeypots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
cve TEXT,
application TEXT,
port INTEGER,
template_html_file TEXT,
detection_endpoint TEXT,
request_regex TEXT,
date_created TEXT,
date_updated TEXT,
redirect_url TEXT,
responders TEXT,
enabled BOOLEAN DEFAULT true
);`
_, err = db.Exec(createTable)
if err != nil {
logError("Failed to create honeypots table: " + err.Error())
return
}
logInfo("Honeypots table created or already exists")
createLogsTable := `
CREATE TABLE IF NOT EXISTS honeypot_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
honeypotID INTEGER,
port INTEGER,
datetime TEXT,
ip_source TEXT,
ip_destination TEXT,
log_event TEXT,
regex_match TEXT,
FOREIGN KEY(honeypotID) REFERENCES honeypots(id)
);`
_, err = db.Exec(createLogsTable)
if err != nil {
logError("Failed to create honeypot_logs table: " + err.Error())
return
}
logInfo("Honeypot_logs table created or already exists")
}
func SelectHoneypotConfig(id int) (*HoneypotConfig, error) {
config := &HoneypotConfig{}
var redirectURLPtr *string
var respondersJSON string
query := `SELECT id, name, cve, application, port, template_html_file, detection_endpoint, request_regex, date_created, date_updated, redirect_url, responders, enabled FROM honeypots WHERE id = ?`
err := db.QueryRow(query, id).Scan(
&config.ID,
&config.Name,
&config.CVE,
&config.Application,
&config.Port,
&config.TemplateHTMLFile,
&config.DetectionEndpoint,
&config.RequestRegex,
&config.DateCreated,
&config.DateUpdated,
&redirectURLPtr,
&respondersJSON,
&config.Enabled,
)
if err != nil {
if err == sql.ErrNoRows {
logInfo(fmt.Sprintf("Honeypot configuration for ID %d not found in database, inserting.", id))
return nil, nil
} else {
logError(fmt.Sprintf("Failed to select config for ID %d: %s", id, err.Error()))
return nil, err
}
}
if redirectURLPtr != nil {
config.RedirectURL = *redirectURLPtr
logInfo(fmt.Sprintf("Redirect URL for config ID %d is '%s'", id, config.RedirectURL))
} else {
config.RedirectURL = ""
logInfo(fmt.Sprintf("Redirect URL for config ID %d is NULL or empty", id))
}
if respondersJSON != "" {
var responders []ResponderConfig
if err := json.Unmarshal([]byte(respondersJSON), &responders); err != nil {
logError("Failed to unmarshal responders: " + err.Error())
} else {
config.Responders = responders
}
}
logInfo(fmt.Sprintf("Successfully selected config: %s (ID %d)", config.Name, config.ID))
return config, nil
}
func InsertHoneypotConfig(config *HoneypotConfig) error {
respondersJSON, err := json.Marshal(config.Responders)
if err != nil {
logError("Failed to serialize responders: " + err.Error())
return err
}
insertSQL := `INSERT INTO honeypots(name, cve, application, port, template_html_file, detection_endpoint, request_regex, date_created, date_updated, redirect_url, responders, enabled) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
_, err = db.Exec(insertSQL, config.Name, config.CVE, config.Application, config.Port, config.TemplateHTMLFile, config.DetectionEndpoint, config.RequestRegex, config.DateCreated, config.DateUpdated, config.RedirectURL, string(respondersJSON), config.Enabled)
if err != nil {
logError("Failed to insert config: " + err.Error())
return err
}
logInfo("Config inserted successfully")
return nil
}
func UpdateHoneypotConfig(config *HoneypotConfig) error {
respondersJSON, err := json.Marshal(config.Responders)
if err != nil {
logError("Failed to serialize responders: " + err.Error())
return err
}
updateSQL := `UPDATE honeypots SET
name = ?,
cve = ?,
application = ?,
port = ?,
template_html_file = ?,
detection_endpoint = ?,
request_regex = ?,
date_created = ?,
date_updated = ?,
redirect_url = ?,
responders = ?,
enabled = ?
WHERE id = ?`
statement, err := db.Prepare(updateSQL)
if err != nil {
logError("Failed to prepare config update: " + err.Error())
return err
}
_, err = statement.Exec(
config.Name,
config.CVE,
config.Application,
config.Port,
config.TemplateHTMLFile,
config.DetectionEndpoint,
config.RequestRegex,
config.DateCreated,
config.DateUpdated,
config.RedirectURL,
string(respondersJSON),
config.Enabled,
config.ID,
)
if err != nil {
logError("Failed to update config: " + err.Error())
return err
}
logInfo(fmt.Sprintf("Config '%s' updated successfully", config.Name))
return nil
}
func DeleteHoneypotConfig(id int) error {
deleteSQL := `DELETE FROM honeypots WHERE id = ?`
statement, err := db.Prepare(deleteSQL)
if err != nil {
logError("Failed to prepare config deletion: " + err.Error())
return err
}
_, err = statement.Exec(id)
if err != nil {
logError("Failed to delete config: " + err.Error())
return err
}
logInfo(fmt.Sprintf("Config with ID %d deleted successfully", id))
return nil
}
type HoneypotLog struct {
ID int
HoneypotID int
Port int
Datetime string
IPSource string
IPDestination string
LogEvent string
RegexMatch string `json:"regex_match"`
}
func InsertHoneypotLog(log *HoneypotLog) (int64, error) {
insertSQL := `INSERT INTO honeypot_logs(honeypotID, port, datetime, ip_source, ip_destination, log_event, regex_match) VALUES (?, ?, ?, ?, ?, ?, ?)`
result, err := db.Exec(insertSQL, log.HoneypotID, log.Port, log.Datetime, log.IPSource, log.IPDestination, log.LogEvent, log.RegexMatch)
if err != nil {
logError("Failed to insert log: " + err.Error())
return 0, err
}
logID, err := result.LastInsertId()
if err != nil {
logError("Failed to retrieve last insert ID: " + err.Error())
return 0, err
}
logInfo(fmt.Sprintf("Log inserted successfully with ID: %d", logID))
return logID, nil
}
func SelectHoneypotLog(honeypotID int) ([]HoneypotLog, error) {
var logs []HoneypotLog
query := `SELECT id, honeypotID, port, datetime, ip_source, ip_destination, log_event, regex_match FROM honeypot_logs WHERE honeypotID = ?`
rows, err := db.Query(query, honeypotID)
if err != nil {
logError("Failed to query logs: " + err.Error())
return nil, err
}
defer rows.Close()
for rows.Next() {
var log HoneypotLog
if err := rows.Scan(&log.ID, &log.HoneypotID, &log.Port, &log.Datetime, &log.IPSource, &log.IPDestination, &log.LogEvent, &log.RegexMatch); err != nil {
logError("Failed to scan log from database: " + err.Error())
continue
}
logs = append(logs, log)
}
if err = rows.Err(); err != nil {
logError("Error iterating through logs: " + err.Error())
return nil, err
}
logInfo(fmt.Sprintf("Retrieved %d logs successfully", len(logs)))
return logs, nil
}
func UpdateHoneypotLog(log *HoneypotLog) error {
updateSQL := `UPDATE honeypot_logs SET port = ?, datetime = ?, ip_source = ?, ip_destination = ?, log_event = ?, regex_match = ? WHERE id = ?`
statement, err := db.Prepare(updateSQL)
if err != nil {
logError("Failed to prepare log update: " + err.Error())
return err
}
_, err = statement.Exec(log.Port, log.Datetime, log.IPSource, log.IPDestination, log.LogEvent, log.RegexMatch, log.ID)
if err != nil {
logError("Failed to update log: " + err.Error())
return err
}
logInfo(fmt.Sprintf("Log with ID %d updated successfully", log.ID))
return nil
}
func DeleteHoneypotLog(id int) error {
deleteSQL := `DELETE FROM honeypot_logs WHERE id = ?`
statement, err := db.Prepare(deleteSQL)
if err != nil {
logError("Failed to prepare log deletion: " + err.Error())
return err
}
_, err = statement.Exec(id)
if err != nil {
logError("Failed to delete log: " + err.Error())
return err
}
logInfo(fmt.Sprintf("Log with ID %d deleted successfully", id))
return nil
}
func RegisterAPIRoutes(router *gin.Engine) {
logInfo("Registering API routes")
// Honeypot configurations routes
router.GET("/api/configs", listAllHoneypotConfigs)
router.POST("/api/configs", insertHoneypotConfig)
router.GET("/api/configs/:id", selectHoneypotConfig)
router.PUT("/api/configs/:id", updateHoneypotConfig)
router.DELETE("/api/configs/:id", deleteHoneypotConfig)
router.PUT("/api/configs/:id/enable-disable", EnableDisableHoneypot)
// Honeypot logs routes
router.GET("/api/logs", listAllHoneypotLogs)
//router.POST("/api/logs", insertHoneypotLog)
router.GET("/api/logs/:honeypotID", selectHoneypotLogs)
router.PUT("/api/logs/:id", updateHoneypotLog)
router.DELETE("/api/logs/:id", deleteHoneypotLog)
}
func insertHoneypotConfig(c *gin.Context) {
var config HoneypotConfig
if err := c.ShouldBindJSON(&config); err != nil {
logError("Error binding JSON for config insert: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := InsertHoneypotConfig(&config); err != nil {
logError("Error inserting config: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "OK", "message": "Configuration added successfully"})
}
func selectHoneypotConfig(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
logError("Invalid ID for config selection: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
return
}
config, err := SelectHoneypotConfig(id)
if err != nil {
logError("Error selecting config: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
logInfo(fmt.Sprintf("Config selected successfully: %+v", config))
c.JSON(http.StatusOK, config)
}
func updateHoneypotConfig(c *gin.Context) {
var config HoneypotConfig
if err := c.ShouldBindJSON(&config); err != nil {
logError("Error binding JSON for config update: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
logError("Invalid ID for config update: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
return
}
config.ID = id
if err := UpdateHoneypotConfig(&config); err != nil {
logError("Error updating config: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
logInfo(fmt.Sprintf("Config updated successfully: %+v", config))
c.JSON(http.StatusOK, gin.H{"status": "OK"})
}
func deleteHoneypotConfig(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
logError("Invalid ID for config deletion: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
return
}
if err := DeleteHoneypotConfig(id); err != nil {
logError("Error deleting config: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
logInfo(fmt.Sprintf("Config with ID %d deleted successfully", id))
c.JSON(http.StatusOK, gin.H{"status": "OK"})
}
func EnableDisableHoneypot(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
logError("Invalid ID: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
return
}
var requestBody struct {
Enabled bool `json:"enabled"`
}
if err := c.ShouldBindJSON(&requestBody); err != nil {
logError("Error binding JSON: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
_, err = db.Exec("UPDATE honeypots SET enabled = ? WHERE id = ?", requestBody.Enabled, id)
if err != nil {
logError("Failed to update enabled state: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
logInfo(fmt.Sprintf("Honeypot configuration with ID %d enabled/disabled successfully", id))
c.JSON(http.StatusOK, gin.H{"status": "OK", "id": id, "enabled": requestBody.Enabled})
}
// Honeypot Log Handlers
// Enhanced insertHoneypotLog with verbose logging
//func insertHoneypotLog(c *gin.Context) {
// var log HoneypotLog
// if err := c.ShouldBindJSON(&log); err != nil {
// logError("Error binding JSON for log insert: " + err.Error())
// c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
// return
// }
//
// if err := InsertHoneypotLog(&log); err != nil {
// logError("Error inserting log: " + err.Error())
// c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
// return
// }
//
// logInfo(fmt.Sprintf("Log inserted successfully: %+v", log))
// c.JSON(http.StatusOK, gin.H{"status": "OK"})
//}
func selectHoneypotLogs(c *gin.Context) {
honeypotID, err := strconv.Atoi(c.Param("honeypotID"))
if err != nil {
logError("Invalid honeypot ID for log selection: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid honeypot ID"})
return
}
logs, err := SelectHoneypotLog(honeypotID)
if err != nil {
logError("Error selecting logs: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
logInfo(fmt.Sprintf("Logs for honeypot ID %d selected successfully", honeypotID))
c.JSON(http.StatusOK, logs)
}
func updateHoneypotLog(c *gin.Context) {
var log HoneypotLog
if err := c.ShouldBindJSON(&log); err != nil {
logError("Error binding JSON for log update: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
logError("Invalid ID for log update: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
return
}
log.ID = id
if err := UpdateHoneypotLog(&log); err != nil {
logError("Error updating log: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
logInfo(fmt.Sprintf("Log with ID %d updated successfully", id))
c.JSON(http.StatusOK, gin.H{"status": "OK"})
}
func deleteHoneypotLog(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
logError("Invalid ID for log deletion: " + err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
return
}
if err := DeleteHoneypotLog(id); err != nil {
logError("Error deleting log: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
logInfo(fmt.Sprintf("Log with ID %d deleted successfully", id))
c.JSON(http.StatusOK, gin.H{"status": "OK"})
}
func SelectHoneypotLogByID(logID int64) (*HoneypotLog, error) {
var log HoneypotLog
err := db.QueryRow("SELECT id, honeypotID, port, datetime, ip_source, ip_destination, log_event, regex_match FROM honeypot_logs WHERE id = ?", logID).Scan(
&log.ID, &log.HoneypotID, &log.Port, &log.Datetime, &log.IPSource, &log.IPDestination, &log.LogEvent, &log.RegexMatch,
)
if err != nil {
return nil, err
}
return &log, nil
}
func listAllHoneypotLogs(c *gin.Context) {
var logs []HoneypotLog
query := "SELECT id, honeypotID, port, datetime, ip_source, ip_destination, log_event, regex_match FROM honeypot_logs"
rows, err := db.Query(query)
if err != nil {
logError("Failed to query database for logs: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database for logs"})
return
}
defer rows.Close()
for rows.Next() {
var log HoneypotLog
if err := rows.Scan(&log.ID, &log.HoneypotID, &log.Port, &log.Datetime, &log.IPSource, &log.IPDestination, &log.LogEvent, &log.RegexMatch); err != nil {
logError("Failed to scan log from database: " + err.Error())
continue
}
logs = append(logs, log)
}
if err = rows.Err(); err != nil {
logError("Error iterating through logs: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error iterating through logs"})
return
}
logInfo(fmt.Sprintf("Total %d logs listed successfully", len(logs)))
c.JSON(http.StatusOK, logs)
}
func listAllHoneypotConfigs(c *gin.Context) {
var configs []HoneypotConfig
query := "SELECT id, name, cve, application, port, template_html_file, detection_endpoint, request_regex, date_created, date_updated, redirect_url, responders, enabled FROM honeypots"
rows, err := db.Query(query)
if err != nil {
logError("Failed to query database for configs: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query database for configs"})
return
}
defer rows.Close()
for rows.Next() {
var config HoneypotConfig
var respondersJSON string
if err := rows.Scan(&config.ID, &config.Name, &config.CVE, &config.Application, &config.Port, &config.TemplateHTMLFile, &config.DetectionEndpoint, &config.RequestRegex, &config.DateCreated, &config.DateUpdated, &config.RedirectURL, &respondersJSON, &config.Enabled); err != nil {
logError("Failed to scan config from database: " + err.Error())
continue
}
if err := json.Unmarshal([]byte(respondersJSON), &config.Responders); err != nil {
logError(fmt.Sprintf("Error deserializing responders JSON: %s", err.Error()))
continue
}
configs = append(configs, config)
}
if err = rows.Err(); err != nil {
logError("Error iterating through configs: " + err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error iterating through configs"})
return
}
logInfo(fmt.Sprintf("Total %d configs listed successfully", len(configs)))
c.JSON(http.StatusOK, configs)
}