-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
699 lines (600 loc) · 18.3 KB
/
server.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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
package main
import (
"archive/zip"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
type Config struct {
Server struct {
Host string `json:"host"`
Port string `json:"port"`
} `json:"Server"`
Cert struct {
Cert string `json:"cert"`
Certkey string `json:"certkey"`
} `json:"Cert"`
Auth struct {
Apikey string `json:"apikey"`
User string `json:"User"`
CREATEDATE string `json:"CREATEDATE"`
} `json:"Auth"`
MAXSTORAGE int64 `json:"MAX_STORAGE"`
DOWNLOAD_VULNREPOAPP bool `json:"DOWNLOAD_VULNREPOAPP"`
}
type Report struct {
ReportID string `json:"report_id"`
ReportName string `json:"report_name"`
ReportCreatedate int64 `json:"report_createdate"`
ReportLastupdate int64 `json:"report_lastupdate"`
EncryptedData string `json:"encrypted_data"`
}
type ListReports struct {
ReportID string `json:"report_id"`
ReportName string `json:"report_name"`
ReportCreatedate int64 `json:"report_createdate"`
ReportLastupdate int64 `json:"report_lastupdate"`
}
type ReportProfile []struct {
ProfileName string `json:"profile_name"`
ReportCSS string `json:"report_css"`
ReportCustomContent string `json:"report_custom_content"`
Logo string `json:"logo"`
Logow int `json:"logow"`
Logoh int `json:"logoh"`
VideoEmbed bool `json:"video_embed"`
RemoveLastpage bool `json:"remove_lastpage"`
RemoveIssueStatus bool `json:"remove_issueStatus"`
RemoveIssuecvss bool `json:"remove_issuecvss"`
RemoveIssuecve bool `json:"remove_issuecve"`
RemoveResearcher bool `json:"remove_researcher"`
RemoveChangelog bool `json:"remove_changelog"`
RemoveTags bool `json:"remove_tags"`
ReportParsingDesc bool `json:"report_parsing_desc"`
ReportParsingPocMarkdown bool `json:"report_parsing_poc_markdown"`
ReportRemoveAttachName bool `json:"report_remove_attach_name"`
ResName string `json:"ResName"`
ResEmail string `json:"ResEmail"`
ResSocial string `json:"ResSocial"`
ResWeb string `json:"ResWeb"`
}
type ReportTemplate []struct {
Title string `json:"title"`
Poc string `json:"poc"`
Desc string `json:"desc"`
Severity string `json:"severity"`
Ref string `json:"ref"`
Cvss string `json:"cvss"`
CvssVector string `json:"cvss_vector"`
Cve string `json:"cve"`
Tags []any `json:"tags"`
}
func main() {
ex, err2 := os.Executable()
if err2 != nil {
panic(err2)
}
exPath := filepath.Dir(ex) + "/"
file, _ := os.Open(exPath + "conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
configuration := Config{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
if configuration.Auth.Apikey == "" {
log.Fatal("Empty api key, check conf.json!!!")
}
mux := http.NewServeMux()
if configuration.DOWNLOAD_VULNREPOAPP {
downloadFile(exPath+"vulnrepo-app-master.zip", "https://github.com/kac89/vulnrepo-build-prod/archive/refs/heads/master.zip")
Unzip(exPath+"vulnrepo-app-master.zip", exPath+"vulnrepo-app/")
// Removing file from the directory
// Using Remove() function
e := os.Remove(exPath + "vulnrepo-app-master.zip")
if e != nil {
log.Fatal(e)
}
fileServer := http.FileServer(http.Dir("./vulnrepo-app/vulnrepo-build-prod-master/"))
mux.Handle("/", http.StripPrefix("/", fileServer))
mux.Handle("/home/", http.StripPrefix("/home", fileServer))
mux.Handle("/my-reports/", http.StripPrefix("/my-reports", fileServer))
mux.Handle("/report/", http.StripPrefix("/report", fileServer))
mux.Handle("/faq/", http.StripPrefix("/faq", fileServer))
mux.Handle("/settings/", http.StripPrefix("/settings", fileServer))
mux.Handle("/vuln-list/", http.StripPrefix("/vuln-list", fileServer))
mux.Handle("/import-report/", http.StripPrefix("/import-report", fileServer))
mux.Handle("/new-report/", http.StripPrefix("/new-report", fileServer))
//mux.Handle("/assets/", http.StripPrefix("/assets", fileServer))
}
mux.HandleFunc("/api/", sayHello)
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
}
srv := &http.Server{
Addr: configuration.Server.Host + ":" + configuration.Server.Port,
Handler: mux,
TLSConfig: cfg,
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
}
fmt.Println("-=[***************************************************************]=-")
fmt.Println("[*] SERVER START: if no errors at this point, should works fine :-)")
if configuration.DOWNLOAD_VULNREPOAPP {
fmt.Println("[*] VULNREPO APP: https://" + configuration.Server.Host + ":" + configuration.Server.Port)
}
fmt.Println("-=[***************************************************************]=-")
fmt.Println("")
fmt.Println("")
log.Fatal(srv.ListenAndServeTLS(configuration.Cert.Cert, configuration.Cert.Certkey))
}
func downloadFile(filepath string, url string) (err error) {
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func Unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer func() {
if err := r.Close(); err != nil {
panic(err)
}
}()
os.MkdirAll(dest, 0755)
// Closure to address file descriptors issue with all the deferred .Close() methods
extractAndWriteFile := func(f *zip.File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer func() {
if err := rc.Close(); err != nil {
panic(err)
}
}()
path := filepath.Join(dest, f.Name)
// Check for ZipSlip (Directory traversal)
if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) {
return fmt.Errorf("illegal file path: %s", path)
}
if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
} else {
os.MkdirAll(filepath.Dir(path), f.Mode())
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
return nil
}
for _, f := range r.File {
err := extractAndWriteFile(f)
if err != nil {
return err
}
}
return nil
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func DirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
func logevent(event string) {
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
if _, err := f.Write([]byte(event)); err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
func logme(event string) {
currentTime := time.Now()
logevent(currentTime.Format("2006/01/02 15:04:05") + event + "\n")
fmt.Println(currentTime.Format("2006/01/02 15:04:05") + event)
}
func IsValidUUID(uuid string) bool {
r := regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$")
return r.MatchString(uuid)
}
func sayHello(w http.ResponseWriter, r *http.Request) {
ip := r.RemoteAddr
xforward := r.Header.Get("X-Forwarded-For")
logme(" | Connection from " + ip)
if xforward != "" {
fmt.Println("X-Forwarded-For : ", xforward)
}
file, _ := os.Open("conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
configuration := Config{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "vulnrepo-auth, vulnrepo-action")
w.Header().Set("Content-Type", "application/json")
if r.URL.Path != "/api/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
myAuth := r.Header.Get("Vulnrepo-Auth")
if configuration.Auth.Apikey == myAuth {
Action := r.Header.Get("Vulnrepo-Action")
switch Action {
case "apiconnect":
w.WriteHeader(http.StatusOK)
//storage size
dirsize, _ := DirSize("./reports")
fmt.Fprintf(w, `{"AUTH": "OK", "WELCOME": "`+configuration.Auth.User+`", "CREATEDATE": "`+configuration.Auth.CREATEDATE+`", "EXPIRYDATE": "0", "CURRENT_STORAGE": "`+fmt.Sprint(dirsize)+`", "MAX_STORAGE": "`+fmt.Sprint(configuration.MAXSTORAGE)+`"}`)
logme(" | apiconnect from: " + ip)
case "getreportslist":
files, err := os.ReadDir("./reports/")
if err != nil {
log.Fatal(err)
}
reports := []ListReports{}
for _, f := range files {
if strings.Contains(f.Name(), ".vulnr") {
dat, err := os.ReadFile("./reports/" + f.Name())
if err != nil {
log.Fatal(err)
}
if dat != nil {
payload, err := url.QueryUnescape(string(dat))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(string(payload))
if err != nil {
log.Fatal("error:", err)
}
var reportsin ListReports
json.Unmarshal([]byte(data), &reportsin)
reports = append(reports, reportsin)
}
}
}
w.WriteHeader(http.StatusOK)
encjson, _ := json.Marshal(reports)
fmt.Fprint(w, string(encjson))
logme(" | getreportslist from: " + ip)
case "getreport":
reportid := r.FormValue("reportid")
files, err := os.ReadDir("./reports/")
if err != nil {
log.Fatal(err)
}
reports := []Report{}
for _, f := range files {
dat, err := os.ReadFile("./reports/" + f.Name())
if err != nil {
log.Fatal(err)
}
if dat != nil {
str, err := url.QueryUnescape(string(dat))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(string(str))
if err != nil {
log.Fatal("error:", err)
}
var report Report
json.Unmarshal([]byte(data), &report)
if reportid == report.ReportID {
reports = append(reports, report)
}
}
}
w.WriteHeader(http.StatusOK)
encjson, _ := json.Marshal(reports)
fmt.Fprint(w, string(encjson))
logme(" | getreport from: " + ip)
case "removereport":
reportid := r.FormValue("reportid")
files, err := os.ReadDir("./reports/")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
dat, err := os.ReadFile("./reports/" + f.Name())
if err != nil {
log.Fatal(err)
}
if dat != nil {
payload, err := url.QueryUnescape(string(dat))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(string(payload))
if err != nil {
log.Fatal("error:", err)
}
var report Report
json.Unmarshal([]byte(data), &report)
if reportid == report.ReportID {
e := os.Remove("./reports/" + f.Name())
if e != nil {
log.Fatal(e)
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"REMOVE_REPORT": "OK"}`)
}
}
}
logme(" | removereport from: " + ip)
case "savereport":
reportdata := r.FormValue("reportdata")
isdir, _ := exists("./reports/")
files, err := os.ReadDir("./reports/")
if err != nil {
log.Fatal(err)
}
if isdir {
//storage size
dirsize, err01 := DirSize("./reports")
if err01 != nil {
log.Fatal(err01)
}
if dirsize > configuration.MAXSTORAGE {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"STORAGE": "NOSPACE"}`)
break
}
payload, err := url.QueryUnescape(string(reportdata))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(payload)
if err != nil {
log.Fatal("error payload base64:", err)
}
var payload_report Report
json.Unmarshal([]byte(data), &payload_report)
reportid := payload_report.ReportID
if reportid != "" && IsValidUUID(reportid) {
if len(files) > 0 {
for _, f := range files {
dat, err := os.ReadFile("./reports/" + f.Name())
if err != nil {
log.Fatal(err)
}
plang, err := url.QueryUnescape(string(dat))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(plang)
if err != nil {
log.Fatal("error base64:", err)
}
var report Report
json.Unmarshal([]byte(data), &report)
if reportid != report.ReportID {
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("./reports/"+reportid+".vulnr", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
_, err = f.Write([]byte(url.QueryEscape(string(reportdata))))
if err != nil {
log.Fatal(err)
}
f.Close()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"REPORT_SAVED": "OK"}`)
break
}
}
} else {
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("./reports/"+reportid+".vulnr", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
_, err = f.Write([]byte(url.QueryEscape(string(reportdata))))
if err != nil {
log.Fatal(err)
}
f.Close()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"REPORT_SAVED": "OK"}`)
break
}
}
}
logme(" | savereport from: " + ip)
case "updatereport":
reportdata := r.FormValue("reportdata")
isdir, _ := exists("./reports/")
files, err := os.ReadDir("./reports/")
if err != nil {
log.Fatal(err)
}
if isdir {
//storage size
dirsize, err23 := DirSize("./reports")
if err23 != nil {
log.Fatal(err23)
}
if dirsize > configuration.MAXSTORAGE {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"STORAGE": "NOSPACE"}`)
break
}
payload, err := url.QueryUnescape(string(reportdata))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(payload)
if err != nil {
log.Fatal("error payload base64:", err)
}
var payload_report Report
json.Unmarshal([]byte(data), &payload_report)
reportid := payload_report.ReportID
if reportid != "" && IsValidUUID(reportid) {
if len(files) > 0 {
for _, f := range files {
dat, err := os.ReadFile("./reports/" + f.Name())
if err != nil {
log.Fatal(err)
}
plang, err := url.QueryUnescape(string(dat))
if err != nil {
panic(err)
}
data, err := base64.StdEncoding.DecodeString(plang)
if err != nil {
log.Fatal("error base64:", err)
}
var report Report
json.Unmarshal([]byte(data), &report)
if reportid == report.ReportID {
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("./reports/"+f.Name(), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
log.Fatal(err)
}
_, err = f.Write([]byte(url.QueryEscape(string(reportdata))))
if err != nil {
log.Fatal(err)
}
f.Close()
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"REPORT_UPDATE": "OK"}`)
break
}
}
}
}
}
logme(" | updatereport from: " + ip)
case "getreportprofiles":
files, err := os.ReadDir("./profiles/")
if err != nil {
log.Fatal(err)
}
reportprofiles := ReportProfile{}
for _, f := range files {
if strings.Contains(f.Name(), ".vulnrepo-profiles") {
dat, err := os.ReadFile("./profiles/" + f.Name())
if err != nil {
log.Fatal(err)
}
if dat != nil {
data := string(dat)
var profile ReportProfile
json.Unmarshal([]byte(data), &profile)
reportprofiles = append(reportprofiles, profile...)
}
}
}
w.WriteHeader(http.StatusOK)
encjson, _ := json.Marshal(reportprofiles)
fmt.Fprint(w, string(encjson))
logme(" | getreportprofiles from: " + ip)
case "getreporttemplates":
files, err := os.ReadDir("./templates/")
if err != nil {
log.Fatal(err)
}
reporttemplates := ReportTemplate{}
for _, f := range files {
if strings.Contains(f.Name(), ".vulnrepo-templates") {
dat, err := os.ReadFile("./templates/" + f.Name())
if err != nil {
log.Fatal(err)
}
if dat != nil {
data := string(dat)
var template ReportTemplate
json.Unmarshal([]byte(data), &template)
reporttemplates = append(reporttemplates, template...)
}
}
}
w.WriteHeader(http.StatusOK)
encjson, _ := json.Marshal(reporttemplates)
fmt.Fprint(w, string(encjson))
logme(" | getreporttemplates from: " + ip)
default:
fmt.Fprintf(w, "Sorry, missing action")
}
}
}