How to use Create method of gvisor Package

Best Syzkaller code snippet using gvisor.Create

runk.go

Source:runk.go Github

copy

Full Screen

...74 }75 k := &kernel.Kernel{76 Platform: p,77 }78 // Create memory file.79 mf, err := createMemoryFile()80 if err != nil {81 return errors.Wrap(err, "creating memory file")82 }83 k.SetMemoryFile(mf)84 vdso, err := loader.PrepareVDSO(nil, k)85 if err != nil {86 return errors.Wrap(err, "error creating vdso")87 }88 tk, err := kernel.NewTimekeeper(k, vdso.ParamPage.FileRange())89 if err != nil {90 return errors.Wrap(err, "error creating timekeeper")91 }92 tk.SetClocks(time.NewCalibratedClocks())93 networkStack, err := netStack(k, k, o.Network)94 if err != nil {95 return err96 }97 stack, ok := networkStack.(*hostinet.Stack)98 if ok {99 if err := stack.Configure(); err != nil {100 return err101 }102 }103 creds := auth.NewUserCredentials(104 auth.KUID(0),105 auth.KGID(0),106 nil,107 nil,108 auth.NewRootUserNamespace())109 if err = k.Init(kernel.InitKernelArgs{110 FeatureSet: cpuid.HostFeatureSet(),111 Timekeeper: tk,112 RootUserNamespace: creds.UserNamespace,113 NetworkStack: networkStack,114 ApplicationCores: uint(runtime.NumCPU()),115 Vdso: vdso,116 RootUTSNamespace: kernel.NewUTSNamespace("sbox", "sbox", creds.UserNamespace),117 RootIPCNamespace: kernel.NewIPCNamespace(creds.UserNamespace),118 RootAbstractSocketNamespace: kernel.NewAbstractSocketNamespace(),119 PIDNamespace: kernel.NewRootPIDNamespace(creds.UserNamespace),120 }); err != nil {121 return errors.Wrap(err, "error initializing kernel")122 }123 ls, err := limits.NewLinuxLimitSet()124 if err != nil {125 return err126 }127 // Create the process arguments.128 procArgs := kernel.CreateProcessArgs{129 Argv: o.Process.Args,130 Envv: []string{},131 WorkingDirectory: "/", // Defaults to '/' if empty.132 Credentials: creds,133 Umask: 0022,134 Limits: ls,135 MaxSymlinkTraversals: linux.MaxSymlinkTraversals,136 UTSNamespace: k.RootUTSNamespace(),137 IPCNamespace: k.RootIPCNamespace(),138 AbstractSocketNamespace: k.RootAbstractSocketNamespace(),139 ContainerID: "sbox",140 PIDNamespace: k.RootPIDNamespace(),141 }142 ctx := procArgs.NewContext(k)143 fdt, err := createFDTable(ctx, k, ls, o.Process.TTY, []int{0, 1, 2})144 if err != nil {145 return errors.Wrap(err, "error importing fds")146 }147 // CreateProcess takes a reference on fdTable if successful. We148 // won't need ours either way.149 procArgs.FDTable = fdt150 rootProcArgs := procArgs151 rootProcArgs.WorkingDirectory = "/"152 rootProcArgs.Credentials = auth.NewRootCredentials(creds.UserNamespace)153 rootProcArgs.Umask = 0022154 rootProcArgs.MaxSymlinkTraversals = linux.MaxSymlinkTraversals155 rootCtx := rootProcArgs.NewContext(k)156 followLinks := uint(linux.MaxSymlinkTraversals)157 mns, err := createMountNamespace(ctx, rootCtx, o.Mounts, &followLinks)158 if err != nil {159 return errors.Wrap(err, "error creating mounts")160 }161 rootProcArgs.MountNamespace = mns162 _, _, err = k.CreateProcess(rootProcArgs)163 if err != nil {164 return errors.Wrap(err, "failed to create init process")165 }166 tg := k.GlobalInit()167 if o.Process.TTY {168 ttyFile, _ := procArgs.FDTable.Get(0)169 defer ttyFile.DecRef()170 ttyfop := ttyFile.FileOperations.(*host.TTYFileOperations)171 // Set the foreground process group on the TTY to the global172 // init process group, since that is what we are about to173 // start running.174 ttyfop.InitForegroundProcessGroup(tg.ProcessGroup())175 }176 if err := k.Start(); err != nil {177 return err178 }179 k.WaitExited()180 return nil181}182func addSubmountOverlay(ctx context.Context, inode *fs.Inode, submounts []string) (*fs.Inode, error) {183 // There is no real filesystem backing this ramfs tree, so we pass in184 // "nil" here.185 msrc := fs.NewNonCachingMountSource(ctx, nil, fs.MountSourceFlags{})186 mountTree, err := ramfs.MakeDirectoryTree(ctx, msrc, submounts)187 if err != nil {188 return nil, errors.Wrap(err, "error creating mount tree")189 }190 overlayInode, err := fs.NewOverlayRoot(ctx, inode, mountTree, fs.MountSourceFlags{})191 if err != nil {192 return nil, errors.Wrap(err, "failed to make mount overlay")193 }194 return overlayInode, err195}196func createMountNamespace(userCtx context.Context, rootCtx context.Context, mounts []string, maxTraversals *uint) (*fs.MountNamespace, error) {197 rootInode, err := createRootMount(rootCtx, mounts)198 if err != nil {199 return nil, errors.Wrap(err, "failed to create root mount")200 }201 mns, err := fs.NewMountNamespace(userCtx, rootInode)202 if err != nil {203 return nil, errors.Wrap(err, "failed to create root mount namespace")204 }205 root := mns.Root()206 defer root.DecRef()207 proc, ok := fs.FindFilesystem("proc")208 if !ok {209 panic(fmt.Sprintf("could not find filesystem proc"))210 }211 ctx := rootCtx212 inode, err := proc.Mount(ctx, "none", fs.MountSourceFlags{}, "", nil)213 if err != nil {214 return nil, errors.Wrap(err, "failed to create mount with source")215 }216 dirent, err := mns.FindInode(ctx, root, root, "/proc", maxTraversals)217 if err != nil {218 return nil, errors.Wrap(err, "failed to find mount destination")219 }220 defer dirent.DecRef()221 if err := mns.Mount(ctx, dirent, inode); err != nil {222 return nil, errors.Wrap(err, "failed to mount at destination")223 }224 return mns, nil225}226func createRootMount(ctx context.Context, mounts []string) (*fs.Inode, error) {227 // First construct the filesystem from the spec.Root.228 mf := fs.MountSourceFlags{ReadOnly: false}229 var (230 rootInode, prevInode *fs.Inode231 err error232 )233 wd, err := os.Getwd()234 if err != nil {235 return nil, err236 }237 host, ok := fs.FindFilesystem("whitelistfs")238 if !ok {239 panic(fmt.Sprintf("could not find filesystem host"))240 }241 for i, m := range mounts {242 if !filepath.IsAbs(m) {243 m = filepath.Join(wd, m)244 }245 rootInode, err = host.Mount(ctx, "", mf, "root="+m, nil)246 if err != nil {247 return nil, errors.Wrap(err, "failed to generate root mount point")248 }249 if i != 0 {250 rootInode, err = fs.NewOverlayRoot(ctx, rootInode, prevInode, fs.MountSourceFlags{})251 if err != nil {252 return nil, errors.Wrap(err, "failed to make mount overlay")253 }254 }255 prevInode = rootInode256 }257 submounts := []string{"/dev", "/sys", "/proc", "/tmp"}258 rootInode, err = addSubmountOverlay(ctx, rootInode, submounts)259 if err != nil {260 return nil, errors.Wrap(err, "error adding submount overlay")261 }262 tmpfs, ok := fs.FindFilesystem("tmpfs")263 if !ok {264 panic(fmt.Sprintf("could not find filesystem tmpfs"))265 }266 upper, err := tmpfs.Mount(ctx, "upper", fs.MountSourceFlags{}, "", nil)267 if err != nil {268 return nil, errors.Wrap(err, "failed to create tmpfs overlay")269 }270 rootInode, err = fs.NewOverlayRoot(ctx, upper, rootInode, fs.MountSourceFlags{})271 if err != nil {272 return nil, errors.Wrap(err, "failed to make mount overlay")273 }274 return rootInode, nil275}276func createFDTable(ctx context.Context, k *kernel.Kernel, l *limits.LimitSet, console bool, stdioFDs []int) (*kernel.FDTable, error) {277 if len(stdioFDs) != 3 {278 return nil, errors.Errorf("stdioFDs should contain exactly 3 FDs (stdin, stdout, and stderr), but %d FDs received", len(stdioFDs))279 }280 fdm := k.NewFDTable()281 defer fdm.DecRef()282 mounter := fs.FileOwnerFromContext(ctx)283 // Maps sandbox FD to host FD.284 fdMap := map[int]int{285 0: stdioFDs[0],286 1: stdioFDs[1],287 2: stdioFDs[2],288 }289 var ttyFile *fs.File290 for appFD, hostFD := range fdMap {291 var appFile *fs.File292 if console && appFD < 3 {293 // Import the file as a host TTY file.294 if ttyFile == nil {295 var err error296 appFile, err = host.ImportFile(ctx, hostFD, mounter, true /* isTTY */)297 if err != nil {298 return nil, err299 }300 defer appFile.DecRef()301 // Remember this in the TTY file, as we will302 // use it for the other stdio FDs.303 ttyFile = appFile304 } else {305 // Re-use the existing TTY file, as all three306 // stdio FDs must point to the same fs.File in307 // order to share TTY state, specifically the308 // foreground process group id.309 appFile = ttyFile310 }311 } else {312 // Import the file as a regular host file.313 var err error314 appFile, err = host.ImportFile(ctx, hostFD, mounter, false /* isTTY */)315 if err != nil {316 return nil, err317 }318 defer appFile.DecRef()319 }320 // Add the file to the FD map.321 if err := fdm.NewFDAt(ctx, int32(appFD), appFile, kernel.FDFlags{}); err != nil {322 return nil, err323 }324 }325 fdm.IncRef()326 return fdm, nil327}328func createMemoryFile() (*pgalloc.MemoryFile, error) {329 const memfileName = "runsc-memory"330 memfd, err := memutil.CreateMemFD(memfileName, 0)331 if err != nil {332 return nil, errors.Wrap(err, "error creating memfd")333 }334 memfile := os.NewFile(uintptr(memfd), memfileName)335 mf, err := pgalloc.NewMemoryFile(memfile, pgalloc.MemoryFileOpts{})336 if err != nil {337 memfile.Close()338 return nil, errors.Wrap(err, "error creating pgalloc.MemoryFile")339 }340 return mf, nil341}...

Full Screen

Full Screen

comm.go

Source:comm.go Github

copy

Full Screen

...60 }61 var linkID stack.LinkEndpoint62 var channelLinkID = channel.New(1024, uint32(mtu), tcpip.LinkAddress(macAddr))63 linkID = channelLinkID64 if err := _netStack.CreateNIC(nicid, linkID); err != nil {65 return _netStack, nil, errors.New(err.String())66 }67 _netStack.SetRouteTable([]tcpip.Route{68 // IPv469 {70 Destination: header.IPv4EmptySubnet,71 NIC: nicid,72 },73 })74 //promiscuous mode 必须75 _netStack.SetPromiscuousMode(nicid, true)76 _netStack.SetSpoofing(nicid, true)77 tcpForwarder := tcp.NewForwarder(_netStack, 0, 512, func(r *tcp.ForwarderRequest) {78 var wq waiter.Queue79 ep, err := r.CreateEndpoint(&wq)80 if err != nil {81 log.Printf("CreateEndpoint" + err.String() + "\r\n")82 r.Complete(true)83 return84 }85 defer ep.Close()86 r.Complete(false)87 if err := setKeepalive(ep); err != nil {88 log.Printf("setKeepalive" + err.Error() + "\r\n")89 }90 conn := gonet.NewTCPConn(&wq, ep)91 defer conn.Close()92 tcpCallback(conn)93 })94 _netStack.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpForwarder.HandlePacket)95 udpForwarder := udp.NewForwarder(_netStack, func(r *udp.ForwarderRequest) {96 var wq waiter.Queue97 ep, err := r.CreateEndpoint(&wq)98 if err != nil {99 log.Printf("r.CreateEndpoint() = %v", err)100 return101 }102 go udpCallback(gonet.NewUDPConn(_netStack, &wq, ep), ep)103 })104 _netStack.SetTransportProtocolHandler(udp.ProtocolNumber, udpForwarder.HandlePacket)105 return _netStack, channelLinkID, nil106}107func setKeepalive(ep tcpip.Endpoint) error {108 idleOpt := tcpip.KeepaliveIdleOption(60 * time.Second)109 if err := ep.SetSockOpt(&idleOpt); err != nil {110 return fmt.Errorf("set keepalive idle: %s", err)111 }112 intervalOpt := tcpip.KeepaliveIntervalOption(30 * time.Second)113 if err := ep.SetSockOpt(&intervalOpt); err != nil {...

Full Screen

Full Screen

netstack_linux.go

Source:netstack_linux.go Github

copy

Full Screen

...23 }24 s := stack.New(stack.Options{25 NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},26 TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol}})27 if err := s.CreateNIC(1, linkEP); err != nil {28 return fmt.Errorf("create nic fail %v", err)29 }30 s.SetNICForwarding(1, ipv4.ProtocolNumber, true)31 s.SetPromiscuousMode(1, true)32 s.SetSpoofing(1, true)33 subnet, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 4)),34 tcpip.AddressMask(strings.Repeat("\x00", 4)))35 subnet6, _ := tcpip.NewSubnet(tcpip.Address(strings.Repeat("\x00", 16)),36 tcpip.AddressMask(strings.Repeat("\x00", 16)))37 s.SetRouteTable([]tcpip.Route{38 {39 Destination: subnet,40 NIC: 1,41 },42 {43 Destination: subnet6,44 NIC: 1,45 },46 })47 tcpFwd := tcp.NewForwarder(s, 0, 256, func(r *tcp.ForwarderRequest) {48 id := r.ID()49 remoteAddr := &net.TCPAddr{IP: net.IP(id.LocalAddress), Port: int(id.LocalPort)}50 newConn := func(kaInterval time.Duration, kaCount int) (net.Conn, error) {51 var wq waiter.Queue52 ep, err := r.CreateEndpoint(&wq)53 if err != nil {54 r.Complete(true)55 return nil, fmt.Errorf("netstack create endpoint fail %s", err)56 }57 r.Complete(false)58 ep.SocketOptions().SetKeepAlive(true)59 {60 opt := tcpip.KeepaliveIdleOption(kaInterval)61 ep.SetSockOpt(&opt)62 }63 {64 opt := tcpip.KeepaliveIntervalOption(kaInterval)65 ep.SetSockOpt(&opt)66 }...

Full Screen

Full Screen

Create

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s := stack.New([]string{stack.NetworkProtocolNameIPv4}, []string{stack.TransportProtocolNameTCP}, stack.Options{})4 tun, err := tun.Create("/dev/net/tun", "tun0")5 if err != nil {6 panic(err)7 }8 if err := s.CreateNIC(1, &fdbased.Endpoint{tun}); err != nil {9 panic(err)10 }11 s.SetRouteTable([]tcpip.Route{{12 }})13 if err := s.AddAddress(1, stack.ProtocolAddress{Protocol: stack.ProtocolAddressIPv4, AddressWithPrefix: tcpip.AddressWithPrefix{Address: "\x0a\x00\x00\x01", PrefixLen: 24}}); err != nil {14 panic(err)15 }16 ep, err := s.NewEndpoint(tcp.ProtocolNumber, stack.TransportProtocolNameTCP, &stack.DefaultTransportOptions{})17 if err != nil {18 panic(err)19 }20 if err := ep.Bind(tcpip.FullAddress{NIC: 1, Addr: "\x0a\x00\x00\x01", Port: 80}, nil); err != nil {21 panic(err)22 }23 if err := ep.Listen(10); err != nil {24 panic(err)25 }26 for {27 wq := new(waiter.Queue)28 ep, _, err := ep.Accept(wq)29 if err != nil {30 panic(err)31 }32 go func() {33 for {34 n, _, err := ep.Read(&b, tcpip.ReadOptions{})

Full Screen

Full Screen

Create

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 f, err := os.Create("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 l, err := f.WriteString("testing testing")8 if err != nil {9 fmt.Println(err)10 f.Close()11 }12 fmt.Println(l, "bytes written successfully")13 err = f.Close()14 if err != nil {15 fmt.Println(err)16 }17}18import (19func main() {20 f, err := os.Open("test.txt")21 if err != nil {22 fmt.Println(err)23 }24 l, err := f.WriteString("testing testing")25 if err != nil {26 fmt.Println(err)27 f.Close()28 }29 fmt.Println(l, "bytes written successfully")30 err = f.Close()31 if err != nil {32 fmt.Println(err)33 }34}35import (36func main() {37 f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0644)38 if err != nil {39 fmt.Println(err)40 }41 l, err := f.WriteString("testing testing")42 if err != nil {43 fmt.Println(err)44 f.Close()45 }46 fmt.Println(l, "bytes written successfully")47 err = f.Close()48 if err != nil {49 fmt.Println(err)50 }51}52import (53func main() {54 fi, err := os.Stat("test.txt")55 if err != nil {56 fmt.Println(err)57 }58 fmt.Println("File Name:", fi.Name())59 fmt.Println("Size in bytes:", fi.Size())

Full Screen

Full Screen

Create

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 gv, err := gvisor.Create()4 if err != nil {5 fmt.Printf("Failed to create gvisor: %v", err)6 }7 err = gv.Start()8 if err != nil {9 fmt.Printf("Failed to start gvisor: %v", err)10 }11 err = gv.Stop()12 if err != nil {13 fmt.Printf("Failed to stop gvisor: %v", err)14 }15}

Full Screen

Full Screen

Create

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 gvisor := gvisor.Create()4 fmt.Println(gvisor)5}6import (7func main() {8 gvisor := gvisor.Create()9 container := gvisor.CreateContainer("container1")10 fmt.Println(container)11}12import (13func main() {14 gvisor := gvisor.Create()15 container := gvisor.CreateContainer("container1")16 container.Start()17 fmt.Println(container)18}19import (20func main() {21 gvisor := gvisor.Create()22 container := gvisor.CreateContainer("container1")23 container.Start()

Full Screen

Full Screen

Create

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 g := gvisor.NewGvisor()4 id, err := g.Create("test", "gvisor", "gvisor", "gvisor", "gvisor", "gvisor", "gvisor", "gvisor")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println("Container created with id: ", id)9 err = g.Start(id)10 if err != nil {11 fmt.Println(err)12 }13 time.Sleep(5 * time.Second)14 err = g.Stop(id)15 if err != nil {16 fmt.Println(err)17 }18}193e3d3c2c2b8a gvisor "/runsc --debug" 6 seconds ago Exited (0) 5 seconds ago test20func (g *Gvisor) Delete(id string) error {21 resp, err := http.NewRequest("DELETE", url, nil)22 if err != nil {23 }24 resp.Header.Set("Authorization", "Bearer "+g.Token)25 _, err = http.DefaultClient.Do(resp)26 if err != nil {27 }28}29import (30func main() {31 g := gvisor.NewGvisor()

Full Screen

Full Screen

Create

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 gvisor := gvisor.Gvisor{}4 gvisor.Create("test", "test", "test")5 fmt.Println("Hello, playground")6}7import (8type Gvisor struct {9}10func (gvisor Gvisor) Create(name string, image string, tag string) {11 fmt.Println("Creating a new container")12 cmd := exec.Command("docker", "run", "--runtime=runsc", "--name", name, "-it", image+":"+tag, "/bin/bash")13 err := cmd.Run()14 if err != nil {15 fmt.Println(err)16 }17}18import (19type Gvisor struct {20}21func (gvisor Gvisor) Create(name string, image string, tag string) {22 fmt.Println("Creating a new container")23 cmd := exec.Command("docker", "run", "--runtime=runsc", "--name", name, "-it", image+":"+tag, "/bin/bash")24 err := cmd.Run()25 if err != nil {26 fmt.Println(err)27 }28}29import (30func main() {31 gvisor := gvisor.Gvisor{}32 gvisor.Create("test", "test", "test")33 fmt.Println("Hello, playground")34}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful