yak

package
v1.3.1-sp2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2024 License: AGPL-3.0 Imports: 87 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// func mirrorHTTPFlow(isHttps, url, request, response, body)
	//     mirror hijacked by filtered http flows
	HOOK_MirrorFilteredHTTPFlow = "mirrorFilteredHTTPFlow"

	// func mirrorHTTPFlow(isHttps, url, request, response, body)
	//     mirror hijacked all
	HOOK_MirrorHTTPFlow = "mirrorHTTPFlow"

	// func mirrorNewWebsite(isHttps, url, request, response, body)
	HOOK_MirrorNewWebsite = "mirrorNewWebsite" // schema + addr

	// func mirrorNewWebsitePath(isHttps, url, request, response, body)
	HOOK_MirrorNewWebsitePath = "mirrorNewWebsitePath" // schema + addr + path (remove params)

	// func mirrorNewWebsitePathParams(isHttps, url, request, response, body)
	HOOK_MirrorNewWebsitePathParams = "mirrorNewWebsitePathParams" // schema + addr + path + param_names

	// func hijackHTTPRequest(isHttps, url, request, forward/*func(modified []byte)*/, drop /*func()*/)
	HOOK_HijackHTTPRequest = "hijackHTTPRequest"

	// func hijackHTTPRequest(isHttps, url, response, forward/*func(modified []byte)*/, drop /*func()*/)
	HOOK_HijackHTTPResponse = "hijackHTTPResponse"
	// func hijackHTTPRequest(isHttps, url, request, response, forward/*func(modified []byte)*/, drop /*func()*/)
	HOOK_HijackHTTPResponseEx = "hijackHTTPResponseEx"

	// func hijackSaveHTTPFlow(record *httpFlow, forward func(*httpFlow), drop func()) return (*httpFlow)
	HOOK_hijackSaveHTTPFlow = "hijackSaveHTTPFlow"

	// func handle(r *fp.MatchResult)
	HOOK_PortScanHandle = "handle"

	// func execNuclei(target)
	HOOK_NucleiScanHandle = "execNuclei"

	HOOK_NaslScanHandle           = "execNasl"
	HOOK_LoadNaslScriptByNameFunc = "loadNaslScriptByNameFunc"
)
View Source
const HOOK_CLAER = "clear"

Variables

View Source
var (
	CRYPTO_KEY_SIZE = 16
)
View Source
var EvalExports = map[string]interface{}{
	"Eval":            QuickEvalWithoutContext,
	"LoadVarFromFile": LoadingVariableFrom,
	"Import":          ImportVarFromFile,
	"IsYakFunc":       yaklang.IsYakFunction,
	"params":          setYakEvalParams,
	"recursive":       setYakBatchImportRecursiveParams,
}
View Source
var GlobalEvalExports = map[string]interface{}{

	"import": ImportVarFromFile,
}
View Source
var HooksExports = map[string]interface{}{
	"NewManager":                   NewYakToCallerManager,
	"NewMixPluginCaller":           NewMixPluginCaller,
	"NewMixPluginCallerWithFilter": NewMixPluginCallerWithFilter,
	"RemoveYakitPluginByName":      removeScriptByNameCtx,
	"LoadYakitPluginContext":       loadScriptCtx,
	"LoadYakitPlugin":              loadScript,
	"LoadYakitPluginByName":        loadScriptByName,
	"CallYakitPluginFunc":          CallYakitPluginFunc,
}
View Source
var SandboxExports = map[string]any{
	"Create":  NewSandbox,
	"library": WithSandbox_ExternalLib,
}
View Source
var Subcommands = []cli.Command{
	{
		Name:  "tag-stats",
		Usage: "Generate Tag Status",
		Action: func(c *cli.Context) error {
			stats, err := yaklib.NewTagStat()
			if err != nil {
				return err
			}
			for _, v := range stats.All() {
				if v.Count <= 1 {
					continue
				}
				fmt.Printf("TAG:[%v]-%v\n", v.Name, v.Count)
			}
			return nil
		},
	},

	{
		Name: "update-nuclei-database", Usage: "把本地的 nuclei-templates 更新到数据库 (yakit plugin database)",
		Category: catNuclei,
		Action: func(c *cli.Context) error {
			var err error
			err = NewScriptEngine(1).ExecuteMain(`loglevel("info")
log.info("start to load local database"); 
die(nuclei.UpdateDatabase())`, "main")
			if err != nil {
				log.Errorf("execute nuclei.UpdateDatabase() failed: %s", err)
				return err
			}
			return nil
		},
	},
	{
		Name: "remove-nuclei-database", Usage: "移除本地的 nuclei-templates 数据库",
		Category: catNuclei,
		Action: func(c *cli.Context) error {
			err := tools.RemovePoCDatabase()
			if err != nil {
				log.Errorf("remove pocs failed: %s", err)
			}
			return nil
		},
	},
	{
		Name:     "synscan",
		Usage:    "【快】SYN 扫描端口",
		Category: catScanner,
		Flags: []cli.Flag{
			cli.StringFlag{
				Name: "target,host,t",
			},
			cli.StringFlag{
				Name:  "port,p",
				Value: "22,80,443,3389,3306,8080-8082,9000-9002,7000-7002",
			},
			cli.IntFlag{
				Name:  "wait,waiting",
				Usage: "在 SYN 包发送完毕之后等待多长时间进行收尾(Seconds)",
				Value: 5,
			},

			cli.BoolFlag{
				Name:  "fingerprint,fp,x",
				Usage: "开启指纹扫描",
			},
			cli.IntFlag{
				Name:  "request-timeout",
				Usage: "单个请求的超时时间(Seconds)",
				Value: 10,
			},
			cli.StringFlag{
				Name:  "rule-path,rule,r",
				Usage: "手动加载规则文件/文件夹",
			},
			cli.BoolFlag{
				Name:  "only-rule",
				Usage: "只加载这个文件夹中的 Web 指纹",
			},
			cli.StringFlag{
				Name:  "fp-json,fpo",
				Usage: "详细结果输出 json 到文件",
			},

			cli.StringFlag{
				Name:  "output",
				Usage: "输出端口开放的信息到文件",
			},

			cli.StringFlag{
				Name:  "output-line-prefix",
				Value: "",
				Usage: "输出 OUTPUT 每一行的前缀,例如:https:// http://",
			},

			cli.IntFlag{
				Name:  "fingerprint-concurrent,fc",
				Value: 60,
				Usage: "设置指纹扫描的并发量(同时进行多少个指纹扫描模块)",
			},
		},
		Action: func(c *cli.Context) {
			target := c.String("target")
			targetList := utils.ParseStringToHosts(target)
			if len(targetList) <= 0 {
				log.Errorf("empty target: %s", c.String("target"))
				return
			}

			var sampleTarget string
			if len(targetList) == 1 {
				sampleTarget = targetList[0]
			} else {
				for _, target := range targetList {
					if !utils.IsLoopback(target) {
						sampleTarget = target
						break
					}
				}
				if sampleTarget == "" {
					sampleTarget = targetList[1]
				}
			}

			options, err := synscan.CreateConfigOptionsByTargetNetworkOrDomain(sampleTarget, 10*time.Second)
			if err != nil {
				log.Errorf("init syn scanner failed: %s", err)
				return
			}
			synScanConfig, err := synscan.NewConfig(options...)
			if err != nil {
				log.Errorf("create synscan config failed: %s", err)
				return
			}

			log.Infof("default config: \n    iface:%v src:%v gateway:%v", synScanConfig.Iface.Name, synScanConfig.SourceIP, synScanConfig.GatewayIP)

			webRules, _ := fp.GetDefaultWebFingerprintRules()
			userRule := webfingerprint.FileOrDirToWebRules(c.String("rule-path"))

			if c.Bool("only-rule") {
				webRules = userRule
			} else {
				webRules = append(webRules, userRule...)
			}

			fingerprintMatchConfigOptions := []fp.ConfigOption{

				fp.WithActiveMode(true),

				fp.WithProbeTimeout(time.Second * time.Duration(c.Int("request-timeout"))),

				fp.WithWebFingerprintUseAllRules(true),

				fp.WithWebFingerprintRule(webRules),

				fp.WithForceEnableAllFingerprint(true),

				fp.WithTransportProtos(fp.TCP),
			}
			fpConfig := fp.NewConfig(fingerprintMatchConfigOptions...)

			scanCenterConfig, err := hybridscan.NewDefaultConfigWithSynScanConfig(
				synScanConfig,
			)
			if err != nil {
				log.Errorf("default config failed: %s", err)
				return
			}

			scanCenterConfig.DisableFingerprintMatch = true

			log.Info("start create hyper scan center...")
			scanCenter, err := hybridscan.NewHyperScanCenter(context.Background(), scanCenterConfig)
			if err != nil {
				log.Error(err)
				return
			}

			log.Info("preparing for result collectors")
			fpLock := new(sync.Mutex)
			openPortLock := new(sync.Mutex)

			var fpResults []*fp.MatchResult
			var openPortCount int
			var openResult []string

			// outputfile
			var outputFile *os.File
			if c.String("output") != "" {
				outputFile, err = os.OpenFile(c.String("output"), os.O_RDWR|os.O_CREATE, os.ModePerm)
				if err != nil {
					log.Errorf("open file %v failed; %s", c.String("output"), err)
				}
				if outputFile != nil {
					defer outputFile.Close()
				}
			}

			log.Infof("start submit task and scan...")
			err = scanCenter.Scan(
				context.Background(),
				c.String("target"), c.String("port"), true, false,
				func(ip net.IP, port int) {
					openPortLock.Lock()
					defer openPortLock.Unlock()

					openPortCount++
					r := utils.HostPort(ip.String(), port)
					log.Infof("found open port -> tcp://%v", r)
					openResult = append(openResult, r)

					if outputFile != nil {

						outputFile.Write(
							[]byte(fmt.Sprintf(
								"%s%v\n",
								c.String("output-line-prefix"),
								r,
							)),
						)
					}
				},
			)
			if err != nil {
				log.Error(err)
				return
			}
			log.Infof("finished submitting.")

			if c.Bool("fingerprint") {
				fpTargetChan := make(chan *fp.PoolTask)
				go func() {
					defer close(fpTargetChan)
					for _, i := range openResult {
						host, port, err := utils.ParseStringToHostPort(i)
						if err != nil {
							continue
						}

						fpTargetChan <- &fp.PoolTask{
							Host:    host,
							Port:    port,
							Options: fingerprintMatchConfigOptions,
						}
					}
				}()
				pool, err := fp.NewExecutingPool(context.Background(), c.Int("fingerprint-concurrent"), fpTargetChan, fpConfig)
				if err != nil {
					log.Errorf("create fingerprint execute pool failed: %s", err)
					return
				}
				pool.AddCallback(func(matcherResult *fp.MatchResult, err error) {
					fpLock.Lock()
					defer fpLock.Unlock()

					if matcherResult != nil {
						fpResults = append(fpResults, matcherResult)
						log.Infof("scan fingerprint finished: -> %v", utils.HostPort(matcherResult.Target, matcherResult.Port))
					}
				})
				err = pool.Run()
				if err != nil {
					log.Errorf("fingerprint execute pool run failed: %v", err)
					return
				}
			}

			analysis := fp.MatcherResultsToAnalysis(fpResults)

			log.Infof("waiting last packet (SYN) for %v seconds", c.Int("waiting"))
			select {
			case <-time.After(time.Second * time.Duration(c.Int("waiting"))):
			}

			hosts := utils.ParseStringToHosts(c.String("target"))
			ports := utils.ParseStringToPorts(c.String("port"))
			analysis.TotalScannedPort = len(hosts) * len(ports)

			if c.Bool("fp") || len(analysis.OpenPortCPEMap) > 0 {
				analysis.Show()
				analysis.ToJson(c.String("fp-json"))
			} else {
				log.Infof("open ports ...\n===================================")
				for _, port := range openResult {
					println(port)
				}
			}
		},
	},
	{
		Name:     "scan-service",
		Usage:    "【精准】指纹扫描",
		Category: catScanner,
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "hosts,target,t",
				Usage: "输入扫描主机,以逗号分隔例如:(192.168.1.1/24,192.168.1.1-23,10.1.1.2)",
			},
			cli.StringFlag{
				Name:  "port,tcp-port,p",
				Usage: "输入想要扫描的端口,支持单个端口和范围,例如(80,443,21-25,8080-8082)",
				Value: "22,80,443,3389,3306,8080-8082,9000-9002,7000-7002",
			},
			cli.StringFlag{
				Name:  "udp-port",
				Usage: "想要扫描的 UDP 端口,支持单个端口和范围",
			},
			cli.StringFlag{
				Name:  "rule-path,rule,r",
				Usage: "手动加载规则文件/文件夹",
			},
			cli.BoolFlag{
				Name:  "only-rule",
				Usage: "只加载这个文件夹中的 Web 指纹",
			},
			cli.IntFlag{
				Name:  "concurrent,thread,c",
				Usage: "并发速度,同时有多少个扫描过程进行?",
				Value: 60,
			},

			cli.BoolFlag{
				Name:  "web",
				Usage: "主动开启 web 扫描模式",
			},
			cli.IntFlag{
				Name:  "request-timeout",
				Usage: "单个请求的超时时间(Seconds)",
				Value: 10,
			},
			cli.StringFlag{
				Name:  "json,o",
				Usage: "详细结果输出 json 到文件",
			},
		},
		Action: func(c *cli.Context) error {
			var options []fp.ConfigOption

			webRules, _ := fp.GetDefaultWebFingerprintRules()
			userRule := webfingerprint.FileOrDirToWebRules(c.String("rule-path"))

			if c.Bool("only-rule") {
				webRules = userRule
			} else {
				webRules = append(webRules, userRule...)
			}

			options = append(
				options,

				fp.WithActiveMode(true),

				fp.WithProbeTimeout(time.Second*time.Duration(c.Int("request-timeout"))),

				fp.WithWebFingerprintUseAllRules(true),

				fp.WithWebFingerprintRule(webRules),
			)
			options = append(
				options, fp.WithForceEnableAllFingerprint(true),
			)

			config := fp.NewConfig(options...)

			matcher, err := fp.NewDefaultFingerprintMatcher(config)
			if err != nil {
				return err
			}

			portSwg := utils.NewSizedWaitGroup(c.Int("concurrent"))

			resultLock := new(sync.Mutex)

			var res []*fp.MatchResult

			scanCore := func(tHost string, tPort int, opts ...fp.ConfigOption) {
				defer portSwg.Done()

				log.Infof("start scan %v", utils.HostPort(tHost, tPort))
				result, err := matcher.Match(
					tHost, tPort,
					opts...,
				)
				if err != nil {
					log.Errorf("scan %v failed: %s", utils.HostPort(tHost, tPort), err)
					return
				}
				resultLock.Lock()
				defer resultLock.Unlock()

				log.Infof("[%6s] %s://%s cpe: %v", result.State, result.GetProto(), utils.HostPort(result.Target, result.Port), result.GetCPEs())
				res = append(res, result)
			}

			for _, host := range utils.ParseStringToHosts(c.String("hosts")) {
				host := host
				for _, tcpPort := range utils.ParseStringToPorts(c.String("port")) {
					tcpPort := tcpPort

					portSwg.Add()
					go scanCore(
						host, tcpPort,
						fp.WithForceEnableAllFingerprint(true),
						fp.WithOnlyEnableWebFingerprint(c.Bool("web")),
						fp.WithTransportProtos(fp.TCP),
					)
				}

				for _, udpPort := range utils.ParseStringToPorts(c.String("udp-port")) {
					udpPort := udpPort

					portSwg.Add()
					go scanCore(host, udpPort, fp.WithDisableWebFingerprint(true),
						fp.WithTransportProtos(fp.UDP))
				}

			}
			portSwg.Wait()

			analysis := fp.MatcherResultsToAnalysis(res)

			analysis.Show()
			analysis.ToJson(c.String("json"))

			return nil
		},
	},
	{
		Name: "fuzz",
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "t,target",
				Usage: "想要测试的 Fuzz 字符串",
			},
		},
		Action: func(c *cli.Context) {
			for _, r := range mutate.MutateQuick(c.String("t")) {
				println(r)
			}
		},
	},
	{
		Name:  "upgrade",
		Usage: "upgrade / reinstall newest yak.",
		Flags: []cli.Flag{
			cli.IntFlag{
				Name:  "timeout",
				Usage: "连接超时时间",
				Value: 30,
			},
		},
		Action: func(c *cli.Context) error {
			exePath, err := os.Executable()
			exeDir := filepath.Dir(exePath)
			if err != nil {
				return utils.Errorf("cannot fetch os.Executable()...: %s", err)
			}

			binary := fmt.Sprintf(`https://yaklang.oss-accelerate.aliyuncs.com/yak/latest/yak_%v_%v`, runtime.GOOS, runtime.GOARCH)
			if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
				binary = fmt.Sprintf(`https://yaklang.oss-accelerate.aliyuncs.com/yak/latest/yak_%v_%v`, runtime.GOOS, "amd64")
			} else if runtime.GOOS == "windows" {
				binary = fmt.Sprintf(`https://yaklang.oss-accelerate.aliyuncs.com/yak/latest/yak_%v_%v.exe`, runtime.GOOS, "amd64")
			}

			versionUrl := `https://yaklang.oss-accelerate.aliyuncs.com/yak/latest/version.txt`
			timeout := float64(c.Int("timeout"))
			rspIns, _, err := poc.DoGET(versionUrl, poc.WithTimeout(timeout))
			if err != nil {
				log.Errorf("获取 yak 引擎最新版本失败:get yak latest version failed: %v", err)
				return err
			}
			if len(rspIns.RawPacket) > 0 {
				raw := lowhttp.GetHTTPPacketBody(rspIns.RawPacket)
				if len(utils.ParseStringToLines(string(raw))) <= 3 {
					log.Infof("当前 yak 核心引擎最新版本为 / current latest yak core engine version:%v", string(raw))
				}
			}

			log.Infof("start to download yak: %v", binary)
			rspIns, _, err = poc.DoGET(binary, poc.WithTimeout(timeout))
			if err != nil {
				log.Errorf("下载 yak 引擎失败:download yak failed: %v", err)
				return err
			}

			newFilePath := filepath.Join(exeDir, "yak.new")
			fd, err := os.OpenFile(newFilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o766)
			if err != nil {
				log.Errorf("create temp file failed: %v", err)
				return err
			}

			log.Infof("downloading for yak binary to local")
			_, err = io.Copy(fd, rspIns.MultiResponseInstances[0].Body)
			if err != nil && err != io.EOF {
				log.Errorf("download failed...: %v", err)
				return err
			}
			log.Infof("yak 核心引擎下载成功... / yak engine downloaded")
			fd.Sync()
			fd.Close()

			destDir, _ := filepath.Split(exePath)
			backupPath := filepath.Join(destDir, fmt.Sprintf("yak_%s", consts.GetYakVersion()))
			if runtime.GOOS == "windows" {
				backupPath += ".exe"
			}
			log.Infof("backup yak old engine to %s", backupPath)

			log.Infof("origin binary: %s", exePath)

			if err := os.Rename(exePath, backupPath); err != nil {
				return utils.Errorf("backup old yak-engine failed: %s, retry re-Install with \n"+
					"    `bash <(curl -sS -L http://oss.yaklang.io/install-latest-yak.sh)`\n\n", err)
			}

			if err := os.Rename(newFilePath, exePath); err != nil {

				rerr := os.Rename(backupPath, exePath)
				if rerr != nil {
					return utils.Errorf("rename new yak-engine failed: %s, rollback failed: %s, retry re-Install with \n"+"    `bash <(curl -sS -L http://oss.yaklang.io/install-latest-yak.sh)`\n\n", err, rerr)
				}

				return utils.Errorf("rename new yak-engine failed: %s, retry re-Install with \n"+
					"    `bash <(curl -sS -L http://oss.yaklang.io/install-latest-yak.sh)`\n\n", err)
			}

			return nil
		},
	},
}
View Source
var YAK_TEMPLATE_NUCLEI_EXECUTOR string

Functions

func BindYakitPluginContextToEngine added in v1.2.3

func BindYakitPluginContextToEngine(nIns *antlr4yak.Engine, pluginContext *YakitPluginContext)

func CallYakitPluginFunc

func CallYakitPluginFunc(scriptName string, hookName string) (interface{}, error)

func ClearHelper added in v1.2.9

func ClearHelper(helper *yakdoc.DocumentHelper)

func DocumentHelperWithVerboseInfo added in v1.3.1

func DocumentHelperWithVerboseInfo(funcMap map[string]interface{}) *yakdoc.DocumentHelper

func EngineToDocumentHelperWithVerboseInfo

func EngineToDocumentHelperWithVerboseInfo(engine *antlr4yak.Engine) *yakdoc.DocumentHelper

func EngineToLibDocuments

func EngineToLibDocuments(engine *antlr4yak.Engine) []yakdocument.LibDoc

! 老接口

func Execute added in v1.2.3

func Execute(code string, params ...map[string]any) (*antlr4yak.Engine, error)

func FeedbackFactory

func FeedbackFactory(db *gorm.DB, caller func(result *ypb.ExecResult) error, saveToDb bool, yakScriptName string) func(i interface{}, items ...interface{})

func FetchFunctionFromSourceCode

func FetchFunctionFromSourceCode(ctx context.Context, pluginContext *YakitPluginContext, timeout time.Duration, id string, code string, hook func(e *antlr4yak.Engine) error, functionNames ...string) (map[string]*YakFunctionCaller, error)

func Fuzz_WithHotPatch added in v1.2.6

func Fuzz_WithHotPatch(ctx context.Context, code string) mutate.FuzzConfigOpt

func GetDeprecatedFunctionDecls added in v1.3.1

func GetDeprecatedFunctionDecls(helper *yakdoc.DocumentHelper) []*yakdoc.DeprecateFunction

func GetInterfaceDocumentFromAST added in v1.2.9

func GetInterfaceDocumentFromAST(pkg *ast.Package, interfaceName string) map[string]string

func GetMethodFuncDeclFromAST added in v1.2.9

func GetMethodFuncDeclFromAST(pkg *ast.Package, libName, structName, methodName, yakFuncName string, fset *token.FileSet) *yakdoc.FuncDecl

func HookCliArgs added in v1.3.1

func HookCliArgs(nIns *antlr4yak.Engine, tempArgs []string) *cli.CliApp

func ImportVarFromFile

func ImportVarFromFile(file string, exportsName string) (interface{}, error)

func ImportVarFromScript

func ImportVarFromScript(engine *antlr4yak.Engine, script string, exportsName string) (interface{}, error)

func ImportVarFromYakFile

func ImportVarFromYakFile(path string, exportsName string) (interface{}, error)

func InitYaklangLib

func InitYaklangLib()

func IsSameTypeName added in v1.2.9

func IsSameTypeName(typName1, typName2 string) bool

func LoadingVariableFrom

func LoadingVariableFrom(path string, exportsName string, opts ...yakEvalConfigOpt) ([]*yakVariable, error)

func MutateHookCaller

func MutateHookCaller(raw string) (func([]byte) []byte, func([]byte) []byte, func([]byte, []byte, map[string]string) map[string]string)

func MutateWithParamsGetter

func MutateWithParamsGetter(raw string) func() *mutate.RegexpMutateCondition

func MutateWithYaklang

func MutateWithYaklang(raw string) *mutate.RegexpMutateCondition

func QuickEvalWithoutContext

func QuickEvalWithoutContext(i interface{}) error

func SetNaslExports added in v1.2.2

func SetNaslExports(lib map[string]interface{})

func StaticAnalyzeYaklang added in v1.3.1

func StaticAnalyzeYaklang(code string, typs ...string) []*result.StaticAnalyzeResult

Types

type Caller

type Caller struct {
	Core    *YakFunctionCaller
	Hash    string
	Id      string
	Verbose string
	Engine  *antlr4yak.Engine
}

type CallerHookDescription

type CallerHookDescription struct {
	// 这两个是
	YakScriptId   string
	YakScriptName string
	VerboseName   string
}

type CallerHooks

type CallerHooks struct {
	HookName string

	Hooks []*CallerHookDescription
}

type EmbedFieldTypeAndMethod added in v1.2.9

type EmbedFieldTypeAndMethod struct {
	FieldType reflect.Type
	Method    reflect.Method
}

type InstanceMethodHandler added in v1.2.9

type InstanceMethodHandler struct {
	// contains filtered or unexported fields
}

type LibFuncWithFrameType

type LibFuncWithFrameType func(*yakvm.Frame) interface{}

type MixPluginCaller

type MixPluginCaller struct {
	// contains filtered or unexported fields
}

func NewMixPluginCaller

func NewMixPluginCaller() (*MixPluginCaller, error)

func NewMixPluginCallerWithFilter added in v1.3.1

func NewMixPluginCallerWithFilter(webFilter *filter.StringFilter) (*MixPluginCaller, error)

func (*MixPluginCaller) CallHijackRequest

func (m *MixPluginCaller) CallHijackRequest(
	isHttps bool, u string, getRequest func() interface{},
	reject func() interface{},
	drop func() interface{},
)

func (*MixPluginCaller) CallHijackResponse

func (m *MixPluginCaller) CallHijackResponse(
	isHttps bool, u string, getResponse,
	reject, drop func() interface{},
)

func (*MixPluginCaller) CallHijackResponseEx

func (m *MixPluginCaller) CallHijackResponseEx(
	isHttps bool, u string, getRequest, getResponse,
	reject, drop func() interface{},
)

func (*MixPluginCaller) FeedbackOrdinary

func (c *MixPluginCaller) FeedbackOrdinary(i interface{})

func (*MixPluginCaller) GetNativeCaller

func (m *MixPluginCaller) GetNativeCaller() *YakToCallerManager

func (*MixPluginCaller) HandleServiceScanResult

func (m *MixPluginCaller) HandleServiceScanResult(r *fp.MatchResult)

func (*MixPluginCaller) HijackSaveHTTPFlow

func (m *MixPluginCaller) HijackSaveHTTPFlow(flow *yakit.HTTPFlow, reject func(httpFlow *yakit.HTTPFlow), drop func())

func (*MixPluginCaller) LoadHotPatch

func (c *MixPluginCaller) LoadHotPatch(ctx context.Context, code string) error

func (*MixPluginCaller) LoadPlugin

func (m *MixPluginCaller) LoadPlugin(scriptName string, params ...*ypb.ExecParamItem) error

func (*MixPluginCaller) LoadPluginByName

func (m *MixPluginCaller) LoadPluginByName(ctx context.Context, name string, params []*ypb.ExecParamItem, codes ...string) error

LoadPluginByName 基于脚本名加载插件,如果没有指定代码,则从数据库中加载,如果指定了代码,则默认视为mitm插件执行

func (*MixPluginCaller) MirrorHTTPFlow

func (m *MixPluginCaller) MirrorHTTPFlow(
	isHttps bool, u string, req, rsp, body []byte,
	filters ...bool,
)

func (*MixPluginCaller) MirrorHTTPFlowEx

func (m *MixPluginCaller) MirrorHTTPFlowEx(
	scanPort bool,
	isHttps bool, u string, req, rsp, body []byte,
	filters ...bool,
)

func (*MixPluginCaller) ResetFilter

func (c *MixPluginCaller) ResetFilter()

func (*MixPluginCaller) SetCache added in v1.2.2

func (m *MixPluginCaller) SetCache(b bool)

func (*MixPluginCaller) SetConcurrent

func (c *MixPluginCaller) SetConcurrent(i int) error

func (*MixPluginCaller) SetDividedContext

func (m *MixPluginCaller) SetDividedContext(b bool)

func (*MixPluginCaller) SetFeedback

func (m *MixPluginCaller) SetFeedback(i func(i *ypb.ExecResult) error)

func (*MixPluginCaller) SetLoadPluginTimeout

func (c *MixPluginCaller) SetLoadPluginTimeout(i float64)

func (*MixPluginCaller) SetProxy added in v1.2.4

func (m *MixPluginCaller) SetProxy(s string)

func (*MixPluginCaller) SetRuntimeId added in v1.2.3

func (m *MixPluginCaller) SetRuntimeId(s string)

func (*MixPluginCaller) Wait

func (c *MixPluginCaller) Wait()

type PalmScriptEngineHelper

type PalmScriptEngineHelper struct {
	Libs             map[string]*PalmScriptLib
	BuildInFunctions map[string]*PalmScriptLibFunc
	UserFunctions    map[string]*PalmScriptLibFunc
	Instances        map[string]*PalmScriptLibInstance
}

func EngineToHelper

func EngineToHelper(engine *antlr4yak.Engine) *PalmScriptEngineHelper

func (*PalmScriptEngineHelper) GetAllLibs

func (p *PalmScriptEngineHelper) GetAllLibs() []string

func (*PalmScriptEngineHelper) HelpInfo

func (p *PalmScriptEngineHelper) HelpInfo() string

func (*PalmScriptEngineHelper) LibHelpInfo

func (p *PalmScriptEngineHelper) LibHelpInfo(name string) string

func (*PalmScriptEngineHelper) ShowHelpInfo

func (p *PalmScriptEngineHelper) ShowHelpInfo()

func (*PalmScriptEngineHelper) ShowLibHelpInfo

func (p *PalmScriptEngineHelper) ShowLibHelpInfo(name string)

type PalmScriptLib

type PalmScriptLib struct {
	Name             string
	Values           map[string]interface{}
	ElementDocs      []string
	FuncElements     []*PalmScriptLibFunc
	InstanceElements []*PalmScriptLibInstance
}

func (*PalmScriptLib) String

func (p *PalmScriptLib) String() string

type PalmScriptLibFunc

type PalmScriptLibFunc struct {
	LibName    string
	MethodName string
	Params     []string
	Returns    []string
}

func (*PalmScriptLibFunc) String

func (p *PalmScriptLibFunc) String() string

type PalmScriptLibInstance

type PalmScriptLibInstance struct {
	LibName      string
	InstanceName string
	Type         string
	Value        interface{}
}

func (*PalmScriptLibInstance) String

func (p *PalmScriptLibInstance) String() string

type Sandbox added in v1.3.1

type Sandbox struct {
	// contains filtered or unexported fields
}

func NewSandbox added in v1.3.1

func NewSandbox(opts ...SandboxOption) *Sandbox

func (*Sandbox) ExecuteAsBoolean added in v1.3.1

func (s *Sandbox) ExecuteAsBoolean(code string, vars ...any) (ret bool, err error)

func (*Sandbox) ExecuteAsExpression added in v1.3.1

func (s *Sandbox) ExecuteAsExpression(code string, vars ...any) (ret any, err error)

type SandboxConfig added in v1.3.1

type SandboxConfig struct {
	// contains filtered or unexported fields
}

type SandboxOption added in v1.3.1

type SandboxOption func(*SandboxConfig)

func WithSandbox_ExternalLib added in v1.3.1

func WithSandbox_ExternalLib(lib map[string]any) SandboxOption

type ScriptEngine

type ScriptEngine struct {

	// 设定几个 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
	// contains filtered or unexported fields
}

func NewScriptEngine

func NewScriptEngine(maxConcurrent int) *ScriptEngine

func NewYakitVirtualClientScriptEngine added in v1.2.2

func NewYakitVirtualClientScriptEngine(client *yaklib.YakitClient) *ScriptEngine

func (*ScriptEngine) Compile

func (e *ScriptEngine) Compile(code string) ([]byte, error)

func (*ScriptEngine) Execute

func (e *ScriptEngine) Execute(code string) error

func (*ScriptEngine) ExecuteEx

func (e *ScriptEngine) ExecuteEx(code string, params map[string]interface{}) (*antlr4yak.Engine, error)

func (*ScriptEngine) ExecuteExWithContext

func (e *ScriptEngine) ExecuteExWithContext(ctx context.Context, code string, params map[string]interface{}) (_ *antlr4yak.Engine, fErr error)

func (*ScriptEngine) ExecuteMain

func (e *ScriptEngine) ExecuteMain(code string, AbsFile string) error

func (*ScriptEngine) ExecuteMainWithContext

func (e *ScriptEngine) ExecuteMainWithContext(ctx context.Context, code string, AbsFile string) error

func (*ScriptEngine) ExecuteWithContext

func (e *ScriptEngine) ExecuteWithContext(ctx context.Context, code string) error

func (*ScriptEngine) ExecuteWithTaskID

func (e *ScriptEngine) ExecuteWithTaskID(taskId, code string) error

func (*ScriptEngine) ExecuteWithTaskIDAndContext

func (e *ScriptEngine) ExecuteWithTaskIDAndContext(ctx context.Context, taskId, code string) error

func (*ScriptEngine) ExecuteWithTaskIDAndParams

func (e *ScriptEngine) ExecuteWithTaskIDAndParams(ctx context.Context, taskId, code string, params map[string]interface{}) error

func (*ScriptEngine) ExecuteWithTemplate

func (e *ScriptEngine) ExecuteWithTemplate(codeTmp string, i map[string][]string) error

func (*ScriptEngine) ExecuteWithoutCache

func (e *ScriptEngine) ExecuteWithoutCache(code string, params map[string]interface{}) (*antlr4yak.Engine, error)

func (*ScriptEngine) GetTaskByTaskID

func (s *ScriptEngine) GetTaskByTaskID(id string) (*Task, error)

func (*ScriptEngine) HookOsExit

func (e *ScriptEngine) HookOsExit()

func (*ScriptEngine) RegisterEngineHooks

func (e *ScriptEngine) RegisterEngineHooks(f func(engine *antlr4yak.Engine) error)

func (*ScriptEngine) SaveTask

func (s *ScriptEngine) SaveTask(task *Task) error

func (*ScriptEngine) SetCryptoKey

func (s *ScriptEngine) SetCryptoKey(key []byte) error

func (*ScriptEngine) SetDebug

func (s *ScriptEngine) SetDebug(debug bool)

func (*ScriptEngine) SetDebugCallback

func (s *ScriptEngine) SetDebugCallback(callback func(*yakvm.Debugger))

func (*ScriptEngine) SetDebugInit

func (s *ScriptEngine) SetDebugInit(callback func(*yakvm.Debugger))

func (*ScriptEngine) SetYakitClient added in v1.2.2

func (e *ScriptEngine) SetYakitClient(client *yaklib.YakitClient)

func (*ScriptEngine) Status

func (s *ScriptEngine) Status() map[string]*Task

type Task

type Task struct {
	TaskID string
	Code   string

	Output   []string
	Log      []string
	Alert    []string
	Finished []string
	Failed   []string
	// contains filtered or unexported fields
}

func (*Task) IsFinished

func (t *Task) IsFinished() bool

func (*Task) IsRunning

func (t *Task) IsRunning() bool

type TextHandlingScript

type TextHandlingScript struct {
	RuleID         string `json:"rule_id" yaml:"rule_id"`
	MatchingScript string `json:"matching_script" yaml:"matching_script"`
	ParsingScript  string `json:"parsing_script" yaml:"parsing_script"`
}

type TextParser

type TextParser struct {
	Scripts map[string]*TextHandlingScript
	// contains filtered or unexported fields
}

func NewTextParser

func NewTextParser() *TextParser

NewTextParser 创建一个新的文本解析器

func (*TextParser) ParseLine

func (t *TextParser) ParseLine(r io.Reader, handler func(line string, r map[string]string, data []map[string]string)) error

type YakFunctionCaller

type YakFunctionCaller struct {
	Handler func(args ...interface{})
}

type YakToCallerManager

type YakToCallerManager struct {
	ContextCancelFuncs *sync.Map
	// contains filtered or unexported fields
}

func NewYakToCallerManager

func NewYakToCallerManager() *YakToCallerManager

func (*YakToCallerManager) Add

func (y *YakToCallerManager) Add(ctx context.Context, id string, params []*ypb.ExecParamItem, code string, hook func(*antlr4yak.Engine) error, funcName ...string) (retError error)

func (*YakToCallerManager) AddForYakit

func (y *YakToCallerManager) AddForYakit(
	ctx context.Context, id string,
	params []*ypb.ExecParamItem,
	code string, callerIf interface {
		Send(result *ypb.ExecResult) error
	},
	hooks ...string,
) error

func (*YakToCallerManager) AddGoNative

func (y *YakToCallerManager) AddGoNative(id string, name string, cb func(...interface{}))

func (*YakToCallerManager) CallByName

func (y *YakToCallerManager) CallByName(name string, items ...interface{})

func (*YakToCallerManager) CallByNameEx

func (y *YakToCallerManager) CallByNameEx(name string, items ...func() interface{})

func (*YakToCallerManager) CallByNameExSync

func (y *YakToCallerManager) CallByNameExSync(name string, items ...func() interface{})

func (*YakToCallerManager) CallPluginKeyByName

func (y *YakToCallerManager) CallPluginKeyByName(pluginId string, name string, items ...interface{})

func (*YakToCallerManager) CallPluginKeyByNameEx

func (y *YakToCallerManager) CallPluginKeyByNameEx(pluginId string, name string, itemsFuncs ...func() interface{})

func (*YakToCallerManager) CallPluginKeyByNameExWithAsync

func (y *YakToCallerManager) CallPluginKeyByNameExWithAsync(forceSync bool, pluginId string, name string, itemsFuncs ...func() interface{})

func (*YakToCallerManager) GetCurrentHooks

func (y *YakToCallerManager) GetCurrentHooks() []*CallerHooks

func (*YakToCallerManager) GetCurrentHooksGRPCModel

func (y *YakToCallerManager) GetCurrentHooksGRPCModel() []*ypb.YakScriptHooks

func (*YakToCallerManager) LoadPlugin

func (y *YakToCallerManager) LoadPlugin(t string, hooks ...string) error

func (*YakToCallerManager) LoadPluginContext

func (y *YakToCallerManager) LoadPluginContext(ctx context.Context, t string, hooks ...string) error

func (*YakToCallerManager) Remove

func (y *YakToCallerManager) Remove(params *ypb.RemoveHookParams)

func (*YakToCallerManager) Set

func (y *YakToCallerManager) Set(ctx context.Context, code string, hook func(engine *antlr4yak.Engine) error, funcName ...string) (retError error)

func (*YakToCallerManager) SetConcurrent

func (m *YakToCallerManager) SetConcurrent(i int) error

func (*YakToCallerManager) SetDividedContext

func (y *YakToCallerManager) SetDividedContext(b bool)

func (*YakToCallerManager) SetForYakit

func (y *YakToCallerManager) SetForYakit(
	ctx context.Context,
	code string, callerIf interface {
		Send(result *ypb.ExecResult) error
	},
	hooks ...string,
) error

func (*YakToCallerManager) SetLoadPluginTimeout

func (c *YakToCallerManager) SetLoadPluginTimeout(i float64)

func (*YakToCallerManager) ShouldCallByName added in v1.2.6

func (y *YakToCallerManager) ShouldCallByName(name string) bool

func (*YakToCallerManager) SyncCallPluginKeyByNameEx

func (y *YakToCallerManager) SyncCallPluginKeyByNameEx(pluginId string, name string, itemsFuncs ...func() interface{})

func (*YakToCallerManager) Wait

func (y *YakToCallerManager) Wait()

func (*YakToCallerManager) WithDefaultFilter added in v1.3.2

func (y *YakToCallerManager) WithDefaultFilter(filter *filter.StringFilter) *YakToCallerManager

type YakitCallerIf

type YakitCallerIf func(result *ypb.ExecResult) error

func (YakitCallerIf) Send

func (y YakitCallerIf) Send(i *ypb.ExecResult) error

type YakitPluginContext added in v1.2.4

type YakitPluginContext struct {
	PluginName string
	RuntimeId  string
	Proxy      string
	Ctx        context.Context
	CliApp     *cli.CliApp
	// contains filtered or unexported fields
}

func CreateYakitPluginContext added in v1.3.1

func CreateYakitPluginContext(runtimeId string) *YakitPluginContext

func (*YakitPluginContext) WithCliApp added in v1.3.1

func (y *YakitPluginContext) WithCliApp(cliApp *cli.CliApp) *YakitPluginContext

func (*YakitPluginContext) WithContext added in v1.3.1

func (*YakitPluginContext) WithDefaultFilter added in v1.3.1

func (y *YakitPluginContext) WithDefaultFilter(filter *filter.StringFilter) *YakitPluginContext

func (*YakitPluginContext) WithPluginName added in v1.3.1

func (y *YakitPluginContext) WithPluginName(id string) *YakitPluginContext

func (*YakitPluginContext) WithProxy added in v1.3.1

func (y *YakitPluginContext) WithProxy(proxy string) *YakitPluginContext

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL