antlr4nasl

package
v1.2.1-sp9 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2023 License: AGPL-3.0 Imports: 39 Imported by: 0

README

NASL 的一些语法规则

变量类型

INT、STRING、DATA、ARRAY、UNDEF

类型 说明 映射到的 Go 类型
INT 整型 int64
STRING 字符串 string
DATA 二进制数据 []byte
ARRAY 数组 struct NaslArray
UNDEF 未定义 nil

array类型是一个特殊类型,和传统的array不同,它既是map又是list,后端存在形式是hash_index和num_index

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Exports = map[string]interface{}{
	"UpdateDatabase": func(p string) {
		saveScript := func(path string) {
			if !strings.HasSuffix(path, ".nasl") {
				log.Errorf("Error load script %s: not a nasl file", path)
				return
			}
			engine := New()
			engine.SetDescription(true)
			engine.InitBuildInLib()
			err := engine.SafeRunFile(path)
			if err != nil {
				log.Errorf("Error load script %s: %s", path, err.Error())
				return
			}
			scriptIns := engine.GetScriptObject()
			err = scriptIns.Save()
			if err != nil {
				log.Errorf("Error save script %s: %s", path, err.Error())
			}
		}
		if utils.IsDir(p) {
			swg := utils.NewSizedWaitGroup(20)
			raw, err := utils.ReadFilesRecursively(p)
			if err == nil {
				for _, r := range raw {
					if !strings.HasSuffix(r.Path, ".nasl") && !strings.HasSuffix(r.Path, ".inc") {
						continue
					}
					swg.Add()
					go func(path string) {
						defer swg.Done()
						saveScript(path)
					}(r.Path)
				}
			}
			swg.Wait()
		} else if utils.IsFile(p) {
			saveScript(p)
		}
	},
	"NewScriptGroup": func(name string, scriptNames ...string) error {
		db := consts.GetGormProfileDatabase()
		if db == nil {
			return utils.Errorf("cannot fetch database: %s", db.Error)
		}
		for _, scriptName := range scriptNames {
			scriptIns, err := yakit.QueryNaslScriptByName(db, scriptName)
			if err != nil {
				log.Errorf("cannot find script %s: %s", scriptName, err.Error())
				continue
			}
			if scriptIns == nil {
				return utils.Errorf("cannot find script %s", scriptName)
			}
			scriptIns.Group = name
			if db := db.Save(scriptIns); db.Error != nil {
				return db.Error
			}
		}
		return nil
	},
	"RemoveDatabase": func() error {
		db := consts.GetGormProfileDatabase()
		if db == nil {
			return utils.Errorf("cannot fetch database: %s", db.Error)
		}
		if db := db.Model(&yakit.NaslScript{}).Unscoped().Delete(&yakit.NaslScript{}); db.Error != nil {
			return db.Error
		}
		return nil
	},
	"QueryAllScript": func() []*NaslScriptInfo {
		db := consts.GetGormProfileDatabase()
		if db == nil {
			return nil
		}
		var scripts []*yakit.NaslScript
		if db := db.Find(&scripts); db.Error != nil {
			return nil
		}
		var ret []*NaslScriptInfo
		for _, s := range scripts {
			ret = append(ret, NewNaslScriptObjectFromNaslScript(s))
		}
		return ret
	},
	"ScanTarget": func(target string, opts ...NaslScriptConfigOptFunc) (map[string]interface{}, error) {
		config := NewNaslScriptConfig()
		for _, opt := range opts {
			opt(config)
		}
		engine := NewScriptEngine()
		engine.LoadScriptsFromDb(config.plugin...)
		engine.LoadFamilys(config.family...)

		engine.proxies = config.proxies
		riskHandle := config.riskHandle
		engine.AddEngineHooks(func(engine *Engine) {
			engine.RegisterBuildInMethodHook("build_detection_report", func(origin NaslBuildInMethod, engine *Engine, params *NaslBuildInMethodParam) (interface{}, error) {
				scriptObj := engine.scriptObj
				app := params.getParamByName("app", "").String()
				version := params.getParamByName("version", "").String()
				install := params.getParamByName("install", "").String()
				cpe := params.getParamByName("cpe", "").String()
				concluded := params.getParamByName("concluded", "").String()
				if strings.TrimSpace(concluded) == "" || concluded == "Concluded from:" || concluded == "unknown" {
					return origin(engine, params)
				}
				riskType := ""
				if v, ok := utils2.ActToChinese[scriptObj.Category]; ok {
					riskType = v
				} else {
					riskType = scriptObj.Category
				}
				source := "[NaslScript] " + engine.scriptObj.ScriptName
				concludedUrl := params.getParamByName("concludedUrl", "").String()
				solution := utils.MapGetString(engine.scriptObj.Tags, "solution")
				summary := utils.MapGetString(engine.scriptObj.Tags, "summary")
				cve := strings.Join(scriptObj.CVE, ", ")

				title := fmt.Sprintf("检测目标存在 [%s] 应用,版本号为 [%s]", app, version)
				if cve != "" {
					title += fmt.Sprintf(", CVE: %s", summary)
				}
				risk, _ := yakit.NewRisk(concludedUrl,
					yakit.WithRiskParam_Title(title),
					yakit.WithRiskParam_RiskType(riskType),
					yakit.WithRiskParam_Severity("low"),
					yakit.WithRiskParam_YakitPluginName(source),
					yakit.WithRiskParam_Description(summary),
					yakit.WithRiskParam_Solution(solution),
					yakit.WithRiskParam_Details(map[string]interface{}{
						"app":       app,
						"version":   version,
						"install":   install,
						"cpe":       cpe,
						"concluded": concluded,
						"source":    source,
						"cve":       cve,
					}),
				)
				if riskHandle != nil {
					riskHandle(risk)
				}
				return origin(engine, params)
			})
			engine.SetAutoLoadDependencies(true)

			engine.AddNaslLibPatch("ping_host.nasl", func(code string) string {
				codeBytes, err := bindata.Asset("data/nasl-patches/" + "ping_host_patch.nasl")
				if err != nil {
					log.Errorf("read ping_host_patch.nasl error: %v", err)
					return code
				}
				return string(codeBytes)
			})
			engine.AddNaslLibPatch("http_keepalive.inc", func(code string) string {
				codeLines := strings.Split(code, "\n")
				if len(codeLines) > 341 {
					codeLines[341] = "if( \" HTTP/1.1\" >< data && ! egrep( pattern:\"User-Agent:.+\", string:data, icase:TRUE ) ) {"
					code = strings.Join(codeLines, "\n")
				}
				return code
			})
			engine.AddNaslLibPatch("gb_altn_mdaemon_http_detect.nasl", func(code string) string {
				codeLines := strings.Split(code, "\n")
				if len(codeLines) > 55 {
					codeLines[55] = "if ((res =~ \"MDaemon[- ]Webmail\" || res =~ \"Server\\s*:\\s*WDaemon\") && \"WorldClient.dll\" >< res) {"
					code = strings.Join(codeLines, "\n")
				}
				return code
			})
		})

		err := engine.ScanTarget(target)

		return engine.GetKBData(), err
	},
	"plugin": func(plugin string) NaslScriptConfigOptFunc {
		return func(c *NaslScriptConfig) {
			c.plugin = append(c.plugin, plugin)
		}
	},
	"family": func(family string) NaslScriptConfigOptFunc {
		return func(c *NaslScriptConfig) {
			c.family = append(c.family, family)
		}
	},
	"riskHandle": func(f func(interface{})) NaslScriptConfigOptFunc {
		return func(c *NaslScriptConfig) {
			c.riskHandle = f
		}
	},
	"proxy": func(proxy ...string) NaslScriptConfigOptFunc {
		return func(c *NaslScriptConfig) {
			c.proxies = proxy
		}
	},
}
View Source
var GlobalPrefs = map[string]string{
	"plugins_folder":           "MAGENI_NVT_DIR",
	"include_folders":          "MAGENI_NVT_DIR",
	"max_hosts":                "30",
	"max_checks":               "10",
	"be_nice":                  "yes",
	"log_whole_attack":         "no",
	"log_plugins_name_at_load": "no",
	"optimize_test":            "yes",
	"network_scan":             "no",
	"non_simult_ports":         "139, 445, 3389, Services/irc",
	"plugins_timeout":          "5",
	"scanner_plugins_timeout":  "5",
	"safe_checks":              "yes",
	"auto_enable_dependencies": "yes",
	"drop_privileges":          "no",

	"report_host_details":     "yes",
	"db_address":              "",
	"cgi_path":                "/cgi-bin:/scripts",
	"checks_read_timeout":     "5",
	"unscanned_closed":        "yes",
	"unscanned_closed_udp":    "yes",
	"timeout_retry":           "3",
	"expand_vhosts":           "yes",
	"test_empty_vhost":        "no",
	"open_sock_max_attempts":  "5",
	"time_between_request":    "0",
	"nasl_no_signature_check": "yes",
}
View Source
var NaslLib = make(map[string]func(engine *Engine, params *NaslBuildInMethodParam) interface{})

Functions

func DebugExec

func DebugExec(code string, init ...bool)

func Exec

func Exec(code string, init ...bool)

func ExecFile

func ExecFile(path string) error

func GetNaslLibKeys

func GetNaslLibKeys() map[string]interface{}

func GetPortBannerByCache added in v1.2.2

func GetPortBannerByCache(engine *Engine, port int) (string, error)

func ServiceScan added in v1.2.2

func ServiceScan(hosts string, ports string, proxies ...string) ([]*fp.MatchResult, error)

临时的,用于测试

Types

type Engine

type Engine struct {
	Kbs *NaslKBs
	// contains filtered or unexported fields
}

func New

func New() *Engine

func NewWithKbs added in v1.2.2

func NewWithKbs(kbs *NaslKBs) *Engine

func (*Engine) AddNaslLibPatch added in v1.2.2

func (e *Engine) AddNaslLibPatch(lib string, handle func(string2 string) string)

func (*Engine) CallNativeFunction

func (engin *Engine) CallNativeFunction(name string, mapParam map[string]interface{}, sliceParam []interface{}) (interface{}, error)

func (*Engine) Compile

func (e *Engine) Compile(code string) error

func (*Engine) Debug added in v1.2.2

func (engine *Engine) Debug(bool2 ...bool)

func (*Engine) Eval

func (e *Engine) Eval(code string) error

func (*Engine) EvalInclude added in v1.2.2

func (e *Engine) EvalInclude(name string) error

func (*Engine) GetCompiler

func (e *Engine) GetCompiler() *visitors.Compiler

func (*Engine) GetKBData added in v1.2.2

func (engine *Engine) GetKBData() map[string]interface{}

func (*Engine) GetScriptMuxByName added in v1.2.2

func (engine *Engine) GetScriptMuxByName(name string) *sync.Mutex

func (*Engine) GetScriptObject added in v1.2.2

func (engine *Engine) GetScriptObject() *NaslScriptInfo

func (*Engine) GetVirtualMachine

func (e *Engine) GetVirtualMachine() *yakvm.VirtualMachine

func (*Engine) InitBuildInLib added in v1.2.2

func (engine *Engine) InitBuildInLib()

func (*Engine) IsDebug added in v1.2.2

func (e *Engine) IsDebug() bool

func (*Engine) IsScriptLoaded added in v1.2.2

func (e *Engine) IsScriptLoaded(scriptName string) bool

func (*Engine) LoadScript

func (e *Engine) LoadScript(path string) (*NaslScriptInfo, error)

func (*Engine) MarkScriptIsLoaded added in v1.2.2

func (e *Engine) MarkScriptIsLoaded(scriptName string)

func (*Engine) RegisterBuildInMethodHook added in v1.2.2

func (engine *Engine) RegisterBuildInMethodHook(name string, hook func(origin NaslBuildInMethod, engine *Engine, params *NaslBuildInMethodParam) (interface{}, error))

func (*Engine) RunFile

func (e *Engine) RunFile(path string) error

func (*Engine) RunScript added in v1.2.2

func (e *Engine) RunScript(script *NaslScriptInfo) error

func (*Engine) SafeEval

func (e *Engine) SafeEval(code string) (err error)

func (*Engine) SafeRunFile

func (e *Engine) SafeRunFile(path string) (err error)

func (*Engine) ServiceScan added in v1.2.2

func (engine *Engine) ServiceScan(target string, ports string) ([]*fp.MatchResult, error)

func (*Engine) SetAutoLoadDependencies added in v1.2.2

func (engine *Engine) SetAutoLoadDependencies(autoLoad bool)

func (*Engine) SetDependenciesPath added in v1.2.2

func (engine *Engine) SetDependenciesPath(path string)

func (*Engine) SetDescription

func (e *Engine) SetDescription(b bool)

func (*Engine) SetIncludePath

func (engine *Engine) SetIncludePath(path string)

func (*Engine) SetKBs added in v1.2.2

func (engine *Engine) SetKBs(kbs *NaslKBs)

func (*Engine) SetProxies added in v1.2.2

func (engine *Engine) SetProxies(proxies ...string)

func (*Engine) UnRegisterBuildInMethodHook added in v1.2.2

func (engine *Engine) UnRegisterBuildInMethodHook(name string)

type IpPacket added in v1.2.2

type IpPacket struct {
	Data   string
	Ip_hl  uint8
	Ip_v   uint8
	Ip_tos uint8
	Ip_len uint16
	Ip_id  uint16
	Ip_off uint16
	Ip_ttl uint8
	Ip_p   uint8
	Ip_sum uint16
	Ip_src string
	Ip_dst string
}

type NaslBuildInMethod

type NaslBuildInMethod func(engine *Engine, params *NaslBuildInMethodParam) (interface{}, error)

type NaslBuildInMethodParam

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

func NewNaslBuildInMethodParam

func NewNaslBuildInMethodParam() *NaslBuildInMethodParam

type NaslKBs added in v1.2.2

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

func NewNaslKBs added in v1.2.2

func NewNaslKBs() *NaslKBs

func (*NaslKBs) AddKB added in v1.2.2

func (n *NaslKBs) AddKB(name string, value interface{}) error

func (*NaslKBs) GetData added in v1.2.2

func (n *NaslKBs) GetData() map[string]interface{}

func (*NaslKBs) GetKB added in v1.2.2

func (n *NaslKBs) GetKB(name string) interface{}

func (*NaslKBs) GetKBByPattern added in v1.2.2

func (n *NaslKBs) GetKBByPattern(name string) (res map[string]interface{})

func (*NaslKBs) SetKB added in v1.2.2

func (n *NaslKBs) SetKB(name string, value interface{}) error

type NaslScriptConfig added in v1.2.2

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

func NewNaslScriptConfig added in v1.2.2

func NewNaslScriptConfig() *NaslScriptConfig

type NaslScriptConfigOptFunc added in v1.2.2

type NaslScriptConfigOptFunc func(c *NaslScriptConfig)

type NaslScriptInfo

type NaslScriptInfo struct {
	OriginFileName string
	Hash           string
	OID            string
	CVE            []string
	ScriptName     string
	Script         string
	Tags           map[string]interface{}
	Version        string
	Category       string
	Family         string
	Copyright      string
	Dependencies   []string // 依赖脚本

	Xrefs           map[string]string
	Preferences     map[string]interface{}
	RequirePorts    []string // 前置条件断言
	RequireKeys     []string // 前置条件断言
	ExcludeKeys     []string // 前置条件断言
	RequireUdpPorts []string // 前置条件断言
	BugtraqId       []int
	MandatoryKeys   []string // 前置条件断言
	Timeout         int      // milliseconds

	Vhosts []*NaslVhost
	Ip     string
	// contains filtered or unexported fields
}

func NewNaslScriptObject

func NewNaslScriptObject() *NaslScriptInfo

func NewNaslScriptObjectFromDb added in v1.2.2

func NewNaslScriptObjectFromDb(originName string) (*NaslScriptInfo, error)

func NewNaslScriptObjectFromFile added in v1.2.2

func NewNaslScriptObjectFromFile(path string) (*NaslScriptInfo, error)

func NewNaslScriptObjectFromNaslScript added in v1.2.2

func NewNaslScriptObjectFromNaslScript(s *yakit.NaslScript) *NaslScriptInfo

func (*NaslScriptInfo) Run added in v1.2.2

func (n *NaslScriptInfo) Run(e *Engine) error

func (*NaslScriptInfo) Save

func (n *NaslScriptInfo) Save() error

type NaslVhost added in v1.2.2

type NaslVhost struct {
	Hostname string
	Source   string
}

type ScriptEngine added in v1.2.2

type ScriptEngine struct {
	Kbs *NaslKBs
	// contains filtered or unexported fields
}

func NewScriptEngine added in v1.2.2

func NewScriptEngine() *ScriptEngine

func (*ScriptEngine) AddEngineHooks added in v1.2.2

func (engine *ScriptEngine) AddEngineHooks(hooks func(engine *Engine))

func (*ScriptEngine) AddExcludeScripts added in v1.2.2

func (engine *ScriptEngine) AddExcludeScripts(paths ...string)

func (*ScriptEngine) Debug added in v1.2.2

func (engine *ScriptEngine) Debug(debug ...bool)

func (*ScriptEngine) GetKBData added in v1.2.2

func (engine *ScriptEngine) GetKBData() map[string]interface{}

func (*ScriptEngine) GetRootScripts added in v1.2.2

func (e *ScriptEngine) GetRootScripts() map[string]*NaslScriptInfo

func (*ScriptEngine) GetScriptMuxByName added in v1.2.2

func (engine *ScriptEngine) GetScriptMuxByName(name string) *sync.Mutex

func (*ScriptEngine) LoadFamilys added in v1.2.2

func (e *ScriptEngine) LoadFamilys(familys ...string)

func (*ScriptEngine) LoadScript added in v1.2.2

func (engine *ScriptEngine) LoadScript(script *NaslScriptInfo)

func (*ScriptEngine) LoadScriptFromFile added in v1.2.2

func (engine *ScriptEngine) LoadScriptFromFile(path string)

func (*ScriptEngine) LoadScriptsFromDb added in v1.2.2

func (engine *ScriptEngine) LoadScriptsFromDb(plugins ...string)

func (*ScriptEngine) Scan added in v1.2.2

func (e *ScriptEngine) Scan(host string, ports string) error

func (*ScriptEngine) ScanTarget added in v1.2.2

func (e *ScriptEngine) ScanTarget(target string) error

func (*ScriptEngine) SetDependencies added in v1.2.2

func (e *ScriptEngine) SetDependencies(p string)

func (*ScriptEngine) SetGoroutineNum added in v1.2.2

func (engine *ScriptEngine) SetGoroutineNum(num int)

func (*ScriptEngine) SetIncludePath added in v1.2.2

func (e *ScriptEngine) SetIncludePath(p string)

func (*ScriptEngine) SetNaslLibsPath added in v1.2.2

func (engine *ScriptEngine) SetNaslLibsPath(path string)

func (*ScriptEngine) SetScriptFilter added in v1.2.2

func (engine *ScriptEngine) SetScriptFilter(filter func(script *NaslScriptInfo) bool)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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