-
Notifications
You must be signed in to change notification settings - Fork 43
/
script_engine.go
755 lines (639 loc) · 20.5 KB
/
script_engine.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
package yak
import (
"bytes"
"context"
"fmt"
"github.com/yaklang/yaklang/common/ai"
"github.com/yaklang/yaklang/common/utils/filesys"
"github.com/yaklang/yaklang/common/utils/pprofutils"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/yaklang/yaklang/common/openapi"
"github.com/yaklang/yaklang/common/binx"
"github.com/yaklang/yaklang/common/utils/yakgit"
"github.com/yaklang/yaklang/common/yakgrpc/ypb"
"github.com/davecgh/go-spew/spew"
"github.com/yaklang/yaklang/common/ai/openai"
"github.com/yaklang/yaklang/common/authhack"
"github.com/yaklang/yaklang/common/chaosmaker"
"github.com/yaklang/yaklang/common/crawler"
"github.com/yaklang/yaklang/common/crawlerx"
"github.com/yaklang/yaklang/common/cve"
"github.com/yaklang/yaklang/common/facades"
"github.com/yaklang/yaklang/common/hids"
"github.com/yaklang/yaklang/common/iiop"
"github.com/yaklang/yaklang/common/ja3"
"github.com/yaklang/yaklang/common/log"
"github.com/yaklang/yaklang/common/mutate"
"github.com/yaklang/yaklang/common/pcapx"
"github.com/yaklang/yaklang/common/rpa"
"github.com/yaklang/yaklang/common/sca"
"github.com/yaklang/yaklang/common/simulator"
"github.com/yaklang/yaklang/common/systemd"
"github.com/yaklang/yaklang/common/t3"
"github.com/yaklang/yaklang/common/utils"
"github.com/yaklang/yaklang/common/utils/comparer"
"github.com/yaklang/yaklang/common/utils/htmlquery"
"github.com/yaklang/yaklang/common/xhtml"
"github.com/yaklang/yaklang/common/yak/antlr4yak"
"github.com/yaklang/yaklang/common/yak/antlr4yak/yakvm"
"github.com/yaklang/yaklang/common/yak/httptpl"
"github.com/yaklang/yaklang/common/yak/ssaapi"
"github.com/yaklang/yaklang/common/yak/yakdoc"
"github.com/yaklang/yaklang/common/yak/yaklang"
"github.com/yaklang/yaklang/common/yak/yaklang/lib/builtin"
"github.com/yaklang/yaklang/common/yak/yaklib"
"github.com/yaklang/yaklang/common/yak/yaklib/tools"
"github.com/yaklang/yaklang/common/yakgrpc/yakit"
"github.com/yaklang/yaklang/common/yserx"
"github.com/yaklang/yaklang/common/yso"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/tevino/abool"
_ "github.com/yaklang/yaklang/common/yak/yaklang/lib/builtin" // 导入 builtin 包
)
var (
CRYPTO_KEY_SIZE = 16
initYaklangLibOnce sync.Once
naslExports interface{}
)
func SetNaslExports(lib map[string]interface{}) {
naslExports = lib
}
func init() {
initYaklangLib()
}
func InitYaklangLib() {
initYaklangLibOnce.Do(func() {
initYaklangLib()
})
}
type LibFuncWithFrameType func(*yakvm.Frame) interface{}
func initYaklangLib() {
importGlobal := func(table map[string]interface{}) {
for k, v := range table {
yaklang.Import(k, v)
}
}
if os.Getenv("YAK_DISABLE") == "output" {
yaklib.GlobalExport["dump"] = func(i ...any) {}
builtin.YaklangBaseLib["print"] = func(a ...any) {}
builtin.YaklangBaseLib["printf"] = func(a ...any) {}
builtin.YaklangBaseLib["println"] = func(a ...any) {}
// yaklib.YakitExports["Info"] = func(a string, b ...interface{}) {}
yaklib.YakitExports["Warn"] = func(a string, b ...interface{}) {}
yaklib.YakitExports["Debug"] = func(a string, b ...interface{}) {}
yaklib.YakitExports["Error"] = func(a string, b ...interface{}) {}
}
importGlobal(yaklib.GlobalExport)
importGlobal(builtin.YaklangBaseLib)
importGlobal(GlobalEvalExports)
// yaklang.Import("", yaklib.GlobalExport)
yaklang.Import("yakit", yaklib.YakitExports)
// 基础库
yaklang.Import("str", yaklib.StringsExport)
yaklang.Import("math", yaklib.MathExport)
yaklang.Import("os", yaklib.SystemExports)
yaklang.Import("file", yaklib.FileExport)
yaklang.Import("filesys", filesys.Exports)
yaklang.Import("re", yaklib.RegexpExport)
yaklang.Import("re2", yaklib.RegexpExport)
yaklang.Import("regen", yaklib.RegenExports)
yaklang.Import("env", yaklib.EnvExports)
// yaklang.Import("grok", yaklib.GrokExports)
yaklang.Import("sync", yaklib.SyncExport)
yaklang.Import("io", yaklib.IoExports)
yaklang.Import("bufio", yaklib.BufioExport)
yaklang.Import("context", yaklib.ContextExports)
yaklang.Import("time", yaklib.TimeExports)
yaklang.Import("timezone", yaklib.TimeZoneExports)
yaklang.Import("codec", yaklib.CodecExports) // 编码解码
yaklang.Import("log", yaklib.LogExports)
// yaklang.Import("net", yaklib.Ne)
yaklang.Import("hids", hids.Exports)
yaklang.Import("systemd", systemd.Exports)
// yaklang.Import("geojson", yaklib.GeoJsonExports)
yaklang.Import("mmdb", yaklib.MmdbExports)
yaklang.Import("crawler", crawler.Exports)
yaklang.Import("mitm", yaklib.MitmExports)
yaklang.Import("tls", yaklib.TlsExports)
// CLI 解析
yaklang.Import("cli", yaklib.CliExports)
// Fuzz 模糊测试
yaklang.Import("fuzz", yaklib.FuzzExports)
// xhtml xss检测基础工具
yaklang.Import("xhtml", xhtml.Exports)
// 基础 http 网络请求的库
yaklang.Import("http", yaklib.HttpExports)
yaklang.Import("httpserver", yaklib.HttpServeExports)
yaklang.Import("httpool", yaklib.HttpPoolExports)
yaklang.Import("dictutil", yaklib.DictUtilExports)
// 漏洞工具的库
yaklang.Import("tools", tools.Exports)
// 基础网络io库
yaklang.Import("tcp", yaklib.TcpExports)
yaklang.Import("udp", yaklib.UDPExport)
// SYN 扫描库
yaklang.Import("synscan", tools.SynPortScanExports)
yaklang.Import("finscan", tools.FinPortScanExports)
// 指纹扫描库
yaklang.Import("servicescan", tools.FingerprintScanExports)
// 子域名扫描库
yaklang.Import("subdomain", tools.SubDomainExports)
// 执行系统命令的库
yaklang.Import("exec", yaklib.ExecExports)
// 爆破
yaklang.Import("brute", tools.BruterExports)
// dns 库
yaklang.Import("dns", yaklib.DnsExports)
// ping
yaklang.Import("ping", yaklib.PingExports)
// traceroute
yaklang.Import("traceroute", yaklib.TracerouteExports)
// shodan / quake / fofa 库
yaklang.Import("spacengine", yaklib.SpaceEngineExports)
// json
yaklang.Import("json", yaklib.JsonExports)
// yaml
yaklang.Import("yaml", yaklib.YamlExports)
// eval
// yaklang.Import("", GlobalEvalExporst)
yaklang.Import("dyn", EvalExports)
// nuclei
yaklang.Import("nuclei", httptpl.Exports)
yaklang.Import("nasl", naslExports)
// jwt
yaklang.Import("jwt", authhack.JWTExports)
// java
yaklang.Import("java", yserx.Exports)
// poc
yaklang.Import("poc", yaklib.PoCExports)
yaklang.Import("csrf", yaklib.CSRFExports)
yaklang.Import("risk", yaklib.RiskExports)
yaklang.Import("report", yakit.ReportExports)
yaklang.Import("dnslog", yaklib.DNSLogExports)
// xpath for html
yaklang.Import("xpath", htmlquery.Exports)
// xml
yaklang.Import("xml", yaklib.XMLExports)
// hooks // 负责加载插件中的插件机制
yaklang.Import("hook", HooksExports)
// 辅助函数库
yaklang.Import("x", yaklib.FunkExports)
// java 反序列化生成
yaklang.Import("yso", yso.Exports)
yaklang.Import("facades", facades.FacadesExports)
// t3反序列化利用
yaklang.Import("t3", t3.Exports)
yaklang.Import("iiop", iiop.Exports)
yaklang.Import("js", yaklib.JSOttoExports)
yaklang.Import("db", yaklib.DatabaseExports)
// 判别
yaklang.Import("judge", comparer.Exports)
//
yaklang.Import("smb", yaklib.SambaExports)
yaklang.Import("ldap", yaklib.LdapExports)
// zip 解压包
yaklang.Import("zip", yaklib.ZipExports)
// gzip 增加 gzip 压缩
yaklang.Import("gzip", yaklib.GzipExports)
// redis
yaklang.Import("redis", yaklib.RedisExports)
// common.rpa
yaklang.Import("rpa", rpa.Exports)
// rdp
yaklang.Import("rdp", yaklib.RdpExports)
// bot
yaklang.Import("bot", yaklib.BotExports)
// simulator
yaklang.Import("simulator", simulator.Exports)
// crawlerX
yaklang.Import("crawlerx", crawlerx.CrawlerXExports)
// CVE
yaklang.Import("cve", cve.CVEExports)
yaklang.Import("cwe", cve.CWEExports)
// openai
yaklang.Import("openai", openai.Exports)
// suricata
yaklang.Import("suricata", chaosmaker.ChaosMakerExports)
yaklang.Import("pcapx", pcapx.Exports)
// ja3
yaklang.Import("ja3", ja3.Exports)
// sca
yaklang.Import("sca", sca.Exports)
// git
yaklang.Import("git", yakgit.Exports)
// binx
yaklang.Import("bin", binx.Exports)
// ssa
yaklang.Import("ssa", ssaapi.Exports)
// openapi
yaklang.Import("openapi", openapi.Exports)
yaklang.Import("sandbox", SandboxExports)
yaklang.Import("ai", ai.Exports)
// pprof utils
yaklang.Import("pprof", pprofutils.Exports)
// 处理 yakit 库的一些函数名
yakdoc.RegisterHook(func(h *yakdoc.DocumentHelper) {
lib, ok := h.Libs["yakit"]
if !ok {
return
}
for name, f := range lib.Functions {
if strings.HasPrefix(f.MethodName, "Yakit") && name != f.MethodName {
f.MethodName = name
}
}
})
}
type ScriptEngine struct {
swg *utils.SizedWaitGroup
logger **yaklib.YakLogger // 由于logger是要对client设置的,而client可以通过hook设置,所以这里用个二级指针,方便修改 logger
tasks *sync.Map
// 设定几个 hook
RegisterLogHook yaklib.RegisterOutputFuncType
UnregisterLogHook yaklib.UnregisterOutputFuncType
RegisterLogConsoleHook yaklib.RegisterOutputFuncType
UnregisterLogConsoleHook yaklib.UnregisterOutputFuncType
RegisterOutputHook yaklib.RegisterOutputFuncType
UnregisterOutputHook yaklib.UnregisterOutputFuncType
RegisterFailedHook yaklib.RegisterOutputFuncType
UnregisterFailedHook yaklib.UnregisterOutputFuncType
RegisterFinishHook yaklib.RegisterOutputFuncType
UnregisterFinishHook yaklib.UnregisterOutputFuncType
RegisterAlertHook yaklib.RegisterOutputFuncType
UnregisterAlertHook yaklib.UnregisterOutputFuncType
engineHooks []func(engine *antlr4yak.Engine) error
// 存储yakc密钥
cryptoKey []byte
// debug
debug bool
debugInit func(*yakvm.Debugger)
debugCallback func(*yakvm.Debugger)
}
func (s *ScriptEngine) GetTaskByTaskID(id string) (*Task, error) {
raw, ok := s.tasks.Load(id)
if ok {
return raw.(*Task), nil
}
return nil, errors.Errorf("no existed task[%s]", id)
}
func (s *ScriptEngine) SaveTask(task *Task) error {
raw, ok := s.tasks.Load(task.TaskID)
if ok {
return errors.Errorf("existed task: %s", task.TaskID)
}
_ = raw
s.tasks.Store(task.TaskID, task)
return nil
}
func (e *ScriptEngine) init() {
yaklib.RegisterLogHook("debug-log", func(taskId string, data string) {
log.Infof("task: %v data: %v", taskId, data)
t, _ := e.GetTaskByTaskID(taskId)
if t != nil {
t.Log = append(t.Log, data)
}
})
yaklib.RegisterFinishHooks("debug-log", func(taskId string, data string) {
t, _ := e.GetTaskByTaskID(taskId)
if t != nil {
t.Finished = append(t.Finished, data)
}
})
yaklib.RegisterAlertHooks("debug-log", func(taskId string, data string) {
t, _ := e.GetTaskByTaskID(taskId)
if t != nil {
t.Alert = append(t.Alert, data)
}
})
yaklib.RegisterOutputHooks("debug-log", func(taskId string, data string) {
t, _ := e.GetTaskByTaskID(taskId)
if t != nil {
t.Output = append(t.Output, data)
}
})
yaklib.RegisterFailedHooks("debug-log", func(taskId string, data string) {
t, _ := e.GetTaskByTaskID(taskId)
if t != nil {
t.Failed = append(t.Failed, data)
}
})
}
func (e *ScriptEngine) RegisterEngineHooks(f func(engine *antlr4yak.Engine) error) {
e.engineHooks = append(e.engineHooks, f)
}
func (e *ScriptEngine) SetYakitClient(client *yaklib.YakitClient) {
e.RegisterEngineHooks(func(engine *antlr4yak.Engine) error {
client.SetYakLog(*e.logger)
log.Debugf("set yakit client: %v", client)
yaklib.SetEngineClient(engine, client)
vm := engine.GetVM()
if vm != nil {
vm.RegisterMapMemberCallHandler("hook", "NewMixPluginCaller", func(i interface{}) interface{} {
origin, ok := i.(func() (*MixPluginCaller, error))
if !ok {
return origin
}
return func() (*MixPluginCaller, error) {
caller, err := origin()
if err != nil {
return nil, err
}
caller.SetFeedback(func(i *ypb.ExecResult) error {
yaklib.RawHandlerToExecOutput(client.Output)(i)
return nil
})
return caller, nil
}
})
}
return nil
})
}
func (e *ScriptEngine) HookOsExit() {
e.RegisterEngineHooks(func(engine *antlr4yak.Engine) error {
val, ok := engine.GetVar("os")
if !ok {
return nil
}
osLib, ok := val.(map[string]interface{})
if !ok {
return nil
}
osLib["Exit"] = func(i ...interface{}) {
panic(fmt.Sprintf("exit current yak context with: %v", spew.Sdump(i)))
}
return nil
})
}
func (e *ScriptEngine) Compile(code string) ([]byte, error) {
engine := yaklang.New()
code = utils.RemoveBOMForString(code)
return engine.Marshal(code, e.cryptoKey)
}
func (e *ScriptEngine) exec(ctx context.Context, id string, code string, params map[string]interface{}, cache bool) (*antlr4yak.Engine, error) {
e.swg.Add()
defer e.swg.Done()
code = utils.RemoveBOMForString(code)
t := &Task{
TaskID: id,
Code: code,
isRunning: abool.New(),
isFinished: abool.New(),
}
err := e.SaveTask(t)
if err != nil {
return nil, err
}
defer func() {
t.isRunning.UnSet()
t.isFinished.Set()
go func() {
select {
case <-time.After(3 * time.Second):
e.tasks.Delete(id)
}
}()
}()
// log.Infof("recv code: %v", code)
engine := yaklang.New()
setCurrentCoreEngine(engine)
defer func() {
unsetCurrentCoreEngine(engine)
}()
// debug
engine.SetDebugMode(e.debug)
engine.SetDebugCallback(e.debugCallback)
engine.SetDebugInit(e.debugInit)
engine.SetVar("id", id)
engine.SetVar("YAK_MAIN", false)
engine.SetVar("YAK_FILENAME", "")
engine.SetVar("YAK_DIR", "")
// 设置参数获取函数
paramGetter := func(key string) interface{} {
if params == nil {
return ""
}
result, ok := params[key]
if !ok {
return ""
}
return result
}
yakMainFlag, ok := params["YAK_MAIN"]
if ok {
res, _ := yakMainFlag.(bool)
if res {
engine.SetVar("YAK_MAIN", true)
}
}
yakAbsFile, _ := params["YAK_FILENAME"]
if yakAbsFile != nil {
engine.SetSourceFilePath(fmt.Sprint(yakAbsFile))
engine.SetVar("YAK_FILENAME", fmt.Sprint(yakAbsFile))
engine.SetVar("YAK_DIR", filepath.Dir(fmt.Sprint(yakAbsFile)))
}
// getParam 和 param 获取参数内容
engine.SetVar("getParam", paramGetter)
engine.SetVar("getParams", paramGetter)
engine.SetVar("param", paramGetter)
yakFileAbsPath := "temporay_script.yak"
if yakAbsFile != nil {
yakFileAbsPath = fmt.Sprint(yakAbsFile)
}
*e.logger = yaklib.CreateYakLogger(yakFileAbsPath)
logger := *e.logger
engine.SetVar("log", map[string]interface{}{
"info": logger.Infof,
"setLevel": logger.SetLevel,
"debug": logger.Debugf,
"warn": logger.Warnf,
"error": logger.Errorf,
"Info": logger.Infof,
"SetLevel": logger.SetLevel,
"Debug": logger.Debugf,
"Warn": logger.Warnf,
"Error": logger.Errorf,
}) // 设置 log 库
(*e.logger).SetEngine(engine)
clientIns := *yaklib.GetYakitClientInstance()
client := &clientIns // 设置全局 client 的 log
client.SetYakLog(*e.logger)
yaklib.SetEngineClient(engine, client)
for _, hook := range e.engineHooks {
err = hook(engine)
if err != nil {
return nil, utils.Errorf("exec engine hooks failed: %s", err)
}
}
t.isRunning.Set()
if antlr4yak.IsYakc([]byte(code)) {
return engine, engine.SafeExecYakc(ctx, []byte(code), e.cryptoKey, code)
}
if !e.debug && cache && !engine.HaveEvaluatedCode() {
if yakcBytes, ok := antlr4yak.HaveYakcCache(code); ok && antlr4yak.IsYakc(yakcBytes) {
return engine, engine.SafeExecYakcWithCode(ctx, yakcBytes, e.cryptoKey, code)
}
}
return engine, engine.SafeEval(ctx, code)
}
func (e *ScriptEngine) ExecuteWithTaskID(taskId, code string) error {
return e.ExecuteWithTaskIDAndParams(context.Background(), taskId, code, make(map[string]interface{}))
}
func (e *ScriptEngine) ExecuteWithTaskIDAndContext(ctx context.Context, taskId, code string) error {
return e.ExecuteWithTaskIDAndParams(ctx, taskId, code, make(map[string]interface{}))
}
func (e *ScriptEngine) ExecuteWithTaskIDAndParams(ctx context.Context, taskId, code string, params map[string]interface{}) error {
engine, err := e.exec(ctx, taskId, code, params, true)
if err != nil {
return err
}
_ = engine
return nil
}
func (e *ScriptEngine) ExecuteWithoutCache(code string, params map[string]interface{}) (*antlr4yak.Engine, error) {
runtimeId := utils.MapGetStringByManyFields(params, "RUNTIME_ID", "RUNTIME_ID", "runtime_id")
if runtimeId == "" {
runtimeId = uuid.New().String()
}
return e.exec(context.Background(), runtimeId, code, params, false)
}
func (e *ScriptEngine) ExecuteEx(code string, params map[string]interface{}) (*antlr4yak.Engine, error) {
runtimeId := utils.MapGetStringByManyFields(params, "RUNTIME_ID", "RUNTIME_ID", "runtime_id")
if runtimeId == "" {
runtimeId = uuid.New().String()
}
return e.exec(context.Background(), runtimeId, code, params, true)
}
func (e *ScriptEngine) ExecuteExWithContext(ctx context.Context, code string, params map[string]interface{}) (_ *antlr4yak.Engine, fErr error) {
defer func() {
if err := recover(); err != nil {
log.Errorf("execute ex with context error: %v", err)
fErr = utils.Errorf("final error: %v", err)
}
}()
runtimeId := utils.MapGetStringByManyFields(params, "RUNTIME_ID", "RUNTIME_ID", "runtime_id")
if runtimeId == "" {
runtimeId = uuid.New().String()
}
return e.exec(ctx, runtimeId, code, params, true)
}
func (e *ScriptEngine) Execute(code string) error {
return e.ExecuteWithTaskID(uuid.New().String(), code)
}
func (e *ScriptEngine) ExecuteWithContext(ctx context.Context, code string) error {
return e.ExecuteWithTaskIDAndContext(ctx, uuid.New().String(), code)
}
func (e *ScriptEngine) ExecuteMain(code string, AbsFile string) error {
return e.ExecuteWithTaskIDAndParams(context.Background(), uuid.New().String(), code, map[string]interface{}{
"YAK_MAIN": true,
"YAK_FILENAME": AbsFile,
})
}
func (e *ScriptEngine) ExecuteMainWithContext(ctx context.Context, code string, AbsFile string) error {
return e.ExecuteWithTaskIDAndParams(ctx, uuid.New().String(), code, map[string]interface{}{
"YAK_MAIN": true,
"YAK_FILENAME": AbsFile,
})
}
func (e *ScriptEngine) ExecuteWithTemplate(codeTmp string, i map[string][]string) error {
results, err := mutate.QuickMutate(codeTmp, nil, mutate.MutateWithExtraParams(i))
if err != nil {
return err
}
wg := new(sync.WaitGroup)
for _, result := range results {
result := result
wg.Add(1)
go func() {
defer wg.Done()
err := e.ExecuteWithTaskID(uuid.New().String(), result)
if err != nil {
log.Errorf("failed: %s", err)
}
}()
}
wg.Wait()
return nil
}
func NewYakitVirtualClientScriptEngine(client *yaklib.YakitClient) *ScriptEngine {
e := NewScriptEngine(20)
e.SetYakitClient(client)
return e
}
func Execute(code string, params ...map[string]any) (*antlr4yak.Engine, error) {
mergedParams := make(map[string]any)
if len(params) > 0 {
for _, param := range params {
for k, v := range param {
mergedParams[k] = v
}
}
}
engine := NewScriptEngine(1)
engine.RegisterEngineHooks(func(engine *antlr4yak.Engine) error {
if mergedParams != nil {
for k, v := range mergedParams {
engine.SetVar(k, v)
}
}
return nil
})
return engine.ExecuteEx(code, mergedParams)
}
func NewScriptEngine(maxConcurrent int) *ScriptEngine {
var logger *yaklib.YakLogger
engine := &ScriptEngine{
swg: utils.NewSizedWaitGroup(maxConcurrent),
tasks: new(sync.Map),
RegisterLogHook: yaklib.RegisterLogHook,
RegisterLogConsoleHook: yaklib.RegisterLogConsoleHook,
RegisterAlertHook: yaklib.RegisterAlertHooks,
RegisterFailedHook: yaklib.RegisterFailedHooks,
RegisterFinishHook: yaklib.RegisterFinishHooks,
RegisterOutputHook: yaklib.RegisterOutputHooks,
UnregisterLogHook: yaklib.UnregisterLogHook,
UnregisterLogConsoleHook: yaklib.UnregisterLogConsoleHook,
UnregisterAlertHook: yaklib.UnregisterAlertHooks,
UnregisterFailedHook: yaklib.UnregisterFailedHooks,
UnregisterFinishHook: yaklib.UnregisterFinishHooks,
UnregisterOutputHook: yaklib.UnregisterOutputHooks,
logger: &logger,
}
engine.init()
return engine
}
func (s *ScriptEngine) SetDebugInit(callback func(*yakvm.Debugger)) {
s.debugInit = callback
}
func (s *ScriptEngine) SetDebugCallback(callback func(*yakvm.Debugger)) {
s.debugCallback = callback
}
func (s *ScriptEngine) SetDebug(debug bool) {
s.debug = debug
}
func (s *ScriptEngine) Status() map[string]*Task {
m := make(map[string]*Task)
s.tasks.Range(func(key, value interface{}) bool {
k := key.(string)
v := value.(*Task)
m[k] = v
return true
})
return m
}
func (s *ScriptEngine) SetCryptoKey(key []byte) error {
if key == nil {
return nil
}
key = bytes.TrimSpace(key)
if len(key) != CRYPTO_KEY_SIZE {
return utils.Errorf("invalid crypto key size: %d", len(key))
}
s.cryptoKey = key
return nil
}