-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
2613 lines (2247 loc) · 74.5 KB
/
main.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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"go/types"
"os"
"path"
"strings"
"sync"
"time"
. "github.com/dave/jennifer/jen"
"github.com/gagliardetto/codebox/gogentools"
"github.com/gagliardetto/codebox/scanner"
"github.com/gagliardetto/feparser"
. "github.com/gagliardetto/utilz"
"github.com/gin-gonic/gin"
)
type CacheType map[string]*feparser.CodeQlFinalVals
var (
mu = &sync.RWMutex{}
)
var (
IncludeCommentsInGeneratedGo bool
InlineGeneratedGo bool
)
func main() {
var pkg string
var runServer bool
var cacheDir string
var generatedDir string
var toStdout bool
var includeBoilerplace bool
var compressCodeQl bool
flag.StringVar(&pkg, "pkg", "", "Package you want to scan (can be either in example.com/hello/world format, or example.com/hello/world@v1.0.1 format)")
flag.StringVar(&cacheDir, "cache-dir", "./cache", "Folder that contains cache of taint-tracking pointers")
flag.StringVar(&generatedDir, "out-dir", "./generated", "Folder that contains the generated assets (each run has its own timestamped folder)")
flag.BoolVar(&runServer, "http", false, "Run http server")
flag.BoolVar(&toStdout, "stdout", false, "Print generated to stdout")
flag.BoolVar(&includeBoilerplace, "stub", true, "Include utility functions (main, sink, link, etc.) in the go test files")
flag.BoolVar(&compressCodeQl, "compress", true, "Compress codeql classes")
flag.BoolVar(&IncludeCommentsInGeneratedGo, "comments", false, "Include comments inside go test code")
flag.BoolVar(&InlineGeneratedGo, "inline", false, "Inline tests in generated go code")
flag.Parse()
// Initialize module scanner:
sc, err := scanner.New(pkg)
if err != nil {
panic(err)
}
pks, err := sc.Scan()
if err != nil {
panic(err)
}
pk := pks[0]
// compose the fePackage:
Infof("Composing fePackage %q", pk.Path)
fePackage, err := feparser.Load(pk)
if err != nil {
panic(err)
}
{ // Create folders:
// folder for all cache:
MustCreateFolderIfNotExists(cacheDir, 0750)
// folder for all folders for assets:
MustCreateFolderIfNotExists(generatedDir, 0750)
}
cacheFilepath := path.Join(cacheDir, feparser.FormatCodeQlName(scanner.RemoveGoSrcClonePath(pk.Path))+".v2.json")
cacheExists := MustFileExists(cacheFilepath)
{ // Load pointer blocks from cache:
// try to use DEPRECATED cache:
deprecatedCacheFilepath := path.Join(cacheDir, feparser.FormatCodeQlName(scanner.RemoveGoSrcClonePath(pk.Path))+".json")
deprecatedCacheExists := MustFileExists(deprecatedCacheFilepath)
canLoadFromDeprecatedCache := !cacheExists && deprecatedCacheExists
if canLoadFromDeprecatedCache {
tempDeprecatedFeModule := &feparser.DEPRECATEDFEModule{}
// Load cache:
Infof("Loading cached fePackage from %q", deprecatedCacheFilepath)
err := LoadJSON(tempDeprecatedFeModule, deprecatedCacheFilepath)
if err != nil {
panic(err)
}
findLatestFunc := func(signature string) *feparser.FEFunc {
for _, latest := range fePackage.Funcs {
if latest.Signature == signature {
return latest
}
}
return nil
}
findLatestTypeMethod := func(signature string) *feparser.FETypeMethod {
for _, latest := range fePackage.TypeMethods {
if latest.Func.Signature == signature {
return latest
}
}
return nil
}
findLatestInterfaceMethod := func(signature string) *feparser.FEInterfaceMethod {
for _, latest := range fePackage.InterfaceMethods {
if latest.Func.Signature == signature {
return latest
}
}
return nil
}
doCopy := true
for _, cached := range tempDeprecatedFeModule.Funcs {
latest := findLatestFunc(cached.Signature)
if latest == nil {
Errorf("latest FEFunc not found for signature %q", cached.Signature)
} else {
// Copy CodeQL object:
latest.CodeQL.IsEnabled = cached.CodeQL.IsEnabled
if doCopy {
{
// Initialize block:
width := len(latest.Parameters) + len(latest.Results)
latest.CodeQL.Blocks = make([]*feparser.FlowBlock, 0)
latest.CodeQL.Blocks = append(
latest.CodeQL.Blocks,
&feparser.FlowBlock{
Inp: make([]bool, width),
Outp: make([]bool, width),
},
)
// Copy legacy pointers into first block:
{
inp := cached.CodeQL.Pointers.Inp
switch inp.Element {
case feparser.ElementParameter:
latest.CodeQL.Blocks[0].Inp[inp.Index] = true
case feparser.ElementResult:
latest.CodeQL.Blocks[0].Inp[inp.Index+len(latest.Parameters)] = true
}
}
{
outp := cached.CodeQL.Pointers.Outp
switch outp.Element {
case feparser.ElementParameter:
latest.CodeQL.Blocks[0].Outp[outp.Index] = true
case feparser.ElementResult:
latest.CodeQL.Blocks[0].Outp[outp.Index+len(latest.Parameters)] = true
}
}
}
}
}
}
for _, cached := range tempDeprecatedFeModule.TypeMethods {
latest := findLatestTypeMethod(cached.Func.Signature)
if latest == nil {
Errorf("latest FETypeMethod not found for signature %q", cached.Func.Signature)
} else {
// Copy CodeQL object:
latest.CodeQL.IsEnabled = cached.CodeQL.IsEnabled
if doCopy {
{
// Initialize block:
width := 1 + len(latest.Func.Parameters) + len(latest.Func.Results)
latest.CodeQL.Blocks = make([]*feparser.FlowBlock, 0)
latest.CodeQL.Blocks = append(
latest.CodeQL.Blocks,
&feparser.FlowBlock{
Inp: make([]bool, width),
Outp: make([]bool, width),
},
)
// Copy legacy pointers into first block:
{
inp := cached.CodeQL.Pointers.Inp
switch inp.Element {
case feparser.ElementReceiver:
latest.CodeQL.Blocks[0].Inp[0] = true
case feparser.ElementParameter:
latest.CodeQL.Blocks[0].Inp[inp.Index+1] = true
case feparser.ElementResult:
latest.CodeQL.Blocks[0].Inp[inp.Index+len(latest.Func.Parameters)+1] = true
}
}
{
outp := cached.CodeQL.Pointers.Outp
switch outp.Element {
case feparser.ElementReceiver:
latest.CodeQL.Blocks[0].Outp[0] = true
case feparser.ElementParameter:
latest.CodeQL.Blocks[0].Outp[outp.Index+1] = true
case feparser.ElementResult:
latest.CodeQL.Blocks[0].Outp[outp.Index+len(latest.Func.Parameters)+1] = true
}
}
}
}
}
}
for _, cached := range tempDeprecatedFeModule.InterfaceMethods {
latest := findLatestInterfaceMethod(cached.Func.Signature)
if latest == nil {
Errorf("latest FEInterfaceMethod not found for signature %q", cached.Func.Signature)
} else {
// Copy CodeQL object:
latest.CodeQL.IsEnabled = cached.CodeQL.IsEnabled
if doCopy {
{
// Initialize block:
width := 1 + len(latest.Func.Parameters) + len(latest.Func.Results)
latest.CodeQL.Blocks = make([]*feparser.FlowBlock, 0)
latest.CodeQL.Blocks = append(
latest.CodeQL.Blocks,
&feparser.FlowBlock{
Inp: make([]bool, width),
Outp: make([]bool, width),
},
)
// Copy legacy pointers into first block:
{
inp := cached.CodeQL.Pointers.Inp
switch inp.Element {
case feparser.ElementReceiver:
latest.CodeQL.Blocks[0].Inp[0] = true
case feparser.ElementParameter:
latest.CodeQL.Blocks[0].Inp[inp.Index+1] = true
case feparser.ElementResult:
latest.CodeQL.Blocks[0].Inp[inp.Index+len(latest.Func.Parameters)+1] = true
}
}
{
outp := cached.CodeQL.Pointers.Outp
switch outp.Element {
case feparser.ElementReceiver:
latest.CodeQL.Blocks[0].Outp[0] = true
case feparser.ElementParameter:
latest.CodeQL.Blocks[0].Outp[outp.Index+1] = true
case feparser.ElementResult:
latest.CodeQL.Blocks[0].Outp[outp.Index+len(latest.Func.Parameters)+1] = true
}
}
}
}
}
}
}
}
{
// try to use v2 cache:
if cacheExists {
cachedMap := make(CacheType)
// Load cache:
Infof("Loading cached fePackage from %q", cacheFilepath)
err := LoadJSON(&cachedMap, cacheFilepath)
if err != nil {
panic(err)
}
findCached := func(signature string) *feparser.CodeQlFinalVals {
for cacheSignature, cached := range cachedMap {
if cacheSignature == signature {
return cached
}
}
return nil
}
// Load from cache:
for _, latest := range fePackage.Funcs {
cached := findCached(latest.Signature)
if cached == nil {
Warnf("cached not found for signature %q", latest.Signature)
} else {
// Copy CodeQL object:
latest.CodeQL = cached
}
}
for _, latest := range fePackage.TypeMethods {
cached := findCached(latest.Func.Signature)
if cached == nil {
Warnf("cached not found for signature %q", latest.Func.Signature)
} else {
// Copy CodeQL object:
latest.CodeQL = cached
}
}
for _, latest := range fePackage.InterfaceMethods {
cached := findCached(latest.Func.Signature)
if cached == nil {
Warnf("cached not found for signature %q", latest.Func.Signature)
} else {
// Copy CodeQL object:
latest.CodeQL = cached
}
}
}
}
lenFuncs := len(fePackage.Funcs)
lenTypeMethods := len(fePackage.TypeMethods)
lenInterfaceMethods := len(fePackage.InterfaceMethods)
lenTotal := lenFuncs + lenTypeMethods + lenInterfaceMethods
Sfln(
IndigoBG("Package %q has %v funcs, %v methods on types, and %v methods on interfaces (total=%v)"),
pk.Name,
lenFuncs,
lenTypeMethods,
lenInterfaceMethods,
lenTotal,
)
// Create index, and load values to it:
index := NewIndex()
{
for _, v := range fePackage.Funcs {
index.MustSetUnique(v.Signature, v)
}
for _, v := range fePackage.TypeMethods {
index.MustSetUnique(v.Func.Signature, v)
}
for _, v := range fePackage.InterfaceMethods {
index.MustSetUnique(v.Func.Signature, v)
}
}
// Callback executed when this program is closed:
onExitCallback := func() {
mu.Lock()
defer mu.Unlock()
PopulateGeneratedClassCodeQL(fePackage)
{
// Save cache:
cacheFilepath := path.Join(cacheDir, feparser.FormatCodeQlName(fePackage.PkgPath)+".v2.json")
cacheMap := make(CacheType)
{
for _, v := range fePackage.Funcs {
cacheMap[v.Signature] = v.CodeQL
}
for _, v := range fePackage.TypeMethods {
cacheMap[v.Func.Signature] = v.CodeQL
}
for _, v := range fePackage.InterfaceMethods {
cacheMap[v.Func.Signature] = v.CodeQL
}
// Remove generated stuff:
for _, v := range cacheMap {
v.GeneratedClass = ""
v.GeneratedConditions = ""
}
}
Infof("Saving cache to %q", MustAbs(cacheFilepath))
err := SaveAsIndentedJSON(cacheMap, cacheFilepath)
if err != nil {
panic(err)
}
}
// Generate golang tests code:
goTestFile := NewTestFile(includeBoilerplace)
testFuncNames := make([]string, 0)
{
for _, fe := range fePackage.Funcs {
if !fe.CodeQL.IsEnabled {
continue
}
if err := fe.CodeQL.Validate(); err != nil {
Errorf("invalid pointers for %q: %s", fe.Signature, err)
continue
}
allCode := generateGoTestBlock_Func(
goTestFile,
fe,
)
for _, codeEnvelope := range allCode {
if codeEnvelope.Statement != nil {
goTestFile.Add(codeEnvelope.Statement.Line())
testFuncNames = append(testFuncNames, codeEnvelope.TestFuncName)
} else {
Warnf("NOTHING GENERATED")
}
}
}
}
{
for _, fe := range fePackage.TypeMethods {
if !fe.CodeQL.IsEnabled {
continue
}
if err := fe.CodeQL.Validate(); err != nil {
Errorf("invalid pointers for %q: %s", fe.Func.Signature, err)
continue
}
allCode := generateGoTestBlock_Method(
goTestFile,
fe,
)
for _, codeEnvelope := range allCode {
if codeEnvelope.Statement != nil {
goTestFile.Add(codeEnvelope.Statement.Line())
testFuncNames = append(testFuncNames, codeEnvelope.TestFuncName)
} else {
Warnf("NOTHING GENERATED")
}
}
}
}
{
for _, fe := range fePackage.InterfaceMethods {
if !fe.CodeQL.IsEnabled {
continue
}
if err := fe.CodeQL.Validate(); err != nil {
Errorf("invalid pointers for %q: %s", fe.Func.Signature, err)
continue
}
converted := feparser.FEIToFET(fe)
allCode := generateGoTestBlock_Method(
goTestFile,
converted,
)
for _, codeEnvelope := range allCode {
if codeEnvelope.Statement != nil {
goTestFile.Add(codeEnvelope.Statement.Line())
testFuncNames = append(testFuncNames, codeEnvelope.TestFuncName)
} else {
Warnf("NOTHING GENERATED")
}
}
}
}
{
code := Func().
Id("RunAllTaints_" + feparser.FormatCodeQlName(fePackage.PkgPath)).
Params().
BlockFunc(func(group *Group) {
for testID, testFuncName := range testFuncNames {
group.BlockFunc(func(testBlock *Group) {
Comments(testBlock, "Create a new source:")
testBlock.Id("source").Op(":=").Id("newSource").Call(Lit(testID))
Comments(testBlock, "Run the taint scenario:")
testBlock.Id("out").Op(":=").Id(testFuncName).Call(Id("source"))
Comments(testBlock, "If the taint step(s) succeeded, then `out` is tainted and will be sink-able here:")
testBlock.Id("sink").Call(Lit(testID), Id("out"))
})
}
})
goTestFile.Add(code.Line())
}
if toStdout {
fmt.Printf("%#v", goTestFile)
}
ts := time.Now()
// Create subfolder for package for generated assets:
packageAssetFolderName := feparser.FormatCodeQlName(fePackage.PkgPath)
packageAssetFolderPath := path.Join(generatedDir, packageAssetFolderName)
MustCreateFolderIfNotExists(packageAssetFolderPath, 0750)
// Create folder for assets generated during this run:
thisRunAssetFolderName := feparser.FormatCodeQlName(fePackage.PkgPath) + "_" + ts.Format(FilenameTimeFormat)
thisRunAssetFolderPath := path.Join(packageAssetFolderPath, thisRunAssetFolderName)
// Create a new assets folder inside the main assets folder:
MustCreateFolderIfNotExists(thisRunAssetFolderPath, 0750)
{
// Save golang assets:
assetFileName := feparser.FormatCodeQlName(fePackage.PkgPath) + ".go"
assetFilepath := path.Join(thisRunAssetFolderPath, assetFileName)
// Create file go test file:
goFile, err := os.Create(assetFilepath)
if err != nil {
panic(err)
}
defer goFile.Close()
// write generated Golang code to file:
Infof("Saving golang assets to %q", MustAbs(assetFilepath))
err = goTestFile.Render(goFile)
if err != nil {
panic(err)
}
}
{
// Save the go.mod file that was used to fetch the desired version of the package:
if srcGoModFilepath := scanner.GetTempGoModFilepath(pkg); srcGoModFilepath != "" {
dstGoModFilepath := path.Join(thisRunAssetFolderPath, "go.mod")
Infof("Saving saving go.mod to %q", MustAbs(dstGoModFilepath))
MustCopyFile(srcGoModFilepath, dstGoModFilepath)
}
}
{
// Generate codeQL tain-tracking classes and qll file:
var buf bytes.Buffer
fileHeader := `/**
* Provides classes modeling security-relevant aspects of the ` + "`" + fePackage.PkgPath + "`" + ` package.
*/
import go` + "\n\n"
moduleHeader := Sf(
"/** Provides models of commonly used functions in the `%s` package. */\nmodule %s {",
fePackage.PkgPath,
feparser.FormatCodeQlName(fePackage.PkgPath),
)
buf.WriteString(fileHeader + moduleHeader)
if compressCodeQl {
err := CompressedGenerateCodeQLTT_All(&buf, fePackage)
if err != nil {
panic(err)
}
} else {
err := GenerateCodeQLTT_Functions(&buf, fePackage.Funcs)
if err != nil {
panic(err)
}
err = GenerateCodeQLTT_TypeMethods(&buf, fePackage.TypeMethods)
if err != nil {
panic(err)
}
err = GenerateCodeQLTT_InterfaceMethods(&buf, fePackage.InterfaceMethods)
if err != nil {
panic(err)
}
}
buf.WriteString("\n}")
if toStdout {
fmt.Println(buf.String())
}
// Save codeql assets:
assetFileName := feparser.FormatCodeQlName(fePackage.PkgPath) + ".qll"
assetFilepath := path.Join(thisRunAssetFolderPath, assetFileName)
// Create file qll file:
qllFile, err := os.Create(assetFilepath)
if err != nil {
panic(err)
}
defer qllFile.Close()
// write generated codeql code to file:
Infof("Saving codeql assets to %q", MustAbs(assetFilepath))
_, err = buf.WriteTo(qllFile)
if err != nil {
panic(err)
}
}
os.Exit(0)
}
var once sync.Once
go Notify(
func(os.Signal) bool {
once.Do(onExitCallback)
return false
},
os.Kill,
os.Interrupt,
)
defer once.Do(onExitCallback)
if runServer {
r := gin.Default()
r.StaticFile("", "./index.html")
r.Static("/static", "./static")
r.GET("/api/source", func(c *gin.Context) {
mu.Lock()
defer mu.Unlock()
PopulateGeneratedClassCodeQL(fePackage)
c.IndentedJSON(200, fePackage)
})
r.POST("/api/disable", func(c *gin.Context) {
var req PayloadDisable
err := c.BindJSON(&req)
if err != nil {
Errorf("error binding JSON: %s", err)
c.Status(400)
return
}
Q(req)
if req.Signature == "" {
Errorf("req.Signature not set")
c.Status(400)
return
}
mu.Lock()
defer mu.Unlock()
stored := index.GetBySignature(req.Signature)
if stored == nil {
Errorf("not found: %q", req.Signature)
c.Status(404)
return
}
if req.Enabled {
Infof("enabling %q", req.Signature)
} else {
Infof("disabling %q", req.Signature)
}
switch stored.GetOriginal().(type) {
case *feparser.FEFunc:
{
fe := stored.GetFEFunc()
if req.Enabled {
// partially validate before enabling:
if err := fe.CodeQL.Validate(); err == nil {
fe.CodeQL.IsEnabled = true
}
} else {
fe.CodeQL.IsEnabled = false
}
}
case *feparser.FETypeMethod, *feparser.FEInterfaceMethod:
{
fe := stored.GetFETypeMethodOrInterfaceMethod()
if req.Enabled {
// partially validate before enabling:
if err := fe.CodeQL.Validate(); err == nil {
fe.CodeQL.IsEnabled = true
}
} else {
fe.CodeQL.IsEnabled = false
}
}
}
})
r.POST("/api/pointers", func(c *gin.Context) {
var req PayloadSetPointers
err := c.BindJSON(&req)
if err != nil {
Errorf("error binding JSON: %s", err)
c.Status(400)
return
}
Q(req)
if err := req.Validate(); err != nil {
Errorf("invalid request for %q: %s", req.Signature, err)
c.Status(400)
return
}
mu.Lock()
defer mu.Unlock()
stored := index.GetBySignature(req.Signature)
if stored == nil {
Errorf("not found: %q", req.Signature)
c.Status(404)
return
}
switch stored.GetOriginal().(type) {
case *feparser.FEFunc:
{
fe := stored.GetFEFunc()
{
if err := validateBlockLen_FEFunc(fe, req.Blocks...); err != nil {
Errorf(
"error validating block: %s", err,
)
c.Status(400)
return
}
}
fe.CodeQL.Blocks = req.Blocks
fe.CodeQL.IsEnabled = true
{
generatedCodeql := new(bytes.Buffer)
err := GenerateCodeQLTT_Functions(generatedCodeql, []*feparser.FEFunc{fe})
if err != nil {
Errorf("error generating codeql: %s", err)
c.Status(400)
return
}
Ln(generatedCodeql)
{
c.IndentedJSON(
200,
GeneratedClassResponse{
GeneratedClass: generatedCodeql.String(),
},
)
return
}
}
}
case *feparser.FETypeMethod, *feparser.FEInterfaceMethod:
{
fe := stored.GetFETypeMethodOrInterfaceMethod()
{
if err := validateBlockLen_FEMethod(fe, req.Blocks...); err != nil {
Errorf(
"error validating block: %s", err,
)
c.Status(400)
return
}
}
fe.CodeQL.Blocks = req.Blocks
fe.CodeQL.IsEnabled = true
{
generatedCodeql := new(bytes.Buffer)
st := stored.GetFETypeMethod()
if st != nil {
err := GenerateCodeQLTT_TypeMethods(generatedCodeql, []*feparser.FETypeMethod{st})
if err != nil {
Errorf("error generating codeql: %s", err)
c.Status(400)
return
}
} else {
st := stored.GetFEInterfaceMethod()
err := GenerateCodeQLTT_InterfaceMethods(generatedCodeql, []*feparser.FEInterfaceMethod{st})
if err != nil {
Errorf("error generating codeql: %s", err)
c.Status(400)
return
}
}
Ln(generatedCodeql)
{
c.IndentedJSON(
200,
GeneratedClassResponse{
GeneratedClass: generatedCodeql.String(),
},
)
return
}
}
}
default:
panic(Sf("unknown type for %v", stored.original))
}
})
r.Run() // listen and serve on 0.0.0.0:8080
}
}
type IndexItem struct {
original interface{}
}
func (item *IndexItem) GetOriginal() interface{} {
return item.original
}
//
func NewIndexItem(v interface{}) *IndexItem {
item := &IndexItem{}
item.SetOriginal(v)
return item
}
//
func (item *IndexItem) SetOriginal(v interface{}) {
item.original = v
}
//
func (item *IndexItem) IsNil() bool {
return item.original == nil
}
//
func (item *IndexItem) GetFEFunc() *feparser.FEFunc {
fe, ok := item.GetOriginal().(*feparser.FEFunc)
if !ok {
return nil
}
return fe
}
//
func (item *IndexItem) GetFETypeMethod() *feparser.FETypeMethod {
fe, ok := item.GetOriginal().(*feparser.FETypeMethod)
if !ok {
return nil
}
return fe
}
func (item *IndexItem) GetFETypeMethodOrInterfaceMethod() *feparser.FETypeMethod {
feTyp, ok := item.GetOriginal().(*feparser.FETypeMethod)
if !ok {
feIt, ok := item.GetOriginal().(*feparser.FEInterfaceMethod)
if !ok {
return nil
}
return feparser.FEIToFET(feIt)
}
return feTyp
}
//
func (item *IndexItem) GetFEInterfaceMethod() *feparser.FEInterfaceMethod {
fe, ok := item.GetOriginal().(*feparser.FEInterfaceMethod)
if !ok {
return nil
}
return fe
}
type Storage struct {
mu *sync.RWMutex
values map[string]*IndexItem
}
func NewIndex() *Storage {
return &Storage{
mu: &sync.RWMutex{},
values: make(map[string]*IndexItem),
}
}
func (index *Storage) GetBySignature(signature string) *IndexItem {
index.mu.RLock()
defer index.mu.RUnlock()
val, ok := index.values[signature]
if !ok {
return nil
}
return val
}
func (index *Storage) Set(signature string, v interface{}) {
index.mu.Lock()
defer index.mu.Unlock()
index.values[signature] = NewIndexItem(v)
}
func (index *Storage) MustSetUnique(signature string, v interface{}) {
existing := index.GetBySignature(signature)
if existing != nil {
Errorf(Sf("%q already in the index", signature))
} else {
index.Set(signature, v)
}
}
type GeneratedClassResponse struct {
GeneratedClass string
}
func PopulateGeneratedClassCodeQL(fePackage *feparser.FEPackage) error {
for i := range fePackage.Funcs {
fe := fePackage.Funcs[i]
if err := fe.CodeQL.Validate(); err == nil {
generatedCodeqlClass := new(bytes.Buffer)
err := GenerateCodeQLTT_Functions(generatedCodeqlClass, []*feparser.FEFunc{fe})
if err != nil {
return fmt.Errorf("error generating codeql conditions for %q: %s", fe.Signature, err)
}
fe.CodeQL.GeneratedClass = generatedCodeqlClass.String()
}
}
for i := range fePackage.TypeMethods {
fe := fePackage.TypeMethods[i]
if err := fe.CodeQL.Validate(); err == nil {
generatedCodeqlClass := new(bytes.Buffer)
err := GenerateCodeQLTT_TypeMethods(generatedCodeqlClass, []*feparser.FETypeMethod{fe})
if err != nil {
return fmt.Errorf("error generating codeql conditions for %q: %s", fe.Func.Signature, err)
}
fe.CodeQL.GeneratedClass = generatedCodeqlClass.String()
}
}
for i := range fePackage.InterfaceMethods {
fe := fePackage.InterfaceMethods[i]
if err := fe.CodeQL.Validate(); err == nil {
generatedCodeqlClass := new(bytes.Buffer)
err := GenerateCodeQLTT_InterfaceMethods(generatedCodeqlClass, []*feparser.FEInterfaceMethod{fe})
if err != nil {
return fmt.Errorf("error generating codeql conditions for %q: %s", fe.Func.Signature, err)
}
fe.CodeQL.GeneratedClass = generatedCodeqlClass.String()
}
}
return nil
}
func GenerateCodeQLTT_Functions(buf *bytes.Buffer, fes []*feparser.FEFunc) error {
tpl, err := NewTextTemplateFromFile("./templates/taint-tracking_function.txt")
if err != nil {
return err
}
for _, fe := range fes {
if !fe.CodeQL.IsEnabled {
continue
}
if err := fe.CodeQL.Validate(); err != nil {
Errorf("invalid pointers for %q: %s", fe.Signature, err)
continue
}
buf.WriteString("\n")
generatedConditions, err := generateCodeQLFlowConditions_FEFunc(fe, fe.CodeQL.Blocks)
if err != nil {
return fmt.Errorf("error generating codeql conditions for %q: %s", fe.Signature, err)
}
fe.CodeQL.GeneratedConditions = PadNewLines(generatedConditions)
err = tpl.Execute(buf, fe)
if err != nil {
return fmt.Errorf("error while executing template for func %q: %s", fe.ID, err)
}
}
return nil
}
func GenerateCodeQLTT_TypeMethods(buf *bytes.Buffer, fes []*feparser.FETypeMethod) error {
tpl, err := NewTextTemplateFromFile("./templates/taint-tracking_type-method.txt")
if err != nil {
return err
}
for _, fe := range fes {
if !fe.CodeQL.IsEnabled {
continue
}
if err := fe.CodeQL.Validate(); err != nil {
Errorf("invalid pointers for %q: %s", fe.Func.Signature, err)
continue
}
buf.WriteString("\n")
generatedConditions, err := generateCodeQLFlowConditions_FEMethod(fe, fe.CodeQL.Blocks)
if err != nil {
return fmt.Errorf("error generating codeql conditions for %q: %s", fe.Func.Signature, err)
}
fe.CodeQL.GeneratedConditions = PadNewLines(generatedConditions)
err = tpl.Execute(buf, fe)
if err != nil {
return fmt.Errorf("error while executing template for type-method %q: %s", fe.ID, err)
}
}
return nil
}
func GenerateCodeQLTT_InterfaceMethods(buf *bytes.Buffer, fes []*feparser.FEInterfaceMethod) error {
tpl, err := NewTextTemplateFromFile("./templates/taint-tracking_interface-method.txt")
if err != nil {
return err
}
for _, fe := range fes {
if !fe.CodeQL.IsEnabled {
continue