Best Syzkaller code snippet using osutil.Sandbox
kvm.go
Source:kvm.go
1// Copyright 2015 syzkaller project authors. All rights reserved.2// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.3// Package kvm provides VMs based on lkvm (kvmtool) virtualization.4// It is not well tested.5package kvm6import (7 "fmt"8 "os"9 "os/exec"10 "path/filepath"11 "runtime"12 "strconv"13 "sync"14 "time"15 "github.com/google/syzkaller/pkg/config"16 "github.com/google/syzkaller/pkg/log"17 "github.com/google/syzkaller/pkg/osutil"18 "github.com/google/syzkaller/vm/vmimpl"19)20const (21 hostAddr = "192.168.33.1"22)23func init() {24 vmimpl.Register("kvm", ctor, true)25}26type Config struct {27 Count int // number of VMs to use28 Lkvm string // lkvm binary name29 Kernel string // e.g. arch/x86/boot/bzImage30 Cmdline string // kernel command line31 CPU int // number of VM CPUs32 Mem int // amount of VM memory in MBs33}34type Pool struct {35 env *vmimpl.Env36 cfg *Config37}38type instance struct {39 cfg *Config40 sandbox string41 sandboxPath string42 lkvm *exec.Cmd43 readerC chan error44 waiterC chan error45 debug bool46 mu sync.Mutex47 outputB []byte48 outputC chan []byte49}50func ctor(env *vmimpl.Env) (vmimpl.Pool, error) {51 cfg := &Config{52 Count: 1,53 Lkvm: "lkvm",54 }55 if err := config.LoadData(env.Config, cfg); err != nil {56 return nil, fmt.Errorf("failed to parse kvm vm config: %v", err)57 }58 if cfg.Count < 1 || cfg.Count > 128 {59 return nil, fmt.Errorf("invalid config param count: %v, want [1, 128]", cfg.Count)60 }61 if env.Debug && cfg.Count > 1 {62 log.Logf(0, "limiting number of VMs from %v to 1 in debug mode", cfg.Count)63 cfg.Count = 164 }65 if env.Image != "" {66 return nil, fmt.Errorf("lkvm does not support custom images")67 }68 if _, err := exec.LookPath(cfg.Lkvm); err != nil {69 return nil, err70 }71 if !osutil.IsExist(cfg.Kernel) {72 return nil, fmt.Errorf("kernel file '%v' does not exist", cfg.Kernel)73 }74 if cfg.CPU < 1 || cfg.CPU > 1024 {75 return nil, fmt.Errorf("invalid config param cpu: %v, want [1-1024]", cfg.CPU)76 }77 if cfg.Mem < 128 || cfg.Mem > 1048576 {78 return nil, fmt.Errorf("invalid config param mem: %v, want [128-1048576]", cfg.Mem)79 }80 cfg.Kernel = osutil.Abs(cfg.Kernel)81 pool := &Pool{82 cfg: cfg,83 env: env,84 }85 return pool, nil86}87func (pool *Pool) Count() int {88 return pool.cfg.Count89}90func (pool *Pool) Create(workdir string, index int) (vmimpl.Instance, error) {91 sandbox := fmt.Sprintf("syz-%v", index)92 inst := &instance{93 cfg: pool.cfg,94 sandbox: sandbox,95 sandboxPath: filepath.Join(os.Getenv("HOME"), ".lkvm", sandbox),96 debug: pool.env.Debug,97 }98 closeInst := inst99 defer func() {100 if closeInst != nil {101 closeInst.Close()102 }103 }()104 os.RemoveAll(inst.sandboxPath)105 os.Remove(inst.sandboxPath + ".sock")106 out, err := osutil.Command(inst.cfg.Lkvm, "setup", sandbox).CombinedOutput()107 if err != nil {108 return nil, fmt.Errorf("failed to lkvm setup: %v\n%s", err, out)109 }110 scriptPath := filepath.Join(workdir, "script.sh")111 if err := osutil.WriteExecFile(scriptPath, []byte(script)); err != nil {112 return nil, fmt.Errorf("failed to create temp file: %v", err)113 }114 rpipe, wpipe, err := osutil.LongPipe()115 if err != nil {116 return nil, fmt.Errorf("failed to create pipe: %v", err)117 }118 inst.lkvm = osutil.Command("taskset", "-c", strconv.Itoa(index%runtime.NumCPU()),119 inst.cfg.Lkvm, "sandbox",120 "--disk", inst.sandbox,121 "--kernel", inst.cfg.Kernel,122 "--params", "slub_debug=UZ "+inst.cfg.Cmdline,123 "--mem", strconv.Itoa(inst.cfg.Mem),124 "--cpus", strconv.Itoa(inst.cfg.CPU),125 "--network", "mode=user",126 "--sandbox", scriptPath,127 )128 inst.lkvm.Stdout = wpipe129 inst.lkvm.Stderr = wpipe130 if err := inst.lkvm.Start(); err != nil {131 rpipe.Close()132 wpipe.Close()133 return nil, fmt.Errorf("failed to start lkvm: %v", err)134 }135 // Start output reading goroutine.136 inst.readerC = make(chan error)137 go func() {138 var buf [64 << 10]byte139 for {140 n, err := rpipe.Read(buf[:])141 if n != 0 {142 if inst.debug {143 os.Stdout.Write(buf[:n])144 os.Stdout.Write([]byte{'\n'})145 }146 inst.mu.Lock()147 inst.outputB = append(inst.outputB, buf[:n]...)148 if inst.outputC != nil {149 select {150 case inst.outputC <- inst.outputB:151 inst.outputB = nil152 default:153 }154 }155 inst.mu.Unlock()156 time.Sleep(time.Millisecond)157 }158 if err != nil {159 rpipe.Close()160 inst.readerC <- err161 return162 }163 }164 }()165 // Wait for the lkvm asynchronously.166 inst.waiterC = make(chan error, 1)167 go func() {168 err := inst.lkvm.Wait()169 wpipe.Close()170 inst.waiterC <- err171 }()172 // Wait for the script to start serving.173 _, errc, err := inst.Run(10*time.Minute, nil, "mount -t debugfs none /sys/kernel/debug/")174 if err == nil {175 err = <-errc176 }177 if err != nil {178 return nil, fmt.Errorf("failed to run script: %v", err)179 }180 closeInst = nil181 return inst, nil182}183func (inst *instance) Close() {184 if inst.lkvm != nil {185 inst.lkvm.Process.Kill()186 err := <-inst.waiterC187 inst.waiterC <- err // repost it for waiting goroutines188 <-inst.readerC189 }190 os.RemoveAll(inst.sandboxPath)191 os.Remove(inst.sandboxPath + ".sock")192}193func (inst *instance) Forward(port int) (string, error) {194 return fmt.Sprintf("%v:%v", hostAddr, port), nil195}196func (inst *instance) Copy(hostSrc string) (string, error) {197 vmDst := filepath.Join("/", filepath.Base(hostSrc))198 dst := filepath.Join(inst.sandboxPath, vmDst)199 if err := osutil.CopyFile(hostSrc, dst); err != nil {200 return "", err201 }202 if err := os.Chmod(dst, 0777); err != nil {203 return "", err204 }205 return vmDst, nil206}207func (inst *instance) Run(timeout time.Duration, stop <-chan bool, command string) (208 <-chan []byte, <-chan error, error) {209 outputC := make(chan []byte, 10)210 errorC := make(chan error, 1)211 inst.mu.Lock()212 inst.outputB = nil213 inst.outputC = outputC214 inst.mu.Unlock()215 cmdFile := filepath.Join(inst.sandboxPath, "/syz-cmd")216 tmpFile := cmdFile + "-tmp"217 if err := osutil.WriteExecFile(tmpFile, []byte(command)); err != nil {218 return nil, nil, err219 }220 if err := osutil.Rename(tmpFile, cmdFile); err != nil {221 return nil, nil, err222 }223 signal := func(err error) {224 inst.mu.Lock()225 if inst.outputC == outputC {226 inst.outputB = nil227 inst.outputC = nil228 }229 inst.mu.Unlock()230 errorC <- err231 }232 go func() {233 timeoutTicker := time.NewTicker(timeout)234 secondTicker := time.NewTicker(time.Second)235 var resultErr error236 loop:237 for {238 select {239 case <-timeoutTicker.C:240 resultErr = vmimpl.ErrTimeout241 break loop242 case <-stop:243 resultErr = vmimpl.ErrTimeout244 break loop245 case <-secondTicker.C:246 if !osutil.IsExist(cmdFile) {247 resultErr = nil248 break loop249 }250 case err := <-inst.waiterC:251 inst.waiterC <- err // repost it for Close252 resultErr = fmt.Errorf("lkvm exited")253 break loop254 }255 }256 signal(resultErr)257 timeoutTicker.Stop()258 secondTicker.Stop()259 }()260 return outputC, errorC, nil261}262func (inst *instance) Diagnose() ([]byte, bool) {263 return nil, false264}265const script = `#! /bin/bash266while true; do267 if [ -e "/syz-cmd" ]; then268 /syz-cmd269 rm -f /syz-cmd270 else271 sleep 1272 fi273done274`...
kernel.go
Source:kernel.go
...23 configFile := filepath.Join(dir, ".config")24 if err := osutil.CopyFile(config, configFile); err != nil {25 return fmt.Errorf("failed to write config file: %v", err)26 }27 if err := osutil.SandboxChown(configFile); err != nil {28 return err29 }30 cmd := osutil.Command("make", "olddefconfig")31 if err := osutil.Sandbox(cmd, true, true); err != nil {32 return err33 }34 cmd.Dir = dir35 if _, err := osutil.Run(10*time.Minute, cmd); err != nil {36 return err37 }38 // We build only bzImage as we currently don't use modules.39 cpu := strconv.Itoa(runtime.NumCPU())40 cmd = osutil.Command("make", "bzImage", "-j", cpu, "CC="+compiler)41 if err := osutil.Sandbox(cmd, true, true); err != nil {42 return err43 }44 cmd.Dir = dir45 // Build of a large kernel can take a while on a 1 CPU VM.46 _, err := osutil.Run(3*time.Hour, cmd)47 return err48}49func Clean(dir string) error {50 cmd := osutil.Command("make", "distclean")51 if err := osutil.Sandbox(cmd, true, true); err != nil {52 return err53 }54 cmd.Dir = dir55 _, err := osutil.Run(10*time.Minute, cmd)56 return err57}58// CreateImage creates a disk image that is suitable for syzkaller.59// Kernel is taken from kernelDir, userspace system is taken from userspaceDir.60// If cmdlineFile is not empty, contents of the file are appended to the kernel command line.61// If sysctlFile is not empty, contents of the file are appended to the image /etc/sysctl.conf.62// Produces image and root ssh key in the specified files.63func CreateImage(kernelDir, userspaceDir, cmdlineFile, sysctlFile, image, sshkey string) error {64 tempDir, err := ioutil.TempDir("", "syz-build")65 if err != nil {...
Sandbox
Using AI Code Generation
1import (2func main() {3 cmd := exec.Command("/bin/bash")4 f, err := pty.Start(cmd)5 if err != nil {6 panic(err)7 }8 defer f.Close()9 if err := cmd.Wait(); err != nil {10 fmt.Println("Command finished with error: ", err)11 }12}
Sandbox
Using AI Code Generation
1import (2func main() {3 user, err := user.Current()4 if err != nil {5 panic(err)6 }7 cmd := exec.Command("bash")8 gid, err := os.Getgid()9 if err != nil {10 panic(err)11 }12 sandbox, err := osutil.NewSandbox(osutil.SandboxOptions{13 Uid: uint32(user.Uid),14 Gid: uint32(user.Gid),15 GidList: []uint32{uint32(gid)},16 })17 if err != nil {18 panic(err)19 }20 cmd.SysProcAttr = &syscall.SysProcAttr{21 }22 if err := cmd.Run(); err != nil {23 panic(err)24 }25}
Sandbox
Using AI Code Generation
1import (2func main() {3 golenv.Load()4 fmt.Println(golosutil.Sandbox("pwd"))5}6import (7func main() {8 golenv.Load()9 fmt.Println(golosutil.Sandbox("ls -l"))10}11import (12func main() {13 golenv.Load()14 fmt.Println(golosutil.Sandbox("cat /etc/hosts"))15}16import (17func main() {18 golenv.Load()19 fmt.Println(golosutil.Sandbox("ls -l /etc"))20}21import (22func main() {23 golenv.Load()24 fmt.Println(golosutil.Sandbox("cat /etc/passwd"))25}26import (27func main() {28 golenv.Load()29 fmt.Println(golosutil.Sandbox("ls -l /etc"))30}31import (
Sandbox
Using AI Code Generation
1import (2func main() {3 user, err := user.Current()4 if err != nil {5 panic(err)6 }7 shell := os.Getenv("SHELL")8 if shell == "" {9 }10 c := exec.Command(shell)11 c.Env = append(c.Env, fmt.Sprintf("USER=%s", user.Username))12 c.Env = append(c.Env, fmt.Sprintf("LOGNAME=%s", user.Username))13 c.Env = append(c.Env, fmt.Sprintf("HOME=%s", user.HomeDir))14 c.Env = append(c.Env, fmt.Sprintf("SHELL=%s", shell))15 c.Env = append(c.Env, fmt.Sprintf("TERM=%s", "xterm-256color"))
Sandbox
Using AI Code Generation
1import (2func main() {3 os := new(utils.OsUtil)4 sandbox := os.Sandbox("/tmp")5 sandbox.Create("test.txt")6 sandbox.WriteFile("test.txt", []byte("Hello World"), true)7 content := sandbox.ReadFile("test.txt")8 fmt.Println(string(content))9}
Sandbox
Using AI Code Generation
1import (2func main() {3 user, err := user.Current()4 if err != nil {5 panic(err)6 }7 wd, err := os.Getwd()8 if err != nil {9 panic(err)10 }11 exe, err := os.Executable()12 if err != nil {13 panic(err)14 }15 exeDir := filepath.Dir(exe)16 sandbox := osutil.NewSandbox()17 sandbox.AddDir(wd)18 sandbox.AddDir(exeDir)19 sandbox.AddDir(homeDir)20 cmd := exec.Command("ls", "-la")21 env := osutil.NewEnvironment()22 env.Set("PATH", "/bin:/usr/bin")23 err = sandbox.Run(cmd, env)24 if err != nil {25 panic(err)26 }27}28import (29func main() {30 user, err := user.Current()31 if err != nil {32 panic(err)33 }34 wd, err := os.Getwd()35 if err != nil {36 panic(err)37 }38 exe, err := os.Executable()39 if err != nil {40 panic(err)41 }42 exeDir := filepath.Dir(exe)
Sandbox
Using AI Code Generation
1import (2func main() {3 s := osutil.NewSandbox()4 s.AddPath("/bin")5 s.AddPath("/usr/bin")6 s.AddPath("/usr/local/bin")7 s.AddPath("/sbin")8 s.AddPath("/usr/sbin")9 s.AddPath("/usr/local/sbin")10 s.AddPath("/usr/local/go/bin")11 s.AddPath("/usr/local/go/pkg/tool/linux_amd64")12 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/link")13 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/asm")14 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/compile")15 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/cover")16 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/dist")17 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/doc")18 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/fix")19 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/nm")20 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/objdump")21 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/pack")22 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/pprof")23 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/trace")24 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/yacc")25 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6a")26 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6c")27 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6g")28 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6l")29 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6p")30 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6pack")31 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6prof")32 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/6trace")33 s.AddPath("/usr/local/go/pkg/tool/linux_amd64/8a")34 s.AddPath("/usr/local/go/pkg
Sandbox
Using AI Code Generation
1import "fmt"2import "os"3import "os/exec"4import "github.com/krishpranav/gosandbox/osutil"5func main() {6 cwd, err := os.Getwd()7 if err != nil {8 fmt.Println(err)9 }10 cmd := exec.Command("echo", "Hello World")11 err = osutil.Sandbox(cmd, cwd)12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println("Success!")16}17import "fmt"18import "os"19import "os/exec"20import "github.com/krishpranav/gosandbox/osutil"21func main() {22 cwd, err := os.Getwd()23 if err != nil {24 fmt.Println(err)25 }26 cmd := exec.Command("cat", "test.txt")27 err = osutil.Sandbox(cmd, cwd)28 if err != nil {29 fmt.Println(err)30 }31 fmt.Println("Success!")32}33import "fmt"34import "os"35import "os/exec"36import "github.com/krishpranav/gosandbox/osutil"37func main() {38 cwd, err := os.Getwd()39 if err != nil {40 fmt.Println(err)41 }42 cmd := exec.Command("ls", "-l")43 err = osutil.Sandbox(cmd, cwd)44 if err != nil {45 fmt.Println(err)46 }47 fmt.Println("Success!")48}
Sandbox
Using AI Code Generation
1func main() {2 osutil.Sandbox()3}4func main() {5 fmt.Println("Enter the command: ")6 fmt.Scanln(&cmd)7 osutil.Sandbox(cmd)8}9func main() {10 fmt.Println("Enter the command: ")11 fmt.Scanln(&cmd)12 osutil.Sandbox(cmd)13}14func main() {15 fmt.Println("Enter the command: ")16 fmt.Scanln(&cmd)17 osutil.Sandbox(cmd)18}19func main() {20 fmt.Println("Enter the command: ")21 fmt.Scanln(&cmd)22 osutil.Sandbox(cmd)23}24func main() {25 fmt.Println("Enter the command: ")26 fmt.Scanln(&cmd)27 osutil.Sandbox(cmd)28}29func main() {30 fmt.Println("Enter the command: ")31 fmt.Scanln(&cmd)32 osutil.Sandbox(cmd)33}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!