How to use checkNetlink method of main Package

Best Syzkaller code snippet using main.checkNetlink

check.go

Source:check.go Github

copy

Full Screen

...101 }102 warnings = append(warnings, warnings2...)103 }104 if netlink {105 warnings3, err := checkNetlink(OS, arch, obj, structTypes, locs)106 if err != nil {107 return nil, err108 }109 warnings = append(warnings, warnings3...)110 }111 for i := range warnings {112 warnings[i].arch = arch113 }114 return warnings, nil115}116const (117 WarnCompiler = "compiler"118 WarnNoSuchStruct = "no-such-struct"119 WarnBadStructSize = "bad-struct-size"120 WarnBadFieldNumber = "bad-field-number"121 WarnBadFieldSize = "bad-field-size"122 WarnBadFieldOffset = "bad-field-offset"123 WarnBadBitfield = "bad-bitfield"124 WarnNoNetlinkPolicy = "no-such-netlink-policy"125 WarnNetlinkBadSize = "bad-kernel-netlink-policy-size"126 WarnNetlinkBadAttrType = "bad-netlink-attr-type"127 WarnNetlinkBadAttr = "bad-netlink-attr"128)129type Warn struct {130 pos ast.Pos131 arch string132 typ string133 msg string134}135func writeWarnings(OS string, narches int, warnings []Warn) error {136 allFiles, err := filepath.Glob(filepath.Join("sys", OS, "*.warn"))137 if err != nil {138 return err139 }140 toRemove := make(map[string]bool)141 for _, file := range allFiles {142 toRemove[file] = true143 }144 byFile := make(map[string][]Warn)145 for _, warn := range warnings {146 // KVM is not supported on ARM completely.147 if OS == "linux" && warn.arch == "arm" && strings.HasSuffix(warn.pos.File, "_kvm.txt") {148 continue149 }150 byFile[warn.pos.File] = append(byFile[warn.pos.File], warn)151 }152 for file, warns := range byFile {153 sort.Slice(warns, func(i, j int) bool {154 w1, w2 := warns[i], warns[j]155 if w1.pos.Line != w2.pos.Line {156 return w1.pos.Line < w2.pos.Line157 }158 if w1.typ != w2.typ {159 return w1.typ < w2.typ160 }161 if w1.msg != w2.msg {162 return w1.msg < w2.msg163 }164 return w1.arch < w2.arch165 })166 buf := new(bytes.Buffer)167 for i := 0; i < len(warns); i++ {168 warn := warns[i]169 arch := warn.arch170 arches := []string{warn.arch}171 for i < len(warns)-1 && warn.msg == warns[i+1].msg {172 if arch != warns[i+1].arch {173 arch = warns[i+1].arch174 arches = append(arches, arch)175 }176 i++177 }178 archStr := ""179 // We do netlink checking only on amd64, so don't add arch.180 if len(arches) < narches && !strings.Contains(warn.typ, "netlink") {181 archStr = fmt.Sprintf(" [%v]", strings.Join(arches, ","))182 }183 fmt.Fprintf(buf, "%v: %v%v\n", warn.typ, warn.msg, archStr)184 }185 warnFile := file + ".warn"186 if err := osutil.WriteFile(warnFile, buf.Bytes()); err != nil {187 return err188 }189 delete(toRemove, warnFile)190 }191 for file := range toRemove {192 os.Remove(file)193 }194 return nil195}196func checkImpl(structs map[string]*dwarf.StructType, structTypes []prog.Type,197 locs map[string]*ast.Struct) ([]Warn, error) {198 var warnings []Warn199 for _, typ := range structTypes {200 name := typ.TemplateName()201 astStruct := locs[name]202 if astStruct == nil {203 continue204 }205 warns, err := checkStruct(typ, astStruct, structs[name])206 if err != nil {207 return nil, err208 }209 warnings = append(warnings, warns...)210 }211 return warnings, nil212}213func checkStruct(typ prog.Type, astStruct *ast.Struct, str *dwarf.StructType) ([]Warn, error) {214 var warnings []Warn215 warn := func(pos ast.Pos, typ, msg string, args ...interface{}) {216 warnings = append(warnings, Warn{pos: pos, typ: typ, msg: fmt.Sprintf(msg, args...)})217 }218 name := typ.TemplateName()219 if str == nil {220 // Varlen structs are frequently not described in kernel (not possible in C).221 if !typ.Varlen() {222 warn(astStruct.Pos, WarnNoSuchStruct, "%v", name)223 }224 return warnings, nil225 }226 if !typ.Varlen() && typ.Size() != uint64(str.ByteSize) {227 warn(astStruct.Pos, WarnBadStructSize, "%v: syz=%v kernel=%v", name, typ.Size(), str.ByteSize)228 }229 // TODO: handle unions, currently we should report some false errors.230 if _, ok := typ.(*prog.UnionType); ok || str.Kind == "union" {231 return warnings, nil232 }233 // TODO: we could also check enums (elements match corresponding flags in syzkaller).234 // TODO: we could also check values of literal constants (dwarf should have that, right?).235 // TODO: handle nested structs/unions, e.g.:236 // struct foo {237 // union {238 // ...239 // } bar;240 // };241 // should be matched with:242 // foo_bar [243 // ...244 // ]245 // TODO: consider making guesses about semantic types of fields,246 // e.g. if a name contains filedes/uid/pid/gid that may be the corresponding resource.247 ai := 0248 offset := uint64(0)249 for _, field := range typ.(*prog.StructType).Fields {250 if field.Type.Varlen() {251 ai = len(str.Field)252 break253 }254 if prog.IsPad(field.Type) {255 offset += field.Type.Size()256 continue257 }258 if ai < len(str.Field) {259 fld := str.Field[ai]260 pos := astStruct.Fields[ai].Pos261 desc := fmt.Sprintf("%v.%v", name, field.Name)262 if field.Name != fld.Name {263 desc += "/" + fld.Name264 }265 if field.Type.UnitSize() != uint64(fld.Type.Size()) {266 warn(pos, WarnBadFieldSize, "%v: syz=%v kernel=%v",267 desc, field.Type.UnitSize(), fld.Type.Size())268 }269 byteOffset := offset - field.Type.UnitOffset()270 if byteOffset != uint64(fld.ByteOffset) {271 warn(pos, WarnBadFieldOffset, "%v: syz=%v kernel=%v",272 desc, byteOffset, fld.ByteOffset)273 }274 // How would you define bitfield offset?275 // Offset of the beginning of the field from the beginning of the memory location, right?276 // No, DWARF defines it as offset of the end of the field from the end of the memory location.277 bitOffset := fld.Type.Size()*8 - fld.BitOffset - fld.BitSize278 if fld.BitSize == 0 {279 // And to make things even more interesting this calculation280 // does not work for normal variables.281 bitOffset = 0282 }283 if field.Type.BitfieldLength() != uint64(fld.BitSize) ||284 field.Type.BitfieldOffset() != uint64(bitOffset) {285 warn(pos, WarnBadBitfield, "%v: size/offset: syz=%v/%v kernel=%v/%v",286 desc, field.Type.BitfieldLength(), field.Type.BitfieldOffset(),287 fld.BitSize, bitOffset)288 }289 }290 ai++291 offset += field.Size()292 }293 if ai != len(str.Field) {294 warn(astStruct.Pos, WarnBadFieldNumber, "%v: syz=%v kernel=%v", name, ai, len(str.Field))295 }296 return warnings, nil297}298func parseDescriptions(OS, arch string) ([]prog.Type, map[string]*ast.Struct, []Warn, error) {299 errorBuf := new(bytes.Buffer)300 var warnings []Warn301 eh := func(pos ast.Pos, msg string) {302 warnings = append(warnings, Warn{pos: pos, typ: WarnCompiler, msg: msg})303 fmt.Fprintf(errorBuf, "%v: %v\n", pos, msg)304 }305 top := ast.ParseGlob(filepath.Join("sys", OS, "*.txt"), eh)306 if top == nil {307 return nil, nil, nil, fmt.Errorf("failed to parse txt files:\n%s", errorBuf.Bytes())308 }309 consts := compiler.DeserializeConstsGlob(filepath.Join("sys", OS, "*_"+arch+".const"), eh)310 if consts == nil {311 return nil, nil, nil, fmt.Errorf("failed to parse const files:\n%s", errorBuf.Bytes())312 }313 prg := compiler.Compile(top, consts, targets.Get(OS, arch), eh)314 if prg == nil {315 return nil, nil, nil, fmt.Errorf("failed to compile descriptions:\n%s", errorBuf.Bytes())316 }317 prog.RestoreLinks(prg.Syscalls, prg.Resources, prg.Types)318 locs := make(map[string]*ast.Struct)319 for _, decl := range top.Nodes {320 switch n := decl.(type) {321 case *ast.Struct:322 locs[n.Name.Name] = n323 case *ast.TypeDef:324 if n.Struct != nil {325 locs[n.Name.Name] = n.Struct326 }327 }328 }329 var structs []prog.Type330 for _, typ := range prg.Types {331 switch typ.(type) {332 case *prog.StructType, *prog.UnionType:333 structs = append(structs, typ)334 }335 }336 return structs, locs, warnings, nil337}338// Overall idea of netlink checking.339// Currnetly we check netlink policies for common detectable mistakes.340// First, we detect what looks like a netlink policy in our descriptions341// (these are structs/unions only with nlattr/nlnext/nlnetw fields).342// Then we find corresponding symbols (offset/size) in vmlinux using nm.343// Then we read elf headers and locate where these symbols are in the rodata section.344// Then read in the symbol data, which is an array of nla_policy structs.345// These structs allow to easily figure out type/size of attributes.346// Finally we compare our descriptions with the kernel policy description.347func checkNetlink(OS, arch, obj string, structTypes []prog.Type,348 locs map[string]*ast.Struct) ([]Warn, error) {349 if arch != "amd64" {350 // Netlink policies are arch-independent (?),351 // so no need to check all arches.352 // Also our definition of nlaPolicy below is 64-bit specific.353 return nil, nil354 }355 ef, err := elf.Open(obj)356 if err != nil {357 return nil, err358 }359 rodata := ef.Section(".rodata")360 if rodata == nil {361 return nil, fmt.Errorf("object file %v does not contain .rodata section", obj)362 }363 symb := symbolizer.NewSymbolizer(targets.Get(OS, arch))364 symbols, err := symb.ReadRodataSymbols(obj)365 if err != nil {366 return nil, err367 }368 var warnings []Warn369 structMap := make(map[string]prog.Type)370 for _, typ := range structTypes {371 structMap[typ.Name()] = typ372 }373 checkedAttrs := make(map[string]*checkAttr)374 for _, typ := range structTypes {375 warnings1, err := checkNetlinkStruct(locs, symbols, rodata, structMap, checkedAttrs, typ)376 if err != nil {377 return nil, err378 }379 warnings = append(warnings, warnings1...)380 }381 warnings = append(warnings, checkMissingAttrs(checkedAttrs)...)382 return warnings, nil383}384func checkNetlinkStruct(locs map[string]*ast.Struct, symbols map[string][]symbolizer.Symbol, rodata *elf.Section,385 structMap map[string]prog.Type, checkedAttrs map[string]*checkAttr, typ prog.Type) ([]Warn, error) {386 name := typ.TemplateName()387 astStruct := locs[name]388 if astStruct == nil {389 return nil, nil390 }391 var fields []prog.Field392 switch t := typ.(type) {393 case *prog.StructType:394 fields = t.Fields395 case *prog.UnionType:396 fields = t.Fields397 }398 if !isNetlinkPolicy(fields) {399 return nil, nil400 }401 kernelName := name402 var ss []symbolizer.Symbol403 // In some cases we split a single policy into multiple ones404 // (more precise description), so try to match our foo_bar_baz405 // with kernel foo_bar and foo as well.406 for kernelName != "" {407 ss = symbols[kernelName]408 if len(ss) != 0 {409 break410 }411 underscore := strings.LastIndexByte(kernelName, '_')412 if underscore == -1 {413 break414 }415 kernelName = kernelName[:underscore]416 }417 if len(ss) == 0 {418 return []Warn{{pos: astStruct.Pos, typ: WarnNoNetlinkPolicy, msg: name}}, nil419 }420 var warnings []Warn421 var warnings1 *[]Warn422 var policy1 []nlaPolicy423 var attrs1 map[int]bool424 // We may have several symbols with the same name (they frequently have internal linking),425 // in such case we choose the one that produces fewer warnings.426 for _, symb := range ss {427 if symb.Size == 0 || symb.Size%int(unsafe.Sizeof(nlaPolicy{})) != 0 {428 warnings = append(warnings, Warn{pos: astStruct.Pos, typ: WarnNetlinkBadSize,429 msg: fmt.Sprintf("%v (%v), size %v", kernelName, name, ss[0].Size)})430 continue431 }432 binary := make([]byte, symb.Size)433 addr := symb.Addr - rodata.Addr434 if _, err := rodata.ReadAt(binary, int64(addr)); err != nil {435 return nil, fmt.Errorf("failed to read policy %v (%v) at %v: %v",436 kernelName, name, symb.Addr, err)437 }438 policy := (*[1e6]nlaPolicy)(unsafe.Pointer(&binary[0]))[:symb.Size/int(unsafe.Sizeof(nlaPolicy{}))]439 warnings2, attrs2, err := checkNetlinkPolicy(structMap, typ, fields, astStruct, policy)440 if err != nil {441 return nil, err442 }443 if warnings1 == nil || len(*warnings1) > len(warnings2) {444 warnings1 = &warnings2445 policy1 = policy446 attrs1 = attrs2447 }448 }449 if warnings1 != nil {450 warnings = append(warnings, *warnings1...)451 ca := checkedAttrs[kernelName]452 if ca == nil {453 ca = &checkAttr{454 pos: astStruct.Pos,455 name: name,456 policy: policy1,457 attrs: make(map[int]bool),458 }459 checkedAttrs[kernelName] = ca460 }461 for attr := range attrs1 {462 ca.attrs[attr] = true463 }464 }465 return warnings, nil466}467type checkAttr struct {468 pos ast.Pos469 name string470 policy []nlaPolicy471 attrs map[int]bool472}473func checkMissingAttrs(checkedAttrs map[string]*checkAttr) []Warn {474 // Missing attribute checking is a bit tricky because we may split a single475 // kernel policy into several policies for better precision.476 // They have different names, but map to the same kernel policy.477 // We want to report a missing attribute iff it's missing in all copies of the policy.478 var warnings []Warn479 for _, ca := range checkedAttrs {480 var missing []int481 for i, pol := range ca.policy {482 // Ignore attributes that are not described in the policy483 // (some of them are unused at all, however there are cases where484 // they are not described but used as inputs, and these are actually485 // the worst ones).486 if !ca.attrs[i] && (pol.typ != NLA_UNSPEC && pol.typ != NLA_REJECT || pol.len != 0) {487 missing = append(missing, i)488 }489 }490 // If we miss too many, there is probably something else going on.491 if len(missing) != 0 && len(missing) <= 5 {492 warnings = append(warnings, Warn{493 pos: ca.pos,494 typ: WarnNetlinkBadAttr,495 msg: fmt.Sprintf("%v: missing attributes: %v", ca.name, missing),496 })497 }498 }499 return warnings500}501func isNetlinkPolicy(fields []prog.Field) bool {502 haveAttr := false503 for _, fld := range fields {504 field := fld.Type505 if prog.IsPad(field) {506 continue507 }508 if isNlattr(field) {509 haveAttr = true510 continue511 }512 if arr, ok := field.(*prog.ArrayType); ok {513 field = arr.Elem514 }515 if field1, ok := field.(*prog.StructType); ok {516 if isNetlinkPolicy(field1.Fields) {517 continue518 }519 }520 if field1, ok := field.(*prog.UnionType); ok {521 if isNetlinkPolicy(field1.Fields) {522 continue523 }524 }525 return false526 }527 return haveAttr528}529const (530 nlattrT = "nlattr_t"531 nlattrTT = "nlattr_tt"532)533func isNlattr(typ prog.Type) bool {534 name := typ.TemplateName()535 return name == nlattrT || name == nlattrTT536}537func checkNetlinkPolicy(structMap map[string]prog.Type, typ prog.Type, fields []prog.Field,538 astStruct *ast.Struct, policy []nlaPolicy) ([]Warn, map[int]bool, error) {539 var warnings []Warn540 warn := func(pos ast.Pos, typ, msg string, args ...interface{}) {541 warnings = append(warnings, Warn{pos: pos, typ: typ, msg: fmt.Sprintf(msg, args...)})542 }543 checked := make(map[int]bool)544 ai := 0545 for _, field := range fields {546 if prog.IsPad(field.Type) {547 continue548 }549 fld := astStruct.Fields[ai]550 ai++551 if !isNlattr(field.Type) {552 continue553 }554 ft := field.Type.(*prog.StructType)555 attr := int(ft.Fields[1].Type.(*prog.ConstType).Val)556 if attr >= len(policy) {557 warn(fld.Pos, WarnNetlinkBadAttrType, "%v.%v: type %v, kernel policy size %v",558 typ.TemplateName(), field.Name, attr, len(policy))559 continue560 }561 if checked[attr] {562 warn(fld.Pos, WarnNetlinkBadAttr, "%v.%v: duplicate attribute",563 typ.TemplateName(), field.Name)564 }565 checked[attr] = true566 w := checkNetlinkAttr(ft, policy[attr])567 if w != "" {568 warn(fld.Pos, WarnNetlinkBadAttr, "%v.%v: %v",569 typ.TemplateName(), field.Name, w)570 }571 }572 return warnings, checked, nil573}574func checkNetlinkAttr(typ *prog.StructType, policy nlaPolicy) string {575 payload := typ.Fields[2].Type576 if typ.TemplateName() == nlattrTT {577 payload = typ.Fields[4].Type578 }579 if warn := checkAttrType(typ, payload, policy); warn != "" {580 return warn581 }582 size, minSize, maxSize := attrSize(policy)583 payloadSize := minTypeSize(payload)584 if size != -1 && size != payloadSize {585 return fmt.Sprintf("bad size %v, expect %v", payloadSize, size)586 }587 if minSize != -1 && minSize > payloadSize {588 return fmt.Sprintf("bad size %v, expect min %v", payloadSize, minSize)...

Full Screen

Full Screen

checkNetlink

Using AI Code Generation

copy

Full Screen

1func main() {2 m.checkNetlink()3}4func main() {5 m.checkNetlink()6}7func main() {8 m.checkNetlink()9}10func main() {11 m.checkNetlink()12}13func main() {14 m.checkNetlink()15}16func main() {17 m.checkNetlink()18}19func main() {20 m.checkNetlink()21}22func main() {23 m.checkNetlink()24}25func main() {26 m.checkNetlink()27}28func main() {29 m.checkNetlink()30}31func main() {32 m.checkNetlink()33}34func main() {35 m.checkNetlink()36}37func main() {38 m.checkNetlink()39}40func main() {41 m.checkNetlink()42}43func main() {

Full Screen

Full Screen

checkNetlink

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m.checkNetlink()4}5import (6func main() {7 m.checkNetlink()8}9import (10func main() {11 m.checkNetlink()12}13import (14func main() {15 m.checkNetlink()16}17import (18func main() {19 m.checkNetlink()20}21import (22func main() {23 m.checkNetlink()24}25import (26func main() {27 m.checkNetlink()28}29import (30func main() {31 m.checkNetlink()32}33import (34func main() {35 m.checkNetlink()36}37import (38func main() {39 m.checkNetlink()40}41import (42func main() {43 m.checkNetlink()44}

Full Screen

Full Screen

checkNetlink

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 nl, err := netlink.NewHandle()4 if err != nil {5 fmt.Printf("Error %v", err)6 }7 defer nl.Delete()8 err = nl.LinkAdd(&netlink.Dummy{netlink.LinkAttrs{Name: "test"}})9 if err != nil {10 fmt.Printf("Error %v", err)11 }12 err = nl.LinkDel(&netlink.Dummy{netlink.LinkAttrs{Name: "test"}})13 if err != nil {14 fmt.Printf("Error %v", err)15 }16}17import (18func main() {19 nl, err := netlink.NewHandle()20 if err != nil {21 fmt.Printf("Error %v", err)22 }23 defer nl.Delete()24 err = nl.LinkAdd(&netlink.Dummy{netlink.LinkAttrs{Name: "test"}})25 if err != nil {26 fmt.Printf("Error %v", err)27 }28 err = nl.LinkDel(&netlink.Dummy{netlink.LinkAttrs{Name: "test"}})29 if err != nil {30 fmt.Printf("Error %v", err)31 }32}

Full Screen

Full Screen

checkNetlink

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if golnet.CheckNetlink() {4 fmt.Println("Netlink is available")5 } else {6 fmt.Println("Netlink not available")7 os.Exit(1)8 }9}10import (11func main() {12 if golnet.CheckDns() {13 fmt.Println("DNS is available")14 } else {15 fmt.Println("DNS not available")16 os.Exit(1)17 }18}19import (20func main() {21 if golnet.CheckHttp() {22 fmt.Println("Http is available")23 } else {24 fmt.Println("Http not available")25 os.Exit(1)26 }27}28import (29func main() {30 if golnet.CheckHttps() {31 fmt.Println("Https is available")32 } else {33 fmt.Println("Https not available")34 os.Exit(1)35 }36}37import (38func main() {39 if golnet.CheckFtp() {40 fmt.Println("Ftp is available")41 } else {42 fmt.Println("Ftp not available")43 os.Exit(1)44 }45}46import (47func main() {48 if golnet.CheckSsh() {49 fmt.Println("Ssh

Full Screen

Full Screen

checkNetlink

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m.checkNetlink()4 fmt.Println("Hello, playground")5}6import (7type main struct {8}9func (m *main) checkNetlink() {10 fmt.Println("Hello, playground")11}12import (13type main struct {14}15func (m *main) checkNetlink() {16 fmt.Println("Hello, playground")17}18import (19type main2 struct {20}21func main() {22 m.checkNetlink()23 fmt.Println("Hello, playground")24}25import (26type main struct {27}28func checkNetlink(m *main) {29 fmt.Println("Hello, playground")30}31func main() {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful